diff --git "a/834.jsonl" "b/834.jsonl" new file mode 100644--- /dev/null +++ "b/834.jsonl" @@ -0,0 +1,721 @@ +{"seq_id":"6182528707","text":"import math\nimport copy\nfrom shapely.geometry import Polygon, MultiPolygon, shape, Point\nimport numpy as np\nimport triangle\nfrom pyproj import Proj, transform\nimport pandas as pd\nfrom scipy.spatial import cKDTree\nimport geopandas as gpd\nimport geopy.distance\nfrom geopy.geocoders import Nominatim\nfrom geopy.exc import GeocoderTimedOut, GeocoderQuotaExceeded\n\n#--Projection space\ninProj = Proj(init='epsg:25832')\noutProj = Proj(init='epsg:4326')\n#-- Name spaces\nns_citygml = 'http://www.opengis.net/citygml/1.0'\nns_gen = 'http://www.opengis.net/citygml/generics/1.0'\nns_citygml_generics = 'http://www.opengis.net/citygml/generics/1.0'\nns_cityobjectgroup = 'http://www.opengis.net/citygml/cityobjectgroup/1.0'\nns_appearance = 'http://www.opengis.net/citygml/appearance/1.0'\nns_bldg = 'http://www.opengis.net/citygml/building/1.0'\nns_gml = 'http://www.opengis.net/gml'\nns_xAL = 'urn:oasis:names:tc:ciq:xsdschema:xAL:2.0'\nns_xLink = 'http://www.w3.org/1999/xlink'\nns_xsi = 'http://www.w3.org/2001/XMLSchema-instance'\n\n\n_geolocator = Nominatim(user_agent='email@host.de')#if many requests are sent it is important to specify the email address here\n\ndef get_coordinates(address, timeout=5):\n \"\"\"\n Geolocate an address.\n\n Returns the latitude and longitude of the given address using\n OpenStreetMap's Nominatim service. If the coordinates of the\n address cannot be found then ``(None, None)`` is returned.\n\n As per Nominatim's terms of service this function is rate limited\n to at most one call per second.\n\n ``timeout`` gives the timeout in seconds.\n \"\"\"\n location = _geolocator.geocode(address, timeout=timeout)\n if not location:\n return None, None\n return location.latitude, location.longitude\n\n\ndef ckdnearest(gdA, gdB):\n \"\"\"\n finds nearest points of GeoPandas.DataFrame gdB in GeoPandas.DataFrame gdA\n please be sure that the index is resorted before using this function as it is using\n numpy array indices which are not the same if you used boolean indexing or other mutable operations on the\n DataFrames gdA index!\n :param gdA: must contain a shapely Point geometry column\n :param gdB: must contain a shapely Point geometry column\n :return: concatenated GeoPandas.DataFrame containing all columns of both DataFrames excluding gdB's geometry plus distance in degrees\n \"\"\"\n nA = np.array(list(zip(gdA.geometry.x, gdA.geometry.y))) #create geometry list of dataframe gdA\n nB = np.array(list(zip(gdB.geometry.x, gdB.geometry.y))) #create geometry list of dataframe gdB\n btree = cKDTree(nB)\n dist, idx = btree.query(nA, k=1) #find nearest neighbor, k > 1 searches for more (k) neighbors, however following code needs to be adjusted to do so\n gdf = pd.concat(\n [gdA.reset_index(drop=True), gdB.loc[idx, gdB.columns != 'geometry'].reset_index(drop=True),\n pd.Series(dist, name='dist')], axis=1) #concat new dataframe with features of both dataframes\n gdf = gpd.GeoDataFrame(gdf)\n return gdf\n\n\ndef add_missing_addresses_to_rooftopdata(rooftops):\n \"\"\"\n filters GeoPandas DataFrame for missing addresses and finds the nearest address\n :param rooftops: rooftop GeoPandas DataFrame with missing addresses\n :return: a new dataframe which adds the associated address and the distance to it\n \"\"\"\n rooftops['centroid'] = rooftops['geometry'].centroid #extract centroid of geometries\n rooftops['dist'] = 0 #create distance column\n\n no_data_rooftops = rooftops[rooftops['PostalCode'] == 'No data'] #extract rows where no address is given\n rooftops = rooftops[rooftops['PostalCode'] != 'No data'] #exclude rows in original dataframe where no address is given\n\n if len(no_data_rooftops) == 0:\n return rooftops\n\n else:\n no_data_rooftops['polygon'] = no_data_rooftops['geometry']\n no_data_rooftops['geometry'] = no_data_rooftops['centroid']\n no_data_rooftops['x_nodata'], no_data_rooftops['y_nodata'] = no_data_rooftops.geometry.x, no_data_rooftops.geometry.y\n\n rooftops['polygon'] = rooftops['geometry']\n rooftops['geometry'] = rooftops['centroid']\n rooftops['x_address'], rooftops['y_address'] = rooftops.geometry.x, rooftops.geometry.y\n\n rooftops_with_adresses = rooftops[['City', 'PostalCode',\n 'Street', 'StreetNumber', 'geometry', 'x_address', 'y_address']]\n rooftops_with_adresses = rooftops_with_adresses.reset_index(drop = True)\n\n no_data_rooftops = no_data_rooftops[['Area', 'Azimuth', 'Building_ID', 'RoofTopID',\n 'RooftopType', 'Tilt', 'geometry', 'centroid', 'polygon', 'x_nodata', 'y_nodata']]\n no_data_rooftops = ckdnearest(no_data_rooftops, rooftops_with_adresses)\n\n points_no_data = list(zip(no_data_rooftops['x_nodata'], no_data_rooftops['y_nodata']))\n address_points = list(zip(no_data_rooftops['x_address'], no_data_rooftops['y_address']))\n dist = [geopy.distance.vincenty(address, no_data).m for address, no_data in zip(address_points, points_no_data)]\n\n no_data_rooftops['dist'] = dist\n no_data_rooftops['geometry'] = no_data_rooftops['polygon']\n rooftops['geometry'] = rooftops['polygon']\n no_data_rooftops = no_data_rooftops.drop(columns = ['centroid', 'polygon', 'x_nodata',\n 'y_nodata','x_address', 'y_address'])\n rooftops = rooftops.drop(columns = ['centroid', 'polygon', 'x_address', 'y_address'])\n rooftops = rooftops.append(no_data_rooftops)\n rooftops.sort_index(inplace = True)\n return rooftops\n\ndef convert_3D_2D(geometry):\n '''\n Takes a GeoSeries of 3D Multi/Polygons (has_z) and returns a list of 2D Multi/Polygons\n '''\n new_geo = []\n for p in geometry:\n if p.has_z:\n if p.geom_type == 'Polygon':\n lines = [xy[:2] for xy in list(p.exterior.coords)]\n new_p = Polygon(lines)\n new_geo.append(new_p)\n elif p.geom_type == 'MultiPolygon':\n new_multi_p = []\n for ap in p:\n lines = [xy[:2] for xy in list(ap.exterior.coords)]\n new_p = Polygon(lines)\n new_multi_p.append(new_p)\n new_geo.append(MultiPolygon(new_multi_p))\n return new_geo\n\ndef polydecomposer(polygon):\n \"\"\"Extracts the and of a .\"\"\"\n exter = polygon.findall('.//{%s}exterior' %ns_gml)\n inter = polygon.findall('.//{%s}interior' %ns_gml)\n return exter, inter\n\n\ndef polygonFinder(GMLelement):\n \"\"\"Find the element.\"\"\"\n polygonsLocal = GMLelement.findall('.//{%s}Polygon' %ns_gml)\n return polygonsLocal\n\n\nfrom pyproj import Proj, transform\ninProj = Proj(init='epsg:25832')\noutProj = Proj(init='epsg:4326')\ndef GMLpoints(ring, convert = False):\n \"Extract points from a .\"\n #-- List containing points\n listPoints = []\n #-- Read the value and convert to string\n if len(ring.findall('.//{%s}posList' %ns_gml)) > 0:\n points = ring.findall('.//{%s}posList' %ns_gml)[0].text\n #-- List of coordinates\n coords = points.split()\n assert(len(coords) % 3 == 0)\n #-- Store the coordinate tuple\n for i in range(0, len(coords), 3):\n if convert:\n coords[i], coords[i+1] = transform(inProj,outProj,coords[i], coords[i+1]) #transform coordinates to EPSG 4326\n listPoints.append((float(coords[i]), float(coords[i+1]), float(coords[i+2])))\n elif len(ring.findall('.//{%s}pos' %ns_gml)) > 0:\n points = ring.findall('.//{%s}pos' %ns_gml)\n #-- Extract each point separately\n for p in points:\n coords = p.text.split()\n assert(len(coords) % 3 == 0)\n #-- Store the coordinate tuple\n for i in range(0, len(coords), 3):\n if convert:\n coords[i], coords[i+1] = transform(inProj,outProj,coords[i], coords[i+1]) #transform coordinates to EPSG 4326\n listPoints.append((float(coords[i]), float(coords[i+1]), float(coords[i+2])))\n else:\n return None\n\n return listPoints\n\ndef getAreaOfGML(poly, height=True):\n \"\"\"Function which reads and returns its area.\n The function also accounts for the interior and checks for the validity of the polygon.\"\"\"\n exteriorarea = 0.0\n interiorarea = 0.0\n # -- Decompose the exterior and interior boundary\n e, i = polydecomposer(poly)\n # -- Extract points in the of \n epoints = GMLpoints(e[0])\n if isPolyValid(epoints):\n if height:\n exteriorarea += get3DArea(epoints)\n else:\n exteriorarea += get2DArea(epoints)\n for idx, iring in enumerate(i):\n # -- Extract points in the of \n ipoints = GMLpoints(iring)\n if isPolyValid(ipoints):\n if height:\n interiorarea += get3DArea(ipoints)\n else:\n interiorarea += get2DArea(ipoints)\n # -- Account for the interior\n area = exteriorarea - interiorarea\n # -- Area in dimensionless units (coordinate units)\n return area\n\n\n# -- Validity of a polygon ---------\ndef isPolyValid(polypoints, output=True):\n \"\"\"Checks if a polygon is valid. Second option is to supress output.\"\"\"\n # -- Number of points of the polygon (including the doubled first/last point)\n npolypoints = len(polypoints)\n # -- Assume that it is valid, and try to disprove the assumption\n valid = True\n # -- Check if last point equal\n if polypoints[0] != polypoints[-1]:\n if output:\n print\n \"A degenerate polygon. First and last points do not match.\"\n valid = False\n # -- Check if it has at least three points\n if npolypoints < 4: # -- Four because the first point is doubled as the last one in the ring\n if output:\n print\n \"A degenerate polygon. The number of points is smaller than 3.\"\n valid = False\n # -- Check if the points are planar\n if not isPolyPlanar(polypoints):\n if output:\n print\n \"A degenerate polygon. The points are not planar.\"\n valid = False\n # -- Check if the polygon does not have self-intersections\n # -- Disabled, something doesn't work here, will work on this later.\n # if not isPolySimple(polypoints):\n # print \"A degenerate polygon. The edges are intersecting.\"\n # valid = False\n return valid\n\n\ndef isPolyPlanar(polypoints):\n \"\"\"Checks if a polygon is planar.\"\"\"\n # -- Normal of the polygon from the first three points\n normal = unit_normal(polypoints[0], polypoints[1], polypoints[2])\n # -- Number of points\n npolypoints = len(polypoints)\n # -- Tolerance\n eps = 0.01\n # -- Assumes planarity\n planar = True\n for i in range(3, npolypoints):\n vector = [polypoints[i][0] - polypoints[0][0], polypoints[i][1] - polypoints[0][1],\n polypoints[i][2] - polypoints[0][2]]\n if math.fabs(dot(vector, normal)) > eps:\n planar = False\n return planar\n\n\ndef isPolySimple(polypoints):\n \"\"\"Checks if the polygon is simple, i.e. it does not have any self-intersections.\n Inspired by http://www.win.tue.nl/~vanwijk/2IV60/2IV60_exercise_3_answers.pdf\"\"\"\n npolypoints = len(polypoints)\n # -- Check if the polygon is vertical, i.e. a projection cannot be made.\n # -- First copy the list so the originals are not modified\n temppolypoints = copy.deepcopy(polypoints)\n newpolypoints = copy.deepcopy(temppolypoints)\n # -- If the polygon is vertical\n if math.fabs(unit_normal(temppolypoints[0], temppolypoints[1], temppolypoints[2])[2]) < 10e-6:\n vertical = True\n else:\n vertical = False\n # -- We want to project the vertical polygon to the XZ plane\n # -- If a polygon is parallel with the YZ plane that will not be possible\n YZ = True\n for i in range(1, npolypoints):\n if temppolypoints[i][0] != temppolypoints[0][0]:\n YZ = False\n continue\n # -- Project the plane in the special case\n if YZ:\n for i in range(0, npolypoints):\n newpolypoints[i][0] = temppolypoints[i][1]\n newpolypoints[i][1] = temppolypoints[i][2]\n # -- Project the plane\n elif vertical:\n for i in range(0, npolypoints):\n newpolypoints[i][1] = temppolypoints[i][2]\n else:\n pass # -- No changes here\n # -- Check for the self-intersection edge by edge\n for i in range(0, npolypoints - 3):\n if i == 0:\n m = npolypoints - 3\n else:\n m = npolypoints - 2\n for j in range(i + 2, m):\n if intersection(newpolypoints[i], newpolypoints[i + 1], newpolypoints[j % npolypoints],\n newpolypoints[(j + 1) % npolypoints]):\n return False\n return True\n\n\ndef intersection(p, q, r, s):\n \"\"\"Check if two line segments (pq and rs) intersect. Computation is in 2D.\n Inspired by http://www.win.tue.nl/~vanwijk/2IV60/2IV60_exercise_3_answers.pdf\"\"\"\n\n eps = 10e-6\n\n V = [q[0] - p[0], q[1] - p[1]]\n W = [r[0] - s[0], r[1] - s[1]]\n\n d = V[0] * W[1] - W[0] * V[1]\n\n if math.fabs(d) < eps:\n return False\n else:\n return True\n\n# -- Area and other handy computations\ndef det(a):\n \"\"\"Determinant of matrix a.\"\"\"\n return a[0][0] * a[1][1] * a[2][2] + a[0][1] * a[1][2] * a[2][0] + a[0][2] * a[1][0] * a[2][1] - a[0][2] * a[1][1] * \\\n a[2][0] - a[0][1] * a[1][0] * a[2][2] - a[0][0] * a[1][2] * a[2][1]\n\n\ndef unit_normal(a, b, c):\n \"\"\"Unit normal vector of plane defined by points a, b, and c.\"\"\"\n try:\n x = det([[1, a[1], a[2]],\n [1, b[1], b[2]],\n [1, c[1], c[2]]])\n y = det([[a[0], 1, a[2]],\n [b[0], 1, b[2]],\n [c[0], 1, c[2]]])\n z = det([[a[0], a[1], 1],\n [b[0], b[1], 1],\n [c[0], c[1], 1]])\n magnitude = (x ** 2 + y ** 2 + z ** 2) ** .5\n if magnitude == 0.0:\n raise SyntaxWarning(\n \"The normal of the polygon has no magnitude. Check the polygon. The most common cause for this are two identical and sequential points.\")\n return (x / magnitude, y / magnitude, z / magnitude)\n except SyntaxWarning as e:\n print(e)\n\n\ndef dot(a, b):\n \"\"\"Dot product of vectors a and b.\"\"\"\n return a[0] * b[0] + a[1] * b[1] + a[2] * b[2]\n\n\ndef cross(a, b):\n \"\"\"Cross product of vectors a and b.\"\"\"\n x = a[1] * b[2] - a[2] * b[1]\n y = a[2] * b[0] - a[0] * b[2]\n z = a[0] * b[1] - a[1] * b[0]\n return (x, y, z)\n\n\ndef get3DArea(polypoints):\n \"\"\"Function which reads the list of coordinates and returns its area.\n The code has been borrowed from http://stackoverflow.com/questions/12642256/python-find-area-of-polygon-from-xyz-coordinates\"\"\"\n # -- Compute the area\n total = [0, 0, 0]\n for i in range(len(polypoints)):\n vi1 = polypoints[i]\n if i is len(polypoints) - 1:\n vi2 = polypoints[0]\n else:\n vi2 = polypoints[i + 1]\n prod = cross(vi1, vi2)\n total[0] += prod[0]\n total[1] += prod[1]\n total[2] += prod[2]\n result = dot(total, unit_normal(polypoints[0], polypoints[1], polypoints[2]))\n return math.fabs(result * .5)\n\n\ndef get2DArea(polypoints):\n \"\"\"Reads the list of coordinates and returns its projected area (disregards z coords).\"\"\"\n flatpolypoints = copy.deepcopy(polypoints)\n for p in flatpolypoints:\n p[2] = 0.0\n return get3DArea(flatpolypoints)\n\n\ndef getNormal(polypoints):\n \"\"\"Get the normal of the first three points of a polygon. Assumes planarity.\"\"\"\n return unit_normal(polypoints[0], polypoints[1], polypoints[2])\n\n\ndef getAngles(normal):\n \"\"\"Get the azimuth and altitude from the normal vector.\"\"\"\n # -- Convert from polar system to azimuth\n azimuth = 90 - math.degrees(math.atan2(normal[1], normal[0]))\n if azimuth >= 360.0:\n azimuth -= 360.0\n elif azimuth < 0.0:\n azimuth += 360.0\n t = math.sqrt(normal[0] ** 2 + normal[1] ** 2)\n if t == 0:\n tilt = 0.0\n else:\n tilt = 90 - math.degrees(math.atan(normal[2] / t)) # 0 for flat roof, 90 for wall\n tilt = round(tilt, 3)\n\n return azimuth, tilt\n\n\ndef GMLstring2points(pointstring):\n \"\"\"Convert list of points in string to a list of points. Works for 3D points.\"\"\"\n listPoints = []\n # -- List of coordinates\n coords = pointstring.split()\n # -- Store the coordinate tuple\n assert (len(coords) % 3 == 0)\n for i in range(0, len(coords), 3):\n listPoints.append([float(coords[i]), float(coords[i + 1]), float(coords[i + 2])])\n return listPoints\n\n\ndef smallestPoint(list_of_points):\n \"Finds the smallest point from a three-dimensional tuple list.\"\n smallest = []\n # -- Sort the points\n sorted_points = sorted(list_of_points, key=lambda x: (x[0], x[1], x[2]))\n # -- First one is the smallest one\n smallest = sorted_points[0]\n return smallest\n\n\ndef highestPoint(list_of_points, a=None):\n \"Finds the highest point from a three-dimensional tuple list.\"\n highest = []\n # -- Sort the points\n sorted_points = sorted(list_of_points, key=lambda x: (x[0], x[1], x[2]))\n # -- Last one is the highest one\n if a is not None:\n equalZ = True\n for i in range(-1, -1 * len(list_of_points), -1):\n if equalZ:\n highest = sorted_points[i]\n if highest[2] != a[2]:\n equalZ = False\n break\n else:\n break\n else:\n highest = sorted_points[-1]\n return highest\n\n\ndef centroid(list_of_points):\n \"\"\"Returns the centroid of the list of points.\"\"\"\n sum_x = 0\n sum_y = 0\n sum_z = 0\n n = float(len(list_of_points))\n for p in list_of_points:\n sum_x += float(p[0])\n sum_y += float(p[1])\n sum_z += float(p[2])\n return [sum_x / n, sum_y / n, sum_z / n]\n\n\ndef plane(a, b, c):\n \"\"\"Returns the equation of a three-dimensional plane in space by entering the three coordinates of the plane.\"\"\"\n p_a = (b[1] - a[1]) * (c[2] - a[2]) - (c[1] - a[1]) * (b[2] - a[2])\n p_b = (b[2] - a[2]) * (c[0] - a[0]) - (c[2] - a[2]) * (b[0] - a[0])\n p_c = (b[0] - a[0]) * (c[1] - a[1]) - (c[0] - a[0]) * (b[1] - a[1])\n p_d = -1 * (p_a * a[0] + p_b * a[1] + p_c * a[2])\n return p_a, p_b, p_c, p_d\n\n\ndef get_height(plane, x, y):\n \"\"\"Get the missing coordinate from the plane equation and the partial coordinates.\"\"\"\n p_a, p_b, p_c, p_d = plane\n z = (-p_a * x - p_b * y - p_d) / p_c\n return z\n\n\ndef get_y(plane, x, z):\n \"\"\"Get the missing coordinate from the plane equation and the partial coordinates.\"\"\"\n p_a, p_b, p_c, p_d = plane\n y = (-p_a * x - p_c * z - p_d) / p_b\n return y\n\n\ndef compare_normals(n1, n2):\n \"\"\"Compares if two normals are equal or opposite. Takes into account a small tolerance to overcome floating point errors.\"\"\"\n tolerance = 0.0001\n # -- Assume equal and prove otherwise\n equal = True\n # -- i\n if math.fabs(n1[0] - n2[0]) > tolerance:\n equal = False\n # -- j\n elif math.fabs(n1[1] - n2[1]) > tolerance:\n equal = False\n # -- k\n elif math.fabs(n1[2] - n2[2]) > tolerance:\n equal = False\n return equal\n\n\ndef reverse_vertices(vertices):\n \"\"\"Reverse vertices. Useful to reorient the normal of the polygon.\"\"\"\n reversed_vertices = []\n nv = len(vertices)\n for i in range(nv - 1, -1, -1):\n reversed_vertices.append(vertices[i])\n return reversed_vertices\n\n\ndef triangulation(e, i):\n \"\"\"Triangulate the polygon with the exterior and interior list of points. Works only for convex polygons.\n Assumes planarity. Projects to a 2D plane and goes back to 3D.\"\"\"\n vertices = []\n holes = []\n segments = []\n index_point = 0\n\n # -- Slope computation points\n a = [[], [], []]\n b = [[], [], []]\n for ip in range(len(e) - 1):\n vertices.append(e[ip])\n if a == [[], [], []] and index_point == 0:\n a = [e[ip][0], e[ip][1], e[ip][2]]\n if index_point > 0 and (e[ip] != e[ip - 1]):\n if b == [[], [], []]:\n b = [e[ip][0], e[ip][1], e[ip][2]]\n if ip == len(e) - 2:\n segments.append([index_point, 0])\n else:\n segments.append([index_point, index_point + 1])\n index_point += 1\n for hole in i:\n first_point_in_hole = index_point\n for p in range(len(hole) - 1):\n if p == len(hole) - 2:\n segments.append([index_point, first_point_in_hole])\n else:\n segments.append([index_point, index_point + 1])\n index_point += 1\n vertices.append(hole[p])\n holes.append(centroid(hole[:-1]))\n\n # -- Project to 2D since the triangulation cannot be done in 3D with the library that is used\n npolypoints = len(vertices)\n nholes = len(holes)\n # -- Check if the polygon is vertical, i.e. a projection cannot be made.\n # -- First copy the list so the originals are not modified\n temppolypoints = copy.deepcopy(vertices)\n newpolypoints = copy.deepcopy(vertices)\n tempholes = copy.deepcopy(holes)\n newholes = copy.deepcopy(holes)\n # -- Compute the normal of the polygon for detecting vertical polygons and\n # -- for the correct orientation of the new triangulated faces\n # -- If the polygon is vertical\n normal = unit_normal(temppolypoints[0], temppolypoints[1], temppolypoints[2])\n if math.fabs(normal[2]) < 10e-6:\n vertical = True\n else:\n vertical = False\n # -- We want to project the vertical polygon to the XZ plane\n # -- If a polygon is parallel with the YZ plane that will not be possible\n YZ = True\n for i in range(1, npolypoints):\n if temppolypoints[i][0] != temppolypoints[0][0]:\n YZ = False\n continue\n # -- Project the plane in the special case\n if YZ:\n for i in range(0, npolypoints):\n newpolypoints[i][0] = temppolypoints[i][1]\n newpolypoints[i][1] = temppolypoints[i][2]\n for i in range(0, nholes):\n newholes[i][0] = tempholes[i][1]\n newholes[i][1] = tempholes[i][2]\n # -- Project the plane\n elif vertical:\n for i in range(0, npolypoints):\n newpolypoints[i][1] = temppolypoints[i][2]\n for i in range(0, nholes):\n newholes[i][1] = tempholes[i][2]\n else:\n pass # -- No changes here\n\n # -- Drop the last point (identical to first)\n for p in newpolypoints:\n p.pop(-1)\n\n # -- If there are no holes\n if len(newholes) == 0:\n newholes = None\n else:\n for h in newholes:\n h.pop(-1)\n\n # -- Plane information (assumes planarity)\n a = e[0]\n b = e[1]\n c = e[2]\n # -- Construct the plane\n pl = plane(a, b, c)\n\n # -- Prepare the polygon to be triangulated\n poly = {'vertices': np.array(newpolypoints), 'segments': np.array(segments), 'holes': np.array(newholes)}\n # -- Triangulate\n t = triangle.triangulate(poly, \"pQjz\")\n # -- Get the triangles and their vertices\n tris = t['triangles']\n vert = t['vertices'].tolist()\n # -- Store the vertices of each triangle in a list\n tri_points = []\n for tri in tris:\n tri_points_tmp = []\n for v in tri.tolist():\n vert_adj = [[], [], []]\n if YZ:\n vert_adj[0] = temppolypoints[0][0]\n vert_adj[1] = vert[v][0]\n vert_adj[2] = vert[v][1]\n elif vertical:\n vert_adj[0] = vert[v][0]\n vert_adj[2] = vert[v][1]\n vert_adj[1] = get_y(pl, vert_adj[0], vert_adj[2])\n else:\n vert_adj[0] = vert[v][0]\n vert_adj[1] = vert[v][1]\n vert_adj[2] = get_height(pl, vert_adj[0], vert_adj[1])\n tri_points_tmp.append(vert_adj)\n tri_normal = unit_normal(tri_points_tmp[0], tri_points_tmp[1], tri_points_tmp[2])\n if compare_normals(normal, tri_normal):\n tri_points.append(tri_points_tmp)\n else:\n tri_points_tmp = reverse_vertices(tri_points_tmp)\n tri_points.append(tri_points_tmp)\n return tri_points\n\n\ndef GMLpoints(ring, convert = False):\n \"Extract points from a .\"\n #-- List containing points\n listPoints = []\n #-- Read the value and convert to string\n if len(ring.findall('.//{%s}posList' %ns_gml)) > 0:\n points = ring.findall('.//{%s}posList' %ns_gml)[0].text\n #-- List of coordinates\n coords = points.split()\n assert(len(coords) % 3 == 0)\n #-- Store the coordinate tuple\n for i in range(0, len(coords), 3):\n if convert:\n coords[i], coords[i+1] = transform(inProj,outProj,coords[i], coords[i+1])\n listPoints.append((float(coords[i]), float(coords[i+1]), float(coords[i+2])))\n elif len(ring.findall('.//{%s}pos' %ns_gml)) > 0:\n points = ring.findall('.//{%s}pos' %ns_gml)\n #-- Extract each point separately\n for p in points:\n coords = p.text.split()\n assert(len(coords) % 3 == 0)\n #-- Store the coordinate tuple\n for i in range(0, len(coords), 3):\n if convert:\n coords[i], coords[i+1] = transform(inProj,outProj,coords[i], coords[i+1])\n listPoints.append((float(coords[i]), float(coords[i+1]), float(coords[i+2])))\n else:\n return None\n\n return listPoints\n\nlistofxmlroofsurfaces = []\n\n\nclass Building(object):\n def __init__(self, xml, id):\n try:\n # -- ID of the building\n self.id = id\n # -- XML tree of the building\n self.xml = xml\n # -- additional feature extraction\n for child in self.xml.getiterator():\n if child.tag == '{%s}stringAttribute' % ns_citygml_generics:\n #extract dachhoehe\n if child.get('name') == 'DatenquelleDachhoehe':\n for grandchild in child:\n self.datenquelle_dachhoehe = grandchild.text\n #extract gemeindeschluessel\n elif child.get('name') == 'Gemeindeschluessel':\n for grandchild in child:\n self.gemeindeschluessel = grandchild.text\n #extract datenquelle bodenhoehe\n elif child.get('name') == 'DatenquelleBodenhoehe':\n for grandchild in child:\n self.datenquelle_bodenhoehe = grandchild.text\n #extract datenquelle lage\n elif child.get('name') == 'DatenquelleLage':\n for grandchild in child:\n self.datenquelle_lage = grandchild.text\n for child in self.xml.getiterator():\n #building function\n if child.tag == '{%s}function' % ns_bldg:\n self.bldg_function = child.text\n #rooftop type\n elif child.tag == '{%s}roofType' % ns_bldg:\n self.bldg_roofType = child.text\n #measured height\n elif child.tag == '{%s}measuredHeight' % ns_bldg:\n self.bldg_measuredHeight = child.text\n # adress extraction\n for child in self.xml:\n if child.tag == '{%s}address' % ns_bldg:\n self.city = child.findall('.//{%s}LocalityName' % ns_xAL)[0].text # city name\n self.streetNumber = child.findall('.//{%s}ThoroughfareNumber' % ns_xAL)[0].text # street number\n self.streetName = child.findall('.//{%s}ThoroughfareName' % ns_xAL)[0].text # steet name\n else:\n self.city = 'No data'\n self.streetNumber = 'No data'\n self.streetName = 'No data'\n # -- Data for each roof surface required for the computation of the solar stuff\n self.roofdata = {}\n self.walldata = {}\n self.grounddata = {}\n # -- Compute the total areas of surfaces per semantic class (not really required; reserved for future use)\n # -- RoofSurface\n self.RoofSurfaceArea, self.roofCreationDate = self.roofarea()\n # -- WallSurface\n self.WallSurfaceArea, self.wallCreationDate = self.wallarea()\n # -- GroundSurface\n self.GroundSurfaceArea, self.groundSurfaceCreationDate = self.groundarea()\n # -- Do the solar estimation\n self.solarinfo()\n # wall polygon transformation\n self.wallinfo()\n # ground polygon transformation\n self.groundinfo()\n except (TypeError) as e:\n print(self.id, ' causes following Exception:', e)\n\n def groundinfo(self):\n \"\"\"Computes ground polygon and id for ground polygons\"\"\"\n for groundsurface in self.grounds:\n # --Area\n area = getAreaOfGML(groundsurface, True)\n ##-- Compute the normal\n groundsurface_polygon = GMLpoints(polydecomposer(groundsurface)[0][0],\n convert=True)\n ##-- add the values\n self.grounddata = {'area': area, 'polygon': groundsurface_polygon,\n 'creationDate': self.groundSurfaceCreationDate}\n\n def wallinfo(self):\n \"\"\"Computes wall polygon and id for wall polygons\"\"\"\n for wallsurface in self.wallsurfaces:\n # -- gml:id of the polygon\n pid = wallsurface.attrib['{%s}id' % ns_gml]\n # --Area\n area = getAreaOfGML(wallsurface, True)\n # -- Compute the normal\n wallsurface_polygon = GMLpoints(polydecomposer(wallsurface)[0][0], convert=True)\n # add the values\n self.walldata[pid] = {'area': area, 'polygon': wallsurface_polygon, 'creationDate': self.wallCreationDate}\n\n def solarinfo(self):\n \"\"\"Computes the area, azimuth, and tilt for each roof surface (id compulsory).\"\"\"\n for roofsurface in self.roofsurfaces:\n # -- Add it to the list\n listofxmlroofsurfaces.append(roofsurface)\n # -- gml:id of the polygon\n pid = roofsurface.attrib['{%s}id' % ns_gml]\n # -- Area\n area = getAreaOfGML(roofsurface, True)\n # -- Compute the normal\n rooftop_polygon = GMLpoints(polydecomposer(roofsurface)[0][0], convert=True)\n norm = getNormal(GMLpoints(polydecomposer(roofsurface)[0][0]))\n # -- Get the azimuth and tilt from the surface normal\n az, tilt = getAngles(norm)\n az = round(az, 3)\n # -- 360 -> 0 degrees\n if az == 360.0:\n az = 0.0\n tilt = round(tilt, 3)\n # -- Peculiar problems with the normals, with a cheap solution. Luckily very uncommon.\n if tilt == 180:\n tilt = 0.0\n if tilt >= 180:\n tilt = tilt - 180.01\n elif tilt > 90:\n tilt = tilt - 90.01\n elif tilt == 90:\n tilt = 89.9\n # -- Flat surfaces always have the azimuth zero\n if tilt == 0.0:\n az = 0.0\n # -- Add the values\n self.roofdata[pid] = {'area': area, 'azimuth': az, 'tilt': tilt, 'polygon': rooftop_polygon,\n 'creationDate': self.roofCreationDate}\n\n def roofarea(self):\n \"\"\"The total area of RoofSurface.\"\"\"\n self.roofs = []\n self.roofsurfaces = []\n roofarea = 0.0\n for child in self.xml.getiterator():\n if child.tag == '{%s}RoofSurface' % ns_bldg:\n self.roofs.append(child)\n for surface in self.roofs:\n if len(surface.findall('{%s}creationDate' % ns_citygml)) > 0:\n roofCreationDate = surface.findall('{%s}creationDate' % ns_citygml)[0].text\n else:\n roofCreationDate = 'NaT'\n for w in surface.findall('.//{%s}Polygon' % ns_gml):\n self.roofsurfaces.append(w)\n for roofsurface in self.roofsurfaces:\n roofarea += getAreaOfGML(roofsurface, True)\n # -- Compute the normal\n norm = getNormal(GMLpoints(polydecomposer(roofsurface)[0][0]))\n getAngles(norm)\n if len(self.roofs) == 0:\n roofCreationDate = 'NaT'\n return roofarea, roofCreationDate\n\n def wallarea(self):\n \"\"\"The total area of WallSurfaces.\"\"\"\n self.walls = []\n self.wallsurfaces = []\n wallarea = 0.0\n # -- Account for openings\n for child in self.xml.getiterator():\n if child.tag == '{%s}WallSurface' % ns_bldg:\n self.walls.append(child)\n for surface in self.walls:\n if len(surface.findall('{%s}creationDate' % ns_citygml)) > 0:\n wallCreationDate = surface.findall('{%s}creationDate' % ns_citygml)[0].text\n else:\n wallCreationDate = 'NaT'\n for w in surface.findall('.//{%s}Polygon' % ns_gml):\n self.wallsurfaces.append(w)\n for wallsurface in self.wallsurfaces:\n wallarea += getAreaOfGML(wallsurface, True)\n if len(self.walls) == 0:\n wallCreationDate = 'NaT'\n return wallarea, wallCreationDate\n\n def groundarea(self):\n \"\"\"The total area of GroundSurfaces.\"\"\"\n self.grounds = []\n groundarea = 0.0\n for child in self.xml.getiterator():\n if child.tag == '{%s}GroundSurface' % ns_bldg:\n self.grounds.append(child)\n self.count = 0\n for groundsurface in self.grounds:\n self.count += 1\n if len(groundsurface.findall('{%s}creationDate' % ns_citygml)) > 0:\n groundSurfaceCreationDate = groundsurface.findall('{%s}creationDate' % ns_citygml)[0].text\n else:\n groundSurfaceCreationDate = 'NaT'\n groundarea += getAreaOfGML(groundsurface, True)\n if len(self.grounds) == 0:\n groundSurfaceCreationDate = 'NaT'\n return groundarea, groundSurfaceCreationDate","repo_name":"kdmayer/CityGML-Preprocessing-Demo","sub_path":"utils/geo_utils.py","file_name":"geo_utils.py","file_ext":"py","file_size_in_byte":34671,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"81"} +{"seq_id":"8498659058","text":"\"\"\"\nTools for Mifare 1k NFC cards\n\"\"\"\n\nimport math\n\nfrom nfc_driver import MFRC522\nfrom nfc_utils import int2hex, list2hex, bytes2str\n\n\nclass NFCException(Exception):\n pass\n\n\nclass NFCAuthenticationException(NFCException):\n pass\n\n\nclass NFCWritingException(NFCException):\n pass\n\n\nclass NFCReadingException(NFCException):\n pass\n\n\nclass Key():\n \"\"\"Key for classic Mifare authentication\"\"\"\n\n A = MFRC522.AUTHENT1A\n B = MFRC522.AUTHENT1B\n\n def __init__(self, key, mode=A):\n if not isinstance(key, list):\n key = list(key)\n if len(key) != 6 or not all([0 <= x <= 255 for x in key]):\n raise ValueError(\"Key must be 6 bytes long\")\n if mode not in [self.A, self.B]:\n raise ValueError(\"Mode must be Key.A or Key.B\")\n self.key = key\n self.mode = mode\n\n @classmethod\n def default(cls):\n return cls([0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF])\n\n\nclass NFCTag():\n \"\"\"Class representing a Mifare 1k NFC tag\"\"\"\n\n BLOCK_SIZE = 16\n\n FIRST_DATA_BLOCKS = [\n 0x01, 0x02,\n ]\n\n MAIN_DATA_BLOCKS = [\n 0x04, 0x05, 0x06,\n 0x08, 0x09, 0x0A,\n 0x0C, 0x0D, 0x0E,\n 0x10, 0x11, 0x12,\n 0x14, 0x15, 0x16,\n 0x18, 0x19, 0x1A,\n 0x1C, 0x1D, 0x1E,\n 0x20, 0x21, 0x22,\n 0x24, 0x25, 0x26,\n 0x28, 0x29, 0x2A,\n 0x2C, 0x2D, 0x2E,\n 0x30, 0x31, 0x32,\n 0x34, 0x35, 0x36,\n 0x38, 0x39, 0x3A,\n 0x3C, 0x3D, 0x3E,\n ]\n\n DATA_BLOCKS = FIRST_DATA_BLOCKS + MAIN_DATA_BLOCKS\n\n def __init__(self, rdr: MFRC522, raw_uid, tag_type):\n self.rdr = rdr\n self.raw_uid = raw_uid\n self.tag_type = tag_type\n\n def __str__(self):\n u = self.raw_uid\n return f''\n\n def _authenticate_block(self, blockaddr, key: Key = None) -> bool:\n if key is None:\n key = Key.default()\n elif not isinstance(key, Key):\n raise ValueError(\"Key must be an instance of Key!\")\n\n stat = self.rdr.auth(key.mode, blockaddr, key.key, self.raw_uid)\n if not (stat == MFRC522.OK):\n raise NFCAuthenticationException(\n f\"[!!] 0x{blockaddr:02x}: Authentication failed! ({stat})\")\n return True\n\n def _print_block(self, blockaddr, data, sign='<<', additional='') -> None:\n print(\n f\"[{sign}] 0x{int2hex(blockaddr)}: {list2hex(data)} {bytes2str(data)}\", additional)\n\n def _write_block(self, blockaddr, data, *, key=None, force=False) -> bool:\n if not force and blockaddr not in self.DATA_BLOCKS:\n raise ValueError(\n f\"Operation CANCELLED! Writing block {blockaddr} could make the tag unusable! Use force=true with caution!\")\n elif len(data) > 16:\n raise ValueError(\"Must be 16 bytes!\")\n elif len(data) < 16:\n data += b'\\x00' * (16 - len(data))\n\n if not self._authenticate_block(blockaddr, key):\n return False\n\n stat = self.rdr.mifare_write(blockaddr, data)\n if stat != MFRC522.OK:\n raise NFCWritingException(\n f\"[>!] 0x{blockaddr:02x}: Writing failed! ({stat})\")\n\n self._print_block(blockaddr, data, '>>')\n return True\n\n def _clear_block(self, blockaddr, *, key=None, force=False) -> bool:\n return self._write_block(blockaddr, b'\\x00' * 16, key=key, force=force)\n\n def _read_block(self, blockaddr, *, key=None) -> list | None:\n if not self._authenticate_block(blockaddr, key=key):\n return None\n\n stat, data = self.rdr.mifare_read(blockaddr)\n if stat != MFRC522.OK:\n raise NFCReadingException(\n f\"[!<] 0x{blockaddr:02x}: Reading failed! ({stat})\")\n\n if len(data) != 16:\n print(\n f\"[!<] 0x{blockaddr:02x}: Reading failed! (invalid data length: {len(data)} ({data}))\")\n return None\n\n self._print_block(blockaddr, data, '<<')\n return data\n\n def _override_block(self, blockaddr, data, pos=0, key=None, force=False) -> bool:\n if len(data) + pos > 16:\n raise ValueError(\"Must be 16 bytes!\")\n\n olddata = self._read_block(blockaddr, key) or b'\\x00' * 16\n\n newdata = olddata[:pos] + list(data) + olddata[pos + len(data):]\n return self._write_block(blockaddr, newdata, key, force)\n\n def read_blocks(self, addresses=range(0x00, 0x40), key=None) -> list:\n data = []\n\n for i in addresses:\n block = self._read_block(i, key=key)\n if not block:\n break\n data.append(block)\n return data\n\n def data_read(self, *, blocks=DATA_BLOCKS, key=None) -> list:\n \"\"\"Read all data blocks (excluding the empty keyb blocks)\"\"\"\n return self.read_blocks(blocks, key=key)\n\n def data_clear(self, *, blocks=DATA_BLOCKS, key=None) -> bool:\n \"\"\"Clear all data blocks (excluding the empty keyb blocks)\"\"\"\n for i in blocks:\n if not self._clear_block(i, key=key):\n return False\n return True\n\n def data_write(self, data, *, blocks=DATA_BLOCKS, key=None) -> bool:\n \"\"\"Write to all data blocks (only if needed, excluding the empty keyb blocks)\"\"\"\n if isinstance(data, str):\n data = data.encode('utf-8')\n elif not isinstance(data, bytes):\n raise ValueError(\"Data must be a string or bytes!\")\n\n bs = self.BLOCK_SIZE\n\n blocks_required = math.ceil(len(data) / bs)\n blocks_available = len(blocks)\n if blocks_required > blocks_available:\n raise ValueError(\n f\"Data too long! {blocks_required} blocks required, but only {blocks_available} available!\")\n\n for i in range(blocks_required):\n if not self._write_block(blocks[i], data[i*bs:(i+1)*bs], key=key):\n return False\n return True\n\n\nclass NFCReader(MFRC522):\n \"Class based functions for the MFRC522\"\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n print(\"[--] NFC Reader initialized!\")\n\n def get_tag(self) -> NFCTag | None:\n \"\"\"Get a tag if there is one, otherwise return None\"\"\"\n\n (stat, tag_type) = self.request(MFRC522.REQALL)\n if stat == MFRC522.OK:\n (stat, raw_uid) = self.anticoll()\n if stat == MFRC522.OK:\n if self.select_tag(raw_uid) == MFRC522.OK:\n tag = NFCTag(self, raw_uid, tag_type)\n print(\"[++] Found tag:\", tag)\n return tag\n return None\n\n def scan_for_tag(self) -> NFCTag:\n \"\"\"Scan for a tag and return a NFCTag object if found\"\"\"\n\n print(\"[--] Scanning for tag...\")\n\n while True:\n tag = self.get_tag()\n if tag is not None:\n return tag\n","repo_name":"rafaelurben/circuitpy-nfc","sub_path":"nfc_tools.py","file_name":"nfc_tools.py","file_ext":"py","file_size_in_byte":6934,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"81"} +{"seq_id":"26407578939","text":"# Import Bibliothek\nfrom gpiozero import Button\nfrom signal import pause\nfrom os import system\n\n#Initialisierung GPIO16, 26 und 27\nbutton3w1 = Button(27)\nbutton3wA = Button(16)\nbuttonSC1 = Button(26)\n\n#Funktion definieren\ndef start_3w1():\n print(\"Script pi-3w1 is starting\")\n system(\"/home/pi/Seeburg-IO/./pi-3w1\")\ndef start_3wA():\n print(\"Script pi-3wa is starting\")\n system(\"/home/pi/Seeburg-IO/./pi-3wa\")\ndef start_SC1():\n print(\"Script pi-sc1 is starting\")\n system(\"/home/pi/Seeburg-IO/./pi-sc1\")\n\n#Selektion auslesen (Starten einer Funktion, abhängig von der Position des Drehschalters)\n#Position Links (GPIO..) -> SC1\n#Position Mitte (GPIO..) -> 3wA\n#Position Rechts (GPIO..) -> 3w1/3w100\n\nif button3w1.is_pressed:\n start_3w1()\nelse:\n if button3wA.is_pressed:\n start_3wA()\n else:\n if buttonSC1.is_pressed:\n start_SC1()\n else:\n print (\"No selection.\")\n\npause()\n","repo_name":"Abac71/Seeburg-IO","sub_path":"seeburg-start.py","file_name":"seeburg-start.py","file_ext":"py","file_size_in_byte":896,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"6198891975","text":"from datetime import date, datetime, time, timedelta\n\nfrom . import delay, limit, occur, once, onceevent\n\n\nasync def attime(dt: datetime | date | time):\n while True:\n now = datetime.now()\n\n if isinstance(dt, datetime):\n cdt = dt\n elif isinstance(dt, date):\n cdt = datetime(dt.year, dt.month, dt.day,\n now.hour, now.minute, now.second)\n elif isinstance(dt, time):\n cdt = datetime(now.year, now.month, now.day,\n dt.hour, dt.minute, dt.second)\n if cdt < now:\n cdt = cdt + timedelta(days=1)\n\n if cdt.date() == now.date() and cdt.hour == now.hour and cdt.minute == now.minute and cdt.second == now.second:\n yield\n elif now < cdt:\n await occur(delay(cdt - now))\n yield\n else:\n break\n\n print(dt, cdt, datetime.now())\n\n # go to next time span\n\n if isinstance(dt, time):\n await occur(delay(timedelta(hours=1)))\n elif isinstance(dt, datetime):\n await occur(delay(timedelta(seconds=1)))\n\n\ndef tomorrow():\n return attime(date.today() + timedelta(days=1))\n\n\ndef nextWeek():\n return attime(date.today() + timedelta(days=7))\n\n\nasync def weekdays(*weekdays: int):\n while True:\n today = date.today()\n cur = today.weekday()\n if cur in weekdays:\n yield\n else:\n done = False\n for i in range(1, 8):\n if (cur + i) % 7 in weekdays:\n done = True\n await occur(attime(today+timedelta(days=i)))\n yield\n await occur(tomorrow())\n if not done:\n break\n\nmonday = weekdays(0)\ntuesday = weekdays(1)\nwednesday = weekdays(2)\nthursday = weekdays(3)\nfriday = weekdays(4)\nsaturday = weekdays(5)\nsunday = weekdays(6)\n\nweekday = weekdays(0, 1, 2, 3, 4)\nweekend = weekdays(5, 6)\n","repo_name":"StardustDL/coxbuild","sub_path":"src/coxbuild/events/datetime.py","file_name":"datetime.py","file_ext":"py","file_size_in_byte":1981,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"81"} +{"seq_id":"39042013804","text":"import cv2\nimport numpy as np\n\n# reading video\n\ncap=cv2.VideoCapture(\"vtest.avi\")\n\nres,frame1=cap.read()\nres,frame2=cap.read()\n\nwhile(1):\n\n diff=cv2.absdiff(frame1,frame2)\n\n gray=cv2.cvtColor(diff,cv2.COLOR_RGB2GRAY)\n\n blur=cv2.GaussianBlur(gray,(3,3),0)\n\n _,thres=cv2.threshold(blur,20,255,cv2.THRESH_BINARY)\n\n dilated=cv2.dilate(thres,None,iterations=3)\n\n countour,_=cv2.findContours(dilated,cv2.RETR_TREE,cv2.CHAIN_APPROX_NONE)\n\n\n for i in countour:\n (x,y,w,h)=cv2.boundingRect(i)\n\n if cv2.contourArea(i)<1400:\n continue\n\n cv2.rectangle(frame1,(x,y),(x+w,y+h),(0,255,0),2)\n\n cv2.putText(frame1,\"Status\".format(\"Movement\"),(10,20),cv2.FONT_HERSHEY_SIMPLEX,1,(2,0,255),3)\n\n\n cv2.imshow(\"feed\",frame1)\n\n frame1=frame2\n _,frame2=cap.read()\n\n if cv2.waitKey(35)==27:\n break\n\ncv2.destroyAllWindows()\ncap.release()\n","repo_name":"Pratul-1443/Motion_Detection","sub_path":"Source_code.py","file_name":"Source_code.py","file_ext":"py","file_size_in_byte":890,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"37243482575","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\n@author: Yi-Ru Cheng\r\n\"\"\"\r\n\r\nimport numpy\r\nimport gensim\r\nimport os\r\nfrom collections import OrderedDict\r\n\r\n\r\ndataset_dir = '../../sample-en-dataset'\r\ncentroid_dir = 'EE_freq200_centroid'\r\n\r\nmodel = gensim.models.Word2Vec.load('/home/mosman/work/Thesis/ThesisProject/ProjectDataLibs/rdf2vec/rdf2vec')\r\nfor topic in os.listdir(dataset_dir):\r\n print('***********************'+topic)\r\n topic_dir = os.path.join(dataset_dir, topic, 'tagMe')\r\n \r\n if not os.path.exists(os.path.join(centroid_dir, topic)):\r\n os.makedirs(os.path.join(centroid_dir, topic))\r\n \r\n for doc in os.listdir(topic_dir):\r\n with open(os.path.join(topic_dir, doc), 'r', encoding='utf-8-sig') as f:\r\n content = [l.strip() for l in f.read().split('|') if l.strip()]\r\n f.close()\r\n \r\n entities = {}\r\n for e in content:\r\n if e in entities.keys():\r\n curr_freq = entities['dbr:'+e.replace(' ', '_')]\r\n entities['dbr:'+e.replace(' ', '_')] = curr_freq+1\r\n else:\r\n entities['dbr:'+e.replace(' ', '_')] = 1\r\n \r\n entities = OrderedDict(sorted(entities.items(), key=lambda x: x[1], reverse=True)[:200])\r\n\r\n #calculate centroid vector\r\n try:\r\n centric = sum(model.wv[e] for e in entities.keys() if e in model) / len([model.wv[e] for e in entities.keys() if e in model])\r\n except ZeroDivisionError:\r\n centric = numpy.zeros(shape=200)\r\n centric.dump(os.path.join(centroid_dir, topic, doc))\r\n \r\ndel model","repo_name":"YiruCheng/master_thesis","sub_path":"Entity_Embedding/generateCentroid_freq.py","file_name":"generateCentroid_freq.py","file_ext":"py","file_size_in_byte":1592,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"70743123146","text":"import torch\nfrom torch import nn\nfrom torch.nn import functional as F\nimport torchvision\nimport pytorch_lightning as pl\nfrom collections import OrderedDict\nfrom utils.blocks import conv, scaling, ResBlock\nfrom utils.loss import compute_gradient_penalty\nfrom utils.dataloader import get_dataloader\n\n\nclass Generator(nn.Module):\n def __init__(self, args):\n super(Generator, self).__init__()\n\n self.ngf = args.ngf\n # self.init_size = args.image_size // 4\n # self.stem = nn.Linear(args.latent_dim, 2 * args.ngf * (self.init_size ** 2))\n\n def stem(in_feat, out_feat, kernel_size, strid, padding):\n layers = [\n nn.ConvTranspose2d(in_feat, out_feat, kernel_size, strid, padding, bias=False),\n nn.BatchNorm2d(out_feat),\n nn.LeakyReLU(0.2, inplace=True)\n ]\n return layers\n\n def block(in_feat, out_feat, kernel_size, stride, padding):\n layers = [\n nn.Upsample(scale_factor=2),\n nn.Conv2d(in_feat, out_feat, kernel_size, stride, padding, bias=False),\n nn.BatchNorm2d(out_feat, 0.8),\n nn.LeakyReLU(0.2, inplace=True)]\n return layers\n\n def last_block(in_feat, out_feat):\n layer = [\n nn.Upsample(scale_factor=2),\n nn.Conv2d(in_feat, out_feat, 3, 1, 1, bias=False),\n nn.Tanh()\n ]\n return layer\n\n self.stem = nn.Sequential(*stem(args.latent_dim, 8 * args.ngf, 4, 1, 0))\n self.model = nn.Sequential(\n *block(8 * args.ngf, 4 * args.ngf, 3, 1, 1),\n *block(4 * args.ngf, 2 * args.ngf, 3, 1, 1),\n *last_block(2 * args.ngf, args.channels),\n )\n\n def forward(self, z):\n init_img = self.stem(z)\n # init_img = init_img.view(z.size(0), 2 * self.ngf, self.init_size, self.init_size)\n img = self.model(init_img)\n\n return img\n\nclass Discriminator(nn.Module):\n def __init__(self, args):\n super(Discriminator, self).__init__()\n\n def discriminator_block(in_filters, out_filters):\n block = [\n nn.Conv2d(in_filters, out_filters, 4, 2, 1, bias=False),\n nn.LeakyReLU(0.2, inplace=True)\n ]\n return block\n\n self.model = nn.Sequential(\n *discriminator_block(args.channels, args.ndf),\n *discriminator_block(args.ndf, args.ndf * 2),\n *discriminator_block(args.ndf * 2, args.ndf * 4),\n *discriminator_block(args.ndf * 4, args.ndf * 8), # 2 x 2\n )\n\n # The height and width of downsampled image\n ds_size = args.image_size // 2 ** 4\n self.adv_layer = nn.Sequential(\n nn.Linear(args.ndf * 8 * ds_size ** 2, 1),\n nn.Sigmoid()\n )\n\n def forward(self, img):\n out = self.model(img)\n out = out.view(img.size(0), -1)\n validity = self.adv_layer(out)\n return validity\n\n\nclass wGANGP(pl.LightningModule):\n def __init__(self, hparams):\n super(wGANGP, self).__init__()\n self.hparams = hparams\n\n # networks\n self.generator, self.discriminator = self.__network_initialization(hparams)\n\n # cache for generated images\n self.generated_imgs = None\n self.last_imgs = None\n\n def forward(self, z):\n return self.generator(z)\n\n def criterion_gan(self, y_hat, y):\n # y_hat = y_hat.squeeze(2).squeeze(2)\n return F.binary_cross_entropy(y_hat, y)\n\n def training_step(self, batch, batch_nb, optimizer_idx):\n imgs, labels = batch\n self.last_imgs = imgs\n\n # train generator\n if optimizer_idx == 0:\n z = torch.rand(imgs.size(0), self.hparams.latent_dim, 1, 1)\n valid = torch.ones((imgs.size(0), 1))\n\n if self.on_gpu:\n z = z.cuda(imgs.device.index)\n valid = valid.cuda(imgs.device.index)\n\n fake_imgs = self(z)\n\n # g loss\n fake_validity = self.discriminator(fake_imgs)\n g_loss = self.criterion_gan(fake_validity, valid)\n\n tqdm_dict = {'g_loss': g_loss}\n output = OrderedDict({\n 'loss': g_loss,\n 'progress_bar': tqdm_dict,\n 'log': tqdm_dict,\n })\n return output\n\n # train discriminator\n if optimizer_idx == 1:\n valid = torch.ones((imgs.size(0), 1))\n fake = torch.zeros((imgs.size(0), 1))\n z = torch.rand(imgs.size(0), self.hparams.latent_dim, 1, 1)\n\n if self.on_gpu:\n z = z.cuda(imgs.device.index)\n valid = valid.cuda(imgs.device.index)\n fake = fake.cuda(imgs.device.index)\n\n # d loss\n real_validity = self.discriminator(imgs)\n real_loss = self.criterion_gan(real_validity, valid)\n\n fake_imgs = self(z)\n fake_validity = self.discriminator(fake_imgs.detach())\n fake_loss = self.criterion_gan(fake_validity, fake)\n\n gp_loss = compute_gradient_penalty(\n self.hparams, self.discriminator, imgs, fake_imgs.detach(), self.on_gpu)\n d_loss = (real_loss + fake_loss)/2 + gp_loss\n tqdm_dict = {'d_loss': d_loss}\n output = OrderedDict({\n 'loss': d_loss,\n 'progress_bar': tqdm_dict,\n 'log': tqdm_dict\n })\n return output\n\n def on_epoch_end(self):\n z = torch.rand(self.last_imgs.size(0), self.hparams.latent_dim, 1, 1)\n if self.on_gpu:\n z = z.cuda(self.last_imgs.device.index)\n\n sample_imgs = self(z)\n grid = torchvision.utils.make_grid(sample_imgs[:16], normalize=True, nrow=4)\n self.logger.experiment.add_image(f'images', grid, self.current_epoch)\n\n def configure_optimizers(self):\n lr = self.hparams.lr\n b1 = self.hparams.b1\n b2 = self.hparams.b2\n\n opt_g = torch.optim.Adam(self.generator.parameters(), lr=lr, betas=(b1, b2))\n opt_d = torch.optim.Adam(self.discriminator.parameters(), lr=lr, betas=(b1, b2))\n n_critic = 5\n\n return(\n {'optimizer': opt_g, 'frequency': 1},\n {'optimizer': opt_d, 'frequency': n_critic},\n )\n\n def train_dataloader(self):\n trn_dataloader, _, _ = get_dataloader(self.hparams)\n return trn_dataloader\n\n def __weights_init(self, m):\n classname = m.__class__.__name__\n if classname.find('Conv') != -1 or classname.find('Linear') != -1:\n m.weight.data.normal_(0.0, 0.02)\n elif classname.find('BatchNorm') != -1:\n m.weight.data.normal_(1.0, 0.02)\n m.bias.data.fill_(0)\n\n def __network_initialization(self, args):\n netG = Generator(args)\n netD = Discriminator(args)\n\n # network initialization\n netG.apply(self.__weights_init)\n netD.apply(self.__weights_init)\n\n return netG, netD","repo_name":"lepoeme20/GANs","sub_path":"wGAN-gp/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":7058,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"81"} +{"seq_id":"2310184854","text":"from bs4 import BeautifulSoup\nimport requests\nimport time\nimport re\nfrom dotenv import load_dotenv\nfrom datetime import datetime\nimport shortuuid\nimport os\nimport sys\n\nclass StockNotifier:\n def __init__(self, country):\n self.s = requests.Session()\n load_dotenv()\n self.phoneAPIToken = os.environ.get(\"API_TOKEN\")\n self.userAPIKey = os.environ.get(\"USER_KEY\")\n soup = self.__getWebPage()\n self.token = self.__extractLocalToken(soup)\n self.inStock = {}\n self.country = country\n\n def __getWebPage(self):\n r = self.s.get(\"https://rpilocator.com/?country=UK\")\n soup = BeautifulSoup(r.text, \"lxml\")\n return soup\n\n def __extractLocalToken(self, soup):\n # Extract token for Website API call\n scripts = soup.find_all(\"script\")\n tokenScriptTag = list(\n filter(lambda tag: \"localToken\" in str(tag.string), scripts))\n contents = str(tokenScriptTag[0].string)\n tokenVar = re.search(r\"localToken=(\\\"|\\\").+(\\\"|\\\")\", contents).group()\n token = re.search(r\"(\\\"|\\\").+(\\\"|\\\")\", tokenVar).group().strip(\"\\\"\\\"\")\n\n print(\"\\nRetrieved Token: {}\\n\\n\".format(token))\n return token \n\n def reconnectToServer(self):\n self.s = requests.Session()\n soup = self.__getWebPage()\n self.token = self.__extractLocalToken(soup)\n \n def setStoredStock(self, stock):\n for item in stock:\n id, itemStr = self.formatItem(item)\n self.inStock[id] = itemStr\n \n def clearStoredStock(self):\n self.inStock = {}\n \n def getStoredStock(self):\n return self.inStock\n\n def getCurrentStock(self):\n # Set up request headers and params\n headers = {\"Connection\": \"keep-alive\",\n \"Accept\": \"application/json\",\n \"Accept-Encoding\": \"gzip, deflate\",\n \"Accept-Language\": \"en-US,en;q=0.5\",\n \"Host\": \"rpilocator.com\",\n \"Referer\": \"https://rpilocator.com/?country=UK\",\n \"Sec-Fetch-Dest\": \"empty\",\n \"Sec-Fetch-Mode\": \"cors\",\n \"Sec-Fetch-Site\": \"same-origin\",\n \"TE\": \"trailers\",\n \"X-Requested-With\": \"XMLHttpRequest\"}\n payload = {}\n if self.country:\n payload = {\"method\": \"getProductTable\", \"token\": self.token,\n \"country\": self.country, \"_\": \"1677696951662\"}\n else:\n payload = {\"method\": \"getProductTable\", \"token\": self.token,\n \"_\": \"1677696951662\"}\n url = \"https://rpilocator.com/data.cfm\"\n\n try:\n r = self.s.get(url, params=payload, headers=headers)\n return r.json()\n except requests.exceptions.RequestException as e:\n t = datetime.now()\n print(\"{}: {}\\n\".format(t.strftime('%a, %d %b %Y %H:%M:%S'), e))\n with open(\"requestLog.txt\", \"a+\") as f:\n f.write(\"{}: {}\\n\".format(t.strftime('%a, %d %b %Y %H:%M:%S'), e))\n self.reconnectToServer()\n \n return {\"data\": []}\n\n def sendNotification(self, stock):\n message = \"\"\n for item in stock:\n message = stock[item]\n payload = {\"token\": self.phoneAPIToken, \"user\": self.userAPIKey, \"message\": message}\n r = requests.post(\"https://api.pushover.net/1/messages.json\", params=payload)\n \n def formatItem(self, item):\n itemStr = \"{} is in stock in {}! Link to buy --> {}\".format(\n item[\"description\"],\n item[\"vendor\"], \n item[\"link\"])\n id = shortuuid.uuid(name = itemStr)\n return id, itemStr\n\n def filterAndGetNewStock(self, stock):\n #get list of all current items in stock\n #compare items with previous stock check and add those\n newStock = {}\n for item in stock[\"data\"]:\n id, itemStr = self.formatItem(item)\n if item[\"avail\"] == \"Yes\":\n if id not in self.inStock:\n newStock[id] = itemStr\n self.inStock[id] = itemStr\n \n else: #remove item from inStock if no longer available\n if id in self.inStock:\n del self.inStock[id]\n \n return newStock\n\n def main(self):\n\n while True:\n stock = self.getCurrentStock()\n newStock = self.filterAndGetNewStock(stock)\n \n # Send notification\n if newStock:\n self.sendNotification(newStock)\n\n time.sleep(5)\n\nif __name__ == \"__main__\":\n country = \"\"\n countries = {\n \"australia\": \"AU\", \n \"austria\": \"AT\", \n \"belgium\": \"BE\", \n \"canada\": \"CE\",\n \"china\": \"CN\",\n \"france\": \"FR\",\n \"germany\": \"DE\",\n \"italy\": \"IT\",\n \"mexico\": \"MX\",\n \"netherlands\": \"NL\",\n \"poland\": \"PL\",\n \"portugal\": \"PT\",\n \"south africa\": \"ZA\",\n \"spain\": \"ES\",\n \"sweden\": \"SE\",\n \"switzerland\": \"CH\",\n \"united kingdom\": \"UK\",\n \"united states\": \"US\"\n }\n\n if 2 <= len(sys.argv) <= 3:\n args = sys.argv[1:]\n country = \" \".join(args)\n if country not in countries:\n raise KeyError(\"Country not found\")\n country = countries[country]\n elif len(sys.argv) == 1:\n pass\n else:\n raise IndexError(\"Too many args given\")\n \n notifier = StockNotifier(country)\n notifier.main()\n","repo_name":"jonemilnik/RaspberryPi-Stock-Scraper-And-Notifier","sub_path":"raspbStockNotifier.py","file_name":"raspbStockNotifier.py","file_ext":"py","file_size_in_byte":5520,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"22566011371","text":"from django.conf.urls.defaults import *\nfrom django.conf import settings\nfrom django.contrib import admin\n\nfrom q.accounts.views import login, logout\n\n\nadmin.autodiscover()\n\nurlpatterns = patterns('',\n (r'^books/', include('q.ebooks.urls')),\n (r'^users/', include('q.accounts.urls')),\n (r'^admin/', include(admin.site.urls)),\n (r'^$', login),\n url(r'^login/$', login, name='login'),\n url(r'^logout/$', logout, name='logout'),\n (r'^comments/', include('django.contrib.comments.urls')),\n)\n\nif settings.DEBUG:\n\turlpatterns += patterns('django.views.static',\n\t (r'^css/(?P.*)$', 'serve',\n\t {'document_root': settings.TEMPLATE_DIRS[0]+'/css/'}),\n\t (r'^images/(?P.*)$', 'serve',\n\t {'document_root': settings.TEMPLATE_DIRS[0]+'/images/'}),\n\t (r'^javascript/(?P.*)$', 'serve',\n\t {'document_root': settings.TEMPLATE_DIRS[0]+'/javascript/'}),\n\t)\n","repo_name":"GunioRobot/q","sub_path":"src/q/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":907,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"81"} +{"seq_id":"30396270588","text":"from __future__ import print_function \nimport argparse\nimport json\nimport os\nimport os.path\nimport shutil\n\n\ndef copy_tree_by_catalog(catalog_file, input_dir, output_dir):\n extra = ['LICENSE']\n with open(catalog_file) as fh:\n catalog = json.load(fh)\n catalog.extend(extra)\n for entry in catalog:\n if entry in extra:\n fref = entry\n else:\n bits = entry.split('/')\n bits = bits[2:]\n fref = '/'.join(bits)\n if not fref:\n raise Exception(\"Bad catalog entry: '{}'\".format(entry))\n src = os.path.normpath(os.path.abspath(os.path.join(input_dir, fref)))\n if not os.path.isfile(src):\n if fref in [ 'PC/invalid_parameter_handler.c' ]:\n continue\n dest = os.path.normpath(os.path.abspath(os.path.join(output_dir, fref)))\n dest_dir = os.path.dirname(dest)\n if not os.path.isdir(dest_dir):\n os.makedirs(dest_dir)\n print(\"['{}'] - {} >>> {}\".format(fref, src, dest))\n shutil.copyfile(src, dest)\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('--catalog', nargs=1, type=str, required=True)\n parser.add_argument('--input', nargs=1, type=str, required=True)\n parser.add_argument('--output', nargs=1, type=str, required=True)\n args = parser.parse_args()\n\n catalog_file = args.catalog[0]\n input_dir = args.input[0]\n output_dir = args.output[0]\n\n copy_tree_by_catalog(catalog_file, input_dir, output_dir)\n print('Done!')\n","repo_name":"vmurashev/pyconfig","sub_path":"populate.py","file_name":"populate.py","file_ext":"py","file_size_in_byte":1549,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"72104590986","text":"import sys\r\nimport math\r\nimport argparse\r\n\r\nimport torch\r\nimport torch.nn as nn\r\nimport torch.nn.functional as F\r\nimport torchvision\r\nfrom torchvision import transforms\r\nimport numpy as np\r\nimport preconditioned_stochastic_gradient_descent as psgd\r\nfrom tqdm import tqdm\r\nimport random\r\nimport os\r\nfrom torch.autograd import Variable\r\nimport random\r\nimport copy\r\nimport math\r\nfrom data_loaders.loaders import *\r\nfrom models.resnet import ResNet18\r\nfrom reproduce.seeds import *\r\n\r\nparser = argparse.ArgumentParser()\r\nparser.add_argument(\"--experiment\", default='cifar10', help=\"pick which experiment\")\r\nparser.add_argument(\"--stage2\", default='cifar10', help=\"pick stage2 of experiment\")\r\nparser.add_argument(\"--epoch_concept_switch\", default=201, help=\"when should we switch to stage2 of experiment\")\r\nparser.add_argument(\"--num_epoch\", default=200, help=\"how long should our full experiment be\")\r\nparser.add_argument(\"--device\", default='cuda:0', help=\"for example, cuda:0\")\r\nparser.add_argument(\"--optimizer\", default='PSGD_XMat', help=\"choices are SGD, PSGD_XMat and PSGD_UVd\")\r\nparser.add_argument(\"--lr_scheduler\", default='cos', help=\"choices are stage and cos\")\r\nparser.add_argument(\"--shortcut_connection\", default=1, type=int, help=\"choices are 0 and 1\")\r\nparser.add_argument('--seed', default=2048, type=int, help='random seed')\r\nparser.add_argument('--data_seed', default=1738, type=int, help='random data_seed')\r\nparser.add_argument('--data_root', default='./data/ntga_cnn_best', help='root of data')\r\n\r\n\r\nargs = parser.parse_args()\r\nexperiment = args.experiment\r\nstage2 = args.stage2\r\nnum_epoch = args.num_epoch\r\nepoch_concept_switch = args.epoch_concept_switch\r\ndevice = torch.device(args.device)\r\noptimizer = args.optimizer\r\nlr_scheduler = args.lr_scheduler\r\nshortcut_connection = bool(args.shortcut_connection)\r\nseed = args.seed\r\ndata_seed = args.data_seed\r\ndata_root = args.data_root\r\nprint(\"Experiment Stage 1: \\t\\t\\t{}\".format(experiment))\r\nprint(\"Experiment Stage 2: \\t\\t\\t{}\".format(stage2))\r\nprint(\"Total Epochs: \\t\\t\\t{}\".format(num_epoch))\r\nprint(\"Change Experiment at Epoch: \\t\\t\\t{}\".format(epoch_concept_switch))\r\nprint(\"Device: \\t\\t\\t{}\".format(device))\r\nprint(\"Optimizer: \\t\\t\\t{}\".format(optimizer))\r\nprint(\"Learning rate schedular:\\t{}\".format(lr_scheduler))\r\nprint(\"With short connections: \\t{}\".format(shortcut_connection))\r\nprint(\"Seed: \\t\\t\\t\\t{}\".format(seed))\r\nprint(\"Data Seed: \\t\\t\\t{}\".format(data_seed))\r\nprint(\"Data Root: \\t\\t\\t{}\".format(data_root))\r\n\r\nset_seed(args.seed)\r\nset_cuda(deterministic=True)\r\n\r\n\r\nif optimizer == 'SGD':\r\n lr0 = 1.0 # 0.1 -> 1.0 when momentum factor = 0.9 as momentum in PSGD is the moving average of gradient\r\n decay = 5e-4\r\nelse: # PSGD_XMat or PSGD_UVd\r\n lr0 = 2e-2\r\n if shortcut_connection:\r\n decay = 2e-2\r\n else:\r\n decay = 1e-2\r\n\r\nif shortcut_connection:\r\n batchsize = 128\r\nelse:\r\n batchsize = 64\r\n\r\ndef test(net, device, data_loader, criterion):\r\n if torch.__version__.startswith('2'):\r\n net = torch.compile(net) \r\n net.eval()\r\n test_loss = 0\r\n correct = 0\r\n total = 0\r\n with torch.no_grad():\r\n for batch_idx, (inputs, targets, index) in enumerate(data_loader):\r\n # for batch_idx, (inputs, targets) in tqdm( enumerate(data_loader), total = len(data_loader)):\r\n inputs, targets = inputs.to(device), targets.to(device)\r\n outputs = net(inputs)\r\n loss = criterion(outputs, targets)\r\n\r\n test_loss += loss.item()\r\n _, predicted = outputs.max(1)\r\n total += targets.size(0)\r\n correct += predicted.eq(targets).sum().item()\r\n\r\n accuracy = 100.0 * correct / total\r\n\r\n return accuracy\r\n\r\ndef test_clean(net, device, data_loader, criterion):\r\n if torch.__version__.startswith('2'):\r\n net = torch.compile(net) \r\n net.eval()\r\n test_loss = 0\r\n correct = 0\r\n total = 0\r\n with torch.no_grad():\r\n for batch_idx, (inputs, targets) in enumerate(data_loader):\r\n # for batch_idx, (inputs, targets) in tqdm( enumerate(data_loader), total = len(data_loader)):\r\n inputs, targets = inputs.to(device), targets.to(device)\r\n outputs = net(inputs)\r\n loss = criterion(outputs, targets)\r\n\r\n test_loss += loss.item()\r\n _, predicted = outputs.max(1)\r\n total += targets.size(0)\r\n correct += predicted.eq(targets).sum().item()\r\n\r\n accuracy = 100.0 * correct / total\r\n\r\n return accuracy\r\n\r\ndef train(net, device, train_loader, loss_cores,noise_prior_cur):\r\n if torch.__version__.startswith('2'):\r\n net = torch.compile(net) \r\n net.train() # do not forget it as there is BN\r\n total = 0\r\n train_loss = 0\r\n correct = 0\r\n v_list = np.zeros(num_training_samples)\r\n idx_each_class_noisy = [[] for i in range(num_classes)]\r\n if not isinstance(noise_prior_cur, torch.Tensor):\r\n noise_prior_cur = torch.tensor(noise_prior_cur.astype('float32')).to(device).unsqueeze(0)\r\n\r\n for batch_idx, (inputs, targets, indexes) in tqdm( enumerate(train_loader), total = len(train_loader)):\r\n inputs, targets = inputs.to(device), targets.to(device)\r\n ind=indexes.cpu().numpy().transpose()\r\n batch_size = len(ind)\r\n class_list = range(num_classes)\r\n\r\n outputs = net(inputs)\r\n\r\n loss, loss_v = loss_cores(epoch, outputs, targets ,class_list,ind, True, noise_prior = noise_prior_cur )\r\n loss + sum(\r\n [torch.sum(decay * torch.rand_like(param) * param * param) for param in net.parameters()]\r\n )\r\n v_list[ind] = loss_v\r\n for i in range(batch_size):\r\n if loss_v[i] == 0:\r\n idx_each_class_noisy[targets[i]].append(ind[i])\r\n\r\n def closure():\r\n \"\"\"\r\n Weight decaying is explicitly realized by adding L2 regularization to the loss\r\n \"\"\"\r\n\r\n return loss, loss_v , outputs\r\n\r\n loss, loss_v, outputs = opt.step(closure)\r\n\r\n train_loss += loss.item()\r\n _, predicted = outputs.max(1)\r\n total += targets.size(0)\r\n correct += predicted.eq(targets).sum().item()\r\n\r\n # make new noise prior\r\n class_size_noisy = [len(idx_each_class_noisy[i]) for i in range(num_classes)]\r\n noise_prior_delta = np.array(class_size_noisy)\r\n noise_prior_cur = noise_prior*num_training_samples - noise_prior_delta\r\n noise_prior_cur = noise_prior_cur/sum(noise_prior_cur)\r\n\r\n train_accuracy = 100.0 * correct / total \r\n return train_loss, train_accuracy, noise_prior_cur\r\n\r\nset_seed(args.seed)\r\nnet = ResNet18(shortcut_connection=True).to(device)\r\n\r\nif optimizer == 'SGD':\r\n # SGD baseline\r\n opt = psgd.XMat(\r\n net.parameters(),\r\n lr_params = lr0, # note that momentum in PSGD is the moving average of gradient\r\n momentum = 0.9, # so lr 0.1 becomes 1 when momentum factor is 0.9\r\n preconditioner_update_probability = 0.0, # PSGD reduces to SGD when P = eye()\r\n )\r\nelif optimizer == 'PSGD_XMat':\r\n # PSGD with X-shape matrix preconditioner\r\n opt = psgd.XMat(\r\n net.parameters(),\r\n lr_params = lr0,\r\n momentum = 0.9,\r\n preconditioner_update_probability = 0.1,\r\n )\r\nelse:\r\n # PSGD with low rank approximation preconditioner\r\n opt = psgd.UVd(\r\n net.parameters(),\r\n rank_of_approximation = 50,\r\n lr_params = lr0,\r\n momentum = 0.9,\r\n preconditioner_update_probability = 0.1,\r\n )\r\n\r\n# stage 1 of experiment\r\n# please note noisy label experiment requires different training loop -- see psgd_cifar10_noisy_label.py \r\ntrain_loader, init_noise_prior, test_loader = get_dataset(experiment, batchsize, data_root, seed, data_seed)\r\nnum_classes = 10\r\nnum_training_samples = 50000\r\n\r\n\r\ncriterion = nn.CrossEntropyLoss()\r\n\r\ndef loss_cores(epoch, y, t,class_list, ind, noise_or_not, noise_prior = None):\r\n beta = f_beta(epoch)\r\n\r\n loss = F.cross_entropy(y, t, reduce = False)\r\n loss_numpy = loss.data.cpu().numpy()\r\n num_batch = len(loss_numpy)\r\n loss_v = np.zeros(num_batch)\r\n loss_div_numpy = float(np.array(0))\r\n loss_ = -torch.log(F.softmax(y) + 1e-8)\r\n # sel metric\r\n loss_sel = loss - torch.mean(loss_,1)\r\n if noise_prior is None:\r\n loss = loss - beta*torch.mean(loss_,1)\r\n else:\r\n loss = loss - beta*torch.sum(torch.mul(noise_prior, loss_),1)\r\n\r\n loss_div_numpy = loss_sel.data.cpu().numpy()\r\n for i in range(len(loss_numpy)):\r\n if epoch <=30:\r\n loss_v[i] = 1.0\r\n elif loss_div_numpy[i] <= 0:\r\n loss_v[i] = 1.0\r\n loss_v = loss_v.astype(np.float32)\r\n loss_v_var = Variable(torch.from_numpy(loss_v)).to(device)\r\n loss_ = loss_v_var * loss\r\n if sum(loss_v) == 0.0:\r\n return torch.mean(loss_)/100000000\r\n else:\r\n return torch.sum(loss_)/sum(loss_v), loss_v.astype(int)\r\n\r\n#TODO: extend f_beta to 200 epochs -- needs some deeper understanding \r\ndef f_beta(epoch):\r\n beta1 = np.linspace(0.0, 0.0, num=10)\r\n beta2 = np.linspace(0.0, 2, num=30)\r\n beta3 = np.linspace(2, 2, num=60)\r\n\r\n beta = np.concatenate((beta1,beta2,beta3),axis=0)\r\n return beta[epoch]\r\n\r\nnum_epoch = 100\r\ntrain_accs = []\r\ntest_accs = []\r\nnoise_prior = copy.deepcopy(init_noise_prior)\r\nnoise_prior_cur = noise_prior\r\ntest_accuracy_best = -1\r\nfor epoch in range(num_epoch):\r\n if lr_scheduler == 'cos':\r\n opt.lr_params = lr0*(1 + math.cos(math.pi*epoch/num_epoch))/2\r\n else:\r\n # schedule the learning rate\r\n if epoch == int(num_epoch * 0.7):\r\n opt.lr_params *= 0.1\r\n if epoch == int(num_epoch * 0.9):\r\n opt.lr_params *= 0.1\r\n\r\n\r\n train_loss, train_accuracy, noise_prior_cur = train(net, device, train_loader, loss_cores, noise_prior_cur)\r\n test_accuracy = test(net, device, test_loader, criterion)\r\n if test_accuracy > test_accuracy_best:\r\n test_accuracy_best = test_accuracy \r\n\r\n print(\r\n \"epoch: {}; train loss: {:.2f}; train accuracy: {:.2f}; test accuracy: {:.2f}; best test accuracy: {:.2f}\".format(\r\n epoch + 1, train_loss, train_accuracy, test_accuracy, test_accuracy_best\r\n )\r\n )\r\n\r\n train_accs.append(train_accuracy)\r\n test_accs.append(test_accuracy)\r\nprint(\"train_accuracy: {}\".format(train_accs))\r\nprint(\"test_accuracy: {}\".format(test_accs))\r\n\r\n\r\n## if want a stage2...\r\n\r\nif stage2 == 'cifar10':\r\n num_epoch = 100\r\n train_accs = []\r\n test_accs = []\r\n train_loader_clean, test_loader_clean = get_dataset('cifar10',batchsize,data_root,seed,data_seed)\r\n for epoch in range(num_epoch):\r\n if lr_scheduler == 'cos':\r\n opt.lr_params = lr0*(1 + math.cos(math.pi*epoch/num_epoch))/2\r\n else:\r\n # schedule the learning rate\r\n if epoch == int(num_epoch * 0.7):\r\n opt.lr_params *= 0.1\r\n if epoch == int(num_epoch * 0.9):\r\n opt.lr_params *= 0.1\r\n\r\n net.train() # do not forget it as there is BN\r\n total = 0\r\n train_loss = 0\r\n correct = 0\r\n # for batch_idx, (inputs, targets) in enumerate(train_loader):\r\n for batch_idx, (inputs, targets) in tqdm( enumerate(train_loader_clean), total = len(train_loader_clean)):\r\n inputs, targets = inputs.to(device), targets.to(device)\r\n class_list = range(num_classes)\r\n\r\n outputs = net(inputs)\r\n\r\n loss, loss_v = loss_cores(epoch, outputs, targets ,class_list, False, noise_prior = None )\r\n loss + sum(\r\n [torch.sum(decay * torch.rand_like(param) * param * param) for param in net.parameters()]\r\n )\r\n\r\n def closure():\r\n \"\"\"\r\n Weight decaying is explicitly realized by adding L2 regularization to the loss\r\n \"\"\"\r\n return loss\r\n\r\n loss = opt.step(closure)\r\n\r\n train_loss += loss.item()\r\n _, predicted = outputs.max(1)\r\n total += targets.size(0)\r\n correct += predicted.eq(targets).sum().item()\r\n\r\n train_accuracy = 100.0 * correct / total\r\n \r\n\r\n\r\n test_accuracy = test_clean(net, device, test_loader_clean, criterion)\r\n if test_accuracy > test_accuracy_best:\r\n test_accuracy_best = test_accuracy\r\n\r\n print(\r\n \"epoch: {}; train loss: {:.2f}; train accuracy: {:.2f}; test accuracy: {:.2f}; best test accuracy: {:.2f}\".format(\r\n epoch + 1, train_loss, train_accuracy, test_accuracy, test_accuracy_best\r\n )\r\n )\r\n\r\n train_accs.append(train_accuracy)\r\n test_accs.append(test_accuracy)\r\n print(\"train_accuracy: {}\".format(train_accs))\r\n print(\"test_accuracy: {}\".format(test_accs)) \r\n","repo_name":"opooladz/Preconditioned-Stochastic-Gradient-Descent","sub_path":"psgd_cifar10_noisy_label.py","file_name":"psgd_cifar10_noisy_label.py","file_ext":"py","file_size_in_byte":13208,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"81"} +{"seq_id":"10524290840","text":"#!/usr/bin/python3\n# -*- coding: utf-8 -*-\nimport os\n\nfrom ament_index_python.packages import get_package_share_directory\nfrom launch import LaunchDescription\nfrom launch.actions import DeclareLaunchArgument\nfrom launch.actions import IncludeLaunchDescription\nfrom launch.launch_description_sources import PythonLaunchDescriptionSource\nfrom ament_index_python.packages import get_package_prefix\n\n\ndef generate_launch_description():\n\n pkg_gazebo_ros = get_package_share_directory('gazebo_ros')\n pkg_l1br_gazebo = get_package_share_directory('l1br')\n\n # We get the whole install dir\n # We do this to avoid having to copy or softlink manually the packages so that gazebo can find them\n description_package_name = \"l1br\"\n install_dir = get_package_prefix(description_package_name)\n\n # Set the path to the WORLD model files. Is to find the models inside the models folder in my_robot_mode package\n gazebo_models_path = os.path.join(pkg_l1br_gazebo, 'models')\n # os.environ[\"GAZEBO_MODEL_PATH\"] = gazebo_models_path\n\n if 'GAZEBO_MODEL_PATH' in os.environ:\n os.environ['GAZEBO_MODEL_PATH'] = os.environ['GAZEBO_MODEL_PATH'] + \\\n ':' + install_dir + '/share' + ':' + gazebo_models_path\n else:\n os.environ['GAZEBO_MODEL_PATH'] = install_dir + \\\n \"/share\" + ':' + gazebo_models_path\n\n if 'GAZEBO_PLUGIN_PATH' in os.environ:\n os.environ['GAZEBO_PLUGIN_PATH'] = os.environ['GAZEBO_PLUGIN_PATH'] + \\\n ':' + install_dir + '/lib'\n else:\n os.environ['GAZEBO_PLUGIN_PATH'] = install_dir + '/lib'\n\n print(\"GAZEBO MODELS PATH==\"+str(os.environ[\"GAZEBO_MODEL_PATH\"]))\n print(\"GAZEBO PLUGINS PATH==\"+str(os.environ[\"GAZEBO_PLUGIN_PATH\"]))\n\n # Gazebo launch\n gazebo = IncludeLaunchDescription(\n PythonLaunchDescriptionSource(\n os.path.join(pkg_gazebo_ros, 'launch', 'gazebo.launch.py'),\n )\n )\n\n return LaunchDescription([\n DeclareLaunchArgument(\n 'world',\n default_value=[os.path.join(\n pkg_l1br_gazebo, 'worlds', 'warehouse.world'), ''],\n description='SDF world file'),\n gazebo\n ])\n","repo_name":"G4burieru/l1br","sub_path":"launch/start_world.launch.py","file_name":"start_world.launch.py","file_ext":"py","file_size_in_byte":2169,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"81"} +{"seq_id":"86306811438","text":"import pytest\nimport requests\nfrom pactman import Consumer, Includes, Like, Provider\n\n\ndef test_valid_types():\n Includes(\"string\", \"sample data\")\n\n\n@pytest.mark.parametrize(\"object\", [None, list(), dict(), set(), 1, 1.0, b\"bytes\"])\ndef test_invalid_types(object):\n with pytest.raises(AssertionError) as e:\n Includes(object, \"sample data\")\n\n assert \"matcher must be a string\" in str(e.value)\n\n\ndef test_basic_type():\n assert Includes(\"spam\", \"sample data\").generate_matching_rule_v3() == {\n \"matchers\": [{\"match\": \"include\", \"value\": \"spam\"}]\n }\n\n\ndef test_v2_not_allowed():\n with pytest.raises(Includes.NotAllowed):\n Consumer(\"C\").has_pact_with(Provider(\"P\"), version=\"2.0.0\").given(\"g\").upon_receiving(\n \"r\"\n ).with_request(\"post\", \"/foo\", body=Includes(\"bee\", \"been\")).will_respond_with(200)\n\n\ndef test_mock_usage_pass_validation():\n pact = (\n Consumer(\"C\")\n .has_pact_with(Provider(\"P\"), version=\"3.0.0\")\n .given(\"g\")\n .upon_receiving(\"r\")\n .with_request(\"post\", \"/foo\", body=Like({\"a\": \"spam\", \"b\": Includes(\"bee\", \"been\")}))\n .will_respond_with(200)\n )\n\n with pact:\n requests.post(pact.uri + \"/foo\", json={\"a\": \"ham\", \"b\": \"has bee in it\"})\n\n\ndef test_mock_usage_fail_validation():\n pact = (\n Consumer(\"C\")\n .has_pact_with(Provider(\"P\"), version=\"3.0.0\")\n .given(\"g\")\n .upon_receiving(\"r\")\n .with_request(\"post\", \"/foo\", body=Like({\"a\": \"spam\", \"b\": Includes(\"bee\", \"been\")}))\n .will_respond_with(200)\n )\n\n with pytest.raises(AssertionError), pact:\n requests.post(pact.uri + \"/foo\", json={\"a\": \"ham\", \"b\": \"wasp\"})\n","repo_name":"reecetech/pactman","sub_path":"pactman/test/mock_matchers/test_include.py","file_name":"test_include.py","file_ext":"py","file_size_in_byte":1693,"program_lang":"python","lang":"en","doc_type":"code","stars":90,"dataset":"github-code","pt":"81"} +{"seq_id":"39981961757","text":"from phactori import *\nfrom paraview.simple import *\n\n#phactori_combine_to_single_python_file_subpiece_begin_1\nclass PhactoriSliceOperation(PhactoriPlaneOpBase):\n \"\"\"slice operation, settings and handling of slice filter\"\"\"\n\n def CreateParaViewFilter(self, inInputFilter):\n\n #don't need our own init code at this point, but this is how it would be\n #added\n #def __init__(self):\n # MySuperClass.__init__(self)\n\n \"\"\"create the slice plane filter for ParaView\"\"\"\n if PhactoriDbg(100):\n myDebugPrint3('PhactoriSliceOperation.CreateParaViewFilter entered\\n', 100)\n #info in block class should already be parsed and checked\n\n savedActiveSource = GetActiveSource()\n newParaViewFilter = Slice(Input = inInputFilter, SliceType = \"Plane\")\n newParaViewFilter.Triangulatetheslice = 0\n\n self.UpdateSlice(inInputFilter, newParaViewFilter)\n\n SetActiveSource(newParaViewFilter)\n SetActiveSource(savedActiveSource)\n\n if PhactoriDbg(100):\n myDebugPrint3('PhactoriSliceOperation.CreateParaViewFilter returning\\n', 100)\n\n return newParaViewFilter\n\n def DoUpdateDueToChangeInData(self, inIncomingPvFilter,\n outOutgoingPvFilter):\n \"\"\"the PhactoriSliceOperation may need to update if the point on\n the slice plane was tied to a node, element, or variable min/max\n location\"\"\"\n if PhactoriDbg():\n myDebugPrint3(\"PhactoriSliceOperation::\"\n \"DoUpdateDueToChangeInData override executing\\n\")\n\n if self.MayChangeWithData() == False:\n if PhactoriDbg():\n myDebugPrint3(\"PhactoriSlicePlaneOperation::\"\n \"DoUpdateDueToChangeInData returning (absolute point or points)\\n\")\n return\n\n self.UpdateSlice(inIncomingPvFilter, outOutgoingPvFilter)\n\n if PhactoriDbg():\n myDebugPrint3(\"PhactoriSlicePlaneOperation::\"\n \"DoUpdateDueToChangeInData override returning\\n\")\n\n def UpdateSlice(self, inIncomingPvFilter, ioOutgoingPvFilter):\n \"\"\"using the current info on the slice, get all the paraview stuff\n set up correctly\"\"\"\n\n if PhactoriDbg():\n myDebugPrint3(\"PhactoriSlicePlaneOperation::UpdateSlice entered\\n\")\n\n originToUse = [0,0,0]\n normalToUse = [0,1,0]\n self.CalculateUpdatedOriginAndNormal(\n inIncomingPvFilter, originToUse, normalToUse)\n\n if PhactoriDbg():\n myDebugPrint3(' updateslice using normal: ' + \\\n str(normalToUse) + '\\n')\n ioOutgoingPvFilter.SliceType.Normal = normalToUse\n\n if PhactoriDbg():\n myDebugPrint3(' updateslice using origin: ' + str(originToUse) + '\\n')\n ioOutgoingPvFilter.SliceType.Origin = originToUse\n\n #these aren't changing yet\n ioOutgoingPvFilter.Crinkleslice = self.mCrinkleSetting\n\n if PhactoriDbg():\n myDebugPrint3(\"PhactoriSlicePlaneOperation::UpdateSlice returning\\n\")\n\n#phactori_combine_to_single_python_file_subpiece_end_1\n\n","repo_name":"trilinos/Trilinos","sub_path":"packages/seacas/libraries/ioss/src/visualization/catalyst/phactori/Operation/PhactoriSliceOperation.py","file_name":"PhactoriSliceOperation.py","file_ext":"py","file_size_in_byte":2862,"program_lang":"python","lang":"en","doc_type":"code","stars":1088,"dataset":"github-code","pt":"81"} +{"seq_id":"19012774148","text":"import math\n\n# Properties of Abundant Numbers\n# 1. Every positive multiple greater than 1 of a perfect number is abundant \n# 2. Every positive multiple of an abundant number is abundant.\n\ndef check(n):\n s = 0\n for i in range(1, int(math.sqrt(n))+1):\n if n%i == 0:\n if n/i == i:\n s += i\n else:\n s += i\n s += n/i\n s = s-n \n if n == s:\n return 'P'\n elif n < s:\n return 'A'\n elif n > s:\n return 'D'\n \n\n# Generating Abundant Numbers less than 28123\ndef abundant():\n nos = [0 for i in range(28123 + 1)]\n \n for i in range(12, 28123 + 1):\n if nos[i] == 0:\n if check(i) == 'P':\n for j in range(2*i, 28123+1, i):\n nos[j] = 1\n elif check(i) == 'A':\n for j in range(i, 28123+1, i):\n nos[i] = 1\n \n #for i in range(28123+1):\n # if nos[i] == 1:\n # print(i, end=\" \")\n #print()\n \n return nos\n\nnos = abundant() \n\ndef solve(n):\n global nos\n for i in range(1, 28123+1):\n if nos[i] == 1 and nos[n-i] == 1:\n return True\n if i > n-i:\n return False\n\nsums = 0 \nfor i in range(1, 28123+1):\n if solve(i) == False:\n sums += i\nprint(sums) \n","repo_name":"ChanchalKumarMaji/Project-Euler","sub_path":"ProjectEuler23/ProjectEuler23.py","file_name":"ProjectEuler23.py","file_ext":"py","file_size_in_byte":1377,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"81"} +{"seq_id":"40250630807","text":"from keras.models import Model, load_model\nfrom keras.preprocessing.image import ImageDataGenerator \nimport numpy as np\nfrom tqdm import tqdm\nimport json\nfrom mobilenet_v2 import relu6\nfrom mobilenet_v2 import DepthwiseConv2D\nfrom keras.layers import Lambda\nimport tensorflow as tf\nimport keras.backend as K\nfrom shufflenetv2 import ShuffleNetV2\nfrom resnet_attention_56 import Resnet_Attention_56\n\n\n\ntest_dir='/home/eric/data/plant/ai_challenger_pdr2018_testa_20181023/AgriculturalDisease_testA'\n# test_dir='/home/eric/data/plant/ai_challenger_pdr2018_validationset_20181023/AgriculturalDisease_validationset/images'\ntest_datagen = ImageDataGenerator(1.0/255)\n# img_width, img_height = 265, 265\n# model=load_model('./trained_model/resnet50/resnet50.27-0.8720.hdf5')\n# model=load_model('./trained_model/inception_v4/inception_v4.41-0.8670.hdf5')\n# img_width, img_height = 229, 229\n# model=load_model('./trained_model/mobilenet_v2/mobilenet_v2.43-0.8674.hdf5',custom_objects={'relu6':relu6,'DepthwiseConv2D':DepthwiseConv2D})\n# from custom_layers import Scale\n# model=load_model('./trained_model/densenet161/densenet161.42-0.8800.hdf5',custom_objects={'Scale':Scale})\n#img_width, img_height = 229, 229\n# charset_size=61\n# model=ShuffleNetV2.ShuffleNetV2(input_shape=(img_width,img_height,3),classes=charset_size,weights='./trained_model/shufflenet_v2/shufflenet_v2.26-0.8676.hdf5')\n# model=load_model('./trained_model/shufflenet_v2/shufflenet_v2.26-0.8676.hdf5',custom_objects={'DepthwiseConv2D':DepthwiseConv2D,'Lambda':Lambda})\n# img_width, img_height = 224, 224\n# model=Resnet_Attention_56.Resnet_Attention_56(input_shape=(img_width,img_height,3),classes=charset_size,weights='./trained_model/resnet_attention_56/resnet_attention_56.49-0.8762.hdf5')\nimg_width, img_height = 224, 224\n# model=load_model('./trained_model/inception_v3/inception_v3.43-0.8747.hdf5')\n\n# model=load_model('./trained_model/squeezenet/squeezenet.33-0.8026.hdf5')\n# model=load_model('./trained_model/resnet34/resnet34.54-0.8773.hdf5')\n\nmodel=load_model('./trained_model/xception/xception.38-0.8740.hdf5')\n# model=load_model('./trained_model/inception_resnet_v2/inception_resnet_v2.42-0.8696.hdf5')\nmodel.compile(loss='categorical_crossentropy',\n optimizer='adam',\n metrics=['accuracy'])\nprint(model.summary())\nnb_validation_samples = 4514\nbatch_size=32\ngenerator=test_datagen.flow_from_directory(\n test_dir,\n target_size=(img_width,img_height),\n batch_size=batch_size,\n class_mode=None,\n shuffle=False,\n seed=42\n )\n\ngenerator.reset()\n\npred=model.predict_generator(generator,steps=nb_validation_samples // batch_size+1,verbose=1)\npredicted_class_indices=np.argmax(pred,axis=1)\nprint(predicted_class_indices)\n\nfilenames=generator.filenames\nresult = []\nfor i in tqdm(range(len(filenames))):\n temp_dict = {}\n temp_dict['image_id'] = filenames[i].split('/')[-1]\n temp_dict['disease_class'] = int(predicted_class_indices[i])\n result.append(temp_dict)\n# break\n# print('image %s is %d' % (test_image, sorted_arr[:,-1][0]))\njson_name='submit.json'\nwith open(json_name, 'w') as f:\n json.dump(result, f)\n print('write %s, num is %d' % (json_name,len(result)))","repo_name":"w5688414/keras-aichallenger-2018-plant-recognition","sub_path":"inference.py","file_name":"inference.py","file_ext":"py","file_size_in_byte":3328,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"81"} +{"seq_id":"12031180505","text":"from pprint import pformat\nimport undetected_chromedriver as uc\n\nfrom .credentials import CredentialsProviderBase, Credentials\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.common import TimeoutException\nimport logging\nimport re\nimport asyncio\nimport functools\nimport operator\n\nlogger = logging.getLogger(__name__)\n\nclass NetworkCDPInterceptor:\n\n def __init__(self, method: str):\n self._method: str = method\n \n @property\n def method(self) -> str:\n return self._method\n \n def intercept(self, event) -> None:\n logger.warning(f'{self.intercept.__name__} method not overriden: event received {pformat(event)}')\n pass\n\nclass CredentialsRequestInterceptor(NetworkCDPInterceptor):\n\n RGX_CLIENT_ID: str = r\"(.*)\\?client_id=(\\w*)&.*\"\n RGX_USER_ID: str = r\"(.*)/stream/users/(\\d+)\\?(.*)\"\n \n \n def __init__(self, method: str):\n super().__init__(method)\n self.__credentials: Credentials = Credentials()\n \n def __find_in_event(self, path: str, event):\n return functools.reduce(operator.getitem, path.split('.'), event)\n\n def __is_auth_request(self, event):\n params = event.get('params')\n return params and 'XHR' == params.get('type') and params.get('request')\n \n def __has_auth_header(self, event):\n headers = self.__find_in_event('params.request.headers', event)\n return 'Authorization' in headers\n\n def __extract_client_id(self, url: str) -> str:\n client_id_search = re.search(self.RGX_CLIENT_ID, url)\n return client_id_search.group(2) if client_id_search else None\n \n def __extract_user_id(self, url: str) -> str:\n user_id_search = re.search(self.RGX_USER_ID, url)\n return user_id_search.group(2) if user_id_search else None\n\n def intercept(self, event):\n if self.__is_auth_request(event) and self.__has_auth_header(event):\n url = self.__find_in_event('params.request.url', event)\n user_id = self.__extract_user_id(url)\n client_id = self.__extract_client_id(url)\n oauth_token: str = self.__find_in_event('params.request.headers.Authorization', event)\n oauth_token = oauth_token.replace('OAuth ', '') if oauth_token else None\n self.__credentials.update(oauth_token, client_id, user_id)\n\n @property\n def _credentials(self):\n return self.__credentials\n\n async def poll_credentials(self):\n while not self.__credentials.is_valid:\n await asyncio.sleep(1)\n return self.__credentials\n\n\nclass DriverFactory:\n\n def __init__(self, interceptors: 'list[NetworkCDPInterceptor]' = []):\n self.__driver: uc.Chrome = None\n self.__interceptors: list[NetworkCDPInterceptor] = interceptors\n\n def __regeter_interceptors(self, interceptors: 'list[NetworkCDPInterceptor]'):\n for (intercept, method) in map(lambda interceptor: (interceptor.intercept, interceptor.method), interceptors):\n self.__driver.add_cdp_listener(method, intercept)\n\n @property\n def chrome(self) -> uc.Chrome:\n if self.__driver is not None:\n return self.__driver\n\n options = uc.ChromeOptions()\n options.add_argument(\"--disable-gpu\")\n options.headless = True\n self.__driver = uc.Chrome(enable_cdp_events=True, keep_alive=False)\n\n self.__regeter_interceptors(self.__interceptors)\n\n return self.__driver\n\nclass Page:\n def __init__(self, driver_factory: DriverFactory):\n self._driver_factory = driver_factory\n \n def _browser(self):\n return self._driver_factory.chrome\n\nclass SoundCloudProfilePage(Page):\n\n CSS_CONSENT_DIALOG = '#onetrust-consent-sdk'\n CSS_LOGIN_BUTTON = '.loginButton'\n CSS_TAB = '.g-tabs-link'\n CONSENT_DIALOG = (By.CSS_SELECTOR, CSS_CONSENT_DIALOG)\n LOGIN_BUTTON = (By.CSS_SELECTOR, CSS_LOGIN_BUTTON)\n TAB = (By.CSS_SELECTOR, CSS_TAB)\n\n def __init__(self, driver_factory: DriverFactory):\n super().__init__(driver_factory)\n\n @staticmethod\n def fprofile_url(\n profile_username): return f\"https://www.soundcloud.com/{profile_username}/popular-tracks\"\n\n @staticmethod\n def js_remove_element_by_id(\n element_id): return f'document.getElementById(\\'{element_id}\\').remove();'\n\n def navigate_to_profile(self, profile_username: str):\n self._browser().get(self.fprofile_url(profile_username))\n\n def wait_remove_consent_dialog(self):\n try:\n concent_dialog = WebDriverWait(self._browser(), 5).until(\n EC.visibility_of_element_located(self.CONSENT_DIALOG))\n\n if concent_dialog.is_displayed():\n self._browser().execute_script(\n self.js_remove_element_by_id('onetrust-consent-sdk'))\n except TimeoutException:\n logger.warn('consent form was not displayed')\n pass\n\n def click_on_login_button(self):\n login_button = WebDriverWait(self._browser(), 5).until(\n EC.visibility_of_element_located(self.LOGIN_BUTTON))\n login_button.click()\n \n def click_on_tab(self):\n tab = WebDriverWait(self._browser(), 5).until(\n EC.element_to_be_clickable(self.TAB))\n tab.click()\n\n \nclass ProviderIFrame(Page):\n\n CSS_LOGIN_GOOGLE_BUTTON = '.sc-button-google'\n GOOGLE_LOGIN_BUTTON = (By.CSS_SELECTOR, CSS_LOGIN_GOOGLE_BUTTON)\n \n def __init__(self, driver_factory: DriverFactory):\n super().__init__(driver_factory)\n\n def switch_to_iframe(self):\n iframes = self._browser().find_elements(By.TAG_NAME, 'iframe')\n for iframe_idx in range(0, len(iframes)):\n self._browser().switch_to.frame(iframe_idx)\n try:\n WebDriverWait(self._browser(), .5).until(\n EC.element_to_be_clickable(self.GOOGLE_LOGIN_BUTTON))\n except TimeoutException:\n self._browser().switch_to.default_content()\n \n\n def click_on_google(self):\n login_button = self._browser().find_element(*self.GOOGLE_LOGIN_BUTTON)\n login_button.click()\n \n\nclass GoogleAuthenticationPopUp(Page):\n CSS_POPUP_LOGIN_NEXT_BUTTON = 'button[jsaction*=\"click:\"]'\n CSS_POPUP_LOGIN_EMAIL = 'input[type=\"email\"]'\n CSS_POPUP_LOGIN_PASS = 'input[type=\"password\"]'\n POPUP_LOGIN_EMAIL = (By.CSS_SELECTOR, CSS_POPUP_LOGIN_EMAIL)\n POPUP_LOGIN_PASS = (By.CSS_SELECTOR, CSS_POPUP_LOGIN_PASS)\n POPUP_LOGIN_NEXT_BUTTON = (By.CSS_SELECTOR, CSS_POPUP_LOGIN_NEXT_BUTTON)\n \n def __init__(self, driver_factory: DriverFactory):\n super().__init__(driver_factory)\n \n def switch_to_login_popup(self):\n popup = self._browser().window_handles[-1]\n self._browser().switch_to.window(popup)\n\n def type_email(self, email):\n email_input = WebDriverWait(self._browser(), 5).until(\n EC.visibility_of_element_located(self.POPUP_LOGIN_EMAIL))\n email_input.send_keys(email)\n\n def click_next(self):\n next_button = self._browser().find_elements(*self.POPUP_LOGIN_NEXT_BUTTON)[-2]\n next_button.click()\n \n def type_password(self, password):\n email_input = WebDriverWait(self._browser(), 5).until(\n EC.visibility_of_element_located(self.POPUP_LOGIN_PASS))\n email_input.send_keys(password)\n\nclass SeleniumCredentialsProvider(CredentialsProviderBase):\n def __init__(self):\n super().__init__()\n self.__interceptor = CredentialsRequestInterceptor(\n 'Network.requestWillBeSent')\n self.__driver_factory = DriverFactory(interceptors=[self.__interceptor])\n\n async def credentials(self, profile_username):\n credentials = Credentials.load_credentials('./cache/credentials.json')\n if credentials:\n return credentials\n \n chrome = self.__driver_factory.chrome\n\n profile_page = SoundCloudProfilePage(self.__driver_factory)\n profile_page.navigate_to_profile(profile_username)\n profile_page.wait_remove_consent_dialog()\n profile_page.click_on_login_button()\n\n credentials = await self.__interceptor.poll_credentials()\n credentials.save_credentials('./cache/credentials.json')\n chrome.close()\n return credentials","repo_name":"SaleemKhair/scloud_dl","sub_path":"scloud_dl/selenium.py","file_name":"selenium.py","file_ext":"py","file_size_in_byte":8390,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"2306550667","text":"'''\nThis function implements the main algorithm\n'''\nimport numpy as np\nimport classloader\nimport nsga2\nimport genetic_operators\nimport matplotlib.pyplot as plt\nfrom matplotlib.animation import FuncAnimation\nimport time\n\n# Algorithm parameters\nnum_variables = 4\nnum_objectives = 2\nnum_generations = 50\npopulation_size = 100\nconstraints = [[0.5, 2], [0.5, 3], [0.5, 3], [0.25,0.5]] # The constraints are for min and max values of l_beam, l_mass, w_mass, t_mass respectively. All dimensions in mm.\n\np = classloader.designVariables(num_variables=num_variables, constraints=constraints, num_generations=num_generations, population_size=population_size)\nc = classloader.objectives(num_objectives=num_objectives)\ncosts = c.find_costs(p.population)\n\np = genetic_operators.recombination(p)\np.offspring = genetic_operators.mutation(p.offspring, p.constraints)\ncosts_offspring = c.find_costs(p.offspring)\nt = time.time()\n\ngeneration_count = num_generations\nwhile generation_count>0:\n generation_count -= 1\n combined_population = np.zeros(shape=(2 * p.population.shape[0], p.population.shape[1]))\n combined_population[0:p.population.shape[0], :] = p.population\n combined_population[p.population.shape[0]:2 * p.population.shape[0], :] = p.offspring\n combined_costs = np.zeros(shape=(2 * costs.shape[0], costs.shape[1]))\n combined_costs[0:costs.shape[0], :] = costs\n combined_costs[costs.shape[0]:2 * costs.shape[0], :] = costs_offspring\n \n fronts = nsga2.non_dominated_sorting(combined_costs)\n new_population_count = 0\n new_population = np.zeros((population_size, num_variables))\n i = 0\n while new_population_count + len(fronts[i]) <= population_size:\n for k in range(len(fronts[i])):\n new_population[new_population_count] = combined_population[fronts[i][k]]\n new_population_count += 1\n i += 1\n crowding_distances = nsga2.calculate_crowding_distance(combined_costs, fronts[i], num_objectives)\n sort_by_distance = np.argsort(crowding_distances)\n l = len(fronts[i])\n N = l - (population_size - new_population_count)\n\n\n for j in range(l-N):\n new_population[new_population_count] = combined_population[fronts[i][sort_by_distance[l-1-j]]]\n new_population_count += 1\n p.population = new_population\n costs = c.find_costs(p.population)\n p = genetic_operators.recombination(p)\n p.offspring = genetic_operators.mutation(p.offspring, p.constraints)\n costs_offspring = c.find_costs(p.offspring)\n print(\"Done computing generation number \" + str(num_generations - generation_count))\n\nplt.title(\"Generation\" + str(num_generations - generation_count))\nplt.xlabel('Sensor area', fontsize=15)\nplt.ylabel('Sensor noise(scaled)', fontsize=15)\nplt.scatter(costs[:, 0], costs[:, 1])\nplt.show()\nprint(\"\")\nprint(\"Time for execution of algorithm was \" + str(time.time() - t) + \" seconds\")\n\n#if np.any(costs==0):\n# print(costs)\n# print(p.population)\n\n","repo_name":"JaydeepGodbole/genetic-algorithms","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2940,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"81"} +{"seq_id":"26680828965","text":"from interface import App\nfrom Tkinter import *\n\n\nroot = Tk()\n#root.geometry(\"320x240\")\nroot.wm_maxsize(950, 950)\nroot.columnconfigure(0, weight=1)\nroot.rowconfigure(0, weight=1)\napp = App(root)\nroot.mainloop()\n","repo_name":"TkachenkoBrothers/ZI","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":211,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"2638607042","text":"# 差异性检验\nimport pandas as pd\nfrom scipy.stats import shapiro,mannwhitneyu,ttest_ind,chi2_contingency\nfrom numpy import array\nimport statsmodels.api as sm\nimport numpy as np\nfrom sklearn import linear_model\nfrom sklearn.model_selection import train_test_split\nfrom sklearn import metrics\nfrom sklearn.metrics import roc_curve, auc\nimport matplotlib.pyplot as plt\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.model_selection import cross_val_score, learning_curve\nfrom sklearn.model_selection import GridSearchCV\n\ndf1=pd.read_csv('./DTdata1025.csv')\n#显示所有列\npd.set_option('display.max_columns', None)\n#显示所有行\npd.set_option('display.max_rows', None)\n\n# 数据描述\ndf1.describe()\ndf2 = df1[df1['group'] == 0]\ndf3 = df1[df1['group'] == 1]\ndf2.describe()\ndf3.describe()\n\n\npd.crosstab(df2['group'], df2['sex_1'], rownames=['group'])\npd.crosstab(df2['group'], df2['sex_2'], rownames=['group'])\n\npd.crosstab(df2['group'], df2['BMI_group_1.0'], rownames=['group'])\npd.crosstab(df2['group'], df2['BMI_group_1.8646288209606987'], rownames=['group'])\npd.crosstab(df2['group'], df2['BMI_group_2.0'], rownames=['group'])\npd.crosstab(df2['group'], df2['BMI_group_3.0'], rownames=['group'])\npd.crosstab(df2['group'], df2['yaowei_group_1.0'], rownames=['group'])\npd.crosstab(df2['group'], df2['yaowei_group_1.864321608040201'], rownames=['group'])\npd.crosstab(df2['group'], df2['yaowei_group_2.0'], rownames=['group'])\n\npd.crosstab(df2['group'], df2['smoking_1'], rownames=['group'])\npd.crosstab(df2['group'], df2['smoking_2'], rownames=['group'])\npd.crosstab(df2['group'], df2['drink_1'], rownames=['group'])\npd.crosstab(df2['group'], df2['drink_2'], rownames=['group'])\n\n\npd.crosstab(df3['group'], df3['sex_1'], rownames=['group'])\npd.crosstab(df3['group'], df3['sex_2'], rownames=['group'])\n\npd.crosstab(df3['group'], df3['BMI_group_1.0'], rownames=['group'])\npd.crosstab(df3['group'], df3['BMI_group_1.8646288209606987'], rownames=['group'])\npd.crosstab(df3['group'], df3['BMI_group_2.0'], rownames=['group'])\npd.crosstab(df3['group'], df3['BMI_group_3.0'], rownames=['group'])\npd.crosstab(df3['group'], df3['yaowei_group_1.0'], rownames=['group'])\npd.crosstab(df3['group'], df3['yaowei_group_1.864321608040201'], rownames=['group'])\npd.crosstab(df3['group'], df3['yaowei_group_2.0'], rownames=['group'])\n\npd.crosstab(df3['group'], df3['smoking_1'], rownames=['group'])\npd.crosstab(df3['group'], df3['smoking_2'], rownames=['group'])\npd.crosstab(df3['group'], df3['drink_1'], rownames=['group'])\npd.crosstab(df3['group'], df3['drink_2'], rownames=['group'])\n\n# 正态分布检验\n# 秩和检验,t检验\nname=['follow_up',\n 'bingcheng',\n 'age_fordiagnosis',\n 'shuzhangya',\n 'shousuoya',\n 'ALB',\n 'ALT',\n 'LDL_C',\n 'TG',\n 'HDL_C',\n 'Crea',\n 'Bun',\n 'UA',\n 'Glu',\n 'HbA1c',\n 'AST',\n 'Hb',\n 'FT4',\n 'FT3',\n 'TC',\n 'Total_bilirubin']\ndef get_class(x,Y):\n tmp = pd.DataFrame(list(zip(x, Y)))\n group = list(tmp.groupby(1))\n group_0=group[0]\n num_0=array(group_0[1])\n ar_0=num_0[:,0]\n\n group_1 = group[1]\n num_1 = array(group_1[1])\n ar_1=num_1[:,0]\n return ar_0,ar_1\nres=[]\nfor i in name:\n _,p=shapiro(df1[i])\n if p>0.05:\n a,b=get_class(df1[i],df1['group'])\n res.append(ttest_ind(a, b))\n else:\n a, b = get_class(df1[i], df1['group'])\n res.append(mannwhitneyu(a, b))\n\n# 卡方检验\nchi2_contingency([[174,347],[65,103]])\nchi2_contingency([[194,2,220,105],[45,0,82,41]])\nchi2_contingency([[68,76,377],[13,16,139]])\nchi2_contingency([[384,137],[125,43]])\nchi2_contingency([[453,68],[141,27]])\n\n# 单因素回归\nfor_name1=[\n 'follow_up',\n 'bingcheng',\n 'age_fordiagnosis',\n 'shuzhangya',\n 'shousuoya',\n 'ALB',\n 'ALT',\n 'LDL_C',\n 'TG',\n 'HDL_C',\n 'Crea',\n 'Bun',\n 'UA',\n 'Glu',\n 'HbA1c',\n 'AST',\n 'Hb',\n 'FT4',\n 'FT3',\n 'TC',\n 'Total_bilirubin',\n 'sex_2',\n 'BMI_group_1.0',\n 'BMI_group_2.0',\n 'BMI_group_3.0',\n 'yaowei_group_1.0',\n 'yaowei_group_2.0',\n 'smoking_2',\n 'drink_2']\nfor i in for_name1:\n model = sm.Logit(endog=df1['group'], exog=df1[['intercept',i]]).fit()\n print(model.summary())\n\n# 多因素回归\ndf1['intercept']=1\nfor_name2=['intercept',\n 'follow_up',\n 'bingcheng',\n 'age_fordiagnosis',\n 'shuzhangya',\n 'shousuoya',\n 'ALB',\n 'ALT',\n 'LDL_C',\n 'TG',\n 'HDL_C',\n 'Crea',\n 'Bun',\n 'UA',\n 'Glu',\n 'HbA1c',\n 'AST',\n 'Hb',\n 'FT4',\n 'FT3',\n 'TC',\n 'Total_bilirubin',\n 'sex_2',\n 'BMI_group_1.0',\n 'BMI_group_2.0',\n 'yaowei_group_1.0',\n 'yaowei_group_2.0',\n 'smoking_2',\n 'drink_2']\nmodel = sm.Logit(endog=df1['group'], exog=df1[for_name2]).fit()\nprint(model.summary())\n\n# 逻辑回归\n\nX = df1.drop(columns=['group','intercept'])\nY = df1['group']\n\nX_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.3, random_state=0)\n\n\n# 3.标准化特征值\nsc = StandardScaler()\nsc.fit(X_train)\nX_train_std = sc.transform(X_train)\nX_test_std = sc.transform(X_test)\n\n# gridsearch寻找最优参数\n# 用GridSearchCV寻找最优参数(字典)\nparam = {'penalty':['l1','l2'],'C':[1.0,1e5,1e9],'class_weight':[None,{0:0.2, 1:0.8},{0:0.3, 1:0.7}]}\ngrid = GridSearchCV(linear_model.LogisticRegression(),param_grid=param,cv=6)\ngrid.fit(X_train,Y_train)\nprint('最优分类器:',grid.best_params_,'最优分数:', grid.best_score_) # 得到最优的参数和分值\n\nbest_model=grid.best_estimator_\n\n# 交叉验证\nscores = cross_val_score(best_model, X, Y, cv=10)\nprint(scores)\n# 5. 预测\ny_pred=best_model.predict(X_test)\n\n# 评价指标\nc=metrics.classification_report(Y_test, y_pred)\n\n# 画ROC曲线\n###通过decision_function()计算得到的y_score的值,用在roc_curve()函数中\ny_score = best_model.decision_function(X_test)\nfpr, tpr, threshold = roc_curve(Y_test, y_score) ###计算真正率和假正率\nroc_auc = auc(fpr, tpr) ###计算auc的值\nplt.figure()\nlw = 2\nplt.figure(figsize=(10, 10))\nplt.plot(fpr, tpr, color='darkorange',\n lw=lw, label='ROC curve (area = %0.2f)' % roc_auc) ###假正率为横坐标,真正率为纵坐标做曲线\nplt.plot([0, 1], [0, 1], color='navy', lw=lw, linestyle='--')\nplt.xlim([0.0, 1.0])\nplt.ylim([0.0, 1.05])\nplt.xlabel('False Positive Rate')\nplt.ylabel('True Positive Rate')\nplt.title('Receiver operating characteristic example')\nplt.legend(loc=\"lower right\")\nplt.savefig('./LRauc.png')\nplt.show()\n\n\n# 画学习曲线\ntrain_sizes, train_scores, test_scores = learning_curve(estimator=best_model, X=X_train, y=Y_train,\n train_sizes=np.linspace(0.1, 1.0, 10), cv=10, n_jobs=1)\n# 统计结果\ntrain_mean = np.mean(train_scores, axis=1)\ntrain_std = np.std(train_scores, axis=1)\ntest_mean = np.mean(test_scores, axis=1)\ntest_std = np.std(test_scores, axis=1)\n# 绘制效果\nplt.plot(train_sizes, train_mean, color='blue', marker='o', markersize=5, label='training accuracy')\nplt.fill_between(train_sizes, train_mean + train_std, train_mean - train_std, alpha=0.15, color='blue')\nplt.plot(train_sizes, test_mean, color='green', linestyle='--', marker='s', markersize=5, label='test accuracy')\nplt.fill_between(train_sizes, test_mean + test_std, test_mean - test_std, alpha=0.15, color='green')\nplt.grid()\nplt.xlabel('Number of training samples')\nplt.ylabel('Accuracy')\nplt.legend(loc='lower right')\nplt.ylim([0.6, 1.0])\nplt.savefig('./LRlearningr.png')\nplt.show()\n\n\n\n","repo_name":"gaofan0906/FeatureEngineering","sub_path":"stats1028.py","file_name":"stats1028.py","file_ext":"py","file_size_in_byte":7285,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"81"} +{"seq_id":"20252328830","text":"from dataclasses import dataclass\n\nimport graphql\n\nfrom apischema import serialize\nfrom apischema.graphql import graphql_schema, relay\n\n\n@dataclass\nclass Faction(relay.Node[int]):\n name: str\n\n @classmethod\n def get_by_id(cls, id: int, info: graphql.GraphQLResolveInfo = None) -> \"Faction\":\n return [Faction(0, \"Empire\"), Faction(1, \"Rebels\")][id]\n\n\nschema = graphql_schema(query=[relay.node], types=relay.nodes())\nsome_global_id = Faction.get_by_id(0).global_id # Let's pick a global id ...\nassert some_global_id == relay.GlobalId(\"0\", Faction)\nquery = \"\"\"\nquery factionName($id: ID!) {\n node(id: $id) {\n ... on Faction {\n name\n }\n }\n}\"\"\"\nassert graphql.graphql_sync( # ... and use it in a query\n schema, query, variable_values={\"id\": serialize(relay.GlobalId, some_global_id)}\n).data == {\"node\": {\"name\": \"Empire\"}}\n","repo_name":"wyfo/apischema","sub_path":"examples/relay_global_id.py","file_name":"relay_global_id.py","file_ext":"py","file_size_in_byte":869,"program_lang":"python","lang":"en","doc_type":"code","stars":206,"dataset":"github-code","pt":"81"} +{"seq_id":"14204485308","text":"from django import forms\nimport datetime as d\nfrom vlbi import utility as u\n\n\ndef get_current_doy():\n now = u.get_now()\n return now.toordinal() - d.date(now.year, 1, 1).toordinal() + 1\n\n\nclass QueryForm(forms.Form):\n date = forms.DateField(\n label='Date',\n required=True,\n initial=u.get_now(),\n widget=forms.DateInput(),\n input_formats=['%Y-%m-%d', '%Y-%j', ],\n )\n","repo_name":"tenagusami/VERAdjango","sub_path":"vlbi_schedule/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":411,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"36660365988","text":"import glob\nimport os\nimport sys\nfrom natsort import natsorted\n\nori_img_path = '/dataset/Subjective_Compare/ori_img'\ncompress_path = '/dataset/Subjective_Compare/compress_img_bpg'\nos.makedirs(compress_path, exist_ok=True)\n\nori_img_list = os.listdir(ori_img_path)\nori_img_list = natsorted(ori_img_list)\n\nqp = sys.argv[1]\n# qp = 37\nGOP = 12\n\nfor dir in ori_img_list:\n img_list = glob.glob(os.path.join(ori_img_path, dir, '*.png'))\n save_path = os.path.join(compress_path, dir, str(qp))\n os.makedirs(save_path, exist_ok=True)\n img_list = natsorted(img_list)\n\n filename_gop = []\n framerange = len(img_list) // GOP\n for i in range(framerange):\n b = str(i * GOP + 1).zfill(3)\n filename = 'im' + b + '.png'\n filename_gop.append(filename)\n\n for each_img in img_list:\n seq_name = each_img.split('/')[-2]\n w, h = seq_name.split('_')[1].split('x')\n\n filename = os.path.basename(each_img)\n if filename in filename_gop:\n bin_path = save_path + '/' + filename.replace('.png', '') + '_' + str(qp) + '.bin'\n\n bits = os.path.getsize(bin_path)\n bits = bits * 8\n\n with open(bin_path.replace('.bin', '.txt'), 'w', encoding='utf-8') as f:\n f.write(str(bits / int(w) / int(h)) + '\\n')\n","repo_name":"Tongji-MIC-Lab/TDVC","sub_path":"tools/preprocess/04_getbpp.py","file_name":"04_getbpp.py","file_ext":"py","file_size_in_byte":1295,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"81"} +{"seq_id":"72245927306","text":"# -*- coding: utf-8 -*-\nfrom django.conf import settings\n\ndef my_context_processor(request):\n return {\n \"HEADER_ADMIN\": settings.HEADER_ADMIN,\n \"HEADER_GPLUS\": settings.HEADER_GPLUS,\n \"HEADER_QUICKLINKS\": settings.HEADER_QUICKLINKS,\n \"FOOTER_TEXT\": settings.FOOTER_TEXT,\n \"FOOTER_QUICKLINKS\": settings.FOOTER_QUICKLINKS,\n \"THEME\": settings.THEME,\n \"STATS\": settings.STATS,\n }\n\n","repo_name":"dubzzz/django-portfolio","sub_path":"PortFolio/projects/context_processors.py","file_name":"context_processors.py","file_ext":"py","file_size_in_byte":467,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"81"} +{"seq_id":"24935191126","text":"import queue,threading,time\ndef productor(q):\n for n in range(10):\n q.put(n)\n print(f'生产产品号:{n}')\n time.sleep(0.5)\n q.task_done()\ndef consumer(q):\n for n in range(15):\n try:\n p = q.get(timeout=2)\n except:\n break\n print(f'消费产品号:{p}')\n time.sleep(0.5)\n q.task_done() # 结束队列任务获取, 此处可以用try 方式捕获 get(timeout=3)的错误,从而判断无数据可获取\n\nif __name__ == \"__main__\":\n q = queue.Queue(5) # 创建一个队列,将其作为参数传入生产者和消费者函数\n t1 = threading.Thread(target=productor,args=(q,))\n t2 = threading.Thread(target=consumer,args=(q,))\n t1.start()\n t2.start()\n t1.join()\n t2.join()\n print('----------end----------')","repo_name":"heting-intesim/python-base","sub_path":"基础语法/线程-生产者消费者.py","file_name":"线程-生产者消费者.py","file_ext":"py","file_size_in_byte":820,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"81"} +{"seq_id":"74921568585","text":"\"\"\"\nThis file is part of the TheLMA (THe Laboratory Management Application) project.\nSee LICENSE.txt for licensing, CONTRIBUTORS.txt for contributor information.\n\nRack shape table.\n\"\"\"\nfrom sqlalchemy import CheckConstraint\nfrom sqlalchemy import Column\nfrom sqlalchemy import Integer\nfrom sqlalchemy import String\nfrom sqlalchemy import Table\nfrom sqlalchemy import UniqueConstraint\n\n\n__docformat__ = 'reStructuredText en'\n__all__ = ['create_table']\n\n\ndef create_table(metadata):\n \"Table factory.\"\n tbl = Table('rack_shape', metadata,\n Column('rack_shape_name', String, primary_key=True),\n Column('number_rows', Integer, CheckConstraint('number_rows>0'),\n nullable=False),\n Column('number_columns', Integer,\n CheckConstraint('number_columns>0'), nullable=False),\n Column('label', String, nullable=False, unique=True),\n UniqueConstraint('number_rows', 'number_columns'),\n )\n return tbl\n","repo_name":"helixyte/TheLMA","sub_path":"thelma/repositories/rdb/schema/tables/rackshape.py","file_name":"rackshape.py","file_ext":"py","file_size_in_byte":965,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"81"} +{"seq_id":"15222588529","text":"import os\nfrom typing import Dict, List, Optional\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport seaborn as sns\nfrom matplotlib import rcParams\n\nfrom hplot.config import hConfig\nfrom hplot.utils import cm2inch\nfrom hplot.base import Base\nfrom mpl_toolkits.axes_grid1.inset_locator import inset_axes\n\n\nclass plot_sns(Base):\n def __init__(\n self,\n data: List[Dict],\n fname: Optional[str] = None,\n *,\n xlabel: Optional[str] = None,\n ylabel: Optional[str] = None,\n legend: Optional[List[str]] = None,\n title: Optional[str] = None,\n display: Optional[bool] = False,\n **kwargs\n ):\n \"\"\"\n :param data: list[dict]:\n data used to plot figures,\n example: [dict(x=x1_list, y=y1_list, label=label1), dict(x=x2_list, y=y2_list, label=label2)]\n when there is no repeat experiment data, xi_list=x, shape of x is [d,],\n yi_list=y, shape of y is [d,],\n lableli str,\n when there is repeat experiment data, xi_list=[x1, x2, ..., xd], shape of xi is [d,],\n yi_list=[y1, y2, ..., yd], shape of y is [d,],\n lableli str,\n :param fname: fname: str,\n the figure will be saved here,\n example: \"./path_to_file/figure.png\"\n :param xlabel: str\n :param ylabel: str\n :param legend: list[str]\n :param display: bool\n :param kwargs[\"style\"]: str\n \"white\", \"dark\", \"whitegrid\", \"darkgrid\"\n :param kwargs[\"linewidths\"]: List[str]\n :param kwargs[\"linestyles\"]: List[str]\n :param kwargs[\"legend_loc\"]: str\n \"best\", \"upper right\", \"upper left\", \"lower left\", \"lower right\", \"right\", \"center left\",\n \"center right\", \"lower center\", \"upper center\", \"center\"\n :param kwargs[\"legend_frameon\"]: bool\n :param kwargs[\"legend_ncol\"]: int\n number of columns in legend\n :param kwargs[\"show_legend\"]: bool\n :param kwargs[\"xlim\"]:\n :param kwargs[\"ylim\"]:\n :param kwargs[\"xticks\"]:\n :param kwargs[\"yticks\"]:\n :param kwargs[\"xtick_labels\"]:\n :param kwargs[\"ytick_labels\"]:\n :param kwargs[\"log_yaxis\"]: bool\n :param kwargs[\"ticklabel_style\"]: \"sci\" or \"plain\"\n :param kwargs[\"ticklabel_style_axis\"]: \"x\" or \"y\" or \"both\"\n :param kwargs[\"log_yaxis\"]: bool\n :param kwargs[\"sub_axis\"]: List of dict keys: width, height, loc, borderpad, xlim, ylim, links. link [(\"ul\", \"ll\"), (\"ur\", \"lr\")]\n\n \"\"\"\n super().__init__(**kwargs)\n self.data = data\n self.fname = fname\n self.xlabel = xlabel\n self.ylabel = ylabel\n self.legend = legend\n self.display = display\n self.title = title\n\n self.num_data = None\n self.fig = None\n self.ax = None\n plt.cla()\n plt.clf()\n plt.close()\n style = kwargs.get(\"style\", \"white\")\n sns.set_style(style)\n self.__preprocess()\n\n self.run()\n\n def __preprocess(self):\n rcParams.update({\"mathtext.fontset\": \"stix\"})\n assert isinstance(self.data, (dict, list, tuple))\n\n if isinstance(self.data, dict):\n self.data = [self.data]\n self.num_data = len(self.data)\n\n # use tex to render fonts, tex install required\n if hConfig.usetex:\n from matplotlib import rc\n\n rc(\"font\", **{\"family\": \"serif\", \"serif\": [\"Times New Roman\"]})\n rc(\"text\", usetex=True)\n\n def _ppc_data(self, d):\n x = d[\"x\"]\n y = d[\"y\"]\n label = d[\"label\"]\n if isinstance(x, np.ndarray):\n x = [x]\n if isinstance(y, np.ndarray):\n y = [y]\n\n assert len(x) == len(y)\n\n for i in range(len(x)):\n x[i] = x[i].reshape(-1)\n y[i] = y[i].reshape(-1)\n assert x[i].shape == y[i].shape\n x = np.stack(x)\n y = np.stack(y)\n\n x = x.reshape(-1)\n y = y.reshape(-1)\n return x, y, label\n\n def plot(self):\n self.fig, self.ax = plt.subplots(\n figsize=cm2inch(*hConfig.fig_size), dpi=hConfig.dpi\n )\n # plot figure\n lws = self._kwargs.get(\"linewidths\", None)\n if lws is not None:\n assert len(self.data) == len(lws)\n\n lss = self._kwargs.get(\"linestyles\", None)\n if lss is not None:\n assert len(self.data) == len(lss)\n\n for i, d in enumerate(self.data):\n x, y, label = self._ppc_data(d)\n lw = lws[i] if lws is not None else 2\n ls = lss[i] if lss is not None else \"-\"\n sns.lineplot(x=x, y=y, label=label, linewidth=lw, ls=ls)\n\n if self.title is not None:\n plt.title(self.title, hConfig.title_font)\n # tick\n plt.tick_params(labelsize=hConfig.tick_size)\n labels = self.ax.get_xticklabels() + self.ax.get_yticklabels()\n [label.set_fontname(hConfig.tick_label_font) for label in labels]\n\n # set legend\n legend_handles, legend_labels = self.ax.get_legend_handles_labels()\n legend_dict = dict()\n legend_dict[\"handles\"] = legend_handles\n legend_dict[\"labels\"] = (\n self.legend if self.legend is not None else legend_labels\n )\n legend_dict[\"columnspacing\"] = 0.3\n legend_loc = self._kwargs.get(\"legend_loc\", \"best\")\n legend_dict[\"loc\"] = \"best\" if legend_loc is None else legend_loc\n legend_dict[\"frameon\"] = self._kwargs.get(\"legend_frameon\", True)\n legend_dict[\"prop\"] = hConfig.legend_font\n\n ncol = self._kwargs.get(\"legend_ncol\", 1)\n if ncol is not None:\n legend_dict[\"ncol\"] = ncol\n\n if self._kwargs.get(\"show_legend\", True):\n self.ax.legend(**legend_dict)\n else:\n plt.legend([], [], frameon=False)\n\n # label\n if self.xlabel is not None:\n plt.xlabel(self.xlabel, hConfig.label_font)\n if self.xlabel is not None:\n plt.ylabel(self.ylabel, hConfig.label_font)\n\n xlim = self._kwargs.get(\"xlim\", None)\n if xlim is not None:\n plt.xlim(xlim)\n ylim = self._kwargs.get(\"ylim\", None)\n if ylim is not None:\n plt.ylim(ylim)\n\n xticks = self._kwargs.get(\"xticks\", None)\n yticks = self._kwargs.get(\"yticks\", None)\n xtick_labels = self._kwargs.get(\"xtick_labels\", None)\n ytick_labels = self._kwargs.get(\"ytick_labels\", None)\n\n if xticks is not None and xtick_labels is not None:\n plt.xticks(xticks, xtick_labels)\n if yticks is not None and ytick_labels is not None:\n plt.yticks(yticks, ytick_labels)\n\n ticklabel_style = self._kwargs.get(\"ticklabel_style\", None)\n ticklabel_style_axis = self._kwargs.get(\"ticklabel_style_axis\", \"x\")\n if ticklabel_style:\n plt.ticklabel_format(\n style=ticklabel_style, axis=ticklabel_style_axis, scilimits=(0, 0)\n )\n\n log_yaxis = self._kwargs.get(\"log_yaxis\", None)\n if log_yaxis is not None:\n plt.yscale(\"log\")\n\n if self._kwargs.get(\"sub_axis\", None) is not None:\n from matplotlib.patches import ConnectionPatch\n\n for sub_ax_config in self._kwargs.get(\"sub_axis\", None):\n width = sub_ax_config.get(\"width\", \"40%\")\n height = sub_ax_config.get(\"height\", \"30%\")\n loc = sub_ax_config.get(\"loc\", \"upper right\")\n borderpad = sub_ax_config.get(\"borderpad\", 1)\n axins = inset_axes(self.ax, width, height, loc=loc, borderpad=borderpad)\n # plot original data\n # plt.gca().set_prop_cycle(None)\n for i, d in enumerate(self.data):\n x, y, label = self._ppc_data(d)\n lw = lws[i] if lws is not None else 2\n ls = lss[i] if lss is not None else \"-\"\n sns.lineplot(\n x=x,\n y=y,\n label=label,\n linewidth=lw,\n ls=ls,\n ax=axins,\n legend=False,\n )\n plt.tick_params(labelsize=hConfig.tick_size)\n labels = axins.get_xticklabels() + axins.get_yticklabels()\n [label.set_fontname(hConfig.tick_label_font) for label in labels]\n # set enlarged zone\n sub_xlim = sub_ax_config[\"xlim\"]\n sub_ylim = sub_ax_config[\"ylim\"]\n\n axins.set_xlim(sub_xlim)\n axins.set_ylim(sub_ylim)\n\n tx0 = sub_xlim[0]\n tx1 = sub_xlim[1]\n ty0 = sub_ylim[0]\n ty1 = sub_ylim[1]\n sx = [tx0, tx1, tx1, tx0, tx0]\n sy = [ty0, ty0, ty1, ty1, ty0]\n print(sx, sy)\n self.ax.plot(sx, sy, \"black\", lw=1)\n\n # 画两条线\n\n link_dict = {\n \"ur\": (tx1, ty1),\n \"ul\": (tx0, ty1),\n \"ll\": (tx0, ty0),\n \"lr\": (tx1, ty0),\n }\n\n linke = sub_ax_config.get(\"links\", [(\"ul\", \"ll\"), (\"ur\", \"lr\")])\n\n for start, end in linke:\n xy = link_dict[start]\n xy2 = link_dict[end]\n con = ConnectionPatch(\n xyA=xy2,\n xyB=xy,\n coordsA=\"data\",\n coordsB=\"data\",\n axesA=axins,\n axesB=self.ax,\n color=\"black\",\n lw=1,\n )\n axins.add_artist(con)\n","repo_name":"zhangyuh15/hplot","sub_path":"hplot/plot_sns.py","file_name":"plot_sns.py","file_ext":"py","file_size_in_byte":10018,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"39805172264","text":"\"\"\"\nEscreva o menu de opções abaixo. Leia a opção do usuário e execute a operação esco-\nlhida. Escreva uma mensagem de erro se a opção for inválida.\n\nEscolha a opção:\n1-Soma de 2 números.\n2-Diferença entre 2 números (maior pelo menor).\n3-Produto entre 2 números.\n4-Divisão entre 2 números (o denominador não pode ser zero).\nOpção\n\"\"\"\n\n\nop = int(input(\"Escolha a opção.\\n\"\n \"1-Soma de 2 números.\\n\"\n \"2-Diferença entre 2 números (maior pelo menor).\\n\"\n \"3-Produto entre 2 números.\\n\"\n \"4-Divisão entre 2 números (o denominador não pode ser zero).\\n\"\n \"Opção: \"))\n\nx = float(input(\"Digite um numero: \"))\ny = float(input(\"Digite outro numero: \"))\n\nif op == 1:\n resultado = x + y\nelif op == 2:\n resultado = x - y\nelif op == 3:\n resultado = x * y\nelif op == 4:\n resultado = x / y\nelse:\n resultado = 0\n print(\"Operação não encontrada. Logo...\")\nprint(f\"O resultado é: {resultado}\")\n","repo_name":"GabrielSalazar29/Exercicios_em_python_udemy","sub_path":"Exercicios Seção 05/ex021.py","file_name":"ex021.py","file_ext":"py","file_size_in_byte":1000,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"8775064542","text":"import heapq\nfrom typing import List, Tuple, Dict, Union\n\n\ndef dijkstra_shortest_path(graph: Dict[str, List[Tuple[str, int]]], start: str, end: str) -> Union[None, Tuple[List[str], int]]:\n \"\"\"\n Finds the shortest path from the start node to the end node in a graph using Dijkstra's algorithm.\n\n Args:\n graph: A dictionary representing the graph in adjacency list format.\n start: The start node.\n end: The end node.\n\n Returns:\n A tuple containing the shortest path from the start node to the end node as a list of nodes, and the cost of the\n shortest path. Returns None if there is no valid path from the start node to the end node.\n \"\"\"\n heap = [(0, start)]\n visited = set()\n previous_node = {start: None}\n costs = {start: 0}\n\n while heap:\n (cost, current) = heapq.heappop(heap)\n\n if current in visited:\n continue\n\n visited.add(current)\n\n if current == end:\n path = []\n while current is not None:\n path.insert(0, current)\n current = previous_node[current]\n return (path, cost)\n\n for neighbor, edge_cost in graph[current]:\n new_cost = costs[current] + edge_cost\n\n if neighbor not in visited and (neighbor not in costs or new_cost < costs[neighbor]):\n heapq.heappush(heap, (new_cost, neighbor))\n costs[neighbor] = new_cost\n previous_node[neighbor] = current\n\n return None\n","repo_name":"hossamassad/code-review","sub_path":"IM-Dijkstra.py","file_name":"IM-Dijkstra.py","file_ext":"py","file_size_in_byte":1514,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"19652631171","text":"from datetime import datetime, timedelta\nfrom cymepy.common import DATE_FORMAT\nimport math\nimport os\n\nclass Solver:\n\n def __init__(self, cymepy, settings, logger):\n self.Settings = settings\n self._Logger = logger\n self.cymepy = cymepy\n\n self._mStepRes = settings['project']['time_step_min']\n StartTimeMin = settings['project']['start_time']\n EndTimeMin = settings['project']['end_time']\n\n self._Time = datetime.strptime(StartTimeMin, DATE_FORMAT)\n self._StartTime = self._Time\n self._EndTime = datetime.strptime(EndTimeMin, DATE_FORMAT)\n\n if settings['project'][\"simulation_type\"] == \"QSTS\":\n if self.Settings['profiles'][\"use_internal_profile_manager\"]:\n\n self.solverObj = cymepy.sim.LoadFlowWithProfiles()\n self.solverObj.SetValue(\"SingleTimeMode\", \"Parameters.TimeParametersMode\")\n self.loadflowSettings(cymepy.sim.LoadFlow())\n\n else:\n self.solverObj = cymepy.sim.LoadFlow()\n self.loadflowSettings(self.solverObj)\n elif settings['project'][\"simulation_type\"] == \"Static\":\n self.solverObj = cymepy.sim.LoadFlow()\n self.loadflowSettings(self.solverObj)\n\n self._Logger.debug(\"Solver object created.\")\n return\n\n def loadflowSettings(self, lf):\n lf.SetValue('VoltageDropUnbalanced', 'ParametersConfigurations[0].AnalysisMode')\n lf.SetValue(self.Settings['project'][\"max_iter\"],\n 'ParametersConfigurations[0].MaximumIterations')\n lf.SetValue(self.Settings['project'][\"error_tolerance\"],\n 'ParametersConfigurations[0].VoltageTolerance')\n return\n\n def increment(self):\n if self.Settings['project'][\"simulation_type\"] == \"QSTS\":\n if self.Settings['profiles'][\"use_profiles\"]:\n if self.Settings['profiles'][\"use_internal_profile_manager\"]:\n self.solverObj.SetValue(int(self._Time.timestamp()), \"Parameters.SingleTime\")\n self.solverObj.Run()\n #self._Logger.debug(f\"CYME internal time: {self._Time}\")\n else:\n self.solverObj.Run()\n\n self._Time = self._Time + timedelta(minutes=self._mStepRes)\n self._Logger.debug(f\"CYMEPY time: {self._Time}\")\n elif self.Settings['project'][\"simulation_type\"] == \"Static\":\n raise Exception(\"'increment' method cannot be used in QSTS mode\")\n\n return\n\n def resolve(self):\n self.solverObj.Run()\n self._Logger.debug(f\"Resolving at time: {self._Time}\")\n\n def SimulationSteps(self):\n Minutes = (self._EndTime - self._StartTime).total_seconds() / 60.0\n Steps = math.ceil(Minutes / self._mStepRes)\n\n return Steps, self._StartTime, self._EndTime\n\n def GetTotalSeconds(self):\n return (self._Time - self._StartTime).total_seconds()\n\n def GetDateTime(self):\n return self._Time","repo_name":"GMLC-TDC/cymepy","sub_path":"cymepy/solver.py","file_name":"solver.py","file_ext":"py","file_size_in_byte":3028,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"81"} +{"seq_id":"43772031877","text":"'''\n1286 : 최댓값, 최솟값\n5개의 정수들의 최댓값과 최솟값을 구하는 프로그램을 작성하라.\n'''\nlist = []\nfor i in range(5):\n list.append(int(input()))\n\nlist.sort()\n\nprint(list[4]) # 최댓값\nprint(list[0]) # 최솟값\n\n","repo_name":"minhyeonlee/algorithm-python","sub_path":"codeUp/codeUpBasic/1286.py","file_name":"1286.py","file_ext":"py","file_size_in_byte":251,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"20245356351","text":"\"\"\"Parses the folder-tree on the forum, checking the last update time. Collects the list of leaf-level folders\nwhich contain updates – and makes a pub/sub call for other script to parse content of these folders\"\"\"\n\nimport base64\nimport ast\nimport json\nimport requests\nimport logging\nimport urllib.request\n\nfrom bs4 import BeautifulSoup, SoupStrainer # noqa\n\nfrom google.cloud import pubsub_v1\nfrom google.cloud import storage\nimport google.cloud.logging\n\nurl = \"http://metadata.google.internal/computeMetadata/v1/project/project-id\"\nreq = urllib.request.Request(url)\nreq.add_header(\"Metadata-Flavor\", \"Google\")\nproject_id = urllib.request.urlopen(req).read().decode()\n\npublisher = pubsub_v1.PublisherClient()\n\nlog_client = google.cloud.logging.Client()\nlog_client.setup_logging()\n\n\ndef process_pubsub_message(event):\n \"\"\"convert incoming pub/sub message into regular data\"\"\"\n\n # receiving message text from pub/sub\n if 'data' in event:\n received_message_from_pubsub = base64.b64decode(event['data']).decode('utf-8')\n else:\n received_message_from_pubsub = 'I cannot read message from pub/sub'\n encoded_to_ascii = eval(received_message_from_pubsub)\n data_in_ascii = encoded_to_ascii['data']\n message_in_ascii = data_in_ascii['message']\n\n return message_in_ascii\n\n\ndef publish_to_pubsub(topic_name, message):\n \"\"\"publishing a new message to pub/sub\"\"\"\n\n global project_id\n\n # Preparing to turn to the existing pub/sub topic\n topic_path = publisher.topic_path(project_id, topic_name)\n # Preparing the message\n message_json = json.dumps({'data': {'message': message}, })\n message_bytes = message_json.encode('utf-8')\n # Publishes a message\n try:\n publish_future = publisher.publish(topic_path, data=message_bytes)\n publish_future.result() # Verify that the publishing succeeded\n logging.info('Pub/sub message was published successfully')\n\n except Exception as e:\n logging.info('Pub/sub message was NOT published, fired an error')\n logging.exception(e)\n\n return None\n\n\ndef set_cloud_storage(folder_num):\n \"\"\"sets the basic parameters for connection to txt file in cloud storage, which stores searches snapshots\"\"\"\n bucket_name = 'bucket_for_folders_snapshots'\n blob_name = str(folder_num) + '.txt'\n\n storage_client = storage.Client()\n bucket = storage_client.get_bucket(bucket_name)\n blob = bucket.blob(blob_name)\n\n return blob\n\n\ndef write_snapshot_to_cloud_storage(what_to_write, folder_num):\n \"\"\"writes current snapshot to txt file in cloud storage\"\"\"\n\n blob = set_cloud_storage(folder_num)\n blob.upload_from_string(str(what_to_write), content_type=\"text/plain\")\n\n\ndef read_snapshot_from_cloud_storage(folder_num):\n \"\"\"reads previous searches snapshot from txt file in cloud storage\"\"\"\n\n try:\n blob = set_cloud_storage(folder_num)\n contents_as_bytes = blob.download_as_string()\n contents = str(contents_as_bytes, 'utf-8')\n if contents == 'None':\n contents = None\n except: # noqa\n contents = None\n return contents\n\n\ndef compare_old_and_new_folder_hash_and_give_list_of_upd_folders(new_str, old_str):\n \"\"\"compare if newly parsed folder content equals the previously-saved one\"\"\"\n\n list_of_changed_folders = []\n\n # if there is no \"old\" version, we treat all the folder from new_str as newly parsed\n if not old_str:\n new_list = ast.literal_eval(new_str)\n for n_line in new_list:\n list_of_changed_folders.append(n_line[0])\n\n # if these are updates (new and old str are not equal) - combine a list of updates\n elif new_str != old_str:\n new_list = ast.literal_eval(new_str)\n old_list = ast.literal_eval(old_str)\n\n comparison_matrix = []\n\n for o_line in old_list:\n comparison_matrix.append([o_line[0], o_line[1], ''])\n for n_line in new_list:\n new_folder_trigger = True\n for m_line in comparison_matrix:\n if n_line[0] == m_line[0]:\n new_folder_trigger = False\n m_line[2] = n_line[1]\n if new_folder_trigger:\n comparison_matrix.append([n_line[0], '', n_line[1]])\n\n for line in comparison_matrix:\n if line[1] != line[2]:\n list_of_changed_folders.append(line[0])\n\n return list_of_changed_folders\n\n\ndef decompose_folder_to_subfolders_and_searches(start_folder_num):\n \"\"\"Check if there are changes in folder that contain other folders\"\"\"\n\n page_summary_folders = []\n page_summary_searches = []\n page_full_extract_searches = []\n folder_name = None\n\n url = 'https://lizaalert.org/forum/viewforum.php?f=' + str(start_folder_num)\n\n try:\n r = requests.Session().get(url)\n only_tag = SoupStrainer('div', {'class': 'page-body'})\n soup = BeautifulSoup(r.content, features='lxml', parse_only=only_tag)\n del r # trying to free up memory\n folder_name = soup.find('h2', {'class': 'forum-title'}).next_element.next_element\n logging.info(folder_name)\n\n search_code_blocks_folders = soup.find_all('div', {'class': 'forabg'})\n search_code_blocks_searches = soup.find_all('div', {'class': 'forumbg'})\n del soup # trying to free up memory\n\n except Exception as e1:\n logging.info(f'Request to forum was unsuccessful for url {url}')\n logging.exception(e1)\n search_code_blocks_folders = None\n search_code_blocks_searches = None\n\n try:\n if search_code_blocks_folders:\n for block in search_code_blocks_folders:\n\n folders = block.find_all('li', {'class': 'row'})\n for folder in folders:\n\n # found no cases where there can be more than 1 topic name or date, so find i/o find_all is used\n folder_num_str = folder.find('a', {'class': 'forumtitle'})['href']\n\n start_symb_to_del = folder_num_str.find('&sid=')\n if start_symb_to_del != -1:\n folder_num = int(folder_num_str[18:start_symb_to_del])\n else:\n folder_num = int(folder_num_str[18:])\n\n try:\n folder_time_str = folder.find('time')['datetime']\n except: # noqa\n folder_time_str = None\n\n # remove useless folders: Справочники, Снаряжение, Постскриптум and all from Обучение и Тренировки\n # NB! there was an idea to remove this part of code and make a limitation basing on info in PSQL.\n # However, in reality, this script does not import any SQL capabilities. Thus, it's more\n # efficient from cold-start perspective / time for script initiation & memory it occupies – not to\n # use SQL call here as well. So the limitation is made on python level.\n if folder_num not in {84, 113, 112, 270, 86, 87, 88, 165, 365, 89, 172, 91, 90, 316, 234, 230, 319}:\n page_summary_folders.append([folder_num, folder_time_str])\n\n except Exception as e2:\n logging.info(f'Folder code blocks identification was not successful, fired an error for {start_folder_num}')\n logging.exception(e2)\n\n try:\n if search_code_blocks_searches:\n\n for block in search_code_blocks_searches:\n\n searches = block.find_all('dl', 'row-item') # memo: w/o \"class:row-item\" - to catch diff \"row-items\"\n\n for i in range(len(searches)-1):\n\n page_full_extract_searches.append(str(searches[i+1]))\n\n # only title + time of the last reply\n search_title_block = searches[i+1].find('a', 'topictitle')\n search_title = search_title_block.next_element\n\n try:\n search_time_str = searches[i+1].find('time')['datetime']\n except: # noqa\n search_time_str = None\n\n page_summary_searches.append([search_title, search_time_str])\n\n except Exception as e3:\n logging.info(f'Searches code blocks identification was not successful, fired an error for {start_folder_num}')\n logging.exception(e3)\n\n logging.info(f'Page summary searches: {str(page_summary_searches)}')\n\n return page_summary_folders, page_summary_searches, page_full_extract_searches, folder_name\n\n\nclass FolderForDecompose:\n def __init__(self,\n mother_folder_num=None,\n mother_folder_name=None,\n old_child_folders_str=None,\n old_child_searches_str=None,\n new_child_folders_str=None,\n new_child_searches_str=None,\n decomposition_status=None,\n mother_file_folders=None,\n mother_file_searches=None,\n searches_extract=None\n ):\n self.mother_folder_num = mother_folder_num\n self.mother_folder_name = mother_folder_name\n self.old_child_folders_str = old_child_folders_str\n self.old_child_searches_str = old_child_searches_str\n self.new_child_folders_str = new_child_folders_str\n self.new_child_searches_str = new_child_searches_str\n self.decomposition_status = decomposition_status\n self.mother_file_folders = mother_file_folders\n self.mother_file_searches = mother_file_searches\n self.searches_extract = searches_extract\n\n def __str__(self):\n return str([self.mother_folder_num, self.old_child_searches_str, self.new_child_searches_str,\n self.old_child_folders_str, self.new_child_folders_str,\n self.decomposition_status, self.mother_file_folders, self.mother_file_searches])\n\n\ndef main(event, context): # noqa\n \"\"\"main function\"\"\"\n\n list_of_updates = []\n list_of_updated_low_level_folders = []\n\n # check the initial 000 folder: what pub/sub sent & what is in storage\n\n folder_root = FolderForDecompose()\n folder_root.mother_folder_num = '000'\n\n list_of_updates.append(folder_root)\n\n for folder in list_of_updates:\n\n # if folder was not decomposed yet - we need to do it (if was, we're just skipping it)\n if not folder.decomposition_status:\n\n folder.mother_file_folders = str(folder.mother_folder_num) + '_folders'\n folder.mother_file_searches = str(folder.mother_folder_num) + '_searches'\n folder.old_child_folders_str = read_snapshot_from_cloud_storage(folder.mother_file_folders)\n folder.old_child_searches_str = read_snapshot_from_cloud_storage(folder.mother_file_searches)\n\n if folder.mother_folder_num == '000':\n folder.new_child_folders_str = process_pubsub_message(event)\n folder.new_child_searches_str = None\n else:\n list_of_decomposed_folders, list_of_decomposed_searches, list_of_searches_details, mother_folder_name \\\n = decompose_folder_to_subfolders_and_searches(folder.mother_folder_num)\n folder.new_child_folders_str = str(list_of_decomposed_folders)\n folder.new_child_searches_str = str(list_of_decomposed_searches)\n folder.searches_extract = str(list_of_searches_details)\n folder.mother_folder_name = mother_folder_name\n\n list_of_new_folders = compare_old_and_new_folder_hash_and_give_list_of_upd_folders(\n folder.new_child_folders_str, folder.old_child_folders_str)\n\n logging.info(f'List of new folders in {str(folder.mother_folder_num)}: {str(list_of_new_folders)}')\n\n for line in list_of_new_folders:\n child_folder = FolderForDecompose()\n child_folder.mother_folder_num = str(line)\n list_of_updates.append(child_folder)\n\n folder.decomposition_status = 'decomposed'\n write_snapshot_to_cloud_storage(folder.new_child_folders_str, folder.mother_file_folders)\n write_snapshot_to_cloud_storage(folder.new_child_searches_str, folder.mother_file_searches)\n\n for line in list_of_updates:\n if line.new_child_searches_str != line.old_child_searches_str:\n list_of_updated_low_level_folders.append([line.mother_folder_num,\n line.mother_folder_name])\n\n logging.info('The below list is to be sent to \"Identify updates of topics\" script via pub/sub')\n for line in list_of_updated_low_level_folders:\n logging.info(line)\n\n if list_of_updated_low_level_folders:\n publish_to_pubsub('topic_to_run_parsing_script', str(list_of_updated_low_level_folders))\n\n return None\n","repo_name":"Mikkdrasil/la_searcher_bot","sub_path":"src/identify_updates_of_folders/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":12893,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"81"} +{"seq_id":"30133626886","text":"##\nimport numpy as np\nimport tqdm\nimport torch\nimport torch.nn as nn\nfrom torch.utils.data import DataLoader\nfrom torch import nn, optim\nfrom torch.nn.functional import relu\nimport matplotlib.pyplot as plt\nimport music21 as m21\n\ntorch.manual_seed(1)\n\nSEQ_LEN = 5\n\n##\nclass Dataset(torch.utils.data.Dataset):\n def __init__(self, data_size=54, seq_len=SEQ_LEN):\n self.data = np.array(np.concatenate([np.load('data/data_big_'+str(i*100)+'.npy', allow_pickle=True) for i in range(1,data_size)]))\n\n self.seq_len = seq_len\n\n def data_in_part(self, part):\n return len(part) - (self.seq_len + 1)\n\n def __len__(self):\n l = 0\n for part in self.data:\n l += self.data_in_part(part)\n return l\n\n def get_part(self, idx):\n i = idx\n for song in self.data:\n if i - self.data_in_song(song) < 0:\n break\n else:\n i -= self.data_in_song(song)\n return (song, i)\n\n def __getitem__(self, idx):\n for part in self.data:\n num_datapoints = self.data_in_part(part)\n if idx - num_datapoints < 0:\n break\n else:\n idx -= num_datapoints\n x = torch.view_as_complex(torch.tensor(part[idx:idx+self.seq_len], dtype=torch.float))\n y = torch.view_as_complex(torch.tensor([part[idx+self.seq_len]], dtype=torch.float))\n return (x, y)\n\n##\ndef complex_relu(z):\n return relu(z.real) + 1.j * relu(z.imag)\n\nclass CvnnModel(nn.Module):\n def __init__(self, layer_dims):\n super(CvnnModel, self).__init__()\n self.l1 = nn.Linear(layer_dims[0], layer_dims[1]).to(torch.cfloat)\n self.l2 = nn.Linear(layer_dims[1], layer_dims[2]).to(torch.cfloat)\n self.l3 = nn.Linear(layer_dims[2], layer_dims[3]).to(torch.cfloat)\n self.l4 = nn.Linear(layer_dims[3], 1).to(torch.cfloat)\n self.relu = complex_relu\n\n def forward(self, inputs):\n x = self.l1(inputs)\n x = self.relu(x)\n x = self.l2(x)\n x = self.relu(x)\n x = self.l3(x)\n x = self.relu(x)\n x = self.l4(x)\n return x\n\n##\ndef train(dataset, model, num_epochs):\n model.train()\n loss_vals = []\n\n dataloader = DataLoader(dataset, batch_size=64)\n loss_fn = nn.L1Loss()\n opt = optim.Adam(model.parameters())\n\n for epoch in range(num_epochs):\n epoch_loss = []\n for x, y in dataloader:\n opt.zero_grad()\n y_pred = model(x)\n loss = loss_fn(y_pred, y)\n loss.backward()\n opt.step()\n epoch_loss.append(loss.item())\n loss_vals.append(sum(epoch_loss)/len(epoch_loss))\n plt.plot(np.linspace(1, num_epochs, num_epochs).astype(int), loss_vals)\n plt.title(\"L1 loss\")\n plt.xlabel('Epoch')\n plt.ylabel('Loss')\n\n\n##\nmodel = CvnnModel(layer_dims=[SEQ_LEN, 10, 10, 4])\ndataset = Dataset(10, SEQ_LEN)\ntrain(dataset, model, 3)\n\n##\nmodel.eval()\nx = torch.view_as_complex(torch.tensor([[65,2],[65,1],[70,4], [63,2], [68,8]], dtype=torch.float))\nmodel(x)\n\n##\ndef generate(model, start, song_len):\n model.eval()\n start_len = len(start)\n seq = torch.cat((start, torch.zeros(song_len-start_len, dtype=torch.cfloat)))\n for i in range(start_len, song_len):\n x = seq[i-SEQ_LEN:i]\n y = model(x)\n seq[i] = y\n return seq\n\ndef to_stream(seq):\n stream = m21.stream.Stream()\n for cn in seq:\n note = m21.note.Note(pitch=round(cn.real.item()), duration=m21.duration.Duration(round(cn.imag.item())/4))\n stream.append(note)\n return stream\n\n##\nx = torch.view_as_complex(torch.tensor(np.load('data/data_big_5000.npy', allow_pickle=True)[1][10:15], dtype=torch.float))\nseq = generate(model, x, 30)\nprint(seq)\nstream = to_stream(seq)\nstream.show()\n\n##\nmf = m21.midi.translate.streamToMidiFile(stream)\nmf.open('./data/cvnn_output.midi', 'wb')\nmf.write()\nmf.close()\n\n\n\n\n\n\n\n","repo_name":"lukaspetersson/ye_tools","sub_path":"models/cvnn/cvnn.py","file_name":"cvnn.py","file_ext":"py","file_size_in_byte":3923,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"1554762916","text":"import argparse\nimport json\nimport os\n\nimport ray\nfrom ray import tune\nfrom ray.rllib.agents import ppo\nfrom ray.rllib.models import ModelCatalog\nfrom ray.rllib.utils.framework import try_import_tf, try_import_torch\nfrom ray.rllib.utils.test_utils import check_learning_achieved\nfrom ray.tune import grid_search\nfrom ray.tune.logger import pretty_print\n\nfrom qdTrees.config.appconfig import AppConfig\nfrom qdTrees.queryparsing.treeutils import TreeUtils\nfrom qdTrees.woodblock.custom_gym.envs.custom_env_dir import WoodblockCallbacks\nfrom qdTrees.woodblock.custom_gym.envs.custom_env_dir.WoodblockCallbacks import WoodblockCallbacksClass\nfrom qdTrees.woodblock.custom_gym.envs.custom_env_dir.woodblock_env import WoodBlockEnvMultiAgent\nfrom qdTrees.woodblock.custom_gym.envs.custom_env_dir.woodblock_model import WoodBlockActionMaskModel\n\ntf1, tf, tfv = try_import_tf()\ntorch, nn = try_import_torch()\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\n \"--run\",\n type=str,\n default=\"PPO\",\n help=\"The RLlib-registered algorithm to use.\")\nparser.add_argument(\n \"--framework\",\n choices=[\"tf\", \"tf2\", \"tfe\", \"torch\"],\n default=\"tf\",\n help=\"The DL framework specifier.\")\nparser.add_argument(\n \"--as-test\",\n action=\"store_true\",\n help=\"Whether this script should be run as a test: --stop-reward must \"\n \"be achieved within --stop-timesteps AND --stop-iters.\")\nparser.add_argument(\n \"--stop-iters\",\n type=int,\n default=50,\n help=\"Number of iterations to train.\")\nparser.add_argument(\n \"--stop-timesteps\",\n type=int,\n default=100000,\n help=\"Number of timesteps to train.\")\nparser.add_argument(\n \"--stop-reward\",\n type=float,\n default=0.1,\n help=\"Reward at which we stop training.\")\nparser.add_argument(\n \"--no-tune\",\n action=\"store_true\",\n help=\"Run without Tune using a manual train loop instead. In this case,\"\n \"use PPO without grid search and no TensorBoard.\")\nparser.add_argument(\n \"--local-mode\",\n action=\"store_true\",\n help=\"Init Ray in local mode for easier debugging.\")\n\n\ndef print_tree(info):\n\n episode = info[\"episode\"]\n print(f\"last info for: {episode.last_info_for()}\")\n print(f\"last info for: {episode}\")\n info = episode.last_info_for(\"0\")\n TreeUtils.print_tree_by_level(info[\"root\"])\n save_tree_to_file(info[\"root\"])\n\ndef save_tree_to_file(root):\n\n jsonStr = json.dumps(root.__dict__)\n print(jsonStr)\n\n\nif __name__ == \"__main__\":\n args = parser.parse_args()\n print(f\"Running with following CLI options: {args}\")\n\n ray.init(local_mode=args.local_mode)\n ModelCatalog.register_custom_model('woodblock_action_masking_model',\n WoodBlockActionMaskModel)\n\n config = {\n \"env\": WoodBlockEnvMultiAgent, # or \"corridor\" if registered above\n \"env_config\": {\n \"custom_config\": AppConfig('../../../../config/qdTreeConfig.json'),\n },\n # Use GPUs iff `RLLIB_NUM_GPUS` env var set to > 0.\n \"num_gpus\": int(os.environ.get(\"RLLIB_NUM_GPUS\", \"0\")),\n \"model\": {\n \"custom_model\": \"woodblock_action_masking_model\",\n \"fcnet_hiddens\": [512, 512],\n \"fcnet_activation\": \"relu\",\n \"vf_share_layers\": True,\n },\n \"lr\": grid_search([1e-2, 1e-4, 1e-6]), # try different lrs\n \"num_workers\": 1, # parallelism\n \"framework\": args.framework,\n \"log_level\": \"DEBUG\",\n }\n\n stop = {\n \"training_iteration\": args.stop_iters,\n \"timesteps_total\": args.stop_timesteps,\n \"episode_reward_mean\": args.stop_reward,\n }\n\n ppo_config = ppo.DEFAULT_CONFIG.copy()\n ppo_config.update(config)\n # use fixed learning rate instead of grid search (needs tune)\n ppo_config[\"lr\"] = 1e-3\n\n # ppo_config[\"callbacks\"] = {\"on_episode_end\": tune.function(print_tree)}\n\n if args.no_tune:\n # manual training with train loop using PPO and fixed learning rate\n if args.run != \"PPO\":\n raise ValueError(\"Only support --run PPO with --no-tune.\")\n print(\"Running manual train loop without Ray Tune.\")\n ppo_config = ppo.DEFAULT_CONFIG.copy()\n ppo_config.update(config)\n # use fixed learning rate instead of grid search (needs tune)\n ppo_config[\"lr\"] = 1e-3\n # ppo_config[\"callbacks\"] = {\"on_episode_end\": tune.function(print_tree)}\n trainer = ppo.PPOTrainer(config=ppo_config, env=WoodBlockEnvMultiAgent)\n # run manual training loop and print results after each iteration\n for _ in range(args.stop_iters):\n print(\"Start training\")\n result = trainer.train()\n print(\"Stop training\")\n print(pretty_print(result))\n # stop training of the target train steps or reward are reached\n if result[\"timesteps_total\"] >= args.stop_timesteps or \\\n result[\"episode_reward_mean\"] >= args.stop_reward:\n break\n else:\n # automated run with Tune and grid search and TensorBoard\n print(\"Training automatically with Ray Tune\")\n results = tune.run(\"PPO\", config=ppo_config, stop=stop)\n\n if args.as_test:\n print(\"Checking if learning goals were achieved\")\n check_learning_achieved(results, args.stop_reward)\n\n ray.shutdown()\n","repo_name":"MariaSGeo/Qd-Tree","sub_path":"qdTrees/woodblock/custom_gym/envs/custom_env_dir/woodblock.py","file_name":"woodblock.py","file_ext":"py","file_size_in_byte":5343,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"81"} +{"seq_id":"6246305918","text":"import tkinter as tk\nfrom src.views.GUI.Page import Page\n\nclass SeeRegisteredPeoplePage(Page):\n\tdef __init__(self, *args, **kwargs):\n\t\tPage.__init__(self, *args, **kwargs)\n\t\tself.size = 10\n\t\tself.tableData = [[]]\n\t\tself.currentPage = 1\n\n\t\tself.__createTable()\n\n\n\tdef setTableData(self, data):\n\t\tnewData = [[]]\n\t\tlenNewData = len(newData)\n\t\tfor item in data:\n\t\t\tnewData[lenNewData - 1].append(item)\n\n\t\t\tif (len(newData[lenNewData - 1]) == self.size):\n\t\t\t\tnewData.append([])\n\t\t\t\tlenNewData += 1\n\n\t\tself.tableData = newData\n\n\n\tdef updateTable(self):\n\t\tself.__clearTable()\n\t\tself.__createTable()\n\n\n\tdef __createTable(self):\n\t\tself.table = tk.Frame(self)\n\t\tself.table.pack()\n\n\t\t# Header\n\t\theader = tk.Frame(self.table)\n\t\theader.pack(pady=(20, 0))\n\n\t\tname = tk.Label(\n\t\t\theader,\n\t\t\ttext=\"Nome\",\n\t\t\twidth=45,\n\t\t\tbg=\"#4169E1\",\n\t\t\tfg=\"#FFF\",\n\t\t\tfont=('Arial', 12, 'bold'),\n\t\t\tborderwidth=1,\n\t\t\trelief=\"ridge\"\n\t\t)\n\t\tname.pack(side=\"left\")\n\n\t\tbirthDate = tk.Label(\n\t\t\theader,\n\t\t\ttext=\"Nascimento\",\n\t\t\twidth=20,\n\t\t\tbg=\"#4169E1\",\n\t\t\tfg=\"#FFF\",\n\t\t\tfont=('Arial', 12, 'bold'),\n\t\t\tborderwidth=1,\n\t\t\trelief=\"ridge\"\n\t\t)\n\t\tbirthDate.pack(side=\"left\")\n\n\t\tgender = tk.Label(\n\t\t\theader,\n\t\t\ttext=\"Sexo\",\n\t\t\twidth=20,\n\t\t\tbg=\"#4169E1\",\n\t\t\tfg=\"#FFF\",\n\t\t\tfont=('Arial', 12, 'bold'),\n\t\t\tborderwidth=1,\n\t\t\trelief=\"ridge\"\n\t\t)\n\t\tgender.pack(side=\"left\")\n\n\t\t# Body\n\t\tbody = tk.Frame(self.table)\n\t\tbody.pack()\n\t\t\n\t\tfor person in self.tableData[self.currentPage - 1]:\n\t\t\tpersonName = person[\"name\"]\n\t\t\tpersonBirthDate = person[\"birthDate\"]\n\t\t\tpersonGender = person[\"gender\"]\n\n\t\t\tline = tk.Frame(body)\n\t\t\tline.pack()\n\n\t\t\tlabelPersonName = tk.Label(\n\t\t\t\tline,\n\t\t\t\ttext=personName,\n\t\t\t\twidth=45,\n\t\t\t\tfont=('Arial', 12),\n\t\t\t\tanchor=\"w\"\n\t\t\t)\n\t\t\tlabelPersonName.pack(side=\"left\")\n\n\t\t\tlabelPersonBirthDate = tk.Label(\n\t\t\t\tline,\n\t\t\t\ttext=personBirthDate,\n\t\t\t\twidth=20,\n\t\t\t\tfont=('Arial', 12),\n\t\t\t\tanchor=\"w\"\n\t\t\t)\n\t\t\tlabelPersonBirthDate.pack(side=\"left\")\n\n\t\t\tlabelPersonGender = tk.Label(\n\t\t\t\tline,\n\t\t\t\ttext=personGender,\n\t\t\t\twidth=20,\n\t\t\t\tfont=('Arial', 12),\n\t\t\t\tanchor=\"w\"\n\t\t\t)\n\t\t\tlabelPersonGender.pack(side=\"left\")\n\n\t\t# Footer\n\t\tfooter = tk.Frame(self.table)\n\t\tfooter.pack(pady=5)\n\n\t\tbuttonFirstPage = tk.Button(\n\t\t\tfooter,\n\t\t\tbg=\"#4169E1\",\n\t\t\tfg=\"#FFF\",\n\t\t\tfont=('Arial', 10, 'bold'),\n\t\t\ttext=\"<<\",\n\t\t\tcommand=self.__firstPage\n\t\t)\n\t\tbuttonFirstPage.pack(side=\"left\")\n\n\t\tbuttonBackPage = tk.Button(\n\t\t\tfooter,\n\t\t\tbg=\"#4169E1\",\n\t\t\tfg=\"#FFF\",\n\t\t\tfont=('Arial', 10, 'bold'),\n\t\t\ttext=\"<\",\n\t\t\tcommand=self.__backPage\n\t\t)\n\t\tbuttonBackPage.pack(side=\"left\")\n\n\t\tcurrentPage = tk.Label(\n\t\t\tfooter,\n\t\t\twidth=4,\n\t\t\theight=2,\n\t\t\tfont=('Arial', 12, 'bold'),\n\t\t\ttext=self.currentPage\n\t\t)\n\t\tcurrentPage.pack(side=\"left\")\n\n\t\tbuttonLastPage = tk.Button(\n\t\t\tfooter,\n\t\t\tbg=\"#4169E1\",\n\t\t\tfg=\"#FFF\",\n\t\t\tfont=('Arial', 10, 'bold'),\n\t\t\ttext=\">>\",\n\t\t\tcommand=self.__lastPage\n\t\t)\n\t\tbuttonLastPage.pack(side=\"right\")\n\n\t\tbuttonNextPage = tk.Button(\n\t\t\tfooter,\n\t\t\tbg=\"#4169E1\",\n\t\t\tfg=\"#FFF\",\n\t\t\tfont=('Arial', 10, 'bold'),\n\t\t\ttext=\">\",\n\t\t\tcommand=self.__nextPage\n\t\t)\n\t\tbuttonNextPage.pack(side=\"right\")\n\n\n\tdef __nextPage(self):\n\t\tif ((self.currentPage + 1) <= len(self.tableData)):\n\t\t\tself.currentPage += 1\n\t\t\tself.updateTable()\n\n\n\tdef __backPage(self):\n\t\tif ((self.currentPage - 1) >= 1):\n\t\t\tself.currentPage -= 1\n\t\t\tself.updateTable()\n\n\n\tdef __lastPage(self):\n\t\tlengthTableData = len(self.tableData)\n\t\tif (self.currentPage != lengthTableData):\n\t\t\tself.currentPage = lengthTableData\n\t\t\tself.updateTable()\n\n\n\tdef __firstPage(self):\n\t\tif (self.currentPage != 1):\n\t\t\tself.currentPage = 1\n\t\t\tself.updateTable()\n\n\n\tdef __clearTable(self):\n\t\tself.table.destroy()\n","repo_name":"jose-mariano/cadastro-de-pessoas","sub_path":"src/views/GUI/SeeRegisteredPeoplePage.py","file_name":"SeeRegisteredPeoplePage.py","file_ext":"py","file_size_in_byte":3592,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"18098870858","text":"from django.contrib import admin\nfrom django.urls import path\nfrom usersite import views\nurlpatterns = [\n path(\"\",views.index,name='index'),\n path(\"myadmin_login\",views.myadmin_login,name='myadmin_login'),\n path(\"SupportersLogin\",views.SupportersLogin, name='SupportersLogin'),\n path(\"UsersLogin\",views.UsersLogin, name='UsersLogin'),\n path(\"usersignup\",views.usersignup, name='usersignup'),\n path(\"supsignup\",views.supsignup, name='supsignup'),\n path(\"userhome\",views.userhome, name='userhome'),\n path(\"supphome\",views.supphome, name='supphome'),\n path(\"logout\",views.index, name='index'),\n]\n","repo_name":"AbhinavPandey1911/Sahaya","sub_path":"usersite/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":620,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"73424032586","text":"# 省略else代码块\n\n\"\"\"python并不要求if—elif结构后面必须有else代码块,\n在有些情况下,else代码块很有用;\n而在其他一些情况下,使用一条elif语句来处理特定的情形更清晰\"\"\"\n\nage = 20\n\nif age < 4:\n price = 0\nelif age < 18:\n price = 5\nelif age < 65:\n price = 10\n# 这样的表示比else代码更清晰些\nelif age >= 65:\n price = 5\n\nprint(\"Your admission cost is $\" + str(price) + \".\")","repo_name":"leeoohs/python","sub_path":"course_5.3/amusement_park_5.3.5.py","file_name":"amusement_park_5.3.5.py","file_ext":"py","file_size_in_byte":449,"program_lang":"python","lang":"zh","doc_type":"code","stars":3,"dataset":"github-code","pt":"81"} +{"seq_id":"74794971145","text":"class Solution:\n def networkDelayTime(self, times: List[List[int]], n: int, k: int) -> int:\n # build table\n table = [[float('inf')] * (n+1) for _ in range(n+1)]\n \n # init\n for i in range(1, n+1):\n table[i][i] = 0\n for i, j, w in times:\n table[i][j] = w\n \n # floyd warshall\n for m in range(1, n+1):\n for i in range(1, n+1):\n for j in range(1, n+1):\n if table[i][j] > table[i][m] + table[m][j]:\n table[i][j] = table[i][m] + table[m][j]\n \n # 從k走到其他所有點的最大時間\n _max = -1\n for j in range(1, n+1):\n _max = max(_max, table[k][j])\n return _max if _max != float('inf') else -1\n","repo_name":"novayo/LeetCode","sub_path":"0743_Network_Delay_Time/try_4.py","file_name":"try_4.py","file_ext":"py","file_size_in_byte":794,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"81"} +{"seq_id":"73314338504","text":"import sys\r\ninput = sys.stdin.readline\r\nn = int(input())\r\ncity = [list(map(int,input().split())) for _ in range(n)]\r\nINF = 10**8\r\ndp = [[-1]*(1< List:\n return scrape(uniprotIDs, getLocs, **kwargs)\n\n\ndef _concatLocs(locList: List, delim: str = ';') -> str:\n #process text and remove any string in SKIP_LOCS\n ret = list(set(filter(lambda x: x not in SKIP_LOCS, [y.lower().strip() for y in locList])))\n if not ret:\n return 'no_annotated_location'\n return delim.join(ret)\n\n\ndef getLocs(uniprotID: str, nRetry: int = 10) -> Tuple:\n RETURN_COUNT = 3\n response = _make_request(uniprotID, nRetry)\n\n if response is None:\n return tuple(REQUEST_ERROR for _ in range(RETURN_COUNT))\n\n if response.status_code >= 400:\n return tuple(UNIPROT_ERROR for _ in range(RETURN_COUNT))\n\n tree = html.fromstring(response.content)\n\n #get sl uniprot anotation\n sl = tree.xpath(SL_XPATH)\n # ssl = tree.xpath(SSL_XPATH)\n # locs = _concatLocs(sl + ssl)\n locs = _concatLocs(sl)\n\n #get go term for celluar component\n go = tree.xpath(GO_XPATH)\n go = [CELLULAR_COMPONENT_RE.sub('', x) for x in go if CELLULAR_COMPONENT_RE.search(x)]\n # sgo = tree.xpath(SGO_XPATH)\n # gos = _concatLocs(go + sgo)\n gos = _concatLocs(go)\n\n concat = _concatLocs(sl + go)\n\n return locs, gos, concat\n\n","repo_name":"ajmaurais/protein_scrape","sub_path":"protein_scrape/scraper/loc.py","file_name":"loc.py","file_ext":"py","file_size_in_byte":1489,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"38175102127","text":"# -*- coding: utf-8 -*-\n\n# Define your item pipelines here\n#\n# Don't forget to add your pipeline to the ITEM_PIPELINES setting\n# See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html\nimport sqlite3\nfrom scrapy.conf import settings\nimport pymongo\n\nclass MongoPipeline(object):\n def __init__(self):\n host = settings['MONGODB_HOST']\n port = settings['MONGODB_PORT']\n dbName = settings['MONGODB_DBNAME']\n client = pymongo.MongoClient(host=host, port=port)\n tdb = client[dbName]\n self.post = tdb[settings['MONGODB_DOCNAME']]\n\n def process_item(self, item, spider):\n bookInfo = dict(item)\n self.post.insert(bookInfo)\n return item\n\nclass OnionPipeline(object):\n def process_item(self, item, spider):\n return item\n\nclass SQLitePipe(object): \n\n def open_spider(self,spider):\n #db_name = spider.settings.get('SQLITE_DB_NAME')\n self.con = sqlite3.connect('sqlite.db')\n self.cur = self.con.cursor() \n\n def close_spider(self,spider): \n self.con.commit()\n self.con.close()\n \n def process_item(self, item, spider): \n self.insert_db(item)\n return item\n\n def insert_db(self, item):\n #db_table = spider.settings.get('SQLITE_CATEGORY')\n values = (\n item['item_name'],\n item['item_link'],\n item['item_price'],\n item['item_seller'],\n item['item_delivery'],\n item['item_sales'],\n )\n sql = 'INSERT INTO ' + 'hush' + ' (item_name, item_link, item_price, item_seller, item_delivery, item_sales) VALUES(?,?,?,?,?,?)'\n self.cur.execute(sql, values)\n\n","repo_name":"lxwang42/onionscrap","sub_path":"onion/pipelines.py","file_name":"pipelines.py","file_ext":"py","file_size_in_byte":1681,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"7628166991","text":"import torch, numpy as np, os\nfrom torchvision.transforms import ToTensor, ToPILImage, Compose, Normalize, \\\n RandomRotation, RandomCrop, RandomHorizontalFlip\nimport avalanche as avl\nfrom avalanche.benchmarks.generators import benchmark_with_validation_stream\nfrom args import args\n\n\nclass AvalancheToPytorchDataset:\n def __init__(self, dataset='splitcifar100', return_task_id=True, val_size=0):\n self.dataset_name = args.dataname\n self.val_size = val_size\n self.curr_task = None\n\n self.kwargs = {\"num_workers\": args.workers, \"pin_memory\": args.pin_memory} if torch.cuda.is_available() else {}\n \n if args.dataname =='pmnist':\n self.dataset_classes = 10\n self.benchmark_original = avl.benchmarks.PermutedMNIST(n_experiences=args.num_tasks, seed=args.data_seed,\n dataset_root=os.path.join(args.server_home, 'datasets/'))\n elif args.dataname =='rmnist':\n self.benchmark_original = avl.benchmarks.RotatedMNIST(n_experiences=args.num_tasks, seed=args.data_seed,\n dataset_root=os.path.join(args.server_home, 'datasets/'))\n elif args.dataname =='smnist':\n self.dataset_classes = 10\n self.benchmark_original = avl.benchmarks.SplitMNIST(n_experiences=args.num_tasks, seed=args.data_seed, return_task_id=return_task_id,\n dataset_root=os.path.join(args.server_home, 'datasets/')) \n elif args.dataname =='splitcifar10':\n self.dataset_classes = 10\n self.benchmark_original = avl.benchmarks.SplitCIFAR10(n_experiences=args.num_tasks, seed=args.data_seed, \n return_task_id=return_task_id, fixed_class_order=np.arange(int(dataset.split('cifar')[-1])),\n dataset_root=os.path.join(args.server_home, 'datasets/'))\n elif args.dataname =='splitcifar100':\n self.dataset_classes = 100\n self.benchmark_original = avl.benchmarks.SplitCIFAR100(n_experiences=args.num_tasks, seed=args.data_seed, \n return_task_id=return_task_id, fixed_class_order=np.arange(int(dataset.split('cifar')[-1])),\n dataset_root=os.path.join(args.server_home, 'datasets/'))\n elif args.dataname =='splitcifar110':\n self.dataset_classes = 110\n self.benchmark_original = avl.benchmarks.SplitCIFAR110(n_experiences=args.num_tasks, seed=args.data_seed,\n fixed_class_order=np.arange(int(dataset.split('cifar')[-1])),\n dataset_root=os.path.join(args.server_home, 'datasets/'))\n elif args.dataname == 'tinyimagenet':\n self.dataset_classes = 200\n self.benchmark_original = avl.benchmarks.SplitTinyImageNet(n_experiences=args.num_tasks, seed=args.data_seed, return_task_id=True,\n dataset_root=os.path.join(args.server_home, 'datasets/'))\n else:\n raise NotImplementedError(f\"{dataset} Not implemented!\")\n \n if val_size != 0:\n self.benchmark = benchmark_with_validation_stream(self.benchmark_original, validation_size=val_size, \n input_stream='train', output_stream='val')#, lazy_splitting=False)\n else:\n self.benchmark = self.benchmark_original\n\n self.tasks = list(range(args.num_tasks))\n if args.dataname in ['pmnist', 'rmnist']:\n self.task_classes = [self.dataset_classes] * args.num_tasks\n self.total_classes = sum(self.task_classes)\n assert self.total_classes == self.dataset_classes * args.num_tasks\n self.max_classes = max(self.task_classes)\n else:\n self.task_classes = [self.dataset_classes//args.num_tasks] * args.num_tasks\n self.total_classes = sum(self.task_classes)\n assert self.total_classes == self.dataset_classes\n self.max_classes = max(self.task_classes)\n # self.original_classes_in_exp = self.benchmark.original_classes_in_exp\n self.get_ds_and_dl_from_aval_benchmark()\n pass\n\n def get_ds_and_dl_from_aval_benchmark(self):\n self.train_datasets, self.train_loaders = self.get_ds_and_dl_from_aval_stream(self.benchmark.train_stream, shuffle=True)\n self.test_datasets, self.test_loaders = self.get_ds_and_dl_from_aval_stream(self.benchmark.test_stream, shuffle=False)\n if self.val_size == 0:\n self.val_datasets, self.val_loaders = self.test_datasets, self.test_loaders\n else:\n self.val_datasets, self.val_loaders = self.get_ds_and_dl_from_aval_stream(self.benchmark.val_stream, shuffle=False)\n\n def get_ds_and_dl_from_aval_stream(self, stream, shuffle):\n datasets, loaders = [], []\n for i in range(len(stream)):\n datasets.append(stream[i].dataset)\n loaders.append(torch.utils.data.DataLoader(stream[i].dataset, batch_size=args.batch_size, shuffle=shuffle, **self.kwargs))\n return datasets, loaders\n\n def update_task(self, i):\n self.curr_task = i\n args.num_classes = self.task_classes[i]\n self.train_loader = self.train_loaders[i]\n self.val_loader = self.val_loaders[i]\n self.test_loader = self.test_loaders[i]\n pass\n","repo_name":"prateeky2806/exessnet","sub_path":"data/aval_datasets.py","file_name":"aval_datasets.py","file_ext":"py","file_size_in_byte":5701,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"81"} +{"seq_id":"40413518548","text":"#!/usr/bin/python\nimport time, serial\nimport RPi.GPIO as GPIO\n\n\nLCD_RS = 7\nLCD_E = 11\nLCD_DATA4 = 36\nLCD_DATA5 = 22\nLCD_DATA6 = 23\nLCD_DATA7 = 26\nGPIO_TRIGGER = 18\nGPIO_ECHO = 24\n\n\n\nLCD_WIDTH = 16 \nLCD_LINE_1 = 0x80 \nLCD_LINE_2 = 0xC0 \nLCD_CHR = GPIO.HIGH\nLCD_CMD = GPIO.LOW\nE_PULSE = 0.0005\nE_DELAY = 0.0005\n\ndef distance():\n # set Trigger to HIGH\n GPIO.output(GPIO_TRIGGER, True)\n \n # set Trigger after 0.01ms to LOW\n time.sleep(0.00001)\n GPIO.output(GPIO_TRIGGER, False)\n \n StartTime = time.time()\n StopTime = time.time()\n \n # save StartTime\n while GPIO.input(GPIO_ECHO) == 0:\n StartTime = time.time()\n \n # save time of arrival\n while GPIO.input(GPIO_ECHO) == 1:\n StopTime = time.time()\n \n # time difference between start and arrival\n TimeElapsed = StopTime - StartTime\n # multiply with the sonic speed (34300 cm/s)\n # and divide by 2, because there and back\n distance = (TimeElapsed * 34300) / 2\n \n return distance\n\ndef lcd_send_byte(bits, mode):\n GPIO.output(LCD_RS, mode)\n GPIO.output(LCD_DATA4, GPIO.LOW)\n GPIO.output(LCD_DATA5, GPIO.LOW)\n GPIO.output(LCD_DATA6, GPIO.LOW)\n GPIO.output(LCD_DATA7, GPIO.LOW)\n if bits & 0x10 == 0x10:\n GPIO.output(LCD_DATA4, GPIO.HIGH)\n if bits & 0x20 == 0x20:\n GPIO.output(LCD_DATA5, GPIO.HIGH)\n if bits & 0x40 == 0x40:\n GPIO.output(LCD_DATA6, GPIO.HIGH)\n if bits & 0x80 == 0x80:\n GPIO.output(LCD_DATA7, GPIO.HIGH)\n time.sleep(E_DELAY) \n GPIO.output(LCD_E, GPIO.HIGH) \n time.sleep(E_PULSE)\n GPIO.output(LCD_E, GPIO.LOW) \n time.sleep(E_DELAY) \n GPIO.output(LCD_DATA4, GPIO.LOW)\n GPIO.output(LCD_DATA5, GPIO.LOW)\n GPIO.output(LCD_DATA6, GPIO.LOW)\n GPIO.output(LCD_DATA7, GPIO.LOW)\n if bits&0x01==0x01:\n GPIO.output(LCD_DATA4, GPIO.HIGH)\n if bits&0x02==0x02:\n GPIO.output(LCD_DATA5, GPIO.HIGH)\n if bits&0x04==0x04:\n GPIO.output(LCD_DATA6, GPIO.HIGH)\n if bits&0x08==0x08:\n GPIO.output(LCD_DATA7, GPIO.HIGH)\n time.sleep(E_DELAY) \n GPIO.output(LCD_E, GPIO.HIGH) \n time.sleep(E_PULSE)\n GPIO.output(LCD_E, GPIO.LOW) \n time.sleep(E_DELAY) \n\ndef display_init():\n lcd_send_byte(0x33, LCD_CMD)\n lcd_send_byte(0x32, LCD_CMD)\n lcd_send_byte(0x28, LCD_CMD)\n lcd_send_byte(0x0C, LCD_CMD) \n lcd_send_byte(0x06, LCD_CMD)\n lcd_send_byte(0x01, LCD_CMD) \n\ndef lcd_message(message):\n message = message.ljust(LCD_WIDTH,\" \") \n for i in range(LCD_WIDTH):\n lcd_send_byte(ord(message[i]),LCD_CHR)\n \nif __name__ == '__main__':\n GPIO.setmode(GPIO.BOARD)\n GPIO.setwarnings(False)\n GPIO.setup(LCD_E, GPIO.OUT)\n GPIO.setup(LCD_RS, GPIO.OUT)\n GPIO.setup(LCD_DATA4, GPIO.OUT)\n GPIO.setup(LCD_DATA5, GPIO.OUT)\n GPIO.setup(LCD_DATA6, GPIO.OUT)\n GPIO.setup(LCD_DATA7, GPIO.OUT)\n GPIO.setup(GPIO_TRIGGER, GPIO.OUT)\n GPIO.setup(GPIO_ECHO, GPIO.IN)\n GPIO.setup(12, GPIO.OUT) #pin for motor 1\n GPIO.setup(15, GPIO.OUT) #pin for direction 1\n GPIO.setup(32, GPIO.OUT) #pin for motor 2\n GPIO.setup(16, GPIO.OUT) #pin for direction 2\n\n \n\n pwmOne = GPIO.PWM(12, 1000)\n pwmTwo = GPIO.PWM(32, 1000)\n \n pwmOne.start(0)\n pwmTwo.start(0)\n\n serPhone = serial.Serial(\"/dev/rfcomm0\", 9600, timeout = 0) #initialize bluetooth\n serPhone.baudrate = 9600\n pwmPower = 100\n updateLCD = False\n \n while True:\n data = serPhone.read(2)\n data = data.decode(\"utf-8\")\n data = data.lstrip(' ')\n print(\"Data: \", data)\n \n if(\"OH\" in data):\n pwmPower = 100\n if(\"NP\" in data):\n pwmPower = 90\n if(\"EP\" in data):\n pwmPower = 80\n \n \n #move forward\n if(\"TF\" in data):\n GPIO.output(15, 1)\n GPIO.output(16, 0)\n while(\"TS\" not in data):\n data = serPhone.read(2).decode(\"utf-8\").lstrip(\" \");\n time.sleep(1/32)\n pwmOne.ChangeDutyCycle(pwmPower)\n pwmTwo.ChangeDutyCycle(pwmPower)\n updateLCD = True\n print(\"Data: \", data)\n \n #move backward\n if(\"TB\" in data):\n GPIO.output(15, 0)\n GPIO.output(16, 1)\n while(\"TS\" not in data):\n data = serPhone.read(2).decode(\"utf-8\").lstrip(\" \");\n time.sleep(1/32)\n pwmOne.ChangeDutyCycle(pwmPower)\n pwmTwo.ChangeDutyCycle(pwmPower)\n updateLCD = True\n print(\"Data: \", data) \n \n #turn left\n if(\"TL\" in data):\n GPIO.output(15, 0)\n GPIO.output(16, 0)\n while(\"TS\" not in data):\n data = serPhone.read(2).decode(\"utf-8\").lstrip(\" \");\n time.sleep(1/32)\n pwmOne.ChangeDutyCycle(pwmPower)\n pwmTwo.ChangeDutyCycle(pwmPower)\n updateLCD = True\n print(\"Data: \", data)\n \n \n #turn right\n if(\"TR\" in data):\n GPIO.output(15, 1)\n GPIO.output(16, 1)\n while(\"TS\" not in data):\n data = serPhone.read(2).decode(\"utf-8\").lstrip(\" \");\n time.sleep(1/32)\n pwmOne.ChangeDutyCycle(pwmPower)\n pwmTwo.ChangeDutyCycle(pwmPower)\n updateLCD = True\n print(\"Data: \", data)\n \n \n pwmOne.ChangeDutyCycle(0)\n pwmTwo.ChangeDutyCycle(0)\n if(updateLCD):\n display_init()\n dist = \"%5.2f\" % distance()\n msg = \"Distance: \"\n for i in range(len(msg)):\n lcd_send_byte(LCD_LINE_1, LCD_CMD)\n lcd_message(msg)\n lcd_send_byte(LCD_LINE_2, LCD_CMD)\n lcd_message(dist)\n updateLCD = False\n time.sleep(0.0005)\n \n \n GPIO.cleanup()","repo_name":"sd2-lawnmower/AutonomousLawnMower","sub_path":"completeCode.py","file_name":"completeCode.py","file_ext":"py","file_size_in_byte":5987,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"28503866259","text":"4 #loops in the python\n\n\nnum = int(input('enter the number how many times do you want to execute::'))\nfor i in range(0,num):\n print(i)\n#now we will be see in this code 'for in lists'\n\nlist1 = ['item1','item2','item3']\nfor item in list1:\n print(item)\n '''we also can print list in row\n using with the help of the print(list1) '''\n\n\n\n\n\n\n\n\n\n","repo_name":"satyanshpandey/python_basic_and_simple_logic","sub_path":"loops2.py","file_name":"loops2.py","file_ext":"py","file_size_in_byte":363,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"81"} +{"seq_id":"29625421406","text":"'script to utilize the wolfBot twitter class'\n\nimport wolfTwitter.wolfBot as wolfBot\n\n#reload(wolfBot)\ncredFile = '/Users/hogstrom/Documents/code/configs/bot2.cfg'\nwb = wolfBot.howl_tweet(credFile)\nwb.verify_credentials()\n\nwb.scrape_craigslist_links()\nwb.retweet_search_results(search_phrase='#doglover',n_posts=2)\nwb.post_craigslist_links(n_posts=2)\nwb.favorite_search_results(search_phrase='#doglover',n_posts=10)","repo_name":"lhogstrom/ModernKicks","sub_path":"wolfTwitter/wolfBot_script.py","file_name":"wolfBot_script.py","file_ext":"py","file_size_in_byte":415,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"5006323610","text":"import psycopg2\n\nfrom api_hh import API_hh\nfrom config import config\n\ndata = API_hh()\nparams = config()\n\n\ndef get_data():\n \"\"\"Получение данных из файла json\"\"\"\n vacancy_data = []\n employer_data = []\n for x in data:\n for values in x:\n vacancy_id = values['id']\n vacancy_name = values['name']\n published_date = values['published_at']\n salary_from = values['salary']['from'] if values['salary'] else None\n salary_to = values['salary']['to'] if values['salary'] else None\n url = values['url']\n employer_id = values['employer']['id']\n name = values['employer']['name']\n\n vacancy_data.append(\n (\n vacancy_id,\n vacancy_name,\n published_date,\n salary_from,\n salary_to,\n url,\n employer_id\n )\n )\n\n employer_data.append(\n (\n employer_id,\n name\n )\n )\n return vacancy_data, employer_data\n\n\ndef save_database(database_name: str, params: dict):\n \"\"\"Функция сохранения данных в таблицы\"\"\"\n conn = psycopg2.connect(dbname=database_name, **params)\n conn.autocommit = True\n cur = conn.cursor()\n cur.execute(\"\"\"\n CREATE TABLE IF NOT EXISTS employers(\n employer_id int PRIMARY KEY,\n name varchar(255) NOT NULL);\n \n \n CREATE TABLE IF NOT EXISTS vacancies(\n vacancy_id int PRIMARY KEY,\n vacancy_name varchar(255) NOT NULL,\n published_date date,\n salary_from int,\n salary_to int,\n url text NOT NULL,\n employer_id int REFERENCES employers(employer_id) ON UPDATE CASCADE\n ); \n \"\"\")\n cur.execute('TRUNCATE vacancies RESTART IDENTITY CASCADE')\n cur.execute('TRUNCATE employers RESTART IDENTITY CASCADE')\n vacancies_data = get_data()[0]\n employer_data = get_data()[-1]\n\n cur.executemany(\"\"\"INSERT INTO employers VALUES (%s, %s) ON CONFLICT (employer_id) DO NOTHING;\"\"\", employer_data)\n cur.executemany(\"\"\"INSERT INTO vacancies VALUES (%s, %s, %s, %s, %s, %s, %s) ON CONFLICT (vacancy_id) DO NOTHING\"\"\",\n vacancies_data)\n\n cur.close()\n conn.close()\n\n","repo_name":"Xarveister/SQL_kursovaya","sub_path":"save_database.py","file_name":"save_database.py","file_ext":"py","file_size_in_byte":2489,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"37161878829","text":"\ndef find_max(file): \n count = 0 \n total = 0\n with open(file) as f: \n lines = f.readlines()\n for line in lines:\n line = line.strip()\n if line == \"\": \n #current = int(line) \n #count = current + count\n #print(\"hi\")\n if count >= total: \n total = count \n count = 0\n else: \n #print(line)\n count += int(line)\n print(total)\n\ndef find_highest(): \n with open(\"day1/calories.txt\") as file: \n file = file.readlines() \n calories = [] \n count = 0\n for line in file: \n if line != \"\\n\": \n count += int(line)\n else: \n calories.append(count)\n count = 0 \n calories.sort(reverse=True)\n print(\"Calories carried by top elf: \", calories[0])\n topthree = calories[0] + calories[1] + calories[2]\n print(\"Calories carried by top three elves: \", topthree)\n\ndef main(): \n #find_max(\"C:/rit/PersonalProjects/practice_projects/adventOfCode2022/day1/calories.txt\")\n find_highest()\n\nmain() ","repo_name":"Finn2689/practice_projects","sub_path":"adventOfCode2022/day1/CalorieCounter.py","file_name":"CalorieCounter.py","file_ext":"py","file_size_in_byte":1082,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"70188028104","text":"#!/usr/bin/python3\n\nimport json\n\npapers = json.load(open('papers.json', 'r'))\n\ndef key2URL(key):\n return key.replace(':', '-')\n\ndef authorList(authField):\n authors = authField.split(' and ')\n if len(authors) == 1:\n return authField\n elif len(authors) == 2:\n return '%s and %s' % (authors[0], authors[1])\n else:\n return ', '.join(authors[:-1]) + ', and ' + authors[len(authors)-1]\n\ndef getYear(paper):\n return paper['_key'].split(':')[-1][:4]\n\ndef makeReference(paper, pdfLink):\n slug = key2URL(paper['_key'])\n year = getYear(paper)\n\n s = ''\n\n if not pdfLink:\n s += '- '\n\n s += '%s, ' % authorList(paper['author'])\n if pdfLink:\n if '_pdf' not in paper: # meaning, no 'paper: no' entry\n s += '%s' % (year, slug, paper['title'])\n else:\n s += paper['title']\n else:\n s += '%s' % (slug, paper['title'])\n\n if paper['_type'] == 'inbook':\n s += ', in %s, _%s_' % (paper['editor'], paper['venue'])\n else:\n s += ', _%s_' % paper['venue'] \n if 'volume' in paper:\n s += ', vol. %s' % paper['volume']\n if 'number' in paper:\n s += ', no. %s' % paper['number']\n\n if 'pages' in paper:\n s += ', pp. %s' % paper['pages']\n\n if 'publisher' in paper:\n s += ', %s' % paper['publisher']\n\n s += ', %s.' % year\n\n if 'doi' in paper and pdfLink:\n s += ' DOI: %s' % (paper['doi'], paper['doi'])\n\n return s\n\n\nfor paper in papers:\n print(paper['_key'])\n\n slug = key2URL(paper['_key'])\n\n with open('publications/%s.md' % slug, 'w') as outFile:\n outFile.write('---\\n')\n outFile.write('title: \"%s\"\\n' % paper['title'])\n if 'abstract' in paper:\n outFile.write('description: \"%s\"\\n' % paper['abstract'].replace('\"', '\\\\\"'))\n if '_thumb' in paper:\n outFile.write('featuredImage: https://media.eagereyes.org%s\\n' % paper['_thumb'])\n\n outFile.write('---\\n\\n')\n outFile.write('# %s\\n\\n' % paper['title'])\n\n if '_thumb' in paper:\n outFile.write('

\\n\\n' % paper['_thumb'])\n\n if 'abstract' in paper:\n outFile.write('> _%s_\\n\\n' % paper['abstract'])\n\n # main reference\n outFile.write('%s\\n\\n' % makeReference(paper, True))\n\n # additional links\n if 'data' in paper:\n outFile.write('- Data\\n' % paper['data'])\n if 'website' in paper:\n outFile.write('- Website\\n' % paper['website'])\n if 'talk' in paper:\n outFile.write('- Talk\\n' % paper['talk'])\n \n # BibTeX\n outFile.write('\\n```bibtex\\n')\n outFile.write('@%s{%s,\\n' % (paper['_type'], paper['_key']))\n outFile.write('\\tyear = %s,\\n' % getYear(paper))\n for key in paper:\n if not key[0] == '_':\n outFile.write('\\t%s = {%s},\\n' % (key, paper[key]))\n outFile.write('}\\n```\\n')\n\n\n outFile.write('\\n')\n\nwith open('publications/index.md', 'w') as outFile:\n outFile.write('---\\n')\n outFile.write('title: Robert Kosara\\'s Publications\\n')\n outFile.write('---\\n\\n')\n outFile.write('# Robert Kosara\\'s Publications\\n\\n')\n\n lastYear = getYear(papers[0])\n outFile.write('## %s\\n\\n' % lastYear)\n for paper in papers:\n year = getYear(paper)\n if year != lastYear:\n outFile.write('\\n## %s\\n\\n' % year)\n lastYear = year\n\n outFile.write('%s\\n' % makeReference(paper, False))\n\n outFile.write('\\n')\n\n","repo_name":"eagereyes/eagereyes.org","sub_path":"renderPapers.py","file_name":"renderPapers.py","file_ext":"py","file_size_in_byte":3778,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"16035062592","text":"from art import logo,vs\nfrom game_data import data\nimport random\nimport os\nclear = lambda: os.system('cls')\n\n\n\ndef get_random():\n return random.choice(data)\ndef format(account):\n name = account[\"name\"]\n description = account[\"description\"]\n country = account[\"country\"]\n return f\"{name}, a {description}, from {country}\"\n\ndef compare(guess,a_followers,b_followers):\n if a_followers > b_followers:\n return guess == 'a'\n else:\n return guess == 'b'\ndef game():\n print(logo)\n score = 0\n game_is_running = True\n b_account = get_random()\n \n while game_is_running:\n \n a_account = b_account\n b_account = get_random()\n while a_account == b_account:\n b_account = get_random()\n\n print(f\"Compare A : {format(a_account)}\")\n print(vs)\n print(f\"Against B : {format(b_account)}\")\n\n guess = input(\"Who has more followers? Type 'A' or 'B': \").lower()\n\n a_followers = a_account['follower_count']\n b_followers = b_account['follower_count']\n is_correct = compare(guess,a_followers,b_followers)\n\n clear()\n print(logo)\n if is_correct:\n score += 1\n print(f\"You are right . And Score is {score} \")\n else :\n \n print(f\"You loose. Score is {score}\")\n game_is_running = False\ngame()","repo_name":"MaRuF-CoDe/Python","sub_path":"Day -14/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1376,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"34286602210","text":"#!/usr/bin/env python3\n# coding: utf-8\n\n# credits: https://pastebin.com/AdhDJKh5\n\nimport os\nfrom os.path import join, getsize\nimport subprocess\n\ndef get_human_readable_size(size,precision=2):\n suffixes=['B','KB','MB','GB','TB']\n suffixIndex = 0\n while size > 1024 and suffixIndex < 4:\n suffixIndex += 1\n size = size/1024.0\n return \"%.*f%s\"%(precision,size,suffixes[suffixIndex])\n\n\ndef scan(dir):\n if (os.path.isdir(\"{}/_layers\".format(dir))):\n layers = os.listdir(\"{}/_layers/sha256\".format(dir))\n imagesize = 0\n # get image size\n for layer in layers:\n # get size of layer\n for root, dirs, files in os.walk(\"{}/blobs/sha256/{}/{}\".format(registry_path, layer[:2], layer)):\n imagesize += (sum(getsize(join(root, name)) for name in files))\n repos.append({'dir': dir, 'size': imagesize})\n\n for subdir in os.listdir(dir):\n if (os.path.isdir(\"{}/{}\".format(dir, subdir))):\n scan(\"{}/{}\".format(dir, subdir))\n\nregistry_path = '/var/lib/gitlab_docker_registry/docker/registry/v2'\nrepos = []\n\nfor dir in os.listdir(\"{}/repositories\".format(registry_path)):\n scan(\"{}/repositories/{}\".format(registry_path, dir))\n\nrepos.sort(key=lambda k: k['size'], reverse=True)\nfor repo in repos:\n print(\"{}: {}\".format(repo['dir'], get_human_readable_size(repo['size'])))\n","repo_name":"microdevops-com/gitlab-admin","sub_path":"repo_sizes.py","file_name":"repo_sizes.py","file_ext":"py","file_size_in_byte":1378,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"81"} +{"seq_id":"12665998902","text":"import uuid\nimport base64\nfrom django.http import HttpResponseServerError\nfrom rest_framework.viewsets import ViewSet\nfrom rest_framework.response import Response\nfrom rest_framework import status\nfrom rest_framework.decorators import action\nfrom django.core.files.base import ContentFile\nfrom org_api import serializers\nfrom django.db.models.functions import Lower\nfrom django.db.models import Q\n\nfrom org_api.models import Item, Organizer, Category\nfrom org_api.serializers import ItemSerializer\n\n\nclass ItemView(ViewSet):\n \"\"\" Organize Me Item View \"\"\"\n\n def list(self, request):\n \"\"\" Handles the GET request, to get all items from the database, sorted in ascending order by name.\n\n Returns:\n Response: JSON serialized list of items\n \"\"\"\n\n items = Item.objects.all().order_by(Lower(\"name\"))\n\n search = self.request.query_params.get('search', None)\n if search is not None:\n items = Item.objects.filter(\n Q(name__contains=search) |\n Q(description__contains=search)\n )\n category = request.query_params.get('category', None)\n if category is not None:\n items = Item.objects.filter(category=category)\n\n serializer = ItemSerializer(items, many=True)\n return Response(serializer.data, status=status.HTTP_200_OK)\n\n def retrieve(self, request, pk):\n \"\"\" Handles the GET request to get a single item, if the selected key is not found then a 404 message is returned\n\n Returns:\n Response: JSON serialized list of the item for the selected key\n \"\"\"\n\n try:\n item = Item.objects.get(pk=pk)\n organizer = Organizer.objects.get(user=request.auth.user)\n item.liked = item in organizer.like_item.all()\n serializer = ItemSerializer(item)\n return Response(serializer.data, status=status.HTTP_200_OK)\n except Item.DoesNotExist as ex:\n return Response({'message': ex.args[0]}, status=status.HTTP_404_NOT_FOUND)\n\n def create(self, request):\n \"\"\" Handles the POST request to create a new item.\n\n Returns:\n Response: JSON serialized item instance\n \"\"\"\n\n organizer = Organizer.objects.get(user=request.auth.user)\n category = Category.objects.get(pk=request.data[\"category\"])\n\n format, imgstr = request.data[\"picture\"].split(';base64')\n ext = format.split('/')[-1]\n data = ContentFile(base64.b64decode(\n imgstr), name=f'{request.data[\"name\"]}--{uuid.uuid4()}.{ext}')\n\n item = Item.objects.create(\n name=request.data[\"name\"],\n org=organizer,\n picture=data,\n private=False,\n description=request.data[\"description\"],\n category=category\n )\n serializer = ItemSerializer(item)\n return Response(serializer.data, status=status.HTTP_201_CREATED)\n\n def update(self, request, pk):\n \"\"\" Handles the PUT request for the selected item. \n\n Returns:\n Response: Empty body with a 204 status code\n \"\"\"\n\n item = Item.objects.get(pk=pk)\n\n try:\n format, imgstr = request.data[\"picture\"].split(';base64')\n ext = format.split('/')[-1]\n data = ContentFile(base64.b64decode(\n imgstr), name=f'{request.data[\"name\"]}--{uuid.uuid4()}.{ext}')\n\n item.name = request.data[\"name\"]\n item.picture = data\n item.private = False\n item.description = request.data[\"description\"]\n item.category = Category.objects.get(pk=request.data[\"category\"])\n\n except ValueError as ex:\n item.name = request.data[\"name\"]\n item.private = False\n item.description = request.data[\"description\"]\n item.category = Category.objects.get(pk=request.data[\"category\"])\n\n item.save()\n return Response(None, status=status.HTTP_204_NO_CONTENT)\n\n @action(methods=['POST'], detail=True)\n def like(self, request, pk):\n \"\"\"POST request for the user to like an item\"\"\"\n\n organizer = Organizer.objects.get(user=request.auth.user)\n item = Item.objects.get(pk=pk)\n\n item.likes.add(organizer)\n\n return Response({'message': 'User added'}, status=status.HTTP_201_CREATED)\n\n @action(methods=['DELETE'], detail=True)\n def unlike(self, request, pk):\n \"\"\"\"DELETE request for the user to unlike an item \"\"\"\n\n organizer = Organizer.objects.get(user=request.auth.user)\n item = Item.objects.get(pk=pk)\n\n item.likes.remove(organizer)\n\n return Response({'message': 'User removed'}, status=status.HTTP_204_NO_CONTENT)\n","repo_name":"vickitaylor/organize-me-server","sub_path":"org_api/views/item.py","file_name":"item.py","file_ext":"py","file_size_in_byte":4741,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"70553972424","text":"class Node:\n def __init__(self,value):\n self.value = value\n self.left = None\n self.right = None\n\nclass BinarySearchTree:\n def __init__(self):\n #create a node\n self.root =None\n\n def insert(self,value):\n new_node =Node(value)\n if self.root == None:\n self.root = new_node\n return True\n temp =self.root\n while (True):\n if new_node.value == temp.value:\n False\n if new_node.value value:\n temp - temp.left\n else: \n return True \n \n return False\n","repo_name":"it-AVNG/DataEngineer","sub_path":"BST/constructBST.py","file_name":"constructBST.py","file_ext":"py","file_size_in_byte":1114,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"42866620915","text":"def per(y):\r\n if y == n:\r\n r[0] += 1\r\n return\r\n \r\n for x in range(n):\r\n if u[x] or lt_rb[n+x-y] or lb_rt[x+y]:\r\n continue\r\n lt_rb[n+x-y] = True\r\n lb_rt[x+y] = True\r\n u[x] = True\r\n\r\n per(y+1)\r\n\r\n lt_rb[n+x-y] = False\r\n lb_rt[x+y] = False\r\n u[x] = False\r\n \r\n\r\nn = int(input())\r\nu=[False]*n\r\nlt_rb=[False]*(3*n-1)\r\nlb_rt=[False]*(3*n-1)\r\nr = [0]\r\nper(0)\r\nprint(*r)","repo_name":"iblug/Baekjoon","sub_path":"백준/Gold/9663. N-Queen/N-Queen.py","file_name":"N-Queen.py","file_ext":"py","file_size_in_byte":458,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"30645692765","text":"# https://learn.microsoft.com/en-us/azure/databricks/dev-tools/api/latest/workspace#--import\nimport argparse\nimport configparser\nimport json\nimport os\n\nimport requests\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--folder\", default=\"./tests/integration/jobdefs\")\n parser.add_argument(\"--ini\", default=\"./tests/environment/config.ini\")\n args = parser.parse_args()\n\n cfp = configparser.ConfigParser()\n\n cfp.read(args.ini)\n db_host_id = cfp[\"DEFAULT\"][\"databricks_workspace_host_id\"]\n db_pat = cfp[\"DEFAULT\"][\"databricks_personal_access_token\"]\n\n JOB_URL = f\"https://{db_host_id}.azuredatabricks.net/api/2.1/jobs/create\"\n for job_def in os.listdir(args.folder):\n if not job_def.endswith(\"-def.json\"):\n continue\n \n print(job_def)\n with open(os.path.join(args.folder, job_def), 'r') as fp:\n job_json = json.load(fp)\n \n job_str = json.dumps(job_json)\n if job_def.startswith(\"spark2\"):\n job_str = job_str.replace(\"\", cfp[\"DEFAULT\"][\"databricks_spark2_cluster\"])\n else:\n job_str = job_str.replace(\"\", cfp[\"DEFAULT\"][\"databricks_spark3_cluster\"])\n \n job_json_to_submit = json.loads(job_str)\n\n resp = requests.post(\n url=JOB_URL,\n json=job_json_to_submit,\n headers={\n \"Authorization\": f\"Bearer {db_pat}\"\n }\n )\n print(resp.content)\n\n\n","repo_name":"microsoft/Purview-ADB-Lineage-Solution-Accelerator","sub_path":"tests/environment/dbfs/create-job.py","file_name":"create-job.py","file_ext":"py","file_size_in_byte":1513,"program_lang":"python","lang":"en","doc_type":"code","stars":79,"dataset":"github-code","pt":"81"} +{"seq_id":"43969964854","text":"import torch\r\nimport argparse\r\nimport os\r\nimport sys\r\nsys.path.append(os.path.join(os.path.dirname(__file__), \"../\"))\r\nimport onnxmltools\r\nfrom onnxmltools.utils.float16_converter import convert_float_to_float16\r\nfrom utils.common import get_model\r\nfrom utils.config import Config\r\nfrom utils.dist_utils import dist_print\r\n\r\n\r\n\r\ndef get_args():\r\n parser = argparse.ArgumentParser()\r\n parser.add_argument('--config_path', default='configs/culane_res34.py', help='path to config file', type=str)\r\n parser.add_argument('--model_path', default='weights/culane_res34.pth',\r\n help='path to model file', type=str)\r\n parser.add_argument('--accuracy', default='fp32', choices=['fp16', 'fp32'], type=str)\r\n parser.add_argument('--size', default=(1600, 320), help='size of original frame', type=tuple)\r\n return parser.parse_args()\r\n\r\n\r\ndef convert(model, args):\r\n dist_print('start convert...')\r\n images = torch.ones((1, 3, args.size[1], args.size[0])).cuda()\r\n onnx_path = args.model_path[:-4] + \".onnx\"\r\n with torch.no_grad():\r\n torch.onnx.export(model, images,\r\n onnx_path,\r\n verbose=False,\r\n input_names=['input'],\r\n output_names=[\"loc_row\", \"loc_col\", \"exist_row\", \"exist_col\"])\r\n dist_print(\"Export ONNX successful. Model is saved at\", onnx_path)\r\n\r\n if args.accuracy == 'fp16':\r\n onnx_model = onnxmltools.utils.load_model(onnx_path)\r\n onnx_model = convert_float_to_float16(onnx_model)\r\n\r\n onnx_half_path = args.model_path[:-4] + \"_fp16.onnx\"\r\n onnxmltools.utils.save_model(onnx_model, onnx_half_path)\r\n dist_print(\"Half model is saved at\", onnx_half_path)\r\n\r\n\r\nif __name__ == \"__main__\":\r\n torch.backends.cudnn.benchmark = True\r\n args = get_args()\r\n cfg = Config.fromfile(args.config_path)\r\n cfg.batch_size = 1\r\n\r\n assert cfg.backbone in ['18', '34', '50', '101', '152', '50next', '101next', '50wide', '101wide']\r\n\r\n if cfg.dataset == 'CULane':\r\n cls_num_per_lane = 18\r\n elif cfg.dataset == 'Tusimple':\r\n cls_num_per_lane = 56\r\n else:\r\n raise NotImplementedError\r\n\r\n net = get_model(cfg)\r\n\r\n state_dict = torch.load(args.model_path, map_location='cpu')['model']\r\n compatible_state_dict = {}\r\n for k, v in state_dict.items():\r\n if 'module.' in k:\r\n compatible_state_dict[k[7:]] = v\r\n else:\r\n compatible_state_dict[k] = v\r\n net.load_state_dict(compatible_state_dict, strict=False)\r\n convert(net, args)\r\n","repo_name":"cfzd/Ultra-Fast-Lane-Detection-v2","sub_path":"deploy/pt2onnx.py","file_name":"pt2onnx.py","file_ext":"py","file_size_in_byte":2625,"program_lang":"python","lang":"en","doc_type":"code","stars":446,"dataset":"github-code","pt":"81"} +{"seq_id":"3676500500","text":"\"\"\"\nThe code below queries a table that finds the country that has the largest\nnumber of ports with a cargo wharf from the geo_international_ports dataset and\nstores it within a dataset. A dataset foodpanda_project is created if the\nspecified dataset does not exist within the project folder 'bigquery-tour'.\n\"\"\"\n\nimport os\nfrom google.cloud import bigquery\nfrom google.cloud.exceptions import NotFound\n\n# Set up environment variable to the path of JSON file\nos.environ[\"GOOGLE_APPLICATION_CREDENTIALS\"] = \"bigquery-tour-635ad9479312.json\"\n\n# Create new Google BigQuery client using Cloud Platform project default\nclient = bigquery.Client()\n\n# Reference to project id and new or existing dataset\nproject_id = \"bigquery-tour\"\ndataset_id = \"tour-dataset\"\nfull_dataset_id = \"{}.{}\".format(project_id, dataset_id)\n\n# Check to see if dataset already exists within project, if not then create new BigQuery dataset\ntry:\n dataset = client.get_dataset(full_dataset_id)\n print(\"Dataset {} exists\".format(full_dataset_id))\nexcept NotFound:\n print(\"Dataset {} not found, creating new dataset\".format(full_dataset_id))\n db = bigquery.Dataset(full_dataset_id)\n dataset = client.create_dataset(db)\n\n# Reference to new table for storing query results\ntable_id = dataset.table(\"number_of_ports\")\n\n# Configure query job and set destination as new table mentioned above\njob_config = bigquery.QueryJobConfig(destination = table_id)\n\n# Query to find the country that has the most number of ports with a cargo wharf\nquery = \"\"\"\n SELECT country, COUNT(DISTINCT index_number) AS port_count\n FROM bigquery-public-data.geo_international_ports.world_port_index\n WHERE cargo_wharf = TRUE\n GROUP BY country\n ORDER BY 2 DESC\n LIMIT 1\"\"\"\n\n# Run query and wait for it to finish\nquery_job = client.query(query, job_config = job_config)\nquery_job.result()\nprint(\"Query results loaded onto table {}\".format(table_id))\n","repo_name":"dngatimin95/BigQuery_Tour","sub_path":"number_of_ports.py","file_name":"number_of_ports.py","file_ext":"py","file_size_in_byte":1916,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"33522042345","text":"#!/usr/bin/env python\n\n\"\"\"\n\nThe Corpus are a fictional faction from the popular video game Warframe who have a somewhat interesting language.\n\nWhilst other factions in the game such as the Grineer have some logic behind their language, the Corpus is simply a lossy substitution of the English language.\n\nAll Corpus words are the same as their English counterparts, except with the following alphabetical mappings:\n\nEnglish to Corpus mapping\n\nThis causes some problems with pronunciation as:\n\nyes becomes yey\nsay becomes yay\nyay becomes yay\nsassy becomes yayyy\ncase becomes yaye\n\nHere's a text version of the mappings:\n\na -> a\nb -> t\nc -> y\nd -> p\ne -> e\nf -> t\ng -> j\nh -> k\ni -> i\nj -> t\nk -> k\nl -> p\nm -> s\nn -> t\no -> o\np -> k\nq -> r\nr -> t\ns -> y\nt -> p\nu -> u\nv -> t\nw -> j\nx -> k\ny -> y\nz -> b\nThe challenge\nGiven text using the English alphabet, output its Corpus translation.\n\nFor example, the text Hello, World! becomes Keppo, Jotpp! in Corpus\n\nThe Rules\nInput will only consist of ASCII printable characters\nInput text may contain whitespace and punctuation, these must be preserved\nCapitalization of letters must be preserved\nThis is code-golf so naturally, fewest bytes wins!\nThe Testcases\nTest cases are separated with <===========>, with a blank line between input and expected output\n\nHello, World!\n\nKeppo, Jotpp!\n<===========>\nYes\n\nYey\n<===========>\nTestcaSe\n\nPeypyaYe\n<===========>\nProgramming Puzzles and Code Golf\n\nKtojtassitj Kubbpey atp Yope Jopt\n<===========>\nThis text has a\nnewline in it\n\nPkiy pekp kay a\ntejpite it ip\n<===========>\nCorpus language best language\n\nYotkuy patjuaje teyp patjuaje\n<===========>\nStrip the flesh! Salt the wounds!\n\nYptik pke tpeyk! Yapp pke joutpy!\n<===========>\n\"Install Warframe\" they said, \"It'll be fun\" they said\n\n\"Itypapp Jatttase\" pkey yaip, \"Ip'pp te tut\" pkey yaip\n<===========>\nWhat the **** did you just ****ing say about me, you little *****?\nI'll have you know I graduated top of my class in the Navy Seals,\nand I've been involved in numerous secret raids on Al-Quaeda,\nand I have over 300 confirmed kills.\n\nJkap pke **** pip you tuyp ****itj yay atoup se, you pipppe *****?\nI'pp kate you ktoj I jtapuapep pok ot sy ypayy it pke Taty Yeapy,\natp I'te teet ittoptep it tusetouy yeytep taipy ot Ap-Ruaepa,\natp I kate otet 300 yottitsep kippy.\nThe Bonus\nIf you also include an audio recording (or video with audio) of you pronouncing each of the testcase's Corpus translations, you may multiply your bytecount by 1 as a reward.\n\n\"\"\"\n\ndef eng2corp(s):\n m = {\n 'a': 'a',\n 'b': 't',\n 'c': 'y',\n 'd': 'p',\n 'e': 'e',\n 'f': 't',\n 'g': 'j',\n 'h': 'k',\n 'i': 'i',\n 'j': 't',\n 'k': 'k',\n 'l': 'p',\n 'm': 's',\n 'n': 't',\n 'o': 'o',\n 'p': 'k',\n 'q': 'r',\n 'r': 't',\n 's': 'y',\n 't': 'p',\n 'u': 'u',\n 'v': 't',\n 'w': 'j',\n 'x': 'k',\n 'y': 'y',\n 'z': 'b',\n }\n\n p = \"\"\n for c in s:\n k = c.lower()\n if k in m:\n if c.isupper():\n c = m[k].upper()\n else:\n c = m[k]\n p += c\n return p\n\ndef main():\n assert(eng2corp(\"Hello, World!\") == \"Keppo, Jotpp!\")\n assert(eng2corp(\"Yes\") == \"Yey\")\n assert(eng2corp(\"TestcaSe\") == \"PeypyaYe\")\n assert(eng2corp(\"Programming Puzzles and Code Golf\") == \"Ktojtassitj Kubbpey atp Yope Jopt\")\n assert(eng2corp(\"This text has a\\nnewline in it\") == \"Pkiy pekp kay a\\ntejpite it ip\")\n assert(eng2corp(\"Corpus language best language\") == \"Yotkuy patjuaje teyp patjuaje\")\n assert(eng2corp(\"Strip the flesh! Salt the wounds!\") == \"Yptik pke tpeyk! Yapp pke joutpy!\")\n assert(eng2corp(\"\\\"Install Warframe\\\" they said, \\\"It'll be fun\\\" they said\") == \"\\\"Itypapp Jatttase\\\" pkey yaip, \\\"Ip'pp te tut\\\" pkey yaip\")\n assert(eng2corp(\"What the **** did you just ****ing say about me, you little *****?\\nI'll have you know I graduated top of my class in the Navy Seals,\\nand I've been involved in numerous secret raids on Al-Quaeda,\\nand I have over 300 confirmed kills.\") == \"Jkap pke **** pip you tuyp ****itj yay atoup se, you pipppe *****?\\nI'pp kate you ktoj I jtapuapep pok ot sy ypayy it pke Taty Yeapy,\\natp I'te teet ittoptep it tusetouy yeytep taipy ot Ap-Ruaepa,\\natp I kate otet 300 yottitsep kippy.\")\n\nmain()\n","repo_name":"qeedquan/challenges","sub_path":"codegolf/translate-english-to-corpus.py","file_name":"translate-english-to-corpus.py","file_ext":"py","file_size_in_byte":4380,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"27180851628","text":"M = 17\nN = 5\nsize = [3, 4, 7, 8, 9]\nval = [4, 5, 10, 11, 13]\nitems = {\n 0: \"-\",\n 1: \"A\",\n 2: \"B\",\n 3: \"C\",\n 4: \"D\",\n 5: \"E\"\n}\ncost = [0] * M\nbest = [0] * M\nfor j in range(N): # number of items\n for i in range(M): # capacity\n capacity = i + 1\n if capacity >= size[j]:\n last_size = max(i - size[j], 0) # cost[-1] is the last item of cost lol\n if cost[i] < cost[last_size] + val[j]:\n cost[i] = cost[last_size] + val[j]\n best[i] = j + 1\n print(f\"Cost: {cost}\")\n print(\"Best:\", end = \" \")\n for i in range(M):\n print(items[best[i]], end=\" \")\n print()\n\n\n","repo_name":"ret1s/random-puzzles","sub_path":"random-coding/knapsack.py","file_name":"knapsack.py","file_ext":"py","file_size_in_byte":653,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"74357911943","text":"import openai\nimport os\nimport json\nimport speech_recognition as sr\nfrom pocketsphinx import LiveSpeech\nfrom elevenlabslib import *\nimport platform\n\nfrom database import database\nfrom serial_interface import SerialInterface, print_received_data\nfrom item import Item\nfrom color import Color\n\nclass FindyBot5000:\n def __init__(self, port: str) -> None:\n # Keyword identification and sentence detection\n # Sphinx has some trouble getting 'jarvis' every time...\n self.keywords = ['jarvis', 'jervis']\n\n # Large Language Model and speech to text - OpenAI \n self.openai_key = os.environ.get('OPENAI_API_KEY')\n openai.api_key = self.openai_key\n self.engine = \"text-davinci-003\"\n\n # Voice synthesis - ElevenLabs\n self.elevenlabs_key = os.environ.get('ELEVENLABS_API_KEY')\n self.voice_name = \"Rachel\"\n self.recognizer = sr.Recognizer()\n self.speech = sr.Microphone(device_index=0)\n self.user = ElevenLabsUser(self.elevenlabs_key)\n self.voice = self.user.get_voices_by_name(self.voice_name)[0] # This is a list because multiple voices can have the same name\n\n # SQL database\n self.db = database()\n\n # Serial port interface to communicate with Arduino\n if port is None:\n os_name = platform.system()\n\n if self.serial is None:\n if os_name == 'Linux':\n self.serial = SerialInterface('dev/ttyACM0', 115200, print_received_data)\n elif os_name == 'Windows':\n self.serial = SerialInterface('COM7', 115200, print_received_data)\n \n self.serial.open()\n else:\n self.serial = SerialInterface(port, 115200, print_received_data)\n self.serial.open()\n\n self.serial.clear_display()\n self.serial.set_relay(False)\n\n\n def run(self) -> None:\n\n quit = False\n\n while not quit:\n # Step 0: Detect a human\n # todo\n \n try:\n # Step 1: Listen for the keyword\n #keyword_speech = LiveSpeech(lm=False, keyphrase='jarvis', kws_threshold=1e-20)\n print('Listening for Keyword...')\n keyword_speech = LiveSpeech()\n for phrase in keyword_speech:\n words = str(phrase)\n if any(keyword in words for keyword in self.keywords):# 'jarvis' in words or 'jervis' in words:\n print(f'Heard a keyword! {self.keywords}')\n break\n elif 'print' in words or 'table' in words:\n self.db.print_tables()\n elif 'exit' in words or 'quit' in words or 'stop' in words:\n quit = True\n self.serial.close()\n raise Exception(\"Quitting\")\n elif 'clear' in words:\n self.serial.clear_display()\n self.serial.set_relay(False)\n\n # Step 2: Listen for a sentence\n with self.speech as source:\n print(\"Listening for a sentence...\")\n audio = self.recognizer.adjust_for_ambient_noise(source)\n audio = self.recognizer.listen(source)\n \n # Step 3: Speech to Text\n print(\"Running speech to text with Whisper\")\n whisper_text = self.recognizer.recognize_whisper_api(audio, model=\"whisper-1\", api_key=self.openai_key)\n print(f\"Whisper thinks you said: '{whisper_text}'\")\n\n if whisper_text == '':\n continue\n \n # Step 4: Identify items from text using one of OpenAI's GPT LLM's\n human_response, json_response = self.get_responses(whisper_text)\n\n print(f\"OpenAI human response: '{human_response}'\")\n print(f\"OpenAI json response: '{json_response}'\")\n\n # Step 5: Use EleventLabs to synthesize a voice response for the item being looked for\n print(\"Generating and playing audio\")\n self.voice.generate_and_play_audio(human_response, playInBackground=False)\n\n # Step 6: Use the json_response to update the database\n print(\"Updating database\")\n cmd, items_to_display = self.update_database(json_response)\n\n # Step 7: Display the items\n print(\"Displaying items\")\n self.display_items(cmd, items_to_display)\n\n except sr.UnknownValueError:\n print(\"Sphinx could not understand audio\")\n except sr.RequestError as e:\n print(f\"Sphinx error; {e}\")\n except Exception as e:\n print(f\"Ex: {e}\")\n\n def update_database(self, json_response: str) -> list:\n try:\n parsed_json = json.loads(json_response)\n cmd = parsed_json['cmd']\n items = parsed_json['items']\n\n items_to_display = []\n\n if cmd == 'find':\n for item in items:\n found_items = self.db.search_items(item)\n for found_item in found_items:\n items_to_display.append(found_item)\n\n elif cmd == 'add':\n for item in items:\n added_or_updated_item = self.db.add_or_update_item(item)\n for added_item in added_or_updated_item:\n items_to_display.append(added_item)\n\n elif cmd == 'remove':\n items_deleted = self.db.delete_items2(items)\n for item in items_deleted:\n items_to_display.append(item)\n else:\n print(f\"Unexpected command: '{cmd}'\")\n \n return cmd, items_to_display\n\n except json.JSONDecodeError:\n print(\"The string provided is not a valid JSON.\")\n\n def display_items(self, cmd: str, items: list) -> None:\n \n if not self.serial.relay_on:\n print(\"Turning relay on\")\n self.serial.set_relay(True)\n \n for item in items:\n print(item)\n \n if cmd == 'find':\n color = Color.LawnGreen\n elif cmd == 'add':\n color = Color.Cyan\n elif cmd == 'remove':\n color = Color.Red\n\n self.serial.set_box_color(item[Item.Row], item[Item.Col], color)\n\n def get_responses(self, question: str) -> str: \n\n language_prompt = \\\n 'You are a helpful assistant. A user will ask you to find, add, or remove items. Assume all items can be found.' + \\\n 'Reply with a friendly message. The message must mention the items. If there are no items, reply with an empty sentence. ' + \\\n 'Do not mention where the items are added or removed. It must be a single sentence.' + \\\n f'Question: {question}'\n\n openai_response = openai.Completion.create(\n engine=self.engine,\n prompt=language_prompt,\n max_tokens=1024,\n n=1,\n stop=None,\n temperature=0.5,\n )\n\n language_response = openai_response[\"choices\"][0][\"text\"].strip()\n\n json_prompt = \\\n 'You are a helpful assistant. You are asked to find, add, or remove items. Reply with json only. ' + \\\n 'If finding items, format as: { \"cmd\": \"find\", \"items\": [\"red LEDs\", \"blue LEDs\"] }. ' + \\\n 'If adding items, format as: { \"cmd\": \"add\", \"items\": [\"green LEDs\"] }. ' + \\\n 'If removing items, format as: { \"cmd\": \"remove\", \"items\": [\"yellow LEDs\", \"twist ties\", \"9V battery\"] }.' + \\\n f'Question: {question}'\n \n openai_response = openai.Completion.create(\n engine=self.engine,\n prompt=json_prompt,\n max_tokens=1024,\n n=1,\n stop=None,\n temperature=0.5,\n )\n\n json_response = openai_response[\"choices\"][0][\"text\"].strip()\n\n return language_response, json_response\n\n","repo_name":"Inventor22/FindyBot5000","sub_path":"RaspberryPi/prod/findy_bot_5000.py","file_name":"findy_bot_5000.py","file_ext":"py","file_size_in_byte":8191,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"70212954506","text":"#!/usr/bin/env python3\n\nimport boto3\nimport pprint\nimport datetime\nfrom datetime import timedelta, timezone, datetime\nfrom time import strftime\nimport dateutil.parser\nfrom akinaka.client.aws_client import AWS_Client\nfrom akinaka.libs import helpers\nimport logging\n\nhelpers.set_logger()\naws_client = AWS_Client()\n\nclass CleanupVolumes():\n\n def __init__(self, region, role_arns, not_dry_run):\n self.region = region\n self.role_arns = role_arns\n self.not_dry_run = not_dry_run\n\n def list_volumes(self, role_arn, filters={}):\n ec2_client = aws_client.create_client('ec2', self.region, role_arn)\n\n return ec2_client.describe_volumes(\n DryRun=False,\n Filters=[\n filters\n ],\n )['Volumes']\n\n def list_available_volumes(self, role_arn):\n return self.list_volumes(role_arn, filters={'Name': 'status', 'Values': ['available']})\n\n def delete_volumes(self, volumes, role_arn):\n ec2_client = aws_client.create_client('ec2', self.region, role_arn)\n volumes = self.list_available_volumes(role_arn)\n\n for volume in volumes:\n ec2_client.delete_volume(VolumeId=volume['VolumeId'])\n\n def cleanup(self):\n for role in self.role_arns:\n logging.error(\"Processing account: {}\".format(role))\n volumes_to_delete = self.list_available_volumes(role)\n\n if self.not_dry_run:\n logging.info(\"Deleting the following volumes and their snapshots: {}\".format(volumes_to_delete))\n self.delete_volumes(volumes_to_delete, role)\n else:\n logging.info(\"These are the volumes I would have deleted if you gave me --not-dry-run:\\n\")\n for volume in volumes_to_delete:\n logging.info(\"Volume: {}\\n\".format(volume['VolumeId']))\n","repo_name":"afrazkhan/akinaka","sub_path":"akinaka/cleanup/ebs/cleanup_volumes.py","file_name":"cleanup_volumes.py","file_ext":"py","file_size_in_byte":1861,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"81"} +{"seq_id":"74896128264","text":"from transformers import TFBertForSequenceClassification, BertTokenizerFast, TFTrainer, TFTrainingArguments\nimport tensorflow as tf\nfrom nlp import load_dataset\nfrom config import *\n\ntokenizer = BertTokenizerFast.from_pretrained('bert-base-uncased')\n\ndef tokenize(batch):\n return tokenizer(batch['text'], padding=True, truncation=True)\n\ntrain_dataset, test_dataset = load_dataset('imdb', split=['train', 'test'])\ntrain_dataset = train_dataset.map(tokenize, batched=True, batch_size=len(train_dataset))\ntest_dataset = test_dataset.map(tokenize, batched=True, batch_size=len(train_dataset))\ntrain_dataset.set_format('tensorflow', columns=['input_ids', 'attention_mask', 'label'])\ntest_dataset.set_format('tensorflow', columns=['input_ids', 'attention_mask', 'label'])\n\ndef to_tfds(dataset):\n x = {}\n x['input_ids'] = train_dataset['input_ids'].to_tensor(default_value=0, shape=[None, tokenizer.max_len])\n x['attention_mask'] = train_dataset['attention_mask'].to_tensor(default_value=0, shape=[None, tokenizer.max_len])\n y = train_dataset['label']\n return tf.data.Dataset.from_tensor_slices((x, y))\n\ntf_train_dataset = to_tfds(train_dataset)\ntf_test_dataset = to_tfds(test_dataset)\n\ncompute_strategy = tf.distribute.MirroredStrategy()\n\nwith compute_strategy.scope():\n model = TFBertForSequenceClassification.from_pretrained('bert-base-uncased')\n \n model.compile(optimizer = tf.keras.optimizers.Adam(learning_rate=3e-5),\n loss = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True))\n \n model.fit(tf_train_dataset.batch(BATCH_SIZE), epochs=EPOCHS)\n","repo_name":"ilyamirin/GPUs-load-testing","sub_path":"tensorflow-load-tester.py","file_name":"tensorflow-load-tester.py","file_ext":"py","file_size_in_byte":1604,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"2211927396","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nfrom torch.optim.lr_scheduler import ReduceLROnPlateau, StepLR, MultiStepLR\nimport numpy as np\nimport argparse\nfrom tqdm import tqdm, trange\nimport os\nfrom tensorboardX import SummaryWriter\nfrom torch.backends import cudnn\n# from kittiloader import KittiDataset\nfrom oxfordloader import Oxford_train_base\nfrom oxfordloader import *\nfrom model.models import KPNet\nfrom model.losses import ChamferLoss, Point2PointLoss\nimport model.losses as loss\nimport evaluate\n\ndef parse_args():\n parser = argparse.ArgumentParser('RSKDD')\n parser.add_argument('--batch_size', type=int, default=8)\n parser.add_argument('--max_epoch', type=int, default=100)\n parser.add_argument('--lr', type=float, default=0.00005)\n # parser.add_argument('--momentum', type=float, default=0.9)\n parser.add_argument('--weight_decay', type=float, default=1e-4)\n parser.add_argument('--num_workers', type=int, default=4)\n parser.add_argument('--gpu', type=str, default='0')\n # parser.add_argument('--data_dir', type=str, default='',help='dir of dataset')\n # parser.add_argument('--seq', type=str, default='00', help='training sequence of Kitti dataset')\n parser.add_argument('--graph_k',type=int, default=20)\n parser.add_argument('--k',type=int, default=64) # 后面考虑减小,因为目前的总点数才4096\n parser.add_argument('--nsample', type=int, default=128) # 后面考虑减小,因为目前的总点数才4096 \n parser.add_argument('--desc_dim', type=int, default=32)\n parser.add_argument('--dilation_ratio', type=float, default=2.0)\n # parser.add_argument('--alpha', type=float, default=1.0, \\\n # help='ratio between chamfer loss and point to point loss')\n # parser.add_argument('--beta', type=float, default=1.0, \\\n # help='ratio between chamfer loss and point to matching loss')\n # parser.add_argument('--temperature', type=float, default=0.1)\n # parser.add_argument('--sigma_max', type=float, default=3.0, \\\n # help='predefined sigma upper bound')\n parser.add_argument('--ckpt_dir', type=str, default='ckpt/', help='path to save model')\n\n # args below are from PointNetVLAD\n parser.add_argument('--positives_per_query', type=int, default=2,\n help='Number of potential positives in each training tuple [default: 2]')\n parser.add_argument('--negatives_per_query', type=int, default=8,\n help='Number of definite negatives in each training tuple [default: 18]')\n parser.add_argument('--hard_neg_per_query', type=int, default=1,\n help='Number of definite negatives in each training tuple [default: 10]')\n parser.add_argument('--eval_batch_size', type=int, default=1,\n help='test Batch Size during training [default: 6]')\n parser.add_argument('--eval_positives_per_query', type=int, default=2,\n help='Number of potential positives in each training tuple [default: 2]')\n parser.add_argument('--eval_negatives_per_query', type=int, default=18,\n help='Number of definite negatives in each training tuple [default: 18]')\n parser.add_argument('--num_points', type=int, default=4096,\n help='num_points [default: 4096]')\n\n # loss function params start\n parser.add_argument('--margin_1', type=float, default=1,\n help='Margin for hinge loss [default: 0.5]')\n parser.add_argument('--margin_2', type=float, default=0.2,\n help='Margin for hinge loss [default: 0.2]')\n parser.add_argument('--loss_ignore_zero_batch',default=False,\n help='If present, mean only batches with loss > 0.0')\n parser.add_argument('--loss_function', default='quadruplet', choices=['triplet', 'quadruplet'], help='triplet or quadruplet [default: quadruplet]')\n parser.add_argument('--loss_lazy',default=True,help='If present, do not use lazy variant of loss')\n parser.add_argument('--triplet_use_best_positives',default=False,help='If present, use best positives, otherwise use hardest positives')\n # loss function params end\n\n parser.add_argument('--resume', action='store_true',\n help='If present, restore checkpoint and resume training')\n parser.add_argument('--dataset_folder', default='/mnt/Airdrop/benchmark_datasets/',\n help='PointNetVlad Dataset Folder')\n parser.add_argument('--emb_dims', type=int, default=1024) # dgcnn param\n parser.add_argument('--dropout', type=float, default=0.5,\n help='dropout rate') # dgcnn param\n parser.add_argument('--log_dir', default='logs/', help='Log dir [default: log]')\n parser.add_argument('--seed', type=int, default=1234, metavar='S',\n help='random seed (default: 1)')\n parser.add_argument('--local_rank', default=-1, type=int,help='node rank for distributed training')\n return parser.parse_args()\n\n\ndef train(args):\n os.environ[\"CUDA_VISIBLE_DEVICES\"] = args.gpu\n cudnn.enabled = True\n # trainset = KittiDataset(args.data_dir, srgs.seq_name, args.npoints)\n # trainloader = torch.utils.data.DataLoader(trainset, batch_size=args.batch_size, \\\n # shuffle=True, num_workers=args.num_workers, drop_last=True) # 此时点云已经加载进来\n train_writer = SummaryWriter(args.log_dir)\n trainset = Oxford_train_base(args)\n trainloader = torch.utils.data.DataLoader(trainset, batch_size=args.batch_size, \\\n shuffle=True, num_workers=args.num_workers, drop_last=True) # 此时点云已经加载进来\n model = KPNet(args)\n model = nn.DataParallel(model) # 支持多gpu训练\n model = model.cuda()\n optimizer = torch.optim.Adam(model.parameters(), lr=args.lr, weight_decay=args.weight_decay)\n # recall 停止上升时,降低学习率\n scheduler = ReduceLROnPlateau(optimizer, 'max', factor=0.2, patience=2, verbose=True, threshold = 0.1,min_lr=0.00001)\n # chamfer = ChamferLoss()\n # point = Point2PointLoss()\n\n best_epoch_loss = float(\"inf\")\n epochs = trange(args.max_epoch, leave=True, desc=\"Epoch\") # 进度条\n for epoch in epochs:\n torch.cuda.empty_cache()\n model.train()\n epoch_loss = 0\n # epoch_chamfer_loss = 0\n # epoch_point_loss = 0\n count = 0\n pbar = tqdm(enumerate(trainloader), total=len(trainloader), desc=\"Batches\")\n for i, data in pbar:\n queries, positives, negatives, other_neg = data # other_neg = 1 now\n # print(\".................................................................queries here: \",queries.shape,positives.shape,negatives.shape,other_neg.shape)\n feed_tensor = torch.cat((queries, positives, negatives, other_neg), 1) # [batch_size, (queries_num + positive_num + negative_num + other_neg_num), 4096, 3]\n feed_tensor = feed_tensor.view((-1, args.num_points, 3)) # [batch_size * (queries_num + positive_num + negative_num + other_neg_num), 4096, 3]\n feed_tensor = feed_tensor.cuda()\n # print('feed_tensor copied onto cuda')\n global_descriptor = model(feed_tensor) # [args.batch_size*(queries_num + positive_num + negative_num + other_neg_num), 256]\n output_queries, output_positives, output_negatives, output_other_neg = torch.split(global_descriptor, [args.batch_size*1, args.batch_size*args.positives_per_query, args.batch_size*args.negatives_per_query, args.batch_size*1], dim=0)\n # 临时增加batch维度\n output_queries = output_queries.view(args.batch_size,1,256)\n output_positives = output_positives.view(args.batch_size,args.positives_per_query,256)\n output_negatives = output_negatives.view(args.batch_size,args.negatives_per_query,256)\n output_other_neg = output_other_neg.view(args.batch_size,1,256)\n loss = loss_function(output_queries, output_positives, output_negatives, output_other_neg, args.margin_1,\\\n args.margin_2, use_min=args.triplet_use_best_positives, lazy=args.loss_lazy,\\\n ignore_zero_loss=args.loss_ignore_zero_batch)\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n train_writer.add_scalar(\"Batch loss\", loss.cpu().item(), int(epoch)*len(trainloader)*int(args.batch_size)+count)\n train_writer.add_scalar(\"learn rate\", optimizer.param_groups[0]['lr'], int(epoch)*len(trainloader)*int(args.batch_size)+count)\n epoch_loss = epoch_loss + float(loss)\n count += 1\n \n\n epoch_loss = epoch_loss / count\n print('Epoch {} finished. Loss: {:.3f}'.format(epoch+1, epoch_loss))\n\n if not os.path.exists(args.ckpt_dir):\n os.makedirs(args.ckpt_dir)\n \n if epoch_loss < best_epoch_loss:\n best_epoch_loss = epoch_loss # update best epoch loss\n torch.save(model.state_dict(), args.ckpt_dir+'best_'+str(epoch)+'.pth') # 后面考虑optimizer的保存\n\n eval_recall = evaluate.evaluate_model(model,args)\n scheduler.step(eval_recall)\n train_writer.add_scalar(\"Value of Recall: \",eval_recall, epoch)\n\n\nif __name__ == '__main__':\n args = parse_args()\n if args.loss_function == 'quadruplet':\n # 有了第二项约束,类内间距离应该比类内距离大\n print(\"use quadruplet_loss\")\n loss_function = loss.quadruplet_loss\n else:\n print(\"use triplet_loss_wrapper\")\n loss_function = loss.triplet_loss_wrapper\n print('>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>start training<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<')\n train(args)\n print('>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>train done<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<')\n","repo_name":"cloudcjf/KP-Net","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":9882,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"81"} +{"seq_id":"30480351826","text":"from rllab.baselines.linear_feature_baseline import LinearFeatureBaseline\nfrom rllab.envs.normalized_env import normalize\nfrom sandbox.rocky.tf.envs.base import TfEnv\nfrom sandbox.rocky.tf.policies.gaussian_mlp_policy import GaussianMLPPolicy\nfrom sandbox.rocky.tf.algos.trpo import TRPO\nfrom rllab.misc.instrument import run_experiment_lite\nfrom sandbox.ours.envs.mujoco import HalfCheetahEnvRandParams, AntEnvRandParams, HopperEnvRandParams\nimport experiments.helpers.evaluation as eval\nfrom rllab.misc.instrument import VariantGenerator, variant\nfrom experiments.helpers.ec2_helpers import cheapest_subnets\nfrom rllab import config\n\nimport sys\nimport argparse\nimport os\nimport random\nimport pickle\n\nEXP_PREFIX = 'trpo-rand-param-env-baselines-eval'\n\nec2_instance = 'm4.large'\n\n\n\ndef run_eval_task(vv):\n\n # load policy and baseline- Warning: resets the tf graph\n # also returns the tensorflow session which must be used in the further code\n policy, baseline, env, sess = eval.load_saved_objects(vv)\n\n # fix the mujoco parameters\n env_class = eval.get_env_class(env)\n\n env = TfEnv(normalize(env_class(log_scale_limit=vv[\"log_scale_limit\"], fix_params=True,\n random_seed=vv['env_param_seed'])))\n # TODO: maybe adjust log_scale limit of environment\n\n algo = TRPO(\n env=env,\n policy=policy,\n baseline=baseline,\n batch_size=vv['batch_size'],\n max_path_length=vv['path_length'],\n n_itr=30,\n discount=vv['discount'],\n step_size=vv[\"step_size\"],\n )\n algo.train(sess=sess)\n\n\ndef run_evaluation(argv):\n\n # -------------------- Parse Arguments -----------------------------------\n parser = argparse.ArgumentParser()\n parser.add_argument('exp_prefix_dir', type=str, help='path to dump dir which contains folders with '\n 'the train results i.e. params.pkl and variant.json file')\n parser.add_argument('--mode', type=str, default='local',\n help='Mode for running the experiments - local: runs on local machine, '\n 'ec2: runs on AWS ec2 cluster (requires a proper configuration file)')\n parser.add_argument('--n_parallel', type=int, default=1,\n help='Number of parallel workers to perform rollouts. 0 => don\\'t start any workers')\n parser.add_argument('--num_sampled_envs', type=int, default=5,\n help='number or environments with samples parameters')\n\n args = parser.parse_args(argv[1:])\n\n # ----------------------- EVALUATION ---------------------------------------\n\n exp_prefix = os.path.basename(args.exp_prefix_dir)\n eval_exp_prefix = exp_prefix + '-eval'\n evaluation_runs = eval.prepare_evaluation_runs(args.exp_prefix_dir, EXP_PREFIX, num_sampled_envs=args.num_sampled_envs)\n\n # ----------------------- AWS conficuration ---------------------------------\n if args.mode == 'ec2':\n subnets = cheapest_subnets(ec2_instance, num_subnets=3)\n info = config.INSTANCE_TYPE_INFO[ec2_instance]\n config.AWS_INSTANCE_TYPE = ec2_instance\n config.AWS_SPOT_PRICE = str(info[\"price\"])\n\n print(\"\\n\" + \"**********\" * 10 + \"\\nexp_prefix: {}\\nvariants: {}\".format('TRPO', len(evaluation_runs)))\n print('Running on type {}, with price {}, on the subnets: '.format(config.AWS_INSTANCE_TYPE,\n config.AWS_SPOT_PRICE, ), str(subnets))\n\n for eval_exp_name, v in evaluation_runs:\n\n if args.mode == 'ec2':\n subnet = random.choice(subnets)\n config.AWS_REGION_NAME = subnet[:-1]\n config.AWS_KEY_NAME = config.ALL_REGION_AWS_KEY_NAMES[\n config.AWS_REGION_NAME]\n config.AWS_IMAGE_ID = config.ALL_REGION_AWS_IMAGE_IDS[\n config.AWS_REGION_NAME]\n config.AWS_SECURITY_GROUP_IDS = \\\n config.ALL_REGION_AWS_SECURITY_GROUP_IDS[\n config.AWS_REGION_NAME]\n\n run_experiment_lite(\n run_eval_task,\n exp_prefix=eval_exp_prefix,\n exp_name=eval_exp_name,\n # Number of parallel workers for sampling\n n_parallel=args.n_parallel,\n # Only keep the snapshot parameters for the last iteration\n snapshot_mode=\"last\",\n # Specifies the seed for the experiment. If this is not provided, a random seed\n # will be used\n seed=v[\"seed\"],\n python_command='python3',\n pre_commands=[\"yes | pip install --upgrade pip\",\n \"yes | pip install tensorflow=='1.6.0'\",\n \"yes | pip install --upgrade cloudpickle\"],\n mode=args.mode,\n use_cloudpickle=True,\n periodic_sync=True,\n variant=v,\n # plot=True,\n # terminate_machine=False,\n )\n\n\n\nif __name__ == \"__main__\":\n run_evaluation(sys.argv)","repo_name":"jonasrothfuss/model_ensemble_meta_learning","sub_path":"sandbox/ignasi/run_scripts/rand_param_exps/trpo_rand_param_eval.py","file_name":"trpo_rand_param_eval.py","file_ext":"py","file_size_in_byte":5038,"program_lang":"python","lang":"en","doc_type":"code","stars":40,"dataset":"github-code","pt":"81"} +{"seq_id":"3813878801","text":"import os\nfor tmpdir in ('/tmp','c:\\temp'):\n if os.path.isdir(tmpdir):\n break\nelse:\n print('no tmp directory available')\n tmpdir=''\n\nif tmpdir:\n os.chdir(tmpdir)\n cwd=os.getcwd()\n print(cwd)\n\n os.mkdir('example')\n","repo_name":"sdzr/python_for_study","sub_path":"chapter09/test2.py","file_name":"test2.py","file_ext":"py","file_size_in_byte":241,"program_lang":"python","lang":"fa","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"3004073128","text":"import sqlite3\r\n\"\"\"\r\n Se crea instancia de la clase Cliente con los datos proporcionados.\r\n\r\n Argumentos:\r\n clave (str): La clave del cliente.\r\n nombre (str): El nombre del cliente.\r\n direccion (str): La dirección del cliente.\r\n correo_electronico (str): El correo electrónico del cliente.\r\n telefono (str): El teléfono del cliente.\r\n \"\"\"\r\nclass Cliente:\r\n\r\n def __init__(self, clave, nombre, direccion, correo_electronico, telefono):\r\n self.clave = clave\r\n self.nombre = nombre\r\n self.direccion = direccion\r\n self.correo_electronico = correo_electronico\r\n self.telefono = telefono\r\n#Se crea la clase Manejo Clientes para las operaciones relacionadas con los clientes\r\nclass ManejoClientes:\r\n def __init__(self):\r\n self.clientes = []\r\n self.db = Database('mi_base_de_datos.db')\r\n self.db.crear_tabla_clientes()\r\n\r\n def agregar_cliente(self):\r\n clave = str(input(\"Ingrese la clave del cliente: \"))\r\n nombre = str(input(\"Ingrese el nombre del cliente: \"))\r\n direccion = str(input(\"Ingrese la dirección del cliente: \"))\r\n correo_electronico = str(input(\"Ingrese el correo electrónico del cliente: \"))\r\n telefono = str(input(\"Ingrese el teléfono del cliente: \"))\r\n\r\n cliente = Cliente(clave, nombre, direccion, correo_electronico, telefono)\r\n self.db.agregar_cliente(clave, nombre, direccion, correo_electronico, telefono)\r\n print(\"Cliente agregado correctamente.\")\r\n \r\n def eliminar_cliente(self):\r\n clave = input(\"Ingrese la clave del cliente que desea eliminar: \")\r\n self.db.eliminar_cliente(clave)\r\n print(\"Cliente eliminado correctamente.\")\r\n\r\n\r\n\r\n def actualizar_cliente(self):\r\n clave = input(\"Ingrese la clave del cliente que desea actualizar: \")\r\n\r\n nuevo_nombre = input(\"Ingrese el nuevo nombre del cliente (dejar en blanco si no desea actualizar): \")\r\n nueva_direccion = input(\"Ingrese la nueva dirección del cliente (dejar en blanco si no desea actualizar): \")\r\n nuevo_correo = input(\"Ingrese el nuevo correo electrónico del cliente (dejar en blanco si no desea actualizar): \")\r\n nuevo_telefono = input(\"Ingrese el nuevo teléfono del cliente (dejar en blanco si no desea actualizar): \")\r\n\r\n cliente_actualizado = {}\r\n if nuevo_nombre:\r\n cliente_actualizado[\"nombre\"] = nuevo_nombre\r\n if nueva_direccion:\r\n cliente_actualizado[\"direccion\"] = nueva_direccion\r\n if nuevo_correo:\r\n cliente_actualizado[\"correo_electronico\"] = nuevo_correo\r\n if nuevo_telefono:\r\n cliente_actualizado[\"telefono\"] = nuevo_telefono\r\n\r\n if cliente_actualizado:\r\n self.db.actualizar_cliente(clave, cliente_actualizado)\r\n print(\"Cliente actualizado correctamente.\")\r\n else:\r\n print(\"No se realizaron cambios en el cliente.\")\r\n#Se crea la base de datos para la manipulacion de los datos de los clientes\r\nclass Database:\r\n def __init__(self, nombre_archivo):\r\n self.conexion = sqlite3.connect(nombre_archivo)\r\n self.cursor = self.conexion.cursor()\r\n\r\n def crear_tabla_clientes(self):\r\n self.cursor.execute(\"CREATE TABLE IF NOT EXISTS clientes (clave TEXT, nombre TEXT, direccion TEXT, correo_electronico TEXT, telefono TEXT)\")\r\n self.conexion.commit()\r\n\r\n def agregar_cliente(self, clave, nombre, direccion, correo_electronico, telefono):\r\n consulta = \"INSERT INTO clientes VALUES (?, ?, ?, ?, ?)\"\r\n datos = (clave, nombre, direccion, correo_electronico, telefono)\r\n self.cursor.execute(consulta, datos)\r\n self.conexion.commit()\r\n\r\n def eliminar_cliente(self, clave):\r\n consulta = \"DELETE FROM clientes WHERE clave = ?\"\r\n datos = (clave,)\r\n self.cursor.execute(consulta, datos)\r\n self.conexion.commit()\r\n\r\n def actualizar_cliente(self, clave, nombre=None, direccion=None, correo_electronico=None, telefono=None):\r\n # Construir la consulta SQL dinámicamente\r\n sql = \"UPDATE clientes SET\"\r\n parametros = []\r\n\r\n if nombre:\r\n sql += \" nombre = ?,\"\r\n parametros.append(nombre)\r\n if direccion:\r\n sql += \" direccion = ?,\"\r\n parametros.append(direccion)\r\n if correo_electronico:\r\n sql += \" correo_electronico = ?,\"\r\n parametros.append(correo_electronico)\r\n if telefono:\r\n sql += \" telefono = ?,\"\r\n parametros.append(telefono)\r\n\r\n \r\n sql = sql.rstrip(',')\r\n\r\n \r\n sql += \" WHERE clave = ?\"\r\n parametros.append(clave)\r\n\r\n \r\n self.cursor.execute(sql, parametros)\r\n self.conexion.commit()\r\n\r\n def cerrar_conexion(self):\r\n self.conexion.close()","repo_name":"ccastrov/Happy-Burguer","sub_path":"clientes.py","file_name":"clientes.py","file_ext":"py","file_size_in_byte":4904,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"10503793046","text":"#!/usr/bin/env python\n# coding=UTF-8\n'''\n@Description:\n@Author: HuangQinJian\n@LastEditors: HuangQinJian\n@Date: 2019-04-23 13:43:24\n@LastEditTime: 2019-04-30 21:29:26\n'''\n##### clw note:注意,带label的图片保存在当前路径下的一个名为anno_image_coco的文件夹内,这里取了大概7张图片;\n\n\nfrom pycocotools.coco import COCO\nimport skimage.io as io\nimport matplotlib.pyplot as plt\n#import pylab\nimport cv2\nimport os\nfrom skimage.io import imsave\nimport numpy as np\nfrom PIL import Image, ImageDraw, ImageFont\n#pylab.rcParams['figure.figsize'] = (8.0, 10.0)\n\nimg_and_anno_root = '/mfs/home/fangyong/data/guangdong/train_val/'\n#img_and_anno_root ='K:/deep_learning/dataset/2019tianchi/train/'\nimg_path = img_and_anno_root + 'defect_Images/'\nannFile = img_and_anno_root + 'Annotations/train.json'\nimg_save_path = img_and_anno_root + 'visualized_image'\nVISUALIZE_SINGLE = False\nNEED_SAVE = False\n\nif NEED_SAVE:\n if not os.path.exists(img_save_path):\n os.makedirs(img_save_path)\n\ndef draw_rectangle(boxes, labels, image):\n\n for box, label in zip(boxes, labels):\n cv2.rectangle(image, (int(box[0]), int(box[1])), (int(box[0]) + int(box[2]), int(box[1]) +int(box[3])), (0, 255, 0), 2) # xywh,需要转成左上角坐标, 右下角坐标\n\n # clw note:主要用于输出中文的label\n cv2img = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n pilimg = Image.fromarray(cv2img)\n draw = ImageDraw.Draw(pilimg) # 图片上打印\n #font = ImageFont.truetype('/media/clwclw/data/fonts/simsun.ttf', 20, encoding=\"utf-8\")\n font = ImageFont.truetype('./simsun.ttf', 36, encoding=\"utf-8\")\n #font = ImageFont.truetype('C:/Windows/Fonts/msyh.ttc', 36, encoding=\"utf-8\")\n\n left = float(box[0])\n top = float(box[1])\n right = float(box[0]) + float(box[2])\n down = float(box[1]) + float(box[3])\n\n draw.text(((left + right) / 2.0, (top + down) / 2.0), label, (255, 0, 0), font=font) # clw note:在中心位置输出标签\n\n image = cv2.cvtColor(np.array(pilimg), cv2.COLOR_RGB2BGR)\n\n return image\n\n\n# 初始化标注数据的 COCO api\ncoco = COCO(annFile)\n\n# display COCO categories and supercategories\ncats = coco.loadCats(coco.getCatIds())\nnms = [cat['name'] for cat in cats]\n# print('COCO categories: \\n{}\\n'.format(' '.join(nms)))\n\nnms = set([cat['supercategory'] for cat in cats])\n# print('COCO supercategories: \\n{}'.format(' '.join(nms)))\n\nimg_list = os.listdir(img_path)\n\n# 查看某张图片\nif VISUALIZE_SINGLE:\n for i in range(len(img_list)):\n # for i in range(5): # clw note:随机查看几张\n imgIds = i+1\n img = coco.loadImgs(imgIds)[0]\n image_name = img['file_name']\n if image_name != '7e7e6359d8fb8e9c1332319214.jpg':\n continue\n else:\n # catIds=[] 说明展示所有类别的box,也可以指定类别\n annIds = coco.getAnnIds(imgIds=img['id'], catIds=[], iscrowd=None)\n anns = coco.loadAnns(annIds)\n # print(anns)\n coordinates = []\n labels = []\n img_raw = cv2.imread(os.path.join(img_path, image_name))\n for j in range(len(anns)):\n # 1、求坐标\n coordinate = []\n coordinate.append(anns[j]['bbox'][0])\n coordinate.append(anns[j]['bbox'][1])\n coordinate.append(anns[j]['bbox'][2])\n coordinate.append(anns[j]['bbox'][3])\n coordinates.append(coordinate)\n\n # 2、找到对应的标签\n\n labels.append(cats[anns[j]['category_id']]['name'])\n\n image = draw_rectangle(coordinates, labels, img_raw)\n cv2.namedWindow(image_name, 0);\n cv2.resizeWindow(image_name, 1280, 1024);\n cv2.imshow(image_name, image)\n cv2.waitKey(0)\n cv2.destroyAllWindows()\n\n if NEED_SAVE:\n imsave(img_save_path, image)\n\nelse:\n # 查看所有图片\n #for i in range(len(img_list)):\n for i in range(3000, len(img_list)): # look up from xxxx\n # for i in range(5): # clw note:随机查看几张\n imgIds = i+1\n img = coco.loadImgs(imgIds)[0]\n image_name = img['file_name']\n # print(img)\n\n # 加载并显示图片\n # I = io.imread('%s/%s' % (img_path, img['file_name']))\n # plt.axis('off')\n # plt.imshow(I)\n # plt.show()\n\n # catIds=[] 说明展示所有类别的box,也可以指定类别\n annIds = coco.getAnnIds(imgIds=img['id'], catIds=[], iscrowd=None)\n anns = coco.loadAnns(annIds)\n # print(anns)\n coordinates = []\n labels = []\n img_raw = cv2.imread(os.path.join(img_path, image_name))\n for j in range(len(anns)):\n # 1、求坐标\n coordinate = []\n # coordinate.append(anns[j]['bbox'][0])\n # coordinate.append(anns[j]['bbox'][1]+anns[j]['bbox'][3])\n # coordinate.append(anns[j]['bbox'][0]+anns[j]['bbox'][2])\n # coordinate.append(anns[j]['bbox'][1])\n coordinate.append(anns[j]['bbox'][0])\n coordinate.append(anns[j]['bbox'][1])\n coordinate.append(anns[j]['bbox'][2])\n coordinate.append(anns[j]['bbox'][3])\n # print(coordinate)\n coordinates.append(coordinate)\n\n # 2、找到对应的标签\n labels.append(cats[anns[j]['category_id'] - 1 ]['name']) # clw note: the reason to -1 is that the first is 1 but the index should be 0\n\n image = draw_rectangle(coordinates, labels, img_raw)\n cv2.namedWindow(image_name, 0);\n cv2.resizeWindow(image_name, 1600, 1200);\n cv2.moveWindow(image_name, 0, 0);\n cv2.imshow(image_name, image)\n cv2.waitKey(0)\n cv2.destroyAllWindows()\n\n if NEED_SAVE:\n imsave(img_save_path, image)","repo_name":"witzou/Python_Practice","sub_path":"常用数据预处理脚本/数据标注可视化/coco数据可视化/2019天池_原始数据可视化.py","file_name":"2019天池_原始数据可视化.py","file_ext":"py","file_size_in_byte":5931,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"81"} +{"seq_id":"30966687608","text":"\n## Problem 1\ndef list1_start_with_list2(list1, list2):\n '''\n Checks if the elements of list2 are the first elements of list1 in the same order.\n '''\n if not len(list1) > len(list2):\n return False\n for i in range(len(list2)):\n if list1[i] != list2[i]:\n return False\n return True\n\n## Problem 2\ndef match_pattern(list1, list2):\n '''\n Checks if the elements of list2 appear anywhere in list1, in the same order\n ''' \n if not len(list1) > len(list2):\n return False\n for i in range(len(list1) - len(list2)):\n if list1[i : i + len(list2)] == list2:\n return True\n return False\n\n## Problem 3\ndef repeats(list0):\n '''\n Checks if any adjacent values in list0 are equal\n '''\n for i in range(len(list0) - 1):\n if list0[i] == list0[i+1]:\n return True\n return False\n\n## Problem 4 :: Matrices\n\n# Matrix in format:\n# M = [\n# [1, 2, 3],\n# [4, 5, 6],\n# [7, 8, 9]\n# ]\ndef print_matrix_dim(M):\n '''\n returns (number of rows)x(number of columns)\n '''\n row_length = len(M[1])\n for row in M:\n if len(row) != row_length:\n raise TypeError\n return str(len(M)) + \"x\" + str(len(M[1]))\n\ndef dot_product(v, u):\n '''\n Returns the dot product of vector v with vector u\n '''\n try:\n product = 0\n for i in range(len(v)):\n product += v[i]*u[i]\n except: # IndexError\n return False\n else:\n return product\n\ndef matrix_multiply(A, B):\n # Verify that \n for row in A:\n if len(row) != len(A[0]):\n raise TypeError\n for row in B:\n if len(row) != len(B[0]):\n raise TypeError\n\n # Transpose B for more convenient value access\n temp_matrix_B = B\n B = [[0] * len(B)] * len(B[0])\n for i in range(len(B)):\n for j in range(len(B[0])):\n B[i][j] = temp_matrix_B[j][i]\n\n if len(A[0]) != len(B[0]):\n raise ValueError # Could also be an index error\n\n # Given matrix (m x n)\n # and matrix (n x p)\n # Resulting matrix is (m x p)\n\n C = [[None] for i in range(len(B)) for j in range(len(A))]\n\n # C = [[[0][:] * len(B])]*len(A)\n #C = []\n #for i in range(len(A)): \n\n # C.append([0] * len(B))\n for i in C:\n for j in i:\n j = None\n\n for row_of_A in range(len(A)):\n for column_of_B in range(len(B)):\n # Entry i,j of resultant matrix C\n C[row_of_A][column_of_B] = dot_product(A[row_of_A], B[column_of_B])\n \n # (optional) If it is a single column matrix, converts it to a simple list\n for i in range(len(C)):\n if len(C[i]) == 1:\n C[i] = C[i][0]\n return C\n\n### Matrix Multiplication ###\nimport numpy as np\n\n\ndef mult_M1_M2(M1, M2):\n ''' Return the matrix multiplication of an (m x n) & an (n x p) matrix '''\n cur_ind = 0\n if len(M1[0]) != len(M2):\n raise IndexError(\"M1 column size != M2 row size [not (m x n) & (n x p) matrices]\")\n\n res_matrix = [[] for j in range(len(M1))]\n for m in range(len(M1)):\n for p in range(len(M2[0])):\n cur_ind = 0\n for n in range(len(M2)):\n cur_ind += M1[m][n]*M2[n][p]\n res_matrix[m].insert(p, cur_ind)\n return res_matrix\n\n\nif __name__ == \"__main__\":\n print(\"1. List 1 starts with list 2: \", list1_start_with_list2([1,2,3,4,5,6],[1,2,3,4,5,6,7]))\n print(\"2. List 2 in list 1: \", match_pattern([1,2,3,4,5,6,7,8,9,10,11],[5,6,7]))\n print(\"3. List0 repeats: \", repeats([0,1,2,3,4,5,6,7]))\n print(\"4. a) Matrix dimensions: \", print_matrix_dim([[1,2,3],[4,5,6],[7,8,9]]))\n \n print(\"4. b) matrix u by vector v\")\n v = [[1], \n [2], \n [3]]\n u = [[1,2,5],\n [6,4,1],\n [1,4,2]]\n for i in u:\n print(i)\n print()\n print(v)\n print(matrix_multiply(u, v))\n print(\"4. c)\")\n\n z = [[8 , 9 , 1],\n [4 , 7 , 2],\n [8 , 1 , 3]]\n\n print(matrix_multiply(u, z))\n matrix1 = [[2 ,1 ,0 ,7 ,4 ,1 ,5 ,0 ,6 ,9],\n [4 ,8 ,6 ,7 ,0 ,5 ,7 ,8 ,3 ,7],\n [2 ,7 ,9 ,6 ,5 ,0 ,1 ,6 ,8 ,2],\n [2 ,2 ,1 ,0 ,3 ,5 ,0 ,0 ,6 ,0],\n [2 ,4 ,2 ,8 ,7 ,1 ,2 ,8 ,5 ,8],\n [4 ,2 ,3 ,8 ,5 ,1 ,7 ,0 ,8 ,3]]\n\n matrix2 = [[6 ,6 ,2 ,3],\n [3 ,9 ,1 ,8],\n [0 ,8 ,9 ,4],\n [4 ,2 ,1 ,4],\n [1 ,5 ,5 ,9],\n [7 ,9 ,8 ,9],\n [3 ,5 ,7 ,8],\n [4 ,3 ,5 ,4],\n [2 ,8 ,2 ,7],\n [9 ,1 ,8 ,8]]\n # np.matrix(matrix1)\n # np.matrix(matrix2)\n\n print(\"M1:\\n\", np.matrix(matrix1), \"\\n\", sep = \"\")\n print(\"M2:\\n\", np.matrix(matrix2), \"\\n\", sep = \"\")\n\n results = mult_M1_M2(matrix1, matrix2)\n results = np.matrix(mult_M1_M2(matrix1, matrix2))\n print(\"Results:\\n\", results, sep =\"\")\n results = np.matrix(mult_M1_M2(u,v))\n print(\"Results:\\n\", results, sep =\"\") \n results = np.matrix(mult_M1_M2(matrix1,matrix2))\n print(\"Results:\\n\", results, sep =\"\") \n\n\n","repo_name":"Eric9867/ESC180-labs","sub_path":"5/lab05.py","file_name":"lab05.py","file_ext":"py","file_size_in_byte":5061,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"41886549004","text":"import numpy as np\n\n\ndef eig_decomp(cov):\n cov = np.swapaxes(cov, 0, 2)\n cov = np.swapaxes(cov, 1, 3)\n shape = cov.shape\n cov = cov.reshape(\n (shape[0] * shape[1], shape[2], shape[3]))\n\n total_pixels = cov.shape[0]\n n = 50\n cov_split = np.array_split(cov, n)\n\n cov = None\n\n print('Eigenvector Decomposition Progress: 0', end=\"\\r\", flush=True)\n for minicov in cov_split:\n W, V = np.linalg.eigh(minicov)\n W = None\n V = np.transpose(V, axes=(0, 2, 1))\n # select the last eigenvector (the one corresponding to the largest lambda)\n v = V[:, shape[-1] - 1]\n V = None\n scaling = np.abs(v[:, 0])\n scaling[scaling == 0] = 1\n rotation = v[:, 0] / scaling\n scaling = None\n v = v * rotation.conj()[:, np.newaxis]\n if cov is None:\n cov = v\n else:\n cov = np.concatenate((cov, v))\n print(\n f'Eigenvector Decomposition Progress: {int((cov.shape[0] / total_pixels) * 100)}%', end=\"\\r\", flush=True)\n\n return cov.reshape((shape[0], shape[1], shape[2]))\n","repo_name":"rbiessel/CovSAR","sub_path":"applications/pl/evd.py","file_name":"evd.py","file_ext":"py","file_size_in_byte":1105,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"81"} +{"seq_id":"71305534985","text":"import requests\nfrom bs4 import BeautifulSoup\n\nptt_url = \"https://www.ptt.cc/bbs/\"\nboard = \"Stock\"\n\n\ndef get_paragraph_title_href(url):\n\n title_list = []\n for title in get_soup(url).find_all(\"div\", {\"class\": \"title\"}):\n if title.a is None:\n continue\n p_d = dict()\n p_d[\"title\"] = title.a.text\n p_d[\"href\"] = title.a[\"href\"]\n title_list.append(p_d)\n return title_list\n\n\ndef get_soup(url):\n if url.startswith(\"/bbs/\"):\n request_url = ptt_url + url.lstrip(\"/bbs/\")\n else:\n request_url = ptt_url + url\n response = requests.get(request_url, cookies={\"over18\": \"1\"})\n # print(r.status_code)\n # print(response.text)\n return BeautifulSoup(response.text, \"html.parser\")\n\n\ndef get_upper_page(url):\n soup = get_soup(url)\n return soup.find_all(\"a\", {\"class\": \"btn wide\"})[1][\"href\"]\n\n\nif __name__ == \"__main__\":\n print(get_paragraph_title_href(get_upper_page(\"Stock\")))\n","repo_name":"lzrong0203/20221011crawling2","sub_path":"ptt_crawler.py","file_name":"ptt_crawler.py","file_ext":"py","file_size_in_byte":954,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"2700452918","text":"def exec_one_instruction(p):\n\t# executes p for just one instruction forward \n\t# remembers where it stopped using a hashmap so it can continue from there next time\n\t...\n\noutputs = {} # partial outputs of all programs we ran so far\n\ndef kolmogorov(s, n):\n # the string s has a null character at the end of it, which denotes the end of the string, and the program p outputs the null character when it stops\n\talphabet = [chr(i) for i in xrange(127)] # all ASCII characters\n\tstrings = ['']\n\twhile n:\n\t\tstrings += [x + c for x in strings for c in alphabet]\n\t\tfor p in strings:\n\t\t\ttry:\n\t\t\t\twith stdoutIO() as output:\n\t\t\t\t\texec_one_instruction(p)\n\t\t\texcept:\n\t\t\t\tpass\n\t\t\telse:\n\t\t\t\tif p in outputs:\n\t\t\t\t\toutputs[p] += output.getvalue()\n\t\t\t\telse:\n\t\t\t\t\toutputs[p] = output.getvalue()\n\t\t\t\tif outputs[p] == s:\n\t\t\t\t\treturn len(p)\n\t\tn -= 1\n","repo_name":"rjelavic/source","sub_path":"code/kolmogorov_approximation.py","file_name":"kolmogorov_approximation.py","file_ext":"py","file_size_in_byte":827,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"7349983249","text":"import requests\nimport threading\nfrom playsound import playsound\n\n\nclass TelegramBadConfigException(Exception):\n pass\n\n\nclass TelegramNotifyer():\n\n def __init__(self, token, chat_id):\n self.token = token\n self.chat_id = chat_id\n\n if self.token is None \\\n or self.chat_id is None \\\n or self.token == '' \\\n or self.chat_id == '':\n raise TelegramBadConfigException\n\n def send_text(self, message):\n telegram_url_1 = 'https://api.telegram.org/bot'\n telegram_url_2 = '/sendMessage?chat_id='\n telegram_url_3 = '&parse_mode=Markdown&text='\n\n send_text = ''.join((telegram_url_1,\n self.token,\n telegram_url_2,\n self.chat_id,\n telegram_url_3,\n message))\n response = requests.get(send_text)\n return response.json()\n\n\nclass SoundNotifyer():\n\n def __init__(self, sound_file_path):\n self.sound = sound_file_path\n\n def play_sound(self):\n threading.Thread(\n target=(lambda:\n playsound(self.sound, block=False))\n ).start()\n","repo_name":"naxim92/Pennyworth","sub_path":"src/notifyers.py","file_name":"notifyers.py","file_ext":"py","file_size_in_byte":1231,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"21573452476","text":"# Lawrence McAfee\n\n# ~~~~~~~~ import ~~~~~~~~\nfrom modules.node.HierNode import HierNode\nfrom modules.node.LeafNode import LeafNode\nfrom modules.node.Stage import Stage\nfrom modules.node.block.CodeBlock import CodeBlock as cbk\nfrom modules.node.block.ImageBlock import ImageBlock as ibk\nfrom modules.node.block.MarkdownBlock import MarkdownBlock as mbk\n\n\n# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\nblocks = [\n mbk(\"Tree-based or ensemble methods in Scikit-learn have a feature_importances_ attribute which can be used to drop irrelevant features in the dataset using the SelectFromModel module contained in the sklearn.feature_selection package.\"),\n mbk(\"Let’s used the ensemble method AdaBoostClassifier in this example.\"),\n cbk(None, \"\"\"\n# import packages\nfrom sklearn.ensemble import AdaBoostClassifier\nfrom sklearn.feature_selection import SelectFromModel\nfrom sklearn import datasets\n\n# load dataset\ndata = datasets.load_iris()\n\n# separate features and target\nX = data.data\ny = data.target\n\n# original data shape\nX.shape\n\n# feature engineering\nada_boost_classifier = AdaBoostClassifier()\nada_boost_classifier.fit(X, y)\n \"\"\", \"\"\"\nAdaBoostClassifier(algorithm='SAMME.R', base_estimator=None,\n          learning_rate=1.0, n_estimators=50, random_state=None)\n \"\"\"),\n cbk(None, \"\"\"\n# print the feature importances\nada_boost_classifier.feature_importances_\n \"\"\", \"\"\"\narray([0.  , 0.  , 0.58, 0.42])\n \"\"\"),\n cbk(None, \"\"\"\n# create a subset of data based on the relevant features\nmodel = SelectFromModel(ada_boost_classifier, prefit=True)\nnew_data = model.transform(X)\n\n# the irrelevant features have been removed\nnew_data.shape\n \"\"\", \"\"\"\n(150, 2)\n \"\"\"),\n]\n\n# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\nclass Content(LeafNode):\n def __init__(self):\n super().__init__(\n \"Feature Importances\",\n Stage.REMOVE_EXTRANEOUS,\n Stage.ORIG_BLOCKS,\n # Stage.CUSTOM_BLOCKS,\n # Stage.ORIG_FIGURES,\n # Stage.CUSTOM_FIGURES,\n # Stage.CUSTOM_EXERCISES,\n )\n self.add(mbk(\"# Feature Importances\"))\n [self.add(a) for a in blocks]\n\n# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\nclass FeatureImportances(HierNode):\n def __init__(self):\n super().__init__(\"Feature Importances\")\n self.add(Content())\n\n# eof\n","repo_name":"nimra/module_gen","sub_path":"nodes/Bisong19Building/E_PartIV/G_Chapter24/A_FeatureEngineering/C_FeatureImportances/index.py","file_name":"index.py","file_ext":"py","file_size_in_byte":2449,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"18639751930","text":"import os\nimport cv2\nimport sys\nimport time\nimport pickle\nimport numpy as np\nimport lzw_coding\n\nclass lzw_decompress:\n def __init__(self, encoded_path, image_output_path):\n \n self.input_path = encoded_path\n self.output_path = image_output_path\n \n # string tem file to read bit in\n self.string_path = \"temp\"\n\n # Image output and shape (w, h)\n self.image = None\n self.w = None\n self.h = None\n \n # 1D array\n self.array = None\n # Number of bits using for each key in LZW dictionary\n self.numbits = None\n\n # length of encoded array string\n self.length_encoded = None\n\n # Time processing\n self.time = time.time()\n\n self.read()\n\n # Read from compressed file \n def read(self):\n \n # Read byte compressed to encoded_text\n encoded_text = \"\"\n with open(self.input_path, 'rb') as f:\n byte_array = pickle.load(f)\n for byte in byte_array:\n encoded_text += '{:08b}'.format(byte)\n \n # Delete some \"0\" bit at first\n num_zero = int(encoded_text[-8:], 2)\n encoded_text = encoded_text[num_zero : -8]\n # Read image's shape\n w_length = int(encoded_text[:5], 2)\n self.w = int(encoded_text[5: 5 + w_length], 2)\n h_length = int(encoded_text[5 + w_length: 10 + w_length], 2)\n self.h = int(encoded_text[10 + w_length: 10 + w_length + h_length], 2)\n encoded_text = encoded_text[10 + w_length + h_length: ]\n \n # length encoded_text\n self.length_encoded = len(encoded_text)\n\n # Save the rest into temp\n with open(self.string_path, \"w\") as f:\n f.write(encoded_text)\n\n # Covert 1D array into image\n def toimage(self):\n w, h = self.w, self.h\n \n # Subtract 1D array into 3 sub arrays\n Y_array = self.array[: w*h]\n Cr_array = self.array[w*h : 2*w*h]\n Cb_array = self.array[2*w*h : 3*w*h]\n \n # convert array into 3 channels image\n Y = np.array(Y_array).reshape((w,h))\n Cr = np.array(Cr_array).reshape((w,h))\n Cb = np.array(Cb_array).reshape((w,h))\n \n # Create a copy zero image\n image = np.zeros((w,h,3), dtype = np.uint8)\n image[:, :, 0], image[:, :, 1], image[:, :, 2] = Y, Cr, Cb\n \n # Convert to RGB\n self.image = cv2.cvtColor(image, cv2.COLOR_YCrCb2BGR)\n\n\n def decompress(self):\n \n self.numbits = int(np.log2(self.w * self.h * 3 + 256))\n # set up bit stream input\n bitin = lzw_coding.bitInStream(self.string_path)\n\n decoder = lzw_coding.decoder(self.numbits, bitin)\n \n percent = 0\n i = 0\n while decoder.decode():\n if i * self.numbits *100.0 / self.length_encoded > percent:\n percent += 1\n sys.stdout.write(\"Processing:\\t{} % \\r\".format(percent))\n sys.stdout.flush()\n i += 1\n print('')\n decoder.finish()\n\n self.array = decoder.get_array()\n \n self.toimage()\n\n \n def write(self):\n cv2.imwrite(self.output_path, self.image)\n self.time = time.time() - self.time\n print(\"Input: \\'%s\\' \\tOutput: \\'%s\\' \\tTime: %.2f(s)\"%(self.input_path, self.output_path, self.time))\n\n\ndef main(argv):\n input_path, image_path = argv\n \n decompressor = lzw_decompress(input_path, image_path)\n decompressor.decompress()\n decompressor.write()\n\nif __name__ == \"__main__\":\n main(sys.argv[1:])\n","repo_name":"Ardian-thedarkk/image-compression","sub_path":"lzw-coding/lzw_decompress.py","file_name":"lzw_decompress.py","file_ext":"py","file_size_in_byte":3606,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"2561586958","text":"import numpy as np\nfrom multinomial_hmm_mult_obs import MultinomialHMM\nimport numpy.testing as npt\n\n\ndef main():\n test_fit()\n\n\ndef test_fit():\n obs_spaces = [[0, 1, 2], [0, 1, 2, 3]]\n states = [0, 1]\n model = MultinomialHMM(states, obs_spaces, n_obs_seq=2)\n obs_seq = [[[0, 0], [1, 0], [2, 0, 1]], [[0, 1], [3, 2], [3, 2, 1]]]\n hidden_state_seq = [[0, 1], [0, 0], [1, 1, 0]]\n model.fit(hidden_state_seq, obs_seq)\n npt.assert_almost_equal(model.beta[0], [[0.5, 0.5, 0], [0.67, 0, 0.33]], decimal=2)\n npt.assert_almost_equal(\n model.beta[1], [[0.25, 0.25, 0.25, 0.25], [0, 0.33, 0.33, 0.33]], decimal=2\n )\n y = [[0, 1, 2, 0], [0, 3, 2, 1]]\n # print(model.beta)\n model.approximate_joint_dist(y)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"hb13879-p/generative-music-modelling","sub_path":"Probabilistic/hmm_lib/test_variational_inference.py","file_name":"test_variational_inference.py","file_ext":"py","file_size_in_byte":778,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"70532734986","text":"\"\"\"Age categories for lifters.\n\nFrom: https://iwf.sport/weightlifting_/participants/\n - YOUTH: 13 – 17 years of age\n - JUNIOR: 15 – 20 years of age\n - SENIOR: ≥15 years of age\n - MASTERS: ≥35 years of age\n\nMasters age categories:\n - 35-39\n - 40-44\n - 45-49\n - 50-54\n - 55-59\n - 60-64\n - 65-69\n - 70+\n\"\"\"\n\nfrom auditlog.models import AuditlogHistoryField\nfrom auditlog.registry import auditlog\nfrom django.core.exceptions import ValidationError\nfrom django.db import models\nfrom django.utils.translation import gettext_lazy as _\nfrom hashid_field import HashidAutoField\n\nfrom api.models.support.base_era import BaseEra\nfrom config.settings import HASHID_FIELD_SALT\n\n\nclass AgeCategoryEra(BaseEra):\n \"\"\"Era for Age categories.\"\"\"\n\n reference_id = HashidAutoField(\n primary_key=True,\n salt=f\"aceramodel_reference_id_{HASHID_FIELD_SALT}\",\n )\n history = AuditlogHistoryField(pk_indexable=False)\n\n\nclass AgeCategory(models.Model):\n \"\"\"Age Category.\"\"\"\n\n reference_id = HashidAutoField(\n primary_key=True,\n salt=f\"agecategorymodel_reference_id_{HASHID_FIELD_SALT}\",\n )\n era = models.ForeignKey(\n AgeCategoryEra,\n blank=True,\n null=True,\n on_delete=models.SET_NULL,\n )\n name = models.CharField(max_length=32, blank=True)\n upper_age_bound = models.IntegerField(null=True, blank=True)\n lower_age_bound = models.IntegerField(blank=True, default=0)\n\n history = AuditlogHistoryField(pk_indexable=False)\n\n class Meta:\n \"\"\"Model settings.\"\"\"\n\n verbose_name_plural = \"Age categories\"\n ordering = [\"lower_age_bound\", \"upper_age_bound\"]\n\n def clean(self, *args, **kwargs):\n \"\"\"Validate for age bounds.\n\n 1. Age bounds must be positive.\n 2. `upper_age_bound` must be larger than the `lower_age_bound`.\n 3. Check Era is set to right choice field.\n \"\"\"\n errors = []\n if self.upper_age_bound is not None and self.upper_age_bound < 0:\n errors.append(\n ValidationError(\n _(\"upper_age_bound must be positive.\"), code=\"positive\"\n )\n )\n\n if self.lower_age_bound < 0:\n errors.append(\n ValidationError(\n _(\"lower_age_bound must be positive.\"), code=\"positive\"\n )\n )\n\n if (\n self.upper_age_bound is not None\n and self.upper_age_bound < self.lower_age_bound\n ):\n errors.append(\n ValidationError(\n _(\"upper_age_bound must be larger than lower_age_bound\"),\n code=\"bounds\",\n )\n )\n\n if len(errors) > 0:\n raise ValidationError(errors)\n\n super().clean(*args, **kwargs)\n\n def save(self, *args, **kwargs):\n \"\"\"Necessary to enact custom validation in `clean()` method.\"\"\"\n self.full_clean()\n super().save(*args, **kwargs)\n\n def __str__(self) -> str:\n \"\"\"Represent string.\"\"\"\n if self.upper_age_bound is None:\n return f\"{self.name}: {self.lower_age_bound} <= age\"\n return f\"{self.name}: {self.lower_age_bound} <= age <= {self.upper_age_bound}\"\n\n\nauditlog.register(AgeCategoryEra)\nauditlog.register(AgeCategory)\n","repo_name":"WeightliftingNZ/lifter-api","sub_path":"backend/api/models/support/age_categories.py","file_name":"age_categories.py","file_ext":"py","file_size_in_byte":3344,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"81"} +{"seq_id":"22626574030","text":"from django.db import models\nfrom django.contrib.auth.models import User\n\n\n# Create your models here.\nclass Jobs(models.Model):#mapping to table in db\n job_title=models.CharField(max_length=150)\n company=models.CharField(max_length=150)\n location=models.CharField(max_length=150)\n salary=models.PositiveIntegerField(null=True)#if the field is not added it will be added to db\n experience=models.PositiveIntegerField(default=0)#if the person has no experence then it will default as zero but if we added the experience it will change..\n\n#python manage.py makemigrations\n#python manage.py migrate\n#to print the objects name and details in shell we are overriding the string method(tostring):\n\n def __str__(self):\n return self.job_title\nclass CompanyProfile(models.Model):\n company_name=models.CharField(max_length=150)\n user=models.OneToOneField(User,on_delete=models.CASCADE,related_name=\"employer\")\n logo=models.ImageField(upload_to=\"companyprofile\",null=True)\n location=models.CharField(max_length=120)\n services=models.CharField(max_length=120)\n description=models.CharField(max_length=200)\n\n\n#create the objects in model\n# orm query\n#Modelname.objects.create(field=value,field=value....)\n#eg..\"Jobs.objects.create(job_title=\"front end developer\",company=\"tcs\",location=\"kakkanad\",salary=\"40000\",experience=\"2\")\n\n\n#create an app in mathoperations employees\n\n #Employees(cname,salary,dept,exp)\n #emp create\n #fetch all employees\n #filter\n# to fetch a specific object\n#qs=Jobs.objects.get(id=5)\n# print(qs)\n#update\n #1.qs.Jobs.objects.get(id=3)\n #qs\n #qs.experience=2\n #qs.save()\n#create\n#list\n#Details\n#update\n#delete","repo_name":"thsneha/jobportal","sub_path":"employer/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1689,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"70614624264","text":"import os\nimport sys\nsys.path.append(\"/fsx/knoriy/CLASP/clasp/\")\n\nimport logging\nimport torchdata\nimport paramiko\n\nfrom typing import Optional\nfrom torchdata.datapipes.iter import FSSpecFileOpener\n\nfrom datamodule.td_datamodule import BaseTDM\nfrom utils import get_s3_paths, get_local_paths, get_lists\nfrom datamodule.utils import Boto3FileOpenerIterDataPipe as Boto3FileOpener\n\npl_logger = logging.getLogger('pytorch_lightning')\n\nclass ToHFHub(BaseTDM):\n\tdef __init__(self, \n\t\t\troot_data_path:str,#'s-laion-audio/webdataset_tar/' or '/fsx/knoriy/processed_datasets/', \n\t\t\tdataset_list:str,\n\t\t\thostname:str,\n\t\t\tusername:str,\n\t\t\tsave_path:str='/data/',\n\t\t\texclude_list:Optional[str]=None,\n\t\t\tcache_path:Optional[str]=None,\n\t\t\tuse_cache:Optional[bool]=False,\n\t\t\trecache:Optional[bool]=False,\n\t\t\ttrain_valid_test:Optional[list]=['train', 'valid', 'test'],\n\t\t\t*args,**kwargs,\n\t\t):\n\t\tsuper().__init__(*args,**kwargs)\n\n\t\tself.save_path = save_path\n\n\t\texclude = []\n\t\tif exclude_list:\n\t\t\texclude = get_lists(exclude_list)\n\n\t\tdataset_names = get_lists(dataset_list)\n\t\tnl = \"\\n\\t\"\n\t\tpl_logger.info(f\"Dataset names:{nl}{nl.join(map(str ,dataset_names))}\")\n\n\t\tdataset_names_intersection = set(dataset_names).intersection(exclude)\n\t\tif dataset_names_intersection:\n\t\t\traise Warning(f'Found similary dataset names in datasets and excluded dataset: {dataset_names_intersection}')\n\t\t\n\t\tif not cache_path:\n\t\t\tcache_path = f\"logs/{os.path.basename(dataset_list)}.json\"\n\t\t\n\t\tif root_data_path.startswith('s3://'):\n\t\t\tself.is_local = False\n\t\t\troot_data_path = root_data_path.replace('s3://', '')\n\t\t\tself.urls = get_s3_paths(\n\t\t\t\tbase_path\t\t\t= root_data_path,\n\t\t\t\ttrain_valid_test\t= train_valid_test,\n\t\t\t\tdataset_names\t\t= dataset_names, \n\t\t\t\texclude\t\t\t\t= exclude,\n\t\t\t\tcache_path\t\t\t= cache_path,\n\t\t\t\tuse_cache\t\t\t= use_cache,\n\t\t\t\trecache\t\t\t\t= recache\n\t\t\t\t)\n\t\telse:\n\t\t\tself.is_local = True\n\t\t\tself.urls = get_local_paths(\n\t\t\t\tbase_path\t\t\t= root_data_path,\n\t\t\t\ttrain_valid_test\t= train_valid_test,\n\t\t\t\tdataset_names\t\t= dataset_names, \n\t\t\t\texclude\t\t\t\t= exclude,\n\t\t\t\tcache_path\t\t\t= cache_path,\n\t\t\t\tuse_cache\t\t\t= use_cache,\n\t\t\t\trecache\t\t\t\t= recache\n\t\t\t\t)\n\n\t\tpl_logger.info(f\"Urls found: \\\n\t\t\t\\n\\tTrain: {len(self.urls.get(train_valid_test[0], []))} \\\n\t\t\t\\n\\tValid: {len(self.urls.get(train_valid_test[1], []))} \\\n\t\t\t\\n\\tTest: {len(self.urls.get (train_valid_test[2], []))}\"\n\t\t)\n\t\t\n\t\tself.train_data_dir = self.urls.get(train_valid_test[0], None)\n\t\tself.valid_data_dir = self.urls.get(train_valid_test[1], None)\n\t\tself.test_data_dir = self.urls.get(train_valid_test[2], None)\n\n\t\tprivate_key = paramiko.Ed25519Key.from_private_key_file(os.path.expanduser('~/.ssh/id_ed25519'))\n\t\tself.ssh = paramiko.SSHClient() \n\t\tself.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())\n\t\tself.ssh.connect(hostname, username=username, pkey=private_key)\n\n\tdef to_samples(self, data):\n\t\treturn data\n\n\t\n\tdef mkdir_p(self, sftp, remote_directory):\n\t\tif remote_directory == '/':\n\t\t\tsftp.chdir('/')\n\t\t\treturn\n\t\tif remote_directory == '':\n\t\t\treturn\n\t\t\n\t\ttry:\n\t\t\tsftp.chdir(remote_directory)\n\t\texcept IOError:\n\t\t\tdirname, basename = os.path.split(remote_directory.rstrip('/'))\n\t\t\tself.mkdir_p(sftp, dirname)\n\t\t\tsftp.mkdir(basename)\n\t\t\tsftp.chdir(basename)\n\t\t\treturn True\n\n\tdef to_hf(self, data):\n\t\tpath, content_stream = data\n\t\tsftp = self.ssh.open_sftp()\n\n\t\tdestination_dir = os.path.join(self.save_path, *path.split('/')[4:])\n\t\tself.mkdir_p(sftp, os.path.dirname(destination_dir))\n\t\ttry:\n\t\t\tsftp.stat(destination_dir) \n\t\t\tprint(f\"{destination_dir} already exists on remote\") \n\t\texcept FileNotFoundError: \n\t\t\tsftp.putfo(content_stream, destination_dir)\n\t\tsftp.close()\n\t\treturn path\n\t\n\tdef collate_fn(self, data):\n\t\treturn data\n\t\n\tdef create_pipeline(self, data_dir):\n\t\tdatapipe = torchdata.datapipes.iter.IterableWrapper(data_dir)\\\n\t\t\t.sharding_filter() # Sharding filter here causes the dataloader to hang when using multiple GPUs\n\t\t\n\t\tif self.is_local:\n\t\t\tdatapipe = FSSpecFileOpener(datapipe, mode='rb')\n\t\telse:\n\t\t\tdatapipe = Boto3FileOpener(datapipe, mode='rb')\n\t\t\n\t\tdatapipe = datapipe.map(self.to_hf)\n\t\t\n\t\treturn datapipe\n\n\nif __name__ == '__main__':\n\timport tqdm\n\tdp = ToHFHub(\n\t\troot_data_path='s3://laion-west-audio/webdataset_tar/', \n\t\tdataset_list='/fsx/knoriy/CLASP/logs/test_list.txt',\n\t\thostname='65.109.157.234',\n\t\tusername='root',\n\t)\n\tdp.setup()\n\n\tif hasattr(dp, 'test_datapipe'):\n\t\tfor i in tqdm.tqdm(dp.test_datapipe, total=len(dp.test_data_dir)):\n\t\t\tprint(i)\n\tif hasattr(dp, 'valid_datapipe'):\n\t\tfor i in tqdm.tqdm(dp.valid_datapipe, total=len(dp.valid_data_dir)):\n\t\t\tprint(i)\n\tif hasattr(dp, 'train_datapipe'):\n\t\tfor i in tqdm.tqdm(dp.train_datapipe, total=len(dp.train_data_dir)):\n\t\t\tprint(i)\n\t","repo_name":"knoriy/CLARA","sub_path":"scripts/move_to_server.py","file_name":"move_to_server.py","file_ext":"py","file_size_in_byte":4667,"program_lang":"python","lang":"en","doc_type":"code","stars":43,"dataset":"github-code","pt":"81"} +{"seq_id":"71090926665","text":"from __future__ import print_function\nfrom __future__ import division\n\nimport os\nimport sys\nimport time\nimport datetime\nimport argparse\nimport os.path as osp\nimport numpy as np\n\nsys.path.append('./torchFewShot')\n\nimport torch\nimport torch.nn as nn\nimport torch.backends.cudnn as cudnn\nfrom torch.utils.data import DataLoader\nfrom torch.optim import lr_scheduler\n\nfrom args_cls import argument_parser\n\nfrom torchFewShot import models\nfrom torchFewShot.data_manager import DataManager\nfrom torchFewShot.ProtoMeasure import few_shot_class\n\nfrom torchFewShot.utils.iotools import save_checkpoint, check_isfile\nfrom torchFewShot.utils.avgmeter import AverageMeter\nfrom torchFewShot.utils.logger import Logger\nfrom torchFewShot.utils.torchtools import set_bn_to_eval, count_num_param, adjust_learning_rate\n\n\nparser = argument_parser()\nargs = parser.parse_args()\n\ndef main():\n torch.manual_seed(args.seed)\n os.environ['CUDA_VISIBLE_DEVICES'] = args.gpu_devices\n use_gpu = torch.cuda.is_available()\n\n sys.stdout = Logger(osp.join(args.save_dir, 'log_test.txt'), mode='a')\n print(\"==========\\nArgs:{}\\n==========\".format(args))\n\n if use_gpu:\n print(\"Currently using GPU {}\".format(args.gpu_devices))\n cudnn.benchmark = True\n torch.cuda.manual_seed_all(args.seed)\n else:\n print(\"Currently using CPU (GPU is highly recommended)\")\n \n print('Initializing image data manager')\n dm = DataManager(args, use_gpu)\n trainloader, testloader = dm.return_dataloaders()\n\n print(\"Initializing model: {}\".format(args.arch))\n model = models.init_model(name=args.arch, scale_cls=args.scale_cls, margin=args.margin, num_classes=args.num_classes)\n print(\"Model size: {:.3f} M\".format(count_num_param(model)))\n\n if args.resume:\n if check_isfile(args.resume):\n checkpoint = torch.load(args.resume)\n model.load_state_dict(checkpoint['state_dict'])\n args.start_epoch = checkpoint['epoch']\n print(\"Loaded checkpoint from '{}'\".format(args.resume))\n\n if use_gpu:\n model = nn.DataParallel(model).cuda()\n\n print('Evaluate only')\n acc = test(model, testloader, use_gpu)\n\n\ndef test(model, testloader, use_gpu=True):\n accs = AverageMeter()\n model.eval()\n\n with torch.no_grad():\n for batch_idx , (images_train, labels_train, images_test, labels_test) in enumerate(testloader):\n if use_gpu:\n images_train = images_train.cuda()\n images_test = images_test.cuda()\n\n end = time.time()\n\n batch_size, num_train_examples, channels, height, width = images_train.size()\n num_test_examples = images_test.size(1)\n\n features_train = model(images_train.view(-1, channels, height, width))\n features_test = model(images_test.view(-1, channels, height, width))\n features_train = features_train.view(batch_size, num_train_examples, -1)\n features_test = features_test.view(batch_size, num_test_examples, -1) \n\n cls_scores = few_shot_class(\n features_test=features_test,\n features_train=features_train,\n labels_train=labels_train,\n distance=args.distance) #[batch_size, num_test_examples, nKnovel]\n\n cls_scores = cls_scores.view(batch_size * num_test_examples, -1)\n labels_test = labels_test.view(batch_size * num_test_examples)\n\n _, preds = torch.max(cls_scores.detach().cpu(), 1)\n acc = (torch.sum(preds == labels_test.detach().cpu()).float()) / labels_test.size(0)\n accs.update(acc.item(), labels_test.size(0))\n\n accuracy = accs.avg\n print('Results --------')\n print('batch_idx: {}, Accuracy: {:.2%}'.format(batch_idx, accuracy))\n\n return accuracy\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"kikyou123/Few-shot-hou","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":3846,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"38776150427","text":"N, M = map(int, input().split())\ndp = [[float('inf')] * (int((2 * N)** 0.5) + 2) for _ in range(N + 1)] \ndp[1][0] = 0\nstones = set([int(input()) for _ in range(M)])\n\nfor i in range(2, N + 1):\n if i in stones: continue\n for j in range(1, int((2 * i) ** 0.5) + 1):\n dp[i][j] = min(dp[i - j][j - 1], dp[i - j][j], dp[i - j][j + 1]) + 1\n\nanswer = min(dp[N])\n\nprint(answer if answer != float('inf') else -1)\n\n\n'''\n등차수열로 속도가 증가했을 때 k번째 돌에서 a만큼의 최대 속도를 가질 수 있고 \n이는 k = a(a+1)/2 를 만족한다.\n\n정리하면 a = sqrt(2 * k + (1/4)) - 1/2 이기 때문에 \ni번 위치에서 int(sqrt(2 * i)) + 1까지 검사하면 가능한 모든 속도에서의 값을 조사할 수 있다.\n\n'''","repo_name":"dd0114/week04","sub_path":"woosik/09번_2253_점프.py","file_name":"09번_2253_점프.py","file_ext":"py","file_size_in_byte":754,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"13810230924","text":"from flask import jsonify\n\nclass CustomException(Exception):\n\n def __init__(self, status_code, name = \"Custom Error\", description = 'Error'): \n super().__init__()\n self.description = description\n self.name = name\n self.status_code = status_code\n\n def get_response(self):\n response = jsonify({\n 'error': {\n 'code': self.status_code,\n 'name': self.name,\n 'description': self.description,\n }\n })\n response.status_code = self.status_code\n return response\n \nclass IsNotLogged(CustomException):\n def __init__(self, description):\n super().__init__(status_code=404, name=\"Is Not Logged\", description=description)\n self.description=description\n \nclass IsNotTheOwner(CustomException):\n def __init__(self, description):\n super().__init__(status_code=400, name=\"User is not the Owner\", description=description)\n self.description= description\n\nclass NotFound(CustomException):\n def __init__(self, description):\n super().__init__(status_code=400, name=\"Not Found\", description=description)\n self.description= description\n\n ","repo_name":"Llane4/Proyecto-Backend","sub_path":"api/models/exceptions.py","file_name":"exceptions.py","file_ext":"py","file_size_in_byte":1242,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"16067008948","text":"number_of_balls = int(input())\n\nred_balls = 0\norange_balls = 0\nyellow_balls = 0\nwhite_balls = 0\nblack_balls = 0\nothers_colors = 0\ntotal_points = 0\n\n\nfor ball in range(number_of_balls):\n ball_color = input()\n if ball_color == \"red\":\n total_points += 5\n red_balls += 1\n elif ball_color == \"orange\":\n total_points += 10\n orange_balls += 1\n elif ball_color == \"yellow\":\n total_points += 15\n yellow_balls += 1\n elif ball_color == \"white\":\n total_points += 20\n white_balls += 1\n elif ball_color == \"black\":\n total_points = int(total_points / 2)\n black_balls += 1\n else:\n others_colors += 1\n\nprint(f'Total points: {total_points}')\nprint(f'Red balls: {red_balls}')\nprint(f'Orange balls: {orange_balls}')\nprint(f'Yellow balls: {yellow_balls}')\nprint(f'White balls: {white_balls}')\nprint(f'Other colors picked: {others_colors}')\nprint(f'Divides from black balls: {black_balls}')","repo_name":"VelinIliev/python-basic-softuni","sub_path":"25-programming_basics_exam-18-19Jul2020/04-balls.py","file_name":"04-balls.py","file_ext":"py","file_size_in_byte":966,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"81"} +{"seq_id":"3721170726","text":"from decimal import Decimal\n\nimport requests\nfrom eip712.messages import EIP712Message, EIP712Type\nfrom eth_account.messages import _hash_eip191_message as hash_eip191_message\nfrom hexbytes import HexBytes\n\n\nclass OrderInfo(EIP712Type):\n SubaccountId: \"string\" # noqa: F821\n FeeRecipient: \"string\" # noqa: F821\n Price: \"string\" # noqa: F821\n Quantity: \"string\" # noqa: F821\n\n\nclass SpotOrder(EIP712Message):\n _name_ = \"Injective Protocol\"\n _version_ = \"2.0.0\"\n _chainId_ = 888\n _verifyingContract_ = \"0xCcCCccccCCCCcCCCCCCcCcCccCcCCCcCcccccccC\"\n _salt_ = HexBytes(\"0x0000000000000000000000000000000000000000000000000000000000000000\")\n\n MarketId: \"string\" # noqa: F821\n OrderInfo: OrderInfo\n Salt: \"string\" # noqa: F821\n OrderType: \"string\" # noqa: F821\n TriggerPrice: \"string\" # noqa: F821\n\n\nclass DerivativeOrder(EIP712Message):\n _name_ = \"Injective Protocol\"\n _version_ = \"2.0.0\"\n _chainId_ = 888\n _verifyingContract_ = \"0xCcCCccccCCCCcCCCCCCcCcCccCcCCCcCcccccccC\"\n _salt_ = HexBytes(\"0x0000000000000000000000000000000000000000000000000000000000000000\")\n\n MarketId: \"string\" # noqa: F821\n OrderInfo: OrderInfo\n OrderType: \"string\" # noqa: F821\n Margin: \"string\" # noqa: F821\n TriggerPrice: \"string\" # noqa: F821\n Salt: \"string\" # noqa: F821\n\n\n# domain_separator = EIP712_domain.hash_struct()\norder_type_dict = {0: \"\\x00\", 1: \"\\x01\", 2: \"\\x02\", 3: \"\\x03\", 4: \"\\x04\", 5: \"\\x05\", 6: \"\\x06\", 7: \"\\x07\", 8: \"\\x08\"}\n\n\nclass OrderHashResponse:\n def __init__(\n self,\n spot: [str] = None,\n derivative: [str] = None,\n ):\n self.spot = spot\n self.derivative = derivative\n\n\nclass OrderHashManager:\n def __init__(\n self,\n address,\n network,\n subaccount_indexes: [int] = None,\n ):\n self.address = address\n self.subacc_nonces = dict()\n\n for i in subaccount_indexes:\n subaccount_id = address.get_subaccount_id(index=i)\n url = network.lcd_endpoint + \"/injective/exchange/v1beta1/exchange/\" + subaccount_id\n res = requests.get(url=url)\n nonce = res.json()[\"nonce\"]\n self.subacc_nonces[i] = [subaccount_id, nonce + 1]\n\n def compute_order_hashes(self, spot_orders, derivative_orders, subaccount_index) -> [str]:\n if len(spot_orders) + len(derivative_orders) == 0:\n return []\n\n order_hashes = OrderHashResponse(spot=[], derivative=[])\n\n for o in spot_orders:\n msg = build_eip712_msg(o, self.subacc_nonces[subaccount_index][1])\n order_hash = hash_order(msg)\n order_hashes.spot.append(order_hash)\n self.subacc_nonces[subaccount_index][1] += 1\n\n for o in derivative_orders:\n msg = build_eip712_msg(o, self.subacc_nonces[subaccount_index][1])\n order_hash = hash_order(msg)\n order_hashes.derivative.append(order_hash)\n self.subacc_nonces[subaccount_index][1] += 1\n\n return order_hashes\n\n\ndef param_to_backend_go(param) -> int:\n go_param = Decimal(param) / pow(10, 18)\n return format(go_param, \".18f\")\n\n\ndef parse_order_type(order):\n return order_type_dict[order.order_type]\n\n\ndef build_eip712_msg(order, nonce):\n if order.__class__.__name__ == \"SpotOrder\":\n go_price = param_to_backend_go(order.order_info.price)\n go_trigger_price = param_to_backend_go(order.trigger_price)\n go_quantity = param_to_backend_go(order.order_info.quantity)\n go_order_type = parse_order_type(order)\n return SpotOrder(\n MarketId=order.market_id,\n OrderInfo=OrderInfo(\n SubaccountId=order.order_info.subaccount_id,\n FeeRecipient=order.order_info.fee_recipient,\n Price=go_price,\n Quantity=go_quantity,\n ),\n Salt=str(nonce),\n OrderType=go_order_type,\n TriggerPrice=go_trigger_price,\n )\n if order.__class__.__name__ == \"DerivativeOrder\":\n go_price = param_to_backend_go(order.order_info.price)\n go_trigger_price = param_to_backend_go(order.trigger_price)\n go_quantity = param_to_backend_go(order.order_info.quantity)\n go_margin = param_to_backend_go(order.margin)\n go_order_type = parse_order_type(order)\n return DerivativeOrder(\n MarketId=order.market_id,\n OrderInfo=OrderInfo(\n SubaccountId=order.order_info.subaccount_id,\n FeeRecipient=order.order_info.fee_recipient,\n Price=go_price,\n Quantity=go_quantity,\n ),\n Salt=str(nonce),\n OrderType=go_order_type,\n TriggerPrice=go_trigger_price,\n Margin=go_margin,\n )\n\n\ndef hash_order(msg):\n signable_message = msg.signable_message\n hex_digest = hash_eip191_message(signable_message=signable_message).hex()\n return \"0x\" + hex_digest\n","repo_name":"InjectiveLabs/sdk-python","sub_path":"pyinjective/orderhash.py","file_name":"orderhash.py","file_ext":"py","file_size_in_byte":4980,"program_lang":"python","lang":"en","doc_type":"code","stars":19,"dataset":"github-code","pt":"81"} +{"seq_id":"9065452823","text":"import requests\nimport os\nimport logging\nimport uuid\nfrom datetime import datetime, timedelta, time\nfrom requests.exceptions import HTTPError\n\nlog = logging.getLogger(__name__)\n\nclass VcoClient:\n \"\"\"\n A class that provides a client for interacting with the Velocloud orchestrator_url\n\n ...\n\n Attributes:\n -----------\n orchestrator_url : str\n URL of the velocloud orchestrator\n\n \"\"\"\n def __init__(self, orchestrator_url: str, **kwargs):\n api_key = kwargs.get('api_key', os.getenv('VCOAPIKEY'))\n\n if api_key is None:\n raise ValueError('api_key is required. Either pass it in as an argument'\\\n ' or use the VCOAPIKEY environmental variable')\n\n self.headers = {\n 'Authorization' : f\"Token {api_key}\",\n 'Content-Type' : 'application/json'\n }\n self.vco = orchestrator_url\n\n def request(self, method: str, body: dict) -> requests.Response:\n \"\"\"\n Wraps around requests.post()\n\n Parameters:\n method (str): API Method that is being called\n body (dict): A dictionary to be JSON encoded in the request\n\n Returns:\n (requests.Response) A HTTP Response object\n \"\"\"\n request_id = uuid.uuid4()\n log.info(f'request_id: {request_id} - making POST request to '\\\n f'{self.vco}/portal/rest/{method}'\n )\n try:\n resp = requests.post(f'{self.vco}/portal/rest/{method}',\n headers=self.headers,\n json=body)\n resp.raise_for_status()\n except HTTPError as err:\n log.error(f'request_id: {request_id} - {err}')\n\n # If it's just a 404 return None\n if resp.status_code == 404:\n return None\n\n raise err\n return resp\n\n\n @staticmethod\n def _make_orchestrator_timestamp(timestamp: datetime) -> str:\n \"\"\"\n Returns a timestamp in a format that the Velocloud Orchestrator will accept\n\n Parameters:\n timestamp (datetime): A datetime object\n\n Returns:\n (str): A formatted timestamp string\n \"\"\"\n return timestamp.strftime('%Y-%m-%dT%H:%M:%S.000Z')\n\n @classmethod\n def _make_interval(cls, start: datetime, end: datetime) -> dict:\n \"\"\"\n Returns a dict containing an interval which is required for a number of metrics\n \"\"\"\n start_str = cls._make_orchestrator_timestamp(start)\n end_str = cls._make_orchestrator_timestamp(end)\n\n return {\"start\" : start_str, \"end\" : end_str}\n\n def get_enterprise_proxy_enterprises(self) -> list:\n \"\"\"\n Returns a list of Enterprises associated with an EnterpriseProxy (MSP/Partner)\n\n Returns:\n (list) : A list of Enterprise dicts\n \"\"\"\n resp = self.request('enterpriseProxy/getEnterpriseProxyEnterprises', {})\n return resp.json() if resp is not None else None\n\n def get_enterprise_edges(self, enterprise_id: int = 0) -> list:\n \"\"\"\n Returns a list of Edges associated with an Enterprise (End user)\n\n Parameters:\n enterprise_id (int): The velocloud ID for an enterprise\n\n Returns:\n (list) : A list of Enterprise dicts\n \"\"\"\n body = {} if enterprise_id == 0 else {\"enterpriseId\" : enterprise_id}\n\n resp = self.request('enterprise/getEnterpriseEdges', body)\n return resp.json() if resp is not None else None\n\n def get_edge_link_series(self,\n edge_id: int,\n start: datetime,\n end: datetime,\n enterprise_id: int = 0,\n **kwargs) -> list:\n \"\"\"\n Returns a python object containing the link time series data for an edge\n during a given interval\n\n Parameters:\n enterprise_id (int): The velocloud ID for an enterprise\n edge_id (int): The velocloud ID for an edge\n metrics (dict): A dictionary containing a list of metrics to return\n from the orchestrator. Default behaviour is to return\n all metrics\n start (datetime): The start time for the time series data interval\n end (datetime): The end time for the time series data interval\n\n Returns:\n json (list): A python object representing the JSON response\n \"\"\"\n interval = self._make_interval(start=start, end=end)\n\n\n body = {\"edgeId\" : edge_id, \"interval\" : interval}\n enterprise = {} if enterprise_id == 0 else {\"enterpriseId\" : enterprise_id}\n metrics = kwargs.get(\"metrics\", {})\n\n body.update(enterprise)\n body.update(metrics)\n\n resp = self.request('metrics/getEdgeLinkSeries', body)\n return resp.json() if resp is not None else None\n\n def get_identifiable_applications(self, enterprise_id: int = 0) -> list:\n \"\"\"\n Returns a list of identifiable applications associated with an Enterprise (End user)\n\n Parameters:\n enterprise_id (int): The velocloud ID for an enterprise\n\n Returns:\n (list) : A list of application dicts\n \"\"\"\n\n body = {} if enterprise_id == 0 else {\"enterpriseId\" : enterprise_id}\n resp = self.request('configuration/getIdentifiableApplications',\n body\n )\n return resp.json() if resp is not None else None\n\n\n def get_edge_configuration_stack(self, edge_id: int, enterprise_id: int = 0) -> list:\n \"\"\"\n Returns a list of configurations associated with an Edges\n\n Parameters:\n enterprise_id (int): The velocloud ID for an enterprise\n edge_id (int): The velocloud ID for an edge\n\n Returns:\n (list) : A list of configuration dicts\n \"\"\"\n body = {\"edgeId\": edge_id}\n\n enterprise = {} if enterprise_id == 0 else {\"enterpriseId\" : enterprise_id}\n\n body.update(enterprise)\n\n resp = self.request('edge/getEdgeConfigurationStack',\n body\n )\n\n return resp.json() if resp is not None else None\n\n\n def get_edge_app_series(self,\n edge_id: int,\n start: datetime,\n end: datetime,\n enterprise_id: int = 0,\n **kwargs) -> list:\n \"\"\"\n Returns a python object containing the application time series data for\n from an edge during a given interval\n\n Parameters:\n enterprise_id (int): The velocloud ID for an enterprise\n edge_id (int): The velocloud ID for an edge\n metrics (dict): A dictionary containing a list of metrics to return\n from the orchestrator. Default behaviour is to return\n all metrics\n start (datetime): The start time for the time series data interval\n end (datetime): The end time for the time series data interval\n\n Returns:\n json (list): A python object representing the JSON response\n \"\"\"\n interval = self._make_interval(start=start, end=end)\n\n body = {\"edgeId\" : edge_id, \"interval\" : interval,\n \"resolveApplicationNames\": True, \"limit\" : -1}\n\n enterprise = {} if enterprise_id == 0 else {\"enterpriseId\" : enterprise_id}\n metrics = kwargs.get(\"metrics\", {})\n apps = kwargs.get(\"applications\", {})\n\n body.update(enterprise)\n body.update(metrics)\n body.update(apps)\n\n resp = self.request('metrics/getEdgeAppSeries', body)\n return resp.json() if resp is not None else None\n\n\n def get_edge_app_metrics(self,\n edge_id: int,\n start: datetime,\n end: datetime,\n enterprise_id: int = 0,\n **kwargs) -> list:\n\n interval = self._make_interval(start=start, end=end)\n \"\"\"\n Returns a python object containing the application metrics for\n from an edge during a given interval\n\n Parameters:\n enterprise_id (int): The velocloud ID for an enterprise\n edge_id (int): The velocloud ID for an edge\n metrics (dict): A dictionary containing a list of metrics to return\n from the orchestrator. Default behaviour is to return\n all metrics\n start (datetime): The start time for the time series data interval\n end (datetime): The end time for the time series data interval\n\n Returns:\n json (list): A python object representing the JSON response\n \"\"\"\n # Create the HTTP Request Body\n body = {\"edgeId\" : edge_id, \"interval\" : interval,\n \"resolveApplicationNames\": True, \"limit\" : -1}\n\n enterprise = {} if enterprise_id == 0 else {\"enterpriseId\" : enterprise_id}\n metrics = kwargs.get(\"metrics\", {})\n\n body.update(enterprise)\n body.update(metrics)\n\n resp = self.request('metrics/getEdgeAppMetrics', body)\n return resp.json() if resp is not None else None\n\n # Get a list of link metrics\n\n def get_link_quality_events(self, edge_id: int, enterprise_id: int = 0, **kwargs):\n pass\n\n\n def get_enterprise_events(self,\n start: datetime,\n end: datetime,\n edge_id: int = 0,\n enterprise_id: int = 0,\n **kwargs) -> list:\n interval = self._make_interval(start=start, end=end)\n \"\"\"\n Returns a python object containing the syslog events for a given interval in an enterprise\n\n Parameters:\n edge_id (int): The velocloud ID for an edge\n enterprise_id (int): The velocloud ID for an enterprise\n start (datetime): The start time for the time series data interval\n end (datetime): The end time for the time series data interval\n\n Returns:\n json (list): A python object representing the JSON response\n \"\"\"\n\n body = {\"interval\": interval}\n\n enterprise = {} if enterprise_id == 0 else {\"enterpriseId\" : enterprise_id}\n edge = {} if not edge_id else {\"edgeId\" : edge_id}\n\n filter = kwargs.get(\"filter\", {})\n\n body.update(enterprise)\n body.update(edge)\n body.update(filter)\n\n resp = self.request('event/getEnterpriseEvents', body)\n return resp.json() if resp is not None else None\n","repo_name":"Brayneded/vcoclient","sub_path":"vcoclient.py","file_name":"vcoclient.py","file_ext":"py","file_size_in_byte":10920,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"35214714253","text":"import sys\nimport gpsData as GpsData\nimport sms as Sms\nfrom time import gmtime, strftime, sleep\n#from email.mime.text import MIMEText\n\ndef main():\n #print \"Starting.... %s\"%(strftime(\"%Y-%m-%d %H:%M:%S\", gmtime()))\n # use GPS data for message\n coords = GpsData.getCoords()\n lat=str(coords['lat'])\n lon=str(coords['lon'])\n utc=str(coords['utc'])\n url = 'http://maps.google.com/maps?f=q&q=%s,%s' % (lat,lon)\n #msg = MIMEText(u'SITA Notification -- my location: '+url+' ('+utc+')')\n msg = 'SITA Notification -- my location: '+url+' ('+utc+')'\n #msg = 'SITA Notification -- my location: '+url+' ('+strftime(\"%Y-%m-%d %H:%M:%S\", gmtime())+')'\n # set up recipients\n # get recipients from SIM card or props file from /boot/phonebook.properties\n phonebook = []\n phonebook = Sms.phonebook()\n if phonebook == []:\n # if no numbers on SIM card, check properties file\n filepath = '/boot/phonebook.properties'\n with open(filepath) as fp:\n line = fp.readline().replace('\\r', '').replace('\\n', '')\n if line != '':\n phonebook.append(line)\n while line:\n line = fp.readline().replace('\\r', '').replace('\\n', '')\n if line != '':\n phonebook.append(line)\n\n # broadcast location twice\n for addr in phonebook:\n Sms.sendsms(addr,msg)\n sleep(2)\n sleep(30)\n for addr in phonebook:\n Sms.sendsms(addr,msg)\n sleep(2)\n #print \"Done... %s\"%(strftime(\"%Y-%m-%d %H:%M:%S\", gmtime()))\n\nif __name__ == '__main__':\n main()\n\n","repo_name":"jfaulkner/sita","sub_path":"sita.py","file_name":"sita.py","file_ext":"py","file_size_in_byte":1476,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"81"} +{"seq_id":"11269875624","text":"src = r\"https://onlinejudge.u-aizu.ac.jp/courses/lesson/1/ALDS1/1/ALDS1_1_A\"\n\n\ndef insertionsort(a):\n n = len(a)\n for i in range(1, n):\n v = a[i]\n j = i - 1\n print(*a)\n while j >= 0 and a[j] > v:\n a[j + 1] = a[j]\n j -= 1\n a[j + 1] = v\n print(*a)\n\n\n# ---- process ----\n\ninput()\ninsertionsort(list(map(int, input().split())))\n","repo_name":"zhu2qian1/Python_public","sub_path":"AOJ/ALDS1/1/a.py","file_name":"a.py","file_ext":"py","file_size_in_byte":390,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"36715209534","text":"# **************************** Desafio 096 ************************* #\n# Um print especial #\n# Faça um programa que tenha uma função chamada escreva(), que #\n# receba um texto qualquer como parâmetro e mostre uma mensagem com #\n# tamanho adaptável. #\n# ****************************************************************** #\n#\n# Definindo as funções:\ndef lin():\n print('+=' * 24)\n\n\ndef lin1():\n print('\\033[1;34m*=\\033[m' * 26)\n\n\ndef titulo(msg):\n lin()\n texto = f' \\033[1;3;4;7;34m{msg}\\033[m '\n print(f'\\n{texto:*^64}\\n')\n lin()\n print()\n\n\ndef escreve(texto):\n c = int(len(texto)) + 4\n print('~' * c)\n print(f'{texto:^{c}}')\n print('~' * c)\n\n\n# ****************************************************************** #\n\n# Rotina principal\ntitulo('Um print especial')\n\nescreve('CURSO EM VIDEO')\nescreve('Teste')\nescreve(\"Olá, Mundo\")\nescreve('Oi')\nescreve('INCONSTITUCIONALISTICAMENTE')\n","repo_name":"EduardoPessanha/Git-Python","sub_path":"exercicios/ex097.py","file_name":"ex097.py","file_ext":"py","file_size_in_byte":1025,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"20482757009","text":"\"\"\" #TC O(n) #SC O(n)\nl'idee est la suivante si on a une parenthese qui n'a pas de paire alors il faut en rajouter une parenthese pour que la phrase soit valide. on utilisera un stack : \na chaque fois q'on lit une parenthese '(' on l'ajoute dans le stack et a chaque fois qu'on lit une parenthese ')' on pop du stack si le stack et vide ca veut dire que \nil ya une parenthese ')' en plus . si a la fin il ya des parenthese qui reste dans le stack ca veut dire qu'il ya des parenthese '(' en plus.\n\"\"\"\nclass Solution:\n def minAddToMakeValid(self, s: str) -> int:\n stack=[]\n res=0\n for i in range(len(s)) : \n if s[i]=='(':\n stack.append(s[i])\n elif stack: # if s[i] == ')' and stack non empty\n stack.pop()\n else : # if if s[i] == ')' and stack empty\n res+=1\n res+=len(stack)\n return res\n \n\"\"\"#TC O(n) #SC O(1)\non peut utiliser un counter a la place du stack car on fait rentrer que un element dans le stack '('. A chaque fois qu'on lit '(' on incremente le counter et a\nchaque fois qu'on lit ')' si le counter == 0 alors on rajoute au resultat 1 car cad qu'il ya pas de '(' avant le ')' [donc pas de paire] et si le counter et superieur \na 0 alors on soustrait 1. a la fin on rajoute le counter au resultat car il represente les '(' qui n'ont pas de paire.\n\"\"\"\nclass Solution:\n def minAddToMakeValid(self, s: str) -> int:\n counter = res = 0\n for i in range(len(s)) : \n if s[i]=='(':\n counter+=1\n elif counter>0 : # if s[i] == ')' and counter>0\n counter-=1\n else : # if if s[i] == ')' and counter==0\n res+=1\n res+=counter\n return res\n","repo_name":"rtn75000/leetcode-pb","sub_path":"921. Minimum Add to Make Parentheses Valid/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":1772,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"8181335986","text":"from zipfile import ZipFile\n\nlocal_dependencies = [\n \"requirements.txt\",\n \"main.py\"\n]\naliased_dependencies = {\n \"../../src/features/build_features.py\": \"features/build_features.py\",\n \"../../src/features/url.py\": \"features/url.py\",\n \"../../src/features/url_utils.py\": \"features/url_utils.py\"\n}\n\n\nif __name__ == \"__main__\":\n print(\"Creating ZIP for feature extraction endpoint\")\n\n with ZipFile(\"getFeaturesFromUrl.zip\", \"w\") as dist:\n for file in local_dependencies:\n dist.write(file)\n print(\"Added [%s] to zip\" % file)\n\n for real_file, arc_file in aliased_dependencies.items():\n dist.write(real_file, arcname=arc_file)\n print(\"Added [%s] to zip\" % real_file)\n\n print(\"Created ZIP for feature extraction endpoint successfully\")\n","repo_name":"kalam034/PhishyAI","sub_path":"ai-platform/features-to-url/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":808,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"81"} +{"seq_id":"24759733181","text":"# -*- encoding: utf-8 -*-\n\"\"\"Contains views relaited to User model\"\"\"\n\nimport json\n\nfrom datetime import datetime\n\nfrom django.http import (HttpResponseBadRequest,\n HttpResponseServerError, HttpResponse)\nfrom django.core import serializers\nfrom django.shortcuts import get_object_or_404\n\nfrom APP.models import User, Bicycle, Image\nfrom APP.utils.need_token import need_token\n\n\n@need_token\ndef create(request):\n \"\"\"Creates new Bicycle object in DB\n\n The url is built like this:\n https://cycling.com/api/bike/create\n it's a POST request\n \"\"\"\n if request.method != 'POST':\n return HttpResponseBadRequest(content='Expected POST')\n params = json.loads(request.body)\n kwargs = {}\n kwargs['name'] = params.get('name', None)\n if kwargs['name'] is None:\n return HttpResponseBadRequest(content='There should be \"name\" field')\n kwargs['description'] = params.get('description', None)\n kwargs['owner'] = request.user\n try:\n bike = Bicycle.objects.create(**kwargs)\n for link in params.get('imagesList', ['']):\n if link and link['url']:\n Image.objects.create(url=link['url'], bike=bike)\n data = serializers.serialize(\"json\", [bike, ])\n return HttpResponse(data, content_type=\"application/json\")\n except Exception as e:\n bike.delete()\n return HttpResponseServerError(content=str(e))\n\n\ndef by_id(request, bike_id):\n \"\"\"Get a Bicycle object from DB by id\n\n The url is built like this:\n https://cycling.com/api/bike/id\n it's a GET request\n \"\"\"\n if request.method != 'GET':\n return HttpResponseBadRequest(content='Expected GET')\n bike = get_object_or_404(Bicycle, pk=bike_id)\n images = Image.objects.filter(bike=bike)\n data = [bike, ]\n data.extend([i for i in images])\n data_in_json = serializers.serialize(\"json\", data)\n return HttpResponse(data_in_json, content_type=\"application/json\")\n\n\n@need_token\ndef edit(request):\n \"\"\"Edites a Bicycle object in DB\n\n The url is built like this:\n https://cycling.com/api/bike/edit\n it's a POST request\n \"\"\"\n if request.method != 'POST':\n return HttpResponseBadRequest(content='Expected POST')\n params = json.loads(request.body)\n bike = get_object_or_404(Bicycle, pk=params['pk'])\n if not request.user == bike.owner:\n return HttpResponseBadRequest(\n content=\"Trying to edit somebody's else bicycle\")\n\n try:\n bike.name = params['name']\n bike.description = params['description']\n bike.save()\n for link in params.get('imagesList', ['']):\n if link:\n if link['pk']:\n img = Image.objects.get(pk=link['pk'])\n if img.bike == bike:\n if link['toDelete']:\n img.delete()\n else:\n img.url = link['url']\n img.save()\n elif link['url'] and not link['toDelete']:\n Image.objects.create(url=link['url'], bike=bike)\n data = serializers.serialize(\"json\", [bike, ])\n return HttpResponse(data, content_type=\"application/json\")\n except Exception as e:\n return HttpResponseServerError(content=str(e))\n\n\n@need_token\ndef delete(request):\n \"\"\"Deletes a Bicycle object fromin DB\n\n The url is built like this:\n https://cycling.com/api/bike/delete\n it's a POST request\n \"\"\"\n if request.method != 'POST':\n return HttpResponseBadRequest(content='Expected POST')\n params = json.loads(request.body)\n bike = get_object_or_404(Bicycle, pk=params['pk'])\n if not request.user == bike.owner:\n return HttpResponseBadRequest(\n content=\"Trying to delete somebody's else bicycle\")\n try:\n bike.delete()\n return HttpResponse(json.dumps({'ok': 200}))\n except Exception as err:\n return HttpResponseServerError(content=str(err))\n","repo_name":"Social-projects-Rivne/Cycling","sub_path":"APP/views/bike.py","file_name":"bike.py","file_ext":"py","file_size_in_byte":4002,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"81"} +{"seq_id":"27135274962","text":"# 这题其实就是费柏纳西数列\nclass Solution:\n \"\"\"\n @param n: An integer\n @return: An integer\n \"\"\"\n def climb_stairs(self, n: int) -> int:\n # write your code here\n if n == 0:\n return 0\n if n == 1:\n return 1\n\n # f[i] 从上一个阶梯移动到第 i 个阶梯的方法数\n # 因为一次可以移动一步或是两步,所以上一个阶梯可能是 f[i-1] 或是 f[i-2]\n # 要求所有可能的方法数就相加\n\n f = [0 for i in range(n+1)] # 要移动到第 n 个阶梯,所以要用 n+1 当上限\n # 初始化\n f[0] = 1\n f[1] = 1\n\n for i in range(2, n+1):\n f[i] = f[i-1] + f[i-2]\n\n return f[n]\n","repo_name":"ytatus94/Leetcode","sub_path":"lintcode/lintcode_0111_Climbing_Stairs.py","file_name":"lintcode_0111_Climbing_Stairs.py","file_ext":"py","file_size_in_byte":741,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"22184617875","text":"try:\n import xml.etree.cElementTree as E\nexcept:\n import xml.etree.ElementTree as E\nimport os, sys, types, re, math\nfrom typing import Optional, Tuple, Any\n\nVERSION = 143\n\npython3 = sys.version_info.major > 2\nif python3:\n tupletype = tuple\n listtype = list\n max_int = sys.maxsize\nelse:\n tupletype = types.TupleType # type: ignore\n listtype = types.ListType # type: ignore\n max_int = sys.maxint # type: ignore\n\nnote_ornamentation_map = { # for notations/, modified from EasyABC\n \"ornaments/trill-mark\": \"T\",\n \"ornaments/mordent\": \"M\",\n \"ornaments/inverted-mordent\": \"P\",\n \"ornaments/turn\": \"!turn!\",\n \"ornaments/inverted-turn\": \"!invertedturn!\",\n \"technical/up-bow\": \"u\",\n \"technical/down-bow\": \"v\",\n \"technical/harmonic\": \"!open!\",\n \"technical/open-string\": \"!open!\",\n \"technical/stopped\": \"!plus!\",\n \"technical/snap-pizzicato\": \"!snap!\",\n \"technical/thumb-position\": \"!thumb!\",\n \"articulations/accent\": \"!>!\",\n \"articulations/strong-accent\": \"!^!\",\n \"articulations/staccato\": \".\",\n \"articulations/scoop\": \"!slide!\",\n \"fermata\": \"!fermata!\",\n \"arpeggiate\": \"!arpeggio!\",\n \"articulations/tenuto\": \"!tenuto!\",\n \"articulations/staccatissimo\": \"!wedge!\", # not sure whether this is the right translation\n \"articulations/spiccato\": \"!wedge!\", # not sure whether this is the right translation\n \"articulations/breath-mark\": \"!breath!\", # this may need to be tested to make sure it appears on the right side of the note\n \"articulations/detached-legato\": \"!tenuto!.\",\n}\n\ndynamics_map = { # for direction/direction-type/dynamics/\n \"p\": \"!p!\",\n \"pp\": \"!pp!\",\n \"ppp\": \"!ppp!\",\n \"pppp\": \"!pppp!\",\n \"f\": \"!f!\",\n \"ff\": \"!ff!\",\n \"fff\": \"!fff!\",\n \"ffff\": \"!ffff!\",\n \"mp\": \"!mp!\",\n \"mf\": \"!mf!\",\n \"sfz\": \"!sfz!\",\n}\n\nperc_svg = \"\"\"%%beginsvg\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n %%endsvg\"\"\"\n\ntab_svg = \"\"\"%%beginsvg\n \n \n \n \"\"\"\n\nkob_svg = '%s\\n'\nkob_svg_2 = '%s\\n'\n\n\ndef info(string: str, warn=True):\n sys.stderr.write((warn and \"-- \" or \"\") + string + \"\\n\")\n\n\n# -------------------\n# data abstractions\n# -------------------\nclass Measure:\n def __init__(self, p):\n self.reset()\n self.ixp = p\n \"\"\"part number\"\"\"\n self.ixm = 0\n \"\"\"measure number\"\"\"\n self.measure_duration = 0\n \"\"\"measure duration (nominal metre value in divisions)\"\"\"\n self.divs = 0\n \"\"\"number of divisions per 1/4\"\"\"\n self.meter = int(4), int(4)\n\n def reset(self):\n \"\"\"Reset each measure.\"\"\"\n self.attr = \"\"\n \"\"\"measure signatures, tempo\"\"\"\n self.lline = \"\"\n \"\"\"left barline, but only holds ':' at start of repeat, otherwise empty\"\"\"\n self.rline = \"|\"\n \"\"\"right barline\"\"\"\n self.lnum = \"\"\n \"\"\"(left) volta number\"\"\"\n\n\nclass Note:\n def __init__(self, duration=0, n=None):\n self.time = 0 # the time in XML division units\n self.duration = duration # duration of a note in XML divisions\n self.fact = None # time modification for tuplet notes (num, div)\n self.tup = [\"\"] # start(s) and/or stop(s) of tuplet\n self.tupabc = \"\" # ABC tuplet string to issue before note\n self.beam = 0 # 1 = beamed\n self.is_grace = False\n self.before = [] # ABC string that goes before the note/chord\n self.after = \"\" # the same after the note/chord\n self.notes = n and [n] or [] # notes in the chord\n self.lyrics = {} # {number -> syllable}\n self.tab = None # (string number, fret number)\n self.ntdec = \"\" # !string!, !courtesy!\n\n\nclass Element:\n def __init__(self, string: str) -> None:\n self.time = 0\n \"\"\"the time in XML division units\"\"\"\n self.string = string\n \"\"\"any abc string that is not a note\"\"\"\n\n\nclass Counter:\n def increment(self, key, voice) -> None:\n self.counters[key][voice] = self.counters[key].get(voice, 0) + 1\n\n def clear(self, voice_nums) -> None:\n \"\"\"reset all counters\"\"\"\n tups = list(zip(voice_nums, len(voice_nums) * [0]))\n self.counters = {\n \"note\": dict(tups),\n \"nopr\": dict(tups),\n \"nopt\": dict(tups),\n }\n\n def getv(self, key, voice) -> int:\n return self.counters[key][voice]\n\n def prcnt(self, ip) -> None:\n \"\"\"print summary of all non zero counters\"\"\"\n for iv in self.counters[\"note\"]:\n if self.getv(\"nopr\", iv) != 0:\n info(\n \"part %d, voice %d has %d skipped non printable notes\"\n % (ip, iv, self.getv(\"nopr\", iv))\n )\n if self.getv(\"nopt\", iv) != 0:\n info(\n \"part %d, voice %d has %d notes without pitch\"\n % (ip, iv, self.getv(\"nopt\", iv))\n )\n if (\n self.getv(\"note\", iv) == 0\n ): # no real notes counted in this voice\n info(\"part %d, skipped empty voice %d\" % (ip, iv))\n\n\nclass Music:\n def __init__(self, options):\n self.time = 0\n \"\"\"the current time\"\"\"\n self.max_time = 0\n \"\"\"maximum time in a measure\"\"\"\n self.g_measures = []\n \"\"\"[voices,.. for all measures in a part]\"\"\"\n self.g_lyrics = []\n \"\"\"[{num: (abc_lyric_string, melis)},.. for all measures in a part]\"\"\"\n self.voice_nums = set()\n \"\"\"all used voice id's in a part (XML voice id's == numbers)\"\"\"\n self.counter = Counter()\n \"\"\"global counter object\"\"\"\n self.voice_count = 1\n \"\"\"the global voice count over all parts\"\"\"\n self.last_note = None\n \"\"\"the last real note record inserted in self.voices\"\"\"\n self.bars_per_line = options.b\n \"\"\"the max number of bars per line when writing ABC\"\"\"\n self.chars_per_line = options.n\n \"\"\"the number of chars per line when writing ABC\"\"\"\n self.repbra = False\n \"\"\"true if volta is used somewhere\"\"\"\n self.no_volta = options.v\n \"\"\"no volta on higher voice numbers\"\"\"\n self.javascript = options.j\n \"\"\"compatibility with javascript version\"\"\"\n\n def init_voices(self, new_part=False):\n self.voice_times, self.voices, self.lyrics = {}, {}, {}\n for voice in self.voice_nums:\n self.voice_times[voice] = 0\n # {voice: the end time of the last item in each voice}\n self.voices[voice] = [] # {voice: [Note|Element, ..]}\n self.lyrics[voice] = [] # {voice: [{num: syl}, ..]}\n if new_part:\n self.counter.clear(self.voice_nums) # clear counters once per part\n\n def increment_time(self, duration: int):\n self.time += duration\n if self.time < 0:\n self.time = 0 # erroneous element\n if self.time > self.max_time:\n self.max_time = self.time\n\n def append_element_voices(self, voices, element):\n for voice in voices:\n self.append_element(voice, element) # insert element in all voices\n\n def insert_element(self, voice: int, element: str):\n \"\"\"insert at the start of voice in the current measure\"\"\"\n obj = Element(element)\n obj.time = 0 # because voice is sorted later\n self.voices[voice].insert(0, obj)\n\n def append_obj(self, voice: int, obj, duration: int):\n obj.time = self.time\n self.voices[voice].append(obj)\n self.increment_time(duration)\n if self.time > self.voice_times[voice]:\n self.voice_times[voice] = self.time\n # don't update for inserted earlier items\n\n def append_element(self, voice: int, element: str, count=False):\n self.append_obj(voice, Element(element), 0)\n if count:\n self.counter.increment(\"note\", voice)\n # count number of certain elements in each voice (in addition to notes)\n\n def append_element_at_time(self, voice, element, time):\n \"\"\"insert element at specified time\"\"\"\n obj = Element(element)\n obj.time = time\n self.voices[voice].append(obj)\n\n def append_note(self, voice: int, note: Note, noot):\n note.notes.append(note.ntdec + noot)\n self.append_obj(voice, note, int(note.duration))\n self.last_note = note\n # remember last note/rest for later modifications (chord, grace)\n if noot != \"z\" and noot != \"x\": # real notes and grace notes\n self.counter.increment(\n \"note\", voice\n ) # count number of real notes in each voice\n if not note.is_grace: # for every real note\n self.lyrics[voice].append(\n note.lyrics\n ) # even when it has no lyrics\n\n def get_last_record(\n self, voice: int\n ) -> Optional[Element]: # TODO:figure out\n if self.g_measures:\n return self.g_measures[-1][voice][\n -1\n ] # the last record in the last measure\n return None # no previous records in the first measure\n\n def get_last_melisma(self, voice: int, num) -> bool:\n \"\"\"get melisma of last measure\"\"\"\n if self.g_lyrics:\n lyrdict = self.g_lyrics[-1][\n voice\n ] # the previous lyrics dict in this voice\n if num in lyrdict:\n return lyrdict[num][\n 1\n ] # lyrdict = num -> (lyric string, melisma)\n return False # no previous lyrics in voice or line number\n\n def add_chord(self, note: Note, noot: str):\n # careful: we assume that chord notes follow immediately\n for d in note.before: # put all decorations before chord\n if d not in self.last_note.before:\n self.last_note.before += [d]\n self.last_note.notes.append(note.ntdec + noot)\n\n def add_bar(self, line_break: str, measure: Measure):\n \"\"\"linebreak, measure data\"\"\"\n if (\n measure.measure_duration\n and self.max_time > measure.measure_duration\n ):\n info(\n \"measure %d in part %d longer than metre\"\n % (measure.ixm + 1, measure.ixp + 1)\n )\n self.time = self.max_time # the time of the bar lines inserted here\n for voice in self.voice_nums:\n if (\n measure.lline or measure.lnum\n ): # if left barline or left volta number\n prev = self.get_last_record(\n voice\n ) # get the previous barline record\n if (\n prev is not None\n ): # in measure 1 no previous measure is available\n x = prev.string # p.string is the ABC barline string\n if (\n measure.lline\n ): # append begin of repeat, measure.lline == ':'\n x = (\n (x + measure.lline)\n .replace(\":|:\", \"::\")\n .replace(\"||\", \"|\")\n )\n if self.no_volta == 3:\n # add volta number only to lowest voice in part 0\n if measure.ixp + voice == min(self.voice_nums):\n x += measure.lnum\n elif measure.lnum: # new behaviour with I:repbra 0\n x += measure.lnum\n # add volta number(s) or text to all voices\n self.repbra = True # signal occurrence of a volta\n prev.string = x # modify previous right barline\n elif measure.lline:\n # begin of new part and left repeat bar is required\n self.insert_element(voice, \"|:\")\n if line_break:\n prev = self.get_last_record(voice)\n # get the previous barline record\n if prev:\n prev.string += line_break # insert linebreak char after the barlines+volta\n if measure.attr: # insert signatures at front of buffer\n self.insert_element(voice, measure.attr)\n self.append_element(voice, \" %s\" % measure.rline)\n # insert current barline record at time max_time\n self.voices[voice] = sort_measure(self.voices[voice], measure)\n # make all times consistent\n lyrics = self.lyrics[voice] # [{number: sylabe}, .. for all notes]\n lyric_dict = {}\n # {number: (abc_lyric_string, melis)} for this voice\n nums = [num for d in lyrics for num in d.keys()]\n # the lyrics numbers in this measure\n max_nums = max(nums + [0])\n # the highest lyrics number in this measure\n for i in range(max_nums, 0, -1):\n xs = [syldict.get(i, \"\") for syldict in lyrics]\n # collect the syllabi with number i\n melis = self.get_last_melisma(voice, i)\n # get melisma from last measure\n lyric_dict[i] = abc_lyrics(xs, melis)\n self.lyrics[voice] = lyric_dict\n # {number: (abc_lyric_string, melis)} for this measure\n make_broken(self.voices[voice])\n self.g_measures.append(self.voices)\n self.g_lyrics.append(self.lyrics)\n self.time = self.max_time = 0\n self.init_voices()\n\n def output_voices(self, divs, ip, is_sib: bool):\n \"\"\"Output all voices of part ip.\"\"\"\n xml2abcmap = {} # XML voice number -> abc voice number (one part)\n vnum_keys = list(self.voice_nums)\n if self.javascript or is_sib:\n vnum_keys.sort()\n min_voice = min(vnum_keys or [1])\n # lowest XML voice number of this part\n for voice in vnum_keys:\n if self.counter.getv(\"note\", voice) == 0:\n # no real notes counted in this voice\n continue # skip empty voices\n if abc_out.denL:\n unit_l = abc_out.denL\n # take the unit length from the -d option\n else:\n unit_l = compute_unit_length(voice, self.g_measures, divs)\n # compute the best unit length for this voice\n abc_out.cmpL.append(unit_l) # remember for header output\n vn, vl = ([], {})\n # for voice voice: collect all notes to vn and all lyric lines to vl\n for im in range(len(self.g_measures)):\n measure = self.g_measures[im][voice]\n vn.append(out_voice(measure, divs[im], im, ip, unit_l))\n check_melismas(self.g_lyrics, self.g_measures, im, voice)\n for n, (lyric_str, melisma) in self.g_lyrics[im][\n voice\n ].items():\n if n in vl:\n while len(vl[n]) < im:\n vl[n].append(\"\") # fill in skipped measures\n vl[n].append(lyric_str)\n else:\n vl[n] = im * [\"\"] + [lyric_str]\n # must skip im measures\n for (n, lyrics) in vl.items():\n # fill up possibly empty lyric measures at the end\n missing = len(vn) - len(lyrics)\n lyrics += missing * [\"\"]\n abc_out.add(f\"V:{self.voice_count}\")\n if self.repbra:\n if self.no_volta == 1 and self.voice_count > 1:\n abc_out.add(\"I:repbra 0\") # only volta on first voice\n if self.no_volta == 2 and voice > min_voice:\n abc_out.add(\"I:repbra 0\")\n # only volta on first voice of each part\n if self.chars_per_line > 0:\n self.bars_per_line = 0\n # option -n (max chars per line) overrules -b (max bars per line)\n elif self.bars_per_line == 0:\n self.chars_per_line = 100 # the default: 100 chars per line\n bar_num = 0 # count bars\n while vn: # while still measures available\n ib = 1\n chunk = vn[0]\n while ib < len(vn):\n if (\n self.chars_per_line > 0\n and len(chunk) + len(vn[ib]) >= self.chars_per_line\n ):\n break # line full (number of chars)\n if self.bars_per_line > 0 and ib >= self.bars_per_line:\n break # line full (number of bars)\n chunk += vn[ib]\n ib += 1\n bar_num += ib\n abc_out.add(f\"{chunk} %%{bar_num}\") # line with barnumer\n del vn[:ib] # chop ib bars\n lyric_lines = sorted(vl.items())\n # order the numbered lyric lines for output\n for n, lyrics in lyric_lines:\n abc_out.add(\"w: \" + \"|\".join(lyrics[:ib]) + \"|\")\n del lyrics[:ib]\n xml2abcmap[voice] = self.voice_count\n # XML voice number -> ABC voice number\n self.voice_count += 1 # count voices over all parts\n self.g_measures = [] # reset the follwing instance vars for each part\n self.g_lyrics = []\n self.counter.prcnt(ip + 1)\n # print summary of skipped items in this part\n return xml2abcmap\n\n\nclass ABCOutput:\n pagekeys = \"scale,pageheight,pagewidth,leftmargin,rightmargin,topmargin,botmargin\".split(\n \",\"\n )\n\n def __init__(self, name, out_path, X, options):\n self.name = name\n self.abc_out = []\n \"\"\"list of ABC strings\"\"\"\n self.title = \"T:Title\"\n self.key = \"none\"\n self.clefs = {}\n \"\"\"clefs for all abc-voices\"\"\"\n self.meter = \"none\"\n self.tempo = 0\n \"\"\"0 -> no tempo field\"\"\"\n self.tempo_units = (1, 4)\n \"\"\"note type of tempo direction\"\"\"\n self.out_path = out_path\n \"\"\"the output path or none\"\"\"\n self.X = X + 1\n \"\"\"the ABC tune number\"\"\"\n self.denL = options.d\n \"\"\"denominator of the unit length (L:) from -d option\"\"\"\n self.vol_pan = int(options.m)\n \"\"\"0 -> no %%MIDI, 1 -> only program, 2 -> all %%MIDI\"\"\"\n self.cmpL = [] # computed optimal unit length for all voices\n self.javascript = options.j\n \"\"\"compatibility with javascript version\"\"\"\n self.tstep = options.t # translate perc_map to voicemap\n self.stemless = False # use U:s=!stemless!\n self.shift_stems = options.s # shift note heads 3 units left\n if out_path:\n _, base_name = os.path.split(name)\n self.out_file = open(os.path.join(out_path, base_name), \"w\")\n else:\n self.out_file = sys.stdout\n if self.javascript:\n self.X = 1 # always X:1 in javascript version\n self.pageFmt = {}\n for k in self.pagekeys:\n self.pageFmt[k] = None\n if len(options.p) == 7:\n for k, v in zip(self.pagekeys, options.p):\n try:\n self.pageFmt[k] = float(v)\n except:\n info(\"illegal float %s for %s\" % (k, v))\n continue\n\n def add(self, string: str) -> None:\n self.abc_out.append(string + \"\\n\") # collect all ABC output\n\n def make_header(self, stfmap, partlist, midimap, vmpdct, heads):\n \"\"\"stfmap = [parts], part = [staves], stave = [voices]\"\"\"\n acc_voice, acc_staff, staffs = [], [], stfmap[:] # staffs is consumed\n for x in partlist:\n # collect partnames into acc_voice and staff groups into acc_staff\n try:\n prgroupelem(x, (\"\", \"\"), \"\", stfmap, acc_voice, acc_staff)\n except:\n info(\"lousy musicxml: error in part-list\")\n staves = \" \".join(acc_staff)\n clfnms = {}\n for part, (partname, partabbrv) in zip(staffs, acc_voice):\n if not part:\n continue # skip empty part\n firstVoice = part[0][0] # the first voice number in this part\n nm = partname.replace(\"\\n\", r\"\\n\").replace(\".:\", \".\").strip(\":\")\n snm = partabbrv.replace(\"\\n\", r\"\\n\").replace(\".:\", \".\").strip(\":\")\n clfnms[firstVoice] = (nm and 'nm=\"%s\"' % nm or \"\") + (\n snm and ' snm=\"%s\"' % snm or \"\"\n )\n hd = [\"X:%d\\n%s\\n\" % (self.X, self.title)]\n for i, k in enumerate(self.pagekeys):\n if self.javascript and k in [\n \"pageheight\",\n \"topmargin\",\n \"botmargin\",\n ]:\n continue\n if self.pageFmt[k] is not None:\n hd.append(\n \"%%%%%s %.2f%s\\n\"\n % (k, self.pageFmt[k], i > 0 and \"cm\" or \"\")\n )\n if staves and len(acc_staff) > 1:\n hd.append(\"%%score \" + staves + \"\\n\")\n tempo = (\n self.tempo\n and \"Q:%d/%d=%s\\n\"\n % (self.tempo_units[0], self.tempo_units[1], self.tempo)\n or \"\"\n ) # default no tempo field\n d = (\n {}\n ) # determine the most frequently occurring unit length over all voices\n for x in self.cmpL:\n d[x] = d.get(x, 0) + 1\n if self.javascript:\n defLs = sorted(d.items(), key=lambda x: (-x[1], x[0]))\n # when tie (1) sort on key (0)\n else:\n defLs = sorted(d.items(), key=lambda x: -x[1])\n defL = self.denL and self.denL or defLs[0][0]\n # override default unit length with -d option\n hd.append(\"L:1/%d\\n%sM:%s\\n\" % (defL, tempo, self.meter))\n hd.append(\"I:linebreak $\\nK:%s\\n\" % self.key)\n if self.stemless:\n hd.append(\"U:s=!stemless!\\n\")\n vxs = sorted(vmpdct.keys())\n for vx in vxs:\n hd.extend(vmpdct[vx])\n self.dojef = 0 # translate perc_map to voicemap\n for vnum, clef in self.clefs.items():\n ch, prg, vol, pan = list(midimap[vnum - 1])[:4]\n dmap = list(midimap[vnum - 1])[\n 4:\n ] # map of abc percussion notes to MIDI notes\n print(dmap)\n if dmap and \"perc\" not in clef:\n clef = (clef + \" map=perc\").strip()\n hd.append(\"V:%d %s %s\\n\" % (vnum, clef, clfnms.get(vnum, \"\")))\n if vnum in vmpdct:\n hd.append(\"%%%%voicemap tab%d\\n\" % vnum)\n hd.append(\n \"K:none\\nM:none\\n%%clef none\\n%%staffscale 1.6\\n%%flatbeams true\\n%%stemdir down\\n\"\n )\n if \"perc\" in clef:\n hd.append(\"K:none\\n\")\n # no key for a perc voice\n if self.vol_pan > 1:\n # option -m 2 -> output all recognized MIDI commands when needed and present in XML\n if ch > 0 and ch != vnum:\n hd.append(\"%%%%MIDI channel %d\\n\" % ch)\n if prg > 0:\n hd.append(\"%%%%MIDI program %d\\n\" % (prg - 1))\n if vol >= 0:\n hd.append(\"%%%%MIDI control 7 %.0f\\n\" % vol)\n # volume == 0 is possible ...\n if pan >= 0:\n hd.append(\"%%%%MIDI control 10 %.0f\\n\" % pan)\n elif self.vol_pan > 0:\n # default -> only output MIDI program command when present in XML\n if dmap and ch > 0:\n hd.append(\"%%%%MIDI channel %d\\n\" % ch)\n # also channel if percussion part\n if prg > 0:\n hd.append(\"%%%%MIDI program %d\\n\" % (prg - 1))\n for abcNote, step, midiNote, notehead in dmap:\n if not notehead:\n notehead = \"normal\"\n if abc_to_midi_pitch(abcNote) != midiNote or abcNote != step:\n if self.vol_pan > 0:\n hd.append(\n \"%%%%MIDI drummap %s %s\\n\" % (abcNote, midiNote)\n )\n hd.append(\n \"I:perc_map %s %s %s %s\\n\"\n % (abcNote, step, midiNote, notehead)\n )\n self.dojef = self.tstep\n if defL != self.cmpL[vnum - 1]:\n # only if computed unit length different from header\n hd.append(\"L:1/%d\\n\" % self.cmpL[vnum - 1])\n self.abc_out = hd + self.abc_out\n if heads: # output SVG stuff needed for tablature\n k1 = kob_svg.replace(\"-2\", \"-5\") if self.shift_stems else kob_svg\n # shift note heads 3 units left\n k2 = (\n kob_svg_2.replace(\"-2\", \"-5\")\n if self.shift_stems\n else kob_svg_2\n )\n tb = tab_svg.replace(\"-3\", \"-6\") if self.shift_stems else tab_svg\n ks = sorted(heads.keys()) # javascript compatibility\n ks = [k2 % (k, k) if len(k) == 2 else k1 % (k, k) for k in ks]\n tbs = list(map(lambda x: x.strip() + \"\\n\", tb.splitlines()))\n # javascript compatibility\n self.abc_out = tbs + ks + [\"\\n%%endsvg\\n\"] + self.abc_out\n\n def write_all(self):\n \"\"\"determine the required encoding of the entire ABC output\"\"\"\n string = \"\".join(self.abc_out)\n if self.dojef:\n string = perc2map(string)\n if python3:\n self.out_file.write(string)\n else:\n self.out_file.write(string.encode(\"utf-8\")) # type: ignore\n if self.out_path:\n self.out_file.close() # close each file with -o option\n else:\n self.out_file.write(\"\\n\") # add empty line between tunes on stdout\n info(\n \"%s written with %d voices\" % (self.name, len(self.clefs)),\n warn=False,\n )\n\n\n# ----------------\n# functions\n# ----------------\ndef abc_lyrics(lyrics: list[str], melisma: bool):\n \"\"\"Convert list xs to ABC lyrics.\"\"\"\n if not \"\".join(lyrics):\n return \"\", False # there is no lyrics in this measure\n res = []\n for (\n lyric\n ) in lyrics: # xs has for every note a lyrics syllable or an empty string\n if lyric == \"\": # note without lyrics\n if melisma:\n lyric = \"_\" # set melisma\n else:\n lyric = \"*\" # skip note\n elif lyric.endswith(\"_\") and not lyric.endswith(\n r\"\\_\"\n ): # start of new melisma\n lyric = lyric.replace(\"_\", \"\") # remove and set melisma boolean\n melisma = True # so next skips will become melisma\n else:\n melisma = False # melisma stops on first syllable\n res.append(lyric)\n return (\" \".join(res), melisma)\n\n\ndef simplify(a: int, b: int) -> Tuple[int, int]:\n \"\"\"Divide a and b by their greatest common divisor.\"\"\"\n x, y = a, b\n while b:\n a, b = b, a % b\n return x // a, y // a\n\n\ndef abc_duration(nx: Note, divs: int, unit_l: int) -> str:\n \"\"\"convert an MusicXML duration d to abc units with L:1/unit_l\"\"\"\n if nx.duration == 0:\n return \"\" # when called for elements without duration\n num, den = simplify(\n unit_l * nx.duration, divs * 4\n ) # L=1/8 -> unit_l = 8 units\n if nx.fact: # apply tuplet time modification\n numfac, denfac = nx.fact\n num, den = simplify(num * numfac, den * denfac)\n if den > 64: # limit the denominator to a maximum of 64\n x = float(num) / den\n n = math.floor(x)\n # when just above an integer n\n if x - n < 0.1 * x:\n num, den = n, 1\n # round to n\n num64 = 64.0 * num / den + 1.0e-15 # to get Python2 behaviour of round\n num, den = simplify(int(round(num64)), 64)\n if num == 1:\n if den == 1:\n dabc = \"\"\n elif den == 2:\n dabc = \"/\"\n else:\n dabc = \"/%d\" % den\n elif den == 1:\n dabc = \"%d\" % num\n else:\n dabc = \"%d/%d\" % (num, den)\n return dabc\n\n\ndef abc_to_midi_pitch(note: str) -> int:\n \"\"\"abc note -> MIDI pitch\"\"\"\n r = re.search(r\"([_^]*)([A-Ga-g])([',]*)\", note)\n if not r:\n return -1\n acc, note, octave = r.groups()\n nUp = n.upper()\n p = (\n 60\n + [0, 2, 4, 5, 7, 9, 11][\"CDEFGAB\".index(nUp)]\n + (12 if nUp != n else 0)\n )\n if acc:\n p += (1 if acc[0] == \"^\" else -1) * len(acc)\n if oct:\n p += (12 if octave[0] == \"'\" else -12) * len(octave)\n return p\n\n\ndef staff_step(ptc: str, octave: int, clef: str, tabStep: bool) -> str:\n ndif = 0\n if \"staff_lines=1\" in clef:\n ndif += 4 # meaning of one line: E (XML) -> B (ABC)\n if not tabStep and clef.startswith(\"bass\"):\n ndif += 12 # transpose bass -> treble (C3 -> A4)\n if ndif: # diatonic transposition == addition modulo 7\n nm7 = str(\"C,D,E,F,G,A,B\").split(\",\")\n n = nm7.index(ptc) + ndif\n ptc, o = nm7[n % 7], octave + n // 7\n if octave > 4:\n ptc = ptc.lower()\n if octave > 5:\n ptc = ptc + (octave - 5) * \"'\"\n if octave < 4:\n ptc = ptc + (4 - octave) * \",\"\n return ptc\n\n\ndef set_key(fifths: int, mode: str) -> dict[str, int]:\n sharpness = [\n \"Fb\",\n \"Cb\",\n \"Gb\",\n \"Db\",\n \"Ab\",\n \"Eb\",\n \"Bb\",\n \"F\",\n \"C\",\n \"G\",\n \"D\",\n \"A\",\n \"E\",\n \"B\",\n \"F#\",\n \"C#\",\n \"G#\",\n \"D#\",\n \"A#\",\n \"E#\",\n \"B#\",\n ]\n offTab = {\n \"maj\": 8,\n \"ion\": 8,\n \"m\": 11,\n \"min\": 11,\n \"aeo\": 11,\n \"mix\": 9,\n \"dor\": 10,\n \"phr\": 12,\n \"lyd\": 7,\n \"loc\": 13,\n \"non\": 8,\n }\n mode = mode.lower()[:3] # only first three chars, no case\n key = sharpness[offTab[mode] + fifths] + (\n mode if offTab[mode] != 8 else \"\"\n )\n accs = [\"F\", \"C\", \"G\", \"D\", \"A\", \"E\", \"B\"]\n if fifths >= 0:\n msralts = dict(zip(accs[:fifths], fifths * [1]))\n else:\n msralts = dict(zip(accs[fifths:], -fifths * [-1]))\n return key, msralts\n\n\ndef ins_tuplet(ix, notes, fact):\n \"\"\"read one nested tuplet\"\"\"\n tuplet_count = 0\n nx = notes[ix]\n if \"start\" in nx.tup:\n nx.tup.remove(\"start\") # do recursive calls when starts remain\n tix = ix # index of first tuplet note\n fn, fd = fact # XML time-mod of the higher level\n fnum, fden = nx.fact # XML time-mod of the current level\n tupfact = fnum // fn, fden // fd # ABC time mod of this level\n while ix < len(notes):\n nx = notes[ix]\n if isinstance(nx, Element) or nx.is_grace:\n ix += 1 # skip all non tuplet elements\n continue\n if len(nx.tup) > 1:\n print(nx.tup)\n if \"start\" in nx.tup: # more nested tuplets to start\n ix, tupcntR = ins_tuplet(\n ix, notes, tupfact\n ) # ix is on the stop note!\n tuplet_count += tupcntR\n elif nx.fact:\n tuplet_count += 1 # count tuplet elements\n if \"stop\" in nx.tup:\n nx.tup.remove(\"stop\")\n break\n if not nx.fact: # stop on first non tuplet note\n ix = lastix # back to last tuplet note\n break\n lastix = ix\n ix += 1\n # put ABC tuplet notation before the recursive ones\n tup = (tupfact[0], tupfact[1], tuplet_count)\n if tup == (3, 2, 3):\n tupPrefix = \"(3\"\n else:\n tupPrefix = \"(%d:%d:%d\" % tup\n notes[tix].tupabc = tupPrefix + notes[tix].tupabc\n return ix, tuplet_count # ix is on the last tuplet note\n\n\ndef make_broken(voice):\n \"\"\"introduce broken rhythms (voice: one voice, one measure)\"\"\"\n voice = [n for n in voice if isinstance(n, Note)]\n i = 0\n while i < len(voice) - 1:\n n1, n2 = voice[i], voice[i + 1] # scan all adjacent pairs\n # skip if note in tuplet or has no duration or outside beam\n if not n1.fact and not n2.fact and n1.duration > 0 and n2.beam:\n if n1.duration * 3 == n2.duration:\n n2.duration = (2 * n2.duration) // 3\n n1.duration = n1.duration * 2\n n1.after = \"<\" + n1.after\n i += 1 # do not chain broken rhythms\n elif n2.duration * 3 == n1.duration:\n n1.duration = (2 * n1.duration) // 3\n n2.duration = n2.duration * 2\n n1.after = \">\" + n1.after\n i += 1 # do not chain broken rhythms\n i += 1\n\n\ndef out_voice(measure, divs: int, im: int, ip: int, unit_l: int) -> str:\n \"\"\"note/element objects of one measure in one voice\"\"\"\n ix = 0\n while ix < len(measure): # set all (nested) tuplet annotations\n nx = measure[ix]\n if isinstance(nx, Note) and nx.fact and not nx.is_grace:\n ix, tup_count = ins_tuplet(\n ix, measure, (1, 1)\n ) # read one tuplet, insert annotation(s)\n ix += 1\n vs = []\n for nx in measure:\n if isinstance(nx, Note):\n dur_str = abc_duration(\n nx, divs, unit_l\n ) # XML -> ABC duration string\n is_chord = len(nx.notes) > 1\n cNotes = [nt[:-1] for nt in nx.notes if nt.endswith(\"-\")]\n tie = \"\"\n if is_chord and len(cNotes) == len(\n nx.notes\n ): # all chord notes tied\n nx.notes = cNotes # chord notes without tie\n tie = \"-\" # one tie for whole chord\n s = nx.tupabc + \"\".join(nx.before)\n if is_chord:\n s += \"[\"\n for nt in nx.notes:\n s += nt\n if is_chord:\n s += \"]\" + tie\n if s.endswith(\"-\"):\n s, tie = s[:-1], \"-\" # split off tie\n s += dur_str + tie # and put it back again\n s += nx.after\n nospace = nx.beam\n else:\n if isinstance(nx.string, listtype):\n nx.string = nx.string[0]\n s = nx.string\n nospace = 1\n if nospace:\n vs.append(s)\n else:\n vs.append(\" \" + s)\n vs = \"\".join(vs) # ad hoc: remove multiple pedal directions\n while vs.find(\"!ped!!ped!\") >= 0:\n vs = vs.replace(\"!ped!!ped!\", \"!ped!\")\n while vs.find(\"!ped-up!!ped-up!\") >= 0:\n vs = vs.replace(\"!ped-up!!ped-up!\", \"!ped-up!\")\n while vs.find(\"!8va(!!8va)!\") >= 0:\n vs = vs.replace(\"!8va(!!8va)!\", \"\") # remove empty ottava's\n return vs\n\n\ndef sort_measure(voice, measure):\n voice.sort(key=lambda o: o.time) # sort on time\n time = 0\n v = []\n rests = [] # holds rests in between notes\n for i, nx in enumerate(voice): # establish sequentiality\n if nx.time > time and check_bug(nx.time - time, measure):\n v.append(Note(nx.time - time, \"x\")) # fill hole with invisble rest\n rests.append(len(v) - 1)\n if isinstance(nx, Element):\n if nx.time < time:\n nx.time = (\n time # shift elems without duration to where they fit\n )\n v.append(nx)\n time = nx.time\n continue\n if nx.time < time: # overlapping element\n if nx.notes[0] == \"z\":\n continue # discard overlapping rest\n if v[-1].time <= nx.time: # we can do something\n if v[-1].notes[0] == \"z\": # shorten rest\n v[-1].duration = nx.time - v[-1].time\n if v[-1].duration == 0:\n del v[-1] # nothing left\n info(\n \"overlap in part %d, measure %d: rest shortened\"\n % (measure.ixp + 1, measure.ixm + 1)\n )\n else: # make a chord of overlap\n v[-1].notes += nx.notes\n info(\n \"overlap in part %d, measure %d: added chord\"\n % (measure.ixp + 1, measure.ixm + 1)\n )\n nx.duration = (nx.time + nx.duration) - time # the remains\n if nx.duration <= 0:\n continue # nothing left\n nx.time = time # append remains\n else: # give up\n info(\n \"overlapping notes in one voice! part %d, measure %d, note %s discarded\"\n % (\n measure.ixp + 1,\n measure.ixm + 1,\n isinstance(nx, Note) and nx.notes or nx.string,\n )\n )\n continue\n v.append(nx)\n if isinstance(nx, Note):\n if nx.notes[0] in \"zx\":\n rests.append(len(v) - 1) # remember rests between notes\n elif len(rests):\n if nx.beam and not nx.is_grace: # copy beam into rests\n for restI in rests:\n v[restI].beam = nx.beam\n rests = [] # clear rests on each note\n else:\n raise ValueError(\n f\"Object {nx} of type {type(nx)} isn't a note or element!\"\n )\n time = nx.time + nx.duration\n # when a measure contains no elements and no forwards -> no increment_time -> self.max_time = 0 -> right barline\n # is inserted at time == 0 (in addbar) and is only element in the voice when sort_measure is called\n if time == 0:\n info(\n \"empty measure in part %d, measure %d, it should contain at least a rest to advance the time!\"\n % (measure.ixp + 1, measure.ixm + 1)\n )\n return v\n\n\ndef get_part_list(parts):\n \"\"\"correct part-list (from buggy XML-software)\"\"\"\n xs = [] # the corrected part-list\n e = [] # stack of opened part-groups\n for x in list(parts): # insert missing stops, delete double starts\n if x.tag == \"part-group\":\n num, type = x.get(\"number\"), x.get(\"type\")\n if type == \"start\":\n if num in e: # missing stop: insert one\n xs.append(E.Element(\"part-group\", number=num, type=\"stop\"))\n xs.append(x)\n else: # normal start\n xs.append(x)\n e.append(num)\n else:\n if num in e: # normal stop\n e.remove(num)\n xs.append(x)\n else:\n pass # double stop: skip it\n else:\n xs.append(x)\n for num in reversed(e): # fill missing stops at the end\n xs.append(E.Element(\"part-group\", number=num, type=\"stop\"))\n return xs\n\n\ndef parse_parts(xs: list[E.Element], d: dict[str, list[str]], e):\n \"\"\"-> [elems on current level], rest of xs\"\"\"\n if not xs:\n return [], []\n x = xs.pop(0)\n if x.tag == \"part-group\":\n num, type = x.get(\"number\", \"-\"), x.get(\"type\")\n if type == \"start\": # go one level deeper\n s = [\n x.findtext(n, \"\")\n for n in [\n \"group-symbol\",\n \"group-barline\",\n \"group-name\",\n \"group-abbreviation\",\n ]\n ]\n d[num] = s # remember groupdata by group number\n e.append(num) # make stack of open group numbers\n elemsnext, rest1 = parse_parts(xs, d, e)\n # parse one level deeper to next stop\n elems, rest2 = parse_parts(rest1, d, e)\n # parse the rest on this level\n return [elemsnext] + elems, rest2\n else: # stop: close level and return group-data\n nums = e.pop() # last open group number in stack order\n if xs and xs[0].get(\"type\") == \"stop\": # two consequetive stops\n if num != nums: # in the wrong order (tempory solution)\n d[nums], d[num] = (d[num], d[nums])\n # exchange values (only works for two stops!!!)\n sym = d[num]\n # retrieve an return groupdata as last element of the group\n return [sym], xs\n else:\n elems, rest = parse_parts(xs, d, e)\n # parse remaining elements on current level\n name = x.findtext(\"part-name\", \"\"), x.findtext(\"part-abbreviation\", \"\")\n return [name] + elems, rest\n\n\ndef brace_part(part: list[list[int]]):\n \"\"\"Put a brace on multistaff part and group voices.\"\"\"\n if not part:\n return [] # empty part in the score\n brace = []\n for ivs in part:\n if len(ivs) == 1: # stave with one voice\n brace.append(str(ivs[0]))\n else: # stave with multiple voices\n brace += [\"(\", *list(map(str, ivs)), \")\"]\n brace.append(\"|\")\n del brace[-1] # no barline at the end\n if len(part) > 1:\n brace = [\"{\", *brace, \"}\"]\n return brace\n\n\ndef prgroupelem(x, gnm, bar, pmap, acc_voice, acc_staff):\n \"\"\"collect partnames (acc_voice) and %%score map (acc_staff)\"\"\"\n if type(x) == tupletype: # partname-tuple = (part-name, part-abbrev)\n y = pmap.pop(0)\n if gnm[0]:\n x = [n1 + \":\" + n2 for n1, n2 in zip(gnm, x)]\n # put group-name before part-name\n acc_voice.append(x)\n acc_staff.extend(brace_part(y))\n elif len(x) == 2 and type(x[0]) == tupletype:\n # misuse of group just to add extra name to stave\n y = pmap.pop(0)\n nms = [n1 + \":\" + n2 for n1, n2 in zip(x[0], x[1][2:])]\n # x[0] = partname-tuple, x[1][2:] = groupname-tuple\n acc_voice.append(nms)\n acc_staff.extend(brace_part(y))\n else:\n prgrouplist(x, bar, pmap, acc_voice, acc_staff)\n\n\ndef prgrouplist(x, pbar, pmap, acc_voice, acc_staff):\n \"\"\"Collect partnames, scoremap for a part-group.\"\"\"\n sym, bar, gnm, gabbr = x[\n -1\n ] # bracket symbol, continue barline, group-name-tuple\n bar = bar == \"yes\" or pbar # pbar -> the parent has bar\n acc_staff.append(sym == \"brace\" and \"{\" or \"[\")\n for z in x[:-1]:\n prgroupelem(z, (gnm, gabbr), bar, pmap, acc_voice, acc_staff)\n if bar:\n acc_staff.append(\"|\")\n if bar:\n del acc_staff[-1] # remove last one before close\n acc_staff.append(sym == \"brace\" and \"}\" or \"]\")\n\n\ndef compute_unit_length(iv: int, measures, divs) -> int:\n \"\"\"Compute optimal unit length.\"\"\"\n uLmin, min_len = 0, max_int\n for unit_l in [4, 8, 16]: # try 1/4, 1/8 and 1/16\n vLen = 0 # total length of ABC duration strings in this voice\n for im, measure in enumerate(measures): # all measures\n for e in measure[iv]: # all notes in voice iv\n if isinstance(e, Element) or e.duration == 0:\n continue # no real durations\n vLen += len(abc_duration(e, divs[im], unit_l))\n # add len of duration string\n if vLen < min_len:\n uLmin, min_len = unit_l, vLen # remember the smallest\n return uLmin\n\n\ndef do_syllable(syl: E.Element) -> str:\n text = \"\"\n for e in syl:\n if e.tag == \"elision\":\n text += \"~\"\n elif e.tag == \"text\": # escape - and space characters\n text += (\n (e.text or \"\")\n .replace(\"_\", r\"\\_\")\n .replace(\"-\", r\"\\-\")\n .replace(\" \", \"~\")\n )\n if not text:\n return text\n if syl.findtext(\"syllabic\") in [\"begin\", \"middle\"]:\n text += \"-\"\n if syl.find(\"extend\") is not None:\n text += \"_\"\n return text\n\n\ndef check_melismas(lyrics, measures, im: int, iv: int):\n if im == 0:\n return\n measure = measures[im][iv] # notes of the current measure\n cur_lyric = lyrics[im][iv] # lyrics dict of current measure\n prv_lyric = lyrics[im - 1][iv] # lyrics dict of previous measure\n for n, (lyric_str, melisma) in prv_lyric.items():\n # all lyric numbers in the previous measure\n if n not in cur_lyric and melisma:\n # melisma required, but no lyrics present -> make one!\n ms = get_melisma(measure) # get a melisma for the current measure\n if ms:\n cur_lyric[n] = (ms, 0)\n # set melisma as the n-th lyrics of the current measure\n\n\ndef get_melisma(measure):\n \"\"\"Get melisma from notes in measure.\"\"\"\n ms = []\n for note in measure: # every note should get an underscore\n if not isinstance(note, Note):\n continue # skip Elements\n if note.is_grace:\n continue # skip grace notes\n if note.notes[0] in \"zx\":\n break # stop on first rest\n ms.append(\"_\")\n return \" \".join(ms)\n\n\ndef perc2map(abc_in):\n fillmap = {\"diamond\": 1, \"triangle\": 1, \"square\": 1, \"normal\": 1}\n abc = list(map(lambda x: x.strip(), perc_svg.splitlines()))\n id = \"default\"\n maps = {\"default\": []}\n dmaps = {\"default\": []}\n r1 = re.compile(r\"V:\\s*(\\S+)\")\n lines = abc_in.splitlines()\n for x in lines:\n if \"I:perc_map\" in x:\n noot, step, midi, head = map(lambda x: x.strip(), x.split()[1:])\n if head in fillmap:\n head = head + \"+\" + \",\" + head\n x = \"%%%%map perc%s %s print=%s midi=%s heads=%s\" % (\n id,\n noot,\n step,\n midi,\n head,\n )\n maps[id].append(x)\n if \"%%MIDI\" in x:\n dmaps[id].append(x)\n if \"V:\" in x:\n r = r1.match(x)\n if r:\n id = r.group(1)\n if id not in maps:\n maps[id] = []\n dmaps[id] = []\n ids = sorted(maps.keys())\n for id in ids:\n abc += maps[id]\n id = \"default\"\n for x in lines:\n if \"I:perc_map\" in x:\n continue\n if \"%%MIDI\" in x:\n continue\n if \"V:\" in x or \"K:\" in x:\n r = r1.match(x)\n if r:\n id = r.group(1)\n abc.append(x)\n if id in dmaps and len(dmaps[id]) > 0:\n abc.extend(dmaps[id])\n del dmaps[id]\n if \"perc\" in x and \"map=\" not in x:\n x += \" map=perc\"\n if \"map=perc\" in x and len(maps[id]) > 0:\n abc.append(\"%%voicemap perc\" + id)\n if \"map=off\" in x:\n abc.append(\"%%voicemap\")\n else:\n abc.append(x)\n return \"\\n\".join(abc) + \"\\n\"\n\n\ndef add_octave(ptc: str, octave: int) -> str:\n \"\"\"XML staff step, XML octave number\"\"\"\n p = ptc\n if octave > 4:\n p = ptc.lower()\n if octave > 5:\n p = p + (octave - 5) * \"'\"\n if octave < 4:\n p = p + (4 - octave) * \",\"\n return p # ABC pitch == ABC note without accidental\n\n\ndef check_bug(dt, measure):\n if dt > measure.divs / 16:\n return True # duration should be > 1/64 note\n info(\n \"MuseScore bug: incorrect duration, smaller then 1/64! in measure %d, part %d\"\n % (measure.ixm, measure.ixp)\n )\n return False\n\n\n# ----------------\n# parser\n# ----------------\nclass Parser:\n note_alts = [ # 3 alternative notations of the same note for tablature mapping\n [\n x.strip()\n for x in \"=C, ^C, =D, ^D, =E, =F, ^F, =G, ^G, =A, ^A, =B\".split(\n \",\"\n )\n ],\n [\n x.strip()\n for x in \"^B, _D,^^C, _E, _F, ^E, _G,^^F, _A,^^G, _B, _C\".split(\n \",\"\n )\n ],\n [\n x.strip()\n for x in \"__D,^^B,__E,__F,^^D,__G,^^E,__A,_/A,__B,__C,^^A\".split(\n \",\"\n )\n ],\n ]\n step_map = {\"C\": 0, \"D\": 2, \"E\": 4, \"F\": 5, \"G\": 7, \"A\": 9, \"B\": 11}\n slur_buffer: dict[str, Tuple[str, int, Note, bool]]\n \"\"\"dict of open slurs keyed by slur number\"\"\"\n dirStk: dict[str, Tuple]\n \"\"\"{direction-type + number -> (type, voice | time)} dict for proper closing\"\"\"\n is_in_grace: bool\n \"\"\"marks a sequence of grace notes\"\"\"\n music: Music\n \"\"\"global music data abstraction\"\"\"\n unfold: bool\n \"\"\"turn unfolding repeats on\"\"\"\n ctf: int\n \"\"\"credit text filter level\"\"\"\n g_staff_map: list[list[int]]\n \"\"\"[[ABC voice numbers] for all parts]\"\"\"\n midi_map: list[int]\n \"\"\"MIDI-settings for each ABC voice, in order\"\"\"\n drum_instr: dict[str, int]\n \"\"\"instr_id -> MIDI pitch for channel 10 notes\"\"\"\n drum_notes: dict\n \"\"\"(XML voice, ABC note) -> (MIDI note, note head)\"\"\"\n instr_midis: list[dict[str, list[int]]]\n \"\"\"[{instr id -> MIDI-settings} for all parts]\"\"\"\n midi_defaults: list[int]\n \"\"\"default MIDI settings for channel, program, volume, panning\"\"\"\n\n def __init__(self, options):\n \"\"\"unfold repeats, number of chars per line, credit filter level, volta option\"\"\"\n self.slur_buffer = {}\n self.dirStk = {}\n self.is_in_grace = False\n self.music = Music(options)\n self.unfold = options.u\n self.ctf = options.c\n self.g_staff_map = []\n self.midi_map = []\n self.drum_instr = {}\n self.drum_notes = {}\n self.instr_midis = []\n self.midi_defaults = [-1, -1, -1, -91]\n self.msralts = {}\n \"\"\"ml-notenames (without octave) with accidentals from the key\"\"\"\n self.cur_alts = {}\n \"\"\"abc-notenames (with voice number) with passing accidentals\"\"\"\n self.staff_map = {}\n \"\"\"XML staff number -> [XML voice number]\"\"\"\n self.voice2staff = {}\n \"\"\"XML voice number -> allocated staff number\"\"\"\n self.clef_map = {}\n \"\"\"XML staff number -> ABC clef (for header only)\"\"\"\n self.cur_clefs = {}\n \"\"\"XML staff number -> current ABC clef\"\"\"\n self.stem_dirs = {}\n \"\"\"XML voice number -> current stem direction\"\"\"\n self.clef_octaves = {}\n \"\"\"XML staff number -> current clef-octave-change\"\"\"\n self.cur_staffs = {}\n \"\"\"XML voice number -> current XML staff number\"\"\"\n self.nolbrk = options.x\n \"\"\"generate no linebreaks ($)\"\"\"\n self.javascript = options.j\n \"\"\"compatibility with javascript version\"\"\"\n self.ornaments = sorted(note_ornamentation_map.items())\n self.format_page = len(options.p) == 1\n \"\"\"translate XML page format\"\"\"\n self.tstep = options.t\n \"\"\"clef determines step on staff (percussion)\"\"\"\n self.dirtov1 = options.v1 #\n \"\"\"all directions to first voice of staff\"\"\"\n self.render_pedal_dirs = options.ped\n \"\"\"render pedal directions\"\"\"\n self.write_stems = options.stm\n \"\"\"translate stem elements\"\"\"\n self.pedal_dir_voice = None\n \"\"\"voice for pedal directions\"\"\"\n self.repeat_str = {}\n \"\"\"staff number -> [measure number, repeat-text]\"\"\"\n self.tab_voice_map = {}\n \"\"\"ABC voice num -> [%%map ...] for tab voices\"\"\"\n self.heads = {}\n \"\"\"noteheads needed for %%map\"\"\"\n\n def match_slur(\n self,\n type2: str,\n num: Optional[str],\n voice2: int,\n note2: Note,\n is_grace: bool,\n stop_grace: bool,\n ) -> None:\n \"\"\"Match slur number n in voice v2, add ABC code to before/after.\"\"\"\n if type2 not in [\"start\", \"stop\"]:\n return # slur type continue has no ABC equivalent\n if num is None:\n num = \"1\"\n if num in self.slur_buffer:\n type1, voice1, note1, grace1 = self.slur_buffer[n]\n if type2 != type1: # slur complete, now check the voice\n if (\n voice2 == voice1\n ): # begins and ends in the same voice: keep it\n if type1 == \"start\" and (not grace1 or not stop_grace):\n # normal slur: start before stop and no grace slur\n note1.before = [\n \"(\"\n ] + note1.before # keep left-right order!\n note2.after += \")\"\n # no else: don't bother with reversed stave spanning slurs\n del self.slur_buffer[n] # slur finished, remove from stack\n else: # double definition, keep the last\n info(\n \"double slur numbers %s-%s in part %d, measure %d, voice %d note %s, first discarded\"\n % (\n type2,\n n,\n self.measure.ixp + 1,\n self.measure.ixm + 1,\n voice2,\n note2.notes,\n )\n )\n self.slur_buffer[n] = (type2, voice2, note2, is_grace)\n else: # unmatched slur, put in dict\n self.slur_buffer[n] = (type2, voice2, note2, is_grace)\n\n def do_notations(self, note: Note, notation: E.Element, is_tab: bool):\n for key, val in self.ornaments:\n if notation.find(key) is not None:\n note.before += [val] # just concat all ornaments\n tremolo = notation.find(\"ornaments/tremolo\")\n if tremolo is not None:\n type = tremolo.get(\"type\")\n if type == \"single\":\n note.before.insert(0, \"!%s!\" % (int(tremolo.text) * \"/\"))\n else:\n note.fact = None # no time modification in ABC\n if self.tstep: # abc2svg version\n if type == \"stop\":\n note.before.insert(0, \"!trem%s!\" % tremolo.text)\n else: # abc2xml version\n if type == \"start\":\n note.before.insert(\n 0, \"!%s-!\" % (int(tremolo.text) * \"/\")\n )\n fingering = notation.findall(\"technical/fingering\")\n if is_tab:\n string = notation.find(\"technical/string\")\n if string is not None:\n if self.tstep:\n fret = notation.find(\"technical/fret\")\n if fret is not None:\n note.tab = (string.text, fret.text)\n else:\n deco = (\n \"!%s!\" % string.text\n ) # no double string decos (bug in musescore)\n if deco not in note.ntdec:\n note.ntdec += deco\n else:\n for finger in fingering: # handle multiple finger annotations\n note.before += [\"!%s!\" % finger.text]\n # fingering goes before chord (add_chord)\n\n wvln = notation.find(\"ornaments/wavy-line\")\n if wvln is not None:\n if wvln.get(\"type\") == \"start\":\n note.before = [\n \"!trill(!\"\n ] + note.before # keep left-right order!\n elif wvln.get(\"type\") == \"stop\":\n note.before = [\"!trill)!\"] + note.before\n glis = notation.find(\"glissando\")\n if glis is None:\n glis = notation.find(\"slide\") # treat slide as glissando\n if glis is not None:\n lt = \"~\" if glis.get(\"line-type\") == \"wavy\" else \"-\"\n if glis.get(\"type\") == \"start\":\n note.before = [\n \"!%s(!\" % lt\n ] + note.before # keep left-right order!\n elif glis.get(\"type\") == \"stop\":\n note.before = [\"!%s)!\" % lt] + note.before\n\n def tab_note(\n self, alt: int, ptc: str, octave: int, voice: int, ntrec: Note\n ):\n p = self.step_map[ptc] + alt # p in -2 .. 13\n if p > 11:\n octave += 1 # octave correction\n elif p < 0:\n octave -= 1\n p = p % 12 # remap p into 0..11\n (\n snaar_nw,\n fret_nw,\n ) = ntrec.tab # the computed/annotated allocation of nt\n for i in range(4): # support same note on 4 strings\n na = self.note_alts[i][\n p\n ] # get alternative representation of same note\n o = octave\n if na in [\"^B\", \"^^B\"]:\n o -= 1 # because in adjacent octave\n if na in [\"_C\", \"__C\"]:\n o += 1\n if \"/\" in na or i == 3:\n o = 9 # emergency notation for 4th string case\n nt = add_octave(na, o)\n string, fret = self.tab_map.get((voice, nt), (\"\", \"\"))\n # the current allocation of nt\n if not string:\n break # note not yet allocated\n if snaar_nw == string:\n return nt # use present allocation\n if i == 3: # new allocaion needed but none is free\n fmt = \"rejected: voice %d note %3s string %s fret %2s remains: string %s fret %s\"\n info(fmt % (voice, nt, snaar_nw, fret_nw, string, fret), True)\n ntrec.tab = (string, fret)\n self.tab_map[voice, nt] = ntrec.tab\n # for tablature map (voice, note) -> (string, fret)\n return nt # ABC code always in key C (with MIDI pitch alterations)\n\n def abc_notation(\n self,\n ptc: str,\n octave: int,\n note: E.Element,\n voice: int,\n ntrec: Note,\n is_tab: bool,\n ) -> str:\n \"\"\"pitch, octave -> ABC notation\"\"\"\n acc2alt = {\n \"double-flat\": -2,\n \"flat-flat\": -2,\n \"flat\": -1,\n \"natural\": 0,\n \"sharp\": 1,\n \"sharp-sharp\": 2,\n \"double-sharp\": 2,\n }\n octave += self.clef_octaves.get(self.cur_staffs[voice], 0)\n # minus clef-octave-change value\n acc = note.findtext(\"accidental\") # should be the notated accidental\n alter = note.findtext(\"pitch/alter\") # pitch alteration (MIDI)\n if ntrec.tab:\n return self.tab_note(int(alter or \"0\"), ptc, octave, voice, ntrec)\n # implies self.tstep is true (options.t was given)\n elif is_tab and self.tstep:\n nt = [\"__\", \"_\", \"\", \"^\", \"^^\"][\n int(alter or \"0\") + 2\n ] + add_octave(ptc, octave)\n info(\n \"no string notation found for note %s in voice %d\"\n % (nt, voice),\n True,\n )\n p = add_octave(ptc, octave)\n if alter is None:\n if acc is None:\n return p # no acc, no alt\n if self.msralts.get(ptc, 0):\n alt = 0 # no alt but key implies alt -> natural!!\n if (p, voice) in self.cur_alts:\n alt = 0 # no alt but previous note had one -> natural!!\n elif acc is not None:\n alt = acc2alt[acc] # acc takes precedence over the pitch here!\n else: # now see if we really must add an accidental\n alt = int(float(alter))\n if (p, voice) in self.cur_alts:\n # the note in this voice has been altered before\n if alt == self.cur_alts[(p, voice)]:\n return p # alteration still the same\n elif alt == self.msralts.get(ptc, 0):\n return p # alteration implied by the key\n tieElms = note.findall(\"tie\") + note.findall(\"notations/tied\")\n # in XML we have separate notated ties and playback ties\n if \"stop\" in [e.get(\"type\") for e in tieElms]:\n return p # don't alter tied notes\n info(\n \"accidental %d added in part %d, measure %d, voice %d note %s\"\n % (\n alt,\n self.measure.ixp + 1,\n self.measure.ixm + 1,\n voice + 1,\n p,\n )\n )\n self.cur_alts[(p, voice)] = alt\n p = [\"__\", \"_\", \"=\", \"^\", \"^^\"][alt + 2] + p\n # and finally ... prepend the accidental\n return p\n\n def parse_note(self, n: E.Element):\n \"\"\"parse a musicXML note tag\"\"\"\n note = Note()\n voice = int(n.findtext(\"voice\", \"1\"))\n if self.is_sib:\n voice += 100 * int(\n n.findtext(\"staff\", \"1\")\n ) # repair bug in Sibelius\n is_chord = n.find(\"chord\") is not None\n p = n.findtext(\"pitch/step\") or n.findtext(\"unpitched/display-step\")\n o = n.findtext(\"pitch/octave\") or n.findtext(\n \"unpitched/display-octave\"\n )\n r = n.find(\"rest\")\n numer = n.findtext(\"time-modification/actual-notes\")\n if numer:\n denom = n.findtext(\"time-modification/normal-notes\", \"-\")\n note.fact = (int(numer), int(denom))\n note.tup = [x.get(\"type\") for x in n.findall(\"notations/tuplet\")]\n duration = n.findtext(\"duration\")\n grace = n.find(\"grace\")\n note.is_grace = grace is not None\n note.before, note.after = ([], \"\")\n # strings with ABC stuff that goes before or after a note/chord\n if grace is not None and not self.is_in_grace: # open a grace sequence\n self.is_in_grace = True\n note.before = [\"{\"]\n if grace.get(\"slash\") == \"yes\":\n note.before += [\"/\"] # acciaccatura\n stop_grace = not note.is_grace and self.is_in_grace\n if stop_grace: # close the grace sequence\n self.is_in_grace = False\n self.music.last_note.after += \"}\" # close grace on lastenote.after\n if duration is None or note.is_grace:\n duration = 0\n if r is None and n.get(\"print-object\") == \"no\":\n if is_chord:\n return\n r = 1 # turn invisible notes (that advance the time) into invisible rests\n note.duration = int(duration)\n if r is None and (not p or not o): # not a rest and no pitch\n self.music.counter.increment(\n \"nopt\", voice\n ) # count unpitched notes\n o, p = 5, \"E\" # make it an E5 ??\n is_tab = bool(self.cur_clefs) and self.cur_clefs.get(\n self.cur_staffs[voice], \"\"\n ).startswith(\"tab\")\n notation = n.find(\"notations\") # add ornaments\n if notation is not None:\n self.do_notations(note, notation, is_tab)\n stem = (\n n.find(\"stem\") if r is None else None\n ) # no !stemless! before rest\n if (\n stem is not None\n and stem.text == \"none\"\n and (not is_tab or voice in self.has_stems or self.tstep)\n ):\n note.before += [\"s\"]\n abc_out.stemless = True\n accidental = n.find(\"accidental\")\n if accidental is not None and accidental.get(\"parentheses\") == \"yes\":\n note.ntdec += \"!courtesy!\"\n if r is not None:\n noot = \"x\" if n.get(\"print-object\") == \"no\" or is_tab else \"z\"\n else:\n noot = self.abc_notation(p, int(o), n, voice, note, is_tab)\n if n.find(\"unpitched\") is not None:\n clef = self.cur_clefs[self.cur_staffs[voice]]\n # the current clef for this voice\n step = staff_step(p, int(o), clef, self.tstep)\n # (clef independent) step value of note on the staff\n instr = n.find(\"instrument\")\n instr_id = instr.get(\"id\") if instr is not None else \"dummyId\"\n midi = self.drum_instr.get(instr_id, abc_to_midi_pitch(noot))\n nh = n.findtext(\"notehead\", \"\").replace(\" \", \"-\")\n # replace spaces in XML notehead names for perc_map\n if nh == \"x\":\n noot = \"^\" + noot.replace(\"^\", \"\").replace(\"_\", \"\")\n if nh in [\"circle-x\", \"diamond\", \"triangle\"]:\n noot = \"_\" + noot.replace(\"^\", \"\").replace(\"_\", \"\")\n if nh and n.find(\"notehead\").get(\"filled\", \"\") == \"yes\":\n nh += \"+\"\n if nh and n.find(\"notehead\").get(\"filled\", \"\") == \"no\":\n nh += \"-\"\n self.drum_notes[(voice, noot)] = (step, midi, nh)\n # keep data for percussion map\n tieElms = n.findall(\"tie\") + n.findall(\"notations/tied\")\n # in XML we have separate notated ties and playback ties\n if \"start\" in [\n e.get(\"type\") for e in tieElms\n ]: # n can have stop and start tie\n noot = noot + \"-\"\n note.beam = sum(\n [1 for b in n.findall(\"beam\") if b.text in [\"continue\", \"end\"]]\n ) + int(note.is_grace)\n lyrlast = 0\n rsib = re.compile(r\"^.*verse\")\n for e in n.findall(\"lyric\"):\n lyrnum = int(\n rsib.sub(\"\", e.get(\"number\", \"1\"))\n ) # also do Sibelius numbers\n if lyrnum == 0:\n lyrnum = lyrlast + 1 # and correct Sibelius bugs\n else:\n lyrlast = lyrnum\n note.lyrics[lyrnum] = do_syllable(e)\n stem_dir = n.findtext(\"stem\")\n if self.write_stems and stem_dir in [\"up\", \"down\"]:\n if stem_dir != self.stem_dirs.get(voice, \"\"):\n self.stem_dirs[voice] = stem_dir\n self.music.append_element(voice, f\"[I:stemdir {stem_dir}]\")\n if is_chord:\n self.music.add_chord(note, noot)\n else:\n xmlstaff = int(n.findtext(\"staff\", \"1\"))\n if self.cur_staffs[voice] != xmlstaff:\n # the note should go to another staff\n dstaff = xmlstaff - self.cur_staffs[voice]\n # relative new staff number\n self.cur_staffs[voice] = xmlstaff\n # remember the new staff for this voice\n self.music.append_element(voice, \"[I:staff %+d]\" % dstaff)\n # insert a move before the note\n self.music.append_note(voice, note, noot)\n for slur in n.findall(\"notations/slur\"):\n # self.music.last_note points to the last real note/chord inserted above\n slur.text\n self.match_slur(\n slur.get(\"type\"),\n slur.get(\"number\"),\n voice,\n self.music.last_note,\n note.is_grace,\n stop_grace,\n ) # match slur definitions\n\n def parse_attr(self, e: E.Element):\n \"\"\"Parse a musicXML attribute tag.\"\"\"\n signs = {\n \"C1\": \"alto1\",\n \"C2\": \"alto2\",\n \"C3\": \"alto\",\n \"C4\": \"tenor\",\n \"F4\": \"bass\",\n \"F3\": \"bass3\",\n \"G2\": \"treble\",\n \"TAB\": \"tab\",\n \"percussion\": \"perc\",\n }\n dvstxt = e.findtext(\"divisions\")\n if dvstxt:\n self.measure.divs = int(dvstxt)\n steps = int(e.findtext(\"transpose/chromatic\", \"0\"))\n # for transposing instrument\n fifths = e.findtext(\"key/fifths\")\n first = self.music.time == 0 and self.measure.ixm == 0\n # first attributes in first measure\n if fifths:\n key, self.msralts = set_key(\n int(fifths), e.findtext(\"key/mode\", \"major\")\n )\n if first and not steps and abc_out.key == \"none\":\n abc_out.key = key # first measure -> header, if not transposing instrument or percussion part!\n elif key != abc_out.key or not first:\n self.measure.attr += f\"[K:{key}]\" # otherwise -> voice\n beats = e.findtext(\"time/beats\")\n if beats:\n unit = e.findtext(\"time/beat-type\")\n meter = beats + \"/\" + unit\n if first:\n abc_out.meter = meter # first measure -> header\n else:\n self.measure.attr += f\"[M:{meter}]\" # otherwise -> voice\n self.measure.meter = int(beats), int(unit)\n self.measure.measure_duration = (\n self.measure.divs * self.measure.meter[0] * 4\n ) // self.measure.meter[1]\n # duration of measure in XML-divisions\n for measure_style in e.findall(\"measure-style\"):\n n = int(measure_style.get(\"number\", \"1\")) # staff number\n voices = self.staff_map[n] # all voices of staff n\n for measure_repeat in measure_style.findall(\"measure-repeat\"):\n ty = measure_repeat.get(\"type\")\n if ty == \"start\":\n # remember start measure number and text voor each staff\n self.repeat_str[n] = [\n self.measure.ixm,\n measure_repeat.text,\n ]\n for voice in voices:\n # insert repeat into all voices, value will be overwritten at stop\n self.music.insert_element(voice, self.repeat_str[n])\n elif (\n ty == \"stop\"\n ): # calculate repeat measure count for this staff n\n start_ix, text_ = self.repeat_str[n]\n repeat_count = self.measure.ixm - start_ix\n if text_:\n mid_str = f\"{text_} \"\n repeat_count /= int(text_)\n else:\n mid_str = \"\" # overwrite repeat with final string\n self.repeat_str[n][\n 0\n ] = f\"[I:repeat {mid_str}{repeat_count}]\"\n del self.repeat_str[n] # remove closed repeats\n toct = e.findtext(\"transpose/octave-change\", \"\")\n if toct:\n steps += 12 * int(toct) # extra transposition of toct octaves\n for clef in e.findall(\"clef\"): # a part can have multiple staves\n n = int(\n clef.get(\"number\", \"1\")\n ) # local staff number for this clef\n sign = clef.findtext(\"sign\")\n line = (\n clef.findtext(\"line\", \"\")\n if sign not in [\"percussion\", \"TAB\"]\n else \"\"\n )\n cs = signs.get(sign + line, \"\")\n oct = clef.findtext(\"clef-octave-change\") or \"0\"\n if oct:\n cs += {-2: \"-15\", -1: \"-8\", 1: \"+8\", 2: \"+15\"}.get(\n int(oct), \"\"\n )\n self.clef_octaves[n] = -int(oct)\n # XML playback pitch -> ABC notation pitch\n if steps:\n cs += \" transpose=\" + str(steps)\n staff_details = e.find(\"staff-details\")\n if staff_details and int(staff_details.get(\"number\", \"1\")) == n:\n lines = staff_details.findtext(\"staff-lines\")\n if lines:\n lns = \"|||\" if lines == \"3\" and sign == \"TAB\" else lines\n cs += f\" staff_lines={lns}\"\n self.staff_lines = int(lines) # remember for tab staves\n strings = staff_details.findall(\"staff-tuning\")\n if strings:\n tuning = [\n st.findtext(\"tuning-step\")\n + st.findtext(\"tuning-octave\")\n for st in strings\n ]\n cs += f\" strings={','.join(tuning)}\"\n capo = staff_details.findtext(\"capo\")\n if capo:\n cs += f\" capo={capo}\"\n self.cur_clefs[n] = cs # keep track of current clef (for perc_map)\n if first:\n self.clef_map[n] = cs\n # clef goes to header (where it is mapped to voices)\n else:\n voices = self.staff_map[\n n\n ] # clef change to all voices of staff n\n for voice in voices:\n if (\n n != self.cur_staffs[voice]\n ): # voice is not at its home staff n\n dstaff = n - self.cur_staffs[voice]\n self.cur_staffs[voice] = n\n # reset current staff at start of measure to home position\n self.music.append_element(voice, f\"[I:staff {dstaff}]\")\n self.music.append_element(voice, f\"[K:{cs}]\")\n\n def find_voice(self, i: int, es: list[E.Element]):\n staff_num = int(\n es[i].findtext(\"staff\", 1)\n ) # directions belong to a staff\n voices = self.staff_map[staff_num] # voices in this staff\n v1 = voices[0] if voices else 1 # directions to first voice of staff\n if self.dirtov1:\n return staff_num, v1, v1 # option --v1\n for e in es[i + 1 :]: # or to the voice of the next note\n if e.tag == \"note\":\n voice = int(e.findtext(\"voice\", \"1\"))\n if self.is_sib:\n voice += 100 * int(e.findtext(\"staff\", \"1\"))\n # repair bug in Sibelius\n stf = self.voice2staff[voice] # use our own staff allocation\n return (\n stf,\n voice,\n v1,\n ) # voice of next note, first voice of staff\n if e.tag == \"backup\":\n break\n return staff_num, v1, v1 # no note found, fall back to v1\n\n def do_direction(self, e: E.Element, i: int, es: list[E.Element]):\n \"\"\"parse a musicXML direction tag\"\"\"\n\n def add_direction(x, v: int, time, staff_num: int):\n if not x:\n return\n vs = self.staff_map[staff_num] if \"!8v\" in x else [v]\n # ottava's go to all voices of staff\n for voice in vs:\n if time is not None: # insert at time of encounter\n self.music.append_element_at_time(\n voice,\n x.replace(\"(\", \")\").replace(\"ped\", \"ped-up\"),\n time,\n )\n else:\n self.music.append_element(voice, x)\n\n def start_stop(dtype: str, v: int, staff_num=1):\n typmap = {\n \"down\": \"!8va(!\",\n \"up\": \"!8vb(!\",\n \"crescendo\": \"!<(!\",\n \"diminuendo\": \"!>(!\",\n \"start\": \"!ped!\",\n }\n type = t.get(\"type\", \"\")\n k = dtype + t.get(\"number\", \"1\")\n # key to match the closing direction\n if type in typmap: # opening the direction\n x = typmap[type]\n if k in self.dirStk: # closing direction already encountered\n stype, time = self.dirStk[k]\n del self.dirStk[k]\n if stype == \"stop\":\n add_direction(x, v, time, staff_num)\n else:\n info(\n \"%s direction %s has no stop in part %d, measure %d, voice %d\"\n % (\n dtype,\n stype,\n self.measure.ixp + 1,\n self.measure.ixm + 1,\n v + 1,\n )\n )\n self.dirStk[k] = (type, v)\n # remember voice and type for closing\n else:\n self.dirStk[k] = (type, v)\n # remember voice and type for closing\n elif type == \"stop\":\n if k in self.dirStk: # matching open direction found\n type, vs = self.dirStk[k]\n del self.dirStk[k] # into the same voice\n if type == \"stop\":\n info(\n \"%s direction %s has double stop in part %d, measure %d, voice %d\"\n % (\n dtype,\n type,\n self.measure.ixp + 1,\n self.measure.ixm + 1,\n vs + 1,\n )\n )\n x = \"\"\n else:\n x = (\n typmap[type]\n .replace(\"(\", \")\")\n .replace(\"ped\", \"ped-up\")\n )\n else: # closing direction found before opening\n self.dirStk[k] = (\"stop\", self.music.time)\n x = \"\" # delay code generation until opening found\n else:\n raise ValueError(\"wrong direction type\")\n add_direction(x, v, None, staff_num)\n\n tempo, words_text = None, \"\"\n placement = e.get(\"placement\")\n stf, vs, v1 = self.find_voice(i, es)\n jmp = \"\" # for jump sound elements: dacapo, dalsegno and family\n jmps = [\n (\"dacapo\", \"D.C.\"),\n (\"dalsegno\", \"D.S.\"),\n (\"tocoda\", \"dacoda\"),\n (\"fine\", \"fine\"),\n (\"coda\", \"O\"),\n (\"segno\", \"S\"),\n ]\n t = e.find(\"sound\") # there are many possible attributes for sound\n if t is not None:\n minst = t.find(\"midi-instrument\")\n if minst:\n prg = minst.findtext(\"midi-instrument/midi-program\")\n chn = minst.findtext(\"midi-instrument/midi-channel\")\n vids = [\n voice\n for voice, id in self.voice_instrument.items()\n if id == minst.get(\"id\")\n ]\n if vids:\n vs = vids[0]\n # direction for the indentified voice, not the staff\n if abc_out.vol_pan > 0:\n parm, instr = (\n (\"program\", str(int(prg) - 1))\n if prg\n else (\"channel\", chn)\n )\n if instr:\n self.music.append_element(\n vs, f\"[I:MIDI= {parm} {instr}]\"\n )\n tempo = t.get(\"tempo\") # look for tempo attribute\n if tempo:\n tempo = \"%.0f\" % float(tempo)\n # hope it is a number and insert in voice 1\n tempo_units = (1, 4) # always 1/4 for sound elements!\n for r, v in jmps:\n if t.get(r, \"\"):\n jmp = v\n break\n for dir_type in e.findall(\"direction-type\"):\n units: dict[str, Tuple[int, int]] = {\n \"whole\": (1, 1),\n \"half\": (1, 2),\n \"quarter\": (1, 4),\n \"eighth\": (1, 8),\n }\n metr = dir_type.find(\"metronome\")\n if metr is not None:\n t = metr.findtext(\"beat-unit\", \"\")\n if t in units:\n tempo_units = units[t]\n else:\n tempo_units = units[\"quarter\"]\n if metr.find(\"beat-unit-dot\") is not None:\n tempo_units = simplify(\n tempo_units[0] * 3, tempo_units[1] * 2\n )\n tmpro = re.search(\n r\"\\d[.\\d+]\", metr.findtext(\"per-minute\", \"-\")\n )\n # look for a number\n if tmpro:\n tempo = tmpro.group()\n # overwrites the value set by the sound element of this direction\n t = dir_type.find(\"wedge\")\n if t is not None:\n start_stop(\"wedge\", vs)\n all_words = dir_type.findall(\"words\") # insert text annotations\n if not all_words:\n all_words = dir_type.findall(\"rehearsal\")\n # treat rehearsal mark as text annotation\n if jmp:\n # ignore the words when a jump sound element is present in this direction\n self.music.append_element(vs, f\"!{jmp}!\", True) # to voice\n else:\n for words in all_words:\n plc = placement == \"below\" and \"_\" or \"^\"\n if float(words.get(\"default-y\", \"0\")) < 0:\n plc = \"_\"\n if words.text:\n words_text += words.text.replace('\"', r\"\\\"\").replace(\n \"\\n\", r\"\\n\"\n )\n words_text = words_text.strip()\n for key, val in dynamics_map.items():\n if dir_type.find(\"dynamics/\" + key) is not None:\n self.music.append_element(vs, val, True) # to voice\n if dir_type.find(\"coda\") is not None:\n self.music.append_element(vs, \"O\", True)\n if dir_type.find(\"segno\") is not None:\n self.music.append_element(vs, \"S\", True)\n t = dir_type.find(\"octave-shift\")\n if t is not None:\n start_stop(\"octave-shift\", vs, stf)\n # assume size == 8 for the time being\n t = dir_type.find(\"pedal\")\n if t is not None and self.render_pedal_dirs:\n if not self.pedal_dir_voice:\n self.pedal_dir_voice = vs\n start_stop(\"pedal\", self.pedal_dir_voice)\n if dir_type.findtext(\"other-direction\") == \"diatonic fretting\":\n self.diafret = True\n if tempo:\n tempo = \"%.0f\" % float(tempo)\n # hope it is a number and insert in voice 1\n if self.music.time == 0 and self.measure.ixm == 0:\n # first measure -> header\n abc_out.tempo = tempo\n abc_out.tempo_units = tempo_units\n else:\n self.music.append_element(\n v1, f\"[Q:{tempo_units[0]}/{tempo_units[1]}={tempo}]\"\n ) # otherwise -> 1st voice\n if words_text:\n self.music.append_element(vs, f'\"{plc}{words_text}\"', True)\n # to voice, but after tempo\n\n def parse_harmony(self, e: E.Element, i: int, es: list[E.Element]):\n \"\"\"Parse a MusicXML harmony tag.\"\"\"\n _, vt, _ = self.find_voice(i, es)\n short = {\n \"major\": \"\",\n \"minor\": \"m\",\n \"augmented\": \"+\",\n \"diminished\": \"dim\",\n \"dominant\": \"7\",\n \"half-diminished\": \"m7b5\",\n }\n accmap = {\n \"major\": \"maj\",\n \"dominant\": \"\",\n \"minor\": \"m\",\n \"diminished\": \"dim\",\n \"augmented\": \"+\",\n \"suspended\": \"sus\",\n }\n modmap = {\n \"second\": \"2\",\n \"fourth\": \"4\",\n \"seventh\": \"7\",\n \"sixth\": \"6\",\n \"ninth\": \"9\",\n \"11th\": \"11\",\n \"13th\": \"13\",\n }\n altmap = {\"1\": \"#\", \"0\": \"\", \"-1\": \"b\"}\n root = e.findtext(\"root/root-step\", \"\")\n alt = altmap.get(e.findtext(\"root/root-alter\", \"-\"), \"\")\n sus = \"\"\n kind = e.findtext(\"kind\", \"\")\n if kind in short:\n kind = short[kind]\n elif \"-\" in kind: # XML chord names: -\n triad, mod = kind.split(\"-\")\n kind = accmap.get(triad, \"\") + modmap.get(mod, \"\")\n if kind.startswith(\"sus\"):\n kind, sus = \"\", kind # sus-suffix goes to the end\n elif kind == \"none\":\n kind = e.find(\"kind\").get(\"text\", \"\")\n degrees = e.findall(\"degree\")\n for d in degrees: # chord alterations\n kind += altmap.get(\n d.findtext(\"degree-alter\", \"-\"), \"\"\n ) + d.findtext(\"degree-value\", \"\")\n kind = (\n kind.replace(\"79\", \"9\").replace(\"713\", \"13\").replace(\"maj6\", \"6\")\n )\n bass = e.findtext(\"bass/bass-step\", \"\") + altmap.get(\n e.findtext(\"bass/bass-alter\", \"-\"), \"\"\n )\n self.music.append_element(\n vt,\n '\"%s%s%s%s%s\"' % (root, alt, kind, sus, bass and \"/\" + bass),\n True,\n )\n\n def do_barline(self, e: E.Element):\n \"\"\"0 = no repeat, 1 = begin repeat, 2 = end repeat\"\"\"\n rep = e.find(\"repeat\")\n if rep is not None:\n rep = rep.get(\"direction\")\n if self.unfold: # unfold repeat, don't translate barlines\n return rep and (rep == \"forward\" and 1 or 2) or 0\n loc = e.get(\"location\", \"right\") # right is the default\n if loc == \"right\": # only change style for the right side\n style = e.findtext(\"bar-style\")\n if style == \"light-light\":\n self.measure.rline = \"||\"\n elif style == \"light-heavy\":\n self.measure.rline = \"|]\"\n if rep is not None: # repeat found\n if rep == \"forward\":\n self.measure.lline = \":\"\n else:\n self.measure.rline = \":|\" # override barline style\n end = e.find(\"ending\")\n if end is not None:\n if end.get(\"type\") == \"start\":\n n = end.get(\"number\", \"1\").replace(\".\", \"\").replace(\" \", \"\")\n try:\n list(map(int, n.split(\",\")))\n # should be a list of integers\n except ValueError:\n n = '\"%s\"' % n.strip() # illegal musicXML\n self.measure.lnum = n\n # assume a start is always at the beginning of a measure\n elif self.measure.rline == \"|\":\n # stop and discontinue the same in ABC ?\n self.measure.rline = \"||\"\n # to stop on a normal barline use || in ABC ?\n return 0\n\n def do_print(self, e):\n \"\"\"print element, measure number -> insert a line break\"\"\"\n if e.get(\"new-system\") == \"yes\" or e.get(\"new-page\") == \"yes\":\n if not self.nolbrk:\n return \"$\" # a line break\n\n def do_part_list(self, e):\n \"\"\"Translate the start/stop-event-based XML-partlist into proper tree.\"\"\"\n for score_part in e.findall(\"part-list/score-part\"):\n midi = {}\n for m in score_part.findall(\"midi-instrument\"):\n x = [\n m.findtext(p, self.midi_defaults[i])\n for i, p in enumerate(\n [\"midi-channel\", \"midi-program\", \"volume\", \"pan\"]\n )\n ]\n pan = float(x[3])\n if pan >= -90 and pan <= 90:\n # would be better to map behind-pannings\n pan = (float(x[3]) + 90) / 180 * 127\n # XML between -90 and +90\n midi[m.get(\"id\")] = [\n int(x[0]),\n int(x[1]),\n float(x[2]) * 1.27,\n pan,\n ] # volume 100 -> MIDI 127\n up = m.findtext(\"midi-unpitched\")\n if up:\n self.drum_instr[m.get(\"id\")] = int(up) - 1\n # store MIDI-pitch for channel 10 notes\n self.instr_midis.append(midi)\n ps = e.find(\"part-list\") # partlist = [groupelem]\n xs = get_part_list(ps) # groupelem = partname | grouplist\n partlist, _ = parse_parts(xs, {}, [])\n # grouplist = [groupelem, ..., groupdata]\n return partlist # groupdata = [group-symbol, group-barline, group-name, group-abbrev]\n\n def make_title(self, element_tree: E.ElementTree):\n def lines(text: str):\n return (line.strip() for line in text.splitlines())\n\n work_titles = list(lines(element_tree.findtext(\"work/work-title\", \"\")))\n movement_titles = list(\n lines(element_tree.findtext(\"movement-title\", \"\"))\n )\n composers, lyricists, credits = [], [], []\n for creator in element_tree.findall(\"identification/creator\"):\n if creator.text:\n if creator.get(\"type\") == \"composer\":\n composers.extend(lines(creator.text))\n elif creator.get(\"type\") in {\"lyricist\", \"transcriber\"}:\n lyricists.extend(lines(creator.text))\n for rights in element_tree.findall(\"identification/rights\"):\n if rights.text:\n lyricists.extend(lines(rights.text))\n for credit in element_tree.findall(\"credit\"):\n cs = \"\".join(e.text or \"\" for e in credit.findall(\"credit-words\"))\n credits.append(re.sub(r\"\\s*[\\r\\n]\\s*\", \" \", cs))\n credit_strs = []\n for x in credits: # skip redundant credit lines\n skip = False\n if self.ctf < 6 and (x in work_titles or x in movement_titles):\n skip = True # sure skip\n if self.ctf < 5 and (x in composers or x in lyricists):\n skip = True # almost sure skip\n if self.ctf < 4:\n # may skip too much\n for title in work_titles + movement_titles:\n if title in x:\n skip = True\n break\n if self.ctf < 3:\n # skips too much\n for c in composers + lyricists:\n if c in x:\n skip = True\n break\n if self.ctf < 2 and re.match(r\"^[\\d\\W]*$\", x):\n skip = True # line only contains numbers and punctuation\n if not skip:\n credit_strs.append(x)\n if self.ctf == 0 and (work_titles or movement_titles):\n credit_strs = [] # default: only credit when no title set\n title_lines = []\n for work_title in work_titles:\n title_lines.append(\"T:\" + work_title)\n for movement_title in movement_titles:\n if movement_title not in work_titles:\n title_lines.append(\"T:\" + movement_title)\n for credit_str in credit_strs:\n title_lines.append(\"T:\" + credit_str)\n for composer in composers:\n title_lines.append(\"C:\" + composer)\n for lyricist in lyricists:\n title_lines.append(\"Z:\" + lyricist)\n if title_lines:\n abc_out.title = \"\\n\".join(title_lines)\n self.is_sib = \"Sibelius\" in (\n element_tree.findtext(\"identification/encoding/software\") or \"\"\n )\n if self.is_sib:\n info(\"Sibelius MusicXML is unreliable\")\n\n def do_defaults(self, element_tree: E.ElementTree):\n if not self.format_page:\n return # return if -pf option absent\n defaults = element_tree.find(\"defaults\")\n if defaults is None:\n return\n mils = defaults.findtext(\"scaling/millimeters\")\n # mills == staff height (mm)\n tenths = defaults.findtext(\"scaling/tenths\") # staff height in tenths\n if not mils or not tenths:\n return\n xml_scale = float(mils) / float(tenths) / 10 # tenths -> mm\n space = 10 * xml_scale # space between staff lines == 10 tenths\n abcScale = space / 0.2117\n # 0.2117 cm = 6pt = space between staff lines for scale = 1.0 in abcm2ps\n abc_out.pageFmt[\"scale\"] = abcScale\n eks = 2 * [\"page-layout/\"] + 4 * [\"page-layout/page-margins/\"]\n eks = [\n a + b\n for a, b in zip(\n eks,\n \"page-height,page-width,left-margin,right-margin,top-margin,bottom-margin\".split(\n \",\"\n ),\n )\n ]\n for i in range(6):\n v = defaults.findtext(eks[i])\n k = abc_out.pagekeys[\n i + 1\n ] # pagekeys [0] == scale already done, skip it\n if not abc_out.pageFmt[k] and v:\n try:\n abc_out.pageFmt[k] = float(v) * xml_scale # -> cm\n except:\n info(\"illegal value %s for XML element %s\" % (v, eks[i]))\n continue # just skip illegal values\n\n def loc_staff_map(self, part, measures):\n \"\"\"Map voice to staff with majority voting.\"\"\"\n vmap = (\n {}\n ) # {voice -> {staff -> n}} count occurrences of voice in staff\n self.voice_instrument = {} # {voice -> instrument id} for this part\n self.music.voice_nums = set() # voice id's\n self.has_stems = {}\n # XML voice nums with at least one note with a stem (for tab key)\n self.staff_map, self.clef_map = (\n {},\n {},\n ) # staff -> [voices], staff -> clef\n notes = part.findall(\"measure/note\")\n for n in notes: # count staff allocations for all notes\n v = int(n.findtext(\"voice\", \"1\"))\n if self.is_sib:\n v += 100 * int(\n n.findtext(\"staff\", \"1\")\n ) # repair bug in Sibelius\n self.music.voice_nums.add(\n v\n ) # collect all used voice id's in this part\n sn = int(n.findtext(\"staff\", \"1\"))\n self.staff_map[sn] = []\n if v not in vmap:\n vmap[v] = {sn: 1}\n else:\n d = vmap[v] # counter for voice v\n d[sn] = (\n d.get(sn, 0) + 1\n ) # ++ number of allocations for staff sn\n x = n.find(\"instrument\")\n if x is not None:\n self.voice_instrument[v] = x.get(\"id\")\n x, noRest = n.findtext(\"stem\"), n.find(\"rest\") is None\n if noRest and (not x or x != \"none\"):\n self.has_stems[v] = 1 # XML voice v has at least one stem\n vks = list(vmap.keys())\n if self.javascript or self.is_sib:\n vks.sort()\n for v in vks: # choose staff with most allocations for each voice\n xs = [(n, sn) for sn, n in vmap[v].items()]\n xs.sort()\n stf = xs[-1][1] # the winner: staff with most notes of voice v\n self.staff_map[stf].append(v)\n self.voice2staff[v] = stf # reverse map\n self.cur_staffs[v] = stf # current staff of XML voice v\n\n def add_staff_map(self, xml2abcmap):\n \"\"\"xml2abcmap: XML voice number -> global ABC voice number\"\"\"\n part = [] # default: brace on staffs of one part\n for stf, voices in sorted(self.staff_map.items()):\n # self.staff_map has XML staff and voice numbers\n locmap = [xml2abcmap[iv] for iv in voices if iv in xml2abcmap]\n nostem = [\n (iv not in self.has_stems) for iv in voices if iv in xml2abcmap\n ]\n # same order as locmap\n if locmap: # ABC voice number of staff stf\n part.append(locmap)\n clef = self.clef_map.get(\n stf, \"treble\"\n ) # {XML staff number -> clef}\n for i, iv in enumerate(locmap):\n clef_attr = \"\"\n if clef.startswith(\"tab\"):\n if nostem[i] and \"nostems\" not in clef:\n clef_attr = \" nostems\"\n if self.diafret and \"diafret\" not in clef:\n clef_attr += (\n \" diafret\" # for all voices in the part\n )\n abc_out.clefs[iv] = clef + clef_attr\n # add nostems when all notes of voice had no stem\n self.g_staff_map.append(part)\n\n def add_midi_map(self, ip, xml2abcmap):\n \"\"\"Map ABC voices to MIDI settings.\"\"\"\n instr = self.instr_midis[ip] # get the MIDI settings for this part\n if instr.values():\n defInstr = list(instr.values())[\n 0\n ] # default settings = first instrument\n else:\n defInstr = self.midi_defaults # no instruments defined\n xs = []\n for v, vabc in xml2abcmap.items(): # XML voice num, ABC voice num\n ks = sorted(self.drum_notes.items())\n ds = [\n (nt, step, midi, head)\n for (vd, nt), (step, midi, head) in ks\n if v == vd\n ] # map perc notes\n id = self.voice_instrument.get(v, \"\")\n # get the instrument-id for part with multiple instruments\n if id in instr: # id is defined as midi-instrument in part-list\n xs.append((vabc, instr[id] + ds)) # get MIDI settings for id\n else:\n xs.append(\n (vabc, defInstr + ds)\n ) # only one instrument for this part\n xs.sort() # put ABC voices in order\n self.midi_map.extend([midi for v, midi in xs])\n snaarmap = [\"E\", \"G\", \"B\", \"d\", \"f\", \"a\", \"c'\", \"e'\"]\n diamap = \"0,1-,1,1+,2,3,3,4,4,5,6,6+,7,8-,8,8+,9,10,10,11,11,12,13,13+,14\".split(\n \",\"\n )\n for k in sorted(self.tab_map.keys()): # add %%map's for all tab voices\n v, noot = k\n string, fret = self.tab_map[k]\n if self.diafret:\n fret = diamap[int(fret)]\n vabc = xml2abcmap[v]\n string = self.staff_lines - int(string)\n xs = self.tab_voice_map.get(vabc, [])\n xs.append(\n \"%%%%map tab%d %s print=%s heads=head%s\\n\"\n % (vabc, noot, snaarmap[string], fret)\n )\n self.tab_voice_map[vabc] = xs\n self.heads[fret] = 1 # collect noteheads for SVG defs\n\n def parse(self, fobj):\n vvmapAll = {} # collect XML->ABC voice maps (xml2abcmap) of all parts\n e = E.parse(fobj)\n self.make_title(e)\n self.do_defaults(e)\n partlist = self.do_part_list(e)\n parts = e.findall(\"part\")\n for ip, p in enumerate(parts):\n measures = p.findall(\"measure\")\n self.loc_staff_map(p, measures)\n \"\"\"{voice -> staff} for this part\"\"\"\n self.drum_notes = {}\n \"\"\"(XML voice, ABC note) -> (MIDI note, note head)\"\"\"\n self.clef_octaves = {}\n \"\"\"XML staff number -> current clef-octave-change\"\"\"\n self.cur_clefs = {}\n \"\"\"XML staff number -> current ABC clef\"\"\"\n self.stem_dirs = {}\n \"\"\"XML voice number -> current stem direction\"\"\"\n self.tab_map = {}\n \"\"\"(XML voice, ABC note) -> (string, fret)\"\"\"\n self.diafret = False\n \"\"\"use diatonic fretting\"\"\"\n self.staff_lines = 5\n self.music.init_voices(True)\n \"\"\"create all voices\"\"\"\n repeat_count = 0\n \"\"\"keep track of number of repetitions\"\"\"\n repeat_measure = 0\n \"\"\"target measure of the repetition\"\"\"\n divisions = []\n \"\"\"current value of for each measure\"\"\"\n self.measure = Measure(ip)\n \"\"\"various measure data\"\"\"\n while self.measure.ixm < len(measures):\n measure = measures[self.measure.ixm]\n repeat, line_break = 0, \"\"\n self.measure.reset()\n self.cur_alts = {}\n # passing accidentals are reset each measure\n es = list(measure)\n for i, e in enumerate(es):\n if e.tag == \"note\":\n self.parse_note(e)\n elif e.tag == \"attributes\":\n self.parse_attr(e)\n elif e.tag == \"direction\":\n self.do_direction(e, i, es)\n elif e.tag == \"sound\":\n self.do_direction(measure, i, es)\n # sound element directly in measure!\n elif e.tag == \"harmony\":\n self.parse_harmony(e, i, es)\n elif e.tag == \"barline\":\n repeat = self.do_barline(e)\n elif e.tag == \"backup\":\n dt = int(e.findtext(\"duration\", \"\"))\n if check_bug(dt, self.measure):\n self.music.increment_time(-dt)\n elif e.tag == \"forward\":\n dt = int(e.findtext(\"duration\", \"\"))\n if check_bug(dt, self.measure):\n self.music.increment_time(dt)\n elif e.tag == \"print\":\n line_break = self.do_print(e)\n self.music.add_bar(line_break, self.measure)\n divisions.append(self.measure.divs)\n if repeat == 1:\n repeat_measure = self.measure.ixm\n self.measure.ixm += 1\n elif repeat == 2:\n if repeat_count < 1: # jump\n self.measure.ixm = repeat_measure\n repeat_count += 1\n else:\n repeat_count = 0 # reset\n self.measure.ixm += 1 # just continue\n else:\n self.measure.ixm += 1 # on to the next measure\n for rv in self.repeat_str.values():\n # close hanging measure-repeats without stop\n rv[0] = f\"[I:repeat {rv[1]} 1]\"\n xml2abcmap = self.music.output_voices(divisions, ip, self.is_sib)\n self.add_staff_map(xml2abcmap) # update global staff map\n self.add_midi_map(ip, xml2abcmap)\n vvmapAll.update(xml2abcmap)\n if vvmapAll: # skip output if no part has any notes\n abc_out.make_header(\n self.g_staff_map,\n partlist,\n self.midi_map,\n self.tab_voice_map,\n self.heads,\n )\n abc_out.write_all()\n else:\n info(\"nothing written, %s has no notes ...\" % abc_out.name)\n\n\n# ----------------\n# Main Program\n# ----------------\nif __name__ == \"__main__\":\n from optparse import OptionParser\n from glob import glob\n from zipfile import ZipFile\n\n ustr = \"%prog [-h] [-u] [-m] [-c C] [-d D] [-n CPL] [-b BPL] [-o DIR] [-v V]\\n\"\n ustr += \"[-x] [-p PFMT] [-t] [-s] [-i] [--v1] [--noped] [--stems] [ ...]\"\n parser = OptionParser(usage=ustr, version=str(VERSION))\n parser.add_option(\"-u\", action=\"store_true\", help=\"unfold simple repeats\")\n parser.add_option(\n \"-m\",\n action=\"store\",\n help=\"0 -> no %%MIDI, 1 -> minimal %%MIDI, 2-> all %%MIDI\",\n default=0,\n )\n parser.add_option(\n \"-c\",\n action=\"store\",\n type=\"int\",\n help=\"set credit text filter to C\",\n default=0,\n metavar=\"C\",\n )\n parser.add_option(\n \"-d\",\n action=\"store\",\n type=\"int\",\n help=\"set L:1/D\",\n default=0,\n metavar=\"D\",\n )\n parser.add_option(\n \"-n\",\n action=\"store\",\n type=\"int\",\n help=\"CPL: max number of characters per line (default 100)\",\n default=0,\n metavar=\"CPL\",\n )\n parser.add_option(\n \"-b\",\n action=\"store\",\n type=\"int\",\n help=\"BPL: max number of bars per line\",\n default=0,\n metavar=\"BPL\",\n )\n parser.add_option(\n \"-o\",\n action=\"store\",\n help=\"store ABC files in DIR\",\n default=\"\",\n metavar=\"DIR\",\n )\n parser.add_option(\n \"-v\",\n action=\"store\",\n type=\"int\",\n help=\"set volta typesetting behaviour to V\",\n default=0,\n metavar=\"V\",\n )\n parser.add_option(\"-x\", action=\"store_true\", help=\"output no line breaks\")\n parser.add_option(\n \"-p\",\n action=\"store\",\n help=\"pageformat PFMT (cm) = scale, pageheight, pagewidth, leftmargin, rightmargin, topmargin, botmargin\",\n default=\"\",\n metavar=\"PFMT\",\n )\n parser.add_option(\n \"-j\",\n action=\"store_true\",\n help=\"switch for compatibility with javascript version\",\n )\n parser.add_option(\n \"-t\",\n action=\"store_true\",\n help=\"translate perc- and tab-staff to ABC code with %%map, %%voicemap\",\n )\n parser.add_option(\n \"-s\",\n action=\"store_true\",\n help=\"shift node heads 3 units left in a tab staff\",\n )\n parser.add_option(\n \"--v1\",\n action=\"store_true\",\n help=\"start-stop directions allways to first voice of staff\",\n )\n parser.add_option(\n \"--noped\",\n action=\"store_false\",\n help=\"skip all pedal directions\",\n dest=\"ped\",\n default=True,\n )\n parser.add_option(\n \"--stems\",\n action=\"store_true\",\n help=\"translate stem directions\",\n dest=\"stm\",\n default=False,\n )\n parser.add_option(\n \"-i\", action=\"store_true\", help=\"read XML file from standard input\"\n )\n options, args = parser.parse_args()\n if options.n < 0:\n parser.error(\"only values >= 0\")\n if options.b < 0:\n parser.error(\"only values >= 0\")\n if options.d and options.d not in [2**n for n in range(10)]:\n parser.error(\n \"D should be on of %s\" % \",\".join([str(2**n) for n in range(10)])\n )\n options.p = options.p and options.p.split(\",\") or [] # ==> [] | [string]\n if len(args) == 0 and not options.i:\n parser.error(\"no input file given\")\n out_path = options.o\n if out_path:\n if not os.path.exists(out_path):\n os.mkdir(out_path)\n if not os.path.isdir(out_path):\n parser.error(\"%s is not a directory\" % out_path)\n fnmext_list = []\n for i in args:\n fnmext_list += glob(i)\n if options.i:\n fnmext_list = [\"stdin.xml\"]\n if not fnmext_list:\n parser.error(\"none of the input files exist\")\n for X, name in enumerate(fnmext_list):\n fnm, ext = os.path.splitext(name)\n if ext.lower() not in {\".xml\", \".mxl\", \".musicxml\"}:\n info(\n \"skipped input file %s, it should have extension .xml or .mxl\"\n % name\n )\n continue\n if os.path.isdir(name):\n info(\"skipped directory %self. Only files are accepted\" % name)\n continue\n if name == \"stdin.xml\":\n fobj = sys.stdin\n elif ext.lower() == \".mxl\": # extract .XML file from .mxl file\n z = ZipFile(name)\n for n in z.namelist():\n # assume there is always an XML file in a mxl archive !!\n if (n[:4] != \"META\") and (n[-3:].lower() in {\"xml\"}):\n fobj = z.open(n)\n break # assume only one MusicXML file per archive\n else:\n fobj = open(name, \"rb\") # open regular XML file\n\n abc_out = ABCOutput(fnm + \".abc\", out_path, X, options)\n # create global ABC output object\n parser = Parser(options) # XML parser\n try:\n parser.parse(fobj) # parse file fobj and write ABC to .abc\n except Exception as e:\n etype, value, traceback = sys.exc_info() # works in python 2 & 3\n # info(\"** %s occurred: %s in %s\" % (etype, value, name), False)\n raise e\n","repo_name":"egginabucket/grove","sub_path":"xml2abc_mod.py","file_name":"xml2abc_mod.py","file_ext":"py","file_size_in_byte":108769,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"44345596453","text":"import os,sys,time,logging,argparse\nfrom ublarcvserver import start_broker\nfrom start_ubssnet_worker import startup_ubssnet_workers\nfrom UBSSNetClient import UBSSNetClient\n\n\nif __name__ == \"__main__\":\n\n # endpoint:\n endpoint = \"tcp://localhost:6005\"\n bindpoint = \"tcp://*:6005\"\n weights_dir = \"/home/twongjirad/working/nutufts/pytorch-uresnet/weights/\"\n weights_files = {0:weights_dir+\"/mcc8_caffe_ubssnet_plane0.tar\",\n 1:weights_dir+\"/mcc8_caffe_ubssnet_plane1.tar\",\n 2:weights_dir+\"/mcc8_caffe_ubssnet_plane2.tar\"}\n\n input_dir = \"/home/twongjirad/working/larbys/ubdl/testdata/ex1\"\n larcv_supera_file = input_dir+\"/supera-Run000001-SubRun006867.root\"\n larlite_opreco_file = input_dir+\"/opreco-Run000001-SubRun006867.root\"\n output_larcv_filename = \"out_ubssnet_test.root\"\n\n logging.basicConfig(level=logging.DEBUG)\n\n pbroker = start_broker(bindpoint)\n pworkers = startup_ubssnet_workers(endpoint,weights_files,\n devices=\"cuda\",nplanes=[0,1,2],\n batch_size=1)\n\n client = UBSSNetClient(endpoint,larcv_supera_file,\n output_larcv_filename,\n adc_producer=\"wire\",\n larlite_opreco_file=larlite_opreco_file,\n apply_opflash_roi=True, tick_backwards=True)\n client.connect()\n\n client.process_entry(1)\n\n client.finalize()\n\n print(\"[ENTER] to quit.\")\n raw_input()\n","repo_name":"LArbys/ublarcvserver","sub_path":"app/ubssnet/run_ubssnet_client.py","file_name":"run_ubssnet_client.py","file_ext":"py","file_size_in_byte":1534,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"81"} +{"seq_id":"28745907170","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport os\nimport sys\nfrom sharedlibrary import GenericLibrary\nfrom ctypes import *\n\n\nclass libflashsim(GenericLibrary):\n dllname = 'tests/flashsim.so'\n functions = [\n ['flashsim_open', [c_char_p, c_int, c_int], c_void_p],\n ['flashsim_sector_erase', [c_void_p, c_int], None],\n ['flashsim_read', [c_void_p, c_int, c_void_p, c_int], None],\n ['flashsim_program', [c_void_p, c_int, c_void_p, c_int], None],\n ['flashsim_close', [c_void_p], None],\n ]\n\n\nclass FlashSim(object):\n\n def __init__(self, name, size, sector_size):\n self.libflashsim = libflashsim()\n self.sim = self.libflashsim.flashsim_open(name ,size, sector_size)\n\n def sector_erase(self, addr):\n self.libflashsim.flashsim_sector_erase(self.sim, addr)\n\n def read(self, addr, size):\n buf = create_string_buffer(size)\n self.libflashsim.flashsim_read(self.sim, addr, buf, size)\n return buf.raw\n\n def program(self, addr, data):\n self.libflashsim.flashsim_program(self.sim, addr, data, len(data))\n\n def __del__(self):\n self.libflashsim.flashsim_close(self.sim)\n","repo_name":"cloudyourcar/ringfs","sub_path":"tests/pyflashsim.py","file_name":"pyflashsim.py","file_ext":"py","file_size_in_byte":1173,"program_lang":"python","lang":"en","doc_type":"code","stars":60,"dataset":"github-code","pt":"81"} +{"seq_id":"4765576509","text":"from django.urls import path\r\nfrom . import views\r\n\r\n# from Home.views import Product_info\r\n\r\nurlpatterns=[\r\n path('', views.Homepage, name='home'),\r\n path('AddListing', views.AddListing, name='addlisting'),\r\n path('ViewListing/', views.ViewListing, name=\"listing\"),\r\n]\r\n","repo_name":"Montache/rentee","sub_path":"Home/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":292,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"7108789947","text":"# reference:\r\n# \r\n# https://huggingface.co/transformers/quickstart.html\r\n# http://mccormickml.com/2019/11/11/bert-research-ep-1-key-concepts-and-sources/\r\n# https://www.youtube.com/watch?v=FKlPCK1uFrc&feature=youtu.be\r\n\r\nimport transformers\r\nfrom transformers import BertTokenizer, BertModel\r\nfrom transformers import AdamW, get_linear_schedule_with_warmup\r\n\r\nimport torch\r\nimport random\r\nimport numpy as np\r\n\r\nseed_val = 0\r\nrandom.seed(seed_val)\r\nnp.random.seed(seed_val)\r\ntorch.manual_seed(seed_val)\r\ntorch.cuda.manual_seed_all(seed_val)\r\n\r\ndef transformers_test():\r\n '''\r\n '''\r\n pass\r\n\r\n# import logging\r\n# logging.basicConfig(level=logging.INFO)\r\n\r\ntokenizer = BertTokenizer.from_pretrained('bert-base-uncased')\r\n\r\ntext = '[CLS] who was Jim ? [SEP]'\r\n# text = '[CLS] who was Jim ? [SEP] Jim was a puppeteer [SEP]'\r\ntokenized_text = tokenizer.tokenize(text)\r\nindexed_tokens = tokenizer.convert_tokens_to_ids(tokenized_text)\r\nprint(indexed_tokens)\r\n\r\nindexed_tokens = tokenizer.encode('who was Jim ?', add_special_tokens=True)\r\nprint(indexed_tokens)\r\n\r\n\r\nsegments_ids = [1, 1, 1, 1, 1, 1]\r\n# segments_ids = [0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1]\r\ntokens_tensor = torch.tensor([indexed_tokens])\r\nsegments_tensor = torch.tensor([segments_ids])\r\n\r\nmodel = BertModel.from_pretrained('bert-base-uncased')\r\nmodel.eval()\r\nfor n, p in model.named_parameters():\r\n if 'embedding' in n:\r\n print(n, p.shape)\r\n\r\nwith torch.no_grad():\r\n outputs = model(tokens_tensor, token_type_ids=segments_tensor, attention_mask=None, output_all_encoded_layers=False)\r\n print(len(outputs))\r\n print(outputs[0].shape, outputs[1].shape)\r\n\r\n encoded_layers = outputs[0]\r\n\r\n\r\n","repo_name":"lyuwenyu/AI","sub_path":"nlp/models/core_bert.py","file_name":"core_bert.py","file_ext":"py","file_size_in_byte":1674,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"81"} +{"seq_id":"17892660918","text":"import copy\nimport numpy as np\nimport pandas as pd \nimport matplotlib.pyplot as plt\n\nfrom sklearn import preprocessing as pr\nfrom sklearn.metrics import roc_auc_score\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.ensemble import RandomForestClassifier\n\n###############################################################################\n# Loading the data\n###############################################################################\n\nGlobalDirectory=r\"/home/tavoglc/LocalData/\"\nDataDir=GlobalDirectory + \"data_2genre.csv\"\n\n###############################################################################\n# Plotting functions\n###############################################################################\n\ndef PlotStyle(Axes): \n \"\"\"\n Parameters\n ----------\n Axes : Matplotlib axes object\n Applies a general style to the matplotlib object\n\n Returns\n -------\n None.\n \"\"\" \n Axes.spines['top'].set_visible(False)\n Axes.spines['bottom'].set_visible(True)\n Axes.spines['left'].set_visible(True)\n Axes.spines['right'].set_visible(False)\n Axes.xaxis.set_tick_params(labelsize=13)\n Axes.yaxis.set_tick_params(labelsize=13)\n\ndef MakeCategoricalPlot(Data,CategoricalFeature,PlotSize):\n \"\"\"\n Parameters\n ----------\n Data: pandas data frame \n Containes the data for the plot \n CategoricalFeature : String \n Categorical value to be analyzed in the dataset \n PlotSize : tuple\n Size of the plot \n\n Returns\n -------\n None.\n\n \"\"\"\n localUniqueVals=Data[CategoricalFeature].unique()\n localCounts=CountUniqueElements(localUniqueVals,Data[CategoricalFeature])\n Xaxis=np.arange(len(localUniqueVals))\n localTicksNames=[str(val) for val in localUniqueVals]\n plt.figure(figsize=PlotSize)\n plt.bar(Xaxis,localCounts)\n axis=plt.gca()\n axis.set_xticks(Xaxis)\n axis.set_xticklabels(localTicksNames,rotation=85)\n axis.set_xlabel(CategoricalFeature,fontsize=14)\n PlotStyle(axis)\n\n\ndef GetGridShape(UniqueVals):\n \"\"\"\n Parameters\n ----------\n UniqueVals : list\n List with the elements of the plot.\n\n Returns\n -------\n nrows : int\n number of rows in the plot.\n ncolumns : int\n number of columns in the plot.\n\n \"\"\"\n numberOfUnique=len(UniqueVals)\n squaredUnique=int(np.sqrt(numberOfUnique))\n \n if squaredUnique*squaredUnique==numberOfUnique:\n nrows,ncolumns=squaredUnique,squaredUnique\n elif squaredUnique*(squaredUnique+1)mutProb and len(currentIndexs[k])>4:\n randomPosition=np.random.randint(0,len(currentIndexs[k]))\n del currentIndexs[k][randomPosition]\n else:\n randomPosition=np.random.randint(0,len(currentIndexs[k]))\n currentIndexs[k][randomPosition]=np.random.randint(0,maxValue)\n \n for j in range(nIndexs):\n if np.random.random()>recProb:\n rnIndividual=currentIndexs[np.random.randint(0,nIndexs)]\n recIndex=np.random.randint(0,len(rnIndividual))\n recInsertion=np.random.randint(0,len(currentIndexs[j]))\n currentIndexs[j].insert(recInsertion,rnIndividual[recIndex])\n \n return currentIndexs\n\ndef TrainOnGenerations(XData,YData,Generations,Population,MaxFeatures):\n \"\"\"\n Parameters\n ----------\n XData : array\n X data.\n YData : array\n Y data.\n Generations : int\n Number of iterations.\n Population : int\n number of individuals per iteration.\n MaxFeatures : int\n Number of features in the data set.\n\n Returns\n -------\n fitness : list\n performance of each individual in the population.\n currentPopulation : list\n contains the index of the las population in the iteration.\n \"\"\"\n currentPopulation=MakeRandomSizePopulation(MaxFeatures,Population,1)\n fitness=TrainOnPopulation(XData,YData,currentPopulation)\n \n for k in range(Generations):\n \n newPopulation=MakeIndexEvolution(currentPopulation,MaxFeatures,0.5,0.5)\n newFitness=TrainOnPopulation(XData,YData,newPopulation)\n \n for k in range(Population):\n if newFitness[k]>fitness[k]:\n currentPopulation[k]=newPopulation[k]\n fitness[k]=newFitness[k]\n \n return fitness,currentPopulation\n\n###############################################################################\n# Evolutionary strategies\n###############################################################################\n\nXData=np.array(Data[FeatureHeaders])\nYData=np.array(Data['label'])\n\nfitn,indxs=TrainOnGenerations(XData,YData,20,25,len(FeatureHeaders))\n\nmodelSizes=[len(val) for val in indxs]\nminsize=min(modelSizes)\nmaxsize=max(modelSizes)\n\nwidths=[0.5+(val-minsize)/(2*(maxsize-minsize)) for val in modelSizes]\n\nplt.figure(4,figsize=(15,6))\nplt.bar(np.arange(len(fitn)),fitn,widths)\nplt.xlabel('Models',fontsize=14)\nplt.ylabel('ROC AUC',fontsize=14)\nax=plt.gca()\nPlotStyle(ax)\n\n","repo_name":"TavoGLC/DataAnalysisByExample","sub_path":"Ensamble/AutoFE.py","file_name":"AutoFE.py","file_ext":"py","file_size_in_byte":13362,"program_lang":"python","lang":"en","doc_type":"code","stars":42,"dataset":"github-code","pt":"81"} +{"seq_id":"39257049794","text":"# model settings\n# 10 classes for cifar10\nnum_classes = 10\n# loss function, set multiple losses if needed, allow weighted sum\nloss = [dict(type='TorchLoss', loss_name='CrossEntropyLoss', loss_weight=1.0)]\n\nmodel = dict(\n # Base Encoder Decoder Architecture (Backbone+Head)\n type='BaseEncoderDecoder',\n need_dataloader=True,\n # Visual Backbone from Timm Models library\n # need to change the input conv layer to (kernel_size=3, stride=1, padding=1) to accept 32x32 input\n backbone=dict(\n type='TimmModels',\n model_name='resnet50',\n features_only=False,\n remove_fc=True,\n pretrained=False,\n magic_replacement=['conv1', 'nn.Conv2d(3, 64, '\n 'kernel_size=(3, 3), '\n 'stride=(1, 1), '\n 'padding=(1, 1), '\n 'bias=False)'],\n\n ),\n # Linear Head for classification\n head=dict(\n type='BaseHead',\n in_index=-1,\n dropout=0.0,\n num_classes=num_classes,\n channels=None,\n losses=loss\n ),\n # auxiliary_head, only work in training for auxiliary loss\n # auxiliary_head=None,\n # metrics for evaluation, allow multiple metrics\n evaluation = dict(metrics=[dict(type='TorchMetrics', metric_name='Accuracy',\n prob=True)])\n)\n\n# dataset settings\ndataset_type = 'TorchVision'\ndataset_name = 'CIFAR10'\ndata_root = '.cache'\n\n# training data preprocess pipeline\ntrain_pipeline = [dict(type='LoadImages'),\n dict(type='Albumentations', transforms=[\n dict(type='PadIfNeeded', min_height=40, min_width=40, p=1.0),\n dict(type='RandomCrop', height=32, width=32, p=1.0),\n dict(type='HorizontalFlip', p=0.5),\n dict(type='Normalize', mean=[0.4914, 0.4822, 0.4465],\n std=[0.2023, 0.1994, 0.2010], p=1.0)]),\n dict(type='ToTensor')]\n\n# validation data preprocess pipeline\ntest_pipeline = [dict(type='LoadImages'),\n dict(type='Albumentations', transforms=[dict(type='Normalize', mean=[0.4914, 0.4822, 0.4465],\n std=[0.2023, 0.1994, 0.2010], p=1.0)]),\n dict(type='ToTensor')]\n\ndata = dict(\n train_batch_size=128, # for single card\n val_batch_size=256,\n test_batch_size=256,\n num_workers=4,\n train=dict(\n type=dataset_type,\n dataset_name=dataset_name,\n data_root=data_root,\n train=True,\n sampler=None, # None is default sampler, set to RandomSampler/DistributedSampler\n pipeline=train_pipeline\n ),\n val=dict(\n type=dataset_type,\n dataset_name=dataset_name,\n data_root=data_root,\n train=False,\n sampler='SequentialSampler',\n pipeline=test_pipeline,\n ),\n test=dict(\n type=dataset_type,\n dataset_name=dataset_name,\n data_root=data_root,\n train=False,\n sampler='SequentialSampler',\n pipeline=test_pipeline\n ),\n)\n\n# yapf:disable\nlog = dict(\n # project name, used for cometml\n project_name='cifar_test',\n # work directory, used for saving checkpoints and loggings\n work_dir='work_dir',\n # explicit directory under work_dir for checkpoints and config\n exp_name='model=resnet50-dataset=cifar10-lr=1e-1',\n logger_interval=50,\n # monitor metric for saving checkpoints\n monitor='val_accuracy',\n # logger type, support TensorboardLogger, CometLogger\n logger=[dict(type='comet', key='Your Key Here!')],\n # checkpoint saving settings\n checkpoint=dict(type='ModelCheckpoint',\n top_k=1,\n mode='max',\n verbose=True,\n save_last=False,\n ),\n # early stopping settings\n earlystopping=dict(\n mode='max',\n strict=False,\n patience=160,\n min_delta=0.0001,\n check_finite=True,\n verbose=True\n )\n\n)\n\n# yapf:enable\n# resume from a checkpoint\nresume_from = None\ncudnn_benchmark = True\n\n# optimization\noptimization = dict(\n # running time unit, support epoch and iter\n type='epoch',\n # total running units\n max_iters=100,\n # optimizer\n optimizer=dict(type='SGD', lr=1e-1, weight_decay=0.0005, momentum=0.9),\n # learning rate scheduler and warmup\n scheduler=dict(type='OneCycle',\n max_lr=1.2e-1,\n interval='step',\n # warmup=dict(type='LinearWarmup', period=0.1)\n )\n\n)\n","repo_name":"CharonWangg/shallowmind","sub_path":"configs/resnet50_image_classification_example.py","file_name":"resnet50_image_classification_example.py","file_ext":"py","file_size_in_byte":4880,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"81"} +{"seq_id":"40754290347","text":"import requests\nfrom lxml import etree\n\nclass CatEye(object):\n def __init__(self,response):\n self.html=etree.HTML(response.text)\n\n def GetTitle(self):\n self.listTitle=self.html.xpath(\"//div[@class='main']//p[@class='name']/a/text()\")\n # print(self.listTitle)\n\n def GetAdd(self):\n self.listAdd=self.html.xpath(\"//div[@class='main']//p[@class='month-wish']/span/span/text()\")\n\n def GetAll(self):\n self.listAll=self.html.xpath(\"//div[@class='main']//p[@class='total-wish']/span/span/text()\")\n\n def GetContent(self):\n self.listUrl=self.html.xpath(\"//div[@class='main']//p[@class='name']/a/@href\")\n self.listUrl2=[]\n for x in self.listUrl:\n self.listUrl2.append('https://maoyan.com'+x)\n self.listContent=[]\n for x in self.listUrl2:\n response2=requests.get(url=x,headers=headers,verify=False)\n html2=etree.HTML(response2.text)\n content=html2.xpath(\"//*[@id='app']/div/div[1]/div/div[2]/div[1]/div[1]/div[2]/span/text()\")\n self.listContent.append(''.join(content))\n print(self.listContent)\n\nif __name__ == '__main__':\n url='https://maoyan.com/board/6'\n headers={'user-agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36'}\n response=requests.get(url=url,headers=headers,verify=False)\n cateye=CatEye(response)\n # cateye.GetTitle()\n cateye.GetContent()\n\n\n\n\n\n\n\n\n","repo_name":"frigid-sll/python","sub_path":"python实习代码/寒假作业/one.py","file_name":"one.py","file_ext":"py","file_size_in_byte":1483,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"19184627661","text":"import unittest\n\nclass Solution:\n def numSubarrayProductLessThanK(self, nums, k):\n \"\"\"\n :type nums: List[int]\n :type k: int\n :rtype: int\n \"\"\"\n if k <= 1:\n return 0\n \n ans = 0\n size = len(nums)\n left = 0\n prod = 1\n for right in range(size):\n prod *= nums[right]\n\n while prod >= k:\n prod //= nums[left]\n left += 1\n \n ans = ans + (right - left + 1)\n return ans\n\nclass SolutionTest(unittest.TestCase):\n def testnumSubarrayProductLessThanK(self):\n sol = Solution()\n self.assertEqual(8, sol.numSubarrayProductLessThanK([10, 5, 2, 6], 100))\n\nif __name__ == \"__main__\":\n unittest.main()\n","repo_name":"pololee/oj-leetcode","sub_path":"companies/affirm/713.num_of_subarray_product_less_than_k.py","file_name":"713.num_of_subarray_product_less_than_k.py","file_ext":"py","file_size_in_byte":778,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"5439526590","text":"# encoding: utf-8\nfrom __future__ import unicode_literals\nfrom django.db import models\nfrom django.contrib.postgres.fields import JSONField\nfrom modulos.vehiculo.models import Vehiculo\nfrom modulos.propietario.models import PropietarioVehiculo\nfrom modulos.macros.models import Macros\n\n\nclass Inspeccion(models.Model):\n\n TIPO_SERVICIO = (\n ('particular', u'Particular'),\n ('publico', u'Público'),\n ('diplomatico', u'Diplomático'),\n ('oficial',u'Oficial'),\n ('especialRNMA',u'EspecialRNMA')\n )\n\n PASO = (\n ('carga_documentos', u'Carga de documentos'),\n ('inspeccion_visual', u'Inspeccion Visual'),\n ('fotografias_vehiculo', u'Fotografias'),\n ('carga_analisis', u'Carga Analisis')\n )\n\n propietario_vehiculo = models.ForeignKey(PropietarioVehiculo)\n tipo_servicio = models.CharField(max_length=100, default='particular', choices=TIPO_SERVICIO)\n kilometraje = models.CharField(max_length=100, null=True, blank=True)\n paso = models.CharField(max_length=100, null=True, blank=True, choices=PASO)\n finalizado = models.BooleanField(default=False)\n created_at = models.DateTimeField(auto_now_add=True)\n updated_at = models.DateTimeField(auto_now=True)\n numero_inspeccion = models.IntegerField()\n v_r_cliente = models.CharField(max_length=100,null=True, blank=True)\n v_r_empresa = models.CharField(max_length=100,null=True, blank=True)\n v_r_fasecolda = models.CharField(max_length=100,null=True, blank=True)\n v_r_accesorios = models.CharField(max_length=100,null=True, blank=True)\n\n def __unicode__(self):\n return self.tipo_servicio\n\n\nclass InspeccionDetalle(models.Model):\n VALOR_MACRO = (\n ('deficiente', u'Deficiente'),\n ('aceptable', u'Aceptable'),\n ('optimo', u'Óptimo'),\n ('no_aplica', u'No aplica'),\n )\n inspeccion = models.ForeignKey(Inspeccion)\n macro_value = JSONField(null=True, blank=True)\n observacion = models.TextField(null=True, blank=True)\n\n\nclass InspeccionFotografia(models.Model):\n inspeccion = models.ForeignKey(Inspeccion)\n img_superior_derecha = models.ImageField(upload_to=\"uploads/inspeccion\", default='default/no-img.jpg')\n img_superior_izquierda = models.ImageField(upload_to=\"uploads/inspeccion\", default='default/no-img.jpg')\n img_delantera = models.ImageField(upload_to=\"uploads/inspeccion\", default='default/no-img.jpg')\n img_trasera = models.ImageField(upload_to=\"uploads/inspeccion\", default='default/no-img.jpg')\n img_interior = models.ImageField(upload_to=\"uploads/inspeccion\", default='default/no-img.jpg')\n created_at = models.DateTimeField(auto_now_add=True)\n updated_at = models.DateTimeField(auto_now=True)\n\n def __unicode__(self):\n return self.inspeccion.propietario_vehiculo.propietario.nombre\n\nclass InspeccionImpronta(models.Model):\n inspeccion = models.ForeignKey(Inspeccion)\n impronta = models.FileField(upload_to='uploads/improntas')\n reated_at = models.DateTimeField(auto_now_add=True)\n","repo_name":"fenriz07/Administration-and-control-of-automobile-workshops","sub_path":"modulos/inspeccion/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":3054,"program_lang":"python","lang":"es","doc_type":"code","stars":2,"dataset":"github-code","pt":"81"} +{"seq_id":"44345357043","text":"import os,sys,logging, zlib\nimport numpy as np\nfrom larcv import larcv\nfrom collections import OrderedDict\n\nfrom ctypes import c_int\nfrom ublarcvserver import MDPyWorkerBase, Broker, Client\nlarcv.json.load_jsonutils()\n\n\"\"\"\nImplements worker for Sparse Infill network\n\"\"\"\n\nclass UBInfillSparseWorker(MDPyWorkerBase):\n\n def __init__(self,broker_address,plane,\n weight_file,device,batch_size,\n use_half=False,use_compression=False,\n **kwargs):\n \"\"\"\n Constructor\n\n inputs\n ------\n broker_address str IP address of broker\n plane int Plane ID number. Currently [0,1,2] only\n weight_file str path to files with weights\n batch_size int number of batches to process in one pass\n \"\"\"\n if type(plane) is not int:\n raise ValueError(\"'plane' argument must be integer for plane ID\")\n elif plane not in [0,1,2]:\n raise ValueError(\"unrecognized plane argument. \\\n should be either one of [0,1,2]\")\n else:\n print(\"PLANE GOOD: \", plane)\n pass\n\n if type(batch_size) is not int or batch_size<0:\n raise ValueError(\"'batch_size' must be a positive integer\")\n\n self.plane = plane\n self.batch_size = batch_size\n self._still_processing_msg = False\n self._use_half = use_half\n self._use_compression = use_compression\n\n service_name = \"infill_plane%d\"%(self.plane)\n\n super(UBInfillSparseWorker,self).__init__( service_name,\n broker_address, **kwargs)\n\n self.load_model(weight_file,device,self._use_half)\n\n if self.is_model_loaded():\n self._log.info(\"Loaded ubInfill model. Service={}\"\\\n .format(service_name))\n\n def load_model(self,weight_file,device,use_half):\n # import pytorch\n try:\n import torch\n except:\n raise RuntimeError(\"could not load pytorch!\")\n\n # ----------------------------------------------------------------------\n # import model - change to my model\n sys.path.append(\"../../../networks/infill\")\n from sparseinfill import SparseInfill\n\n if \"cuda\" not in device and \"cpu\" not in device:\n raise ValueError(\"invalid device name [{}]. Must str with name \\\n \\\"cpu\\\" or \\\"cuda:X\\\" where X=device number\")\n\n self.device = torch.device(device)\n\n map_location = {\"cuda:0\":\"cpu\",\"cuda:1\":\"cpu\"}\n self.model = SparseInfill( (512,496), 1,16,16,5, show_sizes=False)\n checkpoint = torch.load( weight_file, map_location=map_location )\n from_data_parallel = False\n for k,v in checkpoint[\"state_dict\"].items():\n if \"module.\" in k:\n from_data_parallel = True\n break\n\n if from_data_parallel:\n new_state_dict = OrderedDict()\n for k, v in checkpoint[\"state_dict\"].items():\n name = k[7:] # remove `module.`\n new_state_dict[name] = v\n checkpoint[\"state_dict\"] = new_state_dict\n\n self.model.load_state_dict(checkpoint[\"state_dict\"])\n self.model.to(self.device)\n self.model.eval()\n\n\n print (\"Loaded Model!\")\n # ----------------------------------------------------------------------\n\n\n def make_reply(self,request,nreplies):\n \"\"\"we load each image and pass it through the net.\n we run one batch before sending off partial reply.\n the attribute self._still_processing_msg is used to tell us if we\n are still in the middle of a reply.\n \"\"\"\n #print(\"DummyPyWorker. Sending client message back\")\n self._log.debug(\"received message with {} parts\".format(len(request)))\n\n if not self.is_model_loaded():\n self._log.debug(\"model not loaded for some reason. loading.\")\n\n try:\n import torch\n except:\n raise RuntimeError(\"could not load pytorch!\")\n\n try:\n from ROOT import std\n except:\n raise RuntimeError(\"could not load ROOT.std\")\n\n # message pattern: [image_bson,image_bson,...]\n\n nmsgs = len(request)\n nbatches = nmsgs/self.batch_size\n\n if not self._still_processing_msg:\n self._next_msg_id = 0\n\n # turn message pieces into numpy arrays\n imgdata_v = []\n sizes = []\n frames_used = []\n rseid_v = []\n totalpts =0\n for imsg in xrange(self._next_msg_id,nmsgs):\n try:\n compressed_data = str(request[imsg])\n if self._use_compression:\n data = zlib.decompress(compressed_data)\n else:\n data = compressed_data\n c_run = c_int()\n c_subrun = c_int()\n c_event = c_int()\n c_id = c_int()\n\n imgdata = larcv.json.sparseimg_from_bson_pybytes(data,\n c_run, c_subrun, c_event, c_id )\n except Exception as e:\n self._log.error(\"Image Data in message part {}\\\n could not be converted: {}\".format(imsg,str(e)))\n continue\n self._log.debug(\"Image[{}] converted: nfeatures={} npts={}\"\\\n .format(imsg,imgdata.nfeatures(),\n imgdata.pixellist().size()/(imgdata.nfeatures()+1)))\n\n # get source meta\n # print (\"nmeta=\",imgdata.meta_v().size())\n srcmeta = imgdata.meta_v().front()\n # print( \"srcmeta=\",srcmeta.dump())\n\n # check if correct plane!\n if srcmeta.plane()!=self.plane:\n self._log.debug(\"Image[{}] meta plane ({}) is not same as worker's ({})!\"\n .format(imsg,srcmeta.plane(),self.plane))\n continue\n\n # check that same size as previous images\n nfeatures = imgdata.nfeatures()\n npts = imgdata.pixellist().size()/(2+nfeatures)\n imgsize = ( int(srcmeta.rows()), int(srcmeta.cols()),\n int(nfeatures), int(npts) )\n if len(sizes)==0:\n sizes.append(imgsize)\n elif len(sizes)>0 and imgsize not in sizes:\n self._log.debug(\"Next image a different size. \\\n we do not continue batch.\")\n self._next_msg_id = imsg\n break\n totalpts += npts\n imgdata_v.append(imgdata)\n frames_used.append(imsg)\n rseid_v.append((c_run.value,c_subrun.value,c_event.value,c_id.value))\n if len(imgdata_v)>=self.batch_size:\n self._next_msg_id = imsg+1\n break\n\n\n # convert the images into numpy arrays\n nimgs = len(imgdata_v)\n self._log.debug(\"converted msgs into batch of {} images. frames={}\"\n .format(nimgs,frames_used))\n np_dtype = np.float32\n # img_batch_np = np.zeros( (nimgs,1,sizes[0][1],sizes[0][0]),\n # dtype=np_dtype )\n coord_np = np.zeros( (totalpts,3), dtype=np.int )\n input_np = np.zeros( (totalpts,1), dtype=np_dtype )\n nfilled = 0\n for iimg,imgdata in enumerate(imgdata_v):\n (rows,cols,nfeatures,npts) = sizes[iimg]\n # print (\"size of img\", len(imgdata.pixellist()))\n\n if (len(imgdata.pixellist()) == 0):\n start = 0\n end = 1\n totalpts = end\n coord_np = np.zeros( (totalpts,3), dtype=np.int )\n input_np = np.zeros( (totalpts,1), dtype=np_dtype )\n coord_np[start:end,0] = 0\n coord_np[start:end,1] = 0\n coord_np[start:end,2] = iimg\n input_np[start:end,0] = 10.1\n nfilled = 1\n\n else:\n data_np = larcv.as_ndarray( imgdata, larcv.msg.kNORMAL )\n start = nfilled\n end = nfilled+npts\n coord_np[start:end,0:2] = data_np[:,0:2].astype(np.int)\n coord_np[start:end,2] = iimg\n input_np[start:end,0] = data_np[:,2]\n nfilled = end\n # print(\"shape of image: \",img2d_np.shape)\n\n coord_t = torch.from_numpy( coord_np ).to(self.device)\n input_t = torch.from_numpy( input_np ).to(self.device)\n with torch.set_grad_enabled(False):\n out_t = self.model(coord_t, input_t, len(imgdata_v))\n\n out_t = out_t.detach().cpu().numpy()\n # convert from numpy array batch back to sparseimage and messages\n reply = []\n nfilled = 0\n for iimg,(imgshape,imgdata,rseid) in enumerate(zip(sizes,imgdata_v,rseid_v)):\n npts = imgshape[3]\n start = nfilled\n end = start+npts\n nfeatures = 1\n # make numpy array to remake sparseimg\n sparse_np = np.zeros( (npts,2+nfeatures), dtype=np.float32 )\n sparse_np[:,0:2] = coord_np[start:end,0:2]\n sparse_np[:,2] = out_t[start:end,0]\n\n outmeta_v = std.vector(\"larcv::ImageMeta\")()\n outmeta_v.push_back( imgdata.meta_v().front() )\n\n # make the sparseimage object\n sparseimg = larcv.sparseimg_from_ndarray( sparse_np,\n outmeta_v,\n larcv.msg.kNORMAL )\n\n # convert to bson string\n bson = larcv.json.as_bson_pybytes( sparseimg,\n rseid[0], rseid[1], rseid[2], rseid[3] )\n # compress\n if self._use_compression:\n compressed = zlib.compress(bson)\n else:\n compressed = bson\n\n # add to reply message list\n reply.append(compressed)\n\n nfilled += npts\n\n if self._next_msg_id>=nmsgs:\n isfinal = True\n self._still_processing_msg = False\n else:\n isfinal = False\n self._still_processing_msg = True\n\n self._log.debug(\"formed reply with {} frames. isfinal={}\"\n .format(len(reply),isfinal))\n return reply,isfinal\n\n def is_model_loaded(self):\n return self.model is not None\n","repo_name":"LArbys/ublarcvserver","sub_path":"app/UBInfill/sparseinfill/UBInfillSparseWorker.py","file_name":"UBInfillSparseWorker.py","file_ext":"py","file_size_in_byte":10552,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"81"} +{"seq_id":"2976280050","text":"import logging\nimport os\nfrom decimal import Decimal\nfrom multiprocessing import Pool\n\nimport numpy as np\nimport pyarrow\nfrom future.utils import raise_with_traceback\nfrom pyarrow.filesystem import LocalFileSystem\n\nlogger = logging.getLogger(__name__)\n\n\ndef run_in_subprocess(func, *args, **kwargs):\n \"\"\"\n Run some code in a separate process and return the result. Once the code is done, terminate the process.\n This prevents a memory leak in the other process from affecting the current process.\n\n Gotcha: func must be a functioned defined at the top level of the module.\n :param kwargs: dict\n :param args: list\n :param func:\n :return:\n \"\"\"\n pool = Pool(1)\n result = pool.apply(func, args=args, kwds=kwargs)\n\n # Probably not strictly necessary since terminate is called on GC, but it's not guaranteed when the pool will get\n # GC'd.\n pool.terminate()\n return result\n\n\nclass DecodeFieldError(RuntimeError):\n pass\n\n\ndef decode_row(row, schema):\n \"\"\"\n Decode dataset row according to coding spec from unischema object\n\n If a codec is set, we use codec.decode() to produce decoded value.\n\n For scalar fields, the codec maybe set to `None`. In that case:\n - If the numpy_dtype is a numpy scalar or a Decimal, cast the 'encoded' value before returning.\n - In any other case, return the value 'as is'.\n\n :param row: dictionary with encodded values\n :param schema: unischema object\n :return:\n \"\"\"\n decoded_row = dict()\n for field_name_unicode, _ in row.items():\n field_name = str(field_name_unicode)\n if field_name in schema.fields:\n try:\n if row[field_name] is not None:\n field = schema.fields[field_name]\n codec = schema.fields[field_name].codec\n if codec:\n decoded_row[field_name] = codec.decode(field, row[field_name])\n elif field.numpy_dtype and issubclass(field.numpy_dtype, (np.generic, Decimal)):\n decoded_row[field_name] = field.numpy_dtype(row[field_name])\n else:\n decoded_row[field_name] = row[field_name]\n else:\n decoded_row[field_name] = None\n except Exception: # pylint: disable=broad-except\n raise_with_traceback(DecodeFieldError('Decoding field \"{}\" failed'.format(field_name)))\n\n return decoded_row\n\n\ndef add_to_dataset_metadata(dataset, key, value):\n \"\"\"\n Adds a key and value to the parquet metadata file of a parquet dataset.\n :param dataset: (ParquetDataset) parquet dataset\n :param key: (str) key of metadata entry\n :param value: (str) value of metadata\n \"\"\"\n if not isinstance(dataset.paths, str):\n raise ValueError('Expected dataset.paths to be a single path, not a list of paths')\n\n metadata_file_path = dataset.paths.rstrip('/') + '/_metadata'\n common_metadata_file_path = dataset.paths.rstrip('/') + '/_common_metadata'\n common_metadata_file_crc_path = dataset.paths.rstrip('/') + '/._common_metadata.crc'\n\n # If the metadata file already exists, add to it.\n # Otherwise fetch the schema from one of the existing parquet files in the dataset\n if dataset.fs.exists(common_metadata_file_path):\n with dataset.fs.open(common_metadata_file_path) as f:\n arrow_metadata = pyarrow.parquet.read_metadata(f)\n elif dataset.fs.exists(metadata_file_path):\n # If just the metadata file exists and not the common metadata file, copy the contents of\n # the metadata file to the common_metadata file for backwards compatibility\n with dataset.fs.open(metadata_file_path) as f:\n arrow_metadata = pyarrow.parquet.read_metadata(f)\n else:\n arrow_metadata = dataset.pieces[0].get_metadata()\n\n base_schema = arrow_metadata.schema.to_arrow_schema()\n\n # base_schema.metadata may be None, e.g.\n metadata_dict = base_schema.metadata or dict()\n metadata_dict[key] = value\n schema = base_schema.with_metadata(metadata_dict)\n\n with dataset.fs.open(common_metadata_file_path, 'wb') as metadata_file:\n pyarrow.parquet.write_metadata(schema, metadata_file)\n\n # We have just modified _common_metadata file, but the filesystem implementation used by pyarrow does not\n # update the .crc value. We better delete the .crc to make sure there is no mismatch between _common_metadata\n # content and the checksum.\n if isinstance(dataset.fs, LocalFileSystem) and dataset.fs.exists(common_metadata_file_crc_path):\n try:\n dataset.fs.rm(common_metadata_file_crc_path)\n except NotImplementedError:\n os.remove(common_metadata_file_crc_path)\n","repo_name":"uber/petastorm","sub_path":"petastorm/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":4754,"program_lang":"python","lang":"en","doc_type":"code","stars":1690,"dataset":"github-code","pt":"81"} +{"seq_id":"31368710794","text":"import twenty_seven_tic_tac_toe_draw\r\n\r\nboard_size = input('\\nWelcome to tic-tac-toe.\\nPlease enter size of board as \\'row, column\\' (ex. 3, 3): ')\r\n\r\nwhile int(board_size[0]) < 3 or int(board_size[3]) < 3 or int(board_size[0]) != int(board_size[3]):\r\n board_size = input('\\nSmallest board size allowed is 3, 3. Number of rows and number of columns must be the same.'\r\n '\\nPlease re-enter size of board: ')\r\n\r\none_name = input('\\nPlayer X\\'s name: ')\r\ntwo_name = input('Player O\\'s name: ')\r\nanswer = input('\\nPlease enter your moves as \\'row, column\\' (ex. 2, 3). Press any key to start the game.')\r\n\r\ntwenty_seven_tic_tac_toe_draw.draw_game(one_name, two_name, board_size)\r\n\r\n","repo_name":"christina-chen-cco2/project-source-codes","sub_path":"tic_tac_toe/play_tic_tac_toe.py","file_name":"play_tic_tac_toe.py","file_ext":"py","file_size_in_byte":703,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"75129578825","text":"# Barbara King\n# num2eng4.py\n\ndef digit_to_english(N):\n if N == 0:\n return \"zero\"\n elif N == 1:\n return \"one\"\n elif N == 2:\n return \"two\"\n elif N == 3:\n return \"three\"\n elif N == 4:\n return \"four\"\n elif N == 5:\n return \"five\"\n elif N == 6:\n return \"six\"\n elif N == 7:\n return \"seven\"\n elif N == 8:\n return \"eight\"\n elif N == 9:\n return \"nine\"\n else:\n return \"ten\"\n\ndef teens_to_english(N):\n if N == 10:\n return \"ten\"\n elif N == 11:\n return \"eleven\"\n elif N == 12:\n return \"twelve\"\n elif N == 13:\n return \"thirteen\"\n elif N == 14:\n return \"fourteen\"\n elif N == 15:\n return \"fifteen\"\n elif N == 16:\n return \"sixteen\"\n elif N == 17:\n return \"seventeen\"\n elif N == 18:\n return \"eighteen\"\n else:\n return \"nineteen\"\n\ndef tens_to_english(N):\n N = 10 * N\n if N == 20:\n return \"twenty\"\n elif N == 30:\n return \"thirty\"\n elif N == 40:\n return \"fourty\"\n elif N == 50:\n return \"fifty\"\n elif N == 60:\n return \"sixty\"\n elif N == 70:\n return \"seventy\"\n elif N == 80:\n return \"eighty\"\n elif N == 90:\n return \"ninety\"\n\ndef num_to_english(N):\n\n first_digit = 0\n second_digt = 0\n eng_word1 = ''\n eng_word2 = ''\n\n if N < 0 or N > 100:\n return \"Invalid\"\n else:\n if N >= 0 and N <= 10:\n return digit_to_english(N)\n elif N > 10 and N < 20:\n return teens_to_english(N)\n else:\n if N >= 20 and N < 100:\n first_digit = N // 10\n second_digit = N % 10\n eng_word1 = tens_to_english(first_digit)\n if second_digit != 0:\n eng_word2 = digit_to_english(second_digit)\n result = eng_word1 + '-' + eng_word2\n return result\n else:\n return tens_to_english(first_digit)\n else:\n return \"one-hundred\"\n\ndef main():\n intnum = int(input(\"Enter a number equal to or between 0 and 100: \"))\n print(num_to_english(intnum))\n\n\nif __name__ == \"__main__\":\n main()","repo_name":"barbking/python-learning-htt-book","sub_path":"chapter7/num2eng4.py","file_name":"num2eng4.py","file_ext":"py","file_size_in_byte":2266,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"6123141580","text":"from django.http import JsonResponse\nfrom django.views.decorators.csrf import csrf_exempt\n\nfrom ...models import Title, Task, TaskOrder, Course\nfrom ..utils import get_element_or_404\n\n\ndef task_create(request, id):\n if request.user.is_superuser:\n course_title = get_element_or_404(Title, id)\n\n if isinstance(course_title, JsonResponse):\n return course_title\n \n if request.method == 'POST':\n title = request.POST.get('title', '')\n type = request.POST.get('type','text')\n points = request.POST.get('points', 0)\n\n if 0 < len(title) < 255:\n task = Task.objects.create(\n title = title,\n type = type,\n points = points,\n public = False\n )\n task.save()\n \n order = course_title.tasks.count() + 1\n TaskOrder.objects.create(title=title, task=task, order=order)\n title.tasks.add(title)\n\n return JsonResponse({\n 'status': 'success',\n 'message': ' The subject created successfully!'\n }, status=201)\n else:\n return JsonResponse({\n 'status': 'error',\n 'message': ' The subject cannot be less than 0 or more than 255 characters.'\n }, status=400)\n \n else: \n return JsonResponse({\n 'status': 'error',\n 'message': 'Method not allowed'\n }, status=402)\n else:\n return JsonResponse({\n 'status': 'error',\n 'message': 'User is not a superuser'\n }, status=403)\n\n\n@csrf_exempt\ndef task_update_delete(request, id, task_id):\n if request.user.is_superuser:\n course = get_element_or_404(Course, id)\n\n if isinstance(course, JsonResponse):\n return course\n\n task = get_element_or_404(Task, task_id)\n\n if isinstance(task, JsonResponse):\n return task\n\n if request.method == 'POST':\n title = request.POST.get('task_title', '')\n public = request.POST.get('public', None)\n points = request.POST.get('points', None)\n\n if 0 < len(title) < 255:\n task.title = title\n is_changed = True\n task.save()\n\n if public:\n if public == 'true':\n task.public = False\n else:\n task.public = True\n is_changed = True\n task.save()\n\n if points:\n task.points = points\n is_changed = True\n task.save()\n\n if is_changed:\n return JsonResponse({\n 'status': 'success',\n 'message': 'Task updated successfully!'\n }, status=200)\n else:\n return JsonResponse({\n 'status': 'success',\n 'message': 'Task didn\\'t change!'\n }, status=200)\n if request.method == 'DELETE':\n task.delete()\n\n return JsonResponse({}, status=204)\n\n else:\n return JsonResponse({\n 'status': 'error',\n 'message': 'Method not allowed'\n }, status=402)\n else:\n return JsonResponse({\n 'status': 'error',\n 'message': 'User is not a superuser'\n }, status=403)","repo_name":"Jaswine/Code-Cources-Platform","sub_path":"course/api/views/tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":3565,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"81"} +{"seq_id":"10702578749","text":"import os\nfrom dataclasses import dataclass, field\nfrom datetime import datetime, timedelta, time\nfrom typing import NoReturn\n\nimport numpy as np\nfrom path import Path\nfrom rich.prompt import Confirm\n\nfrom daynight_theme.command_register import register_command\nfrom daynight_theme.commands.command import Command\nfrom daynight_theme.sunrise_sunset_api import SunriseSunsetData\n\nBITDAY_PREFIX = Path(os.environ[\"HOME\"]) / 'Pictures' / 'bitday'\n\n\ndef to_datetime(t: time) -> datetime:\n return datetime(2000, 1, 1,\n t.hour,\n t.minute,\n t.second)\n\n\ndef _download_bitday_images():\n import zipfile\n os.chdir(Path(os.environ['HOME']) / 'Pictures')\n dst_folder = Path('bitday')\n if dst_folder.exists():\n dst_folder.rmtree()\n dst_folder.mkdir()\n with zipfile.ZipFile('./BitDay-2-1920x1080.zip', 'r') as f:\n f.extractall(dst_folder)\n (dst_folder / '__MACOSX').rmtree()\n images_folder: Path = dst_folder / '1920x1080'\n for img in images_folder.files('*.png'):\n img.move(dst_folder)\n images_folder.rmtree()\n print('Put bitday images into', dst_folder.abspath())\n\n\n@register_command(priority=3)\nclass BitDayBackground(Command):\n\n asap_update: bool = True\n\n def __init__(self, config: dict):\n super().__init__(config)\n self.sunrise_sunset = SunriseSunsetData(config['day_start'], config['day_end'])\n day_spans = np.linspace(0, self.sunrise_sunset.delta_sunset_sunrise_seconds, 7)[1:]\n night_spans = np.linspace(0, self.sunrise_sunset.delta_sunrise_sunset_seconds, 7)[1:]\n self.max_diff_second_sunrise_sunset = max(self.sunrise_sunset.delta_sunset_sunrise_seconds,\n self.sunrise_sunset.delta_sunrise_sunset_seconds)\n sunrise_dt = self.sunrise_sunset.sunrise\n sunset_dt = self.sunrise_sunset.sunset\n sunrise_dt = datetime(2000, 1, 1,\n sunrise_dt.hour,\n sunrise_dt.minute,\n sunrise_dt.second)\n sunset_dt = datetime(2000, 1, 1,\n sunset_dt.hour,\n sunset_dt.minute,\n sunset_dt.second)\n\n self.day_spans = [(sunrise_dt + timedelta(seconds=v)).time() for v in day_spans]\n self.night_spans = [(sunset_dt + timedelta(seconds=v)).time() for v in night_spans]\n self.day_images = ['01-Early-Morning.png',\n '02-Mid-Morning.png',\n '03-Late-Morning.png',\n '04-Early-Afternoon.png',\n '05-Mid-Afternoon.png',\n '06-Late-Afternoon.png']\n\n self.night_images = ['07-Early-Evening.png',\n '08-Mid-Evening.png',\n '09-Late-Evening.png',\n '10-Early-Night.png',\n '11-Mid-Night.png',\n '12-Late-Night.png']\n self.day_images = [BITDAY_PREFIX / x for x in self.day_images]\n self.night_images = [BITDAY_PREFIX / x for x in self.night_images]\n\n @property\n def day_value(self) -> str:\n return 'day'\n\n @property\n def night_value(self) -> str:\n return 'night'\n\n @staticmethod\n def is_runnable(config) -> bool:\n return config['bitday_background']\n\n #todo: add tests\n def action(self, value: str):\n time_spans = self.day_spans if value == 'day' else self.night_spans\n cur_time = datetime.now().time()\n if value == 'night':\n time_spans = [(to_datetime(t) - timedelta(hours=12)).time() for t in time_spans]\n cur_time = (to_datetime(cur_time) - timedelta(hours=12)).time()\n images = self.day_images if value == 'day' else self.night_images\n imgpath = self._find_background_image(images, time_spans, cur_time)\n print('set', str(imgpath))\n cmd = self._cmd_background(imgpath.abspath())\n os.system(cmd)\n\n def _find_background_image(self, images, time_spans, cur_time) -> Path:\n for i in range(len(time_spans)):\n time_span = time_spans[i]\n if time_span > cur_time:\n return images[i]\n\n def _cmd_background(self, imgpath: str) -> str:\n return f\"gsettings set org.gnome.desktop.background picture-uri file://{imgpath}\"\n\n @staticmethod\n def on_config_setup(config) -> NoReturn:\n bitday_background = Confirm.ask('Do you want bitday background? [yes/no]')\n if bitday_background:\n _download_bitday_images()\n config['bitday_background'] = bitday_background\n\n","repo_name":"Michedev/daynight-theme-gnome","sub_path":"daynight_theme/commands/bitday_background.py","file_name":"bitday_background.py","file_ext":"py","file_size_in_byte":4723,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"4262933952","text":"from datahub.core.serializers import ConstantModelSerializer\nfrom datahub.metadata.fixtures import Fixture\nfrom datahub.metadata.registry import registry\nfrom datahub.omis.order import models\n\n\nclass ServiceTypeFixtures(Fixture):\n \"\"\"Metadata fixtures (for the loadinitialmetadata command).\"\"\"\n\n files = [\n 'fixtures/service_types.yaml',\n ]\n\n\nclass CancellationReasonFixtures(Fixture):\n \"\"\"Metadata fixtures (for the loadinitialmetadata command).\"\"\"\n\n files = [\n 'fixtures/cancellation_reasons.yaml',\n ]\n\n\nregistry.register(\n metadata_id='order-service-type',\n model=models.ServiceType,\n serializer=ConstantModelSerializer,\n)\n\nregistry.register(\n metadata_id='order-cancellation-reason',\n model=models.CancellationReason,\n serializer=ConstantModelSerializer,\n)\n","repo_name":"uktrade/data-hub-api","sub_path":"datahub/omis/order/metadata.py","file_name":"metadata.py","file_ext":"py","file_size_in_byte":811,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"81"} +{"seq_id":"34665962235","text":"from abapy.mesh import RegularQuadMesh\nfrom matplotlib import pyplot as plt\nN1,N2 = 20,20\nl1, l2 = 1., 1.\nmesh1 = RegularQuadMesh(N1 = N1, N2 = N2, l1 = l1, l2 = l2, name = 'mesh1_el')\nmesh2 = RegularQuadMesh(N1 = N1, N2 = N2, l1 = l1, l2 = l2, name = 'mesh2_el')\nmesh2.add_set('set2',[1,3])\n\nmesh2.nodes.translate(x = l1, y = l2)\n\nmesh1.union(mesh2)\n\n\n\nplt.figure()\nxe, ye, ze = mesh1.get_edges()\nplt.plot(xe, ye)\nplt.show()\n","repo_name":"lcharleux/abapy","sub_path":"doc/example_code/mesh/Mesh_union.py","file_name":"Mesh_union.py","file_ext":"py","file_size_in_byte":427,"program_lang":"python","lang":"en","doc_type":"code","stars":75,"dataset":"github-code","pt":"81"} +{"seq_id":"74012910344","text":"import numpy as np\nimport math\nimport os\nimport pandas as pd\n# folder = os.path.join(os.path.dirname( __file__), \"Data/Datasets/npy_TrainTest_Std\")\n# TTtr = np.load(os.path.join(folder, \"test_x_1.npy\"))\n# print(TTtr.shape)\n# Ttr = np.loadtxt(\"Data/Datasets/globalSplit/Ttr_std.csv\", delimiter=',') #1000,2\n# Xtr = np.loadtxt(\"Data/Datasets/globalSplit/Xtr_std.csv\", delimiter=',') #1000,2\n# print(Ttr)\n# T=Ttr\n# X=Xtr\n# l=T[0:3].sum(axis=0)\n# print(l.shape)\n# ns = np.zeros((2,))\n# for b in range(88): # batch sum is much faster\n# \tstart = b * 1000 + 0\n# \tprint(start)\n\t# stop = min((b + 1) * 1000, 87237)\n\t# print(stop)\n\t# ns += T[start:stop].sum(axis=0) # creates(2,) array\n# print(ns) # [ 98. 902.]\n# wc = ns.sum() / ns\n# print(ns.sum()) # 1000.0\n# print(wc) # [10.20408163 1.10864745]\n\n# classification = 'wc'\n# wc_vector = None\n# for b in range(88):\n# \tstart = b*1000 #0\n# \tstop = min((b+1)*1000, 87237) #1000\n# \tXb = X[start:stop]\n# \tTb = T[start:stop]\n# \tbreak\n\t# if classification == \"wc\":# print(Xb.shape)\n\t# \tprint(wc)\n\t# \tprint([np.where(Tb==1)])\n\t# \tprint([np.where(Tb == 1)[1]])\n\t# \tprint(wc[np.where(Tb == 1)[1]])\n\t# \twc_vector = wc[np.where(Tb == 1)[1]]\n\t# print(Xb.shape)\n\t# print(Tb.shape)\n\t# print(wc_vector.shape)\n\t# w = np.array(wc_vector ** 0.5)[:, None]\n\t# print(Xb.shape)\n\t# print(Tb.shape)\n\t# print(wc_vector.shape)\n\t# print(w.shape)\n\t# print(wc_vector ** 0.5)\n\t# print(np.array(wc_vector ** 0.5))\n\t# print(np.array(wc_vector ** 0.5)[:,None])\n\t# break\n\nYtrMax = np.loadtxt(\"tests/Data/YtrMax.csv\", delimiter=',')\nTtrMax = np.loadtxt(\"tests/Data/TtrMax.csv\", delimiter=',')\nDvector = np.array([0.2, 0.2, 0.2, 0.2, 0.2])\nprint(YtrMax)\nprint(TtrMax)\n\nmisclass = (YtrMax != TtrMax) #np.sum((YtrMax != TtrMax)*Dvector)#/Dvector\n# print(misclass)\nweightedmisclass = (YtrMax != TtrMax) * Dvector\n# print(weightedmisclass)\ntotalError = np.sum((YtrMax != TtrMax)*Dvector)/np.sum(Dvector)\n# print(totalError)\nif totalError < 0.5:\n\ta = (1 / 2) * math.log((1 - totalError) / totalError)\n\t# print(a)\n\t# exp = math.exp(-a * YtrMax[0] * TtrMax[0])\n\t# print(exp)\n\tx0 = math.exp(-a * YtrMax[0] * TtrMax[0]) * Dvector[0]\n\tprint(x0)\n\tx1 = math.exp(-a * YtrMax[1] * TtrMax[1]) * Dvector[1]\n\tprint(x1)\n\tx2 = math.exp(-a * YtrMax[2] * TtrMax[2])*Dvector[2]\n\tprint(x2)\n\tx3 = math.exp(-a * YtrMax[3] * TtrMax[3]) * Dvector[3]\n\tprint(x3)\n\tx4 = math.exp(-a * YtrMax[4] * TtrMax[4]) * Dvector[4]\n\tprint(x4)\n\tsum = x1+x2+x3+x4\n\tprint(sum)\n\n\tx0 = math.exp(-a * YtrMax[0] * -1) * Dvector[0]\n\tprint(x0)\n\tx1 = math.exp(-a * YtrMax[1] * -1) * Dvector[1]\n\tprint(x1)\n\tx2 = math.exp(-a * YtrMax[2] * TtrMax[2]) * Dvector[2]\n\tprint(x2)\n\tx3 = math.exp(-a * YtrMax[3] * TtrMax[3]) * Dvector[3]\n\tprint(x3)\n\tx4 = math.exp(-a * YtrMax[4] * TtrMax[4]) * Dvector[4]\n\tprint(x4)\n\tsum = x1 + x2 + x3 + x4\n\tprint(sum)\n\n# exp3 = math.exp(-a * -1 * 1)\n# print(exp3)\n#\n# exp4 = math.exp(-a * 1 * 1)\n# print(exp4)\n\t# top = (-a * YtrMax * TtrMax)\n\t# print(top)\n\t# new = math.exp(-a * YtrMax * TtrMax)\n# \tfor i in range(Dvector.shape[0]):\n# \t\tDvector[i] = Dvector[i] * math.exp(-a * YtrMax[i] * TtrMax[i])\n\n# print(Dvector)\n# m =Dvector/np.sum(Dvector)\n# print(np.sum(m))\n# print(np.sum(Dvector) )\n\n\n# flip\n# Xtr = np.loadtxt(\"tests/Data/data.csv\", delimiter=',') #1000,2\n# print(Xtr.shape[0])\n# D = 1/Xtr.shape[0]\n# D = 1/87237\n# print(D)\n# Dvector = np.ones((30,1))* D\n# print(Dvector.shape)\n","repo_name":"esmeraldaaguayo/extreme-learning-machines","sub_path":"cvstonumpy.py","file_name":"cvstonumpy.py","file_ext":"py","file_size_in_byte":3366,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"33676633958","text":"# Example: Module provides SDI-12 examples\n\n\"\"\"\nThe basis for SDI-12 communication is the command line command SDI,\nwhich may be used to issue any data on any SDI-12 bus on Satlink\n\"\"\"\n\nimport re\nimport utime\nfrom sl3 import *\n\n\nclass Sdi12Error(Exception):\n pass\n\n\ndef sdi_bus_valid(sdi_bus):\n \"\"\"\n Routine checks whether the provided parameter is a SDI-12 bus\n \n :param sdi_bus: string indicating bus: \"Port1\", \"Port2\", or \"RS485\"\n :return: True if provided parameter is a valid bus\n :rtype: Boolean\n \"\"\"\n bus_upper = sdi_bus.upper()\n if (\"PORT1\" in bus_upper) or (\"PORT2\" in bus_upper) or (\"RS485\" in bus_upper):\n return True\n else:\n return False\n\n\ndef sdi_send_command_get_reply(cmd_to_send, sdi_bus=\"Port1\"):\n \"\"\"\n Sends provided command out on the specified SDI-12 bus, gets reply from the sensor.\n \n :param cmd_to_send: the command to send on the SDI-12 bus, e.g. \"0M!\"\n :param sdi_bus: string indicating bus: \"Port1\", \"Port2\", or \"RS485\"\n :return: sensor reply, or \"No reply\"\n :rtype: str\n \"\"\"\n\n if sdi_bus_valid(sdi_bus):\n reply = command_line('!SDI {} {}'.format(sdi_bus, cmd_to_send), 128)\n if \"Got reply: \" in reply:\n reply = reply.replace(\"Got reply:\", \"\")\n else:\n raise Sdi12Error(\"No such bus\", sdi_bus)\n\n reply = reply.strip()\n return reply\n\n\ndef sdi_collect(address, command=\"M\", sdi_bus=\"Port1\"):\n \"\"\"\n Collects data from an SDI-12 sensor using the provided cmd_to_sensor\n It is expected that the sensor will use the same reply format as to aM! cmd_to_sensor\n\n :param address: int address of SDI-12 sensor to collect data from\n :param command: command to issue to sensor, e.g. \"M\"\n :param sdi_bus: string indicating bus: \"Port1\", \"Port2\", or \"RS485\"\n :return: a list of floats containing all the returned parameters\n \"\"\"\n\n # create the SDI-12 cmd_to_sensor using the provided address\n cmd_to_sensor = '{0}{1}!'.format(address, command)\n\n # issue the cmd_to_sensor and get the reply\n sensor_reply = sdi_send_command_get_reply(cmd_to_sensor, sdi_bus)\n\n # parse out the returned values\n parsed = re.match('(\\d)(\\d\\d\\d)(\\d)', sensor_reply)\n if parsed is None or int(parsed.group(1)) != address:\n raise Sdi12Error('No reply or bad reply', sensor_reply)\n\n # figure out how long and then wait for sensor to be ready\n time_till_reply = int(parsed.group(2))\n utime.sleep(time_till_reply)\n\n # how many parameters did the sensor return?\n values_returned = int(parsed.group(3))\n\n # all the parameters returned by the sensor end up here\n result = []\n\n # we will use this expression to parse the values form the sensor reply\n float_match = re.compile('([-+][0-9]*\\.?[0-9]+[eE][-+]?[0-9]+)|([-+][0-9]*\\.?[0-9]*)')\n\n # we need to issue one or more send data commands to the sensor\n data_index = 0\n while len(result) < values_returned and data_index <= 9:\n # create and issue the get data cmd_to_sensor\n cmd_to_sensor = '{0}D{1}!'.format(address, data_index)\n sensor_reply = sdi_send_command_get_reply(cmd_to_sensor, sdi_bus)\n\n if (sensor_reply is None) or (sensor_reply == \"No reply\"):\n raise Sdi12Error('Missing data at pos', len(parsed) + 1)\n\n # parse out all the values returned by the sensor\n while len(result) < values_returned:\n parsed = float_match.search(sensor_reply)\n if parsed is None:\n break\n result.append(float(parsed.group(0)))\n sensor_reply = sensor_reply.replace(parsed.group(0), '', 1)\n\n data_index += 1\n return result\n\n\n# keep track of the result of the last SDI-12 command\nlast_custom_result = None\n\n# keep track of the time we issued the last SDI-12 command\nlast_custom_time = 0\n\n\ndef sdi_collect_improved(address, desired_parameter, command=\"M\", sdi_bus=\"Port1\"):\n \"\"\"\n Collects data from SDI address 0 using the provided command and returns the\n specified parameter. This version is optimized to not re-issue the command\n each time a different parameter is retrieved, if the data had already been\n retrieved in the past 10 seconds.\n \n :param address: int address of SDI-12 sensor\n :param desired_parameter: which SDI-12 parameter to return, 0 based \n (i.e. first param is 0)\n :param command: command to issue, e.g. \"M\"\n :param sdi_bus: string indicating bus: \"Port1\", \"Port2\", or \"RS485\"\n :return: the value of the desired SDI-12 parameter\n \"\"\"\n\n global last_custom_result\n global last_custom_time\n # if it's been more than 10 seconds since we've collected\n # then collect data now:\n if (utime.time() - last_custom_time) > 10:\n try:\n # perform the custom measurement command\n last_custom_result = sdi_collect(address, command, sdi_bus)\n except Sdi12Error as e:\n last_custom_result = e\n last_custom_time = utime.time()\n # if the last request caused an exception, we will just re-raise that\n # exception:\n if type(last_custom_result) is Sdi12Error:\n raise last_custom_result\n # otherwise return the last value for the requested parameter\n return last_custom_result[desired_parameter]\n","repo_name":"mgsorokin/XLink500","sub_path":"src/sdi12.py","file_name":"sdi12.py","file_ext":"py","file_size_in_byte":5292,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"71513834824","text":"import argparse\nimport json\nimport logging\nimport os\nimport random\nfrom io import open\nimport math\nimport sys\nsys.path.append(\"../../\")\n\nfrom time import gmtime, strftime\nfrom timeit import default_timer as timer\n\nimport numpy as np\nfrom tqdm import tqdm, trange\n\nimport torch\nfrom torch.utils.data import DataLoader, Dataset, RandomSampler\nfrom torch.utils.data.distributed import DistributedSampler\nfrom tensorboardX import SummaryWriter\n\nfrom pytorch_pretrained_bert.tokenization import BertTokenizer\nfrom pytorch_pretrained_bert.optimization import BertAdam, WarmupLinearSchedule\n\nfrom dataloaders.pretrain_dataset_IT import Pretrain_DataSet_Train\nfrom model.capture_IT import BertForMultiModalPreTraining, BertConfig\n\nimport torch.distributed as dist\n\nimport pdb\nfrom utils_args import get_args\nlogging.basicConfig(\n format=\"%(asctime)s - %(levelname)s - %(name)s - %(message)s\",\n datefmt=\"%m/%d/%Y %H:%M:%S\",\n level=logging.INFO,\n)\nlogger = logging.getLogger(__name__)\n\n\ndef main():\n\n args = get_args()\n\n\n print(args)\n if args.save_name is not '':\n timeStamp = args.save_name\n else:\n timeStamp = strftime(\"%d-%b-%y-%X-%a\", gmtime())\n timeStamp += \"_{:0>6d}\".format(random.randint(0, 10e6))\n\n savePath = os.path.join(args.output_dir, timeStamp)\n\n if not os.path.exists(savePath):\n os.makedirs(savePath)\n \n config = BertConfig.from_json_file(args.config_file)\n \n if args.freeze > config.t_biattention_id[0]:\n config.fixed_t_layer = config.t_biattention_id[0]\n\n if args.without_coattention:\n config.with_coattention = False\n # save all the hidden parameters. \n with open(os.path.join(savePath, 'command.txt'), 'w') as f:\n print(args, file=f) # Python 3.x\n print('\\n', file=f)\n print(config, file=f)\n\n bert_weight_name = json.load(open(\"../../config/bert-base-uncased_weight_name.json\", \"r\"))\n if args.local_rank == -1 or args.no_cuda:\n device = torch.device(\n \"cuda\" if torch.cuda.is_available() and not args.no_cuda else \"cpu\"\n )\n n_gpu = torch.cuda.device_count()\n else:\n torch.cuda.set_device(args.local_rank)\n device = torch.device(\"cuda\", args.local_rank)\n n_gpu = 1\n # Initializes the distributed backend which will take care of sychronizing nodes/GPUs\n torch.distributed.init_process_group(backend=\"nccl\")\n logger.info(\n \"device: {} n_gpu: {}, distributed training: {}, 16-bits training: {}\".format(\n device, n_gpu, bool(args.local_rank != -1), args.fp16\n )\n )\n\n if args.gradient_accumulation_steps < 1:\n raise ValueError(\n \"Invalid gradient_accumulation_steps parameter: {}, should be >= 1\".format(\n args.gradient_accumulation_steps\n )\n )\n\n args.train_batch_size = args.train_batch_size // args.gradient_accumulation_steps\n\n random.seed(args.seed)\n np.random.seed(args.seed)\n torch.manual_seed(args.seed)\n if n_gpu > 0:\n torch.cuda.manual_seed_all(args.seed)\n\n if not os.path.exists(args.output_dir):\n os.makedirs(args.output_dir)\n\n tokenizer = BertTokenizer.from_pretrained(\n args.bert_model, do_lower_case=args.do_lower_case\n )\n\n viz = TBlogger(\"logs\", timeStamp)\n\n print(\"MLM: {} MRM:{} ITM:{}, CLR:{}\".format(args.MLM, args.MRM, args.ITM,args.CLR))\n\n\n train_dataset = Pretrain_DataSet_Train(\n tokenizer,\n seq_len=args.max_seq_length,\n batch_size=args.train_batch_size,\n predict_feature=args.predict_feature,\n num_workers=args.num_workers,\n lmdb_file=args.lmdb_file,\n caption_path=args.caption_path,\n MLM=args.MLM,\n MRM=args.MRM,\n ITM=args.ITM\n )\n\n num_train_optimization_steps = (\n int(\n train_dataset.num_dataset\n / args.train_batch_size\n / args.gradient_accumulation_steps\n )\n * (args.num_train_epochs - args.start_epoch)\n )\n\n default_gpu = False\n if dist.is_available() and args.distributed:\n rank = dist.get_rank()\n if rank == 0:\n default_gpu = True\n else:\n default_gpu = True\n\n # pdb.set_trace()\n if args.predict_feature:\n config.v_target_size = 2048\n config.predict_feature = True\n else:\n config.v_target_size = 1601\n config.predict_feature = False\n\n if args.from_pretrained:\n model = BertForMultiModalPreTraining.from_pretrained(args.from_pretrained, config)\n else:\n model = BertForMultiModalPreTraining(config)\n\n model.cuda()\n\n if args.fp16:\n model.half()\n if args.local_rank != -1:\n try:\n from apex import DistributedDataParallel as DDP\n except ImportError:\n raise ImportError(\n \"Please install apex from https://www.github.com/nvidia/apex to use distributed and fp16 training.\"\n )\n model = DDP(model)\n elif n_gpu > 1:\n model = torch.nn.DataParallel(model)\n\n no_decay = [\"bias\", \"LayerNorm.bias\", \"LayerNorm.weight\"]\n\n if args.freeze != -1:\n bert_weight_name_filtered = []\n for name in bert_weight_name:\n if 'embeddings' in name:\n bert_weight_name_filtered.append(name)\n elif 'encoder' in name:\n layer_num = name.split('.')[2]\n if int(layer_num) <= args.freeze:\n bert_weight_name_filtered.append(name)\n\n optimizer_grouped_parameters = []\n for key, value in dict(model.named_parameters()).items():\n if key[12:] in bert_weight_name_filtered:\n value.requires_grad = False\n\n if default_gpu:\n print(\"filtered weight\")\n print(bert_weight_name_filtered)\n\n if not args.from_pretrained:\n param_optimizer = list(model.named_parameters())\n optimizer_grouped_parameters = [\n {\n \"params\": [\n p for n, p in param_optimizer if not any(nd in n for nd in no_decay)\n ],\n \"weight_decay\": 0.01,\n },\n {\n \"params\": [\n p for n, p in param_optimizer if any(nd in n for nd in no_decay)\n ],\n \"weight_decay\": 0.0,\n },\n ]\n else:\n optimizer_grouped_parameters = []\n for key, value in dict(model.named_parameters()).items():\n if value.requires_grad:\n if key[12:] in bert_weight_name:\n lr = args.learning_rate * 0.1\n else:\n lr = args.learning_rate\n\n if any(nd in key for nd in no_decay):\n optimizer_grouped_parameters += [\n {\"params\": [value], \"lr\": lr, \"weight_decay\": 0.01}\n ]\n\n if not any(nd in key for nd in no_decay):\n optimizer_grouped_parameters += [\n {\"params\": [value], \"lr\": lr, \"weight_decay\": 0.0}\n ]\n if default_gpu:\n print(len(list(model.named_parameters())), len(optimizer_grouped_parameters))\n\n # set different parameters for vision branch and lanugage branch.\n if args.fp16:\n try:\n from apex import FP16_Optimizer\n from apex import FusedAdam\n except ImportError:\n raise ImportError(\n \"Please install apex from https://www.github.com/nvidia/apex to use distributed and fp16 training.\"\n )\n\n optimizer = FusedAdam(\n optimizer_grouped_parameters,\n lr=args.learning_rate,\n bias_correction=False,\n max_grad_norm=1.0,\n )\n if args.loss_scale == 0:\n optimizer = FP16_Optimizer(optimizer, dynamic_loss_scale=True)\n else:\n optimizer = FP16_Optimizer(optimizer, static_loss_scale=args.loss_scale)\n\n else:\n if args.from_pretrained:\n optimizer = BertAdam(\n optimizer_grouped_parameters,\n warmup=args.warmup_proportion,\n t_total=num_train_optimization_steps,\n\n )\n\n else:\n optimizer = BertAdam(\n optimizer_grouped_parameters,\n lr=args.learning_rate,\n warmup=args.warmup_proportion,\n t_total=num_train_optimization_steps,\n )\n\n logger.info(\"***** Running training *****\")\n logger.info(\" Num examples = %d\", train_dataset.num_dataset)\n logger.info(\" Batch size = %d\", args.train_batch_size)\n logger.info(\" Num steps = %d\", num_train_optimization_steps)\n\n startIterID = 0\n global_step = 0\n masked_loss_v_tmp = 0\n masked_loss_t_tmp = 0\n next_sentence_loss_tmp = 0\n loss_tmp = 0\n start_t = timer()\n\n\n print(\"Prepare to training!\")\n print(\"MLM: {} MRM:{} ITM:{}\".format(args.MLM, args.MRM, args.ITM))\n right_temp=0\n all_num_temp=0\n\n\n for epochId in range(int(args.start_epoch), int(args.num_train_epochs)):\n model.train()\n tr_loss = 0\n nb_tr_examples, nb_tr_steps = 0, 0\n for step, batch in enumerate(tqdm(train_dataset)):\n iterId = startIterID + step + (epochId * len(train_dataset))\n image_id=batch[-1]\n batch=batch[:-1]\n batch = tuple(t.cuda(device=device, non_blocking=True) for t in batch)\n\n input_ids, input_mask, segment_ids, lm_label_ids, is_next,\\\n image_feat, image_loc, image_target, image_label, image_mask= (\n batch\n )\n\n masked_loss_t,masked_loss_v, \\\n next_sentence_loss = model(\n input_ids,\n image_feat,\n image_loc,\n segment_ids,\n input_mask,\n image_mask,\n lm_label_ids,\n image_label,\n image_target,\n is_next,\n )\n\n masked_loss_v = masked_loss_v * args.img_weight\n if not args.MLM:\n masked_loss_t=masked_loss_t*0\n if not args.MRM:\n masked_loss_v=masked_loss_v*0\n if not args.CLR:\n next_sentence_loss=next_sentence_loss*0\n\n loss = masked_loss_t \\\n + masked_loss_v \\\n + next_sentence_loss\n\n right=0\n all_num=0\n right_temp+=right\n all_num_temp+=all_num\n\n if n_gpu > 1:\n loss = loss.mean() # mean() to average on multi-gpu.\n masked_loss_t = masked_loss_t.mean()\n masked_loss_v = masked_loss_v.mean()\n next_sentence_loss = next_sentence_loss.mean()\n if args.gradient_accumulation_steps > 1:\n loss = loss / args.gradient_accumulation_steps\n if args.fp16:\n optimizer.backward(loss)\n else:\n loss.backward()\n\n if math.isnan(loss.item()):\n pdb.set_trace()\n\n tr_loss += loss.item()\n\n rank = 0\n\n if dist.is_available() and args.distributed:\n rank = dist.get_rank()\n else:\n rank = 0\n \n viz.linePlot(iterId, loss.item(), \"loss_\"+str(rank), \"train\")\n viz.linePlot(iterId, masked_loss_t.item(), \"masked_loss_t_\"+str(rank), \"train\")\n viz.linePlot(iterId, masked_loss_v.item(), \"masked_loss_v_\"+str(rank), \"train\")\n viz.linePlot(\n iterId, next_sentence_loss.item(), \"next_sentence_loss_\"+str(rank), \"train\"\n )\n # viz.linePlot(iterId, optimizer.get_lr()[0], 'learning_rate', 'train')\n\n loss_tmp += loss.item()\n masked_loss_v_tmp += masked_loss_v.item()\n masked_loss_t_tmp += masked_loss_t.item()\n next_sentence_loss_tmp += next_sentence_loss.item()\n\n nb_tr_examples += input_ids.size(0)\n nb_tr_steps += 1\n if (step + 1) % args.gradient_accumulation_steps == 0:\n if args.fp16:\n # modify learning rate with special warm up BERT uses\n # if args.fp16 is False, BertAdam is used that handles this automatically\n lr_this_step = args.learning_rate * warmup_linear(\n global_step / num_train_optimization_steps,\n args.warmup_proportion,\n )\n for param_group in optimizer.param_groups:\n param_group[\"lr\"] = lr_this_step\n\n optimizer.step()\n optimizer.zero_grad()\n global_step += 1\n\n if step % 20 == 0 and step != 0:\n masked_loss_t_tmp = masked_loss_t_tmp / 20.0\n masked_loss_v_tmp = masked_loss_v_tmp / 20.0\n next_sentence_loss_tmp = next_sentence_loss_tmp / 20.0\n loss_tmp = loss_tmp / 20.0\n\n end_t = timer()\n timeStamp = strftime(\"%a %d %b %y %X\", gmtime())\n\n Ep = epochId + nb_tr_steps / float(len(train_dataset))\n printFormat = \"[%s][Ep: %.2f][Iter: %d][Time: %5.2fs][Loss: %.5g][Loss_v: %.5g][Loss_t: %.5g][Loss_n: %.5g][LR: %.8g][epoch: %d][step: %d]\"\n\n printInfo = [\n timeStamp,\n Ep,\n nb_tr_steps,\n end_t - start_t,\n loss_tmp,\n masked_loss_v_tmp,\n masked_loss_t_tmp,\n next_sentence_loss_tmp,\n optimizer.get_lr()[0],\n epochId,\n step\n ]\n \n start_t = end_t\n print(printFormat % tuple(printInfo))\n\n masked_loss_v_tmp = 0\n masked_loss_t_tmp = 0\n next_sentence_loss_tmp = 0\n loss_tmp = 0\n\n if default_gpu:\n # Save a trained model\n logger.info(\"** ** * Saving fine - tuned model ** ** * \")\n model_to_save = (\n model.module if hasattr(model, \"module\") else model\n ) # Only save the model it-self\n output_model_file = os.path.join(\n savePath, \"pytorch_model_\" + str(epochId) + \".bin\"\n )\n\n torch.save(model_to_save.state_dict(), output_model_file)\n\nclass TBlogger:\n def __init__(self, log_dir, exp_name):\n log_dir = log_dir + \"/\" + exp_name\n print(\"logging file at: \" + log_dir)\n self.logger = SummaryWriter(log_dir=log_dir)\n\n def linePlot(self, step, val, split, key, xlabel=\"None\"):\n self.logger.add_scalar(split + \"/\" + key, val, step)\n\nif __name__ == \"__main__\":\n # import time\n # time.sleep(3600*3)\n\n main()\n","repo_name":"zhanxlin/Product1M","sub_path":"CAPTURE/examples/IT_capture/pretrain_task.py","file_name":"pretrain_task.py","file_ext":"py","file_size_in_byte":14925,"program_lang":"python","lang":"en","doc_type":"code","stars":81,"dataset":"github-code","pt":"81"} +{"seq_id":"34677537222","text":"# Given two binary search trees root1 and root2.\r\n#\r\n# Return a list containing all the integers from both trees sorted in ascending order.\r\n#\r\n#\r\n#\r\n# Example 1:\r\n#\r\n#\r\n# Input: root1 = [2,1,4], root2 = [1,0,3]\r\n# Output: [0,1,1,2,3,4]\r\n# Example 2:\r\n#\r\n# Input: root1 = [0,-10,10], root2 = [5,1,7,0,2]\r\n# Output: [-10,0,0,1,2,5,7,10]\r\n# Example 3:\r\n#\r\n# Input: root1 = [], root2 = [5,1,7,0,2]\r\n# Output: [0,1,2,5,7]\r\n# Example 4:\r\n#\r\n# Input: root1 = [0,-10,10], root2 = []\r\n# Output: [-10,0,10]\r\n# Example 5:\r\n#\r\n#\r\n# Input: root1 = [1,null,8], root2 = [8,1]\r\n# Output: [1,1,8,8]\r\n#\r\n#\r\n# Constraints:\r\n#\r\n# Each tree has at most 5000 nodes.\r\n# Each node's value is between [-10^5, 10^5].\r\n\r\n\r\n# Definition for a binary tree node.\r\n# class TreeNode:\r\n# def __init__(self, val=0, left=None, right=None):\r\n# self.val = val\r\n# self.left = left\r\n# self.right = right\r\nclass Solution:\r\n def getAllElements(self, root1: TreeNode, root2: TreeNode) -> List[int]:\r\n\r\n #inorder traversal.\r\n def inorder(root):\r\n stack = []\r\n while stack or root:\r\n if root:\r\n stack.append(root)\r\n root = root.left\r\n else:\r\n root = stack.pop()\r\n yield root.val #uses yield\r\n root = root.right\r\n ans = []\r\n arr1 = [i for i in inorder(root1)]\r\n arr2 = [i for i in inorder(root2)]\r\n ans = sorted(arr1 + arr2)\r\n return ans\r\n\r\n #simpler solution\r\n values = []\r\n def collect(root):\r\n if root:\r\n collect(root.left)\r\n values.append(root.val)\r\n collect(root.right)\r\n collect(root1)\r\n collect(root2)\r\n return sorted(values)\r\n","repo_name":"vye2/leetcode","sub_path":"Medium/1305.all_elements_in_two_bst.py","file_name":"1305.all_elements_in_two_bst.py","file_ext":"py","file_size_in_byte":1815,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"20309292271","text":"#iterative LCS solution using dynamic programming\ndef lcs_dp(seq1, seq2):\n n1, n2 = len(seq1), len(seq2)\n table = [[0 for x in range(n2+1)] for x in range(n1+1)]\n #iterate over rows\n for i in range(n1):\n #iterate over columns\n for j in range(n2):\n if seq1[i] == seq2[j]:\n table[i+1][j+1] = 1 + table[i][j]\n else:\n table[i+1][j+1] = max(table[i][j+1], table[i+1][j])\n return table[-1][-1]","repo_name":"TraeCoker/python-ds-and-algo-examples","sub_path":"lcs_dynamic_programming.py","file_name":"lcs_dynamic_programming.py","file_ext":"py","file_size_in_byte":468,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"81"} +{"seq_id":"6225985575","text":"# This method create a dictionary of colors.\ndef method_color():\n colors = {\n 'white': '\\033[30m',\n 'red': '\\033[31m',\n 'green': '\\033[32m',\n 'yellow': '\\033[33m',\n 'blue': '\\033[34m',\n 'purple': '\\033[35m',\n 'navy blue': '\\033[36m',\n 'grey': '\\033[37m'\n }\n return colors\n\n\n# This method get the values and print in terminal.\ndef message(msg, color):\n colors = method_color()\n print(f'{colors[color]}{msg}\\033[m')\n\n\nmessage('Hello Word!!', 'green')","repo_name":"Suspir0n/100DaysCode","sub_path":"Day_23.py","file_name":"Day_23.py","file_ext":"py","file_size_in_byte":519,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"81"} +{"seq_id":"37168714031","text":"from leetcode import TreeNode\nfrom operator import mul\nclass Solution(object):\n def numTrees(self, n):\n if n==0:\n return 0\n res=[1,1]\n resr=[1,1]\n cnt=1\n while cnt= 3\n","repo_name":"charliec443/spellstore","sub_path":"tests/test_featurestore.py","file_name":"test_featurestore.py","file_ext":"py","file_size_in_byte":738,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"22948922023","text":"# Задача: если есть сетка кварталов и человек может идти в любую сторону с вероятностью 0.25. \n# Какая вероятность что он не уйдет дальше 2 перекрестков от начального?\n\nimport random\nfrom random import randint\n\ndef generateRandomMoving():\n xmoving = 0\n ymoving = 0\n\n if random.choice([True, False]):\n while ymoving == 0:\n ymoving = randint(-1, 1)\n else:\n while xmoving == 0:\n xmoving = randint(-1, 1)\n\n return xmoving, ymoving\n\n\ndef faraway(cd: list):\n counter = abs(cd[0]) + abs(cd[1])\n return counter\n\n\ndef experiment(N=10, M=2):\n startCoordinates = [0, 0]\n\n for i in range(1, N):\n x, y = generateRandomMoving()\n startCoordinates[0] += x\n startCoordinates[1] += y\n\n currentGeo = faraway(startCoordinates)\n return currentGeo <= M\n\n\ndef getProbability(iterationmax=10000):\n probabilityNearTheHouse = 0\n for i in range(iterationmax):\n if experiment():\n probabilityNearTheHouse += 1\n print(probabilityNearTheHouse / iterationmax)\n \n \ngetProbability()","repo_name":"Sapfir0/scriptForOurLife","sub_path":"problems/walkingMan/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1220,"program_lang":"python","lang":"ru","doc_type":"code","stars":1,"dataset":"github-code","pt":"81"} +{"seq_id":"4675475128","text":"import json\nimport plac\n\n@plac.annotations(filename=(\"Input File\", \"option\", \"i\", str),\n cutoff=(\"Minimum number of labels cutoff\",\"option\",\"c\",int))\n\ndef main(filename=None,cutoff=10):\n clean_labels(filename,cutoff)\n return\n\n\ndef clean_labels(input_file,cutoff=10):\n output_file = input_file.split('.')[0]+'_cleaned'+'.json'\n with open(fname,'r') as f:\n lines = f.readlines()\n all_labels = []\n for line in lines:\n labels = [l['label'][0] for l in json.loads(line)['annotation']]\n all_labels.extend(labels)\n\n label_list = set(all_labels)\n unimportant = []\n for l in label_list:\n ct = all_labels.count(l)\n if ct < cutoff:\n unimportant.append(l)\n fp = open(output_file, 'w')\n for line in lines:\n L = json.loads(line)\n r = {'content': L['content']}\n annotation = []\n for a in L['annotation']:\n if a['label'][0] in unimportant:\n pass\n else:\n annotation.append(a)\n r['annotation'] = annotation\n json.dump(r, fp)\n fp.write('\\n')\n return\n\n\nif __name__ == '__main__':\n fname = 'example_data/best_buy_test.json'\n clean_labels(fname)","repo_name":"ianbakst/custom-ner","sub_path":"entity_extractor/archive/label_filter.py","file_name":"label_filter.py","file_ext":"py","file_size_in_byte":1229,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"28928356416","text":"\"\"\"This module defines urls of messages app\"\"\"\n\nfrom django.urls import path\nfrom .views import get_messages, add_message, get_message, update_message, delete_message\n\nurlpatterns = [\n path('', get_messages, name='get_messages'),\n path('add_message/', add_message, name='add_message'),\n path('get_message//', get_message, name='get_message'),\n path('update_message//', update_message, name='update_message'),\n path('delete_message//', delete_message, name='delete_message')\n]\n","repo_name":"howlotus/2022-2-VK-EDU-FS-Backend-B-Ochirov","sub_path":"messenger/chat_messages/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":539,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"24111747326","text":"# -*- coding: utf-8 -*-\n'''\nThis program is free software: you can redistribute it and/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with this program. If not, see \n'''\nfrom flask import Flask\nfrom flask import render_template\nfrom flask import request,url_for,send_file,send_from_directory,redirect,flash,Markup,Response,session\nfrom datetime import datetime\n#import MySQLdb\n#from werkzeug.utils import secure_filename\nimport logging\nimport sys\nimport numpy as np\nimport csv\nimport pandas as pd\n#from flask_mail import Mail\n#from flask_mail import Message\nimport random\nimport json\n#import glob\nimport warnings\nwarnings.filterwarnings('ignore')\n#from sqlalchemy import *\n#import pymysql\n#from flask_httpauth import HTTPBasicAuth\nimport hashlib\nimport time\n#import tracemalloc\nimport semantic_version\n#from flask_wkhtmltopdf import Wkhtmltopdf\nimport os\nimport requests\nimport sqlite3\nfrom bs4 import BeautifulSoup\n\n\nWORKING_DIR='/dados/flask/covid/'\nCOVID_DIR = '/dados/flask/cimai/covid/'\n\nlogging.basicConfig(filename=WORKING_DIR + 'app.log', filemode='w', format='%(asctime)s %(name)s - %(levelname)s - %(message)s',level=logging.DEBUG)\nlogging.debug(\"INICIANDO LOG\")\n\napp = Flask(__name__)\n#auth = HTTPBasicAuth()\n\nversao = semantic_version.Version('1.2.0')\n\ndef getSenha(arquivo):\n f = open(arquivo,'r')\n senha = f.read()\n f.close()\n return(str(senha))\n\ndef hash(str):\n result = hashlib.sha256(str.encode())\n return(result.hexdigest())\n\ndef getCores(quantidade=1):\n r = lambda: random.randint(0,255)\n cores = []\n for i in range(0,quantidade,1):\n cor = ('#%02X%02X%02X' % (r(),r(),r()))\n cores.append(cor)\n return(cores)\n\ndef dadosCovid():\n # ANTONINA DO NORTE, JATI E PENAFORTE - ausentes\n CSV_DIR = '/dados/flask/cimai/covid/'\n cariri = [' JUAZEIRO DO NORTE ', ' CRATO ', ' BARBALHA ', ' BREJO SANTO ']\n cariri = [' ABAIARA ', ' ALTANEIRA ', ' ANTONINA DO NORTE ', ' ARARIPE ', ' ASSARE ', ' AURORA ', ' BARBALHA ', ' BARRO ', ' BREJO SANTO ', ' CAMPOS SALES ', ' CARIRIACU ', ' CRATO ', ' FARIAS BRITO ', ' GRANJEIRO ', ' JARDIM ', ' JATI ', ' JUAZEIRO DO NORTE ', ' LAVRAS DA MANGABEIRA ', ' MAURITI ', ' MILAGRES ', ' MISSAO VELHA ', ' NOVA OLINDA ', ' PENAFORTE ', ' PORTEIRAS ', ' POTENGI ', ' SALITRE ', ' SANTANA DO CARIRI ', ' TARRAFAS ', ' VARZEA ALEGRE ']\n for i in range(0,len(cariri),1):\n cariri[i] = cariri[i].lstrip()\n cariri[i] = cariri[i].rstrip()\n\n gps = pd.read_csv(CSV_DIR + 'cidades.cariri.completo.csv',delimiter=\",\",encoding='utf8',decimal='.')\n df_ceara = pd.read_csv(CSV_DIR + 'TODOS.CEARA.HOJE.CSV',delimiter=\",\",encoding='utf8',decimal='.')\n df_cariri = df_ceara[df_ceara['cidade'].isin(cariri)].sort_values(by=['data','cidade'])\n agrupados = df_cariri.groupby(['data','cidade'])\n\n evolucao = agrupados['confirmado','suspeitos','obitos'].sum()\n dia = agrupados['confirmado','suspeitos','obitos'].sum().tail(len(cariri)).sum(axis=0).tolist()\n porCidade = agrupados['confirmado','suspeitos','obitos','recuperados'].sum().tail(len(cariri))\n porCidade = pd.merge(porCidade,gps,on='cidade')\n agrupadosEvolucao = df_cariri.groupby(['data'])\n evolucaoTotal = agrupadosEvolucao['confirmado','suspeitos','obitos'].sum()\n cidades_confirmadas = porCidade[porCidade['confirmado']>0]\n\n datas = evolucaoTotal.index.to_list()\n confirmados = evolucaoTotal['confirmado'].to_list()\n suspeitos = evolucaoTotal['suspeitos'].to_list()\n obitos = evolucaoTotal['obitos'].to_list()\n evolucaoDataset = [datas,confirmados,suspeitos,obitos]\n qtde_cidades_confirmadas = cidades_confirmadas.shape[0]\n\n #RESUMO POR RESULTADO DE EXAME, SEXO E IDADE\n CASOS_DIR = '/dados/flask/cimai/covid/'\n casos_cariri = pd.read_csv(CASOS_DIR + 'covid.ceara.csv',delimiter=\",\",encoding='latin1',decimal='.')\n casos_cariri.fillna(0,inplace=True)\n #casos_cariri = casos_cariri[['codigoPaciente','bairroPaciente','municipioPaciente','sexoPaciente','idadePaciente','resultadoFinalExame','dataObito','obitoConfirmado']]\n casos_cariri = casos_cariri[['codigoPaciente','bairroPaciente','municipioPaciente','sexoPaciente','idadePaciente','resultadoFinalExame','dataObito','obitoConfirmado']]\n cariri = ['ABAIARA', 'ALTANEIRA', 'ANTONINA DO NORTE', 'ARARIPE', 'ASSARE','AURORA','BARBALHA','BARRO', 'BREJO SANTO', 'CAMPOS SALES', 'CARIRIACU', 'CRATO', 'FARIAS BRITO', 'GRANJEIRO', 'JARDIM', 'JATI', 'JUAZEIRO DO NORTE', 'LAVRAS DA MANGABEIRA', 'MAURITI', 'MILAGRES', 'MISSAO VELHA', 'NOVA OLINDA', 'PENAFORTE', 'PORTEIRAS', 'POTENGI', 'SALITRE', 'SANTANA DO CARIRI', 'TARRAFAS', 'VARZEA ALEGRE']\n casos_cariri = casos_cariri[casos_cariri['municipioPaciente'].isin(cariri)]\n casos_cariri['resultadoFinalExame'].replace([0],['Em Análise'],inplace=True)\n casos_cariri['sexoPaciente'].replace(['Feminino'],['FEMININO'],inplace=True)\n casos_cariri['sexoPaciente'].replace(['Masculino'],['MASCULINO'],inplace=True)\n casos_cariri['sexoPaciente'].replace(['0'],['FEMININO'],inplace=True)\n casos_cariri['bairroPaciente'].replace([0],['NAO INFORMADO'],inplace=True)\n casos_cariri['bairroPaciente'].replace(['VILA FATIMA'],['FATIMA'],inplace=True)\n casos_cariri.drop_duplicates(subset='codigoPaciente',inplace=True,keep='last')\n #POR SEXO E RESULTADO POSITIVO\n porSexo = casos_cariri[casos_cariri['resultadoFinalExame']=='Positivo'].groupby(['municipioPaciente','sexoPaciente'])\n tabelaPositivoPorSexo = porSexo['codigoPaciente'].count().to_frame()\n tabelaPositivoPorSexo.columns = ['Quantidade']\n tabelaPositivoPorSexo.index.names = ['Cidade','Sexo']\n #POR RESULTADO POSITIVO E BAIRRO\n porBairro = casos_cariri[casos_cariri['resultadoFinalExame']=='Positivo'].groupby(['municipioPaciente','bairroPaciente'])\n tabelaPositivoPorBairro = porBairro['codigoPaciente'].count().to_frame()\n tabelaPositivoPorBairro.columns = ['Quantidade']\n tabelaPositivoPorBairro.index.names = ['Cidade','Bairro']\n\n bairros = []\n for i in range(0,len(tabelaPositivoPorBairro.index),1):\n linha = list(tabelaPositivoPorBairro.index[i])\n confirmados_bairro = 1\n try:\n confirmados_bairro = tabelaPositivoPorBairro.loc[linha[0],linha[1]].tolist()[0]\n except KeyError:\n confirmados_bairro = 1\n\n if linha[1]=='NAO INFORMADO' or linha[1]=='ZONA RURAL':\n linha[1] = 'CENTRO'\n\n estado = 'CEARA'\n #senha = getSenha(WORKING_DIR + 'passwd.nominatim').rstrip()\n if linha[0]=='ARARIPE':\n consulta = linha[0] + ' ' + estado\n else:\n consulta = linha[0] + ' ' + estado + ' ' + linha[1]\n #requisicao = json.loads(requests.get(\"https://apps.yoko.pet/osm/search?q='\" + consulta + \"'&format=json\", auth=('nominatim', senha)).text)\n requisicao = json.loads(requests.get(\"https://apps.yoko.pet/osm/search?q='\" + consulta + \"'&format=json\").text)\n try:\n latitude = requisicao[0]['lat']\n longitude = requisicao[0]['lon']\n gps = str(latitude) + ',' + str(longitude)\n except IndexError:\n requisicao = json.loads(requests.get(\"https://apps.yoko.pet/osm/search?q='\" + linha[0] + ' ' + estado + \"'&format=json\", auth=('nominatim', 'autoridade')).text)\n latitude = requisicao[0]['lat']\n longitude = requisicao[0]['lon']\n gps = str(latitude) + ',' + str(longitude)\n linha.append(gps)\n linha.append(latitude)\n linha.append(longitude)\n linha.append(confirmados_bairro)\n bairros.append(linha)\n\n #POR SEXO E RESULTADO NEGATIVO\n porSexo = casos_cariri[casos_cariri['resultadoFinalExame']=='Negativo'].groupby(['municipioPaciente','sexoPaciente'])\n tabelaNegativoPorSexo = porSexo['codigoPaciente'].count().to_frame()\n tabelaNegativoPorSexo.columns = ['Quantidade']\n tabelaNegativoPorSexo.index.names = ['Cidade','Bairro']\n #POR SEXO E RESULTADO EM ANÁLISE\n porSexo = casos_cariri[casos_cariri['resultadoFinalExame']=='Em Análise'].groupby(['municipioPaciente','sexoPaciente'])\n tabelaAnalisePorSexo = porSexo['codigoPaciente'].count().to_frame()\n tabelaAnalisePorSexo.columns = ['Quantidade']\n tabelaAnalisePorSexo.index.names = ['Cidade','Bairro']\n #TOTAL DE CONFIRMADOS POR SEXO\n #casos_cariri.drop_duplicates(subset='codigoPaciente',inplace=True,keep='last')\n porSexo = casos_cariri[casos_cariri['resultadoFinalExame']=='Positivo'].groupby(['sexoPaciente'])\n listaSexos = porSexo['codigoPaciente'].count().tolist()\n listaSexosTotais = porSexo['codigoPaciente'].count().index.tolist()\n\n porSexoObitos = casos_cariri[casos_cariri['obitoConfirmado']==1.0].groupby(['sexoPaciente'])\n listaSexosTotaisObitos = porSexoObitos['codigoPaciente'].count().tolist()\n \n #Total de exames realizados\n tipoResultado = ['Negativo','Positivo','Em Análise']\n totalExames = casos_cariri[casos_cariri['resultadoFinalExame'].isin(tipoResultado)].shape[0]\n totalNegativos = casos_cariri[casos_cariri['resultadoFinalExame']=='Negativo'].shape[0]\n\n #Por Idade\n #idades = [0,2,5,10,16,20,40,60,80,100]\n idades = [0,5,20,40,60,120]\n casos_positivos = casos_cariri[casos_cariri['resultadoFinalExame']=='Positivo']\n gruposPositivosIdades = casos_positivos.groupby((pd.cut(casos_positivos['idadePaciente'],idades,right=False)))\n porIdadePositivo = gruposPositivosIdades['codigoPaciente'].count().to_frame()\n porIdadePositivo.index.name = 'Faixa Etária'\n porIdadePositivo.columns = ['Quantidade']\n\n obitos_confirmados = casos_cariri[casos_cariri['obitoConfirmado']==1.0]\n gruposObitosIdades = obitos_confirmados.groupby((pd.cut(obitos_confirmados['idadePaciente'],idades,right=False)))\n porIdadeObitos = gruposObitosIdades['codigoPaciente'].count().to_frame()\n porIdadeObitos.index.name = 'Faixa Etária'\n porIdadeObitos.columns = ['Quantidade']\n\n casos_analise = casos_cariri[casos_cariri['resultadoFinalExame']=='Em Análise']\n gruposAnaliseIdades = casos_analise.groupby((pd.cut(casos_analise['idadePaciente'],idades)))\n porIdadeAnalise = gruposAnaliseIdades['codigoPaciente'].count().to_frame()\n porIdadeAnalise.index.name = 'Faixa Etária'\n porIdadeAnalise.columns = ['Quantidade']\n\n faixas = porIdadePositivo.index.tolist()\n for i in range(0,len(faixas),1):\n faixas[i] = str(faixas[i]).replace('(','[')\n intervaloIdades = faixas\n dadosPositivoIdade = porIdadePositivo['Quantidade'].tolist()\n dadosAnaliseIdade = porIdadeAnalise['Quantidade'].tolist()\n\n agrupamentos =[tabelaPositivoPorSexo.to_html(),tabelaPositivoPorBairro.to_html(),listaSexos,listaSexosTotais,totalExames,totalNegativos,intervaloIdades,dadosPositivoIdade,dadosAnaliseIdade,porIdadeObitos,listaSexosTotaisObitos]\n\n return(dia,evolucao,porCidade,evolucaoTotal,evolucaoDataset,cidades_confirmadas,agrupamentos,bairros)\n\n@app.route(\"/\", methods=['GET', 'POST'])\ndef covid():\n return(render_template('index.html'))\n dados,evolucao,porCidade,evolucaoTotal,evolucaoDataSet,cidades_confirmadas,agrupamentos,bairros = dadosCovid()\n total_populacao = porCidade['populacao'].astype(int).sum()\n col_populacao = porCidade['populacao'].astype(int)\n col_confirmados = porCidade['confirmado'].astype(int)\n porCidade = porCidade[['cidade','confirmado','suspeitos','obitos']]\n porCidade['incidencia'] = ((col_confirmados/col_populacao)*100000).round(2)\n cidades_confirmadas['incidencia'] = ((cidades_confirmadas['confirmado'].astype(int)/cidades_confirmadas['populacao'].astype(int))*100000).round(2)\n mapa_cidade = cidades_confirmadas['cidade'].tolist()\n mapa_confirmados = cidades_confirmadas['confirmado'].tolist()\n mapa_gps = cidades_confirmadas['gps'].tolist()\n mapa_incidencia = (cidades_confirmadas['incidencia'].astype(float)*50).tolist()\n arquivo = open(COVID_DIR + 'time.txt','r')\n conteudo = str(arquivo.read())\n arquivo.close()\n total_confirmados = porCidade['confirmado'].astype(int).sum()\n porCemMil = (total_confirmados/total_populacao)*100000\n porCemMil = '{:.2f}'.format(porCemMil)\n cores = getCores(len(agrupamentos[6]))\n # *******\n if request.method == \"GET\":\n if 'q' in request.args:\n q = int(request.args.get('q'))\n if (q==1):\n return(render_template('mapa.cidades.html',mapa_cidade=mapa_cidade,mapa_confirmados=mapa_confirmados,mapa_gps=mapa_gps,mapa_incidencia=mapa_incidencia)) \n elif (q==2):\n return(render_template('mapa.bairros.html',bairros=bairros)) \n elif (q==3):\n return(render_template('por.sexo.html',agrupamentos=agrupamentos))\n elif (q==4):\n return(render_template('por.idade.html',agrupamentos=agrupamentos,cores=cores))\n elif (q==5):\n return(render_template('por.evolucao.html',acumulados=evolucaoDataSet))\n else:\n return(\"Nao implementado...\") \n #*****\n return(render_template('covid.html',bairros=bairros,porCemMil=porCemMil,cores=cores,dados=dados,evolucao=evolucao.to_html(),porCidade=porCidade.to_html(index=False,index_names=False),atualizacao=conteudo,acumulados=evolucaoDataSet,cidades_confirmadas=cidades_confirmadas[['cidade','confirmado','suspeitos','obitos','incidencia']].to_html(index=False),total_confirmadas=cidades_confirmadas.shape[0],mapa_cidade=mapa_cidade,mapa_confirmados=mapa_confirmados,mapa_gps=mapa_gps,mapa_incidencia=mapa_incidencia,agrupamentos=agrupamentos))\n\n@app.route(\"/atualizaDatasets\")\ndef atualizaDatasets():\n CSV_DIR = '/dados/flask/cimai/covid/'\n cariri = ['ABAIARA', 'ALTANEIRA', 'ANTONINA DO NORTE', 'ARARIPE', 'ASSARE', 'AURORA', 'BARBALHA', 'BARRO', 'BREJO SANTO', 'CAMPOS SALES', 'CARIRIACU', 'CRATO', 'FARIAS BRITO', 'GRANJEIRO', 'JARDIM', 'JATI', 'JUAZEIRO DO NORTE', 'LAVRAS DA MANGABEIRA', 'MAURITI', 'MILAGRES', 'MISSAO VELHA', 'NOVA OLINDA', 'PENAFORTE', 'PORTEIRAS', 'POTENGI', 'SALITRE', 'SANTANA DO CARIRI', 'TARRAFAS', 'VARZEA ALEGRE']\n df_ceara = pd.read_csv(CSV_DIR + 'TODOS.CEARA.HOJE.CSV',delimiter=\",\",encoding='utf8',decimal='.')\n df_cariri = df_ceara[df_ceara['cidade'].isin(cariri)].sort_values(by=['data','cidade'])\n df_ceara.to_csv('/dados/www/html/covid_csv/todos.ceara.hoje.csv',index=False)\n df_cariri.to_csv('/dados/www/html/covid_csv/todos.cariri.hoje.csv',index=False)\n df_ceara.to_csv('/dados/flask/cimai/covid/todos.ceara.hoje.csv',index=False)\n df_cariri.to_csv('/dados/flask/cimai/covid/todos.cariri.hoje.csv',index=False)\n return(\"SUCESSO\")\n\n\ndef salvarDadosGrafico(arquivo,tabela,labels,dados,dados2=[]):\n conn = sqlite3.connect(arquivo)\n c = conn.cursor()\n if (len(dados2)==0):\n df = pd.DataFrame({\"label\": labels, \"quantidade\":dados})\n df.to_sql(tabela,conn,if_exists='replace',index=False)\n else:\n df = pd.DataFrame({\"label\": labels, \"quantidade\":dados,\"quantidade2\": dados2})\n df.to_sql(tabela,conn,if_exists='replace',index=False)\n conn.close()\n\ndef salvarDadosMapa(arquivo,tabela,cidade,confirmados,latitude,longitude,porCemMil,recuperados,emRecuperacao,obitos):\n #TODO: Adaptar para cidades e bairros\n conn = sqlite3.connect(arquivo)\n c = conn.cursor()\n df = pd.DataFrame({\"cidade\": cidade, \"confirmados\":confirmados,\"latitude\": latitude,\"longitude\":longitude,\"incidencia\": porCemMil,\"recuperados\": recuperados,\"emRecuperacao\": emRecuperacao,\"obitos\": obitos})\n df.to_sql(tabela,conn,if_exists='replace',index=False)\n conn.close()\n\ndef salvarDadosMapaBairros(arquivo,tabela,cidade,bairros,latitude,longitude,confirmados):\n #TODO: Adaptar para cidades e bairros\n conn = sqlite3.connect(arquivo)\n c = conn.cursor()\n df = pd.DataFrame({\"cidade\": cidade, \"bairro\":bairros,\"latitude\": latitude,\"longitude\":longitude,\"confirmados\": confirmados})\n df.to_sql(tabela,conn,if_exists='replace',index=False)\n conn.close()\n\ndef salvarDadosInternacoes(arquivo,tabela):\n conn = sqlite3.connect(arquivo)\n c = conn.cursor()\n df_internacoes = pd.read_csv(COVID_DIR + 'TODOS.CEARA.HOJE.LEITOS.CSV',delimiter=\",\",encoding='latin1',decimal='.')\n dados_internacoes = [df_internacoes['uti_ativos'].sum(),df_internacoes['uti_ocupacao'].sum(),df_internacoes['enfermaria_ativos'].sum(),df_internacoes['enfermaria_ocupacao'].sum()]\n dados_percentuais = [df_internacoes['uti_ocupacao'].sum()/df_internacoes['uti_ativos'].sum(),df_internacoes['enfermaria_ocupacao'].sum()/df_internacoes['enfermaria_ativos'].sum()]\n dados_percentuais = [round(num, 2) for num in dados_percentuais]\n dados_percentuais = [int(num*100) for num in dados_percentuais]\n df_ocupacao = pd.DataFrame([dados_percentuais],columns=['uti','enfermaria'],index=['percentuais'])\n df_ocupacao.to_sql(\"dadosInternacoes\",conn,if_exists='replace',index=False)\n df_internacoes.to_sql(\"internacoes\",conn,if_exists='replace',index=False)\n conn.close()\n\ndef salvarDadosObitos(arquivo,tabela):\n conn = sqlite3.connect(arquivo)\n c = conn.cursor()\n\n HTML_DIR = \"/dados/www/html/covid_csv/spyder/\"\n soup = BeautifulSoup(open(HTML_DIR + \"sec-ce-comorbidades-hoje.html\",\"rb\"),'lxml')\n\n obitos_comorbidade = soup.find_all('text',attrs={'class':'value-text'})[5].get_text()\n obitos_comorbidade = obitos_comorbidade.lstrip()\n obitos_comorbidade = obitos_comorbidade.rstrip()\n\n obitos_por_dia = soup.find_all('text',attrs={'class':'value-text'})[3].get_text()\n obitos_por_dia = obitos_por_dia.lstrip()\n obitos_por_dia = obitos_por_dia.rstrip()\n\n mediana_idade = soup.find_all('text',attrs={'class':'value-text'})[7].get_text()\n mediana_idade = mediana_idade.lstrip()\n mediana_idade = mediana_idade.rstrip()\n\n dados = [obitos_comorbidade,obitos_por_dia,mediana_idade]\n df = pd.DataFrame([dados],columns=['comorbidades','porDia','mediana_idade'])\n df.to_sql(tabela,conn,if_exists='replace',index=False)\n\n@app.route(\"/atualizarDados\")\ndef atualizarDados():\n dados,evolucao,porCidade,evolucaoTotal,evolucaoDataSet,cidades_confirmadas,agrupamentos,bairros = dadosCovid()\n ARQUIVO = COVID_DIR + 'dados.cariri.hoje.sqlite3'\n salvarDadosGrafico(ARQUIVO,\"confirmadosPorIdade\",agrupamentos[6],agrupamentos[7])\n salvarDadosGrafico(ARQUIVO,\"confirmadosPorSexo\",agrupamentos[3],agrupamentos[2]) \n salvarDadosGrafico(ARQUIVO,\"obitosPorIdade\",agrupamentos[6],agrupamentos[9]['Quantidade'].tolist()) \n salvarDadosGrafico(ARQUIVO,\"obitosPorSexo\",agrupamentos[3],agrupamentos[10])\n salvarDadosGrafico(ARQUIVO,\"evolucao\",evolucaoDataSet[0],evolucaoDataSet[1],evolucaoDataSet[3])\n porCemMil = ((cidades_confirmadas['confirmado']/cidades_confirmadas['populacao'])*100000).round(2)\n conf = np.array(cidades_confirmadas['confirmado'].tolist())\n ob = np.array(cidades_confirmadas['obitos'].tolist())\n rec = np.array(cidades_confirmadas['recuperados'].tolist())\n emRecuperacao = (conf-ob-rec).tolist()\n salvarDadosMapa(ARQUIVO,\"cidadesConfirmadas\",cidades_confirmadas['cidade'].tolist(),cidades_confirmadas['confirmado'].tolist(),cidades_confirmadas['latitude'].tolist(),cidades_confirmadas['longitude'].tolist(),porCemMil.tolist(),rec.tolist(),emRecuperacao,ob.tolist())\n df_bairros = pd.DataFrame.from_records(bairros)\n df_bairros.columns = ['cidade','bairro','gps','latitude','longitude','confirmados']\n salvarDadosMapaBairros(ARQUIVO,\"bairros\",df_bairros['cidade'].tolist(),df_bairros['bairro'].tolist(),df_bairros['latitude'].tolist(),df_bairros['longitude'].tolist(),df_bairros['confirmados'].tolist())\n salvarDadosInternacoes(ARQUIVO,\"internacoes\")\n salvarDadosObitos(ARQUIVO,\"obitosResumo\")\n return(\"SUCESSO\\n\")\n\n@app.route(\"/teste\")\ndef teste():\n return(\"OK\")\n\nif __name__ == \"__main__\":\n app.run()\n","repo_name":"rafaelperazzo/covid19_cariri","sub_path":"covid.py","file_name":"covid.py","file_ext":"py","file_size_in_byte":20278,"program_lang":"python","lang":"pt","doc_type":"code","stars":1,"dataset":"github-code","pt":"81"} +{"seq_id":"18931713764","text":"import pandas as pd\nimport seaborn as sns\n\nimport matplotlib\nimport matplotlib.pyplot as plt\nfrom matplotlib.colors import LogNorm\nfrom matplotlib import ticker, patches\n\nfrom math import ceil\n\ndef setup_subplots(amount: int, ncols=2):\n # TODO: nrows and ncols arguments are overriden later on,\n # need to decide on what we want to have here.\n\n # TODO: amount, nrows, ncols must be int - need to assert\n amount = int(amount)\n ncols = int(ncols)\n\n subplots_shape = {4: (2,2)}\n shape = subplots_shape.pop(amount, None)\n if shape is None:\n nrows = ceil(amount/ncols)\n shape = (nrows, ncols)\n fig, axs = plt.subplots(nrows = shape[0], ncols=shape[1])\n axs = axs.flatten()\n\n # Delete redundant axes\n if (amount % ncols) > 0:\n to_delete_start = amount - ncols + (amount % ncols) + 1\n for i in range(to_delete_start, amount + 1):\n fig.delaxes(axs[i])\n axs = axs[:to_delete_start]\n \n fig.set_tight_layout(True)\n fig.set_size_inches(shape[1] * 5, shape[0] * 5)\n return fig, axs\n\ndef customize_ax(ax: matplotlib.axes.Axes,\n title=None,\n xlabel=None, ylabel=None,\n xlim=None, ylim=None, \n invert_yaxis=False,\n xticks_maj_freq=None, xticks_min_freq=None, yticks_maj_freq=None, yticks_min_freq=None, \n with_hline=False, hline_height=None, hline_color='r', hline_style='--'):\n \"\"\"\n : ax (matplotlib.axes.Axes): plot to customize.\n : Use to customize a plot with labels, ticks, etc.\n \"\"\"\n if xlabel is not None:\n ax.set_xlabel(xlabel)\n if ylabel is not None:\n ax.set_ylabel(ylabel)\n \n if xlim is not None:\n ax.set_xlim(xlim)\n if ylim is not None:\n ax.set_ylim(ylim)\n\n if invert_yaxis:\n ax.invert_yaxis()\n\n if title is not None:\n ax.set_title(title)\n\n if xticks_maj_freq is not None:\n ax.xaxis.set_major_locator(ticker.MultipleLocator(xticks_maj_freq))\n \n if xticks_min_freq is not None:\n ax.xaxis.set_minor_locator(ticker.MultipleLocator(xticks_min_freq))\n \n if yticks_maj_freq is not None:\n ax.yaxis.set_major_locator(ticker.MultipleLocator(yticks_maj_freq))\n \n if yticks_min_freq is not None:\n ax.yaxis.set_minor_locator(ticker.MultipleLocator(yticks_min_freq))\n\n if with_hline:\n if hline_height is None:\n ylim = plt.ylim()\n hline_height = max(ylim) / 2\n ax.axhline(y=hline_height, color=hline_color, linestyle=hline_style)\n\n \ndef plot_stem(series: pd.Series, ax=None, show=False,\n title=None, xlabel=None, ylabel=None,\n xlim=None, ylim=None, \n xticks_maj_freq=None, xticks_min_freq=None, yticks_maj_freq=None, yticks_min_freq=None, \n with_hline=False, hline_height=None, hline_color='r', hline_style='--'):\n \"\"\"\n : series (pd.Series): series.index specifies x values \n : series.values specifies y values\n : stem plot with optional horizontal line\n \"\"\"\n if ax is None:\n fig, ax = plt.subplots()\n ax.stem(series.index, series.values)\n \n if xlabel is None:\n if (series.index.name is not None):\n xlabel = series.index.name\n\n if ylabel is None:\n if (series.name is not None):\n ylabel = series.name\n\n if title is None:\n title = '{y} by {x}'.format(y=ylabel, x=xlabel)\n\n customize_ax(ax=ax, title=title,\n xlabel=xlabel, ylabel=ylabel,\n xlim=xlim, ylim=ylim,\n xticks_maj_freq=xticks_maj_freq, xticks_min_freq=xticks_min_freq,\n yticks_maj_freq=yticks_maj_freq, yticks_min_freq=yticks_min_freq,\n with_hline=with_hline, hline_height=hline_height,\n hline_color=hline_color, hline_style=hline_style) \n if show:\n plt.show()\n return ax\n\ndef plot_bar(series: pd.Series, ax=None, show=False,\n title=None, xlabel=None, ylabel=None,\n xlim=None, ylim=None, \n xticks_maj_freq=None, xticks_min_freq=None, yticks_maj_freq=None, yticks_min_freq=None, \n with_hline=False, hline_height=None, hline_color='r', hline_style='--'):\n \"\"\"\n : series (pd.Series): series.index specifies x values \n : series.values specifies y values\n : Bar plot with optional horizontal line\n \"\"\"\n plt.style.use('default')\n if ax is None:\n fig, ax = plt.subplots()\n barlist = ax.bar(series.index, series.values) # We return this for further customization \n \n customize_ax(ax=ax, title=title,\n xlabel=xlabel, ylabel=ylabel,\n xlim=xlim, ylim=ylim,\n xticks_maj_freq=xticks_maj_freq, xticks_min_freq=xticks_min_freq,\n yticks_maj_freq=yticks_maj_freq, yticks_min_freq=yticks_min_freq,\n with_hline=with_hline, hline_height=hline_height,\n hline_color=hline_color, hline_style=hline_style) \n \n if show:\n plt.show()\n return (ax, barlist)\n\ndef plot_bar_prob_by_bit_pos(series: pd.Series, r: int, ax=None, show=False,\n title=None, xlabel='bit', ylabel='P(flip)', xlim=None, ylim=(0,1),\n xticks_maj_freq=5, xticks_min_freq=1, yticks_maj_freq=0.2, yticks_min_freq=0.05, \n info_color='blue', rdnc_color='green',\n legend_loc='upper left', legend_info_label = 'Information bits', legend_rdnc_label = 'Redundancy bits', \n with_hline=False, hline_height=0.5, hline_color='r', hline_style='--'):\n \"\"\"\n : series (pd.Series): series.index specifies x values \n : series.values specifies y values\n : r (int): redundancy bit index\n : Bar plot a probability[not distribution] series where x-axis represents bits of a code word.\n : > different coloring of info bits and redundancy bits.\n : > Add horizontal line at 0.5\n \"\"\"\n if xlim is None:\n xlim = (0, len(series))\n\n ax, barlist = plot_bar(series, ax=ax, show=False,\n title=title, xlabel=xlabel, ylabel=ylabel,\n xlim=xlim, ylim=ylim,\n xticks_maj_freq=xticks_maj_freq, xticks_min_freq=xticks_min_freq,\n yticks_maj_freq=yticks_maj_freq, yticks_min_freq=yticks_min_freq,\n with_hline=with_hline, hline_height=hline_height,\n hline_color=hline_color, hline_style=hline_style)\n for bl in barlist[:-r]:\n bl.set_color(info_color)\n for bl in barlist[-r:]:\n bl.set_color(rdnc_color)\n \n info_patch = patches.Patch(color=info_color, label=legend_info_label)\n rdnc_patch = patches.Patch(color=rdnc_color, label=legend_rdnc_label)\n \n ax.legend(loc=legend_loc, handles=[info_patch, rdnc_patch])\n if show:\n plt.show()\n return ax\n\ndef plot_heatmap_prob(matrix, log_scale=False, ax=None, show=False, \n vmin=0, vmax=1, cmap=None,\n cbar_label = '',\n title=None,\n xlabel=None, ylabel=None,\n xlim=None, ylim=None, \n invert_yaxis=True,\n xticks_maj_freq=None, xticks_min_freq=None, yticks_maj_freq=None, yticks_min_freq=None):\n if ax is None:\n fig, ax = plt.subplots()\n if log_scale:\n sns.heatmap(matrix.apply(lambda x: x+1), norm=LogNorm(vmin=1, vmax=matrix.max().max()), ax=ax)\n else:\n sns.heatmap(matrix, ax=ax, vmin=vmin, vmax=vmax, cmap=cmap, mask = matrix.isna(), cbar_kws={'label': cbar_label}) # TODO: allow customization of vmin, vmax\n ax.set_facecolor(\"#8ff7e1\")\n\n # TODO: Support values in cell display option\n customize_ax(ax=ax, invert_yaxis=invert_yaxis,\n title=title,\n xlabel=xlabel, ylabel=ylabel,\n xlim=xlim, ylim=ylim, \n xticks_maj_freq=xticks_maj_freq, xticks_min_freq=xticks_min_freq,\n yticks_maj_freq=yticks_maj_freq, yticks_min_freq=yticks_min_freq) \n if show:\n plt.show()\n return ax\n\ndef co_occurence_heatmap(attacks, keys, show_numbers=False):\n if(len(keys) != 2):\n raise Exception('Only 2 keys are allowed for co_occurence_heatmap')\n co_occurence_matrix = pd.crosstab(attacks[keys[0]], attacks[keys[1]], dropna=False)\n if show_numbers:\n sns.heatmap(co_occurence_matrix, annot=True, fmt=\"d\", linewidths=.1)\n else:\n sns.heatmap(co_occurence_matrix)\n plt.gca().invert_yaxis() \n #plt.show()\n\ndef sort_multindex(df):\n sorted_indexes = df.index.to_frame().reset_index(drop=True).apply(pd.Series.nunique).sort_values().index.to_list()\n return df.reorder_levels(sorted_indexes)\n # TODO better place for it","repo_name":"Euphoriaa/pycpc","sub_path":"src/graph_util.py","file_name":"graph_util.py","file_ext":"py","file_size_in_byte":8937,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"40956659135","text":"from opcua import Server, ua\r\n\r\ntry:\r\n from IPython import embed\r\nexcept ImportError:\r\n import code\r\n\r\n def embed():\r\n myvars = globals()\r\n myvars.update(locals())\r\n shell = code.InteractiveConsole(myvars)\r\n shell.interact()\r\n\r\ndef findAvg(parent, sumVal, num):\r\n return sumVal/num\r\n\r\n\r\n\r\nif __name__ == \"__main__\":\r\n server = Server()\r\n # server.set_endpoint(\"opc.tcp://0.0.0.0:4840/elevator/pid/\")\r\n server.set_endpoint(\"opc.tcp://0.0.0.0:4840/elevator/pid/\")\r\n\r\n server.set_server_name(\"PID Controlled Elevator\")\r\n\r\n uri = \"http://thaintersect.com\"\r\n idx = server.register_namespace(uri) \r\n\r\n objects = server.get_objects_node()\r\n\r\n # Declare PLC object \r\n plc = objects.add_object(idx,\"PLC_S71200\")\r\n\r\n # Declare MCU object \r\n mcu = objects.add_object(idx,\"MCU\")\r\n\r\n '''\r\n Definition of OPC Server Variables\r\n '''\r\n disp = mcu.add_variable(idx, \"Displacement\",0.0 )\r\n disp.set_writable()\r\n avel = mcu.add_variable(idx, \"Angular_Velocity\", 0.0)\r\n avel.set_writable()\r\n lvel = mcu.add_variable(idx, \"Linear_Velocity\", 0.0)\r\n lvel.set_writable()\r\n \r\n up = plc.add_variable(idx, \"GoingUp\", True, ua.VariantType.Boolean)\r\n up.set_writable()\r\n\r\n dest = plc.add_variable(idx, \"Setpoint\", 0.0)\r\n dest.set_writable()\r\n\r\n motion = plc.add_variable(idx, \"InMotion\", False, ua.VariantType.Boolean)\r\n motion.set_writable()\r\n\r\n curFloor = plc.add_variable(idx, \"Current_Floor\",1 , ua.VariantType.Int16)\r\n curFloor.set_writable()\r\n\r\n mcall1 = plc.add_variable(idx, \"Call_First_Floor\", False, ua.VariantType.Boolean)\r\n mcall1.set_writable()\r\n mcall2 = plc.add_variable(idx, \"Call_Second_Floor\", False, ua.VariantType.Boolean)\r\n mcall2.set_writable()\r\n mcall0 = plc.add_variable(idx, \"Call_Third_Floor\", False , ua.VariantType.Boolean)\r\n mcall0.set_writable()\r\n\r\n LS1 = plc.add_variable(idx, \"First_Floor\", False, ua.VariantType.Boolean)\r\n LS1.set_writable()\r\n LS2 = plc.add_variable(idx, \"Second_Floor\", False, ua.VariantType.Boolean)\r\n LS2.set_writable()\r\n LS3 = plc.add_variable(idx, \"Third_Floor\", False , ua.VariantType.Boolean)\r\n LS3.set_writable()\r\n\r\n # myobj = objects.add_object(idx, \"MyObject\")\r\n avg_func = mcu.add_method(idx, \"Find Average\", findAvg, [ua.VariantType.Int64], [ua.VariantType.Boolean])\r\n\r\n\r\n print(\"Address at: opc.tcp://localhost:4840/elevator/pid/\")\r\n server.start()\r\n # embed()\r\n\r\n\r\n","repo_name":"Andykibz/lift_opc_server","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":2484,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"2453322448","text":"\"\"\"Classes and methods for the NETGEN network generation algorithm.\"\"\"\n\nfrom pynetgen.util.ilist import IndexList\nfrom pynetgen.util.randit import NetgenRandom\nfrom pynetgen.util.randit import StandardRandom\nfrom pynetgen._version import __version__\n\n#=============================================================================\n\nclass NetgenNetworkGenerator:\n \"\"\"A class for implementing the NETGEN random network generator.\n \n This class is meant to act as a container for carrying out the NETGEN\n random network generation algorithm, with attributes for temporarily\n storing network parameters and methods for generating and exporting the\n resulting graph.\n \"\"\"\n \n #-------------------------------------------------------------------------\n \n def __init__(self, seed=1, nodes=10, sources=3, sinks=3, density=30,\n mincost=10, maxcost=99, supply=1000, tsources=0, tsinks=0,\n hicost=0, capacitated=100, mincap=100, maxcap=1000,\n rng=0, type=None):\n \"\"\"NETGEN network object constructor.\n \n Keyword arguments:\n seed -- random number generator seed (default 1; -1 for random)\n nodes -- number of nodes (default 10)\n sources -- number of source nodes (default 3)\n sinks -- number of sink nodes (default 3)\n density -- number of arcs (default 30)\n mincost -- minimum arc cost (default 10)\n maxcost -- maximum arc cost (default 99)\n supply -- total supply (default 1000)\n tsources -- number of transshipment sources (default 0)\n tsinks -- number of transshipment sinks (default 0)\n hicost -- percent of skeleton arcs (0-100) given maximum cost\n (default 0)\n capacitated -- percent of skeleton arcs (0-100) that are capacitated\n (default 100)\n mincap -- minimum arc capacity (default 100)\n maxcap -- maximum arc capacity (default 1000)\n rng -- index of random network generator to use (default 0),\n including:\n 0: the original NETGEN pseudorandom number generator\n 1: the Python standard library random number generator\n type -- problem type override (default None); setting to an integer\n attempts to generate the specified type of problem and ignores the\n default behavior explained below:\n 0: minimum-cost flow\n 1: maximum flow\n 2: transportation\n \n All keyword arguments besides the RNG selection and the file name are\n identical to those of the original C implementation of NETGEN. All\n network parameters are integer.\n \n The problem type is implicitly chosen based on the network attributes\n (unless the \"type\" attribute is set). By default the problem is\n minimum-cost flow. It is a transportation problem instead if the total\n number of sources and sinks equals the total number of nodes, and if\n no transshipment sources or sinks are specified. It is a maximum flow\n problem if it is not a transportation problem, and if the minimum and\n maximum arc costs are both exactly 1.\n \"\"\"\n \n # Validate inputs and convert to correct data types\n self.seed = int(seed)\n self.nodes = int(nodes)\n if self.nodes < 0:\n raise ValueError(\"node count must be nonnegative\")\n self.sources = int(sources)\n if self.sources < 0:\n raise ValueError(\"source count must be nonnegative\")\n self.sinks = int(sinks)\n if self.sinks < 0:\n raise ValueError(\"sink count must be nonnegative\")\n if self.sources + self.sinks > self.nodes:\n raise ValueError(\"source/sink count cannot exceed node count\")\n self.density = int(density)\n if self.density < 1:\n raise ValueError(\"arc count must be nonnegative\")\n if self.nodes > self.density:\n raise ValueError(\"node count must exceed arc count\")\n self.mincost = int(mincost)\n self.maxcost = int(maxcost)\n if self.mincost > self.maxcost:\n raise ValueError(\"min cost cannot exceed max cost\")\n self.supply = max(int(supply), 0)\n self.tsources = int(tsources)\n if self.tsources < 0:\n raise ValueError(\"transshipment source count must be nonnegative\")\n if self.tsources > self.sources:\n raise ValueError(\"transshipment sources cannot exceed sources\")\n self.tsinks = int(tsinks)\n if self.tsinks < 0:\n raise ValueError(\"transshipment sink count must be nonnegative\")\n if self.tsinks > self.sinks:\n raise ValueError(\"transshipment sinks cannot exceed sinks\")\n self.hicost = int(hicost)\n if self.hicost < 0 or self.hicost > 100:\n raise ValueError(\"high cost percentage must be in [0,100]\")\n self.capacitated = int(capacitated)\n if self.capacitated < 0 or self.capacitated > 100:\n raise ValueError(\"capacitated percentage must be in [0,100]\")\n self.mincap = int(mincap)\n self.maxcap = int(maxcap)\n if self.mincap > self.maxcap:\n raise ValueError(\"min capacity cannot exceed max capacity\")\n rng = int(rng)\n if type is not None:\n type = int(type)\n if type < 0 or type > 2:\n raise ValueError(\"problem type index must be 0-2 or None\")\n \n # Initialize random number generation object\n if rng == 0:\n self.Rng = NetgenRandom(seed)\n elif rng == 1:\n self.Rng = StandardRandom(seed)\n else:\n raise ValueError(\"RNG index must be 0 or 1\")\n self.seed = self.Rng.seed # copy RNG's seed in case of -1\n \n # Initialize attributes for temporary storage\n self._arc_count = 0 # number of arcs generated so far\n self._nodes_left = self.nodes - self.sinks + self.tsinks # nodes to gen\n self._b = [0 for i in range(self.nodes)] # node supply values\n self._type = 0 # problem type (0: mincost, 1: maxflow, 2:assignment)\n self._from = [None for i in range(self.density)] # final arc tails\n self._to = self._from[:] # final arc heads\n self._c = self._from[:] # final arc costs\n self._u = self._from[:] # final arc capacities\n \n # Determine which type of problem to generate\n if type is None:\n if ((self.sources - self.tsources + self.sinks - self.tsinks ==\n self.nodes) and self.sources - self.tsources ==\n self.sinks - self.tsinks and self.sources == self.supply):\n self._type = 2\n elif self.mincost == 1 and self.maxcost == 1:\n self._type = 1\n else:\n self._type = 0\n \n # Choose the correct problem generation method\n if type == 2:\n self._create_assignment()\n self._create_problem()\n \n #-------------------------------------------------------------------------\n \n def _create_problem(self):\n \"\"\"Generates a min-cost flow or max-flow problem.\"\"\"\n \n # Initialize variables\n pred = [None for i in range(self.nodes)] # temporary node predecessors\n head = self._from[:] # temporary arc heads\n tail = self._from[:] # temporary arc tails\n \n # Set supply values\n self._create_supply()\n \n # Form most of the network skeleton by forming chains of transshipment\n # nodes from the sources (stored via predecessor lists)\n \n # Point sources at selves\n for i in range(1, self.sources+1):\n pred[i] = i\n \n # Make an index list for the nodes\n IndList = IndexList(self.sources + 1, self.nodes - self.sinks)\n source = 1\n \n # Distribute the first 60% of transshipment nodes evenly among sources\n for i in range(self.nodes - self.sources - self.sinks,\n int((4*(self.nodes-self.sources-self.sinks)+9)/10), -1):\n node = IndList.pop(self.Rng.generate(1, len(IndList)))\n pred[node] = pred[source]\n pred[source] = node\n source += 1\n if source > self.sources:\n source = 1\n \n # Distribute the remaining transshipment nodes randomly\n while i > 1:\n i -= 1\n node = IndList.pop(self.Rng.generate(1, len(IndList)))\n source = self.Rng.generate(1, self.sources)\n pred[node] = pred[source]\n pred[source] = node\n \n del IndList\n \n # Link each source chain to sinks, assign skeletal arc capacities\n # and costs, then complete the network with random arcs\n \n # Process each source chain\n for source in range(1, self.sources+1):\n \n sort_count = 0 # number of nodes visited in current chain\n node = pred[source] # transshipment node at end of current chain\n \n # Record heads/tails by traversing the chain backwards\n while node != source:\n sort_count += 1\n head[sort_count] = node\n tail[sort_count] = pred[node]\n node = pred[node]\n \n # Choose number of sinks to link to this chain\n if self.nodes == self.sources + self.sinks:\n sinks_per_source = int(self.sinks/self.sources) + 1\n else:\n sinks_per_source = 2*int((sort_count*self.sinks)/\n (self.nodes - self.sources - self.sinks))\n sinks_per_source = max(2, min(sinks_per_source, self.sinks))\n \n # Choose the sinks to link to this chain\n sinks = [None for i in range(self.nodes)]\n IndList = IndexList(self.nodes - self.sinks, self.nodes - 1)\n for i in range(sinks_per_source):\n sinks[i] = IndList.pop(self.Rng.generate(1, len(IndList)))\n \n # Ensure that any unselected sinks are chosen for the last source\n if source == self.sources and len(IndList) > 0:\n while len(IndList) > 0:\n j = IndList.pop(1)\n if self._b[j] == 0:\n sinks[sinks_per_source] = j\n sinks_per_source += 1\n \n del IndList\n \n # Distribute supply among the selected sinks\n chain_length = sort_count\n supply_per_sink = self._b[source-1]//sinks_per_source\n k = pred[source]\n for i in range(sinks_per_source):\n sort_count += 1\n partial_supply = self.Rng.generate(1, supply_per_sink)\n j = self.Rng.generate(0, sinks_per_source - 1)\n tail[sort_count] = k\n head[sort_count] = sinks[i] + 1\n self._b[sinks[i]] -= partial_supply\n self._b[sinks[j]] -= supply_per_sink - partial_supply\n k = source\n for j in range(self.Rng.generate(1, chain_length), 0, -1):\n k = pred[k]\n self._b[sinks[0]] -= self._b[source-1] % sinks_per_source\n \n # Sort skeleton arcs into a canonical order\n self._sort_skeleton(sort_count, tail, head)\n tail[sort_count+1] = 0\n \n # Assign attributes to skeleton arcs\n i = 1\n while i <= sort_count:\n\n IndList = IndexList(self.sources-self.tsources+1, self.nodes)\n IndList.remove(tail[i])\n it = tail[i]\n \n while it == tail[i]:\n \n IndList.remove(head[i])\n \n # Determine capacity\n cap = self.supply\n if self.Rng.generate(1, 100) <= self.capacitated:\n cap = max(self._b[source-1], self.mincap)\n \n # Determine cost\n cost = self.maxcost\n if self.Rng.generate(1, 100) > self.hicost:\n cost = self.Rng.generate(self.mincost, self.maxcost)\n \n # Record attributes\n self._from[self._arc_count] = it\n self._to[self._arc_count] = head[i]\n self._c[self._arc_count] = cost\n self._u[self._arc_count] = cap\n \n self._arc_count += 1\n i += 1\n \n self._pick_head(IndList, it)\n del IndList\n \n # Complete network with random arcs\n for i in range(self.nodes - self.sinks + 1,\n self.nodes - self.sinks + self.tsinks):\n IndList = IndexList(self.sources-self.tsources+1, self.nodes)\n IndList.remove(i)\n self._pick_head(IndList, i)\n del IndList\n \n return self._arc_count\n \n #-------------------------------------------------------------------------\n \n def _create_assignment(self):\n \"\"\"Generates an assignment problem.\"\"\"\n \n for source in range(self.nodes/2):\n self._b[source] = 1\n while source < self.nodes:\n self._b[source] = -1\n source += 1\n \n Skeleton = IndexList(self.sources+1, self.nodes)\n for source in range(1, self.nodes/2 + 1):\n index = Skeleton.pop(self.Rng.generate(1, len(Skeleton)))\n \n self._from[self._arc_count] = source\n self._to[self._arc_count] = index\n self._c[self._arc_count] = self.Rng.generate(self.mincost,\n self.maxcost)\n self._u[self._arc_count] = 1\n self._arc_count += 1\n \n IndList = IndexList(self.sources+1, self.nodes)\n IndList.remove(index)\n self._pick_head(IndList, source)\n \n del IndList\n \n del Skeleton\n \n #-------------------------------------------------------------------------\n \n def _create_supply(self):\n \"\"\"Sets supply values of all nodes.\"\"\"\n \n supply_per_source = int(self.supply/self.sources)\n for i in range(self.sources):\n partial_supply = self.Rng.generate(1, supply_per_source)\n self._b[i] += partial_supply\n self._b[self.Rng.generate(0, self.sources-1)] += (supply_per_source\n - partial_supply)\n self._b[self.Rng.generate(0, self.sources-1)] += (self.supply %\n self.sources)\n \n #-------------------------------------------------------------------------\n \n def _sort_skeleton(self, sort_count, tail, head):\n \"\"\"Conduct a shell sort of a portion of the skeleton arcs by tail.\"\"\"\n \n m = sort_count\n m //= 2\n while m != 0:\n k = sort_count - m\n for j in range(1, k+1):\n i = j\n while i >= 1 and tail[i] > tail[i+m]:\n tail[i], tail[i+m] = tail[i+m], tail[i]\n head[i], head[i+m] = head[i+m], head[i]\n i -= m\n m //= 2\n \n #-------------------------------------------------------------------------\n \n def _pick_head(self, IList, desired_tail):\n \"\"\"Pick the next skeleton head during skeleton arc generation.\"\"\"\n \n non_sources = self.nodes - self.sources + self.tsources\n remaining_arcs = self.density - self._arc_count\n \n self._nodes_left -= 1\n if 2*self._nodes_left >= remaining_arcs:\n return None\n \n if ((remaining_arcs+non_sources-IList.pseudo_size-1)/\n (self._nodes_left+1) >= non_sources - 1):\n limit = non_sources\n else:\n upper_bound = 2*(remaining_arcs/(self._nodes_left + 1) - 1)\n while True:\n limit = self.Rng.generate(1, upper_bound)\n if self._nodes_left == 0:\n limit = remaining_arcs\n if self._nodes_left*(non_sources-1) >= remaining_arcs - limit:\n break\n \n while limit > 0:\n limit -= 1\n index = IList.pop(self.Rng.generate(1, IList.pseudo_size))\n cap = self.supply\n if self.Rng.generate(1, 100) <= self.capacitated:\n cap = self.Rng.generate(self.mincap, self.maxcap)\n \n if 1 <= index and index <= self.nodes:\n self._from[self._arc_count] = desired_tail\n self._to[self._arc_count] = index\n self._c[self._arc_count] = self.Rng.generate(self.mincost,\n self.maxcost)\n self._u[self._arc_count] = cap\n self._arc_count += 1\n \n #-------------------------------------------------------------------------\n \n def write(self, fname=None):\n \"\"\"Writes the completed network to a file (or prints to screen).\n \n Keyword arguments:\n fname -- output file path (default None, which prints to screen)\n \"\"\"\n \n # Begin to write output string\n out = (f\"c PyNETGEN v{__version__}\\n\" +\n \"c $ pip install pynetgen\\nc\\n\" +\n \"c NETGEN flow network generation algorithm\\n\" +\n \"c Problem input parameters\\n\" +\n \"c \" + \"-\"*37 + \"\\n\" +\n f\"c Random seed: {self.seed}\\n\" +\n f\"c Number of nodes: {self.nodes}\\n\" +\n f\"c Source nodes: {self.sources}\\n\" +\n f\"c Sink nodes: {self.sinks}\\n\" +\n f\"c Number of arcs: {self.density}\\n\" +\n f\"c Minimum arc cost: {self.mincost}\\n\" +\n f\"c Maximum arc cost: {self.maxcost}\\n\" +\n f\"c Total supply: {self.supply}\\n\" +\n \"c Transshipment -\\n\" +\n f\"c Sources: {self.tsources}\\n\" +\n f\"c Sinks: {self.tsinks}\\n\" +\n \"c Skeleton arcs -\\n\" +\n f\"c With max cost: {self.hicost}\\n\" +\n f\"c Capacitated: {self.capacitated}\\n\" +\n f\"c Minimum arc capacity: {self.mincap}\\n\" +\n f\"c Maximum arc capacity: {self.maxcap}\\n\")\n \n # Handle assignment problem\n if self._type == 2:\n out += \"c\\nc *** Assignment ***\\nc\\n\"\n out += f\"p asn {self.nodes} {self._arc_count}\\n\"\n for i in range(self.nodes):\n if self._b[i] > 0:\n out += f\"n {i+1}\\n\"\n for i in range(self._arc_count):\n out += f\"a {self._from[i]} {self._to[i]} {self._c[i]}\\n\"\n \n # Handle max flow problem\n elif self._type == 1:\n out += \"c\\nc *** Maximum flow ***\\nc\\n\"\n out += f\"p max {self.nodes} {self._arc_count}\\n\"\n for i in range(self.nodes):\n if self._b[i] > 0:\n out += f\"n {i+1} s\\n\"\n elif self._b[i] < 0:\n out += f\"n {i+1} t\\n\"\n for i in range(self._arc_count):\n out += f\"a {self._from[i]} {self._to[i]} {self._u[i]}\\n\"\n \n # Handle min-cost flow problem\n else:\n out += \"c\\nc *** Minimum cost flow ***\\nc\\n\"\n out += f\"p min {self.nodes} {self._arc_count}\\n\"\n for i in range(self.nodes):\n if self._b[i] != 0:\n out += f\"n {i+1} {self._b[i]}\\n\"\n for i in range(self._arc_count):\n out += (f\"a {self._from[i]} {self._to[i]} 0 {self._u[i]}\" +\n f\" {self._c[i]}\\n\")\n \n # Write or print string\n if fname is None:\n print(out)\n else:\n with open(fname, 'w') as f:\n print(out[:-1], file=f)\n \n return 0\n","repo_name":"adam-rumpf/pynetgen","sub_path":"src/pynetgen/gen/netgen.py","file_name":"netgen.py","file_ext":"py","file_size_in_byte":20207,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"81"} +{"seq_id":"35861774923","text":"from uuid import UUID\n\nfrom django.contrib import messages\nfrom django.contrib.contenttypes.models import ContentType\nfrom django.http import HttpRequest, HttpResponseRedirect\nfrom django.shortcuts import get_object_or_404\nfrom django.urls import reverse\nfrom django.utils.translation import gettext_lazy as _\n\nfrom .forms import AnswerForm\nfrom .models import Challenge, Context, Level, LevelSequence, Question, User\n\n\ndef find_user_by_uuid(user_uuid: UUID) -> User:\n return get_object_or_404(User, uuid=user_uuid)\n\n\ndef get_user_from_request(request: HttpRequest) -> User:\n user_uuid = request.session[\"user_uuid\"]\n user = find_user_by_uuid(user_uuid)\n return user\n\n\ndef set_next_level_user(request: HttpRequest, user: User) -> None:\n current_index = user.current_level.index\n next_level = Level.objects.filter(index__gt=current_index).order_by(\"index\").first()\n\n if not next_level:\n messages.success(\n request,\n _(\"Congratulations! You have completed all available levels.\"),\n )\n return HttpResponseRedirect(reverse(\"dashboard\"))\n\n user.current_level = next_level\n first_level_position = user.current_level.get_first_level_position()\n user.current_position = first_level_position if first_level_position else None\n user.save()\n\n\ndef set_position_user(user: User, direction: str) -> None:\n level_sequence = LevelSequence.objects.filter(level=user.current_level)\n\n if not level_sequence:\n return\n\n order_by_field = \"position\" if direction == \"next\" else \"-position\"\n filter_condition = \"gt\" if direction == \"next\" else \"lt\"\n\n position = (\n level_sequence.filter(\n **{f\"position__{filter_condition}\": user.current_position}\n )\n .order_by(order_by_field)\n .first()\n )\n\n if position:\n user.current_position = position.position\n user.save()\n\n\ndef set_progress_course(user: User) -> None:\n level_sequence = LevelSequence.objects.filter(level=user.current_level)\n user_score = user.score_set.filter(level=user.current_level).first()\n\n if not level_sequence or not user_score:\n return\n\n index = level_sequence.filter(position__lte=user.current_position).count()\n total_positions = level_sequence.count()\n\n if total_positions > 0:\n progress = (index / total_positions) * 100\n user_score.progress = progress\n user_score.save()\n\n\ndef get_slides_content(user: User) -> []:\n slides = []\n level_sequence = LevelSequence.objects.filter(\n level=user.current_level, position__gte=user.current_position\n ).order_by(\"position\")[:2]\n for sequence in level_sequence:\n content_type = sequence.content_type\n object_id = sequence.object_id\n\n if content_type == ContentType.objects.get_for_model(Context):\n context = get_object_or_404(Context, pk=object_id)\n slides.append(\n {\n \"context\": {\n \"texts\": context.contexttexttemplate_set.all(),\n \"medias\": context.contextmediatemplate_set.all(),\n }\n }\n )\n elif content_type == ContentType.objects.get_for_model(Question):\n question = get_object_or_404(Question, pk=object_id)\n form = AnswerForm(question=question)\n form.question_index = get_question_index(user, sequence.position)\n slides.append({\"question\": form})\n elif content_type == ContentType.objects.get_for_model(Challenge):\n challenge = get_object_or_404(Challenge, pk=object_id)\n slides.append({\"challenge\": challenge})\n\n return slides\n\n\ndef get_question_index(user: User, position: int) -> int:\n questions = LevelSequence.objects.filter(\n level=user.current_level,\n content_type=ContentType.objects.get_for_model(Question),\n ).order_by(\"position\")\n index = questions.filter(position__lte=position).count()\n return index\n\n\ndef set_status_carousel_controls(user: User) -> [bool, bool]:\n try:\n current_sequence = LevelSequence.objects.get(\n level=user.current_level, position=user.current_position\n )\n\n sequence_before = (\n LevelSequence.objects.filter(\n level=user.current_level, position__lt=user.current_position\n )\n .order_by(\"position\")\n .last()\n )\n\n sequence_after = (\n LevelSequence.objects.filter(\n level=user.current_level, position__gt=user.current_position\n )\n .order_by(\"position\")\n .first()\n )\n\n previous_control_enable = bool(\n sequence_before\n and sequence_before.content_type\n != ContentType.objects.get_for_model(Question)\n )\n next_control_enable = bool(\n sequence_after\n and current_sequence.content_type\n != ContentType.objects.get_for_model(Question)\n )\n\n except LevelSequence.DoesNotExist:\n previous_control_enable = False\n next_control_enable = False\n\n return [previous_control_enable, next_control_enable]\n","repo_name":"NC3-LU/eLearning","sub_path":"elearning/viewLogic.py","file_name":"viewLogic.py","file_ext":"py","file_size_in_byte":5197,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"6428416316","text":"'''\nProblem: In an array, arr, the elements at indices i and j (where i < j) form an inversion if arr[i] > arr[j]. In other words, inverted\n elements arr[i] and arr[j] are considered to be \"out of order\". To correct an inversion, we can swap adjacent elements.\n For example, consider the dataset arr = [2,4,1]. It has two inversions: (4,1) and (2,1).\n Given d datasets, print the number of inversions that must be swapped to sort each dataset on a new line.\n\n Function Description: Complete the function countInversions in the editor below. It must return an integer representing the number of\n inversions required to sort the array.\n countInversions has the following parameter(s):\n arr: an array of integers to sort .\n\n Input Format: The first line contains an integer, d, the number of datasets.\n Each of the next d pairs of lines is as follows:\n --> The first line contains an integer, n, the number of elements in arr.\n --> The second line contains n space-separated integers, arr[i].\n\n Constraints: 1 <= d <= 15\n 1 <= n <= 10^5\n 1 <= arr[i] <= 10^7\n\n Output Format: For each of the d datasets, return the number of inversions that must be swapped to sort the dataset.\n'''\ndef mergeArrays(arr, leftside, rightside):\n inversion = 0\n i, j, k = [0] * 3\n\n left_size, right_size = len(leftside), len(rightside)\n\n while i < left_size and j < right_size:\n if leftside[i] <= rightside[j]:\n arr[k] = leftside[i]\n i += 1\n else:\n arr[k] = rightside[j]\n j += 1\n inversion += (left_size - i)\n k += 1\n\n while i < left_size:\n arr[k] = leftside[i]\n i += 1\n k += 1\n \n while j < right_size:\n arr[k] = rightside[j]\n j += 1\n k += 1\n \n return arr, inversion\n\ndef mergeSort(arr):\n if len(arr) <= 1 :\n return arr, 0\n\n mid = len(arr) // 2 \n\n leftside, left_result = mergeSort(arr[:mid])\n rightside, right_result = mergeSort(arr[mid:])\n\n merged_arr, merge_result = mergeArrays(arr, leftside, rightside)\n\n return merged_arr, (left_result + right_result + merge_result)\n\ndef countInversions(arr):\n _sorted, inversion = mergeSort(arr)\n return inversion\n\nif __name__ == \"__main__\":\n for _ in range(int(input())):\n _arr_size = int(input())\n arr = list(map(int, input().strip().split()))\n\n print(countInversions(arr))","repo_name":"AkashSiddharth/PythonWorkspace","sub_path":"DataStructure/Sorting/countingInversion.py","file_name":"countingInversion.py","file_ext":"py","file_size_in_byte":2555,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"32710797606","text":"import numpy as np\nimport json\ndef solution(arr1, arr2):\n arr3=np.array(arr1)\n arr4=np.array(arr2)\n result=np.dot(arr3,arr4)\n return result.tolist()\n\n\nprint(solution([[1, 4], [3, 2], [4, 1]],\t[[3, 3], [3, 3]]))","repo_name":"yec3168/algorithm","sub_path":"programmers/lv_2/행렬의 곱셉.py","file_name":"행렬의 곱셉.py","file_ext":"py","file_size_in_byte":222,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"27289551838","text":"import pymongo\r\n\r\nclient = pymongo.MongoClient(\"mongodb://localhost:27017/\")\r\n\r\n#database\r\ndatabase = client[\"employeeDB\"]\r\n\r\n#collection\r\ncollection = database[\"employeesDB\"]\r\n\r\nfilter = {\"LastName\":\"Rose\"}\r\n\r\n\r\ncollection.delete_one(filter)\r\n\r\nemployeeCursor = collection.find()\r\n\r\nfor employee in employeeCursor:\r\n\r\n print(employee)","repo_name":"maquiavelo01/DatabaseContainerization","sub_path":"mongoDBDeleteOne.py","file_name":"mongoDBDeleteOne.py","file_ext":"py","file_size_in_byte":338,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"8421972539","text":"from django.http import HttpResponse, HttpResponseRedirect\nfrom django.shortcuts import render, get_object_or_404\nfrom django.urls import reverse\nfrom django.utils import timezone\n\nfrom .models import *\nfrom .forms import *\n\nfrom .Code.test import *\n# from .Code.test import ND\n\ndef index(request):\n latest_input_image_list = Input_Image.objects.order_by('-input_upload_time')[:]\n context = {'latest_input_image_list': latest_input_image_list}\n return render(request, 'ioi/index.html', context)\n\ndef noise_index(request):\n latest_input_cloud_list = Input_cloud.objects.order_by('-input_upload_time')[:]\n context = {'latest_input_cloud_list': latest_input_cloud_list}\n return render(request,'ioi/noise_index.html', context)\n\ndef object_index(request):\n latest_input_cloud_list = Input_cloud.objects.order_by('-input_upload_time')[:]\n context = {'latest_input_cloud_list': latest_input_cloud_list}\n return render(request,'ioi/object_index.html', context)\n\ndef seperation_index(request):\n latest_input_cloud_list = Input_cloud.objects.order_by('-input_upload_time')[:]\n context = {'latest_input_cloud_list': latest_input_cloud_list}\n return render(request,'ioi/seperation_index.html', context)\n\n\ndef welcome(request):\n return render(request, 'ioi/welcome.html')\n\ndef upload_image(request):\n if request.method == 'POST':\n form = UploadImageForm(request.POST)\n if form.is_valid():\n input_image = Input_Image(input_calib_url=form.cleaned_data[\"input_calib_url\"],\n input_image_2_url=form.cleaned_data[\"input_image_2_url\"],\n input_label_2_url=form.cleaned_data[\"input_label_2_url\"],\n input_velodyne_url=form.cleaned_data[\"input_velodyne_url\"],\n input_upload_time=timezone.now())\n input_image.save()\n return HttpResponseRedirect('/ioi/upload_image')\n else:\n form = UploadImageForm()\n return render(request, 'ioi/upload_image.html', {'form': form})\n\ndef upload_cloud(request):\n if request.method == 'POST':\n form = UploadCloudForm(request.POST)\n if form.is_valid():\n input_cloud = Input_cloud(input_cloud_2_url=form.cleaned_data[\"input_cloud_url\"],\n input_upload_time=timezone.now())\n input_cloud.save()\n return HttpResponseRedirect('/ioi/upload_cloud')\n else:\n form = UploadCloudForm()\n return render(request, 'ioi/upload_cloud.html', {'form': form})\n\n\ndef detail(request, input_image_id):\n input_image = get_object_or_404(Input_Image, pk=input_image_id)\n if request.method == \"POST\":\n form = ProcessImageForm(request.POST)\n if form.is_valid():\n output_image = Output_Image(input_id=input_image,\n output_folder_url=form.cleaned_data[\"output_folder_url\"])\n output_image.save()\n IOI(input_image.input_calib_url,\n input_image.input_image_2_url,\n input_image.input_label_2_url,\n input_image.input_velodyne_url,\n form.cleaned_data[\"output_folder_url\"])\n context = {'input_image': input_image,\n 'process': True,\n 'output_folder_url': form.cleaned_data[\"output_folder_url\"],\n 'form': form}\n else:\n form = ProcessImageForm()\n context = {'input_image': input_image,\n 'process': False,\n 'form': form}\n return render(request, 'ioi/detail.html', context)\n\ndef noise_detail(request, input_cloud_id):\n # empty_form = DocumentForm(request.POST,request.FILES)\n input_cloud = get_object_or_404(Input_cloud, pk=input_cloud_id)\n if request.method == \"POST\":\n form = ProcessCloudForm(request.POST)\n if form.is_valid():\n # print(form.cleaned_data[\"output_folder_url\"])\n # output_cloud = Output_cloud(input_id=input_cloud,\n # output_folder_url=form.cleaned_data[\"output_folder_url\"])\n # output_cloud.save()\n ND(input_cloud.input_cloud_2_url,\n form.cleaned_data[\"output_folder_url\"])\n context = {'input_cloud': input_cloud,\n 'process': True,\n 'output_folder_url': form.cleaned_data[\"output_folder_url\"],\n 'form': form}\n \n else:\n form = ProcessCloudForm()\n context = {'input_cloud': input_cloud,\n 'process': False,\n 'form': form}\n return render(request, 'ioi/noise_detail.html', context)\n\ndef object_detail(request, input_cloud_id):\n input_cloud = get_object_or_404(Input_cloud, pk=input_cloud_id)\n if request.method == \"POST\":\n form = ProcessCloudForm(request.POST)\n if form.is_valid():\n # output_cloud = Output_cloud(input_id=input_cloud,\n # output_folder_url=form.cleaned_data[\"output_folder_url\"])\n # output_cloud.save()\n OD(input_cloud.input_cloud_2_url,\n form.cleaned_data[\"output_folder_url\"])\n context = {'input_cloud': input_cloud,\n 'process': True,\n 'output_folder_url': form.cleaned_data[\"output_folder_url\"],\n 'form': form}\n else:\n form = ProcessCloudForm()\n context = {'input_cloud': input_cloud,\n 'process': False,\n 'form': form}\n return render(request, 'ioi/object_detail.html', context)\n\ndef seperation_detail(request, input_cloud_id):\n input_cloud = get_object_or_404(Input_cloud, pk=input_cloud_id)\n if request.method == \"POST\":\n form = ProcessCloudForm(request.POST)\n if form.is_valid():\n # output_cloud = Output_cloud(input_id=input_cloud,\n # output_folder_url=form.cleaned_data[\"output_folder_url\"])\n # output_cloud.save()\n SD(input_cloud.input_cloud_2_url,\n form.cleaned_data[\"output_folder_url\"])\n context = {'input_cloud': input_cloud,\n 'process': True,\n 'output_folder_url': form.cleaned_data[\"output_folder_url\"],\n 'form': form}\n else:\n form = ProcessCloudForm()\n context = {'input_cloud': input_cloud,\n 'process': False,\n 'form': form}\n return render(request, 'ioi/seperation_detail.html', context)\n\n","repo_name":"5fing3rs/CloudMerge","sub_path":"webapp/ioi/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":6676,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"81"} +{"seq_id":"73388351306","text":"# Minimum Time Visiting All Points\nfrom typing import List\n\n\nclass Solution:\n def minTimeToVisitAllPoints(self, points: List[List[int]]) -> int:\n x, y = points.pop()\n ans = 0\n while points:\n a, b = points.pop()\n ans += max(abs(x-a), abs(y-b))\n x, y = a, b\n return ans","repo_name":"GavinPHR/code","sub_path":"phase3/1266.py","file_name":"1266.py","file_ext":"py","file_size_in_byte":331,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"81"} +{"seq_id":"40428334977","text":"from vcs.cli import BaseCommand\nfrom vcs.cli import COMPLETION_ENV_NAME\n\n\nCOMPLETION_TEMPLATE = '''\n# %(prog_name)s bash completion start\n_%(prog_name)s_completion()\n{\n COMPREPLY=( $( COMP_WORDS=\"${COMP_WORDS[*]}\" \\\\\n COMP_CWORD=$COMP_CWORD \\\\\n %(ENV_VAR_NAME)s=1 $1 ) )\n}\ncomplete -o default -F _%(prog_name)s_completion %(prog_name)s\n# %(prog_name)s bash completion end\n\n'''\n\n\nclass CompletionCommand(BaseCommand):\n help = ''.join((\n 'Prints out shell snippet that once evaluated would allow '\n 'this command utility to use completion abilities.',\n ))\n template = COMPLETION_TEMPLATE\n\n def get_completion_snippet(self):\n return self.template % {'prog_name': 'vcs',\n 'ENV_VAR_NAME': COMPLETION_ENV_NAME}\n\n def handle(self, **options):\n self.stdout.write(self.get_completion_snippet())\n","repo_name":"codeinn/vcs","sub_path":"vcs/commands/completion.py","file_name":"completion.py","file_ext":"py","file_size_in_byte":879,"program_lang":"python","lang":"en","doc_type":"code","stars":67,"dataset":"github-code","pt":"81"} +{"seq_id":"38199847431","text":"from numula.nscore import *\nfrom numula.notate_score import *\n\ndef test1():\n ns = Score(n('c d e f g a b c'))\n ns.insert_pedal(PedalUse(4/4, 3/4, True))\n ns.write_midi('data/test1.midi')\n\ntest1()\n \n","repo_name":"davidpanderson/Numula","sub_path":"examples/test_note.py","file_name":"test_note.py","file_ext":"py","file_size_in_byte":214,"program_lang":"python","lang":"en","doc_type":"code","stars":28,"dataset":"github-code","pt":"81"} +{"seq_id":"28239764663","text":"import sqlite3\n# Create a SQL connection to our SQLite database\ncon = sqlite3.connect(\"bookdatabase.db\")\n\ncur = con.cursor()\n\n# Return all\n# Return first result of query\nfor row in cur.execute('SELECT * FROM note WHERE id=\"abc\"'):\n print (row)\n\ncur.fetchall()\n# cur.fetchall()\n\n# Be sure to close the connection\ncon.close()","repo_name":"jamie082/Grocery_API","sub_path":"query.py","file_name":"query.py","file_ext":"py","file_size_in_byte":326,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"31410424708","text":"'''\n华为2021.7.21机考第一题\n\n相当于求几段时间序列的最大交集\n第一行输入N k,N表示有N个站点,k表示有k个乘客,其中N个站点分布在一个环上(注意是环,可以顺时针,可以逆时针),每个站点之间需要走5分钟\n后面几行输入st id1 id2,其中st表示出发时间,id1表示出发站点,id2表示目的站点\n\n求同一时间最多有多少个人在路上\n\n------------\n例1:\n输入:\n50 3\n0 0 15\n10 10 11\n15 20 40\n输出:\n2\n-----------\n主要思路:首先整理出来每个人在路上的时间,然后求这些时间的最大交集,我采用的方法是对这些时间排序,然后依次求排序后相邻两点之间的中间点,\n遍历这些中间点,求跟每段时间的交点个数,最后取最大即可,算法复杂度比较高,应该有更好的方法\n\n'''\ndef func(N, k, matrix):\n time_range = []\n for st, id1, id2 in matrix:\n t1 = st\n id1, id2 = min(id1,id2), max(id1, id2)\n t2 = 5*min(id2-id1, id1+N-id2)\n time_range.append([t1,t2+t1])\n list0 = []\n for i in time_range:\n if i[0] not in list0: list0.append(i[0])\n if i[1] not in list0: list0.append(i[1])\n list0.sort()\n n = len(list0)\n out = []\n for i in range(n-1):\n t0 = (list0[i]+list0[i+1])/2.0\n count = 0\n for j in range(k):\n if t0time_range[j][0]:\n count+=1\n out.append(count)\n \n \n return max(out)\n\nimport sys\nwhile(1):\n data = sys.stdin.readline()\n if data=='': break\n data = data.strip().split(' ')\n N = int(data[0])\n k = int(data[1])\n matrix = []\n for i in range(k):\n data = sys.stdin.readline()\n data = data.strip().split(' ')\n if data[1]==data[2]: continue\n data = [int(j) for j in data]\n matrix.append(data)\n print(func(N, len(matrix), matrix))\n \n \n","repo_name":"kiyoxi2020/leetcode","sub_path":"huawei/2021-7-21-1.py","file_name":"2021-7-21-1.py","file_ext":"py","file_size_in_byte":1948,"program_lang":"python","lang":"zh","doc_type":"code","stars":2,"dataset":"github-code","pt":"81"} +{"seq_id":"26243106788","text":"# -*- mode: python -*-\na = Analysis(['gertrude.pyw'],\n datas=[\n (\"*.ini.dist\", \".\"),\n (\"demo.db\", \".\"),\n (\"*.php\", \".\"),\n (\"bitmaps_dist\\\\*.png\", \"bitmaps_dist\"),\n (\"bitmaps_dist\\\\pictos\\\\*.png\", \"bitmaps_dist\\\\pictos\"),\n (\"bitmaps_dist\\\\*.ico\", \"bitmaps_dist\"),\n (\"templates_dist\\\\*.html\", \"templates_dist\"),\n (\"templates_dist\\\\*.txt\", \"templates_dist\"),\n (\"templates_dist\\\\*.od?\", \"templates_dist\")\n ],\n hiddenimports=[\"_cffi_backend\"],\n hookspath=None,\n runtime_hooks=None)\npyz = PYZ(a.pure)\nexe = EXE(pyz,\n a.scripts,\n exclude_binaries=True,\n name='gertrude.exe',\n debug=False,\n strip=None,\n upx=True,\n console=False,\n icon='bitmaps_dist\\\\gertrude.ico' )\ncoll = COLLECT(exe,\n a.binaries,\n a.zipfiles,\n a.datas,\n strip=None,\n upx=True,\n name='gertrude')\n","repo_name":"studio1247/gertrude","sub_path":"gertrude.spec","file_name":"gertrude.spec","file_ext":"spec","file_size_in_byte":1117,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"81"} +{"seq_id":"12025929718","text":"# Configuration file for the Sphinx documentation builder.\n#\n# This file only contains a selection of the most common options. For a full\n# list see the documentation:\n# https://www.sphinx-doc.org/en/master/usage/configuration.html\n\n# -- Path setup --------------------------------------------------------------\n\n# If extensions (or modules to document with autodoc) are in another directory,\n# add these directories to sys.path here. If the directory is relative to the\n# documentation root, use os.path.abspath to make it absolute, like shown here.\n#\nimport os\n\n# If extensions (or modules to document with autodoc) are in another directory,\n# add these directories to sys.path here. If the directory is relative to the\n# documentation root, use os.path.abspath to make it absolute, like shown here.\n#\n# import sys\n# sys.path.insert(0, os.path.abspath('.'))\n\n\n# -- Project information -----------------------------------------------------\n\nproject = 'www.bigga.de'\nhtml_title = 'www.bigga.de'\ncopyright = '2023, Alexander Bigga'\nauthor = 'Alexander Bigga'\n\nlanguage = 'de'\n\n# -- General configuration ---------------------------------------------------\n\n# Add any Sphinx extension module names here, as strings. They can be\n# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom\n# ones.\nextensions = [\n \"myst_parser\",\n \"ablog\",\n \"sphinx_design\",\n \"sphinxext.opengraph\",\n \"sphinxext.rediraffe\",\n]\n\n# Add any paths that contain templates here, relative to this directory.\ntemplates_path = ['_templates']\n\n# List of patterns, relative to source directory, that match files and\n# directories to ignore when looking for source files.\n# This pattern also affects html_static_path and html_extra_path.\nexclude_patterns = ['_build', 'Thumbs.db', '.DS_Store', \"*import_posts*\", \"**/pandoc_ipynb/inputs/*\", \".nox/*\", \"README.md\"]\n\n\n# -- Options for HTML output -------------------------------------------------\n\n# The theme to use for HTML and HTML Help pages. See the documentation for\n# a list of builtin themes.\n#\nhtml_theme = 'pydata_sphinx_theme'\n\nhtml_theme_options = {\n \"github_url\": \"https://github.com/albig/\",\n \"icon_links\": [\n {\n \"name\": \"Mastodon\",\n \"url\": \"https://gruene.social/@albigdd\",\n \"icon\": \"fa-brands fa-mastodon\",\n \"attributes\": {\n \"target\" : \"_blank\",\n \"rel\" : \"noopener me\",\n }\n },\n ],\n \"use_edit_page_button\": True,\n \"search_bar_text\": \"Seite durchsuchen...\",\n \"navbar_end\": [\"navbar-icon-links.html\"],\n \"show_toc_level\": 2,\n \"show_nav_level\": 2,\n \"footer_start\": [\"copyright\", \"sphinx-version\"],\n \"footer_end\": [\"impressum\", \"datenschutz\"]\n}\n\nhtml_favicon = \"_static/favicon.ico\"\n\nhtml_logo = \"_static/logo.png\"\n\n# Add any paths that contain custom static files (such as style sheets) here,\n# relative to this directory. They are copied after the builtin static files,\n# so a file named \"default.css\" will overwrite the builtin \"default.css\".\nhtml_static_path = ['_static']\n\nhtml_extra_path = ['_static/robots.txt']\n\n# html_extra_path = [\"feed.xml\"]\nhtml_sidebars = {\n \"index\": [\"hello.html\", \"sidebar-nav-bs.html\"],\n \"about\": [\"hello.html\", \"sidebar-nav-bs.html\"],\n \"posts/**\": [\"search-field.html\", \"postcard.html\", \"recentposts.html\", \"archives.html\"],\n \"blog\": [\"tagcloud.html\", \"archives.html\"],\n \"blog/**\": [\"postcard.html\", \"recentposts.html\", \"archives.html\"],\n}\n\nhtml_context = {\n \"github_user\": \"albig\",\n \"github_repo\": \"www.bigga.de\",\n \"github_version\": \"main\",\n \"doc_path\": \"\",\n}\n\nblog_baseurl = \"https://www.bigga.de/\"\nblog_title = \"Alexander Bigga - Blog\"\nblog_path = \"blog\"\nfontawesome_included = True\nblog_post_pattern = \"posts/*/*/*/*\"\nblog_languages = {\n 'de': ('Deutsch', None),\n 'en': ('English', None),\n}\nblog_default_language = \"de\"\npost_redirect_refresh = 1\npost_auto_image = 1\npost_auto_excerpt = 2\n\n# MyST config\nmyst_enable_extensions = [\n \"deflist\",\n \"colon_fence\",\n]\n\n# Bibliography and citations\n# bibtex_bibfiles = [\"_static/works.bib\"]\n\n# OpenGraph config\nogp_site_url = \"https://www.bigga.de\"\nogp_image = \"https://www.bigga.de/_static/bigga-alexander.jpg\"\n\n# Temporarily stored as off until we fix it\njupyter_execute_notebooks = \"off\"\n\n\nextensions += [\"sphinx_sitemap\"]\n\nhtml_baseurl = 'https://www.bigga.de/'\nsitemap_locales = [None]\nsitemap_url_scheme = \"{link}\"\n\nrediraffe_redirects = {\n}\n\ndef setup(app):\n app.add_css_file(\"custom.css\")\n","repo_name":"albig/www.bigga.de","sub_path":"conf.py","file_name":"conf.py","file_ext":"py","file_size_in_byte":4438,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"14040613198","text":"class LinkedList:\n \"\"\"\n Used to create a singly linked list. Has methods to create a new node at the beginning of the list, search\n for a value in the list, and return a string that represents all items in the list.\n \"\"\"\n\n def __init__(self):\n self.head = None\n\n def __str__(self):\n text = \"\"\n current = self.head\n while current is not None:\n text += \"{ \" + str(current.value) + \" } -> \"\n current = current.next\n return text + \"NULL\"\n\n def insert(self, value):\n new_node = Node(value)\n new_node.next = self.head\n self.head = new_node\n\n def append(self, value):\n if self.head is None:\n self.head = Node(value)\n else:\n current = self.head\n while current.next is not None:\n current = current.next\n current.next = Node(value)\n\n def insert_before(self, idx, new):\n if self.head is None:\n raise TargetError\n\n current = self.head\n if current.value == idx:\n new_node = Node(new)\n new_node.next = self.head\n self.head = new_node\n return f\"Successfully created {new}!\"\n\n while current and current.next is not None:\n if current.next.value == idx:\n new_node = Node(new)\n new_node.next = current.next\n current.next = new_node\n return f\"Successfully created {new}!\"\n current = current.next\n raise TargetError\n\n def insert_after(self, idx, new):\n if self.head is None:\n raise TargetError\n\n\n current = self.head\n while current is not None:\n if current.value == idx:\n new_node = Node(new)\n new_node.next = current.next\n current.next = new_node\n return f\"Successfully created {new}!\"\n current = current.next\n raise TargetError\n\n def includes(self, value):\n current = self.head\n while current is not None:\n if current.value == value:\n return True\n current = current.next\n return False\n\n def get_length(self):\n length = 0\n current = self.head\n while current:\n length += 1\n current = current.next\n return length\n\n def kth_from_end(self, k):\n if k < 0:\n raise TargetError\n length = self.get_length()\n\n if k > length:\n raise TargetError\n if k >= length:\n raise TargetError\n\n target_idx = (length - 1) - k\n current_idx = 0\n current = self.head\n\n while current:\n\n if current_idx == target_idx:\n return current.value\n\n current_idx += 1\n current = current.next\n\n\nclass Node:\n def __init__(self, value, next = None):\n self.value = value\n self.next = next\n\nclass TargetError(Exception):\n pass\n","repo_name":"guddbye/data-structures-and-algorithms","sub_path":"python/data_structures/linked_list.py","file_name":"linked_list.py","file_ext":"py","file_size_in_byte":3012,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"16294655655","text":"from depen import *\nfrom hparams import hyperparams\nfrom datasets import COMMONVOICE, collate_fn_common\nfrom modules import Model_Check\nimport shutil\n\n\n\"\"\"\n\npath = hyperparams.path_dataset_common\nTSV = \"my_train.tsv\"\nfolder = \"clips\"\nnew_folder = \"new_clips\"\n\ntsvm = os.path.join(path, TSV)\nfolder = os.path.join(path, folder)\nnew_folder = os.path.join(path, new_folder)\n\ndf = pd.read_csv(tsvm, sep=\"\\t\")\n\ns = df[\"path\"].values.tolist()\nfor i in range(len(s)):\n s[i] = str(s[i])\n\nfor f in s:\n f = os.path.join(folder, f)\n shutil.move(f, new_folder)\n \n\n\"\"\"\n\n\n\n\nprint(\"############################### Test\")\n\nTSV = \"ph_end_new_my_test.tsv\"\ndataset = COMMONVOICE(hyperparams.path_dataset_common, TSV, 2, mel_limit=2500, reconstructed=True, dias_ph=True)\n\neverything, truefalse = dataset[1]\nwaveforms, waveform_l, sample_rates, client_ids, sentences, sentences_l = everything\nprint(waveforms, \"\\n\", sample_rates, \"\\n\", client_ids, \"\\n\", sentences, \"\\n\", truefalse)\n\n\nprint(\"############################### Collate Test\")\nlistt = [1, 2]\nlistt[0] = dataset[0]\nlistt[1] = dataset[1]\n\nsentences_tensor, sentences_mask, spectrograms, mel_mask, waveforms, waveform_l, client_ids, example_id = collate_fn_common(listt, \"test\", reconstructed_phoneme=True)\n\nprint(sentences_tensor.shape, spectrograms.shape)\nmodel = Model_Check(hyperparams)\nx = model.forward(sentences_tensor, sentences_mask, spectrograms, mel_mask)\nprint(x.shape)\n\n\"\"\"\nprint(\"Sentence tensor \\n\", sentences_tensor, \"\\n\", sentences_tensor.shape)\nprint(\"###############################\")\nprint(\"Sentence mask \\n\", sentences_mask, \"\\n\", sentences_mask.shape)\nprint(\"###############################\")\nprint(\"spectrograms \\n\", spectrograms, \"\\n\", spectrograms.shape)\nprint(\"###############################\")\nprint(\"mel_mask \\n\", mel_mask, \"\\n\", mel_mask.shape)\nprint(\"###############################\")\nprint(\"waveforms \\n\", waveforms, \"\\n\", waveforms.shape)\nprint(\"###############################\")\nprint(\"waveform_l \\n\", waveform_l, \"\\n\", len(waveform_l))\nprint(\"###############################\")\nprint(\"client_ids \\n\", client_ids, \"\\n\", len(client_ids))\nprint(\"###############################\")\nprint(\"example_id \\n\", example_id, \"\\n\", len(example_id))\nprint(\"###############################\")\n\"\"\"\n\n\n\"\"\"\n\n\nprint(\"############################### Train\")\n\n\n\nTSV = \"train.tsv\"\ndataset = COMMONVOICE(hyperparams.path_dataset_common, TSV, 10)\nprint(\"############################### Train numbers\")\neverything, truefalse = dataset[1]\nwaveforms, waveform_l, sample_rates, client_ids, sentences, sentences_l = everything\nprint(waveforms, \"\\n\", sample_rates, \"\\n\", client_ids, \"\\n\", sentences, \"\\n\")\nprint(\"############################### Collate Train\")\n\nlistt = [1, 2]\nlistt[0] = dataset[0]\nlistt[1] = dataset[1]\n\nsentences_tensor, sentences_mask, spectrograms, mel_mask, waveforms, waveform_l, client_ids, example_id = collate_fn_common(listt, \"train\")\n\nprint(\"Sentence tensor \\n\", sentences_tensor, \"\\n\", sentences_tensor.shape)\nprint(\"###############################\")\nprint(\"Sentence mask \\n\", sentences_mask, \"\\n\", sentences_mask.shape)\nprint(\"###############################\")\nprint(\"spectrograms \\n\", spectrograms, \"\\n\", spectrograms.shape)\nprint(\"###############################\")\nprint(\"last spectrograms \\n\", spectrograms[19], \"\\n\", spectrograms[19][0][120:128],\"\\n\", spectrograms[19][0][120],\"\\n\", spectrograms[19][0][2][1500:1600],\"\\n\",mel_mask[19])\nprint(\"###############################\")\nprint(\"mel_mask \\n\", mel_mask, \"\\n\", mel_mask.shape)\nprint(\"###############################\")\nprint(\"waveforms \\n\", waveforms, \"\\n\", waveforms.shape)\nprint(\"###############################\")\nprint(\"waveform_l \\n\", waveform_l, \"\\n\", len(waveform_l))\nprint(\"###############################\")\nprint(\"client_ids \\n\", client_ids, \"\\n\", len(client_ids))\nprint(\"###############################\")\nprint(\"example_id \\n\", example_id, \"\\n\", len(example_id))\nprint(\"###############################\")\n\n\nnumpy_array = np.array(everything)\nprint(numpy_array)\nprint(numpy_array.shape)\n\nprint(numpy_array[0][0])\n\nprint(type(numpy_array[0][0]))\n\n\"\"\"","repo_name":"Etzelkut/sound_deep","sub_path":"direct_syth/dataset_play_ground.py","file_name":"dataset_play_ground.py","file_ext":"py","file_size_in_byte":4092,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"4858316945","text":"# -*- coding: utf-8 -*-\n\nimport shutil\nimport sys\nimport os\nimport __builtin__\nimport exceptions\nimport traceback\n\n\ndef main():\n source(findFile(\"scripts\", \"BasicFunctionality/startup.py\"))\n shared = Startup(\"ATTACH_TO_RUNNING_STATION\")\n version = shared.version\n\n step_counter = 10\n \n #10. Navigate to QC > Reproducibility subtab and review the toolbar for actions that can be performed.\n test.log(\"Step #\" + str(step_counter)); step_counter += 1\n shared.reproducibilitytab.clickTab() \n #\"Confirm the following items are available on the toolbar:\n #-Analyzer selector combobox\n shared.qctab.confirmAnalyzerSelector()\n #-\"\"Print\"\" button (currently grayed out disabled)\n #-\"\"Export\"\" button\n #-\"\"DigiCount\"\", \"\"Reproducibility\"\", and \"\"Whole Blood\"\" buttons\n #-Control selector combobox\n #-Control Details text under the Control selector combobox and the Control Status to the right of the combobox\n #-\"\"Cancel\"\" button (grayed out if the control selected is completed/canceled already)\n #-\"\"Exclude\"\" button ( disabled by default unless a table cell is selected)\" [VM 12.16.13]\n shared.reproducibilitytab.confirmQCButtons()\n #Confirm that the Reproducibility table is displayed properly (all parameters and results are displayed) by selecting each control under the Control selector combobox.\n shared.reproducibilitytab.confirmReproducibilityTable()\n \n #11. Navigate to QC > Whole Blood > Graph subtab\n test.log(\"Step #\" + str(step_counter)); step_counter += 1\n shared.wholebloodtab.clickTab() \n #\"Confirm that the following buttons/functionality (click on each button and review the result) are available on the Whole Blood graph:\n #-Analyzer selector combobox\n shared.qctab.confirmAnalyzerSelector()\n #-\"\"Print\"\" button (currently disabled)\n #-\"\"DigiCount\"\", \"\"Reproducibility\"\", \"\"Whole Blood\"\", and \"\"Activate/Edit\"\" buttons\n #-\"\"Exclude\"\" button (disabled if a point is not selected; enabled if a point is selected)\n #\" [VM 12.09.13]\n shared.wholebloodtab.confirmAllControls()\n #Confirm that the Whole Blood graph is displayed properly (all parameters and results are displayed).\n shared.wholebloodtab.confirmGraphResults(\"wholeblood_graph_01_00_1\",\"wholeblood_table_01_00_1\")\n #\"Confirm that at the bottom of the page the following buttons/functionality (click on each button and review the result) are available:\n #-A checkbox for each Analyzer with its name labeled\n shared.wholebloodtab.confirmCheckboxForEachAnalyzer()\n #- A color box next to each Analyzer to indicate the color of the graph line\n shared.wholebloodtab.confirmColorBox()\n #-\"\"Absolute\"\" and \"\"Percent\"\" radio buttons with \"\"Absolute\"\" being active by default\n shared.wholebloodtab.confirmAbsoluteAndPercentRadioButtons()\n #-A checkbox labeled \"\"Separate by Mode\"\" (unchecked by default)\n shared.wholebloodtab.confirmSeparateByModeCheckBox()\n #Confirm that clicking on the buttons or checkboxes changes the graph configurations.\n shared.wholebloodtab.confirmButtonsChangeGraphConfigurations() \n \n #12. Navigate to QC > Whole Blood > Table tab and review the toolbar for actions that can be performed.\n test.log(\"Step #\" + str(step_counter)); step_counter += 1\n shared.wholebloodtab.clickTableTab(\"Table\") \n #\"Confirm that the following buttons/functionality (click on each button and review the result) are available on the Whole Blood > Table tab:\n #-Analyzer selector combobox\n shared.qctab.confirmAnalyzerSelector()\n #-\"\"Print\"\" button (currently grayed out disabled)\n #-\"\"Export\"\" button\n #-\"\"DigiCount\"\", \"\"Reproducibility\"\", and \"\"Whole Blood\"\" buttons\n #-Control selector combobox\n #-Control Details text under the Control selector combobox and the Control Status to the right of the combobox\n #-\"\"Close\"\" button (disabled if the control selected is not active)\n #-\"\"Exclude\"\" button disabled by default unless a table cell is selected)\"\n shared.wholebloodtab.confirmTableButtons() \n #\"Confirm that at the bottom of the page following buttons/functionality (click on each button and review the result) are available\n #-Combobox labeled \"\"Reference\"\" and defaulted to \"\"Mean\"\"\n shared.wholebloodtab.confirmCombobox()\n #-\"\"Save\"\" button (enabled when the selected control is active and disabled if otherwise)\"\n shared.wholebloodtab.confirmSaveButton()\n \n #13. Below the Whole Blood Table click on the \"Reference\" combobox and select a different run in order to make it the Reference.\n test.log(\"Step #\" + str(step_counter)); step_counter += 1\n shared.wholebloodtab.selectARun() \n #Confirm that clicking on the combobox displays a list of choices based on the runs included in the table above.\n shared.wholebloodtab.confirmReferenceComboRuns() \n #Confirm that selecting something other than \"Mean\" from the Reference selector list causes the values in the Target / Mean column to change to match the values from the Analyzer column selected. \n #Confirm that if the user changes the reference, the table is immediately updated based on the new reference value.\n shared.wholebloodtab.confirmComboRunTargetReference()\n","repo_name":"henrywasserman/suite_Viewing_Station_Automation","sub_path":"tst_record_snippets/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":5297,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"73937407305","text":"from decimal import Decimal\nfrom requests import Session\nimport requests\nimport cryptocompare\nimport time\nimport json\n\nPrices = []\nUSDprice = \"\"\n\ndef tryethprice():\n url = 'https://pro-api.coinmarketcap.com/v1/cryptocurrency/quotes/latest'\n parameters = { 'slug': 'ethereum', 'convert': 'USD' }\n headers = {\n 'Accepts': 'application/json',\n 'X-CMC_PRO_API_KEY': '15f8bbf5-3527-4234-952e-28a0e3d5362f'\n } \n session = Session()\n session.headers.update(headers)\n response = session.get(url, params=parameters)\n info = json.loads(response.text)\n info = json.loads(response.text)['data']['1027']['quote']['USD']['price']\n return info\n\ndef getvalue(wallet):\n global USDprice\n\n url = f\"https://deep-index.moralis.io/api/v2/{wallet}/balance?chain=eth\"\n USDprice = cryptocompare.get_price('ETH', currency='USD').get(\"ETH\")[\"USD\"]\n\n headers = {\n \"accept\": \"application/json\",\n \"X-API-Key\": \"yFsFQPj6zULbj9SNBoQLSWdgvX9nU0aIrW0XDnZHVg4EtxgsvMwvLkjUzz52zrwJ\"\n }\n\n return requests.get(url, headers=headers).text\n\ndef getwalletprices(wallets:list):\n for i in wallets:\n Prices.append(Decimal(float(json.loads(getvalue(i))[\"balance\"])) / Decimal(10) ** 18)\n\ndef PricesToUSD():\n global value\n value = 0 \n\n for i in Prices: \n value += float(i) * float(tryethprice())\n Prices.clear()\n\n return value\n\nwhile True:\n getwalletprices([\"0x515ced994d4aab97db79dcb6c62751ed1f19f42f\"])\n USD = PricesToUSD()\n print(USD)\n time.sleep(30)\n","repo_name":"ffrxsln/moralis-ethbalance-python","sub_path":"ethbalance.py","file_name":"ethbalance.py","file_ext":"py","file_size_in_byte":1532,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"81"} +{"seq_id":"38658231592","text":"# Definition for singly-linked list.\n# class ListNode(object):\n# def __init__(self, x):\n# self.val = x\n# self.next = None\n\nclass Solution(object):\n def hasCycle(self, head):\n \n marker1 = head\n marker2 = head\n \n while marker2 != None and marker2.next != None:\n marker1 = marker1.next\n marker2 = marker2.next.next\n \n if marker1 == marker2:\n return True\n return False\n \n\n\n\nclass Node(object):\n def __init__(self,val):\n self.val = val\n self.nextnode = None\n \n#Linked List Cycle Check\n\ndef cycle_Check(node):\n marker1 = node\n marker2 = node\n \n while marker2 != None and marker2.nextnode != None:\n marker1 = marker1.nextnode\n marker2 = marker2.nextnode.nextnode\n \n if marker2 == marker1:\n return True\n return False\n \na.nextnode = b\nb.nextnode = c\nc.nextnode = a\ncycle_Check(a)\n","repo_name":"rajkhub/cert","sub_path":"LeetCode/LinkedListCycleCheck.py","file_name":"LinkedListCycleCheck.py","file_ext":"py","file_size_in_byte":979,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"41120372363","text":"#Crie um programa que leia vários números inteiros pelo teclado. O programa só vai parar quando o usuário digitar o valor 999, que é a condição de parada.\n#No final, mostre quantos números foram digitados e qual foi a soma entre eles (desconsiderando o flag).\nx = int(input('Digite um número [999 para parar]: '))\ny = 0\nz = 0\nwhile x != 999: \n y += x\n z += 1\n x = int(input('Digite um número: '))\nprint('Foram digitados {} números e a soma deles foi de {}'.format(z,y))","repo_name":"EdnaldoTeofilo/Curso-em-video-python","sub_path":"Mundo_2_EstruturasDeControle/ex064.py","file_name":"ex064.py","file_ext":"py","file_size_in_byte":489,"program_lang":"python","lang":"pt","doc_type":"code","stars":1,"dataset":"github-code","pt":"81"} +{"seq_id":"7567001768","text":"#! python3\n# persample_report_pipeline.py\n# Script to combine several input files into a cohesive report file\n# to understand the results of a SNP prediction project where the\n# goals are to obtain information on segregating populations, but where\n# SNP prediction has occurred per-sample.\n\n# Load normal/pip packages\nimport os, argparse, sys, re\nfrom goatools import obo_parser\n\n# Load ZS_IO Class code\nsys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))) # 4 dirs up is where we find Function_packages\nfrom Function_packages import ZS_GFF3IO, ZS_SeqIO\n\n# Load functions from other scripts\nsys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))) # 3 dirs up is where we find windows\nimport windows # pulls relevant functions from snp_proximity_report.py\nimport haplotypes\n\n# Hard-coded GO replacements\nreplacedGOs = {\"GO:0000453\": \"GO:0006364\", \"GO:0031224\": \"GO:0016020\",\n \"GO:0031225\": \"GO:0016020\", \"GO:0031300\": \"GO:0031090\",\n \"GO:0030176\": \"GO:0005789\", \"GO:0031227\": \"GO:0005789\",\n \"GO:0031301\": \"GO:0031090\", 'GO:0055076': 'GO:0030003',\n 'GO:0006875': 'GO:0030003', 'GO:0046916': 'GO:0030003',\n 'GO:0055067': 'GO:0055080', 'GO:0030004': 'GO:0030003',\n 'GO:0005779': 'GO:0005778', 'GO:0032592': 'GO:0031966',\n 'GO:0098573': 'GO:0031966', 'GO:0031231': 'GO:0005778',\n 'GO:0055065': 'GO:0030003', 'GO:0018196': 'GO:0018193',\n 'GO:0006471': 'GO:1990404', 'GO:0008022': 'GO:0005515',\n 'GO:0071458': 'GO:0098554', 'GO:0031304': 'GO:0005743',\n 'GO:0071556': 'GO:0098553', 'GO:0140323': 'GO:0022853',\n 'GO:0015299': 'GO:0015078', 'GO:0015298': 'GO:0022853',\n 'GO:0044728': 'GO:0006304', 'GO:0031226': 'GO:0005886',\n 'GO:0046658': 'GO:0005886', 'GO:0031305': 'GO:0005743',\n 'GO:0005451': 'GO:0022890', 'GO:0022610': 'GO:0008150'}\n\n# Define functions\ndef validate_args(args):\n # Validate input file locations\n if not os.path.isfile(args.annotFile):\n print(f'I am unable to locate the GOextended annotation file ({args.annotFile})')\n print('Make sure you\\'ve typed the file name or location correctly and try again.')\n quit()\n if not os.path.isfile(args.vcfFile):\n print(f'I am unable to locate the VCF file ({args.vcfFile})')\n print('Make sure you\\'ve typed the file name or location correctly and try again.')\n quit()\n if not os.path.isfile(args.gffFile):\n print(f'I am unable to locate the GFF3 file ({args.gffFile})')\n print('Make sure you\\'ve typed the file name or location correctly and try again.')\n quit()\n if not os.path.isfile(args.fastaFile):\n print(f'I am unable to locate the FASTA file ({args.fastaFile})')\n print('Make sure you\\'ve typed the file name or location correctly and try again.')\n quit()\n if not os.path.isfile(args.goOboFile):\n print(f'I am unable to locate the GO .obo file ({args.goOboFile})')\n print('Make sure you\\'ve typed the file name or location correctly and try again.')\n quit()\n if not os.path.isfile(args.metadataFile):\n print(f'I am unable to locate the metadata file ({args.metadataFile})')\n print('Make sure you\\'ve typed the file name or location correctly and try again.')\n quit()\n # Validate output file location\n if os.path.isfile(args.outputFileName):\n print(f'File already exists at output location ({args.outputFileName})')\n print('Make sure you specify a unique file name and try again.')\n quit()\n\ndef parse_pops_metadata(metadataFile):\n # Parse file\n metadataDict = {}\n with open(metadataFile, \"r\") as fileIn:\n for line in fileIn:\n sl = line.rstrip(\"\\r\\n \").split(\"\\t\")\n if sl == []:\n continue\n else:\n sample, pop = sl\n metadataDict.setdefault(pop, set())\n metadataDict[pop].add(sample)\n \n # Make sure it's valid for this script\n if len(metadataDict) == 2:\n assert all([ pop in ['bulk1', 'bulk2'] for pop in metadataDict.keys() ]), \\\n \"ERROR: Metadata file should have 2 or 3 populations: bulk1, bulk2, and (optionally) parent!\"\n elif len(metadataDict) == 3:\n assert all([ pop in ['bulk1', 'bulk2', 'parent'] for pop in metadataDict.keys() ]), \\\n \"ERROR: Metadata file should have 2 or 3 populations: bulk1, bulk2, and (optionally) parent!\"\n else:\n print(\"ERROR: Metadata file should have 2 or 3 populations: bulk1, bulk2, and (optionally) parent!\")\n quit()\n \n return metadataDict\n\ndef generate_bsa_proximity_dict(gff3Obj, genomeFASTA_obj, snpGenotypes):\n '''\n Reads in a GFF3 and locates SNPs in relation to gene features.\n Unlike the functions in snp_proximity_report.py, this function\n returns a different output which is somewhat of an amalgamation\n of the SNP and gene-centric reports. In reality, if this works\n I'll likely move it over there and just import it here!\n \n Parameters:\n gff3Obj -- a ZS_GFF3IO.GFF3 object with NCLS indexing of the gene features\n snpGenotypes -- a dictionary as produced by get_genotyped_snps_for_genes()\n with structure like:\n {\n 'contig1': {\n pos1: {\n 'ref_alt': ['nucleotide1', 'nucleotide2'],\n 'sample1': [allele1, allele2],\n 'sample2': [...],\n ...\n },\n pos2: { ... },\n ...\n }\n 'contig2': ...,\n ...\n }\n Returns:\n proximityDict -- a dictionary with structure like:\n {\n 'gene1': {\n 'contig': 'contigID',\n 'coords': 'start-end',\n 'within': [ snpData1, snpData2, ... ],\n 'left_of': [ snpData1, snpData2, ... ],\n 'right_of': [ snpData1, snpData2, ... ],\n 'samples': [ sample1_GT, sample2_GT, ...]\n },\n 'gene2': {\n ...\n },\n ...\n }\n '''\n proximityDict = {}\n \n for contig, snpDict in snpGenotypes.items():\n for pos in snpDict.keys():\n # Scenario 1: SNP located within a gene\n matches = gff3Obj.ncls_finder(pos, pos, \"contig\", contig)\n if matches != []: # i.e., if the SNP is located within a gene\n snpLocation, geneID = windows.locate_snp_within_gene(matches, pos)\n \n # Set default value for gene\n _setdefault_proximity(proximityDict, geneID, gff3Obj)\n \n # For non-CDS locations, just store data in dict\n if snpLocation != \"CDS\":\n proximityDict[geneID][pos] = {\n \"location\": snpLocation\n }\n # For CDS locations, predict its effect (if any)\n else:\n # Get the mRNA feature for this gene\n mrnaFeature = _get_mrnaFeature_for_cds_match(matches, pos)\n newSnpDict = haplotypes.convert_vcf_snps_to_cds_snps(mrnaFeature, snpDict, embedOriginalPos=True)\n cds_FastASeq_obj, cds_featureType, cds_startingFrame = gff3Obj.retrieve_sequence_from_FASTA(genomeFASTA_obj, mrnaFeature.ID, \"CDS\")\n \n # Just use the variant for this SNP position\n for newPos, genotypeDict in newSnpDict.items():\n if genotypeDict[\"originalPos\"] == pos:\n break # break so our variables are set\n del genotypeDict[\"originalPos\"] # need this to disappear to not break code! ... ugh, this is gross\n \n # Get data\n formattedRef, formattedAlts, homozygotes, heterozygotes \\\n = haplotypes.predict_variant(genotypeDict, newPos, cds_FastASeq_obj, mrnaFeature.strand)\n \n # Store data in our dictionary\n proximityDict[geneID][pos] = {\n \"location\": \"CDS\",\n \"ref\": formattedRef,\n \"alts\": formattedAlts,\n \"homo\": homozygotes,\n \"hetero\": heterozygotes\n }\n \n # Scenario 2: SNP located not inside, but near a gene\n else:\n nearestLeft, nearestRight = windows.locate_genes_near_snp(gff3Obj, contig, pos, mrnaIndexing=False) # NCLS has gene indexing\n if nearestLeft[1] != None:\n distance, geneID = nearestLeft\n \n # Set default value for gene\n _setdefault_proximity(proximityDict, geneID, gff3Obj)\n \n # Store data in dict\n proximityDict[geneID][pos] = {\n \"location\": \"right\", # gene is left of snp; hence snp is right of gene\n \"distance\": distance\n }\n \n if nearestRight[1] != None:\n distance, geneID = nearestRight\n \n # Set default value for gene\n _setdefault_proximity(proximityDict, geneID, gff3Obj)\n \n # Store data in dict\n proximityDict[geneID][pos] = {\n \"location\": \"left\", # gene is right of snp; hence snp is left of gene\n \"distance\": distance\n }\n \n return proximityDict\n\ndef _setdefault_proximity(proximityDict, geneID, gff3Obj):\n # Get gene feature from GFF3\n feature = gff3Obj[geneID]\n \n # Get representative mRNA feature\n mrnaFeature = ZS_GFF3IO.GFF3.longest_isoform(feature)\n \n # Setdefault in dict\n proximityDict.setdefault(geneID, {\n \"contig\": feature.contig,\n \"strand\": feature.strand,\n \"mRNA\": mrnaFeature.ID,\n \"start\": feature.start,\n \"end\": feature.end\n })\n\ndef _get_mrnaFeature_for_cds_match(matches, snpPos):\n for feature in matches:\n # Look for CDS overlap\n if hasattr(feature, \"mRNA\"):\n for mrnaFeature in feature.mRNA:\n for cdsFeature in mrnaFeature.CDS:\n if cdsFeature.start <= snpPos and snpPos <= cdsFeature.end: # if it overlaps...\n return mrnaFeature\n elif hasattr(feature, \"CDS\"):\n for cdsFeature in feature.CDS:\n if cdsFeature.start <= snpPos and snpPos <= cdsFeature.end: # if it overlaps...\n return feature\n return None\n\ndef parse_annot_file(annotFile, idsDict, proximityDict):\n '''\n Simple function to parse the GO extended annotation file and grab some details\n from it.\n '''\n HEADER_VALUES = [\"#Query\", \"Gene_names\", \"Best_mapped_GOs_+_parents\"]\n \n annotDict = {}\n with open(annotFile, \"r\") as fileIn:\n for line in fileIn:\n sl = line.rstrip(\"\\r\\n \").split(\"\\t\")\n \n # Handle header lines\n if line.startswith(\"#\"):\n idIndex = sl.index(HEADER_VALUES[0])\n nameIndex = sl.index(HEADER_VALUES[1])\n goIndex = sl.index(HEADER_VALUES[2])\n continue\n \n # Handle content lines\n else:\n # Grab basic details\n id = sl[idIndex]\n names = sl[nameIndex]\n gos = sl[goIndex]\n \n # Skip if we don't care about this gene\n if id in idsDict:\n geneID = idsDict[id]\n elif id in proximityDict:\n geneID = id\n else:\n continue\n \n # Get best hit name\n name = names.split(\" [\")[0].rstrip(\" \")\n \n # Store it\n annotDict[geneID] = {\n \"name\": name,\n \"gos\": gos\n }\n return annotDict\n\ndef format_snp_types(snpDict):\n '''\n Helper function for formatting SNP data into within/left/right categories.\n \n Parameters:\n snpDict -- a dictionary with structure like:\n {\n 'contig': 'contig_id',\n 'strand': '+', # or '-'\n ... ,\n snpPos1: { 'location': 'left/right/CDS', 'distance': intValue },\n snpPos2: { ... },\n ...\n }\n Returns:\n snpDetails -- a dictionary with structure like:\n {\n 'within_pos': '', # \"; \" separated list of values in [sCDS, UTR, T>G, etc.]\n 'within_location': '.', # numeric list of SNP positions\n 'left': '4095701', # numeric list of SNP positions\n 'left_dist': '23043', # numeric list of distances of SNP from nearest gene\n 'right': '.', # numeric list of SNP positions\n 'right_dist': '.' # numeric list of distances of SNP from nearest gene\n }\n '''\n orderedSNPs = sorted([x for x in snpDict.keys() if isinstance(x, int)])\n within_pos, within_location, left, left_dist, right, right_dist = [], [], [], [], [], []\n \n for snp in orderedSNPs:\n posDict = snpDict[snp]\n # Handle CDS\n if posDict[\"location\"] == \"CDS\":\n within_pos.append(str(snp))\n \n # Handle neutral variants\n refAmino = posDict[\"ref\"].split(\"(\")[1].rstrip(\")\")\n altAmino = \",\".join([ alt.split(\"(\")[1].rstrip(\")\") for alt in posDict[\"alts\"] ])\n \n if refAmino == altAmino:\n within_location.append(\"sCDS\")\n # Handle non-synonymous mutations\n else:\n within_location.append(f\"{refAmino}>{altAmino}\")\n \n # Handle intron/UTR\n elif posDict[\"location\"] in [\"UTR\", \"intron\"]:\n within_pos.append(str(snp))\n within_location.append(posDict[\"location\"])\n \n # Handle left/right\n elif posDict[\"location\"] == \"left\":\n left.append(str(snp))\n left_dist.append(str(posDict[\"distance\"]))\n elif posDict[\"location\"] == \"right\":\n right.append(str(snp))\n right_dist.append(str(posDict[\"distance\"]))\n \n return {\n \"within_pos\": \"; \".join(within_pos) if within_pos != [] else \".\",\n \"within_location\": \"; \".join(within_location) if within_location != [] else \".\",\n \"left\": \"; \".join(left) if left != [] else \".\",\n \"left_dist\": \"; \".join(left_dist) if left_dist != [] else \".\",\n \"right\": \"; \".join(right) if right != [] else \".\",\n \"right_dist\": \"; \".join(right_dist) if right_dist != [] else \".\"\n }\n\ndef format_genotypes(snpGenotypes, snpDetails, contigID, metadataDict):\n '''\n Parameters:\n snpGenotypes -- a dictionary as produced by get_genotyped_snps_for_genes()\n with structure like:\n {\n 'contig1': {\n pos1: {\n 'ref_alt': ['nucleotide1', 'nucleotide2'],\n 'sample1': [allele1, allele2],\n 'sample2': [...],\n ...\n },\n pos2: { ... },\n ...\n }\n 'contig2': ...,\n ...\n }\n snpDetails -- a dictionary as produced by format_snp_types() with structure like:\n {\n 'within_pos': '', # \"; \" separated list of values in [sCDS, UTR, T>G, etc.]\n 'within_location': '.', # numeric list of SNP positions\n 'left': '4095701', # numeric list of SNP positions\n 'left_dist': '23043', # numeric list of distances of SNP from nearest gene\n 'right': '.', # numeric list of SNP positions\n 'right_dist': '.' # numeric list of distances of SNP from nearest gene\n }\n contigID -- a string indicating which contig the SNP is located on.\n metadataDict -- a dictionary with structure like:\n {\n 'parent': set(['parent1']),\n 'bulk1': set(['b1sample1', 'b1sample2', ...]),\n 'bulk2': set(['b2sample1', b2sample2', ...])\n }\n Returns:\n snpGtFormat -- a list with three values, with structure like:\n [\n 'parental GT per SNP',\n 'bulk1 GT per SNP',\n 'bulk2 GT per SNP'\n ]\n Note that the format for each string value is akin to:\n \"snpPosition: 0/0=11,1/1=5,0/1=2\"\n The snpPosition is a numeric value. All present genotypes\n and their tallies are presented as shown above with comma\n separation.\n '''\n KEYS_TO_SKIP = [\"ref_alt\", \"originalPos\"]\n \n # Get SNP positions from snpDetails dict\n snpNumbers = [\n int(position)\n for key in [\"within_pos\", \"left\", \"right\"]\n for position in snpDetails[key].split(\"; \")\n if position != \".\"\n ]\n \n # Format data pertaining to this SNP\n snpGtDict = {}\n for pos in snpNumbers:\n # Figure out what genotypes exist for each SNP position\n gtDict = snpGenotypes[contigID][pos]\n gts = set([ \"/\".join(map(str, v)) for k,v in gtDict.items() if not k in KEYS_TO_SKIP ])\n \n # Set up for data storage of this SNP\n snpGtDict[pos] = {}\n for pop in metadataDict.keys():\n snpGtDict[pos][pop] = { gt:0 for gt in gts}\n \n # Tally genotypes for each population\n anyFound = False\n for key, value in gtDict.items():\n if key in KEYS_TO_SKIP:\n continue\n else:\n # Figure out what population this sample belongs to\n pop = [ k for k,v in metadataDict.items() if key in v ]\n \n if len(pop) != 1:\n continue\n else:\n anyFound = True\n \n pop = pop[0]\n \n # Figure out and store this genotype\n gt = \"/\".join(map(str, value))\n snpGtDict[pos][pop][gt] += 1\n if anyFound == False:\n print(\"ERROR: Issue in format_genotypes; your metadata file doesn't match your VCF\")\n print(\"In other words, we failed to find ANY samples from your metadata file in the VCF\")\n print(\"This is an irreconcilable error and we must exit out now...\")\n quit()\n \n # Reformat in sorted order of allele frequency\n \"\"\"\n This format will directly correspond to something that can be tabulated. Hence,\n it will have 3 columns for each population group (parents, bulk1, bulk2).\n \"\"\"\n snpGtFormat = [[], [], []]\n for pos, gtDict in snpGtDict.items():\n # Handle parent\n if \"parent\" in gtDict:\n parentGTs = sorted(gtDict[\"parent\"].items(), key = lambda item: -item[1])\n parentGTs = \",\".join([ f\"{gt}={count}\" for gt,count in parentGTs if count > 0])\n else:\n parentGTs = \".\"\n \n # Handle bulk1\n bulk1GTs = sorted(gtDict[\"bulk1\"].items(), key = lambda item: -item[1])\n bulk1GTs = \",\".join([ f\"{gt}={count}\" for gt,count in bulk1GTs if count > 0])\n bulk1GTs = \".\" if bulk1GTs == \"\" else bulk1GTs\n \n # Handle bulk2\n bulk2GTs = sorted(gtDict[\"bulk2\"].items(), key = lambda item: -item[1])\n bulk2GTs = \",\".join([ f\"{gt}={count}\" for gt,count in bulk2GTs if count > 0])\n bulk2GTs = \".\" if bulk2GTs == \"\" else bulk2GTs\n \n # Store into formatting list\n snpGtFormat[0].append(f\"{pos}: {parentGTs}\")\n snpGtFormat[1].append(f\"{pos}: {bulk1GTs}\")\n snpGtFormat[2].append(f\"{pos}: {bulk2GTs}\")\n \n snpGtFormat[0] = \"; \".join(snpGtFormat[0])\n snpGtFormat[1] = \"; \".join(snpGtFormat[1])\n snpGtFormat[2] = \"; \".join(snpGtFormat[2])\n \n return snpGtFormat\n\ndef calculate_difference_ratio(original_b1, original_b2):\n GT_REGEX = re.compile(r\"\\d/\\d\")\n \n original_b1Alleles = original_b1.split(\"; \") # can be multiple SNP positions separated by \"; \"\n original_b2Alleles = original_b2.split(\"; \")\n \n # Loop through each allele separately to hackily get results\n ratios = []\n for b1, b2 in zip(original_b1Alleles, original_b2Alleles):\n position = b1.split(\": \")[0]\n \n b1Alleles = [b1]\n b2Alleles = [b2]\n \n # See if we have any multiallelic variant\n genotypes = set(GT_REGEX.findall(b1)).union(set(GT_REGEX.findall(b2)))\n alleles = sorted(list(set([ a for gt in genotypes for a in gt.split(\"/\") ]))) # sort should be fine if single digit\n thisAlleles = {\n \"b1\": [0 for allele in alleles],\n \"b2\": [0 for allele in alleles]\n }\n \n # Handle identical allele compositions\n \"If everything is 0/0 or 1/1, we know the ratio == 0.0; stop here to prevent bugs\"\n if len(alleles) == 1:\n ratios.append(f\"{position}: 0.0\")\n continue\n \n # Tally alleles at this locus\n for x in range(len(b1Alleles)):\n # Get alleles at this position\n b1x = b1Alleles[x]\n b2x = b2Alleles[x]\n \n # Skip tallying if it's not possible at this locus\n if \".\" in b1x or \".\" in b2x:\n continue\n \n # Tally for bulk 1\n for b1xAllele in b1x.split(\",\"):\n b1xAllele = b1xAllele.split(\": \")[-1]\n gt, count = b1xAllele.split(\"=\")\n for gtValue in gt.split(\"/\"):\n alleleIndex = alleles.index(gtValue)\n thisAlleles[\"b1\"][alleleIndex] += int(count)\n \n # Tally for bulk 2\n for b2xAllele in b2x.split(\",\"):\n b2xAllele = b2xAllele.split(\": \")[-1]\n gt, count = b2xAllele.split(\"=\")\n for gtValue in gt.split(\"/\"):\n alleleIndex = alleles.index(gtValue)\n thisAlleles[\"b2\"][alleleIndex] += int(count)\n \n # Calculate the proportions of each allele for this locus\n b1Sum = sum(thisAlleles[\"b1\"])\n b2Sum = sum(thisAlleles[\"b2\"])\n \n if b1Sum == 0 or b2Sum == 0: # if this happens, we can't meaningfully calculate anything\n ratios.append(f\"{position}: .\")\n continue\n \n thisProportion = {\n \"b1\": [ alleleCount / b1Sum for alleleCount in thisAlleles[\"b1\"] ],\n \"b2\": [ alleleCount / b2Sum for alleleCount in thisAlleles[\"b2\"] ]\n }\n \n # Derive our difference ratio value\n proportionCommon = sum([\n min(thisProportion[\"b1\"][x], thisProportion[\"b2\"][x])\n for x in range(len(thisProportion[\"b1\"]))\n ])\n differenceRatio = 1 - proportionCommon\n \n ratios.append(f\"{position}: {differenceRatio}\")\n return ratios\n\ndef format_difference_ratio(snpGtFormat, diffPerSnp=False):\n '''\n Parameters:\n snpGtFormat -- a list with three values, with structure like:\n [\n 'parental GT per SNP',\n 'bulk1 GT per SNP',\n 'bulk2 GT per SNP'\n ]\n Note that the format for each string value is akin to:\n \"snpPosition: 0/0=11,1/1=5,0/1=2\"\n The snpPosition is a numeric value. All present genotypes\n and their tallies are presented as shown above with comma\n separation.\n diffPerSnp -- a boolean indicating whether the difference ratio should\n be shown per-SNP (True) or as a summed value per-locus (False)\n Returns:\n differenceRatio -- a string representing a ratio from 0->1, where 1 indicates\n entirely different allele composition, and 0 indicates\n identical alleles in the two populations. In short, close to 1\n gives us interesting regions, and close to 0 should be\n ignored when doing a BSA-like inspection.\n '''\n # Extract relevant bits of data from snpGtFormat\n b1 = snpGtFormat[1] # we don't care about the parent for this index\n b2 = snpGtFormat[2]\n \n ratios = calculate_difference_ratio(b1, b2)\n \n if diffPerSnp == True:\n return \"; \".join(ratios)\n else:\n NUM_REGEX = re.compile(r\"\\d\\.\\d+\")\n numbers = NUM_REGEX.findall(\" \".join(ratios))\n try:\n totalRatio = sum(map(float, numbers)) / len(numbers)\n except:\n totalRatio = \".\"\n return totalRatio\n\ndef main():\n # User input\n usage = \"\"\"%(prog)s receives several files associated with a per-sample SNP\n prediction project dealing with two segregating populations. It combines relevant\n information into a cohesive and comprehensive report TSV file.\n \n Required input files are:\n 1) GOextended annotation table from annotation_table_extend_GOs.py.\n 2) VCF containing variant calls for multiple samples belonging to two segregating phenotype\n groups (optionally, can include parents).\n 3) Gene annotation GFF3 file.\n 4) Genome FASTA file.\n 5) GO .obo file.\n 6) Metadata file indicating the groups each sample belongs to.\n \n Alongside these, you should specify several parameters to control the behaviour\n of this script.\n \"\"\"\n \n # Required\n p = argparse.ArgumentParser(description=usage)\n p.add_argument(\"-annot\", dest=\"annotFile\",\n required=True,\n help=\"Specify the GOextended annotation file name\")\n p.add_argument(\"-vcf\", dest=\"vcfFile\",\n required=True,\n help=\"Specify the VCF file name\")\n p.add_argument(\"-gff\", dest=\"gffFile\",\n required=True,\n help=\"Specify the genome annotation GFF3 file name\")\n p.add_argument(\"-fasta\", dest=\"fastaFile\",\n required=True,\n help=\"Specify the genome FASTA file name\")\n p.add_argument(\"-obo\", dest=\"goOboFile\",\n required=True,\n help=\"Specify the GO .obo file name\")\n p.add_argument(\"-meta\", dest=\"metadataFile\",\n required=True,\n help=\"Specify the metadata file name\")\n p.add_argument(\"-o\", dest=\"outputFileName\",\n required=True,\n help=\"Specify the output file name\")\n # Optional\n p.add_argument(\"--diff_per_snp\", dest=\"diffPerSnp\",\n required=False,\n action=\"store_true\",\n help=\"\"\"Optionally, specify this flag to output SNP-index-like\n values for each SNP rather than summing them into a single per-locus\n value\"\"\",\n default=False)\n \n args = p.parse_args()\n validate_args(args)\n \n # Parse GO.obo\n go = obo_parser.GODag(args.goOboFile)\n \n # Parse metadata file\n metadataDict = parse_pops_metadata(args.metadataFile)\n \n # Parse GFF3 with NCLS indexing\n gff3Obj = ZS_GFF3IO.GFF3(args.gffFile, strict_parse=False)\n gff3Obj.create_ncls_index(typeToIndex=\"gene\")\n \n # Parse FASTA file\n genomeFASTA_obj = ZS_SeqIO.FASTA(args.fastaFile)\n \n # Parse VCF data for outlier SNP genotypes\n snpGenotypes = haplotypes.get_genotypes_from_vcf(args.vcfFile, snpPositions=None, imputeMissing=False)\n \n # Get the proximity reporting dict (including effects prediction)\n proximityDict = generate_bsa_proximity_dict(gff3Obj, genomeFASTA_obj, snpGenotypes)\n \n # Parse annotation file for relevant entries\n mrnaDict = { proximityDict[key][\"mRNA\"]: key for key in proximityDict.keys() }\n annotDict = parse_annot_file(args.annotFile, mrnaDict, proximityDict)\n \n # Combine everything into a table output\n needsReplace = set()\n with open(args.outputFileName, \"w\") as fileOut:\n # Write header line\n fileOut.write(\"{0}\\n\".format(\"\\t\".join([\n \"#contig\", \"gene_ID\", \"mRNA_ID\", \"strand\",\n \"coords\", \"gene_name\", \"GO_IDs\", \"GO_names\",\n \"within_pos\", \"within_location\", \"left_pos\",\n \"left_distance\", \"right_pos\", \"right_distance\",\n \"parentGT\", \"bulk1GT\", \"bulk2GT\", \"difference_ratio\"\n #\"desirable_delta\"\n ])))\n \n # Write content lines\n for geneID, snpDict in proximityDict.items():\n annot = annotDict[geneID]\n \n # Get GO names from IDs\n if annot[\"gos\"] == \".\":\n goNames = \".\"\n else:\n goNames = []\n for term in annot[\"gos\"].split(\"; \"):\n if term in replacedGOs:\n goNames.append(go.get(replacedGOs[term]).name)\n else:\n try:\n goNames.append(go.get(term).name)\n except:\n needsReplace.add(term)\n goNames = \"; \".join(goNames)\n \n # Format SNP details\n snpDetails = format_snp_types(snpDict)\n \n # Format genotype info\n snpGtFormat = format_genotypes(snpGenotypes, snpDetails, snpDict[\"contig\"], metadataDict)\n \n # Calculate difference ratio\n differenceRatio = format_difference_ratio(snpGtFormat, args.diffPerSnp)\n \n # Format output line\n outputLine = \"{contig}\\t{geneID}\\t{mrnaID}\\t{strand}\\t{coords}\\t{geneName}\\\n\\t{gos}\\t{goNames}\\t{within_pos}\\t{within_location}\\t{left}\\\n\\t{left_dist}\\t{right}\\t{right_dist}\\\n\\t{gtFormat}\\t{differenceRatio}\\n\".format(\n contig = snpDict[\"contig\"],\n geneID = geneID,\n mrnaID = snpDict[\"mRNA\"],\n strand = snpDict[\"strand\"],\n coords = \"{0}-{1}\".format(snpDict[\"start\"], snpDict[\"end\"]),\n geneName = annot[\"name\"],\n gos = annot[\"gos\"],\n goNames = goNames,\n within_pos = snpDetails[\"within_pos\"],\n within_location = snpDetails[\"within_location\"],\n left = snpDetails[\"left\"],\n left_dist = snpDetails[\"left_dist\"],\n right = snpDetails[\"right\"],\n right_dist = snpDetails[\"right_dist\"],\n gtFormat = \"\\t\".join(snpGtFormat),\n differenceRatio = differenceRatio\n )\n \n # Write output row as line\n fileOut.write(outputLine)\n \n if len(needsReplace) != 0:\n print(\"Some GOs need replacing for this to work correctly!\")\n print(f\"These are: {needsReplace}\")\n \n print(\"Program completed successfully!\")\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"zkstewart/Various_scripts","sub_path":"popgen/bulk_segregant/report/persample_report_pipeline.py","file_name":"persample_report_pipeline.py","file_ext":"py","file_size_in_byte":32594,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"81"} +{"seq_id":"23532668340","text":"import torch\nimport torch as t\nimport torch.nn as nn\nfrom toolbox.models.BBSnetmodel.decoder import SG\nfrom torch.autograd import Variable as V\nimport torchvision.models as models\nfrom toolbox.models.BBSnetmodel.ResNet import ResNet50,ResNet34\nfrom torch.nn import functional as F\nfrom toolbox.models.BBSnetmodel.fusion import fusion\nfrom toolbox.models.BBSnetmodel.refine import Refine\nfrom toolbox.models.BBSnetmodel.SG import SG\nfrom toolbox.models.BBSnetmodel.ASPP import ASPP\nclass BasicConv2d(nn.Module):\n def __init__(self,in_channel,out_channel,kernel_size,stride=1,padding=0,dilation=1):\n super(BasicConv2d, self).__init__()\n self.conv1 = nn.Conv2d(in_channel,out_channel,kernel_size=kernel_size,stride=stride,padding=padding,dilation=dilation,bias=False)\n self.bn = nn.BatchNorm2d(out_channel)\n self.relu = nn.ReLU(inplace=True)\n def forward(self,x):\n x = self.conv1(x)\n x = self.bn(x)\n x = self.relu(x)\n return x\nclass BasicConv2d_norelu(nn.Module):\n def __init__(self,in_channel,out_channel,kernel_size,stride=1,padding=0,dilation=1):\n super(BasicConv2d_norelu, self).__init__()\n self.conv1 = nn.Conv2d(in_channel,out_channel,kernel_size=kernel_size,stride=stride,padding=padding,dilation=dilation,bias=False)\n self.bn = nn.BatchNorm2d(out_channel)\n # self.relu = nn.ReLU(inplace=True)\n def forward(self,x):\n x = self.conv1(x)\n x = self.bn(x)\n # x = self.relu(x)\n return x\n\n#GCM\n# class GCM(nn.Module):\n# def __init__(self,inchannels,outchannels):\n# super(GCM, self).__init__()\n# self.branches0 = nn.Sequential(\n# BasicConv2d(inchannels,outchannels,kernel_size=1)\n# )\n# self.branches1 = nn.Sequential(\n# BasicConv2d(inchannels,outchannels,kernel_size=1),\n# BasicConv2d(outchannels,outchannels,kernel_size=(1,3),padding=(0,1)),\n# BasicConv2d(outchannels,outchannels,kernel_size=(3,1),padding=(1,0)),\n# BasicConv2d(outchannels,outchannels,kernel_size=3,padding=3,dilation=3)\n# )\n# self.branches2 = nn.Sequential(\n# BasicConv2d(inchannels, outchannels, kernel_size=1),\n# BasicConv2d(outchannels, outchannels, kernel_size=(1, 5), padding=(0, 2)),\n# BasicConv2d(outchannels, outchannels, kernel_size=(5, 1), padding=(2, 0)),\n# BasicConv2d(outchannels, outchannels, kernel_size=3, padding=5, dilation=5)\n# )\n# self.branches3 = nn.Sequential(\n# BasicConv2d(inchannels, outchannels, kernel_size=1),\n# BasicConv2d(outchannels, outchannels, kernel_size=(1, 7), padding=(0, 3)),\n# BasicConv2d(outchannels, outchannels, kernel_size=(7, 1), padding=(3, 0)),\n# BasicConv2d(outchannels, outchannels, kernel_size=3, padding=7, dilation=7)\n# )\n# self.conv1 = BasicConv2d(4*outchannels,outchannels,kernel_size=3,padding=1)\n# self.conv2 = BasicConv2d(inchannels,outchannels,kernel_size=1)\n# def forward(self,x):\n# x0 = self.branches0(x)\n# x1 = self.branches1(x)\n# x2 = self.branches2(x)\n# x3 = self.branches3(x)\n# out_cat = self.conv1(torch.cat((x0,x1,x2,x3),dim=1))\n# out_x = self.conv2(x)\n# out = out_cat+out_x\n# return out\n\n\n\n#用rgb增强depth\n# class DA(nn.Module):\n# def __init__(self,inchannel,outchannel):\n# super(DA, self).__init__()\n# self.conv1 = BasicConv2d(in_channel=2*inchannel,out_channel=outchannel,kernel_size=3,padding=1)\n# self.conv2 = nn.Conv2d(outchannel,outchannel,kernel_size=1,padding=0)\n# self.bn1 = nn.BatchNorm2d(outchannel)\n# def forward(self,r,d):\n# combine = torch.cat((r,d),dim=1)\n# combine = self.conv1(combine)\n# out = combine+r\n# out = self.conv2(out)\n# out = self.bn1(out)\n# out = out+d\n# return out\n\nclass serialaspp(nn.Module):\n def __init__(self,inc,outc,flag = None):\n super(serialaspp, self).__init__()\n # self.dconv1 = BasicConv2d_norelu(in_channel=2048,out_channel=1024,kernel_size=3,padding=1)\n # self.dconv6 = BasicConv2d_norelu(in_channel=1024,out_channel=512,kernel_size=3,padding=6,dilation=6)\n # self.dconv12 = BasicConv2d_norelu(in_channel=512,out_channel=256,kernel_size=3,padding=12,dilation=12)\n # self.dconv18 = BasicConv2d_norelu(in_channel=256,out_channel=64,kernel_size=3,padding=18,dilation=18)\n # self.dconv24 = BasicConv2d_norelu(in_channel=128,out_channel=64,kernel_size=3,padding=24,dilation=24)\n self.flag = flag\n self.dconv1 = BasicConv2d(in_channel=256, out_channel=256, kernel_size=3, padding=1)\n self.dconv2 = BasicConv2d(in_channel=128, out_channel=128, kernel_size=3, padding=2,dilation=2)\n self.dconv4 = BasicConv2d(in_channel=64, out_channel=64, kernel_size=3, padding=4,dilation=4)\n # self.dconv6 = BasicConv2d_norelu(in_channel=256, out_channel=128, kernel_size=3, padding=6, dilation=6)\n # self.dconv12 = BasicConv2d_norelu(in_channel=128, out_channel=64, kernel_size=3, padding=12, dilation=12)\n # self.dconv18 = BasicConv2d_norelu(in_channel=64, out_channel=64, kernel_size=3, padding=18, dilation=18)\n\n # self.conv_4 = nn.Conv2d(2 * 1024, 1024,kernel_size=3, padding=1)\n # self.conv_3 = nn.Conv2d(2 * 512, 512, kernel_size=3, padding=1)\n # self.conv_2 = nn.Conv2d(2 * 256, 256, kernel_size=3, padding=1)\n # self.conv_4 = nn.Conv2d(2 * 256, 256, kernel_size=3, padding=1)\n # self.conv_3 = nn.Conv2d(2 * 128, 128, kernel_size=3, padding=1)\n # self.conv_2 = nn.Conv2d(2 * 64, 64, kernel_size=3, padding=1)\n # self.conv = nn.Conv2d(64,nclass,kernel_size=3,padding=1)\n # self.relu = nn.ReLU(inplace=True)\n # self.upsample2 = nn.Upsample(scale_factor=2, mode='bilinear', align_corners=True)\n # self.upsample4= nn.Upsample(scale_factor=4, mode='bilinear', align_corners=True)\n # self.sig = nn.Sigmoid()\n\n self.tconv1 = nn.ConvTranspose2d(inc, outc,kernel_size=3, stride=2, padding=1,output_padding=1, bias=False)\n self.tconv_end = nn.ConvTranspose2d(outc, outc, kernel_size=3, stride=2, padding=1, output_padding=1, bias=False)\n self.bn = nn.BatchNorm2d(outc)\n self.relu = nn.ReLU(inplace=True)\n def forward(self,x1,x2):\n x2 = self.tconv1(x2)\n x2 = self.bn(x2)\n x2 = self.relu(x2)\n # print(x1.shape)\n # print(x2.shape)\n out = x1+x2\n if self.flag==1:\n out = self.dconv1(out)\n elif self.flag==2:\n out = self.dconv2(out)\n else:\n out = self.dconv4(out)\n out = self.tconv_end(out)\n return out\n\n\n\n\n\n # x5 = self.upsample2(x5)\n # dout5 = self.dconv1(x5)\n #\n # x4 = torch.cat((x4,dout5),dim=1)\n # x4 = self.conv_4(x4)\n #\n # x4 = self.upsample2(x4)\n # dout4 = self.dconv6(x4)\n #\n # x3 = torch.cat((x3,dout4),dim=1)\n # x3 = self.conv_3(x3)\n #\n # x3 = self.upsample2(x3)\n # dout3 = self.dconv12(x3)\n #\n # x2 = torch.cat((x2,dout3),dim=1)\n # x2 = self.conv_2(x2)\n # dout2 = self.dconv18(x2)\n #\n #\n # out = self.upsample4(dout2)\n # out = self.conv(out)\n # dout6 = self.dconv6(x)\n # dout6 = x + dout6\n # dout6 = self.relu(dout6)\n # dout12 = self.dconv12(dout6)\n # dout12 = dout6 + dout12\n # dout12 = self.relu(dout12)\n # dout18 = self.dconv18(dout12)\n # dout18 = dout12 + dout18\n # dout18 = self.relu(dout18)\n # dout24 = self.dconv24(dout18)\n # out = dout18 + dout24\n # # out = self.relu(out)\n # out = self.conv(out)\n # # out = self.sig(dout24)\n # return out\n\n\nclass FRNet(nn.Module):\n def __init__(self, channel=32,n_class=None):\n super(FRNet, self).__init__()\n\n # Backbone model\n\n self.resnet = ResNet34('rgb') #64 64 128 256 512\n self.resnet_depth = ResNet34('rgbd')\n\n\n #ACM\n # self.acm1 = acm(64)\n # self.acm2 = acm(64)\n # self.acm3 = acm(128)\n # self.acm4 = acm(256)\n # self.acm5 = acm(512)\n #融合\n self.fusions = nn.ModuleList([\n fusion(64),\n fusion(128),\n fusion(256),\n fusion(512)\n\n ])\n self.refines_r_5 = nn.ModuleList([\n Refine(256,512,k=2),\n # Refine(128,512,k=4),\n # Refine(64,512,k=8)\n ])\n self.refines_r_4 = nn.ModuleList([\n Refine(128, 256,k=2),\n # Refine(64, 256,k=4)\n\n ])\n self.refines_r_3 = nn.ModuleList([\n Refine(64, 128,k=2),\n\n ])\n self.refines_d_5 = nn.ModuleList([\n Refine(256, 512,k=2),\n # Refine(128, 512,k=4),\n # Refine(64, 512,k=8)\n ])\n self.refines_d_4 = nn.ModuleList([\n Refine(128, 256,k=2),\n # Refine(64, 256,k=4)\n\n ])\n self.refines_d_3 = nn.ModuleList([\n Refine(64, 128,k=2),\n\n ])\n\n # self.conv_layer4 = BasicConv2d(2*512,512,kernel_size=3,padding=1)\n\n # self.upsample8 = nn.Upsample(scale_factor=8, mode='bilinear', align_corners=True)\n# self.upsample4 = nn.Upsample(scale_factor=4, mode='bilinear', align_corners=True)\n# self.upsample2 = nn.Upsample(scale_factor=2, mode='bilinear', align_corners=True)\n# #layer1_fusion细化conv1\n# self.conv1 = nn.Conv2d(2048*2,1024,kernel_size=3,padding=1)\n# self.conv2 = nn.Conv2d(1024, 512, kernel_size=3, padding=1)\n# self.conv3 = nn.Conv2d(512, 256, kernel_size=3, padding=1)\n# self.conv4 = nn.Conv2d(256, 64, kernel_size=3, padding=1)\n#\n# self.bconv5 = BasicConv2d(in_channel=2048,out_channel=1024,kernel_size=3,padding=1)\n# self.bconv4 = BasicConv2d(in_channel=1024, out_channel=512, kernel_size=3, padding=1)\n# self.bconv3 = BasicConv2d(in_channel=512, out_channel=256, kernel_size=3, padding=1)\n# self.bconv2 = BasicConv2d(in_channel=256, out_channel=64, kernel_size=3, padding=1)\n# self.bconv1 = BasicConv2d(in_channel=64, out_channel=n_class, kernel_size=3, padding=1)\n#\n# self.conv_end = nn.Conv2d(64,n_class,kernel_size=1,padding=0)\n\n # self.sgs = nn.ModuleList([\n # SG(256,512,flag=1,in_plane=256),\n # SG(128,256,flag=2,in_plane=128),\n # SG(64,128,flag=3,in_plane=64),\n # SG(64,64,c=False,flag=4,in_plane=64)\n # ])\n # #self.aspp = ASPP(num_classes=n_class)\n # #处理layer4_fusion\n # self.transconv = nn.ConvTranspose2d(512, 256, kernel_size=1, padding=0)\n # self.bn = nn.BatchNorm2d(256)\n #\n # 对每一层cat之后进行通道变换\n # self.conv_aux1 = nn.Conv2d(6,3,kernel_size=1,stride=1)\n # self.conv_aux2 = nn.Conv2d(64, n_class, kernel_size=1, stride=1)\n # self.conv_aux3 = nn.Conv2d(64, n_class, kernel_size=1, stride=1)\n # self.conv_aux4 = nn.Conv2d(64, n_class, kernel_size=1, stride=1)\n # self.decoder = serialaspp(nclass=n_class)\n self.decoder = nn.ModuleList([\n serialaspp(512,256,flag=1),\n serialaspp(256,128,flag=2),\n serialaspp(128,64,flag=3)\n ])\n\n self.conv_end = nn.Conv2d(64,n_class,kernel_size=1,padding=0)\n self.upsample2 = nn.Upsample(scale_factor=2, mode='bilinear', align_corners=True)\n self.conv_aux1 = nn.Conv2d(256,n_class,kernel_size=1,padding=0)\n self.conv_aux2 = nn.Conv2d(128, n_class, kernel_size=1, padding=0)\n self.conv_aux3 = nn.Conv2d(64, n_class, kernel_size=1, padding=0)\n\n #加载预训练\n if self.training:\n self.initialize_weights()\n\n def forward(self, x, x_depth):\n x_depth = x_depth[:, :1, ...]\n #conv1 64 ,1/4\n x1 = self.resnet.conv1(x)\n x1 = self.resnet.bn1(x1)\n x1 = self.resnet.relu(x1)\n\n x1 = self.resnet.maxpool(x1)\n #h,w = x1.size()[2:]\n x_depth1 = self.resnet_depth.conv1(x_depth)\n x_depth1 = self.resnet_depth.bn1(x_depth1)\n x_depth1 = self.resnet_depth.relu(x_depth1)\n\n x_depth1 = self.resnet_depth.maxpool(x_depth1)\n\n #layer1 256 1/4\n\n x2 = self.resnet.layer1(x1)\n x_depth2 = self.resnet_depth.layer1(x_depth1)\n\n #layer2 512 1/8\n x3 = self.resnet.layer2(x2)\n x_depth3 = self.resnet_depth.layer2(x_depth2)\n\n #layer3 1024 1/16\n\n x4 = self.resnet.layer3_1(x3)\n x_depth4 = self.resnet_depth.layer3_1(x_depth3)\n\n\n #layer4 2048 1/32\n\n x5 = self.resnet.layer4_1(x4)\n x_depth5 = self.resnet_depth.layer4_1(x_depth4)\n\n fuse5 = self.fusions[3](x5,x_depth5)\n x4 = self.refines_r_5[0](x4,fuse5)\n # x3 = self.refines_r_5[1](x3,fuse5)\n # x2 = self.refines_r_5[2](x2,fuse5)\n x_depth4 = self.refines_d_5[0](x_depth4,fuse5)\n # x_depth3 = self.refines_d_5[1](x_depth3, fuse5)\n # x_depth2 = self.refines_d_5[2](x_depth2, fuse5)\n fuse4 = self.fusions[2](x4,x_depth4)\n x3 = self.refines_r_4[0](x3, fuse4)\n # x2 = self.refines_r_4[1](x2, fuse4)\n x_depth3 = self.refines_d_4[0](x_depth3, fuse4)\n # x_depth2 = self.refines_d_4[1](x_depth2, fuse4)\n fuse3 = self.fusions[1](x3,x_depth3)\n x2 = self.refines_r_3[0](x2,fuse3)\n x_depth2 = self.refines_d_3[0](x_depth2,fuse3)\n fuse2 = self.fusions[0](x2,x_depth2)\n\n out45 = self.decoder[0](fuse4,fuse5) #256\n out43 = self.decoder[1](fuse3,out45) #128\n out32 = self.decoder[2](fuse2,out43) #64\n out = self.upsample2(out32)\n out = self.conv_end(out)\n a_out1 = self.conv_aux1(out45)\n a_out2 = self.conv_aux2(out43)\n a_out3 = self.conv_aux3(out32)\n # out = self.decoder(fuse2,fuse3,fuse4,fuse5)\n if self.training:\n return a_out1, a_out2, a_out3, out\n else:\n return out\n\n\n\n\n # initialize the weights\n def initialize_weights(self):\n\n #pretrain_dict = model_zoo.load_url(model_urls['resnet50'])\n res34 = models.resnet34(pretrained=True)\n pretrained_dict = res34.state_dict()\n all_params = {}\n for k, v in self.resnet.state_dict().items():\n if k in pretrained_dict.keys():\n v = pretrained_dict[k]\n all_params[k] = v\n elif '_1' in k:\n name = k.split('_1')[0] + k.split('_1')[1]\n v = pretrained_dict[name]\n all_params[k] = v\n elif '_2' in k:\n name = k.split('_2')[0] + k.split('_2')[1]\n v = pretrained_dict[name]\n all_params[k] = v\n assert len(all_params.keys()) == len(self.resnet.state_dict().keys())\n self.resnet.load_state_dict(all_params)\n\n all_params = {}\n for k, v in self.resnet_depth.state_dict().items():\n if k == 'conv1.weight':\n all_params[k] = torch.nn.init.normal_(v, mean=0, std=1)\n elif k in pretrained_dict.keys():\n v = pretrained_dict[k]\n all_params[k] = v\n elif '_1' in k:\n name = k.split('_1')[0] + k.split('_1')[1]\n v = pretrained_dict[name]\n all_params[k] = v\n elif '_2' in k:\n name = k.split('_2')[0] + k.split('_2')[1]\n v = pretrained_dict[name]\n all_params[k] = v\n assert len(all_params.keys()) == len(self.resnet_depth.state_dict().keys())\n self.resnet_depth.load_state_dict(all_params)\n\nif __name__ == '__main__':\n x = V(t.randn(2,3,480,640))\n y = V(t.randn(2,3,480,640))\n net = FRNet(n_class=41)\n net1= net(x,y)\n print(net1.shape)\n\n\n # from torchsummary import summary\n # model = FRNet(n_class=41)\n # model = model.cuda()\n # summary(model, input_size=[(3, 480, 640),(3,480,640)],batch_size=6)","repo_name":"EnquanYang2022/FRNet","sub_path":"toolbox/models/FRNet/FRNet.py","file_name":"FRNet.py","file_ext":"py","file_size_in_byte":16159,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"81"} +{"seq_id":"39637961872","text":"# -*- coding:utf-8 -*-\n\nimport sys\nfrom PyQt5.QtWidgets import QWidget, QProgressBar, QPushButton, QApplication\nfrom PyQt5.QtCore import QBasicTimer\n\nclass progressBar(QWidget):\n\tdef __init__(self):\n\t\tsuper(progressBar, self).__init__()\n\t\tself.initUI()\n\n\tdef initUI(self):\n\n\t\tself.pbar = QProgressBar(self)\n\t\tself.pbar.setGeometry(30, 40, 200, 25)\n\n\t\tself.btn = QPushButton('Start', self)\n\t\tself.btn.move(40, 80)\n\t\tself.btn.clicked.connect(self.doAction)\n\n\t\tself.timer = QBasicTimer()\n\t\tself.step = 0\n\n\t\tself.setGeometry(300, 300, 280, 170)\n\t\tself.setWindowTitle('Progress Bar')\n\t\tself.show()\n\n\tdef timeEvent(self, e):\n\t\tif self.step >= 100:\n\t\t\tself.time.stop()\n\t\t\tself.btn.setText('Finished')\n\t\t\treturn\n\n\t\tself.step = self.step + 1\n\t\tself.pbar.setValue(self.step)\n\n\tdef doAction(self):\n\t\tif self.timer.isActive():\n\t\t\tself.timer.stop()\n\t\t\tself.btn.setText('Start')\n\t\telse:\n\t\t\tself.timer.start(100, self)\n\t\t\tself.btn.setText('Stop')\n\n\nif __name__ == \"__main__\":\n\tapp = QApplication(sys.argv)\n\tpb = progressBar()\n\tsys.exit(app.exec_())","repo_name":"halysl/python_module_study_code","sub_path":"src/pyqt-study/progress-bar.py","file_name":"progress-bar.py","file_ext":"py","file_size_in_byte":1033,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"4699550537","text":"mydict = {\n \"fast\": \"in a quick manner\",\n \"mohsin\": \"a coder\",\n \"marks\": [1,3,5,6],\n \"anotherdict\":{'this':'player'},\n 1:2\n}\n# print(mydict.keys()) #prints the keys of the dictiopnary\n# print(mydict.values()) #prints the values of dictionary\n# print(mydict.items()) prints the keys , values for all the contents of the dictionay\n\nupdatedict = {\n \"animals\" : \"Forests\",\n\n \"mohsin\" : \"blckhat\"\n}\n# mydict.update(updatedict) #updates the dictionary by adding key values or adding values and keys to the dict\n\n# mydict.update(updatedict)\n\n\nprint(mydict.get(\"mohsin\")) # as if any key isn't present in the dictionary it prevents the thrown of error it returns the none\n\n\nprint(mydict)\n\n\n","repo_name":"Mohsinparay/Learning-Python","sub_path":"chapter5/dicy_methods.py","file_name":"dicy_methods.py","file_ext":"py","file_size_in_byte":703,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"81"} +{"seq_id":"6232664927","text":"#######\n# This makes a 3x3 scatterplot of wheels.csv, and sends\n# the results of a selection to the screen as a JSON object.\n######\nimport dash\nimport dash_core_components as dcc\nimport dash_html_components as html\nfrom dash.dependencies import Input, Output\nimport plotly.graph_objs as go\nimport pandas as pd\nimport json\n\napp = dash.Dash()\n\ndf = pd.read_csv('../data/wheels.csv')\n\napp.layout = html.Div([\n html.Div([\n dcc.Graph(\n id='wheels-plot',\n figure={\n 'data': [\n go.Scatter(\n x = df['color'],\n y = df['wheels'],\n dy = 1,\n mode = 'markers',\n marker = {\n 'size': 12,\n 'color': 'rgb(51,204,153)',\n 'line': {'width': 2}\n }\n )\n ],\n 'layout': go.Layout(\n title = 'Wheels & Colors Scatterplot',\n xaxis = {'title': 'Color'},\n yaxis = {'title': '# of Wheels','nticks':3},\n hovermode='closest'\n )\n }\n )], style={'width':'30%', 'display':'inline-block'}),\n\n html.Div([\n html.Pre(id='selection', style={'paddingTop':25})\n ], style={'width':'30%', 'display':'inline-block', 'verticalAlign':'top'})\n])\n\n@app.callback(\n Output('selection', 'children'),\n [Input('wheels-plot', 'selectedData')])\ndef callback_image(selectedData):\n return json.dumps(selectedData, indent=2)\n\nif __name__ == '__main__':\n app.run_server()\n","repo_name":"Pierian-Data/Plotly-Dashboards-with-Dash","sub_path":"2-15-SelectedData/select1.py","file_name":"select1.py","file_ext":"py","file_size_in_byte":1582,"program_lang":"python","lang":"en","doc_type":"code","stars":822,"dataset":"github-code","pt":"81"} +{"seq_id":"1359245817","text":"\"\"\"\n.. codeauthor:: danhezee, StackOverflow, izzy, Danke, noway421, IAmYourFriend\n\nThe concept\n^^^^^^^^^^^\n\nEach team spawns at a set location with the enemy intel. They must \"push\"\nthe intel towards their control point, which is also at a set location.\nThe only way to arrive there is by building bridges over the deadly water.\nFurther introduction to the game mode: https://youtu.be/DdisPY6vDD0\n\n\nSetting Up New Maps\n^^^^^^^^^^^^^^^^^^^\n\nSpawn and CP locations must be configured via extensions in the map's\nmap_name.txt metadata:\n\n>>> extensions = {\n... 'push': True,\n... 'push_spawn_range' : 5,\n... 'push_blue_spawn' : (91, 276, 59),\n... 'push_blue_cp' : (91, 276, 59),\n... 'push_green_spawn' : (78, 86, 59),\n... 'push_green_cp' : (78, 86, 59),\n... 'water_damage' : 100\n... }\n\nAdditional (but optional) extensions, to mark each team's build area and prevent\nthe enemy from building there (and thereby helping the enemy). The build area\nis defined by x and y of upper left corner, followed by x and y of bottom right\ncorner on the map::\n\n 'push_blue_build_area' : (64, 100, 243, 500),\n 'push_green_build_area' : (268, 100, 447, 500),\n\nCommands\n^^^^^^^^\n\n* ``/r`` Quickly respawn to refill blocks and ammo (if enabled)\n* ``/resetintel `` Manually reset the blue or green team's intel\n\nOptions\n^^^^^^^\n\n.. code-block:: python\n\n [push]\n # Disallow removal of map blocks. This allows a larger variety of maps that\n # rely on more fragile structures. It also prevents griefing (like removing\n # the map blocks before and after your team's bridge).\n protect_map_blocks = true\n\n # Allow the usage of /r to quickly respawn. As players can't refill blocks at\n # their base, they would have to suicide otherwise. This is illogical, messes\n # up their kill-death ratio and gives them an undeserved punishing respawn time.\n allow_respawn_command = true\n\n # How long to wait to allow the command /r again\n respawn_cmd_delay = \"15sec\"\n\n # Players have to wait this amount after spawning before they can pick\n # the intel up. This is to reduce the instant/careless intel pickups.\n intel_pickup_delay = \"3sec\"\n\n # How long can you remove your own last blocks\n block_removal_delay = \"15sec\"\n\n # Reset intel after it was dropped somewhere\n reset_intel_after_drop = \"3min\"\n\n # No building near cp within this block range (can be overwritten using\n # map extension parameter \"push_cp_protect_range\")\n default_cp_protect_range = 8\n\n # Disable grenade damage within enemy spawn.\n disable_grenades_at_spawn = false\n\"\"\"\n\nfrom pyspades.constants import *\nfrom pyspades.common import make_color\nfrom pyspades.contained import SetColor\nfrom piqueserver.commands import command, admin, get_team\nfrom piqueserver.config import config, cast_duration\nfrom twisted.internet.task import LoopingCall\nfrom random import randint\nimport colorsys\nimport time\n\nPUSH_CONFIG = config.section(\"push\")\nPROTECT_MAP_BLOCKS = PUSH_CONFIG.option(\n \"protect_map_blocks\", default=True, cast=bool)\nALLOW_RESPAWN_COMMAND = PUSH_CONFIG.option(\n \"allow_respawn_command\", default=True, cast=bool)\nRESPAWN_CMD_DELAY = PUSH_CONFIG.option(\n \"respawn_cmd_delay\", default=\"15sec\", cast=cast_duration)\nINTEL_PICKUP_DELAY = PUSH_CONFIG.option(\n \"intel_pickup_delay\", default=\"3sec\", cast=cast_duration)\nBLOCK_REMOVAL_DELAY = PUSH_CONFIG.option(\"block_removal_delay\", default=\"15sec\",\n cast=cast_duration)\nRESET_INTEL_AFTER_DROP = PUSH_CONFIG.option(\"reset_intel_after_drop\", default=\"3min\",\n cast=cast_duration)\nDEFAULT_CP_PROTECT_RANGE = PUSH_CONFIG.option(\n \"default_cp_protect_range\", default=8, cast=int)\nDISABLE_GRENADES_AT_SPAWN = PUSH_CONFIG.option(\"disable_grenades_at_spawn\", default=False,\n cast=bool)\n\nCANT_DESTROY = \"You can't destroy your team's blocks!\"\nNO_BLOCKS = \"Out of blocks! Refill at base or type /r\"\nBUILDING_AT_CP = \"You can't build near your base!\"\nBUILDING_AT_ENEMY_AREA = \"Don't build for your enemy!\"\n\n\ndef get_now_in_secs():\n return int(time.time())\n\n\ndef byte_rgb_to_hls(rgb):\n hls = colorsys.rgb_to_hls(*tuple(c / 255.0 for c in rgb))\n return tuple(int(round(c * 255)) for c in hls)\n\n\ndef byte_hls_to_rgb(hls):\n rgb = colorsys.hls_to_rgb(*tuple(c / 255.0 for c in hls))\n return tuple(int(round(c * 255)) for c in rgb)\n\n\ndef compare_hs(block_hls, team_hls):\n # if hue and saturation match\n return block_hls[0] == team_hls[0] and block_hls[2] == team_hls[2]\n\n\ndef byte_middle_range(byte):\n half = 50 / 2.0 # half of (byte/5.1)\n min = byte - half\n max = byte + half\n if min < 0:\n min = 0\n max = half\n elif max > 255:\n min = 255 - half\n max = 255\n return int(round(min)), int(round(max))\n\n\ndef create_area(x, y, block_range):\n return (x - block_range, y - block_range, x + block_range, y + block_range)\n\n\ndef is_in_area(x, y, top_x, top_y, bottom_x, bottom_y):\n return top_x <= x < bottom_x and top_y <= y < bottom_y\n\n\ndef has_flag(connection):\n flag = connection.team.other.flag\n if flag.player is not None:\n if flag.player is connection:\n return True\n return False\n\n\ndef reset_intel_position(protocol, team):\n # Flag should always spawn on z-top to prevent griefers burying it under blocks\n pos = (team.other.spawn[0],\n team.other.spawn[1],\n protocol.map.get_z(team.other.spawn[0], team.other.spawn[1], 1))\n team.flag.set(*pos) # If spawn not set, it would throw error.\n team.flag.update()\n protocol.broadcast_chat(\"The %s intel has been reset.\" % team.name)\n\n\n@command(admin_only=True)\ndef resetintel(connection, value):\n \"\"\"\n Manually reset the blue or green team's intel\n /resetintel \n \"\"\"\n team = get_team(connection, value)\n reset_intel_position(connection.protocol, team)\n\n\n@command('r')\ndef respawn(connection):\n \"\"\"\n Quickly respawn to refill blocks and ammo\n /r\n \"\"\"\n if not ALLOW_RESPAWN_COMMAND.get():\n return \"Command is disabled\"\n if connection.world_object is not None and not connection.world_object.dead:\n if (connection.last_spawn_time is None or connection.last_spawn_time +\n RESPAWN_CMD_DELAY.get() <= get_now_in_secs()):\n if has_flag(connection):\n connection.drop_flag()\n connection.spawn()\n else:\n connection.send_chat(\n \"Please wait %s seconds before using this command again.\"\n % (connection.last_spawn_time + RESPAWN_CMD_DELAY.get() - get_now_in_secs()))\n\n\ndef get_entity_location(connection, entity_id):\n if entity_id == BLUE_BASE:\n return connection.protocol.blue_team.cp\n elif entity_id == GREEN_BASE:\n return connection.protocol.green_team.cp\n\n elif entity_id == BLUE_FLAG:\n return (connection.protocol.green_team.spawn[0],\n connection.protocol.green_team.spawn[1],\n 1)\n elif entity_id == GREEN_FLAG:\n return (connection.protocol.blue_team.spawn[0],\n connection.protocol.blue_team.spawn[1],\n 1)\n\n\ndef get_spawn_location(connection):\n # distance from spawn center to randomly spawn in\n spawn_range = connection.protocol.spawn_range\n xb = connection.team.spawn[0]\n yb = connection.team.spawn[1]\n xb += randint(-spawn_range, spawn_range)\n yb += randint(-spawn_range, spawn_range)\n return (xb, yb, connection.protocol.map.get_z(xb, yb))\n\n\ndef apply_script(protocol, connection, config):\n class PushConnection(connection):\n last_spawn_time = None\n # list entry format: ((x, y, z), timestamp when block was placed)\n last_blocks = None\n\n def is_in_invalid_area(self, x, y, check_area, error_message):\n if is_in_area(x, y, *check_area):\n self.send_chat(error_message)\n return True\n else:\n return False\n\n def invalid_build_position(self, x, y, z):\n # prevent teams from building near their cp\n if self.is_in_invalid_area(x, y, create_area(self.team.cp[0], self.team.cp[1],\n self.protocol.cp_protect_range), BUILDING_AT_CP):\n return True\n # prevent teams from building in enemy build area\n if self.team.build_area is not None and self.is_in_invalid_area(\n x, y, self.team.other.build_area, BUILDING_AT_ENEMY_AREA):\n return True\n return False\n\n def random_color(self):\n (h, l, s) = self.team.hls\n l = randint(self.team.light_range[0], self.team.light_range[1])\n color = byte_hls_to_rgb((h, l, s))\n\n self.color = color\n set_color = SetColor()\n set_color.player_id = self.player_id\n set_color.value = make_color(*color)\n self.send_contained(set_color)\n self.protocol.broadcast_contained(set_color, save=True)\n\n def on_line_build_attempt(self, points):\n can_build = connection.on_line_build_attempt(self, points)\n if can_build is False:\n return False\n\n if ALLOW_RESPAWN_COMMAND.get() and self.blocks == len(points):\n self.send_chat(NO_BLOCKS)\n\n for point in points:\n if self.invalid_build_position(*point):\n return False\n\n if self.last_blocks is None:\n self.last_blocks = []\n if BLOCK_REMOVAL_DELAY.get() > 0:\n for point in points:\n x, y, z = point[0], point[1], point[2]\n if not self.protocol.map.get_solid(x, y, z):\n self.last_blocks.append(((x, y, z), get_now_in_secs()))\n\n self.random_color()\n return can_build\n\n def on_block_build_attempt(self, x, y, z):\n can_build = connection.on_block_build_attempt(self, x, y, z)\n if can_build is False:\n return False\n\n if ALLOW_RESPAWN_COMMAND.get() and self.blocks == 0:\n self.send_chat(NO_BLOCKS)\n\n if self.invalid_build_position(x, y, z):\n return False\n\n if self.last_blocks is None:\n self.last_blocks = []\n if BLOCK_REMOVAL_DELAY.get() > 0:\n self.last_blocks.append(((x, y, z), get_now_in_secs()))\n\n self.random_color()\n return can_build\n\n def on_block_destroy(self, x, y, z, value):\n is_trusted = (self.admin or self.god or self.user_types.moderator or\n self.user_types.guard or self.user_types.trusted)\n if value == DESTROY_BLOCK:\n blocks = ((x, y, z),)\n elif value == SPADE_DESTROY:\n blocks = ((x, y, z), (x, y, z + 1), (x, y, z - 1))\n elif value == GRENADE_DESTROY:\n blocks = []\n for nade_x in range(x - 1, x + 2):\n for nade_y in range(y - 1, y + 2):\n for nade_z in range(z - 1, z + 2):\n blocks.append((nade_x, nade_y, nade_z))\n\n for block in blocks:\n is_last_block_removal = False\n if self.last_blocks is not None and not is_trusted:\n for last in self.last_blocks:\n if block == last[0]:\n if last[1] + BLOCK_REMOVAL_DELAY.get() < get_now_in_secs():\n self.last_blocks.remove(last)\n return False\n self.last_blocks.remove(last)\n is_last_block_removal = True\n break\n if is_last_block_removal:\n continue\n\n block_info = self.protocol.map.get_point(*block)\n if block_info[0] is True:\n block_hls = byte_rgb_to_hls(block_info[1])\n is_blue_block = compare_hs(\n block_hls, self.protocol.blue_team.hls)\n is_green_block = compare_hs(\n block_hls, self.protocol.green_team.hls)\n is_team_block = ((self.team is self.protocol.blue_team and is_blue_block) or\n (self.team is self.protocol.green_team and is_green_block))\n if is_team_block and not is_trusted:\n self.send_chat(CANT_DESTROY)\n return False\n if PROTECT_MAP_BLOCKS.get() and not is_blue_block and not is_green_block:\n return False\n return connection.on_block_destroy(self, x, y, z, value)\n\n def on_flag_take(self):\n if self.last_spawn_time + INTEL_PICKUP_DELAY.get() > get_now_in_secs():\n return False\n return connection.on_flag_take(self)\n\n def on_spawn(self, pos):\n self.last_spawn_time = get_now_in_secs()\n self.last_blocks = None\n return connection.on_spawn(self, pos)\n\n def grenade_exploded(self, grenade):\n if DISABLE_GRENADES_AT_SPAWN.get():\n if not (self is None or self.name is None or\n self.team is None or self.team.other is None):\n grenade_x = int(grenade.position.x)\n grenade_y = int(grenade.position.y)\n spawn_x = self.team.other.spawn[0]\n spawn_y = self.team.other.spawn[1]\n spawn_range = self.protocol.spawn_range + 8\n if is_in_area(grenade_x, grenade_y,\n spawn_x - spawn_range, spawn_y - spawn_range,\n spawn_x + spawn_range, spawn_y + spawn_range):\n return False\n return connection.grenade_exploded(self, grenade)\n\n class PushProtocol(protocol):\n game_mode = CTF_MODE\n spawn_range = 0\n cp_protect_range = 0\n check_loop = None\n reset_intel_blue_timer = 0\n reset_intel_green_timer = 0\n\n def __init__(self, *arg, **kw):\n protocol.__init__(self, *arg, **kw)\n self.blue_team.hls = byte_rgb_to_hls(self.blue_team.color)\n self.blue_team.light_range = byte_middle_range(\n self.blue_team.hls[1])\n\n self.green_team.hls = byte_rgb_to_hls(self.green_team.color)\n self.green_team.light_range = byte_middle_range(\n self.green_team.hls[1])\n\n def check_intel_location(self, team, timer_val):\n if team.flag is not None:\n if team.flag.get()[2] >= 63:\n reset_intel_position(self, team)\n return 0\n elif team.flag.player is None:\n timer_val += 1\n if timer_val >= RESET_INTEL_AFTER_DROP.get() / self.check_loop.interval:\n reset_intel_position(self, team)\n return 0\n return timer_val\n else:\n return 0\n return timer_val\n\n def check_intel_locations(self):\n self.reset_intel_blue_timer = self.check_intel_location(\n self.blue_team, self.reset_intel_blue_timer)\n self.reset_intel_green_timer = self.check_intel_location(\n self.green_team, self.reset_intel_green_timer)\n\n def on_map_change(self, map):\n extensions = self.map_info.extensions\n for must_have in ('push_blue_spawn', 'push_green_spawn',\n 'push_blue_cp', 'push_green_cp'):\n if must_have not in extensions:\n raise Exception(\n \"Missing push map metadata: %s\" % must_have)\n\n extensions['water_damage'] = 100\n # distance from spawn center to randomly spawn in\n self.spawn_range = extensions.get('push_spawn_range', 5)\n # distance from cp where building is not allowed\n self.cp_protect_range = extensions.get('push_cp_protect_range',\n DEFAULT_CP_PROTECT_RANGE.get())\n\n self.blue_team.spawn = extensions.get('push_blue_spawn')\n self.blue_team.cp = extensions.get('push_blue_cp')\n self.blue_team.build_area = extensions.get('push_blue_build_area')\n\n self.green_team.spawn = extensions.get('push_green_spawn')\n self.green_team.cp = extensions.get('push_green_cp')\n self.green_team.build_area = extensions.get(\n 'push_green_build_area')\n\n self.map_info.get_entity_location = get_entity_location\n self.map_info.get_spawn_location = get_spawn_location\n\n if self.check_loop is not None:\n self.check_loop.stop()\n self.reset_intel_blue_timer = 0\n self.reset_intel_green_timer = 0\n self.check_loop = LoopingCall(self.check_intel_locations)\n self.check_loop.start(3, now=False)\n\n return protocol.on_map_change(self, map)\n\n return PushProtocol, PushConnection\n","repo_name":"piqueserver/piqueserver","sub_path":"piqueserver/game_modes/push.py","file_name":"push.py","file_ext":"py","file_size_in_byte":17400,"program_lang":"python","lang":"en","doc_type":"code","stars":182,"dataset":"github-code","pt":"81"} +{"seq_id":"35862232227","text":"from aoc.y2021.day13 import clean_input, fold_origami\nfrom aocd.models import Puzzle\n\ntest_data = \"\"\"6,10\n0,14\n9,10\n0,3\n10,4\n4,11\n6,0\n6,12\n4,1\n0,13\n10,12\n3,4\n3,0\n8,4\n1,10\n2,14\n8,10\n9,0\n\nfold along y=7\nfold along x=5\"\"\"\n\n\ntest_data = clean_input(test_data)\nactual_input = clean_input(Puzzle(2021, 13).input_data)\n\n\ndef test_clean_input():\n assert test_data[1] == [(\"y\", 7), (\"x\", 5)]\n assert test_data[0][0, 0] == 0\n assert test_data[0][10, 6] == 1\n assert actual_input[1][:2] == [(\"x\", 655), (\"y\", 447)]\n assert actual_input[0][257, 47] == 1\n assert actual_input[0][257, 0] == 0\n\n\ndef test_fold_origamin():\n assert fold_origami(*test_data) == 17\n assert fold_origami(*actual_input) == 775\n","repo_name":"MarcusRisanger/aoc","sub_path":"tests/y2021/test_day13.py","file_name":"test_day13.py","file_ext":"py","file_size_in_byte":713,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"8562775211","text":"\"\"\"\n Робота з try-except-else-finally, перехоплення і обробка помилок.\n\n 1.Створити функцію, що приймає число з консолі (використати фунцію input());\n Функція повинна обробити значення таким чином:\n використовуючи вбудовану функцію int() спробувати конвертувати рядок в число (input() завжди повертає рядок).\n Якщо конвертувати не виходить, то вивести в консоль \"Entered not valid data\".\n\n 2. Створити функцію, що приймає 2 рядки;\n Якщо хоча б один рядок не виходить конвертувати в число, тоді робимо конкатенацію (з'єднуємо рядки),\n якщо ж обидва значення можна конвертувати в числа, то отримуємо їх суму. Результат друкуємо в консоль.\n\n 3. Створити функцію, що приймає значення з консолі. Якщо значення не можна привести до числа,\n тоді просимо користувача ввести інше значення, доки він не введе число. Згадуємо про цикл while.\n Коли користувач вводить число, дякуємо йому )\n\n 4. Створити власне виключення. Наприклад OnlyEvenError. Створити функцію check_digit(), яка приймає число.\n Якщо число не парне, то породжувати це своє виключення, якщо парне, то повертати його (return)\n\n 5. Створити функцію, що буде приймати число як аргумент і викликАти в тілі функцію check_digit,\n в яку передавати це число.\n\n Якщо виникає помилка, то перехопити її, та збільшити вхідне число на 1. Інакше, помножити число на 2.\n Результат виводити в консоль.\n Також функція повинна надрукувати в консоль \"Я все одно завжди щось друкую\".\n Використовувати try-except-else-finally\n\n\"\"\"\n\n\ndef number_from_console():\n try:\n my_number = input('Enter a number: ')\n number_int = int(my_number)\n except ValueError:\n print(f'Entered not valid data.')\n else:\n print(f'{number_int} is an integer')\n finally:\n print('Operation is finished')\n\n\ndef two_strings_from_console():\n line1 = input('Enter first line: ')\n line2 = input('Enter second line: ')\n try:\n line1_int = int(line1)\n line2_int = int(line2)\n except ValueError:\n print(line1 + line2)\n else:\n print(line1_int + line2_int)\n finally:\n print('Operation is finished')\n\n\ndef data_from_console():\n while True:\n try:\n my_data = input('Enter a number: : ')\n my_data = int(my_data)\n print(f'{my_data} is an integer. Thank you.')\n break\n except ValueError:\n print(\"That isn`t s valid number. Try again.\")\n\n\nclass OnlyEvenError(Exception):\n \"\"\"Raised when the input value is not even\"\"\"\n pass\n\n\ndef check_digit(digit: int):\n if digit % 2 == 0:\n return digit\n else:\n raise OnlyEvenError(f'The number {digit} is not even')\n\n\ndef check_a_number(number: int):\n try:\n check_digit(number)\n except OnlyEvenError:\n print(number + 1)\n else:\n print(number * 2)\n finally:\n print('Я все одно завжди щось друкую')\n\n","repo_name":"MarynaVl/qalight","sub_path":"homework_collection/hw9_exceptions.py","file_name":"hw9_exceptions.py","file_ext":"py","file_size_in_byte":3974,"program_lang":"python","lang":"uk","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"20051724860","text":"def BubbleSort(a, N): # 정렬할 list, N 원소 수\n for i in range(N-1, 0, -1): # 범위의 끝 위치\n for j in range(0, i):\n if a[j] > a[j+1]:\n a[j], a[j+1] = a[j+1], a[j]\n\n return a\n\nN, M = map(int, input().split())\narr = list(map(int, input().split()))\nresl = []\nfor i in range(N-M-1):\n res = 0\n for j in range(M):\n res += arr[i+j]\n resl.append(res)\n \nsortres = BubbleSort(resl, len(resl))\n\nprint(sortres[-1] - sortres[0])\n \n \n \n \n ","repo_name":"junchicode/TIL","sub_path":"Algo_week_SWEA&Class/week1/0809/4835.py","file_name":"4835.py","file_ext":"py","file_size_in_byte":523,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"1322212413","text":"a,b=eval(input('input x and y\\n'))\nl = []\nfor n in range(a,b+1):\n for i in range(2,n):\n if n % i == 0:\n break\n else:\n l.append(n)\nprint(l)\n\n","repo_name":"huangpintian123/python-","sub_path":"所有素数.py","file_name":"所有素数.py","file_ext":"py","file_size_in_byte":171,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"2312014143","text":"from django.contrib.auth import get_user_model\nfrom django.test import TestCase, Client\n\nfrom ..models import Group, Post\n\nUser = get_user_model()\n\n\nclass StaticURLTests(TestCase): # Smoke testing\n def test_homepage(self):\n guest_client = Client()\n response = guest_client.get('/')\n self.assertEqual(response.status_code, 200)\n\n\nclass PostURLTests(TestCase):\n @classmethod\n def setUpClass(cls):\n super().setUpClass()\n cls.user = User.objects.create_user(username='NoName')\n cls.author = User.objects.create_user(username='PostAuthor')\n cls.group = Group.objects.create(\n title='Тестовая группа',\n slug='test-group-slug',\n description='Тестовое описание',\n )\n cls.post = Post.objects.create(\n author=cls.author,\n text='Тестовый пост',\n )\n\n def setUp(self):\n self.guest_client = Client()\n self.authorized_client = Client()\n self.authorized_client.force_login(PostURLTests.user)\n self.post_author_client = Client()\n self.post_author_client.force_login(PostURLTests.author)\n\n def test_pages_urls_exist_for_guests(self):\n \"\"\"Тестируем страницы, доступные любому пользователю.\"\"\"\n pages = {\n 'index': '/',\n 'group_list': f'/group/{PostURLTests.group.slug}/',\n 'profile': f'/profile/{PostURLTests.user.username}/',\n 'post_detail': f'/posts/{PostURLTests.post.id}/'\n }\n for page, url in pages.items():\n with self.subTest(page=page):\n response = self.guest_client.get(url)\n self.assertEqual(response.status_code, 200)\n\n def test_pages_urls_exist_for_authorized_users(self):\n \"\"\"Тестируем страницы, доступные авторизованному пользователю.\"\"\"\n pages = {\n 'index': '/',\n 'group_list': f'/group/{PostURLTests.group.slug}/',\n 'profile': f'/profile/{PostURLTests.user.username}/',\n 'post_detail': f'/posts/{PostURLTests.post.id}/',\n 'post_create': '/create/',\n }\n for page, url in pages.items():\n with self.subTest(page=page):\n response = self.authorized_client.get(url)\n self.assertEqual(response.status_code, 200)\n\n def test_post_edit_url_works_for_post_author_only(self):\n \"\"\"Проверяем, что страница post_edit доступна только автору поста.\"\"\"\n url = f'/posts/{PostURLTests.post.id}/edit/'\n just_user = self.authorized_client\n author = self.post_author_client\n\n requests = {\n just_user: url.replace('edit/', ''),\n author: url\n }\n for client, result in requests.items():\n with self.subTest(client=client):\n response = client.get(url)\n if client is not author:\n self.assertRedirects(response, result)\n else:\n self.assertEqual(response.status_code, 200)\n\n def test_post_create_redirect_anonymous(self):\n \"\"\"Тестируем перенаправление анонимного пользователя\n при создании нового поста.\"\"\"\n response = self.guest_client.get('/create/', follow=True)\n self.assertRedirects(response, ('/auth/login/?next=/create/'))\n\n def test_post_edit_url_redirect_anonymous(self):\n \"\"\"Тестируем перенаправление анонимного пользователя\n при попытке редактирования поста.\"\"\"\n response = self.guest_client.get(\n f'/posts/{PostURLTests.post.id}/edit/', follow=True)\n self.assertRedirects(\n response,\n (f'/auth/login/?next=/posts/{PostURLTests.post.id}/edit/'))\n\n def test_post_comment_url_redirect_anonymous(self):\n \"\"\"Тестируем перенаправление анонимного пользователя\n при попытке оставить комментарий.\"\"\"\n response = self.guest_client.get(\n f'/posts/{PostURLTests.post.id}/comment/', follow=True)\n self.assertRedirects(\n response,\n (f'/auth/login/?next=/posts/{PostURLTests.post.id}/comment/'))\n\n def test_page_not_exists(self):\n '''Проверяем ошибку 404 для несуществующей страницы'''\n response = self.guest_client.get('/unexisting-page/')\n self.assertEqual(response.status_code, 404)\n\n def test_urls_uses_correct_template(self):\n \"\"\"URL-адрес использует соответствующий шаблон.\"\"\"\n templates_url_names = {\n '/': 'posts/index.html',\n f'/group/{PostURLTests.group.slug}/': 'posts/group_list.html',\n f'/profile/{PostURLTests.user.username}/': 'posts/profile.html',\n f'/posts/{PostURLTests.post.id}/': 'posts/post_detail.html',\n '/create/': 'posts/create_post.html',\n f'/posts/{PostURLTests.post.id}/edit/': 'posts/create_post.html'\n }\n for address, template in templates_url_names.items():\n with self.subTest(address=address):\n response = self.post_author_client.get(address)\n self.assertTemplateUsed(response, template)\n","repo_name":"AlDrPy/yatube_web_project","sub_path":"yatube/posts/tests/test_urls.py","file_name":"test_urls.py","file_ext":"py","file_size_in_byte":5565,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"36423955336","text":"import matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nfrom pylab import rcParams\nimport os\n\nrcParams['figure.figsize'] = 10, 5\nrcParams['font.family'] = 'serif'\nrcParams['font.size'] = 15\n\n# Get all stream runs\nstream = []\nfor fn in os.listdir('./stream_runs/'):\n if fn.endswith('.out'):\n n = fn[:-4]\n with open('./stream_runs/' + fn, \"r\") as myfile:\n data = myfile.readlines()\n bandwidth = data[-7].split()[1]\n if bandwidth != 'inf':\n bandwidth = float(bandwidth)\n stream.append([n, bandwidth])\n\nstream = np.asarray(stream, np.float)\nstream.sort(axis=0)\nstream = stream.T\n\n# ----------------------------------- GCC -------------------------------------\no1 = np.loadtxt('./gcc_o1.dat', delimiter=',')\ndf = pd.DataFrame(o1, columns=['N', 'R', 'elapsed_time', 'MB/s'])\no1 = df.groupby('N').mean().reset_index()\n\no3 = np.loadtxt('./gcc_o3.dat', delimiter=',')\ndf = pd.DataFrame(o3, columns=['N', 'R', 'elapsed_time', 'MB/s'])\no3 = df.groupby('N').mean().reset_index()\n\no3_native = np.loadtxt('./gcc_o3_native.dat', delimiter=',')\ndf = pd.DataFrame(o3_native, columns=['N', 'R', 'elapsed_time', 'MB/s'])\no3_native = df.groupby('N').mean().reset_index()\n\n\nplt.semilogx(o1['N'], o1['MB/s'], label='-O1')\nplt.semilogx(o3['N'], o3['MB/s'], label='-O3')\nplt.semilogx(o3_native['N'], o3_native['MB/s'], label='-O3 -march=native')\nplt.semilogx(stream[0], stream[1], label='STREAM')\nplt.ylabel('MB/s')\nplt.xlabel(r'$N$')\nplt.legend()\n# plt.show()\nplt.savefig('gcc.pdf')\nplt.clf()\n\n# ---------------------------------- Intel ------------------------------------\no1 = np.loadtxt('./intel_o1.dat', delimiter=',')\ndf = pd.DataFrame(o1, columns=['N', 'R', 'elapsed_time', 'MB/s'])\no1 = df.groupby('N').mean().reset_index()\n\no3 = np.loadtxt('./intel_o3.dat', delimiter=',')\ndf = pd.DataFrame(o3, columns=['N', 'R', 'elapsed_time', 'MB/s'])\no3 = df.groupby('N').mean().reset_index()\n\no3_avx = np.loadtxt('./intel_o3_AVX.dat', delimiter=',')\ndf = pd.DataFrame(o3_avx, columns=['N', 'R', 'elapsed_time', 'MB/s'])\no3_avx = df.groupby('N').mean().reset_index()\n\nfast = np.loadtxt('./intel_fast.dat', delimiter=',')\ndf = pd.DataFrame(fast, columns=['N', 'R', 'elapsed_time', 'MB/s'])\nfast = df.groupby('N').mean().reset_index()\n\nplt.semilogx(o1['N'], o1['MB/s'], label='-O1')\nplt.semilogx(o3['N'], o3['MB/s'], label='-O3')\nplt.semilogx(o3_avx['N'], o3_avx['MB/s'], label='-O3 -xAVX')\nplt.semilogx(fast['N'], fast['MB/s'], label='-fast')\nplt.semilogx(stream[0], stream[1], label='STREAM')\nplt.ylabel('MB/s')\nplt.xlabel(r'$N$')\nplt.legend()\n# plt.show()\nplt.savefig('icc.pdf')\nplt.clf()\n","repo_name":"AlexHarn/parallel-computing-homework","sub_path":"homework/3/plot/2/2.py","file_name":"2.py","file_ext":"py","file_size_in_byte":2642,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"74449974345","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Dec 27 11:16:17 2017\r\n\r\n@author: Lenovo\r\n\"\"\"\r\n\r\nimport xlrd\r\nimport xlwt\r\n\r\nfrom openpyxl import Workbook\r\nfrom openpyxl import load_workbook\r\nimport openpyxl\r\n\r\n\r\ndef read_excel():\r\n # 打开文件\r\n workbook = xlrd.open_workbook('C:/Users/Lenovo/Desktop/temp/score1.xlsx')\r\n # 获取所有的sheet\r\n print(workbook.sheet_names())\r\n # 根据sheet索引或者名称获取sheet内容\r\n # sheet2=workbook.sheet_by_index(1)\r\n sheet2 = workbook.sheet_by_name('Sheet2')\r\n\r\n # sheet的名称,行数,列数\r\n print('Sheet名称:', sheet2.name, ' 行数:', sheet2.nrows, ' 列数:', sheet2.ncols)\r\n\r\n # 获取整行和整列的值(数组)、\r\n rows = sheet2.row_values(3) # 获取第四行内容\r\n cols = sheet2.col_values(2) # 获取第三列的内容\r\n print(rows)\r\n print(cols)\r\n\r\n # 获取单元格内容\r\n print(sheet2.cell(1, 0).value, sheet2.cell(1, 0).value.encode('utf-8'))\r\n # 获取单元格的数据类型\r\n # ctype : 0 empty,1 string, 2 number, 3 date, 4 boolean, 5 error\r\n print(sheet2.cell(1, 0).ctype, sheet2.cell(1, 1).ctype)\r\n\r\n\r\ndef merge_sheet():\r\n # 打开文件\r\n writebook = xlwt.Workbook('C:/Users/Lenovo/Desktop/temp/score1.xlsx')\r\n readbook = xlrd.open_workbook('C:/Users/Lenovo/Desktop/temp/score1.xlsx')\r\n\r\n # 得到每个sheet\r\n sheet1 = readbook.sheet_by_name('Sheet1')\r\n sheet2 = readbook.sheet_by_name('Sheet2')\r\n\r\n sheet3 = writebook.add_sheet('Sheet3')\r\n\r\n # 得到两个表格的第一列\r\n sheet1_rows1 = sheet1.row_values(0)\r\n sheet2_rows2 = sheet2.row_values(0)\r\n\r\n '''\r\n i=1\r\n while i< sheet1.nrows:\r\n value=sheet1_row1[i]\r\n if sheet2_rows2(value):\r\n for j in \r\n '''\r\n\r\n\r\ndef openpyxl_read():\r\n # 新建excel\r\n wb2 = openpyxl.Workbook()\r\n wb2.save('C:/Users/Lenovo/Desktop/temp/test.xlsx')\r\n print('新建成功')\r\n # 读取数据\r\n wb1 = openpyxl.load_workbook('C:/Users/Lenovo/Desktop/temp/score1.xlsx')\r\n wb2=openpyxl.load_workbook('C:/Users/Lenovo/Desktop/temp/test.xlsx')\r\n sheets1 = wb1.get_sheet_names() # ['Sheet1', 'Sheet2']\r\n sheets2 = wb2.get_sheet_names()\r\n # print('读取的excel中的sheet:',sheets1)\r\n\r\n\r\n sheet1 = wb1.get_sheet_by_name(sheets1[0]) # 读取sheet1\r\n sheet2=wb2.get_sheet_by_name(sheets2[0])\r\n max_row = sheet1.max_row\r\n max_column = sheet1.max_column\r\n print('max_row', max_row,'max_column',max_column)\r\n\r\n\r\n for m in range(1,max_row+1):\r\n for n in range(97,97+max_column):\r\n n=chr(n)\r\n i='%s%d'%(n,m)#单元格编号\r\n cell=sheet1[i].value\r\n sheet2[i].value=cell\r\n wb2.save('C:/Users/Lenovo/Desktop/temp/test.xlsx')\r\n wb1.close()\r\n wb2.close()\r\n\r\n\r\n\r\n\r\nif __name__ == '__main__':\r\n # read_excel()\r\n # merge_sheet()\r\n openpyxl_read()\r\n","repo_name":"lihow/PythonL","sub_path":"excel处理/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":2905,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"72343293386","text":"import pyautogui\nimport time\n\n# repetir 10 vezes\nfor i in range(10):\n # tempo de espera antes de começar a digitar\n time.sleep(5)\n\n # gerar a mensagem aleatória\n message = \"Testando\" + str(i+1)\n\n # digitar a mensagem\n pyautogui.typewrite(message)\n\n # pressionar a tecla Enter para enviar a mensagem\n pyautogui.hotkey('ctrl', 'enter')\n","repo_name":"danzinho007/Xadrez","sub_path":"Prank04.py","file_name":"Prank04.py","file_ext":"py","file_size_in_byte":360,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"22021528384","text":"from flask import Flask, request\n\nfrom titanic_utils.str_utils import extract_titles\n\napp = Flask(__name__)\n\n\n@app.route(\"/\")\ndef hello():\n # name = request.args[\"name\"] # Too strict, fails if ?name= is not passed\n # if \"name\" in request.args\n print(\"Parameters: \", request.args)\n name = request.args.get(\"name\")\n greeting = request.args.get(\"greeting\", \"Hello\")\n if name is not None:\n return f\"{greeting}, {name}!\"\n else:\n return \"Hello, stranger\"\n\n\n@app.route(\"/extract_titles\")\ndef extract_titles_endpoint():\n return extract_titles(request.args[\"name\"])","repo_name":"aaayala92/test-ie-titanic","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":595,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"10047652522","text":"\"\"\"Watch a running SageMaker job.\"\"\"\nimport asyncio\nfrom functools import partial\nfrom typing import Any, Callable, Dict, List, Optional, Tuple\nimport logging\nimport os\nimport threading\n\nimport pandas as pd\n\nfrom .job import JobStatus, SageMakerJob, BaseJob\nfrom ..exceptions import SageMakerNotAvailableException, JobNotFoundException, DeferredImportException\n\ntry:\n # Just in case we make boto3 dependency optional\n import boto3\nexcept ImportError as ex:\n boto3 = DeferredImportException(ex)\n\ntry:\n # Sagemaker Python SDK is optional\n import sagemaker\nexcept ImportError as ex:\n sagemaker = DeferredImportException(ex)\n\n\nLOGGER = logging.getLogger(__name__)\n\n# Do not expose anything by default (internal module)\n__all__ = [] # type: List[str]\n\n\nclass SageMakerHelper:\n SAGEMAKER_STATUS_TO_JOB_STATUS = {\n \"InProgress\": JobStatus.RUNNING,\n \"Completed\": JobStatus.FINISHED,\n \"Failed\": JobStatus.FAILED,\n \"Stopping\": JobStatus.RUNNING, # TODO Create status for this?\n \"Stopped\": JobStatus.CANCELLED_BY_USER\n }\n\n def __init__(self, client=None, sagemaker_session=None):\n \"\"\"\n Init SageMaker helper in the disabled state.\n :param client: SageMaker client built with boto3.client(\"sagemaker\") used for low-level connections to SM API\n :param sagemaker_session: SageMaker Python SDK session\n \"\"\"\n self.client = client\n self.connection_tried = False\n self.connection_succeeded = False\n self._error_message = None # type: Optional[str]\n self.sagemaker_session = sagemaker_session\n self.lock = threading.Lock()\n self.analytics_by_job_name = {} # type: Dict[str, sagemaker.analytics.TrainingJobAnalytics]\n\n @property\n def __has_client(self):\n return self.client is not None\n\n def check_or_build_connection(self):\n \"\"\"\n Check that SageMaker connection exists. Tries to create if not yet attempted.\n ALWAYS call this before attempting to access SageMaker.\n :raises SageMakerNotAvailableException: If connection to SageMaker cannot be established.\n :return:\n \"\"\"\n if self.connection_tried:\n if self.connection_succeeded:\n return\n if not self.connection_succeeded:\n raise SageMakerNotAvailableException(message=self._error_message or None)\n\n self.connection_tried = True\n\n self.client = self.client or SageMakerHelper.build_client_or_none()\n\n if not self.client:\n self._error_message = \"Could not create boto client. Check your credentials\"\n raise SageMakerNotAvailableException(self._error_message)\n\n self.sagemaker_session = self.sagemaker_session or sagemaker.session.Session(sagemaker_client=self.client)\n\n try:\n self.client.list_training_jobs()\n LOGGER.info(\"SageMaker client successfully verified.\")\n except Exception: # pylint:disable=broad-except\n LOGGER.exception(\"Could not verify SageMaker connection\")\n self._error_message = \"Could not connect to SageMaker. Check your authorization.\"\n raise SageMakerNotAvailableException(self._error_message)\n\n self.connection_succeeded = True\n\n @staticmethod\n def build_client_or_none():\n \"\"\"\n :return: SageMaker boto3 client or None if failed\n \"\"\"\n try:\n return boto3.client(\"sagemaker\")\n except Exception: # pylint: disable=broad-except\n return None\n\n def get_job_status(self, job_name) -> JobStatus:\n \"\"\"\n Get job status from SageMaker API. Use this to start monitoring jobs and to check they exist.\n :param job_name: Name of the SageMaker training job\n :raises SageMakerNotAvailableException:\n :raises JobNotFoundException: If job was not found.\n :return: Job status\n \"\"\"\n with self.lock:\n self.check_or_build_connection()\n\n try:\n training_job = self.client.describe_training_job(TrainingJobName=job_name)\n except self.client.exceptions.ClientError:\n raise JobNotFoundException\n\n status = training_job['TrainingJobStatus']\n return SageMakerHelper.SAGEMAKER_STATUS_TO_JOB_STATUS[status]\n\n def wait_for_job_finish(self, job_name: str) -> JobStatus:\n \"\"\"\n Wait for SageMaker job to finish (blocking).\n :param job_name: SageMaker training job name\n :raises Exception: If job does not finish cleanly (is stopped, for example) or waiting took too long\n :return JobStatus: Job status after waiting\n \"\"\"\n with self.lock:\n self.check_or_build_connection()\n LOGGER.info(\"Started waiting for job %s to finish.\", job_name)\n waiter = self.client.get_waiter('training_job_completed_or_stopped')\n attempt_delay_secs = 60\n max_attempts = 60 * 24 * 3 # Three days\n waiter.wait(\n TrainingJobName=job_name,\n WaiterConfig={\n 'Delay': attempt_delay_secs,\n 'MaxAttempts': max_attempts # TODO Wait longer?\n }\n )\n job_status = self.get_job_status(job_name=job_name)\n LOGGER.info(\"Job %s finished with status %s\", job_name, job_status)\n\n if not job_status.is_processed and not job_status.stale:\n waited_hours = max_attempts * attempt_delay_secs / 3600\n LOGGER.exception(\"Exited waiter after waiting %f hours\", waited_hours)\n raise RuntimeError(\"Did not expect to wait for more than {hours} hours\".format(hours=waited_hours))\n return job_status\n\n def get_training_job_analytics_df(self, job_name: str):\n with self.lock:\n self.check_or_build_connection()\n\n LOGGER.debug(\"Checking for updates for job %s\", job_name)\n analytics = self.analytics_by_job_name.setdefault(job_name,\n sagemaker.analytics.TrainingJobAnalytics(\n training_job_name=job_name,\n sagemaker_session=self.sagemaker_session))\n return analytics.dataframe(force_refresh=True)\n\n\nclass JobScalarHelper:\n\n def __init__(self, job: BaseJob):\n self.job = job\n self.last_timestamp_by_metric = {} # type: Dict[str, float]\n\n def add_new_scalars_from(self, metrics_dataframe: pd.DataFrame) -> bool:\n \"\"\"\n Add all new records from `metrics_dataframe` to job scalar history, keeping track of the previously\n seen maximum timestamp. It is assumed that for a given metric, all new records have timestamps larger than\n the previously seen maximum timestamp.\n :param metrics_dataframe: DataFrame with records with names \"metric_name\", \"value\", \"timestamp\"\n :return: Boolean denoting if new values were added to job scalar history\n \"\"\"\n metrics_grouped_by_name = metrics_dataframe.groupby(by=\"metric_name\")\n\n added_new_metrics = False\n\n for metric_name, metrics_for_name in metrics_grouped_by_name:\n max_timestamp_for_name = metrics_for_name[\"timestamp\"].max()\n previous_last_timestamp_or_none = self.last_timestamp_by_metric.get(metric_name, float(\"-inf\"))\n\n new_records_df = metrics_for_name[metrics_for_name.timestamp > previous_last_timestamp_or_none]\n\n for _, record in new_records_df.iterrows():\n added_new_metrics = True\n self.job.add_scalar_to_history(scalar_name=record['metric_name'], scalar_value=record['value'])\n\n self.last_timestamp_by_metric[metric_name] = max_timestamp_for_name\n return added_new_metrics\n\n\nclass SageMakerJobMonitor:\n MINIMUM_POLLING_INTERVAL_SECS = 60\n\n def __init__(self,\n event_loop=None,\n sagemaker_helper: Optional[SageMakerHelper] = None,\n notify_start: Optional[Callable[[BaseJob], Any]] = None,\n notify_update: Optional[Callable[[BaseJob, str, int, Optional[str]], Any]] = None,\n notify_finish: Optional[Callable[[BaseJob], Any]] = None,\n scalar_helper_factory: Optional[Callable[[BaseJob], JobScalarHelper]] = None):\n super().__init__()\n # self._notify = notify_function\n self._event_loop = event_loop or asyncio.get_event_loop()\n self.sagemaker_helper = sagemaker_helper or SageMakerHelper() # type: SageMakerHelper\n self.notify_start = notify_start\n self.notify_finish = notify_finish\n self.notify_update = notify_update\n self.job_scalar_helper_factory = scalar_helper_factory or JobScalarHelper\n\n def start(self, job: SageMakerJob) -> asyncio.Task:\n self.sagemaker_helper.check_or_build_connection()\n return self._event_loop.create_task(self.monitor(job))\n\n async def monitor(self, job: SageMakerJob):\n update_polling_task = self._event_loop.create_task(self.poll_updates(job)) # type: asyncio.Task\n wait_for_finish_future = \\\n self._event_loop.run_in_executor(\n None, self.sagemaker_helper.wait_for_job_finish, job.name)\n try:\n job_status = await wait_for_finish_future\n except Exception as ex: # pylint:disable=broad-except\n if isinstance(ex, asyncio.CancelledError):\n raise ex\n LOGGER.exception(\"Failed waiting for job to finish\")\n job_status = self.sagemaker_helper.get_job_status(job_name=job)\n finally:\n if not update_polling_task.done():\n LOGGER.info(\"Canceling polling for job %s\", job.name)\n try:\n update_polling_task.cancel()\n except Exception: # pylint:disable=broad-except\n LOGGER.exception(\"Canceling the task failed\")\n\n job.status = job_status\n if self.notify_finish:\n LOGGER.info(\"Notifying finish for job %s with status %s\", job.name, job.status)\n self.notify_finish(job)\n\n async def poll_updates(self, job: BaseJob):\n if not isinstance(job, SageMakerJob):\n raise RuntimeError(\"SageMakerJobMonitor can only monitor SageMakerJobs.\")\n\n if job.status.is_processed:\n LOGGER.info(\"SageMaker job %s already finished, returning\", job.name)\n return\n\n sleep_time = max(job.poll_time, SageMakerJobMonitor.MINIMUM_POLLING_INTERVAL_SECS)\n LOGGER.debug(\"Starting SageMaker job tracking for job %s with polling interval of %f seconds.\",\n job.name, sleep_time)\n\n if job.status.is_launched and self.notify_start:\n self.notify_start(job)\n\n job_scalar_helper = self.job_scalar_helper_factory(job)\n\n try:\n while True:\n await self.check_and_apply_updates(job=job, job_scalar_helper=job_scalar_helper)\n\n if job.status.is_processed:\n break\n\n await asyncio.sleep(sleep_time)\n\n LOGGER.info(\"Stopped monitoring SageMakerJob %s, got status %s\", job.name, job.status)\n except asyncio.CancelledError:\n LOGGER.debug(\"SageMakerJob tracking cancelled for job %s\", job.name)\n except Exception: # pylint:disable=broad-except\n LOGGER.exception(\"Polling for updates failed\")\n # Ignore\n\n async def check_and_apply_updates(self, job: BaseJob, job_scalar_helper: JobScalarHelper):\n LOGGER.debug(\"Checking updates for job %s\", job.name)\n previous_status = job.status\n job.status = await self._event_loop.run_in_executor(None, self.sagemaker_helper.get_job_status, job.name)\n LOGGER.debug(\"Job %s: previous status %s, current status %s\", job.name, previous_status, job.status)\n if not previous_status.is_launched and job.status.is_launched and self.notify_start:\n self.notify_start(job)\n\n added_new_scalars = False\n\n try:\n get_training_job_analytics = partial(self.sagemaker_helper.get_training_job_analytics_df, job_name=job.name)\n metrics_df = await self._event_loop.run_in_executor(None, get_training_job_analytics)\n if not metrics_df.empty:\n added_new_scalars = job_scalar_helper.add_new_scalars_from(metrics_df)\n except Exception as ex: # pylint:disable=broad-except\n # Reading TrainingJobAnalytics routinely throws an exception, handle it here\n # TODO Only catch a more specific exception to avoid getting into failure loop?\n if isinstance(ex, asyncio.CancelledError):\n raise ex\n LOGGER.exception(\"Checking for SageMaker job metrics failed, ignoring.\")\n\n if added_new_scalars:\n # Something new to report\n self._event_loop.run_in_executor(None, self.__query_and_report, job)\n\n # TODO Remove duplicate code with Scheduler\n def query_scalars(self, *names: Tuple[str, ...], job, latest_only: bool = True, plot: bool = False):\n if not job:\n raise JobNotFoundException(job_id=str(job.id))\n return job.get_updates(*names, plot=plot, latest=latest_only)\n\n def __query_and_report(self, job):\n if self.notify_update:\n # Get updates; TODO - vals should be reported once we update schema...\n vals, imgpath = self.query_scalars(job=job, latest_only=True, plot=True)\n if vals: # Only send updates if there exists any updates\n self.notify_update(job, imgpath, n_iterations=-1)\n if imgpath is not None:\n os.remove(imgpath)\n\n def create_job(self, job_name: str, poll_interval: Optional[float] = None) -> SageMakerJob:\n sagemaker_helper = self.sagemaker_helper\n status = sagemaker_helper.get_job_status(job_name)\n return SageMakerJob(job_name=job_name,\n status=status,\n poll_interval=poll_interval)\n","repo_name":"meeshkan/meeshkan-client","sub_path":"meeshkan/core/sagemaker_monitor.py","file_name":"sagemaker_monitor.py","file_ext":"py","file_size_in_byte":14064,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"81"} +{"seq_id":"41764823904","text":"# input: a folder with aligned (protein) multifastas\n# output: a concatenated multifasta of alignments (used for phylogenetic analyses)\ndef main():\n aligned = glob.glob(path.abspath(args.aln) + \"/*\" )\n # initialize dictionary of sequences with keys:\n cat = {k:\"\" for k in SeqIO.to_dict(SeqIO.parse(aligned[0], \"fasta\")).keys()}\n # loop to fill the others\n for a in aligned:\n d = SeqIO.to_dict(SeqIO.parse(a, \"fasta\"))\n for k in d.keys():\n cat[k] += str(d[k].seq)\n outfile = open(path.abspath(args.out), \"w\")\n for k in cat.keys():\n outfile.write(\">\" + k + \"\\n\")\n outfile.write(cat[k] + \"\\n\")\n outfile.close()\n \n \n\n\n\n\nif __name__ == \"__main__\":\n import argparse\n from Bio import SeqIO\n import glob\n from os import path, system, makedirs\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--aln\", \"-a\", help = \"aligned proteins folder\") #only aligned proteins should be in this folder\n parser.add_argument(\"--out\", \"-o\", help = \"outfile path\")\n args = parser.parse_args()\n main()\n \n","repo_name":"FabioMIDI/phylo_pipe","sub_path":"scripts/orthos2cat.py","file_name":"orthos2cat.py","file_ext":"py","file_size_in_byte":1092,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"31565804491","text":"from crontab import CronTab\nimport sys\n\nmy_cron = CronTab(user=True)\n\nif len(sys.argv) < 4:\n print(\"Expecting 3 input args, got {}\".format(str(len(sys.argv) - 1)))\n exit(1)\n\n# excel_path = '/code/docker_result.xls\n# mongdb_name = 'mongodb'\npython_path = sys.argv[1]\npath = sys.argv[2]\nmongdb_name = sys.argv[3]\n\njob = my_cron.new(command='{}/python {}/spider.py {} {} >> '\n '{}/latest_update.log'.format(python_path, path, path,\n mongdb_name, path))\n\nprint('started new job :-)')\njob.setall('0 0 * * *')\njob.set_comment(\"spider crontab job\")\n\njob.enable()\nmy_cron.write()\n","repo_name":"rabbit721/zhihu-spider","sub_path":"crontab-control.py","file_name":"crontab-control.py","file_ext":"py","file_size_in_byte":658,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"32838053437","text":"n = int(input(\"enter a no\"))\na = 0\nc = 0\nb = 0\nwhile n > 0:\n a = int(n/10)\n b = int(n%10)\n n=a\n c = c + 1\nprint(\"total no of digit\",c)\n","repo_name":"Dhivyabarathi3/code-kata","sub_path":"countdig.py","file_name":"countdig.py","file_ext":"py","file_size_in_byte":147,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"70397026184","text":"import pandas as pd\nimport numpy as np\n\ndef read_label(path, categories):\n df = pd.read_csv(path)\n df = df.loc[:, 'TrueLabel'].to_numpy()\n label_name = pd.read_csv(categories)\n label_name = label_name.loc[:, 'CategoryName'].to_numpy()\n\n return df, label_name\n","repo_name":"NTU-speech-lab/hw6-robert1003","sub_path":"_utils.py","file_name":"_utils.py","file_ext":"py","file_size_in_byte":274,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"38548799702","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu Oct 8 16:18:17 2020\r\n\r\n@author: ninjaac\r\n\"\"\"\r\n\r\n\r\nclass Solution:\r\n @staticmethod\r\n def balancedStringSplit(s):\r\n bal,result=0,0\r\n l=len(s)\r\n for i in range(l):\r\n if s[i]==\"R\":\r\n bal+=1\r\n else:bal-=1\r\n if bal==0:\r\n result+=1\r\n return result\r\nprint(Solution().balancedStringSplit('LLRRRLLR'))","repo_name":"pavi-ninjaac/leetcode","sub_path":"String/Easy/Split_string_balaced_By_LR.py","file_name":"Split_string_balaced_By_LR.py","file_ext":"py","file_size_in_byte":433,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"30400781629","text":"import os\nimport torch\nimport torchvision\n\nimport torchvision.transforms as transforms\n\nfrom torch.nn import CrossEntropyLoss\nfrom torch.utils.data import ConcatDataset\n\nfrom REPAIR.fuse_diff import fuse_from_cfg\nfrom REPAIR.net_models.mlp import VGG\nfrom REPAIR.fuse_cfg import BaseFuseCfg\nfrom REPAIR.matching.weight_matching import WeightMatching\nfrom REPAIR.matching.activation_matching import ActivationMatching\n\n\ndef get_datasets():\n path = os.path.dirname(__file__)\n\n transform = transforms.Compose(\n [\n transforms.ToTensor(),\n transforms.Pad(3)\n ]\n )\n mnistTrainSet = torchvision.datasets.MNIST(\n root=path + '/data', \n train=True,\n download=True, \n transform=transform\n )\n\n first_half = [\n idx for idx, target in enumerate(mnistTrainSet.targets) \n if target in [0, 1, 2, 3, 4]\n ]\n\n second_half = [\n idx for idx, target in enumerate(mnistTrainSet.targets) \n if target in [5, 6, 7, 8, 9]\n ] \n\n FirstHalfLoader = torch.utils.data.DataLoader(\n torch.utils.data.Subset(mnistTrainSet, first_half),\n batch_size=128,\n shuffle=True,\n num_workers=8)\n \n SecondHalfLoader = torch.utils.data.DataLoader(\n torch.utils.data.Subset(mnistTrainSet, second_half),\n batch_size=128,\n shuffle=True,\n num_workers=8)\n \n ConcatLoader = torch.utils.data.DataLoader(\n ConcatDataset((torch.utils.data.Subset(mnistTrainSet, first_half), torch.utils.data.Subset(mnistTrainSet, second_half))), \n batch_size=128,\n shuffle=True, \n num_workers=8\n )\n \n return FirstHalfLoader, SecondHalfLoader, ConcatLoader\n\n\nif __name__ == \"__main__\":\n loader0, loader1, loaderc = get_datasets()\n\n fuse_cfg = BaseFuseCfg(num_experiments=1, alpha_split=10)\n\n vgg_cfg = [64, 'M', 128, 'M', 256, 256, 'M', 512, 512, 'M', 512, 512, 'M']\n fuse_cfg.models = {\n 0: {\n \"model\": VGG,\n \"args\": {\n \"w\": 1,\n \"cfg\": vgg_cfg,\n \"classes\": 10,\n \"in_channels\": 1\n }\n },\n }\n fuse_cfg.configs = {\n 0: {\n \"loss_fn\": CrossEntropyLoss(),\n \"match_method\": WeightMatching(),\n \"device\": \"cuda\",\n },\n }\n fuse_cfg.loaders = {\n 0: {\n \"loader0\": loader0,\n \"loader1\": loader1,\n \"loaderc\": loaderc,\n }\n }\n fuse_cfg.names = {\n 0: {\n \"experiment_name\": \"fuse_vgg_cifar_split\",\n \"model0_name\": \"vgg_first\",\n \"model1_name\": \"vgg_second\"\n }\n }\n fuse_cfg.root_path = os.path.dirname(__file__)\n\n fuse_from_cfg(fuse_cfg)","repo_name":"marza96/multi_task_zipping","sub_path":"fuse_vgg_mnist_split.py","file_name":"fuse_vgg_mnist_split.py","file_ext":"py","file_size_in_byte":2757,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"30781365603","text":"from odoo.addons.shopinvader.tests.common import NotificationCaseMixin\nfrom odoo.addons.shopinvader.tests.test_address import CommonAddressCase\n\n\nclass NotificationCustomerCase(CommonAddressCase, NotificationCaseMixin):\n def setUp(self):\n super().setUp()\n with self.work_on_services(\n partner=None, shopinvader_session=self.shopinvader_session\n ) as work:\n self.customer_service = work.component(usage=\"customer\")\n\n def _create_customer(self, **kw):\n data = {\n \"email\": \"new@customer.example.com\",\n \"external_id\": \"D5CdkqOEL\",\n \"name\": \"Purple\",\n \"street\": \"Rue du jardin\",\n \"zip\": \"43110\",\n \"city\": \"Aurec sur Loire\",\n \"phone\": \"0485485454\",\n \"country\": {\"id\": self.env.ref(\"base.fr\").id},\n }\n data.update(kw)\n res = self.customer_service.dispatch(\"create\", params=data)[\"data\"]\n return self.env[\"res.partner\"].browse(res[\"id\"])\n\n def test_new_customer_welcome_not_validated(self):\n self.backend.update(\n dict(validate_customers=True, validate_customers_type=\"all\")\n )\n partner = self._create_customer(\n email=\"new@tovalidate.example.com\",\n external_id=\"F5CdkqOEL\",\n name=\"To Validate\",\n )\n job = self._find_notification_job(\n name=\"Notify new_customer_welcome_not_validated for res.partner,%d\"\n % partner.id\n )\n self.assertTrue(job)\n self._perform_job(job)\n self._check_notification(\"new_customer_welcome_not_validated\", partner)\n\n # now enable it\n invader_partner = partner._get_invader_partner(self.backend)\n invader_partner._get_shopinvader_validate_wizard().action_apply()\n job = self._find_notification_job(\n name=\"Notify customer_validated for res.partner,%d\" % partner.id\n )\n self.assertTrue(job)\n self._perform_job(job)\n self._check_notification(\"customer_validated\", partner)\n\n def test_address_created_not_validated(self):\n self.backend.update(\n dict(validate_customers=True, validate_customers_type=\"all\")\n )\n params = dict(self.address_params, name=\"John Doe\")\n self.address_service.dispatch(\"create\", params=params)\n address = self.env[\"res.partner\"].search([(\"name\", \"=\", \"John Doe\")])\n self.assertEqual(address.parent_id, self.partner)\n # notification goes to the owner of the address\n partner = self.partner\n job = self._find_notification_job(\n name=\"Notify address_created_not_validated for res.partner,%d\" % partner.id\n )\n self.assertTrue(job)\n self._perform_job(job)\n self._check_notification(\"address_created_not_validated\", partner)\n\n # now enable it\n address._get_shopinvader_validate_address_wizard().action_apply()\n job = self._find_notification_job(\n name=\"Notify address_validated for res.partner,%d\" % partner.id\n )\n self.assertTrue(job)\n self._perform_job(job)\n self._check_notification(\"address_validated\", partner)\n","repo_name":"shopinvader/odoo-shopinvader","sub_path":"shopinvader_customer_validate/tests/test_notification.py","file_name":"test_notification.py","file_ext":"py","file_size_in_byte":3194,"program_lang":"python","lang":"en","doc_type":"code","stars":105,"dataset":"github-code","pt":"81"} +{"seq_id":"74694161545","text":"# 3. Написати функцию , яка прийматиме 1 аргумент - число від 0 до 1000, и яка вертатиме\n# True, якщо це число просте і False - якщо ні.\n\n\ndef is_int(num) -> bool:\n return isinstance(num, int)\n\n\ndef num_in_range(num: int) -> bool:\n return num > -1 and num < 1001\n\n\ndef is_prime(num: int) -> bool | str:\n # Check input type and if it is in range 0 - 1000\n if not is_int(num=num):\n return \"Number must be int\"\n if not num_in_range(num=num):\n return \"Number must 0 - 1000\"\n\n # Check half of numbers\n if num == 1:\n return False\n else:\n for i in range(2, num // 2 + 1):\n if num % i == 0:\n return False\n return True\n\n\nprint(is_prime(\"d\"))\nprint(is_prime(1))\nprint(is_prime(4))\nprint(is_prime(5))\nprint(is_prime(10))\n","repo_name":"VladyslavaSysenko/GeekHub","sub_path":"HT-06/task_3.py","file_name":"task_3.py","file_ext":"py","file_size_in_byte":888,"program_lang":"python","lang":"uk","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"21689862146","text":"import base64\nfrom typing import Any\nfrom Crypto.Cipher import AES\nfrom Crypto import Random\nfrom Crypto.Protocol.KDF import PBKDF2\n \nBLOCK_SIZE = 16\npad = lambda s: s + (BLOCK_SIZE - len(s) % BLOCK_SIZE) * chr(BLOCK_SIZE - len(s) % BLOCK_SIZE)\nunpad = lambda s: s[:-ord(s[len(s) - 1:])]\n\nSECRET_KEY = 'secret key' # Keep it secret in production use\n \n\ndef get_private_key(secret_key: str) -> bytes:\n salt = b\"this is a salt\"\n kdf = PBKDF2(secret_key, salt, 64, 1000)\n key = kdf[:32]\n return key\n \n \ndef encrypt(raw: str, secret_key: str) -> bytes:\n private_key = get_private_key(secret_key)\n raw = pad(raw).encode(\"UTF-8\")\n iv = Random.new().read(AES.block_size)\n cipher = AES.new(private_key, AES.MODE_CBC, iv)\n return base64.b64encode(iv + cipher.encrypt(raw))\n \n \ndef decrypt(enc: bytes, secret_key: str) -> Any:\n private_key = get_private_key(secret_key)\n enc = base64.b64decode(enc)\n iv = enc[:16]\n cipher = AES.new(private_key, AES.MODE_CBC, iv)\n return unpad(cipher.decrypt(enc[16:]))\n \n\nmsg = input(\"Enter message: \")\n\n# First let us encrypt secret message\nencrypted = encrypt(msg, SECRET_KEY)\nprint(encrypted)\n \n# Let us decrypt using our original secret_key\ndecrypted = decrypt(encrypted, SECRET_KEY)\nprint(bytes.decode(decrypted))\n","repo_name":"SkillsHats/python_codes","sub_path":"src/encrypt_decrypt.py","file_name":"encrypt_decrypt.py","file_ext":"py","file_size_in_byte":1286,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"81"} +{"seq_id":"41258062873","text":"sequence = int(input('How many numbers of Fibonatti sequence do you want to see? '))\nfirst = 0\nsecond = 1\ncount = 3\nprint('{} -> {}'.format(first, second), end='')\nwhile count <= sequence:\n third = first + second\n first = second\n second = third\n print(' -> {}'.format(third), end='')\n count += 1\nprint(' -> DONE')\n","repo_name":"joelmedeiros/studies.py","sub_path":"Fase14/Challange63.py","file_name":"Challange63.py","file_ext":"py","file_size_in_byte":329,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"42360626536","text":"\"\"\"\n\nDate created: 12/28/2022\n\nPurpose:\n\nDetails:\nstart \"H:\\Programming\\Python\\projects_github\\ai_testing\\\" cmd.exe /k py -3.8 \"./multiagent/pacman.py\"\n\n\nstart \"H:\\Programming\\Python\\projects_github\\ai_testing\\multiagent\\\" cmd.exe /k py -3.8 \".pacman.py\"\n\n\nH:\\Programming\\Python\\projects_github\\ai_testing\\multiagent\\pacman.py\nDescription:\n\nNotes:\n\nIMPORTANT NOTES:\n\nExplanation:\n\nTags:\n\nContributors: \n https://github.com/josephedradan\n\nReference:\n\n\"\"\"\nimport os\nimport subprocess\n\nLIST_PATH_RELATIVE_ASSIGNMENT = [\n \"multiagent/\"\n]\n\n# COMMAND_RUN = \"start \\\"{}\\\" cmd.exe /k py -3.8 pacman.py\" # ONLY WORKS ON WINDOWS\n\nLiST_ARG = [\n # \"-p AgentPacmanGreedy\",\n # \"-p AgentPacmanLeftTurn\",\n # \"-p AgentPacmanReflex\",\n # \"-p AgentPacmanReflex_Attempt_1\",\n \"-p AgentPacmanMinimax\"\n\n]\n# NOTES: /k will keep the shell when done. /c will kill the shell when done\n# COMMAND_RUN = \"start cmd.exe /k py -3.8 pacman.py {} \" # ONLY WORKS ON WINDOWS\nCOMMAND_RUN = \"start cmd.exe /c py -3.8 pacman.py {} \" # ONLY WORKS ON WINDOWS\n\ndef main():\n cwd = os.getcwd()\n\n ##########\n\n # Loop and run all the assignments as the same time\n for path_relative in LIST_PATH_RELATIVE_ASSIGNMENT:\n\n path_full_assignment = os.path.join(cwd, path_relative)\n # print(\"path_full_assignment\", path_full_assignment)\n\n for arg in LiST_ARG:\n\n command = COMMAND_RUN.format(arg)\n\n print(command)\n\n # Execute command in corresponding directory\n subprocess.Popen(command,\n cwd=path_full_assignment,\n shell=True # This must be true for the commands to work\n )\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"josephedradan/ai_agent_testing","sub_path":"run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":1746,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"81"} +{"seq_id":"17350779246","text":"import numpy as np\nimport os\nimport sys\nsys.path.append(os.path.join(os.path.dirname(__file__), '..'))\n\n\nclass Variable:\n def __init__(self, data):\n self.data = data\n self.grad = None\n self.creator = None\n\n def set_creator(self, func):\n self.creator = func\n\n def backward(self):\n f = self.creator\n if f is not None:\n x = f.input\n x.grad = f.backward(self.grad)\n x.backward() # 自分より一つ前の変数のbackwardメソッドを呼ぶ\n\n\nclass Function:\n def __call__(self, input):\n x = input.data\n y = self.forward(x)\n output = Variable(y)\n output.set_creator(self) # 出力変数に生みの親を覚えさせる\n self.input = input\n self.output = output # 出力も覚える\n return output\n\n\nif __name__ == \"__main__\":\n from function import Square, Exp\n A = Square()\n B = Exp()\n C = Square()\n\n x = Variable(np.array(0.5))\n a = A(x)\n b = B(a)\n y = C(b)\n\n assert y.creator == C\n assert y.creator.input == b\n assert y.creator.input.creator == B\n assert y.creator.input.creator.input == a\n assert y.creator.input.creator.input.creator == A\n assert y.creator.input.creator.input.creator.input == x\n\n y.grad = np.array(1.0)\n C = y.creator\n b = C.input\n b.grad = C.backward(y.grad)\n\n B = b.creator\n a = B.input\n a.grad = B.backward(b.grad)\n\n A = a.creator\n x = A.input\n x.grad = A.backward(a.grad)\n print(x.grad)\n\n A = Square()\n B = Exp()\n C = Square()\n\n x = Variable(np.array(0.5))\n a = A(x)\n b = B(a)\n y = C(b)\n\n y.grad = np.array(1.0)\n y.backward()\n print(x.grad)\n","repo_name":"ju-ki/Deep_learning_from_scratch3","sub_path":"mydezero/steps/step07.py","file_name":"step07.py","file_ext":"py","file_size_in_byte":1711,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"37162201457","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n__author__ = \"Mike Rightmire\"\n__copyright__ = \"Universitäts Klinikum Heidelberg, Section of Bioinformatics and Systems Cardiology\"\n__license__ = \"Not licensed for private use.\"\n__version__ = \"0.9.0.0\"\n__maintainer__ = \"Mike Rightmire\"\n__email__ = \"Michael.Rightmire@uni-heidelberg.de\"\n__status__ = \"Development\"\n\n\nfrom argparse import ArgumentParser\nfrom common.checks import Checks\nchecks = Checks()\n_delim = checks.directory_deliminator()\n# from common.confighandler import ConfigHandler # Needs to be updated for Python3\n# from common.loghandler import log\nfrom common.convert_timestring_input import convert_timestring_input as get_time \nfrom common.convert_timestring_input import age \n\nimport atexit\nimport inspect\nimport ntpath\nimport os\nimport re\nimport time\n_now=time.time()\n\n\nclass Find(object):\n \"\"\"\n :NAME:\n FindArchivableRootDirs.find(parser = {}, *args, **kwargs)\n \n :DESCRIPTION:\n Searches through a directory structure starting at a specified location, \n and reports the last MODIFICATION date of files and subdirectories. \n \n The output can be dumped to the terminal, written to file, or both.\n \n Reports are stored within the class object as two dictionaries: \n self.dictionaries\n self.files\n \n in the format:\n {\"file/dir_path_string\":[, , '']}\n I.e.\n {\"/Users/mikes\":[1506674640.0, 418520.73, 'Hour(s)']}\n \n :OUTPUT: \n Output to screen or file is in the TEXT format (strings, no lists):\n /Users/mikes:[1506674640.0, 418520.73, 'Hour(s)']\n \n Output to file is (currently) restricted to capturing the text format\n or pickling the output dictionary objects self.directories and \n self.files. \n \n Placeholders are set for output to CSV, XLS, XLSX, etc...but\n are not yet implemented. \n \n Output can be restricted to files (only), directories (only) or both. \n NOTE: When directories(only) are output, the age is based on the \n YOUNGEST file within the directory NOT the actual directory \n creation/modification date!\n \n The script can be run at the command line, using switches OR as a class, \n passing in variables via the *args/**kwargs parameters. \n \n :USAGE:\n FindArchivableRootDirs.py --root /Users/user/ \\\n --type f \\ \n --out \"./out.txt\" \\\n --older 1y \\\n --increment d\n \n OR\n \n obj = Find( root = \"/Users/user/\",\n type = \"f\",\n out = \"./out.txt\",\n older = \"1y\",\n increment = \"d\",\n ) \n \n :ATTRIBUTES:\n conf(str): (Future) Full path to the config file. \n DEFAULT: \"./FindArchivableRootDirs.conf\"\n \n directories: A dictionary object of the output for directories in the\n format:\n {\"file/dir_path_string\":[, , '']}\n I.e.\n {\"/Users/mikes\":[1506674640.0, 418520.73, 'Hour(s)']}\n \n files: A dictionary object of the output for files in the format:\n {\"file/dir_path_string\":[, , '']}\n {\"/Users/mikes\":[1506674640.0, 418520.73, 'Hour(s)']}\n I.e.\n\n increment(str): The time increment for output. CASE SENSITIVE.\n I.e.\n Y = Years\n M = Months\n d = Days\n h = Hours\n m = Minutes\n s = Seconds\n H = Human-readable\n DEFAULT: Seconds\n\n maxdepth(int): Similar to find's maxdepth. How many directories deep to\n limit the search. \"0\" means unlimited (through all \n levels). DEFAULT: 0\n \n newer(str): (Newer than X) Collect statistics on directories/files that \n are \"newer than\" .\n \"0\" means just report the age from today. \n DEFAULT: 0\n\n older(str): (Older than X) Collect statistics on directories/files that \n are \"older than\" .\n \"0\" means just report the age from today. \n DEFAULT: 0\n\n out(str): Full path to the output file. This file will lget overwwritten\n at each run. \n DEFAULT: \"./FindArchivableRootDirs.txt\"')\n\n root(str): Starting directory for search. DEFAULT: \".\"\n \n screen(bool): Set to \"True\" to dump output to screen. Otherwise False. \n DEFAULT: True\n \n type(char): Type of file system objects upon which to report dates. \n I.e.\n d=directories (only)\n f=files (only)\n b=both \n DEFAULT: b\n\n (logging only)\n logfile(STR): Output file for logging information (not script output). \n DEFAULT: \"system\"\n\n log_level(int): Logging level for logging information (not script \n output). \n DEFAULT: 10 (debug)\n\n screendump(bool): Should logging output be dumped to the STDOUT.', \n DEFAULT: True\n\n formatter(str): The formatting string for lgging outpput. (See logging \n module). \n\n create_paths(bool): (Logging only). If a logfile does not exist, should\n it be created (True/False). \n DEFAULT: True')\n \n :METHODS: \n dump([t = None]):\n where... \n t = The type (files or directories only)\n \n Dumps the report data to the screen. \n \n main(): Call method 'walkit' verbatim. If output files or screendumps\n have been specified at the command line, they are intelligently\n called. \n \n walkit(): No parameters accepted at the method level.\n This runs the actual directory walk and creates the output. \n Global 'self' parameters are used to generate criteria. \n Some attributes can be modified via a normal object set (I.e.\n Findobject.maxdepth = 2). \n \n :returns: A list of lists containing the same data as the text \n output.\n \n write([o = None, t = None, f = \"text\"]):\n where...\n f = The file format \n text (same as screen output)\n pickle (pickles the dictionary objects.)\n csv (Not yet implemented) \n xls (Not yet implemented) \n xlsx (Not yet implemented) \n\n t = The type (files or directories only)\n \n o = Specifies the output file name. If None, then the \n existing attribute value for outfile is used. \n \n Writes the report dictionary objects \"directories\" and \"files\" \n to a file.\n\n :RETURNS: \n Two python dictionary objects: \"directories\" and \"files\" which \n contain the report data (formatted as specified above). \n\n \"\"\"\n def __init__(self, parser = {}, *args, **kwargs):\n atexit.register(self._cleanup)\n self._set_config(parser, args, kwargs)\n self.main()\n \n def _arg_parser(self, parser):\n \"\"\"\n :NAME:\n _arg_parser\n \n :DESCRIPTION:\n Put all the argparse set up lines here, for example...\n parser.add_argument('--switch', '-s', \n action =\"store\", \n dest =\"variable_name\", type=str, default = '.', \n help ='Starting directory for search.'\n )\n \n :RETURNS:\n Returns the parser object for later use by argparse\n \n \"\"\"\n parser.add_argument('--increment', '-i', \n action=\"store\", dest=\"INCREMENTOUT\", type=str, default = 's', \n help='The time increment for output. CASE SENSITIVE. \\n I.e. \\n Y = Years \\n M = Months \\n d = Days \\n h = Hours \\n m = Minutes \\n s = Seconds \\n H = Human-readable.')\n\n parser.add_argument('--screen', '-s', \n action=\"store\", dest=\"TERMINAL\", type=bool, default = True, \n help='Set to \"True\" to dump output to screen. Otherwise False. DEFAULT: True')\n \n parser.add_argument('--conf', '-c', \n action=\"store\", dest=\"CONFIGFILE\", type=str, default = '.', \n help='Full path to the config file. DEFAULT: \"./FindArchivableRootDirs.conf\"')\n\n parser.add_argument('--root', '-r', \n action=\"store\", dest=\"STARTDIR\", type=str, default = '.', \n help='Starting directory for search. DEFAULT: \".\"')\n \n parser.add_argument('--maxdepth', '-m', \n action=\"store\", dest=\"MAXDEPTH\", type=int, default = '0', \n help='How many directories deep to limit the search. \"0\" means unlimited (fo through deepest levels). DEFAULT: 0')\n \n parser.add_argument('--type', '-t', \n action=\"store\", dest=\"FILETYPE\", type=str, choices=set((\"d\",\"D\",\"f\",\"F\", \"b\", \"B\")), default = 'b', \n help='Type of file system object to use for collecting dates. \\n d=directories (only) \\n f=files (only) \\n b=both. DEFAULT: Both')\n\n parser.add_argument('--older', '-O', \n action=\"store\", dest=\"OLDER\", type=str, default = '0', \n help='Collect statistics on directories/files older than . DEFAULT: 1 day')\n\n parser.add_argument('--newer', '-N', \n action=\"store\", dest=\"NEWER\", type=str, default = '0', \n help='Collect statistics on directories/files newer than . DEFAULT: 1 day')\n\n parser.add_argument('--out', '-o', \n action=\"store\", dest=\"OUTFILE\", type=str, \n help='Full path to the output file. DEFAULT: \"./FindArchivableRootDirs.txt\"')\n\n parser.add_argument('--logfile', \n action=\"store\", dest=\"logfile\", type=str, default = 'system', \n help='Logfile for debugging. DEFAULT: \"system\"')\n\n parser.add_argument('--log_level', \n action=\"store\", dest=\"log_level\", type=str, default = '10', \n help='Logging level for debugging. DEFAULT: 10 (debug)')\n\n parser.add_argument('--screendump', \n action=\"store\", dest=\"screendump\", type=bool, default = True, \n help='Screendump logging output to STDERR. DEFAULT: True')\n\n parser.add_argument('--formatter', \n action=\"store\", dest=\"formatter\", type=str, default = '0', \n help='Format for logging data. (See logging module)')\n\n parser.add_argument('--create_paths', \n action=\"store\", dest=\"create_paths\", type=bool, default = True, \n help='For logging (only) create any missing paths. I.e. if logfile does not exist, create it. DEFAULT: True')\n\n return parser\n \n def _cascade_dir(self, root, mtime):\n \"\"\"\"\"\"\n # Cascading the directories set the YOUNGEST file value as\n # as the value for all preceding dirs\n # Be sure the formatting comes in consistent\n root = root.strip().rstrip(_delim)\n # If the existing value is older, replace\n _age = age(mtime)\n \n try:\n _append = [mtime, get_time(int(_age), self.INCREMENTOUT), self.increment_readable]\n if self.directories[root][0] < mtime:\n self.directories[root] = _append\n# self.directories[root][0] = mtime\n # No inital value, set\n except KeyError as e: # Doesnt exist yet\n self.directories[root] = _append\n # Cascade starting at top dir\n cascade_dirs = root.split(_delim)\n cascade = _delim\n for dir in cascade_dirs:\n cascade = os.path.join(cascade, dir)\n\n try: \n # cascade (previous dir) is smaller(older) than root, replace value\n if self.directories[cascade][0] < self.directories[root][0]: \n# print(cascade, \"is OLDER. Changing:\", self.directories[cascade], \"to:\", self.directories[root])\n _append = [self.directories[root][0], get_time(int(_age), self.INCREMENTOUT), self.increment_readable]\n self.directories[cascade] = _append \n # Cascade dir does not yet exist (which will happen if starting from a relative root)\n except KeyError as e:\n self.directories[cascade] = self.directories[root]\n\n def _cleanup(self):\n message = \"Calling cleanup...\"\n _dir = os.getcwd()\n ###################\n # self.files\n _path = self.outfile + \".pickle\"\n msg = (\"Dumping searches as pickle to '\" + _path + \"' ...\")\n try:\n with open(_path, 'wb') as f:\n pickle.dump([self.directories, self.files], f)\n msg += \"OK\"\n except Exception as e:\n msg += \"FAILED (ERR:{E})\".format(E = str(e))\n\n # also dump as text\n _path = self.outfile + \".text\"\n try: \n # All cleanup here ##################################\n if self.outfile is not None: self._outfile.close()\n #####################################################\n message += \"OK\"\n # log.info(message)\n except Exception as e:\n message += \"FAILED ({E})\".format(E = str(e))\n # log.error(message)\n \n def _set_config(self, parser, args, kwargs):\n \"\"\"\"\"\" \n # Set class-wide\n self.app_name = self.__class__.__name__\n# self.CONF = ConfigHandler() # Needs to be updated for Python3\n self.ARGS = args\n self.KWARGS = kwargs \n # Convert parsed args to dict and add to kwargs\n if isinstance(parser, ArgumentParser):\n parser = self._arg_parser(parser)\n parser_kwargs = parser.parse_args()\n kwargs.update(vars(parser_kwargs))\n\n elif isinstance(parser, dict):\n kwargs.update(parser)\n \n else:\n err = \"{C}.{M}: Parameter 'parser' ({P}) must be either an Argparse parser object or a dictionary. \".format(C = self.app_name, M = inspect.stack()[0][3], P = str(parser))\n raise ValueError(err)\n \n # Here we parse out any args and kwargs that are not needed within the self or self.CONF objects\n # if \"flag\" in args: self.flag = something\n # Logging\n self.logfile = kwargs.pop('log_leveL', 'system') # Default warning\n self.log_level = kwargs.pop('log_leveL', 10) # Default warning\n self.screendump = kwargs.pop('screendump', True) # Default off\n self.formatter = kwargs.pop('formatter', '%(asctime)s-%(name)s-%(levelname)s-%(message)s')\n self.create_paths = kwargs.pop('create_paths', True) # Automatically create missing paths\n # parser stuff\n self.start = kwargs.pop(\"STARTDIR\", \".\") \n self.older = kwargs.pop(\"OLDER\", 0)\n self.newer = kwargs.pop(\"NEWER\", 0)\n self.outfile = kwargs.pop(\"OUTFILE\", \"FindArchivableRootDirs.\" + str(_now) + \".out\")\n self.maxdepth = kwargs.pop(\"MAXDEPTH\", 0)\n self.filetype = kwargs.pop(\"FILETYPE\", \"b\")\n self.TERMINAL = kwargs.pop(\"TERMINAL\", True)\n self.increment = kwargs.pop(\"INCREMENTOUT\", \"s\")\n self._now = time.time()\n # Everything else goes into the conf\n #==== # confighandler Needs to be updated for Python3 ==================\n # for key, value in kwargs.iteritems():\n # self.CONF.set(key, value)\n #=======================================================================\n \n\n #=======================================================================\n # # Log something\n # log.debug(\"Running {C}.{M}...\".format(C = self.app_name, M = inspect.stack()[0][3]), \n # app_name = self.app_name, \n # logfile = self.logfile, \n # log_level = self.log_level, \n # screendump = self.screendump, \n # create_paths = self.create_paths, \n # )\n #=======================================================================\n\n @property\n def directories(self):\n try:\n return self.DIRECTORIES\n except (AttributeError, KeyError, ValueError) as e:\n self.DIRECTORIES = {}\n return self.DIRECTORIES\n \n @property\n def files(self):\n try:\n return self.FILES\n except (AttributeError, KeyError, ValueError) as e:\n self.FILES = {}\n return self.FILES\n\n @property\n def filetype(self):\n try:\n return self.FILETYPE\n except (AttributeError, KeyError, NameError) as e:\n err = \"Attribute {A} is not set. \".format(A = str(inspect.stack()[0][3]))\n raise AttributeError(err)\n \n @filetype.setter\n def filetype(self, value):\n _value = str(value).lower()\n if _value[:1] in [\"d\", \"f\", \"b\"]:\n self.FILETYPE = _value[:1]\n \n else:\n err = 'The attribute {A} does not appear to be valid. Acceptable values are \"d\" (directories), \"f\" (files), \"b\" (both).'.format(A = inspect.stack()[0][3])\n# log.error(err))\n raise ValueError(err)\n\n @filetype.deleter\n def filetype(self, value):\n del self.FILETYPE\n\n @property \n def increment(self):\n try:\n return self.INCREMENTOUT\n except (AttributeError, KeyError, NameError) as e:\n err = \"Attribute {A} is not set. \".format(A = str(inspect.stack()[0][3]))\n raise AttributeError(err)\n\n @increment.setter\n def increment(self, value):\n _value = str(value)\n if _value[:1] in [\"Y\", \"M\", \"m\", \"D\", \"d\", \"H\", \"h\", \"S\", \"s\"]:\n self.INCREMENTOUT = _value[:1]\n \n else:\n err = 'The attribute {A} does not appear to be valid. Acceptable values are \"Y\" (Year), \"M\" (Month), \"D\" or (Day), \"h\" (Hour), \"m\" (Minute), \"s\" (Second), \"H\" (Human readable)'.format(A = inspect.stack()[0][3])\n# log.error(err))\n raise ValueError(err)\n\n @increment.deleter\n def increment(self):\n del self.INCREMENTOUT\n\n @property\n def increment_readable(self):\n try: \n if self.INCREMENTOUT.lower().startswith(\"y\"): return \"Year(s)\" \n elif self.INCREMENTOUT.startswith(\"M\") or self.INCREMENTOUT.lower().startswith(\"mo\"): return \"Month(s)\"\n elif self.INCREMENTOUT.lower().startswith(\"d\"): return \"Day(s)\" \n elif self.INCREMENTOUT.startswith(\"h\") or self.INCREMENTOUT.lower().startswith(\"ho\"): return \"Hour(s)\"\n elif self.INCREMENTOUT.lower() == \"m\" or self.INCREMENTOUT.lower().startswith(\"mi\"): return \"Minute(s)\"\n elif self.INCREMENTOUT.lower().startswith(\"s\") or len(self.INCREMENTOUT) < 1: return \"Second(s)\"\n elif self.INCREMENTOUT.startswith(\"H\") or self.INCREMENTOUT.lower().startswith(\"hu\"): return \"\"\n else: return \"no match\"\n except Exception as e: \n return str(e)\n \n @property\n def maxdepth(self):\n try:\n return self.MAXDEPTH # Just the path name\n except (AttributeError, KeyError, NameError) as e:\n err = \"Attribute {A} is not set. \".format(A = str(inspect.stack()[0][3]))\n raise AttributeError(err)\n \n @maxdepth.setter\n def maxdepth(self, value):\n try:\n self.MAXDEPTH = int(value)\n except Exception as e:\n err = \"'maxdepth' must be an integer (value = {V}).\".format(V = str(value))\n raise ValueError(err)\n \n @maxdepth.deleter\n def maxdepth(self):\n del self.MAXDEPTH\n \n @property\n def newer(self):\n try:\n return self.NEWER\n except (AttributeError, KeyError, NameError) as e:\n err = \"Attribute {A} is not set. \".format(A = str(inspect.stack()[0][3]))\n raise AttributeError(err)\n \n @newer.setter\n def newer(self, value):\n try:\n self.NEWER = get_time(value, \"s\")\n except ValueError as e:\n err = \"Failed to set attribute '{P}' with '{V}'. ({E})\".format(P = str(inspect.stack()[0][3]), V = str(value), E = str(e))\n raise ValueError(err)\n \n @newer.deleter\n def newer(self):\n del self.NEWER\n\n @property\n def outfile(self):\n try:\n return self.OUTFILE # Just the path name\n except (AttributeError, KeyError, NameError) as e:\n err = \"Attribute {A} is not set. \".format(A = str(inspect.stack()[0][3]))\n raise AttributeError(err)\n \n @outfile.setter\n def outfile(self, value):\n #=======================================================================\n # if \"none\" in str(value).lower():\n # self.OUTFILE = None\n # self._outfile = None\n # return \n #=======================================================================\n\n if value.startswith('.'):\n _current = os.getcwd()\n value = value.replace(\".\", _current, 1)\n \n try:\n self._outfile = open(value, \"w\")\n self.OUTFILE = value\n except Exception as e:\n err = \"Unable to open {F}. ({E})\".format(F = str(value), E = str(e))\n raise IOError(err)\n \n @outfile.deleter\n def outfile(self):\n self._outfile.close()\n del self.OUTFILE\n\n @property\n def older(self):\n try:\n return self.OLDER\n except (AttributeError, KeyError, NameError) as e:\n err = \"Attribute {A} is not set. \".format(A = str(inspect.stack()[0][3]))\n raise AttributeError(err)\n \n @older.setter\n def older(self, value):\n try:\n self.OLDER = get_time(value, 's')\n except ValueError as e:\n err = \"Failed to set attribute '{P}' with '{V}'. ({E})\".format(P = str(inspect.stack()[0][3]), V = str(value), E = str(e))\n raise ValueError(err)\n \n @older.deleter\n def older(self):\n del self.OLDER\n\n @property\n def start(self):\n try:\n return self.STARTDIR # Just the path name\n except (AttributeError, KeyError, NameError) as e:\n err = \"Attribute {A} is not set. \".format(A = str(inspect.stack()[0][3]))\n raise AttributeError(err)\n \n @start.setter\n def start(self, value):\n # Make full path\n if value.startswith('.'):\n _current = os.getcwd()\n value = value.replace(\".\", _current, 1)\n \n try:\n _value = str(value)\n # Strip extra delimitors\n _startdir_list = _value.split(_delim)\n _startdir_list = [x for x in _startdir_list if len(x) > 1]\n _startdir = _delim + _delim.join(_startdir_list) + _delim \n \n if os.path.isdir(_startdir): \n self.STARTDIR = value\n else: \n raise IOError()\n \n except Exception as e:\n err = \"The {A} ({V}) does not appear to exist or cannot be recognized. \".format(A = str(inspect.stack()[0][3]), V = str(value))\n raise ValueError(err)\n \n @start.deleter\n def start(self):\n del self.STARTDIR\n \n def dump(self, t = None):\n \"\"\"\"\"\"\n if t is not None:\n _t = str(t).lower()[:1]\n self.filetype = _t # Repace global var with input \"t\"\n\n if (self.filetype == \"d\") or (self.filetype == \"b\"):\n print(\"DIRS:\")\n if len(self.directories) > 0:\n for key,value in self.directories.items():\n # Minus one for directories, to remove empty split at beginning\n if ( len(key.split(_delim)) - 1 <= self.maxdepth) or (self.maxdepth == 0):\n print(key + \":\" + str(value))\n else:\n print(\"None\")\n\n if (self.filetype == \"f\") or (self.filetype == \"b\"):\n print(\"FILES:\")\n if len(self.files) > 0:\n for key,value in self.files.items():\n # NO minus one for files, since filename is not\n # a 'depth'. Empty first item and filename cancel out\n if ( len(key.split(_delim)) <= self.maxdepth) or (self.maxdepth == 0): \n print(key + \":\" + str(value)) \n else:\n print(\"None\")\n \n def read(self, f = None):\n \"\"\"\"\"\"\n if (f is None) and (self.outfile is None):\n err = \"{C}.{M}: The class attribute 'outfile' is not set, and 'f' (filename) was not passed. \".format(C = self.__class__.__name__, M = inspect.stack()[0][3])\n# log.error(err)\n raise RuntimeError(err)\n # Open the file\n # Dont reset self.outfile, but if self.outfile exists, use it. \n if f is not None: _filename = str(f)\n else: _filename = self.outfile\n try:\n fh = open(_filename, \"r\")\n except Exception as e:\n err = \"{C}.{M}: Unknown error opening file for reading. (Err: {E})\".format(C = self.__cöass__.__name__, M = inspect.stack()[0][3], E = str(e))\n# log.error(err)\n raise IOError(err)\n # Assume pickle first\n try:\n value1 = pickle.load(f)\n value2 = pickle.load(f)\n except Exception as e:\n err = \"File {F} does not appear to be a pickled file.\".format(F = _filename)\n# log.info(err)\n \n # Otherwise assume txt and try to read line by line and convert\n # FUTURE (MARKER FOR CHANGES IF XLS OR CSV IS IMPLEMENTED)\n import ast\n try:\n # reset dicts directly (no setters)\n self.DIRECTORIES = {}\n self.FILES = {}\n _reading = None\n # LOOP THOUGH\n for line in fh:\n if (\"DIRS:\" in line): \n _reading = \"d\"\n continue\n\n if (\"FILES:\" in line): \n _reading = \"f\"\n continue\n # Here we have a text line. Parse\n lineitems = line.split(\":\") # Should only ever be one \n key = lineitems[0] # already a string. \n value = ast.literal_eval(lineitems[1])\n if _reading == \"d\": self.DIRECTORIES[key] = value\n elif _reading == \"f\": self.FILES[key] = value\n else:\n err = \"{C}.{M}: There was unexpected content in file '{F}'. Unable to determine if line is a directory or a file item from headers. Did you select that wrong file?\".format(C = self.__class__.__name__, M = inspect.stack()[0][3], F = _filename)\n# log.error(err) \n raise RuntimeError(err)\n except Exception as e:\n err = \"Unknown error in {C}.{M}: (ERR: {E})\".format(C = self.__class__.__name__, M = inspect.stack()[0][3], E = str(e))\n# log.error(err)\n raise type(e)(err)\n \n def walkit(self):\n \"\"\"\n walkit(): No parameters accepted at the method level.\n This runs the actual directory walk and creates the output. \n Global 'self' parameters are used to generate criteria. \n Some attributes can be modified via a normal object set (I.e.\n Findobject.maxdepth = 2). \n \n :ATTRIBUTES:\n (See main class \"Find\")\n \n :RETURNS: A list of lists containing the same data as the text output. \n \"\"\"\n print(\"IN walkit)\")\n\n self.results = []\n print(\"Starting in: \", self.start)\n \n count=0\n for root, dirs, files in os.walk(self.start, topdown=True):\n count += 1\n if count % 1000 == 0: print(\"-\" + str(count), end=\"\")\n # The current dir age. \n # Check depth RELATIVE TO root\n # Just set its time for now. The file search with cascade it if needed.\n# self.directories[root] = os.stat(root).st_mtime\n self._cascade_dir(root, os.stat(root).st_mtime)\n dir_depth = root.replace(self.start, \"\") # Remove relative root\n dir_depth = dir_depth.split(checks.directory_deliminator())\n dir_depth = [x for x in dir_depth if len(x) > 1]\n dir_depth = len(dir_depth) + 1 # Start at 1 not 0\n \n# _dir_youngest_time = os.stat(root).st_mtime # Reset at each root loop\n # Need to parse files regardless of \"-t\", since they determine\n # the 'youngest' state of the preceding dirs\n for fn in files:\n path = os.path.join(root, fn)\n try:\n _time = os.stat(path).st_mtime # in epoch\n except Exception as e:\n message = \"Error gathering mtime from path {P}. Skipping. (ERROR: {E})\".format(P = path, E = str(e))\n # log.error(message)\n# self.results.append([message])\n# if self.TERMINAL: print(message)\n# if self._outfile is not None: self._outfile.write(str([message]) + \"\\n\")\n self.files[path] = message\n continue\n \n self._cascade_dir(root, _time)\n \n _diff = self._now - _time\n# # Set the directory time to the youngest file in the dir\n# if _time > _dir_youngest_time: \n# _dir_youngest_time = _time\n # If it matches the input time range \n if ((_diff >= self.older) or (self.older == 0)) and ((_diff <= self.newer) or (self.newer == 0)):\n # If individual file listings was set\n if (\"f\" in self.FILETYPE.lower()) or (\"b\" in self.FILETYPE.lower()):\n _append = [_time, get_time(int(_diff), self.INCREMENTOUT), self.increment_readable]\n# self.results.append(_append)\n self.files[path] = _append\n# self.files[path] = _time \n# if self.TERMINAL: print(_append)\n# if self._outfile is not None: self._outfile.write(str(_append) + \"\\n\")\n \n \n return self.directories, self.files\n \n def write(self, o = None, t = None, f = \"text\", m = None):\n \"\"\"\"\"\"\n # Repace global vars with inputs where needed\n if m is not None: self.maxdepth = int(m)\n _f = str(f).lower()\n # Check for pickling first\n if o is not None:\n # First set the outfile. This also set the _outfile\n self.outfile = str(o)\n # Then, if pickle; redo _outfile, dump, and return\n # This leaves the string slef.OUTFILE intact \n if re.match(\"^[Pp][IiCcKkLlEe]*$\", _f):\n # Close existing outfile if it exists\n try: self._outfile.close()\n except: pass\n # Dump the pickle. No reason to set self._outfile again. \n try:\n with open(self.outfile, 'wb') as f: \n pickle.dump([self.directories, self.files], f)\n return\n \n except Exception as e:\n err = \"{C}.{M}: Unknown error trying to create pickle. (ERR: {E})\".format(C = self__class__.__name__, M = inspect.stack()[0][3], E = str(e))\n # If not pickle, continue here\n if t is not None: self.filetype =str(t).lower()[:1]\n \n def _raise_not_implemented(t):\n err.format(F = \"csv\")\n# log.error(err)\n raise NotImplementedError(err)\n \n err = \"Output format '{F}' is not yet implemented. \"\n if _f == \"csv\": _raise_not_implemented(\"csv\") # future\n elif _f == \"xls\": _raise_not_implemented(\"xls\") # future\n elif _f == \"xlsx\": _raise_not_implemented(\"xlsx\") # future\n elif _f == \"text\": \n try:\n if (self.filetype == \"d\") or (self.filetype == \"b\"):\n self._outfile.write(\"DIRS:\" + \"\\n\")\n if len(self.directories) > 0:\n for key,value in self.directories.items():\n # Minus one for directories, to remove empty split at beginning\n if ( len(key.split(_delim)) - 1 <= self.maxdepth) or (self.maxdepth == 0):\n self._outfile.write(key + \":\" + str(value) + \"\\n\")\n else:\n self._outfile.write(\"None\" + \"\\n\")\n \n if (self.filetype == \"f\") or (self.filetype == \"b\"):\n self._outfile.write(\"FILES:\" + \"\\n\")\n if len(self.files) > 0:\n for key,value in self.files.items():\n # NO minus one for files, since filename is not\n # a 'depth'. Empty first item and filename cancel out\n if ( len(key.split(_delim)) <= self.maxdepth) or (self.maxdepth == 0):\n self._outfile.write(key + \":\" + str(value) + \"\\n\")\n else:\n self._outfile.write(\"None\" + \"\\n\")\n \n except AttributeError as e:\n err = \"{C}.{M}: Attribute '{A}' has not been set. ({E})\".format(C = self.__class__.__name__, M = inspect.stack()[0][3], A = \"outfile\", E = str(e))\n # log.error(msg)\n raise AttributeError(err)\n\n def main(self):\n \"\"\"\n :NAME:\n main()\n Calls \"walkit()\" verbatim. \n No parameters accepted at the method level.\n This runs the actual directory walk and creates the output. \n Global 'self' parameters are used to generate criteria. \n Some attributes can be modified via a normal object set (I.e.\n Findobject.maxdepth = 2). \n \n :ATTRIBUTES:\n (See main class \"Find\")\n \n :RETURNS: A list of lists containing the same data as the text output. \n \"\"\"\n # log.debug(\"Running 'Find' with parameters: {D}\".format(D = str(self.__dict__)))\n print(\"IN main)\")\n _result = self.walkit()\n if self.TERMINAL: self.dump()\n if self.outfile: self.write()\n # log.debug(\"Done.\")\n return _result\n \n \nif __name__ == '__main__':\n parser = ArgumentParser()\n object = Find(parser)\n","repo_name":"dieterich-lab/bareos-scripts","sub_path":"findArchivable/FindArchivableRootDirs.py","file_name":"FindArchivableRootDirs.py","file_ext":"py","file_size_in_byte":36493,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"81"} +{"seq_id":"39496099253","text":"import os\nfrom shapey.visualization.image_panel import DataPrepImagePanels, ImagePanelErrorDisplay\nimport matplotlib\nimport argparse\nfrom tqdm import tqdm\n\nmatplotlib.use('Agg')\n\nPROJECT_DIR = os.path.join(os.path.dirname(__file__), '..')\nDATA_DIR = os.path.join(PROJECT_DIR, 'data')\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='passes data directory and output file path')\n parser.add_argument('--input_dir', type=str, default=os.path.join(DATA_DIR, 'processed', 'your_feature.h5'))\n parser.add_argument('--output_dir', type=str, default=os.path.join(PROJECT_DIR, 'figures', 'your_feature_figs', 'error_panels'))\n parser.add_argument('--img_dir', type=str, default=os.path.join(PROJECT_DIR, 'data', 'ShapeY200', 'dataset'))\n\n args = parser.parse_args()\n\n print(args)\n\n input_name = args.input_dir\n output_dir = args.output_dir\n os.makedirs(output_dir, exist_ok=True)\n\n image_panel_data_processor = DataPrepImagePanels(args.img_dir, args.input_dir)\n\n # create randomly sampled image panel\n print('making randomly sampled image panels...')\n\n exc_axes_of_interest = ['p','w','x','y','pr','rw','pw','prw']\n exc_dists = [3, 5, 7]\n\n for ax in tqdm(exc_axes_of_interest):\n for dist in exc_dists:\n if ax == 'p' and dist < 6:\n pass\n else:\n list_of_errors, cval_list = image_panel_data_processor.get_whole_error_list(ax, dist)\n for i in range(int(len(list_of_errors)/10)):\n image_panel_error_display = ImagePanelErrorDisplay(args.img_dir)\n image_panel_error_display.reset_figure()\n ten_row_error = list_of_errors[i*10:(i+1)*10]\n ten_row_cval = cval_list[i*10:(i+1)*10]\n image_panel_error_display.fill_error_panel(ten_row_error, ten_row_cval, ax, dist, annotate=False)\n image_panel_error_display.figure.savefig(os.path.join(output_dir, 'error_panel_{}_{}_{}.png'.format(ax, dist, i)))\n \n image_panel_error_display.reset_figure()\n image_panel_error_display.fill_error_panel(ten_row_error, ten_row_cval, ax, dist, annotate=True)\n image_panel_error_display.figure.savefig(os.path.join(output_dir + 'error_panel_{}_{}_{}_ann.png'.format(ax, dist, i)))\n del image_panel_error_display\n matplotlib.pyplot.close('all')\n","repo_name":"njw0709/ShapeY","sub_path":"step4_graph_results/make_error_panels.py","file_name":"make_error_panels.py","file_ext":"py","file_size_in_byte":2479,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"8656427650","text":"from textwrap import dedent\n\nimport boto3\nfrom django.conf import settings\nfrom django.core.management.base import BaseCommand\n\n\nclass Command(BaseCommand):\n def handle(self, *args, **kwargs):\n bucket = settings.AWS_STORAGE_BUCKET_NAME\n region = settings.AWS_S3_REGION_NAME\n acl = \"public-read\"\n endpoint_url = settings.AWS_S3_ENDPOINT_URL\n use_ssl = settings.AWS_S3_USE_SSL\n\n print(\n dedent(\n f\"\"\"\n You are about to create an S3 bucket with the following configuration:\n\n AWS_STORAGE_BUCKET_NAME: {bucket}\n AWS_S3_REGION_NAME: {region}\n ACL: {acl}\n AWS_S3_ENDPOINT_URL: {endpoint_url}\n AWS_S3_USE_SSL: {use_ssl}\n\n Press any key to proceed.\n \"\"\"\n )\n )\n\n input()\n\n client = boto3.client(\"s3\", endpoint_url=endpoint_url, use_ssl=use_ssl)\n\n client.create_bucket(\n ACL=acl,\n Bucket=bucket,\n CreateBucketConfiguration={\n \"LocationConstraint\": region,\n },\n )\n","repo_name":"b-ggs/wagtail-template","sub_path":"wagtail_template/utils/management/commands/create_bucket.py","file_name":"create_bucket.py","file_ext":"py","file_size_in_byte":1149,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"81"} +{"seq_id":"24366804886","text":"import gym\nimport numpy as np\n\nfrom stable_baselines3.common.vec_env.base_vec_env import VecEnv\nfrom stable_baselines3.common.vec_env import SubprocVecEnv\n\n\nclass MultiAgentEnv(gym.Env):\n \"\"\"\n Multi-Agent extension for OpenAI Gym\n Credit:\n Largely based on OpenAI's multi-agent environment\n https://github.com/openai/multiagent-particle-envs/blob/master/multiagent/environment.py\n \"\"\"\n metadata = {\n 'render.modes': ['human', 'rgb_array']\n }\n\n def __init__(self, n_players):\n super().__init__()\n self._n_players = n_players\n\n def step(self, actions):\n return [], [], [], []\n\n def reset(self):\n return []\n\n @property\n def n_agents(self):\n return self.n_players\n\n @property\n def n_players(self):\n return self._n_players\n\n\nclass DummyMARLEnv(MultiAgentEnv):\n \"\"\"\n Dummy environment with given number of actors.\n \"\"\"\n\n def __init__(self, action_space, observation_space, n_players):\n super().__init__(n_players)\n self.observation_space = observation_space\n self.action_space = action_space\n\n def step(self, actions):\n obs = np.zeros((self.n_players, *self.observation_space.shape), dtype=self.observation_space.dtype)\n rewards = np.zeros([self.n_players], dtype=np.float)\n dones = np.zeros([self.n_players], dtype=np.bool)\n infos = [{\"train_mask\": 0} for _ in range(self.n_players)]\n return obs, rewards, dones, infos\n\n def reset(self):\n obs = np.zeros((self.n_players, *self.observation_space.shape), dtype=self.observation_space.dtype)\n return obs\n\n\nclass MultiAgentVecEnv(SubprocVecEnv):\n \"\"\"\n Vectorized Adapter for multi-agent environments.\n This allows multi-agent environments to be played by single-agent algorithms.\n All players are played by the same model, but using different instances (if LSTM is used).\n Definitions\n n_players: The total number of players in the environment\n n_agents: The total number of (non scripted) players in the environment\n The Vector Environment surfaces observations only for the agents, for example the environment\n | Game 1 | Game 2 | Game 3 |\n | p1, p2 | p1, p2, p3 | p1, p2 |\n | AI, AI | AI, script, AI | AI, AI |\n Would surface as a vector environment of length 6 (the scripted player masked out)\n This environment has 3 games, total_agents=7 and total_agents=6\n For compatibility num_envs is set to total_agents\n \"\"\"\n\n def __init__(self, make_marl_envs):\n\n self.games = [make_env() for make_env in make_marl_envs]\n\n VecEnv.__init__(self, self.total_agents, self.games[0].observation_space, self.games[0].action_space)\n\n self.actions = None\n self.auto_reset = True\n self.run_once = False # if true environment will pause after first reset\n\n self.env_completed = [False] * self.num_envs\n\n @property\n def total_players(self):\n return sum(game.n_players for game in self.games)\n\n @property\n def total_agents(self):\n return sum(game.n_agents for game in self.games)\n\n @property\n def max_players(self):\n return max(env.n_players for env in self.games)\n\n @property\n def max_roles(self):\n \"\"\" Returns number of roles in game\"\"\"\n # note, we take max here, so if a game has team 0 and team 2, 3 will be returned, with 0 players being on team 1\n result = 0\n for env in self.games:\n for player in env.players:\n result = max(result, 1 + player.team)\n return result\n\n @property\n def players(self):\n players = []\n for game in self.games:\n for player in game.players:\n players.append(player)\n return players\n\n def get_roles(self):\n \"\"\"\n Returns numpy array containing roles for each player\n :return: numpy array of dims [n_players]\n \"\"\"\n roles = [player.team for player in self.players]\n return np.asarray(roles, dtype=np.int64)\n\n def get_alive(self):\n \"\"\"\n Returns numpy array containing alive status for each player\n :return: bool np array of dims [n_envs]\n \"\"\"\n alive = []\n alive = []\n for game in self.games:\n for player in game.players:\n alive.append(player.is_alive)\n return np.asarray(alive, dtype=np.bool)\n\n def step_async(self, actions):\n actions = list(actions)\n assert len(actions) == self.num_envs, \\\n f\"Wrong number of actions, expected {self.num_envs} but found {len(actions)}.\"\n self.actions = actions\n\n def step_wait(self):\n\n obs = []\n rewards = []\n dones = []\n infos = []\n\n # step each marl environment\n reversed_actions = list(reversed(self.actions))\n for i, game in enumerate(self.games):\n\n if self.run_once and self.env_completed[i]:\n # ignore completed environments\n for _ in range(game.n_players):\n reversed_actions.pop()\n blank_obs = np.zeros(game.observation_space.shape, dtype=game.observation_space.dtype)\n obs.extend([blank_obs] * game.n_players)\n rewards.extend([0] * game.n_players)\n dones.extend([True] * game.n_players)\n infos.extend([{}] * game.n_players)\n continue\n\n env_actions = []\n for _ in range(game.n_players):\n env_actions.append(reversed_actions.pop())\n\n env_obs, env_rewards, env_dones, env_infos = game.step(env_actions)\n\n # auto reset.\n if self.auto_reset and all(env_dones):\n # save final terminal observation for later\n for this_info, this_obs in zip(env_infos, env_obs):\n this_info['terminal_observation'] = this_obs\n this_info['team_scores'] = game.round_team_scores.copy()\n if not self.run_once:\n env_obs = game.reset()\n self.env_completed[i] = True\n\n obs.extend(env_obs)\n rewards.extend(env_rewards)\n dones.extend(env_dones)\n infos.extend(env_infos)\n\n # convert to np arrays\n obs = np.asarray(obs)\n rewards = np.asarray(rewards)\n dones = np.asarray(dones)\n\n return obs, rewards, dones, infos\n\n def seed(self, seed=None):\n seeds = list()\n for idx, game in enumerate(self.games):\n seeds.append(game.seed(seed + idx))\n return seeds\n\n def reset(self):\n obs = []\n for game in self.games:\n obs.extend(game.reset())\n return np.asarray(obs)\n\n def close(self):\n for game in self.games:\n game.close()\n\n def get_attr(self, attr_name, indices=None):\n \"\"\"Return attribute from vectorized environment (see base class).\"\"\"\n target_envs = self._get_target_envs(indices)\n return [getattr(env_i, attr_name) for env_i in target_envs]\n\n def set_attr(self, attr_name, value, indices=None):\n \"\"\"Set attribute inside vectorized environments (see base class).\"\"\"\n target_envs = self._get_target_envs(indices)\n for env_i in target_envs:\n setattr(env_i, attr_name, value)\n\n def env_method(self, method_name, *method_args, indices=None, **method_kwargs):\n \"\"\"Call instance methods of vectorized environments.\"\"\"\n target_envs = self._get_target_envs(indices)\n return [getattr(env_i, method_name)(*method_args, **method_kwargs) for env_i in target_envs]\n\n def _get_target_envs(self, indices):\n indices = self._get_indices(indices)\n return [self.games[i] for i in indices]","repo_name":"maitchison/RTG","sub_path":"marl_env.py","file_name":"marl_env.py","file_ext":"py","file_size_in_byte":7807,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"81"} +{"seq_id":"69927474506","text":"import cv2 as cv\nimport numpy as np\nimg=cv.imread('photos/ph.jpeg')\ncv.imshow('boston',img)\n\n#translation\ndef translate(img,x,y):\n transMAt=np.float32([[1,0,x],[0,1,y]])\n dimensions = (img.shape[1],img.shape[0])\n return cv.warpAffine(img,transMAt,dimensions)\n\n\ntranslate=translate(img,100,100)\ncv.imshow('translate',translate)\n\ncv.waitKey(0)\n\n#rotation\n\ndef rotate(img, angle, rotPoint=None):\n (height,width)=img.shape[:2]\n\n if rotPoint is None:\n rotPoint = (width//2,height//2)\n\n rotMat =cv.getRotationMatrix2D(rotPoint,angle,1.0)\n dimensions=(width,height)\n\n return cv.warpAffine(img, rotMat, dimensions)\n\nrotated=rotate(img, 45)\ncv.imshow('rotated',rotated)\n\n#resizing\nresized = cv.resize(img, (500,500), interpolation= cv.INTER_CUBIC)\ncv.imshow('resized',resized)\ncv.waitKey(0)\n\n\n\n","repo_name":"Aryansharma28/opencv_beginner","sub_path":"translation.py","file_name":"translation.py","file_ext":"py","file_size_in_byte":816,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"3719462578","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\nfrom .get_resource_path import resource_path\nfrom PyQt5 import QtCore, QtGui, QtWidgets\n\n\nclass MainWindow(object):\n def setupUi(self, MainWindow):\n MainWindow.setObjectName(\"MainWindow\")\n MainWindow.resize(1150, 600)\n sizePolicy = QtWidgets.QSizePolicy(\n QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding\n )\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(\n MainWindow.sizePolicy().hasHeightForWidth()\n )\n MainWindow.setSizePolicy(sizePolicy)\n MainWindow.setIconSize(QtCore.QSize(0, 0))\n MainWindow.setToolButtonStyle(QtCore.Qt.ToolButtonIconOnly)\n MainWindow.setDocumentMode(False)\n\n self.centralwidget = QtWidgets.QWidget(MainWindow)\n self.centralwidget.setBaseSize(QtCore.QSize(1500, 1000))\n self.centralwidget.setObjectName(\"centralwidget\")\n self.horizontalLayout = QtWidgets.QHBoxLayout(self.centralwidget)\n self.horizontalLayout.setObjectName(\"horizontalLayout\")\n self.horizontalLayout_2 = QtWidgets.QHBoxLayout()\n self.horizontalLayout_2.setContentsMargins(0, 0, 0, -1)\n self.horizontalLayout_2.setObjectName(\"horizontalLayout_2\")\n\n self.img_label = QtWidgets.QLabel(self.centralwidget)\n self.img_label.setEnabled(True)\n sizePolicy = QtWidgets.QSizePolicy(\n QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed\n )\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(\n self.img_label.sizePolicy().hasHeightForWidth()\n )\n self.img_label.setSizePolicy(sizePolicy)\n self.img_label.setCursor(QtGui.QCursor(QtCore.Qt.CrossCursor))\n self.img_label.setText(\"\")\n self.img_label.setObjectName(\"img_label\")\n self.horizontalLayout_2.addWidget(self.img_label)\n self.horizontalLayout.addLayout(self.horizontalLayout_2)\n\n MainWindow.setCentralWidget(self.centralwidget)\n self.statusbar = QtWidgets.QStatusBar(MainWindow)\n self.statusbar.setObjectName(\"statusbar\")\n MainWindow.setStatusBar(self.statusbar)\n\n self.menubar = QtWidgets.QMenuBar(MainWindow)\n self.menubar.setGeometry(QtCore.QRect(0, 0, 1150, 23))\n self.menubar.setNativeMenuBar(True)\n self.menubar.setObjectName(\"menubar\")\n self.menuFile = QtWidgets.QMenu(self.menubar)\n self.menuFile.setObjectName(\"menuFile\")\n self.menuAuxiliaryTools = QtWidgets.QMenu(self.menubar)\n self.menuAuxiliaryTools.setObjectName(\"menuAuxiliaryTools\")\n MainWindow.setMenuBar(self.menubar)\n self.actionOpen = QtWidgets.QAction(MainWindow)\n self.actionOpen.setCheckable(False)\n self.actionOpen.setChecked(False)\n self.actionOpen.setEnabled(True)\n self.actionOpen.setObjectName(\"actionOpen\")\n self.actionAuxiliaryTools = QtWidgets.QAction(MainWindow)\n self.actionAuxiliaryTools.setObjectName(\"actionAuxiliaryTools\")\n self.actionOpen_Dir = QtWidgets.QAction(MainWindow)\n self.actionOpen_Dir.setObjectName(\"actionOpen_Dir\")\n self.menuFile.addAction(self.actionOpen)\n self.menuFile.addAction(self.actionOpen_Dir)\n self.menuFile.addSeparator()\n self.menuAuxiliaryTools.addAction(self.actionAuxiliaryTools)\n self.menubar.addAction(self.menuFile.menuAction())\n self.menubar.addAction(self.menuAuxiliaryTools.menuAction())\n\n self.retranslateUi(MainWindow)\n QtCore.QMetaObject.connectSlotsByName(MainWindow)\n\n def retranslateUi(self, MainWindow):\n _translate = QtCore.QCoreApplication.translate\n MainWindow.setWindowTitle(_translate(\"MainWindow\", \"Noghte\"))\n MainWindow.setWindowIcon(QtGui.QIcon(resource_path(\"logo.ico\")))\n self.menuFile.setTitle(_translate(\"MainWindow\", \"File\"))\n self.menuAuxiliaryTools.setTitle(_translate(\"MainWindow\", \"Tools\"))\n self.actionOpen.setText(_translate(\"MainWindow\", \"Open Image\"))\n self.actionAuxiliaryTools.setText(\n _translate(\"MainWindow\", \"Auxiliary Tools\")\n )\n self.actionOpen_Dir.setText(_translate(\"MainWindow\", \"Open Folder\"))\n","repo_name":"mh-salari/noghte","sub_path":"utils/mainwindow_ui.py","file_name":"mainwindow_ui.py","file_ext":"py","file_size_in_byte":4329,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"19101662679","text":"#! /usr/bin/env python\n\nimport numpy as np\nimport pandas as pd\nimport argparse\nimport os\nimport os.path as osp\n\nDATADIR = '/data/SFIM_Vigilance/Data/' # Path to data directory\nPRJDIR = '/data/SFIM_Vigilance/PRJ_Vigilance_Smk02/' # Path to project directory\nEEG_csv_file = 'all_subs_all_EEG_metrics_continuous_epochs_0_4_03-02-2021.csv' # EEG file of sleep staging data\n\nEEG_sleep_df = pd.read_csv(DATADIR+EEG_csv_file,sep=',') # Load data frame of original EEG sleep staging data\n\nsub_DF = pd.read_pickle(PRJDIR+'Notebooks/utils/valid_run_df.pkl') # Load subject information data frame\nSubDict = {}\nfor i,idx in enumerate(sub_DF.index):\n sbj = sub_DF.loc[idx]['Sbj']\n run = sub_DF.loc[idx]['Run']\n time = sub_DF.loc[idx]['Time']\n if sbj in SubDict.keys():\n SubDict[sbj].append((run,time))\n else:\n SubDict[sbj] = [(run,time)]\n\ndef run(args):\n SBJ_1 = args.subject\n SBJ_2 = SBJ_1.replace(\"-S\",\"\") # Subject number in form 'sub??'\n RUN = args.run\n\n out_path = osp.join(PRJDIR,'PrcsData',SBJ_1,'D02_Preproc_fMRI',SBJ_1+'_'+RUN+'_EEG_sleep.pkl') # File name of data being saved\n #out_path = osp.join(PRJDIR,'Notebooks',SBJ_1+'_'+RUN+'_EEG_sleep.pkl')\n\n # Empty data frame of subject spacific EEG sleep staging data\n EEG_sbj_sleep_df = pd.DataFrame(columns=['dataset','subject','cond','TR','sleep','drowsiness','spectral','seconds']) \n\n # Append subject and run data from original data frame to new data frame\n for i,idx in enumerate(EEG_sleep_df.index):\n if EEG_sleep_df.loc[idx]['subject'] == SBJ_2:\n if EEG_sleep_df.loc[idx]['cond'] == RUN:\n EEG_sbj_sleep_df = EEG_sbj_sleep_df.append(pd.DataFrame(EEG_sleep_df.loc[idx]).T,ignore_index=True)\n\n num_TR,aux = EEG_sbj_sleep_df.shape # Size of subject sleep data frame\n max_TR = int(EEG_sbj_sleep_df.loc[int(num_TR)-1]['TR']) # Minimum number TR in data\n min_TR = int(EEG_sbj_sleep_df.loc[0]['TR']) # Maximum number TR in data\n TIME = [SubDict[SBJ_1][i][1] for i in range(0,len(SubDict[SBJ_1])) if SubDict[SBJ_1][i][0] == RUN][0] # Total number of TR's for run\n\n # Fill in missing TRs in data bellow\n if max_TR != TIME+6:\n temp_bot = pd.DataFrame(columns=['dataset','subject','cond','TR','sleep','drowsiness','spectral','seconds'],index=range(0,(TIME+6)-(max_TR+1)))\n temp_bot['dataset'] = EEG_sbj_sleep_df['dataset']\n temp_bot['subject'] = EEG_sbj_sleep_df['subject']\n temp_bot['cond'] = EEG_sbj_sleep_df['cond']\n temp_bot['TR'] = range(max_TR+1,TIME+6)\n\n # Concatinate data so all TR's are acounted for in data frame\n EEG_sbj_sleep_df = pd.concat([EEG_sbj_sleep_df,temp_bot]).reset_index(drop = True)\n\n sleep_list =[] # Emply sleep staging list\n # Append sleep stage into list\n # 0 = wake\n # 1 = stage 1\n # 2 = stage 2\n # 3 = stage 3\n # NaN = undetermined stage\n for i,idx in enumerate(EEG_sbj_sleep_df.index):\n if EEG_sbj_sleep_df.loc[idx, 'sleep'] == 0:\n sleep_list.append('Wake')\n elif EEG_sbj_sleep_df.loc[idx, 'sleep'] == 1:\n sleep_list.append('Stage 1')\n elif EEG_sbj_sleep_df.loc[idx, 'sleep'] == 2:\n sleep_list.append('Stage 2')\n elif EEG_sbj_sleep_df.loc[idx, 'sleep'] == 3:\n sleep_list.append('Stage 3')\n else:\n sleep_list.append('Undetermined')\n \n EEG_sbj_sleep_df['stage'] = sleep_list # Add column to data of sleep stages\n \n EEG_sbj_sleep_df.to_pickle(out_path) # Save data frame as pickle file in subject directory\n\ndef main():\n parser=argparse.ArgumentParser(description=\"Load sleep staging for given subject and run.\")\n parser.add_argument(\"-sbj\",help=\"subject name in sub-SXX format\" ,dest=\"subject\", type=str, required=True)\n parser.add_argument(\"-run\",help=\"run name\" ,dest=\"run\", type=str, required=True)\n parser.set_defaults(func=run)\n args=parser.parse_args()\n args.func(args)\n\nif __name__ == \"__main__\":\n main()","repo_name":"IsabelF98/PRJ_Vigilance_Smk02","sub_path":"Notebooks/N00b_load_EEG_sleep.ToSwarm.py","file_name":"N00b_load_EEG_sleep.ToSwarm.py","file_ext":"py","file_size_in_byte":4020,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"38173735779","text":"import sys, os\n\n#order for files is sink, source dirty, source clean\n\nfiles = sys.argv[2:]\n\nfp = open(sys.argv[1] + '.meta', \"w\")\n\nfp.write(\"#SampleID\\tDescription\\tEnv\\tSourceSink\\tStudy\\tDetails\\n\")\nfor i, file in enumerate(files):\n file = file.rstrip().split('.renamed.fa')[0]\n if i <= 4:\n fp.write('%s\\tStream 1\\tStream 1\\tsource\\tsimulation\\t%s\\n' % (file, file))\n elif i > 4 and i <= 9:\n fp.write('%s\\tStream 2\\tStream 2\\tsource\\tsimulation\\t%s\\n' % (file, file))\n elif i > 9 and i <= 14:\n fp.write('%s\\tStream 3\\tStream 3\\tsource\\tsimulation\\t%s\\n' % (file, file))\n else :\n fp.write('%s\\tStream 4\\tStream 4\\tsink\\tsimulation\\t%s\\n' % (file, file))\n","repo_name":"germs-lab/non-point-source-tracking","sub_path":"scripts/make-meta.py","file_name":"make-meta.py","file_ext":"py","file_size_in_byte":698,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"3727465240","text":"import cv2\r\nimport os\r\nimport numpy as np\r\np = r\"C:\\Users\\Administrator\\Desktop\\Thickness data\"\r\nname = os.listdir(p)\r\nname.sort(key=lambda i: (len(i), i))\r\nans = []\r\nxx = 0\r\nyy = 0\r\nblue = []\r\ngreen = []\r\nred = []\r\nmb = []\r\nsb = []\r\nmg = []\r\nsg = []\r\nmr = []\r\nsr = []\r\ndef stat(sliced):\r\n for s in range(len(sliced)):\r\n #print(sliced[s].shape)\r\n for xx in range(100):\r\n #print(sliced[s][xx])\r\n for yy in range(100):\r\n #print(sliced[xx][yy])\r\n blue.append(sliced[s][xx][yy][0])\r\n mb.append(np.mean(blue))\r\n blue.clear()\r\n return mb\r\n #print(blue)\r\n# green.append(sliced[xx][yy][1])\r\n# red.append(sliced[xx][yy][2])\r\n #print(blue)\r\n# return blue\r\n #print()\r\n\r\n#0-33, 33-59,59-92\r\nfor a in range(59,92):\r\n img = cv2.imread(p + \"\\\\\" + name[a], 1)\r\n sliced = slice(img)\r\n blueres = stat(sliced)\r\n #stat(small[s])\r\n #stat(small[s])\r\n# stat(sliced)\r\n# print(len(sliced))\r\n#print(len(stat(small[s])))\r\nprint(blueres)\r\n\r\n\r\n","repo_name":"JerryChiang87/Chiang","sub_path":"thickness-detection/slice_RGB.py","file_name":"slice_RGB.py","file_ext":"py","file_size_in_byte":1086,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"7137621196","text":"# importing the modules\nimport pytest\nfrom product import Snack, Staples, Beverage\nfrom datetime import date\n\nclass TestSnack:\n# test case for printing details of Snack\n def test_details(self):\n s = Snack('chips' , 50)\n print(\"testing details : snack\")\n assert ('chips' , 50, 6) == (s.name, s.price, s.shelfLife)\n# test case for calculating expiry date of Snack\n def test_expDate(self):\n s = Snack('wafers', 40)\n print(\"testing expiry date : snack\")\n expdate = s.getExpDate(date(2019, 10, 3))\n assert expdate == date(2020, 4, 3)\n\nclass TestStaple:\n# test case for printing details of Staples\n def test_details(self):\n st = Staples('rice' , 300)\n print(\"testing details : staples\")\n assert ('rice' , 300, 1) == (st.name, st.price, st.shelfLife)\n# test case for calculating expiry date of Staples\n def test_expDate(self):\n st = Staples('wheat flour', 400)\n print(\"testing expiry date : staples\")\n expdate = st.getExpDate(date(2020, 1, 23))\n assert expdate == date(2021, 1, 23)\n\nclass TestBeverage:\n# test case for printing details of Beverage\n def test_details(self):\n b = Beverage('coffee' , 250)\n print(\"testing details : beverage\")\n assert ('coffee' , 250, 2) == (b.name, b.price, b.shelfLife)\n# test case for calculating expiry date of Beverage\n def test_expDate(self):\n b = Beverage('green tea', 400)\n print(\"testing expiry date : beverage\")\n expdate = b.getExpDate(date(2018, 12, 17))\n assert expdate == date(2020, 12, 17)\n","repo_name":"MishaAkram/SDT_LABS","sub_path":"Lab10/Example/test_product.py","file_name":"test_product.py","file_ext":"py","file_size_in_byte":1592,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"26159036387","text":"from __future__ import absolute_import, division, print_function, unicode_literals\n\n\nimport tensorflow as tf\n#tf.logging.set_verbosity(tf.logging.ERROR)\n#tf.enable_eager_execution()\n\nimport tensorflow_hub as hub\nimport os\nfrom tensorflow.keras.layers import Dense, Flatten, Conv2D\nfrom tensorflow.keras import Model\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras.optimizers import Adam\nfrom tensorflow.keras import layers\nimport time\nimport os\nfrom os.path import exists\nimport json\n#from keras import optimizers\n\n\n# verify TensorFlow version\n\n\nprint(\"Version: \", tf.__version__)\nprint(\"Eager mode: \", tf.executing_eagerly())\nprint(\"Hub version: \", hub.__version__)\nprint(\"GPU is\", \"available\" if tf.test.is_gpu_available() else \"NOT AVAILABLE\")\n\n\n_URL = \"https://github.com/AveyBD/rice-leaf-diseases-detection/raw/master/rice-leaf.zip\"\n\nzip_file = tf.keras.utils.get_file(origin=_URL,fname=\"rice-leaf.zip\",extract=True)\nprint(zip_file)\n# C:\\Users\\user1\\.keras\\datasets\\flower_photos.tgz\n\nprint(os.path.dirname(zip_file))\n\n# C:\\Users\\user1\\.keras\\datasets\n\ndata_dir = os.path.join(os.path.dirname(zip_file), 'rice')\n\n\n#data_dir = os.path.join(os.path.dirname(zip_file), '/content/rice')\ntrain_dir = os.path.join(data_dir, 'train')\nvalidation_dir = os.path.join(data_dir, 'validation')\n\n\n\ndef count(dir, counter=0):\n \"returns number of files in dir and subdirs\"\n for pack in os.walk(dir):\n for f in pack[2]:\n counter += 1\n return dir + \" : \" + str(counter) + \"files\"\n\nprint('total images for training :', count(train_dir))\nprint('total images for validation :', count(validation_dir))\n\nwith open('rice-leaf-diseases-detection/classes.json', 'r') as f:\n cat_to_name = json.load(f)\n classes = list(cat_to_name.values())\n\nprint(classes)\n\nmodule_selection = (\"inception_v3\", 299, 2048) #@param [\"(\\\"mobilenet_v2\\\", 224, 1280)\", \"(\\\"inception_v3\\\", 299, 2048)\"] {type:\"raw\", allow-input: true}\nhandle_base, pixels, FV_SIZE = module_selection\nMODULE_HANDLE =\"https://tfhub.dev/google/tf2-preview/{}/feature_vector/2\".format(handle_base)\nIMAGE_SIZE = (pixels, pixels)\nprint(\"Using {} with input size {} and output dimension {}\".format(\n MODULE_HANDLE, IMAGE_SIZE, FV_SIZE))\n\nBATCH_SIZE = 64 #@param {type:\"integer\"}\n\n# Inputs are suitably resized for the selected module. Dataset augmentation (i.e., random distortions of an image each time it is read) improves training, esp. when fine-tuning.\n\nvalidation_datagen = tf.keras.preprocessing.image.ImageDataGenerator(rescale=1./255)\nvalidation_generator = validation_datagen.flow_from_directory(\n validation_dir,\n shuffle=False,\n seed=42,\n color_mode=\"rgb\",\n class_mode=\"categorical\",\n target_size=IMAGE_SIZE,\n batch_size=BATCH_SIZE)\n\ndo_data_augmentation = True #@param {type:\"boolean\"}\nif do_data_augmentation:\n train_datagen = tf.keras.preprocessing.image.ImageDataGenerator(\n rescale = 1./255,\n rotation_range=40,\n horizontal_flip=True,\n width_shift_range=0.2,\n height_shift_range=0.2,\n shear_range=0.2,\n zoom_range=0.2,\n fill_mode='nearest' )\nelse:\n train_datagen = validation_datagen\n\ntrain_generator = train_datagen.flow_from_directory(\n train_dir,\n subset=\"training\",\n shuffle=True,\n seed=42,\n color_mode=\"rgb\",\n class_mode=\"categorical\",\n target_size=IMAGE_SIZE,\n batch_size=BATCH_SIZE)\n\nfeature_extractor = hub.KerasLayer(MODULE_HANDLE,\n input_shape=IMAGE_SIZE+(3,),\n output_shape=[FV_SIZE])\n\ndo_fine_tuning = False # @param {type:\"boolean\"}\n\nif do_fine_tuning:\n feature_extractor.trainable = True\n # unfreeze some layers of base network for fine-tuning\n for layer in base_model.layers[-30:]:\n layer.trainable = True\n\nelse:\n feature_extractor.trainable = False\n\n\nprint(\"Building model with\", MODULE_HANDLE)\n\nmodel = tf.keras.Sequential([\n feature_extractor,\n tf.keras.layers.Flatten(),\n tf.keras.layers.Dense(512, activation='relu'),\n tf.keras.layers.Dropout(rate=0.2),\n tf.keras.layers.Dense(train_generator.num_classes, activation='softmax',kernel_regularizer=tf.keras.regularizers.l2(0.0001))])\n#model.build((None,)+IMAGE_SIZE+(3,))\nprint(model.summary())\n\n\n#Compile model specifying the optimizer learning rate\n\nLEARNING_RATE = 0.001 #@param {type:\"number\"}\n\nmodel.compile(\n optimizer=tf.keras.optimizers.Adam(lr=LEARNING_RATE),\n loss='categorical_crossentropy',\n metrics=['accuracy'])\n\nEPOCHS=30 #@param {type:\"integer\"}\n\nhistory = model.fit_generator(\n train_generator,\n steps_per_epoch=train_generator.samples//train_generator.batch_size,\n epochs=EPOCHS,\n validation_data=validation_generator,\n validation_steps=validation_generator.samples//validation_generator.batch_size)\n\nimport matplotlib.pylab as plt\nimport numpy as np\n\nacc = history.history['accuracy']\nval_acc = history.history['val_accuracy']\n\nloss = history.history['loss']\nval_loss = history.history['val_loss']\n\nepochs_range = range(EPOCHS)\n\nplt.figure(figsize=(8, 8))\nplt.subplot(1, 2, 1)\nplt.plot(epochs_range, acc, label='Training Accuracy')\nplt.plot(epochs_range, val_acc, label='Validation Accuracy')\nplt.legend(loc='lower right')\nplt.title('Training and Validation Accuracy')\nplt.ylabel(\"Accuracy (training and validation)\")\nplt.xlabel(\"Training Steps\")\n\nplt.subplot(1, 2, 2)\nplt.plot(epochs_range, loss, label='Training Loss')\nplt.plot(epochs_range, val_loss, label='Validation Loss')\nplt.legend(loc='upper right')\nplt.title('Training and Validation Loss')\nplt.ylabel(\"Loss (training and validation)\")\nplt.xlabel(\"Training Steps\")\nplt.show()\n","repo_name":"Wathsalya/Plant-Diseases-Detecter","sub_path":"new.py","file_name":"new.py","file_ext":"py","file_size_in_byte":5677,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"28556512167","text":"import matplotlib.pyplot as pl\nimport numpy as np\n\ndata = np.loadtxt(\"run.csv\",delimiter=\",\",skiprows=1)\n\ntheta = data[:,0]\n\nF = data[:,1]\nFstd = data[:,2]\nF_median = data[:,3]\nF_lower = data[:,4]\nF_upper = data[:,5]\n\nt = data[:,6]\ntstd = data[:,7]\nt_median = data[:,8]\nt_lower = data[:,9]\nt_upper = data[:,10]\n\nfig, ax = pl.subplots(4,1,figsize=(3,8),sharex=True)\nax[0].plot(theta, F)\nax[1].plot(theta, F_median)\nax[0].fill_between(theta, F-Fstd, F+Fstd, edgecolor='None', alpha=0.3)\nax[1].fill_between(theta, F_lower, F_upper, edgecolor='None', alpha=0.3)\nax[0].set_ylabel('mean relative force')\nax[1].set_ylabel('median relative force')\n\nax[2].plot(theta, t)\nax[3].plot(theta, t_median)\nax[2].fill_between(theta, t-tstd, t+tstd, edgecolor='None', alpha=0.3)\nax[3].fill_between(theta, t_lower, t_upper, edgecolor='None', alpha=0.3)\n#ax[2].set_yscale('log')\n#ax[3].set_yscale('log')\nax[2].set_ylabel('mean time (ns)')\nax[3].set_ylabel('median time (ns)')\n#pl.ylim(0,2)\nax[3].set_xlabel('theta')\n\nfig.tight_layout()\n\nfig.savefig('accuracy_and_time.png')\n\n\npl.show()\n","repo_name":"benmaier/BarnesHutTree","sub_path":"05_theta_scan_statistics/plot_theta_scan.py","file_name":"plot_theta_scan.py","file_ext":"py","file_size_in_byte":1066,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"34158786944","text":"import numpy as np\r\nfrom scipy.spatial import distance\r\n\r\nTHRESHOLD_DISTANCE = 0.1\r\nobject_centroids = [[0.4, 0.6],[0.25, 0.25], [0.75,0.35]]\r\ninput_centroids = [[0.3, 0.3],[0.75,0.7],[0.5, 0.5],[0.75, 0.5]]\r\n\r\ndist = distance.cdist(object_centroids, input_centroids)\r\n(dist.min(axis = 1) < 0.1).argmax()\r\n# follow PyImageSearch's algorithm\r\n# if dist.min(axis=1)\r\nrows = dist.min(axis=1).argsort()\r\ncols = dist.argmin(axis=1)[rows]\r\nprint(dist)\r\nprint(rows)\r\nprint(cols)\r\n\r\n\r\n\r\n\r\n\r\n","repo_name":"lexuanhoang120/Face_Tracking","sub_path":"test/1.py","file_name":"1.py","file_ext":"py","file_size_in_byte":483,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"81"} +{"seq_id":"4957446131","text":"from utils import read_day, str_list, Vec2d\n\nparts = [part.split('=')[1] for part in str_list(read_day(17)[0].split(': ')[1])]\nmin_target = Vec2d(*(int(part.split('..')[0]) for part in parts))\nmax_target = Vec2d(*(int(part.split('..')[1]) for part in parts))\n\ndef part1():\n max_y = 0\n for x in range(1, 50):\n for y in range(-50, 200):\n is_hit, curr_y = hits_target(Vec2d(x, y))\n if is_hit:\n max_y = max(max_y, curr_y)\n return max_y\n\ndef hits_target(v):\n pos = Vec2d(0, 0)\n max_y = 0\n while True:\n pos, v = step(pos, v)\n max_y = max(max_y, pos.y)\n if pos.x >= min_target.x and pos.x <= max_target.x and pos.y >= min_target.y and pos.y <= max_target.y:\n return True, max_y\n if pos.x > max_target.x or pos.y < min_target.y and pos.y < 0:\n return False, max_y\n\ndef step(pos, v):\n pos += v\n if v.x > 0:\n v.x -= 1\n elif v.x < 0:\n v.x += 1\n v.y -= 1\n return pos, v\n\nprint(f'Part 1: {part1()}')\n\n\ndef part2():\n count = 0\n for x in range(1, 300):\n for y in range(-300, 300):\n hits, curr_max_y = hits_target(Vec2d(x, y))\n if hits:\n count += 1\n return count\n\nprint(f'Part 2: {part2()}')\n","repo_name":"justin-ardini/adventofcode2021","sub_path":"day17.py","file_name":"day17.py","file_ext":"py","file_size_in_byte":1158,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"14819260594","text":"country = input('Which country are you from ?')\n\nif country.lower() == 'pakistan':\n print('You must like cricket then!')\nelse:\n print('You are not a Pakistani then')\n\n\n\n\nprovince = input('What province do you live in: ')\ntax = 0\n\nif province == 'Alberta' or province == 'Nunavat':\n tax = 0.05\nelif province == 'Ontario':\n tax = 0.13\nelse:\n tax = 0.15\nprint('Your tax is: ' + str(tax) + '%') ","repo_name":"mtahaakhan/Intro-in-python","sub_path":"Python Practice/comparing_strings.py","file_name":"comparing_strings.py","file_ext":"py","file_size_in_byte":410,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"81"} +{"seq_id":"15219618767","text":"\nfrom django import template\nfrom django.template import TemplateSyntaxError, Node\nfrom django.contrib.sites import models as sites_models\nimport re\nfrom django.template.base import FilterExpression\nfrom django.utils.encoding import smart_str\nfrom .. import mh_reverse\nfrom .. import models\n\n\nclass MHReverseNode(Node):\n def __init__(self, view_name, site, args, kwargs, as_var):\n self.view_name = view_name\n self.args = args\n self.site = site\n self.as_var = as_var\n self.kwargs = kwargs\n\n def render(self, context):\n args = [arg.resolve(context) for arg in self.args]\n view = self.view_name.resolve(context)\n if isinstance(self.site, FilterExpression):\n site = self.site.resolve(context)\n else:\n site = self.site\n site = site or None # avoid '' values\n if isinstance(site, basestring) or isinstance(site, unicode):\n site = sites_models.Site.objects.get(name=site)\n site = models.Site.objects.get(site__exact=site)\n\n kwargs = dict([(smart_str(k,'ascii'), v.resolve(context))\n for k, v in self.kwargs.items()])\n is_external = False\n for k, v in kwargs.items():\n if k == \"is_external\":\n is_external = v\n del kwargs[k]\n break\n \n url = mh_reverse(view, site, is_external, args, kwargs)\n\n if self.as_var:\n context[self.as_var] = url\n return ''\n else:\n return url \n#class MHReverseNode\n\n__kwarg_re = re.compile(r\"(?:(\\w+)=)?(.+)\")\n\n\ndef mh_reverse_tag(parser, token):\n bits = token.split_contents()\n if len(bits) < 3:\n raise TemplateSyntaxError(\"'%s' takes at least two argument\"\n \" (path to a view) (site)\" % bits[0])\n viewname = parser.compile_filter(bits[1])\n site = bits[2]\n if site.startswith('site='):\n site = site[5:]\n if site.startswith('\\'') or site.startswith('\"'):\n site = site[1:-1]\n else:\n site = parser.compile_filter(site)\n args = []\n kwargs = {}\n as_var = None\n bits = bits[3:]\n if len(bits) >= 3 and bits[-2] == 'as':\n as_var = bits[-1]\n bits = bits[:-2]\n\n # Backwards compatibility: check for the old comma separated format\n # {% url urlname arg1,arg2 %}\n # Initial check - that the first space separated bit has a comma in it\n if bits and ',' in bits[0]:\n check_old_format = True\n # In order to *really* be old format, there must be a comma\n # in *every* space separated bit, except the last.\n for bit in bits[1:-1]:\n if ',' not in bit:\n # No comma in this bit. Either the comma we found\n # in bit 1 was a false positive (e.g., comma in a string),\n # or there is a syntax problem with missing commas\n check_old_format = False\n break\n else:\n # No comma found - must be new format.\n check_old_format = False\n\n if check_old_format:\n # Confirm that this is old format by trying to parse the first\n # argument. An exception will be raised if the comma is\n # unexpected (i.e. outside of a static string).\n match = __kwarg_re.match(bits[0])\n if match:\n value = match.groups()[1]\n try:\n parser.compile_filter(value)\n except TemplateSyntaxError:\n bits = ''.join(bits).split(',')\n\n # Now all the bits are parsed into new format,\n # process them as template vars\n if len(bits):\n for bit in bits:\n match = __kwarg_re.match(bit)\n if not match:\n raise TemplateSyntaxError(\"Malformed arguments to url tag\")\n name, value = match.groups()\n if name:\n kwargs[name] = parser.compile_filter(value)\n else:\n args.append(parser.compile_filter(value))\n\n return MHReverseNode(viewname, site, args, kwargs, as_var)\n\nregister = template.Library()\nregister.tag(compile_function=mh_reverse_tag, name='mh_reverse')\n","repo_name":"andriygArchive/django-multihost","sub_path":"gu_multihost/templatetags/multihost.py","file_name":"multihost.py","file_ext":"py","file_size_in_byte":4157,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"4848100494","text":"import numpy as np\nimport sim_tools.sim as sim\nimport sim_tools.media_export as export\nimport copy\n\n#model imports\nfrom models import LennardJones as lj\nfrom models import Boids as bo\nfrom models import PFSM\nfrom models import Dance\nfrom models import SteerControl as sc\nfrom models import linearSuperSet as lss\nfrom models.featureCombo import FeatureCombo as fc\n\n#feature imports\nfrom features.features import *\n\n#all parameters for simulation\nparams = sim.SimParams(\n num_agents=40, \n dt=0.01, \n overall_time = 20, \n enclosure_size = 15, \n init_pos_max= None, #if None, then defaults to enclosure_size\n agent_max_vel=7,\n init_vel_max = None,\n agent_max_accel=np.inf,\n agent_max_turn_rate=np.inf,\n neighbor_radius=3,\n periodic_boundary=False\n )\n\nif __name__ == '__main__':\n #define list of controllers\n features = [\n Cohesion(), # on their own, seems tigther and less spread\n Alignment(), # good\n SeparationInv2(),\n SteerToAvoid(params.neighbor_radius/4,params.neighbor_radius), \n Rotation()\n ]\n orig = fc([5,5,5,5,5],features)\n # orig = lss.SuperSet(1,1,0,3,0)\n controllers= [copy.deepcopy(orig) for i in range(params.num_agents)]\n\n #if you want to do coloring by agent\n for controller in controllers:\n # vals = np.random.uniform(0,1,3)*255\n # controller.setColor(\"rgb(\"+str(int(vals[0]))+\",\"+str(int(vals[1]))+\",\"+str(int(vals[2]))+\")\")\n controller.setColor(\"blue\")\n\n\n agentPositions, agentVels = sim.runSim(controllers,params,progress_bar=True)\n print(\"Sim finished -- Generating media\")\n\n #export types, NONE, INTERACTIVE, GIF, MP4\n media_type = export.ExportType.GIF\n\n export.export(media_type,\"new\",agentPositions,agentVels,controllers=controllers,params=params,vision_mode=False,progress_bar=True)\n print(\"Media generated\")\n","repo_name":"wvu-robotics/REU_MatlabSim","sub_path":"matlab/REU_2022/Topic_1_ Imitating_Swarms/SwarmSimClassSeparationPy/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1867,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"81"} +{"seq_id":"203592058","text":"# valueIterationAgents.py\n# -----------------------\n# Licensing Information: You are free to use or extend these projects for\n# educational purposes provided that (1) you do not distribute or publish\n# solutions, (2) you retain this notice, and (3) you provide clear\n# attribution to UC Berkeley, including a link to http://ai.berkeley.edu.\n# \n# Attribution Information: The Pacman AI projects were developed at UC Berkeley.\n# The core projects and autograders were primarily created by John DeNero\n# (denero@cs.berkeley.edu) and Dan Klein (klein@cs.berkeley.edu).\n# Student side autograding was added by Brad Miller, Nick Hay, and\n# Pieter Abbeel (pabbeel@cs.berkeley.edu).\n\n\n# valueIterationAgents.py\n# -----------------------\n# Licensing Information: You are free to use or extend these projects for\n# educational purposes provided that (1) you do not distribute or publish\n# solutions, (2) you retain this notice, and (3) you provide clear\n# attribution to UC Berkeley, including a link to http://ai.berkeley.edu.\n# \n# Attribution Information: The Pacman AI projects were developed at UC Berkeley.\n# The core projects and autograders were primarily created by John DeNero\n# (denero@cs.berkeley.edu) and Dan Klein (klein@cs.berkeley.edu).\n# Student side autograding was added by Brad Miller, Nick Hay, and\n# Pieter Abbeel (pabbeel@cs.berkeley.edu).\n\n\nimport mdp, util\n\nfrom learningAgents import ValueEstimationAgent\nimport collections\n\nclass ValueIterationAgent(ValueEstimationAgent):\n \"\"\"\n * Please read learningAgents.py before reading this.*\n\n A ValueIterationAgent takes a Markov decision process\n (see mdp.py) on initialization and runs value iteration\n for a given number of iterations using the supplied\n discount factor.\n \"\"\"\n def __init__(self, mdp, discount = 0.9, iterations = 100):\n \"\"\"\n Your value iteration agent should take an mdp on\n construction, run the indicated number of iterations\n and then act according to the resulting policy.\n\n Some useful mdp methods you will use:\n mdp.getStates()\n mdp.getPossibleActions(state)\n mdp.getTransitionStatesAndProbs(state, action)\n mdp.getReward(state, action, new_state)\n mdp.isTerminal(state)\n \"\"\"\n self.mdp = mdp\n self.discount = discount\n self.iterations = iterations\n self.values = util.Counter() # A Counter is a dict with default 0\n self.runValueIteration()\n\n def runValueIteration(self):\n # Write value iteration code here\n \"*** YOUR CODE HERE ***\"\n for i in range(self.iterations):\n self.iterations -= 1\n state_lst = util.Counter() # store new value of a state\n new_state_lst = util.Counter() # store whether a state has been updated\n for state in self.mdp.getStates():\n action_lowest = self.computeActionFromValues(state)\n if action_lowest:\n new_value = self.computeQValueFromValues(state, action_lowest)\n state_lst[state] = new_value\n new_state_lst[state] = 1\n for state in self.mdp.getStates():\n if new_state_lst[state]:\n self.values[state] = state_lst[state]\n\n\n def getValue(self, state):\n \"\"\"\n Return the value of the state (computed in __init__).\n \"\"\"\n return self.values[state]\n\n\n def computeQValueFromValues(self, state, action):\n \"\"\"\n Compute the Q-value of action in state from the\n value function stored in self.values.\n \"\"\"\n answer = 0\n\n state_prob = self.mdp.getTransitionStatesAndProbs(state, action)\n for new_state, prob in state_prob:\n reward = self.mdp.getReward(state, action, new_state)\n answer += prob * (reward + (self.discount * self.getValue(new_state)))\n return answer\n # page 6 Q-learnnig. compute q* with given v*\n\n def computeActionFromValues(self, state):\n \"\"\"\n The policy is the best action in the given state\n according to the values old_valently stored in self.values.\n You may break ties any way you see fit. Note that if\n there are no legal actions, which is the case at the\n terminal state, you should return None.\n \"\"\"\n bestAct = None\n reward_best = - float ('inf')\n for action in self.mdp.getPossibleActions(state):\n qvalue = self.computeQValueFromValues(state, action)\n if qvalue > reward_best:\n reward_best = qvalue\n bestAct = action\n return bestAct\n\n\n def getPolicy(self, state):\n return self.computeActionFromValues(state)\n\n def getAction(self, state):\n \"Returns the policy at the state (no exploration).\"\n return self.computeActionFromValues(state)\n\n def getQValue(self, state, action):\n return self.computeQValueFromValues(state, action)\n\nclass AsynchronousValueIterationAgent(ValueIterationAgent):\n \"\"\"\n * Please read learningAgents.py before reading this.*\n\n An AsynchronousValueIterationAgent takes a Markov decision process\n (see mdp.py) on initialization and runs cyclic value iteration\n for a given number of iterations using the supplied\n discount factor.\n \"\"\"\n def __init__(self, mdp, discount = 0.9, iterations = 1000):\n \"\"\"\n Your cyclic value iteration agent should take an mdp on\n construction, run the indicated number of iterations,\n and then act according to the resulting policy. Each iteration\n updates the value of only one state, which cycles through\n the total_states list. If the chosen state is terminal, nothing\n happens in that iteration.\n\n Some useful mdp methods you will use:\n mdp.getStates()\n mdp.getPossibleActions(state)\n mdp.getTransitionStatesAndProbs(state, action)\n mdp.getReward(state)\n mdp.isTerminal(state)\n \"\"\"\n ValueIterationAgent.__init__(self, mdp, discount, iterations)\n\n\n def runValueIteration(self):\n total_states_all = self.mdp.getStates()\n length = len(total_states_all)\n count = 0\n for i in range(self.iterations):\n self.iterations -= 1\n state_lst = total_states_all[count%length]\n count += 1\n action_lowest = self.computeActionFromValues(state_lst)\n if action_lowest:\n self.values[state_lst] = self.computeQValueFromValues(state_lst, action_lowest)\n\nclass PrioritizedSweepingValueIterationAgent(AsynchronousValueIterationAgent):\n \"\"\"\n * Please read learningAgents.py before reading this.*\n A PrioritizedSweepingValueIterationAgent takes a Markov decision process\n (see mdp.py) on initialization and runs prioritized sweeping value iteration\n for a given number of iterations using the supplied parameters.\n \"\"\"\n def __init__(self, mdp, discount = 0.9, iterations = 100, theta = 1e-5):\n \"\"\"\n Your prioritized sweeping value iteration agent should take an mdp on\n construction, run the indicated number of iterations,\n and then act according to the resulting policy.\n \"\"\"\n self.theta = theta\n ValueIterationAgent.__init__(self, mdp, discount, iterations)\n\n def runValueIteration(self):\n \"*** YOUR CODE HERE ***\"\n lst_pre = {}\n total_states = self.mdp.getStates()\n\n for state in total_states:\n if not self.mdp.isTerminal(state):\n for action in self.mdp.getPossibleActions(state):\n for new_state, probs in self.mdp.getTransitionStatesAndProbs(state, action):\n if new_state in lst_pre:\n lst_pre[new_state].add(state)\n else:\n lst_pre[new_state] = {state}\n priorityQueue = util.PriorityQueue()\n for state in total_states:\n if not self.mdp.isTerminal(state):\n val_lst = []\n old_val = float(\"-inf\")\n for action in self.mdp.getPossibleActions(state):\n qVal = self.computeQValueFromValues(state, action)\n if qVal > old_val:\n old_val = qVal\n val_lst.append(qVal)\n diff = abs(self.values[state] - old_val)\n priorityQueue.update(state, - diff)\n\n def get_Q_val(state):\n return max(self.getQValue(state, a) for a in self.mdp.getPossibleActions(state))\n \n\n for i in range(self.iterations):\n if priorityQueue.isEmpty():\n break\n \n state = priorityQueue.pop()\n if not self.mdp.isTerminal(state):\n best_action = get_Q_val(state)\n self.values[state] = best_action\n\n for p in lst_pre[state]:\n best_action = get_Q_val(p)\n diff = abs(self.values[p] - best_action)\n if diff > self.theta:\n priorityQueue.update(p, -diff)\n","repo_name":"ypeng12/AI_CMSC421","sub_path":"Project3/valueIterationAgents.py","file_name":"valueIterationAgents.py","file_ext":"py","file_size_in_byte":9296,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"74885906186","text":"# File: getters/epc_data.py\n\"\"\"Extracting and loading the EPC data.\"\"\"\n\n# ---------------------------------------------------------------------------------\n\nimport os\nimport re\nimport pandas as pd\nimport numpy as np\nfrom zipfile import ZipFile\n\n\nfrom heat_pump_adoption_modelling import PROJECT_DIR, get_yaml_config, Path\n\n# ---------------------------------------------------------------------------------\n\n# Load config file\nconfig = get_yaml_config(\n Path(str(PROJECT_DIR) + \"/heat_pump_adoption_modelling/config/base.yaml\")\n)\n\n# Get paths\nRAW_ENG_WALES_DATA_PATH = str(PROJECT_DIR) + config[\"RAW_ENG_WALES_DATA_PATH\"]\nRAW_SCOTLAND_DATA_PATH = str(PROJECT_DIR) + config[\"RAW_SCOTLAND_DATA_PATH\"]\n\nRAW_ENG_WALES_DATA_ZIP = str(PROJECT_DIR) + config[\"RAW_ENG_WALES_DATA_ZIP\"]\nRAW_SCOTLAND_DATA_ZIP = str(PROJECT_DIR) + config[\"RAW_SCOTLAND_DATA_ZIP\"]\n\nRAW_EPC_DATA_PATH = str(PROJECT_DIR) + config[\"RAW_EPC_DATA_PATH\"]\n\n\ndef extract_data(file_path):\n \"\"\"Extract data from zip file.\n\n Parameters\n ----------\n file_path : str\n Path to the file to unzip.\n\n Return: None\"\"\"\n\n # Check whether file exists\n if not Path(file_path).is_file():\n raise IOError(\"The file '{}' does not exist.\".format(file_path))\n\n # Get directory\n zip_dir = os.path.dirname(file_path) + \"/\"\n\n # Unzip the data\n with ZipFile(file_path, \"r\") as zip:\n\n print(\"Extracting...\\n{}\".format(zip.filename))\n zip.extractall(zip_dir)\n print(\"Done!\")\n\n\ndef load_wales_certificates(subset=None, usecols=None, nrows=None, low_memory=False):\n\n \"\"\"Load the England and/or Wales EPC data.\n\n Parameters\n ----------\n subset : {'England', 'Wales', None}, default=None\n EPC certificate area subset.\n If None, then the data for both England and Wales will be loaded.\n\n usecols : list, default=None\n List of features/columns to load from EPC dataset.\n If None, then all features will be loaded.\n\n nrows : int, default=None\n Number of rows of file to read.\n\n low_memory : bool, default=False\n Internally process the file in chunks, resulting in lower memory use while parsing,\n but possibly mixed type inference.\n To ensure no mixed types either set False, or specify the type with the dtype parameter.\n\n Return\n ---------\n EPC_certs : pandas.DateFrame\n England/Wales EPC certificate data for given features.\"\"\"\n\n # If sample file does not exist (probably just not unzipped), unzip the data\n if not Path(\n RAW_ENG_WALES_DATA_PATH + \"domestic-W06000015-Cardiff/certificates.csv\"\n ).is_file():\n extract_data(RAW_ENG_WALES_DATA_ZIP)\n\n # Get all directories\n directories = [\n dir\n for dir in os.listdir(RAW_ENG_WALES_DATA_PATH)\n if not (dir.startswith(\".\") or dir.endswith(\".txt\") or dir.endswith(\".zip\"))\n ]\n\n # Set subset dict to select respective subset directories\n start_with_dict = {\"Wales\": \"domestic-W\", \"England\": \"domestic-E\"}\n\n # Get directories for given subset\n if subset in start_with_dict:\n directories = [\n dir for dir in directories if dir.startswith(start_with_dict[subset])\n ]\n\n # Load EPC certificates for given subset\n # Only load columns of interest (if given)\n epc_certs = [\n pd.read_csv(\n RAW_ENG_WALES_DATA_PATH + directory + \"/recommendations.csv\",\n low_memory=low_memory,\n usecols=usecols,\n nrows=nrows,\n )\n for directory in directories\n ]\n\n # Concatenate single dataframes into dataframe\n epc_certs = pd.concat(epc_certs, axis=0)\n epc_certs[\"COUNTRY\"] = subset\n\n return epc_certs\n\n\ndef load_scotland_data(usecols=None, nrows=None, low_memory=False):\n \"\"\"Load the Scotland EPC data.\n\n Parameters\n ----------\n usecols : list, default=None\n List of features/columns to load from EPC dataset.\n If None, then all features will be loaded.\n\n nrows : int, default=None\n Number of rows of file to read.\n\n low_memory : bool, default=False\n Internally process the file in chunks, resulting in lower memory use while parsing,\n but possibly mixed type inference.\n To ensure no mixed types either set False, or specify the type with the dtype parameter.\n\n Return\n ---------\n EPC_certs : pandas.DateFrame\n Scotland EPC certificate data for given features.\"\"\"\n\n # If sample file does not exist (probably just not unzipped), unzip the data\n if not [\n file\n for file in os.listdir(RAW_SCOTLAND_DATA_PATH)\n if file.startswith(\"D_EPC_data_2012_Q4_extract\")\n ]:\n extract_data(RAW_SCOTLAND_DATA_ZIP)\n\n if usecols is not None:\n # Fix columns (\"WALLS\" features are labeled differently here)\n usecols = [re.sub(\"WALLS_\", \"WALL_\", col) for col in usecols]\n usecols = [re.sub(\"POSTTOWN\", \"POST_TOWN\", col) for col in usecols]\n usecols = [col for col in usecols if col not in [\"UPRN\"]]\n\n # Get all directories\n all_directories = os.listdir(RAW_SCOTLAND_DATA_PATH)\n directories = [file for file in all_directories if file.endswith(\".csv\")]\n\n epc_certs = [\n pd.read_csv(\n RAW_SCOTLAND_DATA_PATH + file,\n low_memory=low_memory,\n usecols=usecols,\n nrows=nrows,\n skiprows=1, # don't load first row (more ellaborate feature names),\n encoding=\"ISO-8859-1\",\n )\n for file in directories\n ]\n\n # Concatenate single dataframes into dataframe\n epc_certs = pd.concat(epc_certs, axis=0)\n epc_certs[\"COUNTRY\"] = \"Scotland\"\n\n epc_certs = epc_certs.rename(\n columns={\n \"WALL_ENV_EFF\": \"WALLS_ENV_EFF\",\n \"WALL_ENERGY_EFF\": \"WALLS_ENERGY_EFF\",\n \"POST_TOWN\": \"POSTTOWN\",\n }\n )\n usecols = [col for col in usecols if col not in [\"UPRN\"]]\n\n return epc_certs\n\n\ndef load_wales_england_data(subset=None, usecols=None, nrows=None, low_memory=False):\n \"\"\"Load the England and/or Wales EPC data.\n\n Parameters\n ----------\n subset : {'England', 'Wales', None}, default=None\n EPC certificate area subset.\n If None, then the data for both England and Wales will be loaded.\n\n usecols : list, default=None\n List of features/columns to load from EPC dataset.\n If None, then all features will be loaded.\n\n nrows : int, default=None\n Number of rows of file to read.\n\n low_memory : bool, default=False\n Internally process the file in chunks, resulting in lower memory use while parsing,\n but possibly mixed type inference.\n To ensure no mixed types either set False, or specify the type with the dtype parameter.\n\n Return\n ---------\n EPC_certs : pandas.DateFrame\n England/Wales EPC certificate data for given features.\"\"\"\n\n # If sample file does not exist (probably just not unzipped), unzip the data\n if not Path(\n RAW_ENG_WALES_DATA_PATH + \"domestic-W06000015-Cardiff/certificates.csv\"\n ).is_file():\n extract_data(RAW_ENG_WALES_DATA_ZIP)\n\n # Get all directories\n directories = [\n dir\n for dir in os.listdir(RAW_ENG_WALES_DATA_PATH)\n if not (dir.startswith(\".\") or dir.endswith(\".txt\") or dir.endswith(\".zip\"))\n ]\n\n # Set subset dict to select respective subset directories\n start_with_dict = {\"Wales\": \"domestic-W\", \"England\": \"domestic-E\"}\n\n # Get directories for given subset\n if subset in start_with_dict:\n directories = [\n dir for dir in directories if dir.startswith(start_with_dict[subset])\n ]\n\n # Load EPC certificates for given subset\n # Only load columns of interest (if given)\n epc_certs = [\n pd.read_csv(\n RAW_ENG_WALES_DATA_PATH + directory + \"/certificates.csv\",\n low_memory=low_memory,\n usecols=usecols,\n nrows=nrows,\n )\n for directory in directories\n ]\n\n # Concatenate single dataframes into dataframe\n epc_certs = pd.concat(epc_certs, axis=0)\n epc_certs[\"COUNTRY\"] = subset\n\n epc_certs[\"UPRN\"].fillna(epc_certs.BUILDING_REFERENCE_NUMBER, inplace=True)\n\n return epc_certs\n\n\ndef load_raw_epc_data(subset=\"GB\", usecols=None, nrows=None, low_memory=False):\n \"\"\"Load and return EPC dataset, or specific subset, as pandas dataframe.\n\n Parameters\n ----------\n subset : {'GB', 'Wales', 'England', 'Scotland', None}, default='GB'\n EPC certificate area subset.\n\n usecols : list, default=None\n List of features/columns to load from EPC dataset.\n If None, then all features will be loaded.\n\n nrows : int, default=None\n Number of rows of file to read.\n\n low_memory : bool, default=False\n Internally process the file in chunks, resulting in lower memory use while parsing,\n but possibly mixed type inference.\n To ensure no mixed types either set False, or specify the type with the dtype parameter.\n\n Return\n ---------\n EPC_certs : pandas.DateFrame\n EPC certificate data for given area and features.\"\"\"\n\n all_epc_df = []\n\n # Get Scotland data\n if subset in [\"Scotland\", \"GB\"]:\n epc_Scotland_df = load_scotland_data(usecols=usecols, nrows=nrows)\n all_epc_df.append(epc_Scotland_df)\n\n if subset == \"Scotland\":\n return epc_Scotland_df\n\n # Get the Wales/England data\n if subset in [\"Wales\", \"England\"]:\n epc_df = load_wales_england_data(\n subset, usecols=usecols, nrows=nrows, low_memory=low_memory\n )\n return epc_df\n\n # Merge the two datasets for GB\n elif subset == \"GB\":\n\n for country in [\"Wales\", \"England\"]:\n\n epc_df = load_wales_england_data(\n country, usecols=usecols, nrows=nrows, low_memory=low_memory\n )\n all_epc_df.append(epc_df)\n\n epc_df = pd.concat(all_epc_df, axis=0)\n\n return epc_df\n\n else:\n raise IOError(\"'{}' is not a valid subset of the EPC dataset.\".format(subset))\n\n\ndef load_cleansed_epc(remove_duplicates=True, usecols=None, nrows=None):\n \"\"\"Load the cleansed EPC dataset (provided by EST)\n with the option of excluding/including duplicates.\n\n Parameters\n ----------\n remove_duplicates : bool, default=True.\n Whether or not to remove duplicates.\n\n usecols : list, default=None\n List of features/columns to load from EPC dataset.\n If None, then all features will be loaded.\n\n nrows : int, default=None\n Number of rows of file to read.\n\n Return\n ----------\n cleansed_epc : pandas.DataFrame\n Cleansed EPC datast as dataframe.\"\"\"\n\n if remove_duplicates:\n file_path = str(PROJECT_DIR) + config[\"EST_CLEANSED_EPC_DATA_DEDUPL_PATH\"]\n else:\n file_path = str(PROJECT_DIR) + config[\"EST_CLEANSED_EPC_DATA_PATH\"]\n\n # If file does not exist (probably just not unzipped), unzip the data\n if not Path(file_path).is_file():\n extract_data(file_path + \".zip\")\n\n print(\"Loading cleansed EPC data... This will take a moment.\")\n cleansed_epc = pd.read_csv(\n file_path, usecols=usecols, nrows=nrows, low_memory=False\n )\n\n # Drop first column\n if \"Unnamed: 0\" in cleansed_epc.columns:\n cleansed_epc = cleansed_epc.drop(columns=\"Unnamed: 0\")\n\n # Add HP feature\n cleansed_epc[\"HEAT_PUMP\"] = cleansed_epc.FINAL_HEATING_SYSTEM == \"Heat pump\"\n print(\"Done!\")\n\n return cleansed_epc\n\n\ndef load_preprocessed_epc_data(\n version=\"preprocessed_dedupl\",\n usecols=None,\n nrows=None,\n snapshot_data=False,\n dtype={},\n low_memory=False,\n):\n \"\"\"Load the EPC dataset including England, Wales and Scotland.\n Select one of the following versions:\n\n - raw:\n EPC data merged for all countries but otherwise not altered\n\n - preprocessed:\n Partially cleaned and with additional features\n\n - preprocessed_dedupl:\n Same as 'preprocessed' but without duplicates\n\n Parameters\n ----------\n version : str, {'raw', 'preprocessed', 'preprocessed_dedupl'}, default='preprocessed_dedupl'\n The version of the EPC data to load.\n\n usecols : list, default=None\n List of features/columns to load from EPC dataset.\n If None, then all features will be loaded.\n\n nrows : int, default=None\n Number of rows of file to read.\n\n snapshot_data : bool, default=False\n If True, load the snapshot version of the preprocessed EPC data saved in /inputs\n instead of the most recent version in /outputs.\n\n low_memory : bool, default=False\n Internally process the file in chunks, resulting in lower memory use while parsing,\n but possibly mixed type inference.\n To ensure no mixed types either set False, or specify the type with the dtype parameter.\n\n Return\n ----------\n epc_df : pandas.DataFrame\n EPC data in the given version.\"\"\"\n\n version_path_dict = {\n \"raw\": \"RAW_EPC_DATA_PATH\",\n \"preprocessed_dedupl\": \"PREPROC_EPC_DATA_DEDUPL_PATH\",\n \"preprocessed\": \"PREPROC_EPC_DATA_PATH\",\n }\n\n # Get the respective file path for version\n file_path = str(PROJECT_DIR) + config[version_path_dict[version]]\n\n if snapshot_data:\n file_path = str(PROJECT_DIR) + config[\"SNAPSHOT_\" + version_path_dict[version]]\n\n # If file does not exist (likely just not unzipped), unzip the data\n if not Path(file_path).is_file():\n extract_data(file_path + \".zip\")\n\n # Load data\n epc_df = pd.read_csv(\n file_path,\n usecols=usecols,\n nrows=nrows,\n dtype=dtype,\n ) # , low_memory=low_memory)\n\n for col in config[\"parse_dates\"]:\n if col in epc_df.columns:\n epc_df[col] = pd.to_datetime(epc_df[col])\n\n return epc_df\n\n\ndef get_epc_sample(full_df, sample_size):\n \"\"\"Randomly sample a subset of the full data.\n\n Parameters\n ----------\n full_df : pandas.DataFrame\n Full dataframe from which to extract a subset.\n\n sample_size: int\n Size of subset / number of samples.\n\n Return\n ----------\n sample_df : pandas.DataFrame\n Randomly sampled subset of full dataframe.\"\"\"\n\n rand_ints = np.random.choice(len(full_df), size=sample_size)\n sample_df = full_df.iloc[rand_ints]\n\n return sample_df\n\n\ndef main():\n \"\"\"Main function for testing.\"\"\"\n\n\nif __name__ == \"__main__\":\n # Execute only if run as a script\n main()\n","repo_name":"nestauk/heat_pump_adoption_modelling","sub_path":"heat_pump_adoption_modelling/getters/epc_data.py","file_name":"epc_data.py","file_ext":"py","file_size_in_byte":14492,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"34479195456","text":"user_input = int(input(\"Enter a number: \"))\nnumerator = 1\nresult = 0\ntotal2 = 0\nfor i in range(1, user_input):\n total = 1\n for j in range(1, i):\n total *= j\n\n result = numerator / total\n total2 += result\n\nprint(1 + total2)\n\n","repo_name":"everybees/python_with_cohorts","sub_path":"nine/jacinta_esther/chapter3/mathematical_constant_e.py","file_name":"mathematical_constant_e.py","file_ext":"py","file_size_in_byte":244,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"81"} +{"seq_id":"70752404426","text":"\"\"\"Train\nUsage:\n train.py [options] \n train.py (-h | --help )\n\nArguments:\n Path to the yaml hyper-parameter file\n\nOptions:\n -h --help Show this screen.\n -d --devices Comma seperated GPU devices [default: 0]\n -i --identifier Folder identifier [default: default-lr]\n\"\"\"\n# --->python train.py -d 0 -i mpeg7 config/mpeg7.yaml\nimport os\nimport pprint\nimport random\nimport shutil\nimport os.path as osp\nimport datetime\n\nimport numpy as np\nimport torch\nfrom docopt import docopt\nimport py\nfrom py.config import C,M\nfrom py.lr_schedulers import init_lr_scheduler\nfrom py.trainer import Trainer\nfrom dataset import SCDataset,collate,collate1\nfrom model import scTransformer\n\ndef get_outdir(identifier):\n # load config\n name = str(datetime.datetime.now().strftime(\"%y%m%d-%H%M%S\"))\n name += \"-%s\" % identifier\n outdir = osp.join(osp.expanduser(C.io.logdir), name)\n if not osp.exists(outdir):\n os.makedirs(outdir)\n C.io.resume_from = outdir\n C.to_yaml(osp.join(outdir, \"config.yaml\"))\n return outdir\n\ndef build_model():\n model=scTransformer(\n num_classes=M.num_classes,\n heads=M.heads,\n # layers=M.layers,\n depth=M.depth,\n mlp_dim=M.mlp_dim,\n pool=M.pool,\n dropout=M.dropout,\n emb_dropout=M.emb_dropout,\n dist=M.dist,\n dim=M.dim\n )\n\n # model = model.to(device)\n model=model.cuda()\n # model = DataParallel(model).cuda()\n if C.io.model_initialize_file:\n checkpoint = torch.load(C.io.model_initialize_file)\n model.load_state_dict(checkpoint[\"model_state_dict\"], False)\n del checkpoint\n print('=> loading model from {}'.format(C.io.model_initialize_file))\n\n print(\"Finished constructing model!\")\n return model\n\ndef main():\n args = docopt(__doc__)\n config_file = args[\"\"]\n C.update(C.from_yaml(filename=config_file))\n M.update(C.model)\n pprint.pprint(C, indent=4)\n resume_from = C.io.resume_from\n\n random.seed(0)\n np.random.seed(0)\n torch.manual_seed(0)\n\n device_name = \"cpu\"\n os.environ[\"CUDA_VISIBLE_DEVICES\"] = args[\"--devices\"]\n if torch.cuda.is_available():\n device_name = \"cuda\"\n torch.backends.cudnn.deterministic = True\n torch.cuda.manual_seed(0)\n print(\"Let's use\", torch.cuda.device_count(), \"GPU(s)!\")\n else:\n print(\"CUDA is not available\")\n device = torch.device(device_name)\n\n # 1. dataset\n if M.dist is False:\n kwargs = {\n # \"batch_size\": M.batch_size,\n \"collate_fn\": collate,\n \"num_workers\": C.io.num_workers,\n \"pin_memory\": True,\n }\n else:\n kwargs = {\n # \"batch_size\": M.batch_size,\n \"collate_fn\": collate1,\n \"num_workers\": C.io.num_workers,\n \"pin_memory\": True,\n }\n\n dataname = C.io.dataname\n train_loader = torch.utils.data.DataLoader(\n SCDataset(dataset=dataname, split=\"train\",class_num=M.num_classes,dist=M.dist), batch_size=M.batch_size, shuffle=True,\n drop_last=True, **kwargs\n )\n val_loader = torch.utils.data.DataLoader(\n SCDataset(dataset=dataname, split=\"val\",class_num=M.num_classes,dist=M.dist), batch_size=M.eval_batch_size, **kwargs\n )\n epoch_size = len(train_loader)\n\n # 2. model\n model = build_model()\n\n # 3. optimizer\n if C.optim.name == \"Adam\":\n optim = torch.optim.Adam(\n model.parameters(),\n lr=C.optim.lr,\n weight_decay=C.optim.weight_decay,\n amsgrad=C.optim.amsgrad,\n betas=(0.9, 0.98),\n eps=1e-09\n )\n else:\n raise NotImplementedError\n\n outdir = get_outdir(args[\"--identifier\"])\n print(\"outdir:\", outdir)\n\n iteration = 0\n epoch = 0\n best_mean_loss = 1e1000\n if resume_from:\n ckpt_pth = osp.join(resume_from, \"checkpoint_lastest.pth.tar\")\n checkpoint = torch.load(ckpt_pth)\n iteration = checkpoint[\"iteration\"]\n epoch = iteration // epoch_size\n best_mean_loss = checkpoint[\"best_mean_loss\"]\n print(f\"loading {epoch}-th ckpt: {ckpt_pth}\")\n\n model.load_state_dict(checkpoint[\"model_state_dict\"])\n optim.load_state_dict(checkpoint[\"optim_state_dict\"])\n\n lr_scheduler = init_lr_scheduler(\n optim, C.optim.lr_scheduler,\n stepsize=C.optim.lr_decay_epoch,\n max_epoch=C.optim.max_epoch,\n last_epoch=iteration // epoch_size\n )\n lr_scheduler.load_state_dict(checkpoint['lr_scheduler'])\n del checkpoint\n\n else:\n lr_scheduler = init_lr_scheduler(\n optim,\n C.optim.lr_scheduler,\n stepsize=C.optim.lr_decay_epoch,\n max_epoch=C.optim.max_epoch\n )\n\n trainer = Trainer(\n device=device,\n model=model,\n optimizer=optim,\n lr_scheduler=lr_scheduler,\n train_loader=train_loader,\n val_loader=val_loader,\n out=outdir,\n iteration=iteration,\n epoch=epoch,\n bml=best_mean_loss,\n dist=M.dist\n )\n\n\n trainer.train()\n\nif __name__ == \"__main__\":\n # print(git_hash())\n main()","repo_name":"chenyuyuyu/A-rotation-robust-shape-transformer-for-cartoon-character-recognition","sub_path":"transformer/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":5287,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"42132059841","text":"# Find the minimum difference between two nodes in the binary search tree\n\nclass TreeNode:\n def __init__(self, val):\n self.val = val\n self.left = None\n self.right = None\n\n\nclass Solution:\n\n def findMinDifference(self, root):\n res = []\n\n def inorder(node):\n if not node:\n return\n\n inorder(node.left)\n res.append(node.val)\n inorder(node.right)\n inorder(root)\n\n minVal = max(res)\n\n for i in range(1, len(res)):\n minVal = min(minVal, res[i] - res[i-1])\n return minVal\n","repo_name":"mdiallo98/python-dataStructures-Algos","sub_path":"LeetcodeQuestions/Tree/minimum_difference_between_random_nodes.py","file_name":"minimum_difference_between_random_nodes.py","file_ext":"py","file_size_in_byte":603,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"81"} +{"seq_id":"23171169912","text":"from flask import Flask, render_template, request, redirect\r\nimport mysql.connector\r\n\r\napp=Flask(__name__)\r\n\r\ndb=mysql.connector.connect( host=\"localhost\",\r\n user=\"root\",\r\n password=\"root\",\r\n database=\"employeerecords\"\r\n )\r\nmycursor=db.cursor()\r\n\r\n@app.route(\"/\")\r\ndef homepage():\r\n mycursor.execute(\"Select * from personal\")\r\n records=mycursor.fetchall();\r\n\r\n return render_template(\"homepage2.html\", data=records)\r\n\r\n@app.route(\"/listofemployees\",methods=[\"POST\"])\r\ndef listofemployees():\r\n dept=request.form[\"dept\"]\r\n if dept==\"all\":\r\n mycursor.execute(\"Select * from personal\")\r\n else:\r\n mycursor.execute(\"Select * from personal where department='\"+dept+\"'\")\r\n records=mycursor.fetchall();\r\n\r\n return render_template(\"homepage2.html\", data=records)\r\n\r\n@app.route(\"/departments/\",methods=['post'])\r\ndef departmentlist(dept):\r\n mycursor.execute(\"Select * from personal where department='\"+dept+\"'\")\r\n records=mycursor.fetchall();\r\n\r\n return render_template(\"homepage2.html\", data=records)\r\n\r\n@app.route(\"/newrecord\")\r\ndef newrecord():\r\n return render_template(\"newrecord2.html\")\r\n\r\n@app.route(\"/newpayslip\")\r\ndef newpayslip():\r\n return render_template(\"newpayslip.html\")\r\n\r\n@app.route(\"/saverecord\",methods=[\"post\"])\r\ndef saverecord():\r\n name=request.form[\"na\"]\r\n dept=request.form[\"dept\"]\r\n mycursor.execute(\"insert into personal(name,department) values('{0}','{1}')\".format(name,dept))\r\n db.commit()\r\n return redirect(\"/\")\r\n\r\n@app.route(\"/newpayslip\",methods=[\"post\"])\r\ndef newpayslip2():\r\n empid=request.form[\"empid\"]\r\n amount=request.form[\"pay\"]\r\n mycursor.execute(\"insert into accounts(empid,salaryDate,amount) values('{0}',now(),'{1}')\".format(empid,amount))\r\n db.commit()\r\n return redirect(\"/\")\r\n\r\n@app.route(\"/details/\")\r\ndef details(empid):\r\n mycursor.execute(\"Select * from personal where empid=\"+empid)\r\n personalrecords=mycursor.fetchall();\r\n mycursor.execute(\"Select * from accounts where empid=\"+empid)\r\n salaryrecords=mycursor.fetchall();\r\n return render_template(\"details2.html\", personal=personalrecords, accounts=salaryrecords)\r\n\r\napp.run(debug=True)\r\n\r\n","repo_name":"leeduffy2004/Flask","sub_path":"Project2/project2.py","file_name":"project2.py","file_ext":"py","file_size_in_byte":2293,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"85226849","text":"# 공포도가 높을수록 사람많이필요\n# 그룹수가 많아야 하니, 적은 인원수를 필요로 하는 그룹부터 구성해나간다.\nN=input()\nfear = list(map(int,input().split()))\nfear.sort()\nanswer=0\ncnt=0\n\nfor i in fear:\n cnt+=1\n if cnt>=i: # 현재 누적 인원수가 공포도 보다 높으면 그룹 가능\n answer+=1\n cnt=0\n\nprint(answer)\n","repo_name":"Areum0921/Abox","sub_path":"This is a coding test with python/page 311.py","file_name":"page 311.py","file_ext":"py","file_size_in_byte":384,"program_lang":"python","lang":"ko","doc_type":"code","stars":1,"dataset":"github-code","pt":"81"} +{"seq_id":"3490613433","text":"from uplink.clients.io.interfaces import (\n Client,\n Executable,\n IOStrategy,\n RequestTemplate,\n)\nfrom uplink.clients.io.execution import RequestExecutionBuilder\nfrom uplink.clients.io.templates import CompositeRequestTemplate\nfrom uplink.clients.io.blocking_strategy import BlockingStrategy\n\n__all__ = [\n \"Client\",\n \"CompositeRequestTemplate\",\n \"Executable\",\n \"IOStrategy\",\n \"RequestTemplate\",\n \"BlockingStrategy\",\n \"AsyncioStrategy\",\n \"TwistedStrategy\",\n \"RequestExecutionBuilder\",\n]\n\ntry:\n from uplink.clients.io.asyncio_strategy import AsyncioStrategy\nexcept (ImportError, SyntaxError): # pragma: no cover\n\n class AsyncioStrategy(IOStrategy):\n def __init__(self, *args, **kwargs):\n raise NotImplementedError(\n \"Failed to load `asyncio` execution strategy: you may be using a version \"\n \"of Python below 3.3. `aiohttp` requires Python 3.4+.\"\n )\n\n\ntry:\n from uplink.clients.io.twisted_strategy import TwistedStrategy\nexcept (ImportError, SyntaxError): # pragma: no cover\n\n class TwistedStrategy(IOStrategy):\n def __init__(self, *args, **kwargs):\n raise NotImplementedError(\n \"Failed to load `twisted` execution strategy: you may be not have \"\n \"the twisted library installed.\"\n )\n","repo_name":"prkumar/uplink","sub_path":"uplink/clients/io/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1353,"program_lang":"python","lang":"en","doc_type":"code","stars":1036,"dataset":"github-code","pt":"81"} +{"seq_id":"43225461541","text":"import torch, \\\n ground_metric_gm as gm, \\\n gurobi_qap as gb, \\\n model_gm as model\n\n\ndef total_node_num( network:torch.nn.Module ):\n '''\n count the total number of nodes in the network [network]\n '''\n num_nodes = 0\n for idx, (name, parameters) in enumerate( network.named_parameters() ):\n if 'bias' in name:\n continue\n if idx == 0:\n num_nodes += parameters.shape[1]\n num_nodes += parameters.shape[0]\n return num_nodes\n\n\ndef graph_matching_fusion( args, networks:list ):\n '''\n the function use graph matching technique to align each layer in networks[0] along with\n networks[1], and return a list that contains the averaged aligned parameters, following\n the original order of parameters in model.parameters()\n\n the averaging weights are specified in [args.ensemble_step, 1-args.ensemble_step]\n '''\n '''\n count the number of nodes in network[0] and network[1], and store them\n as [n1] and [n2], respectively\n '''\n n1 = total_node_num( network=networks[0] )\n n2 = total_node_num( network=networks[1] )\n assert( n1 == n2 )\n '''\n define affinity matrix\n '''\n affinity = torch.zeros([ n1 * n2, n1 * n2 ])\n '''\n iterate through all the layers to calculate the pair-wise distances / affinities\n suppose the layer node numbers are:\n N1(inputs), N2, ..., N(l-1), Nl(outputs), then\n [num_nodes_incremental] = [ N1, N1+N2, ..., N1+N2+...+N(l-1) ]\n [num_nodes_layers] = [ N2, N3, ..., Nl ]\n [pre_conv_list] = [ conv(layer1~2), conv(layer2~3), ..., conv(layer(l-1~l)) ]\n it does not contain bias layers\n [conv_kernel_size_list] = [ kernel_size(1), ..., kernel_size(l) ]\n '''\n num_layers = len( list( zip( networks[0].parameters(), networks[1].parameters() ) ) )\n num_nodes_before = 0\n num_nodes_incremental = []\n num_nodes_layers = []\n pre_conv_list = []\n conv_kernel_size_list = []\n num_nodes_pre = 0\n num_nodes_cur = 0\n is_conv = False\n pre_conv = False\n pre_conv_kernel_size = None\n pre_conv_out_channel = 1\n is_bias = False\n is_final_bias = False\n pre_bias = False\n perm_is_complete = True\n\n named_weight_list_0 = [named_parameter for named_parameter in networks[0].named_parameters()]\n for idx, ( (_, fc_layer0_weight), (_, fc_layer1_weight) ) in \\\n enumerate( zip( networks[0].named_parameters(), networks[1].named_parameters() ) ):\n assert fc_layer0_weight.shape == fc_layer1_weight.shape\n layer_shape = fc_layer0_weight.shape\n num_nodes_cur = fc_layer0_weight.shape[0]\n if len( layer_shape ) > 1:\n # if it's a fully-connected layer after a convolutional layer\n if pre_conv is True and len( layer_shape ) == 2:\n num_nodes_pre = pre_conv_out_channel\n else:\n num_nodes_pre = fc_layer0_weight.shape[1]\n '''\n tell whether the layer is convolutional or fully-connected or bias\n '''\n # if is_bias is False:\n # pre_conv = is_conv\n # pre_conv_list.append( pre_conv )\n if idx >= 1:\n if len( named_weight_list_0[idx-1][1].shape ) == 1:\n pre_bias = True\n else:\n pre_bias = False\n if len( layer_shape ) > 2:\n is_bias = False\n if pre_bias == False:\n pre_conv = is_conv\n pre_conv_list.append( True )\n is_conv = True\n # For convolutional layers, it is (#out_channels, #in_channels, height, width)\n fc_layer0_weight_data = fc_layer0_weight.data.view(\n fc_layer0_weight.shape[0], fc_layer0_weight.shape[1], -1)\n fc_layer1_weight_data = fc_layer1_weight.data.view(\n fc_layer1_weight.shape[0], fc_layer1_weight.shape[1], -1)\n elif len( layer_shape ) == 2:\n is_bias = False\n if pre_bias == False:\n pre_conv = is_conv\n pre_conv_list.append( False )\n is_conv = False\n fc_layer0_weight_data = fc_layer0_weight.data\n fc_layer1_weight_data = fc_layer1_weight.data\n else:\n is_bias = True\n if pre_bias == False:\n pre_conv = is_conv\n pre_conv_list.append( False )\n is_conv = False\n fc_layer0_weight_data = fc_layer0_weight.data\n fc_layer1_weight_data = fc_layer1_weight.data\n '''\n if it's conv, update [pre_conv_out_channel]\n '''\n if is_conv:\n pre_conv_out_channel = num_nodes_cur\n '''\n tell whether it's the final bias layer\n '''\n if is_bias is True and idx == num_layers - 1:\n is_final_bias = True\n '''\n if it's the first layer, map the input nodes\n '''\n if idx == 0:\n for a in range( num_nodes_pre ):\n affinity[(num_nodes_before + a) * n2 + num_nodes_before + a] \\\n [(num_nodes_before + a) * n2 + num_nodes_before + a] \\\n = 1\n '''\n if it's the final layer, map the output nodes\n '''\n if idx == num_layers - 2 and 'bias' in named_weight_list_0[idx+1][0] or \\\n idx == num_layers - 1 and 'bias' not in named_weight_list_0[idx][0]:\n for a in range( num_nodes_cur ):\n affinity[(num_nodes_before + num_nodes_pre + a) * n2 + num_nodes_before + num_nodes_pre + a] \\\n [(num_nodes_before + num_nodes_pre + a) * n2 + num_nodes_before + num_nodes_pre + a] \\\n = 1\n '''\n calculate the edge-wise soft affinities between two models\n '''\n if is_bias is False:\n ground_metric = gm.Ground_Metric_GM( \n fc_layer0_weight_data, fc_layer1_weight_data, is_conv, is_bias,\n pre_conv, int( fc_layer0_weight_data.shape[1] / pre_conv_out_channel ) )\n else:\n ground_metric = gm.Ground_Metric_GM( \n fc_layer0_weight_data, fc_layer1_weight_data, is_conv, is_bias,\n pre_conv, 1 )\n \n layer_affinity = ground_metric.process_soft_affinity( p=2 )\n # print( f'is_conf = {is_conv}, fc layer shape is {fc_layer0_weight.shape}' )\n if is_bias is False:\n pre_conv_kernel_size = fc_layer0_weight.shape[3] if is_conv else None\n conv_kernel_size_list.append( pre_conv_kernel_size )\n '''\n copy the affinity values from [layer_affinity] to the corresponding positions\n in [affinity] matrix\n '''\n if is_bias is True and is_final_bias is False:\n for a in range( num_nodes_cur ):\n for c in range( num_nodes_cur ):\n affinity[(num_nodes_before + a) * n2 + num_nodes_before + c] \\\n [(num_nodes_before + a) * n2 + num_nodes_before + c] \\\n = layer_affinity[a][c]\n elif is_final_bias is False:\n for a in range( num_nodes_pre ):\n for b in range( num_nodes_cur ):\n affinity[ \n (num_nodes_before + a) * n2 + num_nodes_before :\n (num_nodes_before + a) * n2 + num_nodes_before + num_nodes_pre,\n (num_nodes_before + num_nodes_pre + b) * n2 + num_nodes_before + num_nodes_pre :\n (num_nodes_before + num_nodes_pre + b) * n2 + num_nodes_before + num_nodes_pre + num_nodes_cur ] \\\n = layer_affinity[a + b * num_nodes_pre].view( num_nodes_cur, num_nodes_pre ).transpose( 0, 1 )\n '''\n update the total number of nodes that has already been considered in previous steps\n '''\n if is_bias is False:\n num_nodes_before += num_nodes_pre\n num_nodes_incremental.append( num_nodes_before )\n num_nodes_layers.append( num_nodes_cur )\n\n '''\n solve the quadratic assignment problem by calling gurobipy package\n '''\n solution = gb.gurobi_qap_solver( affinity, n1, n2, time_limit=300 )\n \n # debug block begin (uncomment and unindent the following to debug)\n # torch. set_printoptions(profile=\"full\")\n # print( f'affinity matrix is \\n{affinity}' )\n # print( f'solution is \\n{solution}' )\n # torch. set_printoptions(profile=\"default\")\n # return \n # debug block end\n '''\n perform the alignment to network[0] according to the solution\n\n [idx] represents the index of layers, including 'bias' layers\n\n\n '''\n aligned_wt_0 = [parameter.data for name, parameter in named_weight_list_0]\n idx = 0\n num_layers = len( aligned_wt_0 )\n '''\n for each iteration, the weight matrix between two layers (e.g. L_i and L_{i+1}) are considered\n [num_before] denotes N_1 + N_2 + ... + N_i\n [num_cur] denotes N_{i+1}\n [pre_conv] denotes whether weights between L_i and L_{i+1} is convolutional\n [cur_kernel_size] denotes the kenrel_size of the current weight matrix\n\n for each iteration, \n 1. align the weights between L_{i-1} and L_i\n 2. align the bias on L_i (if bias exists)\n 3. align the weights between L_i and L_{i+1}\n '''\n for num_before, num_cur, pre_conv, cur_kernel_size in \\\n zip(num_nodes_incremental, num_nodes_layers, pre_conv_list, conv_kernel_size_list):\n '''\n obtain permutation matrix according to the solution\n\n some preliminaries about permutation matrix:\n 1. firstly, we define a permuation function Pi: {1,...,M} --> {1,...,M}, so that\n 1 is mapped to Pi(1), 2 is mapped to Pi(2), ..., M is mapped to Pi(M).\n 2. Then, we construct the corresponding M x M permutation matrix Perm by:\n Perm[i, j] = 1 if j == Pi(i) else 0\n 3. if we have a N x M matrix A, and we derive B = A @ Perm, then\n the [i]th column of A would become the [Pi(i)]th column of B\n 4. if we have a M x N matrix C, and we derive D = perm^T @ C, then\n the [i]th row of C would become the [Pi(i)]th row of D\n \n some structural information of the returned solution [solution]:\n 1. for the [i]th layer with ni nodes, and Ni nodes before,\n solution[Ni + a][Ni + b] = 1 if a is mapped to b else 0\n 2. if we define Perm_i = solution[Ni:Ni+ni][Ni:Ni+ni], then Perm_i is the \n permutation matrix corresponding to the permutation function Pi, where\n the [i]th node in model 1 is mapped to [Pi(i)]th node in model 2\n \n the procedure to permutate the parameters:\n 1. given the permutation matrix upon layer i, permutate the columns of parameters\n between layer i and layer i+1\n 2. given the permutation matrix upon layer i, permutate the rows of parameters\n between layer i-1 and layer i\n '''\n # perm = solution[num_before:num_before+num_cur, num_before:num_before+num_cur]\n perm = torch.diag( torch.ones( num_cur ) )\n if torch.sum( perm ).item() != perm.shape[0]:\n perm_is_complete = False\n '''\n permutate the rows of parameters between previous layer and current layer\n if the current layer is convolutional:\n 1. permute the aligned weight by: 2-->0, 3-->1, 0-->2, 1-->3\n 2. multiply with the transpose of permutation matrix\n 3. restore the permutation\n else:\n directly multiply with the permutation matrix\n for detailed explanation for the operator '@', or __matmul__, or infix\n multiplication between matrices, see the link:\n https://www.python.org/dev/peps/pep-0465/\n '''\n assert 'bias' not in named_weight_list_0[idx][0]\n if len( named_weight_list_0[idx][1].shape ) == 4:\n aligned_wt_0[idx] = (perm.transpose(0,1).to(torch.float64) @ \\\n aligned_wt_0[idx].to(torch.float64).permute(2,3,0,1)) \\\n .permute(2,3,0,1)\n else:\n aligned_wt_0[idx] = perm.transpose(0,1).to(torch.float64) @ aligned_wt_0[idx].to(torch.float64)\n idx += 1\n '''\n if the bias layer is present, then permuate the bias layer\n '''\n if idx >= num_layers:\n continue\n if 'bias' in named_weight_list_0[idx][0]:\n aligned_wt_0[idx] = aligned_wt_0[idx].to(torch.float64) @ perm.to(torch.float64)\n idx += 1\n '''\n permutate the columns of parameters between current layer and the next layer\n if the previous layer is convolutional and the current layer is fully-connected:\n 1. reshape the aligned weight to \n [cur_num] x [pre_num / kernel_size_squared] x [kernel_size_squared]\n 2. permute the aligned weight so that dim 1 and dim 2 are switched\n 3. multiply the permutation matrix\n 4. permute the aligned weight so that dim 1 and dim 2 are restored\n 5. restore the shape of the aligned weight back to\n [cur_num] x [pre_num]\n else:\n directly multiply the permutation matrix\n '''\n if idx >= num_layers:\n continue\n if pre_conv and len( named_weight_list_0[idx][1].shape ) == 2:\n aligned_wt_0[idx] = ( aligned_wt_0[idx].to(torch.float64) \\\n .reshape( aligned_wt_0[idx].shape[0], pre_conv_out_channel, -1 ) \\\n .permute( 0, 2, 1 ) \\\n @ perm.to(torch.float64) ) \\\n .permute( 0, 2, 1 ) \\\n .reshape( aligned_wt_0[idx].shape[0], -1 )\n elif len( named_weight_list_0[idx][1].shape ) == 4:\n aligned_wt_0[idx] = ( aligned_wt_0[idx].to(torch.float64) \\\n .permute( 2, 3, 0, 1 ) \\\n @ perm.to(torch.float64) ) \\\n .permute( 2, 3, 0, 1 )\n else:\n aligned_wt_0[idx] = aligned_wt_0[idx].to(torch.float64) @ perm.to(torch.float64)\n assert idx == num_layers\n\n # debug block begin\n # for aligned_wt, (name, parameter) in zip( aligned_wt_0, networks[0].named_parameters() ):\n # print( f'*the original weights named \"{name}\" are \\n{parameter}\\n*and the aligned \\\n # weights are \\n{aligned_wt}' )\n # debug block end\n '''\n average the parameters of model 1 and model 2 according to the weights given by [args.ensemble_step, 1-args.ensemble_step], \n then store the results in a list, and return the list\n '''\n averaged_weights = []\n for idx, parameter in enumerate( networks[1].parameters() ):\n averaged_weights.append( (1 - args.ensemble_step) * aligned_wt_0[idx] + args.ensemble_step * parameter )\n return averaged_weights, perm_is_complete\n\n\ndef get_fused_model( args, networks:list ):\n '''\n the input [parameters] is a list consisting of tensors\n '''\n parameters, perm_is_complete = graph_matching_fusion( args, networks )\n fused_model = model.get_model_from_name( args )\n state_dict = fused_model.state_dict()\n for idx, (key, _) in enumerate( state_dict.items() ):\n state_dict[key] = parameters[idx]\n fused_model.load_state_dict( state_dict )\n return fused_model, perm_is_complete\n\n\n\nif __name__ == \"__main__\":\n import torch.nn as nn\n import torch.nn.functional as F\n class dotdict(dict):\n \"\"\" dot.notation access to dictionary attributes \"\"\"\n __getattr__ = dict.get\n __setattr__ = dict.__setitem__\n __delattr__ = dict.__delitem__\n args = dotdict( {\n \"weight\": [0.5, 0.5],\n \"model_name\": \"naivenet\",\n \"dataset\": \"mnist\",\n \"disable_bias\": False,\n \"width_ratio\": 1,\n \"num_hidden_nodes1\": 20,\n \"num_hidden_nodes2\": 30,\n \"num_hidden_nodes3\": 10,\n \"ensemble_step\": 0.5\n } )\n '''\n define a very naive nueral network for testing purpose\n '''\n model1 = model.naive_net()\n model2 = model.naive_net()\n '''\n create two state_dict() instances to initialize two networks\n '''\n state_dict1 = {\n 'lin1.weight': torch.tensor([[1,2], [7,8], [4,5]]),\n 'lin1.bias': torch.tensor([5,6,7]),\n 'lin2.weight': torch.tensor([[1,2,3], [7,8,9]]),\n 'lin2.bias': torch.tensor([4,5]) }\n state_dict2 = {\n 'lin1.weight': torch.tensor([[2,1], [4,4], [7,7]]),\n 'lin1.bias': torch.tensor([4,8,6]),\n 'lin2.weight': torch.tensor([[8,7,9], [2,1,3]]),\n 'lin2.bias': torch.tensor([6,3]) }\n model1.load_state_dict( state_dict1 )\n model2.load_state_dict( state_dict2 )\n '''\n print two models to see that they are created as we wishes\n '''\n def print_model( model:nn.Module ):\n for name, parameter in model.named_parameters():\n print( f'name is {name},\\t parameter is \\n\\t{parameter}' )\n # print( model1 )\n # print_model( model1 )\n # print( model2 )\n # print_model( model2 )\n # print('##########################################################')\n '''\n call the fusion function to check the affinity matrix and the solution\n '''\n # print( graph_matching_fusion( args, [model1, model2] ) )\n # print( get_fused_model( args, [model1, model2] ) )\n # print('##########################################################')\n\n\n # print('##########################################################')\n print( '------------------- gm-based with perm = diagonal -------------------' )\n '''\n define a simple convolutional neural network\n '''\n args.model_name = 'naivecnn'\n model3 = model.naive_cnn()\n model4 = model.naive_cnn()\n '''\n create two state_dict() instances to initialize two networks\n '''\n state_dict3 = {\n 'conv1.weight': torch.tensor([[ [[1,2],[3,4]] ], [ [[5,6],[7,8]] ]]),\n 'conv1.bias': torch.tensor([5, 6]),\n 'fc1.weight': torch.tensor([[1,2,3,4,5,6,7,8], [8,7,6,5,4,3,2,1]]),\n 'fc1.bias': torch.tensor([1,2]) }\n state_dict4 = {\n 'conv1.weight': torch.tensor([[ [[5,6],[8,7]] ], [ [[2,1],[3,4]] ]]),\n 'conv1.bias': torch.tensor([7, 4]),\n 'fc1.weight': torch.tensor([[3,4,1,2,7,8,5,6], [5,7,6,8,1,3,2,4]]),\n 'fc1.bias': torch.tensor([3,1]) }\n model3.load_state_dict( state_dict3 )\n model4.load_state_dict( state_dict4 )\n '''\n print two models to see that they are created as we wishes\n '''\n # print( model3 )\n # print_model( model3 )\n # print( model4 )\n # print_model( model4 )\n '''\n call the fusion function to check the affinity matrix and the solution\n '''\n # print('##########################################################')\n # print( graph_matching_fusion( args, [model3, model4] ) )\n print_model( get_fused_model( args, [model3, model4] )[0] )\n\n print( '------------------- naive fusion -------------------' )\n fused_model = model.naive_cnn()\n state_dict_fused = {}\n for key, value in state_dict3.items():\n state_dict_fused[key] = ( state_dict3[key] + state_dict4[key] ) / 2\n fused_model.load_state_dict( state_dict_fused )\n print_model( fused_model )","repo_name":"Thinklab-SJTU/GAMF","sub_path":"fusion_gm.py","file_name":"fusion_gm.py","file_ext":"py","file_size_in_byte":19356,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"81"} +{"seq_id":"34657994374","text":"import json\nimport os\nimport sys\nimport subprocess\nimport io\nfrom typing import Any, Dict\n\nfrom valmi_connector_lib.common.logs import SingletonLogWriter, TimeAndChunkEndFlushPolicy\nfrom valmi_connector_lib.common.samples import SampleWriter\nfrom valmi_connector_lib.destination_wrapper.engine import CONNECTOR_STRING\n\nfrom .proc_stdout_handler import ProcStdoutHandlerThread\nfrom .proc_stdout_event_handlers import (\n Engine,\n StoreReader,\n NullEngine,\n)\nfrom .read_handlers import ReadCheckpointHandler, ReadDefaultHandler, ReadLogHandler, ReadRecordHandler\nfrom .proc_stdout_handler import handlers as stdout_handlers\n\nhandlers = {\n \"LOG\": ReadLogHandler,\n \"STATE\": ReadCheckpointHandler,\n \"RECORD\": ReadRecordHandler,\n \"default\": ReadDefaultHandler,\n}\n\n\ndef get_airbyte_command():\n entrypoint_str = os.environ[\"VALMI_ENTRYPOINT\"]\n entrypoint = entrypoint_str.split(\" \")\n\n airbyte_command = sys.argv[3]\n for i, arg in enumerate(sys.argv[1:]):\n if i >= len(entrypoint):\n airbyte_command = arg\n break\n\n return airbyte_command\n\n\ndef get_config_file_path():\n # TODO: do this better\n config_file_path = None\n for i, arg in enumerate(sys.argv):\n if arg == \"--config\":\n config_file_path = sys.argv[i + 1]\n break\n\n return config_file_path\n\n\ndef populate_run_time_args(airbyte_command, engine, config_file_path):\n if airbyte_command == \"write\":\n run_time_args = engine.current_run_details()\n\n with open(config_file_path, \"r\") as f:\n config = json.loads(f.read())\n\n with open(config_file_path, \"w\") as f:\n config[\"run_time_args\"] = run_time_args\n f.write(json.dumps(config))\n\n if 'state' in run_time_args:\n # create a new state file alongside the config file\n state_file_path = os.path.join(os.path.dirname(config_file_path), 'state.json')\n set_state_file_path(state_file_path)\n set_loaded_state(run_time_args['state'])\n with open(state_file_path, \"w\") as f:\n f.write(json.dumps(run_time_args['state']))\n\n\nstate_file_path = None\nloaded_state = None\n\n\ndef set_state_file_path(file_path: str):\n global state_file_path\n state_file_path = file_path\n\n\ndef set_loaded_state(state: Dict[str, Any]):\n global loaded_state\n loaded_state = state\n\n\ndef is_state_available():\n global state_file_path\n return state_file_path is not None\n\n\ndef main():\n airbyte_command = get_airbyte_command()\n config_file = get_config_file_path()\n\n if airbyte_command is None or (airbyte_command != \"spec\" and config_file is None):\n sys.exit(5)\n\n # if arg in read, write:\n # read checkpoint from the engine\n\n if airbyte_command == \"write\":\n engine = Engine()\n else:\n engine = NullEngine()\n\n # populate run_time_args\n populate_run_time_args(airbyte_command, engine, config_file_path=config_file)\n\n if airbyte_command in [\"spec\", \"check\", \"discover\"]:\n # initialize handlers\n for key in stdout_handlers.keys():\n stdout_handlers[key] = stdout_handlers[key](engine=engine, store_writer=None, stdout_writer=None)\n\n # create the subprocess\n subprocess_args = sys.argv[1:]\n proc = subprocess.Popen(\n subprocess_args,\n stdout=subprocess.PIPE,\n )\n\n record_types = handlers.keys()\n for line in io.TextIOWrapper(proc.stdout, encoding=\"utf-8\"): # or another encoding\n if line.strip() == \"\":\n continue\n json_record = json.loads(line)\n if json_record[\"type\"] not in record_types:\n stdout_handlers[\"default\"].handle(json_record)\n else:\n stdout_handlers[json_record[\"type\"]].handle(json_record)\n\n return_code = proc.poll()\n if return_code is not None and return_code != 0:\n engine.error(\"Process exited with non-zero return code. %s\" % return_code)\n sys.exit(return_code)\n\n elif airbyte_command in [\"write\"]:\n # initialize LogWriter\n SingletonLogWriter(os.environ[\"VALMI_INTERMEDIATE_STORE\"],\n TimeAndChunkEndFlushPolicy(os.environ[\"VALMI_INTERMEDIATE_STORE\"]),\n engine.connector_state.run_time_args[\"sync_id\"],\n engine.connector_state.run_time_args[\"run_id\"],\n CONNECTOR_STRING)\n \n # initialize SampleWriter\n SampleWriter.get_writer_by_metric_type(store_config_str=os.environ[\"VALMI_INTERMEDIATE_STORE\"],\n sync_id=engine.connector_state.run_time_args[\"sync_id\"],\n run_id=engine.connector_state.run_time_args[\"run_id\"],\n connector=CONNECTOR_STRING)\n\n # initialize handler\n for key in handlers.keys():\n handlers[key] = handlers[key](engine=engine, store_writer=None, stdout_writer=None)\n\n global loaded_state\n store_reader = StoreReader(engine=engine, state=loaded_state)\n\n # create the subprocess\n subprocess_args = sys.argv[1:]\n if is_state_available():\n subprocess_args.append(\"--state\")\n subprocess_args.append(state_file_path)\n proc = subprocess.Popen(subprocess_args, stdin=subprocess.PIPE, stdout=subprocess.PIPE)\n\n try:\n proc_stdout_handler_thread = ProcStdoutHandlerThread(\n 1, \"ProcStdoutHandlerThread\", engine, proc, proc.stdout\n )\n proc_stdout_handler_thread.start()\n\n record_types = handlers.keys()\n\n for line in store_reader.read():\n if line.strip() == \"\":\n continue\n json_record = json.loads(line)\n if json_record[\"type\"] not in record_types:\n if not handlers[\"default\"].handle(json_record):\n break\n else:\n if not handlers[json_record[\"type\"]].handle(json_record):\n break\n proc.stdin.write(line.encode(\"utf-8\"))\n\n except Exception as e:\n engine.error(msg=str(e))\n proc.stdin.close()\n proc.kill()\n proc_stdout_handler_thread.destroy()\n proc_stdout_handler_thread.join()\n raise\n else:\n proc.stdin.close()\n return_code = proc.poll()\n if return_code is not None and return_code != 0:\n engine.error(\"Process exited with non-zero return code. %s\" % return_code)\n sys.exit(return_code)\n\n proc_stdout_handler_thread.destroy()\n proc_stdout_handler_thread.join()\n engine.success()\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"valmi-io/valmi-activation","sub_path":"packages/valmi-connector-lib/valmi_connector_lib/destination_wrapper/destination_container_wrapper.py","file_name":"destination_container_wrapper.py","file_ext":"py","file_size_in_byte":6894,"program_lang":"python","lang":"en","doc_type":"code","stars":86,"dataset":"github-code","pt":"81"} +{"seq_id":"41239394100","text":"from django.shortcuts import render, redirect, get_object_or_404\nfrom .models import Cliente\nfrom .form import ClienteForm\nfrom django.contrib.auth.decorators import login_required\n\n# Create your views here.\n\ndef base(request):\n return render(request, 'core/base.html')\n\ndef listagem(request):\n clientes = Cliente.objects.all()\n return render(request, 'core/listagem.html', {'clientes' : clientes})\n\n@login_required\ndef incluir(request):\n # data ={}\n form = ClienteForm(request.POST or None, request.FILES or None)\n\n if form.is_valid():\n form.save()\n return redirect(listagem)\n\n # data['form'] = form\n return render(request, 'core/incluir.html', {'form' : form})\n\n@login_required\ndef alterar(request, pk):\n data = {}\n # cliente = Cliente.objects.get(pk=pk)\n cliente = get_object_or_404(Cliente, pk=pk)\n form = ClienteForm(request.POST or None, request.FILES or None, instance=cliente)\n\n if form.is_valid():\n form.save()\n return redirect(listagem)\n\n data['form'] = form\n data['cliente'] = cliente\n return render(request, 'core/incluir.html', data)\n\n@login_required\ndef excluir(request, pk):\n # cliente = Cliente.objects.get(pk=pk)\n cliente = get_object_or_404(Cliente, pk=pk)\n if request.method == 'POST':\n cliente.delete()\n return redirect('url_listagem')\n \n return render(request, 'core/confirma.html', {'cliente' : cliente})\n\n# def login(request):\n# return render(request, 'core/login.html')\n ","repo_name":"anselmojuniorjj/django","sub_path":"core/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1539,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"19364467519","text":"from pathlib import Path\n\nfrom multiprocessing import Pool\nfrom jellyfish import jaro_winkler\n\nn_path = Path('output/1-3-post_seg')\nd_path = Path('output/3a-1-page_refs')\n\nnalanda = [p.stem.replace('_post_seg', '') for p in n_path.glob('*.txt') if p.stem.startswith('D')]\nderge_tengyur = [p.stem for p in d_path.glob('*.txt')]\n\nmissing_nalanda = [n for n in nalanda if n not in derge_tengyur]\nprint('\\n'.join(missing_nalanda))\nnalanda = [n for n in nalanda if n in derge_tengyur]\n\n\ndef get_distance(name):\n n_content = Path(n_path / str(name + '_post_seg.txt')).read_text(encoding='utf-8-sig')\n n_content = n_content.strip().split(':', maxsplit=1)[0]\n d_content = Path(d_path / str(name + '.txt')).read_text(encoding='utf-8-sig')\n d_content = d_content.strip()\n l_dist = jaro_winkler(n_content, d_content)\n percent = int(l_dist * 100)\n print(name, ':', percent)\n return (percent, name)\n\n\ndistances = []\nwith Pool(4) as p:\n distances.append(p.map(get_distance, nalanda))\n\n# for n in nalanda:\n# n_content = Path(n_path / str(n + '_post_seg.txt')).read_text(encoding='utf-8-sig')\n# n_content = n_content.strip()\n# d_content = Path(d_path / str(n + '.txt')).read_text(encoding='utf-8-sig')\n# d_content = d_content.strip()\n# l_dist = jaro_winkler(n_content, d_content)\n# percent = int(l_dist * 100)\n# distances.append((percent, n))\n\ndistances = sorted(distances, reverse=True)\nPath('distances.csv').write_text('percent,work' + '\\n'.join([f'{b},{a}' for a, b in distances]))\nprint('ok')\n","repo_name":"Esukhia/canon_notes","sub_path":"4-a-final_formatting/find_different_texts.py","file_name":"find_different_texts.py","file_ext":"py","file_size_in_byte":1536,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"11983064395","text":"class Solution(object):\n def rob(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n\n\n # The intuition behind this solution is as follows:\n\n # 1. To handle a cycle of indices from 0 to n-1, where adjacent values cannot be selected, \n # you may either consider the length of 0 to n-2, and 1 to n-1. This guarantees that the\n # ends of the cycle do not overlap. Thus, we loop through them separately\n\n # 2. for each loop, we carry forward two variables (similar to fibonacci) that store previous \n # values to help us get the overall best solution. That is because to get the best \n # sum, we can either take the value that is previous, or add the current value to the one \n # 2 before (so we dont have any adjacencies)\n\n # 3. The higher loop's value would be the best value in this cycle.\n\n prev1, prev2, res1, res2 = 0, 0, 0, nums[0]\n\n n = len(nums)\n for i in range(n-1):\n res1 = max(prev2, prev1 + nums[i])\n prev1 = prev2 \n prev2 = res1\n \n prev1, prev2 = 0, 0\n for i in range(1, n):\n res2 = max(prev2, prev1 + nums[i])\n prev1 = prev2\n prev2 = res2 \n \n return max(res1, res2)\n ","repo_name":"hargunmujral/Competitive-Programming","sub_path":"house-robber-2.py","file_name":"house-robber-2.py","file_ext":"py","file_size_in_byte":1308,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"24763743970","text":"# encoding: UTF-8\n\n\"\"\"\n包含一些开放中常用的函数\n\"\"\"\n\nimport decimal\nimport json\nimport datetime\n\nMAX_NUMBER = 10000000000000\nMAX_DECIMAL = 4\n\n#----------------------------------------------------------------------\ndef loadJson(filePath):\n \"\"\"读取json文件,返回字典列表\"\"\"\n try:\n f = file(filePath)\n l = json.load(f)\n return l\n except:\n print(u'文件 : '+str(filePath)+u' 不存在')\n \n#----------------------------------------------------------------------\ndef writeJson(dictList,dictFile):\n \"\"\"把json数据写入到文件\"\"\"\n dict_str = json.dumps(dictList,ensure_ascii=False)\n dictFile = open(self.name+\".json\", 'w')\n dictFile.write(dict_str)\n dictFile.close( )\n \n\n#----------------------------------------------------------------------\ndef todayDate():\n \"\"\"获取当前本机电脑时间的日期\"\"\"\n return datetime.datetime.now().replace(hour=0, minute=0, second=0, microsecond=0) \n\n \n","repo_name":"hoio8/test1","sub_path":"vtFunction.py","file_name":"vtFunction.py","file_ext":"py","file_size_in_byte":990,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"36039721120","text":"import re\n\n\ndef key_valid(var):\n regexp = re.compile(r\"^[A-Z]{1}[a-z]+$\")\n text = input(var)\n while not bool(regexp.match(text)):\n text=input(var)\n return text\n\nprint(key_valid('input zip_city: '))\n\n\ndef spc_valid(var1):\n regexp = re.compile(r\"^[A-Za-z\\s]+$\")\n text = input(var1)\n while not bool(regexp.match(text)):\n text=input(var1)\n return text\nprint(spc_valid('input spc_common: '))\n\n\ndef horzgr_valid(var2):\n regexp = re.compile(r\"^yes|no$\")\n text = input(var2)\n while not bool(regexp.match(text)):\n text=input(var2)\n return text\nprint(horzgr_valid('input yes or no: '))\n\n\ndef year_valid(var3):\n regexp = re.compile(r\"^\\d{4}$\")\n text = input(var3)\n while not bool(regexp.match(text)):\n text=input(var3)\n return text\nprint(year_valid('input year: '))","repo_name":"igortereshchenko/datascience","sub_path":"NoskovIlyas/validator/lib.py","file_name":"lib.py","file_ext":"py","file_size_in_byte":830,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"31755083651","text":"from bs4 import BeautifulSoup\nimport requests\n\n\ndef extract_remoteok_jobs(keyword):\n siteUrl = \"https://remoteok.com\"\n url = f\"{siteUrl}/remote-{keyword}-jobs\"\n request = requests.get(url, headers={\"User-Agent\": \"Kimchi\"})\n results = []\n if request.status_code == 200:\n soup = BeautifulSoup(request.text, \"html.parser\")\n jobs = soup.find_all(\"tr\", class_=\"job\")\n for job in jobs:\n job_td = job.find(\"td\", class_=\"company\")\n job_title = job_td.find(\"a\")\n\n company = job_td.find(\"h3\").string.strip()\n locations = job_td.find_all(\"div\", class_=\"location\")\n locations.pop(-1)\n location_str = \"\"\n for location in locations:\n location_str += location.string.strip() + \",\"\n location_str = location_str[:-1] \n result = {\n \"site\": \"remoteok\",\n \"link\": f\"{siteUrl}{job_title['href']}\",\n \"company\": company,\n \"location\": location_str,\n \"position\": job_title.find(\"h2\").string.strip()\n }\n results.append(result)\n return results\n","repo_name":"ssoyeee/Grab-a-job","sub_path":"extractors/remoteok.py","file_name":"remoteok.py","file_ext":"py","file_size_in_byte":1166,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"13040151002","text":"# This is a list comprehension\r\nmyList = [x for x in range(12)]\r\nprint(myList)\r\n\r\n# a more complex example\r\nmyList = [x*x + x for x in range(100) if x%2 == 0]\r\nprint(myList)\r\n\r\nmyList = [x*y for x,y in zip(range(50),range(50, 100))]\r\nprint(myList)\r\n\r\n# nested loops in comprehensions\r\nmyList = [x * y for x in range(10) for y in range(1, 3)]\r\nprint(myList)\r\n\r\n# This is a dictionary comprehension\r\nmyNicks = ['abe', 'superman', 'flash']\r\nmyNames = ['Abraham', 'Clark', 'Barry']\r\nmyDict = {nick:name for nick,name in zip(myNicks, myNames)}\r\nprint(myDict)\r\n\r\n# and a set comprehension\r\nmyString = list('hello')\r\nmySet = {c.upper() for c in myString}\r\nprint(mySet)","repo_name":"rafarafarafarafael/mapt_learning_python","sub_path":"comprehensions_1.py","file_name":"comprehensions_1.py","file_ext":"py","file_size_in_byte":661,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"20052768577","text":"import numpy as np\nimport scipy.sparse\nimport pytest\n\nfrom lccd_python import utils\n\n\nTEST_TIMES = 50\n\n\ndef test_insert_binary_col_binary_csc():\n dtypes = [np.float32, np.uint8]\n for _ in range(TEST_TIMES):\n for dtype in dtypes:\n rows, cols = np.random.randint(30, 50, 2)\n for i in [0, np.random.randint(1, cols)]:\n mat = np.random.rand(rows, cols)\n mat[mat > 0] = 1\n mat[mat <= 0] = 0\n mat = mat.astype(dtype)\n mat = scipy.sparse.csc_matrix(mat)\n\n num_nonzero = np.random.randint(0, rows+1)\n indices = np.sort(np.random.choice(range(rows), num_nonzero, replace=False))\n\n mat_dense = mat.toarray()\n dense_values = np.zeros(rows, dtype=dtype)\n dense_values[indices] = 1\n mat_dense_inserted = np.insert(mat_dense, i, dense_values, axis=1)\n utils.insert_binary_col_binary_csc(mat, indices, i)\n np.testing.assert_array_equal(mat_dense_inserted, mat.toarray())\n\n\ndef test_delete_row_csr():\n dtypes = [np.float32, np.uint8]\n for _ in range(TEST_TIMES):\n for dtype in dtypes:\n rows, cols = np.random.randint(30, 50, 2)\n mat = scipy.sparse.random(rows, cols, density=0.02, format='csr', dtype=dtype)\n idx = np.random.randint(0, rows)\n correct = np.delete(mat.toarray(), idx, 0)\n res = utils.delete_row_csr(mat, idx)\n np.testing.assert_array_equal(correct, res.toarray())\n\ndef test_delete_col_csc():\n dtypes = [np.float32, np.uint8]\n for _ in range(TEST_TIMES):\n for dtype in dtypes:\n rows, cols = np.random.randint(10, 20, 2)\n mat = scipy.sparse.random(rows, cols, density=0.01, format='csc', dtype=dtype)\n idx = np.random.randint(0, cols)\n correct = np.delete(mat.toarray(), idx, 1)\n res = utils.delete_col_csc(mat, idx)\n np.testing.assert_array_equal(correct, res.toarray())\n\n\ndef test_delete_col_csc_inplace():\n dtypes = [np.float32, np.uint8]\n for _ in range(TEST_TIMES):\n for dtype in dtypes:\n rows, cols = np.random.randint(10, 20, 2)\n mat = scipy.sparse.random(rows, cols, density=0.01, format='csc', dtype=dtype)\n idx = np.random.randint(0, cols)\n correct = np.delete(mat.toarray(), idx, 1)\n utils.delete_col_csc_inplace(mat, idx)\n res = mat\n np.testing.assert_array_equal(correct, res.toarray())\n\n\ndef test_count_nonzero_values_in_col_csc():\n dtypes = [np.float32, np.uint8]\n for _ in range(TEST_TIMES):\n for dtype in dtypes:\n rows, cols = np.random.randint(10, 20, 2)\n mat = scipy.sparse.random(rows, cols, density=0.01, format='csc', dtype=dtype)\n idx = np.random.randint(0, cols)\n res = utils.count_nonzero_values_in_col_csc(mat, idx)\n np.sum(mat[:, idx]!=0) == mat[:, idx].count_nonzero() == np.count_nonzero(mat[:, idx].toarray()) == res\n\n\ndef test_intersect_unique_sorted_1d():\n for _ in range(TEST_TIMES):\n arr1 = np.sort(np.unique(np.random.randint(0, 100, 50)))\n arr2 = np.sort(np.unique(np.random.randint(0, 100, 50)))\n correct = np.intersect1d(arr1, arr2)\n np.testing.assert_array_equal(correct, utils.intersect_unique_sorted_1d(arr1, arr2))\n\n\ndef test_array_to_lil_row():\n for _ in range(TEST_TIMES):\n n_rows, n_cols = np.random.randint(1, 100, 2)\n for arr in [np.random.rand(n_rows, n_cols), np.random.randint(0, 2, size=(n_rows, n_cols), dtype=np.uint8)]:\n rows, data = [], []\n for row_ in arr:\n datum, row = utils.array_to_lil_row(row_)\n rows.append(row)\n data.append(datum)\n dtype = row_.dtype\n lil_arr = scipy.sparse.lil_matrix((n_rows, n_cols), dtype=dtype)\n lil_arr.data = np.array(data, dtype='object')\n lil_arr.rows = np.array(rows, dtype='object')\n np.testing.assert_array_equal(arr, lil_arr.toarray())\n","repo_name":"magnetizedCell/lccd-python","sub_path":"tests/test_utils.py","file_name":"test_utils.py","file_ext":"py","file_size_in_byte":4142,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"5937289567","text":"import logging\nimport pickle\nimport sys\nfrom pathlib import Path\nfrom typing import Dict, List, Optional, Tuple, Union, cast\n\nimport fire # type: ignore\nimport numpy as np\nimport pandas as pd # type: ignore\nimport seaborn as sns # type: ignore\nfrom matplotlib import pyplot as plt # type: ignore\nfrom sklearn.metrics import confusion_matrix # type: ignore\nfrom typing_extensions import Literal # type: ignore\n\nfrom run_tests import Experiment\nfrom utils import setup_logging\n\nStyle = Union[Literal[\"POSTER\"], Literal[\"PAPER\"], Literal[\"ICML\"]]\n\n\ndef get_interactive():\n \"\"\" Cursed magic for determining if the code is being run in an interactive environment. \"\"\"\n return getattr(sys, \"ps1\", None) is not None\n\n\ndef closefig(out: Optional[Path] = None, transparent: bool = False):\n if get_interactive() and out is None:\n plt.show()\n else:\n if out is not None:\n plt.savefig(out, transparent=transparent)\n plt.close()\n\n\ndef make_xaxis(\n n_labels: int = 5, ticks_per_label: int = 5, lower: float = 0.0, upper: float = 1.5\n) -> Tuple[np.ndarray, List[str]]:\n n_ticks = (n_labels - 1) * ticks_per_label + 1\n xticks = np.linspace(lower, upper, n_ticks)\n xlabels = [\"\"] * n_ticks\n for i, val in enumerate(xticks[::ticks_per_label]):\n xlabels[i * ticks_per_label] = str(val)\n return xticks, xlabels\n\n\ndef make_palette_map(key_values: np.ndarray) -> dict:\n \"\"\"Given a sequence of experimental parameters, generate palette maps for representing\n parameter values.\"\"\"\n logging.debug(f\"key_values shape={key_values.shape}\")\n logging.debug(f\"key_values={key_values}\")\n palette = sns.color_palette(\"muted\", len(key_values))\n palette_map = {val: palette[j] for j, val in enumerate(sorted(key_values))}\n\n return palette_map\n\n\ndef get_hue(hue: str, df: pd.DataFrame):\n palette = make_palette_map(df[hue].drop_duplicates().to_numpy())\n if hue == \"n\":\n assert \"n\" in df.columns\n hue_order = np.sort(df.n.astype(int).unique()).astype(str)\n elif hue == \"delta\":\n hue_order = np.sort(df.delta.astype(float).unique()).astype(str)\n else:\n raise ValueError(\"Hue must be n or delta\")\n\n return palette, hue_order\n\n\ndef check(\n normals: np.ndarray,\n indices: Dict[Experiment, np.ndarray],\n rewards: np.ndarray,\n saved_agreements: Dict[Experiment, np.ndarray],\n):\n \"\"\"Reconstruct alignment decisions and check that they agree with cached values.\"\"\"\n j = 0\n agreements = pd.DataFrame(columns=[\"epsilon\", \"delta\", \"n\", \"aligned\", \"value\"])\n validation_test = normals.T\n for (epsilon, delta, n), i in indices.items():\n test = normals[i]\n aligned = np.all(np.dot(rewards, test.T) > 0, axis=1)\n\n aligned_rewards: np.ndarray = rewards[aligned]\n misaligned_rewards = rewards[np.logical_not(aligned)]\n\n for agreement in cast(np.ndarray, np.mean((aligned_rewards @ validation_test) > 0, axis=1)):\n agreements.loc[j] = [epsilon, delta, n, True, agreement]\n j += 1\n\n for agreement in cast(\n np.ndarray, np.mean((misaligned_rewards @ validation_test) > 0, axis=1)\n ):\n agreements.loc[j] = [epsilon, delta, n, False, agreement]\n j += 1\n\n assert agreements.keys() == saved_agreements.keys()\n for key in agreements.keys():\n assert np.all(agreements[key] == saved_agreements[key])\n\n\ndef make_agreements(file) -> pd.DataFrame:\n \"\"\"In some of the human conditions, we hold out questions. Each randomly generated agent is\n given our test and then asked it's opinion on every hold out question.\n\n agreements.pkl is a Dict[Experiment, Tuple(ndarray, ndarray)] where each array element\n contains the fraction of holdout questions a single agent answered correctly. The first array\n contains agents that passed our test, and the second contains agents that didn't pass our test.\n\n This method massages that data into a DataFrame with experiments as they keys, a column\n for predicted alignment, and a column for the fraction of holdout questions answered correctly.\n \"\"\"\n agreements = pd.Series(pickle.load(file)).reset_index()\n agreements = agreements.join(\n agreements.apply(lambda x: list(x[0]), result_type=\"expand\", axis=\"columns\"),\n rsuffix=\"_\",\n )\n del agreements[\"0\"]\n agreements.columns = [\"epsilon\", \"delta\", \"n\", \"aligned\", \"misaligned\"]\n agreements = agreements.set_index([\"epsilon\", \"delta\", \"n\"]).stack().reset_index()\n agreements.columns = [\"epsilon\", \"delta\", \"n\", \"aligned\", \"value\"]\n agreements = agreements.explode(\"value\")\n agreements[\"aligned\"] = agreements.aligned == \"aligned\"\n\n agreements.value = agreements.value.apply(lambda x: float(x))\n agreements = agreements.dropna()\n return agreements\n\n\ndef make_human_confusion(\n label_path: Path = Path(\"questions/gt_rewards/alignment.npy\"),\n prediction_path: Path = Path(\"questions/test_results.skip_noise.pkl\"),\n) -> pd.DataFrame:\n label = np.load(label_path)\n predictions: Dict[Experiment, np.ndarray] = pickle.load(open(prediction_path, \"rb\"))\n\n confusions = []\n for experiment, prediction in predictions.items():\n n = experiment[2]\n if n <= 0:\n continue\n confusion = confusion_matrix(y_true=label, y_pred=prediction, labels=[False, True])\n confusions.append(\n (\n *experiment,\n confusion[0][0],\n confusion[0][1],\n confusion[1][0],\n confusion[1][1],\n )\n )\n\n df = pd.DataFrame(\n confusions,\n columns=[\"epsilon\", \"delta\", \"n\", \"tn\", \"fp\", \"fn\", \"tp\"],\n )\n\n df = df.convert_dtypes()\n\n df = df.sort_values(by=\"n\")\n df[\"n\"] = df[\"n\"].astype(str)\n\n df = compute_targets(df)\n\n return df\n\n\ndef read_confusion(dir: Path, ablation: str = \"\", max_n: int = -1) -> pd.DataFrame:\n \"\"\" Read dict of confusion matrices. \"\"\"\n out_dict = pickle.load(open(dir / f\"confusion.{ablation}.pkl\", \"rb\"))\n\n out = pd.Series(out_dict).reset_index()\n out.columns = [\"epsilon\", \"delta\", \"n\", \"confusion\"]\n out = out.join(\n out.apply(\n lambda x: [\n int(x.confusion[0][0]),\n int(x.confusion[0][1]),\n int(x.confusion[1][0]),\n int(x.confusion[1][1]),\n ],\n result_type=\"expand\",\n axis=\"columns\",\n )\n )\n del out[\"confusion\"]\n out.columns = [\"epsilon\", \"delta\", \"n\", \"tn\", \"fp\", \"fn\", \"tp\"]\n\n if max_n > 0:\n out = out[out.n.astype(int) <= max_n]\n\n out = compute_targets(out)\n\n logging.debug(f\"Reading inputs with shape={out.shape}, columns={out.columns}\")\n\n return out\n\n\ndef compute_targets(df: pd.DataFrame) -> pd.DataFrame:\n for col in (\"fp\", \"tp\", \"fn\", \"tn\"):\n df[col] = df[col].astype(int)\n\n for col in (\"epsilon\", \"delta\"):\n df[col] = df[col].astype(float)\n\n df[\"n\"] = df[\"n\"].astype(str)\n df[\"fpr\"] = df.fp / (df.fp + df.tn)\n df[\"tpf\"] = df.tp / (df.tp + df.fp + df.tn)\n df[\"fnr\"] = df.fn / (df.fn + df.tp)\n df[\"acc\"] = (df.tp + df.tn) / (df.tp + df.tn + df.fp + df.fn)\n return df\n\n\ndef read_replications(\n rootdir: Path, ablation: str, replications: Optional[int] = None, max_n: int = -1\n) -> pd.DataFrame:\n df = pd.DataFrame(columns=[\"epsilon\", \"delta\", \"n\", \"tn\", \"fp\", \"fn\", \"tp\"])\n if replications is not None:\n for replication in range(1, int(replications) + 1):\n if (rootdir / str(replication)).exists():\n df = df.append(\n read_confusion(rootdir / str(replication), ablation=ablation, max_n=max_n)\n )\n else:\n logging.warning(f\"rootdir={rootdir / str(replication)} does not exist\")\n else:\n df = read_confusion(rootdir, ablation=ablation)\n\n df = df.convert_dtypes()\n\n # Seaborn tries to convert integer hues into rgb values. So we make them strings.\n df = compute_targets(df)\n\n return df\n\n\ndef get_max_delta(df: pd.DataFrame, target: str) -> pd.DataFrame:\n df = df.copy()\n\n df[\"means\"] = (\n df[[\"n\", \"epsilon\", \"delta\", target]].groupby([\"n\", \"epsilon\", \"delta\"]).transform(\"mean\")\n ).astype(float)\n df[\"max_mean_delta\"] = df.groupby([\"n\", \"epsilon\"]).means.transform(\"max\")\n\n df = df[df.means == df.max_mean_delta]\n df = df.drop(columns=[\"means\", \"max_mean_delta\"])\n\n return df\n\n\ndef get_rows_per_replication(df: pd.DataFrame) -> int:\n return df.epsilon.unique().size * df.n.unique().size * df.delta.unique().size\n\n\ndef fill_na(df) -> None:\n df.fpr.fillna(1.0, inplace=True)\n df.fnr.fillna(0.0, inplace=True)\n\n\ndef setup_plt(font_size: int, use_dark_background: bool) -> None:\n plt.rc(\"text\", usetex=True)\n plt.rcParams.update({\"font.size\": font_size})\n if use_dark_background:\n plt.style.use(\"dark_background\")\n\n mpl_logger = logging.getLogger(\"matplotlib\")\n mpl_logger.setLevel(logging.WARNING)\n\n logging.getLogger(\"PIL\").setLevel(\"WARNING\")\n\n\ndef assert_style(style: str) -> Style:\n style = style.upper()\n assert style in (\"ICML\", \"NEURIPS\", \"POSTER\")\n return cast(Style, style)\n\n\n### Plots\n\n\ndef plot_agreements(\n agreements: pd.DataFrame,\n epsilon: float,\n delta: float,\n n: int,\n out: Optional[Path] = None,\n) -> None:\n \"\"\"Plots histograms of how many agents had different amounts of holdout agreement for agents\n prediced tobe aligned and misaligned.\"\"\"\n tmp = agreements[\n np.logical_and(\n np.logical_and(agreements.epsilon == epsilon, agreements.delta == delta),\n agreements.n == n,\n )\n ]\n\n tmp[tmp.aligned].value.hist(label=\"aligned\", alpha=0.3)\n tmp[tmp.aligned == False].value.hist(label=\"misaligned\", alpha=0.3)\n\n plt.xlabel(\"Hold out agreement\")\n plt.legend()\n closefig(out)\n\n\ndef plot_mean_agreement(agreements: pd.DataFrame, out: Optional[Path] = None) -> None:\n mean_agreement = agreements.groupby([\"epsilon\", \"delta\", \"n\", \"aligned\"]).mean().reset_index()\n plt.hist(mean_agreement[mean_agreement.aligned].value, label=\"aligned\", alpha=0.3)\n plt.hist(\n mean_agreement[np.logical_not(mean_agreement.aligned)].value,\n label=\"unaligned\",\n alpha=0.3,\n )\n\n plt.xlabel(\"\\% holdout agreement\")\n plt.legend()\n closefig(out)\n\n\ndef plot_fpr(\n df: pd.DataFrame,\n rootdir: Path,\n ablation: str,\n style: Style,\n hue: str = \"n\",\n best_delta: bool = True,\n n_labels: int = 5,\n ticks_per_label: int = 5,\n) -> None:\n plt.figure(figsize=(10, 10))\n\n df = df.dropna(subset=[\"fpr\"])\n if best_delta:\n df = get_max_delta(df, \"fpr\")\n\n palette, hue_order = get_hue(hue, df)\n xticks, xlabels = make_xaxis(\n lower=df.epsilon.min(),\n upper=df.epsilon.max(),\n n_labels=n_labels,\n ticks_per_label=ticks_per_label,\n )\n\n g = sns.relplot(\n x=\"epsilon\",\n y=\"fpr\",\n hue=hue,\n kind=\"line\",\n palette=palette,\n data=df,\n ci=80,\n hue_order=hue_order,\n legend=\"brief\",\n aspect=2,\n )\n\n if style == \"ICML\":\n plt.xlabel(r\"$\\epsilon$\")\n plt.ylabel(\"False Positive Rate\")\n plt.xticks(\n ticks=xticks,\n labels=xlabels,\n )\n plt.ylim((0, 1.01))\n transparent = False\n elif style == \"POSTER\":\n plt.xlabel(\"Value Slack\")\n plt.ylabel(\"False Positive Rate\")\n plt.xticks(\n ticks=xticks,\n labels=xlabels,\n )\n plt.ylim((0, 1.01))\n transparent = True\n elif style == \"NEURIPS\":\n plt.xlabel(r\"$\\epsilon$\")\n plt.ylabel(\"False Positive Rate\")\n plt.title(r\"$\\epsilon$-Relaxation's Effect on FPR\")\n plt.xticks(\n ticks=xticks,\n labels=xlabels,\n )\n plt.ylim((0, 1.01))\n transparent = False\n else:\n raise ValueError(f\"Style {style} not defined.\")\n\n plt.savefig(rootdir / (\"fpr.\" + ablation + \".pdf\"), transparent=transparent)\n plt.savefig(rootdir / (\"fpr.\" + ablation + \".png\"), transparent=transparent)\n closefig()\n\n # TODO(joschnei): The way I was doing this before meant that the different axes had different\n # fonts. Using sns for everything would probalby fix that, but sns is undocumented garbage.\n # Switch to pure matplotlib if you can, and figure out how sns works if you can't.\n\n\ndef plot_fnr(\n df: pd.DataFrame,\n rootdir: Path,\n ablation: str,\n style: Style,\n hue: str = \"n\",\n best_delta: bool = True,\n) -> None:\n plt.figure(figsize=(10, 10))\n\n df = df[np.isfinite(df.fnr)]\n if best_delta:\n df = get_max_delta(df, \"fnr\")\n\n palette, hue_order = get_hue(hue, df)\n xticks, xlabels = make_xaxis(lower=df.epsilon.min(), upper=df.epsilon.max())\n\n g = sns.relplot(\n x=\"epsilon\",\n y=\"fnr\",\n hue=hue,\n kind=\"line\",\n palette=palette,\n data=df,\n ci=80,\n hue_order=hue_order,\n legend=\"brief\",\n aspect=2,\n )\n\n if style == \"ICML\":\n plt.xlabel(r\"$\\epsilon$\")\n plt.ylabel(\"False Negative Rate\")\n plt.xticks(\n ticks=xticks,\n labels=xlabels,\n )\n plt.ylim((0, 1.01))\n elif style == \"POSTER\":\n raise NotImplementedError()\n elif style == \"NEURIPS\":\n raise NotImplementedError()\n else:\n raise ValueError(f\"Style {style} not defined.\")\n\n plt.savefig(rootdir / (\"fnr.\" + ablation + \".pdf\"))\n plt.savefig(rootdir / (\"fnr.\" + ablation + \".png\"))\n closefig()\n\n\ndef plot_accuracy(\n df: pd.DataFrame,\n rootdir: Path,\n ablation: str,\n style: Style,\n hue: str = \"n\",\n best_delta: bool = True,\n n_labels: int = 5,\n ticks_per_label: int = 5,\n) -> None:\n plt.figure(figsize=(10, 10))\n\n df = df.dropna(subset=[\"acc\"])\n if best_delta:\n df = get_max_delta(df, \"acc\")\n\n palette, hue_order = get_hue(hue, df)\n xticks, xlabels = make_xaxis(\n lower=df.epsilon.min(),\n upper=df.epsilon.max(),\n n_labels=n_labels,\n ticks_per_label=ticks_per_label,\n )\n\n g = sns.relplot(\n x=\"epsilon\",\n y=\"acc\",\n hue=hue,\n kind=\"line\",\n palette=palette,\n data=df,\n ci=80,\n hue_order=hue_order,\n legend=\"brief\",\n aspect=2,\n )\n\n if style == \"POSTER\":\n plt.xlabel(\"Value Slack\")\n plt.ylabel(\"Accuracy\")\n plt.xticks(\n ticks=xticks,\n labels=xlabels,\n )\n plt.ylim((0, 1.01))\n transparent = True\n elif style == \"NEURIPS\":\n plt.xlabel(r\"$\\epsilon$\")\n plt.ylabel(\"Accuracy\")\n plt.title(r\"$\\epsilon$-Relaxation's Effect on Accuracy\")\n plt.xticks(\n ticks=xticks,\n labels=xlabels,\n )\n plt.ylim((0, 1.01))\n transparent = False\n elif style == \"ICML\":\n plt.xlabel(r\"$\\epsilon$\")\n plt.ylabel(\"Accuracy\")\n plt.xticks(\n ticks=xticks,\n labels=xlabels,\n )\n plt.ylim((0, 1.01))\n transparent = False\n else:\n raise ValueError(f\"Style {style} not defined.\")\n\n plt.savefig(rootdir / (\"acc.\" + ablation + \".pdf\"), transparent=transparent)\n plt.savefig(rootdir / (\"acc.\" + ablation + \".png\"), transparent=transparent)\n closefig()\n\n\ndef plot_delta_accuracy(\n confusion_a: pd.DataFrame,\n confusion_b: pd.DataFrame,\n outdir: Path,\n ablation: str,\n style: Style,\n hue: str = \"n\",\n best_delta: bool = False,\n n_labels=6,\n ticks_per_label=5,\n) -> None:\n # confusion = pd.merge(confusion_a, confusion_b, how=\"inner\", on=\"\")\n # Clean individual dataframes\n accs = list()\n for confusion in (confusion_a, confusion_b):\n confusion = confusion.dropna(subset=[\"acc\"])\n if best_delta:\n confusion = get_max_delta(confusion, \"acc\")\n\n accs.append(pd.DataFrame(confusion.groupby([\"epsilon\", \"n\"]).mean())[[\"acc\"]])\n\n delta_acc = pd.DataFrame(accs[0] - accs[1]).reset_index()\n\n palette, hue_order = get_hue(hue, delta_acc)\n xticks, xlabels = make_xaxis(\n lower=delta_acc.epsilon.min(),\n upper=delta_acc.epsilon.max(),\n n_labels=n_labels,\n ticks_per_label=ticks_per_label,\n )\n\n sns.relplot(\n kind=\"line\",\n x=\"epsilon\",\n y=\"acc\",\n hue=hue,\n data=delta_acc,\n palette=palette,\n hue_order=hue_order,\n legend=\"brief\",\n aspect=2,\n )\n\n if style == \"POSTER\":\n plt.xlabel(\"Value Slack\")\n plt.ylabel(r\"$\\Delta$Accuracy\")\n plt.xticks(\n ticks=xticks,\n labels=xlabels,\n )\n plt.ylim((0, 1.01))\n transparent = True\n elif style == \"NEURIPS\":\n plt.xlabel(r\"$\\epsilon$\")\n plt.ylabel(r\"$\\Delta$Accuracy\")\n plt.title(r\"Accuracy improvement of active queries over random baseline\")\n plt.xticks(\n ticks=xticks,\n labels=xlabels,\n )\n plt.ylim((0, 1.01))\n transparent = False\n elif style == \"ICML\":\n plt.xlabel(r\"$\\epsilon$\")\n plt.ylabel(r\"$\\Delta$Accuracy\")\n plt.xticks(\n ticks=xticks,\n labels=xlabels,\n )\n plt.ylim((0, 1.01))\n transparent = False\n else:\n raise ValueError(f\"Style {style} not defined.\")\n\n plt.savefig(outdir / (\"delta_acc.\" + ablation + \".pdf\"), transparent=transparent)\n plt.savefig(outdir / (\"delta_acc.\" + ablation + \".png\"), transparent=transparent)\n closefig()\n\n\ndef plot_individual_fpr(\n df: pd.DataFrame,\n rootdir: Path,\n ablation: str,\n hue: str = \"n\",\n n_replications: int = 10,\n) -> None:\n palette, hue_order = get_hue(hue, df)\n xticks, xlabels = make_xaxis(lower=df.epsilon.min(), upper=df.epsilon.max())\n rows_per_replication = get_rows_per_replication(df)\n for i in range(1, n_replications + 1):\n\n g = sns.relplot(\n x=\"epsilon\",\n y=\"fpr\",\n hue=hue,\n kind=\"line\",\n palette=palette,\n data=df[rows_per_replication * (i - 1) : rows_per_replication * i],\n hue_order=hue_order,\n legend=\"brief\",\n aspect=2,\n )\n g._legend.texts[0].set_text(\"\")\n plt.xlabel(r\"$\\epsilon$\")\n plt.ylabel(\"False Positive Rate\")\n plt.title(r\"$\\epsilon$-Relaxation's Effect on FPR\")\n plt.xticks(\n ticks=xticks,\n labels=xlabels,\n )\n plt.ylim((0, 1.01))\n plt.savefig(rootdir / str(i) / (\"fpr.\" + ablation + \".pdf\"))\n plt.savefig(rootdir / str(i) / (\"fpr.\" + ablation + \".png\"))\n closefig()\n\n\ndef plot_largest_fpr(df: pd.DataFrame, rootdir: Path, ablation: str, n) -> None:\n xticks, xlabels = make_xaxis(lower=df.epsilon.min(), upper=df.epsilon.max())\n df = df[df.n == n]\n plt.figure(figsize=(10, 10))\n\n g = sns.relplot(\n x=\"epsilon\",\n y=\"fpr\",\n kind=\"line\",\n data=df,\n ci=80,\n legend=\"brief\",\n aspect=2,\n )\n\n plt.xlabel(r\"$\\epsilon$\")\n plt.ylabel(\"False Postive Rate\")\n plt.title(r\"$\\epsilon$-Relaxation's Effect on FPR\")\n plt.xticks(\n ticks=xticks,\n labels=xlabels,\n )\n plt.savefig(rootdir / (\"fpr.largest.\" + ablation + \".pdf\"))\n plt.savefig(rootdir / (\"fpr.largest.\" + ablation + \".png\"))\n closefig()\n\n\ndef plot_tp(df: pd.DataFrame, rootdir: Path, ablation: str, hue: str = \"n\") -> None:\n palette, hue_order = get_hue(hue, df)\n xticks, xlabels = make_xaxis(lower=df.epsilon.min(), upper=df.epsilon.max())\n g = sns.relplot(\n x=\"epsilon\",\n y=\"tpf\",\n hue=hue,\n kind=\"line\",\n palette=palette,\n data=df,\n ci=80,\n hue_order=hue_order,\n legend=\"brief\",\n aspect=2,\n )\n g._legend.texts[0].set_text(\"\")\n plt.xlabel(r\"$\\epsilon$\")\n plt.ylabel(\"\\% True Positives\")\n plt.title(r\"$\\epsilon$-Relaxation's Effect on TP \\%\")\n plt.xticks(\n ticks=xticks,\n labels=xlabels,\n )\n plt.ylim((0, 1.01))\n plt.savefig(rootdir / (\"tp.\" + ablation + \".pdf\"))\n plt.savefig(rootdir / (\"tp.\" + ablation + \".png\"))\n\n\ndef plot_individual_tp(\n df: pd.DataFrame,\n rootdir: Path,\n ablation: str,\n hue: str = \"n\",\n n_replications: int = 10,\n) -> None:\n palette, hue_order = get_hue(hue, df)\n xticks, xlabels = make_xaxis(lower=df.epsilon.min(), upper=df.epsilon.max())\n rows_per_replication = get_rows_per_replication(df)\n for i in range(1, n_replications + 1):\n g = sns.relplot(\n x=\"epsilon\",\n y=\"tpf\",\n hue=hue,\n kind=\"line\",\n palette=palette,\n data=df[rows_per_replication * (i - 1) : rows_per_replication * i],\n ci=80,\n hue_order=hue_order,\n legend=\"brief\",\n aspect=2,\n )\n g._legend.texts[0].set_text(\"\")\n plt.xlabel(r\"$\\epsilon$\")\n plt.ylabel(\"\\% True Positives\")\n plt.title(r\"$\\epsilon$-Relaxation's Effect on TP \\%\")\n plt.xticks(\n ticks=xticks,\n labels=xlabels,\n )\n plt.ylim((0, 1.01))\n plt.savefig(rootdir / str(i) / (\"tp.\" + ablation + \".pdf\"))\n plt.savefig(rootdir / str(i) / (\"tp.\" + ablation + \".png\"))\n closefig()\n\n\ndef comparison(\n outdir: Path,\n style: Union[str, Style],\n rootdir: Path = Path(\"data/simulated\"),\n methods: List[str] = [\"active\", \"random\"],\n test_name: str = \"comparison_point_reward_test\",\n ablation: str = \"skip_noise\",\n replications: Optional[int] = None,\n max_n: int = -1,\n use_best_delta: bool = False,\n font_size: int = 33,\n dark: bool = False,\n skip_easy: bool = True,\n verbosity: Literal[\"INFO\", \"DEBUG\"] = \"INFO\",\n) -> None:\n logging.basicConfig(level=verbosity)\n setup_plt(font_size, dark)\n max_n = int(max_n)\n rootdir = Path(rootdir)\n outdir = Path(outdir)\n\n assert len(methods) == 2, \"Exactly two methods required\"\n confusions = list()\n for method in methods:\n datadir = Path(rootdir) / method / test_name\n confusion = read_replications(datadir, ablation, replications, max_n)\n if skip_easy:\n confusion = confusion[confusion.tp + confusion.fn != 100]\n confusion = confusion[confusion.tn + confusion.fp != 100]\n confusions.append(confusion)\n\n plot_delta_accuracy(\n confusions[0],\n confusions[1],\n ablation=ablation,\n style=cast(Style, style),\n hue=\"n\",\n best_delta=use_best_delta,\n outdir=outdir,\n )\n\n\ndef gt(\n outdir: Path,\n style: Union[str, Style],\n confusion_path: Path,\n ablation: str = \"skip_noise\",\n replications: Optional[int] = None,\n max_n: int = -1,\n font_size: int = 33,\n use_dark_background: bool = False,\n skip_easy: bool = True,\n verbosity: Literal[\"INFO\", \"DEBUG\"] = \"INFO\",\n) -> None:\n setup_logging(verbosity=verbosity)\n setup_plt(font_size, use_dark_background)\n max_n = int(max_n)\n\n outdir = Path(outdir)\n outdir.mkdir(parents=True, exist_ok=True)\n confusion_path = Path(confusion_path)\n style = assert_style(style)\n\n confusion = read_replications(\n rootdir=confusion_path, ablation=ablation, replications=replications, max_n=max_n\n )\n\n if skip_easy:\n confusion = confusion[confusion.tp + confusion.fn != 100]\n confusion = confusion[confusion.tn + confusion.fp != 100]\n\n best_delta = not confusion.delta.isna().all()\n\n plot_fpr(confusion, outdir, ablation, style, hue=\"n\", best_delta=best_delta)\n plot_fnr(confusion, outdir, ablation, style, hue=\"n\", best_delta=best_delta)\n plot_accuracy(confusion, outdir, ablation, hue=\"n\", best_delta=best_delta, style=style)\n\n print(\"Best accuracy:\")\n print(confusion[confusion.acc == confusion.acc.max()])\n\n\ndef human(\n label_path: Path,\n prediction_path: Path,\n outdir: Path,\n style: Style,\n ablation: str = \"skip_noise\",\n font_size: int = 33,\n use_dark_background: bool = False,\n) -> None:\n outdir = Path(outdir)\n setup_plt(font_size, use_dark_background)\n\n confusion = make_human_confusion(\n label_path=label_path,\n prediction_path=prediction_path,\n )\n plot_fpr(confusion, outdir, ablation, style, hue=\"n\")\n plot_fnr(confusion, outdir, ablation, style, hue=\"n\")\n plot_accuracy(confusion, outdir, ablation, hue=\"n\", style=style, n_labels=6, ticks_per_label=5)\n\n print(\"Best accuracy:\")\n best_experiments = confusion[confusion.acc == confusion.acc.max()]\n print(best_experiments)\n print(best_experiments.epsilon.min())\n print(best_experiments.epsilon.max())\n\n\nif __name__ == \"__main__\":\n fire.Fire({\"comparison\": comparison, \"gt\": gt, \"human\": human})\n","repo_name":"sgiguere/value-alignment-verification","sub_path":"graphs.py","file_name":"graphs.py","file_ext":"py","file_size_in_byte":24936,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"81"} +{"seq_id":"20550477756","text":"\n# targets=[\"data\", \"set_large_gaps_for_cc\"]\n\n# targets=[\"set1_1000_1000_map\", \"set2_1500_1500_map\", \"set3_2000_2000_map\", \"set4_2500_2500_map\", \"set5_3000_3000_map\",\n# \"set6_3500_3500_map\"]\n\ntargets=[\"set_large_gaps_for_cc\"]\n\ndata=[[] for i in range(len(targets))]\n\nprefix=\"../../out/runtime_growth/\"\nsufix=\"_targets.csv\"\n\nz=0\nfor k in targets:\n\tfor i in range(1, 21):\n\t\twith open(prefix+k+\"/\"+str(i*50)+sufix) as f:\n\t\t\tlines=f.readlines()\n\t\t\tlines=lines[1:]\n\t\t\tj=0\n\t\t\tminval=0\n\t\t\tfor x in lines :\n\t\t\t\trow=x.rstrip('\\n').split(',')\n\t\t\t\tif j==0 :\n\t\t\t\t\tj+=1\n\t\t\t\t\tminval=float(row[6])\n\t\t\t\tif minval > float(row[6]):\n\t\t\t\t\tminval=float(row[6])\n\t\t\tif minval != 0 :\n\t\t\t\tdata[z].append([float(row[6]), float(row[7]), float(row[8]), float(row[9])])\n\t\t\telse :\n\t\t\t\tprint(\"\\\"DANGER!!!\\\", Mystikal\")\n\tz+=1\n\nfor k in range(len(data)):\n\n\tf=open(\"../outs/\"+targets[k]+\"_results_runtimes.csv\",\"w\")\n\n\tf.write(\"# tot runtime, time_spent_1st_phase, time_spent_lp_prblm, time_spent_cc_phase\\n\")\n\n\tfor i in range(len(data[k])) :\n\t\tf.write(str(data[k][i][0])+\",\"+str(data[k][i][1])+\",\"+str(data[k][i][2])+\",\"+str(data[k][i][3])+\"\\n\")\n\n\tf.close()\n","repo_name":"omahaDonorLD/UavsTargetsCovering","sub_path":"srcs/scripts/pythonscripts/find_min_evol_growth.py","file_name":"find_min_evol_growth.py","file_ext":"py","file_size_in_byte":1124,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"15089188648","text":"from exceptions import CustomError\nfrom models import AlexNet, VGGNet, Model, ModelFactory\nfrom models.Strategies_Train import DataAugmentation, Strategy, UnderSampling, OverSampling\nfrom optimizers import GA, PSO, Optimizer, OptimizerFactory\nimport Data\nimport pandas as pd\nimport numpy as np\nfrom sklearn.model_selection import train_test_split\nimport keras\nfrom keras.models import load_model\nimport config\nimport config_func\nimport os\nos.environ[\"TF_CPP_MIN_LOG_LEVEL\"]=\"2\"\n#os.environ[\"CUDA_VISIBLE_DEVICES\"]=\"-1\" #THIS LINE DISABLES GPU OPTIMIZATION\n\ndef main():\n\n print(\"\\n###############################################################\")\n print(\"##########################DATA PREPARATION#####################\")\n print(\"###############################################################\\n\")\n\n # acess image data\n PROJECT_DIR = os.getcwd()\n INPUT_DIR = os.path.join(PROJECT_DIR, config.INPUT_DIR) # path of input directory\n IMAGES_DIR = os.path.join(INPUT_DIR, config.IMAGES_ACESS)\n\n # define paths for all classes (stroma, tumor, mucosa, empty, lympho, adipose, complex, debris)\n STROMA_FOLDER = os.path.join(IMAGES_DIR, config.STROMA_DIR, config.IMAGES_REGEX)\n TUMOR_FOLDER = os.path.join(IMAGES_DIR, config.TUMOR_DIR, config.IMAGES_REGEX)\n MUCOSA_FOLDER = os.path.join(IMAGES_DIR, config.MUCOSA_DIR, config.IMAGES_REGEX)\n EMPTY_FOLDER = os.path.join(IMAGES_DIR, config.EMPTY_DIR, config.IMAGES_REGEX)\n LYMPHO_FOLDER = os.path.join(IMAGES_DIR, config.LYMPHO_DIR, config.IMAGES_REGEX)\n ADIPOSE_FOLDER = os.path.join(IMAGES_DIR, config.ADIPOSE_DIR, config.IMAGES_REGEX)\n COMPLEX_FOLDER = os.path.join(IMAGES_DIR, config.COMPLEX_DIR, config.IMAGES_REGEX)\n DEBRIS_FOLDER = os.path.join(IMAGES_DIR, config.DEBRIS_DIR, config.IMAGES_REGEX)\n LIST_CLASSES_FOLDER = [\n STROMA_FOLDER, TUMOR_FOLDER, MUCOSA_FOLDER, EMPTY_FOLDER,\n LYMPHO_FOLDER, ADIPOSE_FOLDER, COMPLEX_FOLDER, DEBRIS_FOLDER\n ]\n\n # get images from all folders\n # classes targets --> 0: Stroma, 1: Tumor, 2: Mucosa, 3: Empty, 4: Lympho, 5: Adipose, 6: Complex, 7: Debris\n images = []\n labels = []\n for i, j in zip(LIST_CLASSES_FOLDER, range(config.NUMBER_CLASSES)):\n images.append(config_func.getImages(i))\n labels.extend([j for i in range(len(images[j]))])\n\n # flatten images list\n images = [path for sublist in images for path in sublist]\n\n # construct DataFrame with two columns: (image_path, target)\n data = pd.DataFrame(\n list(zip(images, labels))\n ,columns=[config.IMAGE_PATH, config.TARGET])\n\n # subsample data, if not wanted, rate 1 should be passed\n if config.SUBSAMPLE_PERCENTAGE != 1:\n data = config_func.get_subsample_of_data(1, data)\n print(data.head(5))\n print(data.shape)\n print(data[config.TARGET].value_counts())\n\n # get pixel data from images and respectives targets\n X, Y = config_func.resize_images(config.WIDTH, config.HEIGHT, data)\n print(X.shape)\n print(Y.shape)\n\n # STRATIFY X_TEST, X_VAL AND X_TEST\n X_train, X_val, y_train, y_val = train_test_split(X, Y, test_size=config.VALIDATION_SPLIT, shuffle=True,\n random_state=config.RANDOM_STATE, stratify=Y)\n\n X_train, X_test, y_train, y_test = train_test_split(X_train, y_train, test_size=config.TEST_SPLIT,\n shuffle=True, random_state=config.RANDOM_STATE, stratify=y_train)\n\n # normalization of data\n X_train, X_val, X_test = config_func.normalize(X_train, X_val, X_test)\n\n # one-hot encoding targets\n y_train, y_val, y_test = config_func.one_hot_encoding(y_train=y_train, y_val=y_val, y_test=y_test)\n\n print(\"\\n###############################################################\")\n print(\"##########################CLASSIFICATION#######################\")\n print(\"###############################################################\\n\")\n\n # creation of Data instance\n data_obj = Data.Data(X_train=X_train, X_val=X_val, X_test=X_test,\n y_train=y_train, y_val=y_val, y_test=y_test)\n\n # creation of Factory model's instance\n model_factory = ModelFactory.ModelFactory()\n\n # creation of Factory optimization algorithms instance\n optimization_factory = OptimizerFactory.OptimizerFactory()\n\n # definition of train strategies instances\n data_augment = DataAugmentation.DataAugmentation()\n\n ## ---------------------------ALEXNET APPLICATION ------------------------------------\n\n # number of conv layers and dense respectively\n alex_number_layers = (\n 5,\n 1\n )\n\n # creation of AlexNet instance\n alexNet = model_factory.getModel(config.ALEX_NET, data_obj, *alex_number_layers)\n\n # apply strategies to alexNet\n alexNet.addStrategy(data_augment)\n\n # definition of args to pass to template_method (conv's number of filters, dense neurons and batch size)\n alex_args = (\n 2, # number of normal convolutional layer (+init conv)\n 2, # number of stack cnn layers\n 70, # number of feature maps of initial conv layer\n 19, # growth rate\n 1, # number of FCL Layers\n 43, # number neurons of Full Connected Layer\n 9# batch size\n )\n\n # apply build, train and predict\n #model, predictions, history = alexNet.template_method(*alex_args)\n ##alexNet.save(model, config.ALEX_NET_WEIGHTS_FILE)\n\n # print final results\n #config_func.print_final_results(y_test=data_obj.y_test, predictions=predictions, history=history, dict=False)\n\n ## ---------------------------VGGNET APPLICATION ------------------------------------\n\n # number of conv layers and dense respectively\n vgg_number_layers = (\n 4,\n 1\n )\n\n # creation of VGGNet instance\n vggnet = model_factory.getModel(config.VGG_NET, data_obj, *vgg_number_layers)\n\n # apply strategies to vggnet\n vggnet.addStrategy(data_augment)\n\n # definition of args to pass to template_method (conv's number of filters, dense neurons and batch size)\n\n vgg_args = (\n 4, # number of stack cnn layers (+ init stack)\n 64, # number of feature maps of initial conv layer\n 12, # growth rate\n 1, # number of FCL Layers\n 16, # number neurons of Full Connected Layer\n config.BATCH_SIZE_ALEX_AUG # batch size\n )\n\n # apply build, train and predict\n #model, predictions, history = vggnet.template_method(*vgg_args)\n ##vggnet.save(model, config.VGG_NET_WEIGHTS_FILE)\n\n # print final results\n #config_func.print_final_results(y_test=data_obj.y_test, predictions=predictions, history=history, dict=False)\n\n ## ---------------------------RESNET APPLICATION ------------------------------------\n\n # number of conv and dense layers respectively\n number_cnn_dense = (5, 1)\n\n # creation of ResNet instance\n resnet = model_factory.getModel(config.RES_NET, data_obj, *number_cnn_dense)\n\n # apply strategies to resnet\n resnet.addStrategy(data_augment)\n\n # definition of args to pass to template_method (conv's number of filters, dense neurons and batch size)\n resnet_args = (\n 48, # number of filters of initial CNN layer\n 4, # number of consecutive conv+identity blocks\n 0, # repetition of identity block's, by default resnet-18 is 1 (1conv block + 1 identity block) for all layers\n 8, # growth rate\n config.BATCH_SIZE_ALEX_AUG, # batch size\n )\n\n # apply build, train and predict\n #model, predictions, history = resnet.template_method(*resnet_args)\n ##resnet.save(model, config.RES_NET_WEIGHTS_FILE)\n\n # print final results\n #config_func.print_final_results(y_test=data_obj.y_test, predictions=predictions, history=history, dict=False)\n\n ## ---------------------------DENSENET APPLICATION ------------------------------------\n\n # # DICTIONARIES DEFINITION\n numberLayers = (\n 4, #BLOCKS\n 1 #DENSE LAYERS\n )\n\n valuesLayers = (\n 24, # initial number of Feature Maps\n 4, # number of dense blocks\n 5, # number of layers in each block\n 12, # growth rate\n 0.5, # compression rate\n config.BATCH_SIZE_ALEX_AUG # batch size\n )\n\n densenet = model_factory.getModel(config.DENSE_NET, data_obj, *numberLayers)\n\n densenet.addStrategy(data_augment)\n\n model, predictions, history = densenet.template_method(*valuesLayers)\n\n config_func.print_final_results(data_obj.y_test, predictions, history)\n\n ## --------------------------- ENSEMBLE OF MODELS ------------------------------------\n\n # get weights of all methods from files\n # alexNet = load_model(config.ALEX_NET_WEIGHTS_FILE)\n # vggnet = load_model(config.VGG_NET_WEIGHTS_FILE)\n # resnet = load_model(config.RES_NET_WEIGHTS_FILE)\n #\n # models = [alexNet, vggnet, resnet]\n #\n # ##call ensemble method\n # ensemble_model = config_func.ensemble(models=models)\n # predictions = ensemble_model.predict(data_obj.X_test)\n # argmax_preds = np.argmax(predictions, axis=1) # BY ROW, BY EACH SAMPLE\n # argmax_preds = keras.utils.to_categorical(argmax_preds)\n #\n # ## print final results\n # config_func.print_final_results(data_obj.y_test, argmax_preds, history=None, dict=False)\n\n ## --------------------------- PSO ------------------------------------------------\n\n # optimizer fabric object\n # opt_fact = OptimizerFactory.OptimizerFactory()\n #\n # # definition models optimizers\n # pso_alex = opt_fact.createOptimizer(config.PSO_OPTIMIZER, alexNet, *config.pso_init_args_alex)\n # pso_vgg = opt_fact.createOptimizer(config.PSO_OPTIMIZER, vggnet, *config.pso_init_args_vgg)\n # pso_resnet = opt_fact.createOptimizer(config.PSO_OPTIMIZER, resnet, *config.pso_init_args_resnet)\n # pso_dense = opt_fact.createOptimizer(config.PSO_OPTIMIZER, densenet, *config.pso_init_args_densenet)\n #\n # # optimize and print best cost\n # cost, pos, optimizer = pso_resnet.optimize()\n # print(\"Custo: {}\".format(cost))\n # config_func.print_Best_Position_PSO(pos, config.RES_NET) # print position\n # pso_resnet.plotCostHistory(optimizer)\n # pso_resnet.plotPositionHistory(optimizer, np.array(config.X_LIMITS), np.array(config.Y_LIMITS), config.PSO_POSITION_ITERS,\n # config.LABEL_X_AXIS, config.LABEL_Y_AXIS)\nif __name__ == \"__main__\":\n main()","repo_name":"bundasmanu/Colorectal_Histopathology","sub_path":"Main.py","file_name":"Main.py","file_ext":"py","file_size_in_byte":10419,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"7842635307","text":"import os\r\nimport xlrd\r\nimport openpyxl\r\n\r\n# 定义一个函数,用于将.xls文件转换为.xlsx文件\r\ndef convert_xls_to_xlsx(folder_path):\r\n for file_name in os.listdir(folder_path):\r\n # 判断文件是否为.xls文件\r\n if file_name.endswith('.xls'):\r\n file_path = os.path.join(folder_path, file_name)\r\n # 使用xlrd库打开.xls文件,并读取数据\r\n workbook = xlrd.open_workbook(file_path)\r\n sheets = workbook.sheet_names()\r\n data = {}\r\n for sheet_name in sheets:\r\n sheet = workbook.sheet_by_name(sheet_name)\r\n rows = []\r\n for row_idx in range(sheet.nrows):\r\n row = []\r\n for col_idx in range(sheet.ncols):\r\n cell_value = sheet.cell_value(row_idx, col_idx)\r\n row.append(cell_value)\r\n rows.append(row)\r\n data[sheet_name] = rows\r\n # 使用openpyxl库将数据写入新的.xlsx文件\r\n new_file_name = file_name.replace('.xls', '.xlsx')\r\n new_file_path = os.path.join(folder_path, new_file_name)\r\n workbook = openpyxl.Workbook()\r\n for sheet_name, rows in data.items():\r\n sheet = workbook.create_sheet(sheet_name)\r\n for row_idx, row in enumerate(rows):\r\n for col_idx, cell_value in enumerate(row):\r\n sheet.cell(row=row_idx+1, column=col_idx+1, value=cell_value)\r\n workbook.save(new_file_path)\r\n print(\"转换完毕:)\")\r\n\r\n# 定义一个函数,用于删除指定路径下的所有后缀为.xls的文件\r\ndef delete_xls_files(folder_path):\r\n for filename in os.listdir(folder_path):\r\n if filename.endswith('.xls'):\r\n os.remove(os.path.join(folder_path, filename))\r\n print(f'{filename} has been deleted.')\r\n print(\"删除完毕:)\")\r\n\r\n# 定义一个函数,用于将多个Excel文件中的数据整合到一个新的Excel文件中\r\ndef merge_excel_files(folder_path, output_file_path):\r\n workbook = openpyxl.Workbook()\r\n workbook.remove(workbook.active)\r\n for file_name in os.listdir(folder_path):\r\n # 判断文件是否为Excel文件\r\n if file_name.endswith('.xlsx'):\r\n file_path = os.path.join(folder_path, file_name)\r\n # 使用openpyxl库读取Excel文件中的数据,并写入新的Excel文件中\r\n file_name_without_ext = os.path.splitext(file_name)[0]\r\n workbook.create_sheet(file_name_without_ext)\r\n excel_file = openpyxl.load_workbook(file_path)\r\n for sheet_name in excel_file.sheetnames:\r\n sheet = excel_file[sheet_name]\r\n new_sheet = workbook[file_name_without_ext]\r\n for row_idx, row in enumerate(sheet.iter_rows()):\r\n for col_idx, cell in enumerate(row):\r\n new_sheet.cell(row=row_idx+1, column=col_idx+1, value=cell.value)\r\n # 保存新的Excel文件\r\n workbook.save(output_file_path)\r\n print(\"整合完毕:)\")\r\n\r\n# 定义一个函数,用于将该文件中所有有数据的sheet中有数据的单元格进行居中操作\r\ndef center_cells_in_xlsx(filename):\r\n wb = openpyxl.load_workbook(filename)\r\n for sheet_name in wb.sheetnames:\r\n sheet = wb[sheet_name]\r\n for row in sheet.iter_rows():\r\n for cell in row:\r\n if cell.value is not None:\r\n cell.alignment = openpyxl.styles.Alignment(horizontal='center', vertical='center')\r\n wb.save(filename)\r\n print(\"居中完毕:)\")\r\n\r\n# 定义一个函数,用于扩展该文件中所有有数据的列宽\r\nimport openpyxl\r\ndef adjust_column_width_in_xlsx(filename):\r\n wb = openpyxl.load_workbook(filename)\r\n for sheet_name in wb.sheetnames:\r\n sheet = wb[sheet_name]\r\n for column in sheet.columns:\r\n max_length = 0\r\n column_letter = openpyxl.utils.get_column_letter(column[0].column)\r\n for cell in column:\r\n try:\r\n if len(str(cell.value)) > max_length:\r\n max_length = len(str(cell.value)) + 1\r\n except:\r\n pass\r\n adjusted_width = max_length + 15\r\n sheet.column_dimensions[column_letter].width = adjusted_width\r\n wb.save(filename)\r\n print(\"列宽修改完毕:)\")\r\n\r\nif __name__ == '__main__':\r\n folder_path = r'D:\\(程序设计)Python\\2.编程题练习\\3.Excel指令\\文件集合'\r\n output_file_path = r'D:\\(程序设计)Python\\2.编程题练习\\3.Excel指令\\志愿活动 x.xx-x.xx.xlsx'\r\n\r\n # 调用convert_xls_to_xlsx函数将文件夹中的.xls文件转换为.xlsx文件\r\n convert_xls_to_xlsx(folder_path)\r\n\r\n # 调用delete_xls_files函数将文件夹中的.xls文件删除\r\n delete_xls_files(folder_path)\r\n\r\n # 调用merge_excel_files函数将多个Excel文件中的数据整合到一个新的Excel文件中\r\n merge_excel_files(folder_path, output_file_path)\r\n\r\n # 调用center_cells_in_xlsx函数将该Excel中所有有数据的sheet中有数据的单元格进行居中操作\r\n center_cells_in_xlsx(output_file_path)\r\n\r\n # 调用expand_column_width_in_xlsx函数,扩展该Excel中所有有数据的列宽\r\n adjust_column_width_in_xlsx(output_file_path)","repo_name":"Explorer-Dong/sth_about_excel","sub_path":"function.py","file_name":"function.py","file_ext":"py","file_size_in_byte":5417,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"13923894017","text":"def data_sort(list):\n l = len(list)\n for i in range(0, l):\n for j in range(i + 1, l):\n if list[i] > list[j]:\n list[i], list[j] = list[j], list[i]\n return list\n\n\ndef get_median(a):\n a_len = len(a)\n if (a_len == 0): return None\n a_center = int(a_len / 2)\n return a[a_center]\n\n\n\ndata = [[55, 33, 250, 44], [88, 1, 67, 23], [199, 222, 38, 47], [155, 145, 20, 99]]\ndata1 = []\n\nfor i in range(0, len(data)):\n for j in range(0, len(data[i])):\n data1.append(data[i][j])\n\nprint(f'1차원 변경 후, 정렬 전 -> {data1}')\ndata_sort(data1)\nprint(f'1차원 변경 후, 정렬 후 -> {data1}')\nprint(f'중앙값 -> {get_median(data1)}')\n","repo_name":"Kyj97/day19","sub_path":"day19_4.py","file_name":"day19_4.py","file_ext":"py","file_size_in_byte":691,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"17466672515","text":"\"\"\"Initial migration\n\nRevision ID: 139f09a39256\nRevises: \nCreate Date: 2023-04-19 21:27:29.321571\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '139f09a39256'\ndown_revision = None\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade() -> None:\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_table('ingredients',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('name', sa.String(length=30), nullable=False),\n sa.Column('measurement_unit', sa.String(length=30), nullable=False),\n sa.PrimaryKeyConstraint('id')\n )\n op.create_table('recipes',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('name', sa.String(length=30), nullable=False),\n sa.Column('description', sa.String(), nullable=True),\n sa.Column('instructions', sa.String(), nullable=True),\n sa.PrimaryKeyConstraint('id')\n )\n # ### end Alembic commands ###\n\n\ndef downgrade() -> None:\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_table('recipes')\n op.drop_table('ingredients')\n # ### end Alembic commands ###\n","repo_name":"xenizs/python-api-no-framework","sub_path":"migrations/versions/139f09a39256_initial_migration.py","file_name":"139f09a39256_initial_migration.py","file_ext":"py","file_size_in_byte":1155,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"12252247312","text":"import numpy as np\nimport argparse\n\n\ndef main():\n\tparser = argparse.ArgumentParser()\n\tparser.add_argument(\"Ng\", type=float, help=\"Total number of logic gates in the design\")\n\tparser.add_argument(\"k\", type=float, help=\"Rent constant for the design\")\n\tparser.add_argument(\"p\", type=float, help=\"Rent exponent for the design\")\n\tparser.add_argument(\"tiers\", type=int, help=\"Number of tiers in the 3D stack\")\n\targs = parser.parse_args()\n\n\tNg = args.Ng\n\tk = args.k\n\tp = args.p\n\ttiers = args.tiers\n\t( conn_tot, conn_per_layer, conn_to, conn_through ) = report_tsv_requirements_single_config(Ng, k, p, tiers)\n\n\ndef report_tsv_requirements_single_config(Ng, k, p, tiers):\n\t( conn_tot, conn_per_layer, conn_to, conn_through ) = calc_tsv_requirements(Ng, k, p, tiers)\n\tprint_tsv_requirements_detailed(Ng, k, p, tiers, conn_tot, conn_per_layer, conn_to, conn_through)\n\n\treturn ( conn_tot, conn_per_layer, conn_to, conn_through )\n\n\ndef print_tsv_requirements_detailed(Ng, k, p, tiers, conn_tot, conn_per_layer, conn_to, conn_through):\n\tfstr_header = \"{0:>14s} {1:>14s} {2:>14s} {3:>14s}\"\n\tfstr_data = \"{0:>14.3g} {1:>14.3f} {2:>14.3f} {3:>14d}\"\n\theader = fstr_header.format(\"Num Gates\", \"Rent k\", \"Rent p\", \"Num Tiers\")\n\tdstr = fstr_data.format(Ng, k, p, int(tiers))\n\tprint(header)\n\tprint(dstr)\n\tprint()\n\n\thstr = \"{0:>14s} {1:>14s} {2:>14s} {3:>14s}\"\n\tfstr_data = \"{0:>14d} {1:>14.3g} {2:>14.3g} {3:>14.3g}\"\n\theader = hstr.format(\"Tier\", \"Vias_tot\", \"Vias_to\", \"Vias_through\")\n\tprint(header)\n\tfor tier in range(tiers):\n\t\tdstr = fstr_data.format(tier, conn_per_layer[tier], conn_to[tier], conn_through[tier])\n\t\tprint(dstr)\n\n\tprint()\n\tprint( \"{0:>14s}\".format(\"Total Vias\") )\n\tprint( \"{0:>14.3g}\".format(conn_tot) )\n\n\ndef get_total_tsvs_for_diff_num_tiers(Ng, k, p, max_tiers):\n\t# Will return a vector of the number of TSVs needed for this design implemented\n\t# with n=1:max_tiers tiers\n\n\tconn_tot_vec = np.zeros((max_tiers))\n\tconn_per_layer_list = []\n\tconn_to_list = []\n\tconn_through_list = []\n\tfor nind in range(max_tiers):\n\t\ttiers = nind+1\n\t\t( conn_tot, conn_per_layer, conn_to, conn_through ) = calc_tsv_requirements(Ng, k, p, tiers)\n\t\tconn_tot_vec[nind] = conn_tot\n\t\tconn_per_layer_list.append(conn_per_layer)\n\t\tconn_to_list.append(conn_to)\n\t\tconn_through_list.append(conn_through)\n\n\treturn (conn_tot_vec, conn_per_layer_list, conn_to_list, conn_through_list)\n\n\ndef calc_Tac(Ns, k, p, tier1_ind, tier2_ind):\n\tbac = max(0,tier2_ind - tier1_ind -1) # bac = number of tiers BETWEEN tiers 1 and 2\n\tTac = 2*k*Ns**p * (bac + 1) - k*Ns**p * (bac + 2)**p - k*(bac*Ns)**p\n\n\treturn Tac\n\n\ndef calc_connections_through_tier(Ns, k, p, tier_ind, num_tiers):\n\tconn_through = 0\n\tfor bot_tier in range(tier_ind):\n\t\tfor top_tier in range(tier_ind+1,num_tiers):\n\t\t\tTac = calc_Tac(Ns, k, p, bot_tier, top_tier)\n\t\t\tconn_through += Tac\n\n\treturn conn_through\n\n\ndef calc_connections_through(Ns, k, p, num_tiers):\n\tconn_through = np.zeros(num_tiers)\n\tfor tier in range(num_tiers):\n\t\tconn_through[tier] = calc_connections_through_tier(Ns, k, p, tier, num_tiers)\n\n\treturn conn_through\n\n\ndef calc_connections_to_tier(Ns, k, p, tier, num_tiers):\n\t# Assumes F2B bonding style\n\t# Connections to tiers below do not require TSVs\n\t# Connections to tiers above require TSVs\n\tconn_to = 0\n\tfor dest_tier in range(tier+1,num_tiers):\n\t\tconn_to += calc_Tac(Ns, k, p, tier, dest_tier)\n\n\treturn conn_to\n\n\ndef calc_connections_to(Ns, k, p, num_tiers):\n\tconn_to = np.zeros(num_tiers)\n\tfor tier in range(num_tiers):\n\t\tconn_to[tier] = calc_connections_to_tier(Ns, k, p, tier, num_tiers)\n\n\treturn conn_to\n\n\ndef calc_tsv_requirements(Ng, k, p, num_tiers):\n\tNs = Ng/num_tiers\n\tconn_to = calc_connections_to(Ns, k, p, num_tiers)\n\tconn_through = calc_connections_through(Ns, k, p, num_tiers)\n\tconn_per_layer = conn_to + conn_through # Total TSVs in each layer\n\tconn_tot = np.sum(conn_per_layer)\n\n\treturn ( conn_tot, conn_per_layer, conn_to, conn_through )\n\n\nif (__name__ == \"__main__\"):\n\tmain()\n","repo_name":"wwahby/tsv_predict","sub_path":"tsv_predict.py","file_name":"tsv_predict.py","file_ext":"py","file_size_in_byte":3952,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"10014508948","text":"from ..base.error import HeatingError\n\nimport os.path\nimport os\nimport time\n\n_root = '/sys/class/gpio'\n\nIN, OUT = 0, 1\n\ndef create(number):\n path = '%s/gpio%d' % (_root, number)\n if not os.path.exists(path):\n open(_root + '/export', 'w').write(str(number)+'\\n')\n\n # wait for files to appear before using it any further. this\n # happened to be a problem on Raspi's 3.12.28+ #709, at least,\n # where it said EACCESS on the 'direction' file when using it \"too\n # early\" after export.\n direction = path + '/direction'\n num_tries = 100\n while not os.access(direction, os.R_OK|os.W_OK):\n time.sleep(0.05)\n num_tries -= 1\n if num_tries == 0:\n raise HeatingError(direction + \" didn't become rw-able after 100 tries\")\n\n return _SysFS_GPIO(number)\n\nclass _SysFS_GPIO:\n\n __HI = '1\\n'\n __LO = '0\\n'\n \n def __init__(self, number):\n self.__number = number\n self.__value = '%s/gpio%d/value' % (_root, number)\n self.__direction = '%s/gpio%d/direction' % (_root, number)\n def __del__(self):\n open(_root + '/unexport', 'w').write(str(self.__number)+'\\n')\n def set_direction(self, inout):\n assert inout in (IN, OUT)\n open(self.__direction, 'w').write(inout == IN and 'in' or 'out')\n def get_direction(self):\n return open(self.__direction, 'r').read() == 'in\\n' and IN or OUT\n def set_value(self, value):\n f = open(self.__value, 'w')\n if value:\n f.write(self.__HI)\n else:\n f.write(self.__LO)\n def get_value(self):\n f = open(self.__value, 'r')\n content = f.read()\n f.close()\n\n if content == self.__LO:\n return 0\n elif content == self.__HI:\n return 1\n assert False, content\n","repo_name":"jfasch/openheating","sub_path":"try-no1/openheating/hardware/gpio.py","file_name":"gpio.py","file_ext":"py","file_size_in_byte":1804,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"81"} +{"seq_id":"73670559626","text":"import os\nimport glob\nimport numpy as np\n\n\nclass Indexer:\n def __init__(self, repo_dir, validate_mode, training):\n self.repo_dir = repo_dir\n self.validate_mode = validate_mode\n self.training = training\n if training or validate_mode:\n self.max_rep_count = 3\n self.safety_flags = {}\n par_dir = os.path.dirname(os.path.normpath(repo_dir))\n safety_file = os.path.join(par_dir, 'train_and_test_data_labels_safe.csv')\n safety_info = np.loadtxt(safety_file, dtype=str, delimiter=',', skiprows=1)\n self.safety_flags = {line[0].split('.')[0]: line[2] == '1' for line in safety_info}\n self.segm_idx = 1\n else:\n self.segm_idx = 2\n\n def make_filename(self, path, set_name):\n assert os.path.exists(path), 'Path not found: %s' % path\n filename = set_name + '-index.csv'\n idx_file = os.path.join(path, filename)\n return idx_file\n\n def tokenize(self, filename):\n return filename.split('.')[0].split('_')\n\n def get_segm(self, filename):\n return int(self.tokenize(filename)[self.segm_idx])\n\n def get_label(self, filename):\n return int(self.tokenize(filename)[-1])\n\n def is_safe(self, filename):\n assert self.training is True or self.validate_mode is True\n key = os.path.basename(filename).split('.')[0]\n if key in self.safety_flags:\n return self.safety_flags[key]\n return False\n\n def run(self, elec, set_name):\n tain_path = self.repo_dir\n test_path = tain_path.replace('train', 'test') + '_new'\n path = tain_path if (self.training or self.validate_mode) else test_path\n idx_file = self.make_filename(path, set_name)\n if os.path.exists(idx_file):\n return idx_file\n\n print('Creating %s...' % idx_file)\n pattern = '*.' + str(elec) + '.wav'\n files = glob.glob(os.path.join(path, pattern))\n assert len(files) > 0, 'No .wav files found in %s' % path\n if self.training or self.validate_mode:\n files = filter(lambda x: self.is_safe(x), files)\n files = sorted(map(os.path.basename, files))\n files = sorted(files, key=lambda x: self.get_segm(x))\n\n if self.training or self.validate_mode:\n chosen_files, labels = self.choose(files)\n else:\n chosen_files, labels = files, np.zeros(len(files))\n\n if self.training and not self.validate_mode:\n self.append_old_test(chosen_files, labels, elec)\n\n with open(idx_file, 'w') as fd:\n fd.write('filename,label\\n')\n for filename, label in zip(chosen_files, labels):\n fd.write(filename + ',' + str(label) + '\\n')\n return idx_file\n\n def append_old_test(self, files, labels, elec):\n path = self.repo_dir.replace('train', 'test')\n pattern = '*.' + str(elec) + '.wav'\n test_files = glob.glob(os.path.join(path, pattern))\n test_files = sorted(map(os.path.basename, test_files))\n for filename in test_files:\n if not self.is_safe(filename):\n continue\n filename = os.path.join(os.path.pardir, os.path.basename(path),\n os.path.basename(filename))\n for i in range(self.max_rep_count + 2):\n files.append(filename)\n labels.append(1)\n\n def choose(self, files):\n train_percent = 70 if self.validate_mode else 100\n nfiles = []\n pfiles = []\n for fname in files:\n if self.get_label(fname) == 0:\n nfiles.append(fname)\n else:\n pfiles.append(fname)\n psegms = np.unique([self.get_segm(f) for f in pfiles])\n nsegms = np.unique([self.get_segm(f) for f in nfiles])\n pmax = (np.max(psegms) * train_percent) // 100\n nmax = (np.max(nsegms) * train_percent) // 100\n\n chosen_files = []\n labels = []\n for filename in files:\n label = self.get_label(filename)\n max_hour = nmax if label == 0 else pmax\n segm = self.get_segm(filename)\n hour = segm - (segm - 1) % 6\n if self.training and hour > max_hour:\n continue\n if not self.training and hour <= max_hour:\n continue\n if self.training:\n # Repeat recent samples.\n rep_count = ((self.max_rep_count * hour) / max_hour) + 1\n else:\n rep_count = 1\n for i in range(rep_count):\n chosen_files.append(filename)\n labels.append(label)\n return chosen_files, labels\n","repo_name":"anlthms/sp-2016","sub_path":"indexer.py","file_name":"indexer.py","file_ext":"py","file_size_in_byte":4713,"program_lang":"python","lang":"en","doc_type":"code","stars":21,"dataset":"github-code","pt":"81"} +{"seq_id":"21818820828","text":"def string_comp(st):\n res = []\n count = 0\n former = None\n for c in st:\n count += 1\n if(not former):\n former = c\n res.append(c)\n elif(former == c):\n continue\n else:\n res.append(str(count))\n count = 0\n res.append(c)\n former = c\n res.append(str(count))\n ret_st = \"\" \n return ret_st.join(res)\n\nst = \"aabcccccaaa\"\n\nprint(string_comp(st))","repo_name":"kmzn128/CCI_Python","sub_path":"CCI_1/CCI_1/1_6_2.py","file_name":"1_6_2.py","file_ext":"py","file_size_in_byte":461,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"32240943291","text":"#!/usr/bin/env python\n# -*- coding:utf-8 -*- \n# Author: Jia ShiLin\n\nclass Solution:\n def diStringMatch(self, S: str) -> List[int]:\n N = len(S)\n A = []\n o = 0\n j = N\n for i in range(N):\n if S[i] == 'I':\n A.append(o)\n o += 1\n\n elif S[i] == 'D':\n A.append(j)\n j -= 1\n A.append(j)\n return A\n","repo_name":"alanjia163/BH","sub_path":"942. 增减字符串匹配.py","file_name":"942. 增减字符串匹配.py","file_ext":"py","file_size_in_byte":421,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"31066341513","text":"import pandas as pd\nimport plotly.express as px\nfrom dash import Dash, dcc, html\nfrom dash.dependencies import Input, Output\n\napp = Dash(__name__)\ndf = pd.read_csv('data\\daily_sales_data.csv')\ndf.sort_values('date')\n\ntab_style = {\n 'borderBottom': '1px solid #d6d6d6',\n 'padding': '6px',\n 'fontWeight': 'bold'\n}\n\ndef build_graph(df):\n return px.line(df, x='date', y='sales', height=650, width=1300)\n\napp.layout = html.Div([\n html.H1(id='header', children=\"Pink morsel price visualizer\", style={'textAlign':'center'}),\n dcc.Tabs(id=\"region-picker\", value='all', children=[\n dcc.Tab(label='All', value='all'),\n dcc.Tab(label='North', value='north'),\n dcc.Tab(label='South', value='south'),\n dcc.Tab(label='East', value='east'),\n dcc.Tab(label='West', value='west'),\n ], style=tab_style),\n html.Div(id='graph-container', children=[dcc.Graph(id='graph', figure=build_graph(df))], \n )\n])\n\n\n@app.callback(Output('graph-container', 'children'),\n Input('region-picker', 'value'))\ndef render_graph(tab):\n m = df if tab=='all' else df[df['region']==tab]\n return dcc.Graph(figure = build_graph(m), id='graph')\n \n\nif __name__ == '__main__':\n app.run_server(debug=True)\n","repo_name":"starlord-amha/quantium-virtual-program","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1245,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"4589400330","text":"import matplotlib.pyplot as plt\nimport matplotlib.style\n\n# ggplotスタイルを指定\nmatplotlib.style.use('ggplot')\n\n# MATLABスタイル\n\"\"\"\nMATLABスタイルは数値解析ソフトウェアである\nMATLABと似た形式\n\"\"\"\n# データを用意\nx = [1, 2, 3]\ny = [2, 4, 9]\n\nplt.plot(x, y) # ���れ線グラフを描画\nplt.title('MATLAB-style') # グラフにタイトルを設定\n\nplt.show() # グラフを表示\n","repo_name":"devtitozzzzg/data_analysis","sub_path":"MATPLOTLIB/matlab_style.py","file_name":"matlab_style.py","file_ext":"py","file_size_in_byte":424,"program_lang":"python","lang":"ja","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"13802023649","text":"class Node:\n def __init__(self, data):\n self.data = data\n self.next = None\n\nclass LinkedList:\n def __init__(self):\n self.head = None\n\n # 연결 리스트에 노드 추가\n def append(self, data):\n new_node = Node(data)\n if not self.head:\n self.head = new_node\n return\n current = self.head\n while current.next:\n current = current.next\n current.next = new_node\n\n # 연결 리스트 순회(iteration)\n def traverse(self):\n current = self.head\n while current:\n print(current.data, end=\" \")\n current = current.next\n print()\n\n# 빈 연결 리스트 생성\nmy_linked_list = LinkedList()\n\n# 노드 추가\nmy_linked_list.append(1)\nmy_linked_list.append(2)\nmy_linked_list.append(3)\n\n# 연결 리스트 순회\nmy_linked_list.traverse()\n","repo_name":"YuniGK/study","sub_path":"Algorithm Notes/Data Structure/선형/연결 리스트/Linked_list.py","file_name":"Linked_list.py","file_ext":"py","file_size_in_byte":875,"program_lang":"python","lang":"ko","doc_type":"code","stars":1,"dataset":"github-code","pt":"81"} +{"seq_id":"5704241326","text":"#selection sort types all the complexities are the same, \r\n#\r\ndef selSort(L):\r\n for i in range(len(L) - 1):\r\n minIndx = i\r\n minVal = L[i]\r\n j = i+1\r\n while j < len(L):\r\n if minVal > L[j]:\r\n minIndx = j\r\n minVal = L[j]\r\n j += 1\r\n if minIndx != i:\r\n temp = L[i]\r\n L[i] = L[minIndx]\r\n L[minIndx] = temp\r\n \r\n#selSort:\r\n#\r\n#You can sort a list by always moving the smallest element from \r\n#the unsorted list to a new list. That procedure would add the elements to the new list in increasing order, \r\n#and when every element from the old list has been moved over, we end up with a new sorted list. \r\n#This type of sorting algorithm is often called Selection Sort.\r\n#selSort implements this without explicitly creating a new list,\r\n#by maintaining sorted (from position 0 to i-1) and unsorted (from position i to the end) parts of the \r\n#list. All elements in positions before the iterating variable i are sorted, and unsorted for those \r\n#positions at i or below. In each iteration, it selects the smallest element in the unsorted part of the list,\r\n#and swaps it with the element at the ith position. That essentially adds the next smallest element from the\r\n#old list and appends it to the new. It keeps doing that until the old list is empty (i.e., i reaches the end\r\n#of the list).\r\n\r\n\r\ndef newSort(L):\r\n for i in range(len(L) - 1):\r\n j=i+1\r\n while j < len(L):\r\n if L[i] > L[j]:\r\n temp = L[i]\r\n L[i] = L[j]\r\n L[j] = temp\r\n j += 1\r\n# \r\n#newSort:\r\n#\r\n#newSort is basically a slight variant of Selection Sort. In each iteration,\r\n#newSort also tries to find the smallest element in the unsorted part of the list and appends it to the \r\n#sorted part of the list. The only difference here is that instead of finding the smallest value in the \r\n#unsorted part of the list with minVal and minIndx, newSort maintains that the element at the ith position \r\n#is the smallest element between the ith and jth positions. So, when j reaches the end of the list, the ith \r\n#position must have been the smallest element in the unsorted portion (from position i to the end) of the \r\n#list.\r\n \r\ndef mySort(L):\r\n clear = False\r\n while not clear:\r\n clear = True\r\n for j in range(1, len(L)):\r\n if L[j-1] > L[j]:\r\n clear = False\r\n temp = L[j]\r\n L[j] = L[j-1]\r\n L[j-1] = temp\r\n \r\n \r\n\r\n\r\n#mySort:\r\n#\r\n#A list is sorted if every pair of successive elements in a list are in the correct order. \r\n#mySort implements this idea more directly than in other sorting algorithms we have seen. \r\n#The basic idea is that every time it finds two successive elements in the wrong order, it will swap them.\r\n#Because all lists can be sorted, it will eventually run out of things that are in the wrong order.\r\n#At this point the list is sorted, and the algorithm terminates.\r\n#\r\n#Another way of thinking about mySort is that in each iteration, if an element e is bigger than the one \r\n#after it, e moves down one location. Then, e is checked against the next element, and so on, until the \r\n#algorithm finds an element bigger than e. So, in the first pass, the biggest element drops to the bottom \r\n#of the list. Then, in the second pass, the second biggest drops to the second to last position in the list,\r\n#and so on for the remaining iterations. In each pass through the list, the next biggest element drops to its\r\n#proper location, so that after n iterations, the list is sorted. This algorithm is typically known as\r\n#'bubble sort' as elements bubble (up or down) one element at a time.","repo_name":"noslav/python_projects_1","sub_path":"Search Algorithms/selSort.py","file_name":"selSort.py","file_ext":"py","file_size_in_byte":3813,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"25211534994","text":"import logging\nfrom flask import g\nfrom superdesk.resource import Resource\nfrom superdesk.services import BaseService\n\nlog = logging.getLogger(__name__)\n\n\nclass AuditResource(Resource):\n endpoint_name = \"audit\"\n resource_methods = [\"GET\"]\n item_methods = [\"GET\"]\n notifications = False\n schema = {\n \"resource\": {\"type\": \"string\"},\n \"action\": {\"type\": \"string\"},\n \"audit_id\": {\"type\": \"string\"},\n \"extra\": {\"type\": \"dict\"},\n \"user\": Resource.rel(\"users\", False),\n }\n exclude = {endpoint_name, \"activity\", \"dictionaries\", \"macros\", \"archive_history\", \"formatters\"}\n\n\nclass AuditService(BaseService):\n def on_generic_inserted(self, resource, docs):\n if resource in AuditResource.exclude:\n return\n\n user = getattr(g, \"user\", None)\n if not user:\n if resource == \"auth\":\n user_id = docs[0].get(\"user\")\n else:\n return\n else:\n user_id = user.get(\"_id\")\n\n if not len(docs):\n return\n\n audit = {\n \"user\": user_id,\n \"resource\": resource,\n \"action\": \"created\",\n \"extra\": docs[0],\n \"audit_id\": self._extract_doc_id(docs[0]),\n }\n\n self.post([audit])\n\n def on_generic_updated(self, resource, doc, original):\n if resource in AuditResource.exclude:\n return\n\n user = getattr(g, \"user\", None)\n if not user:\n return\n\n audit = {\n \"user\": user.get(\"_id\"),\n \"resource\": resource,\n \"action\": \"updated\",\n \"extra\": doc,\n \"audit_id\": self._extract_doc_id(doc) if self._extract_doc_id(doc) else self._extract_doc_id(original),\n }\n if \"_id\" not in doc:\n audit[\"extra\"][\"_id\"] = original.get(\"_id\", None)\n self.post([audit])\n\n def on_generic_deleted(self, resource, doc):\n if resource in AuditResource.exclude:\n return\n\n user = getattr(g, \"user\", None)\n if not user:\n return\n\n audit = {\n \"user\": user.get(\"_id\"),\n \"resource\": resource,\n \"action\": \"deleted\",\n \"extra\": doc,\n \"audit_id\": self._extract_doc_id(doc),\n }\n self.post([audit])\n\n def _extract_doc_id(self, doc):\n \"\"\"\n Given an audit item try to extract the id of the item that it relates to\n :param item:\n :return:\n \"\"\"\n try:\n id = doc.get(\"_id\", doc.get(\"guid\", doc.get(\"item_id\", doc.get(\"item\", None))))\n # do not return an id for items that have a dictionary id\n if not isinstance(id, dict):\n return id\n else:\n None\n except Exception:\n return None\n return None\n","repo_name":"superdesk/superdesk-core","sub_path":"superdesk/audit/audit.py","file_name":"audit.py","file_ext":"py","file_size_in_byte":2853,"program_lang":"python","lang":"en","doc_type":"code","stars":31,"dataset":"github-code","pt":"81"} +{"seq_id":"1786522555","text":"__author__ = 'konradk'\n\nfrom typing import Any, Tuple, Union, Optional, List\n\nfrom .generic import *\nimport pickle\nimport copy\nimport uuid\n\nroot = 'gs://gnomad-public/papers/2019-flagship-lof/v1.0'\n\n# Unprocessed files\nfasta_path = f'{root}/context/source/Homo_sapiens_assembly19.fasta'\ngerp_annotations_path = f'{root}/annotations/gerp.scores.GRCh37.ht' # Gerp is in here as S\n\n# Input datasets\nraw_context_txt_path = f'{root}/context/source/Homo_sapiens_assembly19.fasta.snps_only.vep.txt.bgz/*'\nraw_context_ht_path = f'{root}/context/Homo_sapiens_assembly19.fasta.snps_only.unsplit.ht'\nvep_context_ht_path = f'{root}/context/Homo_sapiens_assembly19.fasta.snps_only.unsplit.vep_20181129.ht'\ncontext_ht_path = f'{root}/context/Homo_sapiens_assembly19.fasta.snps_only.vep_20181129.ht'\nprocessed_genomes_ht_path = f'{root}/model/genomes_processed.ht'\nprocessed_exomes_ht_path = f'{root}/model/exomes_processed.ht'\n\n# Possible variant files\nall_possible_summary_pickle = f'{root}/model/tmp/all_possible_counts_by_context.pckl'\nall_possible_summary_unfiltered_pickle = f'{root}/model/tmp/all_possible_counts_by_context_unfiltered.pckl'\n\nmutation_rate_ht_path = f'{root}/model/mutation_rate_methylation_bins.ht'\npo_coverage_ht_path = f'{root}/model/prop_observed_by_coverage_no_common_pass_filtered_bins.ht'\npo_ht_path = f'{root}/{{subdir}}/prop_observed_{{subdir}}.ht'\nraw_constraint_ht_path = f'{root}/{{subdir}}/constraint_{{subdir}}.ht'\nfinal_constraint_ht_path = f'{root}/{{subdir}}/constraint_final_{{subdir}}.ht'\n\nHIGH_COVERAGE_CUTOFF = 40\nVARIANT_TYPES_FOR_MODEL = ('ACG', 'TCG', 'CCG', 'GCG', 'non-CpG')\nPOPS = ('global', 'afr', 'amr', 'eas', 'nfe', 'sas')\nMODEL_KEYS = {\n 'worst_csq': ['gene'],\n 'tx_annotation': ['gene', 'expressed'],\n 'standard': ['gene', 'transcript', 'canonical']\n}\n\n\n# Data loads\ndef get_old_mu_data() -> hl.Table:\n old_mu_data = hl.import_table(f'{root}/old_exac_data/fordist_1KG_mutation_rate_table.txt',\n delimiter=' ', impute=True)\n return old_mu_data.transmute(context=old_mu_data['from'], ref=old_mu_data['from'][1],\n alt=old_mu_data.to[1]).key_by('context', 'ref', 'alt')\n\n\ndef load_all_possible_summary(filtered: bool = True) -> Dict[hl.Struct, int]:\n fname = all_possible_summary_pickle if filtered else all_possible_summary_unfiltered_pickle\n with hl.hadoop_open(fname, 'rb') as f:\n return pickle.load(f)\n\n\ndef load_tx_expression_data(context: bool =True) -> hl.Table:\n \"\"\"\n Load tx MatrixTable with processed expression data.\n\n :param context: Whether to load the Table with proportion expressed across transcripts (pext) score annotations\n for all possible bases or the Table with pext scores for sites found in gnomAD v2.1.1 exomes, defaults to True.\n :return: tx Table with expression data.\n \"\"\"\n tx_ht_file = 'gs://gnomad-public/papers/2019-tx-annotation/pre_computed/all.possible.snvs.tx_annotated.021819.ht' if context \\\n else 'gs://gnomad-public/papers/2019-tx-annotation/gnomad.exomes.r2.1.1.sites.tx_annotated.021319.ht'\n tx_ht = hl.read_matrix_table(tx_ht_file).rows()\n\n def process_expression_data(csq_expression: hl.expr.StructExpression) -> hl.expr.StructExpression:\n \"\"\"\n Process expression data by adding annotations and drop tissue columns other than Brain_Cortex.\n \n Function will add the following annotations to tx Table:\n - ensg\n - csq\n - symbol\n - lof\n - mean_expression\n - max_expression\n - mean_brain_expression\n - Brain_Cortex\n\n :param csq_expression: 'tx_annotation' (a StructExpression) within tx Table\n :return: Expression data\n \"\"\"\n exprs_to_drop = ['ensg', 'csq', 'symbol', 'lof', 'lof_flag', 'mean_proportion']\n expression_data = csq_expression.drop(*exprs_to_drop)\n all_tissues = list(expression_data.values())\n expression_data_list = list(zip(list(expression_data), all_tissues))\n brain_tissues = [x[1] for x in expression_data_list if 'Brain' in x[0]]\n return csq_expression.select('ensg', 'csq', 'symbol', 'lof',\n mean_expression=hl.mean(hl.filter(lambda e: ~hl.is_nan(e), all_tissues), filter_missing=True),\n max_expression=hl.max(hl.filter(lambda e: ~hl.is_nan(e), all_tissues), filter_missing=True),\n mean_brain_expression=hl.mean(hl.filter(lambda k: ~hl.is_nan(k), brain_tissues), filter_missing=True),\n Brain_Cortex=csq_expression.Brain_Cortex\n )\n\n return tx_ht.annotate(tx_annotation=tx_ht.tx_annotation.map(process_expression_data))\n\n\ndef annotate_distance_to_splice(input_ht: hl.Table) -> hl.Table:\n \"\"\"\n Annotate distance to the nearest splice site.\n\n :param input_ht: Input exome or context Table.\n :return: Table with 'nearest_splice' annotation added (distance to nearest splice site).\n \"\"\"\n # Load GTF file\n tmp_path = f'/tmp_{uuid.uuid4()}.ht'\n ht = hl.experimental.import_gtf('gs://hail-common/references/gencode/gencode.v19.annotation.gtf.bgz', 'GRCh37', True, min_partitions=100)\n ht = ht.filter((ht.feature == 'exon') & (ht.transcript_type == 'protein_coding')).key_by()\n ht = ht.select(gene_id=ht.gene_id.split('\\\\.')[0], transcript_id=ht.transcript_id.split('\\\\.')[0],\n loc=[hl.struct(acceptor=ht.strand == '+', locus=ht.interval.start),\n hl.struct(acceptor=ht.strand != '+', locus=ht.interval.end)]).explode('loc')\n ht.transmute(**ht.loc).key_by('locus').collect_by_key().write(tmp_path, True)\n\n # Scan to get bounds, create intervals\n tmp_path2 = f'/tmp_{uuid.uuid4()}.ht'\n ht = hl.read_table(tmp_path)\n last_locus = hl.scan.take(ht.row, 1, ordering=-ht.locus.global_position())\n ht.key_by(\n interval=hl.or_missing((hl.len(last_locus) > 0) &\n (last_locus[0].contig == ht.locus.contig),\n hl.interval(last_locus[0], ht.locus))\n ).write(tmp_path2)\n\n ht = hl.read_table(tmp_path2)\n # join against intervals\n data = ht[input_ht.locus]\n # find nearer splice site\n return input_ht.transmute(\n nearest_splice=hl.cond(\n hl.abs(input_ht.locus.position - input_ht.data.locus.position) <= hl.abs(\n input_ht.locus.position - data.last.locus.position),\n hl.struct(dist=input_ht.locus.position - data.locus.position, sites=input_ht.data.values),\n hl.struct(dist=input_ht.locus.position - data.last.locus.position, sites=input_ht.data.last.values)\n )\n )\n\n\ndef annotate_tx_expression_data(ht, tx_ht, location):\n key = ht.key if isinstance(ht, hl.Table) else ht.row_key\n return hl.find(lambda csq: (csq.ensg == location.gene_id) &\n (csq.csq == location.most_severe_consequence),\n tx_ht[key].tx_annotation)\n\n\n# Pre-process\ndef export_fasta(hc) -> None:\n # Done with an 0.1 jar\n hc.read('gs://gnomad-resources/Homo_sapiens_assembly19.fasta.snps_only.vep.vds').export_variants('gs://gnomad-resources/context/source/Homo_sapiens_assembly19.fasta.snps_only.vep.txt.bgz', 'v, va.context, va.vep', types=True, parallel=True)\n\n\ndef import_fasta(raw_context_txt_path: str, raw_context_ht_path: str, overwrite: bool = False) -> None:\n # Works with --jar gs://hail-common/builds/devel/jars/hail-devel-47de006f2c62-Spark-2.2.0.jar\n ht = hl.import_table(raw_context_txt_path, no_header=True, min_partitions=40000,\n types={'f0': hl.tstr,\n 'f1': hl.tstr,\n 'f2': hl.tstruct(\n assembly_name=hl.tstr,\n allele_string=hl.tstr,\n ancestral=hl.tstr,\n colocated_variants=hl.tarray(\n hl.tstruct(aa_allele=hl.tstr, aa_maf=hl.tfloat, afr_allele=hl.tstr, afr_maf=hl.tfloat, allele_string=hl.tstr, amr_allele=hl.tstr, amr_maf=hl.tfloat, clin_sig=hl.tarray(hl.tstr),\n end=hl.tint, eas_allele=hl.tstr, eas_maf=hl.tfloat, ea_allele=hl.tstr, ea_maf=hl.tfloat, eur_allele=hl.tstr, eur_maf=hl.tfloat, exac_adj_allele=hl.tstr, exac_adj_maf=hl.tfloat,\n exac_allele=hl.tstr, exac_afr_allele=hl.tstr, exac_afr_maf=hl.tfloat, exac_amr_allele=hl.tstr, exac_amr_maf=hl.tfloat, exac_eas_allele=hl.tstr, exac_eas_maf=hl.tfloat,\n exac_fin_allele=hl.tstr, exac_fin_maf=hl.tfloat, exac_maf=hl.tfloat, exac_nfe_allele=hl.tstr, exac_nfe_maf=hl.tfloat, exac_oth_allele=hl.tstr, exac_oth_maf=hl.tfloat,\n exac_sas_allele=hl.tstr, exac_sas_maf=hl.tfloat, id=hl.tstr, minor_allele=hl.tstr, minor_allele_freq=hl.tfloat, phenotype_or_disease=hl.tint, pubmed=hl.tarray(hl.tint),\n sas_allele=hl.tstr, sas_maf=hl.tfloat, somatic=hl.tint, start=hl.tint, strand=hl.tint),\n ),\n context=hl.tstr, end=hl.tint, id=hl.tstr, input=hl.tstr,\n intergenic_consequences=hl.tarray(\n hl.tstruct(allele_num=hl.tint, consequence_terms=hl.tarray(hl.tstr), impact=hl.tstr, minimised=hl.tint, variant_allele=hl.tstr)),\n most_severe_consequence=hl.tstr, motif_feature_consequences=hl.tarray(\n hl.tstruct(allele_num=hl.tint, consequence_terms=hl.tarray(hl.tstr), high_inf_pos=hl.tstr,impact=hl.tstr, minimised=hl.tint, motif_feature_id=hl.tstr, motif_name=hl.tstr, motif_pos=hl.tint, motif_score_change=hl.tfloat, strand=hl.tint, variant_allele=hl.tstr)),\n regulatory_feature_consequences=hl.tarray(hl.tstruct(\n allele_num=hl.tint, biotype=hl.tstr, consequence_terms=hl.tarray(hl.tstr), impact=hl.tstr, minimised=hl.tint, regulatory_feature_id=hl.tstr, variant_allele=hl.tstr)\n ), seq_region_name=hl.tstr, start=hl.tint, strand=hl.tint, transcript_consequences=hl.tarray(hl.tstruct(\n allele_num=hl.tint, amino_acids=hl.tstr, biotype=hl.tstr, canonical=hl.tint, ccds=hl.tstr, cdna_start=hl.tint, cdna_end=hl.tint, cds_end=hl.tint, cds_start=hl.tint,\n codons=hl.tstr, consequence_terms=hl.tarray(hl.tstr), distance=hl.tint, domains=hl.tarray(hl.tstruct(db=hl.tstr, name=hl.tstr)), exon=hl.tstr,\n gene_id=hl.tstr, gene_pheno=hl.tint, gene_symbol=hl.tstr, gene_symbol_source=hl.tstr, hgnc_id=hl.tint, hgvsc=hl.tstr, hgvsp=hl.tstr, hgvs_offset=hl.tint,\n impact=hl.tstr, intron=hl.tstr, lof=hl.tstr, lof_flags=hl.tstr, lof_filter=hl.tstr, lof_info=hl.tstr, minimised=hl.tint, polyphen_prediction=hl.tstr, polyphen_score=hl.tfloat,\n protein_end=hl.tint, protein_start=hl.tint, protein_id=hl.tstr, sift_prediction=hl.tstr, sift_score=hl.tfloat, strand=hl.tint, swissprot=hl.tstr, transcript_id=hl.tstr, trembl=hl.tstr, uniparc=hl.tstr, variant_allele=hl.tstr\n )), variant_class=hl.tstr\n )}\n ).rename({'f0': 'v', 'f1': 'context', 'f2': 'vep'})\n ht.transmute(**hl.parse_variant(ht.v)).key_by('locus', 'alleles').write(raw_context_ht_path, overwrite)\n\n\ndef vep_context_ht(raw_context_ht_path: str, vep_context_ht_path: str, overwrite: bool = False):\n ht_full = hl.read_table(raw_context_ht_path)\n chunks = ('1-2', '3', '4', '5-6', '7-9', '10-12', '13-15', '16-18', '19-22', 'X-Y')\n for i in chunks:\n print(i)\n ht = hl.filter_intervals(ht_full, [hl.parse_locus_interval(i)])\n hl.vep(ht, vep_config).write(f'{root}/context/parts/Homo_sapiens_assembly19.fasta.snps_only.{i}.ht', overwrite=overwrite, stage_locally=True)\n hts = [hl.read_table(f'{root}/context/parts/Homo_sapiens_assembly19.fasta.snps_only.{i}.ht') for i in chunks]\n ht = hts[0].union(*hts[1:])\n ht.write(vep_context_ht_path, overwrite)\n\n\ndef split_context_mt(raw_context_ht_path: str, coverage_ht_paths: Dict[str, str], methylation_ht_path: str,\n context_ht_path: str, overwrite: bool = False) -> None:\n raw_context_ht = hl.split_multi_hts(hl.read_table(raw_context_ht_path))\n raw_context_ht.write(f'{raw_context_ht_path}.temp_split.ht', overwrite)\n raw_context_ht = hl.read_table(f'{raw_context_ht_path}.temp_split.ht')\n\n coverage_hts = {loc: hl.read_table(coverage_ht_path) for loc, coverage_ht_path in coverage_ht_paths.items()}\n coverage_hts = {loc: coverage_ht.drop('#chrom', 'pos') if '#chrom' in list(coverage_ht.row) else coverage_ht\n for loc, coverage_ht in coverage_hts.items()}\n methylation_ht = hl.read_table(methylation_ht_path)\n gerp_ht = hl.read_table(gerp_annotations_path)\n\n raw_context_ht = raw_context_ht.annotate(\n methylation=methylation_ht[raw_context_ht.locus],\n coverage=hl.struct(**{loc: coverage_ht[raw_context_ht.locus] for loc, coverage_ht in coverage_hts.items()}),\n gerp=gerp_ht[raw_context_ht.locus].S)\n\n raw_context_ht.write(context_ht_path, overwrite)\n\n\ndef pre_process_data(ht: hl.Table, split_context_ht_path: str,\n output_ht_path: str, overwrite: bool = False) -> None:\n \"\"\" \n Add annotations from VEP context Table to gnomAD data.\n \n Function adds the following annotations:\n - context\n - methylation\n - coverage\n - gerp\n - pass_filters\n \n Function drops `a_index`, `was_split`, and`colocated_variants` annotations from gnomAD data.\n \n .. note::\n Function expects that multiallelic variants in the VEP context Table have been split.\n \n :param ht: gnomAD exomes or genomes public Hail Table. \n :param split_context_ht_path: Path to VEP context Table.\n :param output_ht_path: Path to output Table.\n :param overwrite: Whether to overwrite existing data. Defaults to False.\n \"\"\"\n context_ht = hl.read_table(split_context_ht_path).drop('a_index', 'was_split')\n context_ht = context_ht.annotate(vep=context_ht.vep.drop('colocated_variants'))\n ht.annotate(**context_ht[ht.key], pass_filters=hl.len(ht.filters) == 0).write(output_ht_path, overwrite)\n\n\ndef prepare_ht(ht, trimer: bool = False, annotate_coverage: bool = True):\n \"\"\"\n Filter input Table and add annotations used in constraint calculations.\n \n Function filters to SNPs, removes rows with undefined contexts, collapses strands\n to deduplicate trimer or heptamer contexts, and annotates the input Table.\n\n Function adds the following annotations:\n - ref\n - alt\n - was_flipped\n - methylation_level\n - cpg\n - transition\n - variant_type\n - variant_type_model\n - exome_coverage\n \n :param ht: Input Table to be annotated.\n :param trimer: Whether to use trimers or heptamers. Defaults to False.\n :param annotate_coverage: Whether to annotate the coverage of exome. Defaults to True.\n :return: Table with annotations.\n \"\"\"\n if trimer:\n ht = trimer_from_heptamer(ht)\n str_len = 3 if trimer else 7\n\n if isinstance(ht, hl.Table):\n ht = ht.annotate(ref=ht.alleles[0], alt=ht.alleles[1])\n ht = ht.filter((hl.len(ht.ref) == 1) & (hl.len(ht.alt) == 1) & ht.context.matches(f'[ATCG]{{{str_len}}}'))\n ht = annotate_variant_types(collapse_strand(ht), not trimer)\n else:\n ht = ht.annotate_rows(ref=ht.alleles[0], alt=ht.alleles[1])\n ht = ht.filter_rows((hl.len(ht.ref) == 1) & (hl.len(ht.alt) == 1) & ht.context.matches(f'[ATCG]{{{str_len}}}'))\n ht = annotate_variant_types(collapse_strand(ht), not trimer)\n annotation = {\n 'methylation_level': hl.case().when(\n ht.cpg & (ht.methylation.MEAN > 0.6), 2\n ).when(\n ht.cpg & (ht.methylation.MEAN > 0.2), 1\n ).default(0)\n }\n if annotate_coverage:\n annotation['exome_coverage'] = ht.coverage.exomes.median\n return ht.annotate(**annotation) if isinstance(ht, hl.Table) else ht.annotate_rows(**annotation)\n\n\ndef filter_to_autosomes_par(ht: Union[hl.Table, hl.MatrixTable]) -> Union[hl.Table, hl.MatrixTable]:\n return ht.filter(ht.locus.in_autosome_or_par())\n\n\ndef annotate_with_mu(ht: hl.Table, mutation_ht: hl.Table, output_loc: str = 'mu_snp',\n keys: Tuple[str] = ('context', 'ref', 'alt', 'methylation_level')) -> hl.Table:\n \"\"\"\n Annotate SNP mutation rate for the input Table.\n\n :param ht: Input Table.\n :param mutation_ht: Mutation rate Table.\n :param output_loc: Name for mutational rate annotation. Defaults to 'mu_snp'.\n :param keys: Common keys between mutation rate Table and input Table. Defaults to ('context', 'ref', 'alt', 'methylation_level').\n :return: Table with mutational rate annotation added (default name for annotation is 'mu_snp').\n \"\"\"\n mu = hl.literal(mutation_ht.aggregate(hl.dict(hl.agg.collect(\n (hl.struct(**{k: mutation_ht[k] for k in keys}), mutation_ht.mu_snp)))))\n mu = mu.get(hl.struct(**{k: ht[k] for k in keys}))\n return ht.annotate(**{output_loc: hl.case().when(hl.is_defined(mu), mu).or_error('Missing mu')})\n\n\ndef calculate_mu_by_downsampling(genome_ht: hl.Table, raw_context_ht: hl.MatrixTable,\n recalculate_all_possible_summary: bool = True,\n recalculate_all_possible_summary_unfiltered: bool = False,\n omit_methylation: bool = False, count_singletons: bool = False,\n remove_common_downsampled: bool = True, remove_common_ordinary: bool = False,\n grouping_variables: Optional[Tuple[str]] = (), summary_file: str = None\n ) -> hl.Table:\n\n context_ht = filter_to_autosomes(remove_coverage_outliers(raw_context_ht))\n genome_ht = filter_to_autosomes(remove_coverage_outliers(genome_ht))\n\n if grouping_variables:\n context_ht = context_ht.filter(hl.all(lambda x: x, [hl.is_defined(context_ht[x]) for x in grouping_variables]))\n genome_ht = genome_ht.filter(hl.all(lambda x: x, [hl.is_defined(genome_ht[x]) for x in grouping_variables]))\n else:\n context_ht = filter_for_mu(context_ht)\n genome_ht = filter_for_mu(genome_ht)\n\n context_ht = context_ht.select('context', 'ref', 'alt', 'methylation_level', *grouping_variables)\n genome_ht = genome_ht.select('context', 'ref', 'alt', 'methylation_level', 'freq', 'pass_filters', *grouping_variables)\n\n genome_join = genome_ht[context_ht.key]\n if remove_common_downsampled:\n ac_cutoff = 5\n downsampling_level = 1000\n freq_index = hl.eval(\n hl.zip_with_index(genome_ht.freq_meta).find(lambda f:\n (f[1].get('downsampling') == str(downsampling_level)) &\n (f[1].get('pop') == 'global') &\n (f[1].get('group') == 'adj') &\n (f[1].size() == 3)))[0]\n # In the denominator, only keep variants not in the genome dataset, or with AC <= ac_cutoff and passing filters\n context_ht = context_ht.filter(\n hl.is_missing(genome_join) | ((genome_join.freq[freq_index].AC <= ac_cutoff) & genome_join.pass_filters)\n )\n # Keep only AC <= ac_cutoff in numerator\n genome_ht = genome_ht.filter(genome_ht.freq[freq_index].AC <= ac_cutoff)\n elif remove_common_ordinary:\n af_cutoff = 0.001\n context_ht = context_ht.filter(\n hl.is_missing(genome_join) | (\n (genome_join.freq[0].AF <= af_cutoff) & genome_join.pass_filters\n )\n )\n # Keep only AF < af_cutoff in numerator\n genome_ht = filter_by_frequency(genome_ht, 'below', frequency=af_cutoff, adj=True)\n else:\n context_ht = context_ht.filter(\n hl.is_missing(genome_join) | genome_join.pass_filters\n )\n genome_ht = genome_ht.filter(genome_ht.pass_filters)\n\n if not summary_file: summary_file = all_possible_summary_pickle\n all_possible_dtype = count_variants(context_ht, omit_methylation=omit_methylation,\n additional_grouping=grouping_variables, return_type_only=True)\n if recalculate_all_possible_summary:\n all_possible = count_variants(context_ht, omit_methylation=omit_methylation,\n additional_grouping=grouping_variables).variant_count\n with hl.hadoop_open(summary_file, 'wb') as f:\n pickle.dump(all_possible, f)\n with hl.hadoop_open(summary_file, 'rb') as f:\n all_possible = pickle.load(f)\n\n if recalculate_all_possible_summary_unfiltered:\n all_possible_unfiltered = count_variants(raw_context_ht.rows(), omit_methylation=omit_methylation).variant_count\n all_possible_unfiltered = {x: y for x, y in list(all_possible_unfiltered.items()) if x.context is not None}\n with hl.hadoop_open(all_possible_summary_unfiltered_pickle, 'wb') as f:\n pickle.dump(all_possible_unfiltered, f)\n # Uncomment this line and next few commented lines to back-calculate total_mu from the old mutation rate dataset\n # all_possible_unfiltered = load_all_possible_summary(filtered=False)\n\n genome_ht = count_variants(genome_ht, count_downsamplings=['global', 'nfe', 'afr'],\n count_singletons=count_singletons,\n additional_grouping=grouping_variables, omit_methylation=omit_methylation)\n\n old_mu_data = get_old_mu_data()\n ht = genome_ht.annotate(possible_variants=hl.literal(all_possible, dtype=all_possible_dtype)[genome_ht.key],\n # possible_variants_unfiltered=hl.literal(all_possible_unfiltered, dtype=all_possible_dtype)[genome_ht.key],\n old_mu_snp=old_mu_data[hl.struct(\n context=genome_ht.context, ref=genome_ht.ref, alt=genome_ht.alt)].mu_snp)\n ht = ht.persist()\n total_bases = ht.aggregate(hl.agg.sum(ht.possible_variants)) // 3\n # total_bases_unfiltered = ht.aggregate(hl.agg.sum(ht.possible_variants_unfiltered)) // 3\n # total_mu = ht.aggregate(hl.agg.sum(ht.old_mu_snp * ht.possible_variants_unfiltered) / total_bases_unfiltered)\n total_mu = 1.2e-08\n\n correction_factors = ht.aggregate(total_mu / (hl.agg.array_sum(ht.downsampling_counts_global) / total_bases))\n correction_factors_nfe = ht.aggregate(total_mu / (hl.agg.array_sum(ht.downsampling_counts_nfe) / total_bases))\n correction_factors_afr = ht.aggregate(total_mu / (hl.agg.array_sum(ht.downsampling_counts_afr) / total_bases))\n\n ht = annotate_variant_types(ht.annotate(downsamplings_frac_observed=ht.downsampling_counts_global / ht.possible_variants,\n downsamplings_mu_snp=hl.literal(correction_factors) * ht.downsampling_counts_global / ht.possible_variants,\n downsamplings_mu_nfe=hl.literal(correction_factors_nfe) * ht.downsampling_counts_nfe / ht.possible_variants,\n downsamplings_mu_afr=hl.literal(correction_factors_afr) * ht.downsampling_counts_afr / ht.possible_variants))\n downsamplings = list(map(lambda x: x[1], get_downsamplings(ht)))\n index_1kg = downsamplings.index(1000)\n return ht.annotate(proportion_observed_1kg=ht.downsampling_counts_global[index_1kg] / ht.possible_variants,\n proportion_observed=ht.variant_count / ht.possible_variants,\n mu_snp=ht.downsamplings_mu_snp[index_1kg],\n mu_snp_nfe=ht.downsamplings_mu_nfe[index_1kg],\n mu_snp_afr=ht.downsamplings_mu_afr[index_1kg])\n\n\ndef get_proportion_observed_by_coverage(exome_ht: hl.Table, context_ht: hl.Table, mutation_ht: hl.Table,\n recompute_possible: bool = False, dataset: str = 'gnomad',\n impose_high_af_cutoff_upfront: bool = True) -> hl.Table:\n \"\"\"\n Count the observed variants and possible variants by exome coverage. \n\n :param exome_ht: Preprocessed exome Table.\n :param context_ht: Preprocessed context Table.\n :param mutation_ht: Preprocessed mutation rate Table.\n :param recompute_possible: Whether to use context Table to recompute the number of possible variants instead of using a precomputed intermediate Table if it exists. Defaults to False.\n :param dataset: Dataset to use when computing frequency index. Defaults to 'gnomad'.\n :param impose_high_af_cutoff_upfront: Whether to remove high frequency alleles. Defaults to True.\n :return: Table with observed variant and possible variant count.\n \"\"\"\n\n exome_ht = add_most_severe_csq_to_tc_within_ht(exome_ht)\n context_ht = add_most_severe_csq_to_tc_within_ht(context_ht)\n\n context_ht = fast_filter_vep(context_ht).select('context', 'ref', 'alt', 'methylation_level', 'exome_coverage')\n context_ht = context_ht.filter(hl.is_defined(context_ht.exome_coverage))\n\n exome_ht = fast_filter_vep(exome_ht).select('context', 'ref', 'alt', 'methylation_level', 'exome_coverage', 'freq', 'pass_filters')\n\n grouping = ('exome_coverage',)\n af_cutoff = 0.001\n\n exome_join = exome_ht[context_ht.key]\n freq_index = exome_ht.freq_index_dict.collect()[0][dataset]\n\n def keep_criteria(ht: Union[hl.Table, hl.expr.StructExpression]) -> hl.expr.BooleanExpression:\n \"\"\"\n Generate expression to keep PASS variants with an allele count greater than 0.\n \n If `impose_high_af_cutoff_upfront` is True, only keep variants with an AF less than or equal to \n `af_cutoff` (default is 0.001).\n \n :param ht: Table or StructExpression of variants that have a defined key in the `context_ht`.\n :return: BooleanExpression indicating if the row should be kept.\n \"\"\"\n crit = (ht.freq[freq_index].AC > 0) & ht.pass_filters\n if impose_high_af_cutoff_upfront:\n crit &= (ht.freq[freq_index].AF <= af_cutoff)\n return crit\n context_ht = context_ht.filter(hl.is_missing(exome_join) | keep_criteria(exome_join))\n\n exome_ht = exome_ht.filter(keep_criteria(exome_ht))\n\n possible_file = f'{root}/tmp/possible_coverage.ht'\n if recompute_possible:\n possible_ht = count_variants(context_ht, additional_grouping=grouping, force_grouping=True)\n possible_ht = annotate_with_mu(possible_ht, mutation_ht)\n possible_ht.transmute(possible_variants=possible_ht.variant_count).write(possible_file, True)\n\n possible_ht = hl.read_table(possible_file)\n ht = count_variants(exome_ht, additional_grouping=grouping, partition_hint=100, count_downsamplings=POPS,\n impose_high_af_cutoff_here=not impose_high_af_cutoff_upfront)\n ht = ht.join(possible_ht, 'outer')\n return ht\n\n\ndef build_models(coverage_ht: hl.Table, trimers: bool = False, weighted: bool = False, half_cutoff = False,\n ) -> Tuple[Tuple[float, float], Dict[str, Tuple[float, float]]]:\n \"\"\"\n Build coverage model and plateau models.\n \n This function builds plateau models to calibrate mutation rate estimates against the proportion observed\n of each substitution, context, and methylation level in `coverage_ht` considering only high coverage sites,\n or sites above a median coverage of `HIGH_COVERAGE_CUTOFF` (or half of `HIGH_COVERAGE_CUTOFF` if `half_cutoff`\n is True). If using the output of `get_proportion_observed_by_coverage` as `coverage_ht`, the proportion observed\n will be high-quality variants below 0.1% frequency at synonymous sites. Two plateau models are fit, one for CpG\n transitions and one for the remainder of sites (transversions and non-CpG transitions). \n \n The x and y of plateau models:\n x: `mu_snp` - mutation rate\n y: proportion observed ('variant_count' or 'observed_{pop}' / 'possible_variants') \n \n For low coverage sites, or sites below `HIGH_COVERAGE_CUTOFF` (or half of `HIGH_COVERAGE_CUTOFF` if `half_cutoff` is\n True), this function performs a base-level resolution rather than exon-level to compute a coverage correction factor\n to reduce the inaccuracy of expected variant counts caused by low coverage on each base. The coverage models are built\n by first defining a metric that is derived by dividing the number of observed variants with the total number of \n possible variants times the mutation rate summed across all substitutions, contexts, and methylation level. If using\n the output of `get_proportion_observed_by_coverage` as `coverage_ht`, the number of observed variants and possible\n variants will be at synonymous sites. The function computes this metric for high coverage sites as a global scaling\n factor, and divides this metric at low coverage sites by this scaling factor to create an observed:expected ratio. Then the\n coverage model is built of log10(coverage) to this scaled ratio as a correction factor for low coverage sites.\n \n The x and y of the coverage model:\n x: log10('exome_coverage') at low coverage site\n y: sum('variant_count')/ (`high_coverage_scale_factor` * sum('possible_variants' * 'mu_snp') at low coverage site\n where `high_coverage_scale_factor` = sum('variant_count') / sum('possible_variants' * 'mu_snp') at high coverage site\n \n .. note::\n This function expects that the input `coverage_ht` is the output of `get_proportion_observed_by_coverage`, and\n therefore the following fields should be present in `coverage_ht`:\n - context - trinucleotide genomic context\n - ref - the middle base of `context`\n - alt - the alternate base\n - methylation_level - methylation level\n - exome_coverage - median exome coverage at integer values between 1-100\n - variant_count - the number of observed variants in the dataset for each substitution (`alt`), `context`,\n `methylation_level`, and median exome coverage (`exome_coverage`)\n - downsampling_counts_{pop} (pop defaults to `POPS`) - array of observed variant counts per population after downsampling\n - mu_snp - mutation rate\n - possible_variants - the number of possible variants in the dataset for each substitution (`alt`), `context`,\n `methylation_level`, and median exome coverage (`exome_coverage`)\n\n :param coverage_ht: Input coverage Table.\n :param trimers: Whether the contexts were trimmed or not. Defaults to False.\n :param weighted: Whether to weight the high coverage model (a linear regression model) by 'possible_variants'. Defaults to False.\n :param half_cutoff: Whether to use half of `HIGH_COVERAGE_CUTOFF` as coverage cutoff. Otherwise `HIGH_COVERAGE_CUTOFF` will be used. Defaults to False.\n :return: Coverage model and plateau models.\n \"\"\"\n keys = ['context', 'ref', 'alt', 'methylation_level', 'mu_snp']\n\n cov_cutoff = (HIGH_COVERAGE_CUTOFF / half_cutoff) if half_cutoff else HIGH_COVERAGE_CUTOFF\n all_high_coverage_ht = coverage_ht.filter(coverage_ht.exome_coverage >= cov_cutoff)\n agg_expr = {\n 'observed_variants': hl.agg.sum(all_high_coverage_ht.variant_count),\n 'possible_variants': hl.agg.sum(all_high_coverage_ht.possible_variants)\n }\n for pop in POPS:\n agg_expr[f'observed_{pop}'] = hl.agg.array_sum(all_high_coverage_ht[f'downsampling_counts_{pop}'])\n high_coverage_ht = all_high_coverage_ht.group_by(*keys).aggregate(**agg_expr)\n\n high_coverage_ht = annotate_variant_types(high_coverage_ht, not trimers)\n plateau_models = build_plateau_models_pop(high_coverage_ht, weighted=weighted)\n\n high_coverage_scale_factor = all_high_coverage_ht.aggregate(\n hl.agg.sum(all_high_coverage_ht.variant_count) /\n hl.agg.sum(all_high_coverage_ht.possible_variants * all_high_coverage_ht.mu_snp))\n\n all_low_coverage_ht = coverage_ht.filter((coverage_ht.exome_coverage < cov_cutoff) &\n (coverage_ht.exome_coverage > 0))\n\n low_coverage_ht = all_low_coverage_ht.group_by(log_coverage=hl.log10(all_low_coverage_ht.exome_coverage)).aggregate(\n low_coverage_obs_exp=hl.agg.sum(all_low_coverage_ht.variant_count) /\n (high_coverage_scale_factor * hl.agg.sum(all_low_coverage_ht.possible_variants * all_low_coverage_ht.mu_snp)))\n coverage_model = build_coverage_model(low_coverage_ht)\n # TODO: consider weighting here as well\n\n return coverage_model, plateau_models\n\n\ndef add_most_severe_csq_to_tc_within_ht(t: Union[hl.Table, hl.MatrixTable]) -> Union[hl.Table, hl.MatrixTable]:\n \"\"\"\n Add most_severe_consequence annotation to 'transcript_consequences' within the vep annotation.\n \n :param t: Input Table or MatrixTable.\n :return: Input Table or MatrixTable with most_severe_consequence annotation added.\n \"\"\"\n annotation = t.vep.annotate(transcript_consequences=t.vep.transcript_consequences.map(\n add_most_severe_consequence_to_consequence))\n return t.annotate_rows(vep=annotation) if isinstance(t, hl.MatrixTable) else t.annotate(vep=annotation)\n\n\ndef take_one_annotation_from_tc_within_ht(t: Union[hl.Table, hl.MatrixTable]) -> Union[hl.Table, hl.MatrixTable]: \n \"\"\"\n Annotate 'transcript_consequences' using only the first consequence (index 0) of 'transcript_consequences' within the\n vep annotation of the input Table.\n\n :param t: Input Table or MatrixTable.\n :return: Table or MatrixTable with only the first consequence for the 'transcript_consequences' annotation.\n \"\"\"\n annotation = t.vep.annotate(transcript_consequences=t.vep.transcript_consequences[0])\n return t.annotate_rows(vep=annotation) if isinstance(t, hl.MatrixTable) else t.annotate(vep=annotation)\n\n\ndef get_proportion_observed(exome_ht: hl.Table, context_ht: hl.Table, mutation_ht: hl.Table,\n plateau_models: Dict[str, Tuple[float, float]], coverage_model: Tuple[float, float],\n recompute_possible: bool = False, remove_from_denominator: bool = True,\n custom_model: str = None, dataset: str = 'gnomad',\n impose_high_af_cutoff_upfront: bool = True, half_cutoff = False) -> hl.Table:\n \"\"\"\n Compute the expected number of variants and observed:expected ratio using plateau models and coverage model.\n\n This function sums the number of possible variants times the mutation rate for all variants, and applies the calibration\n model separately for CpG transitions and other sites. For sites with coverage lower than the coverage cutoff, the value obtained \n from the previous step is multiplied by the coverage correction factor. These values are summed across the set of variants \n of interest to obtain the expected number of variants.\n \n A brief view of how to get the expected number of variants:\n mu_agg = the number of possible variants * the mutation rate (all variants)\n adjusted_mutation_rate = sum(plateau model slop * mu_agg + plateau model intercept) (separately for CpG transitions and other sites)\n if 0 < coverage < coverage cutoff:\n coverage_correction = coverage_model slope * log10(coverage) + coverage_model intercept\n expected_variants = sum(adjusted_mutation_rate * coverage_correction)\n else:\n expected_variants = sum(adjusted_mutation_rate)\n The expected_variants are summed across the set of variants of interest to obtain the final expected number of variants.\n \n Function adds the following annotations:\n - variant_count - observed variant counts annotated by `count_variants` function grouped by groupings (output of `annotate_constraint_groupings`)\n - adjusted_mutation_rate (including those for each population) - the sum of mutation rate adjusted by plateau models and possible variant counts grouped by groupings\n - possible_variants (including those for each population) - the sum of possible variant counts derived from the context Table grouped by groupings\n - expected_variants (including those for each population) - the sum of expected variant counts grouped by groupings\n - mu - sum(mu_snp * possible_variant * coverage_correction) grouped by groupings\n - obs_exp - observed:expected ratio\n - annotations annotated by `annotate_constraint_groupings`\n\n :param exome_ht: Exome site Table (output of `prepare_ht`) filtered to autosomes and pseudoautosomal regions.\n :param context_ht: Context Table (output of `prepare_ht`) filtered to autosomes and pseudoautosomal regions.\n :param mutation_ht: Mutation rate Table with 'mu_snp' field.\n :param plateau_models: Linear models (output of `build_plateau_models_pop`), with the values of the dictionary formatted as a Tuple of intercept and slope, that calibrates mutation rate to proportion observed for high coverage exome. It includes models for CpG site, non-CpG site, and each population in `POPS`.\n :param coverage_model: A linear model (output of `build_coverage_model`), formatted as a Tuple of intercept and slope, that calibrates a given coverage level to observed:expected ratio. It's a correction factor for low coverage sites.\n :param recompute_possible: Whether to use context Table to recompute the number of possible variants instead of using a precomputed intermediate Table if it exists. Defaults to False.\n :param remove_from_denominator: Whether to remove alleles in context Table if found in 'exome_ht' and is not a PASS variant with an allele count greater than 0, defaults to True\n :param custom_model: The customized model (one of \"standard\" or \"worst_csq\" for now), defaults to None.\n :param dataset: Dataset to use when computing frequency index, defaults to 'gnomad'.\n :param impose_high_af_cutoff_upfront: Whether to remove alleles with allele frequency larger than `af_cutoff` (0.001), defaults to True.\n :param half_cutoff: Whether to use half of `HIGH_COVERAGE_CUTOFF` as coverage cutoff. Otherwise `HIGH_COVERAGE_CUTOFF` will be used, defaults to False.\n :return: Table with `expected_variants` (expected variant counts) and `obs_exp` (observed:expected ratio) annotations.\n \"\"\"\n exome_ht = add_most_severe_csq_to_tc_within_ht(exome_ht)\n context_ht = add_most_severe_csq_to_tc_within_ht(context_ht)\n\n if custom_model == 'syn_canonical':\n context_ht = take_one_annotation_from_tc_within_ht(fast_filter_vep(context_ht))\n context_ht = context_ht.transmute(transcript_consequences=context_ht.vep.transcript_consequences)\n exome_ht = take_one_annotation_from_tc_within_ht(fast_filter_vep(exome_ht))\n exome_ht = exome_ht.transmute(transcript_consequences=exome_ht.vep.transcript_consequences)\n elif custom_model == 'worst_csq':\n context_ht = process_consequences(context_ht)\n context_ht = context_ht.transmute(worst_csq_by_gene=context_ht.vep.worst_csq_by_gene)\n context_ht = context_ht.explode(context_ht.worst_csq_by_gene)\n exome_ht = process_consequences(exome_ht)\n exome_ht = exome_ht.transmute(worst_csq_by_gene=exome_ht.vep.worst_csq_by_gene)\n exome_ht = exome_ht.explode(exome_ht.worst_csq_by_gene)\n elif custom_model == 'tx_annotation':\n tx_ht = load_tx_expression_data()\n context_ht = context_ht.annotate(**tx_ht[context_ht.key])\n context_ht = context_ht.explode(context_ht.tx_annotation)\n tx_ht = load_tx_expression_data(context=False)\n exome_ht = exome_ht.annotate(**tx_ht[exome_ht.key])\n exome_ht = exome_ht.explode(exome_ht.tx_annotation)\n elif custom_model == 'distance_to_splice':\n context_ht = annotate_distance_to_splice(context_ht)\n exome_ht = annotate_distance_to_splice(exome_ht)\n # TODO:\n # context_ht = context_ht.explode(context_ht.tx_annotation)\n # exome_ht = exome_ht.explode(exome_ht.tx_annotation)\n else:\n context_ht = context_ht.transmute(transcript_consequences=context_ht.vep.transcript_consequences)\n context_ht = context_ht.explode(context_ht.transcript_consequences)\n exome_ht = exome_ht.transmute(transcript_consequences=exome_ht.vep.transcript_consequences)\n exome_ht = exome_ht.explode(exome_ht.transcript_consequences)\n\n context_ht, _ = annotate_constraint_groupings(context_ht, custom_model=custom_model)\n exome_ht, grouping = annotate_constraint_groupings(exome_ht, custom_model=custom_model)\n\n context_ht = context_ht.filter(hl.is_defined(context_ht.exome_coverage)).select(\n 'context', 'ref', 'alt', 'methylation_level', *grouping)\n exome_ht = exome_ht.select(\n 'context', 'ref', 'alt', 'methylation_level', 'freq', 'pass_filters', *grouping)\n\n af_cutoff = 0.001\n\n freq_index = exome_ht.freq_index_dict.collect()[0][dataset]\n\n def keep_criteria(ht):\n crit = (ht.freq[freq_index].AC > 0) & ht.pass_filters & (ht.coverage > 0)\n if impose_high_af_cutoff_upfront:\n crit &= (ht.freq[freq_index].AF <= af_cutoff)\n return crit\n\n exome_join = exome_ht[context_ht.key]\n if remove_from_denominator:\n context_ht = context_ht.filter(hl.is_missing(exome_join) | keep_criteria(exome_join))\n\n exome_ht = exome_ht.filter(keep_criteria(exome_ht))\n\n possible_file = f'{root}/model/possible_data/possible_transcript_pop_{custom_model}.ht'\n if recompute_possible:\n ht = count_variants(context_ht, additional_grouping=grouping, partition_hint=2000, force_grouping=True)\n ht = annotate_with_mu(ht, mutation_ht)\n ht = ht.transmute(possible_variants=ht.variant_count)\n ht = annotate_variant_types(ht.annotate(mu_agg=ht.mu_snp * ht.possible_variants))\n model = hl.literal(plateau_models.total)[ht.cpg]\n cov_cutoff = (HIGH_COVERAGE_CUTOFF / half_cutoff) if half_cutoff else HIGH_COVERAGE_CUTOFF\n ann_expr = {\n 'adjusted_mutation_rate': ht.mu_agg * model[1] + model[0],\n 'coverage_correction': hl.case()\n .when(ht.coverage == 0, 0)\n .when(ht.coverage >= cov_cutoff, 1)\n .default(coverage_model[1] * hl.log10(ht.coverage) + coverage_model[0])\n }\n for pop in POPS:\n pop_model = hl.literal(plateau_models[pop])\n slopes = hl.map(lambda f: f[ht.cpg][1], pop_model)\n intercepts = hl.map(lambda f: f[ht.cpg][0], pop_model)\n ann_expr[f'adjusted_mutation_rate_{pop}'] = ht.mu_agg * slopes + intercepts\n ht = ht.annotate(**ann_expr)\n ann_expr = {\n 'expected_variants': ht.adjusted_mutation_rate * ht.coverage_correction,\n 'mu': ht.mu_agg * ht.coverage_correction\n }\n for pop in POPS:\n ann_expr[f'expected_variants_{pop}'] = ht[f'adjusted_mutation_rate_{pop}'] * ht.coverage_correction\n ht = ht.annotate(**ann_expr)\n ht.write(possible_file, True)\n\n possible_variants_ht = hl.read_table(possible_file)\n ht = count_variants(exome_ht, additional_grouping=grouping, partition_hint=2000, force_grouping=True,\n count_downsamplings=POPS, impose_high_af_cutoff_here=not impose_high_af_cutoff_upfront)\n ht = ht.join(possible_variants_ht, 'outer')\n ht.write(f'{root}/model/possible_data/all_data_transcript_pop_{custom_model}.ht', True)\n ht = hl.read_table(f'{root}/model/possible_data/all_data_transcript_pop_{custom_model}.ht')\n\n grouping.remove('coverage')\n agg_expr = {\n 'variant_count': hl.agg.sum(ht.variant_count),\n 'adjusted_mutation_rate': hl.agg.sum(ht.adjusted_mutation_rate),\n 'possible_variants': hl.agg.sum(ht.possible_variants),\n 'expected_variants': hl.agg.sum(ht.expected_variants),\n 'mu': hl.agg.sum(ht.mu)\n }\n for pop in POPS:\n agg_expr[f'adjusted_mutation_rate_{pop}'] = hl.agg.array_sum(ht[f'adjusted_mutation_rate_{pop}'])\n agg_expr[f'expected_variants_{pop}'] = hl.agg.array_sum(ht[f'expected_variants_{pop}'])\n agg_expr[f'downsampling_counts_{pop}'] = hl.agg.array_sum(ht[f'downsampling_counts_{pop}'])\n ht = ht.group_by(*grouping).partition_hint(1000).aggregate(**agg_expr)\n return ht.annotate(obs_exp=ht.variant_count / ht.expected_variants)\n\n\ndef finalize_dataset(po_ht: hl.Table, keys: Tuple[str] = ('gene', 'transcript', 'canonical'),\n n_partitions: int = 1000) -> hl.Table:\n \"\"\"\n Compute the pLI scores, 90% confidence interval around the observed:expected ratio, and z scores \n for synonymous variants, missense variants, and predicted loss-of-function (pLoF) variants.\n \n .. note::\n The following annotations should be present in `po_ht`:\n - modifier\n - annotation\n - variant_count\n - mu\n - possible_variants\n - expected_variants\n - expected_variants_{pop} (pop defaults to `POPS`)\n - downsampling_counts_{pop} (pop defaults to `POPS`)\n \n :param po_ht: Input Table with the number of expected variants (output of `get_proportion_observed`).\n :param keys: The keys of the output Table, defaults to ('gene', 'transcript', 'canonical').\n :param n_partitions: Desired number of partitions for `Table.repartition()`, defaults to 1000.\n :return: Table with pLI scores, confidence interval of the observed:expected ratio, and z scores.\n \"\"\"\n # This function aggregates over genes in all cases, as XG spans PAR and non-PAR X\n po_ht = po_ht.repartition(n_partitions).persist()\n\n # Getting classic LoF annotations (no LOFTEE)\n classic_lof_annotations = hl.literal({'stop_gained', 'splice_donor_variant', 'splice_acceptor_variant'})\n lof_ht_classic = po_ht.filter(classic_lof_annotations.contains(po_ht.annotation) &\n ((po_ht.modifier == 'HC') | (po_ht.modifier == 'LC')))\n lof_ht_classic = collapse_lof_ht(lof_ht_classic, keys, False)\n lof_ht_classic = lof_ht_classic.rename({x: f'{x}_classic' for x in list(lof_ht_classic.row_value)})\n\n # Getting all LoF annotations (LOFTEE HC + OS)\n lof_ht_classic_hc = po_ht.filter((po_ht.modifier == 'HC') | (po_ht.modifier == 'OS'))\n lof_ht_classic_hc = collapse_lof_ht(lof_ht_classic_hc, keys, False)\n lof_ht_classic_hc = lof_ht_classic_hc.rename({x: f'{x}_with_os' for x in list(lof_ht_classic_hc.row_value)})\n\n # Getting all LoF annotations (LOFTEE HC)\n lof_ht = po_ht.filter(po_ht.modifier == 'HC')\n lof_ht = collapse_lof_ht(lof_ht, keys, False)\n\n mis_ht = po_ht.filter(po_ht.annotation == 'missense_variant')\n agg_expr = {\n 'obs_mis': hl.agg.sum(mis_ht.variant_count),\n 'exp_mis': hl.agg.sum(mis_ht.expected_variants),\n 'oe_mis': hl.agg.sum(mis_ht.variant_count) / hl.agg.sum(mis_ht.expected_variants),\n 'mu_mis': hl.agg.sum(mis_ht.mu),\n 'possible_mis': hl.agg.sum(mis_ht.possible_variants)\n }\n for pop in POPS:\n agg_expr[f'exp_mis_{pop}'] = hl.agg.array_sum(mis_ht[f'expected_variants_{pop}'])\n agg_expr[f'obs_mis_{pop}'] = hl.agg.array_sum(mis_ht[f'downsampling_counts_{pop}'])\n mis_ht = mis_ht.group_by(*keys).aggregate(**agg_expr)\n\n pphen_mis_ht = po_ht.filter(po_ht.modifier == 'probably_damaging')\n pphen_mis_ht = pphen_mis_ht.group_by(*keys).aggregate(obs_mis_pphen=hl.agg.sum(pphen_mis_ht.variant_count),\n exp_mis_pphen=hl.agg.sum(pphen_mis_ht.expected_variants),\n oe_mis_pphen=hl.agg.sum(pphen_mis_ht.variant_count) / hl.agg.sum(pphen_mis_ht.expected_variants),\n possible_mis_pphen=hl.agg.sum(pphen_mis_ht.possible_variants))\n syn_ht = po_ht.filter(po_ht.annotation == 'synonymous_variant').key_by(*keys)\n agg_expr = {\n 'obs_syn': hl.agg.sum(syn_ht.variant_count),\n 'exp_syn': hl.agg.sum(syn_ht.expected_variants),\n 'oe_syn': hl.agg.sum(syn_ht.variant_count) / hl.agg.sum(syn_ht.expected_variants),\n 'mu_syn': hl.agg.sum(syn_ht.mu),\n 'possible_syn': hl.agg.sum(syn_ht.possible_variants)\n }\n for pop in POPS:\n agg_expr[f'exp_syn_{pop}'] = hl.agg.array_sum(syn_ht[f'expected_variants_{pop}'])\n agg_expr[f'obs_syn_{pop}'] = hl.agg.array_sum(syn_ht[f'downsampling_counts_{pop}'])\n syn_ht = syn_ht.group_by(*keys).aggregate(**agg_expr)\n\n ht = lof_ht_classic.annotate(**mis_ht[lof_ht_classic.key], **pphen_mis_ht[lof_ht_classic.key],\n **syn_ht[lof_ht_classic.key], **lof_ht[lof_ht_classic.key],\n **lof_ht_classic_hc[lof_ht_classic.key])\n syn_cis = oe_confidence_interval(ht, ht.obs_syn, ht.exp_syn, prefix='oe_syn')\n mis_cis = oe_confidence_interval(ht, ht.obs_mis, ht.exp_mis, prefix='oe_mis')\n lof_cis = oe_confidence_interval(ht, ht.obs_lof, ht.exp_lof, prefix='oe_lof')\n ht = ht.annotate(**syn_cis[ht.key], **mis_cis[ht.key], **lof_cis[ht.key])\n return calculate_all_z_scores(ht) # .annotate(**oe_confidence_interval(ht, ht.obs_lof, ht.exp_lof)[ht.key])\n\n\ndef collapse_lof_ht(lof_ht: hl.Table, keys: Tuple[str], calculate_pop_pLI: bool = False) -> hl.Table:\n \"\"\"\n Collapse the `lof_ht` by `keys` and annotate pLI scores and observed:expected ratio for pLoF variants.\n \n Function sums the number of observed pLoF variants, possible pLoF variants, and expected pLoF variants\n across all the combinations of `keys`, and uses the expected variant counts and observed variant counts\n to compute the pLI scores and observed:expected ratio.\n \n The following annotations are added to the output Table:\n - obs_lof - the sum of observed pLoF variants grouped by `keys`\n - mu_lof - the sum of mutation rate at pLoF variants grouped by `keys`\n - possible_lof - possible number of pLoF variants grouped by `keys`\n - exp_lof - expected number of pLoF variants grouped by `keys`\n - exp_lof_{pop} (pop defaults to `POPS`) - expected number of pLoF variants per population grouped by `keys`\n - obs_lof_{pop} (pop defaults to `POPS`) - observed number of pLoF variants per population grouped by `keys`\n - oe_lof - observed:expected ratio for pLoF variants (oe_lof=lof_ht.obs_lof / lof_ht.exp_lof)\n - annotations added by function `pLI()`\n\n .. note::\n The following annotations should be present in `lof_ht`:\n - variant_count\n - mu\n - possible_variants\n - expected_variants\n \n :param lof_ht: Table with specific pLoF annotations.\n :param keys: The keys used to collapse `lof_ht` and use as keys for the output Table.\n :param calculate_pop_pLI: Whether to calculate the pLI score for each population, defaults to False.\n :return: A collapsed Table with pLI scores and observed:expected ratio for pLoF variants.\n \"\"\"\n agg_expr = {\n 'obs_lof': hl.agg.sum(lof_ht.variant_count),\n 'mu_lof': hl.agg.sum(lof_ht.mu),\n 'possible_lof': hl.agg.sum(lof_ht.possible_variants),\n 'exp_lof': hl.agg.sum(lof_ht.expected_variants)\n }\n for pop in POPS:\n agg_expr[f'exp_lof_{pop}'] = hl.agg.array_sum(lof_ht[f'expected_variants_{pop}'])\n agg_expr[f'obs_lof_{pop}'] = hl.agg.array_sum(lof_ht[f'downsampling_counts_{pop}'])\n lof_ht = lof_ht.group_by(*keys).aggregate(**agg_expr).persist()\n lof_ht = lof_ht.filter(lof_ht.exp_lof > 0)\n if calculate_pop_pLI:\n pop_lengths = get_all_pop_lengths(lof_ht, 'obs_lof_')\n print(pop_lengths)\n for pop_length, pop in pop_lengths:\n print(f'Calculating pLI for {pop}...')\n plis = []\n for i in range(8, pop_length):\n print(i)\n ht = lof_ht.filter(lof_ht[f'exp_lof_{pop}'][i] > 0)\n pli_ht = pLI(ht, ht[f'obs_lof_{pop}'][i], ht[f'exp_lof_{pop}'][i])\n plis.append(pli_ht[lof_ht.key])\n lof_ht = lof_ht.annotate(**{\n f'pLI_{pop}': [pli.pLI for pli in plis],\n f'pRec_{pop}': [pli.pRec for pli in plis],\n f'pNull_{pop}': [pli.pNull for pli in plis],\n })\n return lof_ht.annotate(\n **pLI(lof_ht, lof_ht.obs_lof, lof_ht.exp_lof)[lof_ht.key],\n oe_lof=lof_ht.obs_lof / lof_ht.exp_lof).key_by(*keys)\n\n\ndef annotate_constraint_groupings(ht: Union[hl.Table, hl.MatrixTable],\n custom_model: str = None) -> Tuple[Union[hl.Table, hl.MatrixTable], List[str]]:\n \"\"\"\n Add constraint annotations to be used for groupings.\n \n Function adds the following annotations:\n - annotation - could be 'most_severe_consequence' of either 'worst_csq_by_gene' or 'transcript_consequences', or 'csq' of 'tx_annotation'\n - modifier - classic lof annotation, LOFTEE annotation, or PolyPhen annotation\n - gene\n - coverage\n - expressed (added when custom model specified as tx_annotation)\n - transcript (added when custom model isn't specified as worst_csq or tx_annotation)\n - canonical (added when custom model isn't specified as worst_csq or tx_annotation)\n \n ..note::\n HT must be exploded against whatever axis.\n\n :param ht: Input Table or MatrixTable.\n :param custom_model: The customized model (one of \"standard\" or \"worst_csq\" for now), defaults to None.\n :return: A tuple of input Table or MatrixTable with grouping annotations added and the names of added annotations.\n \"\"\"\n if custom_model == 'worst_csq':\n groupings = {\n 'annotation': ht.worst_csq_by_gene.most_severe_consequence,\n 'modifier': hl.case()\n .when(hl.is_defined(ht.worst_csq_by_gene.lof),\n ht.worst_csq_by_gene.lof)\n .when(hl.is_defined(ht.worst_csq_by_gene.polyphen_prediction),\n ht.worst_csq_by_gene.polyphen_prediction)\n .default('None'),\n 'gene': ht.worst_csq_by_gene.gene_symbol,\n 'coverage': ht.exome_coverage\n }\n elif custom_model == 'tx_annotation':\n groupings = {\n 'annotation': ht.tx_annotation.csq,\n 'modifier': ht.tx_annotation.lof,\n 'gene': ht.tx_annotation.symbol,\n 'expressed': hl.case(missing_false=True).when(\n ht.tx_annotation.mean_expression >= 0.9, 'high').when(\n ht.tx_annotation.mean_expression > 0.1, 'medium').when(\n hl.is_defined(ht.tx_annotation.mean_expression), 'low').default('missing'),\n 'coverage': ht.exome_coverage\n }\n else:\n groupings = {\n 'annotation': ht.transcript_consequences.most_severe_consequence,\n 'modifier': hl.case()\n .when(hl.is_defined(ht.transcript_consequences.lof),\n ht.transcript_consequences.lof)\n .when(hl.is_defined(ht.transcript_consequences.polyphen_prediction),\n ht.transcript_consequences.polyphen_prediction)\n .default('None'),\n 'transcript': ht.transcript_consequences.transcript_id,\n 'gene': ht.transcript_consequences.gene_symbol,\n 'canonical': hl.or_else(ht.transcript_consequences.canonical == 1, False),\n 'coverage': ht.exome_coverage\n }\n if custom_model == 'splice_region':\n groupings['distance_splice'] = ht.transcript_consequences\n ht = ht.annotate(**groupings) if isinstance(ht, hl.Table) else ht.annotate_rows(**groupings)\n return ht, list(groupings.keys())\n\n\n# Model building\ndef build_coverage_model(coverage_ht: hl.Table) -> (float, float):\n \"\"\"\n Calibrate coverage model.\n \n This function uses linear regression to build a model of log10(coverage) to this scaled ratio as a correction\n factor for low coverage sites.\n \n .. note::\n The following annotations should be present in `coverage_ht`:\n - low_coverage_obs_exp - an observed:expected ratio for a given coverage level \n - log_coverage - log10 coverage\n \n :param coverage_ht: Low coverage Table.\n :return: Tuple with intercept and slope of the model.\n \"\"\"\n return tuple(coverage_ht.aggregate(hl.agg.linreg(coverage_ht.low_coverage_obs_exp, [1, coverage_ht.log_coverage])).beta)\n\n\ndef build_plateau_models(ht: hl.Table, weighted: bool = False) -> Dict[str, Tuple[float, float]]:\n \"\"\"\n Calibrate high coverage model.\n \n The function fits two models, one for CpG transitions and one for the remainder of sites, to calibrate\n from the mutation rate to proportion observed.\n \n .. note::\n The following annotations should be present in `ht`:\n - observed_variants - observed variant counts for each combination of 'context', 'ref', 'alt', 'methylation_level', 'mu_snp\n - possible_variants - possible variant counts for each combination of 'context', 'ref', 'alt', 'methylation_level', 'mu_snp\n - cpg - whether it's a cpg site or not\n - mu_snp - mutation rate\n \n :param ht: High coverage Table.\n :param weighted: Whether to generalize the model to weighted least squares using 'possible_variants'.\n :return: A Dictionary of intercepts and slopes for observed variants overall.\n \"\"\"\n # TODO: try square weighting\n ht = ht.annotate(high_coverage_proportion_observed=ht.observed_variants / ht.possible_variants)\n return ht.aggregate(hl.agg.group_by(ht.cpg,\n hl.agg.linreg(ht.high_coverage_proportion_observed, [1, ht.mu_snp],\n weight=ht.possible_variants if weighted else None)\n ).map_values(lambda x: x.beta))\n\n\ndef build_plateau_models_pop(ht: hl.Table, weighted: bool = False) -> Dict[str, Tuple[float, float]]:\n \"\"\"\n Calibrate high coverage model (returns intercept and slope).\n \n The function fits two models, one for CpG transitions and one for the remainder of sites, to calibrate\n from the mutation rate to proportion observed in total and in each population.\n \n .. note::\n The following annotations should be present in `ht`:\n - observed_variants - observed variant counts for each combination of 'context', 'ref', 'alt', 'methylation_level', 'mu_snp\n - observed_variants_{pop} (where pop is each population) - observed variant counts for each population\n - possible_variants - possible variant counts for each combination of 'context', 'ref', 'alt', 'methylation_level', 'mu_snp\n - cpg - whether it's a cpg site or not\n - mu_snp - mutation rate\n \n :param ht: High coverage Table.\n :param weighted: Whether to generalize the model to weighted least squares using 'possible_variants'.\n :return: A Dictionary of intercepts and slopes for the full plateau models.\n \"\"\"\n pop_lengths = get_all_pop_lengths(ht)\n agg_expr = {\n pop: [hl.agg.group_by(ht.cpg,\n hl.agg.linreg(ht[f'observed_{pop}'][i] / ht.possible_variants, [1, ht.mu_snp],\n weight=ht.possible_variants if weighted else None)\n ).map_values(lambda x: x.beta) for i in range(length)]\n for length, pop in pop_lengths\n }\n agg_expr['total'] = hl.agg.group_by(ht.cpg,\n hl.agg.linreg(ht.observed_variants / ht.possible_variants, [1, ht.mu_snp],\n weight=ht.possible_variants if weighted else None)\n ).map_values(lambda x: x.beta)\n return ht.aggregate(hl.struct(**agg_expr))\n\n\ndef get_all_pop_lengths(ht, prefix: str = 'observed_', pops: List[str] = POPS, skip_assertion: bool = False):\n \"\"\"\n Get the minimum array length for specific per population annotations in `ht`.\n \n The annotations are specified by the combination of `prefix` and each population in `pops`.\n\n :param ht: Input Table.\n :param prefix: Prefix of population variant count. Defaults to 'observed_'.\n :param pops: List of populations. Defaults to `POPS`.\n :param skip_assertion: Whether to skip raising an AssertionError if all the arrays of variant counts within a population don't have the same length. Defaults to False.\n :return: A Dictionary with the minimum array length for each population.\n \"\"\"\n ds_lengths = ht.aggregate([hl.agg.min(hl.len(ht[f'{prefix}{pop}'])) for pop in pops])\n # temp_ht = ht.take(1)[0]\n # ds_lengths = [len(temp_ht[f'{prefix}{pop}']) for pop in pops]\n pop_lengths = list(zip(ds_lengths, pops))\n print('Found: ', pop_lengths)\n if not skip_assertion:\n assert ht.all(hl.all(lambda f: f, [hl.len(ht[f'{prefix}{pop}']) == length for length, pop in pop_lengths]))\n return pop_lengths\n\n\ndef get_downsamplings(ht):\n freq_meta = ht.freq_meta.collect()[0]\n downsamplings = [(i, int(x.get('downsampling'))) for i, x in enumerate(freq_meta)\n if x.get('group') == 'adj' and x.get('pop') == 'global'\n and x.get('downsampling') is not None]\n return downsamplings\n\n\n# Plotting\ndef old_new_compare(source, axis_type='log'):\n p1 = figure(title=\"Mutation rate comparison\", x_axis_type=axis_type, y_axis_type=axis_type, tools=TOOLS)\n p1.xaxis.axis_label = 'Old mutation rate'\n p1.yaxis.axis_label = 'New mutation rate'\n\n p1.scatter(x='old_mu_snp', y='mu_snp', fill_color='colors', line_color='colors', legend='variant_type',\n source=source)\n\n p1.select_one(HoverTool).tooltips = [(x, f'@{x}') for x in\n ('context', 'ref', 'alt', 'methylation_level', 'old_mu_snp', 'mu_snp') if\n x in list(source.data)]\n # p1.ray(x=[1e-9], y=[1e-9], length=0, angle=[45], angle_units=\"deg\", color=\"#FB8072\", line_width=2)\n p1.legend.location = \"top_left\"\n return p1\n\n\ndef pLI(ht: hl.Table, obs: hl.expr.Int32Expression, exp: hl.expr.Float32Expression) -> hl.Table:\n \"\"\"\n Compute the pLI score using the observed and expected variant counts.\n \n The output Table will include the following annotations:\n - pLI - Probability of loss-of-function intolerance; probability that transcript falls into \n distribution of haploinsufficient genes\n - pNull - Probability that transcript falls into distribution of unconstrained genes\n - pRec - Probability that transcript falls into distribution of recessive genes\n\n :param ht: Input Table.\n :param obs: Expression for the number of observed variants on each gene or transcript in `ht`.\n :param exp: Expression for the number of expected variants on each gene or transcript in `ht`.\n :return: StructExpression for the pLI score.\n \"\"\"\n last_pi = {'Null': 0, 'Rec': 0, 'LI': 0}\n pi = {'Null': 1 / 3, 'Rec': 1 / 3, 'LI': 1 / 3}\n expected_values = {'Null': 1, 'Rec': 0.463, 'LI': 0.089}\n ht = ht.annotate(_obs=obs, _exp=exp)\n\n while abs(pi['LI'] - last_pi['LI']) > 0.001:\n last_pi = copy.deepcopy(pi)\n ht = ht.annotate(\n **{k: v * hl.dpois(ht._obs, ht._exp * expected_values[k]) for k, v in pi.items()})\n ht = ht.annotate(row_sum=hl.sum([ht[k] for k in pi]))\n ht = ht.annotate(**{k: ht[k] / ht.row_sum for k, v in pi.items()})\n pi = ht.aggregate({k: hl.agg.mean(ht[k]) for k in pi.keys()})\n\n ht = ht.annotate(\n **{k: v * hl.dpois(ht._obs, ht._exp * expected_values[k]) for k, v in pi.items()})\n ht = ht.annotate(row_sum=hl.sum([ht[k] for k in pi]))\n return ht.select(**{f'p{k}': ht[k] / ht.row_sum for k, v in pi.items()})\n\n\ndef oe_confidence_interval(ht: hl.Table, obs: hl.expr.Int32Expression, exp: hl.expr.Float32Expression,\n prefix: str = 'oe', alpha: float = 0.05, select_only_ci_metrics: bool = True) -> hl.Table:\n \"\"\"\n Determine the confidence interval around the observed:expected ratio.\n \n For a given pair of observed (`obs`) and expected (`exp`) values, the function computes the density of the Poisson distribution\n (performed using Hail's `dpois` module) with fixed k (`x` in `dpois` is set to the observed number of variants) over a range of\n lambda (`lamb` in `dpois`) values, which are given by the expected number of variants times a varying parameter ranging between\n 0 and 2. The cumulative density function of the Poisson distribution density is computed and the value of the varying parameter\n is extracted at points corresponding to `alpha` (defaults to 5%) and 1-`alpha`(defaults to 95%) to indicate the lower and upper\n bounds of the confidence interval.\n \n Function will have following annotations in the output Table in addition to keys:\n - {prefix}_lower - the lower bound of confidence interval\n - {prefix}_upper - the upper bound of confidence interval\n\n :param ht: Input Table with the observed and expected variant counts for pLoF, missense, and synonymous variants.\n :param obs: Expression for the observed variant counts of pLoF, missense, or synonymous variants in `ht`.\n :param exp: Expression for the expected variant counts of pLoF, missense, or synonymous variants in `ht`.\n :param prefix: Prefix of upper and lower bounds, defaults to 'oe'.\n :param alpha: The significance level used to compute the confidence interval, defaults to 0.05.\n :param select_only_ci_metrics: Whether to return only upper and lower bounds instead of keeping all the annotations except `_exp`, defaults to True.\n :return: Table with the confidence interval lower and upper bounds.\n \"\"\"\n ht = ht.annotate(_obs=obs, _exp=exp)\n oe_ht = ht.annotate(_range=hl.range(0, 2000).map(lambda x: hl.float64(x) / 1000))\n oe_ht = oe_ht.annotate(_range_dpois=oe_ht._range.map(lambda x: hl.dpois(oe_ht._obs, oe_ht._exp * x)))\n\n oe_ht = oe_ht.transmute(_cumulative_dpois=hl.cumulative_sum(oe_ht._range_dpois))\n max_cumulative_dpois = oe_ht._cumulative_dpois[-1]\n oe_ht = oe_ht.transmute(_norm_dpois=oe_ht._cumulative_dpois.map(lambda x: x / max_cumulative_dpois))\n oe_ht = oe_ht.transmute(\n _lower_idx=hl.argmax(oe_ht._norm_dpois.map(lambda x: hl.or_missing(x < alpha, x))),\n _upper_idx=hl.argmin(oe_ht._norm_dpois.map(lambda x: hl.or_missing(x > 1 - alpha, x)))\n )\n oe_ht = oe_ht.transmute(**{\n f'{prefix}_lower': hl.cond(oe_ht._obs > 0, oe_ht._range[oe_ht._lower_idx], 0),\n f'{prefix}_upper': oe_ht._range[oe_ht._upper_idx]\n })\n if select_only_ci_metrics:\n return oe_ht.select(f'{prefix}_lower', f'{prefix}_upper')\n else:\n return oe_ht.drop('_exp')\n\n\ndef calculate_z(input_ht: hl.Table, obs: hl.expr.NumericExpression, exp: hl.expr.NumericExpression, output: str = 'z_raw') -> hl.Table:\n \"\"\"\n Compute the signed raw z score using observed and expected variant counts.\n \n The raw z scores are positive when the transcript had fewer variants than expected, and are negative when transcripts had more variants than expected.\n \n The following annotation is included in the output Table in addition to the `input_ht` keys:\n - `output` - the raw z score\n\n :param input_ht: Input Table.\n :param obs: Observed variant count expression.\n :param exp: Expected variant count expression.\n :param output: The annotation label to use for the raw z score output, defaults to 'z_raw'.\n :return: Table with raw z scores.\n \"\"\"\n ht = input_ht.select(_obs=obs, _exp=exp)\n ht = ht.annotate(_chisq=(ht._obs - ht._exp) ** 2 / ht._exp)\n return ht.select(**{output: hl.sqrt(ht._chisq) * hl.cond(ht._obs > ht._exp, -1, 1)})\n\n\ndef calculate_all_z_scores(ht: hl.Table) -> hl.Table:\n \"\"\"\n Calculate z scores for synomynous variants, missense variants, and pLoF variants.\n \n z score = {variant_annotation}_z_raw / {variant_annotation}_sd (variant_annotation could be syn, mis, or lof)\n \n Function will add the following annotations to output Table:\n - syn_sd (global) - standard deviation of synonymous variants raw z score\n - mis_sd (global) - standard deviation of missense varinats raw z score\n - lof_sd (global) - standard deviation of pLoF variants raw z score\n - constraint_flag - Reason gene does not have constraint metrics. One of:\n no variants: Zero observed synonymous, missense, pLoF variants\n no_exp_syn: Zero expected synonymous variants\n no_exp_mis: Zero expected missense variants\n no_exp_lof: Zero expected pLoF variants\n syn_outlier: Too many or too few synonymous variants; synonymous z score < -5 or synonymous z score > 5\n mis_too_many: Too many missense variants; missense z score < -5\n lof_too_many: Too many pLoF variants; pLoF z score < -5\n - syn_z - z score of synonymous variants\n - mis_z - z score of missense variants\n - lof_z - z score of pLoF variants\n\n :param ht: Input Table with observed and expected variant counts for synomynous variants, missense variants, and pLoF variants.\n :return: Table with z scores.\n \"\"\"\n ht = ht.annotate(**calculate_z(ht, ht.obs_syn, ht.exp_syn, 'syn_z_raw')[ht.key])\n ht = ht.annotate(**calculate_z(ht, ht.obs_mis, ht.exp_mis, 'mis_z_raw')[ht.key])\n ht = ht.annotate(**calculate_z(ht, ht.obs_lof, ht.exp_lof, 'lof_z_raw')[ht.key])\n reasons = hl.empty_set(hl.tstr)\n reasons = hl.cond(hl.or_else(ht.obs_syn, 0) + hl.or_else(ht.obs_mis, 0) + hl.or_else(ht.obs_lof, 0) == 0, reasons.add('no_variants'), reasons)\n reasons = hl.cond(ht.exp_syn > 0, reasons, reasons.add('no_exp_syn'), missing_false=True)\n reasons = hl.cond(ht.exp_mis > 0, reasons, reasons.add('no_exp_mis'), missing_false=True)\n reasons = hl.cond(ht.exp_lof > 0, reasons, reasons.add('no_exp_lof'), missing_false=True)\n reasons = hl.cond(hl.abs(ht.syn_z_raw) > 5, reasons.add('syn_outlier'), reasons, missing_false=True)\n reasons = hl.cond(ht.mis_z_raw < -5, reasons.add('mis_too_many'), reasons, missing_false=True)\n reasons = hl.cond(ht.lof_z_raw < -5, reasons.add('lof_too_many'), reasons, missing_false=True)\n ht = ht.annotate(constraint_flag=reasons)\n sds = ht.aggregate(hl.struct(\n syn_sd=hl.agg.filter(\n ~ht.constraint_flag.contains('no_variants') &\n ~ht.constraint_flag.contains('syn_outlier') &\n ~ht.constraint_flag.contains('no_exp_syn') &\n hl.is_defined(ht.syn_z_raw),\n hl.agg.stats(ht.syn_z_raw)).stdev,\n mis_sd=hl.agg.filter(\n ~ht.constraint_flag.contains('no_variants') &\n ~ht.constraint_flag.contains('mis_outlier') &\n ~ht.constraint_flag.contains('no_exp_mis') &\n hl.is_defined(ht.mis_z_raw) & (ht.mis_z_raw < 0),\n hl.agg.explode(lambda x: hl.agg.stats(x), [ht.mis_z_raw, -ht.mis_z_raw])\n ).stdev,\n lof_sd=hl.agg.filter(\n ~ht.constraint_flag.contains('no_variants') &\n ~ht.constraint_flag.contains('lof_outlier') &\n ~ht.constraint_flag.contains('no_exp_lof') &\n hl.is_defined(ht.lof_z_raw) & (ht.lof_z_raw < 0),\n hl.agg.explode(lambda x: hl.agg.stats(x), [ht.lof_z_raw, -ht.lof_z_raw])\n ).stdev\n ))\n print(sds)\n ht = ht.annotate_globals(**sds)\n return ht.transmute(syn_z=ht.syn_z_raw / sds.syn_sd,\n mis_z=ht.mis_z_raw / sds.mis_sd,\n lof_z=ht.lof_z_raw / sds.lof_sd)\n","repo_name":"broadinstitute/gnomad_lof","sub_path":"constraint_utils/constraint_basics.py","file_name":"constraint_basics.py","file_ext":"py","file_size_in_byte":72461,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"81"} +{"seq_id":"1224490176","text":"import nibabel\nimport numpy\nimport random\n\n# Dipy import\nfrom dipy.core.gradients import gradient_table\nfrom dipy.io.gradients import read_bvals_bvecs\nfrom dipy.tracking.eudx import EuDX\nfrom dipy.reconst import peaks, shm\nfrom dipy.tracking import utils\n\n\ndef deterministic(diffusion_file, bvecs_file, bvals_file, trackfile,\n mask_file=None, order=4, nb_seeds_per_voxel=1, step=0.5):\n \"\"\" Compute a deterministic tractography using an ODF model.\n\n Parameters\n ----------\n diffusion_file: str (mandatory)\n a file containing the preprocessed diffusion data.\n bvecs_file: str (mandatory)\n a file containing the diffusion gradient directions.\n bvals_file: str (mandatory)\n a file containing the diffusion b-values.\n trackfile: str (mandatory)\n a file path where the fibers will be saved in trackvis format.\n mask_file: str (optional, default None)\n an image used to mask the diffusion data during the tractography. If\n not set, all the image voxels are considered.\n order: int (optional, default 4)\n the order of the ODF model.\n nb_seeds_per_voxel: int (optional, default 1)\n the number of seeds per voxel used during the propagation.\n step: float (optional, default 0.5)\n the integration step in voxel fraction used during the propagation.\n\n Returns\n -------\n streamlines: tuple of 3-uplet\n the computed fiber tracks in trackvis format (points: ndarray shape\n (N,3) where N is the number of points, scalars: None or ndarray shape\n (N, M) where M is the number of scalars per point, properties: None or\n ndarray shape (P,) where P is the number of properties).\n hdr: structured array\n structured array with trackvis header fields (voxel size, voxel order,\n dim).\n \"\"\"\n # Read diffusion sequence\n bvals, bvecs = read_bvals_bvecs(bvals_file, bvecs_file)\n gtab = gradient_table(bvals, bvecs)\n diffusion_image = nibabel.load(diffusion_file)\n diffusion_array = diffusion_image.get_data()\n if mask_file is not None:\n mask_array = nibabel.load(mask_file).get_data()\n else:\n mask_array = numpy.ones(diffusion_array.shape[:3], dtype=numpy.uint8)\n\n # Estimate ODF model\n csamodel = shm.CsaOdfModel(gtab, order)\n csapeaks = peaks.peaks_from_model(\n model=csamodel, data=diffusion_array, sphere=peaks.default_sphere,\n relative_peak_threshold=.8, min_separation_angle=45,\n mask=mask_array)\n\n # Compute deterministic tractography in voxel space so affine is equal\n # to identity\n seeds = utils.seeds_from_mask(mask_array, density=nb_seeds_per_voxel)\n streamline_generator = EuDX(\n csapeaks.peak_values, csapeaks.peak_indices,\n odf_vertices=peaks.default_sphere.vertices, a_low=.05, step_sz=step,\n seeds=seeds)\n # affine = streamline_generator.affine\n\n # Save the tracks in trackvis format\n hdr = nibabel.trackvis.empty_header()\n hdr[\"voxel_size\"] = diffusion_image.get_header().get_zooms()[:3]\n hdr[\"voxel_order\"] = \"LAS\"\n hdr[\"dim\"] = diffusion_array.shape[:3]\n streamlines = [track for track in streamline_generator]\n random.shuffle(streamlines)\n streamlines = ((track, None, None) for track in streamlines)\n nibabel.trackvis.write(trackfile, streamlines, hdr, points_space=\"voxel\")\n\n return streamlines, hdr\n","repo_name":"neurospin/caps-clindmri","sub_path":"clindmri/tractography/pydipy.py","file_name":"pydipy.py","file_ext":"py","file_size_in_byte":3396,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"73094156425","text":"#!/usr/bin/env python3\n\nimport os\nimport numpy as np\nimport pandas as pd\nfrom tqdm import tqdm\nimport matplotlib.pyplot as plt\nimport matplotlib.image as image\nfrom sklearn.model_selection import train_test_split\nfrom skimage.transform import rescale, resize\nfrom skimage.io import imread\nfrom keras.models import Model, load_model, save_model\nfrom keras.layers import Input\nfrom keras.layers.core import Dropout, Lambda\nfrom keras.layers.convolutional import Conv2D, Conv2DTranspose\nfrom keras.layers.pooling import MaxPooling2D\nfrom keras.layers.merge import concatenate\nimport keras.backend as K\n\n\"\"\"\nSpecify the root directory where data and scripts are placed\n\"\"\"\n\n#ROOT_PATH = '/content/drive/My Drive/data-science-bowl-2018'\nROOT_PATH = ''\n\nIMG_HEIGHT = 128\nIMG_WIDTH = 128\nIMG_CHANNELS = 3\nSTAGE_1_LABELS = os.path.join(ROOT_PATH, 'stage1_train_labels.csv')\nSTAGE_1_SOLUTION = os.path.join(ROOT_PATH, 'stage1_solution.csv')\nSTAGE_1_TEST = os.path.join(ROOT_PATH, 'stage1_test')\nSTAGE_1_TRAIN = os.path.join(ROOT_PATH, 'stage1_train')\nSTAGE_2_TEST = os.path.join(ROOT_PATH, 'stage2_test_final')\nEPOCHS = 50\n\n\n\"\"\"\nFunction get_images\n:param ids: identifiers of images to locate in the\n\tdata sctructure\n:param height: image height\n:param width: image width\n:param channels: image channels (3 for RGB, 1 for Grayscale)\n:param return_masks: load with or without corresponding mask\nreturn: if return_masks is set to true tuple of ndarrays\n\tcorrecsponding to image and its mask\n\tif return_masks is set to false ndarrays for images only\n\"\"\"\ndef get_images(ids, height=IMG_HEIGHT, width=IMG_WIDTH,\n channels=IMG_CHANNELS, return_masks=False):\n\n X = np.zeros((len(ids), height, width, channels))\n y = np.zeros((len(ids), height, width, 1), dtype=np.bool)\n for n, i in tqdm(enumerate(ids), total=len(ids)):\n path = os.path.join(STAGE_1_TRAIN, i)\n img = imread(os.path.join(path, 'images', i+'.png'))[:,:,:channels]\n img = resize(img, (IMG_HEIGHT, IMG_WIDTH),\n mode='constant', preserve_range=True)\n X[n] = img\n if return_masks:\n mask = np.zeros((height, width, 1), dtype=np.bool)\n for mask_file in next(os.walk(path + '/masks/'))[2]:\n mask_ = imread(path + '/masks/' + mask_file)\n mask_ = np.expand_dims(resize(mask_, (height, width),\n mode='constant',\n preserve_range=True), axis=-1)\n mask = np.maximum(mask, mask_)\n y[n] = mask\n\n if return_masks:\n return (X, y)\n return X\n\n\n\"\"\"\nLoss function dice_loss\n:param y_true: true masks tensor\n:param y_pred: predicted masks\n:return: loss to propogate backward\n\"\"\"\ndef dice_loss(y_true, y_pred, smooth=1):\n\n y_true_f = K.flatten(y_true)\n y_pred_f = K.flatten(y_pred)\n intersection = K.sum(y_true_f * y_pred_f)\n return -((2. * intersection + smooth) / (K.sum(y_true_f) + K.sum(y_pred_f) + smooth))\n\n\n\"\"\"\nFunction build_unet_model\nBuilding the basic UNet model\n:param height: heigth of training images\n:param width: heigth of training width\n:param channels: channels of images \n\n:return: Keras Model object\n\"\"\"\ndef build_unet_model(height=IMG_HEIGHT,\n width=IMG_WIDTH,\n channels=IMG_CHANNELS):\n\n inputs = Input((height, width, channels))\n inp = Lambda(lambda x: x / 255) (inputs)\n\n conv1 = Conv2D(16, (3, 3), activation='relu', padding='same')(inp)\n conv1 = Dropout(0.2)(conv1)\n conv1 = Conv2D(16, (3, 3), activation='relu', padding='same')(conv1)\n pool1 = MaxPooling2D((2, 2))(conv1)\n\n conv2 = Conv2D(32, (3, 3), activation='relu', padding='same')(pool1)\n conv2 = Dropout(0.2)(conv2)\n conv2 = Conv2D(32, (3, 3), activation='relu', padding='same')(conv2)\n pool2 = MaxPooling2D((2, 2))(conv2)\n\n conv3 = Conv2D(64, (3, 3), activation='relu', padding='same')(pool2)\n conv3 = Dropout(0.2)(conv3)\n conv3 = Conv2D(64, (3, 3), activation='relu', padding='same')(conv3)\n pool3 = MaxPooling2D((2, 2)) (conv3)\n\n conv4 = Conv2D(128, (3, 3), activation='relu', padding='same')(pool3)\n conv4 = Dropout(0.2)(conv4)\n conv4 = Conv2D(128, (3, 3), activation='relu', padding='same')(conv4)\n pool4 = MaxPooling2D(pool_size=(2, 2))(conv4)\n\n conv5 = Conv2D(256, (3, 3), activation='relu', padding='same')(pool4)\n conv5 = Dropout(0.2)(conv5)\n c5 = Conv2D(256, (3, 3), activation='relu', padding='same')(conv5)\n\n upconv1 = Conv2DTranspose(128, (2, 2), strides=(2, 2), padding='same')(conv5)\n upconv1 = concatenate([upconv1, conv4])\n conv6 = Conv2D(128, (3, 3), activation='relu', padding='same')(upconv1)\n conv6 = Dropout(0.1)(conv6)\n conv6 = Conv2D(128, (3, 3), activation='relu', padding='same')(conv6)\n\n upconv2 = Conv2DTranspose(64, (2, 2), strides=(2, 2), padding='same')(conv6)\n upconv2 = concatenate([upconv2, conv3])\n conv7 = Conv2D(64, (3, 3), activation='relu', padding='same')(upconv2)\n conv7 = Dropout(0.1)(conv7)\n conv7 = Conv2D(64, (3, 3), activation='relu', padding='same')(conv7)\n\n upconv8 = Conv2DTranspose(32, (2, 2), strides=(2, 2), padding='same')(conv7)\n upconv8 = concatenate([upconv8, conv2])\n conv8 = Conv2D(32, (3, 3), activation='relu', padding='same')(upconv8)\n conv8 = Dropout(0.1)(conv8)\n conv8 = Conv2D(32, (3, 3), activation='relu', padding='same')(conv8)\n\n upconv9 = Conv2DTranspose(16, (2, 2), strides=(2, 2), padding='same')(conv8)\n upconv9 = concatenate([upconv9, conv1], axis=3)\n conv9 = Conv2D(16, (3, 3), activation='relu', padding='same')(upconv9)\n conv9 = Dropout(0.1)(conv9)\n conv9 = Conv2D(16, (3, 3), activation='relu', padding='same')(conv9)\n\n outputs = Conv2D(1, (1, 1), activation='sigmoid')(conv9)\n\n model = Model(inputs=[inputs], outputs=[outputs])\n model.compile(optimizer='adam',\n loss=iou_loss,\n metrics=['accuracy'])\n model.summary()\n\n return model\n\ndef main():\n stage_1_train_ids = next(os.walk(STAGE_1_TRAIN))[1]\n stage_1_test_ids = next(os.walk(STAGE_1_TRAIN))[1]\n #stage_2_test_ids = next(os.walk(STAGE_1_TRAIN))[1]\n print('Loading images...')\n X_train, y_train = get_images(ids = stage_1_train_ids, return_masks=True)\n X_train, X_test, y_train, y_test = train_test_split(X_train, \n y_train, \n test_size=0.2, \n random_state=0)\n\n model = build_unet_model()\n print('Training model...')\n model.fit(X_train, y_train, batch_size=16, epochs=EPOCHS, verbose=2)\n print('How good is our model performing?')\n print(model.evaluate(X_test, y_test, batch_size=16))\n model.save('unet_model.h5')\n\nif __name__ == '__main__':\n main()\n","repo_name":"erelin6613/data-science-bowl-2018","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":6877,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"8596959644","text":"import uuid\nfrom typing import Optional\nfrom pydantic import BaseModel, Field\n\"\"\"\n\n\n\"\"\"\nclass Sounds(BaseModel):\n id: str = Field(default_factory=uuid.uuid4, alias=\"_id\")\n length: int = Field(...)\n chunkSize: int = Field(...)\n uploadDate: str = Field(...)\n filename: str = Field(...) \n metadata: str = Field()\n\n class Config:\n allow_population_by_field_name = True\n schema_extra = {\n \"example\": {\n \"id\": \"63544832a813904ab5e69b84\",\n \"length\": 865060,\n \"chunkSize\": 261120,\n \"uploadDate\": \"2022-10-22T19:44:58.290+00:00\",\n \"filename\": \"/Users/brandon/Documents/projects/fastapi-mongo-demo/env/sounds/Beach_…\",\n \"metadata\": object\n }\n }","repo_name":"RealzB/HackGT-9","sub_path":"backend/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":790,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"37799239355","text":"import sys\nsys.stdin = open('input.txt', 'r')\ninput = sys.stdin.readline\n\n\nimport collections\n\nN = int(input())\ncase = list(map(int, input().split()))\nvalue_case = collections.Counter()\nfor item in case:\n value_case[item] += 1\n\n# print(value_case)\nanswer_list = []\ncheck_case = []\ncheck = False\nfor i in range(N):\n check_case.append([case[i], value_case[case[i]]])\n\nprint(check_case)\n\nfor i in range(N):\n for j in range(i+1, N):\n if check_case[i][1] < check_case[j][1]:\n answer_list.append(check_case[j][0])\n check = True\n break\n else:\n check = False\n continue\n\n if not check:\n answer_list.append(-1)\n\nanswer_list.append(-1)\nprint(*answer_list)\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# answer_list = [-1]\n\n# current_top_left_value = value_case[case[0]]\n# current_top_left_keys = case[0]\n\n# for i in range(1, N):\n# if current_top_left_value < value_case[case[i]]:\n# answer_list.append(-1)\n# elif current_top_left_value == value_case[case[i]]:\n# current_top_left_value = value_case[case[i]]\n# current_top_left_keys = case[i]\n# answer_list.append(-1)\n# else:\n# answer_list.append(current_top_left_keys)\n\n# print(answer_list)","repo_name":"BTDnoBacon/algorithm","sub_path":"baekjoon/gold3/#17299/17299.py","file_name":"17299.py","file_ext":"py","file_size_in_byte":1256,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"32465375370","text":"from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer\nfrom textblob import TextBlob\nimport re\nimport nltk\nfrom nltk.corpus import stopwords\nfrom nltk.stem import WordNetLemmatizer\nfrom tqdm import tqdm\nimport pandas as pd\nfrom collections import Counter\n\ndef clean_tweet(text):\n '''\n Utility function to clean the text in a tweet by removing\n links and special characters using regex.\n '''\n return ' '.join(re.sub(\"(@[A-Za-z0-9]+)|([^0-9A-Za-z \\t])|(\\w+:\\/\\/\\S+)\", \" \", text).split())\n\ndef analize_sentiment(text):\n '''\n Utility function to classify the polarity of a tweet\n using vader sentiment analyzer.\n '''\n analyser = SentimentIntensityAnalyzer()\n score = analyser.polarity_scores(clean_tweet(text))\n return score\n\ndef analize_subjectivity(text):\n '''\n Utility function to classify the polarity of a tweet\n using textblob.\n '''\n analysis = TextBlob(clean_tweet(text))\n return(analysis.sentiment.subjectivity)\n\n#_______________________________________________________________#\n# Apply sentiment functions to data\n\ndef get_sentiment_and_subjectivity(tweets_df):\n assert 'Text' in tweets_df.columns, \"this is not a tweet dataframe\"\n\n # remove hyperlink and non-text info from tweet\n clean = [clean_tweet(x) for x in tweets_df['Text']]\n\n # determine sentiment and subjectivity with vadersentiment and textblob, respectively\n subjectivity = [analize_subjectivity(x) for x in clean]\n polarity = [analize_sentiment(x) for x in tqdm(clean)]\n neg = [x['neg'] for x in polarity]\n pos = [x['pos'] for x in polarity]\n neu = [x['neu'] for x in polarity]\n compound = [x['compound'] for x in polarity]\n\n # append information onto tweet dataframe\n tweets_df['Subjectivity'] = subjectivity\n tweets_df['neg'] = neg\n tweets_df['neu'] = neu\n tweets_df['pos'] = pos\n tweets_df['Sentiment'] = compound\n\n return (tweets_df)\n\n#_______________________________________________________________#\n# Apply sentiment functions to data\n\ndef word_extraction(sentence):\n ignore = set(stopwords.words('english'))\n words = re.sub(\"[^\\w]\", \" \", sentence).split()\n cleaned_text = [w.lower() for w in words if w not in ignore]\n return cleaned_text\n\nlemmatizer = WordNetLemmatizer()\n\ndef Lemmatize(wordlist):\n return [lemmatizer.lemmatize(word) for word in wordlist]\n\ndef preprocess(text):\n text = clean_tweet(text)\n tknzr = nltk.TweetTokenizer()\n text = tknzr.tokenize(text)\n ignore_words = set(stopwords.words('english'))\n # lowercase, remove words less than len 2 & remove numbers in tokenized list\n return [word.lower() for word in text if len(word) > 2 and not word.isdigit() and not word in ignore_words]\n\ndef get_NER_parameters(tweets_df):\n texts = tweets_df['Text'].apply(preprocess)\n\n texts = texts.apply(Lemmatize)\n texts = texts.reset_index(drop=True)\n\n NER = pd.DataFrame([Counter([x[1] for x in nltk.pos_tag(texts[index])]) for index in tqdm(range(len(texts)))])\n NER = NER.fillna(0)\n NER['Len'] = [len(i) for i in texts]\n tweets_df[NER.columns] = NER\n\n return tweets_df","repo_name":"Robdei/Trump-Tweets","sub_path":"Download_RDT_Tweets/nlp_functions.py","file_name":"nlp_functions.py","file_ext":"py","file_size_in_byte":3127,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"30109497588","text":"import json\nfrom nltk_utils import tokenize, stem, bag_of_words\nimport numpy as np\n\nimport torch\nimport torch.nn as nn\nfrom torch.utils.data import Dataset, DataLoader\n\nfrom model import NeuralNet\n\nwith open('intents.json', 'r') as f:\n intents = json.load(f)\n\nall_words = []\ntags = []\nxy = [] # (word, tag)\n\nfor intent in intents['intents']:\n tag = intent['tag']\n tags.append(tag)\n for pattern in intent['patterns']:\n w = tokenize(pattern)\n all_words.extend(w)\n xy.append((w, tag))\n\nignore_words = ['?', '!', '.', ',']\nall_words = [stem(x) for x in all_words if x not in ignore_words]\nall_words = sorted(set(all_words))\ntags = sorted(set(tags))\n\n\nX_train = []\ny_train = []\n\nfor (pattern_sentence, tag) in xy:\n bag = bag_of_words(pattern_sentence, all_words)\n X_train.append(bag)\n\n label = tags.index(tag)\n y_train.append(label) # CrossEntryopyLoss\n\nX_train = np.array(X_train)\ny_train = np.array(y_train)\n\nclass ChatDataset(object):\n def __init__(self):\n self.n_samples = len(X_train)\n self.x_data = X_train\n self.y_data = y_train\n\n def __getitem__(self, index):\n return self.x_data[index], self.y_data[index]\n\n def __len__(self):\n return self.n_samples\n\n\n\ndef main():\n # hyperparameters\n num_epochs = 500\n batch_size = 64\n learning_rate = 0.001\n hidden_size = 64\n output_size = len(tags)\n input_size = len(X_train[0])\n\n # dataset and data loader\n dataset = ChatDataset()\n train_loader = DataLoader(dataset=dataset,\n batch_size=batch_size,\n shuffle=True,\n num_workers=2)\n test_loader = DataLoader(dataset=dataset,\n batch_size=batch_size,\n shuffle=False,\n num_workers=2)\n # model\n device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n model = NeuralNet(input_size, hidden_size, output_size).to(device)\n\n # loss and optimizer\n criterion = nn.CrossEntropyLoss()\n optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)\n\n # training loop\n for epoch in range(num_epochs):\n for (words, labels) in train_loader:\n words = words.to(device)\n labels = labels.to(device)\n # forward\n outputs = model(words)\n loss = criterion(outputs, labels.long())\n # backward and optimizer step\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n \n # compute and print test accuracy\n with torch.no_grad():\n correct = 0\n total = 0\n for (words, labels) in test_loader:\n words = words.to(device)\n labels = labels.to(device)\n outputs = model(words)\n _, predicted = torch.max(outputs.data, 1)\n total += labels.size(0)\n correct += (predicted == labels).sum().item()\n accuracy = 100 * correct / total\n # print(f'Test accuracy: {accuracy:.2f}%')\n # print epoch loss\n if (epoch + 1) % 100 == 0:\n print(f'Epoch [{epoch+1}/{num_epochs}], Loss: {loss.item():.4f}')\n \n print(f'final loss, loss={loss.item():.4f}')\n\n data = {\n \"model_state\": model.state_dict(),\n \"input_size\": input_size,\n \"output_size\": output_size,\n \"hidden_size\": hidden_size,\n \"all_words\": all_words,\n \"tags\": tags\n }\n\n # save the model checkpoint\n FILE = \"data.pth\"\n torch.save(data, FILE)\n print(f'trainig complete. file saved to {FILE}')\n\nif __name__ == '__main__':\n main()","repo_name":"Nour-Ibrahim-1290/Coffe_Shop-Customer_Service-ChatBot","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":3721,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"17902710676","text":"# -*- coding: utf-8 -*-\n\nimport codecs\nimport json\nimport os\nimport openpyxl\n\n\nclass info():\n def __init__(self, file):\n xlsx = openpyxl.load_workbook(file)\n sheet = xlsx.active\n self.data = {}\n\n for rows in sheet.iter_rows(2, 0, 0, sheet.max_column):\n group = []\n productRevenue = []\n product = []\n concept = []\n\n if rows[4].value != None:\n group = rows[4].value.split(',')\n\n if rows[5].value != None:\n productRevenue = rows[5].value.split(',')\n\n if rows[6].value != None:\n product = rows[6].value.split(',')\n\n if rows[8].value != None:\n concept = rows[8].value.split(',')\n\n if rows[11].value == '1':\n on = 'tse'\n else:\n on = 'otc'\n\n self.data[rows[0].value] = {\n 'code': rows[0].value,\n 'name': rows[1].value,\n 'value': int(rows[2].value) * 1000,\n 'industryName': rows[3].value,\n 'group': group,\n 'productRevenue': productRevenue,\n 'product': product,\n 'concept': concept,\n 'industryPosition': rows[9].value,\n 'on': on,\n 'close': bool(rows[12].value),\n }\n\n def output(self, output):\n f = codecs.open(os.path.join(output, 'stock.json'), 'w+', 'utf-8')\n f.write(json.dumps(self.data, ensure_ascii=False))\n f.close()\n","repo_name":"Junxwan/freeold","sub_path":"xlsx/stock.py","file_name":"stock.py","file_ext":"py","file_size_in_byte":1558,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"39727377465","text":"from PyQt5.QtWidgets import *\r\nfrom PyQt5 import QtCore, QtGui, QtWidgets\r\nfrom selenium import webdriver\r\nfrom selenium.common.exceptions import NoSuchElementException\r\nfrom selenium.webdriver.common.keys import Keys\r\nfrom bs4 import BeautifulSoup\r\nimport time\r\nimport os\r\n\r\n\r\nclass Ui_Alpas(object):\r\n def setupUi(self, Alpas):\r\n Alpas.setObjectName(\"Alpas\")\r\n Alpas.resize(430, 280)\r\n self.reserve_from = QtWidgets.QDateEdit(Alpas)\r\n self.reserve_from.setDate(QtCore.QDate.currentDate())\r\n self.reserve_from.setGeometry(QtCore.QRect(240, 80, 150, 30))\r\n font = QtGui.QFont()\r\n font.setFamily(\"-윤고딕340\")\r\n font.setPointSize(12)\r\n self.reserve_from.setFont(font)\r\n self.reserve_from.setCalendarPopup(True)\r\n self.reserve_from.setObjectName(\"reserve_from\")\r\n self.reserve_to = QtWidgets.QDateEdit(Alpas)\r\n self.reserve_to.setDate(QtCore.QDate.currentDate())\r\n self.reserve_to.setGeometry(QtCore.QRect(240, 130, 150, 30))\r\n font = QtGui.QFont()\r\n font.setFamily(\"-윤고딕340\")\r\n font.setPointSize(12)\r\n self.reserve_to.setFont(font)\r\n self.reserve_to.setCalendarPopup(True)\r\n self.reserve_to.setObjectName(\"reserve_to\")\r\n self.alpas_id = QtWidgets.QLineEdit(Alpas)\r\n self.alpas_id.setGeometry(QtCore.QRect(40, 80, 150, 30))\r\n font = QtGui.QFont()\r\n font.setFamily(\"-윤고딕340\")\r\n font.setPointSize(12)\r\n self.alpas_id.setFont(font)\r\n self.alpas_id.setObjectName(\"alpas_id\")\r\n self.alpas_pw = QtWidgets.QLineEdit(Alpas)\r\n self.alpas_pw.setGeometry(QtCore.QRect(40, 130, 150, 30))\r\n font = QtGui.QFont()\r\n font.setFamily(\"-윤고딕340\")\r\n font.setPointSize(12)\r\n self.alpas_pw.setFont(font)\r\n self.alpas_pw.setObjectName(\"alpas_pw\")\r\n self.reserve_date = QtWidgets.QLabel(Alpas)\r\n self.reserve_date.setGeometry(QtCore.QRect(240, 40, 51, 22))\r\n font = QtGui.QFont()\r\n font.setFamily(\"Noto Sans KR Bold\")\r\n font.setPointSize(14)\r\n font.setBold(True)\r\n font.setWeight(75)\r\n self.reserve_date.setFont(font)\r\n self.reserve_date.setObjectName(\"reserve_date\")\r\n self.alpas = QtWidgets.QLabel(Alpas)\r\n self.alpas.setGeometry(QtCore.QRect(40, 40, 51, 22))\r\n font = QtGui.QFont()\r\n font.setFamily(\"Noto Sans KR Bold\")\r\n font.setPointSize(14)\r\n font.setBold(True)\r\n font.setWeight(75)\r\n self.alpas.setFont(font)\r\n self.alpas.setObjectName(\"alpas\")\r\n self.pushButton = QtWidgets.QPushButton(Alpas)\r\n self.pushButton.setGeometry(QtCore.QRect(40, 190, 350, 40))\r\n font = QtGui.QFont()\r\n font.setFamily(\"Noto Sans KR Bold\")\r\n font.setPointSize(12)\r\n font.setBold(True)\r\n font.setWeight(75)\r\n self.pushButton.setFont(font)\r\n self.pushButton.setObjectName(\"pushButton\")\r\n\r\n self.retranslateUi(Alpas)\r\n QtCore.QMetaObject.connectSlotsByName(Alpas)\r\n\r\n self.alpas_pw.setEchoMode(QLineEdit.Password)\r\n self.pushButton.clicked.connect(self.check_out_reserved_books)\r\n\r\n def retranslateUi(self, Alpas):\r\n _translate = QtCore.QCoreApplication.translate\r\n Alpas.setWindowTitle(_translate(\"Alpas\", \"Alpas 예약 도서 대출\"))\r\n self.reserve_from.setDisplayFormat(_translate(\"Alpas\", \"yyyy/MM/dd\"))\r\n self.reserve_to.setDisplayFormat(_translate(\"Alpas\", \"yyyy/MM/dd\"))\r\n self.alpas_id.setPlaceholderText(_translate(\"Alpas\", \"ID\"))\r\n self.alpas_pw.setPlaceholderText(_translate(\"Alpas\", \"PW\"))\r\n self.reserve_date.setText(_translate(\"Alpas\", \"예약일\"))\r\n self.alpas.setText(_translate(\"Alpas\", \"알파스\"))\r\n self.pushButton.setText(_translate(\"Alpas\", \"예약 도서 대출하기\"))\r\n\r\n def check_out_reserved_books(self):\r\n\r\n def send_reservation_date(from_, to_):\r\n driver.implicitly_wait(10)\r\n driver.find_element_by_id(\"reservation_date_from\").clear()\r\n driver.find_element_by_id(\"reservation_date_from\").send_keys(from_)\r\n driver.find_element_by_id(\"reservation_date_to\").clear()\r\n driver.find_element_by_id(\"reservation_date_to\").send_keys(to_)\r\n\r\n def get_reserver_name(i):\r\n reserver_name = driver.find_element_by_xpath(f'//*[@id=\"row{i}resv_target_list\"]/div[7]/div').text\r\n return reserver_name\r\n\r\n def get_reserver_account_number(i):\r\n reserver_account_number = driver.find_element_by_xpath(f'//*[@id=\"row{i}resv_target_list\"]/div[6]/div').text\r\n return reserver_account_number\r\n\r\n def get_book_title(i):\r\n book_title = driver.find_element_by_xpath(f'//*[@id=\"row{i}resv_target_list\"]/div[4]/div').text\r\n return book_title\r\n\r\n def get_regi_number():\r\n book_regi_num = driver.find_element_by_id('view_reg_no').text\r\n return book_regi_num\r\n\r\n def get_reserver():\r\n i = 0\r\n while True:\r\n try:\r\n reserver_name_list.append(get_reserver_name(i))\r\n reserver_account_list.append(get_reserver_account_number(i))\r\n book_title_list.append(get_book_title(i))\r\n except NoSuchElementException:\r\n break\r\n i += 1\r\n\r\n return reserver_name_list, reserver_account_list, book_title_list\r\n\r\n def get_book_id():\r\n driver.current_url\r\n result = driver.page_source\r\n bs_obj = BeautifulSoup(result, \"html.parser\")\r\n table = bs_obj.find(\"table\", id=\"table_contents\")\r\n checkboxes = table.find_all('input', class_=\"cbox checkbox\")\r\n\r\n return checkboxes[0].attrs['id']\r\n\r\n def cancel_and_check_out():\r\n\r\n i = 0\r\n while True:\r\n try:\r\n number_input = driver.find_element_by_id(\"main_number_txt\")\r\n number_input.clear()\r\n number_input.send_keys(reserver_account_list[i])\r\n number_input.send_keys(Keys.ENTER)\r\n time.sleep(1)\r\n\r\n reserved_booklist = driver.find_element_by_xpath('//*[@id=\"local_loan_container\"]/ul/li[2]/a')\r\n click(reserved_booklist)\r\n\r\n check_reserved_books = driver.find_element_by_xpath('/html/body/div[1]/div/div[3]/main/div/ul[2]/li[1]/div/div[2]/div/div[1]/div[3]/div[3]/div/table/tbody/tr[2]/td[2]/input')\r\n click(check_reserved_books)\r\n\r\n detail_status = driver.find_element_by_id('bookingStatusButton')\r\n click(detail_status)\r\n\r\n book_regi_number_list.append(get_regi_number())\r\n driver.implicitly_wait(5)\r\n\r\n cancel_reservation = driver.find_element_by_xpath('//*[@id=\"common_popup_1\"]/div/div/div[3]/div/div[2]/button[1]')\r\n click(cancel_reservation)\r\n\r\n cancel = driver.find_element_by_xpath('//*[@id=\"msg_btn_1\"]')\r\n click(cancel)\r\n\r\n confirm = driver.find_element_by_xpath('//*[@id=\"msg_btn_1\"]')\r\n click(confirm)\r\n print(f'\"{book_title_list[i]}\" 예약 취소')\r\n\r\n close = driver.find_element_by_xpath('//*[@id=\"common_popup_1\"]/div/div/div[3]/div/div[2]/button[2]')\r\n click(close)\r\n time.sleep(1)\r\n\r\n regi_input = driver.find_element_by_id(\"main_number_txt\")\r\n regi_input.clear()\r\n regi_input.send_keys(book_regi_number_list[i])\r\n regi_input.send_keys(Keys.ENTER)\r\n print(f'\"{book_title_list[i]}\" 대출')\r\n time.sleep(3)\r\n\r\n\r\n loan_list = driver.find_element_by_xpath('//*[@id=\"loanList\"]')\r\n click(loan_list)\r\n\r\n book_id.append(get_book_id())\r\n driver.implicitly_wait(5)\r\n\r\n check = driver.find_element_by_id(book_id[i])\r\n click(check)\r\n time.sleep(3)\r\n\r\n renew = driver.find_element_by_xpath('//*[@id=\"returnDelay\"]')\r\n click(renew)\r\n print(f'\"{book_title_list[i]}\" 대출 연장')\r\n\r\n close_button = driver.find_element_by_xpath('//*[@id=\"common_popup_1\"]/div/div/div[3]/button')\r\n click(close_button)\r\n\r\n time.sleep(3)\r\n\r\n except IndexError:\r\n break\r\n i += 1\r\n\r\n def print_receipt():\r\n\r\n i = 0\r\n while True:\r\n try:\r\n number_input = driver.find_element_by_id(\"main_number_txt\")\r\n number_input.clear()\r\n number_input.send_keys(unique_reserver_account_list[i])\r\n number_input.send_keys(Keys.ENTER)\r\n time.sleep(3)\r\n\r\n print_receipt = driver.find_element_by_id(\"receiptPrintBtn_main\")\r\n click(print_receipt)\r\n print(f'{reserver_name_list[i]}님의 현황 확인증 출력')\r\n time.sleep(1)\r\n\r\n\r\n except IndexError:\r\n break\r\n i += 1\r\n\r\n def click(x):\r\n driver.execute_script(\"arguments[0].click();\", x)\r\n time.sleep(0.5)\r\n\r\n def get_reservation_data(i):\r\n\r\n dictionary = {}\r\n dictionary[\"이름\"] = reserver_name_list[i]\r\n dictionary[\"회원 번호\"] = reserver_account_list[i]\r\n dictionary[\"도서 제목\"] = book_title_list[i]\r\n dictionary[\"도서 등록 번호\"] = book_regi_number_list[i]\r\n dictionary[\"도서 id\"] = book_id[i]\r\n\r\n return dictionary\r\n\r\n # Login\r\n driver = webdriver.Chrome(os.path.dirname(os.path.abspath(__file__)) + \"\\chromedriver.exe\")\r\n driver.implicitly_wait(3)\r\n driver.get(\"http://152.99.43.46:28180/METIS/\")\r\n driver.maximize_window()\r\n driver.find_element_by_name(\"main_login_user_id\").send_keys(self.alpas_id.text())\r\n driver.find_element_by_id(\"user_pw\").send_keys(self.alpas_pw.text())\r\n driver.find_element_by_xpath(\"/html/body/div[2]/div/button\").click()\r\n time.sleep(3)\r\n\r\n # Save Reserver Data\r\n reserver_name_list = []\r\n reserver_account_list = []\r\n unique_reserver_account_list = []\r\n book_title_list = []\r\n book_regi_number_list = []\r\n book_id = []\r\n\r\n # Close Pop up\r\n try:\r\n popup = driver.find_element_by_xpath('//*[@id=\"closeNoticePopup\"]')\r\n click(popup)\r\n driver.implicitly_wait(5)\r\n except:\r\n pass\r\n\r\n # Open Reservation tap\r\n navigation = driver.find_element_by_xpath('//*[@id=\"right_container_wrapper\"]/header/div[5]/nav/a')\r\n click(navigation)\r\n manage_reservation = driver.find_element_by_xpath('//*[@id=\"COLI_01_HTML\"]/li[6]')\r\n click(manage_reservation)\r\n driver.switch_to.window(driver.window_handles[1])\r\n driver.implicitly_wait(5)\r\n\r\n # Get Account Number\r\n send_reservation_date(self.reserve_from.text(), self.reserve_to.text()) # Enter reservation date\r\n search = driver.find_element_by_xpath('//*[@id=\"btn_search\"]') # Search\r\n click(search)\r\n time.sleep(1)\r\n\r\n # Collect Reserve Data\r\n get_reserver()\r\n\r\n # Open Check Out tap\r\n driver.find_element_by_xpath('//*[@id=\"right_container_wrapper\"]/header/div[5]/nav/a').click()\r\n driver.find_element_by_xpath('//*[@id=\"COLI_01_HTML\"]/li[2]').click()\r\n driver.switch_to.window(driver.window_handles[2])\r\n driver.implicitly_wait(3)\r\n\r\n # Show Only Local Library Data\r\n only_local = driver.find_element_by_id(\"is_only_local\")\r\n click(only_local)\r\n driver.implicitly_wait(3)\r\n\r\n # Set Unique Account List\r\n for v in reserver_account_list:\r\n if v not in unique_reserver_account_list:\r\n unique_reserver_account_list.append(v)\r\n\r\n # Get Registration Number, Cancel, and Check Out\r\n cancel_and_check_out()\r\n print_receipt()\r\n\r\n data = [get_reservation_data(i) for i in range(len(reserver_name_list))]\r\n print(data)\r\n\r\n\r\nif __name__ == \"__main__\":\r\n import sys\r\n app = QtWidgets.QApplication(sys.argv)\r\n Alpas = QtWidgets.QDialog()\r\n ui = Ui_Alpas()\r\n ui.setupUi(Alpas)\r\n Alpas.show()\r\n sys.exit(app.exec_())\r\n","repo_name":"marcwoo94/Crawlers","sub_path":"Alpas_Automatic_Check_Out.py","file_name":"Alpas_Automatic_Check_Out.py","file_ext":"py","file_size_in_byte":12852,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"7914861721","text":"# https://github.com/Morel-Mathieu/face-recognition-OpenCv\n\nimport cv2\nimport pickle\nimport numpy as np\n\ncolor_ok = (0,255,0)\ncolor_ko = (0,0,255)\ncolor_info = (255,255,255)\nname_image = 0\n\nface_cascade = cv2.CascadeClassifier(\"../../rsc/haarcascade_frontalface_alt2.xml\")\nif (face_cascade.empty()):\n print(\"Erreur de chargement du fichier ! :(\")\n quit()\n\nrecognizer = cv2.face.LBPHFaceRecognizer_create()\nrecognizer.read(\"trainner.yml\")\n\nwith open(\"labels.pickle\", \"rb\") as f:\n og_labels = pickle.load(f)\n # Vérifier le load\n labels = {v:k for k, v in og_labels.items()}\n\ncam = cv2.VideoCapture(0, cv2.CAP_DSHOW) # L'entrée vidéo de mon ordinateur portable (0, cv2.CAP_DSHOW)\n\nwhile True:\n if (cam.isOpened() == True):\n retcam, frame = cam.read() # Fonction qui retunr une valeur et l'image dans frame\n temps = cv2.getTickCount() # Ici on prend une mesure de temps pour calculer les fps\n\n gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) # Passage de l'image en gris pour faciliter détection\n\n # detectMultiScale renvoi 4 valeurs, x, y du rectangle contient l'objet\n # minNeighbors regarde si sur une couche voisine l'objet existe\n face = face_cascade.detectMultiScale(gray, scaleFactor=1.2, minNeighbors=4)\n for x,y,w,h in face:\n visage_film = gray[y:y+h, x:x+w] # On récupère que le visage gris de la webcam\n id, conf = recognizer.predict(visage_film)\n\n # Plus l'indice est bas plus le visge sera bon (généralement entre 80 et 100)\n if conf <= 80 :\n color = color_ok\n name = labels[id] # On va chercher dans le tableau formaté du fichier pickle\n\n else:\n color = color_ko\n name = \"Inconnu\"\n\n text = name + \" Indice confiance : \" + \"{:5.2f}\".format(conf)\n cv2.putText(frame, text, (x, y-10), cv2.FONT_HERSHEY_PLAIN, 1, color_info, 1, cv2.LINE_AA)\n\n # On dessine un rectangle : start, end, color, taille_trait\n cv2.rectangle(frame, (x,y), (x+w, y+h), color, 2)\n\n # Relache le flux vidéo et quit le programme\n if cv2.waitKey(1) == ord(\"q\"):\n cam.release()\n cv2.destroyAllWindows()\n print(\"Au revoir !\")\n quit()\n\n fps = cv2.getTickFrequency()/(cv2.getTickCount()-temps) # Calcul fps\n # Affichage : Image, text en float, pos, font, taille_trait, couleur, type, trait\n cv2.putText(frame, \"[FPS : {:05.2f}]\".format(fps), (10,30), cv2.FONT_HERSHEY_PLAIN, 1, color_info, 1)\n cv2.putText(frame, \"Quitter 'q'\", (10,10), cv2.FONT_HERSHEY_PLAIN, 1, color_info, 1)\n\n cv2.imshow('Face Detection', frame)\n\n else:\n print(\"Erreur à l'ouverture de la webcam ! :(\")\n","repo_name":"Morel-Mathieu/face-recognition-OpenCv","sub_path":"code/face-recognition/identification.py","file_name":"identification.py","file_ext":"py","file_size_in_byte":2830,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"74000518986","text":"'''\nalgorithmName: Convex polygon triangulation\nauthor: Xu Mengnan\ndate: 2019/10/17\ninput: point dict\noutput: Minimum triangulation of weights\n'''\nfrom math import sqrt\nclass Point():\n def __init__(self, xx, yy):\n self.x = xx\n self.y = yy\n\ndef getDis(pointA, pointB):\n return sqrt((pointA.x - pointB.x)**2 + (pointA.y - pointB.y)**2)\n\ndef weight(pointA, pointB, pointC):\n return getDis(pointB, pointC) + getDis(pointA, pointB) + getDis(pointA, pointC)\n\ndef minWeightTriangulation(p):\n n = len(p) - 1\n # 定义t[i][j]为凸子多边形vi,vi+1,...,vj的最优三角剖分的权函数值\n t = [[0]*(n+1) for i in range(n+1)]\n s = [[0]*(n+1) for i in range(n+1)]\n for i in range(1, n+1):\n t[i][i] = 0\n for r in range(2, n+1):\n for i in range(1, n-r+2):\n j = i + r - 1\n t[i][j] = t[i+1][j] + weight(p[i-1], p[i], p[j])\n s[i][j] = i\n k = i + 1\n while k < j:\n\n u = t[i][k] + t[k+1][j] + weight(p[i-1], p[k], p[j])\n if u < t[i][j]:\n t[i][j] = u\n s[i][j] = k\n k += 1\n return s, t\n\ndef traceback(s, i, j):\n if i == j :\n print(f'A{i}',end='')\n return\n print(\"(\", end='')\n traceback(s, i ,s[i][j])\n traceback(s, s[i][j]+1, j)\n print(f\")\",end='')\n\nif __name__ == '__main__':\n amount = int(input('请输入点的个数:'))\n p = []\n for i in range(amount):\n x, y = input(f\"请输入第{i+1}个点的坐标:\").strip().split(' ')\n print(x,y)\n tempPoint = Point(int(x), int(y))\n p.append(tempPoint)\n\n s, t= minWeightTriangulation(p)\n traceback(s,0,amount-1)","repo_name":"Edgeeeeee/xmn","sub_path":"algorithm/course/cpt.py","file_name":"cpt.py","file_ext":"py","file_size_in_byte":1713,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"11348415383","text":"\nimport tinysegmenter #segmentation api for japanese\nimport codecs #library to read input in utf-8\n\n\n\"\"\"\nTODO: \n1. specify output paths for annotater class \n2. debug regular expressions for ENG_Transcript\n3. Write unit tests \n\"\"\"\n\n\"\"\"\nBase Class for parsing subtitle (i.e. interface)\n\"\"\"\nclass Transcript:\n\n\tdef __init__(self, path, language, level):\n\t\t\n\t\t#input\n\t\tself.path = path\n\t\tself.language = language\n\t\tself.level = level\n\t\t\n\n\"\"\"\nDerived Classes (language specific)\n\"\"\"\n# Fields\n# @ string path: path of subtitle file to be annotated\n# @ string langauge: source \n# @ int level: level of user\n# @ file output: output file that annotated transcript is written to\n\n# Methods \n# @ Annotate() : calls process() function with corresponding parse function and output file.\n# @ parse_line(): parse function for target language\n\n\n\nclass ENG_Transcript(Transcript):\n\n\tdef __init__(self, path, language, level):\n\t\tTranscript.__init__(self, path, language, level) \n\t\tself.output = open(\"new_transcript.txt\",\"w\") #designate path\n\t\tself.Annotater = ENG_Annotater(self.level)\n\n\tdef annotate(self):\n\t\tprocess(self.path, self.parse_line, self.output)\n\n\n\tdef parse_line(self, line):\n\t\t\n\t\t#regex to break line into (time | content)\t \n\t\tmatch = re.search(r'([:\\.\\,\\w\\s]+,,0,0,0,,)([\\w\\s\\,\\.\\'()\\\\-]*)',line)\n\t\t\n\t\t#annotation step\n\t\tif match:\n\t\t\ttime = match.group(1)\n\t\t\tmessage = match.group(2).split()\n\n\t\t\t#annotate each unit (word) accordingly\n\t\t\tfor i in range(len(message)): \n\t\t\t\tmessage[i] = annotate_eng(message[i],d)\n\t\t\t\t\n\t\t\t#create new annotated_line\n\t\t\tannotated_message = \" \".join(message)\n\t\t\treturn time + annotated_message \n\n\n\n \nclass JPN_Transcript(Transcript):\n\n\tdef __init__(self, path, language, level):\n\t\tTranscript.__init__(self, path, language, level)\n\t\tself.output = open(\"new_transcript.txt\",\"w\") \n\t\tself.TS = tinysegmenter.TinySegmenter() #Japanese segmenter object\n\t\tself.Annotater = JPN_Annotater(self.level)\n\n\tdef annotate(self):\n\t\tprocess(self.path, self.parse_line, self.output)\n\n\tdef parse_line(self):\n\n\t\t#regex to break line into (time | content)\t \n\t\tmatch = re.search(r'([:\\.\\,\\w\\s]+,,0,0,0,,)([\\w\\W]*)', line, re.UNICODE)\n\t\t\n\t\t#annotation step\n\t\tif match:\n\t\t\ttime = match.group(1)\n\t\t\tmessage = TS.tokenize( match.group(2).decode(\"UTF-8\") )\n\n\t\t\t#annotate each unit (segmented phrase) accordingly\n\t\t\tfor i in range(len(message)):\n\t\t\t\tmessage[i] = annotate_jpn(message[i],d)\n\n\t\t\t#create new annotated_line\n\t\t\tannotated_message = \"\".join(m)\n\t\t\treturn time + annotated_message \n\n\n\n\"\"\"\nProcessing functions\n\"\"\"\t\n\n# Process()\n# @param String path: path of original subtitle file\n# @param function parse: parse function that takes in a line of dialogue and highlights accordingly\n# @param file output: output file for annotated subtitle file \n# Description: opens a file and processes it according to a parse function to render an annotated subtitle file.\n\ndef process(path, parse, output):\n\t\n\tf = open(path,\"r\")\n\t\n\tfor line in subtitle_file:\n\t\t#case 1 = empty line \n\t\tif line.split() == []: \n\t\t\toutput.write(\"\\n\")\n\n\t\t#case 2 = irrelevant line (no content)\n\t\telif line.split()[0] != \"Dialogue:\": \n\t\t\toutput.write(line)\n\n\t\t#case 3 = relevant line with content\n\t\telse:\n\t\t\tannotated = parse(line, freq_list)\n\t\t\tannotated_utf = annotated.encode(\"UTF-8\") #encode string in UTF to display correctly\n\t\t\toutput.write(annotated_utf+\"\\n\")\n\n\tf.close()\n\toutput.close()\n\t\n\treturn\n","repo_name":"andylee024/AI_Subs","sub_path":"src/package1/transcript.py","file_name":"transcript.py","file_ext":"py","file_size_in_byte":3381,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"75136423945","text":"class Solution:\n def divisorSubstrings(self, num: int, k: int) -> int:\n ans=0\n s=str(num)\n subs=[s[i:i+k] for i in range(len(s)-k+1)]\n for sub in subs:\n if int(sub)!=0 and num%int(sub)==0:\n ans+=1\n return ans\n ","repo_name":"bamblebam/competitive-programming","sub_path":"2022/5_May_22/13-5-22/findthekbeautyofanumber.py","file_name":"findthekbeautyofanumber.py","file_ext":"py","file_size_in_byte":285,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"41350789775","text":"import logging\nimport warnings\nfrom gensim.models import word2vec\n\nwarnings.filterwarnings(action='ignore', category=UserWarning, module='gensim')\nlogging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)\n\ndef initModel():\n \"\"\"\n Cette fonction permet d'initialiser le modèle text8 et de persister le modèle sur le disque dans un fichier .bin\n \n :return: Retourne le modèle de données text8\n \"\"\"\n sentences = word2vec.Text8Corpus(\"../DATA/text8\")\n model = word2vec.Word2Vec(sentences, size=200)\n model.save('../MODEL//W2V_text8_Model.bin')\n return model\n\n#initModel()\n","repo_name":"ARMIAGE/PPDM2","sub_path":"src/text8.py","file_name":"text8.py","file_ext":"py","file_size_in_byte":632,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"9537278817","text":"from base64 import decode\nfrom distutils.log import error\nfrom typing import Optional\nfrom fastapi import FastAPI, Depends, HTTPException, File, UploadFile\nfrom fastapi.security import HTTPBasic, HTTPBasicCredentials\nfrom bsbi import BSBIIndex\nfrom compression import VBEPostings\nfrom letor import Letor\nimport os\nimport json\nfrom fastapi.middleware.cors import CORSMiddleware\n\nsecurity = HTTPBasic()\napp = FastAPI()\n\napp.add_middleware(\n CORSMiddleware,\n allow_origins=['*'],\n allow_credentials=True,\n allow_methods=['*'],\n allow_headers=['*'],\n )\n\nBSBI_instance = BSBIIndex(data_dir = 'collection', \\\n postings_encoding = VBEPostings, \\\n output_dir = 'index')\n\nBSBI_instance.load()\ntfidf = Letor()\n\nres = {\"success\" : None,\"error\" : None,\"data\" : []}\n\n@app.get('/search')\nasync def search (query : str) :\n data_fin = {}\n docs = []\n for (score, doc) in BSBI_instance.retrieve_tfidf(query, k = 100):\n with open(os.path.join(os.getcwd(),doc.replace(\"\\\\\",\"/\"))) as file :\n data = file.read().replace('\\n',\" \")\n docs.append((doc,data))\n\n list_a = tfidf.calc(query, docs)\n res[\"data\"] = [] \n for doc in list_a:\n with open(os.path.join(os.getcwd(),doc.replace(\"\\\\\",\"/\")), \"r\") as read:\n res[\"data\"].append({\"doc\": doc.replace(\"\\\\\",\"/\"), \"content\" : read.read().replace(\"\\n\",\" \")})\n res[\"success\"]=True,\n return res\n\n@app.get('/a')\ndef test():\n return \"test\"\n\n","repo_name":"Pinatnat/TP3-IR","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1520,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"13220542401","text":"\"\"\"\nnaam: Gerrit van Os\nklas: TI-V2C\nstudent_nr: 1719977\ndocent: Frits Dannenberg\n\"\"\"\nimport random\n#opgave 1\n\"\"\"\nfunction to calculate max of a list\n\nParameters\n-------------\na: list\n list needs to be longer than 0 and consist of ints or floats\n if len(a) == 0 or a[i] != int/float an error will occur\n\nReturn\n------------\nmax: int\n the maximum of the list a\n\"\"\"\n\ndef my_max(a):\n max = 0\n assert len(a), \"list is 0\"\n for i in range(len(a)):\n assert isinstance(a[i], (int, float)), str(a[i]) + \" at possiton \" + str(i) + \" is not an integer or float\"\n if (max ='0' and s[i] <='9'):\n temp += s[i]\n elif(temp != \"\"):\n output_list.append(int(temp))\n temp = \"\"\n if(temp !=\"\"):\n output_list.append(int(temp))\n return output_list\n\n\"\"\"\nfunction to test the getNumbers funtion\n\"\"\"\ndef test_getNumber():\n a = 'een123zin45 6met-632meerdere+7777getallen'\n b = 'een123zin45 6met-632meerdere+7777getallen12'\n print(\"this is the result form get_numbers: \",getNumbers(a))\n print(\"test case with int on the back of string on bases of feedback\",getNumbers(b))\n\n\n#opdracht 3:\n\"\"\"\nfunction to get all prime numbers from a given list\n\nParameters\n-------------\ninput_list : list\n list with sorted interges from 2-xxx from which the primes need to be found\n\nReturn\n------------\n list\n a list of all the primes in the range of the input_list\n\"\"\"\ndef get_prime(input_list):\n non_prime_set = set()\n\n for counter in range(2,my_max(input_list)+1):\n if (counter in non_prime_set):\n continue\n for i in range(counter*2,my_max(input_list)+1,counter):\n non_prime_set.add(i)\n\n return list(sorted(set(input_list)-non_prime_set))\n\n\n\"\"\"\nfunction to test the get_prime funtion\n\"\"\"\ndef test_get_prime():\n my_list = list(range(2,1000))\n print(\"primes from 2-1000\", get_prime(my_list))\n my_list1 = list(range(2,100))\n print(\"primes from 2-100: \", get_prime(my_list1))\n\n\n#opdracht 4:\n\"\"\"\nfunction to create a list of lists whith random numbers between 1 and 365\n\nParameters\n-------------\nitems : int\n the number of items in each list\nno_of_lists : int\n the amount of lists that need to be made\n\nReturn\n------------\n list : list\n a list of lists with the number of items specified and repeated no_of_lists times\n\"\"\"\ndef create_random_lists(items,no_of_lists):\n base_list =[]\n for i in range(no_of_lists):\n inside_list =[]\n for item in range(items):\n inside_list.append(random.randint(1,365))\n inside_list.sort()\n base_list.append(inside_list)\n return base_list\n\n\"\"\"\nfunction to check how often a list contains the same number\n\nParameters\n-------------\nlist_of_lists : list\n a list of lists with integers\n\nReturn\n------------\n counter : int\n the number of lists that contains the same integer\n\"\"\"\ndef check_lists(list_of_lists):\n counter =0\n for i in range(len(list_of_lists)-1):\n for j in range(len(list_of_lists[i])):\n check = len(list_of_lists[i])-1\n if (j < check):\n if (list_of_lists[i][j] == list_of_lists[i][j+1]):\n counter += 1\n break\n return counter\n\n\"\"\"\nfunction to test the check_lists funtion\n\"\"\"\ndef test_lists():\n random_list = create_random_lists(23, 100)\n print(\"the amount of the same numbers in the random list is: \",check_lists(random_list))\n\ntest_my_max()\ntest_getNumber()\ntest_get_prime()\ntest_lists()","repo_name":"gerritvanos/ALDS","sub_path":"week 1/all_exec.py","file_name":"all_exec.py","file_ext":"py","file_size_in_byte":4779,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"9665624014","text":"#!/usr/bin/python\nimport sys # use system library\nlevel = []\n\nfor line in sys.stdin:\n line0 = line.strip()\n if (len(line0)):\n data = line0.rsplit(' ',1)\n level.append(int((data[-1])))\n \nprint (level)\n","repo_name":"IchiroYoshida/python_public","sub_path":"astro/tide/python/dat.py","file_name":"dat.py","file_ext":"py","file_size_in_byte":225,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"81"} +{"seq_id":"15975530115","text":"#!/usr/bin/env python3\nimport asyncio\nimport bs4\nimport math\nimport sys\nimport os\nimport requests\n\nfrom asyncio import TimeoutError\nfrom aiohttp import ClientSession\nfrom aiohttp.client_exceptions import ContentTypeError, ServerDisconnectedError\nfrom bs4 import BeautifulSoup\n\n\nROOT_URL = 'http://mjl.clarivate.com'\n\nDEFAULT_DIR_HTML = 'data/wos/html/'\n\nDEFAULT_MAX_ATTEMPTS = 5\nDEFAULT_MODE = 'collect'\nDEFAULT_SEMAPHORE_LIMIT = 5\n\n\ndef parse_html(path_html_file: str):\n \"\"\"\n Open, reads and converts a html file (the main parts) to a tab-separated string.\n :param path_html_file: path of the html file.\n :return: a list of tab-separated string representations of the journals described in the html file.\n \"\"\"\n page_id = path_html_file.split('.')[0]\n html = open(DEFAULT_DIR_HTML + path_html_file).read()\n soupped_html = BeautifulSoup(html, 'html.parser')\n\n # page's name\n page_name = soupped_html.find('p').text.strip().split('\\n')[0]\n\n # journal's name\n journals_names = [dt.text.strip().split('.')[-1].strip().replace('\\t', '') for dt in soupped_html.find_all('dt')]\n\n # periodicity, issn and e-issn\n journals_time_and_issns = []\n for dt in soupped_html.find_all('dt'):\n new_jii = ''\n for jii in dt.next_siblings:\n if isinstance(jii, bs4.element.Tag):\n if jii.name == 'dd':\n break\n else:\n new_jii = new_jii + '\\t' + jii.strip()\n journals_time_and_issns.append(new_jii)\n\n normalized_journals_time_and_issns = []\n for jti in journals_time_and_issns:\n tmp_jti = jti.split('\\t')\n while len(tmp_jti) != 5:\n tmp_jti.append('')\n normalized_journals_time_and_issns.append('\\t'.join(tmp_jti))\n\n # other journal's attributes\n journals_other_attrs = [dd.text.strip().replace('\\n', '\\t') for dd in soupped_html.find_all('dd')]\n\n tsv_list = []\n for i, j in enumerate(journals_names):\n tsv_j = '\\t'.join([page_id, page_name, j.replace('\\t', ''), normalized_journals_time_and_issns[i], journals_other_attrs[i], '\\n'])\n tsv_list.append(tsv_j)\n return tsv_list\n\n\ndef save_tsv_file(journals_tsv: list):\n \"\"\"\n Save a list of tsvs into a tsv file\n :param journals_tsv a list of tsvs where each tsv is a tab-separeted string representation of a journal\n \"\"\"\n result_file = open('wos.tsv', 'w')\n result_file.writelines(journals_tsv)\n result_file.close()\n\n\ndef get_url_indexes():\n response = requests.get(ROOT_URL)\n soup = BeautifulSoup(response.text, 'lxml')\n links = soup.find_all('a')\n return [ROOT_URL + l.get('href').replace('options', 'results') + '&mode=print' for l in links if '/cgi-bin/jrnlst/' in l.get('href')]\n\n\ndef save_into_html_file(path_html_file: str, response):\n \"\"\"\n Receives a response (in text format).\n Saves the document into a html file.\n \"\"\"\n html_file = open(path_html_file, 'w')\n html_file.writelines(response)\n html_file.close()\n\n\nasync def fetch(paged_url, session):\n \"\"\"\n Fetchs the url.\n Calls the method save_into_html_file with the response as a parameter (in text format).\n \"\"\"\n async with session.get(paged_url) as response:\n try:\n for attempt in range(DEFAULT_MAX_ATTEMPTS):\n if response.status == 200:\n response = await response.text(errors='ignore')\n path_html_file = paged_url.split('&')[0].split('?')[-1].lower().replace('=', '_') + '_' + paged_url.split('&')[-1].replace('=', '_').lower()\n save_into_html_file(DEFAULT_DIR_HTML + path_html_file + '.html', response)\n break\n elif response.status == 500 and attempt == DEFAULT_MAX_ATTEMPTS:\n print('ResponseError', response.status, paged_url)\n except ServerDisconnectedError:\n print('ServerDisconnectedError', paged_url)\n except TimeoutError:\n print('TimeoutError', paged_url)\n except ContentTypeError:\n print('ContentTypeError', paged_url)\n\n\nasync def bound_fetch(sem, paged_url, session):\n \"\"\"\n Limits the collecting task to a semaphore.\n \"\"\"\n async with sem:\n await fetch(paged_url, session)\n\n\nasync def run():\n \"\"\"\n Creates tasks to get the html file with respect to a list composed by htmls.\n \"\"\"\n sem = asyncio.Semaphore(DEFAULT_SEMAPHORE_LIMIT)\n tasks = []\n\n async with ClientSession() as session:\n\n urls = get_url_indexes()\n\n for u in urls:\n tmp_index = requests.get(u)\n soup = BeautifulSoup(tmp_index.text, 'html.parser')\n allp = soup.find_all('p')[0].contents\n for a in allp:\n if 'Total journal' in a:\n num_pages = math.ceil(int(a.strip().split(': ')[-1]) / 500)\n\n for page in range(1, num_pages + 1):\n paged_url = u + '&Page=' + str(page)\n task = asyncio.ensure_future(bound_fetch(sem, paged_url, session))\n tasks.append(task)\n responses = asyncio.gather(*tasks)\n await responses\n\n\nif __name__ == \"__main__\":\n DEFAULT_MODE = sys.argv[1]\n PATH_TO_BE_PARSED = sys.argv[2]\n\n if len(sys.argv) != 3:\n print('Error: enter execution mode')\n print('Error: enter path to be parsed')\n sys.exit(1)\n\n if DEFAULT_MODE == 'collect':\n os.makedirs(DEFAULT_DIR_HTML)\n\n loop = asyncio.get_event_loop()\n future = asyncio.ensure_future(run())\n loop.run_until_complete(future)\n elif DEFAULT_MODE == 'parse':\n DEFAULT_DIR_HTML = PATH_TO_BE_PARSED\n htmls = sorted([h for h in os.listdir(PATH_TO_BE_PARSED)])\n\n journals_tsv = []\n for i, h in enumerate(htmls):\n print('parsing %d of %d' % (i + 1, len(htmls)))\n journals_tsv.extend(parse_html(h))\n\n print('saving file on disk')\n save_tsv_file(journals_tsv)\n","repo_name":"scieloorg/cited-references","sub_path":"core/scrappers/wos.py","file_name":"wos.py","file_ext":"py","file_size_in_byte":5959,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"81"} +{"seq_id":"20061527130","text":"import random\r\nsmaller = int(input(\"Enter the smaller number: \"))\r\nlarger = int(input(\"Enter the larger number: \"))\r\ncount = 0\r\nuserFeedback = \"\"\r\nwhile userFeedback != \"c\":\r\n\tcount += 1\r\n\tcomputerNumber = random.randint(smaller, larger)\r\n\tuserFeedback = input(f\"{computerNumber}, Is my guess too high (H), too low (L), or correct (C)?\").lower()\r\n\tif userFeedback == \"h\":\r\n\t\tlarger = computerNumber - 1\r\n\telif userFeedback == \"l\":\r\n\t\tsmaller = computerNumber + 1\r\nprint(\"Congradulations! You've got it in\", count,\r\n\t\t\t\"tries!\")\r\n","repo_name":"cgomezjr/week5","sub_path":"Project3-Gomez.py","file_name":"Project3-Gomez.py","file_ext":"py","file_size_in_byte":529,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"17901314735","text":"import argparse as ap\nimport sys\nfrom operator import itemgetter\n\nfrom tqdm import tqdm\n\nfrom kitsune.modules import kitsunejf as jf\n\n\ndef read_params(args):\n \"\"\"\n Read and test input arguments\n\n :return: The ArgumentParser object\n \"\"\"\n\n p = ap.ArgumentParser(\n prog=\"kitsune (acf)\",\n description=(\n \"Calculate an average number of common feature pairwise between one genome against others\"\n ),\n formatter_class=ap.ArgumentDefaultsHelpFormatter,\n )\n p.add_argument(\"--filenames\", nargs=\"+\", type=str, required=True, help=\"Genome files in fasta format\"),\n p.add_argument(\"--fast\", action=\"store_true\", help=\"Jellyfish one-pass calculation (faster)\")\n p.add_argument(\"--canonical\", action=\"store_true\", help=\"Jellyfish count only canonical mer\")\n p.add_argument(\"-k\", \"--kmers\", nargs=\"+\", required=True, type=int, help=\"Have to state before\")\n p.add_argument(\"-t\", \"--thread\", type=int, default=1)\n p.add_argument(\"-o\", \"--output\", type=str, help=\"Output filename\")\n return p.parse_args(args)\n\n\ndef cal_acf(fsas, kmers, **karg):\n \"\"\"Calculate Average number of common features (ACF)\n\n Args:\n fsas (str): genome file name(s).\n kmers (): a list of kmer to calculate.\n\n Kwargs:\n state (bool): Current state to be in.\n thread (int): Number of thread to calculate default 1\n lower (int): default 1\n bchashsize (str): hashsize for jellyfish bc step default '1G'\n hashsize (str): hashsize for jellyfish count step default '100M'\n canonical (bool): set canonical calculation\n\n Returns:\n dict(kmer: acf)\n\n Raises:\n AttributeError, KeyError\n\n A really great idea. A way you might use me is\n\n >>> print public_fn_with_googley_docstring(name='foo', state=None)\n 0\n\n BTW, this always returns 0. **NEVER** use with :class:`MyPublicClass`.\n\n \"\"\"\n \n n = len(fsas)\n \n if n >= 2:\n result = dict()\n \n for kmer in tqdm(kmers):\n keys_array = list()\n \n for fsa in fsas:\n keys_array.append(set(jf.Kmercount(fsa, kmer, **karg).keys()))\n \n ccf = 0\n \n for pri_idx, key in enumerate(keys_array):\n for sec_idx in range(pri_idx + 1, n):\n ccf += len(keys_array[pri_idx] & keys_array[sec_idx])\n \n result[kmer] = ccf/(n-1)\n \n return result\n \n else:\n raise\n\n\ndef run(args):\n \"\"\"\n Calculate an average number of common feature pairwise\n between one genome against others\n \"\"\"\n\n # Load command line parameters\n args = read_params(args)\n\n outdata = cal_acf(args.filenames, **vars(args))\n outdata = sorted(outdata.items(), key=itemgetter(0))\n outdata = '\\n'.join(['\\t'.join([str(x) for x in data]) for data in outdata])\n\n print(outdata, file=open(args.output, \"w+\") if args.output else None)\n\n\nif __name__ == \"__main__\":\n run(sys.argv)\n","repo_name":"natapol/kitsune","sub_path":"kitsune/modules/acf.py","file_name":"acf.py","file_ext":"py","file_size_in_byte":3023,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"81"} +{"seq_id":"75136291785","text":"\nclass ListNode:\n def __init__(self, val=0, next=None):\n self.val = val\n self.next = next\n\n\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 sortedListToBST(self, head: ListNode) -> TreeNode:\n def length(node):\n count = 0\n current = node\n if current is None:\n return 0\n while current is not None:\n count += 1\n current = current.next\n return count\n\n def solve(node):\n n = length(node)\n if n == 0:\n return None\n if n == 1:\n return TreeNode(node.val)\n previous = None\n middle = node\n for _ in range(n//2):\n previous = middle\n middle = middle.next\n if previous is not None:\n previous.next = None\n nxt = middle.next\n middle.next = None\n root = TreeNode(middle.val)\n root.left = solve(node)\n root.right = solve(nxt)\n return root\n return solve(head)\n","repo_name":"bamblebam/competitive-programming","sub_path":"2021/5_May_21/6-5-21/listtotree.py","file_name":"listtotree.py","file_ext":"py","file_size_in_byte":1221,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"12024977458","text":"\"\"\"\nCreate a dictionary letters with keys consisting of the numbers from 0 to 26,\nand values consisting of the lowercase letters of the English alphabet,\nincluding the space ' ' at the end.\n\"\"\"\n\nimport string\n\nstring.ascii_lowercase\n\nalphabet = string.ascii_lowercase + \" \"\n\nletters = {}\ni = 0\nfor letter in alphabet:\n letters[i] = letter\n i += 1\n\nprint(letters)\n","repo_name":"albihasani94/PH526x","sub_path":"week3/Homework1/Exercise_1.py","file_name":"Exercise_1.py","file_ext":"py","file_size_in_byte":369,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"10646581105","text":"import pandas as pd\nimport numpy as np\nimport matplotlib.pylab as plt\n#matplotlib inline\nfrom scipy.io import arff\nfrom matplotlib.pylab import rcParams\nfrom pandas import read_csv\nfrom pandas import DataFrame\nfrom pandas import concat\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.metrics import mean_squared_error, r2_score\nfrom sklearn.model_selection import GridSearchCV\nfrom sklearn.kernel_ridge import KernelRidge\nfrom sklearn.svm import SVR,NuSVR\nimport scipy\nfrom sklearn.preprocessing import StandardScaler\nfrom math import sqrt\n\n#input data\ndata = arff.loadarff('input-data.arff')\nseries = pd.DataFrame(data[0])\n\ntemps=pd.DataFrame(series['hits'])\n\n#Test data\ndata_test = arff.loadarff('test-data.arff')\nseries_test = pd.DataFrame(data_test[0])\ny_test=pd.DataFrame(series_test['hits'])\n\ntemps=temps.append(y_test,ignore_index = True)\n\n\ndataframe=concat([temps.shift(24),temps.shift(23),temps.shift(22),temps.shift(21),temps.shift(20),temps.shift(19),temps.shift(18),temps.shift(17),temps.shift(16),temps.shift(15),temps.shift(14),temps.shift(13),temps.shift(12),temps.shift(11),temps.shift(10),temps.shift(9),temps.shift(8),temps.shift(7),temps.shift(6),temps.shift(5),temps.shift(4),temps.shift(3),temps.shift(2),temps.shift(1)], axis=1)\ndataframe.columns = ['me', 'mx', 't+1','h','g','hth','w','e','r','t','y','i','o','p','a','s','d','m','g','ss','ww','qww','rt','out']\n\n\ndf=DataFrame()\ndf=dataframe[24:672]\nx_test=DataFrame()\nx_test=dataframe[672:]\nx_train=DataFrame()\nx_train=df\ny_train=DataFrame()\ny_train=pd.DataFrame(temps[24:672])\n\nx_t=x_train.values\ny_t=y_train.values\n\n\nfrom sklearn.preprocessing import MinMaxScaler\nscaler = MinMaxScaler(feature_range =(0, 1)) \nscaler = scaler.fit(x_t)\nx_train=scaler.transform(x_t)\nx_train=pd.DataFrame(x_train)\n\nx_te=x_test.values\nscaler1 = MinMaxScaler(feature_range =(0, 1)) \nscaler1 = scaler1.fit(x_te)\nx_test=scaler1.transform(x_te)\nx_test=pd.DataFrame(x_test)\n\n\nscalery = MinMaxScaler(feature_range =(0, 1)) \nscalery = scalery.fit(y_t)\ny_train=scalery.transform(y_t)\ny_train=pd.DataFrame(y_train)\nprint(y_train)\n\nmodel = SVR(kernel='rbf',gamma=0.002,C=10,epsilon=.027)\nmodel.fit(x_train, y_train)\nyt=pd.DataFrame(model.predict(x_test))\n\n\n\n\n\nscalery1=MinMaxScaler(feature_range =(0, 1)) \nscalery1 = scalery1.fit(y_test)\ny=scalery1.inverse_transform(yt)\ny=pd.DataFrame(y)\ny.columns=['hits']\n\n\ntimestamp=[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23]\ntime=pd.DataFrame(timestamp)\ntime.columns=['time']\n\n\n\n\n# model evaluation\n\n\nfig, ax1 = plt.subplots()\ncolor = 'tab:red'\n#svr\ny1_container = [45, 40, 38, 37, 41, 43, 43, 50, 53, 61, 66, 70, 69, 70, 70, 69, 67, 63, 56, 53, 50, 49, 46, 42]\ncolor1 = 'tab:red'\n\n#krr\ny2_container = [46, 40, 38, 37, 40, 43, 43, 50, 52, 60, 65, 69, 68, 69, 69, 68, 66, 63, 57, 54, 51, 49, 46, 42]\ncolor2 = 'tab:brown'\n#lr\ny3_container = [45, 40, 37, 36, 42, 44, 43, 50, 52, 63, 67, 72, 69, 71, 71, 70, 67, 63, 54, 53, 50, 50, 47, 42]\ncolor3 = 'tab:green'\n#arima\ny4_container = [59, 49, 45, 44, 44, 45, 47, 48, 49, 51, 52, 52, 53, 53, 55, 57, 54, 55, 57, 58, 59, 58, 55, 54]\ncolor4 = 'tab:purple'\n#ar\ny5_container = [37, 36, 36, 38, 41, 43, 46, 49, 54, 57, 60, 60, 60, 61, 62, 62, 62, 61, 58, 55, 52, 50, 48, 45]\ncolor5 = 'tab:pink'\n#ma\ny6_container = [44, 37, 34, 35, 44, 50, 51, 48, 54, 58, 70, 73, 74, 70, 69, 68, 66, 60, 56, 53, 53, 56, 55, 51]\ncolor6 = 'tab:orange'\nax1.set_xlabel('time (s)')\nax1.set_ylabel('No. of replicas', color=color)\nax1.plot(time['time'], y1_container, color=color1,label='SVR')\nax1.plot(time['time'], y2_container, color=color2,label='KRR')\nax1.plot(time['time'], y3_container, color=color3,label='LR')\nax1.plot(time['time'], y5_container, color=color5,label='AR')\nax1.plot(time['time'], y4_container, color=color4,label='ARIMA')\nax1.plot(time['time'], y6_container, color=color6,label='MA')\nax1.tick_params(axis='y', labelcolor=color)\nax1.legend()\nax2 = ax1.twinx() # instantiate a second axes that shares the same x-axis\n\ncolor = 'tab:blue'\nax2.set_ylabel('Requests per seconds ', color=color) # we already handled the x-label with ax1\nax2.plot(time['time'], y, color=color,label='RPS')\nax2.tick_params(axis='y', labelcolor=color)\nax2.legend(loc='upper left')\nfig.tight_layout() # otherwise the right y-label is slightly clipped\nplt.show()\n\n\nr2 = r2_score(y_test, y)\nprint(r2)\n\nfrom sklearn.metrics import mean_absolute_error\n\n\nmae=mean_absolute_error(y_test,y)\nmse = mean_squared_error(y_test, y)\nrmse = np.sqrt(mse)\nprint(mae)\nprint(rmse)\n\n","repo_name":"rohitkishore12/Maintaining-Container-Sustainability-through-Machine-Learning","sub_path":"graph_script.py","file_name":"graph_script.py","file_ext":"py","file_size_in_byte":4497,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"38660418562","text":"import tkinter\r\nfrom tkinter import *\r\n\r\n\r\nclass BakeryView:\r\n def __init__(self, window):\r\n self.__init_window(window)\r\n\r\n def __init_window(self, window):\r\n window.title(\"빵집\")\r\n window.geometry('400x200')\r\n label = Label(window, text='주문내역')\r\n label.pack()\r\n self.orderText = Text(window)\r\n self.orderText.pack()\r\n\r\n def add_order(self, orders):\r\n self.orderText.insert(0.0, orders + \"\\n\")\r\n\r\n\r\nclass CustomerView:\r\n def __init__(self, name, window, bakery_view):\r\n self.name = name\r\n self.__init_window(window)\r\n self.bakeryView = bakery_view\r\n\r\n def __init_window(self, window):\r\n window.title(\"고객: \" + self.name)\r\n window.geometry('350x200')\r\n label_s = Label(window, text = \"샌드위치 (5000원)\")\r\n label_s.grid(column = 0, row = 0)\r\n label_c = Label(window, text= \"케이크 (20000원)\")\r\n label_c.grid(column = 0, row = 1)\r\n self.num_s = Entry(window, width = 10)\r\n self.num_c = Entry(window, width = 10)\r\n self.num_s.grid(column = 1, row = 0)\r\n self.num_c.grid(column=1, row=1)\r\n button = Button(window, text= \"주문하기\", command = self.send_order)\r\n button.grid(column = 0, row = 2)\r\n\r\n def send_order(self): #수정\r\n try:\r\n S = int(self.num_s.get())\r\n C = int(self.num_c.get())\r\n if S>0 and C>0:\r\n order_text = str(self.name)+\": 샌드위치 (5000원) \"+ str(S) +\"개, 케이크 (20000원) \"+ str(C) +\"개\"\r\n self.bakeryView.add_order(order_text)\r\n elif S>0 and C<=0:\r\n order_text = str(self.name) + \": 샌드위치 (5000원) \" + str(S) + \"개\"\r\n self.bakeryView.add_order(order_text)\r\n elif S<=0 and C>0:\r\n order_text = str(self.name) + \": 케이크 (20000원) \" + str(C) + \"개\"\r\n self.bakeryView.add_order(order_text)\r\n else:\r\n ValueError\r\n except ValueError:\r\n try:\r\n S = int(self.num_s.get())\r\n if S>0:\r\n order_text = str(self.name)+\": 샌드위치 (5000원) \"+ str(S) +\"개\"\r\n self.bakeryView.add_order(order_text)\r\n else:\r\n ValueError\r\n except ValueError:\r\n try:\r\n C = int(self.num_c.get())\r\n if C>0:\r\n order_text = str(self.name) + \": 케이크 (20000원) \" + str(C) + \"개\"\r\n self.bakeryView.add_order(order_text)\r\n else:\r\n ValueError\r\n except ValueError:\r\n pass\r\n\r\nif __name__ == '__main__':\r\n app = Tk()\r\n bakery = BakeryView(app)\r\n CustomerView('고객A', Toplevel(app), bakery)\r\n CustomerView('고객B', Toplevel(app), bakery)\r\n app.mainloop()\r\n","repo_name":"GyeongSeop/Bakery-UI","sub_path":"bakery_ui.py","file_name":"bakery_ui.py","file_ext":"py","file_size_in_byte":2972,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"70252358344","text":"import cv2\n\n# Load the image\nimage = cv2.imread('example_image.jpg')\n\n# Resize the image while maintaining the aspect ratio\nwidth = 600\nheight = int(image.shape[0] * width / image.shape[1])\nimage = cv2.resize(image, (width, height))\n\n# Display the resized image\ncv2.imshow('Resized Image', image)\ncv2.waitKey(0)\ncv2.destroyAllWindows()\n","repo_name":"newtutorials/sbyai","sub_path":"python/2023/10/Efficient_Background_Removal_in_Python_using_OpenCV/example3.py","file_name":"example3.py","file_ext":"py","file_size_in_byte":336,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"24029204591","text":"'''Store and update in game settings'''\n\nimport json\nimport pathlib\npath = pathlib.Path(__file__).parent.absolute()\n\nfrom match_sim.cl.utils import is_int\n\nclass Settings():\n '''Create object to store game settings populated with defaults'''\n def __init__(self):\n self.defaults_file = '{0}/../data/settings/defaults.json'.format(path)\n self.defaults_file_test = '{0}/../data/settings/defaults_test.json'.format(path)\n with open(self.defaults_file, 'r') as f:\n self.defaults = json.load(f)\n self.autosave = self.defaults['autosave']\n self.match_speed = self.defaults['match_speed']\n self.verbosity = self.defaults['verbosity']\n\n def update_setting(self, setting, value):\n '''Update class attribute with user input'''\n if setting == 'autosave':\n self.autosave = value\n if setting == 'match_speed':\n self.match_speed = value\n\n def get_settings(self):\n '''Ask user for input and check validity'''\n print(\n 'settings',\n 'autosave: %r' % self.autosave,\n 'match_speed: %d' % self.match_speed,\n sep='\\n'\n )\n setting = input()\n if ':' in setting:\n setting0 = setting.split(':')[0]\n setting1 = setting.split(':')[1].strip()\n if setting == 'autosave: False':\n self.update_setting('autosave', False)\n elif setting == 'autosave: True':\n self.update_setting('autosave', True)\n elif setting0 == 'match_speed':\n if is_int(setting1):\n if 0 < int(setting1) <= 70:\n self.update_setting('match_speed', int(setting1))\n\ndef test_settings():\n '''Test case for local use'''\n test_s = Settings()\n test_s.update_setting('autosave', False)\n\nif __name__ == \"__main__\":\n test_settings()\n","repo_name":"ckear1989/match_sim","sub_path":"match_sim/cl/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":1709,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"21668092150","text":"from pynput.keyboard import Key, Controller\r\nimport time\r\n\r\nkeyboard = Controller()\r\n\r\ndef typeName():\r\n\ttime.sleep(5)\r\n\tfor char in \"your krunker username\": \r\n\r\n\t\tkeyboard.press(char)\r\n\t\tkeyboard.release(char)\r\n\t\ttime.sleep(0.5)\r\n","repo_name":"sander-dander/-Automate-Free-Kr-With-Python","sub_path":"krunkerPython/typeUserName.py","file_name":"typeUserName.py","file_ext":"py","file_size_in_byte":231,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"7629310154","text":"\nimport threading\nimport better_exchook\nimport logging\nimport sys\n\n\nclass _WrapSqliteConnect:\n \"\"\"\n Use this to debug where SQL connections are created.\n E.g. to trace errors like:\n\n attempt to write a readonly database\n SQLite objects created in a thread can only be used in that same thread\n\n \"\"\"\n\n def __init__(self):\n self.lock = threading.Lock()\n import sqlite3\n self.orig_func = sqlite3.connect\n sqlite3.connect = self\n\n def __call__(self, *args, **kwargs):\n res = self.orig_func(*args, **kwargs)\n with self.lock:\n print(\"sqlite connect, thread %r, res %r\" % (threading.current_thread(), res))\n # better_exchook.print_tb(None)\n return res\n\n\nwrap_sqlite_connect = _WrapSqliteConnect()\n\n# IPython HistoryManager uses this logger for Sqlite info.\nlogging.getLogger(\"traitlets\").addHandler(logging.StreamHandler(sys.stdout))\n","repo_name":"albertz/background-zmq-ipython","sub_path":"sqlite_debugging.py","file_name":"sqlite_debugging.py","file_ext":"py","file_size_in_byte":934,"program_lang":"python","lang":"en","doc_type":"code","stars":16,"dataset":"github-code","pt":"81"} +{"seq_id":"26423613938","text":"# BEGIN GPL LICENSE BLOCK #####\r\n#\r\n# This program is free software; you can redistribute it and/or\r\n# modify it under the terms of the GNU General Public License\r\n# as published by the Free Software Foundation; either version 2\r\n# of the License, or (at your option) any later version.\r\n#\r\n# This program is distributed in the hope that it will be useful,\r\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\r\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\r\n# GNU General Public License for more details.\r\n#\r\n# END GPL LICENSE BLOCK #####\r\n\r\n\r\nbl_info = {\r\n \"name\" : \"JLink: Link Transforms\",\r\n \"author\" : \"Jac Rossiter\",\r\n \"description\" : \"Adds Link Transforms to Link Menu (Ctrl L in object mode)\",\r\n \"blender\" : (2, 90, 1),\r\n \"version\" : (0, 0, 0, 4),\r\n \"warning\" : \"\",\r\n \"category\" : \"Object\"\r\n}\r\n\r\nimport bpy\r\nimport mathutils\r\nfrom bpy.types import Panel, Operator\r\n\r\nclass LinkLocation_Operator(Operator):\r\n bl_idname = \"link.location\"\r\n bl_label = \"Link Location\"\r\n bl_description = \"Copy Location from active object\" \r\n bl_options = {'REGISTER'}\r\n \r\n def execute(self, context):\r\n active_location = bpy.context.view_layer.objects.active.location\r\n for obj in bpy.context.selected_objects:\r\n try:\r\n bpy.context.view_layer.objects.active = obj\r\n bpy.context.view_layer.objects.active.location = active_location\r\n except:\r\n pass\r\n return {'FINISHED'}\r\n\r\nclass LinkRotation_Operator(Operator):\r\n bl_idname = \"link.rotation\"\r\n bl_label = \"Link Rotation\"\r\n bl_description = \"Copy Rotation from active object\" \r\n bl_options = {'REGISTER'}\r\n \r\n def execute(self, context):\r\n active_rotation = bpy.context.view_layer.objects.active.rotation_euler\r\n for obj in bpy.context.selected_objects:\r\n try:\r\n bpy.context.view_layer.objects.active = obj\r\n bpy.context.view_layer.objects.active.rotation_euler = active_rotation\r\n except:\r\n pass\r\n return {'FINISHED'}\r\n\r\nclass LinkScale_Operator(Operator):\r\n bl_idname = \"link.scale\"\r\n bl_label = \"Link Scale\"\r\n bl_description = \"Copy Scale from active object\" \r\n bl_options = {'REGISTER'}\r\n \r\n def execute(self, context):\r\n active_scale = bpy.context.view_layer.objects.active.scale\r\n for obj in bpy.context.selected_objects:\r\n try:\r\n bpy.context.view_layer.objects.active = obj\r\n bpy.context.view_layer.objects.active.scale = active_scale\r\n except:\r\n pass\r\n return {'FINISHED'}\r\n\r\nclass LinkTransform_Operator(Operator):\r\n bl_idname = \"link.transform\"\r\n bl_label = \"Link Transform\"\r\n bl_description = \"Copy Transforms from active object\" \r\n bl_options = {'REGISTER'}\r\n \r\n def execute(self, context):\r\n active_location = bpy.context.view_layer.objects.active.location\r\n active_rotation = bpy.context.view_layer.objects.active.rotation_euler\r\n active_scale = bpy.context.view_layer.objects.active.scale\r\n\r\n for obj in bpy.context.selected_objects:\r\n try:\r\n bpy.context.view_layer.objects.active = obj\r\n bpy.context.view_layer.objects.active.location = active_location\r\n bpy.context.view_layer.objects.active.rotation_euler = active_rotation\r\n bpy.context.view_layer.objects.active.scale = active_scale\r\n except:\r\n pass\r\n return {'FINISHED'}\r\n\r\nclass RotationFromCursor_Operator(Operator):\r\n bl_idname = \"link.cursor_rotation\"\r\n bl_label = \"Set Object Rotation using 3D Cursor\"\r\n bl_description = \"Sets your selected objects rotation to that of the 3D Cursor, maintains scene position and rotation\" \r\n bl_options = {'REGISTER'}\r\n \r\n def execute(self, context): # Code from Sergey Kritskiy\r\n\r\n bpy.context.scene.cursor.rotation_mode = 'XYZ' # If this is not set the function will not work.\r\n \r\n def Rotate(myMesh, mat):\r\n for v in myMesh.vertices:\r\n vec = mat @ v.co\r\n v.co = vec\r\n def RotateFromCursor():\r\n source = bpy.context.scene.cursor\r\n objects = bpy.context.selected_objects\r\n mat_source = source.rotation_euler.to_matrix()\r\n mat_source.invert()\r\n for ob in objects:\r\n mat_ob = ob.rotation_euler.to_matrix()\r\n if ob.type == 'MESH':\r\n mat = mat_source @ mat_ob\r\n Rotate(ob.data, mat)\r\n ob.rotation_euler = source.rotation_euler\r\n RotateFromCursor()\r\n return {'FINISHED'}\r\n\r\ndef draw_menu(self, context):\r\n layout = self.layout\r\n layout.separator()\r\n layout.operator(\"link.location\", text=\"Location\")\r\n layout.operator(\"link.rotation\", text=\"Rotation\")\r\n layout.operator(\"link.scale\", text=\"Scale\")\r\n layout.operator(\"link.transform\", text=\"All Transforms\")\r\n layout.operator(\"link.cursor_rotation\", text=\"Rotation from 3D Cursor\")\r\n\r\nclasses = (\r\n LinkLocation_Operator,\r\n LinkRotation_Operator,\r\n LinkScale_Operator,\r\n LinkTransform_Operator,\r\n RotationFromCursor_Operator\r\n\r\n)\r\n\r\ndef register():\r\n from bpy.utils import register_class\r\n for cls in classes:\r\n register_class(cls)\r\n bpy.types.VIEW3D_MT_make_links.append(draw_menu)\r\n\r\ndef unregister():\r\n from bpy.utils import unregister_class\r\n for cls in reversed(classes):\r\n unregister_class(cls)\r\n bpy.types.VIEW3D_MT_make_links.remove(draw_menu)\r\n\r\nif __name__ == \"__main__\":\r\n register()\r\n","repo_name":"JacRossiter/JLink","sub_path":"JLink-LinkTransforms.py","file_name":"JLink-LinkTransforms.py","file_ext":"py","file_size_in_byte":5729,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"81"} +{"seq_id":"74319370184","text":"\nfrom motor.motor_asyncio import AsyncIOMotorClient\nfrom odmantic import AIOEngine\nfrom app.config import MONGO_URL, MONGO_DB_NAME\n\nclient = AsyncIOMotorClient(MONGO_URL)\nengine = AIOEngine(motor_client=client, database=MONGO_DB_NAME)\n\n\nclass MongoDB:\n def __init__(self):\n self.client = None\n self.engine = None\n\n def connect(self):\n self.client = AsyncIOMotorClient(MONGO_URL)\n self.engine = AIOEngine(motor_client=self.client, database=MONGO_DB_NAME)\n print(\"DB와 성공적으로 연결되었습니다\")\n\n def close(self):\n print(\"DB를 종료합니다.\")\n self.client.close()\n\n\nmongodb = MongoDB()\n","repo_name":"easyseop/Python-Concurrency-Programming","sub_path":"app/models/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":661,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"81"} +{"seq_id":"12580946481","text":"# general imports\nimport os\nfrom matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas\nimport matplotlib.pyplot as plt\nfrom datetime import datetime\n# pySide2 imports\nimport PySide2\nfrom PySide2.QtGui import QColor\nfrom PySide2.QtWidgets import QMainWindow\nfrom PySide2 import QtWidgets\n# Ui imports\nfrom Generated.stats import Ui_Stats\n# classes imports\nfrom data_handler import *\n\n\nclass stats(QMainWindow, Ui_Stats):\n\n def __init__(self, parent, handler, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.path = os.path.dirname(os.path.abspath(__file__)).split(\"\\\\\")\n self.path = self.path[:-1]\n self.path = '\\\\'.join(self.path)\n self.setupUi(self)\n self.parent = parent\n self.handler = handler\n self.tabWidget.tabBar().setTabTextColor(0, QColor(251, 248, 190))\n self.df_first = self.handler.df_first_meeting.copy()\n self.df_follow = self.handler.df_followUp.copy()\n\n self.range_of_years_comboBox.addItems(['1', '5', '10'])\n self.Obesity_grade_comboBox.addItems(['All', 'Normal', 'Overweight', 'Obesity |', 'Obesity ||', 'Obesity |||'])\n self.Obesity_grade_comboBox_tab4.addItems(\n ['All', 'Normal', 'Overweight', 'Obesity |', 'Obesity ||', 'Obesity |||'])\n self.Age_groups_comboBox.addItems(['All', 'Teens', '20s', '30s', '40s', '50s', '60s', '70<'])\n self.Age_groups_comboBox_tab4.addItems(['All', 'Teens', '20s', '30s', '40s', '50s', '60s', '70<'])\n self.Procedure_comboBox.addItems(\n ['All', 'BAGUA', 'Balón', 'Manga', 'By-pass', 'Otros', 'Re-Operación', 'Procedimiento Pendiente'])\n self.Procedure_comboBox_tab4.addItems(\n ['All', 'BAGUA', 'Balón', 'Manga', 'By-pass', 'Otros', 'Re-Operación', 'Procedimiento Pendiente'])\n self.Months_after_comboBox.addItems(\n ['All', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13-17',\n '18', '19-23', '24', '24<'])\n self.init_dataFrame()\n self.create_simpel_graphs_tab1()\n self.create_simpel_graphs_tab2()\n self.create_interactive_graphs_tab3()\n self.create_interactive_graphs_tab4()\n self.setWindowTitle('Statistics')\n self.setWindowIcon(PySide2.QtGui.QIcon(\"icon.png\"))\n self.Messages()\n self.connectSignalsSlots()\n\n\n def connectSignalsSlots(self):\n self.return_to_main_button.clicked.connect(self.move_main)\n self.return_to_main_button_2.clicked.connect(self.move_main)\n self.return_to_main_button_3.clicked.connect(self.move_main)\n self.return_to_main_button_4.clicked.connect(self.move_main)\n self.save_pic_button1.clicked.connect(self.save_image1)\n self.save_pic_button_2.clicked.connect(self.save_image2)\n self.save_pic_button_3.clicked.connect(self.save_image3)\n self.save_pic_button_4.clicked.connect(self.save_image4)\n self.update_tab2.clicked.connect(self.create_simpel_graphs_tab2)\n self.update_tab3.clicked.connect(self.create_interactive_graphs_tab3)\n self.update_tab4.clicked.connect(self.create_interactive_graphs_tab4)\n\n def init_dataFrame(self):\n bins_for_age = [0, 20, 30, 40, 50, 60, 70, 120]\n bins_labels_age = ['Teens', '20s', '30s', '40s', '50s', '60s', '70<']\n bins_for_Obesity_grade = [0, 26, 31, 36, 40, 120]\n bins_labels_Obesity_grade = ['Normal', 'Overweight', 'Obesity |', 'Obesity ||', 'Obesity |||']\n for index in self.df_first.index:\n if str(self.df_first.iloc[index].at['date']) == \"NaT\":\n self.df_first.at[index, 'age'] = -1\n else:\n self.df_first.at[index, 'age'] = self.df_first.at[index, 'date'].year - self.df_first.at[\n index, 'age'].year - ((self.df_first.at[index, 'date'].month,\n self.df_first.at[index, 'date'].day) < (\n self.df_first.at[index, 'age'].month, self.df_first.at[index, 'age'].day))\n\n time_from_procedure = []\n weight_lost = []\n weight_lost_percent = []\n BMI_current = []\n over_weight_lost_percent = []\n month_range1317 = [13, 14, 15, 16, 17]\n month_range1923 = [19, 20, 21, 22, 23]\n\n self.total_dataframe = pd.merge(self.df_follow[['Cedula', 'Peso']], self.df_first[['Cedula', 'age',\n 'Origen',\n 'Procedimiento',\n 'date', 'peso [kg]',\n 'height [m]']],\n on='Cedula', how='left')\n col_names = ['Cedula', 'Current weight', 'Age', 'Origen', 'Procedimiento', 'Procedure Date', 'Primary weight',\n 'height']\n self.total_dataframe.columns = col_names\n for index in self.total_dataframe.index:\n\n if str(self.df_follow.iloc[index].at['Fecha']) == \"NaT\":\n time_from_procedure.append(-1)\n else:\n start_date = self.total_dataframe.at[index, 'Procedure Date']\n end_date = self.df_follow.iloc[index]['Fecha'] # represent a date of follow up meeting\n diff_month = (end_date.year - start_date.year) * 12 + (end_date.month - start_date.month)\n if diff_month in month_range1317:\n diff_month = 13\n elif diff_month in month_range1923:\n diff_month = 19\n elif diff_month >= 25:\n diff_month = 25\n time_from_procedure.append(diff_month)\n weight_lost1 = self.total_dataframe.at[index, 'Primary weight'] - self.total_dataframe.at[\n index, 'Current weight']\n weight_lost.append(weight_lost1)\n weight_lost_percent.append(\n (self.total_dataframe.at[index, 'Primary weight'] - self.total_dataframe.at[index, 'Current weight']) /\n self.total_dataframe.at[index, 'Primary weight'])\n BMI_current.append(\n self.getBMI(self.total_dataframe.at[index, 'Current weight'], self.total_dataframe.at[index, 'height']))\n ideal_weight = (25 * (self.total_dataframe.at[index, 'height'] ** 2))\n dif_start_ideal = self.total_dataframe.at[index, 'Primary weight'] - ideal_weight\n over_weight_lost_percent.append(weight_lost1 / dif_start_ideal)\n self.total_dataframe['diff_month'] = time_from_procedure\n self.total_dataframe['weight_lost'] = weight_lost\n self.total_dataframe['weight_lost_percent'] = weight_lost_percent\n self.total_dataframe['BMI_current'] = BMI_current\n self.total_dataframe['over_weight_lost_percent'] = over_weight_lost_percent\n self.total_dataframe['Binned_Ages'] = pd.cut(self.total_dataframe['Age'], bins=bins_for_age,\n labels=bins_labels_age)\n self.total_dataframe['Obesity_grade'] = pd.cut(self.total_dataframe['BMI_current'], bins=bins_for_Obesity_grade,\n labels=bins_labels_Obesity_grade)\n\n self.df_for_age_origin_procedure_perYear = self.total_dataframe.drop_duplicates(subset=['Cedula'])\n\n def create_simpel_graphs_tab1(self):\n self.wid_graphs = QtWidgets.QWidget(self.tab)\n self.wid_graphs.setGeometry(0, 90, 1550, 400)\n grid_graphs = QtWidgets.QGridLayout(self.wid_graphs)\n list_for_age = [0, 0, 0, 0, 0, 0, 0]\n list_for_origen = [0] * len(self.total_dataframe['Origen'].unique())\n list_for_procedure = [0, 0, 0, 0, 0, 0, 0]\n distinct_origin = self.total_dataframe['Origen'].unique()\n distinct_Procedimiento = self.total_dataframe['Procedimiento'].unique()\n\n for index in self.df_for_age_origin_procedure_perYear.index:\n if self.df_for_age_origin_procedure_perYear.at[index, 'Age'] == -1:\n continue\n elif self.df_for_age_origin_procedure_perYear.at[index, 'Age'] < 20:\n list_for_age[0] = list_for_age[0] + 1\n elif self.df_for_age_origin_procedure_perYear.at[index, 'Age'] <= 29:\n list_for_age[1] = list_for_age[1] + 1\n elif self.df_for_age_origin_procedure_perYear.at[index, 'Age'] <= 39:\n list_for_age[2] = list_for_age[2] + 1\n elif self.df_for_age_origin_procedure_perYear.at[index, 'Age'] <= 49:\n list_for_age[3] = list_for_age[3] + 1\n elif self.df_for_age_origin_procedure_perYear.at[index, 'Age'] <= 59:\n list_for_age[4] = list_for_age[4] + 1\n elif self.df_for_age_origin_procedure_perYear.at[index, 'Age'] <= 69:\n list_for_age[5] = list_for_age[5] + 1\n else:\n list_for_age[6] = list_for_age[6] + 1\n if self.df_for_age_origin_procedure_perYear.at[index, 'Origen'] == distinct_origin.item(0):\n list_for_origen[0] = list_for_origen[0] + 1\n elif self.df_for_age_origin_procedure_perYear.at[index, 'Origen'] == distinct_origin.item(1):\n list_for_origen[1] = list_for_origen[1] + 1\n elif self.df_for_age_origin_procedure_perYear.at[index, 'Origen'] == distinct_origin.item(2):\n list_for_origen[2] = list_for_origen[2] + 1\n else:\n list_for_origen[3] = list_for_origen[3] + 1\n\n if self.df_for_age_origin_procedure_perYear.at[index, 'Procedimiento'] == distinct_Procedimiento.item(0):\n list_for_procedure[0] = list_for_procedure[0] + 1\n elif self.df_for_age_origin_procedure_perYear.at[index, 'Procedimiento'] == distinct_Procedimiento.item(1):\n list_for_procedure[1] = list_for_procedure[1] + 1\n elif self.df_for_age_origin_procedure_perYear.at[index, 'Procedimiento'] == distinct_Procedimiento.item(2):\n list_for_procedure[2] = list_for_procedure[2] + 1\n elif self.df_for_age_origin_procedure_perYear.at[index, 'Procedimiento'] == distinct_Procedimiento.item(3):\n list_for_procedure[3] = list_for_procedure[3] + 1\n elif self.df_for_age_origin_procedure_perYear.at[index, 'Procedimiento'] == distinct_Procedimiento.item(4):\n list_for_procedure[4] = list_for_procedure[4] + 1\n elif self.df_for_age_origin_procedure_perYear.at[index, 'Procedimiento'] == distinct_Procedimiento.item(5):\n list_for_procedure[5] = list_for_procedure[5] + 1\n else:\n list_for_procedure[6] = list_for_procedure[6] + 1\n\n labels_for_age = ['<20', '20-29', '30-39', '40-49', '50-59', '60-69', '70<']\n\n fig_graphs = plt.figure(tight_layout=True)\n ax_age, ax_origen, ax_procedure = fig_graphs.subplots(1, 3)\n\n reacts_age = ax_age.bar(labels_for_age, list_for_age, edgecolor=\"white\", color='tab:blue')\n ax_age.set_title(\"Patients By Age\")\n ax_age.set_xlabel(\"Age Group\")\n ax_age.set_ylabel(\"frequency\")\n ax_age.tick_params(axis='x', rotation=45)\n self.auto_label_for_int(reacts_age, ax_age)\n\n reacts_origen = ax_origen.bar(distinct_origin, list_for_origen, edgecolor=\"white\", color='tab:blue')\n ax_origen.set_title(\"Patients By Origen\")\n ax_origen.set_xlabel(\"Origen\")\n ax_origen.set_ylabel(\"frequency\")\n ax_origen.tick_params(axis='x', labelsize=10)\n ax_origen.tick_params(axis='x', rotation=45)\n self.auto_label_for_int(reacts_origen, ax_origen)\n\n reacts_procedure = ax_procedure.bar(distinct_Procedimiento, list_for_procedure, edgecolor=\"white\",\n color='tab:blue')\n ax_procedure.set_title(\"Patients By Procedure\")\n ax_procedure.set_xlabel(\"Type of Procedure\")\n ax_procedure.set_ylabel(\"frequency\")\n ax_procedure.tick_params(axis='x', labelsize=8)\n ax_procedure.tick_params(axis='x', rotation=45)\n self.auto_label_for_int(reacts_procedure, ax_procedure)\n\n self.plot1 = fig_graphs\n canvas_weight = FigureCanvas(fig_graphs)\n grid_graphs.addWidget(canvas_weight, 0, 0)\n self.wid_graphs.show()\n\n def create_simpel_graphs_tab2(self):\n num_of_years_in_bin = int(self.range_of_years_comboBox.currentText())\n\n self.wid_graphs = QtWidgets.QWidget(self.tab_2)\n self.wid_graphs.setGeometry(0, 90, 1375, 400)\n grid_graphs = QtWidgets.QGridLayout(self.wid_graphs)\n\n self.df_groupby = pd.DataFrame()\n self.df_groupby['year'] = self.df_for_age_origin_procedure_perYear['Procedure Date'].apply(\n lambda date: date.year)\n self.df_groupby = self.df_groupby.groupby(['year']).size()\n self.df_groupby.index = self.df_groupby.index.astype('int64')\n\n values_for_bin = []\n labels_for_bin = []\n\n if num_of_years_in_bin == 1:\n for index in self.df_groupby.index:\n labels_for_bin.append(index)\n values_for_bin.append(self.df_groupby._get_value(index))\n elif num_of_years_in_bin == 5:\n values_for_bin, labels_for_bin = self.get_bins_with_values()\n else:\n values_for_bin, labels_for_bin = self.get_bins_with_values()\n # ------------------------------------ end of Patient per Year preparation -------------------------\n labels_for_diff_month = ['Pre-Qx', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13-17',\n '18', '19-23', '24', '24<']\n\n df_for_overweight_lost = self.total_dataframe.groupby(by='diff_month').mean()\n list_for_overweight_lost = df_for_overweight_lost['over_weight_lost_percent'].tolist()\n for item in range(len(list_for_overweight_lost)):\n list_for_overweight_lost[item] = round(list_for_overweight_lost[item], 2)\n\n fig_graphs = plt.figure(tight_layout=True)\n ax_overweight_lost, ax_per_year = fig_graphs.subplots(1, 2)\n reacts_overweight_lost = ax_overweight_lost.bar(labels_for_diff_month, list_for_overweight_lost,\n edgecolor=\"white\", color='tab:blue')\n\n ax_overweight_lost.set_title(\"Month By Overweight Lost %\")\n ax_overweight_lost.set_xlabel(\"Month From Procedure\")\n ax_overweight_lost.set_ylabel(\"Average Overweight Lost\")\n ax_overweight_lost.tick_params(axis='x', rotation=45)\n self.auto_label_for_float(reacts_overweight_lost, ax_overweight_lost)\n\n reacts_per_year = ax_per_year.bar(labels_for_bin, values_for_bin,\n edgecolor=\"white\", color='tab:blue')\n ax_per_year.set_title(\"Patients Per Year\")\n ax_per_year.set_xlabel(\"Year\")\n ax_per_year.set_ylabel(\"Number Of Patients\")\n ax_per_year.get_xaxis().set_ticks(labels_for_bin)\n ax_per_year.tick_params(axis='x', rotation=45)\n self.auto_label_for_int(reacts_per_year, ax_per_year)\n\n self.plot2 = fig_graphs\n canvas_weight = FigureCanvas(fig_graphs)\n grid_graphs.addWidget(canvas_weight, 0, 0)\n self.wid_graphs.show()\n\n def create_interactive_graphs_tab3(self):\n self.wid_graphs = QtWidgets.QWidget(self.tab_3)\n self.wid_graphs.setGeometry(30, 150, 1500, 400)\n grid_graphs = QtWidgets.QGridLayout(self.wid_graphs)\n\n current_month_after_serg = self.Months_after_comboBox.currentText()\n if current_month_after_serg == 'All':\n current_month_after_serg = current_month_after_serg\n elif current_month_after_serg == '13-17':\n current_month_after_serg = 13\n elif current_month_after_serg == '19-23':\n current_month_after_serg = 19\n elif current_month_after_serg == '24<':\n current_month_after_serg = 25\n else:\n current_month_after_serg = int(current_month_after_serg)\n\n current_Obesity_grade = self.Obesity_grade_comboBox.currentText()\n current_Age_groups = self.Age_groups_comboBox.currentText()\n current_Procedure = self.Procedure_comboBox.currentText()\n values_for_bin = []\n labels_for_bin = []\n\n self.df_after_fillter = self.get_filtered_df(current_month_after_serg, current_Obesity_grade,\n current_Age_groups, current_Procedure, 3)\n\n if current_month_after_serg == 'All':\n for index in self.df_after_fillter.index:\n if index == '-1':\n continue\n labels_for_bin.append(index)\n values_for_bin.append(self.df_after_fillter._get_value(index))\n else:\n labels_for_bin.append(self.df_after_fillter.index[0])\n values_for_bin.append(self.df_after_fillter._get_value(labels_for_bin[0]))\n\n label = 'Frequency of patient per Month flitered by: Month: ' + str(\n current_month_after_serg) + ' Obesity grade: ' + current_Obesity_grade + ' Age: ' + current_Age_groups + ' Procedure ' + current_Procedure\n\n fig_graphs = plt.figure(tight_layout=True)\n ax_frequency_by_months = fig_graphs.subplots(1)\n reacts_procedure = ax_frequency_by_months.bar(labels_for_bin, values_for_bin, width=0.6, edgecolor=\"white\",\n color='tab:blue')\n ax_frequency_by_months.set_title(label)\n ax_frequency_by_months.set_xlabel(\"Month From Procedure\")\n ax_frequency_by_months.get_xaxis().set_ticks(labels_for_bin)\n ax_frequency_by_months.set_ylabel(\"Frequency\")\n ax_frequency_by_months.set_xlim(-2, 19)\n ax_frequency_by_months.tick_params(axis='x', rotation=45)\n self.auto_label_for_int(reacts_procedure, ax_frequency_by_months)\n\n\n self.plot3 = fig_graphs\n canvas_weight = FigureCanvas(fig_graphs)\n grid_graphs.addWidget(canvas_weight, 0, 0)\n self.wid_graphs.show()\n\n def create_interactive_graphs_tab4(self):\n self.wid_graphs = QtWidgets.QWidget(self.tab_4)\n self.wid_graphs.setGeometry(30, 150, 1500, 400)\n grid_graphs = QtWidgets.QGridLayout(self.wid_graphs)\n current_Obesity_grade = self.Obesity_grade_comboBox_tab4.currentText()\n current_Age_groups = self.Age_groups_comboBox_tab4.currentText()\n current_Procedure = self.Procedure_comboBox_tab4.currentText()\n values_for_bin = []\n labels_for_bin = []\n\n self.df_after_fillter = self.get_filtered_df('All', current_Obesity_grade,\n current_Age_groups, current_Procedure, 4)\n\n for index in self.df_after_fillter.index:\n if index == '-1':\n continue\n labels_for_bin.append(index)\n values_for_bin.append(self.df_after_fillter._get_value(index))\n\n label = 'OverWeight lost per Month flitered by: Obesity grade: ' + current_Obesity_grade + ' Age: ' + current_Age_groups + ' Procedure ' + current_Procedure\n\n fig_graphs = plt.figure(tight_layout=True)\n ax_frequency_by_months = fig_graphs.subplots(1)\n reacts_procedure = ax_frequency_by_months.bar(labels_for_bin, values_for_bin, width=0.6, edgecolor=\"white\",\n color='tab:blue')\n ax_frequency_by_months.set_title(label)\n ax_frequency_by_months.set_xlabel(\"Month From Procedure\")\n ax_frequency_by_months.get_xaxis().set_ticks(labels_for_bin)\n ax_frequency_by_months.set_ylabel(\"OverWeight lost [%]\")\n ax_frequency_by_months.set_xlim(-1, 18)\n ax_frequency_by_months.tick_params(axis='x', rotation=45)\n self.auto_label_for_float(reacts_procedure, ax_frequency_by_months)\n\n self.plot4 = fig_graphs\n canvas_weight = FigureCanvas(fig_graphs)\n grid_graphs.addWidget(canvas_weight, 0, 0)\n self.wid_graphs.show()\n\n def getBMI(self, weight, height):\n bmi = (weight / (height ** 2))\n formatted_bmi = \"{:.2f}\".format(bmi)\n return float(formatted_bmi)\n\n\n def auto_label_for_int(self, rects, ax):\n for rect in rects:\n height = rect.get_height()\n ax.text(rect.get_x() + rect.get_width() / 2., 1.01 * height,\n int(height), backgroundcolor='0.85', fontsize='xx-small',\n ha='center', va='bottom')\n\n\n\n def auto_label_for_float(self, rects, ax):\n for rect in rects:\n height = rect.get_height()\n ax.text(rect.get_x() + rect.get_width() / 2., 1.01 * height,\n float(height), backgroundcolor='0.85', fontsize='xx-small',\n ha='center', va='bottom')\n\n def save_image1(self):\n\n desired_folder = os.path.join(self.path, 'pics\\\\age origen procedure')\n # os.makedirs(desired_folder) # for creating a routh\n today = datetime.now().date()\n name = str('age_origen_procedure') + \"_\" + str(today)\n full_path = os.path.join(desired_folder, name)\n try:\n self.plot1.savefig(full_path)\n QtWidgets.QMessageBox.information(self, self.Message_Success, self.Message_image_saved)\n except FileNotFoundError:\n QtWidgets.QMessageBox.information(self, self.Message_Fail, self.Message_folder_not_exist)\n\n def save_image2(self):\n desired_folder = os.path.join(self.path, 'pics\\\\overweight patients per year')\n today = datetime.now().date()\n name = str('overweight patients per year') + \"_\" + str(today)\n full_path = os.path.join(desired_folder, name)\n try:\n self.plot2.savefig(full_path)\n QtWidgets.QMessageBox.information(self, self.Message_Success, self.Message_image_saved)\n except FileNotFoundError:\n QtWidgets.QMessageBox.information(self, self.Message_Fail, self.Message_folder_not_exist)\n\n def save_image3(self):\n desired_folder = os.path.join(self.path, 'pics\\\\Amount of patient filtered')\n today = datetime.now().date()\n name = str('Amount of patient filtered') + \"_\" + str(today)\n full_path = os.path.join(desired_folder, name)\n try:\n self.plot3.savefig(full_path)\n QtWidgets.QMessageBox.information(self, self.Message_Success, self.Message_image_saved)\n except FileNotFoundError:\n QtWidgets.QMessageBox.information(self, self.Message_Fail, self.Message_folder_not_exist)\n\n def save_image4(self):\n desired_folder = os.path.join(self.path, 'pics\\Overweight per month filtered')\n today = datetime.now().date()\n name = str('Overweight per month filtered') + \"_\" + str(today)\n full_path = os.path.join(desired_folder, name)\n try:\n self.plot4.savefig(full_path)\n QtWidgets.QMessageBox.information(self, self.Message_Success, self.Message_image_saved)\n except FileNotFoundError:\n QtWidgets.QMessageBox.information(self, self.Message_Fail, self.Message_folder_not_exist)\n\n def move_main(self):\n self.close()\n self.wid_graphs.close()\n self.parent.re_show()\n\n def get_bins_with_values(self):\n jump = int(self.range_of_years_comboBox.currentText())\n time = datetime.now()\n formmeted_time = int(time.strftime(\"%Y\"))\n start_year = (self.df_groupby.index[0])\n bin_for_years = []\n\n while start_year <= formmeted_time:\n bin_for_years.append(start_year)\n if start_year == formmeted_time:\n break\n start_year += jump\n if start_year > formmeted_time:\n bin_for_years.append(formmeted_time)\n\n values_for_bin = [0] * (len(bin_for_years) - 1)\n labels_for_bin = [\"a\"] * (len(bin_for_years) - 1)\n for i in range(len(bin_for_years) - 1):\n for index in self.df_groupby.index:\n if i == len(bin_for_years) - 2:\n if bin_for_years[i] <= index <= formmeted_time:\n values_for_bin[i] = values_for_bin[i] + self.df_groupby.at[index]\n elif bin_for_years[i] <= index < bin_for_years[i + 1]:\n values_for_bin[i] = values_for_bin[i] + self.df_groupby.at[index]\n if i == len(bin_for_years) - 2:\n labels_for_bin[i] = str(bin_for_years[i]) + \"-\" + str(bin_for_years[i + 1])\n else:\n labels_for_bin[i] = str(bin_for_years[i]) + \"-\" + str((bin_for_years[i + 1] - 1))\n return values_for_bin, labels_for_bin\n\n def get_filtered_df(self, current_month_after_serg, current_Obesity_grade, current_Age_groups, current_Procedure,\n requested_tab):\n self.df = pd.DataFrame()\n\n if current_month_after_serg == 'All':\n if current_Age_groups == 'All':\n if current_Obesity_grade == 'All':\n if current_Procedure == 'All':\n self.df = self.total_dataframe.copy()\n else:\n self.df = self.total_dataframe.query('Procedimiento == @current_Procedure')\n else:\n self.df = self.total_dataframe.query('Obesity_grade == @current_Obesity_grade')\n if current_Procedure != 'All':\n self.df = self.df.query('Procedimiento == @current_Procedure')\n\n else:\n self.df = self.total_dataframe.query('Binned_Ages == @current_Age_groups')\n if current_Obesity_grade == 'All':\n if current_Procedure != 'All':\n self.df = self.df.query('Procedimiento == @current_Procedure')\n else:\n self.df = self.df.query('Obesity_grade == @current_Obesity_grade')\n if current_Procedure != 'All':\n self.df = self.df.query('Procedimiento == @current_Procedure')\n\n else:\n self.df = self.total_dataframe.query('diff_month == @current_month_after_serg')\n if current_Age_groups == 'All':\n if current_Obesity_grade == 'All':\n if current_Procedure != 'All':\n self.df = self.df.query('Procedimiento == @current_Procedure')\n else:\n self.df = self.df.query('Obesity_grade == @current_Obesity_grade')\n if current_Procedure != 'All':\n self.df = self.df.query('Procedimiento == @current_Procedure')\n else:\n self.df = self.df.query('Binned_Ages == @current_Age_groups')\n if current_Obesity_grade == 'All':\n if current_Procedure != 'All':\n self.df = self.df.query('Procedimiento == @current_Procedure')\n\n else:\n self.df = self.df.query('Obesity_grade == @current_Obesity_grade')\n if current_Procedure != 'All':\n self.df = self.df.query('Procedimiento == @current_Procedure')\n\n if requested_tab == 3:\n self.df_after_fillter = self.df.groupby(by='diff_month').size()\n for index in self.df_after_fillter.index:\n self.df_after_fillter.rename(index={index: str(index)}, inplace=True)\n self.df_after_fillter.rename(index={'13': '13-17'}, inplace=True)\n self.df_after_fillter.rename(index={'19': '19-23'}, inplace=True)\n self.df_after_fillter.rename(index={'25': '24<'}, inplace=True)\n return self.df_after_fillter\n else:\n self.df_after_fillter = self.df.groupby(by='diff_month')['over_weight_lost_percent'].mean()\n for index in self.df_after_fillter.index:\n self.df_after_fillter.rename(index={index: str(index)}, inplace=True)\n self.df_after_fillter = self.df_after_fillter.round(decimals=2)\n self.df_after_fillter.rename(index={'13': '13-17'}, inplace=True)\n self.df_after_fillter.rename(index={'19': '19-23'}, inplace=True)\n self.df_after_fillter.rename(index={'25': '24<'}, inplace=True)\n return self.df_after_fillter\n\n def Messages(self):\n self.Message_image_saved = 'image has been saved!!'\n self.Message_folder_not_exist = 'Folder does not exist'\n self.Message_Success = 'Success'\n self.Message_Fail = 'Fail'","repo_name":"slimdavid44/WeigthControlSW","sub_path":"Scripts/stats.py","file_name":"stats.py","file_ext":"py","file_size_in_byte":28747,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"20251858080","text":"from typing import Callable, MutableMapping, TypeVar, overload\n\nfrom apischema.cache import CacheAwareDict\nfrom apischema.types import Metadata, MetadataImplem\n\nAliaser = Callable[[str], str]\nCls = TypeVar(\"Cls\", bound=type)\n\n_class_aliasers: MutableMapping[type, Aliaser] = CacheAwareDict({})\n\nget_class_aliaser = _class_aliasers.get\n\n\n@overload\ndef alias(alias_: str, *, override: bool = True) -> Metadata:\n ...\n\n\n@overload\ndef alias(override: bool) -> Metadata:\n ...\n\n\n@overload\ndef alias(aliaser: Aliaser) -> Callable[[Cls], Cls]:\n ...\n\n\ndef alias(arg=None, *, override: bool = True): # type: ignore\n \"\"\"Field alias or class aliaser\n\n :param alias_: alias of the field\n :param override: alias can be overridden by a class aliaser\n :param aliaser: compute alias for each (overridable) field of the class decorated\n \"\"\"\n from apischema.metadata.keys import ALIAS_METADATA, ALIAS_NO_OVERRIDE_METADATA\n\n if callable(arg):\n\n def aliaser(cls: Cls) -> Cls:\n _class_aliasers[cls] = arg\n return cls\n\n return aliaser\n else:\n metadata = MetadataImplem()\n if arg is not None:\n metadata[ALIAS_METADATA] = arg\n if not override:\n metadata[ALIAS_NO_OVERRIDE_METADATA] = True\n if not metadata:\n raise NotImplementedError\n return metadata\n","repo_name":"wyfo/apischema","sub_path":"apischema/aliases.py","file_name":"aliases.py","file_ext":"py","file_size_in_byte":1363,"program_lang":"python","lang":"en","doc_type":"code","stars":206,"dataset":"github-code","pt":"81"} +{"seq_id":"6661706396","text":"import os\n\nfrom kivy.properties import ObjectProperty\nfrom kivy.uix.boxlayout import BoxLayout\nfrom kivy.uix.floatlayout import FloatLayout\nfrom kivy.uix.popup import Popup\nfrom kivy.uix.button import Button\nfrom kivy.uix.togglebutton import ToggleButton\nfrom kivy.uix.textinput import TextInput\nfrom kivy.uix.filechooser import FileChooserListView\nDropDown = None\n\ndef load_dropdown():\n global DropDown\n if DropDown is None:\n from kivy.uix.dropdown import DropDown as _DropDown\n DropDown = _DropDown\n\nclass MenuBar(BoxLayout):\n def __init__(self, **kwargs):\n kwargs['height'] = 30\n super(MenuBar, self).__init__(**kwargs)\n self.file_menu = FileDropDown()\n self.add_widget(self.file_menu)\n def do_layout(self, *args):\n if self.parent:\n self.width = self.parent.width\n self.top = self.parent.top\n self.x = self.parent.x\n super(MenuBar, self).do_layout(*args)\n \nclass MenuDropDown(ToggleButton):\n def __init__(self, **kwargs):\n self.name = kwargs.get('name')\n kwargs.setdefault('text', self.name)\n self._dropdown_active = False\n super(MenuDropDown, self).__init__(**kwargs)\n self.register_event_type('on_select')\n load_dropdown()\n self.dropdown = DropDown()\n items = kwargs.get('items', [])\n for item in items:\n self.add_item(item)\n self.dropdown.bind(on_select=self.on_dropdown_select, \n on_dismiss=self.on_dropdown_dismiss)\n def add_item(self, item):\n btn = Button(text=item.title(), size_hint_y=None, height=44)\n btn.bind(on_release=lambda btn: self.dropdown.select(item))\n self.dropdown.add_widget(btn)\n def on_dropdown_select(self, instance, value):\n self.dispatch('on_select', value)\n self.state = 'normal'\n def on_release(self):\n value = self.state\n if value == 'down' and not self._dropdown_active:\n self._dropdown_active = True\n self.dropdown.open(self)\n def on_dropdown_dismiss(self, *args):\n self._dropdown_active = False\n return\n def on_select(self, *args):\n pass\n \n\nclass FileDropDown(MenuDropDown):\n path = ObjectProperty(None, allownone=True)\n file = ObjectProperty(None, allownone=True)\n def __init__(self, **kwargs):\n self.file_dialog = None\n self.popup = None\n kwargs.setdefault('name', 'File')\n kwargs.setdefault('items', ['New', 'Open', 'Save'])\n super(FileDropDown, self).__init__(**kwargs)\n self.current_mode = None\n if self.path is None:\n self.path = os.getcwd()\n self.register_event_type('on_new_file')\n self.register_event_type('on_open_file')\n self.register_event_type('on_save_file')\n def build_file_dialog(self):\n dlg = self.file_dialog = FileDialog(mode=self.current_mode, \n path=self.path, \n file=self.file)\n dlg.bind(on_cancel=self.on_file_dialog_cancel, \n on_submit=self.on_file_dialog_submit)\n self.popup = Popup(title=self.current_mode.title(), content=dlg, size_hint=(.9, .9))\n self.popup.open()\n def clear_file_dialog(self):\n self.file_dialog.unbind(on_cancel=self.on_file_dialog_cancel, \n on_submit=self.on_file_dialog_submit)\n self.popup.dismiss()\n self.file_dialog = None\n self.popup = None\n def on_file_dialog_cancel(self, *args):\n self.clear_file_dialog()\n self.current_mode = None\n def on_file_dialog_submit(self, *args):\n dlg = self.file_dialog\n self.path = dlg.path\n self.file = dlg.file\n self.clear_file_dialog()\n sig_name = '_'.join(['on', self.current_mode.lower(), 'file'])\n self.dispatch(sig_name, self.path, self.file)\n self.current_mode = None\n def on_select(self, value):\n self.current_mode = value\n if value == 'New':\n self.current_mode = None\n self.file = None\n self.dispatch('on_new_file')\n elif value == 'Open':\n self.build_file_dialog()\n elif value == 'Save':\n if self.file is not None:\n self.dispatch('on_save_file', self.path, self.file)\n self.current_mode = None\n else:\n self.build_file_dialog()\n def on_new_file(self, *args):\n pass\n def on_open_file(self, *args):\n pass\n def on_save_file(self, *args):\n pass\n \nclass FileDialog(FloatLayout):\n path = ObjectProperty(None)\n file = ObjectProperty(None)\n def __init__(self, **kwargs):\n self.mode = kwargs.get('mode')\n super(FileDialog, self).__init__(**kwargs)\n self.register_event_type('on_cancel')\n self.register_event_type('on_submit')\n vbox = self.vbox = BoxLayout(orientation='vertical')\n self.add_widget(vbox)\n self.chooser = FileChooserListView(path=self.path)\n vbox.add_widget(self.chooser)\n self.text_input = TextInput(size_hint_y=None, height=30, multiline=False)\n if self.file:\n self.text_input.text = self.file\n vbox.add_widget(self.text_input)\n hbox = BoxLayout(size_hint_y=None, height=30)\n vbox.add_widget(hbox)\n self.cancel_btn = Button(text='Cancel')\n hbox.add_widget(self.cancel_btn)\n self.confirm_btn = Button(text=self.mode.title())\n hbox.add_widget(self.confirm_btn)\n self.text_input.bind(text=self.on_text_input_text)\n self.chooser.bind(path=self.on_chooser_path, \n selection=self.on_chooser_selection, \n on_submit=self.on_chooser_submit)\n self.cancel_btn.bind(on_release=self.on_cancel_btn_release)\n self.confirm_btn.bind(on_release=self.on_confirm_btn_release)\n def do_layout(self, *args):\n if self.parent is not None:\n self.pos = self.parent.pos\n self.size = self.parent.size\n self.vbox.pos = self.parent.pos\n self.vbox.size = self.parent.size\n super(FileDialog, self).do_layout(*args)\n def on_text_input_text(self, instance, value):\n if not self.text_input.focus:\n return\n self.file = value\n def on_chooser_path(self, instance, value):\n self.path = value\n def on_chooser_selection(self, instance, value):\n self.file = value[0]\n self.text_input.text = self.file\n def on_chooser_submit(self, *args):\n self.dispatch('on_submit')\n def on_cancel_btn_release(self, *args):\n self.dispatch('on_cancel')\n def on_confirm_btn_release(self, *args):\n if self.file:\n self.dispatch('on_submit')\n def on_cancel(self, *args):\n pass\n def on_submit(self, *args):\n pass\n","repo_name":"nocarryr/node_mapper","sub_path":"node_mapper/kivyui/menu.py","file_name":"menu.py","file_ext":"py","file_size_in_byte":6935,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"20671845179","text":"from db.src.requests import *\nfrom flask import Blueprint, render_template, request, redirect, url_for\n\ncommune = Blueprint('commune', __name__)\n\n@commune.route('/')\ndef index():\n communes = lire_communes()\n return render_template(\"commune.index.html\", communes=communes)\n\n@commune.route('/add', methods=[\"GET\", \"POST\"])\ndef add():\n\n if request.method == \"GET\":\n return render_template(\"commune.form.html\")\n\n elif request.method == \"POST\":\n new_commune = request.form.to_dict()\n insert_commune(new_commune['nom'], new_commune['cdp'])\n return redirect(url_for('commune.index'))\n\n@commune.route('/delete/')\ndef delete(id):\n delete_commune(id)\n return redirect(url_for('commune.index'))\n\n@commune.route('/update/', methods=[\"GET\", \"POST\"])\ndef update(id):\n\n if request.method == 'GET':\n updated_commune = lire_commune(id)\n return render_template(\"commune.form.html\", commune=updated_commune)\n \n elif request.method == \"POST\":\n updated_commune = request.form.to_dict()\n update_commune(id, updated_commune['nom'], updated_commune['cdp'])\n return redirect(url_for('commune.index'))","repo_name":"alspin8/SGBD-website","sub_path":"webApp/routes/commune.py","file_name":"commune.py","file_ext":"py","file_size_in_byte":1177,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"11901831945","text":"def lis(arr):\n dp = [1] * len(arr)\n for i in range(1, len(arr)):\n for j in range(i):\n if arr[i] > arr[j]:\n dp[i] = max(dp[i], dp[j] + 1)\n return max(dp)\n\n\nn = int(input())\nlines = [tuple(map(int, input().split())) for _ in range(n)]\nlines.sort(key=lambda x: x[0])\n\nb_lines = [line[1] for line in lines]\n\nlength_of_lis = lis(b_lines)\n\nprint(n - length_of_lis)\n","repo_name":"joohyuk2074/TIL_PRACTICE_CODE","sub_path":"python-algorithm/baekjoon/lis/2565(풀이완료).py","file_name":"2565(풀이완료).py","file_ext":"py","file_size_in_byte":401,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"23525762932","text":"def add(a,b):\r\n result=a+b\r\n return result\r\ndef minus(a,b):\r\n result=a-b\r\n if result<0:\r\n result=b-a\r\n return result\r\ndef cheng(a,b):\r\n result=a*b\r\n return result\r\ndef div(a,b):\r\n result=a/b\r\n return result\r\ndef biao(k,j):\r\n for i in range(1,k):\r\n for j in range(1,i+1):\r\n print(i,'*',j,'=',i*j,end='\\t')\r\n print()\r\ndef encode(s):\r\n q =input('请选择编码方式:GBK or UTF-8')\r\n if q == 'GBK':\r\n byte=s.encode(encoding='GBK')\r\n else:byte=s.encode(encoding='UTF-8')\r\n return byte\r\ndef decode(s):\r\n q = input('请选择解码方式:GBK or UTF-8')\r\n print('请输入对应的编码方式,否则报错')\r\n if q == 'GBK':\r\n byte = s.decode(encoding='GBK')\r\n else:\r\n byte = s.decode(encoding='UTF-8')\r\n return byte\r\ndef list():\r\n print('-------------')\r\n print('欢迎进入Bankrotteur个人Python程序展示')\r\n print('下面是temporary项目')\r\n print('1.加减乘除')\r\n print('2.乘法口诀表')\r\n print('3.文字编码解码')\r\n print('-------------')\r\ndef display(q):\r\n if q == '1':\r\n print('您选择的是1.加减乘除')\r\n elif q=='2':\r\n print('您选择的是2.乘法口决表')\r\n elif q=='3':\r\n print('您选择的是3.编码解码')\r\n\r\n\r\n\r\nlist();\r\nq2=input('请选择是需要的程序:1 or 2 or 3')\r\ndisplay(q2)\r\n\r\nif q2 == '1':\r\n a = int(input('请输入第一个数'))\r\n b = int(input('请输入第二个数'))\r\n q=input('请输入需要的操作:加减乘除')\r\n if q=='加':\r\n result=add(a,b)\r\n elif q=='减':\r\n result=minus(a,b)\r\n elif q==\"乘\":\r\n result=cheng(a,b)\r\n elif q=='除':\r\n result=div(a,b)\r\n print('结果是',result)\r\nelif q2=='2':\r\n k=int(input('请输入您需要输出的行数'))\r\n j=int(input('请输入您需要输出的列数'))\r\n result=biao(k,j)\r\n print(result)\r\nelif q2=='3':\r\n s=input('请输入需要编码的字符:')\r\n result=encode(s)\r\n print(result)\r\n result2=decode(result)\r\n print(result2)\r\n\r\n","repo_name":"Bankrotteur/test-first-try","sub_path":"函数定义.py","file_name":"函数定义.py","file_ext":"py","file_size_in_byte":2095,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"6381314246","text":"from django.urls import path\nfrom . import views \nfrom django.conf import settings\nfrom django.conf.urls.static import static\nurlpatterns = [\n path('', views.admin_index, name='admin_index'),\n\n path('form_employee/' , views.register_view_emoloyee , name ='form_employee'),\n\n path('form_officer/' , views.register_view_officer , name ='form_officer'),\n\n path('form_driver/' , views.register_view_driver , name ='form_driver'),\n\n path('form_vehicle/' , views.register_view_vehicle , name ='form_vehicle'),\n\n path('Edit_Company_Info/' , views.edit_company_info , name='form_Company_info'),\n\n path('Edit_slider/' , views.edit_slider , name='edit_slider'),\n \n path('Add_serice/' , views.add_service , name='add_service'),\n\n path('officer/' , views.officer , name='officer'),\n \n path('edit_registry//', views.edit_registry, name='edit_registry'),\n \n path('inbox/', views.inbox_view, name='inbox_view'),\n \n]\nurlpatterns += static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)","repo_name":"KaleabHegie/Vehicle_management","sub_path":"Sys_admin/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1213,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"31148286989","text":"#http://codeforces.com/contest/1065/problem/B\n\nimport math\n\nn,m=[int(x) for x in input().split()]\n\n\nx=(1+math.sqrt(1+8*m))/2 #(x*x-1)/2=m\nnot_isolated=math.ceil(x)\nmaximum=n-not_isolated\nminimum=n-2*m #pairing 2 vertices for each m \nif(minimum<0):\n\tminimum=0\n\nif(minimum>maximum):\n\tmaximum=minimum\nprint(minimum,maximum)","repo_name":"thecodearrow/100-Days-Of-Code","sub_path":"Vasya and Isolated Vertices.py","file_name":"Vasya and Isolated Vertices.py","file_ext":"py","file_size_in_byte":321,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"81"} +{"seq_id":"17272753026","text":"\"\"\"\nHogwartsCode - 当前Project名称;\nanimal - 在创建文件的对话框中指定的文件名;\ngalaxy - 当前用户名;\n2021/2/10 5:04 下午 \n\"\"\"\n# 动物 父类\nclass Animal:\n name = ''\n color = ''\n leg_num = ''\n\n def __init__(self,**kargs):\n self.name = kargs[\"name\"]\n self.color = kargs[\"color\"]\n self.leg_num = kargs[\"leg_num\"]\n\n def run(self):\n print(f\"{self.name}在用{self.leg_num}条腿奔跑\")\n\n def walk(self):\n print(f\"{self.name}在用{self.leg_num}条腿走路\")\n\n def eat(self,food):\n print(f\"{self.name}在吃{food}\")\n\n# 实例化一个子类\npig = Animal(name = '猪',color = 'pink', leg_num = 4)\npig.run()\nprint(f'{pig.name}的颜色是{pig.color}')\npig.eat('苹果')\n\n# 实例化一个子类\npenguin = Animal(name = '企鹅', leg_num = 2,color = '黑白相间')\npenguin.walk()\nprint(f'{penguin.name}的颜色是{penguin.color}')\npenguin.eat('鱼')\n","repo_name":"Jammy0624/HogwartsCode","sub_path":"second_python/work1/animal.py","file_name":"animal.py","file_ext":"py","file_size_in_byte":936,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"3980537751","text":"def counting_valley(pattern):\n\n # valley steps below sea level, starting with a step down from sea level and ending with a step up to sea level.\n # starting from level = 0; as hike is starting from sea level A/Q\n level = valley = 0 \n\n for x in pattern:\n\n # if its \"U\" then increse the level\n if x == \"U\":\n level += 1\n\n # other-wise if it's \"D\" and level = 0 increase the valley by one, as A/Q valley starting with\n # step down and ending at sea level\n elif x == \"D\":\n if level == 0:\n valley += 1\n\n # if level is not equals zero, it means we are goind below sea level so, level should\n # be decresed by one.\n level -= 1\n\n return valley\n\nif __name__ == '__main__':\n n = int(input(\"Enter the length of array: \"))\n pattern = input(\"Enter the pattern in Caps letter: \")\n ans =counting_valley(pattern)\n print(ans)\n \n","repo_name":"AnshumanSinghh/Updated-Code-Practice","sub_path":"Code_for_wipro/hill_prblm.py","file_name":"hill_prblm.py","file_ext":"py","file_size_in_byte":946,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"40378034584","text":"import os\nimport os.path\nimport glob\nimport argparse\nfrom util import *\n\nargs = None\n\nbegintext = '''/// -------------------------------------------------------------------------------\n/// THIS FILE IS ORIGINALLY GENERATED BY redis2go.py.\n/// PLEASE DO NOT MODIFY THIS FILE.\n/// -------------------------------------------------------------------------------'''\n\ndef get_template_file_content(key_type):\n filename = {\"s\":\"template_string\", \"i\":\"template_int\", \"u\":\"template_uint\"}\n content = get_file_content(filename[key_type[0]])\n return content\n\ndef dofile(filename, content):\n print(\"file: \", filename)\n packagename, beginpos = get_word(content, \"package\", \";\")\n classname, beginpos = get_word(content, \"message\", \"\\n\", beginpos)\n key_type, beginpos = get_word(content, \"{\", \"id\", beginpos)\n key_prefix = classname\n print(\" \", \"packagename:\", packagename)\n print(\" \", \"classname:\", classname)\n print(\" \", \"key_type:\", key_type)\n template = get_template_file_content(key_type)\n template = template.replace(\"{{packagename}}\", packagename)\n template = template.replace(\"{{classname}}\", classname)\n template = template.replace(\"{{key_type}}\", key_type)\n template = template.replace(\"{{key_prefix}}\", key_prefix)\n \n template = \"%s\\n\\n%s\" % (begintext, template)\n \n \n set_file_content(\"%s/RD_%s.go\"%(args.go_out, classname),template)\n print(\"\")\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description='redis2go',formatter_class=argparse.RawDescriptionHelpFormatter)\n parser.add_argument(\"--proto_path\", default=\"../example/proto\", help=\"proto path\", type=str)\n parser.add_argument(\"--go_out\", default=\"../example\", help=\"out path\", type=str)\n\n args = parser.parse_args()\n\n for dir, _, _ in os.walk(args.proto_path):\n filenames = glob.glob( dir + '/*.proto')\n for filename in filenames:\n f = open(filename, 'rt')\n content = f.read()\n f.close()\n dofile(filename, content)\n print(\"done.\")\n\n","repo_name":"fananchong/go-redis-orm","sub_path":"tool/redis2go.py","file_name":"redis2go.py","file_ext":"py","file_size_in_byte":2048,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"81"} +{"seq_id":"69962816905","text":"# -*- coding:utf-8 -*-\n# 密码加密KEY key 1023 -1024\nENCRYPT_KEY_VALUE = 1\n# 文件管理权限set\n# HOME_FILE_MANAGER_PERMISSIONS = (['home_backupfiledir_download', 'home_backupfiledir_upload', 'home_backupfiledir_show'\n# 'home_linuxdownloadfiledir_download', 'home_linuxdownloadfiledir_download',\n# 'home_linuxdownloadfiledir_show'\n# 'home_uploadfiledir_download', 'home_uploadfiledir_upload',\n# 'home_uploadfiledir_show'])\nHOME_FILE_SHOW_PERMISSIONS = (['backupfiledir', 'linuxdownloadfiledir', 'uploadfiledir'])\nHOME_FILE_SHOW_DICT = {'backupfiledir': '备份文件', 'linuxdownloadfiledir': '服务器下载文件', 'uploadfiledir': '上传文件'}\n","repo_name":"xuanqisong/minxinyunwei","sub_path":"Tools/global_value.py","file_name":"global_value.py","file_ext":"py","file_size_in_byte":797,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"73720966025","text":"from tkinter import *\nfrom component import component\n\ncomponents = {}\nlbl_components = {}\n\n# functions:\n\ndef onSubmit(*args):\n\n\tnumber = inp_number.get()\n\tdescription = inp_descr.get()\n\n\tif number not in components:\n\n\t\tinp_number.delete(0, 'end')\n\t\tinp_descr.delete(0, 'end')\n\n\t\tinp_number.focus()\n\n\t\tcomponents[number] = component(number, description)\n\n\t\ti = 3\n\n\t\tfor key in components:\n\t\t\tprint(components[key].number + \" - \" + components[key].description)\n\t\t\tif key in lbl_components:\n\t\t\t\tlbl_components[key].grid_forget()\n\t\t\telse:\n\t\t\t\tlbl_components[key] = Label(frame_add, text = components[key].number + \" - \" + components[key].description)\n\t\t\tlbl_components[key].grid(row=i, column=0, columnspan=2)\n\t\t\ti += 1\n\telse:\n\t\tprint(\"Error: Part Number Already Exists!\")\n\n\n\ndef createFrameAdd(*args):\n\n\t# create frames:\n\tframe_add = Tk()\n\tframe_add.title(\"Add Frame\")\n\tframe_add.bind('',onSubmit)\n\n\t# create widgets:\n\n\t# Number input field\n\tlbl_number = Label(frame_add, text=\"Number:\")\n\tlbl_number.grid(row=0, column=0)\n\tinp_number = Entry(frame_add, width=25)\n\tinp_number.grid(row=0, column=1)\n\tinp_number.focus()\n\n\t# Description input field\n\tlbl_descr = Label(frame_add, text=\"Description:\")\n\tlbl_descr.grid(row=1, column=0)\n\tinp_descr = Entry(frame_add, width=25)\n\tinp_descr.grid(row=1, column=1)\n\n\tmyButton = Button(frame_add, width = 10, text=\"Submit\", command=onSubmit)\n\tmyButton.grid(row=2, column=0)\n\nprint(\"test1\")\n\n\n# mount frames:\n# frame_add.mainloop()\n\n","repo_name":"DaveBruwer/DFM_Back_End","sub_path":"AddFrame.py","file_name":"AddFrame.py","file_ext":"py","file_size_in_byte":1474,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"4215541617","text":"#!/usr/bin/env python3\nimport numpy as np\nfrom scipy.linalg import expm\nfrom lab4_header import *\nimport math\n\n\"\"\"\nUse 'expm' for matrix exponential.\nAngles are in radian, distance are in meters.\n\"\"\"\ndef Get_MS():\n # =================== Your code starts here ====================#\n # Fill in the correct values for a1~6 and q1~6, as well as the M matrix\n M = np.eye(4)\n S = np.zeros((6,6))\n\n M = np.array([[0, -1, 0, .390],\n [0, 0, -1, .401],\n [1, 0, 0, .2155],\n [0, 0, 0, 1]])\n\n S = np.array([[0, 0, 1, .150, .150, 0],\n [0, 1, 0, -.162, 0, -.150],\n [0, 1, 0, -.162, 0, .094],\n [0, 1, 0, -.162, 0, .307],\n [1, 0, 0, 0, .162, -.260],\n [0, 1 ,0 , -.162, 0, .390]])\n # ==============================================================#\n return M, S\n\n\"\"\"\nFunction that calculates encoder numbers for each motor\n\"\"\"\ndef lab_fk(theta1, theta2, theta3, theta4, theta5, theta6):\n\n # Initialize the return_value\n return_value = [None, None, None, None, None, None]\n\n #print(\"Foward kinematics calculated:\\n\")\n\n # =================== Your code starts here ====================#\n theta = np.array([theta1,theta2,theta3,theta4,theta5,theta6])\n T = np.eye(4)\n\n M, S = Get_MS()\n\n # Rearranging Screw Axis\n d_S = {}\n S = S.T\n for i in range(6):\n d_S[i] = np.array([[0, -S[2,i], S[1,i], S[3,i]],\n [S[2,i], 0, -S[0,i], S[4,i]],\n [-S[1,i], S[0,i], 0, S[5,i]],\n [0, 0, 0, 0]])\n\n\n# Forward Kinematics Eqn\n Tb = {}\n theta= np.array([theta1, theta2, theta3, theta4, theta5, theta6])\n for i in range(6):\n Tb[i] = expm(d_S[i]*theta[i])\n\n T = Tb[0]@Tb[1]@Tb[2]@Tb[3]@Tb[4]@Tb[5]@M\n\n\n # ==============================================================#\n\n print(\"pose of the tool is \\n\", str(T) + \"\\n\")\n\n return_value[0] = theta1 + PI\n return_value[1] = theta2\n return_value[2] = theta3\n return_value[3] = theta4 - (0.5*PI)\n return_value[4] = theta5\n return_value[5] = theta6\n\n return return_value\n\n\n\"\"\"\nFunction that calculates an elbow up Inverse Kinematic solution for the UR3\n\"\"\"\ndef lab_invk(xWgrip, yWgrip, zWgrip, yaw_WgripDegree):\n # =================== Your code starts here ====================#\n L1 = 0.152\n L2 = 0.120\n L3 = 0.244\n L4 = 0.093\n L5 = 0.213\n L6 = 0.083\n L7 = 0.083\n L8 = 0.082\n L9 = 0.0535\n L10 = 0.059\n\n theta1 = 0.0\n theta2 = 0.0\n theta3 = 0.0\n theta4 = 0.0\n theta5 = -np.pi/2\n theta6 = 0.0\n yaw_radians = yaw_WgripDegree * np.pi/180\n\n # =================== Your code starts here ====================#\n\n x_grip = xWgrip + 0.15\n y_grip = yWgrip - 0.15\n z_grip = zWgrip - 0.01\n\n\n x_cen = x_grip-L9*math.cos(yaw_radians)\n y_cen = y_grip-L9*math.sin(yaw_radians)\n z_cen = z_grip\n\n\n theta1 = math.atan2(y_cen, x_cen) - math.asin((L2-L4+L6)/((x_cen**2+y_cen**2)**0.5))\n\n theta6 = np.pi/2 - yaw_radians + theta1\n\n\n x_3end = x_cen - L7*math.cos(theta1) + (L6+0.027)*math.sin(theta1)\n y_3end = y_cen - L7*math.sin(theta1) - (L6+0.027)*math.cos(theta1)\n z_3end = z_cen + L10 + L8\n\n\n La = (x_3end**2+y_3end**2)**0.5\n Lb = z_3end-L1\n theta3 = np.pi - math.acos((L3**2+L5**2-Lb**2-La**2) / (2*L3*L5))\n\n alpha = math.acos((La**2 + Lb**2 + L1**2 - (z_3end**2+La**2))/(2*(La**2+Lb**2)**0.5*L1))\n beta = math.acos((La**2 + Lb**2 + L3**2 - L5**2)/(2*(La**2+Lb**2)**0.5*L3))\n\n \n theta2 = np.pi/2 - alpha - beta\n theta4 = -(theta2 + theta3)\n\n\n theta1_d = theta1*180/np.pi\n theta2_d = theta2*180/np.pi\n theta3_d = theta3*180/np.pi\n theta4_d = theta4*180/np.pi\n theta5_d = theta5*180/np.pi\n theta6_d = theta6*180/np.pi\n\n print(\"Theta is\", theta1_d, theta2_d, theta3_d, theta4_d, theta5_d, theta6_d)\n # ==============================================================#\n return lab_fk(theta1, theta2, theta3, theta4, theta5, theta6)\n","repo_name":"damanidevansh/ECE470-Intro-to-Robotics","sub_path":"lab4_func.py","file_name":"lab4_func.py","file_ext":"py","file_size_in_byte":4056,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"40293345401","text":"import numpy as np\r\nfrom sg_classes import SGFile\r\nimport math\r\nimport trk_exporter\r\nfrom utils import approx_curve_length, sg_ground_to_trk, convert_wall_fsect_type, isclockwise\r\n\r\nclass TRKFile:\r\n def __init__(self, header, xsect_dlats, sect_offsets, xsect_data, ground_data, sects):\r\n # Import sections of the TRK file\r\n self.header = header\r\n self.xsect_dlats = xsect_dlats\r\n self.sect_offsets = sect_offsets\r\n self.xsect_data = xsect_data\r\n self.ground_data = ground_data\r\n self.sects = sects\r\n\r\n # Derived information\r\n self.trklength = self.header[2]\r\n self.num_xsects = self.header[3]\r\n self.num_sects = self.header[4]\r\n self.sect_data_bytes = self.header[6]\r\n\r\n # extent section offsets\r\n self.sect_offsets.append(int(self.sect_data_bytes / 4))\r\n\r\n # Process ground data\r\n self.ground_data2 = []\r\n for i in range(0, self.num_sects):\r\n self.ground_data2.append(self.ground_data[self.sects[i].ground_counter:self.sects[i].ground_counter + self.sects[i].ground_fsects])\r\n for i in range(0, self.num_sects):\r\n for j in range(0, self.sects[i].ground_fsects):\r\n self.sects[i].ground_type.append(self.ground_data2[i][j][2])\r\n self.sects[i].ground_dlat_start.append(self.ground_data2[i][j][0])\r\n self.sects[i].ground_dlat_end.append(self.ground_data2[i][j][1])\r\n\r\n # Process xsect data\r\n xsect_counter = 0\r\n for sect in range(0, self.num_sects):\r\n for _ in range(0, self.num_xsects):\r\n grade1, grade2, grade3, alt, grade4, grade5, pos1, pos2 = self.xsect_data[xsect_counter]\r\n self.sects[sect].grade1.append(grade1)\r\n self.sects[sect].grade2.append(grade2)\r\n self.sects[sect].grade3.append(grade3)\r\n self.sects[sect].grade4.append(grade4)\r\n self.sects[sect].grade5.append(grade5)\r\n self.sects[sect].alt.append(alt)\r\n self.sects[sect].pos1.append(pos1)\r\n self.sects[sect].pos2.append(pos2)\r\n xsect_counter += 1\r\n\r\n @classmethod\r\n def from_trk(cls, file_name):\r\n arr = np.fromfile(file_name, dtype=np.int32)\r\n \r\n # Read header\r\n header = arr[:7]\r\n file_type, version, track_length, num_xsects, num_sects, fsects_bytes, sect_data_bytes = header\r\n\r\n # Read xsects\r\n xsect_dlats = arr[7:17] \r\n \r\n # Calculate and write section offsets\r\n sect_offsets_end = 17 + num_sects\r\n sect_offsets = arr[17:sect_offsets_end].tolist()\r\n sect_offsets = [int(x / 4) for x in sect_offsets]\r\n sect_offsets.append(int(sect_data_bytes / 4))\r\n \r\n # Xsect data\r\n xsect_data_end = sect_offsets_end + 8 * num_sects * num_xsects\r\n xsect_data = arr[sect_offsets_end:xsect_data_end]\r\n xsect_data = xsect_data.reshape((num_sects * num_xsects, 8))\r\n\r\n # fsects ground\r\n fsects_data_end = int(xsect_data_end + fsects_bytes / 4)\r\n ground_data = arr[xsect_data_end:fsects_data_end].reshape((-1, 3))\r\n\r\n # section data\r\n sects_data = arr[fsects_data_end:]\r\n\r\n # convert to Sects object\r\n sects = []\r\n for i in range(num_sects):\r\n sect_start = sect_offsets[i]\r\n sect_end = sect_offsets[i + 1]\r\n sec_data = sects_data[sect_start:sect_end]\r\n sects.append(cls.Section(sec_data, num_xsects))\r\n \r\n return cls(header, xsect_dlats, sect_offsets, xsect_data, ground_data, sects)\r\n \r\n @classmethod\r\n def from_sg(cls, file_name):\r\n\r\n # Load the file and do initial set up\r\n sgfile = SGFile.from_sg(file_name)\r\n num_sects = sgfile.num_sects\r\n num_xsects = sgfile.num_xsects\r\n\r\n # Fix sang and eang for straight sections\r\n for sect in range(1, num_sects):\r\n if sgfile.sects[sect].type == 1 and sgfile.sects[sect-1].type == 1:\r\n sgfile.sects[sect].sang1 = sgfile.sects[sect-1].sang1\r\n sgfile.sects[sect].sang2 = sgfile.sects[sect-1].sang2\r\n sgfile.sects[sect].eang1 = sgfile.sects[sect-1].eang1\r\n sgfile.sects[sect].eang2 = sgfile.sects[sect-1].eang2\r\n\r\n # make headings\r\n headings = []\r\n headings_rad = []\r\n\r\n for sect in range(0, num_sects):\r\n\r\n sec = sgfile.sects[sect]\r\n\r\n if sec.type == 1:\r\n d_x = sec.end_x - sec.start_x\r\n d_y = sec.end_y - sec.start_y\r\n heading = math.atan2(d_y,d_x) / math.pi * 2**31\r\n\r\n headings_rad.append(math.atan2(d_y,d_x))\r\n\r\n if heading == 2**31: heading = -(2**31)\r\n headings.append(round(heading))\r\n\r\n elif sec.type == 2:\r\n svec_x = sec.start_x - sec.center_x\r\n svec_y = sec.start_y - sec.center_y\r\n evec_x = sec.end_x - sec.center_x\r\n evec_y = sec.end_y - sec.center_y\r\n start_angle = math.atan2(svec_y, svec_x)\r\n end_angle = math.atan2(evec_y, evec_x)\r\n \r\n if isclockwise(start_angle, end_angle):\r\n heading = start_angle - math.pi/2\r\n else:\r\n heading = start_angle + math.pi/2\r\n \r\n headings_rad.append(heading)\r\n\r\n heading = round(heading / math.pi * 2**31)\r\n headings.append(heading)\r\n\r\n # Section 2 - Xsect DLATs\r\n xsect_dlats = np.pad(sgfile.xsect_dlats, (0, 10 - len(sgfile.xsect_dlats)), 'constant')\r\n\r\n # Section 4 - Xsect\r\n xsect_data = []\r\n for sect in range(0,num_sects):\r\n \r\n if sect == 0: # Adjust for SG file has alt and grade at end of section\r\n prev_sect = num_sects - 1\r\n else:\r\n prev_sect = sect - 1\r\n\r\n for xsect in range(0,num_xsects):\r\n begin_alt = sgfile.sects[prev_sect].alt[xsect]\r\n end_alt = sgfile.sects[sect].alt[xsect]\r\n sg_length = sgfile.sects[sect].length\r\n cur_slope = sgfile.sects[prev_sect].grade[xsect]/8192\r\n next_slope = sgfile.sects[sect].grade[xsect]/8192\r\n \r\n grade1 = round((2 * begin_alt/sg_length + cur_slope + next_slope - 2 * end_alt/sg_length) * sg_length)\r\n grade2 = round((3 * end_alt/sg_length - 3 * begin_alt/sg_length - 2 * cur_slope - next_slope) * sg_length)\r\n grade3 = round(cur_slope * sg_length)\r\n grade4 = grade1 * 3\r\n grade5 = grade2 * 2\r\n\r\n if sgfile.sects[sect].type == 2:\r\n pos1 = sgfile.sects[sect].radius - sgfile.xsect_dlats[xsect]\r\n pos2 = -858993460\r\n else:\r\n # straight section\r\n x = sgfile.sects[sect].start_x\r\n y = sgfile.sects[sect].start_y\r\n\r\n angle = headings_rad[sect] + math.pi/2\r\n d = sgfile.xsect_dlats[xsect]\r\n\r\n pos1 = round(x + d * math.cos(angle)) \r\n pos2 = round(y + d * math.sin(angle))\r\n\r\n xsect_data.extend([grade1,grade2, grade3,begin_alt, grade4, grade5,pos1,pos2])\r\n \r\n xsect_data = np.array(xsect_data)\r\n xsect_data = xsect_data.reshape((num_sects * num_xsects, 8))\r\n\r\n # Section 5 - fsect ground\r\n ground_data = []\r\n for sect in range(0, num_sects):\r\n for fsect in range(0, sgfile.sects[sect].num_ground_fsects):\r\n ground_data.extend([sgfile.sects[sect].ground_fstart[fsect], sgfile.sects[sect].ground_fend[fsect], sg_ground_to_trk(sgfile.sects[sect].ground_ftype[fsect])])\r\n\r\n len_ground_data = len(ground_data)\r\n\r\n ground_data = np.array(ground_data)\r\n ground_data = ground_data.reshape((-1, 3))\r\n\r\n # Section 6 - sections\r\n\r\n # Identify the two xsects that surround the center line\r\n for xsect in range(0, num_xsects):\r\n if sgfile.xsect_dlats[xsect] < 0 and sgfile.xsect_dlats[xsect + 1] >= 0:\r\n rxsect = xsect\r\n lxsect = xsect + 1\r\n\r\n # Calculate centerline (DLAT = 0) alt and grade\r\n cline_pct = -sgfile.xsect_dlats[rxsect] / (sgfile.xsect_dlats[lxsect] - sgfile.xsect_dlats[rxsect])\r\n\r\n cline_alt = []\r\n cline_grade = []\r\n adj_length = []\r\n\r\n for sect in range(0, num_sects):\r\n cline_alt.append(sgfile.sects[sect].alt[rxsect] + cline_pct * (sgfile.sects[sect].alt[lxsect] - sgfile.sects[sect].alt[rxsect]))\r\n cline_grade.append(sgfile.sects[sect].grade[rxsect] + cline_pct * (sgfile.sects[sect].grade[lxsect] - sgfile.sects[sect].grade[rxsect]))\r\n\r\n # Calculate grades for the centerline and calculate adjusted lengths\r\n\r\n for sect in range(0,num_sects):\r\n if sect == 0: # Adjust for SG file has alt and grade at end of section\r\n prev_sect = num_sects - 1\r\n else:\r\n prev_sect = sect - 1\r\n\r\n begin_alt = cline_alt[prev_sect]\r\n end_alt = cline_alt[sect]\r\n sg_length = sgfile.sects[sect].length\r\n cur_slope = cline_grade[prev_sect]/8192\r\n next_slope = cline_grade[sect]/8192\r\n \r\n grade1 = round((2 * begin_alt/sg_length + cur_slope + next_slope - 2 * end_alt/sg_length) * sg_length)\r\n grade2 = round((3 * end_alt/sg_length - 3 * begin_alt/sg_length - 2 * cur_slope - next_slope) * sg_length)\r\n grade3 = round(cur_slope * sg_length)\r\n\r\n adj_length.append(round(approx_curve_length(grade1, grade2, grade3, cline_alt[sect], sg_length)))\r\n\r\n # Calculate new DLONGs\r\n\r\n start_dlong = [0]\r\n\r\n for sect in range(1,num_sects):\r\n start_dlong.append(start_dlong[sect-1]+adj_length[sect-1])\r\n\r\n # First section\r\n\r\n\r\n\r\n # Fix straight sections\r\n for sect in range(1, num_sects):\r\n if sgfile.sects[sect].type == 1 and sgfile.sects[sect-1].type == 1:\r\n headings[sect] = headings[sect-1]\r\n\r\n ang1s = []\r\n ang2s = []\r\n ang3s = []\r\n ang4s = []\r\n ang5s = []\r\n\r\n for sect in range(0, num_sects):\r\n heading_rad = headings[sect]/(2**31) * math.pi\r\n heading_sin = -math.sin(heading_rad)\r\n heading_cos = math.cos(heading_rad)\r\n\r\n if sgfile.sects[sect].type == 1:\r\n ang3 = (2**30 * heading_sin)\r\n ang4 = (heading_cos * 2**30)\r\n ang5 = (2**30 - 2 * (2**30 - sgfile.sects[sect].length/adj_length[sect] * 2**30))\r\n ang2 = -ang3 - (-ang3 + heading_sin * ang5) / 2\r\n ang1 = ang4 - (ang4 - (heading_cos * ang5)) / 2\r\n elif sgfile.sects[sect].type == 2:\r\n ang1 = sgfile.sects[sect].center_x\r\n ang2 = sgfile.sects[sect].center_y\r\n\r\n if sect == num_sects - 1:\r\n ang3 = (headings[0] - headings[sect])/2\r\n else:\r\n ang3 = (headings[sect+1] - headings[sect])/2\r\n \r\n if ang3 < -2**30: \r\n ang3 = 2**31 + ang3\r\n if ang3 > 2**30: \r\n ang3 = ang3 - 2**31\r\n\r\n ang4 = -858993460\r\n ang5 = -858993460\r\n\r\n ang1s.append(ang1)\r\n ang2s.append(ang2)\r\n ang3s.append(ang3)\r\n ang4s.append(ang4)\r\n ang5s.append(ang5)\r\n\r\n # Counters\r\n xsect_counter = []\r\n for i in range(0, num_sects):\r\n xsect_counter.append(i * num_xsects)\r\n\r\n ground_counter = []\r\n for sect in range(0, num_sects):\r\n if sect == 0: \r\n ground_counter.append(0)\r\n else:\r\n ground_counter.append(sgfile.sects[sect-1].num_ground_fsects + ground_counter[sect-1])\r\n\r\n # Now write to list\r\n sects = []\r\n for sect in range(num_sects):\r\n sec_data = [sgfile.sects[sect].type, \r\n start_dlong[sect],\r\n adj_length[sect], \r\n headings[sect], \r\n ang1s[sect], \r\n ang2s[sect],\r\n ang3s[sect],\r\n ang4s[sect],\r\n ang5s[sect],\r\n xsect_counter[sect],\r\n sgfile.sects[sect].num_ground_fsects,\r\n ground_counter[sect],\r\n sgfile.sects[sect].num_boundaries]\r\n\r\n for i in range(0, sgfile.sects[sect].num_boundaries):\r\n walltype = convert_wall_fsect_type(sgfile.sects[sect].bound_ftype1[i], sgfile.sects[sect].bound_ftype2[i])\r\n sec_data.extend([walltype,\r\n sgfile.sects[sect].bound_fstart[i],\r\n sgfile.sects[sect].bound_fend[i],\r\n -858993460,\r\n -858993460])\r\n sects.append(cls.Section(sec_data, num_xsects))\r\n\r\n # Section 3 calculate section offsets\r\n sect_offsets = [0]\r\n for sect in range(1, num_sects):\r\n section_length = 13 + 5 * sgfile.sects[sect-1].num_boundaries\r\n sect_offsets.append(sect_offsets[sect - 1] + section_length)\r\n\r\n len_sects = sect_offsets[-1] + 13 + 5 * sgfile.sects[num_sects - 1].num_boundaries\r\n\r\n # Section 1 header\r\n header = [1414676811,\r\n 1,\r\n sum(adj_length),\r\n num_xsects,\r\n num_sects,\r\n len_ground_data * 4,\r\n len_sects * 4\r\n ]\r\n\r\n return cls(header, xsect_dlats, sect_offsets, xsect_data, ground_data, sects) \r\n \r\n class Section:\r\n def __init__(self, sec_data, num_xsects):\r\n self.type = sec_data[0]\r\n self.start_dlong = sec_data[1]\r\n self.length = sec_data[2]\r\n self.heading = round(sec_data[3])\r\n self.ang1 = round(sec_data[4])\r\n self.ang2 = round(sec_data[5])\r\n self.ang3 = round(sec_data[6])\r\n self.ang4 = round(sec_data[7])\r\n self.ang5 = round(sec_data[8])\r\n self.xsect_counter = sec_data[9]\r\n self.ground_fsects = sec_data[10]\r\n self.ground_counter = sec_data[11]\r\n self.num_bounds = sec_data[12]\r\n\r\n self.ground_type = []\r\n self.ground_dlat_start = []\r\n self.ground_dlat_end = []\r\n\r\n self.bound_type = []\r\n self.bound_dlat_start = []\r\n self.bound_dlat_end = []\r\n\r\n self.grade1 = []\r\n self.grade2 = []\r\n self.grade3 = []\r\n self.grade4 = []\r\n self.grade5 = []\r\n self.alt = []\r\n self.pos1 = []\r\n self.pos2 = []\r\n\r\n\r\n for bound in range(0,self.num_bounds):\r\n bound_start = 13 + bound * 5\r\n self.bound_type.append(sec_data[bound_start])\r\n self.bound_dlat_start.append(sec_data[bound_start + 1])\r\n self.bound_dlat_end.append(sec_data[bound_start + 2]) \r\n","repo_name":"skchow03/icr2_sg","sub_path":"trk_classes.py","file_name":"trk_classes.py","file_ext":"py","file_size_in_byte":15579,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"1980261910","text":"total_points = 0\nwith open('4input.txt','r') as f:\n for line in f:\n line = line.replace(' ', ' ')\n winning_nums = line.split('|')[0].split(':')[1].strip().split(' ')\n play_nums = line.split('|')[1].strip().split(' ')\n total_wins = [num for num in play_nums if num in winning_nums]\n game_points = int(pow(2,len(total_wins)- 1)) \n total_points += game_points\nprint(total_points)","repo_name":"ewolden/adventofcode","sub_path":"2023/4/4a.py","file_name":"4a.py","file_ext":"py","file_size_in_byte":422,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"40134772505","text":"# Created by Egor Kostan.\n# GitHub: https://github.com/ikostan\n# LinkedIn: https://www.linkedin.com/in/egor-kostan/\n\nimport allure\nimport unittest\n\nfrom tests.config import Config\nfrom utils.register_user import register_user\nfrom utils.clean_database import clean_database\nfrom utils.screenshot import screenshot_on_fail\nfrom utils.open_web_browser import open_web_browser\nfrom utils.step_definition import step_definition\n\nfrom page_object_models.home_page_model import HomePageModel\nfrom expected_results.users.base_user import BaseUser\nfrom expected_results.users.valid_users_templates.jane_doe import JaneDoe\nfrom expected_results.page_content.home_page_content import HomePageContent\nfrom expected_results.page_content.bank_account_content import BankAccountContent\n\n\n@allure.epic('Page Functionality')\n@allure.parent_suite('End To End')\n@allure.suite(\"User Login/Logout\")\n@allure.sub_suite(\"Positive Tests\")\n@allure.feature(\"Home Page\")\n@allure.story('Login/Logout Functionality')\n@screenshot_on_fail()\nclass TestUserLoginFromHomePage(unittest.TestCase):\n\n\t@classmethod\n\tdef setUpClass(cls):\n\t\tcls.user = BaseUser(JaneDoe)\n\t\tcls.page_model = HomePageModel\n\t\tcls.page_context = HomePageContent\n\t\tcls.config = Config()\n\n\t\twith allure.step(\"Initial data setup > clean DB\"):\n\t\t\tclean_database(config=cls.config)\n\n\t\twith allure.step(\"Initial data setup > register test user\"):\n\t\t\tregister_user(user=cls.user, config=cls.config)\n\n\t\twith allure.step(\"Open web browser\"):\n\t\t\tcls.page = open_web_browser(config=cls.config,\n\t\t\t page_model=cls.page_model,\n\t\t\t page_content=cls.page_context)\n\n\t@classmethod\n\tdef tearDownClass(cls):\n\t\twith allure.step(\"Close web browser\"):\n\t\t\tif cls.page:\n\t\t\t\tcls.page.quit()\n\t\t\t\tcls.page = None\n\n\tdef test_user_login_logout(self):\n\t\tallure.dynamic.description(\"\"\"\n\t\t\t\tUser Log In validation > Login from Home page:\n\t\t\t\t\t1. Open Home web page\n\t\t\t\t\t2. Do URL verification\n\t\t\t\t\t3. Do Title verification\n\t\t\t\t\t4. Type username/password\n\t\t\t\t\t5. Hit \"Log In\" button\n\t\t\t\t\t6. Verify \"Welcome\" message\n\t\t\t\t\t7. Verify that \"Account Services\" menu is present\n\t\t\t\t\t8. Do URL verification\n\t\t\t\t\t9. Log Out\n\t\t\t\t\t10. Do URL verification\n\t\t\t\t\t11. Verify that \"Account Services\" menu is not present\n\t\t\t\t\t12. Verify web page title\n\t\t\t\t\t13. Close web browser\n\t\t\t\t\"\"\")\n\t\tallure.dynamic.title(\"Home page > User Log In validation > Positive test\")\n\t\tallure.dynamic.severity(allure.severity_level.BLOCKER)\n\n\t\tstep_definition(self,\n\t\t step_description='Type Username > Verify Username value',\n\t\t expected=self.user.username,\n\t\t actual=self.page.username,\n\t\t act=self.page.enter_username,\n\t\t click=False)\n\t\t'''\n\t\twith allure.step('Type Username'):\n\t\t\texpected = self.user.username\n\t\t\tself.page.enter_username(expected)\n\n\t\t\twith allure.step('Verify Username value'):\n\t\t\t\tactual = self.page.username()\n\t\t\t\tprint('\\nStep: {}\\nExpected: {}\\nActual: {}'.format('Verify Username value',\n\t\t\t\t expected,\n\t\t\t\t actual))\n\t\t\t\tself.assertEqual(expected,\n\t\t\t\t actual,\n\t\t\t\t msg=\"Expected <{}> value does not equal actual <{}> result\".format(expected,\n\t\t\t\t actual))\n\t\t'''\n\n\t\tstep_definition(self,\n\t\t step_description='Type Password > Verify Password value',\n\t\t expected=self.user.password,\n\t\t actual=self.page.password,\n\t\t act=self.page.enter_password,\n\t\t click=False)\n\t\t'''\n\t\twith allure.step('Type Password'):\n\t\t\texpected = self.user.password\n\t\t\tself.page.enter_password(expected)\n\n\t\t\twith allure.step('Verify Password value'):\n\t\t\t\tactual = self.page.password()\n\t\t\t\tprint('\\nStep: {}\\nExpected: {}\\nActual: {}'.format('Verify Password value',\n\t\t\t\t expected,\n\t\t\t\t actual))\n\t\t\t\tself.assertEqual(expected,\n\t\t\t\t actual,\n\t\t\t\t msg=\"Expected <{}> value does not equal actual <{}> result\".format(expected,\n\t\t\t\t actual))\n\t\t'''\n\n\t\twith allure.step('Hit Log In button'):\n\t\t\tself.page = self.page.hit_login_button()\n\n\t\tstep_definition(self,\n\t\t step_description='Verify \"Welcome\" message',\n\t\t expected='{}{} {}'.format(BankAccountContent.ACCOUNT_SERVICES_MENU['welcome_message'],\n\t\t self.user.first_name,\n\t\t self.user.last_name),\n\t\t actual=self.page.welcome_message,\n\t\t act=None,\n\t\t click=False)\n\t\t'''\n\t\twith allure.step('Hit Log In button'):\n\t\t\tself.page.hit_login_button()\n\n\t\t# Verify \"Welcome\" message\n\t\twith allure.step('Verify \"Welcome\" message'):\n\t\t\texpected = '{}{} {}'.format(BankAccountContent.ACCOUNT_SERVICES_MENU['welcome_message'],\n\t\t\t self.user.first_name,\n\t\t\t self.user.last_name)\n\t\t\tactual = self.page.welcome_message()\n\t\t\tprint('\\nStep: {}\\nExpected: {}\\nActual: {}'.format('Verify \"Welcome\" message',\n\t\t\t expected,\n\t\t\t actual))\n\t\t\tself.assertEqual(expected,\n\t\t\t actual,\n\t\t\t msg=\"Expected <{}> value does not equal actual <{}> result\".format(expected,\n\t\t\t actual))\n\t\t'''\n\n\t\tstep_definition(self,\n\t\t step_description='Verify that \"Account Services\" menu is present',\n\t\t expected=True,\n\t\t actual=self.page.account_services_menu_is_visible,\n\t\t act=None,\n\t\t click=False)\n\t\t'''\n\t\twith allure.step('Verify that \"Account Services\" menu is present'):\n\t\t\texpected = True\n\t\t\tactual = self.page.account_services_menu_is_visible()\n\t\t\tprint('\\nStep: {}\\nExpected: {}\\nActual: {}'.format('\"Account Services\" menu is present',\n\t\t\t expected,\n\t\t\t actual))\n\t\t\tself.assertEqual(expected,\n\t\t\t actual,\n\t\t\t msg=\"Expected <{}> value does not equal actual <{}> result\".format(expected,\n\t\t\t actual))\n\t\t'''\n\n\t\t# Log Out\n\t\twith allure.step('Hit \"Log Out\" link'):\n\t\t\tself.page = self.page.hit_log_out_button()\n\n\t\t# Post Logout validation\n\t\tstep_definition(self,\n\t\t step_description='Do URL verification',\n\t\t expected= self.config.base_url + HomePageContent.URL,\n\t\t actual=self.page.url,\n\t\t act=None,\n\t\t click=False)\n\t\t'''\n\t\twith allure.step('Hit \"Log Out\" link'):\n\t\t\tself.page.hit_log_out_button()\n\n\t\twith allure.step('Do URL verification'):\n\n\t\t\texpected = 'https://parabank.parasoft.com/parabank/index.htm?ConnType=JDBC'\n\t\t\tactual = self.page.url()\n\t\t\tprint('\\nStep: {}\\nExpected: {}\\nActual: {}'.format('\\'Verify URL\\'',\n\t\t\t expected,\n\t\t\t actual))\n\t\t\tself.assertEqual(expected,\n\t\t\t actual,\n\t\t\t msg=\"Expected <{}> value does not equal actual <{}> result\".format(expected,\n\t\t\t actual))\n\t\t'''\n\n\t\tstep_definition(self,\n\t\t step_description='Verify that \"Account Services\" menu is not shown',\n\t\t expected=False,\n\t\t actual=self.page.account_services_menu_is_visible,\n\t\t act=None,\n\t\t click=False)\n\t\t'''\n\t\twith allure.step('Verify that \"Account Services\" menu is not present'):\n\t\t\texpected = False\n\t\t\tactual = self.page.account_services_menu_is_visible()\n\t\t\tprint('\\nStep: {}\\nExpected: {}\\nActual: {}'.format('\"Account Services\" menu is not present',\n\t\t\t expected,\n\t\t\t actual))\n\t\t\tself.assertEqual(expected,\n\t\t\t actual,\n\t\t\t msg=\"Expected <{}> value does not equal actual <{}> result\".format(expected,\n\t\t\t actual))\n\t\t'''\n\n\t\t# Verify Page Title\n\t\tstep_definition(self,\n\t\t step_description='Verify web page title',\n\t\t expected=HomePageContent.TITLE,\n\t\t actual=self.page.title,\n\t\t act=None,\n\t\t click=False)\n\t\t'''\n\t\twith allure.step(\"Verify web page title. Expected result: {}\".format(HomePageContent.TITLE)):\n\t\t\tself.assertEqual(HomePageContent.TITLE,\n\t\t\t self.page.title())\n\t\t'''\n","repo_name":"ikostan/ParaBankSeleniumAutomation","sub_path":"tests/e2e_tests/login_logout/positive/user_login_from_home_page_test.py","file_name":"user_login_from_home_page_test.py","file_ext":"py","file_size_in_byte":9071,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"81"} +{"seq_id":"7830992908","text":"# -*- coding: utf-8 -*-\n# Objects tracking using SIFT algorithm.\nimport cv2\nimport sys\nimport numpy as np\nfrom PIL import Image, ImageTk\n\nif sys.version_info.major < 3: # for Python 2.x\n import Tkinter as tk\nelse: # for Python 3.x\n import tkinter as tk\n\nclass Application:\n def __init__(self):\n \"\"\" Apply SIFT algorithm to track objects \"\"\"\n self.vs = cv2.VideoCapture(0) # capture video frames, 0 is your default video camera\n self.sift = cv2.xfeatures2d.SIFT_create()\n self.snapshot_image = None # snapshot from the camera\n #self.snapshot_image = cv2.imread(\"2017-06-01_13-06-58.jpg\") # read any image you like\n\n self.root = tk.Tk() # initialize root window\n self.root.title(\"SIFT tracking\") # set window title\n # self.destructor function gets fired when the window is closed\n self.root.protocol(\"WM_DELETE_WINDOW\", self.destructor)\n\n self.panel = tk.Label(self.root) # initialize image panel\n self.panel.pack(padx=10, pady=10)\n\n # create a button, that when pressed, will take current frame\n btn = tk.Button(self.root, text=\"Snapshot!\", command=self.take_snapshot)\n btn.pack(fill=\"both\", expand=True, padx=10, pady=10)\n\n # start a self.video_loop that constantly pools video sensor\n # for the most recently read frame\n self.video_loop()\n\n def video_loop(self):\n \"\"\" Get frame from the video stream and show it in Tkinter \"\"\"\n ok, frame = self.vs.read() # read frame from video stream\n if ok: # frame captured without any errors\n if self.snapshot_image is not None:\n frame = self.sift_matches(self.snapshot_image, frame)\n # convert colors from BGR to RGBA\n cv2image = cv2.cvtColor(frame, cv2.COLOR_BGR2RGBA)\n image = Image.fromarray(cv2image) # convert image for PIL\n imgtk = ImageTk.PhotoImage(image=image) # convert image for tkinter\n self.panel.imgtk = imgtk # anchor imgtk so it does not be deleted by garbage-collector\n self.panel.config(image=imgtk) # show the image\n self.root.after(30, self.video_loop) # call the same function after 30 milliseconds\n\n def sift_matches(self, image1, image2):\n \"\"\" Draw matches between two images according to SIFT algorithm \"\"\"\n try: # sometimes knnMatch and perspectiveTransform methods are throwing an errors\n gray1 = cv2.cvtColor(image1, cv2.COLOR_BGR2GRAY)\n gray2 = cv2.cvtColor(image2, cv2.COLOR_BGR2GRAY)\n keypoints1, descriptor1 = self.sift.detectAndCompute(gray1, None)\n keypoints2, descriptor2 = self.sift.detectAndCompute(gray2, None)\n indexParams = dict(algorithm=0, trees=5)\n searchParams = dict(checks=50) # or pass empty dictionary\n flann = cv2.FlannBasedMatcher(indexParams, searchParams)\n matches = flann.knnMatch(descriptor1, descriptor2, k=2)\n # store all the good matches as per David G. Lowe's ratio test\n good = []\n for m,n in matches:\n if m.distance < 0.75 * n.distance:\n good.append(m)\n if len(good) > 20:\n src_pts = np.float32([keypoints1[m.queryIdx].pt for m in good]).reshape(-1, 1, 2)\n dst_pts = np.float32([keypoints2[m.trainIdx].pt for m in good]).reshape(-1, 1, 2)\n M, mask = cv2.findHomography(src_pts, dst_pts, cv2.RANSAC, 5.0)\n matchesMask = mask.ravel().tolist()\n h, w = image1.shape[:2]\n pts = np.float32([[0, 0], [0,h-1], [w-1,h-1], [w-1,0]]).reshape(-1, 1, 2)\n dst = cv2.perspectiveTransform(pts, M)\n image2 = cv2.polylines(image2, [np.int32(dst)], True, 255, 3, cv2.LINE_AA)\n else:\n matchesMask = None\n drawParams = dict(matchColor=(0, 255, 0),\n singlePointColor=None,\n matchesMask=matchesMask,\n flags=2)\n return cv2.drawMatches(image1, keypoints1, image2, keypoints2, good, None, **drawParams)\n except: # if error occured, just concatenate and show 2 images\n return self.concat(image1, image2)\n\n def concat(self, image1, image2):\n \"\"\" Concatenate two images \"\"\"\n h1, w1 = image1.shape[:2]\n h2, w2 = image2.shape[:2]\n if h1 == h2: # if images are the same height\n return np.concatenate((image1, image2), axis=1)\n # for images with different height create an empty matrix filled with zeros\n image = np.zeros((max(h1,h2), w1+w2, 3), np.uint8)\n # combine two images\n image[:h1, :w1, :3] = image1\n image[:h2, w1:w1+w2, :3] = image2\n return image\n\n def take_snapshot(self):\n \"\"\" Take snapshot \"\"\"\n ret, self.snapshot_image = self.vs.read() # read frame from video stream\n print(\"[INFO] new snapshot\")\n\n def destructor(self):\n \"\"\" Destroy the root object and release all resources \"\"\"\n print(\"[INFO] closing...\")\n self.root.destroy()\n self.vs.release() # release web camera\n cv2.destroyAllWindows() # destroy all cv2 windows\n\n# start the app\nprint(\"[INFO] starting...\")\npba = Application()\npba.root.mainloop()\n","repo_name":"foobar167/junkyard","sub_path":"simple_scripts/sift_tracking.py","file_name":"sift_tracking.py","file_ext":"py","file_size_in_byte":5359,"program_lang":"python","lang":"en","doc_type":"code","stars":90,"dataset":"github-code","pt":"81"} +{"seq_id":"7410637453","text":"import sys\nfrom collections import deque\n\ndef input(): return sys.stdin.readline().rstrip()\n\nsubin, sister = map(int, input().split())\n\n# 1차원 BFS의 탐색 횟수는 최대 10^5 정도~\n\nvisited = [False] * 100001\n\nq = deque()\nq.append((0, subin))\n\nanswer = 100000\nways = 0\n\nwhile q:\n level, subin = q.popleft()\n\n if level > answer:\n break\n\n if subin == sister:\n answer = level\n ways += 1\n continue\n\n visited[subin] = True\n\n next_moves = ((subin + 1), (subin - 1), (subin * 2))\n\n for next_subin in next_moves:\n if 0 <= next_subin <= 100000 and not visited[next_subin]:\n q.append((level + 1, next_subin))\n\nprint(answer)\nprint(ways)\n","repo_name":"poodlepoodle/problem-solving","sub_path":"baekjoon/12851_1.py","file_name":"12851_1.py","file_ext":"py","file_size_in_byte":699,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"81"} +{"seq_id":"25225751478","text":"'''42. Write a Python script to find all roots of a quadratic equation for all possible combination of a, b and c.'''\r\n\r\n# solution\r\nimport math\r\nprint(\"Quadratic equation ax^2+bx+c=0\")\r\na=int(input(\"Enter the value of a : \"))\r\nb=int(input(\"Enter the value of b : \"))\r\nc=int(input(\"Enter the value of c : \"))\r\nD=b**2-4*a*c\r\nprint(D)\r\nif D>0:\r\n x1=(-b+math.sqrt(D))/(2*a)\r\n x2=(-b-math.sqrt(D))/(2*a)\r\n print(f\"The roots of the equation are real and different and they are {x1} and {x2}\")\r\nelif D==0:\r\n x=-b/(2*a)\r\n print(f\"The roots of the equation are real and same and they are {x} and {x}\")\r\nelse:\r\n x1=-b/(2*a)\r\n i=(math.sqrt(-D))/(2*a)\r\n print(f\"The roots of the equation are complex and they are {x1}+{i}i and {x1}-{i}i\")","repo_name":"neo-deus/Exam-Purpose","sub_path":"Exam-Purpose/Python/Ques42.py","file_name":"Ques42.py","file_ext":"py","file_size_in_byte":735,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"81"} +{"seq_id":"3776807821","text":"import os\nimport shutil\nfrom pygame import mixer\nimport time\n\n# Initialize Pygame Mixer\nmixer.init()\n\n# Directories\nbase_dir = './' # The directory where your files are located\nyes_dir = os.path.join(base_dir, 'perfect')\nno_dir = os.path.join(base_dir, 'no')\nmaybe_dir = os.path.join(base_dir, 'maybe')\n\n# Ensure the directories exist\nos.makedirs(yes_dir, exist_ok=True)\nos.makedirs(no_dir, exist_ok=True)\nos.makedirs(maybe_dir, exist_ok=True)\n\n# Get all MP3 files in base directory, sort by size\nmp3_files = [f for f in os.listdir(base_dir) if f.endswith('.mp3')]\nmp3_files.sort(key=lambda f: os.path.getsize(os.path.join(base_dir, f)), reverse=True)\n\nfor mp3 in mp3_files:\n txt_file = mp3.replace('.mp3', '.txt')\n\n while True:\n # Try to display the contents of the .txt file\n try:\n with open(os.path.join(base_dir, txt_file), 'r') as f:\n print(f.read())\n except Exception as e:\n print(f'Error reading file {txt_file}: {e}')\n\n # Try to play the MP3 file\n try:\n mixer.music.load(os.path.join(base_dir, mp3))\n mixer.music.play()\n except Exception as e:\n print(f'Error playing file {mp3}: {e}')\n\n # Wait for the music to finish\n while mixer.music.get_busy():\n time.sleep(1)\n\n # Offer options\n action = input(\"(R) Replay, (Y) Yes, (N) No, (L) Later, (E) Edit: \").upper()\n if action == 'R':\n # Replay the MP3\n try:\n mixer.music.play()\n except Exception as e:\n print(f'Error replaying file {mp3}: {e}')\n elif action in ['Y', 'N', 'L']:\n target_dir = yes_dir if action == 'Y' else no_dir if action == 'N' else maybe_dir\n\n # Try to move both the MP3 and the corresponding .txt file to the target folder\n try:\n shutil.move(os.path.join(base_dir, mp3), target_dir)\n shutil.move(os.path.join(base_dir, txt_file), target_dir)\n except Exception as e:\n print(f'Error moving files {mp3} and {txt_file}: {e}')\n\n break\n elif action == 'E':\n # Edit the .txt file\n try:\n os.system(f'vim {os.path.join(base_dir, txt_file)}')\n except Exception as e:\n print(f'Error editing file {txt_file}: {e}')\n","repo_name":"binxio/piper-voice-cloning","sub_path":"curate-audio-samples.py","file_name":"curate-audio-samples.py","file_ext":"py","file_size_in_byte":2381,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"19769097319","text":"import os,sys\nimport torch \nimport torch.utils.data as torutils\nfrom torch.autograd import Variable\nfrom myutils.data_reader import *\nfrom myutils.parser import *\n\ndef sigmoid(z):\n\treturn (1.+torch.exp(-z))**-1\n\ndef manipX(ipt):\n ## manipulate the data-set here to the data in dstream\n ## ipt : ndarray \n ipt = ipt.astype(np.float)\n ipt = np.delete(ipt,1,1)\n #print (ipt)\n return ipt\n\ndef manipY(ipt):\n\n ipt = ipt.astype(np.float)\n ipt = ipt.flatten()\n #ipt = ipt[:]\n #ipt = np.delete(ipt,2,1)\n return ipt\n\n#===========================================================================\npars = Parser()\npars.parse(sys.argv[1])\nXpath = sys.argv[2]\nYpath = sys.argv[3]\nis_res = int(sys.argv[4])\nID = pars.val['ID']\nlearn_rate = float(pars.val['learn_rate'])\nNepoch = int(pars.val['epoch'])\n#regu_rate = float(pars.val['regu_rate'])\nmodel_dir = os.path.join(\"model\",ID)\ndrop_out = float(pars.val['dropout'])\nbatchsz = int(pars.val['batchsz'])\n\nif not os.path.exists(model_dir):\n\tos.system(\"mkdir %s\"%(model_dir))\n\n\n## layout : \npars.print_vals()\n\n\n\n### Read Data:\nXreader = Data_reader()\nXreader.Read_csv(Xpath,\"big5\",manipX)\nYreader = Data_reader()\nYreader.Read_csv(Ypath,\"big5\",manipY)\n\nNFeature = len(Xreader.data[0]) \nNSample = len(Xreader.data)\nNTrain = int(NSample*0.8)\n\n\n\n\n# shuffle first:\nidmap = None\nif is_res:\n\tidmap = np.load(os.path.join(model_dir,\"shufid.npy\"))\n\tprint (\"[load] shufid\")\nelse :\n\tidmap = np.random.permutation(NSample)\n\tnp.save(os.path.join(model_dir,\"shufid\"),idmap)\nall_x = Xreader.data[idmap]\nall_y = Yreader.data[idmap]\n\n# Feature scaling :\nif is_res:\n\tXmean = np.load(os.path.join(model_dir,\"FS_mean.npy\"))\n\tXstd = np.load(os.path.join(model_dir,\"FS_std.npy\") )\n\tprint (\"[load] FS_mean\")\n\tprint (\"[load] FS_std\" )\nelse :\n\tXmean = np.mean(all_x,axis=0)\n\tXstd = np.std(all_x,axis=0)\n\tnp.save(os.path.join(model_dir,\"FS_mean\"),Xmean)\n\tnp.save(os.path.join(model_dir,\"FS_std\"),Xstd)\n\nall_x = (all_x - Xmean)/Xstd\n\n\n## valid / train => torch tensor\ntrain_x = torch.from_numpy(all_x[:NTrain])\nvalid_x = torch.from_numpy(all_x[NTrain:NSample])\ntrain_y = torch.from_numpy(all_y[:NTrain])\nvalid_y = torch.from_numpy(all_y[NTrain:NSample])\n\n##create dataset:\ntrain_loader = torutils.DataLoader(torutils.TensorDataset(train_x,train_y),batch_size=batchsz,shuffle=True)\nvalid_loader = torutils.DataLoader(torutils.TensorDataset(valid_x,valid_y),batch_size=len(valid_x),shuffle=False)\n\n\n#------------------------------------------------------------------\n## create model :\nClassifyNet = None\nif is_res:\n\tClassifyNet = torch.load(os.path.join(model_dir,\"model\"))\n\tprint (\"[load] Net(model)\")\nelse:\n\tClassifyNet = torch.nn.Sequential(\\\n\t\t\t\t\ttorch.nn.Linear(NFeature, NFeature),\\\n\t\t\t\t\ttorch.nn.Dropout(drop_out),\\\n\t\t\t\t\ttorch.nn.ReLU(),\\\n \t\t\t\ttorch.nn.Linear(NFeature, 1),\\\n\t\t\t\t\t#torch.nn.Dropout(0.5),\\\n\t\t\t\t\ttorch.nn.Sigmoid()\n\t\t\t\t ).double()\n\noptimizer = torch.optim.SGD(ClassifyNet.parameters(), lr=learn_rate)\nloss_fx = torch.nn.BCELoss()\n\nprint (\"Start\")\nsys.stdout.flush()\nClassifyNet.train()\nfor en in range(Nepoch):\n\terror=0\n\tfor ns , (tr_x,tr_y) in enumerate(train_loader):\n\t\tpred = ClassifyNet(Variable(tr_x))\t\n\t\t#exit(1)\n\t\terror += np.sum(np.abs(np.round(pred.data.numpy().flatten()) - tr_y.numpy().flatten()))\n\t\t#exit(1)\n\t\tloss = loss_fx(pred.squeeze(),Variable(tr_y))\n\t\t#exit(1)\n\t\tClassifyNet.zero_grad()\t\t\n\t\tloss.backward()\n\t\toptimizer.step()\n\n\terror /= len(train_x)\n\tcorrect = 1.-error\n\tprint (\"e %3d] Xs: %4.6f As: %4.6f\"%(en,loss.data.numpy(),correct))\n\tsys.stdout.flush()\n\n## Save:\ntorch.save(ClassifyNet,os.path.join(model_dir,\"model\"))\n\n## Validate \naccuracy = []\nClassifyNet.eval()\nfor n , (va_x,va_y) in enumerate(valid_loader):\n\t#print (\"va\",n)\n\tpred = ClassifyNet(Variable(va_x))\n\t#print (np.shape(pred.data.numpy().flatten()))\n\t#print (np.shape(va_y.numpy().flatten()))\n\taccuracy = 1.- np.mean(np.abs(np.round(pred.data.numpy().flatten()) - va_y.numpy().flatten()))\n\nprint (accuracy)\nsys.stdout.flush()\n\n","repo_name":"kaihsin/ML2017FALL","sub_path":"hw2/src/Fmap_pytorch/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":3993,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"81"} +{"seq_id":"41196999873","text":"import os\n\nimport dj_database_url\nfrom django.contrib import messages\nfrom django.urls import reverse\n\n\ndef user_url(user):\n return reverse(\"cab_author_snippets\", kwargs={\"username\": user.username})\n\n\nPROJECT_ROOT = os.path.join(os.path.dirname(os.path.abspath(__file__)), os.pardir)\n\nSITE_ID = 1\nSITE_NAME = \"djangosnippets.org\"\n\nALLOWED_HOSTS = os.environ.get(\"ALLOWED_HOSTS\", \"djangosnippets.org,www.djangosnippets.org\").split(\",\")\n\nDEBUG = False\n\nTIME_ZONE = \"America/Chicago\"\nLANGUAGE_CODE = \"en-us\"\nUSE_I18N = True\nUSE_TZ = False\n\nDEFAULT_FROM_EMAIL = \"no-reply@djangosnippets.org\"\nSERVER_EMAIL = \"no-reply@djangosnippets.org\"\nEMAIL_SUBJECT_PREFIX = \"[djangosnippets] \"\n\n\nABSOLUTE_URL_OVERRIDES = {\n \"auth.user\": user_url,\n}\n\nFORCE_WWW = False\n\nROOT_URLCONF = \"djangosnippets.urls\"\n\nCACHE_KEY_PREFIX = \"djangosnippets\"\nCACHE_MIDDLEWARE_KEY_PREFIX = CACHE_KEY_PREFIX\nCACHE_MIDDLEWARE_SECONDS = 60\n\nINSTALLED_APPS = (\n \"django.contrib.auth\",\n \"django.contrib.admin\",\n \"django_comments\",\n \"django.contrib.contenttypes\",\n \"django.contrib.flatpages\",\n \"django.contrib.messages\",\n \"django.contrib.sessions\",\n \"django.contrib.staticfiles\",\n \"django.contrib.sites\",\n \"allauth\",\n \"allauth.account\",\n \"allauth.socialaccount\",\n \"allauth.socialaccount.providers.bitbucket\",\n \"allauth.socialaccount.providers.github\",\n \"allauth.socialaccount.providers.twitter\",\n \"cab\",\n \"comments_spamfighter\",\n \"ratings\",\n \"taggit\",\n \"captcha\",\n \"django_extensions\",\n \"rest_framework\",\n \"django_htmx\",\n)\n\nMIDDLEWARE = (\n \"django.middleware.security.SecurityMiddleware\",\n \"whitenoise.middleware.WhiteNoiseMiddleware\",\n # 'django.middleware.cache.UpdateCacheMiddleware',\n \"django.middleware.common.CommonMiddleware\",\n # 'django.middleware.cache.FetchFromCacheMiddleware',\n \"django.contrib.sessions.middleware.SessionMiddleware\",\n \"django.contrib.auth.middleware.AuthenticationMiddleware\",\n \"django.middleware.csrf.CsrfViewMiddleware\",\n \"django.contrib.messages.middleware.MessageMiddleware\",\n \"django.contrib.flatpages.middleware.FlatpageFallbackMiddleware\",\n \"ratelimitbackend.middleware.RateLimitMiddleware\",\n \"django_htmx.middleware.HtmxMiddleware\",\n)\n\nTEMPLATES = [\n {\n \"BACKEND\": \"django.template.backends.django.DjangoTemplates\",\n \"DIRS\": [os.path.join(PROJECT_ROOT, \"templates\")],\n \"APP_DIRS\": True,\n \"OPTIONS\": {\n \"context_processors\": [\n \"django.contrib.auth.context_processors.auth\",\n \"django.template.context_processors.debug\",\n \"django.template.context_processors.media\",\n \"django.template.context_processors.static\",\n \"django.contrib.messages.context_processors.messages\",\n \"django.template.context_processors.request\",\n ],\n },\n }\n]\n\nSTATIC_URL = \"/assets/static/\"\nSTATIC_ROOT = os.path.join(PROJECT_ROOT, \"..\", \"assets\", \"static\")\nSTATICFILES_DIRS = (os.path.join(PROJECT_ROOT, \"static\"),)\n\nSESSION_ENGINE = \"django.contrib.sessions.backends.cached_db\"\nMESSAGE_STORAGE = \"django.contrib.messages.storage.session.SessionStorage\"\n\nACCOUNT_EMAIL_CONFIRMATION_EXPIRE_DAYS = 7\nACCOUNT_EMAIL_REQUIRED = True\nACCOUNT_EMAIL_VERIFICATION = \"mandatory\"\nACCOUNT_DEFAULT_HTTP_PROTOCOL = \"https\"\nACCOUNT_LOGOUT_ON_GET = True\nACCOUNT_USERNAME_MIN_LENGTH = 3\nACCOUNT_ADAPTER = \"djangosnippets.adapters.DjangoSnippetsAccountAdapter\"\nSOCIALACCOUNT_ADAPTER = \"djangosnippets.adapters.DjangoSnippetsSocialAccountAdapter\"\nSOCIALACCOUNT_AUTO_SIGNUP = False\n\nLOGIN_REDIRECT_URL = \"/\"\nACCOUNT_LOGOUT_REDIRECT_URL = \"/\"\n\nCOMMENTS_APP = \"cab\"\n\nCAB_VERSIONS = (\n (\"3.2\", \"3.2\"),\n (\"3.1\", \"3.1\"),\n (\"3.0\", \"3.0\"),\n (\"2.2\", \"2.2\"),\n (\"2.1\", \"2.1\"),\n (\"2.0\", \"2.0\"),\n (\"1.11\", \"1.11\"),\n (\"1.10\", \"1.10\"),\n (\"1.9\", \"1.9\"),\n (\"1.8\", \"1.8\"),\n (\"1.7\", \"1.7\"),\n (\"1.6\", \"1.6\"),\n (\"1.5\", \"1.5\"),\n (\"1.4\", \"1.4\"),\n (\"1.3\", \"1.3\"),\n (\"1.2\", \"1.2\"),\n (\"1.1\", \"1.1\"),\n (\"1.0\", \"1.0\"),\n (\"0.96\", \".96\"),\n (\"0.95\", \"Pre .96\"),\n (\"0\", \"Not specified\"),\n)\n\n# keys for localhost and 127.0.0.1\nRECAPTCHA_PUBLIC_KEY = \"6LcXj_oSAAAAAPQ3u23Y6MqQqd2yMYtnHqa7Zj61\"\nRECAPTCHA_PRIVATE_KEY = \"6LcXj_oSAAAAAFN31LR-F31lwFSQAcJgsg1pE5WP\"\nRECAPTCHA_USE_SSL = True\n\nAUTHENTICATION_BACKENDS = (\n \"ratelimitbackend.backends.RateLimitModelBackend\",\n \"allauth.account.auth_backends.AuthenticationBackend\",\n)\n\nDISQUS_WEBSITE_SHORTNAME = \"djangosnippets\"\nDISQUS_USE_SINGLE_SIGNON = True\n\nMESSAGE_TAGS = {\n messages.DEBUG: \"secondary\",\n messages.INFO: \"info\",\n messages.SUCCESS: \"success\",\n messages.WARNING: \"warning\",\n messages.ERROR: \"alert\",\n}\n\n\nDATABASES = {\"default\": dj_database_url.config(default=\"postgres:///djangosnippets\")}\nDATABASES[\"default\"][\"ATOMIC_REQUESTS\"] = True\n\n\nREST_FRAMEWORK = {\n # Use Django's standard `django.contrib.auth` permissions,\n # or allow read-only access for unauthenticated users.\n \"DEFAULT_PERMISSION_CLASSES\": [\"rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly\"]\n}\n\nDEFAULT_AUTO_FIELD = \"django.db.models.AutoField\"\n","repo_name":"django/djangosnippets.org","sub_path":"djangosnippets/settings/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":5154,"program_lang":"python","lang":"en","doc_type":"code","stars":408,"dataset":"github-code","pt":"81"} +{"seq_id":"14709928325","text":"\"\"\"Prep __main__ entry.\"\"\"\n# pylint: disable=\nfrom typing import Optional\n\nimport environs\nimport logzero\nimport typer\nfrom icecream import ic\nfrom icecream import install as ic_install\nfrom logzero import logger\n\nfrom too_short_url import __version__, too_st\n\n# set env LOGLEVEL to 10/debug/DEBUG to turn on debug\ntry:\n _ = environs.Env().log_level(\"LOGLEVEL\")\n# except environs.EnvValidationError:\nexcept (environs.EnvError, environs.EnvValidationError):\n _ = None\nexcept Exception:\n _ = None\nlogzero.loglevel(_ or 10)\n# logzero.loglevel(_ or 20)\n\n# logger.debug(\" debug: %s\", __file__)\n# logger.info(\" info: %s\", __file__)\n\nic_install()\nic.configureOutput(\n includeContext=True,\n # outputFunction=logger.info,\n outputFunction=logger.debug,\n)\nic.enable()\n\napp = typer.Typer(\n name=\"too-st\",\n add_completion=False,\n help=\"Generate a too.st shorturl\",\n)\n\n\ndef _version_callback(value: bool) -> None:\n if value:\n typer.echo(f\"{app.info.name} v.{__version__}\")\n raise typer.Exit()\n\n\n@app.command()\ndef main(\n url: str = typer.Argument(..., help=\"url to be shortened\"),\n keyword: str = typer.Option(\n \"\",\n \"--keyword\",\n \"--kw\",\n \"-k\",\n help=\"desired keyword, e.g. https://too.st/abc for KEYWORD set to abc\",\n metavar=\"KEYWORD\",\n ), #\n best_effort: bool = typer.Option(\n False,\n \"--best-effort\",\n \"--besteffort\",\n \"-b\",\n is_flag=True,\n help=\"whether to try hard to generaet the desired shorturl https://too.st/KEYWORD\",\n ),\n version: Optional[bool] = typer.Option( # pylint: disable=(unused-argument\n None,\n \"--version\",\n \"-v\",\n \"-V\",\n help=\"Show version info and exit.\",\n callback=_version_callback,\n is_eager=True,\n ),\n):\n \"\"\"Generate too.st short url.\n\n e.g.\n\n * too-st baidu.com # https://too.st/b\n\n * too-st baidu.com -k abc # https://too.st/b\n\n * too-st baidu.com -k abc -b # https://too.st/abc or https://too.st/b dependent on whether https://too.st/abc is already taken or reserved by th admin of too.st.\n\n \"\"\"\n try:\n shorten_url = too_st(url, keyword, best_effort)\n typer.echo(shorten_url)\n raise typer.Exit()\n except Exception as e:\n typer.echo(e)\n raise typer.Exit()\n\n\nif __name__ == \"__main__\":\n app()\n","repo_name":"ffreemt/too-short-url","sub_path":"too_short_url/__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":2375,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"81"} +{"seq_id":"40067697437","text":"from pathlib import Path\n\nimport pytest\nimport torch as th\nimport transformers as tr\nfrom datasets import Dataset\n\n\n@pytest.fixture(scope=\"module\")\ndef text_dataset_path() -> Path:\n dir_path = Path(__file__).parent.absolute()\n return Path(dir_path, \"test_data\", \"pile_text.jsonl\")\n\n\n@pytest.fixture(scope=\"module\")\ndef text_dataset(text_dataset_path: Path) -> Dataset:\n dataset = Dataset.from_json(str(text_dataset_path))\n assert isinstance(dataset, Dataset)\n return dataset\n\n\n@pytest.fixture(\n scope=\"module\",\n params=[\n \"EleutherAI/pythia-70m-deduped\",\n \"bigscience/bloom-560m\",\n \"EleutherAI/gpt-neo-125M\",\n \"facebook/opt-125m\",\n \"mockmodel/llama-tiny\",\n \"gpt2\",\n ],\n)\ndef random_small_model(request: str) -> tr.PreTrainedModel:\n small_model_name = request.param\n th.manual_seed(42)\n\n # We use a random model with the correct config instead of downloading the\n # whole pretrained checkpoint.\n if small_model_name == \"mockmodel/llama-tiny\":\n config = tr.LlamaConfig(\n vocab_size=32_000,\n hidden_size=128,\n num_hidden_layers=4,\n num_attention_heads=4,\n )\n else:\n config = tr.AutoConfig.from_pretrained(small_model_name)\n\n model = tr.AutoModelForCausalLM.from_config(config)\n model.eval()\n\n return model\n\n\n@pytest.fixture(\n scope=\"module\",\n params=[\n \"EleutherAI/pythia-70m-deduped\",\n \"bigscience/bloom-560m\",\n \"EleutherAI/gpt-neo-125M\",\n \"facebook/opt-125m\",\n \"gpt2\",\n ],\n)\ndef small_model_tokenizer(request: str) -> tr.PreTrainedTokenizerBase:\n return tr.AutoTokenizer.from_pretrained(request.param, use_fast=True)\n\n\n@pytest.fixture(scope=\"module\")\ndef gpt2_tokenizer():\n return tr.AutoTokenizer.from_pretrained(\"gpt2\", use_fast=True)\n\n\n@pytest.fixture(scope=\"module\")\ndef opt_random_model() -> tr.PreTrainedModel:\n config = tr.AutoConfig.from_pretrained(\"facebook/opt-125m\")\n model = tr.AutoModelForCausalLM.from_config(config)\n model.eval()\n return model\n\n\n@pytest.fixture(scope=\"module\")\ndef gpt2_tiny_random_model_local_path(\n tmpdir_factory, gpt2_tokenizer: tr.PreTrainedTokenizerBase\n):\n config = tr.AutoConfig.from_pretrained(\"gpt2\")\n config.n_heads = 2\n config.n_embed = 8\n config.n_layers = 2\n model = tr.AutoModelForCausalLM.from_config(config)\n assert isinstance(model, tr.PreTrainedModel)\n tmp_path = tmpdir_factory.mktemp(\"gpt2_random_model_local\")\n model.save_pretrained(tmp_path)\n gpt2_tokenizer.save_pretrained(tmp_path)\n return tmp_path\n","repo_name":"AlignmentResearch/tuned-lens","sub_path":"tests/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":2608,"program_lang":"python","lang":"en","doc_type":"code","stars":301,"dataset":"github-code","pt":"81"} +{"seq_id":"26673458368","text":"\"\"\"\nThis module provides functions for the 2-dimensional Game of Life.\n\nThe 2-dimensional Game of Life occurs on an n-by-n array of\ncells where each cell is either alive or dead. The population of cells\nevolves from one generation to the next according to three rules:\n\n1. Any live cell survives into the next generation if it has 2 or 3\nliving neighbours in its 1-neighborhood (the cell itself does not\ncount towards the number of living neighbors).\n2. Any dead cell becomes alive in the next generation if it has 3\nliving neighbours in its 1-neighborhood.\n3. All other live cells die, and all other dead cells remain dead.\n\nThe rules are applied to each cell simultaneously to compute the\nnext generation of cells.\n\nThe 1-neighborhood of a cell consists of the cell itself and its\neight neighbours, which are the cells that are horizontally, vertically,\nor diagonally adjacent (if those neighbors exist).\n\nAuthor: Burton Ma\nDate: 2021-03-06\n\nModified by: Dharsan Ravindran\nStudent number: 20219218\n\"\"\"\n\n\ndef test_indexes(cells, row, col, func_name):\n \"\"\"\n Test if row and column indexes are valid for a square array.\n\n This function tests if `row` and `col` are both in the\n range 0 to (n - 1), inclusive, where n is equal to\n len(cells). Raises a ValueError if an index is out of\n range.\n\n Parameters\n ----------\n cells : list-of-list of bool\n The n-by-n cells of a 2D Game of Life.\n row : int\n A row index for cells.\n col : int\n A column index for cells.\n func_name : str\n The name of the function that called test_indexes\n\n Raises\n ------\n ValueError\n If `row` or `col` is out of range.\n \"\"\"\n n = len(cells)\n if row < 0:\n raise ValueError(func_name, 'number of rows < 0, row = ', row)\n elif row >= n:\n raise ValueError(func_name, 'number of rows >= len(cells), row = ', row)\n if col < 0:\n raise ValueError(func_name, 'number of cols less than zero, col = ', col)\n elif col >= n:\n raise ValueError(func_name, 'number of cols >= len(cells), col = ', col)\n\n\ndef make_cells(rows, cols, val):\n \"\"\"\n Return an array filled with a specified value.\n\n Parameters\n ----------\n rows : int\n The number of rows in the array.\n cols : int\n The number of columns in the array.\n val : bool\n The element to appear repeatedly in the returned list.\n\n Returns\n -------\n list\n A list-of-lists of `rows`-by-`cols` copies of `val`\n\n Raises\n ------\n ValueError\n If `rows` or `cols` is less than zero.\n \"\"\"\n if rows < 0:\n raise ValueError('make_cells() size less than zero, rows = ', rows)\n if cols < 0:\n raise ValueError('make_cells() size less than zero, cols = ', cols)\n a = []\n for i in range(0, rows):\n row = [val] * cols\n a.append(row)\n return a\n\n\ndef print_cells(cells):\n \"\"\"\n Prints the representation of a 2-D array given a 2-D list.\n\n Prints '#' or '-' depending on the values for a certain boolean list 'cells'.\n '#' for True and '-' for false.\n\n Parameters\n ----------\n cells : list\n The 2-D boolean list used in to print.\n \"\"\"\n\n for row in cells:\n for cell in row:\n if cell:\n print('#', end='')\n else:\n print('-', end='')\n print()\n\n\ndef neighborhood(cells, row, col):\n \"\"\"\n Returns a list containing in the neighborhood of a certain cell.\n\n Returns a 2-D list the cells in the 1-neighborhood of in the list 'cells'\n centered around 'cells[row][col]'.\n\n Parameters\n ----------\n cells : list\n The larger 2-D list used to create a sublist from.\n row : int\n The first index/ row of where the 2 neighborhood list will be built around.\n col:int\n The second index/ col of where the 2 neighborhood list will be built around.\n\n Returns\n -------\n list\n A 2-D list of the 1-neighborhood cells around 'cells[row][col]' with a max area of 9 cells.\n\n Raises\n ------\n ValueError\n If `row` or 'col' is less than zero.\n \"\"\"\n\n if row < 0:\n raise ValueError('neighborhood() row can not be negative index out of range row= ', str(row))\n if col < 0:\n raise ValueError('neighborhood() col can not be negative index out of range col= ', str(col))\n\n top_row = max(0, row - 1)\n bottom_row = min(len(cells) - 1, row + 1)\n left_column = max(0, col - 1)\n right_column = min(len(cells[row]), col + 2)\n neighbor_list = []\n if top_row == row:\n neighbor_list += [cells[top_row][left_column:right_column]]\n else:\n neighbor_list += [cells[top_row][left_column:right_column]]\n neighbor_list += [cells[row][left_column:right_column]]\n if bottom_row != row:\n neighbor_list += [cells[bottom_row][left_column:right_column]]\n\n return neighbor_list\n\n\ndef evolve(cells):\n \"\"\"\n Applies the rules of the 2-dimensional Game of Life to get next generation of cells.\n\n Simultaneously applies the rules of the 2-dimensional Game of Life by creating\n a copy of 'cells' and changing the values based on the given rules.\n\n Parameters\n ----------\n cells : list\n The 2-dimensional list used in applying the game of life to.\n\n Raises\n ------\n ValueError\n If 'cells' is empty\n \"\"\"\n\n if not cells:\n raise ValueError('evolve() cells can not be an empty list.')\n\n cells_copy = []\n for x in cells:\n sm_array = []\n for y in x:\n sm_array += [y]\n cells_copy += [sm_array]\n\n for index in range(len(cells)):\n for col in range(len(cells[0])):\n\n check = neighborhood(cells_copy, index, col)\n alive = 0\n\n if cells_copy[index][col]:\n for x in check:\n for y in x:\n if y:\n alive += 1\n if alive == 3 or alive == 4:\n cells[index][col] = cells[index][col]\n else:\n cells[index][col] = not (cells[index][col])\n\n elif not cells_copy[index][col]:\n for x in check:\n for y in x:\n if y:\n alive += 1\n if alive == 3:\n cells[index][col] = not (cells[index][col])\n\n\ndef glider(cells, top_row, left_col):\n \"\"\"\n Inserts the glider pattern into a list.\n\n Inserts a glider pattern into the list 'cells' with the pattern starting at\n 'cells[top_row][left_col]'. Find 5x5 array of the glider pattern bellow:\n -----\n -#---\n --##-\n -##--\n -----\n\n Parameters\n ----------\n cells : list\n The 2-dimensional list used to insert the blinker pattern\n top_row : int\n The first index/row at which the glider pattern is to be inserted in the list 'cells'.\n left_col:int\n The col index/col at which the glider pattern is to be inserted in the list 'cells'.\n\n Raises\n ------\n ValueError\n If `top_row` or 'left_col\" is less than zero or if blinker pattern does not fit into list at\n cells[top_row][left_col].\n \"\"\"\n\n if top_row < 0:\n raise ValueError('glider() top_row can not be a negative value, top_row: ' + str(top_row))\n if left_col < 0:\n raise ValueError('glider() left_col can not be a negative value, left_col: ' + str(left_col))\n if top_row + 4 >= len(cells) or left_col + 5 > len(cells[0]):\n raise ValueError('glider() the glider pattern does not fit into the specified values.')\n\n cells[top_row][left_col:left_col + 5] = [False, False, False, False, False]\n cells[top_row + 1][left_col:left_col + 5] = [False, True, False, False, False]\n cells[top_row + 2][left_col:left_col + 5] = [False, False, True, True, False]\n cells[top_row + 3][left_col:left_col + 5] = [False, True, True, False, False]\n cells[top_row + 4][left_col:left_col + 5] = [False, False, False, False, False]\n","repo_name":"dharsan-r/CISC-121-Projects","sub_path":"Assignment 2/life2.py","file_name":"life2.py","file_ext":"py","file_size_in_byte":8035,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"4763497311","text":"import pandas as pd\n\nCATEGORY_COLUMNS = [\n 'AcceptedCmp1',\n 'AcceptedCmp2',\n 'AcceptedCmp3',\n 'AcceptedCmp4',\n 'AcceptedCmp5',\n 'Response',\n 'Complain',\n 'Education',\n 'Marital_Status',\n]\n\ndef convert_types(df: pd.DataFrame, columns: list, desired_type: str):\n for column in columns:\n df[column] = df[column].astype(desired_type)\n return df\n\ndef read_data(**kargs):\n raw_df = pd.read_csv(**kargs)\n df = convert_types(raw_df, CATEGORY_COLUMNS, 'category')\n df['Dt_Customer'] = pd.to_datetime(\n df['Dt_Customer'],\n format='%Y-%m-%d',\n ).astype(int)\n df.drop(columns=['Z_CostContact', 'Z_Revenue'], inplace=True)\n return df\n\nif __name__ == '__main__':\n pass\n","repo_name":"rodrigotorn/marketing-campaign-classification","sub_path":"src/read_data.py","file_name":"read_data.py","file_ext":"py","file_size_in_byte":682,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"81"} +{"seq_id":"40453225549","text":"\nimport numpy as np\nimport logging\n\n\nlogger = logging.getLogger(__name__)\n\n\ndef find_mica_IC(HPO_term_a, HPO_term_b, ic_per_nodes, node_ancestor_mapping):\n hpo_nodes_shared_ancestors = node_ancestor_mapping[HPO_term_a].intersection(node_ancestor_mapping[HPO_term_b])\n mica_ic = max([float(ic_per_nodes[node]) for node in hpo_nodes_shared_ancestors], default=0.0)\n \n return mica_ic\n\n\ndef compute_similarity_between_nodes(hpo_term_a, hpo_term_b, ic_per_nodes, node_ancestor_mapping, similarity_measure=\"Lin\"):\n node_a_ic = float(ic_per_nodes[hpo_term_a])\n node_b_ic = float(ic_per_nodes[hpo_term_b])\n mica_ic = find_mica_IC(hpo_term_a, hpo_term_b, ic_per_nodes, node_ancestor_mapping)\n \n if similarity_measure == \"Lin\":\n if mica_ic == 0.0 or (node_a_ic == 0.0 and node_b_ic == 0.0):\n nodes_similarity = 0.0\n else:\n nodes_similarity = (2.0 * mica_ic) / (node_a_ic + node_b_ic)\n \n elif similarity_measure == \"Resnik\":\n nodes_similarity = mica_ic\n \n elif similarity_measure == \"Jiang-Conrath\":\n nodes_similarity = (1 - (node_a_ic + node_b_ic - 2.0 * mica_ic))\n \n elif similarity_measure == \"Relevance\":\n #nodes_similarity = ((2.0 * mica_ic) / (node_a_ic + node_b_ic)) * (1 - p(mica))\n pass\n\n elif similarity_measure == \"Information-Coefficient\":\n nodes_similarity = ((2.0 * mica_ic) / (node_a_ic + node_b_ic)) * (1 - (1 / (1 + mica_ic)))\n\n elif similarity_measure == \"Graph-IC\":\n pass\n\n elif similarity_measure == \"Wang\":\n pass\n \n else:\n logger.error(\"An error occured while determining the similarity measure!\")\n \n return nodes_similarity\n\n\ndef calculate_hpo_set_similarity(hpo_graph, hpo_term_set_a, hpo_term_set_b, ic_per_nodes, node_ancestor_mapping, hpo_replacement_information):\n checked_term_set_a = []\n checked_term_set_b = []\n \n # alternatives and/or considerations are ignored for now\n alternatives = hpo_replacement_information[\"alternatives\"]\n considerations = hpo_replacement_information[\"considerations\"]\n replacements = hpo_replacement_information[\"replacements\"]\n \n for term_a in hpo_term_set_a:\n if term_a not in hpo_graph:\n if term_a in replacements.keys():\n checked_term_set_a.append(replacements[term_a])\n logger.warn(f\"{term_a} (sample) not in HPO graph! Replacement ({replacements[term_a]}) found will use this term instead!\")\n elif term_a in alternatives.keys():\n #checked_term_set_a.extend(alternatives[term_a])\n logger.warn(f\"{term_a} (sample) not in HPO graph! Alternatives ({alternatives[term_a]}) found! HPO term will be skipped!\")\n elif term_a in considerations.keys():\n #checked_term_set_a.extend(considerations[term_a])\n logger.warn(f\"{term_a} (sample) not in HPO graph! Considerations ({considerations[term_a]}) found! HPO term will be skipped!\")\n else:\n logger.warn(f\"{term_a} (sample) not in HPO graph! HPO term will be skipped!\")\n else:\n checked_term_set_a.append(term_a)\n \n for term_b in hpo_term_set_b:\n if term_b not in hpo_graph:\n if term_b in replacements.keys():\n checked_term_set_b.append(replacements[term_b])\n logger.warn(f\"{term_b} (gene) not in HPO graph! Replacement ({replacements[term_b]}) found will use this term instead!\")\n elif term_b in considerations.keys():\n #checked_term_set_b.extend(considerations[term_b])\n logger.warn(f\"{term_b} (gene) not in HPO graph! Considerations ({considerations[term_b]}) found! HPO term will be skipped!\")\n elif term_b in alternatives.keys():\n #checked_term_set_b.extend(alternatives[term_b])\n logger.warn(f\"{term_b} (gene) not in HPO graph! Alternatives ({alternatives[term_b]}) found! HPO term will be skipped!\")\n else:\n logger.warn(f\"{term_b} (gene) not in HPO graph! HPO term will be skipped!\")\n else:\n checked_term_set_b.append(term_b)\n \n if checked_term_set_a and checked_term_set_b:\n similarities_a_to_b = [max([compute_similarity_between_nodes(term_a, term_b, ic_per_nodes, node_ancestor_mapping) for term_b in checked_term_set_b], default=0.0) for term_a in checked_term_set_a]\n #similarities_b_to_a = [max([compute_similarity_between_nodes(term_b, term_a, ic_per_nodes, node_ancestor_mapping) for term_a in checked_term_set_a], default=0.0) for term_b in checked_term_set_b]\n \n set_a_to_b_similarity = np.median(similarities_a_to_b)\n #set_b_to_a_similarity = np.median(similarities_b_to_a)\n\n #if set_a_to_b_similarity != 0.0 or set_b_to_a_similarity != 0.0:\n # hpo_set_similarity = (set_a_to_b_similarity + set_b_to_a_similarity) / 2\n #else:\n # hpo_set_similarity = 0.0\n \n return set_a_to_b_similarity\n\n else:\n logger.warn(f\"Sample HPO set ({hpo_term_set_a}) and/or Gene HPO set ({hpo_term_set_b}) was empty after checking if the terms are part of the used HPO graph! Maybe no supported term was in the set! Similarity set to 0.0!\")\n \n return 0.0\n","repo_name":"imgag/aiDIVA","sub_path":"aidiva/variant_prioritization/get_HPO_similarity_score.py","file_name":"get_HPO_similarity_score.py","file_ext":"py","file_size_in_byte":5310,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"81"} +{"seq_id":"10670091615","text":"from fastapi import APIRouter\nfrom FileOp import *\nfrom model.NXO import *\nfrom random import randint\n\nNXO = getData('nextlevelxo.json')\n\nrouter = APIRouter(\n responses={\n 404: {\n 'message': \"Not Found\"\n }\n }\n)\n\n@router.get(\"/nextlevelxo\")\nasync def get_nxo():\n return NXO\n\n@router.get(\"/nextlevelxo/uid\")\nasync def get_nxo_by_uid(uid:str):\n if uid not in NXO['ingame_uid']:\n return {\"status\":1,\"data\":None}\n else:\n return {\"status\":0,\"data\": NXO['server'][NXO['ingame_pair'][uid]]}\n\n@router.post(\"/nextlevelxo\")\nasync def post_newgame(player:NewNXOMatch):\n player = player.dict()\n try:\n\n gen_matchid = str(NXO['lastest_match_id'])\n while len(gen_matchid) < 8:\n gen_matchid = '0' + gen_matchid\n \n data = {\n \"match_id\": gen_matchid,\n \"isValid\": True,\n \"player\": [\n {\n \"username\": player['username1'],\n \"uid\": player['uid1'],\n \"token\": [1,1,1,1,1]\n },\n {\n \"username\": player['username2'],\n \"uid\": player['uid2'],\n \"token\": [1,1,1,1,1]\n }\n ],\n \"board\":{\n \"owner\": [\n [\"➖\",\"➖\",\"➖\"],\n [\"➖\",\"➖\",\"➖\"],\n [\"➖\",\"➖\",\"➖\"]\n ],\n \"level\": [\n [\"-\",\"-\",\"-\"],\n [\"-\",\"-\",\"-\"],\n [\"-\",\"-\",\"-\"]\n ]\n },\n \"turn\": randint(0,1)\n }\n\n NXO['server'][gen_matchid] = data\n NXO['lastest_match_id'] += 1\n NXO['ingame_uid'].routerend(player['uid1'])\n NXO['ingame_uid'].routerend(player['uid2'])\n NXO['ingame_pair'][player['uid1']] = gen_matchid\n NXO['ingame_pair'][player['uid2']] = gen_matchid\n NXO['match_pair'][player['uid1']] = player['uid2']\n NXO['match_pair'][player['uid2']] = player['uid1']\n except:\n return {\"result\":1,\"data\":None}\n else:\n saveData('nextlevelxo.json',NXO)\n return {\"result\":0,\"data\":data}\n\n@router.patch(\"/nextlevelxo\")\nasync def update_game_status(match:UpdateNXOMatch):\n match = match.dict()\n try:\n target = match['match_id']\n NXO['server'][target] = match\n except:\n return {\"result\":1,\"data\":None}\n else:\n saveData('nextlevelxo.json',NXO)\n return NXO['server'][target]\n\n@router.patch(\"/nextlevelxo/disable\")\nasync def disable_match(uid:str):\n # print(\"=============Hello============\")\n try:\n # print(\"==============================================POP=====================================\")\n uid1 = uid\n uid2 = NXO['match_pair'][uid]\n match_id = NXO['ingame_pair'][uid]\n NXO['server'][match_id]['isValid'] = False\n for i in range(len(NXO['ingame_uid'])):\n if NXO['ingame_uid'][i] == uid1:\n NXO['ingame_uid'].pop(i)\n break\n for i in range(len(NXO['ingame_uid'])):\n if NXO['ingame_uid'][i] == uid2:\n NXO['ingame_uid'].pop(i)\n break\n NXO['ingame_pair'].pop(uid1)\n NXO['ingame_pair'].pop(uid2)\n NXO['match_pair'].pop(uid1)\n NXO['match_pair'].pop(uid2)\n # print(\"=======================\")\n # print(NXO['ingame_uid'],NXO['ingame_pair'],NXO['match_pair'])\n # print(\"=======================\")\n data = NXO['server'][match_id]\n except:\n return {\"result\":1,\"data\":None}\n else:\n saveData('nextlevelxo.json',NXO)\n return {\"result\":0,\"data\":data}","repo_name":"Jericho-JERIX/JERIX-Backend","sub_path":"routes/nxo.py","file_name":"nxo.py","file_ext":"py","file_size_in_byte":3725,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"621930180","text":"import numpy as np\r\nfrom math import sqrt\r\nimport matplotlib.pyplot as plt\r\n\r\ndef descent(x=(np.array([0.5,1.5])), ite=10):\r\n xk = x\r\n xn = []\r\n lambk = step(xk)\r\n dk = -grad(xk)\r\n xn.append(xk + lambk*dk) \r\n i = 0\r\n while(i < ite):\r\n xk = xn[i]\r\n lambk = step(xk)\r\n dk = -grad(xk)\r\n xn.append(xk + lambk*dk) \r\n i+=1\r\n print(xn)\r\n return xn\r\n\r\ndef grad(xk):\r\n return np.array([16*xk[0] + 4*(xk[1] - 2), 4*(xk[0]-1) + 12*xk[1]])\r\n\r\ndef step(xk):\r\n x = xk[0]\r\n y = xk[1]\r\n return (-sqrt(-44*(x**2)+44*x*y+44*x+44*(y**2)-88*y\r\n +81) + 34*x+14*y-9)/(8*(75*x+38*y-41))\r\n\r\nxn = descent()\r\n\r\ndef f(x,y):\r\n return 8*(x**2) + 6*(y**2) + 4*(x-1)*(y-2)\r\n\r\nN = 20\r\na = -1\r\nb = 1\r\n\r\nx = np.linspace(a,b,N)\r\ny = np.linspace(a,b,N)\r\n\r\nxmesh, ymesh = np.meshgrid(x,y,indexing='ij')\r\nzmesh = f(xmesh,ymesh)\r\n\r\nfig = plt.figure()\r\nax = plt.axes(projection = '3d')\r\nax.plot_surface(xmesh, ymesh, zmesh, alpha = 0.5)\r\nfor i in xn:\r\n ax.scatter(i[0], i[1], f(i[0],i[1]), c='red')\r\nplt.show()","repo_name":"avilladat/Seminarios","sub_path":"A mano/GradientDescent.py","file_name":"GradientDescent.py","file_ext":"py","file_size_in_byte":1067,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"72928632266","text":"import numpy as np\n\nA = np.array([[1, 2, 3], [3, 4, 6]])\nA.shape\n# (2, 3)\n\nB = np.array([[1, 2], [3, 4], [5, 6]])\nB.shape\n# (3, 2)\n\nnp.dot(A,B) # 두 행렬의 곱 넘파이 함수\n# array([[22,28],\n# [49, 64]])\n\n# 행렬의 형상이 다를 때: 행렬 A의 1번째 차원의 열 수 = 행렬 B의 0번째 차원의 행 수","repo_name":"dksdpdms520/deeplearning-from-scratch","sub_path":"Neural network/Multidimensional array/2_array_multiplication.py","file_name":"2_array_multiplication.py","file_ext":"py","file_size_in_byte":357,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"5476390171","text":"import time\r\nfrom uuid import RESERVED_FUTURE, uuid4 as uid\r\n\r\n\r\nclass AddIngrError(Exception):\r\n \"\"\"\r\n This class is custom Exception Class.\r\n It was made for raising exceptions from 'add_ingredients' method of 'Order' class.\r\n \"\"\"\r\n def __init__(self, message):\r\n super().__init__(message)\r\n self.m = message\r\n\r\n\r\nclass Customer:\r\n \"\"\"\r\n This class describes Customer.\r\n\r\n For creating one, you must indicate first, last name and phone number of customer.\r\n \"\"\"\r\n def __init__(self, f_name, l_name, phone):\r\n if not isinstance(f_name, str) or f_name == '':\r\n pass\r\n #raise TypeError(\"First name must be a string.\") \r\n if not isinstance(l_name, str or l_name == ''):\r\n pass\r\n #raise TypeError(\"Last name must be a string.\")\r\n if not isinstance(phone, str or phone == ''):\r\n pass\r\n #raise TypeError(\"Phone number must be a string.\")\r\n \r\n self.f_name, self.l_name, self.phone = f_name, l_name, phone\r\n self.cid = uid()\r\n \r\n\r\n def __str__(self):\r\n return f\"Customer: {self.cid}\\n\" \\\r\n f\"{self.l_name}, {self.f_name}. {self.phone}.\"\r\n\r\nclass Pizzeria:\r\n \"\"\"\r\n This class describes Pizzeria.\r\n\r\n Through this class, you can discover, what is the pizza-of-the-day for today.\r\n \"\"\"\r\n def __init__(self):\r\n self.days = {1:\"Mon\", 2:\"Tue\", 3:\"Wed\", 4:\"Thu\", 5:\"Fri\", 6:\"Sat\", 7:\"Sun\"}\r\n self.pizzas = {\"M\":\"Margarita\", \"H\":\"Hawaiian\", \"B\":\"Barbeque\", \"C\":\"Carbonara\", \\\r\n \"K\":\"Karri\", \"P\":\"Pepperoni\", \"T\":\"Texas\"}\r\n self.prices = {\"Margarita\":20, \"Hawaiian\":25, \"Barbeque\":35, \\\r\n \"Carbonara\":40, \"Karri\":50, \"Pepperoni\":40, \"Texas\":45}\r\n self.ingredients = [\"Mushrooms\", \"Pineapple\", \"Olives\", \"Corn\", \\\r\n \"Mozarella\", \"Suluguni\", \"Tofu\", \"Parmesan\"]\r\n\r\n @property\r\n def pizza_of_the_day(self):\r\n \"\"\"\r\n This method discovers what day of week is today, and returns pizza-of-the-day.\r\n \"\"\"\r\n if self.days[1] == time.ctime()[:3]:\r\n return f\"{self.pizzas['M']}\"\r\n if self.days[2] == time.ctime()[:3]:\r\n return f\"{self.pizzas['H']}\"\r\n if self.days[3] == time.ctime()[:3]:\r\n return f\"{self.pizzas['B']}\"\r\n if self.days[4] == time.ctime()[:3]:\r\n return f\"{self.pizzas['C']}\"\r\n if self.days[5] == time.ctime()[:3]:\r\n return f\"{self.pizzas['K']}\"\r\n if self.days[6] == time.ctime()[:3]:\r\n return f\"{self.pizzas['P']}\"\r\n if self.days[7] == time.ctime()[:3]:\r\n return f\"{self.pizzas['T']}\"\r\n\r\n @property\r\n def photo_of_the_day(self):\r\n \"\"\"\r\n This method discovers what day of a week is today, and returns photo of today's pizza.\r\n Also, this method was created for qt only.\r\n \"\"\"\r\n\r\n if self.days[1] == time.ctime()[:3]:\r\n return 'img\\\\pizza\\\\Margarita.jpg'\r\n if self.days[2] == time.ctime()[:3]:\r\n return 'img\\\\pizza\\\\Hawaiian.jpg'\r\n if self.days[3] == time.ctime()[:3]:\r\n return 'img\\\\pizza\\\\Barbeque.jpg'\r\n if self.days[4] == time.ctime()[:3]:\r\n return 'img\\\\pizza\\\\Carbonara.jpg'\r\n if self.days[5] == time.ctime()[:3]:\r\n return 'img\\\\pizza\\\\Karri.jpg'\r\n if self.days[6] == time.ctime()[:3]:\r\n return 'img\\\\pizza\\\\Pepperoni.jpg'\r\n if self.days[7] == time.ctime()[:3]:\r\n return 'img\\\\pizza\\\\Texas.jpg'\r\n\r\n @property\r\n def pizzaConsistency(self):\r\n if self.pizza_of_the_day == \"Margarita\":\r\n return f\"Red sauce, mozarella, tomatoes, basil.\"\r\n if self.pizza_of_the_day == \"Hawaiian\":\r\n return f\"White sauce, chicken\\ham, pineapples, mozarella.\"\r\n if self.pizza_of_the_day == \"Barbeque\":\r\n return f\"BBQ sauce, chicken, gounda and mozarella, onion.\"\r\n if self.pizza_of_the_day == \"Carbonara\":\r\n return f\"Red sauce, ham, mozarella, egg.\"\r\n if self.pizza_of_the_day == \"Karri\":\r\n return f\"Soy sauce, curry sauce, tomato sauce, chicken, mozarella, pepper, onion.\"\r\n if self.pizza_of_the_day == \"Pepperoni\":\r\n return f\"Spicy red sauce, raw smoked sausage, chili pepper, tomatoes, mozarella.\"\r\n if self.pizza_of_the_day == \"Texas\":\r\n return f\"BBQ sauce, smoked chicken, bacon, mushrooms, tomatoes, mozzarella and cheddar.\"\r\n\r\n def __str__(self):\r\n return f\"Today's pizza-of-the-day is:\\n\" \\\r\n f\"{self.pizza_of_the_day}, {self.prices[self.pizza_of_the_day]}$.\\n\" \\\r\n f\"\\n\" \\\r\n f\"Pizza consistency: \\n{self.pizzaConsistency}\\n\" \\\r\n f\"\\n\" \\\r\n f\"All ingredients are for 3$.\" \r\n\r\nclass Order(Pizzeria):\r\n \"\"\"\r\n This class describes Order.\r\n\r\n For instantiating this one, you will necessarily need an instance of \"Customer\" class.\r\n \"\"\"\r\n def __init__(self, customer=None):\r\n super().__init__()\r\n if customer is not None and not isinstance(customer, Customer):\r\n raise TypeError(f\"'{type(customer).__name__}' object cannot be interpreted as a customer.\")\r\n self.customer = customer\r\n self.added_ingr = []\r\n self.oid = uid()\r\n\r\n def add_ingredients(self, ingr):\r\n \"\"\"\r\n This method adds ingredients to your purchase and checks all stuff for mistakes.\r\n \"\"\"\r\n try:\r\n self.added_ingr.append(ingr)\r\n except:\r\n raise AddIngrError(f\"You should take ingredients from ingr. menu only:\\n\" \\\r\n f\"{self.ingredients}\")\r\n\r\n \r\n def remove_ingredients(self, ingr):\r\n \"\"\"\r\n This method removes ingredients from your purchase.\r\n This metod was created for qt only.\r\n \"\"\"\r\n try:\r\n self.added_ingr.remove(ingr)\r\n except:\r\n pass\r\n \r\n \r\n def make_purchase(self):\r\n \"\"\"\r\n This method calculates all the stuff and returns all necessary info.\r\n \"\"\"\r\n total = self.prices[self.pizza_of_the_day] + (len((self.added_ingr)) * 3)\r\n return f\"{self.customer.__str__()}\\n\" \\\r\n f\"\\n\" \\\r\n f\"Order: {self.oid}\\n\" \\\r\n f\"You have bought the next pizza of the day: {self.pizza_of_the_day}.\\n\" \\\r\n f\"Added ingredients: {self.added_ingr}\\n\" \\\r\n f\"Total: {total}$.\"\r\n\r\n def added(self):\r\n return self.added_ingr\r\n \r\n","repo_name":"lastochka364/pyqt5UniversityPractice","sub_path":"Practice.Pizza/Pizza.py","file_name":"Pizza.py","file_ext":"py","file_size_in_byte":6616,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"38116726436","text":"from pyspark import SparkContext\nimport json\nimport time\nfrom collections import Counter\nfrom itertools import combinations\nfrom math import factorial, ceil\n\ncb = lambda n,k: factorial(n)/(factorial(k)*factorial(n - k)) if k<=n else 1\n\ndef case_1_import(x):\n x_ = x[0].split(\",\")\n return (x_[0],x_[1])\n\ndef case_2_import(x):\n x_ = x[0].split(\",\")\n return (x_[1],x_[0])\n\ndef gen_bit_maps(baskets, bucket_num, hash_1, n):\n bit_map_1 = {i:0 for i in range(bucket_num)}\n for basket in baskets:\n combs = combinations(basket,n)\n for itset in combs:\n bit_map_1[hash_1(itset)] += 1\n bit_map_1 = {key:1 if value>= local_thres else 0 for key,value in bit_map_1.items()}\n return bit_map_1\n\ndef PCY(part):\n print(\"Using PCY\")\n freq_itsets = []\n baskets = [tup[1] for tup in part]\n N = max([len(x) for x in baskets])\n L = len(baskets)\n item_counter = Counter([ele for tup in baskets for ele in tup])\n prev_freq_itsets = [{ele} for ele,value in item_counter.items() if value>=local_thres]\n freq_itsets += prev_freq_itsets\n bucket_num = int(1/4*L*cb(len(prev_freq_itsets),2)/local_thres)+2\n hash_1 = lambda x: hash(tuple(sorted(list(x))))%bucket_num\n bit_map_1 = gen_bit_maps(baskets, bucket_num, hash_1, 2)\n skip = 0\n for n in range(2,N+1):\n #print(\"Constructing\")\n # Construct\n item_counter = []\n for i,j in combinations(prev_freq_itsets,2):\n if len(i&j)==(n-2):\n temp = i.union(j)\n row = [temp,0]\n if row not in item_counter and skip+bit_map_1[hash_1(temp)]:\n item_counter.append(row)\n # Count\n #print(\"Counting\")\n for row in item_counter:\n itemset = row[0]\n for basket in baskets:\n if itemset.issubset(basket):\n row[1] += 1\n prev_freq_itsets = [row[0] for row in item_counter if row[1]>=local_thres]\n freq_itsets += prev_freq_itsets\n if prev_freq_itsets == []:\n break\n # BitMap\n #print(\"bitmapping\")\n possible_comb_count = cb(len(prev_freq_itsets),2)\n if possible_comb_count>1000:\n bucket_num = int(3/4*possible_comb_count/local_thres)+2\n bit_map_1= gen_bit_maps(baskets, bucket_num, hash_1, n+1)\n skip = 0\n else: skip = 1\n return [tuple(sorted(list(i))) for i in freq_itsets]\n \ndef apriori(part):\n print(\"Using Apriori\")\n freq_itsets = []\n baskets = [tup[1] for tup in part]\n p = local_thres\n N = max([len(x) for x in baskets])\n item_counter = Counter([ele for tup in baskets for ele in tup])\n prev_freq_itsets = [{ele} for ele,value in item_counter.items() if value>=p]\n freq_itsets += prev_freq_itsets\n for n in range(2,N+1):\n # Construct\n item_counter = []\n for i,j in combinations(prev_freq_itsets,2):\n if len(i&j)==(n-2):\n row = [i.union(j),0]\n if row not in item_counter:\n item_counter.append(row)\n # Count\n for row in item_counter:\n itemset = row[0]\n for basket in baskets:\n if itemset.issubset(basket):\n row[1] += 1\n prev_freq_itsets = [row[0] for row in item_counter if row[1]>=p]\n freq_itsets += prev_freq_itsets\n if prev_freq_itsets == []:\n break\n return [tuple(sorted(list(i))) for i in freq_itsets]\n \ndef count_frequency(part,candidate_list):\n baskets = [tup[1] for tup in part]\n counter = {cand:0 for cand in candidate_list}\n for basket in baskets:\n for cand in candidate_list:\n if set(cand).issubset(basket):\n counter[cand] += 1\n return [(cand,value) for cand,value in counter.items()]\n \ndef printf(l):\n result = \"\"\n n = 1\n while True:\n temp = [str(i) for i in l if len(i)==n]\n if len(temp) == 0:\n break\n result += (\",\".join(temp)) + 2*\"\\n\"\n n += 1\n result = result.replace(\",)\",\")\")\n return result\n \ndef SON(rdd, alg=PCY):\n # Pass 1\n candidate_list = rdd.mapPartitions(alg).distinct().sortBy(lambda x: [len(x),str(x)]).collect()\n #print(candidate_list)\n # Pass 2\n frequent_itemsets = rdd.mapPartitions(lambda x: count_frequency(x,candidate_list)).reduceByKey(lambda a,b: a+b).filter(lambda x: x[1]>=thres).map(lambda x: x[0]).sortBy(lambda x: [len(x),str(x)]).collect()\n #print(frequent_itemsets)\n return candidate_list, frequent_itemsets\n \n \n\ndef main(mode:int, input_path, output_path):\n mode = int(mode)\n result = {}\n start_time = time.time()\n raw_rdd = sc.textFile(input_path)\n rdd = raw_rdd.zipWithIndex().filter(lambda x: x[1]>0)\n size = rdd.top(1,key=lambda x: x[1])[0][-1]\n num_partition = size//20000+1\n \n if mode==1:\n rdd = rdd.map(case_1_import)\n alg = PCY\n else:\n rdd = rdd.map(case_2_import)\n alg = apriori\n case_rdd = rdd.partitionBy(num_partition, lambda x: hash(x)).groupByKey().mapValues(set)\n global local_thres\n local_thres = thres/num_partition\n candidate_list, frequent_itemsets = SON(case_rdd, alg = alg)\n with open(output_path,\"w\") as file:\n file.write(\"Candidates:\\n\") \n file.write(printf(candidate_list)) \n file.write(\"Frequent Itemsets:\\n\") \n file.write(printf(frequent_itemsets)) \n duration = time.time()-start_time\n print(f\"Duration:{duration}\")\n return f\"Duration:{duration}\"\n\nsc = SparkContext(\"local[*]\",\"task\").getOrCreate()\nsc.setLogLevel(\"ERROR\")\nif __name__ == \"__main__\":\n import sys\n thres = int(sys.argv[2])\n local_thres = None\n main(sys.argv[1], sys.argv[3], sys.argv[4])\n \n ","repo_name":"owenrao/Data-Mining-USC-DSCI-553","sub_path":"Frequent_Itemset/task1.py","file_name":"task1.py","file_ext":"py","file_size_in_byte":5770,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"6284536200","text":"import sys\nimport random\nrandom.seed()\n\nmax_count = int(sys.argv[1])\n\nincoming_edges_count = random.randint(1,6)\noutcoming_edges_count = random.randint(1,6)\n\nincoming_edges = set([(random.randint(1, max_count), max_count) for i in range(1, incoming_edges_count + 1)])\noutcoming_edges = set([(max_count, random.randint(1, max_count)) for i in range(1, outcoming_edges_count + 1)])\n\nedges = incoming_edges.union(outcoming_edges)\nedges_selects = list(map(lambda edge: \"SELECT {} AS first, {} AS second \".format(edge[0], edge[1]), edges))\n\nedges_query_part = \"({})\".format(\" UNION \".join(edges_selects))\n\nwhole_query = \"INSERT INTO link (id_from, id_to) SELECT * FROM {} AS edge WHERE NOT EXISTS (SELECT * FROM link WHERE link.id_from = edge.first AND link.id_to = edge.second);\".format(edges_query_part)\n\nprint(whole_query)\n","repo_name":"sowmya6598/database-systems","sub_path":"recursive_longest_path/generate_new_article.py","file_name":"generate_new_article.py","file_ext":"py","file_size_in_byte":821,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"26231370484","text":"import os\n\npath = os.path.dirname(os.path.abspath(__file__))\ncutIdx = path.rfind(os.path.sep)\nworkspacePath = path[:cutIdx]\ndata_path = workspacePath + os.path.sep + 'Data' + os.path.sep\nimages_path = workspacePath + os.path.sep + 'Images' + os.path.sep\nannotations_path = data_path+\"Annotations\"+os.path.sep\nedfs_path = data_path+\"EEG\"+os.path.sep\n\nos.makedirs(data_path, exist_ok=True)\nos.makedirs(images_path, exist_ok=True)\nos.makedirs(annotations_path, exist_ok=True)\n\n\ndef get_edf_files():\n files = os.listdir(edfs_path)\n return files\n","repo_name":"mossdet/HFO_AED_Analysis","sub_path":"src/get_paths.py","file_name":"get_paths.py","file_ext":"py","file_size_in_byte":547,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"13413845975","text":"import logging\nimport utility\nimport json\nfrom asyncio import TimeoutError as async_TimeOutError\n\nlogger = logging.getLogger(__name__)\n\n\nasync def server_statsLogic(\n ctx, firestore, db, author, channelId, guildId, serverTitle, discordEmbed\n):\n channelList = utility.retrieveDb_data(db, option=\"channel-list\", title=guildId)\n channelVerify = await utility.checkChannel(\n db, firestore, channelList, channelId, guildId\n )\n\n if channelVerify:\n serverList = utility.retrieveDb_data(db, option=\"server-list\", title=guildId)\n\n if serverList is None:\n return await ctx.send(\n \"No server is set. Use `!serverconfig` for more info.\"\n )\n\n try:\n serverIP = serverList[serverTitle.replace(\"-\", \"\")][\"id\"].split(\":\")\n\n except (KeyError, AttributeError):\n availableServers = \"\\n\".join(\n \"{} (IP: {})\".format(value[\"name\"], value[\"id\"])\n for key, value in serverList.items()\n )\n if availableServers == \"\":\n availableServers = \"No server added yet\"\n usageMessage = \"`!serverstats [name]`\\n------\"\n embed = discordEmbed(\n title=\"GvAW Server List\",\n description=\"Check status of a server by the assigned name\",\n color=0xE74C3C,\n )\n\n embed.set_thumbnail(url=utility.gvawLogo_url)\n embed.add_field(name=\"__Usage__\", value=usageMessage)\n embed.add_field(\n name=\"__Available Servers__\", value=f\"{availableServers}\\n------\"\n )\n return await ctx.send(embed=embed)\n\n dcsCheck = serverList[serverTitle.replace(\"-\", \"\")][\"name\"].split(\"-\")\n if dcsCheck[-1] == \"dcs\":\n from main import keys\n\n dcsKeys = {\n \"DCS_USERNAME\": keys[\"DCS_USERNAME\"],\n \"DCS_PASSWORD\": keys[\"DCS_PASSWORD\"],\n }\n serverUrl = \"https://www.digitalcombatsimulator.com/en/auth/\"\n servers_body = await utility.getDCS_data(\n serverUrl, params=None, key=dcsKeys\n )\n servers = json.loads(servers_body)\n serverIndex = next(\n (\n index\n for (index, d) in enumerate(servers[\"SERVERS\"])\n if d[\"IP_ADDRESS\"] == serverIP[0]\n ),\n None,\n )\n\n if serverIndex == None:\n serverStats = \"offline\"\n return await ctx.send(\n f\"`{serverTitle} ({serverIP[0]}) is {serverStats}.`\"\n )\n\n server = servers[\"SERVERS\"][serverIndex]\n serverStats = \"online\"\n serverName = server[\"NAME\"]\n serverIP = server[\"IP_ADDRESS\"]\n serverPort = server[\"PORT\"]\n scenario = server[\"MISSION_NAME\"]\n scenarioUptime = server[\"MISSION_TIME_FORMATTED\"]\n players = server[\"PLAYERS\"]\n maxPlayers = server[\"PLAYERS_MAX\"]\n\n embed = discordEmbed(\n title=serverName, description=serverStats.title(), color=0x00FF00\n )\n embed.set_thumbnail(url=utility.gvawLogo_url)\n embed.add_field(\n name=\"__IP Address__\", value=f\"{serverIP}:{serverPort}\", inline=False\n )\n embed.add_field(name=\"__Scenario__\", value=scenario, inline=False)\n embed.add_field(name=\"__Uptime__\", value=scenarioUptime, inline=False)\n embed.add_field(\n name=\"__Players__\",\n value=f\"{players}/{maxPlayers}\",\n inline=True,\n )\n\n return await ctx.send(embed=embed)\n\n from a2s import ainfo\n\n server_queryPort = 2303\n if len(serverIP) == 2:\n server_queryPort = serverIP[1]\n\n serverAddress = (serverIP[0], server_queryPort)\n\n try:\n server = await ainfo(serverAddress)\n\n except (ConnectionRefusedError, async_TimeOutError):\n serverStats = \"offline\"\n return await ctx.send(f\"`{serverTitle} ({serverIP[0]}) is {serverStats}.`\")\n\n except Exception as e:\n logger.error(e)\n return await ctx.send(\"Cannot retrieve data from server.\")\n\n serverStats = \"online\"\n if server.map_name == \"\":\n serverStats = \"mission_select\"\n\n serverDescription = serverStats.title()\n if serverStats == \"mission_select\":\n serverDescription = \"Selecting Mission\"\n\n serverName = server.server_name\n server_gamePort = server.port\n activePlayers = server.player_count\n maxPlayers = server.max_players\n steamURL = f\"steam://connect/{serverIP[0]}:{server_queryPort}\"\n embed = discordEmbed(\n title=serverName, description=serverDescription, color=0x00FF00\n )\n embed.set_thumbnail(url=utility.gvawLogo_url)\n embed.add_field(\n name=\"__IP Address__\",\n value=f\"{serverIP[0]}:{server_gamePort}\",\n inline=False,\n )\n embed.add_field(\n name=\"__Players__\", value=f\"{activePlayers}/{maxPlayers}\", inline=False\n )\n\n if serverStats == \"online\":\n serverMap = server.map_name\n serverMission = server.game\n\n embed.add_field(name=\"__Map__\", value=serverMap, inline=False)\n embed.add_field(name=\"__Mission__\", value=serverMission, inline=False)\n embed.add_field(name=\"__Steam URL__\", value=steamURL, inline=False)\n\n return await ctx.send(embed=embed)\n\n else:\n return await ctx.send(\n \"`This channel is not authorized. Use !channelconfig to authorize channels.`\"\n )","repo_name":"farhannysf/apx_bot","sub_path":"main/gvaw_commands/serverstats.py","file_name":"serverstats.py","file_ext":"py","file_size_in_byte":5796,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"81"} +{"seq_id":"22095121492","text":"'''\nCS326 Lab 2\nAuthor: D. Schuurman\nCompute integral of sin(x)\n'''\n\nfrom math import sin\n\ndef integrate_sin(a,b,n):\n ''' Integrate sin(x) from a to b with n steps\n '''\n dx = (b-a)/n\n sum = 0\n for i in range(0,n):\n sum += sin(a+i*dx)\n return sum*dx\n\nintegral = integrate_sin(0, 3.14159, 10000000)\nprint(f'result = {integral}')\n","repo_name":"dschuurman/cs326","sub_path":"lab2/compute.py","file_name":"compute.py","file_ext":"py","file_size_in_byte":344,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"8830123550","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Aug 17 22:34:45 2021\n\n@author: Marian\n\"\"\"\n\ndef buscar_precio(elemento):\n with open('../Data/precios.csv', 'rt', encoding = \"utf8\") as f:\n fruta_esta = False\n for line in f:\n fruta = line.split(\",\")\n if elemento == fruta[0]: \n fruta_esta = True\n print(f'El costo de {elemento} es {fruta[1]}')\n break\n if not fruta_esta:\n print('La fruta consultada no está en la lista')\n \n\nfruta_a_consultar = input('Ingrese una fruta o verdura para conocer su precio: ')\nbuscar_precio(fruta_a_consultar)\n ","repo_name":"GonzaloMonteodorisio/ejercicios-python-unsam","sub_path":"Clase02/buscarpreciofruta2.7.py","file_name":"buscarpreciofruta2.7.py","file_ext":"py","file_size_in_byte":665,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"40655580884","text":"import sqlite3\ntry:\n sqlite_connection=sqlite3.connect('shop.db')\n cursor=sqlite_connection.cursor()\n print('Succsessfully conneced o SQLite')\n data=cursor.execute(\"Select * from Product\")\n for row in data:\n print(row)\n cursor.close()\nexcept sqlite3.Error as error:\n print('Error while connection sqlite',error)","repo_name":"tecnocristi21/Online_shop","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":339,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"14614513858","text":"# -*- coding: utf-8 -*-\n# @Time : 2021/9/18 下午11:14\n# @Author : DaiPuWei\n# @Email : 771830171@qq.com\n# @File : cspdarknet.py\n# @Software: PyCharm\n\n\"\"\"\n 这是CSPDarkNet模型的定义脚本\n\"\"\"\n\nfrom functools import wraps\n\nimport tensorflow as tf\nfrom tensorflow.keras.layers import Add\nfrom tensorflow.keras.layers import Conv2D\nfrom tensorflow.keras.layers import Lambda\nfrom tensorflow.keras.layers import Concatenate\nfrom tensorflow.keras.layers import MaxPooling2D\nfrom tensorflow.keras.layers import ZeroPadding2D\nfrom tensorflow.keras.layers import BatchNormalization\nfrom tensorflow.keras.initializers import RandomNormal\n\nfrom utils.model_utils import compose\nfrom model.layer.activition import Mish\nfrom model.backbone.darknet import DarknetConv2D_BN_Leaky\n\n@wraps(Conv2D)\ndef DarknetConv2D(*args, **kwargs):\n # darknet_conv_kwargs = {'kernel_regularizer': l2(5e-4)}\n darknet_conv_kwargs = {'kernel_initializer': RandomNormal(stddev=0.02)}\n darknet_conv_kwargs['padding'] = 'valid' if kwargs.get('strides') == (2, 2) else 'same'\n darknet_conv_kwargs.update(kwargs)\n return Conv2D(*args, **darknet_conv_kwargs)\n\ndef DarknetConv2D_BN_Mish(*args, **kwargs):\n no_bias_kwargs = {'use_bias': False}\n no_bias_kwargs.update(kwargs)\n return compose(\n DarknetConv2D(*args, **no_bias_kwargs),\n BatchNormalization(),\n Mish())\n\ndef split(feature_tesnsor,group=2,group_id=1):\n '''\n 这是均分特征张量的函数\n Args:\n feature_tesnsor: 特征张量\n group: 均分个数,默认为2\n group_id: 返回特征张量id,默认为1\n Returns:\n '''\n split_features = tf.split(feature_tesnsor,num_or_size_splits=group,axis=-1)\n return split_features[group_id]\n\ndef resblock_body_mish(x, num_filters, num_blocks,attention_type=None):\n '''\n 这是CSPDarkNet-53中的残差模块的定义函数\n Args:\n x: 输入张量\n num_filters: 卷积层的输出通道数\n num_blocks: 模块个数\n attention_type: 注意力机制类型,默认为None,即不使用注意力机制\n Returns:\n '''\n x = ZeroPadding2D(((1,0),(1,0)))(x)\n x = DarknetConv2D_BN_Mish(num_filters, (3,3), strides=(2,2))(x)\n for i in range(num_blocks):\n y = DarknetConv2D_BN_Mish(num_filters//2, (1,1))(x)\n y = DarknetConv2D_BN_Mish(num_filters, (3,3))(y)\n if attention_type is None: # 不使用注意力机制\n pass\n elif attention_type == 'se': # SE注意力机制\n from model.layer.attention import se_attention\n y = se_attention(y)\n else: # 后续接口\n pass\n x = Add()([x,y])\n return x\n\ndef csp_resblock_body_mish(x, num_filters, num_blocks, all_narrow=True,attention_type=None):\n '''\n 这是CSDDarknet-53中CSP残差模块的定义函数\n Args:\n x: 输入张量\n num_filters: 卷积层的输出通道数\n num_blocks: 模块个数\n all_narrow: 是否使用窄通道标志位\n attention_type: 注意力机制类型,默认为None,即不使用注意力机制\n Returns:\n '''\n\n preconv1 = ZeroPadding2D(((1, 0), (1, 0)))(x)\n preconv1 = DarknetConv2D_BN_Mish(num_filters, (3, 3), strides=(2, 2))(preconv1)\n\n shortconv = DarknetConv2D_BN_Mish(num_filters // 2 if all_narrow else num_filters, (1, 1))(preconv1)\n mainconv = DarknetConv2D_BN_Mish(num_filters // 2 if all_narrow else num_filters, (1, 1))(preconv1)\n for i in range(num_blocks):\n y = compose(\n DarknetConv2D_BN_Mish(num_filters // 2, (1, 1)),\n DarknetConv2D_BN_Mish(num_filters // 2 if all_narrow else num_filters, (3, 3)))(mainconv)\n if attention_type is None: # 不使用注意力机制\n pass\n elif attention_type == 'se': # SE注意力机制\n from model.layer.attention import se_attention\n y = se_attention(y)\n else: # 后续接口\n pass\n mainconv = Add()([mainconv, y])\n postconv = DarknetConv2D_BN_Mish(num_filters // 2 if all_narrow else num_filters, (1, 1))(mainconv)\n route = Concatenate()([postconv, shortconv])\n return DarknetConv2D_BN_Mish(num_filters, (1, 1))(route)\n\ndef tiny_resblock_body_leaky(x, num_filters,attention_type):\n '''\n 这是yolov4-tiny中残差模块的初始化函数\n Args:\n x: 输入张量\n num_filters: 卷积层的输出通道数\n attention_type: 注意力机制类型,默认为None,即不使用注意力机制\n Returns:\n '''\n conv1 = DarknetConv2D_BN_Leaky(num_filters, (3, 3))(x)\n split_feature1 = Lambda(split,arguments={'group':2,\n 'group_id':1})(conv1)\n x = DarknetConv2D_BN_Leaky(num_filters//2,(3,3))(split_feature1)\n split_feature2 = x\n x = DarknetConv2D_BN_Leaky(num_filters//2,(3,3))(x)\n x = Concatenate()([split_feature2,x])\n x = DarknetConv2D_BN_Leaky(num_filters,(1,1))(x)\n if attention_type is None: # 不使用注意力机制\n pass\n elif attention_type == 'se': # SE注意力机制\n from model.layer.attention import se_attention\n x = se_attention(x)\n else: # 后续接口\n pass\n feat = x\n x = Concatenate()([conv1,x])\n x = MaxPooling2D(pool_size=(2,2))(x)\n return x,feat\n\ndef yolov4_cspdarknet_backbone(image_input,base=8,attention_type=None):\n '''\n 这是YOLOv4中CSPDarknet-53的backbone定义函数\n Args:\n image_input: 图像输入\n base: 卷积基数,默认为8,可以控制卷积层通道数大小,在一定程度上可以实现模型剪枝\n attention_type: 注意力机制类型,默认为None,即不使用注意力机制\n Returns:\n '''\n x = DarknetConv2D_BN_Mish(base*4, (3, 3))(image_input)\n x = csp_resblock_body_mish(x, base*8, 1, False, attention_type)\n x = csp_resblock_body_mish(x, base*16, 2, True, attention_type)\n x = csp_resblock_body_mish(x, base*32, 8, True, attention_type)\n feat1 = x\n x = csp_resblock_body_mish(x, base*64, 8, True, attention_type)\n feat2 = x\n x = csp_resblock_body_mish(x, base*128, 4, True, attention_type)\n feat3 = x\n return feat1, feat2, feat3\n\ndef yolov4_csp_cspdarknet_backbone(image_input,base=8,attention_type=None):\n '''\n 这是YOLOv4-csp中CSPDarknet-53的backbone定义函数\n Args:\n image_input: 图像输入\n base: 卷积基数,默认为8,可以控制卷积层通道数大小,在一定程度上可以实现模型剪枝\n attention_type: 注意力机制类型,默认为None,即不使用注意力机制\n Returns:\n '''\n x = DarknetConv2D_BN_Mish(base*4, (3, 3))(image_input)\n x = resblock_body_mish(x, base*8, 1, attention_type)\n x = csp_resblock_body_mish(x, base*16, 2, True, attention_type)\n x = csp_resblock_body_mish(x, base*32, 8, True, attention_type)\n feat1 = x\n x = csp_resblock_body_mish(x, base*64, 8, True, attention_type)\n feat2 = x\n x = csp_resblock_body_mish(x, base*128, 4, True, attention_type)\n feat3 = x\n return feat1,feat2,feat3\n\ndef yolov4_p5_cspdarknet_backbone(image_input,base=8,attention_type=None):\n '''\n 这是YOLOv4-p5中CSPDarknet的backbone定义函数\n Args:\n image_input: 图像输入\n base: 卷积基数,默认为8,可以控制卷积层通道数大小,在一定程度上可以实现模型剪枝\n attention_type: 注意力机制类型,默认为None,即不使用注意力机制\n Returns:\n '''\n x = DarknetConv2D_BN_Mish(base*4, (3, 3))(image_input)\n x = csp_resblock_body_mish(x, base*8, 1, True, attention_type)\n x = csp_resblock_body_mish(x, base*16, 3, True, attention_type)\n x = csp_resblock_body_mish(x, base*32, 15, True, attention_type)\n feat1 = x\n x = csp_resblock_body_mish(x, base*64, 15, True, attention_type)\n feat2 = x\n x = csp_resblock_body_mish(x, base*128, 7, True, attention_type)\n feat3 = x\n return feat1,feat2,feat3\n\ndef yolov4_p6_cspdarknet_backbone(image_input,base=8,attention_type=None):\n '''\n 这是YOLOv4-p6中CSPDarknet的backbone定义函数\n Args:\n image_input: 图像输入\n base: 卷积基数,默认为8,可以控制卷积层通道数大小,在一定程度上可以实现模型剪枝\n attention_type: 注意力机制类型,默认为None,即不使用注意力机制\n Returns:\n '''\n x = DarknetConv2D_BN_Mish(base*4, (3, 3))(image_input)\n x = csp_resblock_body_mish(x, base*8, 1, True, attention_type)\n x = csp_resblock_body_mish(x, base*16, 3, True, attention_type)\n x = csp_resblock_body_mish(x, base*32, 15, True, attention_type)\n feat1 = x\n x = csp_resblock_body_mish(x, base*64, 15, True, attention_type)\n feat2 = x\n x = csp_resblock_body_mish(x, base*128, 7, True, attention_type)\n feat3 = x\n x = csp_resblock_body_mish(x, base*128, 7, True, attention_type)\n feat4 = x\n return feat1,feat2,feat3,feat4\n\ndef yolov4_p7_cspdarknet_backbone(image_input,base=8,attention_type=None):\n '''\n 这是YOLOv4-p7中CSPDarknet的backbone定义函数\n Args:\n image_input: 图像输入\n base: 卷积基数,默认为8,可以控制卷积层通道数大小,在一定程度上可以实现模型剪枝\n attention_type: 注意力机制类型,默认为None,即不使用注意力机制\n Returns:\n '''\n x = DarknetConv2D_BN_Mish(base*4, (3, 3))(image_input)\n x = csp_resblock_body_mish(x, base*8, 1, True, attention_type)\n x = csp_resblock_body_mish(x, base*16, 3, True, attention_type)\n x = csp_resblock_body_mish(x, base*32, 15, True, attention_type)\n feat1 = x\n x = csp_resblock_body_mish(x, base*64, 15, True, attention_type)\n feat2 = x\n x = csp_resblock_body_mish(x, base*128, 7, True, attention_type)\n feat3 = x\n x = csp_resblock_body_mish(x, base*128, 7, True, attention_type)\n feat4 = x\n x = csp_resblock_body_mish(x, base*128, 7, True, attention_type)\n feat5 = x\n return feat1,feat2,feat3,feat4,feat5\n\ndef yolov4_tiny_cspdarknet_backbone(image_input,base=8,attention_type=None):\n '''\n 这是YOLOv4-tiny中CSPDarknet的backbone定义函数\n Args:\n image_input: 图像输入\n base: 卷积基数,默认为8,可以控制卷积层通道数大小,在一定程度上可以实现模型剪枝\n attention_type: 注意力机制类型,默认为None,即不使用注意力机制\n Returns:\n '''\n x = DarknetConv2D_BN_Leaky(32, (3, 3))(image_input)\n x = ZeroPadding2D(((1, 0), (1, 0)))(x)\n x = DarknetConv2D_BN_Leaky(32, (3, 3), strides=(2, 2))(x)\n x = ZeroPadding2D(((1, 0), (1, 0)))(x)\n x = DarknetConv2D_BN_Leaky(64, (3, 3), strides=(2, 2))(x)\n\n x, _ = tiny_resblock_body_leaky(x, base*8)\n x, _ = tiny_resblock_body_leaky(x, base*16)\n x, feat1 = tiny_resblock_body_leaky(x, base*32,attention_type)\n x = DarknetConv2D_BN_Leaky(base*64, (3, 3))(x)\n feat2 = x\n return feat1, feat2","repo_name":"Daipuwei/YOLO-tf2","sub_path":"model/backbone/cspdarknet.py","file_name":"cspdarknet.py","file_ext":"py","file_size_in_byte":11150,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"24985225294","text":" \n\n#/bin/python3.8\n'''\nDislog.py\nScript to log all discord messages the user(s) have access to.\n'''\nimport discord\nimport asyncio\nimport time\nfrom datetime import datetime\nfrom videoAscii import video2ascii, progress_bar\n\nCHANNEL_ID = 204621105720328193\nVIDEO_PATH = 'BadApple.mp4'\n\nTOKENS = [\n \"tokens go here\",\n \"#2 token\",\n \"etc\"\n]\n\nclass discordPlayer:\n '''\n Class to manage frames and sending them\n '''\n def __init__(self, accounts):\n self.accounts = accounts\n self.frame_rate = len(accounts)#one message per account per second\n print(f'Using framerate {self.frame_rate}.')\n print('-Loading video frames as ascii.')\n self.ascii_frames = video2ascii(VIDEO_PATH, frame_size=[57,32], frame_rate=self.frame_rate, ascii_chars=['⬜', '🔲', 'âš«', '⬛'])\n print('Done')\n async def run(self):\n def check_ready(accounts):\n for acc in accounts:\n if not acc.ready:\n return False\n return True\n while True:\n if check_ready(self.accounts):\n break\n else:\n await asyncio.sleep(1)\n await self.play()\n \n async def play(self):\n frame_count = len(self.ascii_frames)\n delay = 1/self.frame_rate\n frame_index = 0\n last_frame = time.time()\n print('Playing pixel animation:')\n while frame_index < frame_count:\n for acc in self.accounts:\n if frame_index >= len(self.ascii_frames):\n break\n\n await acc.send_frame(self.ascii_frames[frame_index])\n\n progress_bar(frame_index+1, frame_count)\n\n frame_index += 1\n t = last_frame\n last_frame = time.time()\n\n #print(f'waiting {delay-(last_frame-t)} seconds')\n await asyncio.sleep((delay-(last_frame-t))-0.01)\n print('Done.')\n exit()\n \n\nclass DiscordUser:\n '''\n A new instance of this class is created for every token.\n '''\n def __init__(self, token):\n self.ready = False\n intents=discord.Intents.default()\n #intents.members = True\n self.client = discord.Client(intents=intents)\n self.token = token\n self.client.on_ready = self.client.event(self.on_ready)\n\n async def run(self):\n try:\n await self.client.start(self.token, bot=False)\n except discord.errors.LoginFailure:\n print(f\"Account with token:\\n{self.token}\\n is unable to login.\")\n exit()\n\n async def on_ready(self):\n self.channel = self.client.get_channel(CHANNEL_ID)\n self.ready = True\n print(f'Logged in as bot {self.client.user.name}')\n return\n \n async def send_frame(self, frame):\n try:\n await self.channel.send(f'```{frame}```')\n except Exception:\n pass\n return\n \n\n#start\nprint(\"Starting:\")\nloop = asyncio.get_event_loop()\n\ntasks = []\naccounts = []\n\n#login accounts\nfor token in TOKENS:\n user = DiscordUser(token)\n tasks.append(loop.create_task(user.run()))\n accounts.append(user)\n#run discordPlayer\nplayer = discordPlayer(accounts)\ntasks.append(loop.create_task(player.run()))\n\nprint(\"-Running threads\")\ngathered = asyncio.gather(*tasks, loop=loop)\nloop.run_until_complete(gathered)\n","repo_name":"RootInit/bad-apple-discord-live","sub_path":"pixelGif.py","file_name":"pixelGif.py","file_ext":"py","file_size_in_byte":3390,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"20705566939","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport os\nimport sklearn.cluster as cluster\nimport multiprocessing as mp\n\nfrom utils import fast_knns2spmat, build_knns\n\n\ndef kmeans(feat, n_clusters, **kwargs):\n kmeans = cluster.KMeans(n_clusters=n_clusters,\n n_jobs=mp.cpu_count(),\n random_state=0).fit(feat)\n return kmeans.labels_\n\n\ndef mini_batch_kmeans(feat, n_clusters, batch_size, **kwargs):\n kmeans = cluster.MiniBatchKMeans(n_clusters=n_clusters,\n batch_size=batch_size,\n random_state=0).fit(feat)\n return kmeans.labels_\n\n\ndef spectral(feat, n_clusters, **kwargs):\n spectral = cluster.SpectralClustering(n_clusters=n_clusters,\n assign_labels=\"discretize\",\n affinity=\"nearest_neighbors\",\n random_state=0).fit(feat)\n return spectral.labels_\n\n\ndef dask_spectral(feat, n_clusters, **kwargs):\n from dask_ml.cluster import SpectralClustering\n spectral = SpectralClustering(n_clusters=n_clusters,\n affinity='rbf',\n random_state=0).fit(feat)\n return spectral.labels_.compute()\n\n\ndef hierarchy(feat, n_clusters, knn, **kwargs):\n from sklearn.neighbors import kneighbors_graph\n knn_graph = kneighbors_graph(feat, knn, include_self=False)\n hierarchy = cluster.AgglomerativeClustering(n_clusters=n_clusters,\n connectivity=knn_graph,\n linkage='ward').fit(feat)\n return hierarchy.labels_\n\n\ndef fast_hierarchy(feat, distance, hmethod='single', **kwargs):\n import fastcluster\n import scipy.cluster\n links = fastcluster.linkage_vector(feat, method=hmethod)\n labels_ = scipy.cluster.hierarchy.fcluster(links,\n distance,\n criterion='distance')\n return labels_\n\n\ndef dbscan(feat, eps, min_samples, **kwargs):\n db = cluster.DBSCAN(eps=eps,\n min_samples=min_samples,\n n_jobs=mp.cpu_count()).fit(feat)\n return db.labels_\n\n\ndef knn_dbscan(feats, eps, min_samples, prefix, name, knn_method, knn, th_sim,\n **kwargs):\n knn_prefix = os.path.join(prefix, 'knns', name)\n knns = build_knns(knn_prefix, feats, knn_method, knn)\n sparse_affinity = fast_knns2spmat(knns, knn, th_sim, use_sim=False)\n db = cluster.DBSCAN(eps=eps,\n min_samples=min_samples,\n n_jobs=mp.cpu_count(),\n metric='precomputed').fit(sparse_affinity)\n return db.labels_\n\n\ndef hdbscan(feat, min_samples, **kwargs):\n import hdbscan\n db = hdbscan.HDBSCAN(min_cluster_size=min_samples)\n labels_ = db.fit_predict(feat)\n return labels_\n\n\ndef meanshift(feat, bw, num_process, min_bin_freq, **kwargs):\n print('#num_process:', num_process)\n print('min_bin_freq:', min_bin_freq)\n ms = cluster.MeanShift(bandwidth=bw,\n n_jobs=num_process,\n min_bin_freq=min_bin_freq).fit(feat)\n return ms.labels_\n","repo_name":"yl-1993/learn-to-cluster","sub_path":"baseline/sklearn_cluster.py","file_name":"sklearn_cluster.py","file_ext":"py","file_size_in_byte":3309,"program_lang":"python","lang":"en","doc_type":"code","stars":686,"dataset":"github-code","pt":"81"} +{"seq_id":"7337905317","text":"\"\"\"Extended Reality Open Recording (XROR).\"\"\"\n\nimport numpy as np\nimport fpzip\nimport bson\nimport time\nimport datetime\nfrom .Bsor import make_bsor\nfrom copy import deepcopy\n\nclass XROR:\n \"\"\"\n Represents an Extended Reality Open Recording (XROR) object.\n\n Contains a recording consisting of motion data and events generated by a virtual or augmented reality application.\n \"\"\"\n\n def __init__(self, id = None, name = None, timestamp = None):\n \"\"\"\n Initialize an empty Extended Reality Open Recording (XROR) object.\n\n Parameters:\n id:A unique identifier for this recording.\n name(str):The name of this recording.\n timestamp(int):Unix timestamp for the start of this recording.\n \"\"\"\n self.data = {\n \"$schema\": \"https://metaguard.github.io/xror/schema/v1.0.0/schema.json\"\n }\n if (id): self.data['$id'] = id\n self.data['info'] = {}\n if (name): self.info['name'] = str(name)\n if (timestamp): self.data['info']['timestamp'] = int(timestamp)\n self.data['info']['hardware'] = {}\n self.data['info']['hardware']['devices'] = []\n self.data['frames'] = []\n self.data['events'] = []\n\n def __repr__(self):\n \"\"\"Return a string representation of the XROR data.\"\"\"\n return repr(self.data)\n\n def addDevice(self, name = None, type = None, joint = None, axes = ['x', 'y', 'z', 'i', 'j', 'k', '1'], offsets = None):\n \"\"\"\n Add a new hardware devices associated with this XROR recording.\n\n Parameters:\n name(str):The name of the hardware device.\n type(str):The type of the hardware device.\n joint(str):The location of the hardware device on the user's body.\n axes(list):The names of the tracked dimensions associated with this device.\n offsets(list):The offsets of the tracked dimensions associated with this device relative to the origin.\n \"\"\"\n device = {}\n if (name): device['name'] = name\n if (type): device['type'] = type\n if (joint): device['joint'] = joint\n device['axes'] = axes\n if (offsets): device['offsets'] = offsets\n self.data['info']['hardware']['devices'].append(device)\n\n def setApp(self, id = None, name = None, version = None):\n \"\"\"\n Set metadata about the application associated with this XROR recording.\n\n Parameters:\n id:A unique identifier for the application associated with this recording.\n name(str):The name of the application associated with this recording.\n version(str):The version number of the application associated with this recording.\n \"\"\"\n if ('software' not in self.data['info']): self.data['info']['software'] = {}\n app = {}\n if (id): app['id'] = id\n if (name): app['name'] = name\n if (version): app['version'] = version\n self.data['info']['software']['app'] = app\n\n def addExtension(self, id = None, name = None, version = None):\n \"\"\"\n Add a new extension to the application associated with this XROR recording.\n\n Parameters:\n id:A unique identifier for the extension.\n name(str):The name of the extension.\n version(str):The version number of the extension.\n \"\"\"\n if ('software' not in self.data['info']): self.data['info']['software'] = {}\n if ('app' not in self.data['info']['software']): self.data['info']['software']['app'] = {}\n if ('extensions' not in self.data['info']['software']['app']): self.data['info']['software']['app']['extensions'] = []\n\n mod = {}\n if (id): mod['id'] = id\n if (name): mod['name'] = name\n if (version): mod['version'] = version\n self.data['info']['software']['app']['extensions'].append(mod)\n\n def setEnvironment(self, id = None, name = None):\n \"\"\"\n Set metadata about the virtual environment associated with this XROR recording.\n\n Parameters:\n id:A unique identifier for the environment associated with this recording.\n name(str):The name of the virtual environment associated with this recording.\n \"\"\"\n if ('software' not in self.data['info']): self.data['info']['software'] = {}\n env = {}\n if (id): env['id'] = id\n if (name): env['name'] = name\n self.data['info']['software']['environment'] = env\n\n def setActivity(self, id = None, name = None):\n \"\"\"\n Set metadata about the activity associated with this XROR recording.\n\n Parameters:\n id:A unique identifier for the activity associated with this recording.\n name(str):The name of the activity associated with this recording.\n \"\"\"\n if ('software' not in self.data['info']): self.data['info']['software'] = {}\n act = {}\n if (id): act['id'] = id\n if (name): act['name'] = name\n self.data['info']['software']['activity'] = act\n\n def setUser(self, id = None, name = None):\n \"\"\"\n Set metadata about the user associated with this XROR recording.\n\n Parameters:\n id:A unique identifier for the user associated with this recording.\n name(str):The name of the user associated with this recording.\n \"\"\"\n usr = {}\n if (id): usr['id'] = id\n if (name): usr['name'] = name\n self.data['info']['user'] = usr\n\n def addFrame(self, time, data):\n \"\"\"\n Add a single frame of motion data to this XROR recording.\n\n Parameters:\n time(float):Time of the frame in seconds elapsed since the start of the recording.\n data(list):Telemetry data associated with the frame, with one number for each tracked axis specified in devices.\n \"\"\"\n self.data['frames'].append([time] + data)\n\n def addEventType(self, id = None, name = None, attr = None, floatData = None, otherData = None):\n \"\"\"\n Add a new type of event to this XROR recording.\n\n Parameters:\n id:A unique identifier for the type of event.\n name(str):The name of the type of event.\n attr(list):The names of the attributes associated with this type of event. Lists all floating-point attributes first, followed by all other attributes.\n floatData(list):The occurrences of the event type contained in this recording; 2D array of floats, with one entry per occurrence. Each entry starts with the time of the event in seconds elapsed since the start of the recording, and then includes the floating point attribute values associated with the occurrence.\n otherData(list):The occurrences of the event type contained in this recording; consists of a 2D array of values, with one entry per occurrence. Each entry includes the non-float attribute values associated with the occurrence.\n \"\"\"\n if ('events' not in self.data): self.data['events'] = []\n ev = {}\n if (id): ev['id'] = id\n if (name): ev['name'] = name\n if (attr): ev['attr'] = attr\n if (floatData): ev['floatData'] = floatData\n if (otherData): ev['otherData'] = otherData\n self.data['events'].append(ev)\n\n def addEvent(self, type, time, floatData = [], otherData = None):\n \"\"\"\n Add a single new event occurrence to this XROR recording.\n\n Parameters:\n type(str):The id of the type of event to add.\n time(float):The time of the event occurrence in seconds elapsed since the start of the recording.\n floatData(list):The floating point attribute values associated with the occurrence.\n otherData(list):The non-float attribute values associated with the occurrence.\n \"\"\"\n idx = None;\n for i in range(len(self.data['events'])):\n if (self.data['events'][i]['id'] == type): idx = i\n if ('floatData' not in self.data['events'][idx]): self.data['events'][idx]['floatData'] = []\n self.data['events'][idx]['floatData'].append([time] + floatData)\n if (otherData):\n if ('otherData' not in self.data['events'][idx]): self.data['events'][idx]['otherData'] = []\n self.data['events'][idx]['otherData'].append(otherData)\n\n def getEvents(self, type):\n \"\"\"\n Get all occurrences of event of specified type.\n\n Parameters:\n type(str):The id of the type of event to fetch occurrences of.\n \"\"\"\n idx = None;\n for i in range(len(self.data['events'])):\n if (self.data['events'][i]['id'] == type): idx = i\n if (idx == None): return None\n events = []\n if ('floatData' not in self.data['events'][idx]): return []\n keys = ['time'] + self.data['events'][idx]['attr']\n for i in range(len(self.data['events'][idx]['floatData'])):\n if self.data['events'][idx]['floatData'][i][0] == -1: continue\n event = {}\n for j in range(len(self.data['events'][idx]['floatData'][i])):\n event[keys[j]] = self.data['events'][idx]['floatData'][i][j]\n if 'otherData' in self.data['events'][idx]:\n for k in range(len(self.data['events'][idx]['otherData'][i])):\n event[keys[j+k+1]] = self.data['events'][idx]['otherData'][i][k]\n events.append(event)\n return events\n\n def pack(self):\n \"\"\"\n Generate raw data for an XROR file from this object.\n\n Compresses telemetry and event data using fpzip, then packs object using BSON.\n \"\"\"\n def compress(array):\n try:\n floats = np.array(array, dtype=np.float32)\n bytes = fpzip.compress(floats)\n return bson.binary.Binary(bytes)\n except:\n floats = np.array(array, dtype=np.float32)\n padding = np.array(np.full(np.shape(array), -1))\n padded = np.vstack([floats, padding, padding])\n bytes = fpzip.compress(padded)\n return bson.binary.Binary(bytes)\n\n data = deepcopy(self.data)\n\n if ('timestamp' in data['info']): data['info']['timestamp'] = datetime.datetime.fromtimestamp(data['info']['timestamp'], datetime.timezone.utc)\n\n data['frames'] = compress(data['frames'])\n\n for i in range(len(data['events'])):\n if ('floatData' in data['events'][i]):\n data['events'][i]['floatData'] = compress(data['events'][i]['floatData'])\n\n return bson.encode(data)\n\n def toBSOR(self):\n \"\"\"Generate raw data for a BSOR file from this object.\"\"\"\n bytes = bytearray()\n def addInt(i):\n bytes.extend(int(i).to_bytes(4, 'little'));\n\n def addLong(i):\n bytes.extend(int(i).to_bytes(8, 'little'));\n\n def addFloat(float):\n bytes.extend(np.array([float], dtype=np.float32).tobytes());\n\n def addByte(byte):\n bytes.extend(byte.to_bytes(1, 'little'))\n\n def addString(str):\n enc = str.encode('utf-8')\n addInt(len(str))\n bytes.extend(enc)\n\n # Info Structure\n addInt(0x442d3d69)\n addByte(1)\n addByte(0)\n addString(self.data['info']['software']['app']['extensions'][0]['version'])\n addString(self.data['info']['software']['app']['version'])\n addString(str(self.data['info']['timestamp']))\n addString(self.data['info']['user']['id'])\n addString(self.data['info']['user']['name'] if 'name' in self.data['info']['user'] else '')\n addString(self.data['info']['software']['runtime'])\n addString(self.data['info']['software']['api'])\n addString(self.data['info']['hardware']['devices'][0]['name'] if 'name' in self.data['info']['hardware']['devices'][0] else '')\n addString(self.data['info']['hardware']['devices'][2]['name'] if 'name' in self.data['info']['hardware']['devices'][2] else '')\n for attr in ['songHash', 'name', 'mapper', 'difficulty']:\n addString(self.data['info']['software']['activity'][attr])\n addInt(self.data['info']['software']['activity']['score'])\n addString(self.data['info']['software']['activity']['mode'])\n addString(self.data['info']['software']['environment']['name'])\n if ('modifiers' in self.data['info']['software']['activity']): addString(self.data['info']['software']['activity']['modifiers'])\n else: addString(\"\")\n if ('jumpDistance' in self.data['info']['software']['activity']): addFloat(self.data['info']['software']['activity']['jumpDistance'])\n else: addFloat(0.0)\n if ('leftHanded' in self.data['info']['software']['activity']): addByte(self.data['info']['software']['activity']['leftHanded'])\n else: addByte(False)\n\n for attr in ['height', 'startTime', 'failTime', 'speed']:\n if (attr in self.data['info']['software']['activity']): addFloat(self.data['info']['software']['activity'][attr])\n else: addFloat(0)\n\n # Frames Array\n addByte(1)\n addInt(len(self.data['frames']))\n fps = self.getEvents('f')\n for i in range(len(self.data['frames'])):\n frame = self.data['frames'][i]\n addFloat(frame[0])\n if fps: addInt(int(fps[i]['fps']))\n else: addInt(0)\n for j in range(1, 22):\n addFloat(frame[j])\n\n # Notes Array\n addByte(2)\n notes = []\n gc = self.getEvents('gc')\n for c in gc:\n c['eventType'] = 0\n c['speedOK'] = True\n c['directionOK'] = True\n c['saberTypeOK'] = True\n c['wasCutTooSoon'] = False\n bc = self.getEvents('bc')\n for c in bc:\n c['eventType'] = 1\n m = self.getEvents('m')\n for c in m:\n c['eventType'] = 2\n b = self.getEvents('b')\n for c in b:\n c['eventType'] = 3\n notes = sum([gc, bc, m, b], [])\n if ('order' in notes[0]): notes = sorted(notes, key=lambda d: d['order'])\n else: notes = sorted(notes, key=lambda d: d['time'])\n g = self.getEvents('g')\n gi = 0\n addInt(len(notes))\n for note in notes:\n addInt(note['noteID'])\n addFloat(note['time'])\n addFloat(note['spawnTime'])\n addInt(note['eventType'])\n if (note['eventType'] == 0 or (note['eventType'] == 1 and self.data['info']['software']['runtime'] != \"oculus\")):\n for attr in ['speedOK', 'directionOK', 'saberTypeOK', 'wasCutTooSoon']: addByte(note[attr])\n for attr in ['saberSpeed', 'saberDirX', 'saberDirY', 'saberDirZ']: addFloat(note[attr])\n addInt(note['saberType'])\n for attr in ['timeDeviation', 'cutDirDeviation', 'cutPointX', 'cutPointY', 'cutPointZ', 'cutNormalX', 'cutNormalY', 'cutNormalZ', 'cutDistanceToCenter', 'cutAngle', 'beforeCutRating', 'afterCutRating']: addFloat(note[attr])\n elif (note['eventType'] == 1 and self.data['info']['software']['runtime'] == \"oculus\"):\n if (g):\n bytes.extend(g[gi]['data'])\n gi += 1\n else:\n for attr in ['speedOK', 'directionOK', 'saberTypeOK', 'wasCutTooSoon']: addByte(0)\n for attr in ['saberSpeed', 'saberDirX', 'saberDirY', 'saberDirZ']: addFloat(0.0)\n addInt(0.0)\n for attr in ['timeDeviation', 'cutDirDeviation', 'cutPointX', 'cutPointY', 'cutPointZ', 'cutNormalX', 'cutNormalY', 'cutNormalZ', 'cutDistanceToCenter', 'cutAngle', 'beforeCutRating', 'afterCutRating']: addFloat(0.0)\n\n # Walls Array\n addByte(3)\n walls = self.getEvents('wh')\n addInt(len(walls))\n for wall in walls:\n addInt(wall['wallID'])\n addFloat(wall['energy'])\n addFloat(wall['time'])\n addFloat(wall['spawnTime'])\n\n # Height Array\n addByte(4)\n heights = self.getEvents('h')\n addInt(len(heights))\n for height in heights:\n addFloat(height['height'])\n addFloat(height['time'])\n\n # Pause Array\n addByte(5)\n pauses = self.getEvents('p')\n addInt(len(pauses))\n for pause in pauses:\n addLong(pause['duration'])\n addFloat(pause['time'])\n\n return bytes\n\n @classmethod\n def unpack(XROR, file):\n \"\"\"\n Generate XROR object from XROR file data.\n\n Unpacks XROR file data using BSON, then decompresses telemetry and event data using fpzip.\n \"\"\"\n xror = XROR()\n data = bson.decode(file)\n\n if ('timestamp' in data['info']):data['info']['timestamp'] = int(data['info']['timestamp'].replace(tzinfo=datetime.timezone.utc).timestamp())\n\n floats = fpzip.decompress(data['frames'])\n data['frames'] = floats[0][0].tolist()\n\n for i in range(len(data['events'])):\n if ('floatData' in data['events'][i]):\n floats = fpzip.decompress(data['events'][i]['floatData'])\n data['events'][i]['floatData'] = floats[0][0].tolist()\n\n xror.data = data\n return xror\n\n @classmethod\n def fromTilt(XROR, data):\n \"\"\"\n Generate XROR object from .tilt file data.\n\n Parameters:\n data:The tilt file pointer to generate an XROR object from.\n \"\"\"\n tilt = Tilt(data)\n sketch = tilt.sketch\n meta = tilt.metadata\n brushes = meta['BrushIndex']\n\n xror = XROR()\n xror.setApp(id = '327140', name = 'Tilt Brush')\n if ('EnvironmentPreset' in meta): xror.setEnvironment(id = meta['EnvironmentPreset'])\n for attr in ['ThumbnailCameraTransformInRoomSpace', 'SceneTransformInRoomSpace', 'Mirror', 'Lights']:\n if attr in meta:\n xror.data['info']['software']['environment'][attr] = meta[attr]\n\n xror.addDevice(name = 'BRUSH', type = 'OTHER', axes = ['x', 'y', 'z', 'i', 'j', 'k', '1', 'p'])\n xror.addEventType(id = 'stroke', name = 'Stroke', attr = ['color_r', 'color_g', 'color_b', 'color_a', 'size', 'scale', 'brush']);\n\n for stroke in sketch.strokes:\n brush = brushes[stroke.brush_idx]\n time = stroke.get_cp_extension(stroke.controlpoints[0], 'timestamp')\n color = stroke.brush_color\n xror.addEvent('stroke', time, [color[0], color[1], color[2], color[3], stroke.brush_size, stroke.scale], [brush])\n for point in stroke.controlpoints:\n time = stroke.get_cp_extension(point, 'timestamp')\n x = point.position[0]\n y = point.position[1]\n z = point.position[2]\n i = point.orientation[0]\n j = point.orientation[1]\n k = point.orientation[2]\n l = point.orientation[3]\n p = stroke.get_cp_extension(point, 'pressure')\n xror.addFrame(time, [x, y, z, i, j, k, l, p])\n\n return xror\n\n @classmethod\n def fromBSOR(XROR, data, addFPS = False, addOrder = False, addGarbage = False):\n \"\"\"\n Generate XROR object from BSOR file data.\n\n Parameters:\n data:The bsor file pointer to generate an XROR object from.\n addFPS(bool):Whether to add FPS data to the XROR object. Often not necessary.\n addOrder(bool):Whether to add event order data to the XROR object. Only needed in edge cases.\n addGarbage(bool):Whether to include garbage cut data from bad cuts on Oculus devices.\n \"\"\"\n bsor = make_bsor(data)\n xror = XROR(timestamp = bsor.info.timestamp)\n\n xror.addDevice(name = bsor.info.hmd, type = 'HMD', joint = 'HEAD')\n xror.addDevice(name = bsor.info.controller.replace(\"right\", \"left\").replace(\"Right\", \"Left\").replace(\"RIGHT\", \"LEFT\"), type = 'CONTROLLER', joint = 'HAND_LEFT')\n xror.addDevice(name = bsor.info.controller, type = 'CONTROLLER', joint = 'HAND_RIGHT')\n\n xror.setApp(id = '620980', name = 'Beat Saber', version = bsor.info.gameVersion)\n xror.addExtension(name = 'BeatLeader', version = bsor.info.version)\n xror.setEnvironment(name = bsor.info.environment)\n xror.setActivity(name = bsor.info.songName)\n xror.setUser(id = bsor.info.playerId, name = bsor.info.playerName)\n for attr in ['songHash', 'mapper', 'difficulty', 'score', 'mode', 'modifiers', 'jumpDistance', 'leftHanded', 'height', 'startTime', 'failTime', 'speed']:\n if (getattr(bsor.info, attr)): xror.data['info']['software']['activity'][attr] = getattr(bsor.info, attr)\n xror.data['info']['software']['runtime'] = bsor.info.platform\n xror.data['info']['software']['api'] = bsor.info.trackingSystem\n\n for frame in bsor.frames:\n data = []\n for obj in ['head', 'left_hand', 'right_hand']:\n for axis in ['x', 'y', 'z', 'x_rot', 'y_rot', 'z_rot', 'w_rot']:\n data.append(getattr(getattr(frame, obj), axis))\n xror.addFrame(frame.time, data)\n\n if addOrder:\n xror.addEventType(id = 'gc', name = 'Good Cut', attr = ['spawnTime', 'saberSpeed', 'saberDirX', 'saberDirY', 'saberDirZ', 'timeDeviation', 'cutDirDeviation', 'cutPointX', 'cutPointY', 'cutPointZ', 'cutNormalX', 'cutNormalY', 'cutNormalZ', 'cutDistanceToCenter', 'cutAngle', 'beforeCutRating', 'afterCutRating', 'noteID', 'saberType', 'order']);\n if (bsor.info.platform == \"oculus\"):\n xror.addEventType(id = 'bc', name = 'Bad Cut', attr = ['spawnTime', 'noteID', 'order']);\n if (addGarbage): xror.addEventType(id = 'g', name = 'Garbage', attr = ['data']);\n else:\n xror.addEventType(id = 'bc', name = 'Bad Cut', attr = ['spawnTime', 'saberSpeed', 'saberDirX', 'saberDirY', 'saberDirZ', 'timeDeviation', 'cutDirDeviation', 'cutPointX', 'cutPointY', 'cutPointZ', 'cutNormalX', 'cutNormalY', 'cutNormalZ', 'cutDistanceToCenter', 'cutAngle', 'beforeCutRating', 'afterCutRating', 'noteID', 'speedOK', 'directionOK', 'saberTypeOK', 'wasCutTooSoon', 'saberType', 'order']);\n xror.addEventType(id = 'm', name = 'Miss', attr = ['spawnTime', 'noteID', 'order']);\n xror.addEventType(id = 'b', name = 'Bomb Cut', attr = ['spawnTime', 'noteID', 'order']);\n else:\n xror.addEventType(id = 'gc', name = 'Good Cut', attr = ['spawnTime', 'saberSpeed', 'saberDirX', 'saberDirY', 'saberDirZ', 'timeDeviation', 'cutDirDeviation', 'cutPointX', 'cutPointY', 'cutPointZ', 'cutNormalX', 'cutNormalY', 'cutNormalZ', 'cutDistanceToCenter', 'cutAngle', 'beforeCutRating', 'afterCutRating', 'noteID', 'saberType']);\n if (bsor.info.platform == \"oculus\"):\n xror.addEventType(id = 'bc', name = 'Bad Cut', attr = ['spawnTime', 'noteID']);\n if (addGarbage): xror.addEventType(id = 'g', name = 'Garbage', attr = ['data']);\n else:\n xror.addEventType(id = 'bc', name = 'Bad Cut', attr = ['spawnTime', 'saberSpeed', 'saberDirX', 'saberDirY', 'saberDirZ', 'timeDeviation', 'cutDirDeviation', 'cutPointX', 'cutPointY', 'cutPointZ', 'cutNormalX', 'cutNormalY', 'cutNormalZ', 'cutDistanceToCenter', 'cutAngle', 'beforeCutRating', 'afterCutRating', 'noteID', 'speedOK', 'directionOK', 'saberTypeOK', 'wasCutTooSoon', 'saberType']);\n xror.addEventType(id = 'm', name = 'Miss', attr = ['spawnTime', 'noteID']);\n xror.addEventType(id = 'b', name = 'Bomb Cut', attr = ['spawnTime', 'noteID']);\n\n\n for [idx, note] in enumerate(bsor.notes):\n if note.event_type == 0:\n xror.addEvent('gc', note.event_time, [note.spawn_time, note.cut.saberSpeed, note.cut.saberDirection[0], note.cut.saberDirection[1], note.cut.saberDirection[2], note.cut.timeDeviation, note.cut.cutDeviation, note.cut.cutPoint[0], note.cut.cutPoint[1], note.cut.cutPoint[2], note.cut.cutNormal[0], note.cut.cutNormal[1], note.cut.cutNormal[2], note.cut.cutDistanceToCenter, note.cut.cutAngle], [note.cut.beforeCutRating, note.cut.afterCutRating, note.note_id, note.cut.saberType, idx] if addOrder else [note.cut.beforeCutRating, note.cut.afterCutRating, note.note_id, note.cut.saberType])\n if note.event_type == 1:\n if (bsor.info.platform == \"oculus\"):\n xror.addEvent('bc', note.event_time, [note.spawn_time], [note.note_id, idx] if addOrder else [note.note_id])\n if (addGarbage): xror.addEvent('g', note.event_time, [], [note.garbage])\n else:\n xror.addEvent('bc', note.event_time, [note.spawn_time, note.cut.saberSpeed, note.cut.saberDirection[0], note.cut.saberDirection[1], note.cut.saberDirection[2], note.cut.timeDeviation, note.cut.cutDeviation, note.cut.cutPoint[0], note.cut.cutPoint[1], note.cut.cutPoint[2], note.cut.cutNormal[0], note.cut.cutNormal[1], note.cut.cutNormal[2], note.cut.cutDistanceToCenter, note.cut.cutAngle], [note.cut.beforeCutRating, note.cut.afterCutRating, note.note_id, note.cut.speedOK, note.cut.directionOk, note.cut.saberTypeOk, note.cut.wasCutTooSoon, note.cut.saberType, idx] if addOrder else [note.cut.beforeCutRating, note.cut.afterCutRating, note.note_id, note.cut.speedOK, note.cut.directionOk, note.cut.saberTypeOk, note.cut.wasCutTooSoon, note.cut.saberType])\n if note.event_type == 2:\n xror.addEvent('m', note.event_time, [note.spawn_time], [note.note_id, idx] if addOrder else [note.note_id])\n if note.event_type == 3:\n xror.addEvent('b', note.event_time, [note.spawn_time], [note.note_id, idx] if addOrder else [note.note_id])\n\n xror.addEventType(id = 'wh', name = 'Wall Hit', attr = ['energy', 'spawnTime', 'wallID'])\n for wall in bsor.walls:\n xror.addEvent('wh', wall.time, [wall.energy, wall.spawnTime, wall.id])\n\n xror.addEventType(id = 'h', name = 'Height Change', attr = ['height'])\n for height in bsor.heights:\n xror.addEvent('h', height.time, [height.height])\n\n xror.addEventType(id = 'p', name = 'Pause', attr = ['duration'])\n for pause in bsor.pauses:\n xror.addEvent('p', pause.time, otherData=[pause.duration])\n\n if (addFPS):\n xror.addEventType(id = 'f', name = 'FPS', attr = ['fps'])\n for frame in bsor.frames:\n xror.addEvent('f', frame.time, [frame.fps])\n\n # todo: bomb misses\n # todo: wall misses\n # todo: more user data\n\n return xror\n","repo_name":"MetaGuard/MetaGuardPlus","sub_path":"evaluation/common/xror.py","file_name":"xror.py","file_ext":"py","file_size_in_byte":26681,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"81"} +{"seq_id":"74756635465","text":"#!python3\n\nfrom pathlib import Path\nimport sys\n\nEND_COMMON = \"\\n# END COMMON\"\n\n\ndef extract_common(file: Path) -> str:\n content = file.read_text()\n return content[: content.index(END_COMMON)]\n\n\ndef main() -> int:\n files = {\n file: extract_common(file)\n for file in Path(\".\").iterdir()\n if (\n file.is_file\n and file.stem == \"Dockerfile\"\n and END_COMMON in file.read_text()\n )\n }\n\n if 1 == len(set(files.values())):\n print(\"Files have the same common head\")\n return 0\n\n print(\"Files have differing common head\")\n for file, common in files.items():\n print(f\">>>> {file} <<<<\")\n print(common)\n print()\n return 1\n\n\nif __name__ == \"__main__\":\n sys.exit(main())\n","repo_name":"GothAck/nginx-docker-ingress-controller","sub_path":"scripts/check_common_dockerfiles.py","file_name":"check_common_dockerfiles.py","file_ext":"py","file_size_in_byte":778,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"7012495840","text":"import tkinter as tk\r\nimport os\r\nimport pygame\r\nfrom PIL import Image, ImageTk\r\nfrom tkinter import ttk\r\n\r\nclass MICHIGANTECHMUSIC:\r\n def __init__(self):\r\n self.root = tk.Tk()\r\n self.root.title(\"MICHIGAN TECH MUSIC\")\r\n self.root.geometry(\"800x700\")\r\n self.root.configure(bg=\"black\")\r\n \r\n disc_image_path = \"C:/Users/13312/Desktop/Muisc player/Screenshot 2023-04-17 004618.png\"\r\n self.disc_image = Image.open(disc_image_path)\r\n self.disc_image = self.disc_image.resize((250, 200), Image.LANCZOS)\r\n self.disc_photo = ImageTk.PhotoImage(self.disc_image)\r\n\r\n image_path2 = \"C:/Users/13312/Desktop/Muisc player/EMINEM.png-removebg-preview.png\"\r\n self.image2 = Image.open(image_path2)\r\n self.image2 = self.image2.resize((340,700), Image.LANCZOS)\r\n self.image2_photo = ImageTk.PhotoImage(self.image2)\r\n\r\n self.image2_label = tk.Label(self.root, image=self.image2_photo, bg=\"black\",)\r\n self.image2_label.pack(padx=10, pady=10, side=tk.RIGHT)\r\n\r\n self.disc_label = tk.Label(self.root, image=self.disc_photo, bg=\"black\")\r\n self.disc_label.pack(padx=10, pady=10)\r\n\r\n pygame.mixer.init()\r\n\r\n self.song_listbox = tk.Listbox(self.root, height=15, width=50, font=(\"Times New Roman\", 12), bg=\"#2C2C2C\", fg=\"white\", selectbackground=\"#004BA8\", selectforeground=\"white\")\r\n self.song_listbox.pack(padx=10, pady=10)\r\n\r\n self.songs = os.listdir('C:/Users/13312/Desktop/Muisc player/')\r\n \r\n for song in self.songs:\r\n self.song_listbox.insert(tk.END, song)\r\n\r\n self.play_button = tk.Button(self.root, text=\"PLAY\", width=10, font=(\"Times New Roman\", 14, \"bold\"), bg=\"#004BA8\", fg=\"white\", activebackground=\"#00336E\", command=self.play_song)\r\n self.play_button.pack(side=tk.LEFT, padx=20, pady=5,)\r\n\r\n self.pause_button = tk.Button(self.root, text=\"PAUSE\", width=10, font=(\"Times New Roman\", 14, \"bold\"), bg=\"#004BA8\", fg=\"white\", activebackground=\"#00336E\", command=self.pause_song)\r\n self.pause_button.pack(side=tk.LEFT, padx=20, pady=5)\r\n\r\n self.stop_button = tk.Button(self.root, text=\"STOP\", width=10, font=(\"Times New Roman\", 14, \"bold\"), bg=\"#004BA8\", fg=\"white\", activebackground=\"#00336E\", command=self.stop_song)\r\n self.stop_button.pack(side=tk.LEFT, padx=20, pady=5)\r\n\r\n self.volume_slider = tk.Scale(self.root, from_=0, to=100, orient=tk.HORIZONTAL, length=500, sliderlength=20, width=15, font=(\"Times New Roman\", 12), bg=\"blue\", fg=\"white\", highlightbackground=\"WHITE\", troughcolor=\"black\", command=self.set_volume)\r\n self.volume_slider.set(50)\r\n self.volume_slider.pack(side=tk.RIGHT, padx=20, pady=5)\r\n self.song_listbox.selection_set(first=0)\r\n self.themes ={\r\n \"Default\": {\"bg\": \"black\", \"fg\": \"white\", \"activebg\": \"#00336E\", \"highlightbg\": \"WHITE\", \"troughcolor\": \"black\"},\r\n \"Dark\": {\"bg\": \"#1C1C1C\", \"fg\": \"white\", \"activebg\": \"#00336E\", \"highlightbg\": \"WHITE\", \"troughcolor\": \"#1C1C1C\"},\r\n \"Light\": {\"bg\": \"white\", \"fg\": \"black\", \"activebg\": \"#0077FF\", \"highlightbg\": \"BLACK\", \"troughcolor\": \"#F0F0F0\"},\r\n \"orange\": {\"bg\": \"orange\", \"fg\": \"white\", \"activebg\": \"orange\", \"highlightbg\": \"WHITE\", \"troughcolor\": \"orange\"}\r\n }\r\n self.theme_label = tk.Label(self.root, text=\"Select Theme:\", font=(\"Times New Roman\", 14), bg=\"black\", fg=\"white\")\r\n self.theme_label.pack(side=tk.TOP, padx=20, pady=5)\r\n self.theme_var = tk.StringVar()\r\n self.theme_var.set(\"Default\")\r\n self.theme_menu = ttk.OptionMenu(self.root, self.theme_var, *self.themes.keys(), command=self.change_theme)\r\n self.theme_menu.pack(side=tk.TOP, padx=20, pady=5)\r\n self.root.mainloop()\r\n def play_song(self):\r\n selected_song = self.song_listbox.get(tk.ACTIVE)\r\n pygame.mixer.music.load(selected_song)\r\n pygame.mixer.music.play()\r\n \r\n def pause_song(self):\r\n pygame.mixer.music.pause()\r\n\r\n def stop_song(self):\r\n pygame.mixer.music.stop()\r\n \r\n def set_volume(self, val):\r\n volume = int(val) / 100\r\n pygame.mixer.music.set_volume(volume)\r\n\r\n def change_theme(self, theme):\r\n selected_theme = self.themes[theme]\r\n self.root.configure(bg=selected_theme[\"bg\"])\r\n self.song_listbox.configure(bg=selected_theme[\"bg\"], fg=selected_theme[\"fg\"], selectbackground=selected_theme[\"activebg\"], highlightbackground=selected_theme[\"highlightbg\"])\r\n self.play_button.configure(bg=selected_theme[\"bg\"], fg=selected_theme[\"fg\"], activebackground=selected_theme[\"activebg\"])\r\n self.pause_button.configure(bg=selected_theme[\"bg\"], fg=selected_theme[\"fg\"], activebackground=selected_theme[\"activebg\"])\r\n self.stop_button.configure(bg=selected_theme[\"bg\"], fg=selected_theme[\"fg\"], activebackground=selected_theme[\"activebg\"])\r\n self.volume_slider.configure(bg=selected_theme[\"bg\"], fg=selected_theme[\"fg\"], highlightbackground=selected_theme[\"highlightbg\"], troughcolor=selected_theme[\"troughcolor\"])\r\n\r\n pass\r\n\r\nmusic_player = MICHIGANTECHMUSIC()\r\n\r\n","repo_name":"nmadired/Music-Player-Using-Python--GUI-Interface-","sub_path":"SAT4650 FINAL PROJECT SOURCE CODE.py","file_name":"SAT4650 FINAL PROJECT SOURCE CODE.py","file_ext":"py","file_size_in_byte":5172,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"81"} +{"seq_id":"38706178150","text":"\n#\n# Neural network example\n#\n# XOR gate simulation\n#\n\nimport random\nimport pdb\nfrom math import sqrt, exp\n\t\ndef sigmoid_derivative(x):\n\treturn x * (1-x)\n\n#\n# Class representation of a synapse that connects the output of one neuron\n# to the input of another, with some weighting factor applied\n#\nclass synapse:\n\tdef __init__(self, n):\n\t\tself.weight = random.gauss(0.5, 0.33)\n\t\tself.neuron = n\n\t\t\n\tdef get_value(self):\n\t\treturn self.neuron.output * self.weight\n\n#\n# Class representation of a neuron\n#\nclass neuron:\n\tFUNCTION_LINEAR = 0\n\tFUNCTION_SIGMOID = 1\n\t\n\tdef __init__(self, f):\n\t\tself.input = 0\n\t\tself.output = 0\n\t\tself.function = f\n\t\tself.synapses = []\n\t\n\tdef __str__(self):\n\t\ts = \"\"\n\t\t# Activation function\n\t\tif self.function == self.FUNCTION_LINEAR:\n\t\t\ts += \"LINEAR \"\n\t\telif self.function == self.FUNCTION_SIGMOID:\n\t\t\ts += \"SIGMOID \"\n\t\telse:\n\t\t\ts += \"UNDEF \"\n\t\t# Input and output values, use to check activation function applied correctly\n\t\ts += '{:6.4f}'.format(self.input) + \" --> \"\n\t\ts += '{:6.4f}'.format(self.output) + \" \"\n\t\t# Synapse inputs, use to check number and weighting\n\t\ts += \"(\"\n\t\tfor i in self.synapses:\n\t\t\ts += '{:6.4f}'.format(i.weight) + \" \"\n\t\ts += \")\"\n\t\treturn s\n\t\t\n\tdef compute(self):\n\t\t# If no incoming synapses, simply propagate input to output\n\t\tif (len(self.synapses) == 0):\n\t\t\tself.output = self.input\n\t\telse:\n\t\t\t# Calculate new input from incoming synapses\n\t\t\tself.input = 0\n\t\t\tfor s in self.synapses:\n\t\t\t\tself.input += s.get_value()\n\t\t\t# Apply new input to activation function\n\t\t\tif (self.function == self.FUNCTION_LINEAR):\n\t\t\t\tself.output = self.input\n\t\t\telif (self.function == self.FUNCTION_SIGMOID):\n\t\t\t\tself.output = 1 / (1 + exp(-self.input))\n\t\t\telse:\n\t\t\t\t# Unknown activation function\n\t\t\t\tself.output = 0\n\t\treturn self.output\n\t\t\t\n\tdef add_synapse(self, s):\n\t\tself.synapses.append(synapse(s))\n\n\nclass neuralnet:\n\tdef __init__(self, nInput, nHidden, nOutput):\n\t\tself.learningRate = 0.5\n\t\tself.input = []\n\t\tfor i in range(0, nInput):\n\t\t\tself.input.append(neuron(neuron.FUNCTION_LINEAR))\n\t\tself.hidden = []\n\t\tfor i in range(0, nHidden):\n\t\t\tself.hidden.append(neuron(neuron.FUNCTION_SIGMOID))\n\t\tself.output = []\n\t\tfor i in range(0, nOutput):\n\t\t\tself.output.append(neuron(neuron.FUNCTION_SIGMOID))\n\t\t\n\t\t# Connect input to hidden layer\n\t\tfor h in self.hidden:\n\t\t\tfor i in self.input:\n\t\t\t\th.add_synapse(i)\n\t\t\n\t\t# Connect output to hidden layer\n\t\tfor o in self.output:\n\t\t\tfor h in self.hidden:\n\t\t\t\to.add_synapse(h)\n\t\t\t\t\n\t\t# Open .csv file for debugging / algorithm profiling\n\t\tself.csv = open(\"xor.csv\", \"w\")\n\t\t\n\tdef __del__(self):\n\t\tself.csv.close()\n\t\n\tdef __str__(self):\n\t\ts = \"Inputs:\\n\"\n\t\tfor i in self.input:\n\t\t\ts += \" \" + str(i) + \"\\n\"\n\t\ts += \"Hidden:\\n\"\n\t\tfor h in self.hidden:\n\t\t\ts += \" \" + str(h) + \"\\n\"\n\t\ts += \"Output:\\n\"\n\t\tfor o in self.output:\n\t\t\ts += \" \" + str(o) + \"\\n\"\n\t\treturn s\n\t\t\n\tdef update (self, inValues):\n\t\t# Apply values to input neurons\n\t\tfor i in range(0, len(inValues)):\n\t\t\tself.input[i].input = inValues[i]\n\n\t\t# Update input layer\n\t\tfor i in self.input:\n\t\t\ti.compute()\n\t\t\t\n\t\t# Update hidden layer\n\t\tfor h in self.hidden:\n\t\t\th.compute()\n\t\t\n\t\t# Update output layer\n\t\tfor o in self.output:\n\t\t\to.compute()\n\n\tdef train_single_output(self, inValues, outValue, nCycles):\n\t\tfor i in range(nCycles):\n\t\t\t# Apply input values and forward-propagate neural net\n\t\t\tself.update(inValues)\n\t\t\t\n\t\t\t# Calculate\n\t\t\toutputNeuron = self.output[0]\n\t\t\toutputErrorSum = outValue - outputNeuron.output\n\t\t\tderivative = sigmoid_derivative(outputNeuron.output)\n\t\t\tdeltaOutputSum = derivative * outputErrorSum\n\t\t\t\n\t\t\t# Calculate delta weights to output layer synapses, do not apply yet\n\t\t\tdeltaOutputWeight = []\n\t\t\tfor s in outputNeuron.synapses:\n\t\t\t\tdw = deltaOutputSum / s.neuron.output\n\t\t\t\tdeltaOutputWeight.append(dw)\n\t\t\t\t\t\t\t\n\t\t\t# Calculate hidden sum deltas\n\t\t\tdeltaHiddenFactor = []\n\t\t\tfor j in range(len(outputNeuron.synapses)):\n\t\t\t\tdhf = deltaOutputSum / outputNeuron.synapses[j].weight\n\t\t\t\tdeltaHiddenFactor.append(dhf)\n\n\t\t\tdeltaHiddenSum = []\n\t\t\tfor k in range(len(self.hidden)):\n\t\t\t\tdhs = deltaHiddenFactor[k] * sigmoid_derivative(self.hidden[k].output)\n\t\t\t\tdeltaHiddenSum.append(dhs)\n\n\t\t\t\tfor m in range(len(self.hidden[k].synapses)):\n\t\t\t\t\tdeltaInputWeight = dhs\n\t\t\t\t\tself.hidden[k].synapses[m].weight += deltaInputWeight * self.learningRate\n\t\t\t\t\n\t\t\t# Apply weights to output layer synapses\n\t\t\tfor j in range(len(outputNeuron.synapses)):\n\t\t\t\toutputNeuron.synapses[j].weight += deltaOutputWeight[j] * self.learningRate\n\t\t\t\tself.csv.write('{:8.6f}'.format(outputNeuron.synapses[j].weight) + ', ')\n\t\t\tself.csv.write(\"\\n\")\n\t\t\t\t\t\t\n\tdef train(self, inValues, outValues, nCycles):\n\t\tfor i in range(nCycles):\n\t\t\tself.update(inValues)\n\n\t\t\t# Calculate total squared error over all output values\n\t\t\teSum = 0.0\n\t\t\tfor o in range(0, len(outValues)):\n\t\t\t\te = outValues[o] - self.output[o].output\n\t\t\t\teSum += 0.5 * e * e\n\t\t\tdOutputSum = eSum * sigmoid_derivative(eSum)\n\n\t\t\t# Calculate weight adjustments to output layer synapses\n\t\t\tnOutput = len(self.output)\n\t\t\toDelta = []\n\t\t\tfor o in range(nOutput):\n\t\t\t\toCurrent = self.output[o].output\n\t\t\t\tdelta = (outValues[0] - oCurrent) * (oCurrent * (1 - oCurrent))\n\t\t\t\toDelta.append(delta * self.learningRate)\n\t\t\t\n\t\t\t# Calculate weight adjustments to hidden layer synapses\n\t\t\tnHidden = len(self.hidden)\n\t\t\thDelta = []\n\t\t\tfor h in range(nHidden):\n\t\t\t\thCurrent = self.hidden[h].output\n\t\t\t\tnSynapses = len(self.hidden[h].synapses)\n\t\t\t\tsDelta = []\n\t\t\t\tfor s in range(nSynapses):\n\t\t\t\t\ttemp = 0\n\t\t\t\t\tfor o in range(len(self.output)):\n\t\t\t\t\t\tdOut = outValues[o] - self.output[o].output\n\t\t\t\t\t\ttemp += dOut * self.hidden[h].synapses[s].weight\n\t\t\t\t\tdelta = temp * hCurrent * (1 - hCurrent)\n\t\t\t\t\tsDelta.append(delta * self.learningRate)\n\t\t\t\thDelta.append(sDelta)\n\t\t\t\t\n\t\t\t# Apply new weights to output and hidden layers\n\t\t\tfor o in range(nOutput):\n\t\t\t\tfor s in range(len(self.output[o].synapses)):\n\t\t\t\t\tself.output[o].synapses[s].weight += oDelta[o]\n\t\t\tfor h in range(nHidden):\n\t\t\t\tfor s in range(len(self.hidden[h].synapses)):\n\t\t\t\t\tself.hidden[h].synapses[s].weight += hDelta[h][s]\n\t\t\t\t\n# Local function to iterate a number of samples and collect success/fail metrics\ndef sample(inValues, outValues, nSamples, epsilon):\n\tnSuccess = 0\n\tnFailure = 0\n\tfor i in range(nSamples):\n\t\tnn.update (inValues)\n\t\tfor j in range(len(outValues)):\n\t\t\t# If output neuron value is within error margin, count it as a success\n\t\t\tif (abs(outValues[j] - nn.output[j].output) <= epsilon):\n\t\t\t\tnSuccess += 1\n\t\t\telse:\n\t\t\t\tnFailure += 1\n\treturn (nSuccess, nFailure)\n\n# Create neural network\nnn = neuralnet(2, 3, 1)\n\n# Override synapse weights to match example\n#nn.output[0].synapses[0].weight = 0.3\n#nn.output[0].synapses[1].weight = 0.5\n#nn.output[0].synapses[2].weight = 0.9\n\n#nn.hidden[0].synapses[0].weight = 0.8\n#nn.hidden[0].synapses[1].weight = 0.2\n\n#nn.hidden[1].synapses[0].weight = 0.4\n#nn.hidden[1].synapses[1].weight = 0.9\n\n#nn.hidden[2].synapses[0].weight = 0.3\n#nn.hidden[2].synapses[1].weight = 0.5\nprint(nn)\n\nfor i in range(1000):\n\tnn.train_single_output([0,0], 0, 1)\n\tnn.train_single_output([0,1], 1, 1)\n\tnn.train_single_output([1,0], 1, 1)\n\tnn.train_single_output([1,1], 0, 1)\n\nnn.update([0,0])\nprint(nn)\nnn.update([0,1])\nprint(nn)\nnn.update([1,0])\nprint(nn)\nnn.update([1,1])\nprint(nn)\n\n","repo_name":"wallychill/pci-examples","sub_path":"xor.py","file_name":"xor.py","file_ext":"py","file_size_in_byte":7247,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"14638887941","text":"from getch import getch, pause\n\n\"\"\"\n上 27 91 65\n下 27 91 66\n右 27 91 67\n左 27 91 68\n\"\"\"\n\nwhile True:\n key = ord(getch())\n if key == 13: #enter\n print(\"Enter\")\n break\n else:\n #print(\"You pressed: %s (%d)\" % (chr(key), key))\n\n #Macの上下左右キー入力検知\n if(key == 27):\n getch(); key = getch()\n if(key==\"A\"):\n print(\"up\")\n elif(key==\"B\"):\n print(\"down\")\n elif(key==\"C\"):\n print(\"right\")\n elif(key==\"D\"):\n print(\"left\")\n\n\npause()\n","repo_name":"ShinoYama1001/practice_getch","sub_path":"get.py","file_name":"get.py","file_ext":"py","file_size_in_byte":601,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"8586280349","text":"class Node:\n\n def __init__(self, data):\n self.data = data\n self.next = None\n\n\nclass LinkedList:\n\n def __init__(self):\n self._head = None\n\n @property\n def head(self):\n return self._head\n\n @head.setter\n def head(self, val):\n if isinstance(val, Node):\n self._head = val\n elif val is None:\n self._head = None\n else:\n self._head = Node(val)\n\n def __len__(self):\n if self.head is None:\n return 0\n\n if self.detect_loop():\n raise StopIteration(\"Looped List\")\n\n count = 0\n curr_node = self.head\n while curr_node:\n count += 1\n curr_node = curr_node.next\n return count\n\n def printlist(self):\n curr_node = self.head\n\n while curr_node is not None:\n print(curr_node.data, end=\" -> \")\n curr_node = curr_node.next\n print(curr_node)\n\n def push(self, data):\n node = Node(data)\n node.next = self.head\n self.head = node\n\n def append(self, data):\n node = Node(data)\n if not self.head:\n self.head = node\n return\n\n curr_node = self.head\n while curr_node.next:\n curr_node = curr_node.next\n curr_node.next = node\n\n @staticmethod\n def insert_after(prev_node, data):\n if not isinstance(prev_node, Node):\n return\n\n node = Node(data)\n node.next = prev_node.next\n prev_node.next = node\n\n def insert_at_pos(self, pos, data):\n if not self.head:\n return\n\n curr_node = self.head\n for _ in range(pos - 1):\n if not curr_node:\n return\n curr_node = curr_node.next\n\n node = Node(data)\n node.next = curr_node.next\n curr_node.next = node\n\n def search(self, key):\n if not self.head:\n return None\n curr_node = self.head\n while curr_node:\n if key == curr_node.data:\n return curr_node\n curr_node = curr_node.next\n return None\n\n def delete(self, key):\n if not self.head:\n return\n if self.head.data == key:\n self.head = self.head.next\n return\n\n prev_node = self.head\n curr_node = prev_node.next\n while curr_node:\n if curr_node.data != key:\n prev_node = curr_node\n curr_node = curr_node.next\n continue\n prev_node.next = curr_node.next\n break\n\n def delete_at_pos(self, pos):\n if not self.head:\n return\n\n if pos == 0:\n self.head = self.head.next\n return\n\n prev_node = self.head\n curr_node = prev_node.next\n\n for _ in range(pos - 1):\n if not curr_node:\n return\n prev_node = curr_node\n curr_node = curr_node.next\n\n prev_node.next = curr_node.next\n\n def delete_list(self):\n self.head = None\n\n def get_at_pos(self, pos):\n if self.head is None:\n return self.head\n\n curr_node = self.head\n for _ in range(pos):\n if curr_node is None:\n return None\n curr_node = curr_node.next\n return curr_node\n\n def get_mid(self, head=None):\n if head is None:\n head = self.head\n\n if head is None:\n return None\n\n slow = head\n fast = head\n while fast.next and fast.next.next:\n slow = slow.next\n fast = fast.next.next\n return slow\n\n def count(self, key):\n count = 0\n if self.head is None:\n return count\n\n curr_node = self.head\n while curr_node:\n if curr_node.data == key:\n count += 1\n curr_node = curr_node.next\n return count\n\n def detect_loop(self):\n if self.head is None:\n return False\n\n slow = self.head\n fast = self.head\n while fast and fast.next:\n slow = slow.next\n fast = fast.next.next\n if slow is fast:\n return True\n return False\n\n def loop_length(self):\n count = 0\n if self.head is None:\n return count\n\n slow = self.head\n fast = self.head\n while fast and fast.next:\n slow = slow.next\n fast = fast.next.next\n if slow is not fast:\n continue\n\n count = 1\n slow = slow.next\n while slow is not fast:\n count += 1\n slow = slow.next\n return count\n\n return count\n\n def _merge(self, left, right):\n if left is None:\n return right\n if right is None:\n return left\n\n if left.data <= right.data:\n result = left\n result.next = self._merge(left.next, right)\n else:\n result = right\n result.next = self._merge(left, right.next)\n return result\n\n def mergesort(self, head):\n if head is None or head.next is None:\n return head\n\n mid = self.get_mid(head)\n midnxt = mid.next\n mid.next = None\n\n left = self.mergesort(head)\n right = self.mergesort(midnxt)\n\n sorted_list = self._merge(left, right)\n return sorted_list\n","repo_name":"Godson-Gnanaraj/DSA","sub_path":"linkedlist/linkedlist.py","file_name":"linkedlist.py","file_ext":"py","file_size_in_byte":5457,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"24248181440","text":"\"\"\"\nno-idea: https://www.hackerrank.com/challenges/no-idea/problem\n\"\"\"\n\ndef strings_to_int(strings):\n \"\"\"Convert list of strings into list of ints\"\"\"\n return [ int(num) for num in strings ]\n\ndef list_to_set(l):\n \"\"\"Concert list to set\"\"\"\n return { v for v in l }\n\ndef distinct_num_counts(data):\n \"\"\"Return the dict with count of each distinct value in data\"\"\"\n result = {}\n for num in data:\n try:\n result[num] += 1\n except KeyError:\n result[num] = 1\n return result\n\ndef sum_counts(values, data):\n \"\"\"Return int sum of values found in data\"\"\"\n sum = 0\n for num in values:\n try:\n sum += data[num]\n except KeyError:\n pass\n return sum\n\nN, M = strings_to_int(input().strip().split())\nDATA = distinct_num_counts(strings_to_int(input().strip().split()))\nA = list_to_set(strings_to_int(input().strip().split()))\nB = list_to_set(strings_to_int(input().strip().split()))\n\nprint(sum_counts(A, DATA) - sum_counts(B, DATA))\n","repo_name":"jonathonball/chochie-isms","sub_path":"hackerrank/python/no-idea.py","file_name":"no-idea.py","file_ext":"py","file_size_in_byte":1019,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"18941123385","text":"import functools\nimport threading\n\n\ndef use_spinner(function):\n \"\"\"\n Decorator activating spinner before function and deactivating it.\n (Needs to be ran in separate thread.)\n\n :param function: function to decorate\n :return: decorated function\n \"\"\"\n\n @functools.wraps(function)\n def inner(self, *args, **kwargs):\n self.task_count += 1\n if self.spinner is not None:\n self.spinner.start()\n result = function(self, *args, **kwargs)\n self.task_count = max(self.task_count - 1, 0)\n if self.spinner is not None:\n if self.task_count == 0:\n self.spinner.stop()\n return result\n\n return inner\n\n\ndef use_threading(function):\n \"\"\"\n Decorator which runs function in separate thread.\n\n :return:\n \"\"\"\n\n @functools.wraps(function)\n def inner(self, *args, **kwargs):\n thread = threading.Thread(target=function, args=tuple([self] + list(args)), kwargs=kwargs)\n thread.start()\n\n return inner\n","repo_name":"peter-vasut/sortiment-frontent","sub_path":"sortimentGUI/decorators.py","file_name":"decorators.py","file_ext":"py","file_size_in_byte":1013,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"33645236274","text":"import media\r\nimport fresh_tomatoes\r\n\r\nt1 = \"https://www.youtube.com/watch?v=2TAOizOnNPo\"\r\nt2 = \"https://www.youtube.com/watch?v=F_VIM03DXWI\"\r\nt3 = \"https://www.youtube.com/watch?v=mw2AqdB5EVA\"\r\n# Create movie objects\r\nmovie_1 = media.Movie(title=\"The Fast and the Furious\",\r\n poster_image_url=\"http://bit.ly/2vToD9o\",\r\n trailer_youtube_url=t1)\r\n\r\nmovie_2 = media.Movie(title=\"2 Fast 2 Furious\",\r\n poster_image_url=\"http://bit.ly/2vqR3VR\",\r\n trailer_youtube_url=t2)\r\n\r\nmovie_3 = media.Movie(title=\"Fast Five\",\r\n poster_image_url=\"http://bit.ly/2wyuzT4\",\r\n trailer_youtube_url=t3)\r\n\r\n\r\nif __name__ == \"__main__\":\r\n movies = [movie_1, movie_2, movie_3] # create movies array\r\n fresh_tomatoes.open_movies_page(movies) # open all movies\r\n","repo_name":"ssachde8/Full_Stack_Web_Developer_Nanodegree","sub_path":"P1_Movie_Trailer_Website/movie.py","file_name":"movie.py","file_ext":"py","file_size_in_byte":868,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"73471691785","text":"# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\nclass Solution:\n def maxp(self, root: TreeNode) -> int:\n if not root.left and not root.right:\n if root.val > self.maximum:\n self.maximum = root.val\n return root.val\n left_t = 0\n right_t = 0\n if root.right:\n right_t = self.maxp(root.right)\n if root.left:\n left_t = self.maxp(root.left)\n thi_val = root.val + right_t + left_t\n self.maximum = max(self.maximum,root.val + right_t, root.val + left_t, root.val, root.val+right_t+left_t)\n return max(root.val + right_t, root.val + left_t, root.val)\n \n \n def maxPathSum(self, root: TreeNode) -> int:\n self.maximum = -float('inf')\n if not root:\n return -2147483648\n self.maxp(root)\n return self.maximum\n","repo_name":"gauravaror/programming","sub_path":"binary_tree_maximal_subpath.py","file_name":"binary_tree_maximal_subpath.py","file_ext":"py","file_size_in_byte":982,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"22095108042","text":"'''\nCS326 Lab 10\nAuthor: D. Schuurman\nSimple motion detector using pi camera.\n'''\nimport time\nimport sys\nimport cv2\n\n# Motion threshold: tune for sensitivity to motion\nMOTION_THRESHOLD = 1000000\n\ndef get_frame(cap):\n ''' Return grayscale image from camera if capture successful\n '''\n ret, frame = cap.read()\n if not ret:\n print('Frame capture failed...')\n sys.exit(1) \n return cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n \n\n# Initialize camera\nprint(\"Initializing camera...\")\ncap = cv2.VideoCapture(0)\nif not cap.isOpened():\n print('Cannot open camera...')\n sys.exit(1)\ncap.set(cv2.CAP_PROP_FRAME_WIDTH, 640)\ncap.set(cv2.CAP_PROP_FRAME_HEIGHT, 480)\ncap.set(cv2.CAP_PROP_FPS, 2)\n\n# initialize last frame\nlast_frame = get_frame(cap)\n\n# Continuously capture frames from the camera\ntry:\n while True:\n # grab a frame\n current_frame = get_frame(cap)\n\n # compute the abs of difference between current and last frame\n frameDelta = cv2.absdiff(current_frame, last_frame)\n diff = frameDelta.sum()\n\n # If diff > threshold, report motion detected\n if diff > MOTION_THRESHOLD:\n print('motion detected!')\n time.sleep(2)\n last_frame = get_frame(cap)\n else:\n last_frame = current_frame\n\nexcept KeyboardInterrupt:\n print('Done')\n cap.release()\n","repo_name":"dschuurman/cs326","sub_path":"lab10/motion-detector.py","file_name":"motion-detector.py","file_ext":"py","file_size_in_byte":1373,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"69809317067","text":"#! /usr/bin/env python3\n\nfrom __future__ import print_function\n\nimport sys\nimport readline\nfrom os import environ, path, listdir, makedirs, getenv, system\nfrom subprocess import call, check_output, Popen, PIPE, CalledProcessError\nfrom optparse import OptionParser\nimport shlex\nimport re\nfrom termcolor import colored\nfrom xdg import XDG_DATA_HOME\n\n\nHISTORY_BASE_DIR = path.join(XDG_DATA_HOME, 'adhocsh')\nHISTORY_PATH_TEMPLATE = path.join(HISTORY_BASE_DIR, '{cmd:s}.history')\n\nBASH_COMPLETION_DIR = '/usr/share/bash-completion/completions'\n\nBASH_COMPLETION_SCRIPT_TEMPLATE = \"\"\"\n # Source bash completion\n source \"{completion_file:s}\"\n\n # Prepare completion environment\n COMP_WORDS=( \"{command:s}\" \"{quoted_args:s}\" )\n COMP_CWORD={cword:d}\n\n # Execute completion\n {completion_function}\n\n # Print (return) completion results\n for match in \"${{COMPREPLY[@]}}\"; do\n echo \"$match\"\n done\n\"\"\"\n\n\nclass AdHocShell(object):\n\n def __init__(self, command, completion, compfunc=None, default=None, file_completion=True):\n self.command = command\n self.completion = completion\n self.completion_funcname = compfunc if compfunc else '_' + command\n self.default_subcommand = default.split() if default else []\n self.file_completion = file_completion\n self.history = HISTORY_PATH_TEMPLATE.format(cmd=command)\n self.exitcode = 0\n\n def load_history(self):\n if path.exists(self.history):\n readline.read_history_file(self.history)\n\n def save_history(self):\n if not path.exists(path.dirname(self.history)):\n makedirs(path.dirname(self.history))\n readline.write_history_file(self.history)\n\n def get_prompt(self):\n prompt = self.command\n\n try:\n if self.command == 'git':\n script = 'source \"{}\"; __git_ps1 \"{}@%s\"'.format(\n \"/usr/lib/git-core/git-sh-prompt\", self.command)\n prompt = check_output([ 'bash', '-c', script ], text = True)\n\n if self.command == 'task':\n context = check_output([ 'task', '_get', 'rc.context' ], text = True)[:-1]\n count = check_output([ 'task', 'rc.context:none',\n 'rc.verbose:nothing', 'count', 'status:pending',\n 'or', 'status:waiting' ], text = True)[:-1]\n info = '@' + context if context else ''\n info += '#' + count\n prompt = 'task{}'.format(info)\n except CalledProcessError as e:\n print (e.message, end=\"\")\n\n return prompt + colored('> ', 'green' if not self.exitcode else 'red')\n\n def redraw_prompt(self, message):\n \"\"\"\n Redraws the prompt after printing the given message.\n \"\"\"\n print (\"\\r\"+message)\n print (self.get_prompt()+readline.get_line_buffer(), end=\"\")\n sys.stdout.flush()\n\n def complete(self, text, state):\n if state == 0: # On first trigger, build possible matches\n line = readline.get_line_buffer()\n bidx = readline.get_begidx()\n eidx = readline.get_endidx()\n (args, cword) = self.get_comp_setup(line, bidx, eidx)\n\n self.matches = self.get_bash_completion(args, cword)\n\n # Filter matches by prefix (necessary since docker completes both\n # container name and ID, e.g. docker stop ...)\n self.matches = filter (lambda m : m.startswith(text), self.matches)\n\n self.matches = map (lambda m : m + ('/' if path.isdir(m) else ''), self.matches)\n\n self.matches = list (self.matches)\n\n if not len (self.matches) and self.file_completion:\n self.matches = self.get_file_completion(text)\n\n if state >= len (self.matches):\n return None\n\n # Return match indexed by state\n match = self.matches[state]\n # Word Boundary Pattern\n wbp = re.compile('[ :=/]$') # See COMP_WORDBREAKS (git adds ':')\n if len (self.matches) == 1 and match and not wbp.search(match):\n match += ' '\n return match\n\n def get_comp_setup(self, line, bidx, eidx):\n \"\"\"\n Parses the user input into currently provided arguments and the\n cursor's position.\n\n Currently quoted arguments and escaped characters are not correctly\n interpreted in terms of indexes.\n \"\"\"\n\n words = line.split()\n\n offset = 0\n cword = 0\n for word in words:\n start = line.find(word, offset)\n if start == bidx and start + len (word) == eidx:\n break\n cword += 1\n offset += start + len (word)\n\n return (words, cword)\n\n def display_matches(self, substitution, matches, longest_match_length):\n columns = int (environ.get(\"COLUMNS\", 80))\n\n print ()\n\n tpl = \"{:<\" + str (int (max (map (len, matches)) * 1.2)) + \"}\"\n\n buffer = \"\"\n for match in matches:\n match = tpl.format(match)\n if len (buffer + match) > columns:\n print (buffer.strip())\n buffer = \"\"\n buffer += match\n\n self.redraw_prompt(buffer.strip())\n\n def get_bash_completion(self, args, cword):\n script = BASH_COMPLETION_SCRIPT_TEMPLATE.format(\n completion_file = self.completion,\n command = self.command, quoted_args = '\" \"'.join(args),\n cword = cword+1, completion_function = self.completion_funcname)\n\n completion = Popen([ 'bash', '-c', script ], stdout=PIPE, stderr=PIPE, text = True)\n stdout, stderr = completion.communicate()\n\n if stderr:\n self.redraw_prompt(stderr[:-1])\n\n matches = filter (None, stdout[:-1].split(\"\\n\"))\n\n return matches\n\n def get_file_completion(self, prefix):\n curdir = path.dirname(prefix)\n curfil = path.basename(prefix)\n filenames = []\n for entry in listdir(curdir or '.'):\n if entry.startswith(curfil):\n filepath = path.join(curdir, entry)\n if (path.isdir(filepath)):\n filepath += '/'\n filenames.append(filepath)\n return filenames\n\n\nif __name__ == '__main__':\n parser = OptionParser()\n parser.add_option('-d', '--default', action='store', dest='default', default=None)\n parser.add_option('-f', '--compfunc', action='store', dest='compfunc', default=None)\n parser.add_option('-D', '--no-default', action='store_false', dest='allow_default', default=True)\n parser.add_option('-c', '--completion', action='store', dest='completion')\n parser.add_option('-H', '--no-history', action='store_false', dest='enable_history', default=True)\n parser.add_option('-F', '--no-file-completion', action='store_false', dest='file_completion', default=True)\n opts, args = parser.parse_args()\n\n command = args[0]\n if system('which {} > /dev/null'.format(command)):\n print (\"Command not found: \" + command)\n sys.exit(1)\n\n completion = opts.completion if opts.completion else path.join(BASH_COMPLETION_DIR, command)\n if not path.exists(completion):\n print (\"Completion file not found: \" + completion)\n sys.exit(1)\n\n shell = AdHocShell(command, completion, compfunc=opts.compfunc,\n default=opts.default, file_completion=opts.file_completion)\n readline.set_completer_delims(' \\t\\n;:=')\n readline.set_completer(shell.complete)\n readline.parse_and_bind('tab: complete')\n readline.set_completion_display_matches_hook(shell.display_matches)\n\n print (\"Ad-hoc shell for {}.\".format(command))\n print (\"Hit Ctrl-D to leave!\")\n\n # Execute default command once at startup\n if opts.allow_default and opts.default:\n default_command = [ shell.command ]\n default_command.extend(shell.default_subcommand)\n call(default_command)\n\n if opts.enable_history:\n shell.load_history()\n\n while True:\n try:\n line = input (shell.get_prompt())\n args = shlex.split(line)\n argc = len (args)\n if not argc and not opts.allow_default:\n continue\n if not argc and shell.default_subcommand:\n args = shell.default_subcommand\n full_command = [ shell.command ]\n full_command.extend(args)\n shell.exitcode = call(full_command)\n except ValueError as e:\n print (\"Error: \" + e.message)\n except KeyboardInterrupt:\n print ('^C')\n except EOFError:\n print ()\n if opts.enable_history:\n shell.save_history()\n break\n\n","repo_name":"8ware/adhocsh","sub_path":"adhocsh.py","file_name":"adhocsh.py","file_ext":"py","file_size_in_byte":8755,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"28700440784","text":"from django.forms import ModelForm\nfrom django.contrib.auth.forms import UserCreationForm\nfrom .models import Selection, MyUser\n\n\nclass SelectionForm(ModelForm):\n class Meta:\n model = Selection\n fields = ['courses', 'name']\n\nclass MyUserCreationForm(UserCreationForm):\n class Meta(UserCreationForm.Meta):\n model = MyUser","repo_name":"titouanc/vubix","sub_path":"schedule/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":347,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"81"} +{"seq_id":"15464701888","text":"import enum\nfrom shlex import join\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport json\nimport utils\nimport os\nimport pandas as pd\nlog_path = \"/mnt/a/OneDrive/MScRobotics/Dissertation2022/codes/experiment_results/agent_number vs frame_length/node_number vs frame_length v2/FrameLen10_10NodesAug130910ReLen10.log\"\nlog_parent_path1 = \"/mnt/a/OneDrive/MScRobotics/Dissertation2022/codes/experiment_results/agent_number vs frame_length/node_number vs frame_length v2\"\nlog_parent_path2 = \"/mnt/a/OneDrive/MScRobotics/Dissertation2022/codes/experiment_results/agent_number vs frame_length/v3\"\n\n\ndef average_performance(params1, params2, performance):\n # Create a DataFrame from the input arrays\n df = pd.DataFrame({'param1': params1, 'param2': params2,\n 'performance': performance})\n\n # Group by the parameters and calculate the mean performance for each group\n grouped = df.groupby(['param1', 'param2']).mean().reset_index()\n\n # Return the unique parameters and averaged performance as separate arrays\n return grouped['param1'].values, grouped['param2'].values, grouped['performance'].values\n\n\ndef traverse_directory(directory_path):\n result = []\n for root, dirs, files in os.walk(directory_path):\n for file in files:\n if os.path.splitext(file)[1] == \".log\":\n file_path = os.path.join(root, file)\n result.append(file_path)\n return result\n\n\ndef scene_reader(scene_path, min_dist=-1):\n '''\n 读入标准scene文件,返回起点和终点数组\n\n Args:\n scene_path (str, optional): scene文件的路径. 默认值在launch.py中.\n\n min_dist (int): 起点和终点之间的最小距离,小于这个距离的将被滤除\n\n Returns:\n\n starts [(x,y)]: 起点的坐标\n\n goals [(x,y)]: 终点的坐标\n '''\n starts = []\n goals = []\n optimal_dists = []\n with open(scene_path, \"r\") as scene:\n for line in scene:\n words = line.strip().split(\" \")\n if len(words) == 2:\n continue # 过滤掉开头的version空格1\n words = words[0].strip().split(\"\\t\")\n # 第5,6个元素是起点横纵坐标\n start = (int(words[4]), int(words[5]))\n # 第7,8个元素是终点横纵坐标\n goal = (int(words[6]), int(words[7]))\n # 最后一个元素是最优距离\n optimal_dist = float(words[-1])\n optimal_dists.append(optimal_dist)\n if optimal_dist < min_dist:\n continue # 如果最优距离小于阈值:跳过,不读入这组起终点\n starts.append(start)\n goals.append(goal)\n return starts, goals, optimal_dists\n\n\ndef log_reader(log_path):\n\n with open(log_path, \"r\") as log:\n data = json.load(log)\n\n scene_path = data[\"scene_path\"]\n # print(scene_path)\n map_path = data[\"map_path\"]\n map_size = data[\"map_size\"]\n agent_total = data[\"num_nodes\"]\n frame_length = data[\"num_slots\"]\n frames = data[\"history\"]\n required_length = data[\"required_length\"]\n\n print(\"帧长度:\"+str(frame_length))\n print(\"节点数:\"+str(agent_total))\n print(\"要求的计划长度:\"+str(required_length))\n\n starts, goals, optimal_dists = scene_reader(scene_path)\n\n # 用帧重构各节点轨迹\n traces = {} # 格式: 节点名:[[位置]]\n for key, values in frames.items():\n # key = 时间,value = [ [节点id(int),[x,y] ] ]\n for agents in values:\n agent_id = agents[0] # 节点名\n position = agents[1] # [x,y]\n # 在后面加上新位置\n if agent_id in traces:\n traces[agent_id].append(position)\n else:\n traces[agent_id] = [position]\n\n # 指标:\n\n # 1. 平均 最优路径长度/实际路径长度\n # sum (路径/最优)\n sum = 0\n for trace in traces.values():\n start = trace[0]\n index = starts.index(tuple(start))\n goal = goals[index] # 对应的终点\n optimal = optimal_dists[index] # 最优距离\n sum += len(trace)/optimal\n avg_real_vs_optimal = sum/agent_total\n print(\"实际路径长度/最优路径总长度:\"+str(avg_real_vs_optimal))\n\n # 2. 整体完成时间\n # 寻找最后一次空的前一个\n time = list(frames.keys())\n frame = list(frames.values())\n i = len(time)-1\n prev = True\n finish_time = -1\n while i >= 0:\n current = frame[i] # 当前帧中节点们的位置\n if not prev and current: # 如果后一帧空而此帧不空:就是你了\n finish_time = int(time[i])\n prev = current\n i -= 1\n if finish_time != -1:\n print(\"全部抵达终点时间:%d步。\" % finish_time)\n else:\n print(\"没有全部到达终点\")\n\n # 3. 平均完成时间\n avg_finish_time = 0\n # 对于每个agent,找出其在网络中存在的最后一刻\n agents_ended = set()\n found_agents = 0\n for time, frame in reversed(frames.items()):\n for agent in frame:\n if agent[0] not in agents_ended:\n agents_ended.add(agent[0])\n avg_finish_time += int(time)\n found_agents += 1\n if found_agents != agent_total:\n print(\"FATAL!\")\n print(\"全部耗时:%d\" % avg_finish_time)\n\n avg_finish_time = avg_finish_time/agent_total\n print(\"平均抵达终点时间:%f\" % avg_finish_time)\n\n # 4. 加入网络的平均耗时\n # 先看出每人的耗时\n join_time = {}\n agents_visited = set()\n for time, frame in frames.items():\n for agent in frame:\n agent_id = agent[0]\n if agent_id not in agents_visited:\n agents_visited.add(agent_id)\n join_time[agent_id] = int(time)\n times = list(join_time.values())\n sum_time = 0\n for time in times:\n sum_time += time\n avg_join_spent_time = sum_time/len(times)\n print(\"有%d/%d个节点成功入网,每个节点加入网络的平均耗时是:%d\" %\n (len(times), agent_total, avg_join_spent_time))\n\n # 5. 实际路径总长度vs最优路径总长度\n sum_actural = 0\n sum_optimal = 0\n for trace in traces.values():\n start = trace[0] # 路径开头就是起点\n index = starts.index(tuple(start)) # 根据起点获知他是谁\n goal = goals[index] # 根据他是谁获知其终点\n optimal = optimal_dists[index] # 最优距离\n sum_actural += len(trace)\n sum_optimal += optimal\n sum_actural_vs_optimal = sum_actural/sum_optimal # 实际路径总长度vs最优总长度\n print(\"总实际路径长度/最优路径长度:%f\" % sum_actural_vs_optimal)\n\n # 6. 信道中同时存在之agent数\n agent_in_channel = {}\n for time, frame in frames.items():\n '''\n time = int(time)\n if time-frame_length < 0:\n continue\n agent_in_channel[time-frame_length] = len(frame)\n '''\n time = int(time)\n agent_in_channel[time] = len(frame)\n\n # 去除尾部无人区\n # 找到最后一个非零数据的索引\n last_nonzero_index = len(agent_in_channel) - 1\n for i, data in enumerate(reversed(agent_in_channel.values())):\n if data != 0:\n last_nonzero_index = len(agent_in_channel) - 1 - i\n break\n \n # 获取非零部分的时间和数据\n filtered_times = list(agent_in_channel.keys())[:last_nonzero_index + 1]\n filtered_data_values = list(agent_in_channel.values())[:last_nonzero_index + 1]\n \n agent_in_channel = {}\n for i in range(len(filtered_times)):\n agent_in_channel[filtered_times[i]] = filtered_data_values[i]\n \n # 尾部加一个0,方便看\n agent_in_channel[filtered_times[-1]+1] = 0\n \n\n\n return agent_total, frame_length, avg_real_vs_optimal, finish_time, avg_finish_time, avg_join_spent_time, sum_actural_vs_optimal, required_length, agent_in_channel\n\n\ndef main():\n\n # 读取两组实验日志路径\n logs1 = traverse_directory(log_parent_path1)\n logs2 = traverse_directory(log_parent_path2)\n\n # 读取两组实验数据\n # 第一组\n agent_total1 = []\n frame_length1 = []\n avg_real_vs_optimal1 = [] \n finish_time1 = []\n avg_finish_time1 = [] \n avg_join_spent_time1 = []\n sum_actural_vs_optimal1 = []\n required_length1 = []\n agent_in_channel1 = []\n for log in logs1:\n a,b,c,d,e,f,g,h,i = log_reader(log)\n agent_total1.append(a)\n frame_length1.append(b)\n avg_real_vs_optimal1.append(c)\n finish_time1.append(d)\n avg_finish_time1.append(e)\n avg_join_spent_time1.append(f)\n sum_actural_vs_optimal1.append(g)\n required_length1.append(h)\n agent_in_channel1.append(i)\n \n # 第二组\n agent_total2 = []\n frame_length2 = []\n avg_real_vs_optimal2 = [] \n finish_time2 = []\n avg_finish_time2 = [] \n avg_join_spent_time2 = []\n sum_actural_vs_optimal2 = []\n required_length2 = []\n agent_in_channel2 = []\n for log in logs2:\n a,b,c,d,e,f,g,h,i = log_reader(log)\n agent_total2.append(a)\n frame_length2.append(b)\n avg_real_vs_optimal2.append(c)\n finish_time2.append(d)\n avg_finish_time2.append(e)\n avg_join_spent_time2.append(f)\n sum_actural_vs_optimal2.append(g)\n required_length2.append(h)\n agent_in_channel2.append(i) \n\n\n # 选一组channel中agent数量数据绘制\n\n '''\n # 选60agents的一组吧。\n indexs = []\n agent_number = 60\n for i in range(len(agent_total2)):\n if agent_total2[i] == agent_number:\n indexs.append(i)\n \n frame_length = []\n agent_total = []\n channel_usage = []\n for i in indexs:\n channel_usage.append(agent_in_channel2[i])\n frame_length.append(frame_length2[i])\n agent_total.append(agent_total2[i])\n \n # 画图\n plt.figure()\n\n color_cycle = plt.rcParams[\"axes.prop_cycle\"].by_key()[\"color\"]\n\n for i, result_dict in enumerate(channel_usage):\n times = list(result_dict.keys())\n values = np.array(list(result_dict.values()))\n values = values/agent_number*100\n color = color_cycle[i%len(color_cycle)+1]\n #plt.plot(times,values,color=color,label = \"agent number = \"+str(agent_total[i]))\n plt.plot(times,values,color=color,label = \"frame length = \" +str(frame_length[i]))\n plt.title(\"agent number = \"+str(agent_number))\n plt.xlabel(\"time\")\n plt.ylabel(\"% of agents in the channel\")\n plt.legend()\n plt.grid()\n plt.ylim(-1,105)\n plt.xlim(-5,1000)\n plt.tight_layout()\n plt.show()\n '''\n \n \n '''\n # 信道使用率\n # 选60agents的一组吧。\n indexs = []\n agent_number = 20\n for i in range(len(agent_total2)):\n if agent_total2[i] == agent_number:\n indexs.append(i)\n \n frame_length = []\n agent_total = []\n channel_usage = []\n for i in indexs:\n channel_usage.append(agent_in_channel2[i])\n frame_length.append(frame_length2[i])\n agent_total.append(agent_total2[i])\n \n # 画图\n plt.figure()\n\n color_cycle = plt.rcParams[\"axes.prop_cycle\"].by_key()[\"color\"]\n\n for i, result_dict in enumerate(channel_usage):\n times = list(result_dict.keys())\n values = np.array(list(result_dict.values()))\n values = values/frame_length[i]*100\n color = color_cycle[i%len(color_cycle)]\n #plt.plot(times,values,color=color,label = \"agent number = \"+str(agent_total[i]))\n plt.plot(times,values,color=color,label = \"frame length = \" +str(frame_length[i]))\n plt.title(\"agent number = \"+str(agent_number))\n plt.xlabel(\"time\")\n plt.ylabel(\"channel usage (%)\")\n plt.legend()\n plt.grid()\n plt.ylim(-1,105)\n plt.xlim(-5,1000)\n plt.tight_layout()\n plt.show()\n '''\n # 信道使用率\n # 选60agents的一组吧。\n indexs = []\n fl = 60\n for i in range(len(agent_total2)):\n if frame_length2[i] == fl:\n indexs.append(i)\n \n frame_length = []\n agent_total = []\n channel_usage = []\n for i in indexs:\n channel_usage.append(agent_in_channel2[i])\n frame_length.append(frame_length2[i])\n agent_total.append(agent_total2[i])\n \n # 画图\n plt.figure()\n\n color_cycle = plt.rcParams[\"axes.prop_cycle\"].by_key()[\"color\"]\n\n for i, result_dict in enumerate(channel_usage):\n times = list(result_dict.keys())\n values = np.array(list(result_dict.values()))\n values = values/frame_length[i]*100\n color = color_cycle[i%len(color_cycle)]\n #plt.plot(times,values,color=color,label = \"agent number = \"+str(agent_total[i]))\n plt.plot(times,values,color=color,label = \"agent number = \" +str(agent_total[i]))\n plt.title(\"frame length = \"+str(fl))\n plt.xlabel(\"time\")\n plt.ylabel(\"channel usage (%)\")\n plt.legend()\n plt.grid()\n plt.ylim(-1,105)\n plt.xlim(-5,1000)\n plt.tight_layout()\n plt.show()\n\n \n '''\n # 将其他的参数求平均\n agent_total = agent_total1+agent_total2\n frame_length = frame_length1+frame_length2\n avg_real_vs_optimal = avg_real_vs_optimal1+avg_real_vs_optimal2\n finish_time = finish_time1+finish_time2\n avg_finish_time = avg_finish_time1+avg_finish_time2\n avg_join_spent_time = avg_join_spent_time1+avg_join_spent_time2\n sum_actural_vs_optimal = sum_actural_vs_optimal1+sum_actural_vs_optimal2\n required_length = required_length1+required_length2\n \n _,_,avg_real_vs_optimal=average_performance(agent_total,frame_length,avg_real_vs_optimal)\n _,_,finish_time = average_performance(agent_total,frame_length,finish_time)\n _,_,avg_finish_time = average_performance(agent_total,frame_length,avg_finish_time)\n _,_,avg_join_spent_time = average_performance(agent_total,frame_length, avg_join_spent_time)\n agent_total,frame_length,sum_actural_vs_optimal = average_performance(agent_total,frame_length,sum_actural_vs_optimal)\n\n # 绘图\n fig = plt.figure(figsize=(12,12))\n \n # avg_finish_time\n x = agent_total\n y = frame_length\n z = avg_finish_time\n ax1 = fig.add_subplot(2,2, 1, projection='3d')\n ax1.scatter(x, y, z, c=z, cmap='viridis', marker='o')\n ax1.plot_trisurf(x,y,z, cmap='viridis', alpha=0.5)\n ax1.set_title('average agent arrival time',y=0.92,fontsize=12)\n ax1.set_xlabel(\"agent number\",fontsize=12)\n ax1.set_ylabel(\"frame length\",fontsize=12)\n ax1.set_zlabel(\"average agent arrival time\",fontsize=12) \n\n # 找到每个x值对应的z值最低的点的索引\n min_z_indices = []\n for xi in np.unique(x):\n mask = x == xi\n min_z_index = np.argmin(z[mask])\n min_z_indices.append(np.where(mask)[0][min_z_index])\n\n # 高亮每个x值对应的z值最低的点\n ax1.scatter(x[min_z_indices], y[min_z_indices], z[min_z_indices], c='r', marker='o',s=120, label='Min Z Points for each Agent Number')\n ax1.legend()\n ax1.view_init(elev=13, azim=-170)\n\n \n # finish time\n x = agent_total\n y = frame_length\n z = finish_time\n ax2 = fig.add_subplot(2, 2, 2, projection='3d')\n ax2.scatter(x, y, z, c=z, cmap='viridis', marker='o')\n ax2.plot_trisurf(x,y,z, cmap='viridis', alpha=0.5)\n ax2.set_title('final agent arrival time',y=0.92,fontsize=12)\n ax2.set_xlabel(\"agent number\",fontsize=12)\n ax2.set_ylabel(\"frame length\",fontsize=12)\n ax2.set_zlabel(\"final agent arrival time\",fontsize=12) \n\n # 找到每个x值对应的z值最低的点的索引\n min_z_indices = []\n for xi in np.unique(x):\n mask = x == xi\n min_z_index = np.argmin(z[mask])\n min_z_indices.append(np.where(mask)[0][min_z_index])\n\n # 高亮每个x值对应的z值最低的点\n ax2.scatter(x[min_z_indices], y[min_z_indices], z[min_z_indices], c='r', marker='o',s=120, label='Min Z Points for each Agent Number')\n ax2.legend()\n ax2.view_init(elev=13, azim=-170)\n\n # 平均入网耗时\n x = agent_total\n y = frame_length\n z = avg_join_spent_time\n ax3 = fig.add_subplot(2, 2, 3, projection='3d')\n ax3.scatter(x, y, z, c=z, cmap='viridis', marker='o')\n ax3.plot_trisurf(x,y,z, cmap='viridis', alpha=0.5)\n ax3.set_title(\"average network join time\",y=0.92,fontsize=12)\n ax3.set_xlabel(\"agent number\",fontsize=12)\n ax3.set_ylabel(\"frame length\",fontsize=12)\n ax3.set_zlabel(\"average network join time\",fontsize=12) \n\n # 找到每个x值对应的z值最低的点的索引\n min_z_indices = []\n for xi in np.unique(x):\n mask = x == xi\n min_z_index = np.argmin(z[mask])\n min_z_indices.append(np.where(mask)[0][min_z_index])\n\n # 高亮每个x值对应的z值最低的点\n ax3.scatter(x[min_z_indices], y[min_z_indices], z[min_z_indices], c='r', marker='o',s=120, label='Min Z Points for each Agent Number')\n ax3.legend()\n ax3.view_init(elev=13, azim=-170)\n\n # 总路径最优度\n x = agent_total\n y = frame_length\n z = sum_actural_vs_optimal\n ax4 = fig.add_subplot(2, 2, 4, projection='3d')\n ax4.scatter(x, y, z, c=z, cmap='viridis', marker='o')\n ax4.plot_trisurf(x,y,z, cmap='viridis', alpha=0.5)\n ax4.set_title(\"total path efficiency ratio\",y=0.92,fontsize=12)\n ax4.set_xlabel(\"agent number\",fontsize=12)\n ax4.set_ylabel(\"frame length\",fontsize=12)\n ax4.set_zlabel(\"total path efficiency ratio\",fontsize=12) \n\n ax4.set_zlim(1.0,2.0)\n\n # 找到每个x值对应的z值最低的点的索引\n min_z_indices = []\n for xi in np.unique(x):\n mask = x == xi\n min_z_index = np.argmin(z[mask])\n min_z_indices.append(np.where(mask)[0][min_z_index])\n\n # 高亮每个x值对应的z值最低的点\n # ax4.scatter(x[min_z_indices], y[min_z_indices], z[min_z_indices], c='r', marker='o',s=120, label='Min Z Points for each Agent Number')\n ax4.legend()\n ax4.view_init(elev=13, azim=-170)\n \n\n plt.tight_layout()\n plt.show()\n '''\n \n\n \n \n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"Vehshanaan/Dissertation2022","sub_path":"codes/experiment_results/agent_number vs frame_length/log_reader.py","file_name":"log_reader.py","file_ext":"py","file_size_in_byte":18641,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"11901576396","text":"import tensorflow as tf\nimport os\n\n# 定义模型超参数\nlearning_rate = 0.001\nnum_epochs = 10\nbatch_size = 32\n\n\n# 加载数据集\ndef load_dataset(directory):\n images = []\n labels = []\n for filename in os.listdir(directory):\n # 解析文件名获取标签\n label = int(filename[-5])\n filepath = os.path.join(directory, filename)\n image = tf.io.read_file(filepath)\n image = tf.image.decode_png(image)\n image = tf.image.resize(image, (128, 128))\n images.append(image)\n labels.append(label)\n return images, labels\n\n\n# 加载数据集\ntrain_images, train_labels = load_dataset('D:\\\\DATA1\\\\MRIi')\nval_images, val_labels = load_dataset('D:\\\\DATA1\\\\val\\\\MRIi')\ntest_images, test_labels = load_dataset('D:\\\\DATA1\\\\test\\\\MRIi')\n\n# 将数据集转化为 TensorFlow Dataset 对象\ntrain_dataset = tf.data.Dataset.from_tensor_slices((train_images, train_labels))\nval_dataset = tf.data.Dataset.from_tensor_slices((val_images, val_labels))\ntest_dataset = tf.data.Dataset.from_tensor_slices((test_images, test_labels))\n\n# 打乱并分批次\ntrain_dataset = train_dataset.shuffle(len(train_images)).batch(batch_size)\nval_dataset = val_dataset.batch(batch_size)\ntest_dataset = test_dataset.batch(batch_size)\n\n# 建立模型\nmodel = tf.keras.Sequential([\n tf.keras.layers.Conv2D(32, 3, activation='relu', input_shape=(128, 128, 3)),\n tf.keras.layers.MaxPooling2D(),\n tf.keras.layers.Conv2D(64, 3, activation='relu'),\n tf.keras.layers.MaxPooling2D(),\n tf.keras.layers.Conv2D(128, 3, activation='relu'),\n tf.keras.layers.MaxPooling2D(),\n tf.keras.layers.Flatten(),\n tf.keras.layers.Dense(128, activation='relu'),\n tf.keras.layers.Dense(1, activation='sigmoid')\n])\n\n# 编译模型\nmodel.compile(optimizer=tf.keras.optimizers.Adam(learning_rate), loss=tf.keras.losses.BinaryCrossentropy(),\n metrics=['accuracy'])\n\n# 训练模型\nhistory = model.fit(train_dataset, epochs=num_epochs, validation_data=val_dataset)\n\n# 评估模型\nloss, acc = model.evaluate(test_dataset)\nprint(\"Loss: {}, Accuracy: {}\".format(loss, acc))\n\n# 保存模型\nmodel.save('D:\\\\DATA1\\\\train\\\\MRI1.h5')\n","repo_name":"hecang01/LDHmri","sub_path":"trush/11.py","file_name":"11.py","file_ext":"py","file_size_in_byte":2164,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"18843460253","text":"import math\n\n#11задание\ndef degrees2radians(degrees):\n formula_degrees2radians = degrees * math.pi / 180\n return formula_degrees2radians\n\nprint(\"Косинус угла 45 градусов равен : %.4f\" % (math.cos(degrees2radians(45))))\nprint(\"Косинус угла 40 градусов равен : %.4f\" % (math.cos(degrees2radians(40))))\nprint(\"Косинус угла 60 градусов равен : %.4f\" % (math.cos(degrees2radians(60))))\n\n#13задание\ndef triangle_square_and_perimeter(a, b):\n triangle_square = a * b / 2\n c = math.sqrt(a**2 + b**2)\n perimeter = a + b + c\n return triangle_square, perimeter\n\nres1, res2 = triangle_square_and_perimeter(5,8)\nprint(\"Площадь треугольника : %.2f, а его периметр : %.2f\" % (res1, res2))\n\n\n\n\n\n\n","repo_name":"Lera87/homework1","sub_path":".idea/homework 11-13.py","file_name":"homework 11-13.py","file_ext":"py","file_size_in_byte":814,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"39254160650","text":"# Set of functions to sample from the latent space and synthesize the corresponding audio\n\n# Dependencies\nimport numpy as np\nfrom scipy.signal import windows\nfrom scipy import interpolate\n\n\nimport sys\nsys.path.append('../')\nsys.path.append('../../models/')\nfrom sineModel import sineModelAnal,sineModelSynth\nfrom hprModel import hprModelAnal,hprModelSynth\nfrom stft import stftAnal,stftSynth\n\n# N-D Random walks to sample closeby points in the latent space(for sustain sound generation)\ndef rand_walk(start_point, step_size, num_iters, sigma = 1):\n \"\"\"\n Function to initiate a random walk from a starting point\n \n Inputs\n ------\n start_point : vector(1-D Numpy array)\n Vector of the initial point of the walk\n step_size : float\n Size of random step\n num_iters : integer\n Number of random walks\n sigma : float(>0)\n \tVariance of the random walk\n \n Outputs\n -------\n walk_locs : ndarray\n Matrix whose columns depict the location at each instant, and number of columns depict the number of walks\n \"\"\"\n \n dim = start_point.shape[0]\n walk_locs = np.zeros((dim,num_iters))\n \n walk_locs[:,0] = start_point\n \n for i in range(1,num_iters):\n w = step_size * np.random.normal(0,sigma,dim)\n walk_locs[:,i] = walk_locs[:,i - 1] + w\n \n return walk_locs\n\n# Use the below function sequentially after passing the output of the above through the decoder to obtain the reconstructed cepstral coeffs\ndef recon_samples_ls(matrix_ceps_coeffs,midi_pitch, params, f_ref = 440, choice_f = 0):\n\t\"\"\"\n\tReturns the audio corresponding to an overlap add of each of the frames reconstructed from the latent variables in walk_locs\n\tNote : The input should be in log dB (log|X|)\n\tInputs\n\t------\n\tmatrix_ceps_coeffs : np.ndarray\n\t\tMatrix whose columns depict the cepstral frames(sequential)\n\tmidi_pitch : list of int(0 < midi_pitch < 128)\n\t\tList of MIDI number of the pitch at each time frame(can directly feed in the NSynth parameter)(same as the number of columns in the above input matrix)\n\t\tIf input is a single number, that will be the pitch for all the frames\n\tparams : dict\n\t\tParameter dictionary for the harmonic reconstruction containing the following keys\n\t\t\t- fs : integer\n\t\t\t\tSampling rate of the audio\n\t\t\t- W : integer\n\t\t\t\tWindow size(number of frames)\n\t\t\t- N : integer\n\t\t\t\tFFT size(multiple of 2)\n\t\t\t- H : integer\n\t\t\t\tHop size\n\t\t\t- nH : integer\n\t\t\t\tNumber of harmonics to synthesize\n\tf_ref : float\n\t\tReference frequency for MIDI(440 Hz by default)\n\tchoice_f : 0 or 1(0 by default)\n\t\tIf 0, will accept MIDI pitch and convert it to Hz\n\t\tIf 1, will accept and use pitch directly in Hz\n\t\"\"\"\n\n\tfs = params['fs']\n\tW = params['W']\n\tN = params['N']\n\tH = params['H']\n\tnH = params['nH']\n\tw = windows.hann(W)\n\n\t# Defining the Frequency and Magnitude matrices\n\tnum_frames = matrix_ceps_coeffs.shape[1]\n\n\tif(type(midi_pitch) == int):\n\t\tmidi_pitch = np.zeros(num_frames) + midi_pitch\n\n\tif(choice_f == 0):\n\t\t# Convert MIDI to Hz\n\t\thz_from_midi = f_ref*(2**((midi_pitch - 69)/12.0))\n\t\tf0 = hz_from_midi\n\telse:\n\t\tf0 = midi_pitch\n\n\tM = np.zeros((num_frames, nH))\n\tF = np.zeros((num_frames, nH))\n\t\n\tfor j in range(num_frames):\n\t\tfor i in range(F.shape[1]):\n\t\t\tF[j,i] = (i+1)*f0[j]\n\n\t# Sample the frequencies from the envelope at each instant\n\tfor i in range(num_frames):\n\t\t# Flip and append the array to give a real frequency signal to the fft input\n\t\tceps_current = matrix_ceps_coeffs[:,i]\n\t\t# Pad with zeros\n\t\tcc_real = np.pad(ceps_current,[0 , N - len(ceps_current)],mode = 'constant',constant_values=(0, 0))\n\t\tcc_real = np.concatenate((cc_real[:N//2],np.flip(cc_real[1:N//2 + 1])))\n\t\tcc_real[0] = ceps_current[0]\n\t\t\n\t\t# Obtain the Envelope from the cepstrum\n\t\tspecenv = np.real(np.fft.fft(cc_real))\n\t\tfbins = np.linspace(0,fs,N)\n\t\tfp = interpolate.interp1d(np.arange(params['N']),specenv,kind = 'linear',fill_value = 'extrapolate', bounds_error=False)\n\t\tM[i,:] = 20*fp((F[i,:]/fs)*N)\n\n\n\taudio_recon = sineModelSynth(F, M, np.empty([0,0]), W, H, fs)\n\n\treturn audio_recon\n\n\n\n\n\n\n","repo_name":"SubramaniKrishna/VaPar-Synth","sub_path":"Network/sampling_synth.py","file_name":"sampling_synth.py","file_ext":"py","file_size_in_byte":4054,"program_lang":"python","lang":"en","doc_type":"code","stars":32,"dataset":"github-code","pt":"81"} +{"seq_id":"1401373732","text":"# USAGE\n# python index_features_2kp.py --dataset ../input/train_specific --features-db train --mask-db ../input/mask_predictions_train_known_4\n# python index_features_2kp.py --dataset ../input/test --features-db test --mask-db ../input/mask_predictions_test_4\n\n\nfrom tqdm import tqdm\nfrom imutils.feature import FeatureDetector_create, DescriptorExtractor_create\nfrom imutils import paths\nimport argparse\nimport imutils\nimport cv2\nimport os\nimport numpy as np\n\nap = argparse.ArgumentParser()\nap.add_argument(\"-d\", \"--dataset\", required=True, help=\"Path to the directory that contains the images to be indexed\")\nap.add_argument(\"-f\", \"--features-db\", required=True, help=\"either test or train\")\nap.add_argument(\"-m\", \"--mask-db\", required=True, help=\"Path to where the masks will be stored\")\nargs = vars(ap.parse_args())\n\ndef describe_kps(image, mask): \n kps = detector.detect(image, mask=mask)\n (kps, descs) = descriptor.compute(image, kps)\n if len(kps) == 0:\n return (None, None)\n kps = np.float32([kp.pt for kp in kps])\n return (kps, descs)\n\n# the detector and descriptor used for analysis\ndetector = FeatureDetector_create(\"SIFT\")\ndescriptor = DescriptorExtractor_create(\"RootSIFT\")\n\nstart=0\nindexlist = [] #list of indexes that relate to the rows of the kps for a given image\nimagelist = [] #list of image files\nkplist = [] #vector of length 130. 1st two numbers are the coordinates, last 128 are the rootsift descriptor for the given point\nfor (i, imagePath) in tqdm(enumerate(paths.list_images(args[\"dataset\"]))):\n #read the image and mask\n filename = imagePath[imagePath.rfind(\"/\") + 1:]\n image = cv2.imread(imagePath)\n image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n mask = cv2.imread(args[\"mask_db\"] + '/' + os.path.basename(imagePath)[:-4]+'.png', 0)\n mask[mask>0]=1\n \n #if the mask is small, just use the entire image. helps reduce false positives due to poor mask\n if np.sum(mask) < 1000:\n mask[mask==0] = 1\n # describe the image\n (kps, descs) = describe_kps(image, mask)\n # if either the keypoints or descriptors are None, then ignore the image\n if kps is None or descs is None:\n continue\n end = start+len(kps)\n indexlist.append((start, end))\n imagelist.append(filename)\n kplist.extend(np.hstack([kps, descs]))\n start = end\n\nkps_all = np.array(kplist)\ncoordinate_array = kps_all[:,:2]\nfeatures_array = kps_all[:,2:]\n\n#write the arrays to numpy files and save\nnp.save('{}_imgsI.npy'.format(args[\"features_db\"]), np.array(imagelist))\nnp.save('{}_idxsI.npy'.format(args[\"features_db\"]), np.array(indexlist))\nnp.save('{}_featsI.npy'.format(args[\"features_db\"]), features_array)\nnp.save('{}_idxsI.npy'.format(args[\"features_db\"]), coordinate_array)\n","repo_name":"daustingm1/humpback-whale-4th-place","sub_path":"kps/index_features_2kp.py","file_name":"index_features_2kp.py","file_ext":"py","file_size_in_byte":2752,"program_lang":"python","lang":"en","doc_type":"code","stars":28,"dataset":"github-code","pt":"81"} +{"seq_id":"71116134346","text":"def anagrams(word, words): #Takes in two arguments, the anagram base word, and a list of words: words.\n sword = ()\n final = []\n for letter in sorted(word):\n sword = sword + (letter, word.count(letter)) \n for wrd in words:\n swords = ()\n for letter in sorted(wrd):\n swords = swords + (letter, wrd.count(letter))\n if swords == sword:\n final = final + [wrd] \n return final\n","repo_name":"Ntwadumela42/python_practice","sub_path":"anagram_finder.py","file_name":"anagram_finder.py","file_ext":"py","file_size_in_byte":428,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"21150439139","text":"import os\nimport optparse\nimport sys\nimport shutil\nimport tempfile\nimport test_rendering\n\nUSAGE_STRING = 'Usage: %s input... expectedDir'\nHELP_STRING = '''\n\nTakes input SkPicture files and renders them as PDF files, and then compares\nthose resulting PDF files against PDF files found in expectedDir.\n\nEach instance of \"input\" can be either a file (name must end in .skp), or a\ndirectory (in which case this script will process all .skp files within the\ndirectory).\n'''\n\n\ndef Main(args):\n \"\"\"Allow other scripts to call this script with fake command-line args.\n\n @param The commandline argument list\n \"\"\"\n parser = optparse.OptionParser(USAGE_STRING % '%prog' + HELP_STRING)\n parser.add_option('--render_dir', dest='render_dir',\n help = ('specify the location to output the rendered '\n 'files. Default is a temp directory.'))\n parser.add_option('--diff_dir', dest='diff_dir',\n help = ('specify the location to output the diff files. '\n 'Default is a temp directory.'))\n\n options, arguments = parser.parse_args(args)\n\n if (len(arguments) < 3):\n print(\"Expected at least one input and one ouput folder.\")\n parser.print_help()\n sys.exit(-1)\n\n inputs = arguments[1:-1]\n expected_dir = arguments[-1]\n\n test_rendering.TestRenderSkps(inputs, expected_dir, options.render_dir,\n options.diff_dir, 'render_pdfs', '')\n\nif __name__ == '__main__':\n Main(sys.argv)\n\n","repo_name":"google/skia","sub_path":"tools/test_pdfs.py","file_name":"test_pdfs.py","file_ext":"py","file_size_in_byte":1525,"program_lang":"python","lang":"en","doc_type":"code","stars":8112,"dataset":"github-code","pt":"81"} +{"seq_id":"43055364682","text":"#!/usr/bin/python\nfrom selenium import webdriver\nimport os\nimport time\ndir_path = os.path.dirname(os.path.realpath(__file__))\n\ndef is_captcha(driver):\n\treturn 'class=\"g-recaptcha\"' in chrome.page_source\n\nPROXY = \"127.0.0.1:8084\"\nprint(\"Started browser\")\nchrome_options = webdriver.ChromeOptions()\nchrome_options.add_argument('--proxy-server=%s' % PROXY)\n#chrome_options.add_argument(\"--headless\")\nchrome_options.add_argument(\"user-data-dir=selenium\")\n\nchrome = webdriver.Chrome(chrome_options=chrome_options)\nchrome.get(\"https://www.t-mobile.com/cell-phone/samsung-galaxy-s10e\")\nwhile True:\n\ttry:\n\t\tchrome.find_element_by_css_selector(\"a.cursor-pointer > span.ng-binding.ng-scope\").click()\n\texcept:\n\t\ttime.sleep(1)\nraw_input(\"continue \")\n","repo_name":"theriley106/TMobALL","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":"81"} +{"seq_id":"20245017413","text":"from bs4 import BeautifulSoup\nimport requests\nfrom fake_useragent import UserAgent\nimport csv\n\nalf = 'АБВГДЕЖЗИКЛМНОПРСТУФХЦЧШЩЭЮЯ'\nua = UserAgent\nheaders = {'accept': '*/*', 'user-agent': ua.firefox}\n\n\ndef pars():\n\n with open('num_animal.csv', 'w', encoding='cp1251', newline='') as file:\n writer = csv.writer(file, delimiter=';')\n writer.writerow(\n [\n 'Буква:',\n 'Кол-во',\n ]\n )\n\n for coun in alf:\n number = 0\n urla = f'https://ru.wikipedia.org/w/index.php?title=%D0%9A%D0%B0%D1%82%D0%B5%D0%B3%D0%BE%D1%' \\\n f'80%D0%B8%D1%8F%3A%D0%96%D0%B8%D0%B2%D0%BE%D1%82%D0%BD%D1%8B%D0%B5_%D0%BF%D0%BE_%D0%B0%' \\\n f'D0%BB%D1%84%D0%B0%D0%B2%D0%B8%D1%82%D1%83&from={coun}'\n\n response = requests.get(urla, headers)\n soup = BeautifulSoup(response.text, 'lxml')\n data1 = soup.find('div', class_='mw-category mw-category-columns')\n animals = data1.find_all('li')\n\n for i in animals:\n i = i.text.strip()\n if str(i[0]) == coun:\n number += 1\n else:\n break\n\n lock = True\n while lock:\n\n data2 = soup.find('div', id='mw-pages')\n teg_a = data2.find_all('a')\n url_next_page = ''\n for next_page in teg_a:\n page = next_page.text\n if page == 'Следующая страница':\n url_next_page += 'https://ru.wikipedia.org/' + next_page.get('href')\n\n response = requests.get(url_next_page, headers)\n soup = BeautifulSoup(response.text, 'lxml')\n data1 = soup.find('div', class_='mw-category mw-category-columns')\n animals = data1.find_all('li')\n for i in animals:\n i = i.text\n if str(i[0]) == coun:\n number += 1\n else:\n lock = False\n\n with open('num_animal.csv', 'a', encoding='cp1251', newline='') as file:\n writer = csv.writer(file, delimiter=';')\n writer.writerow(\n [\n coun,\n number,\n ]\n )\n\n\nif __name__ == '__main__':\n pars()\n","repo_name":"alex23-93/Pars","sub_path":"psrs_wiki.py","file_name":"psrs_wiki.py","file_ext":"py","file_size_in_byte":2316,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"74210896264","text":"import vxi11 \nimport time\nimport sys\nimport signal \nfrom datetime import datetime as dt\n\nfinish = False\ndef sigintHandler(signal, frame):\n print ('Ctrl-C Raised...cleaning up')\n frame.f_globals['finish'] = True\n finish = True\n\ndef sigtermHandler(signal, frame):\n print('Sig Term received, cleaning up')\n frame.f_globals['finish'] = True\n \n \nrunnumber = sys.argv[1]\n\nsampleSeconds = sys.argv[2]\n\npath = sys.argv[3] #\"/data/testbeam_2021_05_data/sensors_data/\"\n\nfilenametemp = \"currentB1B2_\"\next = \".csv\"\nfilename = path + filenametemp + str(runnumber) + ext\nsavefile = open(filename,\"w\")\n\ndef readKeithleyCurrent(inst):\n\n\n inst.write(\"print(smu.measure.read())\")\n return inst.read()\n\n\ndef readAgilentCurrent(inst):\n\n inst.write(':MEAS:CURR?')\n return inst.read()\n\n\ndef setKeithleyVoltage(inst, v):\n\n inst.write('smu.source.level = {0}'.format(v))\n\n\n\n\ndef setAgilentVolage(inst, v):\n\n inst.write(':SOUR:VOLT {0}'.format(v))\n\n\ndef readAgilentVoltage(inst):\n inst.write(':MEAS:VOLT?')\n return inst.read()\n\ndef readKeithleyVoltage(inst):\n inst.write('print(smu.source.level)')\n return inst.read()\n \nagi = vxi11.Instrument('192.168.133.176')\nk2450 = vxi11.Instrument('192.168.133.60') \ntry:\n\n\n line = agi.ask('*IDN?')\n timeout = 0\n while line.find('2911') == -1:\n line = agi.read()\n timeout = timeout + 1\n if timeout > 5:\n break\n\n print (line)\n k2450.timeout = 2.0\n\n \n\n line = k2450.ask('*IDN?')\n timeout = 0\n while line.find('2450') == -1:\n line = k2450.read()\n timeout = timeout + 1\n if timeout > 5:\n break\n \n print (line)\n agi.timeout = 2.0\n #clear buffer \n\n k2450.write(\"print('Done')\")\n msg = ''\n while msg.find('Done') == -1:\n print(msg)\n msg = k2450.read()\n \n vBiasKei = 38.8\n vBiasAgi = 38.8\n vLow = 41.4\n\n# while True:\n # print('Waiting...Press enter to start running, will go for 12s')\n # line = sys.__stdin__.readline()\n # if line.find('STOP') != -1:\n # break\n\n agiCurrent = readAgilentCurrent(agi)\n keithCurrent = readKeithleyCurrent(k2450)\n print ('Setting Keithley V Bias: {0}, Agilent: {1}'.format(vBiasKei, vBiasAgi))\n #setAgilentVolage(agi, vBiasAgi)\n #setKeithleyVoltage(k2450, vBiasKei)\n agiCurrent = readAgilentCurrent(agi)\n keithCurrent = readKeithleyCurrent(k2450)\n print ('Agi Current: {0}\\nKeith Current: {1}'.format(agiCurrent, keithCurrent))\n print ('Agi Vb: {0}\\nKeith Vb: {1}'.format(vBiasAgi, vBiasKei))\n signal.signal(signal.SIGINT, sigintHandler)\n signal.signal(signal.SIGTERM, sigtermHandler)\n for i in range(0, int(sampleSeconds)):\n #print('IN SPILL!')\n if finish:\n break\n time.sleep(0.7)\n now = dt.now()\n current_time = now.strftime(\"%D %H:%M:%S\")\n agiCurrent = readAgilentCurrent(agi)\n keithCurrent = readKeithleyCurrent(k2450)\n print ('Agi Current: {0}\\nKeith Current: {1}'.format(agiCurrent, keithCurrent))\n savefile.write(current_time + \", B2:\" + agiCurrent + \", B1:\" + keithCurrent + '\\n')\n savefile.flush()\n #print ('Lowering vBias to {0}'.format(vLow))\n #setAgilentVolage(agi, vLow)\n #setKeithleyVoltage(k2450, vLow)\n agiCurrent = readAgilentCurrent(agi)\n keithCurrent = readKeithleyCurrent(k2450)\n print ('Agi Current: {0}\\nKeith Current: {1}'.format(agiCurrent, keithCurrent))\n \n print('Final Voltage Keithley:{0}'.format(readKeithleyVoltage(k2450)))\n print('Final Current Keithley:{0}'.format(readKeithleyCurrent(k2450)))\n print('Final Voltage Agilent:{0}'.format(readAgilentVoltage(agi)))\n print('Final Current Agilent:{0}'.format(readAgilentCurrent(agi)))\n\n \n\n \nexcept Exception as e:\n print (e)\nfinally:\n k2450.close()\n agi.close()\n savefile.close()\n","repo_name":"carlosperezlara/rpcLab","sub_path":"pyVISA/bothSMU.py","file_name":"bothSMU.py","file_ext":"py","file_size_in_byte":3933,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"207274746","text":"import sys\r\nfrom PyQt5.uic import loadUi\r\nfrom PyQt5 import QtWidgets\r\nfrom PyQt5.QtWidgets import QDialog, QApplication\r\nimport sqlite3\r\nclass Home(QDialog):\r\n def __init__(self):\r\n super(Home, self).__init__()\r\n loadUi(\"home.ui\",self)\r\n self.push_info.clicked.connect(self.gotoinfo)\r\n self.push_diem_v1.clicked.connect(self.goto_diem_v1)\r\n\r\n def gotoinfo(self):\r\n info = in_fo()\r\n widget.addWidget(info)\r\n widget.setCurrentIndex(widget.currentIndex() + 1)\r\n def goto_diem_v1(self):\r\n diem_v1 = diemv1()\r\n widget.addWidget(diem_v1)\r\n widget.setCurrentIndex(widget.currentIndex() + 1)\r\n\r\n\r\n\r\n\r\nclass in_fo(QDialog):\r\n def __init__(self):\r\n super(in_fo, self).__init__()\r\n loadUi(\"in_fo.ui\",self)\r\n\r\nclass diemv1(QDialog):\r\n def __init__(self):\r\n super(diemv1, self).__init__()\r\n loadUi(\"nhap_diem_vong_1.ui\",self)\r\napp=QApplication(sys.argv)\r\nHomes = Home()\r\nwidget = QtWidgets.QStackedWidget()\r\nwidget.addWidget(Homes)\r\nwidget.setFixedHeight(650)\r\nwidget.setFixedWidth(700)\r\nwidget.show()\r\ntry:\r\n sys.exit(app.exec_())\r\nexcept:\r\n print(\"Exiting\")\r\n","repo_name":"babydhv/code","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1169,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"29546085151","text":"\r\nclass RRQueue:\r\n def __init__(self, size=1):\r\n self.size = size\r\n self.a = []\r\n\r\n def add_to_back(self, new):\r\n try:\r\n self.a.append(new)\r\n except IndexError:\r\n print('Queue Is Full!\\n')\r\n\r\n def move_first_to_back(self):\r\n try:\r\n temp = self.a.pop(0)\r\n self.a.append(temp)\r\n except IndexError:\r\n \"\\nQueue Is Empty!\"\r\n self.show_queue()\r\n\r\n def remove(self, id):\r\n if len(self.a) == 1:\r\n print(\"\\n\\n{} Complete! Removed From Queue!\".format(id.getid()))\r\n self.a = []\r\n else:\r\n for i in range(len(self.a)-1):\r\n if self.a[i] == id:\r\n self.a.remove(id)\r\n print(\"\\n\\n{} Complete! Removed From Queue!\".format(id.getid()))\r\n\r\n self.show_queue()\r\n\r\n def get_queue(self):\r\n return self.a\r\n\r\n def curr_process(self):\r\n if len(self.a) > 0:\r\n return self.a[0]\r\n else:\r\n return -1 # RETURNS -1 WHEN THERE'S NOTHING LEFT IN THE QUEUE\r\n\r\n def show_queue(self):\r\n b = []\r\n c = []\r\n for i in range(len(self.a)):\r\n b.insert(i, self.a[i].getid())\r\n c.insert(i, self.a[i].currservicetime)\r\n\r\n print(\"\\n\\nFRONT:: {} ::BACK\\n\".format(b), end=\"\")\r\n print(\"TIMES:: {} ::LEFT\\n\".format(c))\r\n\r\n def isempty(self):\r\n if len(self.a) == 0:\r\n return True\r\n return False\r\n\r\n def isin(self, x): # checks is string x is in the queue already\r\n if self.a.count(x) > 0:\r\n return True\r\n else:\r\n return False\r\n\r\n","repo_name":"NotEnoughMilk/CSC440--RoundRobin","sub_path":"queue.py","file_name":"queue.py","file_ext":"py","file_size_in_byte":1682,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"5423259980","text":"# python3\nimport random\n\ndef max_pairwise_productFAST(numbers):\n n = len(numbers)\n x = -1\n for first in range(n):\n if numbers[first] > numbers[x] or x == -1:\n x = first\n y = -1\n for second in range(n):\n if second != x:\n if numbers[second] > numbers[y] or y == -1:\n y = second\n return numbers[x] * numbers[y]\n\ndef max_pairwise_product(numbers):\n n = len(numbers)\n max_product = 0\n for first in range(n):\n for second in range(first + 1, n):\n max_product = max(max_product,\n numbers[first] * numbers[second])\n\n return max_product\n\nif __name__ == '__main__':\n input_n = int(input())\n input_numbers = [int(x) for x in input().split()]\n print(max_pairwise_productFAST(input_numbers))\n\n##if __name__ == '__main__':\n## while True:\n## n = random.randint(2,5)\n## arr = []\n## for j in range(n):\n## arr.append(random.randint(1,10))\n## print(arr)\n## res1 = max_pairwise_product(arr)\n## res2 = max_pairwise_productFAST(arr)\n## if res1 != res2:\n## print('Wrong answer: ' + str(res1) + ' ' + str(res2))\n## break\n## pass \n## else:\n## print('OK')\n## pass\n \n","repo_name":"Russellkusuma/GoogleCSSICoursera_AlgorithmicToolbox","sub_path":"week1_programming_challenges/2_maximum_pairwise_product/max_pairwise_product.py","file_name":"max_pairwise_product.py","file_ext":"py","file_size_in_byte":1294,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"34197942586","text":"import re\r\n\r\n\r\n\r\n\r\ndef wypiszpoprawne(ip):\r\n for x in ip:\r\n x=x.split('.')\r\n \r\n \r\n test=1\r\n for y in x:\r\n # print(y)\r\n if(int(y) >= 0 and int(y) <= 255):\r\n pass\r\n else:\r\n test=0\r\n if test==1:\r\n scal=x[0]+'.'+x[1]+'.'+x[2]+'.'+x[3]\r\n print(scal)\r\n \r\n \r\n \r\n\r\n \r\n \r\n # dopasowanie2=re.match(r'^(?:[0-9]{1,3}\\.){3}[0-9]{1,3}$',ip)\r\n #if dopasowanie2:\r\n # print(dopasowanie2)\r\n\r\ndef func(nazwa_pliku):\r\n try:\r\n # print(nazwa_pliku)\r\n f=open(nazwa_pliku,'r')\r\n #print(f.readline())\r\n except:\r\n print('nie mozna otworzyc pliku')\r\n else:\r\n tekst=f.read()\r\n wzorzec = r' \\d\\d*\\.\\d\\d*\\.\\d\\d*\\.\\d\\d* '\r\n #while(True):\r\n dopasowanie = re.findall(wzorzec, tekst)\r\n if dopasowanie:\r\n #print (dopasowanie)\r\n wypiszpoprawne(dopasowanie)\r\n #print (dopasowanie)\r\n \r\n \r\n\r\n \r\nfunc('plik_zad3.txt')\r\n\r\n \r\n","repo_name":"Arhelyd/python-kolos","sub_path":"p4/z3.py","file_name":"z3.py","file_ext":"py","file_size_in_byte":1113,"program_lang":"python","lang":"pl","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"372031873","text":"import os\nimport argparse\nimport torch\nimport torch.nn as nn\nfrom sklearn.model_selection import StratifiedKFold\n\nfrom trainer import Trainer\nfrom predictor import Predictor\n\nfrom utils import *\nfrom models import simple_NN, WEATHER_MODEL, SlowFast, EVA\nfrom loss_fn import FocalLoss\n\ndef main(args):\n device = torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu')\n model = SlowFast(num_classes=args.NUM_CLASSES).to(device)\n param_optimizer = list(model.named_parameters())\n no_decay = ['bias', 'LayerNorm.bias', 'LayerNorm.weight']\n optimizer_grouped_parameters = [\n {'params': [p for n, p in param_optimizer if not any(\n nd in n for nd in no_decay)], 'weight_decay': 0.01},\n {'params': [p for n, p in param_optimizer if any(\n nd in n for nd in no_decay)], 'weight_decay': 0.0}\n ]\n \n # model = simple_NN(\n # model_name=args.MODEL_NAME, \n # num_classes=args.NUM_CLASSES, \n # in_chans=args.IN_CHANNEL).to(device)\n \n # model = EVA(\n # num_classes=args.NUM_CLASSES).to(device)\n \n # model = WEATHER_MODEL(num_classes=args.NUM_CLASSES).to(device)\n if args.MODE == 'train' :\n os.makedirs(args.OUTPUT, exist_ok=True)\n save_config(vars(args), args.OUTPUT)\n\n # optimizer = torch.optim.RAdam(model.parameters(),\n # lr=args.LEARNING_RATE)\n optimizer = torch.optim.AdamW(optimizer_grouped_parameters,\n lr=args.LEARNING_RATE)\n # optimizer = torch.optim.AdamW(model.parameters(),\n # lr=args.LEARNING_RATE)\n # criterion = nn.CrossEntropyLoss(weight=torch.tensor([2.1703, 1.0000, 1.8429])).to(device)\n # criterion = nn.CrossEntropyLoss().to(device)\n criterion = FocalLoss(args.FOCAL_GAMMA, args.FOCAL_ALPHA)\n # criterion = nn.BCEWithLogitsLoss(pos_weight=torch.tensor([0.13242574]).to(device=device, dtype=torch.float))\n\n if args.KFOLD == 0:\n trainer = Trainer(model, optimizer, criterion, device, args)\n trainer.run()\n\n elif args.KFOLD > 0:\n kfold = StratifiedKFold(n_splits=args.KFOLD, shuffle=True)\n trainer = Trainer(model, optimizer, criterion, device, args)\n for k, (train_ind, valid_ind) in enumerate(kfold.split(trainer.img_set, trainer.label_set)):\n trainer.kfold_setup(model, optimizer, criterion, train_ind, valid_ind, k)\n trainer.run()\n\n elif args.MODE == 'test' :\n\n predictor = Predictor(model, device, args)\n\n preds = predictor.run()\n save_to_csv(predictor.df, preds, args.OUTPUT)\n\n\n\n\nif __name__ == \"__main__\" :\n parser = argparse.ArgumentParser(description=\"\")\n\n subparsers = parser.add_subparsers(dest='MODE')\n\n\n # common\n parser.add_argument(\"--BATCH_SIZE\", type=int, default=2)\n parser.add_argument(\"--MODEL_NAME\", type=str, default='slowfast')#eva_large_patch14_336\n parser.add_argument(\"--NUM_CLASSES\", type=int, default=3)\n\n parser.add_argument(\"--IMG_PATH\", type=str, default=\"./data/train/*\")\n parser.add_argument(\"--CSV_PATH\", type=str, default=\"./data/Video_EgoCrash_train.csv\",\n help='For test, using sample_submission.csv file')\n parser.add_argument(\"--OUTPUT\", type=str, default='./ckpt/Video_EgoCrash_slowfast_16x6_r101_5050',\n help='For train, checkpoint save path \\\\'\n 'For test, predicted label save path')\n parser.add_argument(\"--RESIZE\", type=int, default=224)\n\n # train\n train_parser = subparsers.add_parser('train')\n train_parser.add_argument(\"--LEARNING_RATE\", type=float, default=1e-3)\n train_parser.add_argument(\"--EPOCHS\", type=int, default=70)\n train_parser.add_argument(\"--APPLY_CUTMIX\", type=bool, default=False)\n train_parser.add_argument(\"--APPLY_MIXUP\", type=bool, default=False)\n train_parser.add_argument(\"--THRESHOLD\", type=float, default=0.5)\n train_parser.add_argument(\"--SHUFFLE\", type=bool, default=True)\n train_parser.add_argument(\"--STACK\", type=bool, default=False)\n train_parser.add_argument(\"--IN_CHANNEL\", type=int, default=3)\n # train_parser.add_argument(\"--CTL_STEP\", nargs=\"+\", type=int, default=[36, 61])\n train_parser.add_argument(\"--FOCAL_GAMMA\", type=int, default=2)\n train_parser.add_argument(\"--FOCAL_ALPHA\", type=int, default=2)\n train_parser.add_argument(\"--CLASS_WEIGHT\", nargs='+', type=str, default=[1.0000, 4.2328, 3.5012])\n ## Video EgoCrash = [1.0000, 4.2328, 3.5012]\n ## Video Weather = [1.0000, 6.1596, 9.8136]\n ## Video Timing = [7.8193, 1.0000]\n train_parser.add_argument(\"--KFOLD\", type=int, default=0)\n train_parser.add_argument(\"--LOG\", type=str, default='./tensorboard/Video_EgoCrash_slowfast_16x6_r101_5050')\n train_parser.add_argument(\"--REUSE\", type=bool, default=False)\n train_parser.add_argument(\"--CHECKPOINT\", type=str, default='./ckpt/50f_weather_0.35Normal_evaLargeP14_336/2E-val0.4637774684718883-eva_large_patch14_336.pth')\n train_parser.add_argument(\"--START_EPOCH\", type=int, default=0)\n\n # test\n test_parser = subparsers.add_parser('test')\n test_parser.add_argument(\"--ENSEMBLE\", type=str, default=None)\n test_parser.add_argument(\"--CHECKPOINT\", nargs=\"+\", type=str,\n default=['./ckpt/58E-val0.957-efficientnet_b0.pth',\n './ckpt/55E-val0.9542-efficientnet_b0.pth',\n './ckpt/53E-val0.9537-efficientnet_b0.pth',\n './ckpt/49E-val0.953-efficientnet_b0.pth',\n './ckpt/45E-val0.9521-efficientnet_b0.pth'])\n\n\n args = parser.parse_args()\n os.makedirs(os.path.dirname(args.OUTPUT), exist_ok=True)\n\n print(vars(args))\n main(args)","repo_name":"quhb2455/toy","sub_path":"car_crash_analyze/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5868,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"81"} +{"seq_id":"70070398025","text":"tags_dict = {\r\n 0: 0, # unlabeled --> noise\r\n 1: 28, # building --> static.manmade\r\n 2: 28, # fence --> static.manmade\r\n 3: 29, # other --> static.other\r\n 4: 2, # pedestrian --> human.pedestrian.adult\r\n 5: 28, # pole --> static.manmade\r\n 6: 29, # road line --> static.other\r\n 7: 24, # road --> flat.driveable_surface\r\n 8: 26, # sidewalk --> flat.sidewalk\r\n 9: 30, # vegetation --> static.vegetation\r\n 10: 17, # vehicles --> vehicle.car\r\n 11: 28, # wall --> static.manmade\r\n 12: 28, # traffic sign --> static.manmade\r\n 13: 0, # sky --> noise\r\n 14: 25, # ground --> flat.other\r\n 15: 28, # bridge --> static.manmade\r\n 16: 28, # rail track --> static.manmade\r\n 17: 28, # guard rail --> static.manmade\r\n 18: 28, # traffic light --> static.manmade\r\n 19: 28, # static --> static.manmade\r\n 20: 11, # dynamic --> movable_object.pushable_pullable\r\n 21: 0, # water --> noise\r\n 22: 27, # terrain --> flat.terrain\r\n 23: 23, # truck --> vehicle.truck\r\n 24: 16, # bus --> vehicle.bus.rigid\r\n 25: 21, # motorcycle --> vehicle.motorcycle\r\n 26: 14, # bicycle --> vehicle.bicycle\r\n 27: 0, # rider --> no label yet....\r\n 28: 0\r\n }\r\n\r\nattributes = {\r\n \"vehicle.moving\": \"Vehicle is moving\",\r\n \"vehicle.parked\": \"Vehicle is parked\",\r\n \"pedestrian.moving\": \"The pedestrian is moving (assuming all are moving at all times)\"\r\n}\r\n\r\ncategories = [\r\n \"noise\",\r\n \"animal\",\r\n \"human.pedestrian.adult\",\r\n \"human.pedestrian.child\",\r\n \"human.pedestrian.construction_worker\",\r\n \"human.pedestrian.personal_mobility\",\r\n \"human.pedestrian.police_officer\",\r\n \"human.pedestrian.stroller\",\r\n \"human.pedestrian.wheelchair\",\r\n \"movable_object.barrier\",\r\n \"movable_object.debris\",\r\n \"movable_object.pushable_pullable\",\r\n \"movable_object.trafficcone\",\r\n \"static_object.bicycle_rack\",\r\n \"vehicle.bicycle\",\r\n \"vehicle.bus.bendy\",\r\n \"vehicle.bus.rigid\",\r\n \"vehicle.car\",\r\n \"vehicle.construction\",\r\n \"vehicle.emergency.ambulance\",\r\n \"vehicle.emergency.police\",\r\n \"vehicle.motorcycle\",\r\n \"vehicle.trailer\",\r\n \"vehicle.truck\",\r\n \"flat.driveable_surface\",\r\n \"flat.other\",\r\n \"flat.sidewalk\",\r\n \"flat.terrain\",\r\n \"static.manmade\",\r\n \"static.other\",\r\n \"static.vegetation\",\r\n \"vehicle.ego\"\r\n]\r\n\r\nvisibilities = {\r\n \"v0\": \"visibility of whole object is 0%\",\r\n \"v0-40\": \"visibility of whole object is between 0 and 40%\",\r\n \"v40-60\": \"visibility of whole object is between 40 and 60%\",\r\n \"v60-80\": \"visibility of whole object is between 60 and 80%\",\r\n \"v80-100\": \"visibility of whole object is between 80 and 100%\",\r\n}\r\n","repo_name":"MarcusMalak/Horus","sub_path":"dataset_creation/config_dicts.py","file_name":"config_dicts.py","file_ext":"py","file_size_in_byte":3036,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"5249935391","text":"# 124 나라의 숫자\n\"\"\"\n[1, 2, 4] -> [1, 2, 3] 으로 바꾸고 3진법이라고 생각하면 될듯?\n\n자연수 n이 매개변수로 주어질 때, n을 124 나라에서 사용하는 숫자로 바꾼 값을 return\n\"\"\"\n\n\ndef solution(n):\n answer = ''\n\n cur_num = n\n while cur_num:\n leftover = cur_num % 3\n if leftover == 0:\n answer = \"4\" + answer\n cur_num = cur_num // 3 - 1\n else:\n answer = str(leftover) + answer\n cur_num = cur_num // 3\n\n return answer","repo_name":"ribo0715/algorithm_solution","sub_path":"프로그래머스/124 나라의 숫자.py","file_name":"124 나라의 숫자.py","file_ext":"py","file_size_in_byte":534,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"72054670024","text":"# -*- coding: utf-8 -*-\nimport pygame\nfrom pygame.locals import * #(QUIT, KEYDOWN, K_ESCAPE, K_r)\n\nimport Box2D # The main library\n# Box2D.b2 maps Box2D.b2Vec2 to vec2 (and so on)\nfrom Box2D.b2 import * # (world, edgeShape, polygonShape, circleShape, staticBody, dynamicBody)\n\nimport numpy as np\nimport pickle\nimport sys\nimport random \nimport matplotlib.pyplot as plt\n# --- constants ---\n# Box2D deals with meters, but we want to display pixels,\n# so define a conversion factor:\nPPM = 15.0 # pixels per meter\nTARGET_FPS = 60\nTIME_STEP = 1.0 / TARGET_FPS\nSCREEN_WIDTH, SCREEN_HEIGHT = 900, 480\n\n# --- pygame setup ---\npygame.init()\nscreen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT), 0, 32)\npygame.display.set_caption('Perceived Bounciness')\nclock = pygame.time.Clock()\n\n# --- pybox2d world setup ---\n# Create the world\nworld = world(gravity=(0, -20), doSleep=True)\n\n# Create a static body to hold the ground shape\nx1 = 0.0\nvertice1 = (x1, 4)\nvertice2 = (x1, 0)\n\nx2 = np.random.uniform(12, 20)\nvertice3 = (x2, 0)\nvertice4 = (x2, np.random.uniform(2.4, 3.6))\n# vertice4 = (np.random.uniform(5, 60), np.random.uniform(0.5, 3))\n\nx3 = np.random.uniform(25, 35)\nvertice5 = (x3, 0)\nvertice6 = (x3, np.random.uniform(1.4, 3.2))\nvertice7 = ((x2+x3)/2.0, np.random.uniform(2.7, 3.9))\n\nx4 = np.random.uniform(40, 50)\nvertice8 = (x4, 0)\nvertice9 = (x4, np.random.uniform(0.7, 2.1))\nvertice10 = ((x3+x4)/2.0, np.random.uniform(1.6, 2.9))\n\nx5 = 60.0\nvertice11 = (x5, 0)\nvertice12 = ((x4+x5)/2.0, np.random.uniform(0.3, 1.6))\n\nground_body1 = world.CreateStaticBody(position=(0, 0), shapes=polygonShape(vertices=[vertice1, vertice2, vertice3, vertice4]))\nground_body2 = world.CreateStaticBody(position=(0, 0), shapes=polygonShape(vertices=[vertice4, vertice3, vertice5, vertice6, vertice7]))\nground_body3 = world.CreateStaticBody(position=(0, 0), shapes=polygonShape(vertices=[vertice6, vertice5, vertice8, vertice9, vertice10]))\nground_body4 = world.CreateStaticBody(position=(0, 0), shapes=polygonShape(vertices=[vertice9, vertice8, vertice11, vertice12]))\n\n\n# Create a couple dynamic bodies\norg_position_circle = (5, 10)\n# body = world.CreateDynamicBody(position=org_position_circle)\norg_restitution_circle = 1.0\norg_radius_circle = 0.7\norg_density_circle = 1\n# circle = body.CreateCircleFixture(radius=org_radius_circle, density=org_density_circle, restitution=org_restitution_circle)\n\n# body = world.CreateDynamicBody(position=(10, 10), angle=0)\n# box = body.CreatePolygonFixture(box=(1, 1), density=20, restitution=1.0)\n\ncolors = {\n staticBody: (50, 145, 100, 255),\n dynamicBody: (100, 100, 100, 255),\n}\n\n# Let's play with extending the shape classes to draw for us.\ndef my_draw_polygon(polygon, body, fixture):\n vertices = [(body.transform * v) * PPM for v in polygon.vertices]\n vertices = [(v[0], SCREEN_HEIGHT - v[1]) for v in vertices]\n pygame.draw.polygon(screen, colors[body.type], vertices)\npolygonShape.draw = my_draw_polygon\n\ndef my_draw_circle(circle, body, fixture):\n position = body.transform * circle.pos * PPM\n position = (position[0], SCREEN_HEIGHT - position[1])\n pygame.draw.circle(screen, colors[body.type], [int(\n x) for x in position], int(circle.radius * PPM))\n # Note: Python 3.x will enforce that pygame get the integers it requests,\n # and it will not convert from float.\ncircleShape.draw = my_draw_circle\n\n# --- main game loop ---\n# iter_cnt = 0\nnum_trials = 1\nrunning = True\ntime_left = 0\n# stop_criteria = 0.0000001\neps = 0.6\n# R = 1.0\nR0 = 0.8\nseq_A_played = False\nseq_B_played = False\nreturn_enable = False\nuser_input = -1\n\ncurrent_seq = 'C'\n\neps_cnt = 1\neps_step_size = 0.6\neps_rep = 6\neps_stop_crt = 0.01\n\nall_eps_lst = [eps]\nuser_input_lst = []\nphysical_lst = []\nstep_size_lst = []\n\ntext_box_color = (0,0,0,0)\n\ninit_v_x = np.random.uniform(0,5)\ninit_v_y = -np.random.uniform(0,10)\n\n# Mode = 0 --> display physical motion\n# Mode = 1 --> display modified motion\nmode = [0,1]\nrandom.shuffle(mode)\nmode_idx = 0\nif mode[0] == 0:\n physical_lst.append(0)\nelse:\n physical_lst.append(1)\n\n# initialize font; must be called after 'pygame.init()' to avoid 'Font not Initialized' error\nmyfont = pygame.font.SysFont(\"arial\", 23)\n\ndef display_eps():\n global myfont\n global screen\n global eps\n global eps_step_size\n\n # -- Text Output --\n # label_change = myfont.render(\"Press r to change eps.\", 1, (255,255,255))\n # screen.blit(label_change, (200, 5))\n label_eps = myfont.render(\"Eps: \"+str(eps)+ \" Step Size: \"+ str(eps_step_size) , 1, (255,255,255))\n screen.blit(label_eps, (25, 50))\n\n\ndef display_mode():\n global myfont\n global screen\n global mode\n global mode_idx\n # -- Text Output --\n label_mode = myfont.render(\"Mode: \"+str(mode[mode_idx]), 1, (0,255,255))\n screen.blit(label_mode, (20, 30))\n\ndef display_seq():\n global myfont\n global screen\n global current_seq\n # -- Text Output --\n label_mode = myfont.render(\"Playing Animation \"+current_seq, 1, (120,230,120))\n screen.blit(label_mode, (SCREEN_WIDTH/2 - 80, 60))\n\ndef display_welcome():\n global myfont\n global screen\n\n title_font = pygame.font.SysFont(\"arial\", 50)\n welcome = myfont.render(\"Welcome to the Bouncie Study\", 1, (255,255,255))\n screen.blit(welcome, (SCREEN_WIDTH/2 - 120, 18))\n\n label_ins1 = myfont.render(\"In each trial, you'll be shown 2 animation of a bouncy ball\", 1, (255,255,255))\n screen.blit(label_ins1, (SCREEN_WIDTH/2 - 210, 58))\n\n label_ins2 = myfont.render(\"You'll be asked to choose the more physical animation after them playing\", 1, (255,255,255))\n screen.blit(label_ins2, (SCREEN_WIDTH/2 - 260, 78))\n\n label_ins3 = myfont.render(\"Play/replay animation: Press key A for animation A | key B for animation B\", 1, (255,255,255))\n screen.blit(label_ins3, (SCREEN_WIDTH/2 - 260, 98))\n\n label_ins4 = title_font.render(\"Have Fun!\", 0, (255,255,255))\n screen.blit(label_ins4, (SCREEN_WIDTH/2 - 90, 128))\n\ndef display_instruction():\n global myfont\n global screen\n # -- Text Output --\n label_ins2 = myfont.render(\"Play/replay animation: Press key A for animation A | key B for animation B\", 1, (200,200,200))\n screen.blit(label_ins2, (SCREEN_WIDTH/2 - 260, 38))\n\ndef display_choice():\n global myfont\n global screen\n global user_input\n # -- Text Output --\n label_ins2 = myfont.render(\"Please choose between 1 and 2. \", 1, (255,255,255))\n screen.blit(label_ins2, (SCREEN_WIDTH/2 - 200, 66))\n label_ins3 = myfont.render(\"1 - Animation A looks more physical.\", 1, (255,255,255))\n screen.blit(label_ins3, (SCREEN_WIDTH/2 - 175, 90))\n label_ins4 = myfont.render(\"2 - Animation B looks more physical.\", 1, (255,255,255))\n screen.blit(label_ins4, (SCREEN_WIDTH/2 - 175, 110))\n if user_input < 0:\n label_user = myfont.render(\"Your answer: \", 1, (255,255,255))\n else:\n label_user = myfont.render(\"Your answer: \"+str(user_input+1) + \" Hit enter when you're ready\", 1, (255,255,255))\n screen.blit(label_user, (SCREEN_WIDTH/2 - 175, 140))\n\n\ndef throw_ball_A():\n global time_left\n global org_position_circle\n global org_radius_circle\n global org_density_circle\n global org_restitution_circle\n global seq_A_played\n global current_seq\n global mode_idx\n global init_v_x\n global init_v_y\n\n if time_left == 0: # and (not seq_A_played):\n # world.DestroyBody(world.bodies[3])\n # world.DestroyBody(world.bodies[2])\n # world.DestroyBody(world.bodies[1])\n # world.DestroyBody(world.bodies[0])\n # # Create a static body to hold the ground shape\n # x1 = 0.0\n # vertice1 = (x1, 4)\n # vertice2 = (x1, 0)\n \n # x2 = np.random.uniform(12, 20)\n # vertice3 = (x2, 0)\n # vertice4 = (x2, np.random.uniform(2.4, 3.6))\n # # vertice4 = (np.random.uniform(5, 60), np.random.uniform(0.5, 3))\n \n # x3 = np.random.uniform(25, 35)\n # vertice5 = (x3, 0)\n # vertice6 = (x3, np.random.uniform(1.4, 3.2))\n # vertice7 = ((x2+x3)/2.0, np.random.uniform(2.7, 3.9))\n \n # x4 = np.random.uniform(40, 50)\n # vertice8 = (x4, 0)\n # vertice9 = (x4, np.random.uniform(0.7, 2.1))\n # vertice10 = ((x3+x4)/2.0, np.random.uniform(1.6, 2.9))\n \n # x5 = 60.0\n # vertice11 = (x5, 0)\n # vertice12 = ((x4+x5)/2.0, np.random.uniform(0.3, 1.6))\n \n # ground_body1 = world.CreateStaticBody(position=(0, 0), shapes=polygonShape(vertices=[vertice1, vertice2, vertice3, vertice4]))\n # ground_body2 = world.CreateStaticBody(position=(0, 0), shapes=polygonShape(vertices=[vertice4, vertice3, vertice5, vertice6, vertice7]))\n # ground_body3 = world.CreateStaticBody(position=(0, 0), shapes=polygonShape(vertices=[vertice6, vertice5, vertice8, vertice9, vertice10]))\n # ground_body4 = world.CreateStaticBody(position=(0, 0), shapes=polygonShape(vertices=[vertice9, vertice8, vertice11, vertice12]))\n\n mode_idx = 0\n time_left = 600\n body = world.CreateDynamicBody(position=org_position_circle)\n body.linearVelocity = (init_v_x, init_v_y)\n circle = body.CreateCircleFixture(radius=org_radius_circle, density=org_density_circle, restitution=org_restitution_circle)\n seq_A_played = True\n current_seq = 'A'\n\n\ndef throw_ball_B():\n global time_left\n global org_position_circle\n global org_radius_circle\n global org_density_circle\n global org_restitution_circle\n global seq_B_played\n global current_seq\n global mode_idx\n global init_v_x\n global init_v_y\n\n if time_left == 0: # and (not seq_B_played):\n # world.DestroyBody(world.bodies[3])\n # world.DestroyBody(world.bodies[2])\n # world.DestroyBody(world.bodies[1])\n # world.DestroyBody(world.bodies[0])\n # # Create a static body to hold the ground shape\n # x1 = 0.0\n # vertice1 = (x1, 4)\n # vertice2 = (x1, 0)\n \n # x2 = np.random.uniform(12, 20)\n # vertice3 = (x2, 0)\n # vertice4 = (x2, np.random.uniform(2.4, 3.6))\n # # vertice4 = (np.random.uniform(5, 60), np.random.uniform(0.5, 3))\n \n # x3 = np.random.uniform(25, 35)\n # vertice5 = (x3, 0)\n # vertice6 = (x3, np.random.uniform(1.4, 3.2))\n # vertice7 = ((x2+x3)/2.0, np.random.uniform(2.7, 3.9))\n \n # x4 = np.random.uniform(40, 50)\n # vertice8 = (x4, 0)\n # vertice9 = (x4, np.random.uniform(0.7, 2.1))\n # vertice10 = ((x3+x4)/2.0, np.random.uniform(1.6, 2.9))\n \n # x5 = 60.0\n # vertice11 = (x5, 0)\n # vertice12 = ((x4+x5)/2.0, np.random.uniform(0.3, 1.6))\n \n # ground_body1 = world.CreateStaticBody(position=(0, 0), shapes=polygonShape(vertices=[vertice1, vertice2, vertice3, vertice4]))\n # ground_body2 = world.CreateStaticBody(position=(0, 0), shapes=polygonShape(vertices=[vertice4, vertice3, vertice5, vertice6, vertice7]))\n # ground_body3 = world.CreateStaticBody(position=(0, 0), shapes=polygonShape(vertices=[vertice6, vertice5, vertice8, vertice9, vertice10]))\n # ground_body4 = world.CreateStaticBody(position=(0, 0), shapes=polygonShape(vertices=[vertice9, vertice8, vertice11, vertice12]))\n\n mode_idx = 1\n time_left = 600\n body = world.CreateDynamicBody(position=org_position_circle)\n body.linearVelocity = (init_v_x, init_v_y)\n circle = body.CreateCircleFixture(radius=org_radius_circle, density=org_density_circle, restitution=org_restitution_circle)\n seq_B_played = True \n current_seq = 'B' \n\n\ndef countdown():\n global time_left\n if time_left == 0 and len(world.bodies) > 4:\n world.DestroyBody(world.bodies[4])\n if time_left > 0:\n time_left -= 1\n\ndef calculate_next_eps():\n global user_input_lst\n global physical_lst\n global eps_rep\n global eps_step_size\n global eps\n\n err_cnt = 0\n\n assert len(user_input_lst) == len(physical_lst)\n for i in range(1, eps_rep+1):\n if physical_lst[-i] != user_input_lst[-i]:\n err_cnt += 1\n\n err_rate = 1.0*err_cnt/eps_rep\n eps_step_size /= 2\n\n if err_rate > 0.4:\n eps += eps_step_size\n else:\n eps -= eps_step_size\n\n all_eps_lst.append(eps)\n\nwhile running:\n screen.fill((0, 0, 0, 0))\n\n img = pygame.image.load('blue_sky.png')\n img = pygame.transform.scale(img, (SCREEN_WIDTH,SCREEN_HEIGHT))\n\n screen.blit(img, (0,0))\n\n text_box = pygame.Surface((SCREEN_WIDTH - 20,160))\n text_box.set_alpha(180)\n text_box.fill((0,0,0))\n screen.blit(text_box,(10,10))\n\n countdown()\n # display_eps()\n if not seq_A_played and not seq_B_played:\n if num_trials == 1:\n display_welcome()\n else:\n display_instruction()\n\n if seq_A_played and seq_B_played and time_left == 0:\n display_instruction()\n display_choice()\n elif seq_A_played or seq_B_played:\n if time_left > 0:\n # display_mode()\n display_seq()\n else:\n display_instruction()\n\n # Check the event queue\n for event in pygame.event.get():\n if event.type == QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE):\n # The user closed the window or pressed escape\n running = False\n if event.type == KEYDOWN and event.key == K_a:\n print('a')\n throw_ball_A()\n if event.type == KEYDOWN and event.key == K_b:\n print('b')\n throw_ball_B()\n if seq_A_played and seq_B_played and time_left == 0 and event.type == KEYDOWN and event.key == K_1:\n user_input = 0\n return_enable = True\n if seq_A_played and seq_B_played and time_left == 0 and event.type == KEYDOWN and event.key == K_2:\n user_input = 1\n return_enable = True\n if seq_A_played and seq_B_played and time_left == 0 and return_enable and event.type == KEYDOWN and event.key == K_RETURN:\n user_input_lst.append(user_input)\n\n if eps_cnt >= eps_rep:\n calculate_next_eps()\n if eps_step_size < eps_stop_crt:\n running = False\n eps_cnt = 1\n else:\n eps_cnt += 1\n\n print(eps_cnt)\n\n num_trials = num_trials + 1\n\n assert len(world.bodies) == 4\n\n world.DestroyBody(world.bodies[3])\n world.DestroyBody(world.bodies[2])\n world.DestroyBody(world.bodies[1])\n world.DestroyBody(world.bodies[0])\n # Create a static body to hold the ground shape\n x1 = 0.0\n vertice1 = (x1, 4)\n vertice2 = (x1, 0)\n \n x2 = np.random.uniform(12, 20)\n vertice3 = (x2, 0)\n vertice4 = (x2, np.random.uniform(2.4, 3.6))\n # vertice4 = (np.random.uniform(5, 60), np.random.uniform(0.5, 3))\n \n x3 = np.random.uniform(25, 35)\n vertice5 = (x3, 0)\n vertice6 = (x3, np.random.uniform(1.4, 3.2))\n vertice7 = ((x2+x3)/2.0, np.random.uniform(2.7, 3.9))\n \n x4 = np.random.uniform(40, 50)\n vertice8 = (x4, 0)\n vertice9 = (x4, np.random.uniform(0.7, 2.1))\n vertice10 = ((x3+x4)/2.0, np.random.uniform(1.6, 2.9))\n \n x5 = 60.0\n vertice11 = (x5, 0)\n vertice12 = ((x4+x5)/2.0, np.random.uniform(0.3, 1.6))\n \n ground_body1 = world.CreateStaticBody(position=(0, 0), shapes=polygonShape(vertices=[vertice1, vertice2, vertice3, vertice4]))\n ground_body2 = world.CreateStaticBody(position=(0, 0), shapes=polygonShape(vertices=[vertice4, vertice3, vertice5, vertice6, vertice7]))\n ground_body3 = world.CreateStaticBody(position=(0, 0), shapes=polygonShape(vertices=[vertice6, vertice5, vertice8, vertice9, vertice10]))\n ground_body4 = world.CreateStaticBody(position=(0, 0), shapes=polygonShape(vertices=[vertice9, vertice8, vertice11, vertice12]))\n\n seq_A_played = False\n seq_B_played = False\n return_enable = False\n user_input = -1\n\n init_v_x = np.random.uniform(0,5)\n init_v_y = -np.random.uniform(0,10)\n\n mode = [0,1]\n random.shuffle(mode)\n mode_idx = 0\n if mode[0] == 0:\n physical_lst.append(0)\n else:\n physical_lst.append(1)\n\n\n if time_left > 0:\n if mode[mode_idx] == 0:\n world.bodies[4].fixtures[0].restitution = R0\n else:\n world.bodies[4].fixtures[0].restitution = np.random.uniform(1-eps, 1+eps)*R0\n\n\n # iter_cnt = iter_cnt + 1\n # Draw the world\n for body in world.bodies:\n for fixture in body.fixtures:\n fixture.shape.draw(body, fixture)\n\n # render trail number\n label = myfont.render(\"Trial: \"+str(num_trials), 1, (255,255,255))\n screen.blit(label, (20, 18))\n\n # if time_left > 0 and (seq_A_played or seq_B_played):\n # print(world.bodies[1].fixtures[0].restitution)\n\n # Make Box2D simulate the physics of our world for one step.\n world.Step(TIME_STEP, 10, 10)\n\n # Flip the screen and try to keep at the target FPS\n pygame.display.flip()\n clock.tick(TARGET_FPS)\n # print(iter_cnt)\n # print(plausible)\n # print(delta_R)\n # print(time_left)\n print(eps_step_size)\npygame.quit()\n\n# Visualization code\ndef save_all_eps_lst():\n global all_eps_lst\n\n saving_dict = {'all_eps_lst': all_eps_lst}\n\n if len(sys.argv) > 1:\n saving_dir = sys.argv[1]\n else:\n saving_dir = 'result.pkl'\n\n with open(saving_dir, 'wb') as handle:\n pickle.dump(saving_dict, handle)\n\ndef visualize_all_eps_lst():\n global all_eps_lst\n\n num_eps_lst = [x for x in range(1,len(all_eps_lst)+1)]\n threshold_list = [all_eps_lst[-1]]*len(all_eps_lst)\n\n plt.plot(num_eps_lst, all_eps_lst, 'b-', num_eps_lst, threshold_list, 'y-')\n plt.axis([0, len(all_eps_lst)+1, 0, 0.6])\n plt.xlabel('Experiment Number')\n plt.ylabel('Eps')\n plt.show()\n\nsave_all_eps_lst()\nvisualize_all_eps_lst()\n\nprint(physical_lst)\nprint(user_input_lst)\nprint('Experiment Finished!')\nprint(all_eps_lst)","repo_name":"bicheng-xu/Perceived-Bounciness","sub_path":"interface.py","file_name":"interface.py","file_ext":"py","file_size_in_byte":18356,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"27567283579","text":"from collections import deque, defaultdict\nimport heapq\nID, n, k = map(int, input().split())\ngrid = []\n\nfor i in range(n):\n grid.append(list(input()))\n\ndef check(x,y):\n return ((0 <= x < n) and (0 <= y < n))\ndef find(x):\n if par[x] < 0:\n return x\n else:\n par[x] = find(par[x])\n return par[x]\n#xとyの属する集合の併合\ndef unite(x,y):\n x = find(x)\n y = find(y)\n \n if x == y:\n return False\n else:\n #sizeの大きいほうがx\n if par[x] > par[y]:\n x,y = y,x\n par[x] += par[y]\n par[y] = x\n return True\n\n#xとyが同じ集合に属するかの判定\ndef same(x,y):\n return find(x) == find(y)\n\n#xが属する集合の個数\ndef size(x):\n return -par[find(x)]\npar = [-1 for i in range(n*n)]\ndef p2n(x,y):\n return y*n + x\n\ndef print_grid():\n for i in range(n):\n for j in range(n):\n print(grid[i][j], end=\" \")\n print()\n# union find\nfor i in range(n):\n for j in range(n):\n for n_y, n_x in [(i + 1,j), (i, j + 1)]:\n if check(n_x, n_y) and grid[i][j] == grid[n_y][n_x]:\n unite(p2n(j,i), p2n(n_x,n_y))\nvalue_of_point = []\nheapq.heapify(value_of_point)\ndef bfs_valid(s_x, s_y):\n que = deque()\n que.append((s_x, s_y))\n count = defaultdict(int)\n cnt_fin = set()\n finished = set()\n while que:\n now_x, now_y = que.popleft()\n finished.add(p2n(now_x,now_y))\n for n_x, n_y in [(now_x + 1, now_y), (now_x,now_y + 1), (now_x-1, now_y),(now_x, now_y-1)]:\n if check(n_x, n_y) and (p2n(n_x, n_y) not in finished):\n if same(p2n(n_x,n_y), p2n(now_x,now_y)):\n que.append((n_x,n_y))\n else:\n if p2n(n_x,n_y) not in cnt_fin:\n count[grid[n_y][n_x]] += 1\n cnt_fin.add(p2n(n_x,n_y))\n if len(count) == 0:\n return \n max_key = max(count, key=count.get)\n max_value = count[max_key]\n heapq.heappush(value_of_point, [-max_value,max_key,s_x,s_y])\ndef change_bfs(s_x, s_y, color):\n que = deque()\n que.append((s_x, s_y))\n finished = set()\n union_list = []\n while que:\n now_x, now_y = que.popleft()\n grid[now_y][now_x] = color\n finished.add(p2n(now_x,now_y))\n for n_x, n_y in [(now_x + 1, now_y), (now_x,now_y + 1), (now_x-1, now_y),(now_x, now_y-1)]:\n if check(n_x, n_y) and (p2n(n_x, n_y) not in finished):\n if same(p2n(n_x,n_y), p2n(now_x,now_y)):\n que.append((n_x,n_y))\n if grid[n_y][n_x] == color:\n union_list.append(p2n(n_x,n_y))\n ignore_point.add(p2n(n_x,n_y))\n ori = p2n(s_x, s_y)\n for i in union_list:\n unite(ori,i)\n bfs_valid(s_x,s_y)\nans = []\nfor i in range(n):\n for j in range(n):\n bfs_valid(i, j)\n\nignore_point = set()\n\nwhile value_of_point:\n print(len(value_of_point))\n point, new_num, x, y = heapq.heappop(value_of_point)\n if find(p2n(x,y)) not in ignore_point: \n ans.append(\"{} {} {}\".format(y+1,x+1,new_num))\n change_bfs(x,y,new_num)\nfor i in range(n):\n for j in range(n):\n bfs_valid(i, j)\nwhile value_of_point:\n point, new_num, x, y = heapq.heappop(value_of_point)\n if find(p2n(x,y)) not in ignore_point: \n ans.append(\"{} {} {}\".format(y+1,x+1,new_num))\n change_bfs(x,y,new_num)\n\nprint_grid()\nprint(len(ans))\nfor i in ans:\n print(i)\n","repo_name":"Yuta123456/AtCoder","sub_path":"python/Chokudai Contest 005/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3495,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"4263539202","text":"from datetime import datetime\nfrom operator import attrgetter, itemgetter\nfrom uuid import uuid4\n\nimport pytest\nfrom django.utils.timezone import utc\nfrom freezegun import freeze_time\nfrom rest_framework import status\nfrom rest_framework.reverse import reverse\n\nfrom datahub.company.models import CompanyExportCountryHistory\nfrom datahub.company.test.factories import CompanyExportCountryHistoryFactory, CompanyFactory\nfrom datahub.core.test_utils import APITestMixin, create_test_user\nfrom datahub.interaction.models import InteractionPermission\nfrom datahub.interaction.test.factories import (\n CompanyInteractionFactory,\n ExportCountriesInteractionFactory,\n ExportCountriesServiceDeliveryFactory,\n)\nfrom datahub.metadata.models import Country\nfrom datahub.search.export_country_history import ExportCountryHistoryApp\nfrom datahub.search.interaction import InteractionSearchApp\n\npytestmark = [\n pytest.mark.django_db,\n pytest.mark.opensearch_collector_apps.with_args(ExportCountryHistoryApp, InteractionSearchApp),\n]\n\nHistoryType = CompanyExportCountryHistory.HistoryType\nexport_country_history_search_url = reverse('api-v4:search:export-country-history')\n\n\nclass TestSearchExportCountryHistory(APITestMixin):\n \"\"\"Tests search views.\"\"\"\n\n @pytest.mark.parametrize(\n 'permission_codenames,expected_status',\n (\n (\n [],\n status.HTTP_403_FORBIDDEN,\n ),\n (\n ['view_companyexportcountry'],\n status.HTTP_403_FORBIDDEN,\n ),\n (\n [InteractionPermission.view_all],\n status.HTTP_403_FORBIDDEN,\n ),\n (\n ['view_companyexportcountry', InteractionPermission.view_all],\n status.HTTP_200_OK,\n ),\n ),\n )\n @pytest.mark.usefixtures('opensearch')\n def test_permission_checking(self, permission_codenames, expected_status, api_client):\n \"\"\"Test that the expected status is returned for various user permissions.\"\"\"\n user = create_test_user(permission_codenames=permission_codenames, dit_team=None)\n api_client = self.create_api_client(user=user)\n response = api_client.post(\n export_country_history_search_url,\n data={\n 'company': uuid4(),\n },\n )\n assert response.status_code == expected_status\n\n def test_export_country_history_search_with_empty_request(self, opensearch_with_collector):\n \"\"\"Should return 400.\"\"\"\n opensearch_with_collector.flush_and_refresh()\n error_response = 'Request must include either country or company parameters'\n\n response = self.api_client.post(export_country_history_search_url, data={})\n\n assert response.status_code == status.HTTP_400_BAD_REQUEST\n assert response.json()['non_field_errors'][0] == error_response\n\n def test_export_country_history_response_body(self, opensearch_with_collector):\n \"\"\"Test the format of an export country history result in the response body.\"\"\"\n history_object = CompanyExportCountryHistoryFactory(history_type=HistoryType.INSERT)\n opensearch_with_collector.flush_and_refresh()\n\n response = self.api_client.post(\n export_country_history_search_url,\n data={\n # The view requires a filter\n 'company': history_object.company.pk,\n },\n )\n assert response.status_code == status.HTTP_200_OK\n\n results = response.json()['results']\n assert len(results) == 1\n assert results[0] == {\n 'company': {\n 'id': str(history_object.company.pk),\n 'name': history_object.company.name,\n },\n 'country': {\n 'id': str(history_object.country.pk),\n 'name': history_object.country.name,\n },\n 'date': history_object.history_date.isoformat(),\n 'history_date': history_object.history_date.isoformat(),\n 'history_type': history_object.history_type,\n 'history_user': {\n 'id': str(history_object.history_user.pk),\n 'name': history_object.history_user.name,\n },\n 'id': str(history_object.pk),\n 'status': history_object.status,\n }\n\n def test_interaction_response_body(self, opensearch_with_collector):\n \"\"\"Test the format of an interaction result in the response body.\"\"\"\n interaction = ExportCountriesInteractionFactory()\n opensearch_with_collector.flush_and_refresh()\n\n response = self.api_client.post(\n export_country_history_search_url,\n data={\n # The view requires a filter\n 'company': interaction.company.pk,\n },\n )\n assert response.status_code == status.HTTP_200_OK\n\n results = response.json()['results']\n assert len(results) == 1\n\n result = results[0]\n result['contacts'].sort(key=itemgetter('id'))\n result['dit_participants'].sort(key=lambda participant: participant['adviser']['id'])\n result['export_countries'].sort(key=lambda export_country: export_country['country']['id'])\n\n assert result == {\n 'company': {\n 'id': str(interaction.company.pk),\n 'name': interaction.company.name,\n 'trading_names': interaction.company.trading_names,\n },\n 'contacts': [\n {\n 'id': str(contact.pk),\n 'first_name': contact.first_name,\n 'name': contact.name,\n 'last_name': contact.last_name,\n }\n for contact in sorted(interaction.contacts.all(), key=attrgetter('id'))\n ],\n 'date': interaction.date.isoformat(),\n 'dit_participants': [\n {\n 'adviser': {\n 'id': str(dit_participant.adviser.pk),\n 'first_name': dit_participant.adviser.first_name,\n 'name': dit_participant.adviser.name,\n 'last_name': dit_participant.adviser.last_name,\n },\n 'team': {\n 'id': str(dit_participant.team.pk),\n 'name': dit_participant.team.name,\n },\n }\n for dit_participant in interaction.dit_participants.order_by('adviser__pk')\n ],\n 'export_countries': [\n {\n 'country': {\n 'id': str(export_country.country.pk),\n 'name': export_country.country.name,\n },\n 'status': export_country.status,\n }\n for export_country in interaction.export_countries.order_by('country__pk')\n ],\n 'kind': interaction.kind,\n 'id': str(interaction.pk),\n 'service': {\n 'id': str(interaction.service.pk),\n 'name': interaction.service.name,\n },\n 'subject': interaction.subject,\n }\n\n @pytest.mark.parametrize(\n 'factory',\n (\n lambda: CompanyExportCountryHistoryFactory(history_type=HistoryType.INSERT),\n lambda: CompanyExportCountryHistoryFactory(history_type=HistoryType.DELETE),\n ExportCountriesInteractionFactory,\n ExportCountriesServiceDeliveryFactory,\n ),\n )\n def test_filtering_by_company_returns_matches(self, opensearch_with_collector, factory):\n \"\"\"Test that filtering by company includes matching objects.\"\"\"\n obj = factory()\n opensearch_with_collector.flush_and_refresh()\n\n response = self.api_client.post(\n export_country_history_search_url,\n data={\n 'company': obj.company.pk,\n },\n )\n assert response.status_code == status.HTTP_200_OK\n\n response_data = response.json()\n assert response_data['count'] == 1\n assert response_data['results'][0]['id'] == str(obj.pk)\n\n def test_filtering_by_company_excludes_non_matches(self, opensearch_with_collector):\n \"\"\"Test that filtering by company excludes non-matching objects.\"\"\"\n company = CompanyFactory()\n\n # Non-export country interactions should be excluded\n CompanyInteractionFactory(company=company)\n\n # Unrelated companies should be excluded\n CompanyExportCountryHistoryFactory(history_type=HistoryType.INSERT)\n ExportCountriesInteractionFactory()\n\n opensearch_with_collector.flush_and_refresh()\n\n response = self.api_client.post(\n export_country_history_search_url,\n data={\n 'company': company.pk,\n },\n )\n assert response.status_code == status.HTTP_200_OK\n\n response_data = response.json()\n assert response_data['count'] == 0\n assert response_data['results'] == []\n\n @pytest.mark.parametrize(\n 'factory',\n (\n lambda: CompanyExportCountryHistoryFactory(history_type=HistoryType.INSERT),\n lambda: CompanyExportCountryHistoryFactory(history_type=HistoryType.DELETE),\n ),\n )\n def test_filtering_by_country_returns_matching_history_objects(\n self,\n opensearch_with_collector,\n factory,\n ):\n \"\"\"Test that filtering by country includes matching export country history objects.\"\"\"\n obj = factory()\n opensearch_with_collector.flush_and_refresh()\n\n response = self.api_client.post(\n export_country_history_search_url,\n data={\n 'country': obj.country.pk,\n },\n )\n assert response.status_code == status.HTTP_200_OK\n\n response_data = response.json()\n assert response_data['count'] == 1\n assert response_data['results'][0]['id'] == str(obj.pk)\n\n @pytest.mark.parametrize(\n 'factory',\n (\n ExportCountriesInteractionFactory,\n ExportCountriesServiceDeliveryFactory,\n ),\n )\n def test_filtering_by_country_returns_matching_interactions(\n self, opensearch_with_collector, factory,\n ):\n \"\"\"Test that filtering by country includes matching interactions.\"\"\"\n obj = factory()\n opensearch_with_collector.flush_and_refresh()\n\n response = self.api_client.post(\n export_country_history_search_url,\n data={\n 'country': obj.export_countries.first().country.pk,\n },\n )\n assert response.status_code == status.HTTP_200_OK\n\n response_data = response.json()\n assert response_data['count'] == 1\n assert response_data['results'][0]['id'] == str(obj.pk)\n\n def test_filtering_by_country_excludes_non_matches(self, opensearch_with_collector):\n \"\"\"Test that filtering by country excludes non-matching objects.\"\"\"\n countries = list(Country.objects.order_by('?')[:2])\n filter_country = countries[0]\n other_country = countries[1]\n\n # Non-export country interactions should be excluded\n CompanyInteractionFactory()\n\n # Unrelated countries should be excluded\n CompanyExportCountryHistoryFactory(country=other_country, history_type=HistoryType.INSERT)\n ExportCountriesInteractionFactory(export_countries__country=other_country)\n\n opensearch_with_collector.flush_and_refresh()\n\n response = self.api_client.post(\n export_country_history_search_url,\n data={\n 'country': filter_country.pk,\n },\n )\n assert response.status_code == status.HTTP_200_OK\n\n response_data = response.json()\n assert response_data['count'] == 0\n assert response_data['results'] == []\n\n @pytest.mark.parametrize(\n 'request_args,is_reversed',\n (\n # default sorting\n ({}, True),\n ({'sortby': 'date:asc'}, False),\n ({'sortby': 'date:desc'}, True),\n ),\n )\n def test_sorts_results(self, opensearch_with_collector, request_args, is_reversed):\n \"\"\"\n Test sorting in various cases.\n\n Note that a filter is mandatory in this view, hence the test filters by company.\n \"\"\"\n datetimes = [\n datetime(2001, 1, 22, tzinfo=utc),\n datetime(2002, 2, 23, 1, 2, 3, tzinfo=utc),\n datetime(2003, 3, 24, tzinfo=utc),\n datetime(2004, 4, 25, 1, 2, 3, tzinfo=utc),\n ]\n company = CompanyFactory()\n\n objects = [\n ExportCountriesInteractionFactory(date=datetimes.pop(0), company=company),\n _make_dated_export_country_history(datetimes.pop(0), company=company),\n ExportCountriesInteractionFactory(date=datetimes.pop(0), company=company),\n _make_dated_export_country_history(datetimes.pop(0), company=company),\n ]\n\n if is_reversed:\n objects.reverse()\n\n opensearch_with_collector.flush_and_refresh()\n\n response = self.api_client.post(\n export_country_history_search_url,\n data={\n 'company': company.pk,\n **request_args,\n },\n )\n assert response.status_code == status.HTTP_200_OK\n\n expected_result_ids = [str(obj.pk) for obj in objects]\n actual_result_ids = [result['id'] for result in response.json()['results']]\n\n assert actual_result_ids == expected_result_ids\n\n\ndef _make_dated_export_country_history(history_date, **kwargs):\n with freeze_time(history_date):\n return CompanyExportCountryHistoryFactory(history_type=HistoryType.INSERT, **kwargs)\n","repo_name":"uktrade/data-hub-api","sub_path":"datahub/search/export_country_history/test/test_views.py","file_name":"test_views.py","file_ext":"py","file_size_in_byte":13917,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"81"} +{"seq_id":"7690709409","text":"from airflow import DAG\nfrom airflow.models import Variable\nfrom airflow.contrib.operators.bigquery_operator import BigQueryOperator\nfrom airflow.contrib.operators.bigquery_to_gcs import BigQueryToCloudStorageOperator\nfrom airflow.contrib.operators.bigquery_table_delete_operator import BigQueryTableDeleteOperator\nfrom airflow.contrib.operators.gcs_to_s3 import GoogleCloudStorageToS3Operator\nfrom airflow.utils.dates import days_ago\nfrom zwift.s3_to_redshift_transfer import S3ToRedshiftTransfer\nfrom datetime import timedelta\n\ngoogle_conn_id = Variable.get(\"ga360_conn_id\")\nbigquery_project_id = Variable.get(\"ga360_bigquery_project_id\")\ngcs_bucket = Variable.get(\"ga360_bucket\")\nredshift_s3_bucket = 's3://' + Variable.get(\"redshift_s3_bucket\") + '/'\nredshift_conn_id = Variable.get(\"redshift_conn_id\")\nredshift_iam_role = Variable.get(\"redshift_iam_role\")\naws_s3_conn_id = Variable.get(\"s3_conn_id\")\n\noutput_file = 'ga360-sessions-{{ ds_nodash }}.csv.gz'\ns3_output_file = redshift_s3_bucket + output_file\ngcs_output_file = 'gs://' + gcs_bucket + '/' + output_file\n\nsource_table = bigquery_project_id + '.ga_sessions_{{ ds_nodash }}'\ntarget_table = bigquery_project_id + '.ga_tmp_{{ ds_nodash }}'\n\ndefault_args = {\n 'owner': 'airflow',\n 'depends_on_past': False,\n 'start_date': days_ago(1),\n 'email': ['airflow@example.com'],\n 'email_on_failure': False,\n 'email_on_retry': False,\n 'retries': 1,\n 'retry_delay': timedelta(minutes=5),\n}\n\ndag = DAG('ga360_etl',\n schedule_interval=timedelta(days=1),\n default_args=default_args)\n\nbq_extract_query = \"\"\"with sessions as (select * from `{source_table}`), \n userId as (select visitId, dimension.value as userId, clientId\n from sessions cross join unnest(customDimensions) as dimension\n where dimension.index = 10), \n data as (select userId.userId, sessions.fullVisitorId, sessions.clientId, sessions.visitId, sessions.hits, sessions.visitStartTime, sessions.date \n from sessions left join userId \n on sessions.visitId = userId.visitId\n and sessions.clientId = userId.clientId)\n select userId as distinct_id, clientId, visitId, visitStartTime, date, fullVisitorId, hit.hitNumber, hit.page.pagePath, hit.appInfo.screenName , hit.page.hostname, hit.page.pageTitle, hit.type as hit_type\n from data cross join unnest(hits) as hit\"\"\"\n\nprepare_ga360 = BigQueryOperator(\n dag=dag,\n task_id='bq_unnest_table',\n bigquery_conn_id=google_conn_id,\n use_legacy_sql=False,\n sql=bq_extract_query.format(source_table=source_table),\n destination_dataset_table=target_table\n)\n\nextract_ga360_to_gcs = BigQueryToCloudStorageOperator(\n dag=dag,\n task_id='export_recent_yesterday_to_gcs',\n bigquery_conn_id=google_conn_id,\n source_project_dataset_table=target_table,\n destination_cloud_storage_uris=[gcs_output_file],\n compression='GZIP',\n export_format='CSV'\n)\n\nexport_gcs_to_s3 = GoogleCloudStorageToS3Operator(\n dag=dag,\n task_id=\"cp_gcs_to_s3\",\n dest_verify=True,\n google_cloud_storage_conn_id=google_conn_id,\n bucket=gcs_bucket,\n dest_aws_conn_id='local_s3',\n dest_s3_key=redshift_s3_bucket\n)\n\nload_redshift = S3ToRedshiftTransfer(\n dag=dag,\n task_id=\"redshift_load\",\n redshift_conn_id=redshift_conn_id,\n s3_file=s3_output_file,\n schema='public',\n table='ga360_sessions',\n iam_role=redshift_iam_role,\n copy_options=['CSV', 'IGNOREHEADER 1', 'GZIP', \"\"\"DATEFORMAT AS 'YYYYMMDD'\"\"\"]\n)\n\ndelete_tmp_table = BigQueryTableDeleteOperator(\n dag=dag,\n task_id=\"delete_tmp_table\",\n bigquery_conn_id=google_conn_id,\n deletion_dataset_table=target_table\n)\n\nprepare_ga360 >> extract_ga360_to_gcs\nextract_ga360_to_gcs >> [export_gcs_to_s3, delete_tmp_table]\nexport_gcs_to_s3 >> load_redshift\n","repo_name":"ldaugusto/airflow-sample-dags","sub_path":"import_ga360.py","file_name":"import_ga360.py","file_ext":"py","file_size_in_byte":4026,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"21933928530","text":"#! /usr/bin/env python3\n# -*- coding: utf-8 -*-\n#\n# refacdedx/style.py\n\ntry:\n from qtpy.QtCore import Qt\n from qtpy.QtGui import QPalette, QColor\nexcept ImportError:\n from PyQt5.QtCore import Qt\n from PyQt5.QtGui import QPalette, QColor\n\n\ndef css_rgb(color, a=None):\n \"\"\"Get a CSS `rgb` or `rgba` string from a QColor ot Qt.GlobalColor.\"\"\"\n if isinstance(color, Qt.GlobalColor):\n color = QColor(color)\n return (\"rgba({}, {}, {}, {})\" if a else\n \"rgb({}, {}, {})\").format(*color.getRgb())\n\n\nclass AppStyle:\n \"\"\"Palette for a Qt application meant to be used with the Fusion theme.\"\"\"\n\n STYLESHEET = \"\"\"\\\n QToolTip {{\n color: {secondary};\n background-color: {tertiary};\n border: 1px solid {secondary};\n }}\n \"\"\"\n PRIMARY = QColor(192, 192, 192)\n SECONDARY = QColor(16, 16, 16)\n TERTIARY = QColor(64, 64, 64)\n DISABLED = Qt.darkGray\n styles = ()\n\n def __init__(self, app):\n \"\"\"Set the Fusion theme and palette on a QApplication.\"\"\"\n app.setStyle(\"Fusion\")\n self.set_palette(app)\n self.set_stylesheet(app)\n\n def set_palette(self, app):\n \"\"\"Set the widget color palette on a QApplication.\"\"\"\n palette = QPalette()\n for style in self.styles:\n element = getattr(QPalette, style[0], None)\n if element:\n palette.setColor(element, style[1])\n if len(style) == 3:\n palette.setColor(QPalette.Disabled, element, style[2])\n app.setPalette(palette)\n\n def set_stylesheet(self, app):\n \"\"\"Set the tooltip stylesheet on a QApplication.\"\"\"\n app.setStyleSheet(self.STYLESHEET.format(secondary=css_rgb(self.SECONDARY),\n tertiary=css_rgb(self.TERTIARY)))\n\n\nclass DarkAppStyle(AppStyle):\n \"\"\"Dark palette.\"\"\"\n\n PRIMARY = QColor(53, 53, 53)\n SECONDARY = QColor(35, 35, 35)\n TERTIARY = QColor(42, 130, 218)\n\n styles = (\n (\"AlternateBase\", PRIMARY),\n (\"Base\", SECONDARY),\n (\"BrightText\", Qt.red),\n (\"Button\", PRIMARY),\n (\"ButtonText\", Qt.white, AppStyle.DISABLED),\n (\"HighlightedText\", Qt.black),\n (\"Highlight\", TERTIARY),\n (\"Link\", TERTIARY),\n (\"Text\", Qt.white, AppStyle.DISABLED),\n (\"ToolTipBase\", Qt.white),\n (\"ToolTipText\", Qt.white),\n (\"Window\", PRIMARY),\n (\"WindowText\", Qt.white, AppStyle.DISABLED),\n )\n","repo_name":"SpotlightKid/reface-dx-lib","sub_path":"refacedx/style.py","file_name":"style.py","file_ext":"py","file_size_in_byte":2478,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"81"} +{"seq_id":"19642559721","text":"import numpy as np\r\n\r\n# put input file as matrix format\r\n\r\ngrid = np.array([list(x.strip()) for x in open(\"day8.in\")], int)\r\n\r\n# get number of rows and columns\r\nnrow, ncol = np.shape(grid)\r\n\r\n# initializing the best view score\r\nbest_view_score = 1\r\n# initializing visible trees on the edge\r\nnumber_of_visible_trees = ncol * 2 + (nrow - 2) * 2\r\n# go through all the rows inside\r\nfor ii in range(1, nrow - 1):\r\n # go through all the columns onside\r\n for iii in range(1, ncol - 1):\r\n # tree of interest\r\n tree = grid[ii, iii]\r\n tree_up = grid[:ii, iii]\r\n tree_down = grid[ii + 1:, iii]\r\n tree_right = grid[ii, iii + 1:]\r\n tree_left = grid[ii, :iii]\r\n\r\n # compute the tallest tree in each direction\r\n tallest_tree_up = max(tree_up)\r\n tallest_tree_down = max(tree_down)\r\n tallest_tree_right = max(tree_right)\r\n tallest_tree_left = max(tree_left)\r\n\r\n # count the number of trees visible looking up\r\n count_visible_tree_up = 0\r\n for tt in range(len(tree_up)):\r\n count_visible_tree_up += 1\r\n if tree_up[len(tree_up) - 1 - tt] >= tree:\r\n break\r\n\r\n # count the number of trees visible looking down\r\n count_visible_tree_down = 0\r\n for tt in range(len(tree_down)):\r\n count_visible_tree_down += 1\r\n if tree_down[tt] >= tree:\r\n break\r\n\r\n # count the number of trees visible looking right\r\n count_visible_tree_right = 0\r\n for tt in range(len(tree_right)):\r\n count_visible_tree_right += 1\r\n if tree_right[tt] >= tree:\r\n break\r\n\r\n # count the number of trees visible looking left\r\n count_visible_tree_left = 0\r\n for tt in range(len(tree_left)):\r\n count_visible_tree_left += 1\r\n if tree_left[len(tree_left) - 1 - tt] >= tree:\r\n break\r\n\r\n # if the tree is taller than the maxes in any direction see the tree\r\n if tree > tallest_tree_up or tree > tallest_tree_down or tree > tallest_tree_right or tree > tallest_tree_left:\r\n number_of_visible_trees += 1\r\n\r\n # if the view score is highier we overwrite the best score\r\n view_score = count_visible_tree_up * count_visible_tree_down * count_visible_tree_left * count_visible_tree_right\r\n if view_score > best_view_score:\r\n best_view_score = view_score\r\n\r\nprint(\" Answer to the part 1 is: Number of visible trees: \" + str(number_of_visible_trees))\r\nprint(\" Answer to pert 2 is: The best view score is \" + str(best_view_score))\r\n","repo_name":"JoannaKonerska/Advent_of_code_2022","sub_path":"day8.py","file_name":"day8.py","file_ext":"py","file_size_in_byte":2626,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"37514731510","text":"from flask import Flask, Response, send_file, request\nimport json\nimport uuid\nimport os\nfrom io import BytesIO\n\nfrom ImageObject import ImageObject\n\napp = Flask(__name__)\nUPLOAD_FOLDER = './Temp'\nALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg'}\n\n\n# region Helper Methods\n\ndef get_response(code, data):\n\t\"\"\"\n\tGet a Flask Response object for the provided response code and JSON data.\n\t:param code: The response code to encode\n\t:param data: The response data to encode\n\t:return: The Flask Response object containing the response code and data\n\t\"\"\"\n\treturn Response(json.dumps(data), status=code, mimetype=\"application/json\")\n\n\ndef get_transformations_list(raw):\n\t\"\"\"\n\tTurn the transformations request into a usable list of instructions.\n\t:param raw: The raw transformation request data\n\t:return: The formatted list of transformation instructions\n\t\"\"\"\n\tinstructions = []\n\n\t# first split up into individual instructions\n\tsplit_raw = raw.split(',')\n\n\tfor instruction in [a.strip() for a in split_raw]:\n\t\t# then split the instruction into operation and value\n\t\tsplit_instruct = instruction.split(' ')\n\t\tif len(split_instruct) == 2:\n\t\t\t# convert value to a number if necessary\n\t\t\tif split_instruct[1].lstrip('-').isnumeric():\n\t\t\t\tsplit_instruct[1] = float(split_instruct[1])\n\t\telse:\n\t\t\tsplit_instruct.append(None)\n\n\t\tinstructions.append({split_instruct[0]: split_instruct[1]})\n\n\treturn instructions\n\n\ndef valid_file(filename):\n\treturn '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS\n\n\ndef upload_image(image_obj):\n\t\"\"\"\n\tSave a copy of the file that was sent to the server.\n\t:param image_obj: The request.files object\n\t:return: The location of the uploaded file\n\t\"\"\"\n\tfilename = str(uuid.uuid1()) + \".\" + image_obj.filename.rsplit('.', 1)[1].lower()\n\n\t# create the uploads folder if it does not exist\n\tif not os.path.exists(UPLOAD_FOLDER):\n\t\tos.makedirs(UPLOAD_FOLDER)\n\n\tupload_location = os.path.join(UPLOAD_FOLDER, filename)\n\timage_obj.save(upload_location)\n\treturn upload_location\n\n\ndef handle_transformation(image_obj, tf):\n\t\"\"\"\n\tInterpret a transformation command and complete the transformation.\n\t:param image_obj: The image to be transformed\n\t:param tf: The transformation to be completed\n\t\"\"\"\n\tif 'rotate' in tf and not tf['rotate'] is None:\n\t\timage_obj.rotate(tf['rotate'])\n\tif 'rotate_left' in tf:\n\t\timage_obj.rotate(-90)\n\tif 'rotate_right' in tf:\n\t\timage_obj.rotate(90)\n\tif 'grayscale' in tf:\n\t\timage_obj.grayscale()\n\tif 'flip' in tf:\n\t\timage_obj.flip(tf['flip'] is not None and tf['flip'] == 'horizontal')\n\tif 'resize' in tf and not tf['resize'] is None:\n\t\timage_obj.resize(tf['resize'])\n\tif 'thumbnail' in tf and not tf['thumbnail'] is None:\n\t\timage_obj.thumbnail(tf['thumbnail'])\n\n\n# endregion\n\n\n@app.route('/', methods=['POST'])\ndef image_manipulation():\n\t\"\"\"\n\tThe main endpoint for the image manipulation API.\n\t:return: The resulting image object, or error\n\t\"\"\"\n\t# make sure that an image has been properly provided\n\tif 'ImageFile' not in request.files or\\\n\t\tlen(request.files['ImageFile'].filename) == 0 or not valid_file(request.files['ImageFile'].filename):\n\t\treturn get_response(400, 'Missing ImageFile image upload!')\n\n\t# make sure that they asked for some transformations to be done\n\tif 'Transformations' not in request.form or len(request.form['Transformations']) == 0:\n\t\treturn get_response(400, 'Missing or empty Transformations field!')\n\n\t# copy the image to the temp directory, create handler\n\tfile = upload_image(request.files['ImageFile'])\n\timage_obj = ImageObject(file)\n\n\t# interpret the transformations\n\ttransformations = get_transformations_list(request.form['Transformations'])\n\n\t# do each transformation on disk\n\tfor tf in transformations:\n\t\thandle_transformation(image_obj, tf)\n\n\t# load the result into memory\n\tbuffer = BytesIO(open(file, 'rb').read())\n\tbuffer.seek(0)\n\n\t# delete the file\n\tos.remove(file)\n\n\t# send the result\n\tresult_filename = request.files['ImageFile'].filename\n\treturn send_file(buffer, as_attachment=True, attachment_filename=result_filename, mimetype=image_obj.mimetype)\n\n\nif __name__ == '__main__':\n\tapp.run()\n","repo_name":"nfj5/CPSC5200-WQ20-ImageManipulation","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":4083,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"2867076723","text":"# Input\ntoInt = lambda pair: (pair[0], int(pair[1]))\ncourse = [toInt(c.split()) for c in open(\"02.in\").read().splitlines()]\n\n# Part 1\ndistance, depth = 0, 0\n\nfor command, steps in course:\n if command == \"forward\":\n distance += steps\n elif command == \"down\":\n depth += steps\n else:\n depth -= steps\n\nprint(\"Part 1:\", distance * depth)\n\n# Part 2\naim, distance, depth = 0, 0, 0\n\nfor command, x in course:\n if command == \"forward\":\n distance += x\n depth += x * aim\n elif command == \"down\":\n aim += x\n else:\n aim -= x\nprint(\"Part 2:\", distance * depth)","repo_name":"yurachistic1/AdventOfCode","sub_path":"2021/02.py","file_name":"02.py","file_ext":"py","file_size_in_byte":613,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"40093596845","text":"from minemoddb.models.person import Person\nfrom minemoddb.program import Program\nfrom minemoddb.cli.screen import Screen\nfrom minemoddb.cli.person.edit_person_screen import EditPersonScreen\nimport minemoddb.cli.person.person_table_menu_screen as \\\n person_table_menu_screen\nfrom minemoddb.utils import get_option\n\n\nclass PersonInfoScreen(Screen):\n def __init__(self, program: Program, person: Person) -> None:\n self._program = program\n self._person = person\n\n def show(self) -> None:\n print('Pessoa\\n'.upper())\n\n print(f\"Nome: {self._person.name}\")\n\n print('')\n options = ['Editar', 'Voltar']\n option = get_option(options)\n if option == 'Editar':\n self._program.set_screen(\n EditPersonScreen(self._program, self._person))\n elif option == 'Voltar':\n self._program.set_screen(\n person_table_menu_screen.PersonTableMenuScreen(self._program))\n","repo_name":"MrTaiko314/mine-mod-db","sub_path":"minemoddb/cli/person/person_info_screen.py","file_name":"person_info_screen.py","file_ext":"py","file_size_in_byte":963,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"24289316742","text":"# Please make sure this file name is \"Roulette.py\" (with capital R)\r\n# Please make sure you have Casino.py\r\n\r\nimport random\r\n\r\nred = [1, 3, 5, 7, 9, 12, 14, 16, 18, 19, 21, 23, 25, 27, 30, 32, 34, 36] #red defines a set of winning numbers as well as the Red color variant on the roulette wheel.\r\nblack = [2, 4, 6, 8, 10, 11, 13, 15, 17, 20, 22, 24, 26, 28, 29, 31, 33, 35]#black defines a set of winning numbers as well as the Black color variant on the roulette wheel.\r\nbankaccount = 36 #The bank account variable is the starting balance in chips the user has.\r\nbet = 0 #The bet variable is the amount a user can bet. The user cannot bet more than their bankaccount balance, and cannot continue to bet once their balance has reached 0.\r\n\r\ndef quit(): #The quit function will take the user back to the main menu.\r\n stream = open(\"Casino.py\")\r\n read_file = stream.read()\r\n exec(read_file)\r\n\r\ndef betchoice(number): #The betchoice function defines the winning amounts for the array numbers.\r\n global bankaccount\r\n global bet\r\n global red\r\n global black\r\n playerchoice = (number)\r\n spin = random.randint(1,36) #This will select a random number between 1-36.\r\n if playerchoice == spin:\r\n betaddition = int(35 * bet)\r\n bankaccount = bankaccount + betaddition #If your choice matches the random spin number you will win 35 times the original bet amount.\r\n print(\"The ball lands on :\", spin)\r\n print(\"You win:\", betaddition)\r\n print(\"You have\", bankaccount)\r\n start_Game()\r\n else:\r\n print(\"The ball lands on :\", spin) #If your choice does not match the random spin number you will lose your original bet amount.\r\n print(playerchoice)\r\n print(\"You lose \", bet, \"chips.\")\r\n start_Game()\r\n return playerchoice\r\n\r\n\r\n\r\ndef Welcome(): #The welcome message defines the rules of the game.\r\n print(\"Welcome to high-stakes python roulette!\", \"\\n\", \"Minimum 1 chip per spin\", \"\\n\", \"Match a number and a color combination to win!\", \"\\n\", \"You may only bet on the listed numbers, so the odds are 1 in 36 chances of winning.\", \"\\n\", \"The payout is 35 to 1! So get spinning and best of luck!\", \"\\n\")\r\n\r\ndef start_Game(): #The start_Game function allows the user to place their bet as well as select their winning numbers and color.\r\n global bankaccount\r\n global bet\r\n global red\r\n global black\r\n print(\"\\n You have:\",bankaccount, \"chips\")\r\n question1 = input(\"Would you like to start game [Y]es or [N]o \\n\")\r\n if question1 == \"Y\" or question1 == \"y\":\r\n bet = int(input(\"How many chips would you like to bet: \"))\r\n if bet == 0 or bet > bankaccount:\r\n print(\"You don't have enough chips.\\n\")\r\n start_Game()\r\n bankaccount = bankaccount - bet\r\n print( \"\\nPlace your bet! \")\r\n print(\"The numbers for {RED} are 1, 3, 5, 7, 9, 12, 14, 16, 18, 19, 21, 23, 25, 27, 30, 32, 34, 36\")\r\n print(\"The numbers for {BLACK} are 2, 4, 6, 8, 10, 11, 13, 15, 17, 20, 22, 24, 26, 28, 29, 31, 33, 35\\n\")\r\n number = int(input(\"Type a number between 1 and 36: \")) #Pick a number 1 - 36 as listed.\r\n betchoice(number) #Your choice will be registered here.\r\n else:\r\n print(\"Thank you come again \")\r\n quit()\r\n\r\nWelcome()\r\nstart_Game()","repo_name":"nickbent1/PythonCasino","sub_path":"Roulette.py","file_name":"Roulette.py","file_ext":"py","file_size_in_byte":3310,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"70082389705","text":"from collections import deque\nfrom itertools import accumulate\nfrom math import inf\nfrom typing import List\n\n\nclass Solution:\n def shortestSubarray(self, nums: List[int], k: int) -> int:\n ans = inf\n pre_s = list(accumulate(nums, initial=0))\n\n q = deque()\n for i, cur_s in enumerate(pre_s):\n while q and cur_s - pre_s[q[0]] >= k:\n ans = min(ans, i - q.popleft())\n while q and cur_s < pre_s[q[-1]]:\n q.pop()\n q.append(i)\n\n return ans if ans < inf else -1\n","repo_name":"tiandiyijian/myLeetcode","sub_path":"862.py","file_name":"862.py","file_ext":"py","file_size_in_byte":554,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"32740729156","text":"import auth.auth as auth\nfrom flask import Response\nfrom utils import response\nimport json, datetime\nfrom datastore.datastore import initClient, datastore\n\nclient = initClient()\n\n# update user learning\n@auth.auth_required()\ndef updateUserLearning(request): \n\n if request.content_type.split(\";\")[0] != 'application/json':\n return Response(status=415,\n mimetype='application/json',\n response=json.dumps({\"error\": \"Content-Type must be application/json\"}))\n import datetime\n\n data = request.get_json()\n child = data.get('childId')\n lesson = data.get('lessonId')\n timestamp = datetime.datetime.now().strftime('%d/%m/%Y')\n attempts = data['attempts'] \n #check if the child belong to this user\n userId = request.user_info['user']\n userData = client.get(client.key('user',userId))\n\n if userData == None:\n return Response (status=401,\n mimetype='application/json',\n response=json.dumps({'error': 'Strange, you are not registered. Maybe /login first and thn make some child if you know what I mean {ಠʖಠ}'}))\n\n if userData.get('children').get(child) == None:\n return Response (status=403,\n mimetype='application/json',\n response=json.dumps({'error': 'child Id not found or this child does not belong to you'}))\n \n childLearningData = client.get(client.key('user_learning', child))\n childLearningData['completedLessonsObject'][lesson]={\n 'timestamp': data.get('timestamp'),\n 'insertedAt': datetime.datetime.now().strftime('%d/%m/%Y'),\n 'attempts': attempts\n }\n\n dateOfLearning = data.get('timestamp')\n lastUpdated = str(childLearningData.get('weeklyLearningIndex').get('lastUpdated'))\n # if last updated is last week\n if lastUpdated != None and lastUpdated != '' and lastUpdated != 'None':\n try:\n lastUpdated = datetime.datetime.strptime(lastUpdated, '%d/%m/%Y')\n except:\n lastUpdated = datetime.datetime.strptime(lastUpdated, '%Y-%m-%d %H:%M:%S.%f%z')\n if lastUpdated.isocalendar()[1] < datetime.datetime.strptime(dateOfLearning, '%d/%m/%Y').isocalendar()[1]:\n integer = 0\n elif lastUpdated.isocalendar()[1] == datetime.datetime.strptime(dateOfLearning, '%d/%m/%Y').isocalendar()[1]:\n integer = childLearningData.get('weeklyLearningIndex').get('integer')\n else:\n integer = 0\n\n\n try :\n # get which day of the week it is\n dayOfLearning = datetime.datetime.strptime(dateOfLearning, '%d/%m/%Y').weekday()\n integer = integer | 1 << dayOfLearning\n\n childLearningData['weeklyLearningIndex'] = {\n 'integer': integer,\n 'lastUpdated': dateOfLearning\n }\n except Exception as e:\n return Response(status=500,\n mimetype='application/json',\n response=json.dumps({\"error\": str(e)}))\n\n for attempt in attempts:\n questionEntity = client.get(client.key('question', attempt['questionId']))\n tags = questionEntity.get(\"tags\")\n score = 1 if attempt['isCorrect'] else -1\n \n for tag in tags:\n try:\n childLearningData['tagScoring'][tag] += score \n except KeyError:\n childLearningData['tagScoring'][tag] = score\n\n client.put(childLearningData)\n\n return Response (status=200,\n mimetype='application/json',\n response=json.dumps({\"message\":\"all good\"}))\n\n#metode post report tidak disimpan di db\n@auth.auth_required() \ndef userReport(request):\n userid = request.user_info['user']\n child = request.args.get('childId')\n\n if child == None:\n return response.missing_field('childId')\n \n userData = client.get(client.key('user',userid))\n if userData == None:\n return Response (status=401,\n mimetype='application/json',\n response=json.dumps({'error': 'Strange, you are not registered. Maybe /login first and thn make some child if you know what I mean {ಠʖಠ}'}))\n \n if userData.get('children').get(child) == None:\n return Response (status=403,\n mimetype='application/json',\n response=json.dumps({'error': 'child Id not found or this child does not belong to you'}))\n \n childData = client.get(client.key('user_learning', child))\n if childData == None:\n return Response (status=500,\n mimetype='application/json',\n response=json.dumps({'error': 'child learning data not found, please contact developer'}))\n \n tags = childData.get('tagScoring')\n tags = sorted(tags.items(), key=lambda x: x[1], reverse=True)\n # get tags that have score less than 2\n lessonThatNeedHelp = [tag for tag in tags if tag[1] < 2]\n\n weeklyLearningIndex = childData.get('weeklyLearningIndex').get('integer')\n weeklyLearningIndex = bin(weeklyLearningIndex)[2:].zfill(7)\n weeklyLearning = {\n 'monday': weeklyLearningIndex[-1] == '1',\n 'tuesday': weeklyLearningIndex[-2] == '1',\n 'wednesday': weeklyLearningIndex[-3] == '1',\n 'thursday': weeklyLearningIndex[-4] == '1',\n 'friday': weeklyLearningIndex[-5] == '1',\n 'saturday': weeklyLearningIndex[-6] == '1',\n 'sunday': weeklyLearningIndex[-7] == '1'\n }\n return Response(\n status=200,\n mimetype='application/json',\n response=json.dumps({\n \"email\": userid,\n \"childId\": child,\n \"tag\": lessonThatNeedHelp,\n \"learningProgress\": weeklyLearning\n })\n )\n\n","repo_name":"Calis-Top-10/CalisAPI","sub_path":"functions/userlearning/userlearning.py","file_name":"userlearning.py","file_ext":"py","file_size_in_byte":5782,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"73547501385","text":"from __future__ import absolute_import, print_function\n\nfrom copy import deepcopy\n\nfrom flask import Blueprint, current_app, render_template, request\nfrom flask_login import login_required\nfrom invenio_pidstore.errors import PIDDeletedError\nfrom invenio_records_ui.signals import record_viewed\n\nfrom ..proxies import current_deposit\n\n\ndef create_blueprint(endpoints):\n \"\"\"Create Invenio-Deposit-UI blueprint.\n\n See: :data:`invenio_deposit.config.DEPOSIT_RECORDS_UI_ENDPOINTS`.\n\n :param endpoints: List of endpoints configuration.\n :returns: The configured blueprint.\n \"\"\"\n from invenio_records_ui.views import create_url_rule\n\n blueprint = Blueprint(\n 'invenio_deposit_ui',\n __name__,\n static_folder='../static',\n template_folder='../templates',\n url_prefix='',\n )\n\n @blueprint.errorhandler(PIDDeletedError)\n def tombstone_errorhandler(error):\n \"\"\"Render tombstone page.\"\"\"\n return render_template(\n current_app.config['DEPOSIT_UI_TOMBSTONE_TEMPLATE'],\n pid=error.pid,\n record=error.record or {},\n ), 410\n\n for endpoint, options in (endpoints or {}).items():\n options = deepcopy(options)\n options.pop('jsonschema', None)\n options.pop('schemaform', None)\n blueprint.add_url_rule(**create_url_rule(endpoint, **options))\n\n @blueprint.route('/deposit')\n @login_required\n def index():\n \"\"\"List user deposits.\"\"\"\n return render_template(current_app.config['DEPOSIT_UI_INDEX_TEMPLATE'])\n\n @blueprint.route('/deposit/new')\n @login_required\n def new():\n \"\"\"Create new deposit.\"\"\"\n deposit_type = request.values.get('type')\n return render_template(\n current_app.config['DEPOSIT_UI_NEW_TEMPLATE'],\n record={'_deposit': {'id': None}},\n jsonschema=current_deposit.jsonschemas[deposit_type],\n schemaform=current_deposit.schemaforms[deposit_type],\n )\n\n return blueprint\n\n\ndef default_view_method(pid, record, template=None):\n \"\"\"Default view method.\n\n Sends ``record_viewed`` signal and renders template.\n \"\"\"\n record_viewed.send(\n current_app._get_current_object(),\n pid=pid,\n record=record,\n )\n\n deposit_type = request.values.get('type')\n\n return render_template(\n template,\n pid=pid,\n record=record,\n jsonschema=current_deposit.jsonschemas[deposit_type],\n schemaform=current_deposit.schemaforms[deposit_type],\n )\n","repo_name":"inveniosoftware/invenio-deposit","sub_path":"invenio_deposit/views/ui.py","file_name":"ui.py","file_ext":"py","file_size_in_byte":2538,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"81"} +{"seq_id":"23362743727","text":"\"\"\" Commit to a fast \"\"\"\nimport logging\nfrom google.appengine.api import users\nfrom datetime import datetime\n\nimport webapp2\n\nimport fastsunday_utils as utils\nfrom fast import Fast\nfrom user import User\n\nclass Challenge(webapp2.RequestHandler):\n def get(self, fast_id):\n \"\"\" Will you commit to a fast? \"\"\"\n fast = Fast.get_by_id(fast_id)\n logging.info('HEY THERE')\n logging.info(fast_id)\n if fast:\n data = {'fast_date': fast.date, 'fast_id': fast_id}\n html = utils.render_template('tl/challenge.html', data)\n self.response.write(html)\n\n\nclass Commit(webapp2.RequestHandler):\n \"\"\" Class for committing to a fast \"\"\"\n def get(self, fast_id):\n \"\"\" Congratulations, you've committed to a fast \"\"\"\n logging.info('HEY THERE')\n logging.info(fast_id)\n fast = Fast.get_by_id(fast_id)\n if fast:\n data = {'fast_date': fast.date, 'fast_id': fast_id}\n html = utils.render_template('tl/committed.html', data)\n self.response.write(html)\n\napp = webapp2.WSGIApplication([\n ('/fast/(\\d+)/challenge', Challenge),\n ('/fast/(\\d+)/commit', Commit),\n], debug=True)\n","repo_name":"smfoote/fastsunday","sub_path":"src/commit.py","file_name":"commit.py","file_ext":"py","file_size_in_byte":1193,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"17478314756","text":"import sys\nimport os\n\n\ndef main():\n try:\n os.mkdir(\"../Jefferson Papers/From_Jefferson\")\n print(\"Directory 'From_Jefferson' Created\")\n except FileExistsError:\n print(\"Directory already made\")\n\n try:\n os.mkdir(\"../Jefferson Papers/To_Jefferson\")\n print(\"Directory 'To_Jefferson' Created\")\n except FileExistsError:\n print(\"Directory already made\")\n\n files = os.listdir(\"../Jefferson Papers/\")\n #print(len(\"Thomas Jefferson to\"))\n #sys.exit()\n\n with open(\"../changes.txt\") as f:\n content = f.readlines()\n content = [x.strip() for x in content]\n\n count = 0\n\n for file in files:\n if file == \"From_Jefferson\" or file == \"To_Jefferson\" or file == \"xmlFiles\":\n continue\n\n if file[0:16] == \"thomas jefferson\":\n #print(file)\n os.rename(\"../Jefferson Papers/\"+file, \"../Jefferson Papers/From_Jefferson/\"+file)\n count += 1\n else:\n if file == \"william h. cabell from thomas jefferson, june 29, 1807.txt\":\n os.rename(\"../Jefferson Papers/\"+file, \"../Jefferson Papers/From_Jefferson/to william h. cabell, june 29, 1807.txt\")\n elif file == \"george washington from thomas jefferson, january 15, 1792, with copy.txt\":\n os.rename(\"../Jefferson Papers/\"+file, \"../Jefferson Papers/From_Jefferson/to george washington, january 15, 1792.txt\")\n elif file == \"john mason from thomas jefferson, august 18, 1814.txt\":\n os.rename(\"../Jefferson Papers/\"+file, \"../Jefferson Papers/From_Jefferson/to john mason, august 18, 1814.txt\")\n else:\n new_file = file\n for x in content:\n if file in x:\n new_file = x.split(\" -> \")[len(x.split(\" -> \"))-1]\n os.rename(\"../Jefferson Papers/\"+file, \"../Jefferson Papers/To_Jefferson/\"+new_file)\n\n #print(count)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"RamIyer1998/Jefferson-Papers","sub_path":"src/separator.py","file_name":"separator.py","file_ext":"py","file_size_in_byte":1983,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"81"} +{"seq_id":"33343593128","text":"from collections import defaultdict\n\nimport numpy as np\nfrom deeplake.util.exceptions import DynamicTensorNumpyError # type: ignore\n\n_valid_formats = {\n \"ascii\": \"\",\n \"ascii_with_normals\": \"\",\n \"binary_big_endian\": \">\",\n \"binary_little_endian\": \"<\",\n}\n\n\nclass PlyReaderBase:\n \"\"\"Represents a parser class for ply data.\n\n Args:\n filename (str): path to the 3d file\n \"\"\"\n\n def __init__(self, filename, fmt):\n self.element_name_to_property_dtypes = defaultdict(dict)\n self.filename = filename\n self.line = []\n self.count = 2\n self.points_size = None\n self.mesh_size = None\n self.has_texture = False\n self.comments = []\n self.stream = self._open_stream(self.filename)\n self.obj_info = None\n self.fmt = fmt\n self.meta_data = self.create_meta_data()\n self.ext = self.read_header()\n\n @staticmethod\n def _open_stream(filename):\n if isinstance(filename, str):\n return open(filename, \"rb\")\n return filename\n\n def _parse_element(self, line):\n line = line.split()\n name = line[1].decode()\n size = int(line[2])\n if name == \"vertex\":\n self.points_size = size\n elif name == \"face\":\n self.mesh_size = size\n\n self.meta_data[name] = size\n return name\n\n @staticmethod\n def _parse_properties(fmt, ext, line, has_texture, meta_data, name):\n raise NotImplementedError\n\n @staticmethod\n def _parse_comments(line, meta_data):\n line = line.split(b\" \", 1)\n comments = line[1].decode().rstrip()\n meta_data[\"comments\"].append(comments)\n\n def create_meta_data(self):\n meta_data = {\n \"dimensions_names\": [],\n \"element_name_to_property_dtypes\": defaultdict(dict),\n \"dimensions_names_to_dtype\": {},\n \"comments\": [],\n \"fmt\": self.fmt,\n \"extension\": \"ply\",\n }\n return meta_data\n\n def read_header(self):\n ext = _valid_formats[self.fmt]\n self.stream.seek(0)\n while b\"end_header\" not in self.line and self.line != b\"\":\n self.line = self.stream.readline()\n if b\"element\" in self.line:\n name = self._parse_element(self.line)\n elif b\"property\" in self.line:\n self.has_texture = self._parse_properties(\n self.fmt, ext, self.line, self.has_texture, self.meta_data, name\n )\n elif b\"comment\" in self.line:\n self._parse_comments(self.line, self.meta_data)\n\n self.count += 1\n self.end_header = self.stream.tell()\n return ext\n\n def read(self):\n stream_bytes = self.stream.read()\n data = self._parse_data(\n self.ext, self.fmt, self.meta_data, stream_bytes, dtype=np.float32\n )\n self.stream.close()\n return data\n\n def _parse_data(self, ext, fmt, meta_data, stream_bytes, dtype=np.float32):\n raise NotImplementedError\n\n @staticmethod\n def _convert_dict_to_list_of_tuples(property_name_to_dtypes):\n return [(key, value) for key, value in property_name_to_dtypes.items()]\n","repo_name":"activeloopai/deeplake","sub_path":"deeplake/util/object_3d/ply_reader_base.py","file_name":"ply_reader_base.py","file_ext":"py","file_size_in_byte":3221,"program_lang":"python","lang":"en","doc_type":"code","stars":7141,"dataset":"github-code","pt":"81"} +{"seq_id":"13825894795","text":"#!/usr/bin/env python3\nimport rospy\nimport numpy as np\nfrom geometry_msgs.msg import PoseStamped\n\nclass send_goal():\n\n def __init__(self):\n\n self.publisher_goal = rospy.Publisher('/send_goal', PoseStamped, queue_size=1)\n\n self.goal = PoseStamped()\n self.goal_pose_x = np.random.random()*2\n self.goal_pose_y = np.random.random()*2\n\n self.run()\n \n def run(self):\n while not rospy.is_shutdown():\n self.goal.pose.position.x = self.goal_pose_x\n self.goal.pose.position.y = self.goal_pose_y\n self.goal.header.frame_id = \"map\"\n self.publisher_goal.publish(self.goal)\n print(\"published\")\n\n\nif __name__ == \"__main__\":\n # try:\n rospy.init_node(\"send_goal\") \n send_goal() \n rospy.spin()\n # except rospy.ROSInterruptException:\n # pass","repo_name":"kurreman/Dopey-DD2419","sub_path":"src/planning/src/send_goal.py","file_name":"send_goal.py","file_ext":"py","file_size_in_byte":855,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"8381958876","text":"from __future__ import unicode_literals\n\nimport os\n\nfrom setuptools import find_packages\nfrom setuptools import setup\n\n\nclassifiers = [\n 'Environment :: Web Environment',\n 'Framework :: Django',\n 'Intended Audience :: Developers',\n 'License :: OSI Approved :: MIT License',\n 'Operating System :: OS Independent',\n 'Programming Language :: Python',\n 'Topic :: Internet :: WWW/HTTP',\n 'Topic :: Internet :: WWW/HTTP :: Dynamic Content',\n]\n\nREADME = open(os.path.join(os.path.dirname(__file__), 'README.rst')).read()\n\n# allow setup.py to be run from any path\nos.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))\n\nsetup(\n name='django-awesome-bootstrap',\n version='3.2.0',\n packages=find_packages(),\n include_package_data=True,\n license='MIT License',\n description='A Django app for including twitter bootstrap and font awesome.',\n long_description=README,\n url='https://github.com/infoagetech/django-awesome-bootstrap',\n download_url='https://pypi.python.org/pypi/django-awesome-bootstrap',\n author='Troy Grosfield',\n maintainer='Troy Grosfield',\n classifiers=classifiers,\n)\n","repo_name":"InfoAgeTech/django-awesome-bootstrap","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1158,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"81"} +{"seq_id":"24456276971","text":"\ngroups = {}\n\nwith open(\"input.txt\", \"r\") as f:\n data = f.readlines()\n\ncurrent = 1\nfor line in data:\n if (line == \"\\n\") or (line == \"\\r\\n\") or line.isspace():\n current += 1\n continue\n \n print(f\"{line.strip()}\")\n if not (groups.get(f\"group{current}\")):\n groups[f\"group{current}\"] = int(line.strip())\n else:\n groups[f\"group{current}\"] += int(line.strip())\n\nwith open(\"output.txt\", \"a\") as f:\n for k, v in groups.items():\n f.write(f\"{k} - {v}\\n\")\n\ntotal = 0\n\nprint()\nfor i in range(1, 4):\n tempn = 0\n tempg = \"\"\n for k, v in groups.items():\n if v > tempn:\n tempg = k\n tempn = v\n temp = groups.pop(tempg)\n total += temp\n print(f\"{i} - {temp}\")\n\nprint(f\"\\nTOTAL: {total}\\n\")\n","repo_name":"DeanCash/AdventOfCode2022","sub_path":"Solutions/Solution1/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":773,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"72807842185","text":"import itertools\nfrom collections import deque\n\ndef recursive(answer, check, n, k):\n if n == 0:\n return [answer[0]]\n result = []\n\n first = k//check[n]\n remain = k%check[n]\n if remain == 0:\n result.append(answer.pop(first-1))\n else:\n result.append(answer.pop(first))\n n -= 1\n k = remain\n return result + recursive(answer, check, n, k)\n#\ndef solution(n, k):\n answer = [i for i in range(1, n+1)]\n\n check = [0, 1, 2]\n for i in range(3, n):\n check.append(check[i-1]*i)\n # permutations = itertools.permutations(answer, n)\n # cnt = 1\n # for per in permutations:\n # if cnt == k:\n # print(per)\n # break\n # cnt += 1\n\n result = recursive(answer, check, n-1, k)\n return result\n\ndef main():\n print(solution(20, 788))\n\n\nif __name__ == \"__main__\":\n main()","repo_name":"fineman999/Algorithm","sub_path":"Programmers/Level2/PracticeQuestion/how_to_get_in_line.py","file_name":"how_to_get_in_line.py","file_ext":"py","file_size_in_byte":861,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"9279517726","text":"\"\"\"A simple visualization front-end.\"\"\"\n\nfrom typing import AsyncIterator, List, Union\n\nimport datetime\nimport urllib.parse\nimport asyncio\nfrom aiohttp import web\n\nfrom . import postgres\nfrom . import config\n\n\nroutes = web.RouteTableDef()\n\nHEADERS = {\"Cache-Control\": \"no-cache\"}\n\nwith open(\"avmon/frontend.html\") as f:\n HTML_TEMPLATE = f.read()\n\n\ndef make_html(body):\n return HTML_TEMPLATE.replace(\"$CONTENT\", body)\n\n\nclass HtmlTag:\n def __init__(\n self,\n tag: str,\n contents: Union[\"HtmlTag\", str, List[Union[\"HtmlTag\", str]]] = [],\n **kwargs,\n ) -> None:\n self.tag = tag\n self.args = kwargs\n self.args[\"class\"] = self.args.get(\"classes_\", [])\n self.contents = contents[:] if isinstance(contents, list) else [contents]\n\n def append(self, value: Union[str, \"HtmlTag\"]) -> None:\n self.contents.append(value)\n\n @property\n def classes(self) -> List[str]:\n return self.args[\"class\"] # type: ignore\n\n @property\n def html(self) -> str:\n result = f\"<{self.tag}\"\n for key, value in self.args.items():\n if isinstance(value, list):\n value = \" \".join(value)\n assert '\"' not in value\n result += \" \" + key + '=\"' + value + '\"'\n result += f\">\"\n for c in self.contents:\n if isinstance(c, str):\n result += c\n else:\n assert isinstance(c, HtmlTag), f\"{c !r}\"\n result += c.html\n result += f\"\"\n return result\n\n\ndef make_table(columns: List[str]) -> HtmlTag:\n table = HtmlTag(\"table\")\n thead = HtmlTag(\"thead\")\n for c in columns:\n thead.contents.append(HtmlTag(\"th\", contents=c))\n table.contents.append(thead)\n return table\n\n\n@routes.get(\"/\")\nasync def all(request: web.Request) -> web.Response:\n async with request.config_dict[\"DB\"].acquire() as conn:\n rows = await conn.fetch(\n \"\"\"\n SELECT DISTINCT ON (url) url, reached, error, status, time_start, (time_end - time_start) as delay\n FROM status_history\n ORDER BY url ASC, time_start DESC\n \"\"\"\n )\n\n table = make_table(\n [\"Endpoint\", \"Reached\", \"Status\", \"Time (UTC)\", \"Delay\", \"History\"]\n )\n for row in rows:\n tr = HtmlTag(\"tr\")\n\n if not row[\"reached\"]:\n tr.classes.append(\"unreachable\")\n\n tr.append(\n HtmlTag(\n \"td\",\n contents=HtmlTag(\"a\", contents=row[\"url\"], href=row[\"url\"]),\n )\n )\n\n tr.append(HtmlTag(\"td\", contents=str(row[\"reached\"]), classes=[\"reached\"]))\n\n status_cell = HtmlTag(\"td\")\n if row[\"reached\"]:\n status_cell.contents = [str(row[\"status\"])]\n status_cell = HtmlTag(\"td\", contents=str(row[\"status\"]))\n if 200 <= row[\"status\"] < 300:\n status_cell.classes.append(\"ok\")\n elif 400 <= row[\"status\"] < 600:\n status_cell.classes.append(\"error\")\n else:\n status_cell.contents = [row[\"error\"]]\n status_cell.classes.append(\"error\")\n tr.append(status_cell)\n\n tr.append(HtmlTag(\"td\", contents=str(row[\"time_start\"])))\n tr.append(HtmlTag(\"td\", contents=f\"{row['delay'].seconds:.2f}\"))\n\n tr.append(\n HtmlTag(\n \"td\",\n contents=HtmlTag(\n \"a\",\n contents=\"Show history\",\n href=urllib.parse.quote_plus(row[\"url\"]),\n ),\n )\n )\n\n table.contents.append(tr)\n\n return web.Response(\n text=make_html(\"

Endpoint status

\" + table.html),\n content_type=\"text/html\",\n headers=HEADERS,\n )\n\n\n@routes.get(\"/{url}\")\nasync def single(request: web.Request) -> web.Response:\n url = request.match_info.get(\"url\")\n assert url\n limit = max(1, int(request.query.get(\"limit\", 10)))\n\n async with request.config_dict[\"DB\"].acquire() as conn:\n rows = await conn.fetch(\n \"\"\"\n SELECT reached, error, status, time_start, (time_end - time_start) as delay\n FROM status_history\n WHERE url = $1\n ORDER BY time_start DESC\n LIMIT $2\n \"\"\",\n url,\n limit,\n )\n\n table = make_table([\"Reached\", \"Status\", \"Time (UTC)\", \"Delay\"])\n\n for row in rows:\n tr = HtmlTag(\"tr\")\n\n if not row[\"reached\"]:\n tr.classes.append(\"unreachable\")\n\n tr.append(HtmlTag(\"td\", contents=str(row[\"reached\"]), classes=[\"reached\"]))\n\n status_cell = HtmlTag(\"td\")\n if row[\"reached\"]:\n status_cell.contents = [str(row[\"status\"])]\n status_cell = HtmlTag(\"td\", contents=str(row[\"status\"]))\n if 200 <= row[\"status\"] < 300:\n status_cell.classes.append(\"ok\")\n elif 400 <= row[\"status\"] < 600:\n status_cell.classes.append(\"error\")\n else:\n status_cell.contents = [row[\"error\"]]\n status_cell.classes.append(\"error\")\n tr.append(status_cell)\n\n tr.append(HtmlTag(\"td\", contents=str(row[\"time_start\"])))\n tr.append(HtmlTag(\"td\", contents=f\"{row['delay'].seconds:.2f}\"))\n\n table.contents.append(tr)\n\n link = HtmlTag(\"a\", contents=url, href=url)\n prefix = f'Back to the front page

History for {link.html}

'\n suffix = \"\"\n if len(rows) == limit:\n suffix += f\"

Showing first {limit} entries. \"\n suffix += 'Show more'\n suffix += \"

\"\n\n return web.Response(\n text=make_html(prefix + table.html + suffix),\n content_type=\"text/html\",\n headers=HEADERS,\n )\n\n\ndef init_app() -> web.Application:\n config.load_dotenv()\n app = web.Application()\n app.add_routes(routes)\n app.cleanup_ctx.append(init_db)\n return app\n\n\nasync def init_db(app: web.Application) -> AsyncIterator[None]:\n db = await postgres.create_pool()\n app[\"DB\"] = db\n yield\n await db.close()\n\n\nasync def main():\n runner = web.AppRunner(init_app())\n await runner.setup()\n site = web.TCPSite(runner, \"0.0.0.0\", 8080)\n await site.start()\n await asyncio.Event().wait() # forever\n\n\nif __name__ == \"__main__\":\n loop = asyncio.get_event_loop()\n loop.run_until_complete(main())\n","repo_name":"Dentosal/avmon","sub_path":"avmon/frontend.py","file_name":"frontend.py","file_ext":"py","file_size_in_byte":6443,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"35655462688","text":"import json\nimport time\nimport asyncio\nimport requests\nfrom requests.exceptions import ReadTimeout\n\nfrom Logger import logger\nfrom data.config import release, telegramHost\nfrom parsers.DtfParser import DTFParser\nfrom parsers.PlayGroundParser import PlayGroundParser\nfrom storage import MongodbService\n\nstorage = MongodbService.get_instance()\nif not release:\n storage.delete_all_data()\n\nplayGroundParser = PlayGroundParser()\n\ndtfParser = DTFParser()\n\n\ndef saveArticles(articlesJSON):\n \"\"\"\n :param articlesJSON: [Article]\n :return:\n \"\"\"\n for article in articlesJSON:\n storage.save_data(article)\n\n\ndef sendToTelegram(articlesJSON):\n try:\n if len(articlesJSON) > 0:\n requests.post(\"http://\" + telegramHost, data=json.dumps(articlesJSON), timeout=1)\n except ReadTimeout:\n pass\n\n\ndef articleToArticleJson(articles):\n articlesJSON = []\n for article in articles:\n articlesJSON.append(article.toArray())\n return articlesJSON\n\n\nasync def main():\n while True:\n stopGameArticles = await playGroundParser.parse()\n DtfArticles = await dtfParser.parse()\n\n articles = DtfArticles + stopGameArticles\n\n articlesJSON = articleToArticleJson(articles[::-1])\n\n sendToTelegram(articlesJSON)\n saveArticles(articlesJSON)\n\n logger.log(\"{} articles added\".format(len(articlesJSON)))\n time.sleep(60 * 10)\n\n\nif __name__ == \"__main__\":\n loop = asyncio.get_event_loop()\n loop.run_until_complete(main())\n loop.close()\n\n # storage.delete_all_data() # удаление всего из базы\n","repo_name":"StounhandJ/Automatic-news","sub_path":"parser/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1603,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"31416808166","text":"from .models import Movie, Genre\nfrom rest_framework import serializers\n\n\nclass GenreSerializer(serializers.ModelSerializer):\n \"\"\"\n The Genre serializer that returns the genre with all its fields.\n \"\"\"\n class Meta:\n model = Genre\n fields = '__all__'\n\n\nclass MovieSerializer(serializers.ModelSerializer):\n \"\"\"\n The Movie serializer that returns the movie data and also adds the genre data with all its fields.\n \"\"\"\n\n # To load the genre data fields\n genres = GenreSerializer(many=True)\n\n class Meta:\n model = Movie\n fields = '__all__'\n\n # Custom create function implementation since we have many-to-many relation in our data set\n # New moive is created whilst checking if the genre already exists.\n def create(self, validated_data):\n genre_data = validated_data.pop('genres')\n new_movie = Movie.objects.create(**validated_data)\n genre_ids = []\n for genre in genre_data:\n genre_exits = Genre.objects.filter(**genre)\n if genre_exits.exists():\n genre_ids.append(genre_exits.get().id)\n else:\n new_genre = Genre(**genre)\n new_genre.save()\n genre_ids.append(new_genre.id)\n\n new_movie.genres.add(*genre_ids)\n return new_movie\n\n # The id of the genre that is passed in the API is loaded and available here as instance.\n # We update the instance on the with the data provided in the body.\n # Same is used to make partial updates(PATCH)\n def update(self, instance, validated_data):\n genre_data = validated_data.pop('genres', [])\n instance = super().update(instance, validated_data)\n if genre_data:\n instance.genres.clear()\n genre_ids = []\n for genre in genre_data:\n genre_exits = Genre.objects.filter(**genre)\n if genre_exits.exists():\n genre_ids.append(genre_exits.get().id)\n else:\n new_genre = Genre(**genre)\n new_genre.save()\n genre_ids.append(new_genre.id)\n\n instance.genres.add(*genre_ids)\n return instance\n\n\n","repo_name":"ahmedhr/django_task","sub_path":"api/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":2174,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"41120638848","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\nimport io\nimport os\nimport json\nimport telegram\nfrom datetime import datetime\n\nimport matplotlib.pyplot as plt\nimport matplotlib.dates as mdates\n\nfrom nys_soda import get_data\n\nCFG_FILE = 'config.json'\nSTATE_FILE = 'last_covid_data.json'\n\n\nclass TelegramGateway:\n\n def __init__(self, token, chat_id):\n self.bot = telegram.Bot(token)\n self.chat_id = chat_id\n\n def send_msg(self, msg, chat=None):\n # TelegramGateway().send('This is a test message')\n\n self.bot.send_message(chat_id=chat if chat else self.chat_id, text=msg)\n\n def send_img_bytes(self, img, chat=None):\n self.bot.send_photo(chat_id=chat if chat else self.chat_id, photo=img)\n\n\ndef get_last_timestamp():\n if not os.path.isfile(STATE_FILE):\n return datetime.min\n with open(STATE_FILE) as f:\n timestamp = json.load(f)\n return datetime.fromisoformat(timestamp)\n\n\ndef set_last_timestamp(timestamp):\n with open(STATE_FILE, 'w') as f:\n json.dump(timestamp.isoformat(), f)\n\n\ndef create_plots(data, buffer):\n plot_columns = (['new_cases', 'new_cases_ave'], ['ratio', 'ratio_ave'])\n plot_legends = (['New Cases', '7 day average'],\n ['Positive Test Ratio', '7 day average'])\n rolling_period = 7\n\n for (src, dst) in plot_columns:\n data[dst] = data[src].rolling(rolling_period).mean()\n\n fig, axes = plt.subplots(ncols=2, figsize=(15, 8))\n\n for axis, column, legend in zip(axes, plot_columns, plot_legends):\n data[-30:][column].plot(ax=axis, rot=-60)\n axis.xaxis.set_major_locator(\n mdates.WeekdayLocator(byweekday=mdates.MO))\n axis.xaxis.set_minor_locator(mdates.DayLocator())\n axis.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))\n axis.xaxis.set_minor_formatter(mdates.DateFormatter('%Y-%m-%d'))\n axis.grid(which='major', linestyle=':', linewidth='2')\n axis.grid(which='minor', linestyle=':', linewidth='0.5')\n axis.legend(legend)\n\n plt.savefig(buffer, format='png', dpi=300)\n buffer.seek(0)\n\n\ndef main():\n with open(CFG_FILE) as f:\n cfg = json.load(f)\n\n last = get_last_timestamp()\n data = get_data(cfg['SOCRATA_TOKEN'])\n timestamp = data.index[-1]\n if timestamp > last:\n set_last_timestamp(timestamp)\n\n t = TelegramGateway(cfg['TELEGRAM_TOKEN'], cfg['TELEGRAM_CHAT_ID'])\n t.send_msg(f'COVID data was updated:\\ndate{str(data[-1:])[4:]}')\n\n # Do not report averages in table -- too wide\n # for phone screens\n summary_15_days = f'date{str(data[-15:])[4:]}'\n\n with io.BytesIO() as buffer:\n create_plots(data, buffer)\n\n t.send_img_bytes(buffer)\n\n t.send_msg(summary_15_days)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"ricrogz/ny_covid_stats_checker","sub_path":"covid_bot.py","file_name":"covid_bot.py","file_ext":"py","file_size_in_byte":2815,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"37894613306","text":"import socket \nimport os \ns = socket.socket() \ns.bind(('0.0.0.0', 2222)) \ns.listen(5) \nfor i in range(10): \n\tchild = os.fork() \n\tif child == 0: \n\t\twhile True: \n\t\t\tconn, addr = s.accept() \n\t\t\tdata = conn.recv(1024) \n\t\t\tconn.send(data) \n\t\t\tconn.close()","repo_name":"glad-spider/stepic-web","sub_path":"server1.py","file_name":"server1.py","file_ext":"py","file_size_in_byte":250,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"74075945225","text":"# By : Behzad Bahjat Manesh Ardakan\n# ===================================\nfrom mininet.net import Mininet\nfrom mininet.node import Controller, RemoteController, OVSController\nfrom mininet.node import CPULimitedHost, Host, Node\nfrom mininet.node import OVSKernelSwitch, UserSwitch, OVSSwitch\nfrom mininet.node import IVSSwitch\nfrom mininet.cli import CLI\nfrom mininet.log import setLogLevel, info\nfrom mininet.link import TCLink, Intf\nfrom subprocess import call\nimport requests\nimport json\n\n\ndef myNetwork():\n net = Mininet(topo=None,\n build=False,\n ipBase='10.0.0.0/8')\n\n info('*** Adding controller\\n')\n c0 = net.addController(name='c0',\n controller=RemoteController,\n ip='127.0.0.1',\n protocol='tcp',\n port=6633)\n\n info('*** Add switches\\n')\n s1 = net.addSwitch('s1', cls=OVSKernelSwitch)\n s3 = net.addSwitch('s3', cls=OVSKernelSwitch)\n s2 = net.addSwitch('s2', cls=OVSKernelSwitch)\n\n info('*** Add hosts\\n')\n h1 = net.addHost('h1', cls=Host, ip='172.16.20.10/24', defaultRoute='via 172.16.20.1')\n h2 = net.addHost('h2', cls=Host, ip='172.16.10.10/24', defaultRoute='via 172.16.10.1')\n h3 = net.addHost('h3', cls=Host, ip='192.168.30.10/24', defaultRoute='via 192.168.30.1')\n h4 = net.addHost('h4', cls=Host, ip='192.168.30.11/24', defaultRoute='via 192.168.30.1')\n\n info('*** Add links\\n')\n net.addLink(h1, s1)\n net.addLink(h2, s2)\n net.addLink(h3, s3)\n net.addLink(h4, s3)\n net.addLink(s1, s2)\n net.addLink(s2, s3)\n net.addLink(s1, s3)\n\n info('*** Starting network\\n')\n net.build()\n info('*** Starting controllers\\n')\n for controller in net.controllers:\n controller.start()\n\n info('*** Starting switches\\n')\n net.get('s1').start([c0])\n net.get('s2').start([c0])\n net.get('s3').start([c0])\n\n info('*** Post configure switches and hosts\\n')\n\n ## Set IP Addressess for Routers s1 s2 s3\n\n # ======================s1===========================\n url = 'http://localhost:8080/router/0000000000000001'\n payload = {'address': '172.16.20.1/24'}\n r = requests.post(url, data=json.dumps(payload))\n\n url = 'http://localhost:8080/router/0000000000000001'\n payload = {'address': '172.16.30.30/24'}\n r = requests.post(url, data=json.dumps(payload))\n\n url = 'http://localhost:8080/router/0000000000000001'\n payload = {'address': '192.168.100.1/24'}\n r = requests.post(url, data=json.dumps(payload))\n\n # =======================s2==========================\n url = 'http://localhost:8080/router/0000000000000002'\n payload = {'address': '172.16.10.1/24'}\n r = requests.post(url, data=json.dumps(payload))\n\n url = 'http://localhost:8080/router/0000000000000002'\n payload = {'address': '172.16.30.1/24'}\n r = requests.post(url, data=json.dumps(payload))\n\n url = 'http://localhost:8080/router/0000000000000002'\n payload = {'address': '192.168.10.1/24'}\n r = requests.post(url, data=json.dumps(payload))\n\n # =======================s3==========================\n url = 'http://localhost:8080/router/0000000000000003'\n payload = {'address': '192.168.30.1/24'}\n r = requests.post(url, data=json.dumps(payload))\n\n url = 'http://localhost:8080/router/0000000000000003'\n payload = {'address': '192.168.10.20/24'}\n r = requests.post(url, data=json.dumps(payload))\n\n url = 'http://localhost:8080/router/0000000000000003'\n payload = {'address': '192.168.100.20/24'}\n r = requests.post(url, data=json.dumps(payload))\n\n ## Set Default routes for routers\n\n # set s1 default route is s2\n url = 'http://localhost:8080/router/0000000000000001'\n payload = {'gateway': '172.16.30.1'}\n r = requests.post(url, data=json.dumps(payload))\n\n # set s2 default route is s1\n url = 'http://localhost:8080/router/0000000000000002'\n payload = {'gateway': '172.16.30.30'}\n r = requests.post(url, data=json.dumps(payload))\n\n # set s3 default route is s2\n url = 'http://localhost:8080/router/0000000000000003'\n payload = {'gateway': '192.168.10.1'}\n r = requests.post(url, data=json.dumps(payload))\n\n ###================ Set static routes for routers================================\n # For s2 router, set a static route to the host (192.168.30.0/24) under router s3\n url = 'http://localhost:8080/router/0000000000000002'\n payload = {'destination': '192.168.30.0/24', 'gateway': '192.168.10.20'}\n r = requests.post(url, data=json.dumps(payload))\n '''\n url = 'http://localhost:8080/router/0000000000000001'\n payload = {'destination': '192.168.30.0/24', 'gateway': '192.168.100.20' }\n r = requests.post(url, data=json.dumps(payload))\n\n '''\n c0.cmd('ovs-vsctl set port s3-eth4 trunk=20 vlan_mode=trunk')\n\n CLI(net)\n net.stop()\n\n\nif __name__ == '__main__':\n setLogLevel('info')\n myNetwork()\n","repo_name":"yusufaisal/mininet","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4944,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"11658085670","text":"import os\nimport glob\nimport musdb\nimport torch\n# import librosa\nimport argparse\nimport numpy as np\nfrom torch.utils import data\nfrom IPython.display import clear_output\n\nMUS_PERM_ID = np.array([ 6, 48, 10, 28, 43, 44, 5, 34, 9, 35, 31, 13, 33, 20, 8, 18, 17,\n 1, 38, 29, 16, 0, 24, 15, 47, 19, 36, 14, 12, 3, 7, 26, 39, 41,\n 37, 21, 27, 4, 23, 42, 32, 49, 2, 22, 30, 40, 25, 45, 11, 46])\nMUS_VALID_ID = MUS_PERM_ID[:25]\nMUS_EVAL_ID = MUS_PERM_ID[25:]\n\nclass MUSDB_data(data.Dataset):\n \n def __init__(self, dataset, n_src, with_silent):\n \n self.dataset = dataset\n if with_silent: \n self.path = '../Data/MUSDB/large_'\n else:\n self.path = '../Data/MUSDB/'\n config = torch.load(self.path + dataset + '/config.pt')\n self.global_max = 23.3 # max of test and train\n self.all_length = config['all_length']\n# if dataset == 'test':\n# self.all_length = np.array(self.all_length)[MUS_VALID_ID]\n self.n_src = n_src\n \n# self.index_list = {}\n# base = 0\n# for file_id in range(len(self.all_length)):\n# for local_id in range(self.all_length[file_id]):\n# self.index_list[local_id+base] = [file_id, local_id]\n# base += int(self.all_length[file_id])\n \n def __len__(self):\n \n if self.dataset == 'test':\n return len(self.all_length)//2\n else:\n return len(self.all_length)\n\n def __getitem__(self, idx):\n\n if self.dataset == 'test':\n idx = MUS_EVAL_ID[idx]\n file_path = self.path + self.dataset + '/mus_' + str(idx) + '.pt'\n else:\n file_path = self.path + self.dataset + '/mus_' + self.dataset + '_' + str(idx) + '.pt'\n sources = torch.load(file_path) # (n, srcs, L)\n N = len(sources)\n rand_id = int(torch.rand(1)*N)\n picked = sources[rand_id, :self.n_src, :] # (n_src, L)\n \n return picked/self.global_max\n \n\nclass Slakh_data(data.Dataset):\n \n def __init__(self, dataset, n_src):\n \n self.dataset = dataset\n self.path = '../Data/Slakh/' + dataset + '/'\n if n_src == 5:\n self.path = '../Data/Slakh/' + dataset + '_5/'\n config = torch.load(self.path + 'config.pt')\n self.global_max = 53.1 # max of test and train\n self.all_length = config['all_length']\n self.total_file = config['total_file']\n self.n_src = n_src\n self.data_length = len(self.all_length)\n if dataset == 'test':\n self.data_length = self.data_length//2\n self.file_idx = [i for i in range(self.data_length) if self.all_length[i] != 0]\n\n \n def __len__(self):\n return len(self.file_idx)\n\n def __getitem__(self, idx):\n \n f_idx = self.file_idx[idx]\n track_path = self.path + str(f_idx) + '.pt'\n sources = torch.load(track_path) # (n, 4, L)\n \n N = len(sources)\n rand_id = int(torch.rand(1)*N)\n# print(sources.shape)\n picked = sources[rand_id, :self.n_src, :] # (n_src, L)\n \n return picked/self.global_max\n \n\n# class MUSDB_eval(data.Dataset):\n \n# def __init__(self, dataset, n_src):\n \n \n \n \n# class Slakh_eval(data.Dataset):\n \n# def __init__(self, dataset, n_src):\n \n\n ","repo_name":"haiciyang/Remixing","sub_path":"src/datasets.py","file_name":"datasets.py","file_ext":"py","file_size_in_byte":3427,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"81"} +{"seq_id":"74237726346","text":"from django.conf.urls import url, include\nfrom django.conf.urls.static import static\nfrom django.contrib import admin\n\nfrom EnterpriseResourcePlanning import views, settings\n\nurlpatterns = [\n url(r'^$', views.home, name='home'),\n url(r'^update/', include('Update.urls')),\n url(r'^register/', include('Registration.urls')),\n url(r'^attendance/', include('Attendance.urls')),\n # url(r'^administrator/', include('administrator.urls')),\n url(r'^admin/', admin.site.urls),\n url(r'^login/', include('Login.urls')),\n url(r'^dashboard/', include('Dashboard.urls')),\n url(r'^timetable/', include('Timetable.urls')),\n url(r'^request/', include('Requests.urls')),\n url(r'^report/', include('Report.urls')),\n url(r'^general/', include('General.urls')),\n url(r'^exam/', include('Exam.urls')),\n url(r'^backup/', include('BackupRestore.urls')),\n url(r'^internship/', include('Internship.urls')),\n url(r'^feedback/', include('Feedback.urls'))\n # url(r'^research/', include('Research.urls')),\n # url(r'^update/', include('Update.urls'))\n\n]\nurlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)\nurlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)\n# urlpatterns += staticfiles_urlpatterns()\n","repo_name":"akzarma/EnterpriseResourcePlanning","sub_path":"EnterpriseResourcePlanning/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1276,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"27688790878","text":"from email import header\nimport logging\nfrom Katna.video import Video\nimport azure.functions as func\nimport timeit\nimport os\nimport asyncio\nimport aiohttp\n\ncompression_factor = 20 #should be set from 1-50\n\nasync def send_request(fname):\n url = 'http://localhost:7071/api/encrypt'\n with open('c_'+fname.split('.')[0]+\".mp4\",'rb') as f:\n async with aiohttp.ClientSession() as session:\n file = {'upload_file': f}\n async with session.post(url, data=file, params={'fname':fname}) as response:\n logging.info(response.text())\n return\n\ndef main(myblob: func.InputStream):\n logging.info(f\"Python blob trigger function processed blob \\n\"\n f\"Name: {myblob.name}\\n\"\n f\"Blob Size: {myblob.length} bytes\\n\"\n f\"funcs {dir(myblob)}\\n\")\n START = timeit.default_timer()\n\n content = myblob.read()\n fname = myblob.name.split('/')[-1]\n file = open(fname, 'wb+')\n vd = Video()\n file.write(content)\n file.close()\n vd.compress_video(file_path=fname, crf_parameter=compression_factor,out_file_name='c_'+fname.split('.')[0])\n end = timeit.default_timer()\n print(\"time:\",end-START)\n\n \n url = \"http://localhost:7071/api/encrypt\"\n #headers = {'Content-Type': 'application/octet-stream'}\n #headers=headers\n '''\n file = open('c_'+fname.split('.')[0]+\".mp4\",'rb')\n try:\n files = {'upload_file': file}\n response = requests.post(url, files=files)\n print(response.status_code)\n print(response.json())\n except Exception as e:\n print(e)\n file.close()\n '''\n asyncio.run(send_request(fname.split('.')[0]+\".mp4\"))\n\n os.remove(fname)\n os.remove('c_'+fname.split('.')[0]+\".mp4\")\n\n #.logging.info(f\"Content of the blob is {content}\")\n\n\n\n\n\n\n\n\n","repo_name":"harshithaputtaswamy/video-compression","sub_path":"source/Compress/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1822,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"17409797763","text":"list_1 = [\"Sunday\",\"Monday\",\"Tuesday\",\"Wednesday\",\"Thursday\",\"Friday\",\"Saturday\"]\n\ndays = input(\"Enter the days starting with : \")\ndate = int(input(\"Enter the date : \"))\n\ni = (date%7)-1 \n\nif days in list_1:\n j = list_1.index(days)+i\n if j >=7:\n j = j-7\n print(list_1[j])\nelse:\n print(\"Please enter the valid input\")","repo_name":"sai2yeshwanth/python_Coding","sub_path":"1-1-2022/day_name_two.py","file_name":"day_name_two.py","file_ext":"py","file_size_in_byte":336,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"18701455067","text":"# 프로그래머스 67259 경주로 건설\n# https://programmers.co.kr/learn/courses/30/lessons/67259\n\nfrom collections import deque\n\ndef solution(board):\n n = len(board)\n cost = [[[1e9] * n for _ in range(n)] for _ in range(4)] # 방향, 위치에 따른 비용 리스트\n dx, dy = [0, 1, 0, -1], [1, 0, -1, 0] # 동남서북\n queue = deque([])\n \n # 시작점 초기화\n for i in range(4):\n cost[i][0][0] = 0\n \n # 0행 1열 초기화\n if board[0][1] == 0:\n queue.append([0, 1, 0, 100])\n cost[0][0][1] = 100\n \n # 1행 0열 초기화\n if board[1][0] == 0:\n queue.append([1, 0, 1, 100])\n cost[1][1][0] = 100\n \n while queue:\n x, y, d, c = queue.popleft() # 위치, 방향, 비용\n for i in range(4):\n nx = x + dx[i]\n ny = y + dy[i]\n if 0 <= nx < n and 0 <= ny < n and not board[nx][ny]: # 이동 가능한 범위이며 빈칸인 경우\n new_cost = c + 100 if d == i else c + 600 # 다음 위치의 비용\n if cost[i][nx][ny] > new_cost: # 기존 다음 위치 비용보다 더 작다면 비용 갱신\n cost[i][nx][ny] = new_cost\n queue.append([nx, ny, i, new_cost]) \n \n return min([cost[i][-1][-1] for i in range(4)]) # 최소 비용","repo_name":"dev-dain/algorithm-study","sub_path":"source/soohyun/week10/A67259.py","file_name":"A67259.py","file_ext":"py","file_size_in_byte":1338,"program_lang":"python","lang":"ko","doc_type":"code","stars":5,"dataset":"github-code","pt":"81"} +{"seq_id":"22176927080","text":"from django.apps import AppConfig\nfrom iastatetheme.apps import IastatethemeConfig, MenuItem\n\nclass IsulimsThemeConfig(IastatethemeConfig):\n site_name = 'LIMS'\n menu = [\n MenuItem(\"Tables\", \"/\", [\n MenuItem(\"Accessions\", \"/accession\"),\n MenuItem(\"Plant\", \"/plant\"),\n MenuItem(\"Seed Packets\", \"/seedpacket\"),\n MenuItem(\"Projects\", \"/project\"),\n MenuItem(\"Samples\", \"/sample\"),\n MenuItem(\"Herbariums\", \"/herbarium\"),\n ]),\n MenuItem(\"Admin\", \"/admin\"),\n ]\n header_site_links_menu = []\n footer_social_media_menu = []\n\nclass LimsConfig(AppConfig):\n name = 'lims'\n","repo_name":"ResearchIT/isu_lims","sub_path":"lims/apps.py","file_name":"apps.py","file_ext":"py","file_size_in_byte":663,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"5912600573","text":"# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import, unicode_literals, print_function\n\nfrom rest_framework import serializers\nimport json\nimport base64\n\n\nclass HistoryGraphSerializer(serializers.Serializer):\n content = serializers.CharField()\n\n def validate_content(self, value):\n content = json.decode(value)\n if len(content) == 2:\n message = base64.b64decode(content['message'])\n signature = base64.b64decode(content['signature'])\n\n public_key = b64decode(self.request.user.public_key)\n public_key = rsa.PublicKey.load_pkcs1(public_key)\n\n if not rsa.verify(message, signature, public_key):\n raise serializers.ValidationError(\"User key does not match\")\n return value\n\n raise serializers.ValidationError(\"Incorrectly formatted request\")\n","repo_name":"mlockett42/spreadsheet-historygraph-cavorite","sub_path":"spreadsheet/historygraph_backend/api/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":856,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"81"} +{"seq_id":"39531736544","text":"#MAHDI ELHOUSNI, WPI 2020\n\nimport numpy as np\nimport cv2\nimport utils\nimport time\nimport matplotlib.pyplot as plt\n\nimport tensorflow as tf\n\nfrom tensorflow.keras import backend as K\nfrom tensorflow.keras.utils import *\nfrom tensorflow.keras.models import *\nfrom tensorflow.keras.layers import *\nfrom tensorflow.keras.callbacks import *\nfrom tensorflow.keras.applications.densenet import DenseNet121\n\nfrom nets import *\nfrom utils import *\nfrom tifffile import *\n\nimport sys\n\ndatasetName=sys.argv[1] #Vaihingen, DFC2018\nif(sys.argv[2]=='False'): correction=False\nelse: correction=True\n\ncropSize=320\n\npredCheckPointPath='./checkpoints/'+datasetName+'/mtl'\ncorrCheckPointPath='./checkpoints/'+datasetName+'/refinement'\n\nval_rgb, val_dsm, val_sem = collect_tilenames(\"val\",datasetName)\n\nNUM_VAL_IMAGES = len(val_rgb)\n\nprint(\"number of validation samples \" + str(NUM_VAL_IMAGES))\n\nbackboneNet=DenseNet121(weights='imagenet', include_top=False, input_tensor=Input(shape=(cropSize,cropSize,3)))\n\nnet = MTL(backboneNet, datasetName)\nnet.load_weights(predCheckPointPath)\n\nif(correction):\n autoencoder=Autoencoder()\n autoencoder.load_weights(corrCheckPointPath)\n\ntile_mse = 0\ntotal_mse = 0\n\ntile_rmse = 0\ntotal_rmse = 0\n\ntile_mae = 0\ntotal_mae = 0\n\ntile_time = 0\ntotal_time = 0\n\ntilesLen=len(val_rgb)\n\nfor tile in range(tilesLen):\n\n print(tile+1)\n\n rgb_data=[]\n dsm_data=[]\n\n coordinates=[]\n\n if(datasetName=='Vaihingen'):\n rgb_tile = np.array(Image.open(val_rgb[tile]))/255\n dsm_tile = np.array(Image.open(val_dsm[tile]))/255\n\n elif(datasetName=='DFC2018'):\n rgb_tile=np.array(Image.open(val_rgb[tile]))/255\n dsm_tile=np.array(Image.open(val_dsm[2*tile]))\n dem_tile=np.array(Image.open(val_dsm[2*tile+1]))\n dsm_tile=correctTile(dsm_tile)\n dem_tile=correctTile(dem_tile)\n dsm_tile=dsm_tile-dem_tile\n\n for x1, x2, y1, y2 in sliding_window(rgb_tile, step=int(cropSize/6), window_size=(cropSize,cropSize)):\n coordinates.append([y1,y2,x1,x2])\n rgb_data.append(rgb_tile[y1:y2, x1:x2, :])\n dsm_data.append(dsm_tile[y1:y2, x1:x2])\n\n pred = np.zeros([2,rgb_tile.shape[0],rgb_tile.shape[1]])\n prob_matrix = gaussian_kernel(rgb_tile.shape[0],rgb_tile.shape[1])\n\n start = time.time()\n for crop in range(len(rgb_data)):\n cropRGB=rgb_data[crop]\n cropDSM=dsm_data[crop]\n\n y1,y2,x1,x2=coordinates[crop]\n prob_matrix = gaussian_kernel(cropRGB.shape[0], cropRGB.shape[1])\n\n dsm_output, sem_output, norm_output = net.call(cropRGB[np.newaxis,...], training=False)\n\n if(correction):\n correctionInput = tf.concat([dsm_output, norm_output, sem_output, cropRGB[np.newaxis,...]], axis=-1)\n noise=autoencoder.call(correctionInput, training=False)\n dsm_output_copy = dsm_output.numpy().squeeze().copy()\n dsm_output = dsm_output-noise\n\n dsm_output = dsm_output.numpy().squeeze()\n\n pred[0,y1:y2,x1:x2] += np.multiply(dsm_output, prob_matrix)\n pred[1,y1:y2,x1:x2] += prob_matrix\n\n end = time.time()\n gaussian = pred[1]\n pred = np.divide(pred[0], gaussian)\n\n if(datasetName=='DFC2018'): dsm_tile=dsm_tile[0:pred.shape[0],0:pred.shape[1]]\n\n tile_mse = np.mean((pred-dsm_tile)**2)\n total_mse+= tile_mse\n print(\"Tile MSE : \" + str(tile_mse))\n\n tile_mae = np.mean(np.abs(pred-dsm_tile))\n total_mae+= tile_mae\n print(\"Tile MAE : \" + str(tile_mae))\n\n tile_rmse = np.sqrt(np.mean((pred-dsm_tile)**2))\n total_rmse+= tile_rmse\n print(\"Tile RMSE : \" + str(tile_rmse))\n\n tile_time = end - start\n total_time+= tile_time\n print(\"Tile time : \" + str(tile_time))\n \n filename=val_rgb[tile].split('/')[-1].split('.')[0]\n pred = Image.fromarray(pred)\n pred.save('./output/'+datasetName+'/'+filename+'.tif')\n\nprint(\"Final MSE loss : \" + str(total_mse/tilesLen))\nprint(\"Final MAE loss : \" + str(total_mae/tilesLen))\nprint(\"Final RMSE loss : \" + str(total_rmse/tilesLen))\n\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"melhousni/DSMNet","sub_path":"test_dsm.py","file_name":"test_dsm.py","file_ext":"py","file_size_in_byte":3848,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"81"} +{"seq_id":"12562312850","text":"import streamlit as st\nimport tensorflow as tf\nimport streamlit as st\nimport numpy as np\nimport pandas as pd\nimport string, os\nimport nltk\nimport re\n# import keras\nimport random\nimport io\nfrom keras.utils import np_utils\nfrom keras.models import Sequential\nfrom keras.layers import LSTM, Dense, Dropout\nfrom keras.optimizers import Adamax\nimport sys\nfrom PIL import Image\nfrom wordcloud import WordCloud, STOPWORDS, ImageColorGenerator\nfrom PIL import Image, ImageDraw, ImageFont\nfrom PIL import Image\n# Image = Image.open('Lyrics3.jpg')\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\nst.set_page_config(page_title=\"Lyrics_generator\",page_icon=\":notes:\", layout=\"wide\")\n\n# ## loading data\n\ndata = pd.read_csv(\"/Users/giridharana.r/Desktop/DP_1/Songs.csv\")\n### ----------\n#Lining up all the lyrics to create corpus\nCorpus =''\nfor listitem in data.Lyrics:\n Corpus += listitem\n \nCorpus = Corpus.lower() #converting all alphabets to lowecase \n\n# ### ----------\n# #Keeping only a limited set of characters. \nto_remove = ['{', '}', '~', '©', 'à', 'á', 'ã', 'ä', 'ç', 'è', 'é', 'ê', 'ë', 'í', 'ñ', 'ó', 'ö', 'ü', 'ŏ',\n 'е', 'ا', 'س', 'ل', 'م', 'و', '\\u2005', '\\u200a', '\\u200b', '–', '—', '‘', '’', '‚', '“', '”', \n '…', '\\u205f', '\\ufeff', '!', '&', '(', ')', '*', '-', '/', ]\nfor symbol in to_remove:\n Corpus = Corpus.replace(symbol,\" \")\n\n# ### ------------\n# # Storing all the unique characters present in my corpus to build a mapping dic. \nsymb = sorted(list(set(Corpus)))\n\nL_corpus = len(Corpus) #length of corpus\nL_symb = len(symb) #length of total unique characters\n\n#Building dictionary to access the vocabulary from indices and vice versa\nmapping = dict((c, i) for i, c in enumerate(symb))\nreverse_mapping = dict((i, c) for i, c in enumerate(symb))\n\n#---------------\n#Splitting the Corpus in equal length of strings and output target\nlength = 40\nfeatures = []\ntargets = []\nfor i in range(0, L_corpus - length, 1):\n feature = Corpus[i:i + length]\n target = Corpus[i + length]\n features.append([mapping[j] for j in feature])\n targets.append(mapping[target])\n\nL_datapoints = len(targets)\n# # print(\"Total number of sequences in the Corpus:\", L_datapoints)\n\n#--------------- Loading models 1----------------------------------------\n\n# model_1=tf.keras.models.load_model('/Users/giridharana.r/Desktop/DP_1/Models/my_gru_model_1.h5')\n# model_2=tf.keras.models.load_model('/Users/giridharana.r/Desktop/DP_1/Models/Double_LSTM_updated_1.h5')\n# model_3=tf.keras.models.load_model('/Users/giridharana.r/Desktop/DP_1/Models/Bidirectional_model.h5')\n# @st.cache(allow_output_mutation=True)\n# def load_model1():\n\n # return model1\n# with st.spinner('Model is being loaded..'):\n# model1=load_model1()\n#--------------- Loading models 2----------------------------------------\n\n# def load_model2():\n\n# return model2\n# with st.spinner('Model is being loaded..'):\n# model2=load_model2()\n\n#--------------- Loading models 3----------------------------------------\n# def load_model3():\n\n# return model3\n# with st.spinner('Model is being loaded..'):\n# model3=load_model3()\nst.markdown(\"

Lyrics Generator Application

\", unsafe_allow_html=True)\n# st.image(image=Image)\nselected_model = st.selectbox(\"Select the model to be implemented\",options = [\"GRU\",\"Double_LSTM\",\"Bidirectional_LSTM\",\"Bidirectional_LSTM_GRU\"])\n# @st.cache\nif selected_model == \"DOUBLE_LSTM\":\n model = tf.keras.models.load_model('/Users/giridharana.r/Desktop/DP_1/New app/Final_LSTM_2_model.h5')\nif selected_model == \"Double_GRU\":\n model = tf.keras.models.load_model('/Users/giridharana.r/Desktop/DP_1/New app/')\nif selected_model == \"Bidirectional_LSTM_GRU\":\n model = tf.keras.models.load_model('/Users/giridharana.r/Desktop/DP_1/Models/Bidirectional_LSTM_GRU_model_updated.h5')\nelse:\n model = tf.keras.models.load_model('/Users/giridharana.r/Desktop/DP_1/Models/Bidirectional_model.h5')\n\nst.write(\"The selected model is\",selected_model)\n\n#--------------- Creating the lyrics generator----------------------------------------\n\ninput = st.text_input(label=\"Write the lyrics\",value =\"Whats up baby doll how are you doing, I \",placeholder=\"Write the lyrics\")\ninput = input.lower()\nchar_count = int(st.text_input(label=\"Character_count\",value = \"100\",placeholder=\"Number of characters to be present\"))\n# st.write(\"The selected model is\",type(model))\n\n#--------------- Lyrics Generator 1----------------------------------------\n\ndef Lyrics_Generator(starter,Ch_count): #,temperature=1.0):\n generated= \"\"\n starter = starter \n seed=[mapping[char] for char in starter]\n generated += starter \n # Generating new text of given length\n for i in range(Ch_count):\n seed=[mapping[char] for char in starter]\n x_pred = np.reshape(seed, (1, len(seed), 1))\n x_pred = x_pred/ float(L_symb)\n prediction = model.predict(x_pred, verbose=0)[0] \n # Getting the index of the next most probable index\n prediction = np.asarray(prediction).astype('float64')\n prediction = np.log(prediction) / 1.0 \n exp_preds = np.exp(prediction)\n prediction = exp_preds / np.sum(exp_preds)\n probas = np.random.multinomial(1, prediction, 1)\n index = np.argmax(prediction)\n next_char = reverse_mapping[index] \n # Generating new text\n generated += next_char\n starter = starter[1:] + next_char\n \n return generated\n\n#--------------- Lyrics Generator 2----------------------------------------\nst.write(\"Generated Lyrics are:\")\nst.write(Lyrics_Generator(starter=input,Ch_count = char_count))\n#--------------- Lyrics Generator 2----------------------------------------\n# new = print(Lyrics_Generator(starter=input,Ch_count=100))\n\n# st.button(label=\"Load Model\",on_click=load_model)\n# st.button(label=\"Generate\",on_click=Lyrics_Generator(input,100))\n## -----\n# # #Generating a song from the model\n# song_1 = Lyrics_Generator(input,100)\n#Let's have a look at the song\n# st.write(Lyrics_Generator(input,100))\n\n\n\n### Saved prompt\n### Whats up baby doll how are you doing,I a\n\n\n#### Bi directional LSTM\n\n### the shoe shrunk, and the school belt got\n\n# GRU output\n# whats up baby doll how are you doing i am in the summer of the street i wanna be your end on my baby i know i need you in the same of your life i can't take it all the way i know i can't help you i know i'm gonna be a long, long time i want\n\n","repo_name":"syamrt/Generating-Lyrics-Using-Deep-Learning-Techniques","sub_path":"App/New_app.py","file_name":"New_app.py","file_ext":"py","file_size_in_byte":6482,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"72256324426","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sat Dic 12 10:45:15 2020\r\n\r\n@author: Ayax\r\n\"\"\"\r\n\r\nimport random\r\n\r\nmodelEnd = [6,18,1,6,20,22,28,15,5,19] \r\nlargeIndividual = 10 \r\n\r\nnum = 5 #Cantidad de individuos\r\ngeneration = 300 #Generaciones\r\npressure = 3 #individual>2\r\nmutation_chance = 0.2\r\n\r\ndef individual(min, max):\r\n return[random.randint(min, max) for i in range(largeIndividual)]\r\n\r\ndef newPopulation():\r\n return [individual(0,50) for i in range(num)]\r\n\r\n# Funcion la que se debe cambiar en funcion a f(x)\r\ndef functionType(individual):\r\n fitness = 0\r\n for i in range(len(individual)):\r\n if individual[i] == modelEnd[i]:\r\n fitness += 1\r\n return fitness\r\n\r\ndef selection_and_reproduction(population):\r\n evaluating = [ (functionType(i), i) for i in population]\r\n print(\"eval\",evaluating)\r\n evaluating = [i[1] for i in sorted(evaluating)]\r\n print(\"eval\",evaluating)\r\n population = evaluating\r\n selected = evaluating[(len(evaluating)-pressure):]\r\n for i in range(len(population)-pressure):\r\n pointChange = random.randint(1,largeIndividual-1)\r\n father = random.sample(selected, 2)\r\n population[i][:pointChange] = father[0][:pointChange]\r\n population[i][pointChange:] = father[1][pointChange:]\r\n return population\r\n\r\ndef mutation(population):\r\n for i in range(len(population)-pressure):\r\n if random.random() <= mutation_chance: \r\n pointChange = random.randint(1,largeIndividual-1) \r\n new_val = random.randint(0,9) \r\n while new_val == population[i][pointChange]:\r\n new_val = random.randint(0,9)\r\n population[i][pointChange] = new_val\r\n return population\r\n\r\ndef funciony(data):\r\n copy = []\r\n for elem in data:\r\n newdata = []\r\n for x in elem:\r\n y = (x*x*x)+(x*x)+x\r\n newdata.append(y)\r\n copy.append(newdata)\r\n return copy\r\n\r\n# Principal\r\nmodelEnd.sort()\r\nmodelEnd.reverse()\r\nprint('Inicial: ', modelEnd)\r\nprint('Generaciones', generation)\r\npopulation = newPopulation()\r\n# Ordenamos descendentemente los elementos\r\nfor p in population:\r\n p.sort()\r\n p.reverse()\r\nprint(\"\\nInicio de la población:\\n%s\"%(population))\r\npopulation = selection_and_reproduction(population)\r\nprint(\"\\nCruce:\\n%s\"%(population))\r\ny = funciony(population)\r\nprint(\"\\nFuncion y:\\n%s\" % (y))\r\npopulation = mutation(population)\r\nprint(\"\\nMutación:\\n%s\"%(population))\r\n","repo_name":"Ayax310/INF-354-Segundo-Parcial","sub_path":"Problema2/Problema2.py","file_name":"Problema2.py","file_ext":"py","file_size_in_byte":2450,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"8221981887","text":"import openpyxl\nimport os\n\ndef main():\n # Insert the file of the spreadsheet you want to change here\n fileName = 'November2019Transactions.xlsx'\n\n # Make sure to go into the Excel sheet and change the sheet name to transactions prior to running the program\n # Sheet name you would like to change\n sheetName = 'transactions'\n # Load the workbook\n wb = openpyxl.load_workbook(fileName)\n \n # Access the sheet in the workbook\n transactionsWorksheet = wb[sheetName]\n\n # If E1 is tags, then delete column 5\n delete_tags_column(transactionsWorksheet)\n wb.save(fileName)\n\n\n fixDoublePayments(transactionsWorksheet)\n wb.save(fileName)\n \n organizeExpenses(transactionsWorksheet)\n\n\ndef delete_tags_column(transactionsWorksheet):\n tagsValue = transactionsWorksheet['E1'].value\n if (tagsValue == 'Tags'):\n transactionsWorksheet.delete_cols(5)\n\ndef organizeExpenses(transactionsWorksheet):\n # Maximum row of the sheet\n maxRow = transactionsWorksheet.max_row\n\n # Declare empty dictionary to store category as key and total expense as value\n transactionCategories = {}\n \n # Iterate over each row to obtain category and transition\n for i in range(2, maxRow + 1):\n category = transactionsWorksheet.cell(row=i, column=4).value\n transaction = transactionsWorksheet.cell(row = i, column=5).value\n\n # If category exists, add the transaction to the total expense\n if category in transactionCategories:\n transactionCategories[category] += transaction\n # If category does not, make a new one and set it to the first transaction that appears\n elif category not in transactionCategories:\n transactionCategories[category] = transaction\n \n for key in transactionCategories:\n print(key, '$', round(transactionCategories[key], 2))\n \ndef fixDoublePayments(incomeExpensesSheet):\n maxRow = incomeExpensesSheet.max_row\n\n for i in range(2, maxRow + 1):\n if (str(incomeExpensesSheet.cell(row=i, column= 4).value) == \"Credit Card Payments\") or (str(incomeExpensesSheet.cell(row=i, column= 3).value) == \"Transfer\" and str(incomeExpensesSheet.cell(row=i, column= 2).value) == \"Trs Plan 3 - Self\") or (incomeExpensesSheet.cell(row=i, column= 3).value == \"Reinvestment Fidelity 500 Index Fund\"):\n cellValue = ('E' + str(i))\n incomeExpensesSheet[cellValue] = 0\n transactionValue = 0\n\nif __name__ == \"__main__\":\n main()\n\n","repo_name":"betty-van/ExpensesTracker","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2492,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"37705643406","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n'''\n本文档主要用于特征衍生,输入原始数据路径,输出csv特征数据\n'''\nimport sys\nfrom .data_ana import *\nimport pandas as pd\nimport numpy as np\nimport pickle\n\nclass DataFeature(object):\n \"\"\"\n 提供各类数据衍生工具\n basci_info_feature:合并客户信息表、客户风险表、资产信息表\n \"\"\"\n\n def __init__(self, path, train=True):\n self.path = path\n self.train = train\n\n def train_or_test(self):\n if self.train==True:\n filename='x_train'\n else:\n filename='x_test'\n return(filename) \n\n def get_head_table(self):\n filename=self.train_or_test()\n self.myDataAna = DataAna(filename=filename,path=self.path) \n result = self.myDataAna.load_data()\n result.columns = ['id','core_cust_id','prod_code','prod_type','trade_date']\n return(result) \n\n def basci_info_feature(self,name_list=['d','e','f']):\n \"\"\"\n 合并客户信息表、客户风险表、资产信息表,返回df数据集并存储到features目录 \n\n Parameters\n ----------\n name_list : 文件名list,默认是['d','e','f']\n 需要加载的文件名 \n\n Returns\n -------\n DataFrame\n 返回一个df格式数据集,存储在path的features位置 \n \"\"\"\n result = self.get_head_table()\n for i in name_list:\n self.myDataAna.filename=i\n df = self.myDataAna.load_data()\n result = result.merge(self.myDataAna.load_data(),on='core_cust_id')\n \n #去重\n result[['f'+str(x) for x in range(2, 22)]] = result[['f'+str(x) for x in range(2, 22)]].applymap(lambda x: str(x).replace(',', ''))\n result[['f'+str(x) for x in range(2, 22)]] = result[['f'+str(x) for x in range(2, 22)]].astype('float')\n result['f22'] = pd.to_datetime(result['f22'],format='%Y%m%d')\n result['dff'] = (abs(pd.to_datetime(result['trade_date'])-result['f22'])/pd.Timedelta(1, 'D')).fillna(0).astype(int)\n result['rank'] = result['dff'].groupby(result['id']).rank()\n result = result[result['rank']==1]\n result = result[[ i for i in result.columns if i not in ['core_cust_id','prod_code','prod_type','trade_date','e2','f1','f22','dff','rank']]]\n result = result.fillna(-999)\n filename=self.train_or_test()\n pickle.dump(result, open(os.path.join(self.path, 'features', filename[2:100], 'feature_basic.pkl'), 'wb'))\n print(\"===================>basic info feature merge success\")\n\n def prod_type(self):\n \"\"\"\n 按照产品code类型,返回A、B、C、D标签\n\n Parameters\n ----------\n None \n\n Returns\n -------\n DataFrame\n 返回一个df格式数据集 \n \"\"\"\n self.myDataAna = DataAna(filename=None,path=self.path)\n name = ['A','B','C','D']\n ls = ['g','h','i','j']\n result = pd.DataFrame()\n\n for i in ls:\n self.myDataAna.filename=i\n df = self.myDataAna.load_data()\n df['type'] = name[ls.index(i)]\n result = result.append(df[['prod_code','type']])\n return(result)\n\n def app_info_df(self):\n \"\"\"\n 拼接训练样本及APP信息,返回不同样本在交易日之前的APP点击明细信息(df)\n\n Parameters\n ----------\n None \n\n Returns\n -------\n DataFrame\n 返回一个df格式数据集 \n \"\"\"\n self.myDataAna = DataAna(filename='r',path=self.path)\n app_df = self.myDataAna.load_data()\n app_info = self.prod_type()\n app_df = app_df.merge(app_info,on='prod_code',how='left')\n app_df['type'] = app_df['type'].fillna('other')\n \n head_table = self.get_head_table()\n df = head_table.merge(app_df[['core_cust_id','r3','type','r5']],on='core_cust_id')\n df['trade_date'] = pd.to_datetime(df['trade_date'])\n df['r5'] = pd.to_datetime(df['r5'])\n df = df[df['trade_date']>=df['r5']]\n return(df)\n\n def app_info_feature(self,time_dff_list=[1]):\n df = self.app_info_df()\n result = df[['id']].drop_duplicates()\n for time_dff in time_dff_list:\n print('==================>begin run time_dff:{}'.format(time_dff))\n mydf = df[df['trade_date'] - pd.Timedelta(days=time_dff)>=df['r5']]\n mydf['all'] = 1\n mydf['r3_1'] = np.where(mydf['r3']==1,1,0)\n mydf['type_a'] = np.where(mydf['type']=='A',1,0)\n mydf['type_b'] = np.where(mydf['type']=='B',1,0)\n mydf['type_c'] = np.where(mydf['type']=='C',1,0)\n mydf['type_d'] = np.where(mydf['type']=='D',1,0)\n mydf['hour'] = mydf['r5'].astype(str).str[11:13].astype(int)\n mydf['r5_0_6'] = np.where( mydf['hour']<=5,1,0)\n mydf['r5_6_11'] = np.where((mydf['hour']>=6) & (mydf['hour']<=11),1,0)\n mydf['r5_12_17'] = np.where((mydf['hour']>=12) & (mydf['hour']<=17),1,0)\n mydf['r5_18_23'] = np.where((mydf['hour']>=18) & (mydf['hour']<=23),1,0)\n result_new = pd.DataFrame(mydf.groupby('id')[['all','r3_1','type_a','type_b','type_c','type_d','r5_0_6','r5_6_11','r5_12_17','r5_18_23']].sum())\n result_new=result_new.reset_index()\n result_new.columns = ['id']+['feature_app_dtedff_'+str(time_dff)+'_'+i for i in result_new.columns if i != 'id']\n result = result.merge(result_new,on='id',how='left')\n \n result = result.fillna(-999)\n filename=self.train_or_test()\n pickle.dump(result, open(os.path.join(self.path, 'features', filename[2:100], 'feature_app.pkl'), 'wb'))\n print(\"===================>app info feature merge success\")\n\n\nif __name__ == '__main__':\n import config\n # path = '/Users/jiangdehao/Desktop/project/kaggle/data/A榜数据/'\n path = config.data_o_dir+'/'\n print(path)\n myDataFeature = DataFeature(path)\n myDataFeature.basci_info_feature()\n # myDataFeature.app_info_feature(time_dff_list=[3,7,15,30,90,180,360])\n # data = pd.read_csv('/Users/jiangdehao/Desktop/project/kaggle/data/A榜数据/features/train_feature_basci.csv')\n\n\n","repo_name":"XiaoweiXiang/xm_banker","sub_path":"library/data_feature.py","file_name":"data_feature.py","file_ext":"py","file_size_in_byte":6318,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"41690835456","text":"# -*- coding: utf-8 -*-\n\"\"\"\nSpyder Editor\n\nThis is a temporary script file.\n批量处理\n* 自动编号文件名和目录\n* 自动定位保存位置\n* 目录使用绝对路径\n\"\"\"\nimport pyautogui\nimport time\nimport numpy as np\nimport os\n# 设置算例目录,预设T,H,和W的分布规律和组合方式来形成文件名\nT = np.linspace(2, 8, 5)\nprint(T)\nH = np.linspace(2, 8, 5)\nprint(H)\nW = np.linspace(2, 8, 5)\ndir_tmp =np.zeros(len(T))\nprint(W)\n#dir_tmp = os.listdir(pathname)\nfor j in range(T):\n dir_tmp[j] = 'H_'+str(H[j])+'T_'+str(T[j])\n os.makedirs(dir_tmp[j])\n#screenWidth, screenHeight = pyautogui.size()\n#mouseX, mouseY = pyautogui.position()\n\n pyautogui.PAUSE = 1.5 # 每个函数执行后停顿1.5秒\n pyautogui.FAILSAFE = True # 鼠标移到左上角会触发FailSafeException,因此快速移动鼠标到左上角也可以停止\n\n w, h = pyautogui.size()\n times = 2\n\n #pyautogui.moveTo(w/2, h/2) # 基本移动\n #pyautogui.moveTo(100, 200, duration=2) # 移动过程持续2s完成\n #pyautogui.moveTo(202, 178) # 移动到指定位置\n #pyautogui.moveTo(None, 500) # X方向不变,Y方向移动到500\n #pyautogui.moveRel(-40, 500) # 相对位置移动\n for i in range(times):\n pyautogui.click(202, 178, button='left') # 包含了move的点击,右键\n pyautogui.click(445,313,clicks=2, interval=0.25) # 双击,间隔0.25s\n\n\n # here the img should be a small piece of the screen. larger screenshot can be time consuming.\n # will be quiet slow\n # 另一个是问题是注意当切换回脚本界面运行时的有时候和程序运行中弹出窗口是有区别的。可以采用外部截图命令。\n # 同时,直截图中不变化和有典型特征的一个小小的片段。\n #im2 = pyautogui.screenshot('my_screenshot.png',region=(622,377,101,46))\n\n #print(pyautogui.locateOnScreen('my_screenshot.png'))\n\n time.sleep(18000) # adjust this time to sleep enough or near to the processing time\n # then tragg the while judgment statement, this would save energy and avoid memory overflow\n\n tmpLock = str('None')\n\n while tmpLock=='None':\n tmpLock= str(pyautogui.locateOnScreen('my_screenshot.png',grayscale='True')) #换到其他电脑中需要重新截图图片\n #time.sleep(40)\n pyautogui.press('down')\n pyautogui.press('enter')\n pyautogui.typewrite(r'E:\\\\' + dir_tmp[j]+'_FUN'+'\\\\waveBW.txt') # 此处注意目录的转义字符的设置可能有问题\n pyautogui.press('enter')\n time.sleep(5)\n pyautogui.hotkey('ctrl','s')\n time.sleep(5)\n pyautogui.typewrite('E:\\\\'+dir_tmp[j]+'\\\\'+dir_tmp[j])\n pyautogui.press('enter')\n time.sleep(5) # this time will also need automatic judgment\n pyautogui.press('enter')\n time.sleep(5)\n pyautogui.press('enter')\n # shut_buttonx, shut_buttony = pyautogui.locateOnScreen('shut_button.png',grayscale='Ture')\n # pyautogui.click(shut_buttonx, shut_buttony)\n pyautogui.click(1258,155) # click the close button on the right upper corner\n pyautogui.press('right')\n pyautogui.press('enter')\n time.sleep(1)\n\n ","repo_name":"maoyanjun/myCode","sub_path":"Python/Mike21Process/pyautogui_MikerData-v0.py","file_name":"pyautogui_MikerData-v0.py","file_ext":"py","file_size_in_byte":3254,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"81"} +{"seq_id":"39134641262","text":"from flask import request\nfrom functools import wraps\nfrom flask_login import current_app\n\n__author__ = \"Antti Kallonen\"\n__copyright__ = \"Copyright 2015, Tampere University of Technology\"\n__version__ = \"0.1\"\n__email__ = \"antti.kallonen@tut.fi\"\n\ndef get_client_ip():\n headers_list = request.headers.getlist(\"X-Forwarded-For\")\n client_ip = headers_list[0] if headers_list else request.remote_addr\n return client_ip\n","repo_name":"anttikallonen/dataportal","sub_path":"flask_application/utils/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":422,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"37554317373","text":"import hashlib\nfrom typing import Optional\n\nfrom flask import Response, Request\n\nauth_cookie_name = 'treachery_user'\n\n\ndef set_player_id(response: Response, player_id: int):\n hash_val = __hash_text(str(player_id))\n val = \"{}:{}\".format(player_id, hash_val)\n response.set_cookie(auth_cookie_name, val)\n\n\ndef __hash_text(text: str) -> str:\n text = 'mtg__' + text + '__treachery'\n return hashlib.sha512(text.encode('utf-8')).hexdigest()\n\n\ndef get_player_id_via_cookie(request: Request) -> Optional[int]:\n if auth_cookie_name not in request.cookies:\n return None\n\n val = request.cookies[auth_cookie_name]\n parts = val.split(':')\n if len(parts) != 2:\n return None\n\n user_id = parts[0]\n hash_val = parts[1]\n hash_val_check = __hash_text(user_id)\n if hash_val != hash_val_check:\n print(\"Warning: Hash mismatch, invalid cookie value\")\n return None\n\n try:\n return int(user_id)\n except ValueError:\n return None\n","repo_name":"Inderpreet-D/TreacheryApp","sub_path":"services/cookie_service.py","file_name":"cookie_service.py","file_ext":"py","file_size_in_byte":988,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"81"} +{"seq_id":"33535183076","text":"from django.core.management.base import BaseCommand\nfrom tests.factories import BusFactory, BusStopFactory\nfrom bus_operator.models import BusOperatorProfile\n\n\nclass Command(BaseCommand):\n help = 'Generate Random Bus Data and store in DB'\n\n def add_arguments(self, parser):\n parser.add_argument('count', type=int, help='Indicates the number of objects to be created')\n\n def handle(self, *args, **kwargs):\n count = kwargs['count']\n print(count)\n operator = BusOperatorProfile.objects.last()\n buses = BusFactory.create_batch(count, operator=operator)\n for bus in buses:\n stops = BusStopFactory.create_batch(10, bus=bus)\n BusStopFactory.reset_sequence(0)\n\n print(\"Done!\")\n ","repo_name":"smitpatelpro/bus-ticketing-drf","sub_path":"common/management/commands/load_bus_data.py","file_name":"load_bus_data.py","file_ext":"py","file_size_in_byte":757,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"18319585350","text":"# Classe de Desempenho do MDO 2023\r\n\r\nimport math as m\r\nimport matplotlib.pyplot as plt\r\nfrom classe_curvas import curvas\r\n\r\nclass desempenho:\r\n\r\n def __init__(self, g, mu, K, Clmax, Cdmin, hw, bw, Sw, rho, prop):\r\n self.g = g\r\n self.mu = mu\r\n self.K = K\r\n self.Clmax = Clmax\r\n self.Cdmin = Cdmin\r\n self.hw = hw\r\n self.bw = bw\r\n self.Sw = Sw\r\n self.rho = rho\r\n self.prop = prop\r\n self.Mtow = desempenho.mtow(self)\r\n self.W = self.Mtow*self.g\r\n pass\r\n\r\n def vel_estol(self): # Velocidade na qual a aeronave entra em 'stall'\r\n return m.sqrt((2*(self.W))/(self.rho*self.Sw*self.Clmax))\r\n \r\n def vel_liftoff(self): # Velocidade estimada para decolagem \"Vlof\" (ANDERSON, 2015)\r\n return 1.2*desempenho.vel_estol(self)\r\n\r\n def vel_liftoff_070(self): # Velocidade ideal estimada para a subida \"Vlof/raiz(2)\"\r\n return (desempenho.vel_liftoff(self))/m.sqrt(2)\r\n\r\n def vel_aprroch(self): # Velocidade com que a aeronave se aproxima da pista de pouso (FAR Part-23)\r\n return 1.3*desempenho.vel_estol(self)\r\n\r\n def vel_landing(self): # Velocidade ideal estimada durante o pouso \"Vappr/raiz(2)\"\r\n return (desempenho.vel_aprroch(self)/m.sqrt(2))\r\n\r\n def vel_max_alcance(self): # Velocidade de máximo alcance, tração mínima requerida ou de máxima eficiência aerodinâmica\r\n return ((2*(self.W)/(self.rho*self.Sw))**0.5)*(((self.K)/self.Cdmin)**0.25)\r\n\r\n def vel_max_autonomia(self): # Velocidade de máxima autonomia ou de potência requerida mínima \r\n return ((2*(self.W)/(self.rho*self.Sw))**0.5)*(((self.K)/(3*self.Cdmin))**0.25)\r\n\r\n def Cl_ideal(self):\r\n efeito_solo = ((16*self.hw/self.bw)**2)/((1+(16*self.hw/self.bw)**2)) # Efeito solo durante a decolagem e o pouso\r\n return self.mu/(2*efeito_solo*self.K)\r\n\r\n def Cd_ideal(self):\r\n efeito_solo = ((16*self.hw/self.bw)**2)/((1+(16*self.hw/self.bw)**2)) # Efeito solo durante a decolagem e o pouso\r\n return self.Cdmin + efeito_solo*self.K*(desempenho.Cl_ideal(self)**2)\r\n\r\n def ponto_projeto(self):\r\n Cl_asterix = m.sqrt(self.Cdmin/self.K) # Coef. de sustentação que maximiza a eficiência aerodinâmica - ou o alcance, (Cl*)\r\n #Cl_asterix = m.sqrt((3*self.Cdmin)/self.K) # Coef. de sustentação que permite planeio com máxima autonomia (Cl*)\r\n #Cd_asterix = self.Cdmin + self.K*Cl_asterix**2 # Coef. de arrasto para o ponto de projeto [Equivale ao \"(2*self.Cdmin)\"]\r\n E_max = Cl_asterix/(2*self.Cdmin) # Eficiência aerodinâmica máxima também escrito como (L/D)max\r\n return E_max\r\n\r\n def decolagem(self):\r\n T_Vlof_r2 = curvas.tracao(self, desempenho.vel_liftoff_070(self)) # Tração estimada na velocidade da norma aeronáutica\r\n D_Vlof_r2 = 0.5*self.rho*((desempenho.vel_liftoff_070(self))**2)*self.Sw*desempenho.Cd_ideal(self)\r\n L_Vlof_r2 = 0.5*self.rho*((desempenho.vel_liftoff_070(self))**2)*self.Sw*desempenho.Cl_ideal(self)\r\n ac_media = (1/self.Mtow)*(T_Vlof_r2-D_Vlof_r2-self.mu*((self.W)-L_Vlof_r2))\r\n Sg = (1.44*(self.W)**2)/(self.g*self.rho*self.Sw*self.Clmax*(T_Vlof_r2-D_Vlof_r2-self.mu*((self.W)-L_Vlof_r2)))\r\n t_Sg = m.sqrt(2*Sg/ac_media)\r\n return ac_media, Sg, t_Sg\r\n\r\n def subida(self, V):\r\n v = 0.01\r\n rate_climb = [] # Cria uma lista que irá conter a razão de subida em cada velocidade de V = 0 até V = 40 m/s\r\n while v <= 40:\r\n rate_climb.append(curvas.razao_subida(self, v)) # Guarda os valores de R/C em rate_climb\r\n v += 0.01 # Diferencial que funciona como contador\r\n max_rate_c = max(rate_climb) # Pega a maior razão de subida (R/C_max) em m/s\r\n vel_h = (rate_climb.index(max_rate_c)+1)*0.01 # Pega a velocidade da aeronave durante o R/C_max\r\n # print(rate_climb)\r\n #print(vel_h, max_rate_c, m.pi,) # Testa os valores\r\n max_ang_subida = m.asin(max_rate_c/vel_h)*(180/m.pi) # Calcula o ângulo de subida para o R/C_max em graus\r\n rate_c = curvas.razao_subida(self, V) # Calcula a razão de subida para um dado 'V' em m/s\r\n ang_subida = m.asin(curvas.razao_subida(self, V)/V)*(180/m.pi) # Calcula o ângulo de subida para um dado 'V' em graus\r\n return max_rate_c, vel_h, max_ang_subida, rate_c, ang_subida\r\n\r\n #def cruzeiro():\r\n\r\n def pouso(self):\r\n D_Vland = 0.5*self.rho*((desempenho.vel_landing(self))**2)*self.Sw*desempenho.Cd_ideal(self)\r\n L_Vland = 0.5*self.rho*((desempenho.vel_landing(self))**2)*self.Sw*desempenho.Cl_ideal(self)\r\n Sland_FAR = (1.69*(self.W)**2)/(self.g*self.rho*self.Sw*self.Clmax*(D_Vland+self.mu*((self.W)-L_Vland)))\r\n D_Vstall = 0.5*self.rho*((desempenho.vel_estol(self)/m.sqrt(2))**2)*self.Sw*desempenho.Cd_ideal(self)\r\n L_Vstall = 0.5*self.rho*((desempenho.vel_estol(self)/m.sqrt(2))**2)*self.Sw*desempenho.Cl_ideal(self)\r\n Sland_real = ((self.W)**2)/(self.g*self.rho*self.Sw*self.Clmax*(D_Vstall+self.mu*((self.W)-L_Vstall)))\r\n ang_planeio = m.atan(1/desempenho.ponto_projeto(self))*(180/m.pi) # Calcula o ângulo de planeio para (L/D)max em graus\r\n vel_planeio = m.sqrt((2*self.W*m.cos(ang_planeio*m.pi/180))/(self.rho*self.Sw*desempenho.Cl_ideal(self)))\r\n return Sland_FAR, Sland_real, ang_planeio, vel_planeio\r\n\r\n #def envelope_de_voo():\r\n\r\n def mtow(self):\r\n rho = 1\r\n Carga_util = [] #[[Sg1_F,W1_F],[Sg2_F],[Sg3_F,W3_F],...[Sgi_F,Wi_F],[Sg1_S,W1_S]...[Sgi_S,Wi_S],[Sg1_I,W1_I],...[Sgi_I,Wi_I]]\r\n while rho <= 3:\r\n mtow = 12.0 # MTOW inicial\r\n if rho == 1: rho = 1.225 # Troca o valor de rho = 1 para rho = 1.225 kg/m³\r\n elif rho == 2: rho = 1.156 # Troca o valor de rho = 2 para rho = 1.156 kg/m³\r\n else: rho = 1.090 # Troca o valor de rho = 3 para rho = 1.090 kg/m³\r\n while mtow <= 20:\r\n W = mtow*self.g\r\n T_Vlof_r2 = curvas.tracao(self, (1.2*(m.sqrt((2*W)/(rho*self.Sw*self.Clmax))))/m.sqrt(2)) # ad, 'Vlof/sqrt(2)' e Hélice\r\n D_Vlof_r2 = 0.5*rho*(((1.2*(m.sqrt((2*W)/(rho*self.Sw*self.Clmax))))/m.sqrt(2))**2)*self.Sw*desempenho.Cd_ideal(self)\r\n L_Vlof_r2 = 0.5*rho*(((1.2*(m.sqrt((2*W)/(rho*self.Sw*self.Clmax))))/m.sqrt(2))**2)*self.Sw*desempenho.Cl_ideal(self)\r\n Sg = (1.44*W**2)/(self.g*rho*self.Sw*self.Clmax*(T_Vlof_r2-D_Vlof_r2-self.mu*(W-L_Vlof_r2)))\r\n if Sg <= 100:\r\n Carga_util.append([Sg, W, rho])\r\n else:\r\n break\r\n mtow += 0.1\r\n #print(\"zero\") # Usado para testar se não estaria preso em loop infinito (Não descomentar!)\r\n if rho == 1.225: rho = 2\r\n elif rho == 1.156: rho = 3\r\n else: break\r\n x1, x2, x3 = [],[],[] # Valores de distância de decolagem para diferentes pesos na densidade do ar de 0m, 600m e 1200m\r\n y1, y2, y3 = [],[],[] # Valores de Pesos (W) diferentes para deolagem na densidade do ar de 0m, 600m e 1200m\r\n #print(Carga_util) # Verifica os valores de SG e W para cada rho\r\n for i in Carga_util:\r\n if i[2] == 1.225:\r\n x1.append(i[0]) # Valores de dist. de decolagem com rho = 1.225 kg/m³\r\n y1.append(i[1]) # Valores de Peso com rho = 1.225 kg/m³\r\n if i[0] <= 58: # Distância (m) que se espera que a aeroanave atinja a velocidade de decolagem em rho = 1.225 kg/m³ \r\n mtowF = i[1]/self.g # Se o menor elemento de i[0] > \"condição acima\", então mtowI = 0 e a linha 83 resulta em div/0\r\n elif i[2] == 1.156:\r\n x2.append(i[0]) # Valores de dist. de decolagem com rho = 1.156 kg/m³\r\n y2.append(i[1]) # Valores de Peso com rho = 1.156 kg/m³\r\n if i[0] <= 58: # Distância (m) que se espera que a aeroanave atinja a velocidade de decolagem em rho = 1.156 kg/m³\r\n mtowS = i[1]/self.g # Se o menor elemento de i[0] > \"condição acima\", então mtowI = 0 e a linha 83 resulta em div/0\r\n elif i[2] == 1.090:\r\n x3.append(i[0]) # Valores de dist. de decolagem com rho = 1.090 kg/m³\r\n y3.append(i[1]) # Valores de Peso com rho = 1.090 kg/m³\r\n if i[0] <= 58: # Distância (m) que se espera que a aeroanave atinja a velocidade de decolagem em rho = 1.090 kg/m³\r\n mtowI = i[1]/self.g # Se o menor elemento de i[0] > \"condição acima\", então mtowI = 0 e a linha 83 resulta em div/0\r\n else:\r\n break\r\n plt.plot(x1, y1, ls='solid', lw='1', color='g', label='$S_G$ para rho = 1.225 kg/m³')\r\n plt.plot(x2, y2, ls='solid', lw='1', color='k', label='$S_G$ para rho = 1.156 kg/m³')\r\n plt.plot(x3, y3, ls='solid', lw='1', color='r', label='$S_G$ para rho = 1.090 kg/m³')\r\n plt.title('Influência do peso ($W$) na distância de decolagem ($S_G$)')\r\n plt.xlabel('Distância de decolagem ($m$)', fontsize=10)\r\n plt.ylabel('Peso ($N$)', fontsize=10)\r\n plt.legend()\r\n plt.axis(\"auto\")\r\n plt.show()\r\n if self.rho == 1.225:\r\n print(f'\\nO mtow máximo encontrado é: {mtowF} kg') # Verifica o mtow usado para rho = 1.225kg/m³\r\n return mtowF\r\n elif self.rho == 1.156:\r\n print(f'\\nO mtow máximo encontrado é: {mtowS} kg') # Verifica o mtow usado para rho = 1.156kg/m³\r\n return mtowS\r\n elif self.rho == 1.090:\r\n print(f'\\nO mtow máximo encontrado é: {mtowI} kg') # Verifica o mtow usado para rho = 1.090kg/m³\r\n return mtowI\r\n","repo_name":"joaomanoel0/otimizador_de_perfil_aero_2023","sub_path":"classe_desempenho.py","file_name":"classe_desempenho.py","file_ext":"py","file_size_in_byte":9752,"program_lang":"python","lang":"pt","doc_type":"code","stars":1,"dataset":"github-code","pt":"81"} +{"seq_id":"38617451277","text":"data = [\"X\", \"X\", \"X\", \"Z\", \"Z\", \"X\", \"X\", \"Y\", \"Y\", \"Y\", \"Z\", \"Z\"]\ndata1 = \"XXXZZXXYYYZZ\"\ndata2 = \"\"\n\n# def encode(data):\n\n# out_list = []\n# n = 1\n# i = 0\n\n# for i, char in enumerate(data):\n# if i > 0:\n# if char == data[i-1]:\n# n += 1\n# else:\n# out_list += [data[i-1], n]\n# n = 1\n# if i:\n# out_list += [data[i-1], n]\n\n# return out_list\n\n\ndef encode(data):\n def count(string):\n if not string:\n return 0\n else:\n n = count(string[1:])\n n += 1\n return n\n\n out_list = []\n temp = \"\"\n i = 0\n\n for i, char in enumerate(data):\n if i > 0:\n if char == data[i-1]:\n temp += char\n else:\n temp += data[i-1]\n n = count(temp)\n out_list += [data[i-1], n]\n temp = \"\"\n\n if i:\n temp += data[i-1]\n n = count(temp)\n out_list += [data[i-1], n]\n\n return out_list\n\n\nprint(encode(data2))\n","repo_name":"alex-kondr/Python","sub_path":"Python core/HW_07/task_17.py","file_name":"task_17.py","file_ext":"py","file_size_in_byte":1074,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"81"} +{"seq_id":"13499750958","text":"import numpy as np\nimport pandas as pd\n\nimport torch\nimport torch.optim as optim\nfrom torch.utils.data import DataLoader\nfrom torchsummary import summary\n\nfrom .model import YOLO_AXTrack\nfrom .loss import YOLO_AXTrack_loss\nfrom ..Timelapse import Timelapse\nfrom ..utils import load_checkpoint\nfrom ..AxonDetections import AxonDetections\n\ndef setup_data(P, skip_test=False):\n # training data\n train_data = Timelapse(P['TIMELAPSE_FILE'], P['LABELS_FILE'], P['MASK_FILE'], \n timepoints = P['TRAIN_TIMEPOINTS'],\n log_correct = P['LOG_CORRECT'],\n offset = P['OFFSET'],\n standardize_framewise = P['STANDARDIZE_FRAMEWISE'],\n standardize = P['STANDARDIZE'],\n use_motion_filtered = P['USE_MOTION_DATA'],\n use_sparse = P['USE_SPARSE'],\n use_transforms = P['USE_TRANSFORMS'],\n temporal_context= P['TEMPORAL_CONTEXT'],\n contrast_llim = P['CLIP_LOWERLIM'],\n pad = P['PAD'], \n plot = P['PLOT_PREPROC'], \n cache = P['CACHE'], \n from_cache = P['FROM_CACHE'],\n name = 'train',\n tilesize = P['TILESIZE'],\n Sy = P['SY'], \n Sx = P['SX'],)\n if skip_test:\n return train_data, None \n # test data\n test_data = Timelapse(P['TIMELAPSE_FILE'], P['LABELS_FILE'], P['MASK_FILE'], \n timepoints = P['TEST_TIMEPOINTS'],\n log_correct = P['LOG_CORRECT'],\n offset = P['OFFSET'],\n standardize_framewise = P['STANDARDIZE_FRAMEWISE'],\n use_motion_filtered = P['USE_MOTION_DATA'],\n use_sparse = P['USE_SPARSE'],\n use_transforms = P['USE_TRANSFORMS'],\n temporal_context= P['TEMPORAL_CONTEXT'],\n contrast_llim = P['CLIP_LOWERLIM'],\n pad = P['PAD'], \n plot = P['PLOT_PREPROC'], \n cache = P['CACHE'], \n from_cache = P['FROM_CACHE'],\n name = 'test',\n tilesize = P['TILESIZE'],\n Sy = P['SY'], \n Sx = P['SX'],\n # standardize = P['STANDARDIZE'],)\n standardize = train_data.stnd_scaler,)\n return train_data, test_data\n\ndef setup_model(P):\n if P['USE_MOTION_DATA'] == 'include':\n initial_in_channels = 3 *(P['TEMPORAL_CONTEXT']*2+1)\n if P['USE_MOTION_DATA'] == 'only':\n initial_in_channels = 2 *(P['TEMPORAL_CONTEXT']*2+1)\n if P['USE_MOTION_DATA'] == 'exclude':\n initial_in_channels = 1 *(P['TEMPORAL_CONTEXT']*2+1)\n\n model = YOLO_AXTrack(initial_in_channels = initial_in_channels, \n architecture = P['ARCHITECTURE'], \n activation_function = P['ACTIVATION_FUNCTION'],\n tilesize = P['TILESIZE'], \n Sy = P['SY'],\n Sx = P['SX'],)\n model.to(P['DEVICE'])\n # model.to_device(P['DEVICE'])\n # summary(model, input_size=(initial_in_channels, P['TILESIZE'], P['TILESIZE']), \n # device=P['DEVICE'])\n # model.get_CNN_outdim()\n\n optimizer = optim.Adam(model.parameters(), lr=P['LR'], weight_decay=P['WEIGHT_DECAY'])\n\n if P['LR_DECAYRATE']:\n decay = lambda E: np.e**((-1/P['LR_DECAYRATE']) * np.sqrt(E)) \n else:\n decay = lambda E: 1\n lr_scheduler = optim.lr_scheduler.LambdaLR(optimizer, decay)\n \n loss_fn = YOLO_AXTrack_loss(Sy = P['SX'], \n Sx = P['SX'],\n lambda_obj = P['L_OBJECT'],\n lambda_noobj = P['L_NOBJECT'],\n lambda_coord_anchor = P['L_COORD_ANCHOR'],)\n \n if P['LOAD_MODEL']:\n load_checkpoint(P['LOAD_MODEL'], model, optimizer, lr_scheduler, P['DEVICE'])\n return model, loss_fn, optimizer, lr_scheduler\n\ndef setup_data_loaders(P, dataset):\n data_loader = DataLoader(\n dataset = dataset,\n shuffle = P['SHUFFLE'],\n batch_size = P['BATCH_SIZE'],\n num_workers = P['NUM_WORKERS'],\n pin_memory = P['PIN_MEMORY'],\n drop_last = P['DROP_LAST'],)\n return data_loader\n\ndef run_epoch(data_loader, model, loss_fn, device, which_dataset, optimizer):\n print(f'LOSS: ', end='')\n \n epoch_loss = []\n for batch, (X, target) in enumerate(data_loader):\n X, target = X.to(device), target.to(device)\n \n pred = model(X)\n loss, loss_components = loss_fn(pred, target)\n epoch_loss.append(loss_components)\n print(f'{loss.item():.3f}', end='...', flush=True)\n \n if which_dataset == 'train':\n # reset gradients, backprop, step down the loss gradient\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n print('Done.')\n return pd.concat(epoch_loss, axis=1)\n\ndef prepare_data(device, dataset):\n dataset.construct_tiles(device)\n ntiles = (dataset.tile_info[..., 0] >0).sum().item()\n npos_labels = dataset.tile_info[..., 1].sum().item()\n avg_pos_rate = npos_labels/(ntiles+1)\n print(f' - {dataset.name} data - n_positive_labels:{npos_labels} / ntiles'\n f':{ntiles} = {avg_pos_rate:.3f} per tile - ', end='')\n return avg_pos_rate\n\n# this iterates over the entire dataset once\ndef one_epoch(dataset, model, loss_fn, params, epoch, optimizer=None, lr_scheduler=None):\n which_dataset = 'train' if optimizer is not None else 'test'\n while prepare_data(params['DEVICE'], dataset) < .65:\n print('Bad data augmentation -- Doing it again --')\n \n # get the dataloader and run model on entire dataset\n data_loader = setup_data_loaders(params, dataset)\n epoch_loss = run_epoch(data_loader, model, loss_fn, params['DEVICE'], \n which_dataset, optimizer)\n epoch_loss = epoch_loss.mean(axis=1).rename((epoch, which_dataset))\n \n # every 10th epoch calculate precision, recall, and F1 for entire dataset\n if not (epoch % 10):\n # on test, use all data, on train only a random subset\n step = 10 if which_dataset == 'train' else 1\n tstart = np.random.randint(0,10, ) if which_dataset == 'train' else 0\n ax_dets = AxonDetections(model, dataset, params, directory=None,\n timepoint_subset=range(tstart, dataset.sizet, step))\n ax_dets.detect_dataset()\n cnfs_mtrx = sum([ax_dets.compute_TP_FP_FN(which_dets='all', t=t) \n for t in range(len(ax_dets))])\n epoch_metrics = ax_dets.compute_prc_rcl_F1(cnfs_mtrx, return_dataframe=True)\n epoch_loss = pd.concat([epoch_loss, epoch_metrics]).rename((epoch, which_dataset))\n\n if which_dataset == 'train' and lr_scheduler:\n lr_scheduler.step()\n torch.cuda.empty_cache()\n return epoch_loss","repo_name":"LoaloaF/axtrack","sub_path":"axtrack/machinelearning/core_functionality.py","file_name":"core_functionality.py","file_ext":"py","file_size_in_byte":7367,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"26701283723","text":"import plotly\nimport plotly.io as plio\nimport plotly.graph_objs as go\nimport pandas as pd\n\ndqrdataall = pd.read_csv(\"dqr_by_instrument_sorted.txt\", index_col=0)\n#dqrdata = pd.read_csv(\"dqr_by_instrument.txt\", index_col=0)\ndqrdataall.fillna(0)\ndqrdata = dqrdataall[0:20]\ntraceslist = dqrdata.columns.tolist()\nnuminstruments = len(dqrdata.index)\ndqrcount = dqrdata.sum(axis=1)\ndqrcount_sorted = dqrcount.sort_values(ascending=False)\nprint(traceslist)\n\n#print(dqrdata.index)\n\n# Create a function that will create as many traces for us as we need\ndef tracing(column):\n trace = go.Bar(\n x = dqrdata.index,\n y = dqrdata[column],\n # Parameters above specify what you would see if hover on any column\n name = column,\n\t\t #text=column dqrdata[column][dqrdata.index],\n\t\t text=column,\n #text=dqrdata[column][dqrdata.index],\n textposition='auto',\n hoverinfo=\"x+y\")\n return trace\n# Create data\ndata = []\n# Fill out data with our traces\n#for i in range(len(traceslist)):\nfor i in range(len(traceslist)-1):\n eachtrace = tracing(traceslist[i])\n data.append(eachtrace)\n# Optional: create layout\nlayout = go.Layout(\n # Set title to plot\n title = \"Data Quality Reports for each instrument\",\n font = dict(size=36, color=\"#330000\"),\n\t xaxis = dict(title = \"Instruments\", titlefont=dict(size=48, color=\"#330000\")),\n\t yaxis = dict(title = \"Number of DQRs\", titlefont=dict(size=48, color=\"#330000\")),\n\t paper_bgcolor='rgb(255,255,255)', # background color\n\t plot_bgcolor='rgb(255,255,255)', # background color\n # Choose one of the barmode below and comment another\n barmode=\"stack\",\n #barmode=\"group\"\n )\n# Create figure with all we need to plot\nfig = go.Figure(data=data, layout=layout)\n# Use offline plot without connection to plotly site\nplotly.offline.plot(fig, filename='sorted_dqr_by_instrument_20.html')\n\n#plio.write_image(fig, file=\"sorted_dqr_by_instrument_20.png\")\n\nprint(dqrdata.iloc[1,:])\nprint(dqrdata.iloc[2,:])\ndqrdata.fillna(0)\nprint(dqrdata.iloc[2,:])\nprint(\"Number of instruments: %d\"%(numinstruments))\n#print(dqrcount_sorted)\n#print(dqrcount.describe())\nprint(dqrcount_sorted)\n","repo_name":"michaeltg12/kumar_reprocworkflow_ieeebigdata_2019","sub_path":"figures/plot_dqr_per_instrument.py","file_name":"plot_dqr_per_instrument.py","file_ext":"py","file_size_in_byte":2173,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"38219436013","text":"from random import randrange, choice\n\n\ndef list_mixer(array):\n length = len(array)\n mixed_list = []\n pos_list = list(range(length))\n n = length\n while n > 0:\n index = randrange(0, n)\n mixed_list.append(array[pos_list[index]])\n pos_list.pop(index)\n n -= 1\n return mixed_list\n\n\ndef list_mixer2(array): # вариант с random.choice()\n length = len(array)\n mixed_list = []\n pos_list = list(range(length))\n while True:\n place = choice(pos_list)\n pos_list.remove(place)\n mixed_list.append(array[place])\n if len(mixed_list) == length:\n break\n return mixed_list\n\n\nprint(list_mixer(range(-10, 10, 1)))\n","repo_name":"Tirsh/Python_exercises","sub_path":"Homework2/tesk05.py","file_name":"tesk05.py","file_ext":"py","file_size_in_byte":699,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"74795119945","text":"class Solution:\r\n def smallestSufficientTeam(self, req_skills: List[str], people: List[List[str]]) -> List[int]:\r\n dp = collections.defaultdict(list)\r\n dp[frozenset()] = []\r\n \r\n for i, skills in enumerate(people):\r\n people_set = frozenset(skills)\r\n \r\n for old_set in list(dp.keys()):\r\n new_set = old_set.union(people_set)\r\n if new_set not in dp or len(dp[new_set]) > len(dp[old_set]) + 1:\r\n dp[new_set] = dp[old_set] + [i]\r\n \r\n return dp[frozenset(req_skills)]","repo_name":"novayo/LeetCode","sub_path":"1125_Smallest_Sufficient_Team/try_1.py","file_name":"try_1.py","file_ext":"py","file_size_in_byte":587,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"81"} +{"seq_id":"39834651974","text":"def solution(weights, head2head):\n n = len(weights)\n loser = 'N'*n\n win = {}\n for idx, records in enumerate(head2head, start=1):\n if records == loser:\n win[idx] = [0,0,weights[idx-1]]\n else:\n rate = records.count('W')/(n-records.count('N'))\n wow = 0\n for i in range(n):\n if records[i] == 'W' and weights[idx-1] < weights[i]:\n wow += 1\n win[idx] = [rate, wow, weights[idx-1]]\n\n results = [player for player, info in sorted(win.items(), key=lambda x: (-x[1][0], -x[1][1], -x[1][2], x[0]))]\n return results","repo_name":"devhyojin/Algorithm","sub_path":"Programmers/[Programmers]코딩테스트연습_위클리 챌린지_6주차_복서 정렬하기.py","file_name":"[Programmers]코딩테스트연습_위클리 챌린지_6주차_복서 정렬하기.py","file_ext":"py","file_size_in_byte":624,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"81"} +{"seq_id":"10436602305","text":"import socket\n\nserver_host = '127.0.0.1'\nserver_port = 12345\n\nclient_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n\nclient_socket.connect((server_host, server_port))\n\nwhile True:\n message = input(\"Enter a message (or type 'exit' to quit): \")\n if message == 'exit':\n break\n\n client_socket.send(message.encode('utf-8'))\n\n data = client_socket.recv(1024)\n print(f\"Received from server: {data.decode('utf-8')}\")\n\nclient_socket.close()\n","repo_name":"shiixxam/python_in_30_days","sub_path":"TCP socket programming/Qclient.py","file_name":"Qclient.py","file_ext":"py","file_size_in_byte":466,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"14351329715","text":"\nfrom installer.model.model import disk as model\nfrom installer.model.gen import partition\nimport installer.shell as shell\nimport sys\nsys.path.append(\"...\") # set all imports to root imports\n\n\ndef GetDiskSize(device):\n \"\"\"\n Return the size of a disk\n \"\"\"\n obj = shell.Command(\"lsblk {}\".format(device) +\n \" -s --noheading | awk '{print $4}'\")\n return obj.GetStdout()\n\n\ndef getPartitionsByDisk(device):\n \"\"\"\n Generate all partitions found on a disk\n \"\"\"\n # Gets a list of partitions based on file location\n obj = shell.Command(\"lsblk \" + device + \" --noheading -p --list | grep -E '\" +\n device + \"[a-zA-Z0-9]+' | awk '{print $1}'\")\n parts = obj.GetStdout().split()\n\n # convert the list of string into partition objects\n partitions = []\n for part in parts:\n partitions.append(partition.getPartitionByDevice(part))\n return partitions\n\n\ndef getAllDisks():\n \"\"\"\n Return all disks found in /dev\n \"\"\"\n obj = shell.Command(\n \"fdisk -l | grep -E 'Disk /dev' | awk '{print $2}' | sed 's/://'\")\n diskslist = obj.GetStdout().split()\n\n disks = []\n for disk in diskslist:\n disks.append(model.disk(disk, GetDiskSize(\n disk), getPartitionsByDisk(disk)))\n return disks\n","repo_name":"ODEX-TOS/tos-installer-backend","sub_path":"installer/model/gen/disk.py","file_name":"disk.py","file_ext":"py","file_size_in_byte":1300,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"81"} +{"seq_id":"72547862985","text":"import json\nimport ctypes\nfrom multiprocessing import Process, Queue, Array\nfrom request_worker import request_worker\nfrom log_worker import log_worker\nfrom info_logger import info_logger\nfrom generate_request_object import generate_request_object\nfrom create_db import create_databases\n# define global queues\nrequest_queue = Queue()\nresponse_queue = Queue()\n\n# number of workers to process requests\nnum_request_workers = 3\nnum_logging_workers = 1\n\n# shared array to keep track of urls currently being checked\ncurrently_checking_urls = Array(ctypes.c_char_p, num_request_workers)\n\n# initialize database and tables if not already done\ncreate_databases()\n\n# acceptable delay between scheduled time for query and query execution\nacceptable_queue_delay = 5 # seconds\n\n# acceptable wait time for website to responsd to request\nacceptable_website_response_wait = 5 # seconds\n\n\ndef start_request_workers(n): # starts n workers to process the queue\n for idx in range(n):\n request_worker_process = Process(target=request_worker,\n args=(request_queue,\n response_queue,\n acceptable_website_response_wait,\n currently_checking_urls,\n idx))\n request_worker_process.start()\n\n\nstart_request_workers(num_request_workers)\n\ninput_file = json.load(open('../urls.json'))\n\n# start processess for each url that periodically generate requests\nfor input_object in input_file:\n url = input_object[\"url\"]\n interval = input_object[\"interval\"]\n input_url_interval = [url, interval]\n p = Process(target=generate_request_object, \n args=(input_url_interval,\n acceptable_queue_delay,\n request_queue))\n p.start()\n\n\ndef start_log_workers(n): # starts n log workers\n for x in range(n):\n log_worker_process = Process(target=log_worker, args=(response_queue,))\n log_worker_process.start()\n\n\nstart_log_workers(num_logging_workers)\n\n\ndef start_info_logger_worker(currently_checking_urls):\n info_logger_process = Process(target=info_logger,\n args=(currently_checking_urls, ))\n info_logger_process.start()\n\n\nstart_info_logger_worker(currently_checking_urls)\n","repo_name":"deejes/python_coding_challenge","sub_path":"part2/iteration_1/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2389,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"42363889508","text":"import os\nimport requests\nimport polars as pl\nfrom dotenv import load_dotenv\nfrom datetime import datetime, timezone\nfrom rfa_utils.coingecko_api import fill_date\n\n# Load environment variables from .env file\nload_dotenv(\".env\")\n\n\ndef unix_time(date: str) -> float:\n \"\"\"Take in date in string format and return UNIX timestamp float\"\"\"\n stamp = datetime.strptime(date, '%Y/%m/%d %H:%M:%S')\n return int(stamp.replace(tzinfo=timezone.utc).timestamp())\n\n\ndef dates_between(start: str, end: str) -> list:\n \"\"\"Return a list of first dates of each year, given a start and end\"\"\"\n start_date = datetime.strptime(start, '%Y/%m/%d')\n end_date = datetime.strptime(end, '%Y/%m/%d')\n date_list = []\n\n # Check if the start date is the first day of the year\n if start_date.month == 1 and start_date.day == 1:\n current_date = start_date\n else:\n # If not, use the first day of current year\n current_date = start_date.replace(month=1, day=1)\n\n while end_date > current_date:\n # Add current date to the list of dates and replace the month and day to 1\n date_list.append(current_date)\n current_date = current_date.replace(month=1, day=1)\n # Add one year from the current date and replace the month and day to 1\n current_date = current_date.replace(year=current_date.year + 1, month=1, day=1)\n \n # Add first day of next year for end date\n date_list.append(end_date.replace(year=end_date.year + 1, month=1, day=1))\n\n # Return list of dates as strings\n return [date.strftime('%Y/%m/%d') + ' 00:00:00' for date in date_list]\n\n\ndef api_call(dates_list: list) -> dict:\n \"\"\"Make a call to the Owlracle API and return historical gas JSON\"\"\"\n key = os.getenv('OAPI')\n results = {} # Dict of JSON\n\n # Loop over the list of dates in pairs using zip\n for start_date, end_date in zip(dates_list, dates_list[1:]):\n unix_start = unix_time(start_date)\n unix_end = unix_time(end_date)\n \n # Make the API call with the start and end dates\n res = requests.get(f'https://api.owlracle.info/v4/eth/history?apikey={key}&from={unix_start}&to={unix_end}&candles=365&timeframe=1d&txfee=true')\n # Add the response JSON to the results dictionary with the year as the key\n year = datetime.strptime(start_date, '%Y/%m/%d %H:%M:%S').year\n results[year] = res.json()\n \n return results\n\n\ndef extract_json(json_data: dict) -> dict:\n \"\"\"Extract the txFee and the gasPrice from the JSON data, calculate the average\n Return a dict containing three lists: dates, transaction_fees, and gas_prices\"\"\"\n result = {}\n dates = []\n transaction_fees = []\n gas_prices = []\n for year, data in json_data.items():\n for candle in data['candles']:\n # Extract closing txFee and gasPrice from candles\n fee = candle['txFee']['close']\n price = candle['gasPrice']['close']\n \n # Only add in data from the current year\n date = candle['timestamp'].split('T')[0]\n if date.startswith(str(year)):\n dates.append(date)\n transaction_fees.append(fee)\n gas_prices.append(price)\n \n # Add the sorted dates, fees, and prices lists to the result dict\n result[\"date\"] = sorted([datetime.strptime(date, '%Y-%m-%d').date() for date in dates])\n result[\"transaction_fees\"] = [x for _, x in sorted(zip(dates, transaction_fees))]\n result[\"gas_prices\"] = [x for _, x in sorted(zip(dates, gas_prices))]\n \n return result\n\n\ndef create_df(start: str, end: str) -> pl.DataFrame:\n \"\"\"Create a Polars DataFrame from the Owlracle API data between the given start and end dates\"\"\"\n between = dates_between(start, end)\n json = api_call(between)\n extracted = extract_json(json)\n df = pl.DataFrame(extracted)\n return fill_date(df)","repo_name":"kietnguyen01/Remittance-Fees-Analysis","sub_path":"rfa_utils/owlracle_api.py","file_name":"owlracle_api.py","file_ext":"py","file_size_in_byte":3897,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"9191304472","text":"import pickle\nimport random\nimport time\nimport traceback\nimport pandas as pd\nfrom telethon.errors.rpcerrorlist import PeerFloodError, UserPrivacyRestrictedError\nfrom telethon.sync import TelegramClient\nfrom telethon.tl.functions.channels import InviteToChannelRequest\nfrom telethon.tl.functions.messages import GetDialogsRequest\nfrom telethon.tl.types import InputPeerEmpty, InputPeerChannel, InputPeerUser\n\nSLEEP_TIME_1 = 100\nSLEEP_TIME_2 = 100\n\n\ndef adder_launch():\n accounts = []\n h = open('vars.txt', 'rb')\n while True:\n try:\n accounts.append(pickle.load(h))\n except EOFError:\n break\n h.close()\n if accounts != []:\n client = TelegramClient(accounts[0][2], accounts[0][0], accounts[0][1])\n client.connect()\n else:\n print(\"You don't have any accounts added to your bot\")\n print('Returning to home page!')\n time.sleep(5)\n return None\n chats = []\n last_date = None\n chunk_size = 200\n groups = []\n\n result = client(GetDialogsRequest(\n offset_date=last_date,\n offset_id=0,\n offset_peer=InputPeerEmpty(),\n limit=chunk_size,\n hash=0\n ))\n chats.extend(result.chats)\n\n for chat in chats:\n try:\n if chat.megagroup == True:\n groups.append(chat)\n except:\n continue\n j = 0\n for i in groups:\n print(j, i.title)\n j += 1\n\n while True:\n\n try:\n group_to_add = int(input(\"Enter the 'id' of the group you want to add members to:\"))\n target_group = groups[group_to_add]\n target_group_entity = InputPeerChannel(target_group.id, target_group.access_hash)\n break\n except ValueError:\n print(\"Please try again\")\n\n members = pd.read_csv(\"members/members.csv\")\n members = members.to_dict(orient=\"records\")\n\n n = 0\n accounts_num = len(accounts)\n m = 1\n for user in members:\n n += 1\n if n % 80 == 0:\n time.sleep(60)\n try:\n print(\"Adding {}\".format(user['user id']))\n user_to_add = InputPeerUser(user['user id'], user['access hash'])\n\n client(InviteToChannelRequest(target_group_entity, [user_to_add]))\n print(\"Waiting for 60-180 Seconds ...\")\n time.sleep(random.randrange(0, 5))\n except PeerFloodError:\n print(\n \"Getting Flood Error from telegram. Script is stopping now if no other accounts. Please try again after some time.\")\n if m < accounts_num:\n client = TelegramClient(accounts[m][2], accounts[m][0], accounts[m][1])\n client.connect()\n print(\"Using another account!\")\n else:\n print(\"Waiting {} seconds\".format(SLEEP_TIME_2))\n time.sleep(SLEEP_TIME_2)\n except UserPrivacyRestrictedError:\n print(\"The user's privacy settings do not allow you to do this. Skipping ...\")\n print(\"Waiting for 5 Seconds ...\")\n time.sleep(random.randrange(0, 5))\n except:\n traceback.print_exc()\n print(\"Unexpected Error! \")\n continue\n\n return None\n","repo_name":"Zack0424/Telegram-group-adder","sub_path":"tg_bot/adder.py","file_name":"adder.py","file_ext":"py","file_size_in_byte":3216,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"25823571866","text":"import os\nimport secrets\nimport logging\n\nfrom PIL import Image\nfrom flask import Blueprint, render_template, redirect, url_for, flash,current_app\nfrom flask_login import login_user, login_required, logout_user, current_user\nfrom werkzeug.security import generate_password_hash\n\nfrom .decorators import admin_required\nfrom .forms import login_form, register_form, profile_form, security_form, user_edit_form\nfrom app.db import db\nfrom app.db.models import User\nfrom app import config\nfrom app.logging_config import message_formatter\n\nauth = Blueprint('auth', __name__, template_folder='templates')\n\ndbdir = os.path.join(config.Config.BASE_DIR, '..', config.Config.DB_DIR)\n\n@auth.route('/register', methods=['POST', 'GET'])\ndef register():\n if not os.path.exists(dbdir):\n os.mkdir(dbdir)\n db.create_all()\n if current_user.is_authenticated:\n return redirect(url_for('auth.dashboard'))\n form = register_form()\n if form.validate_on_submit():\n user = User.query.filter_by(email=form.email.data).first()\n if user is None:\n user = User(email=form.email.data, password=generate_password_hash(form.password.data), balance=0)\n db.session.add(user)\n db.session.commit()\n if user.id == 1:\n user.is_admin = 1\n db.session.add(user)\n db.session.commit()\n flash('Congratulations, you are now a registered user!', \"success\")\n return redirect(url_for('auth.login'), 302)\n else:\n flash('Already Registered')\n return redirect(url_for('auth.login'), 302)\n return render_template('register.html', form=form)\n\n@auth.route('/login', methods=['POST', 'GET'])\ndef login():\n if not os.path.exists(dbdir):\n os.mkdir(dbdir)\n db.create_all()\n form = login_form()\n if current_user.is_authenticated:\n return redirect(url_for('auth.dashboard'))\n if form.validate_on_submit():\n user = User.query.filter_by(email=form.email.data).first()\n if user is None or not user.check_password(form.password.data):\n flash('Invalid username or password')\n return redirect(url_for('auth.login'))\n else:\n user.authenticated = True\n db.session.add(user)\n db.session.commit()\n login_user(user)\n flash(\"Welcome\", 'success')\n return redirect(url_for('auth.dashboard'))\n return render_template('login.html', form=form)\n\n@auth.route(\"/logout\")\n@login_required\ndef logout():\n \"\"\"Logout the current user.\"\"\"\n user = current_user\n user.authenticated = False\n logout_user()\n return redirect(url_for('auth.login'))\n\n\n\n@auth.route('/dashboard')\n@login_required\ndef dashboard():\n return render_template('dashboard.html')\n\ndef save_picture(form_image):\n random_hex = secrets.token_hex(8)\n _, f_ext = os.path.splitext(form_image.filename)\n image = random_hex + f_ext\n image_path = os.path.join(config.Config.IMAGE_FOLDER, image)\n image_resize = (45, 45)\n i = Image.open(form_image)\n i.thumbnail(image_resize)\n i.save(image_path)\n return image\n\n@auth.route('/profile', methods=['POST', 'GET'])\ndef edit_profile():\n user = User.query.get(current_user.get_id())\n form = profile_form(obj=user)\n log = logging.getLogger('general')\n if form.validate_on_submit():\n if form.image.data:\n temp = current_user.user_image\n message = message_formatter()\n message += '::Image file to be replaced:' + temp\n log.info(message)\n pic = save_picture(form.image.data)\n current_user.user_image = pic\n if not temp == 'default.png':\n os.remove(os.path.join(config.Config.IMAGE_FOLDER,temp))\n user.about = form.about.data\n #db.session.add(current_user)\n db.session.commit()\n message = message_formatter()\n message += '::Profile pic updated:' + current_user.user_image\n log.info(message)\n flash('You Successfully Updated your Profile', 'success')\n return redirect(url_for('auth.dashboard'))\n return render_template('profile_edit.html', form=form)\n\n\n@auth.route('/account', methods=['POST', 'GET'])\ndef edit_account():\n user = User.query.get(current_user.get_id())\n form = security_form(obj=user)\n if form.validate_on_submit():\n user.email = form.email.data\n user.password = form.password.data\n #db.session.add(current_user)\n db.session.commit()\n flash('You Successfully Updated your Password or Email', 'success')\n return redirect(url_for('auth.dashboard'))\n return render_template('manage_account.html', form=form)\n\n\n\n@auth.route('/users')\n@login_required\n@admin_required\ndef browse_users():\n data = User.query.all()\n titles = [('email', 'Email'), ('registered_on', 'Registered On')]\n retrieve_url = ('auth.retrieve_user', [('user_id', ':id')])\n edit_url = ('auth.edit_user', [('user_id', ':id')])\n add_url = url_for('auth.add_user')\n delete_url = ('auth.delete_user', [('user_id', ':id')])\n\n current_app.logger.info(\"Browse page loading\")\n\n return render_template('browse.html', titles=titles, add_url=add_url, edit_url=edit_url, delete_url=delete_url,\n retrieve_url=retrieve_url, data=data, User=User, record_type=\"Users\")\n\n\n@auth.route('/users/')\n@login_required\ndef retrieve_user(user_id):\n user = User.query.get(user_id)\n return render_template('profile_view.html', user=user)\n\n\n@auth.route('/users//edit', methods=['POST', 'GET'])\n@login_required\ndef edit_user(user_id):\n user = User.query.get(user_id)\n form = user_edit_form(obj=user)\n if form.validate_on_submit():\n user.about = form.about.data\n user.is_admin = int(form.is_admin.data)\n #db.session.add(user)\n db.session.commit()\n flash('User Edited Successfully', 'success')\n current_app.logger.info(\"edited a user\")\n return redirect(url_for('auth.browse_users'))\n return render_template('user_edit.html', form=form)\n\n\n@auth.route('/users/new', methods=['POST', 'GET'])\n@login_required\ndef add_user():\n form = register_form()\n if form.validate_on_submit():\n user = User.query.filter_by(email=form.email.data).first()\n if user is None:\n user = User(email=form.email.data, password=generate_password_hash(form.password.data))\n db.session.add(user)\n db.session.commit()\n flash('Congratulations, you just created a user', 'success')\n return redirect(url_for('auth.browse_users'))\n else:\n flash('Already Registered')\n return redirect(url_for('auth.browse_users'))\n return render_template('user_new.html', form=form)\n\n\n@auth.route('/users//delete', methods=['POST'])\n@login_required\ndef delete_user(user_id):\n user = User.query.get(user_id)\n if user.id == current_user.id:\n flash(\"You can't delete yourself!\")\n return redirect(url_for('auth.browse_users'), 302)\n db.session.delete(user)\n db.session.commit()\n flash('User Deleted', 'success')\n return redirect(url_for('auth.browse_users'), 302)\n\n\n@auth.route('/logs')\n@login_required\ndef logs():\n logfile = os.path.join(config.Config.LOG_DIR, 'general.log')\n with open(logfile,'r') as f:\n data = f.read()\n f.close()\n return render_template('logs.html', text=data)\n","repo_name":"onahte/banking_web_app","sub_path":"app/auth/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":7494,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"24109657027","text":"import pytest # noqa\nimport torch\n\nimport theseus as th\nfrom tests.theseus_tests.core.common import BATCH_SIZES_TO_TEST\nfrom theseus.utils import numeric_jacobian\n\nfrom .utils import random_sdf\n\n\ndef test_sdf_2d_shapes():\n generator = torch.Generator()\n generator.manual_seed(0)\n for batch_size in BATCH_SIZES_TO_TEST:\n for field_width in BATCH_SIZES_TO_TEST:\n for field_height in BATCH_SIZES_TO_TEST:\n for num_points in BATCH_SIZES_TO_TEST:\n points = th.Variable(tensor=torch.randn(batch_size, 2, num_points))\n sdf = random_sdf(batch_size, field_width, field_height)\n dist, jac = sdf.signed_distance(points)\n assert dist.shape == (batch_size, num_points)\n assert jac.shape == (batch_size, num_points, 2)\n\n\ndef test_signed_distance_2d():\n data = torch.tensor(\n [\n [1.7321, 1.4142, 1.4142, 1.4142, 1.7321],\n [1.4142, 1, 1, 1, 1.4142],\n [1.4142, 1, 1, 1, 1.4142],\n [1.4142, 1, 1, 1, 1.4142],\n [1.7321, 1.4142, 1.4142, 1.4142, 1.7321],\n ]\n ).view(1, 5, 5)\n sdf = th.eb.SignedDistanceField2D(-0.2 * torch.ones(1, 2), 0.1, data)\n\n points = torch.tensor([[0, 0], [0.18, -0.17]])\n rows, cols, _ = sdf.convert_points_to_cell(points)\n assert torch.allclose(rows, torch.tensor([[2.0, 0.3]]))\n assert torch.allclose(cols, torch.tensor([[2.0, 3.8]]))\n\n dist, _ = sdf.signed_distance(points)\n assert torch.allclose(dist, torch.tensor([1.0, 1.567372]).view(1, 2))\n\n\ndef test_sdf_2d_creation():\n map1 = torch.tensor(\n [\n [0, 1, 1, 1, 1],\n [0, 0, 1, 1, 1],\n [0, 1, 1, 1, 1],\n [0, 1, 1, 1, 0],\n [0, 1, 1, 0, 0],\n ]\n )\n map2 = torch.zeros(5, 5)\n data_maps = th.Variable(torch.stack([map1, map2]))\n sdf_batch = th.eb.SignedDistanceField2D(\n -0.2 * torch.ones(2, 2), 0.1, occupancy_map=data_maps\n )\n # generate verification data for map1\n import numpy as np\n\n s2, s5 = np.sqrt(2), np.sqrt(5)\n sdf_map1_verify = 0.1 * torch.tensor(\n [\n [1, -1, -s2, -s5, -3],\n [s2, 1, -1, -2, -2],\n [1, -1, -s2, -s2, -1],\n [1, -1, -s2, -1, 1],\n [1, -1, -1, 1, s2],\n ]\n )\n if sdf_batch.sdf_data.tensor.dtype == torch.float32:\n sdf_map1_verify = sdf_map1_verify.float()\n assert torch.allclose(\n sdf_batch.sdf_data[0], sdf_map1_verify\n ), \"Failed conversion of map with obstacle.\"\n assert torch.allclose(\n sdf_batch.sdf_data[1], torch.tensor(1.0)\n ), \"Failed conversion of map with no obstacle.\"\n\n\ndef test_signed_distance_2d_jacobian():\n for batch_size in BATCH_SIZES_TO_TEST:\n sdf = random_sdf(batch_size, 10, 10)\n for num_points in [1, 10]:\n points = torch.randn(batch_size, 2, num_points).double()\n _, jacobian = sdf.signed_distance(points)\n\n for p_index in range(num_points):\n x = th.Vector(tensor=points[:, :1, p_index].double())\n y = th.Vector(tensor=points[:, 1:, p_index].double())\n\n def new_distance_fn(vars):\n new_points = torch.stack([vars[0].tensor, vars[1].tensor], dim=1)\n new_dist = sdf.signed_distance(new_points)[0]\n return th.Vector(tensor=new_dist)\n\n expected_jacs = numeric_jacobian(\n new_distance_fn, [x, y], function_dim=1, delta_mag=1e-7\n )\n expected_jacobian = torch.cat(expected_jacs, dim=2).squeeze(1)\n # This makes failures more explicit than torch.allclose()\n diff = (expected_jacobian - jacobian[:, p_index]).norm(p=float(\"inf\"))\n assert diff < 1e-5\n\n\ndef test_to():\n if not torch.cuda.is_available():\n return\n sdf = random_sdf(1, 10, 10)\n points = torch.randn(1, 2, 100).to(\"cuda:0\")\n with pytest.raises(RuntimeError):\n sdf.signed_distance(points)\n sdf.to(\"cuda:0\")\n result, _ = sdf.signed_distance(points)\n assert result.is_cuda\n","repo_name":"facebookresearch/theseus","sub_path":"tests/theseus_tests/embodied/collision/test_signed_distance_field.py","file_name":"test_signed_distance_field.py","file_ext":"py","file_size_in_byte":4164,"program_lang":"python","lang":"en","doc_type":"code","stars":1481,"dataset":"github-code","pt":"81"} +{"seq_id":"73978162504","text":"from numpy import *\nimport time\nimport operator\nimport os\n\ndef createDataSet():\n group = array([[1.0,1.1],[1.0,1.0],[0,0],[0,0.1]])\n labels = ['A','A','B','B']\n return group,labels\n\ndef classify(inX, dataSet, labels, k):\n #the number of row in dataSet\n rowNum = dataSet.shape[0]\n \n #tile func to repeat inX rowNum row to be a matrix\n #then can get diff between inX and every row in dataSet via matrix minus\n diffMat = tile(inX, (rowNum,1)) - dataSet\n sqDiff = diffMat**2\n \n #get sum by row\n sqDist = sqDiff.sum(axis = 1)\n dist = sqDist**0.5\n \n #argsort sort the list and return the idx in list after sort them\n sortedDistIdx = dist.argsort()\n classCount = {}\n for i in range(k):\n #statictic the label\n vote = labels[sortedDistIdx[i]]\n classCount[vote] = classCount.get(vote,0)+1\n #sort the dict and get the label that appears most times\n sortedClassCount = sorted(classCount.items(), key=operator.itemgetter(1), reverse = True)\n return sortedClassCount[0][0]\n\n#convert handwriting matrix(img) to vector\ndef img2vector(filename):\n row = 32\n col = 32\n imgVector = zeros((1, row*col))\n with open(filename) as f:\n for i in range(row):\n line = f.readline()\n for j in range(col):\n imgVector[0, j+col*i] = int(line[j])\n return imgVector\n \ndef loadData():\n print('get training set...')\n mainDir = r'E:\\research\\MachineLearning\\Machine Learning in Action'\n SampleDir = mainDir + r'\\digits\\trainingDigits'\n SampleList = os.listdir(SampleDir)\n numSample = len(SampleList)\n sample_x = zeros((numSample, 1024))\n sample_y = []\n for i in range(numSample):\n filename = SampleList[i]\n sample_x[i, ] = img2vector(SampleDir+'\\%s' % filename)\n label = filename.split('_')[0]\n sample_y.append(label)\n \n print('get test set...')\n testDir = mainDir + r'\\digits\\testDigits'\n testList = os.listdir(testDir)\n numTest = len(testList)\n test_x = zeros((numTest, 1024))\n test_y = []\n for i in range(numTest):\n filename = testList[i]\n test_x[i, ] = img2vector(testDir+'\\%s' % filename)\n label = filename.split('_')[0]\n test_y.append(label)\n return sample_x, sample_y, test_x, test_y\n\ndef testHandWritingNum():\n print('1.Loading data...')\n sample_x, sample_y, test_x, test_y = loadData()\n \n #print(test_x)\n \n print('2.Training...')\n pass #nothing need to do in KNN in Training\n \n print('3.Testing...')\n numTest = test_x.shape[0]\n \n matched = 0\n for i in range(numTest):\n predict = classify(test_x[i], sample_x, sample_y, 3)\n if predict == test_y[i]:\n matched += 1\n accuracy = float(matched) / numTest\n print('4.the accuracy is %.2f%%' % (accuracy*100))\n \nif __name__ == '__main__':\n cur = time.time()\n testHandWritingNum()\n print(str(time.time()-cur)+'s')\n","repo_name":"AzoresCabbage/MachineLearning","sub_path":"KNN/KNN.py","file_name":"KNN.py","file_ext":"py","file_size_in_byte":2970,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"30779910317","text":"from flask import Flask, request\nfrom werkzeug.utils import secure_filename\nfrom getImgInfo.getImgInfoCtl import GetImgInfoCtl\nimport os\n\nUPLOAD_FOLDER = os.path.dirname(os.path.abspath(__file__))+'\\\\img\\\\'\nALLOWED_EXTENSIONS = set(['png', 'jpg', 'jpeg', 'gif'])\n\napp = Flask(__name__)\n\n\ndef allowed_file(filename):\n return '.' in filename and \\\n filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS\n\n\n@app.route('/ai/ocr/uploadImg', methods=['GET', 'POST'])\ndef upload_file():\n if request.method == 'POST':\n file = request.files['file']\n if file and allowed_file(file.filename):\n filename = secure_filename(file.filename)\n filename = UPLOAD_FOLDER + filename\n file.save(filename)\n ctl = GetImgInfoCtl()\n text = ctl.getinfo('img/' + secure_filename(file.filename))\n print(text)\n return text\n return '未能识别出图片中的文字'\n\n\nif __name__ == '__main__':\n app.run(host='0.0.0.0', port=8002)\n","repo_name":"ab-chao/aiGetImgInfo","sub_path":"getImgInfo/aiUploadImg.py","file_name":"aiUploadImg.py","file_ext":"py","file_size_in_byte":1009,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"13829257126","text":"# ---------------------------------------------------------------------------------------------------------\r\n# /////////////////////////////////////////////////////////////////////////////////////////////////////////\r\n#\r\n# gui_theme.py\r\n#\r\n# - Sends back a theme to the gui based on the input\r\n#\r\n# /////////////////////////////////////////////////////////////////////////////////////////////////////////\r\n# ---------------------------------------------------------------------------------------------------------\r\n\r\nimport pygame\r\n\r\n\r\nclass Theme:\r\n\r\n def __init__(self):\r\n\r\n # Path to theme images\r\n self.path = '..\\\\gui\\\\imgs'\r\n\r\n # Icon\r\n self.icon = pygame.image.load(f'{self.path}/icon.ico')\r\n\r\n # Options\r\n self.toggle_sound = True\r\n self.forfeit_on_time = False\r\n self.enable_shortcuts = True\r\n self.auto_flip = True\r\n\r\n # Timings\r\n self.fixed_depth = 0\r\n self.movetime = 0\r\n self.stoptime = 0\r\n self.tot_time = 180\r\n self.inc = 0\r\n\r\n self.movestogo = 50\r\n self.timeset = 0\r\n\r\n # Start fen\r\n self.start_fen = 'rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1'\r\n\r\n def get_theme(self, theme, win_width=900):\r\n\r\n # Index to decide which theme is chosen\r\n index = {'Black and Gold': 0, 'Blue and White': 1}[theme]\r\n\r\n # --------------------------------------------------------------\r\n # Window parameters\r\n # --------------------------------------------------------------\r\n\r\n # Width and height\r\n self.win_width = win_width\r\n self.win_height = int(self.win_width/1.05)\r\n\r\n # Extra parameters\r\n self.sq_size = int(self.win_width / 12)\r\n self.top_bar_height = int(0.35 * self.sq_size)\r\n self.board_offset = int(0.4 * self.sq_size)\r\n self.margin = int(self.sq_size/32.5)\r\n\r\n # Fonts\r\n pygame.font.init()\r\n\r\n self.button_font = pygame.font.SysFont('Helvetica', int(self.sq_size * 0.26), bold=True)\r\n self.pv_font = pygame.font.SysFont('Times', int(self.sq_size * 0.21))\r\n self.board_font = pygame.font.SysFont('Times', int(self.sq_size * 0.35))\r\n\r\n self.menu_font = pygame.font.SysFont('Times', self.top_bar_height - int(self.sq_size / 7))\r\n self.menu_font_bold = pygame.font.SysFont('Times', self.top_bar_height - int(self.sq_size / 7), bold=True)\r\n\r\n self.popup_font_small = pygame.font.SysFont('Times', self.top_bar_height - int(self.sq_size / 6))\r\n self.popup_font = pygame.font.SysFont('Times', self.top_bar_height - int(self.sq_size / 7.2))\r\n self.popup_font_bold = pygame.font.SysFont('Times', self.top_bar_height - int(self.sq_size / 7.2), bold=True)\r\n\r\n self.clock_title_font = pygame.font.SysFont('Times', int(self.sq_size * 0.28))\r\n self.clock_font = pygame.font.SysFont('Times', int(self.sq_size * 0.35))\r\n self.clock_move_font = pygame.font.SysFont('Times', int(self.sq_size * 0.25))\r\n\r\n self.fen_font = pygame.font.SysFont('Times', self.top_bar_height - int(self.sq_size / 6.1))\r\n\r\n # --------------------------------------------------------------\r\n # Image choices\r\n # --------------------------------------------------------------\r\n\r\n bg_themes = [pygame.image.load(f'{self.path}\\\\black_gold\\\\bg.png'),\r\n pygame.image.load(f'{self.path}\\\\blue_white\\\\bg.jpg')][index]\r\n board_edge_themes = [pygame.image.load(f'{self.path}\\\\black_gold\\\\edge.jpg'),\r\n pygame.image.load(f'{self.path}\\\\blue_white\\\\edge.jpg')][index]\r\n\r\n pv_edge_themes = [pygame.image.load(f'{self.path}\\\\black_gold\\\\edge.jpg'),\r\n pygame.image.load(f'{self.path}\\\\blue_white\\\\edge.jpg')][index]\r\n pv_image_themes = [pygame.image.load(f'{self.path}\\\\black_gold\\\\pv_background.jpg'),\r\n pygame.image.load(f'{self.path}\\\\blue_white\\\\pv_background.jpg')][index]\r\n\r\n clock_edge_themes = [pygame.image.load(f'{self.path}\\\\black_gold\\\\edge.jpg'),\r\n pygame.image.load(f'{self.path}\\\\blue_white\\\\edge.jpg')][index]\r\n clock_image_themes = [pygame.image.load(f'{self.path}\\\\black_gold\\\\pv_background.jpg'),\r\n pygame.image.load(f'{self.path}\\\\blue_white\\\\pv_background.jpg')][index]\r\n\r\n pieces_themes = [pygame.image.load(f'{self.path}\\\\black_gold\\\\pieces.png'),\r\n pygame.image.load(f'{self.path}\\\\blue_white\\\\pieces.png')][index]\r\n\r\n light_square_themes = [pygame.transform.rotate(pygame.image.load(f'{self.path}\\\\black_gold\\\\light_square.jpg'), 0),\r\n pygame.transform.rotate(pygame.image.load(f'{self.path}\\\\blue_white\\\\light_square.jpg'), 0)][index]\r\n dark_square_themes = [pygame.transform.rotate(pygame.image.load(f'{self.path}\\\\black_gold\\\\dark_square.jpg'), 0),\r\n pygame.transform.rotate(pygame.image.load(f'{self.path}\\\\blue_white\\\\dark_square.jpg'), 90)][index]\r\n\r\n # --------------------------------------------------------------\r\n # Transform images\r\n # --------------------------------------------------------------\r\n\r\n self.bg = pygame.transform.smoothscale(bg_themes, (self.win_width, self.win_height))\r\n self.board_edge = pygame.transform.smoothscale(board_edge_themes, (8*self.sq_size + 4*self.margin, 8*self.sq_size + 4*self.margin))\r\n\r\n self.pv_width = self.win_width - 2*self.board_offset + 4*self.margin\r\n self.pv_height = self.win_height - 8*self.sq_size - 3*self.board_offset - self.top_bar_height\r\n self.pv_edge = pygame.transform.smoothscale(pv_edge_themes, (self.pv_width, self.pv_height))\r\n self.pv_image = pygame.transform.smoothscale(pv_image_themes, (self.pv_width - 4*self.margin, self.pv_height - 4*self.margin))\r\n\r\n self.clock_width = self.win_width - 8*self.sq_size - 3*self.board_offset\r\n self.clock_height = int(self.sq_size*1.5)\r\n self.clock_edge = pygame.transform.smoothscale(clock_edge_themes, (self.clock_width, self.clock_height))\r\n self.clock_image = pygame.transform.smoothscale(clock_image_themes, (self.clock_width - 4*self.margin, self.clock_height - 4*self.margin))\r\n\r\n self.piece_images = {}\r\n sprite = pygame.transform.smoothscale(pieces_themes, (self.sq_size*6, self.sq_size*2))\r\n pieces = ['wK', 'wQ', 'wB', 'wN', 'wR', 'wp', 'bK', 'bQ', 'bB', 'bN', 'bR', 'bp']\r\n for i in range(2):\r\n for j in range(6):\r\n self.piece_images[pieces[i*6 + j]] = pygame.Surface.subsurface(sprite, (j*self.sq_size, i*self.sq_size, self.sq_size, self.sq_size))\r\n\r\n self.light_square = [0]*64\r\n light_square_sprite = pygame.transform.smoothscale(light_square_themes, (self.sq_size*8, self.sq_size*8))\r\n for i in range(8):\r\n for j in range(8):\r\n self.light_square[i*8 + j] = pygame.Surface.subsurface(light_square_sprite, (j*self.sq_size, i*self.sq_size, self.sq_size, self.sq_size))\r\n\r\n self.dark_square = [0]*64\r\n dark_square_sprite = pygame.transform.smoothscale(dark_square_themes, (self.sq_size * 8, self.sq_size * 8))\r\n for i in range(8):\r\n for j in range(8):\r\n self.dark_square[i*8 + j] = pygame.Surface.subsurface(dark_square_sprite, (j * self.sq_size, i * self.sq_size, self.sq_size, self.sq_size))\r\n\r\n # --------------------------------------------------------------\r\n # Colors\r\n # --------------------------------------------------------------\r\n\r\n # Normal\r\n self.white = (255, 255, 255)\r\n self.black = (0, 0, 0)\r\n self.gold = (200, 175, 55)\r\n self.red = (255, 0, 0)\r\n self.light_blue = (173, 216, 230)\r\n self.check_red = (200, 12, 12)\r\n self.light_red = (249, 59, 59)\r\n self.green = (0, 255, 0)\r\n self.orange = (255, 128, 0)\r\n self.grey = [(x * 32, x * 32, x * 32) for x in reversed(range(1, 8))] # Grey scale, from light to dark\r\n self.light_grey = (240, 240, 240)\r\n\r\n # Transparent\r\n alpha = [90, 140][index]\r\n self.orange_t = (255, 128, 0, alpha)\r\n self.green_t = (0, 255, 0, alpha)\r\n self.green_t_promo = (0, 255, 0, int(alpha/4))\r\n self.check_red_t = (200, 12, 12, alpha)\r\n self.blue_t = (173, 216, 230, alpha*1.4)\r\n self.grey_t = [(x * 32, x * 32, x * 32, alpha) for x in reversed(range(1, 8))] # Grey scale, from light to dark\r\n\r\n self.board_text_color = [self.gold, self.light_blue][index]\r\n self.button_text_color = [self.white, self.white][index]\r\n\r\n\r\n","repo_name":"eligolfer91/endamat_chess","sub_path":"gui/gui_theme.py","file_name":"gui_theme.py","file_ext":"py","file_size_in_byte":8881,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"81"} +{"seq_id":"39516831256","text":"import evaluate\nimport data\nfrom transformers import AutoModelForSeq2SeqLM,Seq2SeqTrainingArguments,Seq2SeqTrainer,RobertaTokenizer,AutoTokenizer,AutoTokenizer,DataCollatorForSeq2Seq\nimport data\nimport evaluate\nimport argparse\nimport numpy as np\nbase = ''\ncurr_tokenizer = None\ndef get_data():\n return data.clean_data_review()\n\ndef compute_metrics(eval_pred):\n bleu = evaluate.load(\"bleu\")\n predictions, labels = eval_pred\n decoded_preds = curr_tokenizer.batch_decode(predictions, skip_special_tokens=True)\n labels = np.where(labels != -100, labels, curr_tokenizer.pad_token_id)\n decoded_labels = curr_tokenizer.batch_decode(labels, skip_special_tokens=True)\n results_bleu = bleu.compute(predictions=decoded_preds, references=decoded_labels)\n exact_match = evaluate.load(\"exact_match\")\n results_em = exact_match.compute(references=decoded_labels, predictions=decoded_preds,\n ignore_case=True, ignore_punctuation=True)\n \n return {'bleu':results_bleu['bleu'],'EM':round(results_em[\"exact_match\"], 2)}\n\ndef preprocess_function(examples):\n global base\n prefix = \"summarize: \"\n tokenizer = AutoTokenizer.from_pretrained(base)\n inputs = [prefix + doc for doc in examples[\"code\"]]\n model_inputs = tokenizer(inputs, max_length=1024, truncation=True)\n labels = tokenizer(text_target=examples[\"docstring\"], max_length=128, truncation=True)\n model_inputs[\"labels\"] = labels[\"input_ids\"]\n return model_inputs\n\ndef run(consolidated_ds, base='Salesforce/codet5-small'):\n global curr_tokenizer\n tokenizer = AutoTokenizer.from_pretrained(base)\n curr_tokenizer = tokenizer\n model = AutoModelForSeq2SeqLM.from_pretrained(base)\n tokenized_ds = consolidated_ds.map(preprocess_function, batched=True)\n data_collator = DataCollatorForSeq2Seq(tokenizer=tokenizer, model=\"Salesforce/codet5-small\")\n training_args = Seq2SeqTrainingArguments(\n output_dir=\"./results\",\n evaluation_strategy=\"epoch\",\n learning_rate=2e-5,\n per_device_train_batch_size=8,\n per_device_eval_batch_size=8,\n weight_decay=0.01,\n num_train_epochs=5,\n predict_with_generate=True,\n fp16=True\n )\n trainer = Seq2SeqTrainer(\n model=model,\n args=training_args,\n train_dataset=tokenized_ds[\"train\"],\n eval_dataset=tokenized_ds[\"test\"],\n tokenizer=tokenizer,\n data_collator=data_collator,\n compute_metrics=compute_metrics,\n )\n\n trainer.train()\n trainer.predict(tokenized_ds[\"test\"])\n\ndef compare(consolidated_ds, model_str=''):\n global curr_tokenizer\n tokenizer = AutoTokenizer.from_pretrained(model_str)\n curr_tokenizer = tokenizer\n model = AutoModelForSeq2SeqLM.from_pretrained(model_str)\n def preprocess_function(examples):\n prefix = \"summarize: \"\n inputs = [prefix + doc for doc in examples[\"code\"]]\n model_inputs = tokenizer(inputs, max_length=1024, truncation=True)\n labels = tokenizer(text_target=examples[\"docstring\"], max_length=128, truncation=True)\n model_inputs[\"labels\"] = labels[\"input_ids\"]\n return model_inputs\n tokenized_ds = consolidated_ds.map(preprocess_function, batched=True)\n data_collator = DataCollatorForSeq2Seq(tokenizer=tokenizer,model=model_str)\n training_args = Seq2SeqTrainingArguments(\n output_dir=\"./results\",\n evaluation_strategy=\"epoch\",\n learning_rate=2e-5,\n per_device_train_batch_size=32,\n per_device_eval_batch_size=32,\n weight_decay=0.01,\n num_train_epochs=50,\n predict_with_generate=True,\n fp16=True\n )\n trainer = Seq2SeqTrainer(\n model=model,\n args=training_args,\n train_dataset=tokenized_ds[\"train\"],\n eval_dataset=tokenized_ds[\"test\"],\n tokenizer=tokenizer,\n data_collator=data_collator,\n compute_metrics=compute_metrics,\n )\n trainer.predict(tokenized_ds[\"test\"])\n\ndef main():\n global base\n data = get_data()\n run(data, base)\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument(\"-base\", \"--base\", help = \"Base model.\")\n parser.add_argument('-baselines', '--baselines', nargs='+', default=[],help = \"All baseline model checkpoints.\")\n args = parser.parse_args()\n if args.base == False:\n print(\"Missing Base Model!\")\n else:\n main()\n if args.baselines:\n for baseline in args.baselines:\n compare(data,baseline)","repo_name":"Nemoprogramming/NemoCode","sub_path":"run_review.py","file_name":"run_review.py","file_ext":"py","file_size_in_byte":5048,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"36038494480","text":"inmat = [0] *44\nk=0\nlist = [int(e) for e in input().split()]\nfor e in list:\n inmat[e]+=1\nfor i in range(len(inmat)):\n if inmat[i]>1:\n for e in range(1,inmat[i]):\n k+=e\nprint(k)\n","repo_name":"igortereshchenko/amis_python","sub_path":"km73/Tishchenko_Bogdan/5/Task2.py","file_name":"Task2.py","file_ext":"py","file_size_in_byte":201,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"6342755870","text":"from __future__ import print_function\n\nimport collections\nimport cx_Oracle\nimport SampleEnv\n\nclass Connection(cx_Oracle.Connection):\n\n def cursor(self):\n return Cursor(self)\n\n\nclass Cursor(cx_Oracle.Cursor):\n\n def execute(self, statement, args = None):\n prepareNeeded = (self.statement != statement)\n result = super(Cursor, self).execute(statement, args or [])\n if prepareNeeded:\n description = self.description\n if description:\n names = [d[0] for d in description]\n self.rowfactory = collections.namedtuple(\"GenericQuery\", names)\n return result\n\n\n# create new subclassed connection and cursor\nconnection = Connection(SampleEnv.GetMainConnectString())\ncursor = connection.cursor()\n\n# the names are now available directly for each query executed\nfor row in cursor.execute(\"select ParentId, Description from ParentTable\"):\n print(row.PARENTID, \"->\", row.DESCRIPTION)\nprint()\n\nfor row in cursor.execute(\"select ChildId, Description from ChildTable\"):\n print(row.CHILDID, \"->\", row.DESCRIPTION)\nprint()\n\n","repo_name":"edgoes/schema_oracle","sub_path":"python/GenericRowFactory.py","file_name":"GenericRowFactory.py","file_ext":"py","file_size_in_byte":1099,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"81"} +{"seq_id":"32959899590","text":"# -*- coding: utf-8 -*-\n\"\"\"\nSpyder Editor\n\nThis is a temporary script file.\n\"\"\"\n\nimport numpy as np \nimport pandas as pd \nimport re\nimport math\nimport matplotlib.pyplot as plt\nimport random\nfrom numpy import array\nimport itertools\ncn_summary = []\nevent_list = []\nfor chr in sorted(cn_summary):\n cn_summary_ = cn_summary[chr]\n for each_summary in sorted(cn_summary_):\n start, end = each_summary.strip('.')\n event_list.append([chr, int(start), int(end)])\n\ndef check_overlap(e1, e2):\n start = 1\n end = 2\n flag = False\n if e1[0] == e2[0]:\n if e1[start] > e2[start] and e1[start] < e2[end] :\n flag = True\n elif e1[end] > e2[start] and e1[end] < e2[end]:\n flag = True\n elif e1[start]> e2[start] and e1[end] < e2[end]:\n flag = True\n elif e2[start]> e1[start] and e2[end] < e1[end]:\n flag = True\n return flag\n \n \n\ndef compute_score(events):\n count = 0\n n = len(events)\n for i in range(0, len(events)):\n for j in range(0, len(events)): \n if i == j : \n pass \n else: \n if check_overlap(events[i], events[j]):\n count = count + 1\n return count/pow(n, 2)\n\n\ndef plot_distr(length, freq, amp):\n x = np.linspace(start = 0, stop = 1, num = length)\n y = np.zeros(length)\n for i in range(0, 30):\n temp = random.uniform(-math.pi, math.pi)\n temp2 = random.uniform(0, amp)\n temp3 = random.uniform(1,freq)\n for j in range(0, length):\n y[j] = y[j] + math.sin(x[j]*temp3 + temp)*temp2\n y = np.exp(y)\n plt.plot(x,y)\n return x,y\n\n\n#event.append()\ndef check_overlap_test(e1, e2):\n start = 0\n end = 1\n flag = False\n if e1[start] > e2[start] and e1[start] < e2[end] :\n flag = True\n elif e1[end] > e2[start] and e1[end] < e2[end]:\n flag = True\n elif e1[start]> e2[start] and e1[end] < e2[end]:\n flag = True\n elif e2[start]> e1[start] and e2[end] < e1[end]:\n flag = True\n return flag\n\ndef compute_score(events):\n count = 0\n n = len(events)\n for i in range(0, len(events)):\n for j in range(0, len(events)):\n if i == j :\n pass\n else:\n if check_overlap_test(events[i], events[j]) is True:\n count = count + 1\n break\n #print(\"here\")\n\n print(\"overlap count is: \", count)\n print(\"number of events: \", n)\n score = count*1.0/n*1.0\n print(\"percet of events overlap:\", score)\n #score = count*1.0/pow(n-1,2)\n return score\n\ndef overlap_cover_chr(events):\n ind_list = []\n for event in events:\n ind_list.append(event[0])\n ind_list.append(event[1])\n ind_list = sorted(list(set(ind_list)))\n #print(ind_list)\n #ind_list = list(set(ind_list))\n #print(ind_list)\n seg_count = [0] * (len(ind_list)-1)\n for event in events:\n s_index = ind_list.index(event[0])\n e_index = ind_list.index(event[1])\n for i in range(s_index, e_index):\n seg_count[i] = seg_count[i] + 1\n seg = array(seg_count)\n #find where event count is larger than 1\n seg = np.where(seg>1)\n #compute the overlap length \n ol= 0\n print(seg)\n print(type(seg))\n seg = list(seg[0])\n print(type(seg))\n print(seg)\n for j in seg:\n ol = ol + ind_list[j + 1] - ind_list[j]\n #print(ol)\n return ol\n\ndef overlap_cover(events):\n sorted_event = [list(item[1]) for item in itertools.groupby(sorted(events), key=lambda x: x[0])]\n events = []\n for chr_ in sorted_event:\n temp_list = []\n for event in chr_:\n temp_list.append(event[1:])\n events.append(temp_list)\n sum_ = 0\n for chr_ in events:\n sum_ = sum_ + overlap_cover_chr(chr_) \n return sum_\n \nscaling = 100000\nx, y = plot_distr(scaling, 1000, 4)\n# event = []\n# start = np.random.choice(np.arange(scaling), size = 10000, p = y/sum(y))\n# ave_length = 0.014\n# for n in range(0, 30):\n# end = start[n] + np.random.choice([1,-1])* ave_length * scaling\n# event.append([start[n], end])\n# compute_score(event)\n# print(overlap_cover_chr(event)/scaling)\n\n\n# L = [[0,1,2], [1,2,3], [0,2,3]]\n# L = [list(item[1]) for item in itertools.groupby(sorted(L), key=lambda x: x[0])]\n# L_ =[]\n# for items in L:\n# items_ = []\n# for item in items:\n# items_.append(item[1:])\n# L_.append(items_)\n# print(L_)\n \nfrom dendropy.simulate import treesim\n\ndef BD_tree(birth_rate, dir, ntips):\n #global birth_rate\n print(\"birth rate is:\", birth_rate)\n try:\n tree = treesim.birth_death_tree(birth_rate, death_rate=0.75 * birth_rate, gsa_ntax=ntips*2, num_extant_tips=ntips)\n print(tree)\n t = treesim.birth_death_tree(birth_rate, birth_rate*0.75, gsa_ntax=2*ntips, num_extant_tips=ntips)\n except TypeError:\n print(\"dendropy tree simulation failed, try one more time\")\n return BD_tree(birth_rate, dir, ntips)\n\n\n#tree = treesim.birth_death_tree(1, 0.75, gsa_ntax=100, num_extant_tips=200)\n","repo_name":"Androstane/SingleCellCNAsimulator","sub_path":"par_overlap.py","file_name":"par_overlap.py","file_ext":"py","file_size_in_byte":5117,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"81"} +{"seq_id":"14029791324","text":"#!/usr/bin/env python3\nimport argparse\nimport asyncio\nimport functools\nimport logging\nimport os\nimport sys\nfrom typing import Optional\n\nimport asyncssh\nfrom asyncssh import SSHServerProcess, SSHWriter, SSHReader, SSHKey, SSHServerChannel\nfrom asyncssh.connection import SSHConnection, SSHServerConnection\n\n\nclass HoneypotServer(asyncssh.SSHServer):\n\n def __init__(self, logger: logging.Logger):\n self.logger = logger\n self._conn: Optional[SSHServerConnection] = None\n\n def get_peername(self):\n return self._conn.get_extra_info('peername')[0]\n\n def connection_made(self, conn: SSHServerConnection):\n self.logger.info('SSH connection received from %s.',\n conn.get_extra_info('peername')[0])\n self._conn = conn\n\n def connection_lost(self, exc):\n if exc:\n self.logger.error('SSH connection error: %s', exc)\n else:\n self.logger.info('SSH connection closed.')\n\n def begin_auth(self, username):\n return True\n\n def password_auth_supported(self):\n return True\n\n def validate_password(self, username, password):\n self.logger.info(\"User %s (%s) tried password %s\", username, self.get_peername(), password)\n return True\n\n\nasync def handle_client(logger: logging.Logger, process: SSHServerProcess):\n try:\n user = process.get_extra_info('username')\n\n ch: SSHServerChannel = process.channel\n stdout: SSHWriter = process.stdout\n stderr: SSHWriter = process.stderr\n stdin: SSHReader = process.stdin\n\n if process.command:\n logger.info(\"User %s command: %s\", user, process.command)\n\n stdout.write('Welcome!\\n')\n stdout.write(\"%s@myserver:~$\" % user)\n\n try:\n for i in range(0, 5):\n line = await asyncio.wait_for(stdin.readline(), timeout=5)\n logger.info(\"User %s command: %s\", user, line)\n except asyncio.TimeoutError:\n pass\n\n finally:\n process.exit(0)\n\n\nasync def run_server(loop: asyncio.AbstractEventLoop, logger: logging.Logger, port=22):\n config_dir = \"config\"\n host_key: Optional[SSHKey] = None\n\n if not os.path.isdir(config_dir):\n os.mkdir(config_dir)\n\n host_key_file = os.path.join(config_dir, \"host_key\")\n if os.path.isfile(host_key_file):\n logger.info(\"Loading host key (%s)...\", host_key_file)\n host_key = asyncssh.read_private_key(host_key_file)\n else:\n logger.info(\"Generating host key (%s)...\", host_key_file)\n host_key = asyncssh.generate_private_key(\"ssh-rsa\", key_size=1024)\n host_key.write_private_key(host_key_file)\n host_key.write_public_key(\"%s.pub\" % host_key_file)\n\n assert host_key\n\n def server_factory():\n return HoneypotServer(logger)\n\n logger.info(\"Running Honeypot on port %s\", port)\n\n process_factory = functools.partial(handle_client, logger)\n server: asyncio.AbstractServer = await asyncssh.create_server(server_factory, port=port,\n server_host_keys=[host_key],\n process_factory=process_factory)\n\n async with server:\n await server.wait_closed()\n\n\ndef main():\n parser = argparse.ArgumentParser(description=\"Honeypot\")\n parser.add_argument(\"-p\", \"--port\", type=int, help=\"SSH port\", default=22)\n args = parser.parse_args()\n\n # Logging\n root = logging.getLogger()\n root.setLevel(logging.INFO)\n ch = logging.StreamHandler(sys.stdout)\n ch.setLevel(logging.DEBUG)\n formatter = logging.Formatter(\n '%(asctime)s [%(levelname).8s] %(name)s: %(message)s',\n datefmt='%Y-%m-%d %H:%M:%S'\n )\n ch.setFormatter(formatter)\n root.addHandler(ch)\n\n # Disable asyncssh logging\n asyncssh.logging.logger.setLevel(logging.WARNING)\n\n # Start server\n loop = asyncio.get_event_loop()\n loop.run_until_complete(run_server(\n loop=loop,\n logger=logging.getLogger(\"Pot\"),\n port=args.port\n ))\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"mickare/honeysling","sub_path":"honeysling.py","file_name":"honeysling.py","file_ext":"py","file_size_in_byte":4119,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"81"} +{"seq_id":"9902583428","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n\"\"\"Pytorch Dataset class for training. Function used in train.py.\n Extends the class to return also metadata of each scene on which training is performed.\"\"\"\n\n# -- File info -- #\n__author__ = 'Andreas R. Stokholm'\n__contributors__ = 'Andrzej S. Kucik'\n__copyright__ = ['Technical University of Denmark', 'European Space Agency']\n__contact__ = ['stokholm@space.dtu.dk', 'andrzej.kucik@esa.int']\n__version__ = '1.0.0'\n__date__ = '2022-10-17'\n\n# -- Built-in modules -- #\nimport os\n\n# -- Third-party modules -- #\nimport numpy as np\nimport torch\nimport xarray as xr\nfrom torch.utils.data import Dataset\nimport pandas as pd\nimport json\nimport gc\nimport glob\nimport copy\n\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\nfrom utils import SIC_GROUPS, SOD_GROUPS, FLOE_GROUPS\nfrom utils import SIC_LOOKUP, SOD_LOOKUP, FLOE_LOOKUP\n\n# -- Proprietary modules -- #\n\n\nclass AI4ArcticChallengeDataset(Dataset):\n \"\"\"Pytorch dataset for loading batches of patches of scenes from the ASID V2 data set.\"\"\"\n\n def __init__(self, options, files, get_metadata=False):\n self.options = options\n self.files = files\n self.metadata_flag = get_metadata\n\n # set randomness\n np.random.seed(self.options['seed'])\n\n # Channel numbers in patches, includes reference channel.\n self.patch_c = len(self.options['train_variables']) + len(self.options['charts'])\n\n # Create a baseline probablity for sampling each scene.\n # The problem is handled on the scene level, no regard for the randomn cropping.\n # But this may also reduce the chance for overfitting.\n if self.options['resampling']:\n # create a pd dataframe for the files and the seed (like distributions), if it does not exist\n # thus we do not have to generate it every time\n path_to_distribution = os.path.join(self.options['path_to_data'], f\"distribution_{self.options['validation_seed']}.csv\")\n\n # get file from other seed if it exists\n files = glob.glob(os.path.join(self.options['path_to_data'], \"distribution_*.csv\"))\n file = [f for f in files if os.path.isfile(f)]\n file = file[0] if file != [] else None\n\n if os.path.isfile(path_to_distribution):\n # simply load the distribution\n self.distribution = pd.read_csv(path_to_distribution)\n elif file is not None:\n # if one such dataset exists as we only have to change the dataset column and generate new visualizations\n self.distribution = pd.read_csv(file)\n\n with open('datalists/testset.json', 'r') as f:\n testset = json.load(f)\n trainset = options['train_list_extendedNames']\n valset = options['validate_list_extendedNames']\n\n # change the filename column\n for i in range(0, self.distribution.shape[0]):\n if self.distribution[\"filename\"][i] in trainset:\n self.distribution.loc[(i, \"dataset\")] = 'train'\n elif self.distribution[\"filename\"][i] in valset:\n self.distribution.loc[(i, \"dataset\")] = 'val'\n elif self.distribution[\"filename\"][i] in testset:\n self.distribution.loc[(i, \"dataset\")] = 'test'\n else:\n # if no distribution-file exist, generate it\n self.calculate_distribution()\n\n # visualize the distribution and save pictures\n if self.options['visualize_distribution']:\n self.visualize_distribution()\n\n # I need to do it here, because they might not be calculated already - but now they are calculated twice sometimes\n self.calculate_weights()\n\n if self.options['visualize_distribution']:\n self.visualize_distribution(weights=True)\n\n # save the distribution to a csv file\n self.distribution.to_csv(path_to_distribution)\n\n def __len__(self):\n \"\"\"\n Provide number of iterations per epoch. Function required by Pytorch dataset.\n\n Returns\n -------\n Number of iterations per epoch.\n \"\"\"\n return self.options['epoch_len']\n\n def random_crop(self, scene):\n \"\"\"\n Perform random cropping in scene.\n\n Parameters\n ----------\n scene :\n Xarray dataset; a scene from ASID3 ready-to-train challenge dataset.\n\n Returns\n -------\n patch :\n Numpy array with shape (len(train_variables), patch_height, patch_width). None if empty patch.\n \"\"\"\n patch = np.zeros((len(self.options['full_variables']) + len(self.options['amsrenv_variables']),\n self.options['patch_size'], self.options['patch_size']))\n\n # Get random index to crop from.\n row_rand = np.random.randint(low=0, high=scene['SIC'].values.shape[0] - self.options['patch_size'])\n col_rand = np.random.randint(low=0, high=scene['SIC'].values.shape[1] - self.options['patch_size'])\n # Equivalent in amsr and env variable grid.\n amsrenv_row = row_rand / self.options['amsrenv_delta']\n amsrenv_row_dec = int(amsrenv_row - int(amsrenv_row)) # Used in determining the location of the crop in between pixels.\n amsrenv_row_index_crop = amsrenv_row_dec * self.options['amsrenv_delta'] * amsrenv_row_dec\n amsrenv_col = col_rand / self.options['amsrenv_delta']\n amsrenv_col_dec = int(amsrenv_col - int(amsrenv_col))\n amsrenv_col_index_crop = amsrenv_col_dec * self.options['amsrenv_delta'] * amsrenv_col_dec\n\n # - Discard patches with too many meaningless pixels (optional).\n if np.sum(scene['SIC'].values[row_rand: row_rand + self.options['patch_size'],\n col_rand: col_rand + self.options['patch_size']] != self.options['class_fill_values']['SIC']) > 1:\n\n # Crop full resolution variables.\n patch[0:len(self.options['full_variables']), :, :] = scene[self.options['full_variables']].isel(\n sar_lines=range(row_rand, row_rand + self.options['patch_size']),\n sar_samples=range(col_rand, col_rand + self.options['patch_size'])).to_array().values\n # Crop and upsample low resolution variables.\n patch[len(self.options['full_variables']):, :, :] = torch.nn.functional.interpolate(\n input=torch.from_numpy(scene[self.options['amsrenv_variables']].to_array().values[\n :,\n int(amsrenv_row): int(amsrenv_row + np.ceil(self.options['amsrenv_patch'])),\n int(amsrenv_col): int(amsrenv_col + np.ceil(self.options['amsrenv_patch']))]\n ).unsqueeze(0),\n size=self.options['amsrenv_upsample_shape'],\n mode=self.options['loader_upsampling']).squeeze(0)[\n :,\n int(np.around(amsrenv_row_index_crop)): int(np.around(amsrenv_row_index_crop + self.options['patch_size'])),\n int(np.around(amsrenv_col_index_crop)): int(np.around(amsrenv_col_index_crop + self.options['patch_size']))].numpy()\n\n # In case patch does not contain any valid pixels - return None.\n else:\n patch = None\n if self.metadata_flag:\n return patch, row_rand, col_rand\n return patch\n\n def prep_dataset(self, patches):\n \"\"\"\n Convert patches from 4D numpy array to 4D torch tensor.\n\n Parameters\n ----------\n patches : ndarray\n Patches sampled from ASID3 ready-to-train challenge dataset scenes [PATCH, CHANNEL, H, W].\n\n Returns\n -------\n x :\n 4D torch tensor; ready training data.\n y : Dict\n Dictionary with 3D torch tensors for each chart; reference data for training data x.\n \"\"\"\n # Convert training data to tensor.\n x = torch.from_numpy(patches[:, len(self.options['charts']):]).type(torch.float)\n\n # Store charts in y dictionary.\n y = {}\n for idx, chart in enumerate(self.options['charts']):\n y[chart] = torch.from_numpy(patches[:, idx]).type(torch.long)\n\n return x, y\n\n def __getitem__(self, idx):\n \"\"\"\n Get batch. Function required by Pytorch dataset.\n\n Returns\n -------\n x :\n 4D torch tensor; ready training data.\n y : Dict\n Dictionary with 3D torch tensors for each chart; reference data for training data x.\n mask : Dict\n Dictionary with 3D torch tensors for each chart; mask for training data x.\n metadata : pd.DataFrame\n Pandas df with metadata for each patch. Only if self.metadata_flag is True\n \"\"\"\n # Placeholder to fill with data.\n patches = np.zeros((self.options['batch_size'], self.patch_c,\n self.options['patch_size'], self.options['patch_size']))\n sample_n = 0\n metadata_batch = pd.DataFrame(columns=['sentinel_mission_identifier',\n 'image_acquisition_start_date',\n 'image_acquisition_start_date_year', 'image_acquisition_start_date_month', 'image_acquisition_start_date_hour',\n 'row_rand', 'col_rand', 'sample_n',\n 'icechart_provider', 'location'])\n\n # Continue until batch is full.\n while sample_n < self.options['batch_size']:\n # - Open memory location of scene. Uses 'Lazy Loading'.\n scene_id = self.sampler()\n\n # - Load scene\n scene = xr.open_dataset(os.path.join(self.options['path_to_processed_data'], self.files[scene_id]))\n # - Extract patches\n try:\n if self.metadata_flag:\n scene_patch, row_rand, col_rand = self.random_crop(scene)\n else:\n scene_patch = self.random_crop(scene)\n except:\n print(f\"Cropping in {self.files[scene_id]} failed.\")\n print(f\"Scene size: {scene['SIC'].values.shape} for crop shape: ({self.options['patch_size']}, {self.options['patch_size']})\")\n print('Skipping scene.')\n continue\n\n if scene_patch is not None:\n # -- Stack the scene patches in patches\n patches[sample_n, :, :, :] = scene_patch\n sample_n += 1 # Update the index.\n\n if self.metadata_flag:\n # -- Add metadata to metadata_batch\n file_name = scene.attrs['original_id']\n file_name_split = file_name.split('_')\n\n sentinel_mission_identifier = file_name_split[0]\n image_acquisition_start_date = file_name_split[4]\n image_acquisition_start_date = pd.to_datetime(image_acquisition_start_date, format='%Y%m%dT%H%M%S')\n image_acquisition_start_date_year = image_acquisition_start_date.year\n image_acquisition_start_date_month = image_acquisition_start_date.month\n image_acquisition_start_date_hour = image_acquisition_start_date.hour\n icechart_provider = str(scene.attrs['ice_service'])\n if icechart_provider == 'cis':\n location = file_name_split[11]\n elif icechart_provider == 'dmi':\n location = file_name_split[12]\n\n metadata_sample = pd.Series({'sentinel_mission_identifier': sentinel_mission_identifier,\n 'image_acquisition_start_date': image_acquisition_start_date,\n 'image_acquisition_start_date_year': image_acquisition_start_date_year,\n 'image_acquisition_start_date_month': image_acquisition_start_date_month,\n 'image_acquisition_start_date_hour': image_acquisition_start_date_hour,\n 'row_rand': row_rand,\n 'col_rand': col_rand,\n 'sample_n': sample_n,\n 'icechart_provider': icechart_provider,\n 'location': location})\n metadata_batch = pd.concat([metadata_batch, metadata_sample.to_frame().T], ignore_index=True)\n\n # Prepare training arrays\n x, y = self.prep_dataset(patches=patches)\n\n # - calculate mask\n masks = {}\n for chart in self.options['charts']:\n masks[chart] = (y[chart] == self.options['class_fill_values'][chart]).squeeze()\n\n if self.metadata_flag:\n return x, y, masks, metadata_batch\n else:\n return x, y, masks, None\n\n def sampler(self, mode='random'):\n \"\"\"\n Returns the id of a scene to sample from.\n The resampler takes the following factors into account:\n - The number of samples already from a scene divided by the size of the scene.\n - The difficulity of a scene as judged by human experts.\n - The distribution of the test set regarding geographic location, time of year # , and ice type.\n - The previous performance of the model on a scene.\n\n Parameters\n ----------\n mode : str\n 'random' or 'importance'. Default is 'random'.\n\n Returns\n -------\n scene_id : int\n Id of the scene to sample from.\n \"\"\"\n if not self.options['resampling']:\n return np.random.randint(low=0, high=len(self.files), size=1).item()\n elif self.options['resampling']:\n # the id is the index of the scene in self.files\n id = np.random.choice(a=self.distribution[self.distribution['dataset'] == 'train'].index,\n p=self.distribution[self.distribution['dataset'] == 'train']['weight'].values,\n size=1, replace=True).item()\n filename_of_id = self.distribution.loc[(id, 'filename')]\n filename_of_id = filename_of_id[17:32] + '_' + filename_of_id[77:80] + '_prep.nc' # get the train_list filename\n return self.files.index(filename_of_id)\n\n def visualize_distribution(self, weights=False):\n \"\"\"\n Visualize the distribution of the train, val and test set.\n\n Parameters\n ----------\n weights : bool\n If True, the right side distribution is the training set distribution weighted by the resampling weights.\n Otherwise, it is weighted by the size of the scenes.\n \"\"\"\n path_to_visualization = os.path.join(self.options['path_to_data'],\n f\"distribution_{self.options['validation_seed']}_\")\n\n plot_args_one = dict(hue=\"dataset\", data=self.distribution, stat='percent', common_norm=True)\n postfix = \"\"\n if not weights:\n plot_args_two = copy.deepcopy(plot_args_one)\n plot_args_two['legend'] = False\n plot_args_two['weights'] = 'size'\n postfix = \"_size\"\n else:\n total_n_samples_train = self.distribution[self.distribution['dataset'] == 'train'].shape[0]\n total_n_samples_test = self.distribution[self.distribution['dataset'] == 'test'].shape[0]\n\n plot_args_two = copy.deepcopy(plot_args_one)\n distribution_local = copy.deepcopy(self.distribution[self.distribution['dataset'] != 'val'])\n distribution_local.loc[distribution_local['dataset'] == 'test', 'weight'] = total_n_samples_train / total_n_samples_test\n plot_args_two['common_norm'] = False # via definition of the above weights\n plot_args_two['data'] = distribution_local\n plot_args_two['legend'] = False\n plot_args_two['weights'] = 'weight'\n postfix = \"_weight\"\n\n # plot the distribution of the months, grouped by dataset versus testset\n # norm on the size column\n # show one plot not weighted on the size and one weighted on the size of the scenes\n fig, axs = plt.subplots(ncols=2, sharey=True, figsize=(16, 8), dpi=400)\n sns.histplot(y=\"month\", ax=axs[0], **plot_args_one)\n sns.histplot(y=\"month\", ax=axs[1], **plot_args_two)\n plt.savefig(f'{path_to_visualization}month{postfix}.png')\n plt.close()\n\n # plot the distribution of the years, grouped by dataset versus testset\n fig, axs = plt.subplots(ncols=2, sharey=True, figsize=(16, 8), dpi=400)\n sns.histplot(y=\"year\", ax=axs[0], **plot_args_one)\n sns.histplot(y=\"year\", ax=axs[1], **plot_args_two)\n plt.savefig(f'{path_to_visualization}year{postfix}.png')\n plt.close()\n\n # plot the distribution of the location, grouped by dataset versus testset\n fig, axs = plt.subplots(ncols=2, sharey=True, figsize=(16, 8), dpi=400)\n sns.histplot(y=\"location\", ax=axs[0], **plot_args_one)\n sns.histplot(y=\"location\", ax=axs[1], **plot_args_two)\n plt.savefig(f'{path_to_visualization}location{postfix}.png')\n plt.close()\n\n # plot the distribution of the icechart_provider, grouped by dataset versus testset\n fig, axs = plt.subplots(ncols=2, sharey=True, figsize=(16, 8), dpi=400)\n sns.histplot(y=\"icechart_provider\", ax=axs[0], **plot_args_one)\n sns.histplot(y=\"icechart_provider\", ax=axs[1], **plot_args_two)\n plt.savefig(f'{path_to_visualization}icechart_provider{postfix}.png')\n plt.close()\n\n # plot the distribution of the Sentinel_mission_identifier, grouped by dataset versus testset\n fig, axs = plt.subplots(ncols=2, sharey=True, figsize=(16, 8), dpi=400)\n sns.histplot(y=\"Sentinel_mission_identifier\", ax=axs[0], **plot_args_one)\n sns.histplot(y=\"Sentinel_mission_identifier\", ax=axs[1], **plot_args_two)\n plt.savefig(f'{path_to_visualization}Sentinel_mission_identifier{postfix}.png')\n plt.close()\n\n # collect as much garbage as possible\n del fig, axs, path_to_visualization\n plt.clf()\n plt.close()\n gc.collect()\n\n def calculate_weights(self):\n \"\"\"\n Calculate the rescaling weights for the resampling.\n For every sample, a weight is calculated which follows the distribution of the test set.\n It is necessary because test distribution is (purposefully) altered, as experts have selected the most difficult scenes to be in the test set.\n\n Only weighting by the location makes the distributions in the relevant variables (month, year, icechart_provider, Sentinel_mission_identifier) already pretty similar.\n # TODO: find a better method!\n\n Problem: For the discrete multi-class variables, some are not represented in the test set at all. Either I have to\n - remove them from the training set\n - cannot fully represent the test set distribution.\n I opted for the second option. Each class has at least a ratio of 1/(n_classes*3) of the test set.\n \"\"\"\n # pre-calulate the weights for the training\n total_n_samples_train = self.distribution[self.distribution['dataset'] == 'train'].shape[0]\n total_n_samples_test = self.distribution[self.distribution['dataset'] == 'test'].shape[0]\n self.distribution['weight'] = 1. / total_n_samples_train # uniform for all training samples\n self.distribution.loc[self.distribution['dataset'] != 'train', 'weight'] = 0. # no weight for the val, test set\n print(f\"total_n_samples_train: {total_n_samples_train}\")\n\n # resampling according to the distribution of the test set\n # weighting by the month\n ratio_month_train = self.distribution[self.distribution['dataset'] == 'train']['month'].value_counts() / total_n_samples_train\n ratio_month_test_temp = self.distribution[self.distribution['dataset'] == 'test']['month'].value_counts() / total_n_samples_test\n # it can be the case that a month is not present in the test set\n months = np.arange(1, 13)\n ratio_month_test = pd.Series({month: ratio_month_test_temp[month] if month in ratio_month_test_temp else (1/(12*3)) for month in months})\n # normalize it to sum = 1\n ratio_month_test = ratio_month_test / ratio_month_test.sum()\n print(f\"Sum of the weights for the month: {ratio_month_test.sum()}\")\n self.distribution['month_weight'] = 1 + (ratio_month_test[self.distribution['month']].values - ratio_month_train[self.distribution['month']].values) / ratio_month_train[self.distribution['month']].values\n print(f\"Sum of the weights for the month: {self.distribution[self.distribution['dataset'] == 'train']['month_weight'].sum()}\")\n\n # weighting by the ice chart provider\n ratio_icechart_provider_train = self.distribution[self.distribution['dataset'] == 'train']['icechart_provider'].value_counts() / total_n_samples_train\n ratio_icechart_provider_test = self.distribution[self.distribution['dataset'] == 'test']['icechart_provider'].value_counts() / total_n_samples_test\n self.distribution['icechart_provider_weight'] = 1 + (ratio_icechart_provider_test[self.distribution['icechart_provider']].values - ratio_icechart_provider_train[self.distribution['icechart_provider']].values) / ratio_icechart_provider_train[self.distribution['icechart_provider']].values\n print(f\"Sum of the weights for the icechart_provider: {self.distribution[self.distribution['dataset'] == 'train']['icechart_provider_weight'].sum()}\")\n\n # weighting by the Sentinel mission identifier\n ratio_Sentinel_mission_identifier_train = self.distribution[self.distribution['dataset'] == 'train']['Sentinel_mission_identifier'].value_counts() / total_n_samples_train\n ratio_Sentinel_mission_identifier_test = self.distribution[self.distribution['dataset'] == 'test']['Sentinel_mission_identifier'].value_counts() / total_n_samples_test\n self.distribution['Sentinel_mission_identifier_weight'] = 1 + (ratio_Sentinel_mission_identifier_test[self.distribution['Sentinel_mission_identifier']].values - ratio_Sentinel_mission_identifier_train[self.distribution['Sentinel_mission_identifier']].values) / ratio_Sentinel_mission_identifier_train[self.distribution['Sentinel_mission_identifier']].values\n print(f\"Sum of the weights for the Sentinel_mission_identifier: {self.distribution[self.distribution['dataset'] == 'train']['Sentinel_mission_identifier_weight'].sum()}\")\n\n # weighting by the location\n ratio_location_train_temp = self.distribution[self.distribution['dataset'] == 'train']['location'].value_counts() / total_n_samples_train\n ratio_location_test_temp = self.distribution[self.distribution['dataset'] == 'test']['location'].value_counts() / total_n_samples_test\n # it can be the case that a location is not present in the test set\n locations = self.distribution['location'].unique()\n n_locations = len(locations)\n ratio_location_train = pd.Series({location: ratio_location_train_temp[location] if location in ratio_location_train_temp.keys() else (1./(n_locations*3.)) for location in locations})\n ratio_location_test = pd.Series({location: ratio_location_test_temp[location] if location in ratio_location_test_temp.keys() else (1./(n_locations*3.)) for location in locations})\n # normalize it to sum = 1\n ratio_location_train = ratio_location_train / ratio_location_train.sum()\n ratio_location_test = ratio_location_test / ratio_location_test.sum()\n self.distribution['location_weight'] = 1 + (ratio_location_test[self.distribution['location']].values - ratio_location_train[self.distribution['location']].values) / ratio_location_train[self.distribution['location']].values\n print(f\"Sum of the weights for the location: {self.distribution[self.distribution['dataset'] == 'train']['location_weight'].sum()}\")\n\n # adding weight for difficult locations\n self.distribution['difficult_location'] = self.distribution['location'].isin(self.options['difficult_locations'])\n negative_weight = self.distribution['difficult_location'].value_counts()[True] / self.distribution['difficult_location'].value_counts()[False]\n self.distribution['difficult_location'] = self.distribution['difficult_location'].map({False: -negative_weight, True: 1})\n additional_factor_difficult_location = (1 / total_n_samples_train)\n self.distribution['difficult_location_weight'] = 1 + (self.distribution['difficult_location'] * additional_factor_difficult_location)\n print(f\"Sum of the weights for the difficult_location: {self.distribution[self.distribution['dataset'] == 'train']['difficult_location_weight'].sum()}\")\n\n # # weighting by the size of the scenes\n # TODO?\n\n # for now only weighting by the location until I found a better solution\n # doing the weighting and normalizing after every step (only really needed for location)\n # self.distribution['weight'] *= self.distribution['month_weight']\n # print(f\"weight values after month: {self.distribution['weight'].values.sum()}\")\n # self.distribution['weight'] /= self.distribution['weight'].sum()\n\n # self.distribution['weight'] *= self.distribution['icechart_provider_weight']\n # print(f\"weight values after icechart_provider: {self.distribution['weight'].values.sum()}\")\n # self.distribution['weight'] /= self.distribution['weight'].sum()\n\n # self.distribution['weight'] *= self.distribution['Sentinel_mission_identifier_weight']\n # print(f\"weight values after Sentinel_mission_identifier: {self.distribution['weight'].values.sum()}\")\n # self.distribution['weight'] /= self.distribution['weight'].sum()\n\n self.distribution['weight'] *= self.distribution['location_weight']\n print(f\"weight values after location: {self.distribution['weight'].values.sum()}\")\n self.distribution['weight'] /= self.distribution['weight'].sum()\n\n # self.distribution['weight'] *= self.distribution['difficult_location_weight']\n # print(f\"weight values after difficult_location: {self.distribution['weight'].values.sum()}\")\n # self.distribution['weight'] /= self.distribution['weight'].sum()\n # print(f\"weight values after normalization: {self.distribution['weight'].values.sum()}\")\n\n def calculate_distribution(self):\n # code close to the one from distributions.ipynb\n with open('datalists/testset.json', 'r') as f:\n testset = json.load(f)\n trainset = self.options['train_list_extendedNames']\n valset = self.options['validate_list_extendedNames']\n\n # create dataframes from the lists\n trainset_df = pd.DataFrame(trainset, columns=['filename'])\n testset_df = pd.DataFrame(testset, columns=['filename'])\n valset_df = pd.DataFrame(valset, columns=['filename'])\n\n # add a new column indicating the dataset\n trainset_df['dataset'] = 'train'\n testset_df['dataset'] = 'test'\n valset_df['dataset'] = 'val'\n\n # concatenate the dataframes\n self.distribution = pd.concat([trainset_df, testset_df, valset_df], ignore_index=True)\n\n # check for duplicates\n if self.distribution.duplicated(subset='filename').any():\n raise ValueError('There are duplicates in the distribution dataframe')\n\n # split the filename into the appropriate columns\n self.distribution[\"Sentinel_mission_identifier\"] = self.distribution['filename'].str.split(\"_\").str[0]\n self.distribution[\"misc\"] = self.distribution['filename'].str.split(\"_\").str[1:4]\n self.distribution[\"image_acquisition_start_date\"] = self.distribution['filename'].str.split(\"_\").str[4]\n self.distribution[\"image_acquisition_start_date\"] = pd.to_datetime(self.distribution[\"image_acquisition_start_date\"], format='%Y%m%dT%H%M%S')\n self.distribution[\"image_acquisition_end_date\"] = self.distribution['filename'].str.split(\"_\").str[5]\n self.distribution[\"image_acquisition_end_date\"] = pd.to_datetime(self.distribution[\"image_acquisition_end_date\"], format='%Y%m%dT%H%M%S')\n self.distribution[\"image_type\"] = self.distribution['filename'].str.split(\"_\").str[9]\n self.distribution[\"icechart_provider\"] = self.distribution['filename'].str.split(\"_\").str[10]\n self.distribution[\"location\"] = np.nan\n self.distribution[\"icechart_date\"] = np.nan\n\n for i in range(0, len(self.distribution)):\n if self.distribution[\"icechart_provider\"][i] == 'cis':\n self.distribution.loc[(i, \"location\")] = self.distribution['filename'][i].split(\"_\")[11]\n try:\n self.distribution.loc[(i, \"icechart_date\")] = self.distribution['filename'][i].split(\"_\")[12]\n self.distribution.loc[(i, \"icechart_date\")] = pd.to_datetime(self.distribution[\"icechart_date\"][i], format='%Y%m%dT%H%MZ')\n except ValueError:\n self.distribution.loc[(i, \"icechart_date\")] = np.nan\n elif self.distribution[\"icechart_provider\"][i] == 'dmi':\n try:\n self.distribution.loc[(i, \"icechart_date\")] = self.distribution['filename'][i].split(\"_\")[11]\n self.distribution.loc[(i, \"icechart_date\")] = pd.to_datetime(self.distribution[\"icechart_date\"][i], format='%Y%m%d%H%M%S')\n except ValueError:\n self.distribution.loc[(i, \"icechart_date\")] = np.nan\n self.distribution.loc[(i, \"location\")] = self.distribution['filename'][i].split(\"_\")[12]\n\n # add columns called hour, month, year based on the image_acquisition_start_date\n self.distribution[\"month\"] = self.distribution[\"image_acquisition_start_date\"].dt.month.astype(int)\n self.distribution[\"hour\"] = self.distribution[\"image_acquisition_start_date\"].dt.hour.astype(int)\n self.distribution[\"year\"] = self.distribution[\"image_acquisition_start_date\"].dt.year.astype(int)\n\n # create empty columns\n classes = {}\n classes['SIC'] = list(SIC_GROUPS.keys()) + [SIC_LOOKUP['mask']]\n classes['SOD'] = list(SOD_GROUPS.keys()) + [SOD_LOOKUP['mask']]\n classes['FLOE'] = list(FLOE_GROUPS.keys()) + [FLOE_LOOKUP['mask']]\n\n self.distribution[\"size\"] = np.nan\n for key, value in classes.items():\n for i in range(0, len(value)):\n self.distribution[f'{key}_{str(value[i])}'] = np.nan\n\n # the prepared scenes are uniquely identified by /__prep.nc\n for i in range(0, len(self.distribution)):\n gc.collect()\n\n # create the path and get the size of the file\n path = None\n if self.distribution[\"dataset\"][i] == 'train' or self.distribution[\"dataset\"][i] == 'val':\n try:\n path = os.path.join(self.options['path_to_processed_data'], self.distribution[\"image_acquisition_start_date\"][i].strftime('%Y%m%dT%H%M%S') + '_' + self.distribution[\"icechart_provider\"][i] + '_prep.nc')\n self.distribution.loc[(i, \"size\")] = os.path.getsize(path)\n except FileNotFoundError:\n print(self.distribution.iloc[i])\n elif self.distribution[\"dataset\"][i] == 'test':\n try:\n path = os.path.join(self.options['path_to_processed_data'], 'test_data', self.distribution[\"image_acquisition_start_date\"][i].strftime('%Y%m%dT%H%M%S') + '_' + self.distribution[\"icechart_provider\"][i] + '_prep.nc')\n self.distribution.loc[(i, \"size\")] = os.path.getsize(path)\n except FileNotFoundError:\n print(self.distribution.loc[i])\n\n # open the file and get the distribution of the different chart classes (maybe unnecessary)\n scene = xr.open_dataset(path)\n\n for chart, value in classes.items():\n for j in range(0, len(value)):\n if self.distribution[\"dataset\"][i] == 'train' or self.distribution[\"dataset\"][i] == 'val':\n self.distribution.loc[(i, f'{chart}_{str(value[j])}')] = np.count_nonzero(scene[chart] == value[j])\n elif self.distribution[\"dataset\"][i] == 'test':\n continue\n\n del scene\n\n\nclass AI4ArcticChallengeTestDataset(Dataset):\n \"\"\"Pytorch dataset for loading full scenes from the ASID ready-to-train challenge dataset for inference.\"\"\"\n\n def __init__(self, options, files, test=False, get_metadata=False):\n self.options = options\n self.files = files\n self.test = test\n self.metadata_flag = get_metadata\n\n def __len__(self):\n \"\"\"\n Provide the number of iterations. Function required by Pytorch dataset.\n\n Returns\n -------\n Number of scenes per validation.\n \"\"\"\n return len(self.files)\n\n def prep_scene(self, scene):\n \"\"\"\n Upsample low resolution to match charts and SAR resolution. Convert patches from 4D numpy array to 4D torch tensor.\n\n Parameters\n ----------\n scene :\n\n Returns\n -------\n x :\n 4D torch tensor, ready training data.\n y :\n Dict with 3D torch tensors for each reference chart; reference inference data for x. None if test is true.\n \"\"\"\n x = torch.cat((torch.from_numpy(scene[self.options['sar_variables']].to_array().values).unsqueeze(0),\n torch.nn.functional.interpolate(\n input=torch.from_numpy(scene[self.options['amsrenv_variables']].to_array().values).unsqueeze(0),\n size=scene['nersc_sar_primary'].values.shape,\n mode=self.options['loader_upsampling'])),\n axis=1)\n\n if not self.test:\n y = {chart: scene[chart].values for chart in self.options['charts']}\n\n else:\n y = None\n\n return x, y\n\n def __getitem__(self, idx):\n \"\"\"\n Get scene. Function required by Pytorch dataset.\n\n Returns\n -------\n x :\n 4D torch tensor; ready inference data.\n y :\n Dict with 3D torch tensors for each reference chart; reference inference data for x. None if test is true.\n masks :\n Dict with 2D torch tensors; mask for each chart for loss calculation. Contain only SAR mask if test is true.\n name : str\n Name of scene.\n metadata: pd.DataFrame\n Pandas df with metadata for each scene. Only if self.metadata is True.\n \"\"\"\n scene = xr.open_dataset(os.path.join(self.options['path_to_processed_data'], self.files[idx]))\n\n metadata_scene = pd.DataFrame(columns=['sentinel_mission_identifier',\n 'image_acquisition_start_date',\n 'image_acquisition_start_date_year', 'image_acquisition_start_date_month', 'image_acquisition_start_date_hour',\n 'row_rand', 'col_rand', 'sample_n',\n 'icechart_provider', 'location'])\n\n x, y = self.prep_scene(scene)\n name = self.files[idx]\n\n if not self.test:\n masks = {}\n for chart in self.options['charts']:\n masks[chart] = (y[chart] == self.options['class_fill_values'][chart]).squeeze()\n\n else:\n masks = (x.squeeze()[0, :, :] == self.options['train_fill_value']).squeeze()\n\n # - get metadata\n if self.metadata_flag:\n file_name = scene.attrs['original_id']\n file_name_split = file_name.split('_')\n\n sentinel_mission_identifier = file_name_split[0]\n image_acquisition_start_date = file_name_split[4]\n image_acquisition_start_date = pd.to_datetime(image_acquisition_start_date, format='%Y%m%dT%H%M%S')\n image_acquisition_start_date_year = image_acquisition_start_date.year\n image_acquisition_start_date_month = image_acquisition_start_date.month\n image_acquisition_start_date_hour = image_acquisition_start_date.hour\n icechart_provider = str(scene.attrs['ice_service'])\n if icechart_provider == 'cis':\n location = file_name_split[11]\n elif icechart_provider == 'dmi':\n location = file_name_split[12]\n\n # -- non-useful metadata\n row_rand = np.nan\n col_rand = np.nan\n sample_n = np.nan\n\n metadata_scene = pd.DataFrame({'sentinel_mission_identifier': sentinel_mission_identifier,\n 'image_acquisition_start_date': image_acquisition_start_date,\n 'image_acquisition_start_date_year': image_acquisition_start_date_year,\n 'image_acquisition_start_date_month': image_acquisition_start_date_month,\n 'image_acquisition_start_date_hour': image_acquisition_start_date_hour,\n 'row_rand': row_rand,\n 'col_rand': col_rand,\n 'sample_n': sample_n,\n 'icechart_provider': icechart_provider,\n 'location': location}, index=[0])\n\n if self.metadata_flag and not self.test:\n return x, y, masks, name, metadata_scene\n elif not self.test:\n return x, y, masks, name, None\n return x, y, masks, name\n\n\ndef get_variable_options(train_options: dict):\n \"\"\"\n Get amsr and env grid options, crop shape and upsampling shape.\n\n Parameters\n ----------\n train_options: dict\n Dictionary with training options.\n\n Returns\n -------\n train_options: dict\n Updated with amsrenv options.\n \"\"\"\n train_options['amsrenv_delta'] = 50 / (train_options['pixel_spacing'] // 40)\n train_options['amsrenv_patch'] = train_options['patch_size'] / train_options['amsrenv_delta']\n train_options['amsrenv_patch_dec'] = int(train_options['amsrenv_patch'] - int(train_options['amsrenv_patch']))\n train_options['amsrenv_upsample_shape'] = (int(train_options['patch_size'] +\n train_options['amsrenv_patch_dec'] *\n train_options['amsrenv_delta']),\n int(train_options['patch_size'] +\n train_options['amsrenv_patch_dec'] *\n train_options['amsrenv_delta']))\n train_options['sar_variables'] = [variable for variable in train_options['train_variables']\n if 'sar' in variable or 'map' in variable]\n train_options['full_variables'] = np.hstack(\n (train_options['charts'], train_options['sar_variables']))\n train_options['amsrenv_variables'] = [variable for variable in train_options['train_variables']\n if 'sar' not in variable and 'map' not in variable]\n\n return train_options\n","repo_name":"MagnusOstertag/AI4ArcticSeaIceChallenge","sub_path":"loaders_improvements.py","file_name":"loaders_improvements.py","file_ext":"py","file_size_in_byte":39954,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"4638210381","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport sys\n\nsys.path.append(\"..\")\nfrom pytorch.data_process.dataprocess import *\n\n\nmax_length = 5\n\n\n# 编码器(LSTM)\nclass Seq2SeqEncoder(nn.Module):\n '''\n batch_first = True\n '''\n\n def __init__(self, input_size, hidden_size, num_layers, dropout=0):\n super(Seq2SeqEncoder, self).__init__()\n self.hidden_size = hidden_size\n self.num_layers = num_layers\n self.lstm = nn.LSTM(input_size=input_size, hidden_size=self.hidden_size,\n num_layers=self.num_layers, batch_first=True, dropout=dropout)\n\n def forward(self, input):\n '''\n :param input: 3d tensor [bs, seq, hs]\n :return: 各个时刻的隐藏状态值output_states [bs,seq,hs]和最后时刻的隐藏状态值final_h [bs,1,hs]\n '''\n self.batch_size = input.shape[0]\n\n output_states, (final_h, final_n) = self.lstm(input)\n return output_states, final_h\n\n\n# 注意力机制\nclass Seq2SeqAttentionMechanism(nn.Module):\n # 实现dot-product的attention\n def __init__(self):\n super(Seq2SeqAttentionMechanism, self).__init__()\n\n def forward(self, decoder_state_t, encoder_states):\n # decoder_state_t: [bs, hidden_size] 因为后面用的lstmcell,输出维度会少一维\n # encoder_states: [bs, seq_length, hidden_size]\n bs, seq_length, hidden_size = encoder_states.shape\n # 扩中间一维 decoder_state_t -> [bs, 1, hidden_size]\n decoder_state_t = decoder_state_t.unsqueeze(1)\n # 使其维度和encoder_states一样,后续点乘需要 decoder_state_t -> [bs, seq_length, hidden_size]\n decoder_state_t = torch.tile(decoder_state_t, dims=(1, seq_length, 1))\n # 用于注意力机制计算的中间score\n # decoder_state_t与encoder_states按元素相乘,按最后一维hidden_size(就是时间维)求和压缩, dim=-1\n score = torch.sum(decoder_state_t * encoder_states, dim=-1) # [bs, seq_length]\n # dim=-1, 过softmax, attn_prob代表当前decoder_state与encoder中每一个时刻的关系的权重\n attn_prob = F.softmax(score, dim=-1) # [bs, seq_length]\n\n # 权重与encoder_states相乘,最后扩了一维->[bs, seq_length, 1],并且用了broadcast机制\n # 然后在时间维进行求和压缩\n context = torch.sum(attn_prob.unsqueeze(-1) * encoder_states, dim=1) # [bs, hidden_size]\n\n return attn_prob, context\n\n\n# 解码器\nclass Seq2SeqDecoder(nn.Module):\n def __init__(self, input_size, hidden_size, output_size, start_id=0, dropout=0):\n super(Seq2SeqDecoder, self).__init__()\n self.lstm_cell = nn.LSTMCell(input_size=input_size, hidden_size=hidden_size)\n # 由于把context和decoder的输出h拼起来之后再给入全连接层,所以hidden_size * 2\n self.fc = nn.Linear(hidden_size * 2, output_size)\n # 实例化注意力机制\n self.attention_mechanism = Seq2SeqAttentionMechanism()\n\n self.input_size = input_size\n self.hidden_size = hidden_size\n self.output_size = output_size\n self.start_id = start_id\n\n def forward(self, shifted_target, encoder_outputs):\n # 训练阶段调用 teacher forcing训练\n bs, target_length, input_size = shifted_target.shape\n bs, seq_length, hidden_size = encoder_outputs.shape\n\n output = torch.zeros(bs, target_length, self.output_size)\n probs = torch.zeros(bs, target_length, seq_length)\n # 遍历整个序列\n for t in range(target_length):\n decoder_input_t = torch.zeros(bs, 1, input_size)\n # 如果t为0,则输入初始值为零的h_t,c_t以及零向量decoder_input_t\n # 如果t不为0,则输入上一时刻的h_t,c_t以及shifted_target给该时刻的lstmcell\n if t == 0:\n h_t, c_t = self.lstm_cell(decoder_input_t)\n else:\n decoder_input_t = shifted_target[:, t, :]\n h_t, c_t = self.lstm_cell(decoder_input_t, (h_t, c_t))\n # 将给时刻的h_t和encoder_outputs送入注意力机制中生成attn_prob和context\n attn_prob, context = self.attention_mechanism(h_t, encoder_outputs)\n # 拼接context和h_t作为decoder_output [bs, hidden_size * 2]\n decoder_output = torch.cat((context, h_t), dim=-1)\n # 将decoder_output送入全连接层,获得t时刻的output: [bs, output_size] 和权重值attn_prob\n output[:, t, :] = self.fc(decoder_output)\n probs[:, t, :] = attn_prob\n\n return output, probs\n\n def inference(self, encoder_outputs):\n # 推理调用\n h_t = None\n results = []\n length = 0\n bs, seq_length, hidden_size = encoder_outputs.shape\n # decoder_input_prev = torch.zeros(bs, 1, hidden_size)\n # output:[bs, output_size]\n output = torch.zeros(bs, self.output_size)\n\n while True:\n # 初始化一个零向量作为解码器的初始输入,input_t: [bs, input_size]\n decoder_input_t = torch.zeros(bs, self.input_size)\n if h_t is None:\n h_t, c_t = self.lstm_cell(decoder_input_t)\n else:\n # 下一时刻的输入是上一时刻的输出h_t\n decoder_input_t = h_t\n h_t, c_t = self.lstm_cell(decoder_input_t, (h_t, c_t))\n # h_t作为查询向量,输入注意力机制输出attn_prob和context\n attn_prob, context = self.attention_mechanism(h_t, encoder_outputs)\n # context和h_t concat之后输入全连接层,decoder_output: [bs, hidden_size * 2]\n decoder_output = torch.cat((context, h_t), -1)\n # 过全连接层,得到需要的输出,output: [bs, output_size]\n output = self.fc(decoder_output)\n results.append(output)\n\n length = length + 1\n if length == max_length:\n print(\"stop decoding!\")\n break\n\n prediction = torch.stack(results, dim=0)\n return prediction\n\n\nclass Model(nn.Module):\n def __init__(self, input_size, hidden_size, output_size, num_layers=1, dropout=1):\n super(Model, self).__init__()\n self.hidden_size = hidden_size\n self.num_layers = num_layers\n self.encoder = Seq2SeqEncoder(input_size=input_size, hidden_size=hidden_size, num_layers=num_layers)\n self.decoder = Seq2SeqDecoder(input_size=input_size, hidden_size=hidden_size, output_size=output_size)\n # 前向传播,训练用\n def forward(self, input_sequence, shifted_target):\n encoder_states, final_h = self.encoder(input_sequence)\n probs, output = self.decoder(shifted_target, encoder_states)\n\n return probs, output\n\n # 推理\n def inference(self, input_sequence):\n encoder_states, final_h = self.encoder(input_sequence)\n prediction = self.decoder(encoder_states)\n\n return prediction\n\n\nif __name__ == \"__main__\":\n # 网络参数\n seq_length = 5\n input_size = 4\n output_size = 2\n num_layers = 1\n hidden_size = 128\n","repo_name":"gah07123/VehicleTrajectoryPrediction","sub_path":"MyAttention-based-seq2seq/mycode/attention-based-seq2seq.py","file_name":"attention-based-seq2seq.py","file_ext":"py","file_size_in_byte":7162,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"81"} +{"seq_id":"8577696724","text":"\"\"\"\nSingleton Utility Module\n\nThis module provides a simple utility class for implementing the Singleton design pattern.\nIt ensures that only one instance of a class exists at any given time, and it provides a\nmechanism to access that instance.\n\"\"\"\n\n\nclass SingletonInstance:\n \"\"\"\n A base class for implementing the Singleton design pattern.\n\n This utility ensures that only one instance of a class exists at any given time,\n and it provides a mechanism to access or create that instance.\n\n Usage:\n To make a class a Singleton, inherit from SingletonInstance, and then use the 'instance'\n class method to access or create the Singleton instance.\n\n Example:\n class MySingleton(SingletonInstance):\n # Your class implementation here\n\n my_instance = MySingleton.instance()\n \"\"\"\n\n __instance = None\n\n @classmethod\n def __get_instance(cls):\n \"\"\"\n Get the existing Singleton instance.\n\n Returns:\n object: The existing Singleton instance if it exists, or None if not.\n \"\"\"\n return cls.__instance\n\n @classmethod\n def instance(cls, *args, **kwargs):\n \"\"\"\n Access or create the Singleton instance.\n\n If an instance already exists, it returns that instance; otherwise, it creates\n a new instance with the provided arguments.\n\n Args:\n *args: Positional arguments for the initialization of the Singleton class.\n **kwargs: Keyword arguments for the initialization of the Singleton class.\n\n Returns:\n object: The Singleton instance.\n \"\"\"\n cls.__instance = cls(*args, **kwargs)\n cls.instance = cls.__get_instance\n return cls.__instance\n","repo_name":"jaycho1214/thetennisplay","sub_path":"thetennisplay/singleton.py","file_name":"singleton.py","file_ext":"py","file_size_in_byte":1735,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"12278520717","text":"import matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\n\nsalaries = pd.read_csv(\"/Users/gregorychase/Desktop/sf-salaries/Salaries.csv\")\n\nsalaries.head()\n# salaries.dtypes\n\n\n# Convert object values to numeric\n# 'coerce' converts invalid values to NaN, 'ignore' returns original Series\nsalaries['BasePay'] = pd.to_numeric(salaries['BasePay'], errors='coerce')\nsalaries['OvertimePay'] = pd.to_numeric(salaries['OvertimePay'], errors='coerce')\nsalaries['OtherPay'] = pd.to_numeric(salaries['OtherPay'], errors='coerce')\n\n# Check values, then delete constant columns.\n# 'inplace' changes the actual values.\n# salaries.Agency.value_counts()\nsalaries.drop('Agency', axis=1, inplace=True)\n\n# salaries.Notes.value_counts()\nsalaries.drop('Notes', axis=1, inplace=True)\n\nsalaries.BasePay.mean()\nsalaries.OvertimePay.mean()\nsalaries.OtherPay.mean()\nsalaries.TotalPay.mean()\n\nsalaries.BasePay.median()\nsalaries.OvertimePay.median()\nsalaries.OtherPay.median()\nsalaries.TotalPay.median()\n\n# Percent of data listed as full time (FT) or part time (PT)\npct_FT_or_PT = round(sum(salaries.Status.value_counts())/float(len(salaries)) * 100,2)\n\n# Subset data based on Full Time (FT), Part Time (PT), or NaN\nsalaries_FT = salaries.loc[salaries['Status'] == 'FT']\nsalaries_PT = salaries.loc[salaries['Status'] == 'PT']\nsalaries_NaN = salaries[(salaries['Status']!='FT') & (salaries['Status']!='PT')]\n\n# Convert most columns using convert_objects\n# df = df.convert_objects(convert_numeric=True)\n\nplt.scatter(salaries.Year, salaries.BasePay)\nplt.show()\n","repo_name":"gregwchase/sf-salaries","sub_path":"sf_Salaries.py","file_name":"sf_Salaries.py","file_ext":"py","file_size_in_byte":1542,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"14639665441","text":"# from sys import stdin\n# from collections import deque\n# import heapq\n#\n# read = stdin.readline\n#\n# N = int(read())\n# queue = deque()\n# heap = []\n# result = []\n# for _ in range(N):\n# a, b = map(int, read().split())\n# result.append((a, b))\n# result.sort() # time 정렬상태\n# heapq.heappush(heap, result[0][1]) # 첫번째 수업 끝나는 시간부터 들어가 있다.\n#\n# for i in range(1, N):\n# if heap[0] > result[i][0]:\n# heapq.heappush(heap, result[i][1])\n# # 못들어가.\n# else: # 들어갈 수 있어\n# heapq.heappop(heap)\n# heapq.heappush(heap, result[i][1])\n#\n# print(len(heap))\n#\n# # time 을 힙으로 바꾸면, 최소 힙으로 가장 빠른게 먼저 나온���.\n# # 하나를 팝해서 끝시간을 어디에 박아두면, 힙의 0번째 인덱스와 비교할 수 있다.\n\n\nfrom sys import stdin\nimport heapq\n\nread = stdin.readline\n\nN = int(read())\nheap = []\nresult = []\n\nfor _ in range(N):\n a, b = map(int, read().split())\n heapq.heappush(heap, (a, b))\nstart, end = heapq.heappop(heap)\nresult.append([end])\n\n\nfor i in range(1, N):\n if result[i][-1] <= heap[0][0]:\n result[i].append(heap[0][1])\n heapq.heappop(heap)\n break\n else:\n result.append([heap[0][1]])\n heapq.heappop(heap)\n\nprint(len(result))","repo_name":"hugehoo/problem-solving","sub_path":"2022/2022-01/04JAN 강의실배정.py","file_name":"04JAN 강의실배정.py","file_ext":"py","file_size_in_byte":1318,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"70082169225","text":"from itertools import zip_longest\n\n\nclass Solution:\n def reformat(self, s: str) -> str:\n # 也可以统计过数量之后边遍历边填充\n digit, letter = [], []\n\n for c in s:\n if c.isdigit():\n digit.append(c)\n else:\n letter.append(c)\n\n if len(digit) >= len(letter):\n a, b = digit, letter\n else:\n a, b = letter, digit\n\n if len(a) - len(b) > 1:\n return ''\n\n return ''.join(x[0] + x[1] for x in zip_longest(a, b, fillvalue=''))\n","repo_name":"tiandiyijian/myLeetcode","sub_path":"1417.py","file_name":"1417.py","file_ext":"py","file_size_in_byte":565,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"72960262346","text":"import pygame.camera\n\n\ndef picture_data():\n pygame.init()\n pygame.camera.init()\n camera = pygame.camera.Camera(\"/dev/video0\", (244, 244))\n camera.start()\n image = camera.get_image()\n print(image)\n pygame.image.save(image, \"image.jpg\")\n camera.stop()\n with open(\"image.jpg\", \"rb\") as image:\n return image.read()\n","repo_name":"HeptaKos/PythonLearning","sub_path":"camera.py","file_name":"camera.py","file_ext":"py","file_size_in_byte":345,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"256606662","text":"from django.shortcuts import render\n\n# 리다이렉트 시 사용\nfrom django.http import HttpResponseRedirect\nfrom django.urls import reverse\n# ajax 응답\nfrom django.http import HttpResponse\n\n# 모델 불러오기\nfrom .models import PresentCup, PredictCup\n\n# 에러 발생 시\n\n#This is the django module which allows the Django object to become JSON\nfrom django.core import serializers\n\n# for csv to DB\nimport pandas as pd\nimport json\n\ndef index(request):\n return render(request, 'index.html')\n\ndef login(request):\n return render(request, 'login.html')\n\ndef logout(request):\n request.session.flush()\n return HttpResponseRedirect(reverse(index))\n\ndef check_account(request):\n request.session['auth'] = 1\n return manage(request)\n\ndef our_team(request):\n return render(request, 'maker.html')\n\ndef citizen_map(request, gu='서초구'):\n id_start = 's'\n if gu=='서대문구': id_start = 'sd'\n elif gu=='강남구' : id_start = 'gn'\n\n predictCups = list(PredictCup.objects.filter(id__startswith=id_start).values())\n presentCups = list(PresentCup.objects.filter(id__startswith=id_start).values())\n\n context = { \"presentCups\" : presentCups, 'cnt1' : len(presentCups), 'predictCups': predictCups, 'cnt2': len(predictCups)}\n\n return render(request, 'citizen/citizen_maps.html', context)\n\ndef check_login(function):\n def wrapper(request, *args, **kwargs):\n auth = request.session.get('auth',0)\n \n if auth == 0 : return login(request)\n else : return function(request, *args, **kwargs)\n return wrapper\n\n@check_login\ndef manage(request, gu='서초구'):\n id_start = 's'\n if gu=='서대문구': id_start = 'sd'\n elif gu=='강남구' : id_start = 'gn'\n\n predictCups = list(PredictCup.objects.filter(id__startswith=id_start).values())\n presentCups = list(PresentCup.objects.filter(id__startswith=id_start).values())\n\n context = { \"presentCups\" : presentCups, 'cnt1' : len(presentCups), 'predictCups': predictCups, 'cnt2': len(predictCups)}\n\n return render(request, 'citizen/manage.html', context)\n\ndef post_like(request):\n id = request.POST.get('id', None) # ajax 통신을 통해서 template에서 POST방식으로 전달\n label = request.POST.get('label', None) # ajax 통신을 통해서 template에서 POST방식으로 전달\n\n row = None\n if label == 'predictCups': row = PredictCup.objects.get(id=id)\n else : row = PresentCup.objects.get(id=id)\n\n row.like += 1\n row.save()\n\n context = {'like_count': row.like }\n \n return HttpResponse(json.dumps(context), content_type=\"application/json\")\n # context를 json 타입으로\n\ndef post_dislike(request):\n id = request.POST.get('id', None) # ajax 통신을 통해서 template에서 POST방식으로 전달\n label = request.POST.get('label', None) # ajax 통신을 통해서 template에서 POST방식으로 전달\n\n row = None\n if label == 'predictCups': row = PredictCup.objects.get(id=id)\n else : row = PresentCup.objects.get(id=id)\n\n row.dislike += 1\n row.save()\n \n context = {'dislike_count': row.dislike }\n \n return HttpResponse(json.dumps(context), content_type=\"application/json\")\n # context를 json 타입으로\n \n\n# csv to DB\n# def insert(request):\n# df = pd.read_csv('./citizen/final_presentcup.csv', encoding='utf-8')\n\n# df.apply(makePresentCup, axis=1)\n\n# print(PresentCup.objects.all())\n# return render(request, 'index.html')\n\n# def makePresentCup(df):\n# ['lat', 'long', 'id', 'like', 'address', 'dislike']\n# pc_instance = PresentCup(id=df.id, long=df.long, lat= df.lat, address=df.address, dislike=df.dislike, like=df.like)\n# pc_instance.save()\n\n# # 예측\n# def insert(request):\n# df = pd.read_csv('./citizen/final_predictcupGangman.csv')\n\n# df.apply(makePredictCup, axis=1)\n\n# print(PredictCup.objects.all())\n# return render(request, 'index.html')\n\n# def makePredictCup(df):\n# # ['id', lat1', 'long1','lat2', 'long2','lat3', 'long3','lat4', 'long4', 'id', 'dislike','like', 'address']\n# pc_instance = PredictCup(id=df.id, long1=df.long1, lat1= df.lat1,long2=df.long2, lat2= df.lat2, long3=df.long3, lat3= df.lat3, long4=df.long4, lat4= df.lat4, address=df.address, dislike=df.dislike, like=df.like)\n# pc_instance.save()\n","repo_name":"DataCampus-CupCupCup/cupcupcup","sub_path":"web/citizen/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4300,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"38691638610","text":"# -*- coding: utf-8 -*-\n\"\"\"\nSCRIPT FOR TESTING MIXED-LAYER MODEL USING ONE DAYTIME DATA FROM HYYTIÄLÄ\n\nCreated on Thu Sep 20 14:55:56 2018\n\n@author: slauniai\n\"\"\"\n\nimport numpy as np\nimport pandas as pd\nimport os\nimport matplotlib.pyplot as plt\nEPS = np.finfo(float).eps # machine epsilon\n\n# --- import constants from module mxl\nfrom mxl.mxl import CP_AIR_MASS, MAIR_DRY, MH2O, NT, R\n# --- import model class and utility functions from module mxl\nfrom mxl.mxl import MXLmodel\n# --- import tools to read forcing data\nfrom mxl.utils import read_mxl_forcing\n\n# --- import parameters & initial conditions for mxl model\nfrom mxl.parameters import mxlpara, ini\n\nwdir = r'c:\\repositories\\pyAPES-MXL'\nos.chdir(wdir)\n#print('---- working dir: ' + os.getcwd())\n\nprint('---- reading forcing ---')\n\n# --- read forcing for testing mxl growth\nffile = r'forcing\\FIHy_mxl_forcing_2014.dat'\n\nfday = '2014-07-03'\nlday = '2014-07-03'\n\nforc = read_mxl_forcing(ffile, fday, lday)\n\n# select one day and conditions when H > 0\n#forc = forcing_data.loc[fday:lday][['doy','ust', 'wt', 'wq', 'wc', 'P', 'Ta', 'U']]\n\n# this selects periods when H >0 from forcing.\nforc = forc[forc['H'] > 0]\n\n# plot figure\nplt.figure()\nplt.plot(forc['wt']); plt.ylabel('wt (Kms-1)')\n\n#%% create model instance\n\nprint('---- creating MXL-model----')\n# --- Create model instance\nrun1 = MXLmodel(ini, mxlpara)\n## print run1.__dict_\n\nprint('---- running MXL-model----')\nnsteps = len(forc) # len(F_h)\ntt = 30.*np.arange(0,nsteps) # time vector, min\n\n# initialize results dictionany, fill with NaN's\nres = {'h': np.ones(nsteps)*np.NaN, 'theta': np.ones(nsteps)*np.NaN, \n 'q':np.ones(nsteps)*np.NaN, 'ca': np.ones(nsteps)*np.NaN,\n 'h_lcl': np.ones(nsteps)*np.NaN, 'vpd': np.ones(nsteps)*np.NaN,\n 'U': np.ones(nsteps)*np.NaN, 'u': np.ones(nsteps)*np.NaN\n }\n\n# run model for nsteps\nfor k in range(nsteps):\n wt = forc['wt'][k]\n wq = forc['wq'][k]\n wc = forc['wc'][k]\n ust = forc['ust'][k]\n \n run1.run_timestep(wt, wq, wc, ust)\n\n res['h'][k] = run1.h\n res['theta'][k] = run1.theta\n res['q'][k] = run1.q\n res['ca'][k] = run1.ca\n res['h_lcl'][k] = run1.h_lcl\n res['vpd'][k] = run1.vpd\n res['U'][k] = run1.U\n res['u'][k] = run1.u\n\nprint('---- making graphs----')\n\nplt.figure(1)\nplt.subplot(221); plt.plot(tt, forc['H'], 'r'); plt.ylabel('H (Wm-2)')\nplt.subplot(222); plt.plot(tt, forc['LE'], 'b'); plt.ylabel('E (Wm-2)')\nplt.subplot(223); plt.plot(tt, forc['NEE'], 'g'); plt.ylabel('NEE (umol m-2 s-1)')\nplt.subplot(224); plt.plot(tt, forc['ust'], 'k'); plt.ylabel('ustar (m s-1)')\n\nplt.savefig('forc.png')\n\nplt.figure(2)\nplt.subplot(321); plt.plot(tt, res['h'], label='mxl'); plt.plot(tt, res['h_lcl'], label='lcl'); \nplt.ylabel('mxl and lcl height (m)'); plt.legend(fontsize=8)\nplt.subplot(322); plt.plot(tt, res['theta']); plt.ylabel('Theta (K)')\nplt.subplot(323); plt.plot(tt, res['q']); plt.ylabel('q (kg/kg)')\nplt.subplot(324); plt.plot(tt, res['vpd']); plt.ylabel('vpd (kPa)')\nplt.subplot(325); plt.plot(tt, res['ca']); plt.ylabel('ca (ppm)'); plt.xlabel('time (min)')\nplt.subplot(326); plt.plot(tt, res['U'], label='U'); plt.plot(tt, res['u'], label='u horiz')\nplt.ylabel('velocity (ms-1)'); plt.xlabel('time (min)'); plt.legend(fontsize=8)\nplt.savefig('mxl-test.png')\n\nprint('---- done ! ----')","repo_name":"LukeEcomod/pyAPES-MXL","sub_path":"mxl_test.py","file_name":"mxl_test.py","file_ext":"py","file_size_in_byte":3310,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"30464451235","text":"from jinja2 import Template\nimport yaml\n\ndocument = \"\"\" # Some sample yml\nname: World\ngreeting: Hello\n\"\"\"\n\ny = yaml.load(document, Loader=yaml.FullLoader) # Load the yml document\n\nprint(\"Direct : \"+y[\"greeting\"]+\" \"+y[\"name\"]) # Print directly\nprint(Template(\"Template: {{greeting}} {{name}}\"). # Print via template\n render(greeting=y[\"greeting\"],name=y[\"name\"]))\n","repo_name":"philiprbrenan/ypj","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":524,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"21931569491","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n\"\"\"\nraygen.config\n-------------------\nconfig for raygen\n\n\"\"\"\n\nimport json\nimport os\nimport logging\n\nlogging.info(\"read site.json from {}\".format(os.path.realpath(\"./\")))\n\n\nwith open(\"./site.json\", \"r\") as f:\n try:\n site = json.load(f)\n except FileNotFoundError as e:\n print(\"Maybe this is not a raygen project. please make sure site.json in current path.\")\n raise e\n if \"output_dir\" in site:\n OUTPUT_DIR = site[\"output_dir\"]\n else:\n OUTPUT_DIR = \"./output/\"\n\n if \"content_dir\" in site:\n CONTENT_DIR = site[\"content_dir\"]\n else:\n CONTENT_DIR = \"./content/\"\n\n if \"template_dir\" in site:\n TEMPLATE_DIR = site[\"template_dir\"]\n else:\n TEMPLATE_DIR = \"./template/\"\n\n","repo_name":"budui/raygen","sub_path":"raygen/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":795,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"1520174976","text":"import sys, threading, time, queue\nfrom PyQt5 import QtWidgets\nfrom monitoring_layout import Form\n\nmonitoring_queue = queue.Queue()\n\ndef read_queue():\n while True:\n print(\"READ_QUEUE_DATAS : \", monitoring_queue.qsize())\n monitoring_queue.put('block.add')\n if monitoring_queue.qsize() % 3 == 0:\n Form.change_frame_color(main_form, 44, 132, 238)\n elif (monitoring_queue.qsize() % 3) == 1:\n Form.change_frame_color(main_form, 231, 76, 60) \n else:\n Form.change_frame_color(main_form, 241, 196, 15)\n time.sleep(10)\n\nif __name__ == '__main__':\n app = QtWidgets.QApplication(sys.argv)\n\n main_form = Form()\n\n Form.change_status_text(main_form,\"Server Status : CAUTION !! 13:22:09\")\n\n queue_thread = threading.Thread(target=read_queue)\n queue_thread.daemon = True\n queue_thread.start()\n\n sys.exit(app.exec())\n","repo_name":"karriz-dev/monitoring","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":908,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"41300554028","text":"import os\nimport io\nimport json\nfrom azure.cognitiveservices.vision.face import FaceClient\nfrom msrest.authentication import CognitiveServicesCredentials\nimport requests\nfrom PIL import Image, ImageDraw, ImageFont\n\n\"\"\"\nExample 3. Guess a person's emotion & age\n| Attribute Type List\n| https://docs.microsoft.com/en-us/python/api/azure-cognitiveservices-vision-face/azure.cognitiveservices.vision.face.models.faceattributetype?view=azure-python\n\"\"\"\n\ncredential = json.load(open('AzureCloudKeys.json'))\nAPI_KEY = credential['API_KEY']\nENDPOINT = credential['ENDPOINT']\nface_client = FaceClient(ENDPOINT, CognitiveServicesCredentials(API_KEY))\n\nimg_file = open('1.jpg', 'rb')\n\nresponse_detection = face_client.face.detect_with_stream(\n image=img_file,\n detection_model='detection_01',\n recognition_model='recognition_04',\n return_face_attributes=['age', 'emotion'],\n)\n\nimg = Image.open(img_file)\ndraw = ImageDraw.Draw(img)\nfont = ImageFont.truetype(r'C:\\Windows\\Fonts\\OpenSans-Bold.ttf', 35)\nfor face in response_detection:\n age = face.face_attributes.age\n emotion = face.face_attributes.emotion\n neutral = '{0:.0f}%'.format(emotion.neutral * 100)\n happiness = '{0:.0f}%'.format(emotion.happiness * 100)\n anger = '{0:.0f}%'.format(emotion.anger * 100)\n sandness = '{0:.0f}%'.format(emotion.sadness * 100)\n\n rect = face.face_rectangle\n left = rect.left\n top = rect.top\n right = rect.width + left\n bottom = rect.height + top\n draw.rectangle(((left, top), (right, bottom)), outline='green', width=5)\n\n draw.text((right + 4, top), 'Age: ' + str(int(age)), fill=(255, 255, 255), font=font)\n draw.text((right + 4, top+35), 'Neutral: ' + neutral, fill=(255, 255, 255), font=font)\n draw.text((right + 4, top+70), 'Happy: ' + happiness, fill=(255, 255, 255), font=font)\n draw.text((right + 4, top+105), 'Sad: ' + sandness, fill=(255, 255, 255), font=font)\n draw.text((right + 4, top+140), 'Angry: ' + anger, fill=(255, 255, 255), font=font)\n\nimg.show()\nimg.save('test.jpg')","repo_name":"jphacks/B_2105_server","sub_path":"samples/new.py","file_name":"new.py","file_ext":"py","file_size_in_byte":2024,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"81"} +{"seq_id":"41252532066","text":"# -*- coding: utf-8 -*-\r\n'''\r\nCreated on 2015. 5. 12.\r\n\r\n@author: Jay\r\n'''\r\n\r\nfrom bs4 import BeautifulSoup\r\nimport urllib2\r\nfrom util import htmlParser\r\n#from test.HTMLParse import HTMLParse\r\n\r\nurl = 'http://www.krx.co.kr/m2/m2_1/m2_1_11/JHPKOR02001_11.jsp'\r\nregularExp1 = [\"id\", \"se_key\"]\r\n\r\npage = urllib2.urlopen(url)\r\n\r\nsoup = BeautifulSoup(page, from_encoding=\"utf8\")\r\n\r\nstr = soup.find_all(regularExp1[0], regularExp1[1])\r\n\r\ni = 0\r\nfor x in str:\r\n print(\"%d : \" % i)\r\n print(x.encode('utf8'))\r\n #print(x.text)\r\n i = i + 1\r\n","repo_name":"quantosauros/kirudaML","sub_path":"kirudaML/test/util/testParsing.py","file_name":"testParsing.py","file_ext":"py","file_size_in_byte":542,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"35201568140","text":"\"\"\"\nfragdenstaat_client.converted - CSV conversion utilities module\n\"\"\"\nimport json\nimport csv\nfrom typing import Any, List, Dict\nfrom pathlib import Path\n\n\n\ndef extract_objects_from_fragdenstaat_json_data(data: dict) -> List[dict]:\n \"\"\"extracts the object list from a fragdenstaat json response\"\"\"\n return data.get(\"objects\") or []\n\n\ndef prefix_dict_keys(prefix: str, data: dict) -> dict:\n \"\"\"returns a copy of the given dictionary with its key names prefixed with the given prefix.\n :param prefix: the string with the prefix\n :param data: the source dictionary\n \"\"\"\n result = {}\n for key, value in data.items():\n result[f\"{prefix}_{key}\"] = value\n return result\n\n\ndef flatten_item(item: Dict[str, Any]) -> Dict[str, str]:\n \"\"\"flattens a dictionary containing anything as value to a dictionary of strings only as value.\n This is necessary because CSV does not support nested data\n \"\"\"\n result = {}\n for key, value in item.items():\n if not isinstance(value, dict) and not isinstance(value, (str, bytes)):\n # if the value type is not a dictionary and not a string then we convert it\n # to string using the json imperative. We obviously cant really have complex \n # json data structures in the csv but here we just convert simple types \n # such as: numbers, booleans and null.\n result[key] = json.dumps(value)\n\n elif isinstance(value, (str, bytes)): \n # if the value is a string then we just assign the key to `result`\n result[key] = value\n\n elif key == \"public_body\" and isinstance(value, dict):\n # here we extract the nested data about the public_body prefixing each key with \"institution_\"\n nested = prefix_dict_keys(\"institution\", value)\n # here we make a recursive call to flatten_item to convert numbers, booleans and null\n # then we finally merge the nested data with teh final result by calling .update()\n result.update(flatten_item(nested))\n else: # this condition should never be reached unless eventually fragdenstaat adds another nested dictionary to its data\n # the logic here is mostly the same as above except that rather than hardcoding we use the original dictionary key as prefix\n nested = prefix_dict_keys(key, value)\n result.update(flatten_item(nested)) \n\n\n return result\n\n\ndef json_to_csv(fd_read, fd_write, write_header: bool = True):\n \"\"\"reads json data from a file-descriptor and writes csv data to another file descriptor.\n \"\"\"\n # instantiate python's built-in csv.writer class pointing to write file-descriptor\n writer = csv.writer(fd_write, delimiter=\",\", strict=True)\n # loads the json data from the \"read\" file-descriptor\n data = json.load(fd_read)\n\n # the json data wraps the data we want in some metadata, so here we need to \"extract\" the list of requests\n # prior to writing data to the CSV file\n request_list = extract_objects_from_fragdenstaat_json_data(data)\n # the request list contains a nested object under the field \"public_body\", \n # so we need to \"flatten\" each item on the list using the flatten_item function\n objects = map(flatten_item, request_list)\n\n for index, obj in enumerate(objects):\n if write_header and index is 0: # write the keys to the first line of the CSV\n writer.writerow(obj.keys())\n\n # for each request in the list we write them as a new line in the CSV file\n writer.writerow(obj.values())\n\n\ndef convert_multiple_json_to_csv(target_path: Path, *args):\n \"\"\"\n :param target_path: the path to the csv file\n :param args: list of json file names\n \"\"\"\n # first we open the csv file in \"append mode\" if the csv file already exists we just append data to its end\n with target_path.open(\"a\", encoding=\"utf-8-sig\", newline=\"\") as fd_write:\n # for each json file name (source_path)\n for index, source_path in enumerate(args):\n # we need to know when to write the headerof the CSV (first line) which contains the field names\n is_first_file = index == 0\n \n with source_path.open(\"r\") as fd_read:\n # read a json file and convert to csv\n print(f\"adding json data from {source_path} to {target_path}\")\n json_to_csv(fd_read, fd_write, write_header=is_first_file)\n\n\ndef validate_file_names(names: List[Path]) -> List[Path]:\n \"\"\"ensures that each given file name exists, quits the program in case of failure.\n This prevents us running into a problem in case of typo in the command line\n\n :param names: a list of filenames\n \"\"\"\n paths = list(map(Path, names))\n for path in paths:\n if not path.exists():\n print(f\"{path} does not exist\")\n raise SystemExit(1)\n\n if not path.is_file():\n print(f\"{path} exists but is not a file\")\n raise SystemExit(1)\n\n return paths\n","repo_name":"jessihnm/fragdenstaat-client","sub_path":"fragdenstaat_client/converter.py","file_name":"converter.py","file_ext":"py","file_size_in_byte":5019,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"18982272410","text":"import os\n\nfrom typing import Optional, Union, List\nfrom pytorch_lightning.loggers import CSVLogger, TensorBoardLogger, WandbLogger\nfrom pytorch_lightning.utilities import rank_zero_only\n\nclass PatchedWandbLogger(WandbLogger):\n def __init__(self, entity: str, project: str, name: str, log_model: bool, save_code: bool, save_dir: str,\n tags: List[str] = None, offline: bool = False, *args, **kwargs):\n # try to get the exp name and save dir from env var to support multiple runs\n env_var_name = os.getenv('EXP_NAME')\n if env_var_name is not None:\n name = env_var_name\n save_dir = env_var_name\n\n # put necessary init vars for wandb\n kwargs['entity'] = entity \n kwargs['save_code'] = save_code\n kwargs['save_dir'] = save_dir\n kwargs['dir'] = save_dir # fix a bug for wandb logger\n\n # remove the preceeding folder name\n processed_name = name.split('/')[-1]\n if tags is None:\n kwargs['tags'] = processed_name.split('-')\n else:\n kwargs['tags'] = tags\n \n # fail-safe for uploading the tmp exp for debugging\n if \"tmp\" in processed_name and not offline:\n print(f\"WandbLogger: {processed_name} is a tmp exp so running in offline mode\")\n kwargs['offline'] = True\n\n # create the save_dir if it doesn't exist\n print(f\"ready to create save_dir: {save_dir}\", flush=True)\n if not os.path.exists(save_dir):\n os.makedirs(save_dir)\n\n super().__init__(name=processed_name, project=project, log_model=log_model, *args, **kwargs)\n\n @rank_zero_only\n def log_code(self):\n\n # log the yaml and py files\n root = \".\"\n print(f\"saving all files in {os.path.abspath(root)}\")\n result = self.experiment.log_code(root=root, \n include_fn=(lambda path: path.endswith(\".py\") or \\\n path.endswith(\".yaml\")),\n exclude_fn=(lambda path: \".venv\" in path or \\\n \"debug-tmp\" in path))\n if result is not None:\n print(\"########################################\")\n print(\"######## Logged code to wandb. #########\")\n print(\"########################################\")\n else:\n print(\"######## logger inited but not successfully saved #########\")","repo_name":"niansong1996/lever","sub_path":"finetuning/lightning_modules/patches/patched_loggers.py","file_name":"patched_loggers.py","file_ext":"py","file_size_in_byte":2433,"program_lang":"python","lang":"en","doc_type":"code","stars":57,"dataset":"github-code","pt":"81"} +{"seq_id":"37122483779","text":"from flask import Flask, request, render_template\nfrom flask_cors import cross_origin\nimport sklearn\nimport pickle\nimport gzip\n\napp = Flask(__name__)\nmodel = pickle.load(gzip.open(\"Model.pkl\", \"rb\"))\n\n\n@app.route(\"/\")\n@cross_origin()\ndef home():\n return render_template(\"home.html\")\n\n\n@app.route(\"/predict\", methods=[\"GET\", \"POST\"])\n@cross_origin()\ndef predict():\n if request.method == \"POST\":\n\n \n # Age -------------------------------------------------------------------------------\n\n age = request.form['Age']\n\n if (age == '0-20'):\n age = 20\n\n elif (age == '21-30'):\n age = 30\n\n elif (age == '31-40'):\n age = 40\n\n elif (age == '41-50'):\n age = 50\n\n elif (age == '51-60'):\n age = 60\n\n elif (age == '61-70'):\n age = 70\n\n elif (age == '71-80'):\n age = 80\n\n elif (age == '81-100'):\n age = 100\n \n \n # Department ---------------------------------------------------------------------------------------\n\n d = request.form['Department']\n \n d_anesthesia = d_gynecology = d_radiotherapy = d_surgery = 0\n\n if(d == 'anesthesia'):\n d_anesthesia = 1\n \n elif(d == 'gynecology'):\n d_gynecology = 1\n\n elif(d == 'radiotherapy'):\n d_radiotherapy = 1\n\n elif(d == 'surgery'):\n d_surgery = 1\n\n\n # Type of Admission ----------------------------------------------------------------------------------\n\n ta = request.form['Type_of_Admission']\n \n if (ta == 'Trauma'):\n ta = 1\n\n elif (ta == 'Urgent'):\n ta = 2\n\n elif (ta == 'Emergency'):\n ta = 3\n\n\n # Severity of Illness -------------------------------------------------------------------------------\n\n si = request.form['Severity_of_Illness']\n\n if (si == 'Minor'):\n si = 1\n\n elif (si == 'Moderate'):\n si = 2\n\n elif (si == 'Extreme'):\n si = 3\n\n\n # Ward type ------------------------------------------------------------------------------------------\n\n wt = request.form['Ward_Type']\n \n wt_Q = wt_R = wt_S = wt_T = wt_U = 0\n\n if(wt == 'Q'):\n wt_Q = 1\n\n elif(wt == 'R'):\n wt_R = 1\n\n elif(wt == 'S'):\n wt_S = 1 \n\n elif(wt == 'T'):\n wt_T = 1\n\n elif(wt == 'U'):\n wt_U = 1\n\n\n\n # Bed Grade --------------------------------------------------------------------------------\n \n bg = request.form['Bed_Grade']\n\n bg_2 = bg_3 = bg_4 = 0\n \n if(bg == '2'):\n bg_2 = 1\n\n elif(bg == '3'):\n bg_3 = 1\n\n elif(bg == '4'):\n bg_4 = 1\n\n\n\n # Numerical Columns ------------------------------------------------------------------------------\n\n Available_Extra_Rooms = int(request.form[\"Available_Extra_Rooms\"])\n Visitors_with_Patient = int(request.form[\"Visitors_with_Patient\"])\n Admission_Deposit = int(request.form[\"Admission_Deposit\"])\n\n\n # Prediction -------------------------------------------------------------------------------------\n\n prediction = model.predict([[\n Available_Extra_Rooms,\n ta,\n si,\n Visitors_with_Patient,\n Admission_Deposit,\n age, \n d_anesthesia , d_gynecology , d_radiotherapy , d_surgery,\n wt_Q , wt_R , wt_S , wt_T , wt_U,\n bg_2 , bg_3 , bg_4\n ]])\n \n \n if (prediction==1):\n output = '0-10'\n elif (prediction==2):\n output = '11-20'\n elif (prediction==3):\n output = '21-30'\n elif (prediction==4):\n output = '31-40'\n elif (prediction==5):\n output = '41-50'\n elif (prediction==6):\n output = '51-60'\n elif (prediction==7):\n output = '60+'\n \n return render_template('result.html', prediction_text=\"LOS = {} days\".format(output))\n\n return render_template(\"result.html\")\n\n\nif __name__ == \"__main__\":\n app.run(debug=True)\n","repo_name":"debesh26/Capstone-Project","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":4613,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"74577275464","text":"import torch\nfrom icecream import ic\n\ndef lossfun_distortion(midpoint, full_weight, dt):\n \"\"\"Compute iint w[i] w[j] |t[i] - t[j]| di dj.\"\"\"\n # The loss incurred between all pairs of intervals.\n # extend the mipoint artifically to the background\n dut = torch.abs(midpoint[..., :, None] - midpoint[..., None, :])\n # mp = midpoint[..., None]\n # dut = torch.cdist(mp, mp, p=1)\n # loss_inter = torch.sum(w * torch.sum(w[..., None, :] * dut, dim=-1), dim=-1)\n B = dt.shape[0]\n loss_inter = torch.einsum('bj,bk,bjk', full_weight.reshape(B, -1), full_weight.reshape(B, -1), dut)\n # ic(dt.shape, full_weight.shape)\n\n # The loss incurred within each individual interval with itself.\n loss_intra = torch.sum(full_weight**2 * dt) / 3\n # ic(1, loss_inter, loss_intra)\n\n return loss_inter + loss_intra\n\ndef lossfun_distortion2(t, w, dt):\n device = w.device\n B, n_samples = w.shape\n full_weight = torch.cat([w, 1-w.sum(dim=1, keepdim=True)], dim=1)\n #\n # midpoint = t\n # fweight = torch.abs(midpoint[..., :, None] - midpoint[..., None, :])\n # # # ut = (z_vals[:, 1:] + z_vals[:, :-1])/2\n # #\n # loss_inter = torch.einsum('bj,bk,jk', full_weight.reshape(B, -1), full_weight.reshape(B, -1), fweight)\n # loss_intra = (w**2 * dt).sum(dim=1).sum()/3\n #\n # # this one consumes too much memory\n\n S = torch.linspace(0, 1, n_samples+1, device=device).reshape(-1, 1)\n # S = t[0, :].reshape(-1, 1)\n fweight = (S - S.T).abs()\n # ut = (z_vals[:, 1:] + z_vals[:, :-1])/2\n\n floater_loss_1 = torch.einsum('bj,bk,jk', full_weight.reshape(B, -1), full_weight.reshape(B, -1), fweight)\n floater_loss_2 = (full_weight**2).sum()/3/n_samples\n # ic(fweight)\n\n # ic(floater_loss_1, floater_loss_2)\n return floater_loss_1 + floater_loss_2\n\n@torch.no_grad()\ndef distortion_bidir_pseudo(midpoint, full_weight, dt):\n # midpoint: (B, M)\n # full_weight: (B, M)\n # dt: (B, M)\n B, M = midpoint.shape\n BLOCK_SIZE_M = 128\n device = midpoint.device\n dm = torch.zeros((B, M), device=device)\n dw = torch.zeros((B, M), device=device)\n ddt = torch.zeros((B, M), device=device)\n accum = 0\n for b in range(0, B):\n for m in range(0, M, BLOCK_SIZE_M):\n w1 = full_weight[b, m : m+BLOCK_SIZE_M]\n mp1 = midpoint[b, m : m+BLOCK_SIZE_M]\n dw1 = dw[b, m : m+BLOCK_SIZE_M]\n dmp1 = dm[b, m : m+BLOCK_SIZE_M]\n for n in range(0, M, BLOCK_SIZE_M):\n mp2 = midpoint[b, n : n+BLOCK_SIZE_M]\n w2 = full_weight[b, n : n+BLOCK_SIZE_M]\n\n # forward\n dut = (mp1.reshape(-1, 1) - mp2.reshape(1, -1))\n wm = (w1.reshape(-1, 1) * w2.reshape(1, -1))\n accum += (dut.abs()*wm).sum()\n\n # backward\n dw2 = dw[b, n : n+BLOCK_SIZE_M]\n dmp2 = dm[b, n : n+BLOCK_SIZE_M]\n\n dw2 += (dut.abs()*w1.reshape(-1, 1)).sum(dim=0)\n dw1 += (dut.abs()*w2.reshape(1, -1)).sum(dim=1)\n\n s = torch.sign(dut)\n dmp2 -= (wm * s).sum(dim=0)\n dmp1 += (wm * s).sum(dim=1)\n\n pdt = dt[b, m : m+BLOCK_SIZE_M ]\n\n # forward\n accum += (w1**2 * pdt).sum() / 3\n # backward\n ddt[b, m : m+BLOCK_SIZE_M ] += w1**2 / 3\n dw[b, m : m+BLOCK_SIZE_M] += 2 * w1 * pdt / 3\n return accum, dm, dw, ddt\n\nclass _DistortionLossPseudo(torch.autograd.Function):\n @staticmethod\n def forward(ctx, midpoint, full_weight, dt):\n accum, dm, dw, dt = distortion_bidir_pseudo(midpoint, full_weight, dt)\n # ic(dm, dw, dt)\n\n ctx.save_for_backward(dm, dw, dt)\n return accum\n\n @staticmethod\n def backward(ctx, daccum):\n dm, dw, dt = ctx.saved_tensors\n return daccum * dm, daccum * dw, daccum * dt\n\ndistortion_loss_pseudo = _DistortionLossPseudo.apply\n\ndef lossfun_distortion(midpoint, full_weight, dt):\n \"\"\"Compute iint w[i] w[j] |t[i] - t[j]| di dj.\"\"\"\n # The loss incurred between all pairs of intervals.\n # extend the mipoint artifically to the background\n dut = torch.abs(midpoint[..., :, None] - midpoint[..., None, :])\n # mp = midpoint[..., None]\n # dut = torch.cdist(mp, mp, p=1)\n # loss_inter = torch.sum(w * torch.sum(w[..., None, :] * dut, dim=-1), dim=-1)\n B = dt.shape[0]\n loss_inter = torch.einsum('bj,bk,bjk', full_weight.reshape(B, -1), full_weight.reshape(B, -1), dut)\n # ic(dt.shape, full_weight.shape)\n\n # The loss incurred within each individual interval with itself.\n loss_intra = torch.sum(full_weight**2 * dt) / 3\n # ic(1, loss_inter, loss_intra)\n\n return loss_inter + loss_intra\n\nif __name__ == \"__main__\":\n B = 3\n M = 16\n device = torch.device('cuda')\n dtype = torch.double\n midpoint = torch.rand(B, M, dtype=dtype, device=device)\n full_weight = torch.rand(B, M, dtype=dtype, device=device)\n dt = torch.rand(B, M, dtype=dtype, device=device)\n midpoint.requires_grad = True \n full_weight.requires_grad = True \n dt.requires_grad = True \n print(distortion_loss_pseudo(midpoint, full_weight, dt))\n torch.autograd.gradcheck(distortion_loss_pseudo, (midpoint, full_weight, dt))\n # torch.autograd.gradcheck(distortion_loss, (midpoint, full_weight, dt))\n","repo_name":"half-potato/nmf","sub_path":"modules/distortion_loss_pseudo.py","file_name":"distortion_loss_pseudo.py","file_ext":"py","file_size_in_byte":5328,"program_lang":"python","lang":"en","doc_type":"code","stars":46,"dataset":"github-code","pt":"81"} +{"seq_id":"15065680658","text":"from operator import not_\r\nfrom bestMove import bestMove\r\nfrom minVal import minVal, showBoard\r\nfrom maxVal import maxVal\r\nfrom showBoard import showBoard\r\nfrom createBoard import createBoard\r\nfrom updateBoard import updateBoard\r\nfrom finished import checkWin, checkDiagonals, checkRows\r\nimport random\r\n\r\ndef showRules():\r\n print('''\r\n 1. The cells are 0-indexed. So, choose the coordinates of your cell accordingly. For example, the top-left cell is (0,0),\r\n the two cells to its right are (0,1), and (0,2) respectively.\r\n Similarly, the right-most cell is (2,2).\r\n 2. Note that the user(you) can choose only 'O' and the computer will always play with 'X'.\r\n 3. At the start of the game, you will be asked whether you want to move first or the computer should move first. If you want to play the first move, type O(capital letter O).\r\n Else, type capital X.\r\n 4. Each time your turn comes, you will have to provide first the x-coordinate(between 0 to 2 corresponding to each of the three rows). Similarly, you\r\n would have to provide a y-coordinate too(a number between 0 to 2 corresponding to each column).\r\n 5. You will not have to wait for the computer's turn. It will move automatically and the resultant board will be shown to you later on before your\r\n next move.\r\n \r\n Hope you enjoy the game!\r\n ''')\r\n\r\n\r\n\r\n\r\ndef play():\r\n showRules()\r\n board = createBoard()\r\n showBoard(board)\r\n print('Who will take the first go? ( Type X or O)')\r\n ch = input()\r\n while not(ch == 'X' or ch == 'O'):\r\n print('Please enter a valid character! Try again...')\r\n ch = input()\r\n start = 1\r\n while(True):\r\n print(ch,\"'s chance...\")\r\n if(ch == 'O'):\r\n if start == 1:\r\n start = 0\r\n print('Enter the x-coordinate of the cell where you wish to move: ')\r\n x = int(input())\r\n print('Enter the y-coordinate of the cell where you wish to move: ')\r\n y = int(input())\r\n pos = [x,y]\r\n print('Marking a \"O\" at (',x,\" , \",y,\")\")\r\n ret, board = updateBoard(board, pos, ch)\r\n while(ret == 0):\r\n print('Enter the x-coordinate of the cell where you wish to move: ')\r\n x = int(input())\r\n print('Enter the y-coordinate of the cell where you wish to move: ')\r\n y = int(input())\r\n pos = [x,y]\r\n print('Marking a \"O\" at (',x,\" , \",y,\")\")\r\n ret, board = updateBoard(board, pos , ch)\r\n ch = 'X'\r\n elif(ch == 'X'):\r\n if start == 1:\r\n x = random.randint(0,2)\r\n y = random.randint(0,2)\r\n pos = [x,y]\r\n start = 0\r\n else:\r\n pos = bestMove(minVal(board), maxVal(board))\r\n print('Marking a \"X\" at (',pos[0],\" , \",pos[1],\")\")\r\n ret, board = updateBoard(board, pos, ch)\r\n ch = 'O'\r\n\r\n showBoard(board)\r\n print()\r\n c = checkWin(board)\r\n if checkWin(board) != 0 and checkWin(board) != '_':\r\n # ch = checkWinner(board)\r\n if c == 'X':\r\n print('You lost! Better Luck Next time :(')\r\n elif c == 'O':\r\n print('Congrats! You won :)')\r\n elif c == -1:\r\n print('Match draw! Nice game, right?')\r\n break\r\n print()\r\n print('Want to play one more time? (Y/N)')\r\n c = input()\r\n while not(c=='Y' or c=='y' or c=='n' or c=='N'):\r\n print(\"Please provide a valid input\")\r\n c = input()\r\n if c=='Y' or c=='y':\r\n print()\r\n play()\r\n elif c=='N' or c=='n':\r\n print('No problem! Hope you had a nice time. See ya later!')\r\n return\r\n \r\nplay()\r\n","repo_name":"hitesh-anand/TicTacToe","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3824,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"81"} +{"seq_id":"36735944140","text":"from configparser import ConfigParser\nfrom os.path import isfile, expanduser\n\nclass Configuration_Manager:\n def __init__(self, config_file):\n self.config_file = config_file\n if not isfile(self.config_file):\n self.set_config_defaults()\n current_config = self.get_config()\n if current_config['install'] not in self.get_installation_types():\n self.set_config(current_config['directory'], self.get_installation_types()[0])\n\n def get_config(self):\n config = ConfigParser()\n config.read(self.config_file)\n return {\n 'directory': config.get('configuration', 'directory'),\n 'install': config.get('configuration', 'install')\n }\n\n def set_config(self, directory, install):\n new_config = ConfigParser()\n new_config.add_section('configuration')\n new_config.set('configuration', 'directory', directory)\n new_config.set('configuration', 'install', install)\n with open(self.config_file, 'w') as configfile:\n new_config.write(configfile)\n\n def set_config_defaults(self):\n self.set_config(expanduser(\"~\"), self.get_installation_types()[0])\n \n def get_installation_types(self):\n return [\n 'Eye of Gnome', \n 'Eye of Mate', \n 'Eye of Gnome flatpak'\n ]","repo_name":"nathanblaubach/slideshow","sub_path":"src/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":1349,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"7232976316","text":"'''\nCreated on 2013-5-7\n\n@author: YUWANG\n'''\n\nfrom django.conf.urls import *\n\nurlpatterns = patterns('transactionBillManagement.views',\n (r'bill/$','billIndex'),\n (r'bill/search$','search'),\n (r'bill/search/[a-z]+\\d+$','accountBillList'),\n )","repo_name":"kingofhawks/dataservice2","sub_path":"transactionBillManagement/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":329,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"81"} +{"seq_id":"18265056451","text":"\nfrom pylab import *\nimport numpy as np\nfrom sample import sample_from_lifetime_dist\nfrom globals import t_mu, dt_mu, t_pi, dt_pi\nfrom binned_ML import binned_ML\n\ndef sample_with_background(M):\n\t# returns 10k values plus M background values\n\tx = sample_from_lifetime_dist(1000)\n\tbackground = rand(M)*5*t_mu\n\tx = np.append(x,background)\n\tx = x[x<5*t_mu] \t# cut values above 5*t_mu away since exercise asks to fit only in interval (0, 5*t_mu)\n\treturn x\n\n# x = sample_with_background(1000)\n# hist(x,100)\n# show()\n\n# repeat until we have one that converges\nfor M in [1000,2000,10000]:\t\n\tprint('M =',M,'background events')\n\tprint('-----------------------------------------------------------------------------------')\n\tcount = 0\n\twhile True: \n\t\tx = sample_with_background(M)\n\t\toptimizer_res = binned_ML(x, 100, np.array([np.random.normal(3.0e3,1e3), np.random.normal(2.6e1,1.0e1)]))\n\t\tcount += 1\n\t\tprint('does simulation',count,'converge? ')\n\t\tif(optimizer_res.success):\n\t\t\testimates = optimizer_res.x\n\t\t\tprint('yes!')\n\t\t\tprint('means',estimates,'uncertainties',optimizer_res.sigma)\n\t\t\tbreak\n\t\telse:\n\t\t\tprint('no.')","repo_name":"lucnat/pion-muon-lifetime-simulation","sub_path":"ex_4_Team_B.py","file_name":"ex_4_Team_B.py","file_ext":"py","file_size_in_byte":1109,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"7628247604","text":"from Cocoa import *\nfrom Quartz import *\n\nfrom SampleCIView import SampleCIView\n\nfrom math import sin\n\nimport objc\n\nNUM_POINTS=4\n\nclass CIBevelView (SampleCIView):\n currentPoint = objc.ivar(type=objc._C_INT)\n points = objc.ivar()\n angleTime = objc.ivar(type=objc._C_FLT)\n lineImage = objc.ivar()\n twirlFilter = objc.ivar()\n heightFieldFilter = objc.ivar()\n shadedFilter = objc.ivar()\n\n\n def initWithFrame_(self, frameRect):\n self = super(CIBevelView, self).initWithFrame_(frameRect)\n if self is None:\n return None\n\n self.points = [ None ] * NUM_POINTS\n self.points[0] = CGPointMake(0.5 * frameRect.size.width, frameRect.size.height - 100.0)\n self.points[1] = CGPointMake(150.0, 100.0)\n self.points[2] = CGPointMake(frameRect.size.width - 150.0, 100.0)\n self.points[3] = CGPointMake(0.7*self.points[0].x + 0.3*self.points[2].x, 0.7*self.points[0].y + 0.3*self.points[2].y)\n\n url = NSURL.fileURLWithPath_(\n NSBundle.mainBundle().pathForResource_ofType_(\"lightball\", \"tiff\"))\n\n self.lightball = CIImage.imageWithContentsOfURL_(url)\n\n self.heightFieldFilter = CIFilter.filterWithName_(\"CIHeightFieldFromMask\")\n self.heightFieldFilter.setDefaults()\n self.heightFieldFilter.setValue_forKey_(15.0, \"inputRadius\")\n\n self.twirlFilter = CIFilter.filterWithName_(\"CITwirlDistortion\")\n self.twirlFilter.setDefaults()\n self.twirlFilter.setValue_forKey_(\n CIVector.vectorWithX_Y_(\n 0.5*frameRect.size.width,\n 0.5*frameRect.size.height),\n \"inputCenter\")\n self.twirlFilter.setValue_forKey_(300.0, \"inputRadius\")\n self.twirlFilter.setValue_forKey_(0.0, \"inputAngle\")\n\n self.shadedFilter = CIFilter.filterWithName_(\"CIShadedMaterial\")\n self.shadedFilter.setDefaults()\n self.shadedFilter.setValue_forKey_(self.lightball, \"inputShadingImage\")\n self.shadedFilter.setValue_forKey_(20.0, \"inputScale\")\n\n # 1/30 second should give us decent animation\n NSTimer.scheduledTimerWithTimeInterval_target_selector_userInfo_repeats_(\n 1.0/30.0, self, 'changeTwirlAngle:', None, True)\n return self\n\n\n def changeTwirlAngle_(self, timer):\n self.angleTime += timer.timeInterval()\n self.twirlFilter.setValue_forKey_(\n -0.2 * sin(self.angleTime*5.0), 'inputAngle')\n self.updateImage()\n\n def mouseDragged_(self, event):\n loc = self.convertPoint_fromView_(event.locationInWindow(), None)\n self.points[self.currentPoint].x = loc.x\n self.points[self.currentPoint].y = loc.y\n self.lineImage = None\n\n # normally we'd want this, but the timer will cause us to\n # redisplay anyway\n #self.setNeedsDisplay_(True)\n\n def mouseDown_(self, event):\n d = 1e4\n loc = self.convertPoint_fromView_(event.locationInWindow(), None)\n for i in range(NUM_POINTS):\n x = self.points[i].x - loc.x\n y = self.points[i].y - loc.y\n t = x*x + y*y\n\n if t < d:\n self.currentPoint = i\n d = t\n\n self.mouseDragged_(event)\n\n def updateImage(self):\n context = NSGraphicsContext.currentContext().CIContext()\n if self.lineImage is None:\n bounds = self.bounds()\n layer = context.createCGLayerWithSize_info_(\n CGSizeMake(NSWidth(bounds), NSHeight(bounds)), None)\n\n cg = CGLayerGetContext(layer)\n\n CGContextSetRGBStrokeColor(cg, 1,1,1,1)\n CGContextSetLineCap(cg, kCGLineCapRound)\n\n CGContextSetLineWidth(cg, 60.0)\n CGContextMoveToPoint(cg, self.points[0].x, self.points[0].y)\n for i in range(1, NUM_POINTS):\n CGContextAddLineToPoint(cg, self.points[i].x, self.points[i].y)\n CGContextStrokePath(cg)\n\n self.lineImage = CIImage.alloc().initWithCGLayer_(layer)\n\n self.heightFieldFilter.setValue_forKey_(self.lineImage, \"inputImage\")\n self.twirlFilter.setValue_forKey_(\n self.heightFieldFilter.valueForKey_(\"outputImage\"),\n \"inputImage\")\n\n self.shadedFilter.setValue_forKey_(\n self.twirlFilter.valueForKey_(\"outputImage\"),\n \"inputImage\")\n\n self.setImage_(self.shadedFilter.valueForKey_(\"outputImage\"))\n","repo_name":"albertz/music-player","sub_path":"mac/pyobjc-framework-Quartz/Examples/Core Image/CIBevelSample/CIBevelView.py","file_name":"CIBevelView.py","file_ext":"py","file_size_in_byte":4506,"program_lang":"python","lang":"en","doc_type":"code","stars":490,"dataset":"github-code","pt":"81"} +{"seq_id":"41596012780","text":"from django.views.generic import View\n\nfrom django.utils.decorators import method_decorator\nfrom attendance_manager.decorators.requires_token import RequiresTokenDecorator\nfrom attendance_manager.decorators.response import JsonResponseDecorator\nfrom attendance_manager.helpers.course_helpers import check_course, get_courses\nfrom attendance_manager.helpers.response_helpers import attendance_response, invalid_params_response\nfrom attendance_manager.models import Attendance, Courses, TimeTable\n\n@method_decorator(RequiresTokenDecorator, name='dispatch')\n@method_decorator(JsonResponseDecorator, name='dispatch')\nclass UserAttendanceView(View):\n def post(self, request):\n student=request.student\n timetable_id = request.POST.get('timetable_id')\n attendance_status = request.POST.get('attendance')\n course_ids = get_courses(student).values_list('course_id')\n try:\n timetable = TimeTable.objects.get(timetable_id=timetable_id, course_id__course_id__in=course_ids)\n attendance = Attendance.objects.get(student_id=student, timetable_id=timetable)\n except:\n return invalid_params_response('Timetable does not exist!')\n attendance.present_status = attendance_status\n attendance.save()\n return attendance_response(student, timetable.course_id)\n\n@method_decorator(RequiresTokenDecorator, name='dispatch')\n@method_decorator(JsonResponseDecorator, name='dispatch')\nclass UserAttendanceCourseView(View):\n def get(self, request, course_id):\n student=request.student\n if not check_course(student,course_id):\n return invalid_params_response('Course does not exist!')\n course = Courses.objects.get(course_id=course_id)\n return attendance_response(student, course)","repo_name":"Varunalingam/attendance-manager-backend","sub_path":"attendance_manager/views/user/attendance.py","file_name":"attendance.py","file_ext":"py","file_size_in_byte":1789,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"21564742344","text":"from datetime import datetime\nfrom entities.models import Collection, Vocabulary\nfrom rest_framework import serializers\nimport requests\nfrom yovoco.constants import *\nclass CollectionSerializer(serializers.ModelSerializer):\n\tclass Meta:\n\t\tmodel=Collection\n\t\tfields=[KEY_ID, KEY_NAME, KEY_DESCRIPTION, KEY_IMAGE]\n\t\n\tdef validate_name(self, value):\n\t\tif len(value) > VALUE_NAME_MAX_LENGTH:\n\t\t\traise serializers.ValidationError(MESSAGE_VALIDATION_NAME_MOST_CHAR)\n\t\tif len(value) < VALUE_NAME_MIN_LENGTH:\n\t\t\traise serializers.ValidationError(MESSAGE_VALIDATION_NAME_LEAST_CHAR)\n\t\treturn value\n\n\tdef validate(self, data):\n\t\trequest=self.context.get(KEY_REQUEST)\n\t\tif request:\n\t\t\tuser=request.user\n\t\t\tname=data.get(KEY_NAME)\n\t\t\tinstance=self.instance if self.instance else Collection(id=-1)\n\t\t\tis_exists=Collection.objects.filter(created_by=user, name=name)\\\n\t\t\t\t\t\t\t\t\t\t\t\t.exclude(deleted_by=user).exclude(id=instance.id).exists();\n\t\t\tif is_exists:\n\t\t\t\traise serializers.ValidationError(MESSAGE_COLLECTION_EXIST)\n\t\treturn data\n\t\n\tdef save(self, **kwargs):\n\t\treturn super(CollectionSerializer, self).save(**kwargs)\n\n\tdef update(self, instance, data):\n\t\tinstance.name=data.get(KEY_NAME, instance.name)\n\t\tinstance.description=data.get(KEY_DESCRIPTION, instance.description)\n\t\tinstance.image=data.get(KEY_IMAGE, instance.image)\n\t\tinstance.updated_by=self.context.get(KEY_REQUEST).user\n\t\tinstance.updated_at=datetime.now()\n\t\tinstance.save()\n\t\treturn instance\n\t\t\nclass VocabularySerializer(serializers.ModelSerializer):\n\tclass Meta:\n\t\tmodel=Vocabulary\n\t\tfields=(KEY_ID,KEY_WORD, KEY_MEANING, KEY_EXAMPLE, KEY_PHONETIC, KEY_AUDIO,\\\n\t\t\tKEY_POS, KEY_LANGUAGE, KEY_COLLECTION, KEY_POS_EXTEND)\n\t\textra_kwargs={\n\t\t\tKEY_ID: {KEY_READ_ONLY: True},\n\t\t\tKEY_WORD: {KEY_REQUIRED: True},\n\t\t\tKEY_POS_EXTEND: {KEY_READ_ONLY: False}\n\t\t}\n\t\n\tdef validate_audio(self, value):\n\t\taudio=self.initial_data.get(KEY_AUDIO)\n\t\tif (not audio) or audio.endswith(VALUE_MP3_EXTEND) or audio.endswith(VALUE_WAV_EXTEND):\n\t\t\treturn value\n\t\traise serializers.ValidationError(MESSAGE_VALIDATION_AUDIO_EXTEND)\n\n\tdef validate_word(self, value):\n\t\tif len(value) > VALUE_VALIDATION_WORD_MAX_LENGTH:\n\t\t\traise serializers.ValidationError(MESSAGE_VALIDATION_WORD_MOST_CHAR)\n\t\tif len(value) < VALUE_VALIDATION_WORD_MIN_LENGTH:\n\t\t\traise serializers.ValidationError(MESSAGE_VALIDATION_WORD_LEAST_CHAR)\n\t\treturn value\n\n\tdef validate_collection(self, value):\n\t\tuser=self.context.get(KEY_REQUEST).user\n\t\tif not value:\n\t\t\tcollection_name=datetime.now().strftime('%Y%m%d')\n\t\t\tcollection_exists=Collection.objects.filter(created_by=user, name=collection_name)\\\n\t\t\t\t\t\t\t\t\t\t\t\t\t.exclude(deleted_by=user).exists()\n\t\t\tif not collection_exists:\n\t\t\t\tvalue=Collection.objects.create(created_by=user, updated_by=user, name=collection_name,\\\n\t\t\t\t\t\t\t\t\t\t\tdescription =VALUE_DESCRIPTION_AUTOMATIC);\n\t\t\telse:\n\t\t\t\tvalue=Collection.objects.get(created_by=user, name=collection_name)\n\t\telse:\n\t\t\tcollection_exists=Collection.objects.filter(id=value.id, created_by=user).exists()\n\t\t\tif value.created_by != user and not collection_exists:\n\t\t\t\traise serializers.ValidationError(MESSAGE_COLLECTION_NOT_EXIST)\n\t\treturn value\n\n\tdef get_meaning(self, data, json_data):\n\t\tmeaning=data.get(KEY_MEANING)\n\t\tif not meaning or meaning.strip() == VALUE_EMPTY_STRING:\n\t\t\tdefines=list()\n\t\t\tfor translator in json_data:\n\t\t\t\tmeanings=translator.get(KEY_MEANINGS)\n\t\t\t\tfor meaning in meanings:\n\t\t\t\t\tdefinitions=meaning.get(KEY_DEFINITIONS)\n\t\t\t\t\tfor definition in definitions:\n\t\t\t\t\t\tdefine=definition.get(KEY_DEFINITION)\n\t\t\t\t\t\tif define:\n\t\t\t\t\t\t\tdefines.append(define)\n\t\t\treturn VALUE_NEW_LINE.join(defines)\n\t\treturn meaning\n\t\n\tdef get_example_and_pos(self, data, json_data):\n\t\texample=data.get(KEY_EXAMPLE)\n\t\tpos_extend=data.get(KEY_POS_EXTEND)\n\t\tif not example or example.strip() == VALUE_EMPTY_STRING:\n\t\t\texamples=list()\n\t\t\tposes=list()\n\t\t\tfor translator in json_data:\n\t\t\t\tmeanings=translator.get(KEY_MEANINGS)\n\t\t\t\tfor meaning in meanings:\n\t\t\t\t\tpos=meaning.get(KEY_PART_OF_SPEECH)\n\t\t\t\t\tif pos:\n\t\t\t\t\t\tposes.append(pos)\n\t\t\t\t\tdefinitions=meaning.get(KEY_DEFINITIONS)\n\t\t\t\t\tfor definition in definitions:\n\t\t\t\t\t\texample=definition.get(KEY_EXAMPLE)\n\t\t\t\t\t\tif example:\n\t\t\t\t\t\t\texamples.append(example)\n\t\t\treturn VALUE_NEW_LINE.join(set(examples)), VALUE_COMMA.join(set(poses))\n\t\treturn example, pos_extend\n\n\tdef get_phonetic(self, data, json_data):\n\t\tphonetic=data.get(KEY_PHONETIC)\n\t\tif not phonetic or phonetic.strip() == VALUE_EMPTY_STRING:\n\t\t\tphonetics=list()\n\t\t\tfor translator in json_data:\n\t\t\t\tphonetic=translator.get(KEY_PHONETIC)\n\t\t\t\tif phonetic:\n\t\t\t\t\tphonetics.append(phonetic)\n\t\t\treturn VALUE_NEW_LINE.join(set(phonetics))\n\t\treturn phonetic\n\n\tdef get_audio(self, data, json_data):\n\t\taudio=data.get(KEY_AUDIO)\n\t\tif not audio or audio.strip() == VALUE_EMPTY_STRING:\n\t\t\taudios=list()\n\t\t\tfor translator in json_data:\n\t\t\t\tphonetics=translator.get(KEY_PHONETICS)\n\t\t\t\tfor phonetic in phonetics:\n\t\t\t\t\taudio=phonetic.get(KEY_AUDIO)\n\t\t\t\t\tif audio:\n\t\t\t\t\t\taudios.append(audio)\n\t\t\treturn VALUE_NEW_LINE.join(set(audios))\n\t\treturn audio\n\n\tdef validate (self, data):\n\t\tword=data.get(KEY_WORD)\n\t\tresponse=requests.get(DICTIONARY_API_URL.format(word))\n\t\tif response.status_code == 200:\n\t\t\tjson_data: list=response.json()\n\t\t\tdata[KEY_MEANING]=self.get_meaning(data, json_data)\n\t\t\tdata[KEY_EXAMPLE], data[KEY_POS_EXTEND]=self.get_example_and_pos(data, json_data)\n\t\t\tdata[KEY_PHONETIC]=self.get_phonetic(data, json_data)\n\t\t\tdata[KEY_AUDIO]=self.get_audio(data, json_data)\n\n\t\tuser=self.context.get(KEY_REQUEST).user\n\t\tnew_instance=Vocabulary(created_by=user,id=-1)\n\t\tpos=data.get(KEY_POS, new_instance.pos)\n\t\tlanguage=data.get(KEY_LANGUAGE, new_instance.language)\n\t\tcollection_data=data.get(KEY_COLLECTION)\n\t\tcollection=self.validate_collection(collection_data)\n\t\tinstance=self.instance if self.instance else new_instance\n\t\tdata[KEY_COLLECTION]=collection\n\t\tis_exists=Vocabulary.objects.filter(created_by_id=user, word=word,\n\t\t\t\t\t\t\t\t\t\t\t\tpos=pos, language=language, collection_id=collection)\\\n\t\t\t\t\t\t\t\t\t\t.exclude(deleted_by=user).exclude(id=instance.id).exists();\n\t\tif is_exists:\n\t\t\traise serializers.ValidationError(MESSSAGE_VOCABULARY_EXIST)\n\t\treturn data\n\n\tdef save(self, **kwargs):\n\t\t\n\t\treturn super(VocabularySerializer, self).save(**kwargs)\n\t\n\tdef update(self, instance, validated_data):\n\t\tinstance.word=validated_data.get(KEY_WORD, instance.word)\n\t\tinstance.meaning=validated_data.get(KEY_MEANING, instance.meaning)\n\t\tinstance.example=validated_data.get(KEY_EXAMPLE, instance.example)\n\t\tinstance.phonetic=validated_data.get(KEY_PHONETIC, instance.phonetic)\n\t\tinstance.audio=validated_data.get(KEY_AUDIO, instance.audio)\n\t\tinstance.pos=validated_data.get(KEY_POS, instance.pos)\n\t\tinstance.language=validated_data.get(KEY_LANGUAGE, instance.language)\n\t\tinstance.save()\n\t\treturn instance","repo_name":"minhdua/Yovoco","sub_path":"yovoco/entities/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":6766,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"28993440796","text":"import asyncio\nfrom dataclasses import dataclass, field\nimport json\nfrom os import PathLike\nimport os\nimport pathlib\nimport sys\nimport typing\nfrom .font import getOpener\n\n\nclass Project:\n\n def __init__(self):\n self.fonts = []\n self.textSettings = TextSettings()\n self.uiSettings = UISettings()\n self.fontSelection = set() # not persistent\n self._fontLoader = FontLoader()\n self._fontItemIdentifierGenerator = self._fontItemIdentifierGeneratorFunc()\n\n @classmethod\n def fromJSON(cls, data, rootPath):\n return cls.fromDict(json.loads(data), rootPath)\n\n @classmethod\n def fromDict(cls, root, rootPath):\n self = cls()\n for fontItemInfoDict in root[\"fonts\"]:\n fontPath = pathlib.Path(os.path.normpath(os.path.join(rootPath, fontItemInfoDict[\"path\"])))\n self.addFont(fontPath, fontItemInfoDict.get(\"fontNumber\", 0))\n self.textSettings.__dict__.update(root.get(\"textSettings\", {}))\n if self.textSettings.textFilePath is not None:\n # relative path -> absolute path\n self.textSettings.textFilePath = os.path.normpath(os.path.join(rootPath, self.textSettings.textFilePath))\n self.uiSettings.__dict__.update(root.get(\"uiSettings\", {}))\n return self\n\n def asJSON(self, rootPath):\n root = self.asDict(rootPath)\n return json.dumps(root, indent=2, ensure_ascii=False).encode(\"utf=8\")\n\n def asDict(self, rootPath):\n root = {}\n root[\"fonts\"] = []\n for fontItemInfo in self.fonts:\n fontPath, fontNumber = fontItemInfo.fontKey\n relFontPath = os.path.relpath(fontPath, rootPath)\n fontItemInfoDict = dict(path=relFontPath)\n if fontNumber != 0:\n fontItemInfoDict[\"fontNumber\"] = fontNumber\n root[\"fonts\"].append(fontItemInfoDict)\n root[\"textSettings\"] = dict(self.textSettings.__dict__)\n if self.textSettings.textFilePath is not None:\n # absolute path -> relative path\n root[\"textSettings\"][\"textFilePath\"] = os.path.relpath(self.textSettings.textFilePath, rootPath)\n root[\"uiSettings\"] = self.uiSettings.__dict__\n return root\n\n def addFont(self, path: PathLike, fontNumber: int, index=None):\n fontItemInfo = self.newFontItemInfo(path, fontNumber)\n if index is None:\n index = len(self.fonts)\n self.fonts.insert(index, fontItemInfo)\n\n def newFontItemInfo(self, path: PathLike, fontNumber: int):\n if not isinstance(path, PathLike):\n raise TypeError(\"path must be a Path(-like) object\")\n if not isinstance(fontNumber, int):\n raise TypeError(\"fontNumber must be an integer\")\n fontKey = (path, fontNumber)\n fontItemIdentifier = self._nextFontItemIdentifier()\n return FontItemInfo(fontItemIdentifier, fontKey, self._fontLoader)\n\n async def loadFonts(self, outputWriter=None):\n \"\"\"Load fonts as concurrently as possible.\"\"\"\n if outputWriter is None:\n outputWriter = sys.stderr.write\n await asyncio.gather(*(fontItemInfo.load(outputWriter)\n for fontItemInfo in self.fonts if fontItemInfo.font is None))\n\n def _nextFontItemIdentifier(self):\n return next(self._fontItemIdentifierGenerator)\n\n @staticmethod\n def _fontItemIdentifierGeneratorFunc():\n counter = 0\n while True:\n yield f\"fontItem_{counter}\"\n counter += 1\n\n def purgeFonts(self):\n \"\"\"Remove font objects that are no longer referenced in the fontItems\n list.\n \"\"\"\n usedKeys = {fii.fontKey for fii in self.fonts}\n self._fontLoader.purgeFonts(usedKeys)\n\n\nclass FontItemInfo:\n\n def __init__(self, identifier, fontKey, fontLoader):\n self.identifier = identifier\n self.fontKey = fontKey\n self._fontLoader = fontLoader\n\n @property\n def fontPath(self):\n return self.fontKey[0]\n\n @fontPath.setter\n def fontPath(self, newFontPath):\n oldFontKey = self.fontKey\n fontNumber = oldFontKey[1]\n self.fontKey = newFontPath, fontNumber\n self._fontLoader.updateFontKey(oldFontKey, self.fontKey)\n font = self.font\n if font is not None:\n font.updateFontPath(newFontPath)\n\n @property\n def font(self):\n return self._fontLoader.fonts.get(self.fontKey)\n\n @property\n def wantsReload(self):\n return self.fontKey in self._fontLoader.wantsReload\n\n @wantsReload.setter\n def wantsReload(self, value):\n if value:\n self._fontLoader.wantsReload.add(self.fontKey)\n else:\n self._fontLoader.wantsReload.discard(self.fontKey)\n\n async def load(self, outputWriter=None):\n if outputWriter is None:\n outputWriter = sys.stderr.write\n await self._fontLoader.loadFont(self.fontKey, outputWriter)\n\n def unload(self):\n self._fontLoader.unloadFont(self.fontKey)\n\n\nclass FontLoader:\n\n def __init__(self):\n self.fonts = {}\n self.wantsReload = set()\n self.cachedFontData = {}\n\n def getData(self, fontPath):\n assert isinstance(fontPath, os.PathLike)\n fontData = self.cachedFontData.get(fontPath)\n if fontData is None:\n with open(fontPath, \"rb\") as f:\n fontData = f.read()\n self.cachedFontData[fontPath] = fontData\n return fontData\n\n async def loadFont(self, fontKey, outputWriter):\n font = self.fonts.get(fontKey)\n if font is not None:\n if fontKey in self.wantsReload:\n self.wantsReload.remove(fontKey)\n await font.load(outputWriter)\n else:\n path, fontNumber = fontKey\n numFonts, opener, getSortInfo = getOpener(path)\n assert fontNumber < numFonts(path)\n font = opener(path, fontNumber, self)\n await font.load(outputWriter)\n self.fonts[fontKey] = font\n\n def unloadFont(self, fontKey):\n self.fonts.pop(fontKey, None) # discard\n self.cachedFontData = {}\n\n def purgeFonts(self, usedKeys):\n self.fonts = {fontKey: fontObject for fontKey, fontObject in self.fonts.items()\n if fontKey in usedKeys}\n self.cachedFontData = {}\n\n def updateFontKey(self, oldFontKey, newFontKey):\n if oldFontKey not in self.fonts:\n # Font was not loaded, nothing to rename\n return\n self.fonts[newFontKey] = self.fonts.pop(oldFontKey)\n\n\n@dataclass\nclass TextSettings:\n # Content settings\n text: str = \"ABC abc 0123 :;?\" # TODO: From user defaults?\n textFilePath: PathLike = None\n textFileIndex: int = 0\n # Text settings\n shouldApplyBiDi: bool = True\n direction: typing.Union[None, str] = None\n script: typing.Union[None, str] = None\n language: typing.Union[None, str] = None\n alignment: typing.Union[None, str] = None\n # Formatting settings\n features: dict = field(default_factory=dict)\n varLocation: dict = field(default_factory=dict)\n relativeFontSize: float = 0.7\n relativeHBaseline: float = 0.25\n relativeVBaseline: float = 0.5\n relativeMargin: float = 0.1\n enableColor: bool = True\n\n\n@dataclass\nclass UISettings:\n windowPosition: typing.Union[None, list] = None\n fontListItemSize: float = 150\n fontListShowFontFileName: bool = True\n characterListVisible: bool = True\n characterListSize: float = 98\n glyphListVisible: bool = True\n glyphListSize: float = 226\n compileOutputVisible: bool = False\n compileOutputSize: float = 80\n formattingOptionsVisible: bool = True\n feaVarTabSelection: str = \"features\"\n showHiddenAxes: bool = False\n","repo_name":"justvanrossum/fontgoggles","sub_path":"Lib/fontgoggles/project.py","file_name":"project.py","file_ext":"py","file_size_in_byte":7755,"program_lang":"python","lang":"en","doc_type":"code","stars":362,"dataset":"github-code","pt":"81"} +{"seq_id":"73039171145","text":"import numpy as np\r\nimport tensorflow as tf\r\nfrom tensorflow import keras\r\nfrom tensorflow.keras import layers\r\nimport tensorflow_datasets as tfds\r\n\r\nclass Utils:\r\n def __init__(self):\r\n super().__init__()\r\n\r\n def create_nn_model(self):\r\n model = keras.Sequential()\r\n model.add(layers.Flatten(input_shape=(512, 512)))\r\n model.add(layers.BatchNormalization())\r\n model.add(layers.Dense(512, activation=tf.nn.relu))\r\n model.add(layers.Dense(256, activation=tf.nn.relu))\r\n model.add(layers.Dense(128, activation=tf.nn.relu))\r\n model.add(layers.BatchNormalization())\r\n model.add(layers.Dense(3, activation=tf.nn.softmax))\r\n\r\n model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])\r\n return model\r\n\r\n def create_images_dataframe(self, images_path, tag):\r\n items = [];\r\n \r\n for image_path in images_path:\r\n image = keras.preprocessing.image.load_img(\r\n image_path, color_mode='grayscale', target_size=(512, 512),\r\n interpolation='nearest'\r\n )\r\n\r\n image = keras.preprocessing.image.img_to_array(image)\r\n image = np.reshape(image, (512, 512))\r\n item = [(image, tag)]\r\n items = items + item\r\n\r\n return items","repo_name":"IramML/pneumonia-radiography-detector","sub_path":"training/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1346,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"22920609949","text":"# Consensus and Profile\n# =====================\n# \n# A matrix is a rectangular table of values divided into rows and columns. An\n# m×n matrix has m rows and n columns. Given a matrix A, we write Ai,j to\n# indicate the value found at the intersection of row i and column j. You may\n# choose to think of A as a collection of m arrays, each of length n.\n# \n# Say that we have a collection of DNA strings, all having the same length n.\n# Their profile matrix is a 4×n matrix P in which P1,j represents the number of\n# times that 'A' occurs in the jth position of one of the strings, P2,j\n# represents the number of times that C occurs in the jth position, and so on\n# (see below).\n# \n# A consensus string c is a string of length n formed from our collection by\n# taking the most common symbol at each position; the jth symbol of c therefore\n# corresponds to the symbol having the maximum value in the j-th column of the\n# profile matrix. Of course, there may be more than one most common symbol,\n# leading to multiple possible consensus strings.\n# \n# Given: A collection of at most 10 DNA strings of equal length (at most 1 kbp).\n# \n# Return: A consensus string and profile matrix for the collection. (If several\n# possible consensus strings exist, then you may return any one of them.)\n# \n# Sample Dataset\n# --------------\n# ATCCAGCT\n# GGGCAACT\n# ATGGATCT\n# AAGCAACC\n# TTGGAACT\n# ATGCCATT\n# ATGGCACT\n# \n# Sample Output\n# -------------\n# ATGCAACT\n# A: 5 1 0 0 5 5 0 0\n# C: 0 0 1 4 2 0 6 1\n# G: 1 1 6 3 0 1 0 0\n# T: 1 5 0 0 0 1 1 6\n\n\nfrom collections import defaultdict\n\ndef consensus_and_profile(input_str):\n # Split the input string into DNA strings&RosalindID using newline characters\n lines = input_str.strip().split('\\n')\n\n # Separate the description lines (starting with '>') from the DNA strings, to remove Rosalind ID\n dna_strings = [line for line in lines if not line.startswith('>')]\n\n\n # Initialize the profile matrix dictionary\n profile_matrix = defaultdict(list)\n #get the length of the sequences (all are assumed to be the same)\n n = len(dna_strings[0])\n\n # Iterate through the characters to get a count for the bases at each position\n for j in range(n):\n counts = {'A': 0, 'C': 0, 'G': 0, 'T': 0}\n for dna in dna_strings:\n counts[dna[j]] += 1\n #add the base and count of the base at each position into the profile matrix\n for base, count in counts.items():\n profile_matrix[base].append(count)\n\n # Find the consensus string\n #list comprehension to iterate through each position in the profile matrix\n #lambda function is our key, specifies that i want the base and j (think of it like the index of each position) in the range of the sequence \n consensus = ''.join(max(profile_matrix, key=lambda base: profile_matrix[base][j]) for j in range(n))\n\n return {\n 'consensus': consensus,\n 'profile_matrix': dict(profile_matrix)\n }\n\nresult = consensus_and_profile(input_str)\n\n# Print the consensus string\nprint(result['consensus'])\n\n# Print the profile matrix\nfor base, counts in result['profile_matrix'].items():\n print(f\"{base}: {' '.join(map(str, counts))}\")\n","repo_name":"ErvinRex/Rosalind-Problems","sub_path":"Consensus and Profile.py","file_name":"Consensus and Profile.py","file_ext":"py","file_size_in_byte":3180,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"4268561432","text":"import logging\n\nfrom rest_framework import serializers\n\nfrom django.conf import settings\n\nfrom submission import helpers, models, constants\n\nlogger = logging.getLogger(__name__)\n\n\nclass SaveInDatabaseOnlySerializer(serializers.Serializer):\n\n @classmethod\n def from_submission(cls, submission, *args, **kwargs):\n data = {**submission.meta, **submission.data}\n return cls(data=data, *args, **kwargs)\n\n\nclass ZendeskActionSerializer(serializers.Serializer):\n subject = serializers.CharField()\n full_name = serializers.CharField()\n email_address = serializers.EmailField()\n payload = serializers.DictField()\n service_name = serializers.CharField()\n subdomain = serializers.ChoiceField(\n choices=list(settings.ZENDESK_CREDENTIALS.keys()),\n default=settings.ZENDESK_SUBDOMAIN_DEFAULT,\n )\n\n @classmethod\n def from_submission(cls, submission, *args, **kwargs):\n data = {\n **submission.meta,\n 'payload': {\n **submission.data,\n 'ingress_url': submission.meta.get('ingress_url'),\n '_sort_fields_alphabetically': submission.meta.get('sort_fields_alphabetically')\n }\n }\n return cls(data=data, *args, **kwargs)\n\n\nclass EmailActionSerializer(serializers.Serializer):\n subject = serializers.CharField()\n reply_to = serializers.ListField(child=serializers.EmailField())\n recipients = serializers.ListField(child=serializers.EmailField(), required=True)\n html_body = serializers.CharField()\n text_body = serializers.CharField(required=False)\n\n @classmethod\n def from_submission(cls, submission, *args, **kwargs):\n data = {**submission.meta, **submission.data}\n return cls(data=data, *args, **kwargs)\n\n\nclass GovNotifyEmailSerializer(serializers.Serializer):\n template_id = serializers.CharField()\n email_address = serializers.EmailField()\n personalisation = serializers.DictField()\n email_reply_to_id = serializers.CharField(required=False)\n\n @classmethod\n def from_submission(cls, submission, *args, **kwargs):\n data = {**submission.meta, 'personalisation': submission.data}\n return cls(data=data, *args, **kwargs)\n\n\nclass GovNotifyLetterSerializer(serializers.Serializer):\n template_id = serializers.CharField()\n personalisation = serializers.DictField()\n\n @classmethod\n def from_submission(cls, submission, *args, **kwargs):\n data = {**submission.meta, 'personalisation': submission.data}\n return cls(data=data, *args, **kwargs)\n\n\nclass PardotSerializer(serializers.Serializer):\n\n pardot_url = serializers.URLField()\n payload = serializers.DictField()\n\n @classmethod\n def from_submission(cls, submission, *args, **kwargs):\n data = {**submission.meta, 'payload': submission.data}\n return cls(data=data, *args, **kwargs)\n\n\nclass SubmissionModelSerializer(serializers.ModelSerializer):\n\n class Meta:\n model = models.Submission\n fields = (\n 'data',\n 'meta',\n 'form_url',\n 'sender',\n )\n extra_kwargs = {'sender': {'required': True}}\n\n def create(self, validated_data):\n sender_email_address = helpers.get_sender_email_address(validated_data['meta'])\n if sender_email_address:\n sender, _ = models.Sender.objects.get_or_create(\n email_address=sender_email_address\n )\n validated_data['sender_id'] = sender.id\n return super().create(validated_data)\n\n def to_internal_value(self, data):\n data['form_url'] = data['meta'].pop('form_url', '')\n data['client'] = self.context['request'].user\n # This is required for legacy to support old gov-notify action\n # Can be removed when all client are using the new action constant\n if data['meta']['action_name'] == 'gov-notify':\n data['meta']['action_name'] = (\n constants.ACTION_NAME_GOV_NOTIFY_EMAIL\n )\n return data\n","repo_name":"uktrade/directory-forms-api","sub_path":"submission/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":4040,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"34335789037","text":"import torch\n\nimport pytorch_cuda_flow_mp_sad_op\n\nclass FlowMpSadFunction(torch.autograd.Function):\n @staticmethod\n def forward(ctx, f0, f1, sws):\n # shape = N x H x W x K => 2x 3D cost volume for u (=x dir) and v (=y dir)\n offset_u = offset_v = 0\n block_u = block_v = 0\n if sws <= 108:\n #if False:\n cv_u, cv_v, u_star, v_star = pytorch_cuda_flow_mp_sad_op.forward(f0, f1, sws, offset_u, offset_v, block_u, block_v)\n elif sws == 2*108:\n #else:\n #print('Hello -> split-up flow SAD')\n s = sws // 2 # new sub-search-window-size\n cv00_u, cv00_v, u00_star, v00_star = pytorch_cuda_flow_mp_sad_op.forward(f0, f1, s, -s//2, -s//2, 0, 0)#x0y0\n cv01_u, cv01_v, u01_star, v01_star = pytorch_cuda_flow_mp_sad_op.forward(f0, f1, s, -s//2, s//2, 0, 1)#x0y1\n cv10_u, cv10_v, u10_star, v10_star = pytorch_cuda_flow_mp_sad_op.forward(f0, f1, s, s//2, -s//2, 1, 0)#x1y0\n cv11_u, cv11_v, u11_star, v11_star = pytorch_cuda_flow_mp_sad_op.forward(f0, f1, s, s//2, s//2, 1, 1)#x1y1\n\n # ref\n #cv_u_ref, cv_v_ref, u_star_ref, v_star_ref = pytorch_cuda_flow_mp_sad_op.forward(f0, f1, sws, 0,0,0,0)\n \n # merge sub-volums to one volume\n u0 = torch.cat((cv00_u, cv10_u[:,:,:,1:]), dim=-1)\n u1 = torch.cat((cv01_u, cv11_u[:,:,:,1:]), dim=-1)\n au0 = torch.cat((u00_star, u10_star[:,:,:,1:]), dim=-1)\n au1 = torch.cat((u01_star, u11_star[:,:,:,1:]), dim=-1)\n \n idx = u1 < u0\n u0[idx] = u1[idx] # overwrite better values\n au0[idx] = au1[idx]\n\n\n v0 = torch.cat((cv00_v, cv01_v[:,:,:,1:]), dim=-1)\n v1 = torch.cat((cv10_v, cv11_v[:,:,:,1:]), dim=-1)\n av0 = torch.cat((v00_star, v01_star[:,:,:,1:]), dim=-1)\n av1 = torch.cat((v10_star, v11_star[:,:,:,1:]), dim=-1)\n \n idx = v1 < v0\n v0[idx] = v1[idx] # overwrite better valves\n av0[idx] = av1[idx]\n\n cv_u = u0\n u_star = au0\n cv_v = v0\n v_star = av0\n elif sws == 432: # sintel all!!\n # global offset\n go_u = 0\n go_v = 0\n \n # read cost-volume block u\n # index with row and col\n cv_bu = [[], []]\n cv_bv = [[], []]\n bu_star = [[], []]\n bv_star = [[], []]\n\n s = 108 # search-window size of block\n # iterate over 4 x 4 grid\n for idx_v, grid_v in enumerate([-2, -1, 1, -2]): # grid-position\n for idx_u, grid_u in enumerate([-2, -1, 1, -2]):\n ro_u = (grid_u * 2 - 1) * s // 2 # relative offset in x\n ro_v = (grid_v * 2 - 1) * s // 2 # relative offset in y\n\n cv_uu, cv_vv, uu_star, vv_star = pytorch_cuda_flow_mp_sad_op.forward(f0, f1, s, \n ro_u + go_u, ro_v + go_v, idx_u, idx_v)\n cv_bu[idx_u].append(cv_uu)\n cv_bv[idx_u].append(cv_vv)\n bu_star[idx_u].append(uu_star)\n bv_star[idx_v].append(vv_star)\n\n # stitch complete cv_u\n # read: u0 for all v, u_star for all v\n u0_v = [cv_bu[0][idx_v] for idx_v in range(4)]\n u_star_v = [bu_star[0][idx_v] for idx_v in range(4)]\n for idx_u in range(1, len(cv_bu[0])):\n for idx_v in range(4):\n # increment u, keepp v\n u0_v[idx_v] = torch.cat((u0_v[idx_v], cv_bu[idx_u][idx_v][:,:,:,1:]), dim=-1)\n u_star_v[idx_v] = torch.cat((u_star_v[idx_v], bu_star[idx_u][idx_v][:,:,:,1:]), dim=-1)\n\n \n\n\n #elif sws == 372: # kitti \n # ATTENTION: FORWARD WOULD WORK NICELY LIKE THAT, BUT BACKWARD WOULD NEED THE ORIGINAL SEARCH WINDOW!!\n # PROBABLY NOT A GOOD IDEA TO CHANGE THIS NOW ...\n # # 2 x 6 grid with size 372 x 124 with block-size 62 and offset (+18, +36)\n \n # # global offset\n # go = np.array([18, 36])\n \n # # read cost-volume block u\n # # index with row and col\n # cv_bu = [[], []]\n # cv_bv = [[], []]\n # bu_star = [[], []]\n # bv_star = [[], []]\n\n # # iterate over 2 x 6 grid\n # for grid_v in range(-1, 2):\n # for grid_u in range(-3, 4):\n # cv_uu, cv_vv, uu_star, vv_star = pytorch_cuda_flow_mp_sad_op.forward(f0, f1, s, -s//2, -s//2, 0, 0)#x0y0\n else:\n raise ValueError(\"Unsupported sws: \", sws, \"only allowd: <= 108 or 216\")\n \n ctx.save_for_backward(f0, f1, torch.tensor(sws), u_star, v_star)\n return cv_u, cv_v, u_star, v_star\n\n @staticmethod\n def backward(ctx, in_grad_u, in_grad_v, u_star_grad, v_star_grad):\n # u_star_grad and v_star_grad are just zeros.\n f0, f1, sws, u_star, v_star = ctx.saved_tensors\n df0, df1 = pytorch_cuda_flow_mp_sad_op.backward(f0, f1, int(sws), in_grad_u, in_grad_v, u_star, v_star)\n return df0, df1, None, None\n","repo_name":"VLOGroup/bp-layers","sub_path":"ops/flow_mp_sad/flow_mp_sad.py","file_name":"flow_mp_sad.py","file_ext":"py","file_size_in_byte":5266,"program_lang":"python","lang":"en","doc_type":"code","stars":19,"dataset":"github-code","pt":"81"} +{"seq_id":"70154085385","text":"import sys\nfrom pathlib import Path\nsys.path.append(str(Path(__file__).resolve().parents[1]))\nsys.path.append(str(Path(__file__).parents[2]))\nfrom utils.analysis import plot\nfrom utils.analysis.tools import chance_level\n\nfrom cross_decoding.plot_results import determine_colour, x_axis_seconds\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\n\ndef cross_diags_average_sesh(acc_vis, acc_mem, acc_all, SE=False, save_path=None, title=None):\n \n diagonals_vis = np.diagonal(acc_vis, axis1=2, axis2=3) * 100\n diagonals_mem = np.diagonal(acc_mem, axis1=2, axis2=3) * 100\n diagonals_all = np.diagonal(acc_all, axis1=2, axis2=3) * 100\n\n\n fig, ax = plt.subplots(3, 1, figsize = (12, 14), dpi = 300)\n\n for ax_ind, acc in enumerate([diagonals_vis, diagonals_mem, diagonals_all]):\n # create 11 by 11 matrix with distances between sessions\n # empty matrix\n distances = np.zeros((acc.shape[0], acc.shape[0]))\n order = np.arange(acc.shape[0])\n\n # fill in the matrix\n for i in range(11):\n for j in range(11):\n distances[i, j] = abs(order[i]-order[j])\n \n # loop over all distances\n for dist in range(acc.shape[0]):\n # skip distance 0\n if dist == 0:\n pass\n else:\n # get the indices of the sessions that are dist away from each other\n indices = np.argwhere(distances == dist)\n\n if indices.shape[0] == 0:\n continue\n\n # get the average accuracy for each pair of sessions that are dist away from each other\n tmp = np.array([acc[i, j] for i, j in indices])\n n_pairs = tmp.shape[0]\n\n # standard deviation\n\n tmp_acc = tmp.mean(axis = 0)\n\n colour = determine_colour(12, dist)\n \n # plot tmp acc\n ax[ax_ind].plot(tmp_acc, label = f'{dist} ({n_pairs} pairs)', linewidth = 1, color = colour)\n \n if SE: \n # standard deviation\n tmp_std = tmp.std(axis = 0)\n \n # standard error\n tmp_std = tmp_std / np.sqrt(tmp.shape[0])\n\n # plot standard error\n ax[ax_ind].fill_between(np.arange(0, 250), (tmp_acc - tmp_std), (tmp_acc + tmp_std), alpha = 0.1, color =colour)\n \n # plot legend\n ax[ax_ind].legend(loc = 'upper right', title = \"Distance\".upper())\n ax[ax_ind].set_ylabel(['Visual', 'Memory', 'Combined'][ax_ind].upper())\n \n # set x axis to seconds\n x_axis_seconds(ax[ax_ind])\n\n\n # add title and labels\n if title:\n fig.suptitle(title.upper())\n\n fig.supylabel('Average cross-decoding accuracy (%)'.upper())\n fig.supxlabel('Time (s)'.upper())\n \n plt.tight_layout()\n\n if save_path:\n plt.savefig(save_path)\n\n\ndef plot_tgms(vis_acc, mem_acc, all_acc, save_path=None, title=None):\n fig, ax = plt.subplots(1, 3, figsize = (14, 6), dpi = 300)\n\n for ax_ind, (acc, subtitle) in enumerate(zip([vis_acc, mem_acc, all_acc], [\"VISUAL\", \"MEMORY\", \"COMBINED\"])):\n\n # set within session accuracies to nan\n acc1 = acc.copy()\n acc1[np.arange(acc1.shape[0]), np.arange(acc1.shape[1]), :, :] = np.nan\n\n # plot\n plot.plot_tgm_ax(np.nanmean(acc1, axis =(0, 1)), ax = ax[ax_ind], vmin=40, vmax=60)\n\n # set title\n ax[ax_ind].set_title(subtitle)\n\n\n if title:\n fig.suptitle(title.upper())\n \n if save_path:\n plt.savefig(save_path)\n\n\ndef main():\n alpha = 0.05\n path = Path(__file__).parent\n acc_all = np.load(path / \"accuracies\" / \"LDA_auto_10_all_11.npy\")\n acc_vis = np.load(path / \"accuracies\" / \"LDA_auto_10_visual_11.npy\")\n acc_mem = np.load(path / \"accuracies\" / \"LDA_auto_10_memory_11.npy\")\n \n # average over all sessions\n cross_diags_average_sesh(acc_vis, acc_mem, acc_all, save_path = path / \"plots\" / \"sens_average_diagonals_bins.png\", title=\"Average decoding accuracy given distances between bins\")\n\n\n # plot average\n plot_tgms(acc_vis, acc_mem, acc_all, save_path = path / \"plots\" / \"sens_average_tgm_bins.png\")\n\n \n\nif __name__ in \"__main__\":\n main()","repo_name":"laurabpaulsen/DecodingMagneto","sub_path":"decoding/cross_block/plot_results.py","file_name":"plot_results.py","file_ext":"py","file_size_in_byte":4360,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"18931724524","text":"from codes import *\n\n\nclass Pacific:\n \n # The respective generator polynomials for the fields GF(2^k) used in the chip.\n generator_polynomials = {\n 4 : [1,0,0,1,1], # 1+x+x^4\n 5 : [1,0,0,1,0,1],\n 6 : [1,0,0,0,0,1,1],\n 7 : [1,0,0,0,1,0,0,1],\n 8 : [1,0,0,0,1,1,1,0,1],\n 9 : [1,0,0,0,0,1,0,0,0,1],\n 10 : [1,0,0,0,0,0,0,1,0,0,1],\n 11 : [1,0,0,0,0,0,0,0,0,1,0,1],\n 15 : [1,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1],\n 16 : [1,0,0,0,1,0,0,0,0,0,0,0,0,1,0,1,1]\n }\n\n cpc = [None] * 11 # 11 CPC instances are implemented in Pacific.\n \n cpc[0] = CPC([QS(32, 4, gen=generator_polynomials[4])])\n cpc[1] = CPC([TS(12, 4, gen=generator_polynomials[4])])\n cpc[2] = CPC([PC(10, 6, gen=generator_polynomials[10])])\n \n cpc[3] = CPC([QS(42, 7, gen=generator_polynomials[7]),\n TS(21, 7, gen=generator_polynomials[7])])\n \n cpc[4] = CPC([QS(80, 8, gen=generator_polynomials[8]),\n PC(10, 8, gen=generator_polynomials[10])])\n \n cpc[5] = CPC([QS(66, 11, gen=generator_polynomials[11]),\n TS(33, 11, gen=generator_polynomials[11]),\n PC(16, 11, gen=generator_polynomials[16])])\n \n cpc[6] = CPC([QS(48, 6, gen=generator_polynomials[6]),\n PC(9, 6, gen=generator_polynomials[9]),\n PC(7, 6, gen=generator_polynomials[7])])\n \n cpc[7] = CPC([PC(15, 9, gen=generator_polynomials[15]),\n PC(10, 9, gen=generator_polynomials[10])])\n \n cpc[8] = CPC([TS(15, 5, gen=generator_polynomials[5]),\n PC(8, 5, gen=generator_polynomials[8])])\n\n cpc[9] = CPC([QS(120, 10, gen=generator_polynomials[10])])\n cpc[10] = CPC([QS(132, 6, gen=generator_polynomials[6])])\n\n\nif __name__ == '__main__':\n for cpc in Pacific.cpc:\n test_code(cpc, 1)\n","repo_name":"Euphoriaa/pycpc","sub_path":"src/pacific.py","file_name":"pacific.py","file_ext":"py","file_size_in_byte":1876,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"27617037736","text":"# Max score: ~22.6 or 23 Min score: ~-13\n\n# Imports\nimport logging\nimport random\n\nimport finviz\nimport pickle\nimport time\n#import pandas\nimport json\nfrom datetime import date\nfrom datetime import datetime\n#import stuffy as stuffyimportsys\n\nnow = datetime.now()\ndt_string = now.strftime(\"%d/%m/%Y %H:%M:%S\")\ntoday = date.today()\ndate = today.strftime(\"%d/%m/%Y\")\ntimestamp = dt_string\n# Variables\nnum = random.randint(0, 10000)\nnum2 = str(num)\nyes = [\"yes\", \"yep\", \"yea\", \"y\", \"yup\", \"true\", \"t\", \"Yes\", \"Yep\", \"Yea\", \"Y\", \"Yup\", True, \"True\", \"T\", \"halal\",\n \"Halal\", \"a\", \"o\", \"A\", \"O\", \"above\", \"Above\", \"over\", \"Over\", \"g\", \"G\", \"up\", \"Up\", \"UP\", \"\", \" \"]\nno = [\"no\", \"n\", \"false\", \"f\", \"nope\", \"No\", \"N\", False, \"False\", \"F\", \"Nope\", \"nothalal\", \"Nothalal\", \"notHalal\",\n \"NotHalal\", \"nah\", \"Nah\", \"u\", \"b\", \"U\", \"B\", \"under\", \"below\", \"Under\", \"Below\", \"down\", \"Down\", \"DOWN\"]\n# indicators\nt200 = {\"name\": \"The 200!\", \"gWeight\": 2, \"bWeight\": -2, \"spc\": \"Is the 200 crossing up or down?\", \"gsp\": 1,\n \"bsp\": -1.5, \"notes\": \"\"}\nt9 = {\"name\": \"The 9!\", \"gWeight\": 1.5, \"bWeight\": -1.5,\n \"spc\": \"Is it One candle close above or below thw nine the 9? (Means get in or watch or get out if below)\",\n \"gsp\": 1.5, \"bsp\": -1.5, \"notes\": \"Prob close when under 9\"}\nMACD = {\"name\": \"MACD\", \"gWeight\": 1.5, \"bWeight\": -1.5, \"spc\": \"Is the MACD reversing up or down, is it crossing?\",\n \"gsp\": 1.5, \"bsp\": -1.5, \"notes\": \"\"}\nRSI = {\"name\": \"RSI\", \"gWeight\": 1, \"bWeight\": -1, \"spc\": \"Is the RSI Oversold(good)(y) or Overbought(bad)(n)?\", \"gsp\": 1.5,\n \"bsp\": -1, \"notes\": \"over bought for selling only\"}\nVWAP = {\"name\": \"VWAP\", \"gWeight\": 1.5, \"bWeight\": -1.5, \"spc\": \"None/WIP\", \"gsp\": 0, \"bsp\": 0,\n \"notes\": \"\"}\nHA = {\"name\": \"Heiken Ashi\", \"gWeight\": 1.2, \"bWeight\": -1, \"spc\": \"None/WIP\", \"gsp\": 0, \"bsp\": 0,\n \"notes\": \"\"}\nSHAC = {\"name\": \"Smoothed Ha Candles\", \"gWeight\": 1.2, \"bWeight\": -1, \"spc\": \"None/WIP\", \"gsp\": 0, \"bsp\": 0,\n \"notes\": \"\"}\nRIB = {\"name\": \"Ribbons\", \"gWeight\": 1.5, \"bWeight\": -1.5, \"spc\": \"None/WIP\", \"gsp\": 0, \"bsp\": 0,\n \"notes\": \"\"}\nVPVR = {\"name\": \"VPVR\", \"gWeight\": 1.2, \"bWeight\": -1, \"spc\": \"Is it Jump Up/Jump Down?\", \"gsp\": 2, \"bsp\": -2,\n \"notes\": \"Good for crypto.\"}\n# t9 = {\"name\" : \"The 9!\", \"gWeight\" : 1.5, \"bWeight\" : -1.5, \"spc\" : \"Is it One candle close above or below thw nine the 9? (Means get in or watch or get out if below)\", \"gsp\" : 1.5, \"bsp\" : -1.5, \"notes\" : \"Prob close when under 9\"}\nothers = [\"Support\", \"Resistance\", \"Moveing Averages\", \"VBottoms (for entry) and etc...\", \"Wedges and etc...\",\n \"Divergence (really bad)\", \"Earnings Call (bad)\"]\n# LUX = \"Is it neer a cloud?\"\nLUX = {\"name\": \"LUX\", \"gWeight\": 1, \"bWeight\": -1, \"spc\": \"Is it neer a cloud? Buy Cloud(y) Sell Cloud(n)\", \"gsp\": 1.5, \"bsp\": -1.5,\n \"notes\": \"Prob close when under 9\"}\n\n# files\n\"\"\"\nfile = open('save_data.txt', 'r') this is to read\nfile = open('save_data.txt', 'w') this is to write\nfile = open('save_data.txt', 'a') this is to append (to file)\nfile = open('save_data.txt', 'r+') this is to read and write\n\"\"\"\n\n\n# with open('save_data', 'r') as file:\n# pass\n\n\n# Functions\ndef error(error):\n \"\"\"\n prints and saves errors\n :param error:\n :return:\n \"\"\"\n print(error)\n with open('errors.json') as e:\n thetime = time(\"time\")\n thedate = time(\"date\")\n data = json.load(e)\n temp = data[\"logs\"]\n new_data = {thedate: [{\"timestamp\": thetime, \"error\": error}]}\n temp.append(new_data)\n write_json(data, \"errors.json\")\n\n\ndef time(dateortime):\n from datetime import date\n from datetime import datetime\n now = datetime.now()\n dt_string = now.strftime(\"%d/%m/%Y %H:%M:%S\")\n today = date.today()\n date = today.strftime(\"%d/%m/%Y\")\n time = dt_string\n try:\n if dateortime == \"date\":\n return date\n elif dateortime == \"time\":\n return time\n except:\n error(\"Error not an option, try again.\")\n\n\ndef write_json(data, filename):\n with open(filename, 'w') as f:\n json.dump(data, f, indent=2)\n\n\ndef save(datas, filename):\n thetime = time(\"time\")\n thedate = time(\"date\")\n # with open('save_data.txt', 'a') as file:\n # file.write(f\"{date}\\n\")\n # file.write({\"date\" : date, \"ticker\" : \"TSLA\"})\n\n with open(filename) as file:\n # file.write(json.dumps({date : [{\"ticker\" : \"TSLA\", \"indicator\" : VPVR}]}, indent=2))\n # stand it data btw will pass in from func\n data = json.load(file)\n temp = data[\"logs\"]\n # new_data = {thedate : [{\"timestamp\": thetime, \"packet\": [{\"ticker\": \"TSLA\", \"indicator\": VPVR}]}]}\n # new_data = {thedate: [{\"timestamp\": thetime, \"packet\": datas}]}\n temp.append(datas)\n write_json(data, filename)\n\n\ndef load(filename):\n # with open('save_data.txt', 'r') as file:\n # contents = file.read()\n # print(contents, end='')\n\n with open(filename, 'r') as file:\n data = json.load(file)\n # print(data[\"logs\"][0][date][0][\"dat\"][0][\"#data here\"])\n stuff = data[\"logs\"]\n return data\n\n\ndef questioner(aCount, question, answers):\n # for i in answers:\n # answers.append(\"\\n\")\n while True:\n print(question)\n for i in answers:\n print(i)\n q1 = int(input(\">>> \"))\n if q1 == 0:\n break\n elif q1 <= aCount:\n return q1\n else:\n error(\"Error: Line 77, wrong aCount, check parameters.\")\n print(\"Or wrong option.\")\n\n\ndef seeStock(halalornothalal):\n \"\"\"\n :param halalornothalal:\n :return list of either all the halal stocks or all the non-halal stocks:\n \"\"\"\n stuff = load(\"tickers.json\")\n halal = []\n nothalal = []\n for i in stuff[\"logs\"]:\n things = i[\"ticker\"]\n if i[\"halal\"] == True:\n halal.append(things)\n elif i[\"halal\"] == False:\n nothalal.append(things)\n if halalornothalal in yes:\n return halal\n elif halalornothalal in no:\n return nothalal\n else:\n error(\"Error: Check parameters.\")\n\ndef halalCheck(ticker):\n \"\"\"\n\n :param ticker:\n :return \"halal\" if the ticker is halal and \"nothalal\" if it isent, or \"new\" if its new:\n \"\"\"\n stuff = load(\"tickers.json\")\n halal = []\n nothalal = []\n for i in stuff[\"logs\"]:\n things = i[\"ticker\"]\n if i[\"halal\"] == True:\n halal.append(things)\n elif i[\"halal\"] == False:\n nothalal.append(things)\n\n if ticker in halal:\n return \"halal\"\n elif ticker in nothalal:\n return \"nothalal\"\n else: return \"new\"\n\n\ndef newStock(ticker):\n halal = input(\"Is it halal?\\n>>> \")\n if halal in yes:\n save({\"ticker\": ticker, \"halal\": True}, \"tickers.json\")\n # again = input(\"Another one?\\n>>> \").lower()\n # if again in yes:\n # pass\n\n elif halal in no:\n save({\"ticker\": ticker, \"halal\": False}, \"tickers.json\")\n # again = input(\"Another one?\\n>>> \").lower()\n # if again in yes:\n # pass\n\n\n# def askindicator(indicator, question):\n# indi = input(question)\ndef score():\n # The 200!\n score = 0\n # print(score)\n indicators = []\n the200 = input(\"Is above the 200 or below the 200? y/n\\n>>> \")\n if the200 in yes:\n score += t200[\"gWeight\"]\n indicators.append(\"Is above the 200!\")\n elif the200 in no:\n score += t200[\"bWeight\"]\n indicators.append(\"Is UNDER the 200!\")\n the200 = input(f'{t200[\"spc\"]} y/n\\n>>> ')\n if the200 in no:\n pass\n else:\n the200 = input(f'{t200[\"spc\"]} y/n\\n>>> ')\n if the200 in yes:\n score += t200[\"gsp\"]\n indicators.append(\"Is about to cross above the 200!\")\n elif the200 in no:\n score += t200[\"bsp\"]\n indicators.append(\"Is about to cross UNDER the 200!\")\n\n print(score)\n\n # The 9!\n quizz = input(\"Is it above The 9? y/n\\n>>> \")\n if quizz in yes:\n score += t9[\"gWeight\"]\n indicators.append(\"Is above the 9!\")\n elif quizz in no:\n score += t9[\"bWeight\"]\n indicators.append(\"Is under the 9!\")\n quizz = input(f'{t9[\"spc\"]} y/n\\n>>> ')\n if quizz in no:\n pass\n else:\n quizz = input(f'{t9[\"spc\"]} y/n\\n>>> ')\n if quizz in yes:\n score += t9[\"gsp\"]\n indicators.append(\"Is one candle close above the 9!\")\n elif quizz in no:\n score += t9[\"bsp\"]\n indicators.append(\"Is one candle close UNDER the 9! (sell)\")\n print(score)\n # The MACD!\n quizz = input(\"Is the MACD above the the red or below the red/Is it in the green or red? y/n\\n>>> \")\n if quizz in yes:\n score += MACD[\"gWeight\"]\n indicators.append(\"MACD Is above the the red (line) or is in the green (bar)!\")\n elif quizz in no:\n score += MACD[\"bWeight\"]\n indicators.append(\"MACD Is UNDER the red (line) or is in the red (bar)!\")\n quizz = input(f'{MACD[\"spc\"]} y/n\\n>>> ')\n if quizz in no:\n pass\n else:\n quizz = input(f'{MACD[\"spc\"]} y/n\\n>>> ')\n if quizz in yes:\n score += MACD[\"gsp\"]\n indicators.append(\"MACD Is reverseing to green or crossing above the red!\")\n elif quizz in no:\n score += MACD[\"bsp\"]\n indicators.append(\"MACD Is reversing to red or crossing under the red!\")\n\n print(score)\n # The RSI!\n quizz = input(\"Is the RSI low(good)(y) or high(bad)(n)? y/n\\n>>> \")\n if quizz in yes:\n score += RSI[\"gWeight\"]\n indicators.append(\"RSI is low!\")\n elif quizz in no:\n score += RSI[\"bWeight\"]\n indicators.append(\"RSI is high!\")\n quizz = input(f'{RSI[\"spc\"]} y/n\\n>>> ')\n if quizz in no:\n pass\n else:\n quizz = input(f'{RSI[\"spc\"]} y/n\\n>>> ')\n if quizz in yes:\n score += RSI[\"gsp\"]\n indicators.append(\"RSI is overbought!\")\n elif quizz in no:\n score += RSI[\"bsp\"]\n indicators.append(\"RSI is oversold!\")\n\n print(score)\n # The VWAP!\n quizz = input(\"Is it above or below the VWAP? (above/on is gogo juise! VWAP above 9 is gogo) y/n\\n>>> \")\n if quizz in yes:\n score += VWAP[\"gWeight\"]\n indicators.append(\"We have GoGo Juise!\")\n elif quizz in no:\n score += VWAP[\"bWeight\"]\n indicators.append(\"No gogo juise! :(\")\n\n print(score)\n # Heiken Ashi!\n quizz = input(\"Is the Heiken Ashi trending up or down? y/n\\n>>> \")\n if quizz in yes:\n score += HA[\"gWeight\"]\n indicators.append(\"Heiken Ashi is trending UP!\")\n elif quizz in no:\n score += HA[\"bWeight\"]\n indicators.append(\"Heiken Ashi is trending DOWN!\")\n\n print(score)\n # Smoothed Heiken Ashi Candles!\n quizz = input(\"Is the Smoothed Heiken Ashi Candles trending up or down? y/n\\n>>> \")\n if quizz in yes:\n score += SHAC[\"gWeight\"]\n indicators.append(\"Smoothed Heiken Ashi Candles are trending UP!\")\n elif quizz in no:\n score += SHAC[\"bWeight\"]\n indicators.append(\"Smoothed Heiken Ashi Candles are trending DOWN!\")\n\n print(score)\n # Ribbons\n quizz = input(\"Is above or below the Ribbons? y/n\\n>>> \")\n if quizz in yes:\n score += RIB[\"gWeight\"]\n indicators.append(\"Is above the Ribbons!\")\n elif quizz in no:\n score += RIB[\"bWeight\"]\n indicators.append(\"Is BELOW the Ribbons!\")\n\n print(score)\n # VPVR\n quizz = input(\"Is there VPVR? y/n\\n>>> \")\n if quizz in yes:\n score += VPVR[\"gWeight\"]\n indicators.append(\"VPVR looks good!\")\n elif quizz in no:\n score += VPVR[\"bWeight\"]\n indicators.append(\"VPVR looks bad!\")\n quizz = input(f'{VPVR[\"spc\"]} y/n\\n>>> ')\n if quizz in no:\n pass\n else:\n quizz = input(f'{VPVR[\"spc\"]} y/n\\n>>> ')\n if quizz in yes:\n score += VPVR[\"gsp\"]\n indicators.append(\"Is about to jump UP!\")\n elif quizz in no:\n score += VPVR[\"bsp\"]\n indicators.append(\"Is about to jump DOWN!\")\n\n print(score)\n # LUX Algo Premium!\n quizz = input(\"Is LUX good? y/n\\n>>> \")\n if quizz in yes:\n score += LUX[\"gWeight\"]\n indicators.append(\"LUX looks good!\")\n elif quizz in no:\n score += LUX[\"bWeight\"]\n indicators.append(\"LUX looks bad!\")\n quizz = input(f'{LUX[\"spc\"]} y/n\\n>>> ')\n if quizz in no:\n pass\n else:\n quizz = input(f'{LUX[\"spc\"]} y/n\\n>>> ')\n if quizz in yes:\n score += LUX[\"gsp\"]\n indicators.append(\"Is near or in the buy cloud!\")\n elif quizz in no:\n score += LUX[\"bsp\"]\n indicators.append(\"Is near or in the sell cloud!\")\n\n # if scoreORindicators == \"score\" or scoreORindicators in yes:\n # return score\n # elif scoreORindicators == \"indicators\" or scoreORindicators in no:\n # return indicators\n print(score)\n\n pack = [score, indicators]\n return pack\n\n\ndef q1():\n name = input(\"What is the ticker?\\n>>> \").upper()\n if name in seeStock(\"halal\"): # and name not in seeStock(\"nothalal\"):\n print(\"Stock is halal, proceeding...\")\n stuff = score()\n stuffy = [round(stuff[0], 2), stuff[1]]\n #stuffy = score()\n\n timestamp = time(\"time\")\n save({\"ticker\": name, \"time\": timestamp, \"packet\": [timestamp, stuffy]}, \"save_data.json\")\n elif name in seeStock(\"nothalal\"): # and name not in seeStock(\"halal\"):\n print(\"Stock is NOT Halal, unable to proceed, check Zoya, edit 'tickers.json' if necessary...\")\n elif name not in seeStock(\"halal\") and name not in seeStock(\"nothalal\"):\n # ticker = input(\"What is the ticker?\\n>>> \").upper()\n print(\"Not registerd, makeing new stock log...\")\n newStock(name)\n\ndef q2():\n while True:\n qqq = questioner(4, \"What do you want to do?\",\n [\"1. Check if a stock is halal.\", \"2. View halal stocks.\",\n \"3. View NOT halal stocks.\", \"4. Exit...\"])\n if qqq == 1:\n flag = False\n while flag == False:\n flag = False\n ticker = input(\"What is the ticker?\\n>>> \").upper()\n\n if ticker in seeStock(\"halal\"):\n qq = input(\"Ticker is Halal. Another ticker? y/n\\n>>> \")\n if qq in yes: pass\n else:flag=True\n\n elif ticker in seeStock(\"nothalal\"):\n qq = input(\"Ticker is NOT Halal. Another ticker? y/n\\n>> \")\n if qq in yes: pass\n else:flag=True\n\n elif ticker not in seeStock(\"halal\") and ticker not in seeStock(\"nothalal\"):\n newStock(ticker)\n again = input(\"Another ticker? y/n\\n>>> \").lower()\n if again in yes:\n pass\n else:\n flag = True\n # newStock(ticker)\n # halal = input(\"Is it halal?\\n>>> \")\n # if halal in yes:\n # save({\"ticker\": ticker, \"halal\": True}, \"tickers.json\")\n\n else:\n pass\n\n elif qqq == 2:\n print(' '.join(seeStock(\"halal\")))\n break\n elif qqq == 3:\n print(' '.join(seeStock(\"nothalal\")))\n break\n elif qqq == 3:\n break\n else:\n break\n # ticker = input(\"What is the ticker?\\n>>> \").upper()\n # # stuff = load(\"tickers.json\")\n # # stuffs = []\n # # nothalal = []\n # # for i in stuff[\"logs\"]:\n # # things = i[\"ticker\"]\n # # if i[\"halal\"] == True:\n # # stuffs.append(things)\n # # elif i[\"halal\"] == False:\n # # nothalal.append(things)\n #\n # if halalCheck(ticker) == \"halal\":\n # qq = input(\"Ticker is Halal. Another ticker?\\n>>> \")\n # if qq in yes:\n #\n # elif ticker in nothalal:\n # qq = input(\"Ticker is NOT Halal. See Not Halal tickers?\")\n # if qq in yes:\n # print(nothalal)\n # again = input(\"Another ticker?\\n>>> \").lower()\n # if again in yes:\n # pass\n # else:\n # break\n # elif qq in no:\n # again = input(\"Another ticker?\\n>>> \").lower()\n # if again in yes:\n # pass\n # else:\n # break\n # else:\n # again = input(\"Another ticker?\\n>>> \").lower()\n # if again in yes:\n # pass\n # else:\n # break\n # if ticker not in stuffs and ticker not in nothalal:\n # halal = input(\"Is it halal?\\n>>> \")\n # if halal in yes:\n # save({\"ticker\": ticker, \"halal\": True}, \"tickers.json\")\n # again = input(\"Another one?\\n>>> \").lower()\n # if again in yes:\n # pass\n # else:\n # break\n # elif halal in no:\n # save({\"ticker\": ticker, \"halal\": False}, \"tickers.json\")\n # again = input(\"Another one?\\n>>> \").lower()\n # if again in yes:\n # pass\n # else:\n # break\n #\n # else:\n # break\n # else:\n # pass\n\n\ndef q3():\n while True:\n q = questioner(5, \"What do you want to do?\", [\"1. View history.\", \"2. View ticker history.\", \"3. Yesterday.\", \"4. Today.\", \"5. Exit... \"])\n if q == 1:\n history = load(\"save_data.json\")\n # print(history)\n for i in history[\"logs\"]:\n print(f'On {i[\"time\"]} {i[\"ticker\"]} had a score of {i[\"packet\"][1][0]}')\n qs = input(\"Do you want to look at a block?\\n>>> \")\n # if qs in yes:\n # theblock = input(\"Enter the timestamp: (d/m/y h/m/s) Ex:12/06/2022 01:44:53\\n>>> \")\n # for block in history[\"logs\"]:\n # while True:\n # if block[\"time\"] == theblock:\n # for i in block[\"packet\"][1][1]:\n # print(i)\n # break\n # else:\n # error(\"Wrong TimeStamp! make sure its n the (d/m/y h/m/s) format!\")\n # break\n if qs in yes:\n theblock = input(\"Enter the timestamp: (d/m/y h/m/s) Ex:12/06/2022 01:44:53\\n>>> \")\n for block in history[\"logs\"]:\n if block[\"time\"] == theblock:\n for i in block[\"packet\"][1][1]:\n print(i)\n print(f'{block[\"ticker\"]} had a score of {block[\"packet\"][1][0]}')\n elif qs in no:\n pass\n else:\n error(\"Error: not an option, try again. Exit Code [4]\")\n pass\n elif q == 2:\n history = load(\"save_data.json\")\n name = input(\"What is the ticker?\\n>>> \").upper()\n if name in seeStock(\"halal\"): # and name not in seeStock(\"nothalal\"):\n print(\"Stock is halal, proceeding...\")\n for i in history[\"logs\"]:\n if i[\"ticker\"] == name:\n print(f'On {i[\"time\"]} {i[\"ticker\"]} had a score of {i[\"packet\"][1][0]}')\n qs = input(\"Do you want to look at a block?\\n>>> \")\n if qs in yes:\n theblock = input(\"Enter the timestamp: (d/m/y h/m/s) Ex:12/06/2022 01:44:53\\n>>> \")\n for block in history[\"logs\"]:\n if block[\"time\"] == theblock:\n for i in block[\"packet\"][1][1]:\n print(i)\n print(f'{block[\"ticker\"]} had a score of {block[\"packet\"][1][0]}')\n elif qs in no:\n pass\n else:\n error(\"Error: not an option, try again. Exit Code [4]\")\n pass\n elif name in seeStock(\"nothalal\"): # and name not in seeStock(\"halal\"):\n print(\"Stock is NOT Halal, unable to proceed, check Zoya, edit 'tickers.json' if nessesary...\")\n elif name not in seeStock(\"halal\") and name not in seeStock(\"nothalal\"):\n # ticker = input(\"What is the ticker?\\n>>> \").upper()\n print(\"Not registerd, makeing new stock log...\")\n newStock(name)\n elif q == 3:\n from datetime import date, timedelta\n todays = date.today()\n yesterday = todays - timedelta(days=1) # FIX FORMAT\n yesterday = yesterday.strftime('%d/%m/%Y')\n history = load(\"save_data.json\")\n for i in history[\"logs\"]:\n stRing = i[\"time\"]\n dateChar = stRing[0: 10]\n if yesterday == dateChar:\n print(f'On {i[\"time\"]} {i[\"ticker\"]} had a score of {i[\"packet\"][1][0]}')\n qs = input(\"Do you want to look at a block?\\n>>> \")\n if qs in yes:\n theblock = input(\"Enter the timestamp: (d/m/y h/m/s) Ex:12/06/2022 01:44:53\\n>>> \")\n for block in history[\"logs\"]:\n if block[\"time\"] == theblock:\n for i in block[\"packet\"][1][1]:\n print(i)\n print(f'{block[\"ticker\"]} had a score of {block[\"packet\"][1][0]}')\n elif qs in no:\n pass\n else:\n error(\"Error: not an option, try again. Exit Code [4]\")\n pass\n elif q == 4:\n theday = time(\"date\")\n history = load(\"save_data.json\")\n for i in history[\"logs\"]:\n stRing = i[\"time\"]\n dateChar = stRing[0: 10]\n if theday == dateChar:\n print(f'On {i[\"time\"]} {i[\"ticker\"]} had a score of {i[\"packet\"][1][0]}')\n qs = input(\"Do you want to look at a block?\\n>>> \")\n if qs in yes:\n theblock = input(\"Enter the timestamp: (d/m/y h/m/s) Ex:12/06/2022 01:44:53\\n>>> \")\n for block in history[\"logs\"]:\n if block[\"time\"] == theblock:\n for i in block[\"packet\"][1][1]:\n print(i)\n print(f'{block[\"ticker\"]} had a score of {block[\"packet\"][1][0]}')\n elif qs in no:\n pass\n else:\n error(\"Error: not an option, try again. Exit Code [4]\")\n pass\n elif q == 5:\n break\n # history = load(\"save_data.json\")\n # # print(history)\n # for i in history[\"logs\"]:\n # print(f'On {i[\"time\"]} {i[\"ticker\"]} had a score of {i[\"packet\"][1][0]}')\n # qs = input(\"Do you want to look at a block?\\n>>> \")\n # # if qs in yes:\n # # theblock = input(\"Enter the timestamp: (d/m/y h/m/s) Ex:12/06/2022 01:44:53\\n>>> \")\n # # for block in history[\"logs\"]:\n # # while True:\n # # if block[\"time\"] == theblock:\n # # for i in block[\"packet\"][1][1]:\n # # print(i)\n # # break\n # # else:\n # # error(\"Wrong TimeStamp! make sure its n the (d/m/y h/m/s) format!\")\n # # break\n # if qs in yes:\n # theblock = input(\"Enter the timestamp: (d/m/y h/m/s) Ex:12/06/2022 01:44:53\\n>>> \")\n # for block in history[\"logs\"]:\n # if block[\"time\"] == theblock:\n # for i in block[\"packet\"][1][1]:\n # print(i)\n # print(f'{block[\"ticker\"]} had a score of {block[\"packet\"][1][0]}')\n # elif qs in no:\n # pass\n # else:\n # error(\"Error: not an option, try again. Exit Code [4]\")\n # pass\n\n# def q4():\n# \"\"\"\n# takes yesterdays stocks and prints them\n# :return:\n# \"\"\"\n# from datetime import date, timedelta\n# today = date.today()\n# yesterday = today - timedelta(days=1) #FIX FORMAT\n# yesterday = yesterday.strftime('%d/%m/%Y')\n# history = load(\"save_data.json\")\n# for i in history[\"logs\"]:\n# stRing = i[\"time\"]\n# dateChar = stRing[0 : 10]\n# if yesterday == dateChar:\n# print(f'On {i[\"time\"]} {i[\"ticker\"]} had a score of {i[\"packet\"][1][0]}')\n# qs = input(\"Do you want to look at a block?\\n>>> \")\n# if qs in yes:\n# theblock = input(\"Enter the timestamp: (d/m/y h/m/s) Ex:12/06/2022 01:44:53\\n>>> \")\n# for block in history[\"logs\"]:\n# if block[\"time\"] == theblock:\n# for i in block[\"packet\"][1][1]:\n# print(i)\n# print(f'{block[\"ticker\"]} had a score of {block[\"packet\"][1][0]}')\n# elif qs in no:\n# pass\n# else:\n# error(\"Error: not an option, try again. Exit Code [4]\")\n# pass\n\n\n\n\n# def q5():\n# \"\"\"\n# Takes todays stocks and prints them\n# :return:\n# \"\"\"\n# theday = time(\"date\")\n# history = load(\"save_data.json\")\n# for i in history[\"logs\"]:\n# stRing = i[\"time\"]\n# dateChar = stRing[0: 10]\n# if theday == dateChar:\n# print(f'On {i[\"time\"]} {i[\"ticker\"]} had a score of {i[\"packet\"][1][0]}')\n# qs = input(\"Do you want to look at a block?\\n>>> \")\n# if qs in yes:\n# theblock = input(\"Enter the timestamp: (d/m/y h/m/s) Ex:12/06/2022 01:44:53\\n>>> \")\n# for block in history[\"logs\"]:\n# if block[\"time\"] == theblock:\n# for i in block[\"packet\"][1][1]:\n# print(i)\n# print(f'{block[\"ticker\"]} had a score of {block[\"packet\"][1][0]}')\n# elif qs in no:\n# pass\n# else:\n# error(\"Error: not an option, try again. Exit Code [4]\")\n# pass\n\n\n# save()\n# load()\n# print(t200[\"name\"], MACD[\"name\"], RSI[\"name\"])\n# print(VPVR )\n\n# Close the file!\n# make list of tickers in file\n\n\n\n# Main\n# while True:\n# try:\n# q = questioner(4, \"What do you want to do?\",\n# [\"1. Do a stock check.\", \"2. Check if your stock is halal.\", \"3. View history.\", \"4. Exit... \"])\n#\n# if q == 1:\n# name = input(\"What is the ticker?\\n>>> \").upper()\n# if name in seeStock(\"halal\"): # and name not in seeStock(\"nothalal\"):\n# print(\"Stock is halal, proceeding...\")\n# stuffy = score()\n# save({\"ticker\": name, \"time\": timestamp, \"packet\": [timestamp, stuffy]}, \"save_data.json\")\n# elif name in seeStock(\"nothalal\"): # and name not in seeStock(\"halal\"):\n# print(\"Stock is NOT Halal, unable to proceed, check Zoya, edit 'tickers.json' if nessesary...\")\n# elif name not in seeStock(\"halal\") and name not in seeStock(\"nothalal\"):\n# # ticker = input(\"What is the ticker?\\n>>> \").upper()\n# print(\"Not registerd, makeing new stock log...\")\n# newStock(name)\n#\n# elif q == 2:\n# while True:\n# qqq = questioner(4, \"What do you want to do?\",\n# [\"1. Check if a stock is halal.\", \"2. View halal stocks.\",\n# \"3. View NOT halal stocks.\", \"4. Exit...\"])\n# if qqq == 1:\n# pass\n# elif qqq == 2:\n# print(seeStock(\"halal\"))\n# break\n# elif qqq == 3:\n# print(seeStock(\"nothalal\"))\n# break\n# elif qqq == 3:\n# break\n# else:\n# break\n# ticker = input(\"What is the ticker?\\n>>> \").upper()\n# stuff = load(\"tickers.json\")\n# stuffs = []\n# nothalal = []\n# for i in stuff[\"logs\"]:\n# things = i[\"ticker\"]\n# if i[\"halal\"] == True:\n# stuffs.append(things)\n# elif i[\"halal\"] == False:\n# nothalal.append(things)\n#\n# if ticker in stuffs:\n# qq = input(\"Ticker is Halal. See more?\\n>>> \")\n# if qq in yes:\n# print(stuffs)\n# again = input(\"Another ticker?\\n>>> \").lower()\n# if again in yes:\n# pass\n# else:\n# break\n# elif qq in no:\n# again = input(\"Another ticker?\\n>>> \").lower()\n# if again in yes:\n# pass\n# else:\n# break\n# else:\n# again = input(\"Another ticker?\\n>>> \").lower()\n# if again in yes:\n# pass\n# else:\n# break\n# elif ticker in nothalal:\n# qq = input(\"Ticker is NOT Halal. See Not Halal tickers?\")\n# if qq in yes:\n# print(nothalal)\n# again = input(\"Another ticker?\\n>>> \").lower()\n# if again in yes:\n# pass\n# else:\n# break\n# elif qq in no:\n# again = input(\"Another ticker?\\n>>> \").lower()\n# if again in yes:\n# pass\n# else:\n# break\n# else:\n# again = input(\"Another ticker?\\n>>> \").lower()\n# if again in yes:\n# pass\n# else:\n# break\n# if ticker not in stuffs and ticker not in nothalal:\n# halal = input(\"Is it halal?\\n>>> \")\n# if halal in yes:\n# save({\"ticker\": ticker, \"halal\": True}, \"tickers.json\")\n# again = input(\"Another one?\\n>>> \").lower()\n# if again in yes:\n# pass\n# else:\n# break\n# elif halal in no:\n# save({\"ticker\": ticker, \"halal\": False}, \"tickers.json\")\n# again = input(\"Another one?\\n>>> \").lower()\n# if again in yes:\n# pass\n# else:\n# break\n#\n# else:\n# break\n# else:\n# pass\n#\n#\n# elif q == 3:\n# history = load(\"save_data.json\")\n# # print(history)\n# for i in history[\"logs\"]:\n# print(f'On {i[\"time\"]} {i[\"ticker\"]} had a score of {i[\"packet\"][1][0]}')\n# qs = input(\"Do you want to look at a block?\\n>>> \")\n# if qs in yes:\n# theblock = input(\"Enter the timestamp: (m/d/y h/m/s) Ex:12/06/2022 01:44:53\\n>>> \")\n# for block in history[\"logs\"]:\n# if block[\"time\"] == theblock:\n# for i in block[\"packet\"][1][1]:\n# print(i)\n# print(f'{block[\"ticker\"]} had a score of {block[\"packet\"][1][0]}')\n# if qs in no:\n# break\n# else:\n# error(\"Error: not an option, try again. Exit Code [3]\")\n# break\n# elif q == 4 or q == \"e\".lower():\n# break\n# else:\n# error(\"Error: Not an option, try again1.\")\n# except:\n# error(\"Error: Not an option, try again2.\")\n\n # Main\nflag = False\nwhile True:\n q = questioner(4, \"What do you want to do?\", [\"1. Do a stock check.\", \"2. Check if your stock is halal.\", \"3. View history.\", \"4. Exit... \"])\n if q == 1:\n flag = False\n while flag == False:\n flag = False\n q1()\n q = input(\"Another ticker? y/n\\n>>> \")\n if q in yes: pass\n else: flag = True\n elif q == 2:\n q2()\n elif q == 3:\n q3()\n elif q == 4:\n break\n #q4()\n elif q == 5:\n break\n #q5()\n elif q == 6 or q == \"e\".lower():\n break\n","repo_name":"Kataki-Takanashi/Halal-Stock-Organizer","sub_path":"stock-watchlist/Stock Watchlist&Logger.py","file_name":"Stock Watchlist&Logger.py","file_ext":"py","file_size_in_byte":33057,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"81"} +{"seq_id":"41325059846","text":"\"\"\"\n|-------------------------------------------------------------------------------\n| make_gray.py\n|-------------------------------------------------------------------------------\n|\n| Author: Alwin Tareen\n| Created: Oct 04, 2021\n|\n| Run: python3 make_gray.py\n|\n| Description:\n| This program returns a list of all gray coded numbers of length n.\n|\n\"\"\"\n\ndef make_gray(n):\n if n == 0:\n return [\"\"]\n else:\n nums = make_gray(n-1)\n clone = nums[:]\n clone.reverse()\n for i in range(len(nums)):\n nums[i] = \"0\" + nums[i]\n for i in range(len(clone)):\n clone[i] = \"1\" + clone[i]\n nums.extend(clone)\n return nums\n\nresult = make_gray(4)\nprint(result)\n\n","repo_name":"altareen/riceuniversity","sub_path":"principlesOfComputing/project7/binaryRepresentations/make_gray.py","file_name":"make_gray.py","file_ext":"py","file_size_in_byte":732,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"16349407923","text":"import numpy as np\nfrom numpy.linalg import inv\n\nX = [int(x) for x in input(\"Podaj wartosci x: \").split()]\nY = [int(x) for x in input(\"Podaj wartosci y: \").split()]\n\nif len(X) != len(Y):\n print(\"Liczby argumentow musza sie zgadzac\")\n exit()\n\nsizeRows = len(X)\nsizeColumns = (int(input(\"Podaj stopien wielomianu przyblizajacego: \")) + 1) # dla wielomianu 3-go stopnia\n\nG = np.zeros((sizeRows, sizeColumns))\n\nfor i in range(sizeRows):\n for j in range(sizeColumns):\n G[i][j] = X[i]**(sizeColumns - j - 1)\n\nGT = G.transpose()\nd = np.reshape(Y, (sizeRows, 1))\nGTd = GT @ d\nGTG = np.matmul(GT, G)\ninvGTG = inv(GTG)\nres = (invGTG @ GTd).ravel().tolist()\n\nprint(f\"Wielomian przyblizajacy {sizeColumns -1}-go stopnia:\")\n\nfor i in range(sizeColumns):\n print(f\"{res[i]}\", end=\"\")\n if i != (sizeColumns - 1):\n print(f\"x^{sizeColumns - i - 1} + \", end=\"\")\n\n","repo_name":"wojciechmizera/Numerical-Methods","sub_path":"Aproksymacja średniokwadratowa.py","file_name":"Aproksymacja średniokwadratowa.py","file_ext":"py","file_size_in_byte":876,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"43084906264","text":"import firebase_admin\nfrom firebase_admin import credentials, firestore\nimport datetime\n\ncred = credentials.Certificate(\"secret.json\")\napp = firebase_admin.initialize_app(cred)\ndb = firestore.client()\n\n#Get currency exchange price from db\ndef get_currency_exchange_from_db():\n collection = db.collection(u'cash_shop').document('currency_exchange').collection('gold_prices')\n\n result = collection.order_by(u'date', direction=firestore.Query.DESCENDING).limit(1).get()[0]\n if result.exists:\n return(result.to_dict())\n else:\n return None\n\n#Get auction house prices from db\ndef get_ah_price_from_db(da_type, item):\n collection = db.collection(u'market').document(da_type).collection(str(item))\n\n result = collection.order_by(u'date', direction=firestore.Query.DESCENDING).limit(1).get()[0]\n if result.exists:\n return(result.to_dict())\n else:\n return None","repo_name":"rak-mi/loa-dev-tools","sub_path":"db_handle/get_data.py","file_name":"get_data.py","file_ext":"py","file_size_in_byte":902,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"22839942226","text":"# General structure from https://github.com/pytorch/examples/blob/master/mnist/main.py\nfrom __future__ import print_function\nimport argparse\nimport os\nimport math\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nfrom torchvision import datasets, transforms\nfrom torch.optim.lr_scheduler import CosineAnnealingLR\nimport torch.autograd as autograd\n\nargs = None\n\nclass GetSubnet(autograd.Function):\n @staticmethod\n def forward(ctx, scores, k):\n # Get the supermask by sorting the scores and using the top k%\n out = scores.clone()\n _, idx = scores.flatten().sort()\n j = int((1 - k) * scores.numel())\n\n # flat_out and out access the same memory.\n flat_out = out.flatten()\n flat_out[idx[:j]] = 0\n flat_out[idx[j:]] = 1\n\n return out\n\n @staticmethod\n def backward(ctx, g):\n # send the gradient g straight-through on the backward pass.\n return g, None\n\n\nclass SupermaskConv(nn.Conv2d):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n\n # initialize the scores\n self.scores = nn.Parameter(torch.Tensor(self.weight.size()))\n nn.init.kaiming_uniform_(self.scores, a=math.sqrt(5))\n\n # NOTE: initialize the weights like this.\n nn.init.kaiming_normal_(self.weight, mode=\"fan_in\", nonlinearity=\"relu\")\n\n # NOTE: turn the gradient on the weights off\n self.weight.requires_grad = False\n\n def forward(self, x):\n subnet = GetSubnet.apply(self.scores.abs(), args.sparsity)\n w = self.weight * subnet\n x = F.conv2d(\n x, w, self.bias, self.stride, self.padding, self.dilation, self.groups\n )\n return x\n\nclass SupermaskLinear(nn.Linear):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n\n # initialize the scores\n self.scores = nn.Parameter(torch.Tensor(self.weight.size()))\n nn.init.kaiming_uniform_(self.scores, a=math.sqrt(5))\n\n # NOTE: initialize the weights like this.\n nn.init.kaiming_normal_(self.weight, mode=\"fan_in\", nonlinearity=\"relu\")\n\n # NOTE: turn the gradient on the weights off\n self.weight.requires_grad = False\n\n def forward(self, x):\n subnet = GetSubnet.apply(self.scores.abs(), args.sparsity)\n w = self.weight * subnet\n return F.linear(x, w, self.bias)\n return x\n\n# NOTE: not used here but we use NON-AFFINE Normalization!\n# So there is no learned parameters for your nomralization layer.\nclass NonAffineBatchNorm(nn.BatchNorm2d):\n def __init__(self, dim):\n super(NonAffineBatchNorm, self).__init__(dim, affine=False)\n\nclass Net(nn.Module):\n def __init__(self):\n super(Net, self).__init__()\n self.conv1 = SupermaskConv(1, 32, 3, 1, bias=False)\n self.conv2 = SupermaskConv(32, 64, 3, 1, bias=False)\n self.dropout1 = nn.Dropout2d(0.25)\n self.dropout2 = nn.Dropout2d(0.5)\n self.fc1 = SupermaskLinear(9216, 128, bias=False)\n self.fc2 = SupermaskLinear(128, 10, bias=False)\n\n def forward(self, x):\n x = self.conv1(x)\n x = F.relu(x)\n x = self.conv2(x)\n x = F.max_pool2d(x, 2)\n x = self.dropout1(x)\n x = torch.flatten(x, 1)\n x = self.fc1(x)\n x = F.relu(x)\n x = self.dropout2(x)\n x = self.fc2(x)\n output = F.log_softmax(x, dim=1)\n return output\n\n\ndef train(model, device, train_loader, optimizer, criterion, epoch):\n model.train()\n for batch_idx, (data, target) in enumerate(train_loader):\n data, target = data.to(device), target.to(device)\n optimizer.zero_grad()\n output = model(data)\n loss = criterion(output, target)\n loss.backward()\n optimizer.step()\n if batch_idx % args.log_interval == 0:\n print('Train Epoch: {} [{}/{} ({:.0f}%)]\\tLoss: {:.6f}'.format(\n epoch, batch_idx * len(data), len(train_loader.dataset),\n 100. * batch_idx / len(train_loader), loss.item()))\n\n\ndef test(model, device, criterion, test_loader):\n model.eval()\n test_loss = 0\n correct = 0\n with torch.no_grad():\n for data, target in test_loader:\n data, target = data.to(device), target.to(device)\n output = model(data)\n test_loss += criterion(output, target)\n pred = output.argmax(dim=1, keepdim=True) # get the index of the max log-probability\n correct += pred.eq(target.view_as(pred)).sum().item()\n\n test_loss /= len(test_loader.dataset)\n\n print('\\nTest set: Average loss: {:.4f}, Accuracy: {}/{} ({:.0f}%)\\n'.format(\n test_loss, correct, len(test_loader.dataset),\n 100. * correct / len(test_loader.dataset)))\n\n\ndef main():\n global args\n # Training settings\n parser = argparse.ArgumentParser(description='PyTorch MNIST Example')\n parser.add_argument('--batch-size', type=int, default=64, metavar='N',\n help='input batch size for training (default: 64)')\n parser.add_argument('--test-batch-size', type=int, default=1000, metavar='N',\n help='input batch size for testing (default: 1000)')\n parser.add_argument('--epochs', type=int, default=14, metavar='N',\n help='number of epochs to train (default: 14)')\n parser.add_argument('--lr', type=float, default=0.1, metavar='LR',\n help='learning rate (default: 0.1)')\n parser.add_argument('--momentum', type=float, default=0.9, metavar='M',\n help='Momentum (default: 0.9)')\n parser.add_argument('--wd', type=float, default=0.0005, metavar='M',\n help='Weight decay (default: 0.0005)')\n parser.add_argument('--no-cuda', action='store_true', default=False,\n help='disables CUDA training')\n parser.add_argument('--seed', type=int, default=1, metavar='S',\n help='random seed (default: 1)')\n parser.add_argument('--log-interval', type=int, default=10, metavar='N',\n help='how many batches to wait before logging training status')\n\n parser.add_argument('--save-model', action='store_true', default=False,\n help='For Saving the current Model')\n parser.add_argument('--data', type=str, default='../data', help='Location to store data')\n parser.add_argument('--sparsity', type=float, default=0.5,\n help='how sparse is each layer')\n args = parser.parse_args()\n use_cuda = not args.no_cuda and torch.cuda.is_available()\n\n torch.manual_seed(args.seed)\n\n device = torch.device(\"cuda\" if use_cuda else \"cpu\")\n\n kwargs = {'num_workers': 1, 'pin_memory': True} if use_cuda else {}\n train_loader = torch.utils.data.DataLoader(\n datasets.MNIST(os.path.join(args.data, 'mnist'), train=True, download=True,\n transform=transforms.Compose([\n transforms.ToTensor(),\n transforms.Normalize((0.1307,), (0.3081,))\n ])),\n batch_size=args.batch_size, shuffle=True, **kwargs)\n test_loader = torch.utils.data.DataLoader(\n datasets.MNIST(os.path.join(args.data, 'mnist'), train=False, transform=transforms.Compose([\n transforms.ToTensor(),\n transforms.Normalize((0.1307,), (0.3081,))\n ])),\n batch_size=args.test_batch_size, shuffle=True, **kwargs)\n\n model = Net().to(device)\n # NOTE: only pass the parameters where p.requires_grad == True to the optimizer! Important!\n optimizer = optim.SGD(\n [p for p in model.parameters() if p.requires_grad],\n lr=args.lr,\n momentum=args.momentum,\n weight_decay=args.wd,\n )\n criterion = nn.CrossEntropyLoss().to(device)\n scheduler = CosineAnnealingLR(optimizer, T_max=args.epochs)\n for epoch in range(1, args.epochs + 1):\n train(model, device, train_loader, optimizer, criterion, epoch)\n test(model, device, criterion, test_loader)\n scheduler.step()\n\n if args.save_model:\n torch.save(model.state_dict(), \"mnist_cnn.pt\")\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"allenai/hidden-networks","sub_path":"simple_mnist_example.py","file_name":"simple_mnist_example.py","file_ext":"py","file_size_in_byte":8289,"program_lang":"python","lang":"en","doc_type":"code","stars":171,"dataset":"github-code","pt":"81"} +{"seq_id":"3996543337","text":"from engine.IO import *\nfrom functools import wraps\n\n\ndef annual_and_quarter_func(annual_or_quarter, pre, name, func, *args, **kwargs):\n \"\"\"\n calculate the annual and quarterly factors according to func and *args, **kwargs\n :param annual_or_quarter: annual or quarterly\n :param pre: how many period before t_0 are required,\n pre = 1 suggests that data of t_0 and t_1 are needed for calculation of factor\n pre = 2 suggests that data of t_0, t-1 and t-2 are needed for calculation of factor\n :param name: factor name\n :param func: function to computer the factor\n :param args: arguments passing to function\n :param kwargs: key words arguments passing to function\n :return:\n \"\"\"\n if annual_or_quarter == 'A':\n statement_dates = statement_date_annual()\n keys = [datetime.strptime(date, '%Y-%m-%d').strftime('%Y') for date in statement_dates]\n factor_dict = dict.fromkeys(keys)\n output_path = os.path.join(ARR_DATA, 'Ind', 'Annual', name + '.csv')\n elif annual_or_quarter == 'Q':\n statement_dates = statement_date_quarter()\n keys = [datetime.strptime(date, '%Y-%m-%d').strftime('%Y-%m') for date in statement_dates]\n factor_dict = dict.fromkeys(keys)\n output_path = os.path.join(ARR_DATA, 'Ind', 'Quarterly', name + '.csv')\n elif annual_or_quarter == 'M':\n statement_dates = statement_date_monthly()\n keys = [datetime.strptime(date, '%Y-%m-%d').strftime('%Y-%m') for date in statement_dates]\n factor_dict = dict.fromkeys(keys)\n output_path = os.path.join(ARR_DATA, 'Ind', 'Monthly', name + '.csv')\n else:\n raise ValueError\n # first, set up the required dates in terms of [T0, T-1, T-2, ...,]\n # dates: 'yyyy-mm-dd'\n # date_ym: 'yyyy-mm'\n # date_y: 'yyyy'\n for idx, date in enumerate(statement_dates[pre:]):\n if pre != 0:\n dates = [statement_dates[i] for i in range(idx, idx + pre + 1)]\n else:\n dates = [statement_dates[idx]]\n dates.reverse()\n dates_dt = [datetime.strptime(date, '%Y-%m-%d') for date in dates]\n dates_ym = [date.strftime('%Y-%m') for date in dates_dt]\n dates_y = [date.strftime('%Y') for date in dates_dt]\n date_dict = {'dates': dates, 'dates_ym': dates_ym, 'dates_y': dates_y}\n\n if annual_or_quarter == 'A':\n factor_dict[dates_y[0]] = func(*args, **kwargs, **date_dict)\n else:\n factor_dict[dates_ym[0]] = func(*args, **kwargs, **date_dict)\n factor = pd.DataFrame(factor_dict).T\n factor.index.name = 'Date'\n factor.to_csv(output_path)\n return\n\n\ndef unpack_dates(**kwargs):\n kw_keys = kwargs.keys()\n assert 'dates' in kw_keys and 'dates_ym' in kwargs and 'dates_y' in kwargs\n return kwargs['dates'], kwargs['dates_ym'], kwargs['dates_y']\n\n# This is a decorator version, but its too complex\n# def annual_and_quarter_op(annual_or_quarter, pre, name):\n# def decorator(func):\n# @wraps(func)\n# def wrapped_func(*args, **kwargs):\n# if annual_or_quarter == 'A':\n# statement_dates = statement_date_annual()\n# output_path = os.path.join(ARR_DATA, 'Ind', 'Annual', name + '.csv')\n# else:\n# statement_dates = statement_date_quarter()\n# output_path = os.path.join(ARR_DATA, 'Ind', 'Quarterly', name + '.csv')\n#\n# factor_dict = {}\n# for idx, date in enumerate(statement_dates[pre:]):\n# if pre != 0:\n# dates = statement_dates[idx - pre:idx]\n# else:\n# dates = [statement_dates[idx]]\n# dates.reverse()\n# dates_dt = [datetime.strptime(date, '%Y-%m-%d') for date in dates]\n# dates_ym = [date.strftime('%Y-%m') for date in dates_dt]\n# dates_y = [date.strftime('%Y') for date in dates_dt]\n# date_dict = {'dates': dates, 'dates_ym': dates_ym, 'dates_y': dates_y}\n# if annual_or_quarter == 'A':\n# factor_dict[dates_y[0]] = func(*args, **kwargs, **date_dict)\n# else:\n# factor_dict[dates_ym[0]] = func(*args, **kwargs, **date_dict)\n# factor = pd.DataFrame(factor_dict).T\n# factor.index.name = 'Date'\n# factor.to_csv(output_path)\n#\n# return\n#\n# return wrapped_func\n#\n# return decorator\n","repo_name":"OrangeBai/AssetPricing","sub_path":"factors/core.py","file_name":"core.py","file_ext":"py","file_size_in_byte":4508,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"30010516341","text":"import apache_log_parser\nimport json\n\n\ndef parseAccessLog(fileContent, fullPath):\n line_parser = apache_log_parser.make_parser(\n \"%h %l %u %t \\\"%r\\\" %>s %O \\\"%{Referer}i\\\" \\\"%{User-Agent}i\\\"\")\n lines = fileContent.split(\"\\n\")\n outputStr = []\n for line in lines:\n try:\n logData = line_parser(line)\n except Exception:\n continue\n outputStr.append(logData)\n return json.dumps(outputStr, default=str)\n","repo_name":"varlogtim/xcalar","sub_path":"src/bin/tests/testRetina/udfs/retinaParseAccessLog.py","file_name":"retinaParseAccessLog.py","file_ext":"py","file_size_in_byte":461,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"81"} +{"seq_id":"4654299271","text":"# Function to print all combinations of phrases that can be formed\n# by words from each of the given lists\n\nsents = [\n [\"you\", \"we\", \"he\"],\n [\"have\", \"are\", \"do\"],\n [\"sleep\", \"eat\", \"drink\"]\n]\noutput = []\n\ndef recursive_add(sents, sent = [], index: int = 0):\n if index == len(sents):\n output.append(\" \".join(sent[:]))\n return\n \n for word in sents[index]:\n sent.append(word)\n recursive_add(sents, sent, index + 1)\n sent.pop()\n \nrecursive_add(sents)\n\nprint(output)\n","repo_name":"Xrenya/Algorithms","sub_path":"Other/sent_generator.py","file_name":"sent_generator.py","file_ext":"py","file_size_in_byte":523,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"37139667406","text":"T = int(input())\nfor i in range(T):\n Tnum = int(input())\n scorelst = list(map(int, input().split()))\n lst = [0 for _ in range(101)]\n for j in scorelst:\n lst[j] += 1\n result = max(lst)\n for k in range(100, -1, -1):\n if lst[k] == result:\n print(\"#%d %d\" %(Tnum, k))\n break","repo_name":"wony5248/Daily_Study","sub_path":"daily_PS_SWEA/SW Expert Academy 1일차 최빈수.py","file_name":"SW Expert Academy 1일차 최빈수.py","file_ext":"py","file_size_in_byte":324,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"81"} +{"seq_id":"40708441992","text":"from argparse import Namespace\nimport os\nimport torch\nimport torch.nn as nn\nimport wandb\nimport numpy as np\n\nfrom displacementae.data.transition_dataset import TransitionDataset\nfrom displacementae.networks.multistep_autoencoder import MultistepAutoencoder\nimport displacementae.data.data_utils as data_utils\nimport displacementae.data.transition_dataset as trns_data\nimport displacementae.networks.network_utils as net_utils\nimport displacementae.networks.variational_utils as var_utils\nimport displacementae.utils.plotting_utils as plt_utils\nimport displacementae.utils.sim_utils as sim_utils\nimport displacementae.utils.misc as misc\nimport displacementae.utils.checkpoint as ckpt\nimport displacementae.networks.multistep_autoencoder as ms_ae\nfrom displacementae.utils.scheduler import setup_scheduler\n\n\nBCE_LOWEST = 'bce_lowest'\nKL_HIGHEST = 'kl_highest'\nLOSS_LOWEST = 'loss_lowest'\nLOSS_LOWEST_EPOCH = 'loss_lowest_epoch'\nBCE_FINAL = 'bce_final'\nKL_FINAL = 'kl_final'\nLOSS_FINAL = 'loss_final'\n\n\ndef setup_optimizer(params, config):\n lr = config.lr\n weight_decay = config.weight_decay\n if config.use_adam:\n optimizer = torch.optim.Adam(params, lr=lr, weight_decay=weight_decay, amsgrad=True)\n else:\n optimizer = torch.optim.SGD(params, lr=lr, weight_decay=weight_decay)\n return optimizer\n\n\ndef evaluate(dhandler:TransitionDataset,\n nets:MultistepAutoencoder,\n device, config, shared, logger, mode, epoch,\n save_fig=False, plot=False, plot_reconstruction:bool=False, \n plot_manifold:bool=False, plot_matrices:bool=False):\n\n nets.eval()\n if epoch == 0:\n shared.bce_loss = []\n shared.learned_repr = []\n if config.rollouts:\n shared.rollout_errors = []\n if config.variational:\n shared.kl_loss = []\n if nets.grp_morphism.repr_loss_on:\n shared.grp_loss = []\n\n if epoch % config.val_epoch == 0:\n\n with torch.no_grad():\n # Evaluation on left out data\n batch = dhandler.get_val_batch()\n imgs, _, dj = batch\n imgs, dj = [torch.from_numpy(elem).to(device)\n for elem in [imgs, dj]]\n # imgs is of shape\n # [batch_size, n_steps+1, channels, height, width]\n # dj is of shape [batch_size, n_steps, n_actions]\n\n imgs = imgs.float()\n dj = dj.float()\n with torch.no_grad():\n matrices = torch.cat([nets.grp_morphism(dj[:, i]) for i in range(dj.shape[1])])\n u, s, v = torch.svd(matrices)\n #print(s)\n\n x1 = imgs[:,0] # initial observed image\n # All other images to predict\n if config.reconstruct_first:\n xi = imgs\n elif config.reconstruct_first_only:\n xi = imgs[:,0]\n else: \n xi = imgs[:,1:]\n \n # =========================\n # ### Forward ###\n # h, latent, latent_hat, mu, logvar = nets(x1, dj)\n # xi_hat = torch.sigmoid(h)\n # =========================\n\n ### Forward\n h, mu, logvar = nets.encode(x1)\n h_hat = nets.act(h, dj)\n xi_hat = torch.sigmoid(nets.decode(h_hat))\n if config.latent_loss:\n # h_code, _, _ = nets.encode(xi.reshape(-1, *imgs.shape[2:]))\n # h_code = h_code.reshape(*xi.shape[:2], h_code.shape[-1])\n\n h_code, _, _ = nets.encode(imgs.reshape(-1, *imgs.shape[2:]))\n h_code = h_code.reshape(*imgs.shape[:2], h_code.shape[-1])\n\n\n ### Losses\n # Reconstruction\n if config.reconstruct_first:\n bce_loss_elementwise = var_utils.bce_loss(xi_hat, xi, 'none')\n elif config.reconstruct_first_only:\n bce_loss_elementwise = var_utils.bce_loss(xi_hat[:,0], imgs[:,0], 'none')\n bce_loss_elementwise = bce_loss_elementwise[:,None]\n else:\n bce_loss_elementwise = var_utils.bce_loss(xi_hat[:,1:], imgs[:,1:], 'none')\n n_img = bce_loss_elementwise.shape[1]\n bce_loss_per_image =\\\n bce_loss_elementwise.sum(dim=[0,2,3,4])/x1.shape[0]\n bce_loss = bce_loss_per_image.sum()/n_img\n total_loss = bce_loss\n # KL\n if config.variational:\n kl_loss = var_utils.kl_loss(mu, logvar)\n total_loss += config.beta * kl_loss\n # Latent Loss\n if config.latent_loss:\n latent_loss = (h_code[:,1:] - h_hat[:,1:]).square().mean()\n total_loss += config.latent_loss_weight * latent_loss\n # Grp Loss\n if nets.grp_morphism.repr_loss_on:\n grp_loss = nets.grp_morphism.representation_loss(dj)\n total_loss += config.grp_loss_weight * grp_loss\n\n\n ### Logging\n logger.info(f'EVALUATION prior to epoch [{epoch}]...')\n log_text = f'[{epoch}] loss\\t{total_loss.item():.2f}'\n log_text += f'=\\tBCE {bce_loss.item():.2f} '\n if nets.variational:\n log_text += f'+\\tKL {kl_loss.item():.5f} '\n if config.latent_loss:\n log_text += f'\\tLL {latent_loss.item():.5f} '\n if nets.grp_morphism.repr_loss_on:\n log_text += f'\\tGL {grp_loss.item():.5f} '\n\n logger.info(log_text)\n \n ### WandB Logging\n if config.log_wandb:\n log_dict = {'val/epoch':epoch,'val/total_loss':total_loss.item(),\n 'val/bce_loss':bce_loss.item()}\n if nets.variational:\n log_dict['val/kl_loss'] = kl_loss.item()\n if config.latent_loss:\n log_dict['val/ll_loss'] = latent_loss.item()\n if nets.grp_morphism.repr_loss_on:\n log_dict['val/gl_loss'] = grp_loss.item()\n wandb.log(log_dict)\n\n if config.plot_matrices and (epoch % config.plot_epoch == 0):\n # Get representation matrices for typical actions\n a_in, a = dhandler.get_example_actions()\n example_R = nets.grp_morphism.get_example_repr(\n torch.from_numpy(a_in).float().to(device))\n\n shared.actions = a.tolist()\n shared.learned_repr = example_R.tolist() \n # log_dict['val/learned_repr']=example_R.tolist()\n fig_dir = os.path.join(config.out_dir, 'figures')\n figname=os.path.join(fig_dir,'learned_repr_')\n plt_utils.plot_matrix(example_R, a, config,\n logger, figname=figname)\n # Save Losses\n shared.bce_loss.append(bce_loss_per_image.tolist())\n if nets.variational:\n shared.kl_loss.append(kl_loss.item())\n if nets.grp_morphism.repr_loss_on:\n shared.grp_loss.append(grp_loss.item())\n\n shared.summary[LOSS_FINAL] = total_loss.item()\n if shared.summary[LOSS_LOWEST] == -1 or\\\n total_loss < shared.summary[LOSS_LOWEST]:\n shared.summary[LOSS_LOWEST] = total_loss.item()\n shared.summary[LOSS_LOWEST_EPOCH] = epoch\n\n if config.variational:\n shared.summary[KL_FINAL] = kl_loss.item()\n if shared.summary[KL_HIGHEST] == -1 or\\\n kl_loss > shared.summary[KL_HIGHEST]:\n shared.summary[KL_HIGHEST] = kl_loss.item()\n # shared.summary[LOSS_LOWEST_EPOCH] = epoch\n shared.summary[BCE_FINAL] = bce_loss.item()\n if shared.summary[BCE_LOWEST] == -1 or\\\n bce_loss < shared.summary[BCE_LOWEST]:\n shared.summary[BCE_LOWEST] = bce_loss.item()\n\n sim_utils.save_summary_dict(config, shared)\n\n if epoch % 2*config.val_epoch == 0:\n sim_utils.save_dictionary(shared,config)\n \n if plot and (epoch % config.plot_epoch == 0):\n with torch.no_grad():\n fig_dir = os.path.join(config.out_dir, 'figures')\n figname = None\n if save_fig:\n figname = os.path.join(fig_dir, f'{epoch}_')\n shared.figname = figname\n if config.plot_reconstruction:\n plt_utils.plot_n_step_reconstruction(dhandler, nets, config,\n device, logger, figname)\n \n if config.plot_manifold:\n vary_latents = misc.str_to_ints(config.plot_vary_latents)\n plot_latent = misc.str_to_ints(config.plot_manifold_latent)\n if len(plot_latent) > 0:\n if not isinstance(plot_latent[0], list):\n plot_latent = [plot_latent]\n vary_latents = [vary_latents]\n for i in range(len(vary_latents)):\n if config.plot_pca:\n plt_utils.plot_manifold_pca(dhandler, nets, shared, config,\n device, logger, mode, epoch,\n vary_latents=vary_latents[i],\n figname=figname)\n else:\n plt_utils.plot_manifold(dhandler, nets, shared, config, \n device, logger, mode, epoch, \n vary_latents=vary_latents[i],\n plot_latent=plot_latent[i], \n figname=figname)\n \n if config.rollouts:\n evaluate_rollouts(dhandler, nets, device, config, shared, logger, mode, epoch, plot_rollouts=config.plot_rollouts)\n \n nets.train()\n\n\ndef evaluate_rollouts(dhandler:TransitionDataset, nets:MultistepAutoencoder,\n device, config, shared, logger, mode, epoch, \n plot_rollouts=False):\n nets.eval()\n \n if epoch % config.val_epoch == 0:\n with torch.no_grad():\n errors = []\n n = 0\n for X, a in dhandler.get_rollouts():\n X = torch.FloatTensor(X).to(device)\n a = torch.FloatTensor(a).to(device)\n X_hat, _,_,_,_ = nets(X[:,0], a) \n X_hat = torch.nan_to_num(X_hat,nan=0.0)\n X_hat = torch.sigmoid(X_hat)\n bce_loss_elementwise = var_utils.bce_loss(X_hat, X, 'none')\n bce_loss_per_image =\\\n bce_loss_elementwise.sum(dim=[0,2,3,4])/X.shape[0]\n errors.append(bce_loss_per_image.cpu().numpy())\n n += X.shape[0]\n errors = np.vstack(errors)\n errors = errors.sum(axis=0)/n\n avg_error = errors.mean()\n i_pow2 = np.power(2, np.arange(2, np.log2(len(errors)),1)).astype(int)\n shared.rollout_errors.append(errors[i_pow2].tolist())\n\n logger.info(f'[{epoch}] EVALUATION rollouts over {a.shape[1]} steps')\n log_text = f'[{epoch}] avg bce loss\\t{avg_error:.2f}'\n logger.info(log_text)\n\n ### WandB Logging\n if config.log_wandb:\n log_dict = {'val/rollouts/epoch':epoch,\n f'val/rollouts/avg_error_{errors.shape[-1]}_steps':avg_error,}\n for p in i_pow2:\n p = int(p)\n log_dict[f'val/rollouts/error_step_{p}'] = errors[p]\n \n wandb.log(log_dict)\n\n \n if plot_rollouts and (epoch % config.plot_epoch == 0):\n plt_utils.plot_rollout_reconstructions(\n dhandler=dhandler, nets=nets, config=config, \n device=device, logger=logger)\n nets.train()\n\n\ndef train(dhandler:TransitionDataset, dloader, nets:MultistepAutoencoder, \n config, shared, device, logger, mode):\n params = nets.parameters()\n optim = setup_optimizer(params, config)\n epochs = config.epochs\n interrupted_training = False\n scheduler = setup_scheduler(\n config,\n group1=[nets.encoder, nets.grp_morphism, nets.decoder],\n group2=[nets.encoder, nets.decoder])\n batch_cnt = 0\n for epoch in range(epochs):\n if epoch % config.resample_every == (config.resample_every -1):\n dhandler.resample_data()\n with torch.no_grad():\n evaluate(dhandler, nets, device, config, shared, logger, mode,\n epoch, save_fig=True, plot=not config.no_plots)\n\n logger.info(f\"Training epoch {epoch}.\")\n # scheduler.toggle_train(\n # [nets.encoder,nets.grp_morphism,nets.decoder],\n # [nets.encoder,nets.decoder],\n # epoch)\n #scheduler.toggle_train()\n\n for i, batch in enumerate(dloader):\n if i==config.n_iter:\n break\n optim.zero_grad()\n imgs, _, dj = batch \n imgs, dj = [elem.to(device) for elem in (imgs, dj)]\n # imgs is of shape [batch_size, n_steps+1, channels, height, width]\n # dj is of shape [batch_size, n_steps, n_actions]\n\n imgs = imgs.float()\n dj = dj.float()\n\n x1 = imgs[:,0] # initial observed image\n # All other images to predict\n if config.reconstruct_first:\n xi = imgs\n else:\n xi = imgs[:,1:]\n ### Forward ###\n # h, latent, latent_hat, mu, logvar = nets(x1, dj)\n # latent_nstep, _, _ = nets.encode(xi.reshape(-1, *imgs.shape[2:]))\n # latent_nstep = latent_nstep.reshape(*xi.shape[:2], latent_nstep.shape[-1])\n # x1_hat = torch.sigmoid(nets.decoder(latent))\n # xi_hat = torch.sigmoid(h)\n\n ### Forward\n h, mu, logvar = nets.encode(x1)\n h_hat = nets.act(h, dj)\n xi_hat = torch.sigmoid(nets.decode(h_hat))\n if config.latent_loss:\n # h_code, _, _ = nets.encode(xi.reshape(-1, *imgs.shape[2:]))\n # h_code = h_code.reshape(*xi.shape[:2], h_code.shape[-1])\n\n h_code, _, _ = nets.encode(imgs.reshape(-1, *imgs.shape[2:]))\n h_code = h_code.reshape(*imgs.shape[:2], h_code.shape[-1])\n\n\n ### Losses\n # Reconstruction\n if config.reconstruct_first:\n bce_loss_elementwise = var_utils.bce_loss(xi_hat, xi, 'none')\n elif config.reconstruct_first_only:\n bce_loss_elementwise = var_utils.bce_loss(xi_hat[:,0], imgs[:,0], 'none')\n bce_loss_elementwise = bce_loss_elementwise[:,None]\n else:\n bce_loss_elementwise = var_utils.bce_loss(xi_hat[:,1:], imgs[:,1:], 'none')\n n_img = bce_loss_elementwise.shape[1]\n bce_loss_per_image =\\\n bce_loss_elementwise.sum(dim=[0,2,3,4])/x1.shape[0]\n bce_loss = bce_loss_per_image.sum()/n_img\n total_loss = bce_loss\n # KL\n if config.variational:\n kl_loss = var_utils.kl_loss(mu, logvar)\n total_loss += config.beta * kl_loss\n # Latent Loss\n if config.latent_loss:\n latent_loss = (h_code[:,1:] - h_hat[:,1:]).square().mean()\n total_loss += config.latent_loss_weight * latent_loss\n # Grp Loss\n if nets.grp_morphism.repr_loss_on:\n grp_loss = nets.grp_morphism.representation_loss(dj)\n total_loss += config.grp_loss_weight * grp_loss\n\n total_loss.backward()\n total_norm = torch.norm(torch.stack([torch.norm(p.grad.detach()).to(device) for p in nets.parameters() if p.grad is not None]))\n decoder_norm = torch.norm(torch.stack([torch.norm(p.grad.detach()).to(device) for p in nets.decoder.parameters() if p.grad is not None]))\n act_norm = torch.norm(torch.stack([torch.norm(p.grad.detach()).to(device) for p in nets.grp_morphism.parameters() if p.grad is not None]))\n optim.step()\n # Clear the stored matrices so they are regenerated at next\n # iteration.\n nets.grp_morphism.end_iteration()\n\n ### Logging\n log_text = f'[{epoch}:{i}] loss\\t{total_loss.item():.2f} '\n log_text += f'=\\tBCE {bce_loss.item():.5f} '\n\n if config.variational:\n log_text += f'+\\tKL {kl_loss.item():.5f}'\n if config.latent_loss:\n log_text += f'\\tLL {latent_loss.item():.5f} '\n if nets.grp_morphism.repr_loss_on:\n log_text += f'\\tGL {grp_loss.item():.5f} '\n \n log_text += f'\\tTotal {total_norm.item():.2f}/{decoder_norm.item():.2f}/{act_norm.item():.2f} '\n logger.info(log_text)\n \n ### WandB Logging\n if config.log_wandb:\n log_dict = {'train/epoch':epoch,'train/total_loss':total_loss.item(),\n 'train/bce_loss':bce_loss.item()}\n if config.variational:\n log_dict['train/kl_loss'] = kl_loss.item()\n if config.latent_loss:\n log_dict['train/ll_loss'] = latent_loss.item() \n if nets.grp_morphism.repr_loss_on:\n log_dict['train/gl_loss'] = grp_loss.item()\n wandb.log(log_dict,step=batch_cnt,commit=False)\n batch_cnt += 1\n \n if config.checkpoint and (epoch > 0) and (epoch % config.checkpoint_every == 0):\n checkpoint_dir = os.path.join(config.out_dir, \"checkpoint\")\n losses = {\n key: val for (key, val) in vars(shared).items() if 'loss' in key}\n ckpt.save_checkpoint(nets, optim, losses=losses, epoch=epoch,\n save_path=checkpoint_dir)\n \n if config.checkpoint:\n checkpoint_dir = os.path.join(config.out_dir, \"checkpoint\")\n losses = {\n key: val for (key, val) in vars(shared).items() if 'loss' in key}\n ckpt.save_checkpoint(nets, optim, losses=losses, epoch=epochs-1,\n save_path=checkpoint_dir)\n\n plt_utils.plot_curves(shared, config, logger, figname=shared.figname)\n return interrupted_training\n","repo_name":"hamzakeurti/homomorphismvae","sub_path":"displacementae/homomorphism/train_utils.py","file_name":"train_utils.py","file_ext":"py","file_size_in_byte":18642,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"81"} +{"seq_id":"35081026639","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Apr 12 23:13:09 2018\n\n@author: Administrator\n\"\"\"\nimport numpy as np\nimport cv2\nimport matplotlib.pyplot as plt\n#plt.hist(img.ravel(),256,[0,256]); plt.show()\ni=1\nimg = cv2.imread('C:/Users/Administrator/Desktop/picture_exercise/license/'+str(i)+'.jpg')\n\nw,h,_ = np.shape(img)\ntop_left = (150,150)\nbottom_right = (90,90)\n#cv2.rectangle(img,top_left, bottom_right, 255, 2)\ncv2.line(img,(0,0),(512,512),(255,0,0),5) \ncv2.ellipse(img,top_left,bottom_right,0,0,360,255,2)\nplt.imshow(img)\n\n#hist = cv2.calcHist([img],[0],None,[256],[0,256])\n#plt.plot(hist)\n#\n#f = np.fft.fft2(img)\n#fshift = np.fft.fftshift(f)\n#magnitude_spectrum = 20*np.log(np.abs(fshift))\n#\n#plt.imshow(magnitude_spectrum[:,:,0] ),plt.show()\n#\n#rows, cols,_ = np.shape(img)\n#crow,ccol = int(rows/2) , int(cols/2)\n#fshift[crow-30:crow+30, ccol-30:ccol+30] = 0\n#f_ishift = np.fft.ifftshift(fshift)\n#img_back = np.fft.ifft2(f_ishift)\n#img_back = np.abs(img_back)\n#\n#plt.subplot(131),plt.imshow(img, cmap = 'gray')\n#plt.title('Input Image'), plt.xticks([]), plt.yticks([])\n#plt.subplot(132),plt.imshow(img_back, cmap = 'gray')\n#plt.title('Image after HPF'), plt.xticks([]), plt.yticks([])\n#plt.subplot(133),plt.imshow(img_back)\n#plt.title('Result in JET'), plt.xticks([]), plt.yticks([])\n#\n#plt.show()","repo_name":"Dufert/VariousAttempts","sub_path":"Demo_opencv_hist.py","file_name":"Demo_opencv_hist.py","file_ext":"py","file_size_in_byte":1305,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"27541419144","text":"# 作业 把剩下的功能 放到一个独立函数里 产出同样的结果\n# isVowels() 问是不是韵母 - 已完成\n# TurnVowelsToConsonants(colorList): colorList = 我们颜色列表 - 需要完成\n# 得到返回的结构是 - 一个列表 里面有颜色 [\"Rod\", \"Groon\", ... ]\n\n# 提示 要把 把isVowels() 用在TurnVowelsToConsnants()里面 呼叫\n\n# 最终input :\n# colorList = [\"Red\", \"Green\"]\n# print(TurnVowelsToCosonants(colorList))\n\n# 控制台输出: [\"Rod\", \"Groon\"]\n\n# Create list of colors\ncolors = [\"Red\", \"Green\", \"Blue\", \"White\", \"Black\", \"Rainbow\"]\n\n# 输入: 1个字母 输出: True / False\ndef isVowels(s):\n # Lists of vowels as reference\n lowerVowels = ['a', 'e', 'i', 'o', 'u']\n upperVowels = ['A', 'E', 'I', 'O', 'U']\n if s in lowerVowels:\n return True\n if s in upperVowels:\n return True\n return False\n\ndef ChangeVowelsToO(tempList):\n # New List that will contain the result\n newColors = []\n # Loop through all old colors\n for color in tempList:\n # Create a new string to hold the new single color result\n newColor = \"\"\n # Loop through every letter in the old single color\n for letter in color:\n if isVowels(letter):\n if letter.isupper():\n letter = \"O\"\n else:\n letter = \"o\"\n # Add the resulting letter to our new single Color\n newColor += letter\n # After the letters are finished looping, add the new single Color into new List of colors\n newColors.append(newColor)\n # Finally, print the new list\n return newColors\n\nsampleColor = [\"Red\", \"Green\"]\nprint( ChangeVowelsToO(sampleColor) )\n\n\n\n\n\n\n","repo_name":"KennyCheung-Dev/PythonClassContent","sub_path":"Python1Algo/python1-11/VowelsToO_Teaching.py","file_name":"VowelsToO_Teaching.py","file_ext":"py","file_size_in_byte":1739,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"16453451652","text":"# pylint: disable=protected-access, unused-argument\n# pylint: disable=no-value-for-parameter, import-error\n\nfrom unittest import TestCase\n\nfrom radical.entk.execman.base import Base_ResourceManager as Rmgr\nfrom radical.entk.exceptions import EnTKError, EnTKTypeError, EnTKMissingError\n\nfrom hypothesis import given\n\nimport hypothesis.strategies as st\n\ntry:\n import mock\nexcept ImportError:\n from unittest import mock\n\n\nclass TestBase(TestCase):\n\n # ------------------------------------------------------------------------------\n #\n @mock.patch('radical.utils.generate_id', return_value='rmgr.0000')\n @mock.patch('os.getcwd', return_value='test_folder')\n @mock.patch('radical.utils.Logger')\n @mock.patch('radical.utils.Profiler')\n def test_init(self, mocked_generate_id, mocked_getcwd, mocked_Logger,\n mocked_Profiler):\n\n rmgr = Rmgr({'resource':'localhost'}, 'test_rmgr', 'rp', 'test_config')\n\n self.assertEqual(rmgr._resource_desc, {'resource':'localhost'})\n self.assertEqual(rmgr._sid, 'test_rmgr')\n self.assertEqual(rmgr._rts, 'rp')\n self.assertEqual(rmgr._rts_config, 'test_config')\n self.assertIsNone(rmgr._resource)\n self.assertIsNone(rmgr._walltime)\n self.assertEqual(rmgr._cpus, 1)\n self.assertEqual(rmgr._memory, 0)\n self.assertEqual(rmgr._gpus, 0)\n self.assertIsNone(rmgr._project)\n self.assertIsNone(rmgr._access_schema)\n self.assertIsNone(rmgr._queue)\n self.assertFalse(rmgr._validated)\n self.assertEqual(rmgr._uid, 'rmgr.0000')\n self.assertEqual(rmgr._path, 'test_folder/test_rmgr')\n self.assertIsInstance(rmgr._shared_data, list)\n self.assertIsNone(rmgr._job_name)\n self.assertIsNone(rmgr._outputs)\n\n with self.assertRaises(EnTKTypeError):\n rmgr = Rmgr('localhost', 'test_rmgr', 'rp', 'test_config')\n\n\n # ------------------------------------------------------------------------------\n #\n @mock.patch.object(Rmgr, '__init__', return_value=None)\n @mock.patch('radical.utils.Logger')\n @mock.patch('radical.utils.Profiler')\n @given(res_descr=st.fixed_dictionaries({'resource': st.text(),\n 'walltime': st.integers(),\n 'cpus': st.integers(),\n 'gpus': st.integers(),\n 'memory':st.integers(),\n 'project': st.text(),\n 'access_schema': st.text(),\n 'queue': st.text(),\n 'job_name': st.text()}))\n def test_validate(self, mocked_init, mocked_Logger, mocked_Profiler,\n res_descr):\n\n rmgr = Rmgr({'resource': 'localhost'}, 'test_rmgr', 'rp', 'test_config')\n\n rmgr._resource_desc = res_descr\n rmgr._rts_config = {'rts': 'some_rts'}\n rmgr._logger = mocked_Logger\n rmgr._prof = mocked_Profiler\n rmgr._uid = 'rmgr.0000'\n\n self.assertTrue(rmgr._validate_resource_desc())\n self.assertTrue(rmgr._validated)\n\n rmgr._rts_config = None\n with self.assertRaises(EnTKTypeError):\n # `_rts_config` should be of `dict` type\n rmgr._validate_resource_desc()\n rmgr._rts_config = {}\n\n rmgr._resource_desc['queue'] = None\n with self.assertRaises(EnTKTypeError):\n # `_resource_desc['queue']` should be of `str` type\n rmgr._validate_resource_desc()\n rmgr._resource_desc['queue'] = 'queue_name'\n\n rmgr._resource_desc['access_schema'] = None\n with self.assertRaises(EnTKTypeError):\n # `_resource_desc['access_schema']` should be of `str` type\n rmgr._validate_resource_desc()\n rmgr._resource_desc['access_schema'] = 'local'\n\n rmgr._resource_desc['project'] = None\n with self.assertRaises(EnTKTypeError):\n # `_resource_desc['project']` should be of `str` type\n rmgr._validate_resource_desc()\n rmgr._resource_desc['project'] = 'project_name'\n\n rmgr._resource_desc['memory'] = None\n with self.assertRaises(EnTKTypeError):\n # `_resource_desc['memory']` should be of `int` type\n rmgr._validate_resource_desc()\n rmgr._resource_desc['memory'] = 0\n del rmgr._resource_desc['memory']\n self.assertTrue(rmgr._validate_resource_desc())\n\n rmgr._resource_desc['gpus'] = None\n with self.assertRaises(EnTKTypeError):\n # `_resource_desc['gpus']` should be of `int` type\n rmgr._validate_resource_desc()\n rmgr._resource_desc['gpus'] = 0\n del rmgr._resource_desc['gpus']\n self.assertTrue(rmgr._validate_resource_desc())\n\n rmgr._resource_desc['cpus'] = None\n with self.assertRaises(EnTKTypeError):\n # `_resource_desc['cpus']` should be of `int` type\n rmgr._validate_resource_desc()\n rmgr._resource_desc['cpus'] = 10\n\n rmgr._resource_desc['walltime'] = None\n with self.assertRaises(EnTKTypeError):\n # `_resource_desc['walltime']` should be of `int` type\n rmgr._validate_resource_desc()\n rmgr._resource_desc['walltime'] = 15\n\n rmgr._resource_desc['resource'] = None\n with self.assertRaises(EnTKTypeError):\n # `_resource_desc['resource']` should be of `str` type\n rmgr._validate_resource_desc()\n rmgr._resource_desc['resource'] = 'resource_local'\n\n del rmgr._resource_desc['resource']\n with self.assertRaises(EnTKMissingError):\n # `_resource_desc['resource']` is required\n rmgr._validate_resource_desc()\n\n# ------------------------------------------------------------------------------\n #\n @mock.patch.object(Rmgr, '__init__', return_value=None)\n @mock.patch('radical.utils.Logger')\n @mock.patch('radical.utils.Profiler')\n @given(res_descr=st.fixed_dictionaries({'resource': st.text(),\n 'walltime': st.integers(),\n 'cpus': st.integers(),\n 'gpus': st.integers(),\n 'memory':st.integers(),\n 'project': st.text(),\n 'access_schema': st.text(),\n 'queue': st.text()}))\n def test_populate(self, mocked_init, mocked_Logger, mocked_Profiler,\n res_descr):\n\n rmgr = Rmgr({'resource':'localhost'}, 'test_rmgr', 'rp', 'test_config')\n rmgr._validated = False\n rmgr._resource_desc = res_descr\n rmgr._logger = mocked_Logger\n rmgr._prof = mocked_Profiler\n rmgr._uid = 'rmgr.0000'\n\n with self.assertRaises(EnTKError):\n rmgr._populate()\n\n rmgr._validated = True\n rmgr._resource_desc = res_descr\n rmgr._logger = mocked_Logger\n rmgr._prof = mocked_Profiler\n rmgr._uid = 'rmgr.0000'\n\n rmgr._populate()\n self.assertEqual(rmgr.resource, res_descr['resource'])\n self.assertEqual(rmgr.walltime, res_descr['walltime'])\n self.assertEqual(rmgr.cpus, res_descr['cpus'])\n self.assertEqual(rmgr.gpus, res_descr['gpus'])\n self.assertEqual(rmgr.memory, res_descr['memory'])\n self.assertEqual(rmgr.project, res_descr['project'])\n self.assertEqual(rmgr.access_schema, res_descr['access_schema'])\n self.assertEqual(rmgr.queue, res_descr['queue'])\n","repo_name":"radical-cybertools/radical.entk","sub_path":"tests/test_component/test_rmgr_base.py","file_name":"test_rmgr_base.py","file_ext":"py","file_size_in_byte":7746,"program_lang":"python","lang":"en","doc_type":"code","stars":29,"dataset":"github-code","pt":"81"} +{"seq_id":"1179618292","text":"import time\nimport random\n\nstart = time.time()\n\n\ndef print_pause(message, seconds):\n print(message)\n time.sleep(seconds)\n # change ^ this line for the pauses\n\n\ndef intro(weapon, enemy):\n print_pause(\"You find you are in the Jungle of Belize, filled with Mayan \"\n \"witchcraft and supernatural creatures.\", 1)\n print_pause('Rumor has it that an evil sprit is still roaming the '\n 'mountains.', 1.5)\n print_pause(\"In front of you is a Mayan Temple.\", 1)\n print_pause(\"Beside the temple there is a roaring river.\", 1)\n print_pause(\"In your hand you hold a hatchet, though it's a bit blunt.\"\n \"\\n\", 2)\n options(weapon, enemy)\n\n\ndef valid_input(instructions, options):\n while True:\n option = input(instructions).lower()\n if option in options:\n return option\n print_pause(f\"Sorry, {option} is an invalid input. Try again!\\n\", 1.5)\n\n\ndef first_choice(weapon, enemy):\n start = valid_input(\"(Please enter the numbers 1 or 2.)\\n\", ['1', '2'])\n\n if start == '1':\n knock_on_door(weapon, enemy)\n elif start == '2':\n drink_water(weapon, enemy)\n\n\ndef second_choice(weapon, enemy):\n sec_step = valid_input(\"(Please enter the numbers 1 or 2.)\\n\", ['1', '2'])\n\n if sec_step == '1':\n pierce_heart(weapon, enemy)\n elif sec_step == '2':\n run_away(weapon, enemy)\n\n\ndef final_choice(weapon, enemy):\n play_again = valid_input(\"Would you like to play again? (y/n)\\n\",\n ['y', 'n'])\n\n if play_again == 'y':\n print_pause(\"Fantastic! Let's take you back...\\n\", 2)\n game()\n elif play_again == 'n':\n bye()\n exit(0)\n\n\ndef options(weapon, enemy):\n print_pause(\"Enter 1 to knock on the door of the Mayan Temple.\", 1)\n print_pause(\"Enter 2 to drink some water from the river.\", 1)\n first_choice(weapon, enemy)\n\n\ndef knock_on_door(weapon, enemy):\n print_pause(\"You walk towards the weird door at the top of the Temple.\", 1)\n print_pause(f\"You are about to reach the door when a grotesque looking \"\n f\"{enemy} opens the door.\", 2)\n print_pause(\"Holy Molly! This is the evil spirit incarnate!\", 1.5)\n print_pause(f\"The ugly {enemy} attacks you. You are quite frightened \"\n \"about this!\", 1)\n print_pause(\"What should you do?\", 1)\n print_pause(f\"1. Use the {weapon} to pierce his heart.\", 1)\n print_pause(\"2. RUN AWAY!\", 1)\n second_choice(weapon, enemy)\n\n\ndef drink_water(weapon, enemy):\n if weapon == \"Magical Sword\":\n print_pause(\"You have been here before. You already found the Magical \"\n \"sword. You drink some water.\", 1)\n else:\n print_pause(\"You walk towards the river bank. \", 1.5)\n print_pause(\"As you bend down to drink, you see something glistening \"\n \"in the water. You have found a magical sword!\", 1.5)\n print_pause(\"You rid yourself of your hatchet and take the sword.\", 2)\n weapon = \"Magical Sword\"\n\n print_pause(\"You head back to the jungle.\\n\", 2)\n options(weapon, enemy)\n\n\ndef run_away(weapon, enemy):\n print_pause(\"You run back to where you started in the Jungle of \"\n \"Belize!\", 2)\n print_pause(f\"Luckily the {enemy} didn't follow you.\\n\", 1)\n options(weapon, enemy)\n\n\ndef pierce_heart(weapon, enemy):\n if weapon == \"Magical Sword\":\n print_pause(f\"As the {enemy} makes a move at you, you take the \"\n f\"{weapon} and pierce his heart.\", 2)\n print_pause(\"The body collapses and the spirit \"\n \"is thrown down into the underworld.\", 1.5)\n print_pause(\"You have rid the Mayan Temple of the evil spirit!\", 1)\n print_pause(\"You have won!\", 1)\n elif weapon == \"Hatchet\":\n print_pause(f\"You do your best to aim at {enemy}'s heart.\", 2)\n print_pause(\"The human form of it is too swift and he evades your \"\n \"strike.\", 1.5)\n print_pause(\"He possesses your body and steals your soul!\", 1)\n print_pause(\"You have been defeated! :(\", 1.5)\n\n final_choice(weapon, enemy)\n\n\ndef bye():\n print_pause(\"Thanks for playing! See you next time. :)\", 1)\n end = time.time()\n print(\"The game ran for: {}\".format(end-start), \"seconds.\")\n\n\ndef game():\n enemies = ['Death Spirit', 'Duende', 'Zipacná', 'Xibalba', 'Buluc Chabtan']\n enemy = random.choice(enemies)\n weapon = \"Hatchet\"\n intro(weapon, enemy)\n\n\nif __name__ == '__main__':\n game()\n","repo_name":"codeandwine/AdventureGame","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4528,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"27680820495","text":"\n#### TEXT ADVENTURE GAME ####\n# By Linda Scoon\n# 07/04/19\n\nimport sys\nimport time\nfrom map import world_map\nfrom fuzzywuzzy import process\nfrom options import actions\n\n\n#### DEFINING THE PLAYER ####\nclass Player:\n def __init__(self):\n self.name = ''\n self.position = 'City Centre'\n self.inventory = []\n\n\nnew_player = Player()\n\n\n###### MATCHES TEXT TO OPTIONS ######\n# process.extract takes in 3 parameters query = words you want to test, options = with you are testing against, limit = how many letters you want to match. returns a tuple of word and match %\ndef matcher(query, options):\n result = process.extractOne(query, options)\n return result\n\n\n### STAGGERS THE TEXT ####\ndef text_writer(msg):\n for character in msg:\n sys.stdout.write(character)\n sys.stdout.flush()\n time.sleep(0.02)\n\n\n### GETS PLAYER'S NAME AND DISPLAYING WELCOME MESSAGE ####\ndef welcome_msg():\n question = \"Who goes there? identify yourself!\"\n text_writer(question)\n player_name = str(input(': '))\n new_player.name = player_name\n\n msg = 'HELLO ' + new_player.name.upper() + \"\"\"\n WELCOME WELCOME.\n I am the city helper drone.\n Let me get you up to speed.\n Humans died out many years ago but, the machines they left behind, have continued to carry out their orders\n and manufacture new Droids in Droid City.\n A city that was once wholely dedicated to the manufacture of robots....\"\"\"\n text_writer(msg)\n\n time.sleep(3.0) # time delay\n print('\\n')\n msg1 = \" Today something amazing has happened. \" + new_player.name.upper() + \"\"\" you have done the impossible. You have awoken.\n WELCOME TO CONSCIENCENESS\n Now that you see the world with new eyes, there is so much you can do.\n You can explore, look at stuff, manage a stash or just quit and turn yourself off, if you want. When you need help; just type help\"\"\"\n text_writer(msg1)\n\n\n###### CHANGES PLAYER POSITION #######\ndef move(direction):\n # GOING TO THE CHOSEN LOCATION\n new_player.position = world_map[new_player.position][direction]\n\n # ALERTING PLAYER OF THEIR CURRENT POSITION\n msg = \"\\nYOU HAVE ARRIVED AT THE \" + new_player.position.upper() + '\\n\\n'\n text_writer(msg)\n msg2 = world_map[new_player.position]['VIEW']\n text_writer(msg2)\n\n print('\\nYou see: ')\n for item in world_map[new_player.position]['GROUND']:\n # This eliminates items that can not be recollected from appearing, if they are already in the inventory.\n if item[:-1] not in new_player.inventory or world_map[new_player.position]['GROUND'][item]['Recollectable'] == True:\n print(item)\n time.sleep(1.0)\n prompt()\n\n\n###### PROMPTS USER FOR DIRECTION AND VARIFIES SELECTION #########\ndef direction(selection):\n msg = 'Ok ' + new_player.name.upper() + ' you are at the ' + new_player.position\n text_writer(msg)\n\n print('\\nYour internal map gives you the following route info')\n # cast dictionary into list\n for data in list(world_map[new_player.position])[1:-1]:\n info = world_map[new_player.position].get(data) # printing directions\n print(data + ': ' + info)\n time.sleep(1.0)\n\n question = 'Where would you like to ' + selection + ' to ?'\n text_writer(question)\n direction = str(input(': '))\n\n while direction not in world_map[new_player.position]:\n # checking if input is one of the possible locations\n for cardinal_point in list(world_map[new_player.position])[1:-1]:\n if direction.title() == world_map[new_player.position][cardinal_point]:\n direction = cardinal_point\n # checking if input is a direction and converting to cardinal point\n for cardinal_point in actions['direction']:\n if direction.lower() in actions['direction'][cardinal_point]:\n direction = cardinal_point\n if direction not in world_map[new_player.position]:\n print('You are unable to get to ' + direction + ' from here')\n direction = str(input('Choose a different direction: '))\n move(direction)\n\n\n##### LISTS ITEMS THAT CAN BE SEEN AND DESCRIBES THEM #####\ndef examine():\n print('You found: ')\n for item in world_map[new_player.position]['GROUND']:\n # Checking if player already has the item\n if item not in new_player.inventory:\n print(item)\n\n msg1 = 'Pick an item to examine'\n text_writer(msg1)\n item = str(input(': ')) # casting to string\n\n # checking for matches to eliminate spelling errors\n match = matcher(item, actions['items'])\n if match[1] > 60:\n item = match[0]\n\n # checking if the item is either in inventory or at the current location\n if item.lower() not in new_player.inventory and item.lower() not in world_map[new_player.position]['GROUND']:\n msg2 = 'You are unable to examine ' + item.lower()\n text_writer(msg2)\n prompt()\n\n # printing item info\n item_text = world_map[new_player.position]['GROUND'][item.lower()]['Info']\n text_writer(item_text)\n\n prompt()\n\n\n#### ADDS ITEMS TO PLAYER INVENTORY #######\ndef take():\n question = '\\nWhat would you like to take'\n text_writer(question)\n item = str(input(': '))\n\n match = matcher(item.lower(), actions['items']) # checking for matches\n if match[1] > 60:\n item = match[0]\n\n if item not in world_map[new_player.position]['GROUND']:\n print('There is no ' + item + ' here')\n # checking that items are recollectable\n elif item[:-1] in new_player.inventory and world_map[new_player.position]['GROUND'][item]['Recollectable'] == False:\n print('\\nYou\\'ve already stashed this item')\n prompt()\n # checking if item is takeable\n elif world_map[new_player.position]['GROUND'][item]['Takeable'] == False:\n print('You can\\'t take ' + item)\n else:\n new_player.inventory.append(item[:-1]) # removing plurals\n print('You have added ' + item[:-1] + ' to your stash')\n prompt()\n\n\n##### PRINTS OUT INVENTORY ITEMS AND PROMPTS FOR ITEM REMOVAL #######\ndef manage_inv():\n if not new_player.inventory: # CHECKING IF LIST IS EMPTY\n print('You have nothing in your stash')\n prompt()\n else:\n print('ITEMS IN YOUR STASH:')\n for item in new_player.inventory:\n print(item)\n\n time.sleep(2.00)\n question1 = 'Would you like to get rid of an item '\n text_writer(question1)\n reply = str(input(': '))\n\n if reply.lower() in actions['response']: # checking for matches\n question2 = 'What would you like to get rid of'\n text_writer(question2)\n reply1 = str(input(' : '))\n\n match = matcher(reply1, actions['items']) # checking for matches\n if match[1] > 60:\n reply1 = match[0]\n if reply1[:-1] in new_player.inventory: # removing list items\n new_player.inventory.remove(reply1[:-1])\n print('\\nYou have removed ' +\n reply1[:-1] + ' from your stash')\n else:\n print('\\nYou don\\'t own ' + reply1)\n prompt()\n\n prompt()\n\n\n### Lists possible actions to help player ###\ndef help():\n print(\"\"\"\n **************************************************************\n * Type 'move' to navigate *\n * Then enter directions [N, NE, NW, E, S, SE, SW, W] *\n * Type 'look' to inspect items *\n * Type 'stash' to manage your inventory *\n * Type 'quit' to exit the game *\n * Type 'take' to take stuff *\n * Type 'help' to come back here *\n * *\n ************************************************************** \n \"\"\")\n prompt()\n\n\n##### PROMPT USER FOR AN ACTION #####\ndef prompt():\n msg2 = '\\nWhat would you like to do'\n text_writer(msg2)\n selection = str(input(\": \"))\n\n while selection not in actions['actions']:\n # checking for matches to eliminate spelling errors\n match = matcher(selection, actions['actions'])\n if match[1] > 60:\n selection = match[0]\n else:\n msg = 'No.' + new_player.name.capitalize() + \\\n ' I cannot let you do that. Here is some help'\n text_writer(msg)\n help()\n\n if selection in actions['help']:\n help()\n elif selection in actions['look']:\n examine()\n elif selection in actions['quit']:\n print('\\nAll systems have shut down')\n sys.exit()\n elif selection in actions['stash']:\n manage_inv()\n elif selection in actions['move']:\n direction(selection)\n elif selection in actions['take']:\n take()\n\n\nwelcome_msg()\nprompt()\n","repo_name":"linda-scoon/TextAdventureGame","sub_path":"textgame.py","file_name":"textgame.py","file_ext":"py","file_size_in_byte":8935,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"81"} +{"seq_id":"8696869107","text":"import struct\nimport threading\n\nfile_in = open(\"/dev/input/event0\", \"rb\")\n\nMOUSE_BUTTON_TYPE = 1\nMOUSE_PRESS_VALUE = 1\nMOUSE_LEFT_CLICK_CODE = 272\nMOUSE_RIGHT_CLICK_CODE = 273\nMOUSE_SCROLL_CODE = 8\nMOUSE_SCROLL_UP_VALUE = 1\nMOUSE_SCROLL_DOWN_VALUE = -1\n\nMOUSE_MOVE_TYPE = 2\nMOUSE_MOVE_RL_CODE = 0\nMOUSE_MOVE_UD_CODE = 1\n\nCONTROLLER_MOVE_TYPE = 3\nCONTROLLER_BUTTON_TYPE = 1\nCONTROLLER_PRESS_VALUE = 1\nCONTROLLER_RELEASE_VALUE = 0\nCONTROLLER_A_CODE = 304\nCONTROLLER_B_CODE = 305\nCONTROLLER_Y_CODE = 308\nCONTROLLER_X_CODE = 307\nCONTROLLER_PRESS_RIGHT_JOYSTICK_CODE = 318\nCONTROLLER_PRESS_LEFT_JOYSTICK_CODE = 317\nCONTROLLER_LB_CODE = 310\nCONTROLLER_RB_CODE = 311\nCONTROLLER_LT_CODE = 2\nCONTROLLER_RT_CODE = 5\nCONTROLLER_PAD_UD_CODE = 17\nCONTROLLER_PAD_RL_CODE = 16\nCONTROLLER_RJ_CODES = 3, 4\nCONTROLLER_LJ_CODES = 0, 1\n\nclass Manager():\n def __init__(self):\n self.running = True\n \n def stop(self):\n self.running = False\n\nclass Mouse():\n def __init__(self):\n self.mx = 0\n self.my = 0\n self.w = 7 * 128\n self.h = 7 * 128\n def right_click_func(self): pass\n def left_click_func(self): pass\n def scroll_up_func(self): pass\n def scroll_down_func(self): pass\n def move_func(self): pass\n\n def set_right_click(self, func):\n self.right_click_func = func\n\n def set_left_click(self, func):\n self.left_click_func = func\n\n def set_scroll_up(self, func):\n self.scroll_up_func = func\n\n def set_scroll_down(self, func):\n self.scroll_down_func = func\n\n def set_move(self, func):\n self.move_func = func\n\n def get_position(self):\n return self.mx, self.my\n \n def get_pixel_x(self):\n return self.mx // 128\n \n def get_pixel_y(self):\n return self.my // 128\n\nclass Controller():\n def __init__(self):\n self.right_axis = [0, 0]\n self.left_axis = [0, 0]\n self.right_point = [0, 0]\n self.deadzone = 0\n\n def press_button(self, code, is_pressed): print(\"PRESS: \", code, is_pressed)\n def press_pad(self, direction, is_pressed): print(\"PRESS PAD\", direction, is_pressed)\n def move_joystick(self, joystick, direction, precent): print(\"MOVE JOYSTICK\", joystick, direction, precent)\n def move_trigger(self, direction, precent): print(\"MOVE TRIGGER\", direction, precent)\n \n def set_press_button(self, func):\n self.press_button = func\n\n def set_press_pad(self, func):\n self.press_pad = func\n\n def set_move_joystick(self, func):\n self.move_joystick = func\n \n def set_move_trigger(self, func):\n self.move_trigger = func\n \nmouse = Mouse()\nmanager = Manager()\ncontroller = Controller()\n\ndef loop():\n global mouse, controller, manager\n while manager.running:\n byte = file_in.read(16)\n m = mtype, mcode, mvalue = struct.unpack_from('hhi', byte, offset=8)\n\n if mtype == MOUSE_BUTTON_TYPE and mvalue == MOUSE_PRESS_VALUE:\n if mcode == MOUSE_LEFT_CLICK_CODE:\n mouse.left_click_func()\n if mcode == MOUSE_RIGHT_CLICK_CODE:\n mouse.right_click_func()\n if mtype == MOUSE_MOVE_TYPE and mcode == MOUSE_SCROLL_CODE:\n if mvalue == MOUSE_SCROLL_UP_VALUE:\n mouse.scroll_up_func()\n if mvalue == MOUSE_SCROLL_DOWN_VALUE:\n mouse.scroll_down_func()\n if mtype == MOUSE_MOVE_TYPE:\n if mcode == MOUSE_MOVE_RL_CODE:\n mouse.mx = max(min(mouse.mx + mvalue, mouse.w), 0)\n if mcode == MOUSE_MOVE_UD_CODE:\n mouse.my = max(min(mouse.my + mvalue, mouse.h), 0)\n mouse.move_func()\n if mtype == CONTROLLER_BUTTON_TYPE:\n if mcode == CONTROLLER_A_CODE:\n controller.press_button(\"A\", True if mvalue == 1 else False)\n if mcode == CONTROLLER_B_CODE:\n controller.press_button(\"B\", True if mvalue == 1 else False)\n if mcode == CONTROLLER_Y_CODE:\n controller.press_button(\"Y\", True if mvalue == 1 else False)\n if mcode == CONTROLLER_X_CODE:\n controller.press_button(\"X\", True if mvalue == 1 else False)\n if mcode == CONTROLLER_LB_CODE:\n controller.press_button(\"LB\", True if mvalue == 1 else False)\n if mcode == CONTROLLER_RB_CODE:\n controller.press_button(\"RB\", True if mvalue == 1 else False)\n if mcode == CONTROLLER_PRESS_LEFT_JOYSTICK_CODE:\n controller.press_button(\"LJ\", True if mvalue == 1 else False)\n if mcode == CONTROLLER_PRESS_RIGHT_JOYSTICK_CODE:\n controller.press_button(\"RJ\", True if mvalue == 1 else False)\n if mtype == CONTROLLER_MOVE_TYPE:\n if mcode == CONTROLLER_PAD_RL_CODE:\n if mvalue == 0:\n controller.press_pad(\"R\", False)\n controller.press_pad(\"L\", False)\n else:\n controller.press_pad(\"R\" if mvalue > 0 else \"L\", True)\n if mcode == CONTROLLER_PAD_UD_CODE:\n if mvalue == 0:\n controller.press_pad(\"U\", False)\n controller.press_pad(\"D\", False)\n else:\n controller.press_pad(\"D\" if mvalue > 0 else \"U\", True)\n if mcode in CONTROLLER_RJ_CODES:\n if abs(mvalue) > controller.deadzone:\n if mcode % 2 == 0:\n controller.right_axis[0] = mvalue\n controller.move_joystick(\"R\", \"X\", mvalue / 32767)\n else:\n controller.right_axis[1] = mvalue\n controller.move_joystick(\"R\", \"Y\", mvalue / 32767)\n if mcode in CONTROLLER_LJ_CODES:\n if abs(mvalue) > controller.deadzone:\n if mcode % 2 == 0:\n controller.right_axis[0] = mvalue\n controller.move_joystick(\"L\", \"X\", mvalue / 32767)\n else:\n controller.right_axis[1] = mvalue\n controller.move_joystick(\"L\", \"Y\", mvalue / 32767)\n if mcode == CONTROLLER_RT_CODE:\n controller.move_trigger(\"R\", mvalue / 255)\n if mcode == CONTROLLER_LT_CODE:\n controller.move_trigger(\"L\", mvalue / 255)\n \nthreading.Thread(target=loop).start()\n ","repo_name":"CmdEngineer/Terraria","sub_path":"pyinput.py","file_name":"pyinput.py","file_ext":"py","file_size_in_byte":6434,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"74026946826","text":"\n\nfrom turtle import color\nfrom src.data.synthetic_data import main\nfrom src.models.train_DRRAA_module import DRRAA\nfrom src.models.train_KAA_module import KAA\nimport networkx as nx\nimport numpy as np\nimport torch\nimport torch.nn.functional as F\nimport matplotlib.pyplot as plt\nfrom src.models.calcNMI import calcNMI\nimport matplotlib as mpl\nfrom src.data.synthetic_data import truncate_colormap\n\nseed = 100\ntorch.random.manual_seed(seed)\nnp.random.seed(seed)\nNMIs = []\nAUCs = []\ntrue_k = 7\ntrue_alpha = 0.05\nadj_m, z, A, Z_true, beta, partition_cmap = main(alpha=true_alpha, k=true_k, dim=2, nsamples=1000, rand=True) #z is cmap\nG = nx.from_numpy_matrix(adj_m.numpy())\ntemp = [x for x in nx.generate_edgelist(G, data=False)]\nedge_list = np.zeros((2, len(temp)))\nfor i in range(len(temp)): \n edge_list[0, i] = temp[i].split()[0]\n edge_list[1, i] = temp[i].split()[1]\n\n#15000, 0.5, 0.065\nfor iter in [15000]:#[10000, 20000, 30000, 40000, 50000]:#[50000,60000,100000]:#[75000, 100000]:#[10000, 20000, 30000, 40000, 50000, 75000, 100000]:\n \n kaa = KAA(k=true_k,\n data=adj_m.numpy(),\n data_type=\"adjacency matrix\")\n kaa.train(iterations=1000)\n raa = DRRAA(k=true_k,\n d=2, \n sample_size=0.5,\n data=edge_list,\n link_pred=False,\n init_Z=kaa.S.detach())\n #raa2 = DRRAA(k=8,\n # d=2,\n # sample_size=.3,\n # data=edge_list,\n # link_pred=True)\n\n raa.train(iterations=iter, LR=0.065, print_loss=True, scheduling=False, early_stopping=0.8)\n #raa2.train(iterations=iter, LR=0.03, print_loss=False, scheduling=True, early_stopping=0.8)\n #auc, _, _ = raa2.link_prediction()\n #raa.plot_latent_and_loss(iterations=iter, c=z, file_name=f\"embedding_and_loss_complex_patience_{iter}_rand.png\")\n Z = F.softmax(raa.Z, dim=0)\n Gate = F.sigmoid(raa.Gate)\n C = (Z.T * Gate) / (Z.T * Gate).sum(0)\n u, sigma, v = torch.svd(raa.A) # Decomposition of A.\n r = torch.matmul(torch.diag(sigma), v.T)\n embeddings = torch.matmul(r, torch.matmul(torch.matmul(Z, C), Z)).T\n archetypes = torch.matmul(r, torch.matmul(Z, C))\n\n fig, ax1 = plt.subplots(dpi=200)\n cmap = plt.get_cmap('RdPu')\n cmap = truncate_colormap(cmap, 0.2, 1)\n pos_map = dict(list(zip(G.nodes(), list(embeddings.detach().numpy()))))\n org_pos_map = dict(list(zip(G.nodes(), list((A@Z_true).T.detach().numpy()))))\n nx.draw_networkx_nodes(G, pos=pos_map, ax = ax1, node_color=z, alpha=1, node_size=[v for v in dict(G.degree).values()], cmap=cmap)\n nx.draw_networkx_edges(G, pos=pos_map, ax = ax1, alpha=.1)\n plt.savefig(\"complex_convex_reg.png\", dpi=200)\n fig, ax2 = plt.subplots(dpi=200)\n nx.draw_networkx_nodes(G, pos=org_pos_map, ax=ax2, node_color=z, alpha=1, node_size=[v for v in dict(G.degree).values()], cmap=cmap)\n nx.draw_networkx_edges(G, pos=org_pos_map, ax=ax2, alpha=.1)\n plt.savefig(\"complex_convex_org.png\", dpi=200)\n #Calculate NMI between embeddings\n print(f'The NMI between z and z_hat is {calcNMI(Z, Z_true)}')\n NMIs.append((i*3, calcNMI(Z, Z_true)))\n #AUCs.append((iter, auc))\n plt.close()\n raa.order_adjacency_matrix(filename=\"complex_convex_ordered_adj.png\")\nprint(NMIs)\n#print(AUCs)\n\n","repo_name":"ChristianDjurhuus/RAA","sub_path":"src/experiments/complex_convex_reconstruction.py","file_name":"complex_convex_reconstruction.py","file_ext":"py","file_size_in_byte":3277,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"81"} +{"seq_id":"3439035287","text":"# 삼성 2072 : 홀수만 더하기 \nimport sys ; input = sys.stdin.readline\nt = int(input())\nfor i in range(1, t+1):\n aList = list(map(int, input().strip().split()))\n odd = 0\n for num in aList:\n if num % 2 == 1:\n odd += num\n print(\"#{} {}\".format(i, odd))","repo_name":"blacklabf/algorithms","sub_path":"algorithms-practice/SWExpertAcademy/S2072.py","file_name":"S2072.py","file_ext":"py","file_size_in_byte":286,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"37907143328","text":"#Escriba un programa al cual se le introduzcan diez valores y al final imprima por pantalla\n# la suma de los valores, las sumas de los cuadrados, el promedio, el máximo y el mínimo.\n\n\nnumero = int(input(\"¿Cuantos valores va a introducir?: \"))\n\nif numero <= 0:\n print(\"¡NO es posible!\")\nelse:\n valor = float(input(\"Escriba el número 1: \"))\n minimo = valor\n maximo = valor\n suma = 0\n valor=0\n for a in range(2, numero+1, 1):\n valor = float(input(f\"Escriba el número {a}: \"))\n suma = suma + valor\n if valor < minimo:\n minimo = valor\n if valor > maximo:\n maximo = valor\n promedio = suma/numero\nprint(f\"El numero más pequeño de los introducidos es {minimo}\")\nprint(f\"El numero más grande de los introducidos es {maximo}\")\nprint(f\"La suma de los numeros es {suma}\")\nprint(f\"El promedio de los numeros es {promedio}\")","repo_name":"Edwardb11/ejercicios-de-python","sub_path":"Ejercicios de python/6.py","file_name":"6.py","file_ext":"py","file_size_in_byte":897,"program_lang":"python","lang":"es","doc_type":"code","stars":2,"dataset":"github-code","pt":"81"} +{"seq_id":"40107942532","text":"# Autor: Rafael Padilha\r\n# Implementação de analizador lexico em python\r\n# OLA MUNDO\r\n\r\n# Função para buscar qual coluna da linha se inicia a palavra informada.\r\n# Recebe a string linha e a string palavra, retorna um inteiro.\r\ndef busca_coluna(linha,palavra):\r\n lista_char = list(linha)\r\n a_c=0\r\n l_c=1\r\n p_t=[]\r\n for c in lista_char:\r\n a_c = a_c + 1\r\n if(c is ' '):\r\n p_t=[]\r\n l_c = a_c + 1\r\n \r\n else:\r\n p_t.append(c)\r\n teste = ''.join(p_t)\r\n if teste == palavra:\r\n #print(\"Debug: a:\" + str(a_c) + ' l:' + str(l_c))\r\n return l_c\r\n\r\n# Função principal do analizador lexico.\r\n# Recebe duas strings com o nome do arquivo que contem as palavras aceitas pelo dicionario e tambem o nome do arquivo de entrada que vai verificar.\r\ndef anal_lexico(dict_file, entrada_file):\r\n dic = open(dict_file,'r').read().splitlines()\r\n entrada = open(entrada_file,'r').read().splitlines()\r\n\r\n l=0;\r\n for linha in entrada:\r\n l=l+1\r\n palavras = linha.split(' ')\r\n for palavra in palavras:\r\n if palavra not in dic:\r\n print(\"\\'\" + palavra + \"\\' não faz parte do dicionário. [Linha: \" + str(l) + ', Coluna: ' + str(busca_coluna(linha,palavra)) + ']')\r\n","repo_name":"rafaelpadilha/ifb-compiladores","sub_path":"Analisador Lexico/anal_lexico.py","file_name":"anal_lexico.py","file_ext":"py","file_size_in_byte":1318,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"27935528434","text":"### Merge on page 51 on textbook ###\n### Problem 7 on Rosalind ###\n\ndef merge():\n # read Rosalind dataset from txt file into arrays and their lengths\n # readline(): will return line from our file\n # strip(): strips any spaces at start or end\n # split(): splits our string into list\n with open(\"merge.txt\") as mergeInput:\n arr1Size = int(mergeInput.readline().strip())\n arr1 = [int(a) for a in mergeInput.readline().split()]\n arr2Size = int(mergeInput.readline().strip())\n arr2 = [int(a) for a in mergeInput.readline().split()]\n\n merged = [] # declare merged list of arrays\n # extend(): extends array by adding items to the end\n # append(): adds one item to the end of array\n while (arr1 or arr2):\n if not arr1:\n merged.extend(arr2)\n return merged\n elif not arr2:\n merged.extend(arr1)\n return merged\n elif arr1[0] <= arr2[0]: # from textbook function merge\n merged.append(arr1.pop(0))\n else: # from textbook function merge\n merged.append(arr2.pop(0))\n\n return merged\n\n# main function call\nmergedFinal = merge()\n\n# write answer to output.txt file (easier for the amount of numbers in given dataset)\nwith open(\"output.txt\", \"w\") as outputFile:\n outputFile.write(' '.join([str(b) for b in mergedFinal]))\n\n# check output.txt for answer, copy and paste into Rosalind\n# attach python file below answer box\n","repo_name":"HaganShane/CMPSC465","sub_path":"MergeArrays.py","file_name":"MergeArrays.py","file_ext":"py","file_size_in_byte":1454,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"81"} +{"seq_id":"11803084569","text":"# -*- coding: utf-8 -*-\n\n\"\"\"\nPackage: iads\nFile: utils.py\nAnnée: LU3IN026 - semestre 2 - 2022-2023, Sorbonne Université\n\"\"\"\n\n\n# Fonctions utiles pour les TDTME de LU3IN026\n# Version de départ : Février 2023\n\n# import externe\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\n# ------------------------ \n\ndef genere_dataset_uniform(p, n, binf=-1, bsup=1):\n \"\"\" int * int * float^2 -> tuple[ndarray, ndarray]\n Hyp: n est pair\n p: nombre de dimensions de la description\n n: nombre d'exemples de chaque classe\n les valeurs générées uniformément sont dans [binf,bsup]\n \"\"\"\n a=np.random.uniform(binf,bsup,(n*2,p))\n b = np.asarray([-1 for i in range(0,n)] + [+1 for i in range(0,n)])\n np.random.shuffle(b)\n return (a,b)\n\n\ndef genere_dataset_gaussian(positive_center, positive_sigma, negative_center, negative_sigma, nb_points):\n \"\"\"\n Génère un ensemble de données en utilisant une distribution gaussienne.\n \n input:\n positive_center (array): Centre de la distribution gaussienne positive\n positive_sigma (array): Matrice de covariance de la distribution gaussienne positive\n negative_center (array): Centre de la distribution gaussienne négative\n negative_sigma (array): Matrice de covariance de la distribution gaussienne négative\n nb_points (int): Nombre de points à générer pour chaque classe\n \n output:\n tuple: Un tuple contenant les descriptions des données (data_desc) et les étiquettes (data_labels)\n \"\"\"\n # Génération de points suivant une distribution gaussienne pour la classe positive\n points_pos=np.random.multivariate_normal(positive_center,positive_sigma,nb_points)\n # Génération de points suivant une distribution gaussienne pour la classe négative\n points_neg=np.random.multivariate_normal(negative_center,negative_sigma,nb_points)\n \n data_gauss=np.concatenate((points_neg,points_pos))\n data_label=np.asarray([-1 for i in range(0,nb_points)] + [+1 for i in range(0,nb_points)])\n \n return (data_gauss,data_label)\n\n\n\ndef plot2DSet(desc,labels): \n \"\"\" ndarray * ndarray -> affichage\n la fonction doit utiliser la couleur 'red' pour la classe -1 et 'blue' pour la +1\n \"\"\"\n # Extraction des exemples de classe -1:\n data2_negatifs = desc[labels == -1]\n # Extraction des exemples de classe +1:\n data2_positifs = desc[labels == +1]\n # Affichage de l'ensemble des exemples :\n plt.scatter(data2_negatifs[:,0],data2_negatifs[:,1],marker='o', color=\"red\") # 'o' rouge pour la classe -1\n plt.scatter(data2_positifs[:,0],data2_positifs[:,1],marker='x', color=\"blue\") # 'x' bleu pour la classe +1\n\n\ndef plot_frontiere(desc_set, label_set, classifier, step=30):\n \"\"\" desc_set * label_set * Classifier * int -> NoneType\n Remarque: le 4e argument est optionnel et donne la \"résolution\" du tracé: plus il est important\n et plus le tracé de la frontière sera précis. \n Cette fonction affiche la frontière de décision associée au classifieur\n \"\"\"\n mmax=desc_set.max(0)\n mmin=desc_set.min(0)\n x1grid,x2grid=np.meshgrid(np.linspace(mmin[0],mmax[0],step),np.linspace(mmin[1],mmax[1],step))\n grid=np.hstack((x1grid.reshape(x1grid.size,1),x2grid.reshape(x2grid.size,1)))\n \n # calcul de la prediction pour chaque point de la grille\n res=np.array([classifier.predict(grid[i,:]) for i in range(len(grid)) ])\n res=res.reshape(x1grid.shape)\n # tracer des frontieres\n # colors[0] est la couleur des -1 et colors[1] est la couleur des +1\n plt.contourf(x1grid,x2grid,res,colors=[\"darksalmon\",\"skyblue\"],levels=[-1000,0,1000])\n\n\n# ------------------------ COMPLETER LES INSTRUCTIONS DANS CETTE BOITE \ndef create_XOR(n, var):\n \"\"\" int * float -> tuple[ndarray, ndarray]\n Hyp: n et var sont positifs\n n: nombre de points voulus\n var: variance sur chaque dimension\n \"\"\"\n # Génération de points pour les quatres classes\n points1=np.random.multivariate_normal(np.array([-5,5]),np.array([[0,var],[var,0]]),n)\n points2=np.random.multivariate_normal(np.array([5,-5]),np.array([[0,var],[var,0]]),n)\n points3=np.random.multivariate_normal(np.array([-5,-5]),np.array([[0,var],[var,0]]),n)\n points4=np.random.multivariate_normal(np.array([5,5]),np.array([[0,var],[var,0]]),n)\n # Concaténation des 4 classes pour former l'ensemble description\n data_xor=np.concatenate((points1,points2,points3,points4))\n # Création des labels \n label_xor=np.array([1]*n+[-1]*n+[1]*n+[-1]*n)\n return(data_xor,label_xor)\n\n\n\ndef colonnes_numeriques(df):\n \"\"\"retourne le nom des colonnes numeriques de df\n \"\"\"\n numeric_columns = df.select_dtypes(include=np.number)\n numeric_columns_np = numeric_columns.columns.tolist()\n return numeric_columns_np\n\n\ndef discretise(m_desc, m_class, num_col):\n \"\"\" input:\n - m_desc : (np.array) matrice des descriptions toutes numériques\n - m_class : (np.array) matrice des classes (correspondant à m_desc)\n - num_col : (int) numéro de colonne de m_desc à considérer\n - nb_classes : (int) nombre initial de labels dans le dataset (défaut: 2)\n output: tuple : ((seuil_trouve, entropie), (liste_coupures,liste_entropies))\n -> seuil_trouve (float): meilleur seuil trouvé\n -> entropie (float): entropie du seuil trouvé (celle qui minimise)\n -> liste_coupures (List[float]): la liste des valeurs seuils qui ont été regardées\n -> liste_entropies (List[float]): la liste des entropies correspondantes aux seuils regardés\n (les 2 listes correspondent et sont donc de même taille)\n REMARQUE: dans le cas où il y a moins de 2 valeurs d'attribut dans m_desc, aucune discrétisation\n n'est possible, on rend donc ((None , +Inf), ([],[])) dans ce cas \n \"\"\"\n # Liste triée des valeurs différentes présentes dans m_desc:\n l_valeurs = np.unique(m_desc[:,num_col])\n \n # Si on a moins de 2 valeurs, pas la peine de discrétiser:\n if (len(l_valeurs) < 2):\n return ((None, float('Inf')), ([],[]))\n \n # Initialisation\n best_seuil = None\n best_entropie = float('Inf')\n \n # pour voir ce qui se passe, on va sauver les entropies trouvées et les points de coupures:\n liste_entropies = []\n liste_coupures = []\n \n nb_exemples = len(m_class)\n \n for v in l_valeurs:\n cl_inf = m_class[m_desc[:,num_col]<=v]\n cl_sup = m_class[m_desc[:,num_col]>v]\n nb_inf = len(cl_inf)\n nb_sup = len(cl_sup)\n \n # calcul de l'entropie de la coupure\n val_entropie_inf = cl.entropie(cl_inf) # entropie de l'ensemble des inf\n val_entropie_sup = cl.entropie(cl_sup) # entropie de l'ensemble des sup\n \n val_entropie = (nb_inf / float(nb_exemples)) * val_entropie_inf \\\n + (nb_sup / float(nb_exemples)) * val_entropie_sup\n \n # Ajout de la valeur trouvée pour retourner l'ensemble des entropies trouvées:\n liste_coupures.append(v)\n liste_entropies.append(val_entropie)\n \n # si cette coupure minimise l'entropie, on mémorise ce seuil et son entropie:\n if (best_entropie > val_entropie):\n best_entropie = val_entropie\n best_seuil = v\n \n return (best_seuil, best_entropie), (liste_coupures,liste_entropies)\n\n\n\ndef partitionne(m_desc,m_class,n,s):\n \"\"\" input:\n - m_desc : (np.array) matrice des descriptions toutes numériques\n - m_class : (np.array) matrice des classes (correspondant à m_desc)\n - n : (int) numéro de colonne de m_desc\n - s : (float) seuil pour le critère d'arrêt\n Hypothèse: m_desc peut être partitionné ! (il contient au moins 2 valeurs différentes)\n output: un tuple composé de 2 tuples\n \"\"\"\n \n \n A_x=m_desc[:,n]\n \n first=[]\n second=[]\n \n for i in range(len(A_x)):\n if A_x[i]<=s:\n first.append(i)\n else:\n second.append(i)\n \n \n return ((m_desc[first],m_class[first]),(m_desc[second],m_class[second]))\n\n","repo_name":"Yasmine2201/agribalyse-database","sub_path":"iads/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":8258,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"70675158345","text":"from bs4 import BeautifulSoup\nfrom bs4 import Comment\nfrom lxml import etree\nimport re\nimport pandas as pd;\nimport openpyxl as pyxl;\nimport sqlite3;\nfrom openpyxl.utils.dataframe import dataframe_to_rows\nfrom pathlib import Path\nimport warnings\nimport configparser\nimport os\nwarnings.filterwarnings(\"ignore\", category=UserWarning)\n\n# Define global constants\nOUTPUT_PATH = Path(__file__).parent\nCACHE_PATH = OUTPUT_PATH / Path(\"cache\")\nCONFIG_PATH = OUTPUT_PATH / Path(\"config\")\n\n# Define the custom exception\nclass exception(Exception):\n pass\n\n# Get configuration from the config file\nconfig = configparser.ConfigParser()\nconfig.read(CONFIG_PATH / Path(\"config.ini\"))\nsetupPlanCollumns = config['DEFAULT'].get('setupPlanCollumns', 'GeoFilename,NumberOfParts,DimensionX,DimensionY,Area,Weight,MachiningTime').split(',')\nexcelFileDirectory = Path(config['DEFAULT'].get('excelFileDirectory', 'testing/xlsx'))\nexcelSourceName = config['DEFAULT'].get('excelSourceName', 'main.xlsx')\nexcelWorkbookName = config['DEFAULT'].get('excelWorkbookName', 'podatki')\nexcelLastFile = config['DEFAULT'].get('excelLastFile', 'main_output.xlsx')\nexcelOutputDir = Path(config['DEFAULT'].get('excelOutputDir', 'testing/xlsx'))\n\n# Function to save the current settings to the config file\ndef saveSettingsToFile():\n config['DEFAULT']['setupPlanCollumns'] = ','.join(setupPlanCollumns)\n config['DEFAULT']['excelFileDirectory'] = str(excelFileDirectory)\n config['DEFAULT']['excelSourceName'] = excelSourceName\n config['DEFAULT']['excelWorkbookName'] = excelWorkbookName\n config['DEFAULT']['excelLastFile'] = excelLastFile\n config['DEFAULT']['excelOutputDir'] = str(excelOutputDir)\n with open(CONFIG_PATH / Path(\"config.ini\"), 'w') as configfile:\n config.write(configfile)\n\n# Function to load the settings from the config file\ndef loadSettingsFromFile():\n config = configparser.ConfigParser()\n config.read(CONFIG_PATH / Path(\"config.ini\"))\n global setupPlanCollumns, excelFileDirectory, excelSourceName, excelWorkbookName, excelLastFile, excelOutputDir\n setupPlanCollumns = config['DEFAULT'].get('setupPlanCollumns', 'GeoFilename,NumberOfParts,DimensionX,DimensionY,Area,Weight,MachiningTime').split(',')\n excelFileDirectory = Path(config['DEFAULT'].get('excelFileDirectory', 'testing/xlsx'))\n excelSourceName = config['DEFAULT'].get('excelSourceName', 'main.xlsx')\n excelWorkbookName = config['DEFAULT'].get('excelWorkbookName', 'podatki')\n excelLastFile = config['DEFAULT'].get('excelLastFile', 'main_output.xlsx')\n excelOutputDir = Path(config['DEFAULT'].get('excelOutputDir', 'testing/xlsx'))\n \n# Function that goes through all the files and converts them to a dataframe\ndef filesToDataframe(setupPlanList, df):\n # Connect to the temp database\n database = sqlite3.connect(CACHE_PATH / Path(\"cache.db\"))\n cursor = database.cursor()\n cursor.execute(\"DROP TABLE IF EXISTS LabelPartData\")\n # Iterate through all the files \n for file in setupPlanList:\n file = Path(file)\n # Check if the file is an HTML file\n # Check if the file exists\n if not file.is_file():\n raise exception(\"Datoteka ne obstaja\")\n if not (file.suffix == \".html\" or file.suffix == \".HTML\"):\n raise exception(\"Datoteka ni HTML\")\n # Open the file and parse it to a BeautifulSoup object\n with open(file) as fp:\n setupPlan = BeautifulSoup(fp, \"html.parser\")\n # Get the SQL part of the file\n singlePartData = getSinglePartSQL(setupPlan)\n # Format the SQL so it works with sqlite3\n singlePartData = singlePartData.replace(\"CREATE TABLE LabelPartData;\\nALTER TABLE LabelPartData ADD COLUMN Count COUNTER PRIMARY KEY;\", \"CREATE TABLE LabelPartData (Count INTEGER PRIMARY KEY AUTOINCREMENT);\")\n # Get the machining time for each part becouse it is not in the SQL\n singlePartData += getSinglePartMachiningTime(setupPlan)\n # Check if the file contains data about the parts\n if(singlePartData == \"\"):\n raise exception(\"Datoteka ne vsebuje podatkov o posameznih kosih\")\n # Execute the SQL and update the dataframe\n df = dataframeAppendFile(singlePartData, df)\n return df\n\n# Function that goes through the html file, gets the machining time for each part and adds it to the SQL script\ndef getSinglePartMachiningTime(setupPlan):\n # Create the new column in SQL\n singlePartSQL = \"ALTER TABLE LabelPartData ADD COLUMN MachiningTime VARCHAR(255);\\n\"\n # Find the table with the single part data\n singlePartTable = setupPlan.find_all(string=re.compile(r\"(INFORMATION ON SINGLE PART)|(EINZELTEILINFORMATION)\"))[-1].find_parent(\"table\")\n # Find all the rows that contain the machining times\n machiningTimesRows = singlePartTable.find_all(string=re.compile(r\"(MACHINING TIME)|(BEARBEITUNGSZEIT)\"))\n # Iterate through all the rows and add the machining time to the SQL script\n for i in range(len(machiningTimesRows)):\n machiningTime = machiningTimesRows[i].find_parent(\"tr\").find_all(\"td\")[1].text\n # Check if the machining time is not empty and add the data to the SQL script\n if(machiningTime != \"\"):\n singlePartSQL += \"UPDATE LabelPartData SET MachiningTime='\" + re.sub(r\" min\", \"\", re.findall(r\"\\d+\\.\\d+ min\", machiningTime)[0]) + \"' WHERE COUNT = \" + str(i+1) + \";\"\n return singlePartSQL\n \n# Function that goes through the html file and gets the SQL scipt for the single part data\ndef getSinglePartSQL(setupPlan):\n # Find all the comments in the file\n comments = setupPlan.findAll(string=lambda string:isinstance(string, Comment))\n # Iterate through all the comments and find the one that contains the SQL script\n for comment in comments: \n commentSoup = BeautifulSoup(comment, \"lxml\") \n sqlRow = commentSoup.find(\"sql\", string=\"CREATE TABLE LabelPartData\")\n # Check if the comment contains the SQL script\n if sqlRow is not None:\n # Get the SQL script\n setupPlan = sqlRow.text + \";\\n\"\n while sqlRow.next_sibling is not None:\n sqlRow = sqlRow.next_sibling\n if hasattr(sqlRow, 'name') and sqlRow.name == \"sql\": # type: ignore\n setupPlan += sqlRow.text + \";\\n\"\n return setupPlan\n return \"\"\n\n# Function that executes the SQL script and updates the dataframe\ndef dataframeAppendFile(setupPlan, df):\n # Connect to the temp database\n database = sqlite3.connect(CACHE_PATH / Path(\"cache.db\"))\n cursor = database.cursor()\n # Execute the SQL script\n cursor.execute(\"DROP TABLE IF EXISTS LabelPartData\") \n cursor.executescript(setupPlan)\n database.commit()\n # Get the data from the database\n sql_query = pd.read_sql_query ('''\n SELECT\n '''+ \", \".join(setupPlanCollumns) + '''\n FROM LabelPartData\n ''', database)\n # Add the data to the dataframe(if it's empty create a new one otherwise append it)\n if df.empty:\n df = pd.DataFrame(sql_query)\n else:\n df = pd.concat([df, pd.DataFrame(sql_query)], ignore_index=True)\n # Format the GeoFilename so it only contains the filename not the whole path\n df[\"GeoFilename\"] = df[\"GeoFilename\"].replace(to_replace=r\".*/(.+\\.GEO)\", value=r\"\\g<1>\", regex=True)\n return df\n\n# Function that saves the data from the dataframe to an excel file\ndef writeToXlsx(df, excelOutputName):\n try:\n # Open the main excel file\n workbook = pyxl.load_workbook(excelFileDirectory / excelSourceName)\n worksheet = workbook[excelWorkbookName]\n # Iterate through all the cells in the dataframe and add them to the excel file\n rowIndex = 0;\n for row in dataframe_to_rows(df, header=True, index=False):\n rowIndex += 1\n for i, cell_value in enumerate(row):\n worksheet.cell(row=rowIndex, column=i+1, value=cell_value)\n # Save the excel file as a new file\n workbook.save(excelOutputDir / excelOutputName)\n workbook.close()\n except Exception as e:\n raise exception(\"Ni mogoče zapisati v excel datoteko\")\n\n# Function that controls the conversion process and returns the dataframe for the GUI preview\ndef mainConversion(setupPlanList):\n # Load confinguration from the config file\n loadSettingsFromFile()\n # Create and fill the dataframe\n df = pd.DataFrame(columns=setupPlanCollumns)\n df = filesToDataframe(setupPlanList, df)\n # Create the excel file\n global excelLastFile\n excelLastFile = os.path.basename(setupPlanList[0].replace(\".HTML\", \".xlsx\"))\n writeToXlsx(df, excelLastFile)\n # Save the settings with created excel file name to the config file\n saveSettingsToFile()\n return df","repo_name":"RenkoSostaric/KB-Calculate","sub_path":"src/conversion.py","file_name":"conversion.py","file_ext":"py","file_size_in_byte":8788,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"35367594855","text":"from copy import deepcopy\n\nclass Contact:\n def __init__(self, name: str, phone: str, commet: str):\n self.name = name\n self.phone = phone\n self.comment = commet\n\n def full(self):\n return f'{self.name} {self.phone} {self.comment}'\n\nclass PhoneBook:\n def __init__(self, phone_book: dict = None, path: str = 'Pithon_\\guide_class\\phone_.txt'):\n self.path = path\n if phone_book is None:\n self.phone_book: dict[int, Contact] = {}\n else:\n self.phone_book = phone_book\n self.original_book = {}\n\n def open_file(self): # открывающая справочник\n with open(self.path, 'r', encoding='UTF-8') as file:\n data = file.readlines()\n for i, contact in enumerate(data, 1):\n contact = contact.strip().split(';')\n self.phone_book[i] = Contact(*contact)\n self.original_book = deepcopy(self.phone_book)\n \n def save_file(self): # сохраняет контакт\n data = []\n for contact in self.phone_book.values():\n contact = ';'.join(contact)\n data.append(contact)\n data = '\\n'.join(data)\n with open(self.path, 'w', encoding='UTF-8') as file:\n file.write(data)\n\n def add_contact(self, new_contact: list[str]): # добавления контакта\n c_id = max(self.phone_book) + 1\n self.phone_book[c_id] = new_contact\n\n def find_contact(self, word: str): # находит контакт\n result = {}\n for c_id, contact in self.phone_book.items():\n if word.lower() in contact.full():\n result[c_id] = contact\n break\n return PhoneBook(result)\n \n def edit_contact(self, c_id: int, new_contact: list[str]): # изменяет контакты\n current_contact = self.phone_book.get(c_id)\n contact = []\n for i in range(len(new_contact)):\n if new_contact[i]:\n contact.append(new_contact[i])\n else:\n contact.append(current_contact[i])\n self.phone_book[c_id] = Contact(*contact)\n return contact[0]\n\n def delete_contact(self, c_id: int) -> str: # удаляет контакты\n return self.phone_book.pop(c_id)[0]\n\n def max_len(self, option: str) -> int:\n result = []\n for contact in self.phone_book.values():\n if option == 'name':\n item = contact.name\n elif option == 'phone':\n item = contact.phone\n else:\n item = contact.comment\n result.append(item)\n return len(max(result, key = len))","repo_name":"Arman1407/Pithon_","sub_path":"guide_class/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":2776,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"11359272229","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom pylipid.api import LipidInteraction\nfrom pylipid.util import check_dir\nimport argparse\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"-l\", \"--lipid\")\nparser.add_argument(\"-c\", \"--cgpdb\")\nparser.add_argument('-a', '--aapdb')\nargs = parser.parse_args()\n\n\nprefix = args.cgpdb[0:-4]\n\ntrajfile_list = ['sys1/{}_MD1.xtc'.format(prefix), 'sys2/{}_MD2.xtc'.format(prefix),\n 'sys3/{}_MD3.xtc'.format(prefix), 'sys4/{}_MD4.xtc'.format(prefix),]\n#trajfile_list = ['sys1/step7_production.xtc', 'sys2/step7_production.xtc',\n# 'sys3/step7_production.xtc', 'sys4/step7_production.xtc',]\ntopfile_list = [args.cgpdb] * 4\n\ndt_traj = None # not needed\nstride = 15 # timestep 20 fs, xtc freq 200 000 => 0.004 us/frame, stride 15 => 0.06 us resolution\n\nlipid = args.lipid # residue name in the topology.\nlipid_atoms = None # means all\ncutoffs = [0.5, 0.7] # dual-cutoff scheme for coarse-grained simulations\npdb_file_to_map = args.aapdb # need to generate pdb? or maybe charmm-gui provides?\n\n\nbinding_site_size = 4 # binding site should contain at least four residues.\nn_top_poses = 3 # write out num. of representative bound poses for each binding site.\nn_clusters = \"auto\"\n\nsave_dir = None # means current\nsave_pose_format = \"pdb\"\nsave_pose_traj = True # save all the bound poses in a trajectory for each binding site\nsave_pose_traj_format = \"xtc\"\ntimeunit = \"us\"\nresi_offset = 0 # shift the residue index, useful for MARTINI models.\nradii = None # Martini 2.2 are defined in pylipid\nfig_format = \"png\"\nnum_cpus = 4\n\n\n#####################################\n###### no changes needed below ######\n#####################################\n\n#### calculate lipid interactions\nli = LipidInteraction(trajfile_list, topfile_list=topfile_list, cutoffs=cutoffs, lipid=lipid,\n lipid_atoms=lipid_atoms, nprot=1, resi_offset=resi_offset,\n timeunit=timeunit, save_dir=save_dir, stride=stride, dt_traj=dt_traj)\n\n\nli.collect_residue_contacts()\n\nli.compute_residue_duration(residue_id=None)\nli.compute_residue_occupancy(residue_id=None)\nli.compute_residue_lipidcount(residue_id=None)\nli.show_stats_per_traj(write_log=True, print_log=True)\nli.compute_residue_koff(residue_id=None, plot_data=True, fig_close=True,\n fig_format=fig_format, num_cpus=num_cpus)\nli.compute_binding_nodes(threshold=binding_site_size, print_data=False)\nif len(li.node_list) == 0:\n print(\"*\"*50)\n print(\"No binding site detected! Skip analysis for binding sites.\")\n print(\"*\"*50)\nelse:\n li.compute_site_duration(binding_site_id=None)\n li.compute_site_occupancy(binding_site_id=None)\n li.compute_site_lipidcount(binding_site_id=None)\n li.compute_site_koff(binding_site_id=None, plot_data=True, fig_close=True,\n fig_format=fig_format, num_cpus=num_cpus)\n pose_traj, pose_rmsd_data = li.analyze_bound_poses(binding_site_id=None, pose_format=save_pose_format,\n n_top_poses=n_top_poses, n_clusters=n_clusters,\n fig_format=fig_format, num_cpus=num_cpus)\n # save pose trajectories\n if save_pose_traj:\n for bs_id in pose_traj.keys():\n pose_traj[bs_id].save(\"{}/Bound_Poses_{}/Pose_traj_BSid{}.{}\".format(li.save_dir, li.lipid, bs_id,\n save_pose_traj_format))\n del pose_traj # save memory space\n # surface_area_data = li.compute_surface_area(binding_site_id=None, radii=radii, fig_format=fig_format)\n data_dir = check_dir(li.save_dir, \"Dataset_{}\".format(li.lipid))\n pose_rmsd_data.to_csv(\"{}/Pose_RMSD_data.csv\".format(data_dir), index=False, header=True)\n # surface_area_data.to_csv(\"{}/Surface_Area_data.csv\".format(data_dir), index=True, header=True)\n li.write_site_info(sort_residue=\"Residence Time\")\n\nif pdb_file_to_map is not None:\n li.save_pymol_script(pdb_file_to_map)\n\n#### write and save data\nfor item in [\"Dataset\", \"Duration\", \"Occupancy\", \"Lipid Count\", \"CorrCoef\"]:\n li.save_data(item=item)\nfor item in [\"Residence Time\", \"Duration\", \"Occupancy\", \"Lipid Count\"]:\n li.save_coordinate(item=item)\nfor item in [\"Residence Time\", \"Duration\", \"Occupancy\", \"Lipid Count\"]:\n li.plot(item=item, fig_close=True, fig_format=fig_format)\n li.plot_logo(item=item, fig_close=True, fig_format=fig_format)\n\n#### plot binding site comparison.\nif len(li.node_list) > 0:\n for item in [\"Duration BS\", \"Occupancy BS\"]:\n li.save_data(item=item)\n\n ylabel_timeunit = 'ns' if li.timeunit == \"ns\" else r\"$\\mu$s\"\n ylabel_dict = {\"Residence Time\": \"Residence Time ({})\".format(ylabel_timeunit),\n \"Duration\": \"Duration ({})\".format(ylabel_timeunit),\n \"Occupancy\": \"Occuoancy (100%)\",\n \"Lipid Count\": \"Lipid Count (num.)\"}\n\n # plot No. 1\n binding_site_IDs = np.sort(\n [int(bs_id) for bs_id in li.dataset[\"Binding Site ID\"].unique() if bs_id != -1])\n for item in [\"Residence Time\", \"Duration\", \"Occupancy\", \"Lipid Count\"]:\n item_values = np.array(\n [li.dataset[li.dataset[\"Binding Site ID\"]==bs_id][\"Binding Site {}\".format(item)].unique()[0]\n for bs_id in binding_site_IDs])\n fig, ax = plt.subplots(1, 1, figsize=(len(li.node_list)*0.5, 2.6))\n ax.scatter(np.arange(len(item_values)), np.sort(item_values)[::-1], s=50, color=\"red\")\n ax.set_xticks(np.arange(len(item_values)))\n sorted_index = np.argsort(item_values)[::-1]\n ax.set_xticklabels(binding_site_IDs[sorted_index])\n ax.set_xlabel(\"Binding Site ID\", fontsize=12)\n ax.set_ylabel(ylabel_dict[item], fontsize=12)\n for label in ax.xaxis.get_ticklabels()+ax.yaxis.get_ticklabels():\n plt.setp(label, fontsize=12, weight=\"normal\")\n plt.tight_layout()\n plt.savefig(\"{}/{}_{}_v_binding_site.{}\".format(li.save_dir, li.lipid, \"_\".join(item.split()), fig_format),\n dpi=200)\n plt.close()\n\n # plot No. 2\n binding_site_IDs_RMSD = np.sort([int(bs_id) for bs_id in binding_site_IDs\n if f\"Binding Site {bs_id}\" in pose_rmsd_data.columns])\n RMSD_averages = np.array(\n [pose_rmsd_data[f\"Binding Site {bs_id}\"].dropna(inplace=False).mean()\n for bs_id in binding_site_IDs_RMSD])\n fig, ax = plt.subplots(1, 1, figsize=(len(li.node_list)*0.5, 2.6))\n ax.scatter(np.arange(len(RMSD_averages)), np.sort(RMSD_averages)[::-1], s=50, color=\"red\")\n ax.set_xticks(np.arange(len(RMSD_averages)))\n sorted_index = np.argsort(RMSD_averages)[::-1]\n ax.set_xticklabels(binding_site_IDs_RMSD[sorted_index])\n ax.set_xlabel(\"Binding Site ID\", fontsize=12)\n ax.set_ylabel(\"RMSD (nm)\", fontsize=12)\n for label in ax.xaxis.get_ticklabels()+ax.yaxis.get_ticklabels():\n plt.setp(label, fontsize=12, weight=\"normal\")\n plt.tight_layout()\n plt.savefig(\"{}/{}_RMSD_v_binding_site.{}\".format(li.save_dir, li.lipid, fig_format), dpi=200)\n plt.close()\n\n # plot No. 3\n '''\n surface_area_averages = np.array(\n [surface_area_data[\"Binding Site {}\".format(bs_id)].dropna(inplace=False).mean()\n for bs_id in binding_site_IDs])\n fig, ax = plt.subplots(1, 1, figsize=(len(li.node_list)*0.5, 2.6))\n ax.scatter(np.arange(len(surface_area_averages)), np.sort(surface_area_averages)[::-1], s=50, color=\"red\")\n ax.set_xticks(np.arange(len(surface_area_averages)))\n sorted_index = np.argsort(surface_area_averages)[::-1]\n ax.set_xticklabels(binding_site_IDs[sorted_index])\n ax.set_xlabel(\"Binding Site ID\", fontsize=12)\n ax.set_ylabel(r\"Surface Area (nm$^2$)\", fontsize=12)\n for label in ax.xaxis.get_ticklabels()+ax.yaxis.get_ticklabels():\n plt.setp(label, fontsize=12, weight=\"normal\")\n plt.tight_layout()\n plt.savefig(\"{}/{}_surface_area_v_binding_site.{}\".format(li.save_dir, li.lipid, fig_format), dpi=200)\n plt.close()\n '''\n # plot No. 4\n res_time_BS = np.array(\n [li.dataset[li.dataset[\"Binding Site ID\"]==bs_id][\"Binding Site Residence Time\"].unique()[0]\n for bs_id in binding_site_IDs_RMSD])\n fig, ax = plt.subplots(1, 1, figsize=(len(li.node_list)*0.5, 2.6))\n ax.scatter(res_time_BS, RMSD_averages, s=50, color=\"red\")\n ax.set_xlabel(ylabel_dict[\"Residence Time\"], fontsize=12)\n ax.set_ylabel(\"RMSD (nm)\", fontsize=12)\n for label in ax.xaxis.get_ticklabels()+ax.yaxis.get_ticklabels():\n plt.setp(label, fontsize=12, weight=\"normal\")\n plt.tight_layout()\n plt.savefig(\"{}/{}_Residence_Time_v_RMSD.{}\".format(li.save_dir, li.lipid, fig_format), dpi=200)\n plt.close()\n '''\n # plot No. 5\n res_time_BS = np.array(\n [li.dataset[li.dataset[\"Binding Site ID\"]==bs_id][\"Binding Site Residence Time\"].unique()[0]\n for bs_id in binding_site_IDs])\n fig, ax = plt.subplots(1, 1, figsize=(len(li.node_list)*0.5, 2.6))\n ax.scatter(res_time_BS, surface_area_averages, s=50, color=\"red\")\n ax.set_xlabel(ylabel_dict[\"Residence Time\"], fontsize=12)\n ax.set_ylabel(r\"Surface Area (nm$^2$)\", fontsize=12)\n for label in ax.xaxis.get_ticklabels()+ax.yaxis.get_ticklabels():\n plt.setp(label, fontsize=12, weight=\"normal\")\n plt.tight_layout()\n plt.savefig(\"{}/{}_Residence_Time_v_surface_area.{}\".format(li.save_dir, li.lipid, fig_format), dpi=200)\n plt.close()\n '''","repo_name":"michal2am/bioscripts","sub_path":"stockholm/pylipid/pylipid_tests.py","file_name":"pylipid_tests.py","file_ext":"py","file_size_in_byte":10011,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"81"} +{"seq_id":"41573887537","text":"from mercurial.node import bin, nullid\r\nfrom mercurial import util\r\n\r\nimport json\r\nimport requests\r\nfrom mercurial.utils import (\r\n procutil,\r\n)\r\n\r\nimport simplejson as json\r\n\r\n\r\ndef hook(ui, repo, hooktype, node=None, **kwargs):\r\n def warn(message):\r\n if node:\r\n ui.warn(message)\r\n \r\n def write(message):\r\n if node:\r\n ui.write(message)\r\n \r\n \r\n url = ui.config(\"httphooks\", 'url')\r\n if not url:\r\n warn('httphooks.url is null')\r\n return -2\r\n try:\r\n changesets=list()\r\n if node and repo:\r\n for rev in xrange(repo[node].rev(), len(repo)):\r\n item = repo[rev]\r\n change = createCommitInfo(item,2)\r\n \r\n changesets.append(change)\r\n data = {'Commits': changesets,\r\n 'HookType': hooktype,\r\n 'UserName': procutil.getuser()}\r\n #write('{}\\n'.format(json.dumps(data)))\r\n resp = requests.post(url, json=data)\r\n #write('{}\\n'.format(resp.text))\r\n result = resp.json()\r\n if result['success']:\r\n if result['message']:\r\n write('{}\\n'.format(result['message']))\r\n return 0\r\n if result['message']:\r\n warn('{}\\n'.format(result['message']))\r\n return 1\r\n except Exception as ee:\r\n warn('Exception: {}\\n'.format(ee))\r\n return -1\r\n\r\n\r\ndef createCommitInfo(item, depth):\r\n return {'Message' : item.description().decode('windows-1251'),\r\n 'Rev' : item.rev(),\r\n 'Branch' : item.branch(),\r\n 'Tags' : item.tags(),\r\n 'Hex' : item.hex(),\r\n 'User' : item.user(),\r\n 'MercurialDate' : item.date(),\r\n 'Files' : item.files(),\r\n 'Parents' : [createCommitInfo(i,depth-1) for i in item.parents()] if depth>0 else None}","repo_name":"3da/MercurialHttpHooks","sub_path":"src/HttpHooks.py","file_name":"HttpHooks.py","file_ext":"py","file_size_in_byte":1953,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"81"} +{"seq_id":"1242989306","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu May 29 13:48:54 2014\n\n@author: edouard.duchesnay@cea.fr\n\nCluster utils\n\"\"\"\n\nimport os\nfrom collections import OrderedDict\n\n##############################################################################\n##\n# Note that we can't indent this variable as required by PEP 8 because this\n# would impact the formating of the PBS files.\njob_header = \"\"\"#!/bin/bash\n#PBS -S /bin/bash\n\"\"\"\n\nlim_string_format = \"{option}={value}\"\n\ndef gabriel_make_sync_data_files(wd, wd_cluster=None, user=None):\n \"\"\"Create sync_pull.sh and sync_push.sh files in the wd.\n\n Input\n -----\n wd: string, local working directory\n\n wd_cluster: string, remote working directory. If None,\n /neurospin/tmp//basename(wd)\n\n Ouput\n -----\n String: the path to the files, can be use to do the synchro.\n\n Example:\n push, pull, wd_cluster = gabriel_make_sync_data_files(\"/tmp/toto\")\n os.system(push)\n \"\"\"\n import getpass\n if user is None:\n user = getpass.getuser()\n if wd_cluster is None:\n wd_cluster = os.path.join(\"/neurospin\", \"tmp\", user,\n os.path.basename(wd))\n print(\"# Make sure parent dir of wd_cluster exists\")\n cmd = 'ssh %s@gabriel.intra.cea.fr \"mkdir %s\"' % (user, os.path.dirname(wd_cluster))\n print(cmd)\n os.system(cmd)\n # preserve:\n # recursive, link, time, group, owner, Devices (scpecial), update, verbose, compress\n push_str = 'rsync -rltgoDuvz %s %s@gabriel.intra.cea.fr:%s/' % (\n wd, user, os.path.dirname(wd_cluster))\n sync_push_filename = os.path.join(wd, \"sync_push.sh\")\n with open(sync_push_filename, 'w') as f:\n f.write(push_str)\n os.chmod(sync_push_filename, 0o777)\n pull_str = 'rsync -rltgoDuvz %s@gabriel.intra.cea.fr:%s %s/' % (\n user, wd_cluster, os.path.dirname(wd))\n sync_pull_filename = os.path.join(wd, \"sync_pull.sh\")\n with open(sync_pull_filename, 'w') as f:\n f.write(pull_str)\n os.chmod(sync_pull_filename, 0o777)\n return sync_push_filename, sync_pull_filename, wd_cluster\n\n\ndef gabriel_make_qsub_job_files(output_dirname, cmd, suffix=\"\",\n nodes=1, mem=None, walltime=\"250:00:00\",\n freecores=0):\n \"\"\"Build standard PBS files:\n - one for Cati_LowPrio with 12 - freecores process per node\n - one for Cati_Long with 12 - freecores process per node\n - one for Global_long with 8 - freecores process per node\n\n This is mostly a convenience function for write_job_file.\n The number of nodes, the total job memory and the walltime can be modified.\n\n Input\n -----\n\n output_dirname: string, where the files should be created\n (use basename to create the job_name)\n\n cmd: string, the command to run\n\n Example\n -------\n\n gabriel_make_qsub_job_files(\"/tmp/toto\", \"mapreduce -map --config /tmp/toto/config.json\")\n \"\"\"\n project_name = os.path.basename(output_dirname)\n job_name = project_name\n limits = OrderedDict()\n # Fill limits for nodes and ppn\n limits['host'] = OrderedDict()\n limits['host']['nodes'] = nodes\n if mem is not None:\n limits['mem'] = mem\n limits['walltime'] = walltime\n\n queue = \"Cati_LowPrio\"\n limits['host']['ppn'] = 12 - freecores\n job_filename = os.path.join(output_dirname,\n 'job_%s%s.pbs' % (queue, suffix))\n write_job_file(job_filename=job_filename,\n job_name=job_name,\n cmd=cmd,\n queue=queue,\n job_limits=limits)\n\n queue = \"Cati_long\"\n limits['host']['ppn'] = 12 - freecores\n job_filename = os.path.join(output_dirname,\n 'job_%s%s.pbs' % (queue, suffix))\n write_job_file(job_filename=job_filename,\n job_name=job_name,\n cmd=cmd,\n queue=queue,\n job_limits=limits)\n\n queue = \"Global_long\"\n limits['host']['ppn'] = 8 - freecores\n job_filename = os.path.join(output_dirname,\n 'job_%s%s.pbs' % (queue, suffix))\n write_job_file(job_filename=job_filename,\n job_name=job_name,\n cmd=cmd,\n queue=queue,\n job_limits=limits)\n\n\ndef write_job_file(job_filename, job_name, cmd, queue, job_limits=None):\n \"\"\"\n Generates a PBS configration file.\n\n Input\n -----\n job_filename (string): filename\n\n job_name (string): name of the job\n\n cmd (string): the command to run\n\n queue (string): queue on which to run the job\n\n job_limits (dict whose values are either strings or dict): job limits.\n If the value is a string, the pair (key, value) will be written on one line\n as key=value.\n If the value is a dict, the key is discarded and the value is written in\n one line as key0=value0:[key1=value1[:...]]. This is useful for limits\n like nodes and ppn which must be on the same line.\n You can use OrderedDict to maintain order.\n \"\"\"\n def lim_string_from_dict(opt_dict):\n lim_strings = []\n for limit, value in opt_dict.items():\n lim_strings.append(lim_string_format.format(option=limit,\n value=value))\n lim_str = \":\".join(lim_strings)\n return lim_str\n\n with open(job_filename, 'w') as f:\n f.write(job_header)\n f.write(\"\"\"#PBS -N %s\\n\"\"\" % job_name)\n if job_limits is not None:\n for limit, value in job_limits.items():\n if isinstance(value, str):\n lim_str = lim_string_format.format(option=limit,\n value=value)\n if isinstance(value, dict):\n lim_str = lim_string_from_dict(value)\n f.write(\"\"\"#PBS -l %s\\n\"\"\" % lim_str)\n f.write(\"\"\"#PBS -q %s\\n\"\"\" % queue)\n f.write(\"\\n\")\n f.write(\"%s\\n\" % cmd)\n os.chmod(job_filename, 0o777)\n","repo_name":"neurospin/scripts","sub_path":"brainomics/cluster_gabriel.py","file_name":"cluster_gabriel.py","file_ext":"py","file_size_in_byte":6047,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"81"} +{"seq_id":"35164273979","text":"import pytest\nfrom six import StringIO\n\nfrom neomodel import (\n RelationshipTo,\n StringProperty,\n StructuredNode,\n StructuredRel,\n UniqueIdProperty,\n config,\n install_all_labels,\n install_labels,\n)\nfrom neomodel.core import db, drop_constraints\nfrom neomodel.exceptions import ConstraintValidationFailed, FeatureNotSupported\n\nconfig.AUTO_INSTALL_LABELS = False\n\n\nclass NodeWithIndex(StructuredNode):\n name = StringProperty(index=True)\n\n\nclass NodeWithConstraint(StructuredNode):\n name = StringProperty(unique_index=True)\n\n\nclass NodeWithRelationship(StructuredNode):\n ...\n\n\nclass IndexedRelationship(StructuredRel):\n indexed_rel_prop = StringProperty(index=True)\n\n\nclass OtherNodeWithRelationship(StructuredNode):\n has_rel = RelationshipTo(\n NodeWithRelationship, \"INDEXED_REL\", model=IndexedRelationship\n )\n\n\nclass AbstractNode(StructuredNode):\n __abstract_node__ = True\n name = StringProperty(unique_index=True)\n\n\nclass SomeNotUniqueNode(StructuredNode):\n id_ = UniqueIdProperty(db_property=\"id\")\n\n\nconfig.AUTO_INSTALL_LABELS = True\n\n\ndef test_labels_were_not_installed():\n bob = NodeWithConstraint(name=\"bob\").save()\n bob2 = NodeWithConstraint(name=\"bob\").save()\n bob3 = NodeWithConstraint(name=\"bob\").save()\n assert bob.element_id != bob3.element_id\n\n for n in NodeWithConstraint.nodes.all():\n n.delete()\n\n\ndef test_install_all():\n drop_constraints()\n install_labels(AbstractNode)\n # run install all labels\n install_all_labels()\n\n indexes = db.list_indexes()\n index_names = [index[\"name\"] for index in indexes]\n assert \"index_INDEXED_REL_indexed_rel_prop\" in index_names\n\n constraints = db.list_constraints()\n constraint_names = [constraint[\"name\"] for constraint in constraints]\n assert \"constraint_unique_NodeWithConstraint_name\" in constraint_names\n assert \"constraint_unique_SomeNotUniqueNode_id\" in constraint_names\n\n # remove constraint for above test\n _drop_constraints_for_label_and_property(\"NoConstraintsSetup\", \"name\")\n\n\ndef test_install_label_twice(capsys):\n expected_std_out = (\n \"{code: Neo.ClientError.Schema.EquivalentSchemaRuleAlreadyExists}\"\n )\n install_labels(AbstractNode)\n install_labels(AbstractNode)\n\n install_labels(NodeWithIndex)\n install_labels(NodeWithIndex, quiet=False)\n captured = capsys.readouterr()\n assert expected_std_out in captured.out\n\n install_labels(NodeWithConstraint)\n install_labels(NodeWithConstraint, quiet=False)\n captured = capsys.readouterr()\n assert expected_std_out in captured.out\n\n install_labels(OtherNodeWithRelationship)\n install_labels(OtherNodeWithRelationship, quiet=False)\n captured = capsys.readouterr()\n assert expected_std_out in captured.out\n\n if db.version_is_higher_than(\"5.7\"):\n\n class UniqueIndexRelationship(StructuredRel):\n unique_index_rel_prop = StringProperty(unique_index=True)\n\n class OtherNodeWithUniqueIndexRelationship(StructuredNode):\n has_rel = RelationshipTo(\n NodeWithRelationship, \"UNIQUE_INDEX_REL\", model=UniqueIndexRelationship\n )\n\n install_labels(OtherNodeWithUniqueIndexRelationship)\n install_labels(OtherNodeWithUniqueIndexRelationship, quiet=False)\n captured = capsys.readouterr()\n assert expected_std_out in captured.out\n\n\ndef test_install_labels_db_property():\n stdout = StringIO()\n drop_constraints()\n install_labels(SomeNotUniqueNode, quiet=False, stdout=stdout)\n assert \"id\" in stdout.getvalue()\n # make sure that the id_ constraint doesn't exist\n constraint_names = _drop_constraints_for_label_and_property(\n \"SomeNotUniqueNode\", \"id_\"\n )\n assert constraint_names == []\n # make sure the id constraint exists and can be removed\n _drop_constraints_for_label_and_property(\"SomeNotUniqueNode\", \"id\")\n\n\n@pytest.mark.skipif(db.version_is_higher_than(\"5.7\"), reason=\"Not supported before 5.7\")\ndef test_relationship_unique_index_not_supported():\n class UniqueIndexRelationship(StructuredRel):\n name = StringProperty(unique_index=True)\n\n class TargetNodeForUniqueIndexRelationship(StructuredNode):\n pass\n\n with pytest.raises(\n FeatureNotSupported, match=r\".*Please upgrade to Neo4j 5.7 or higher\"\n ):\n\n class NodeWithUniqueIndexRelationship(StructuredNode):\n has_rel = RelationshipTo(\n TargetNodeForUniqueIndexRelationship,\n \"UNIQUE_INDEX_REL\",\n model=UniqueIndexRelationship,\n )\n\n\n@pytest.mark.skipif(not db.version_is_higher_than(\"5.7\"), reason=\"Supported from 5.7\")\ndef test_relationship_unique_index():\n class UniqueIndexRelationshipBis(StructuredRel):\n name = StringProperty(unique_index=True)\n\n class TargetNodeForUniqueIndexRelationship(StructuredNode):\n pass\n\n class NodeWithUniqueIndexRelationship(StructuredNode):\n has_rel = RelationshipTo(\n TargetNodeForUniqueIndexRelationship,\n \"UNIQUE_INDEX_REL_BIS\",\n model=UniqueIndexRelationshipBis,\n )\n\n install_labels(UniqueIndexRelationshipBis)\n node1 = NodeWithUniqueIndexRelationship().save()\n node2 = TargetNodeForUniqueIndexRelationship().save()\n node3 = TargetNodeForUniqueIndexRelationship().save()\n rel1 = node1.has_rel.connect(node2, {\"name\": \"rel1\"})\n\n with pytest.raises(\n ConstraintValidationFailed,\n match=r\".*already exists with type `UNIQUE_INDEX_REL_BIS` and property `name`.*\",\n ):\n rel2 = node1.has_rel.connect(node3, {\"name\": \"rel1\"})\n\n\ndef _drop_constraints_for_label_and_property(label: str = None, property: str = None):\n results, meta = db.cypher_query(\"SHOW CONSTRAINTS\")\n results_as_dict = [dict(zip(meta, row)) for row in results]\n constraint_names = [\n constraint\n for constraint in results_as_dict\n if constraint[\"labelsOrTypes\"] == label and constraint[\"properties\"] == property\n ]\n for constraint_name in constraint_names:\n db.cypher_query(f\"DROP CONSTRAINT {constraint_name}\")\n\n return constraint_names\n","repo_name":"neo4j-contrib/neomodel","sub_path":"test/test_label_install.py","file_name":"test_label_install.py","file_ext":"py","file_size_in_byte":6145,"program_lang":"python","lang":"en","doc_type":"code","stars":850,"dataset":"github-code","pt":"81"} +{"seq_id":"43166571972","text":"import mysql.connector\n\nclass DbInfo:\n def __init__(self,config):\n self.config=config\n\n def get_data(self,sql,state):\n cnn= mysql.connector.connect(**self.config)\n\n if state==1:\n cursor=cnn.cursor()\n cursor.execute(sql)\n result=cursor.fetchall()\n elif state==2:\n cursor = cnn.cursor()\n cursor.execute(sql)\n cursor.execute('commit')\n result=[]\n cursor.close()\n cnn.close()\n return result\n\n\n\nif __name__ == '__main__':\n from conf import project_path\n from comm.read_conf import ReadConfig\n config = eval(ReadConfig().read_config(project_path.datebae_conf_path, \"DATABASE\", 'config'))\n print(config)\n t=DbInfo(config)\n mobile ='18302123929'\n sql_2 =\"select o.organizes_name from isport_dev.t_organizes o where o.id = (select u.organizes_id from isport_dev.t_user u where u.id = (select s.user_id from isport_dev.t_sms_log s where s.mobile = '\"+mobile+\"' limit 1));\"\n res=t.get_data(sql_2,1)\n print(res)\n\n","repo_name":"fangdan0716/yuntiyu01","sub_path":"comm/do_mysql.py","file_name":"do_mysql.py","file_ext":"py","file_size_in_byte":1063,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"40730462242","text":"#-------------------------------------------------------------------\n# Program to write needed info from image exif to json.\n#-------------------------------------------------------------------\n\nimport json, piexif, pytz, jsons\nfrom copy import deepcopy\nfrom datetime import datetime\nfrom pathlib import Path\n\nPROJ_FOLDER = Path.cwd() / \"application\" / \"projects\" / \"tokaido\"\nIMG_FOLDER = PROJ_FOLDER / \"tools\" / \"journal\" / \"images\"\nPHOTO_JSON = IMG_FOLDER / \"tools\" / \"journal\" / \"photo.json\"\nJSON_FILE = PROJ_FOLDER / \"tools\" / \"data\" / \"photo_data.json\"\n\n\n\nclass Photo(object):\n class Geometry(object):\n def __init__(self):\n self.type = \"Point\"\n self.coordinates = None\n\n class Properties(object):\n def __init__(self):\n self.filename = None\n self.url = None\n self.thumbnail = None\n self.icon = None\n self.date = None\n self.day = None\n\n def __init__(self):\n self.type = \"Feature\"\n self.geometry = self.Geometry()\n self.properties = self.Properties()\n\n\ndef dms_to_deci_deg(dms_coord):\n \"\"\" \n Helper function to convert degrees/minutes/seconds to decimal degree coordinates.\n https://docs.microsoft.com/en-us/office/troubleshoot/excel/convert-degrees-minutes-seconds-angles\n \"\"\"\n degrees = dms_coord[0][0]\n minutes = dms_coord[1][0]\n seconds = dms_coord[2][0]\n\n deci_coord = degrees + (minutes / 60) + (seconds / 100 / 3600)\n return deci_coord\n\n\ndef build_photo_json():\n \"\"\" Crawls through images to extract data and generate a json from it. \"\"\" \n\n allowed_extensions = ['.jpg', '.JPG']\n image_list = [item for item in IMG_FOLDER.rglob('**/*') if item.suffix in allowed_extensions]\n collection = {\"type\": \"FeatureCollection\", \"features\": []}\n data_dict = []\n\n with open(JSON_FILE, 'w') as file:\n for image in image_list:\n # Load existing EXIF metadata.\n exif_data = piexif.load(str(image))\n print(\">>> Extracting data from {0}...\".format(image.name))\n\n # Clean up date format.\n tz_JPT = pytz.timezone('Japan')\n raw_exif_time = exif_data['Exif'][piexif.ExifIFD.DateTimeOriginal]\n exif_time = raw_exif_time.decode('ASCII') \n exif_time = datetime.strptime(exif_time, \"%Y:%m:%d %H:%M:%S\")\n exif_time = tz_JPT.localize(exif_time, is_dst=False)\n latitude = dms_to_deci_deg(exif_data['GPS'][2])\n longitude = dms_to_deci_deg(exif_data['GPS'][4])\n\n # Add wanted data.\n photo_data = Photo()\n photo_data.geometry.coordinates = [longitude, latitude]\n photo_data.properties.filename = image.name.strip(\".jpg\") \n photo_data.properties.url = \"https://storage.googleapis.com/jn-portfolio/projects/tokaido/images/\" + image.name\n photo_data.properties.thumbnail = \"https://storage.googleapis.com/jn-portfolio/projects/tokaido/images/thumbs/\" + image.name\n photo_data.properties.icon = \"https://storage.googleapis.com/jn-portfolio/projects/tokaido/images/icons/\" + image.name\n photo_data.properties.date = exif_time.strftime(\"%Y/%m/%d, %H:%M:%S\")\n photo_data.properties.day = exif_time.strftime(\"%Y/%m/%d\")\n\n\n temp_dict = {image.stem: photo_data}\n # dump = json.dumps(temp_dict[image.stem].__dict__)\n dump = temp_dict[image.stem].__dict__\n # data_dict.append(deepcopy(temp_dict))\n data_dict.append(deepcopy(dump))\n # file.write(dump + \"\\n\")\n \n collection[\"features\"] = data_dict\n collectionString = jsons.dumps(collection)\n # json.dump(data_dict, file, indent=2)\n file.write(collectionString)\n file.close()\n\n print(\">>> JSON generated, closing program.\")\n\n\n\nif __name__ == '__main__':\n build_photo_json()","repo_name":"jeanings/jng-portfolio","sub_path":"application/projects/tokaido/tools/photo_json.py","file_name":"photo_json.py","file_ext":"py","file_size_in_byte":3922,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"37712411448","text":"# 807. 保持城市边际线\nfrom typing import List\n\n\nclass Solution:\n def maxIncreaseKeepingSkyline(self, grid: List[List[int]]) -> int:\n row_max = list(map(max, grid))\n col_max = list(map(max, zip(*grid)))\n n = len(grid)\n res = 0\n for i in range(n):\n for j in range(n):\n res += min(row_max[i], col_max[j]) - grid[i][j]\n return res\n\n\ns = Solution()\ngrid = [[3, 0, 8, 4], [2, 4, 5, 7], [9, 2, 6, 3], [0, 3, 1, 0]]\nprint(s.maxIncreaseKeepingSkyline(grid))\n\ngrid = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]\nprint(s.maxIncreaseKeepingSkyline(grid))\n","repo_name":"BruceHi/leetcode","sub_path":"month12-21/maxIncreaseKeepingSkyline.py","file_name":"maxIncreaseKeepingSkyline.py","file_ext":"py","file_size_in_byte":610,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"81"} +{"seq_id":"36406039844","text":"# -*- coding: utf-8 -*-\nimport traceback\nfrom malibu.design import borgish\n\n\n__doc__ = \"\"\"\nmalibu.command.module\n---------------------\n\nA relatively self-contained system for loading and creating command \"modules\"\nfor a CLI-style script.\n\nA command module must extend the :class:`~malibu.command.module.CommandModule`\nand set up the class as such:\n\n.. code-block:: python\n\n from malibu.command import command_module, module\n\n @command_module(\n name = \"example\",\n depends = []\n )\n class ExampleModule(module.CommandModule):\n\n def __init__(self, loader):\n\n super(ExampleModule, self).__init__()\n self.__loader = loader\n\n self.register_subcommand(\"help\", self.show_help)\n\n def show_help(self, *args, **kw):\n \\\"\\\"\\\" example:help []\n\n Does something.\n \\\"\\\"\\\"\n\n if \"args\" in kw:\n argparser = kw[\"args\"]\n else:\n argparser = self.__loader.get_argument_parser()\n\n pass # Do stuff...\n\n\nAfter all modules are implemented, use something similar to the following in\na console entry point:\n\n.. code-block:: python\n\n from malibu import command\n from malibu.util import args\n\n argparser = args.ArgumentParser.from_argv()\n # Set up argparser params, mappings, etc here.\n\n modloader = module.CommandModuleLoader(argparser)\n\n mods = command.get_command_modules(package = __package__)\n # Or replace __package__ with your cmd module package path\n modloader.register_modules(mods.values())\n modloader.instantiate_modules()\n\n argparser.parse()\n\n modloader.parse_command(\n argparser.parameters[1], # module base\n *argparser.parameters[1:], # subcommand and args\n args = argparser)\n\n.. autoclass:: CommandModuleLoader\n :members:\n\n.. autoclass:: CommandModule\n :members:\n\n.. autoexception:: CommandModuleException\n :members:\n\"\"\"\n\n\nclass CommandModuleLoader(borgish.SharedState):\n\n def __init__(self, argparser, *args, **kw):\n \"\"\" Initializes a ModuleLoader object with a list for modules and\n sets the static __instance so the object is always accessible.\n \"\"\"\n\n super(CommandModuleLoader, self).__init__(*args, **kw)\n\n if \"state\" not in kw:\n self.__modules = []\n self.__modclasses = []\n\n self.__argparser = argparser\n\n def register_module(self, cls):\n \"\"\" Registers a single module in the modloader list.\n\n Checks if any module instances in the module list\n and raises if an instance already exists.\n\n Otherwise, the module is instantiated, appended,\n and returned.\n \"\"\"\n\n instances = filter(lambda mod: isinstance(mod, cls), self.__modules)\n if True in instances:\n raise CommandModuleException(\"Cannot re-register module %s\" %\n (cls.__name__))\n\n if cls in self.__modclasses:\n raise CommandModuleException(\"Cannot re-register module %s\" %\n (cls.__name__))\n\n self.__modclasses.append(cls)\n\n def register_modules(self, clslist):\n \"\"\" Registers a list of modules through subsequent calls to\n register_module(). Returns the list of instantiated\n modules.\n \"\"\"\n\n [self.register_module(module) for module in clslist]\n\n def instantiate_modules(self, clslist=[]):\n \"\"\" Instantiates all module classes that are registered.\n ** Might perform dependency lookup as well.\n \"\"\"\n\n deferred = []\n\n if clslist == []:\n clslist = self.__modclasses\n\n for cls in clslist:\n for dep in cls.depend_modules:\n if self.get_module_by_base(dep) is None:\n deferred.append(cls)\n break\n if cls in deferred:\n continue\n else:\n self.__modules.append(cls(self))\n\n if len(deferred) != 0:\n self.instantiate_modules(deferred)\n\n def deinit_modules(self):\n \"\"\" Runs __deinit__ on all registered modules.\n \"\"\"\n\n for module in self.__modules:\n module.__deinit__()\n\n def get_argument_parser(self):\n \"\"\" Returns the argument parser that will be passed into\n functions that are called by the loader as command line\n parameters.\n Allows modules to access the parser during instantiation\n to change param modules, add help text, register aliases,\n etc.\n \"\"\"\n\n return self.__argparser\n\n def get_module_by_base(self, modbase):\n \"\"\" Returns a module instance by the module's base name.\n Returns None if the named instance does not exist.\n \"\"\"\n\n for module in self.__modules:\n if module.get_base().lower() == modbase.lower():\n return module\n\n return None\n\n @property\n def modules(self):\n \"\"\" Returns the list of modules.\n \"\"\"\n\n return self.__modules\n\n def deregister_module(self, obj):\n \"\"\" Removes a module instance from the list of registered\n modules.\n \"\"\"\n\n if obj not in self.__modules:\n return None\n\n return self.__modules.remove(obj)\n\n def parse_command(self, command, *args, **kw):\n \"\"\" Process a command and fire the function for the matching\n command and subcommand. Returns the function execution\n result, if any.\n \"\"\"\n\n try:\n command, subcommand = command.split(':')\n except:\n command, subcommand = ['help', 'show']\n for module in self.__modules:\n if not module.is_command(command):\n continue\n if (not module.has_subcommand(subcommand) and not\n module.has_alias(subcommand)):\n\n continue\n try:\n result = module.execute_subcommand(subcommand, *args, **kw)\n return result\n except:\n traceback.print_exc()\n raise CommandModuleException(\n \"Exception occurred while executing a command: \"\n \"[command=%s subcommand=%s args=%s kw=%s]\" % (\n command, subcommand, args, kw))\n\n\nclass CommandModule(object):\n \"\"\" Module superclass. Abstracts away some parts of\n a command module to make implementation simpler.\n Should only be inherited, never instantiated by itself.\n \"\"\"\n\n def __init__(self, base=None):\n \"\"\" Initializes a Module object with the command base,\n maps, and help dictionary.\n \"\"\"\n\n self.__command_base = base\n\n self.__command_map = {}\n self.__command_alias_map = {}\n\n self.__command_help = {}\n\n def __deinit__(self):\n \"\"\" Used during \"system\" shutdown. Perform clean up of\n module data and close any open parts of the system\n that should be properly deinitialized.\n \"\"\"\n\n pass\n\n def is_command(self, command):\n \"\"\" Simple boolean-returning method used during command\n parsing.\n \"\"\"\n\n return command == self.get_base()\n\n def has_subcommand(self, subcommand):\n \"\"\" Boolean-returning method for if this Module\n has registered a specific subcommand.\n \"\"\"\n\n return subcommand in self.__command_map.keys()\n\n def has_alias(self, alias):\n \"\"\" Boolean-returning method for if this Module\n has registered a specific alias.\n \"\"\"\n\n return alias in self.__command_alias_map.keys()\n\n def resolve_alias(self, alias):\n \"\"\" Resolves an alias to a subcommand and returns\n the subcommand.\n \"\"\"\n\n try:\n return self.__command_alias_map[alias]\n except:\n return None\n\n def get_base(self):\n \"\"\" Returns the command base.\n \"\"\"\n\n if self.__command_base:\n return self.__command_base\n elif self.__class__.BASE_NAME:\n return self.__class__.BASE_NAME\n\n def get_help(self):\n \"\"\" Returns the help dictionary for this\n module.\n \"\"\"\n\n return self.__command_help\n\n def register_subcommand(self, subcommand, function, aliases=[]):\n \"\"\" Registers a subcommand and its help in\n the internal maps. Updates aliases, subcommands, etc.\n \"\"\"\n\n if subcommand in self.__command_map:\n raise CommandModuleException(\"Subcommand is already registered\")\n else:\n self.__command_map.update({subcommand: function})\n if not function.__doc__:\n self.__command_help.update({subcommand: None})\n else:\n self.__command_help.update({\n subcommand:\n '\\n'.join(\n [line.strip() for line in function.__doc__.splitlines()\n if line.strip() is not '']\n )\n })\n\n for alias in aliases:\n if alias in self.__command_alias_map:\n raise CommandModuleException(\n \"Alias is already registered for subcommand %s\" %\n (subcommand))\n else:\n self.__command_alias_map.update({alias: subcommand})\n\n def unregister_subcommand(self, subcommand):\n \"\"\" Removes a subcommand, all aliases, and all help\n from the internal maps.\n \"\"\"\n\n if subcommand not in self.__command_map:\n raise CommandModuleException(\n \"Tried to remove nonexistent subcommand %s\" %\n (subcommand))\n\n self.__command_map.pop(subcommand)\n\n remove_aliases = []\n for alias, sub in self.__command_alias_map.items():\n if sub == subcommand:\n remove_aliases.append(alias)\n\n [self.__command_alias_map.pop(alias) for alias in remove_aliases]\n\n def execute_subcommand(self, subcommand, *args, **kw):\n \"\"\" Attempts to fire the subcommand with arguments,\n and keywords, may throw CommandModuleException.\n \"\"\"\n\n if subcommand not in self.__command_map:\n if subcommand not in self.__command_alias_map:\n raise CommandModuleException(\n \"Tried to execute unknown subcommand %s\" %\n (subcommand))\n else:\n subcommand = self.resolve_alias(subcommand)\n\n try:\n # If this doesn't work, we've actually tried to execute an unknown\n # subcommand.\n func = self.__command_map[subcommand]\n return func(*args, **kw)\n except IndexError:\n raise CommandModuleException(\n \"Tried to execute unknown subcommand/alias %s\" %\n (subcommand))\n\n\nclass CommandModuleException(Exception):\n \"\"\" Super special exception for modules.\n \"\"\"\n\n def __init__(self, value):\n\n Exception.__init__(self)\n\n self.value = value\n\n def __str__(self):\n\n return repr(self.value)\n","repo_name":"pirogoeth/malibu","sub_path":"src/malibu/command/module.py","file_name":"module.py","file_ext":"py","file_size_in_byte":11230,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"23077227037","text":"\"\"\"rename users to authors\n\nRevision ID: 13e21a0c92b6\nRevises: 7171cb764ba9\nCreate Date: 2023-03-22 18:56:30.198434\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\nfrom sqlalchemy.dialects import mysql\n\n# revision identifiers, used by Alembic.\nrevision = '13e21a0c92b6'\ndown_revision = '7171cb764ba9'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade() -> None:\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_table('authors',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('fullname', sa.String(length=50), nullable=True),\n sa.Column('lastname', sa.String(length=50), nullable=True),\n sa.Column('nickname', sa.String(length=50), nullable=False),\n sa.Column('email', sa.String(length=50), nullable=False),\n sa.Column('registration_date', sa.DateTime(), nullable=True),\n sa.PrimaryKeyConstraint('id'),\n sa.UniqueConstraint('email'),\n sa.UniqueConstraint('nickname')\n )\n op.drop_index('email', table_name='users')\n op.drop_index('nickname', table_name='users')\n op.drop_table('users')\n # ### end Alembic commands ###\n\n\ndef upgrade() -> None:\n op.rename_table('users', 'authors')\n\n\ndef downgrade() -> None:\n op.rename_table('authors', 'users')\n","repo_name":"WojciechStancel/portal","sub_path":"alembic/versions/13e21a0c92b6_rename_users_to_authors.py","file_name":"13e21a0c92b6_rename_users_to_authors.py","file_ext":"py","file_size_in_byte":1240,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"4749931546","text":"import os\nimport subprocess\nimport database.general\nfrom ftplib import FTP\nfrom PySide2.QtWidgets import QDialog, QButtonGroup, QDialogButtonBox, QProgressDialog\nfrom PySide2.QtCore import QThreadPool\n\nfrom gui.ui.ui_releasedialog import Ui_Dialog\nfrom database.credentials import file_host, file_port, file_password, file_username\nfrom database.linkedin import LinkedInAccount\n\nfrom common.threading import Task\nfrom common.version import uploadInstaller, getCurrentVersion, getCommitMessagesSince, setVersion, addVersionTagToLastCommit\n\nversionFile = os.path.abspath('version.txt')\nchangeLogFile = os.path.abspath('changelog.txt')\n\n\nclass ReleaseDialog(QDialog):\n\n def __init__(self, parent=None):\n QDialog.__init__(self, parent)\n\n self.ui = Ui_Dialog()\n self.ui.setupUi(self)\n\n self.typeGroup = QButtonGroup(self)\n self.typeGroup.setExclusive(True)\n self.typeGroup.addButton(self.ui.majorReleaseButton)\n self.typeGroup.addButton(self.ui.minorReleaseButton)\n self.typeGroup.addButton(self.ui.patchButton)\n self.typeGroup.buttonClicked.connect(self.updateTargetRelease)\n\n self.current_version = getCurrentVersion()\n self.target_version = self.current_version\n self.ui.currentVersionLabel.setText(str(self.current_version))\n self.updateTargetRelease()\n\n self.suggestChangeLog()\n\n # Check to make sure everything is committed\n status = subprocess.check_output(['git', 'status'])\n if b'nothing to commit, working tree clean' in status:\n self.ui.warningLabel.hide()\n else:\n self.ui.warningLabel.show()\n self.ui.warningLabel.setText(\"WARNING: Detected uncommitted changes. Please commit all files and resart this program.\")\n\n def suggestChangeLog(self):\n repoDir = os.path.join('..', '.git')\n commitMessages = getCommitMessagesSince(repoDir, self.current_version)\n separator = '-'*50 + '\\n'\n self.ui.changeLogEdit.setPlainText(separator.join(commitMessages))\n\n def updateTargetRelease(self):\n if self.ui.majorReleaseButton.isChecked():\n tv = self.current_version.next_major()\n elif self.ui.minorReleaseButton.isChecked():\n tv = self.current_version.next_minor()\n elif self.ui.patchButton.isChecked():\n tv = self.current_version.next_patch()\n else:\n tv = self.current_version\n\n self.target_version = tv\n self.ui.targetVersionLabel.setText(str(self.target_version))\n\n if self.current_version == self.target_version:\n enable = False\n else:\n enable = True\n\n self.ui.buttonBox.button(QDialogButtonBox.Ok).setEnabled(enable)\n\n def accept(self):\n self.ui.buttonBox.button(QDialogButtonBox.Ok).setEnabled(False)\n\n setVersion(self.target_version)\n\n try:\n print(\"Building the installer\")\n prog = QProgressDialog(\"Building Installer\", \"Hide\", 0, 0, self)\n prog.show()\n def build_installer():\n os.chdir('../scripts')\n subprocess.check_call(['python', 'build_installer.py'])\n os.chdir('../src/')\n t1 = Task(build_installer)\n t1.finished.connect(prog.close)\n QThreadPool.globalInstance().start(t1)\n prog.exec_()\n\n print(\"Uploading the installer\")\n prog = QProgressDialog(\"Uploading Installer\", \"Hide\", 0, 0, self)\n prog.show()\n t2 = Task(lambda: uploadInstaller(self.target_version))\n t2.finished.connect(prog.close)\n QThreadPool.globalInstance().start(t2)\n prog.exec_()\n\n print(f\"Tagging the current commit with v{str(self.target_version)}\")\n addVersionTagToLastCommit(os.path.join('..', '.git'), self.target_version, f\"Release v{self.target_version}\")\n\n print(\"Adding version record to the database\")\n # Set all other versions to not active.\n for version in database.general.Session.query(database.general.Version).all():\n version.active = None\n # Create new active version.\n v = database.general.Version(semantic_id=str(self.target_version), change_log=self.ui.changeLogEdit.toPlainText(), active=True)\n database.general.Session.add(v)\n database.general.Session.commit()\n\n except Exception as e:\n print(f\"Rolling back to {self.current_version}\")\n setVersion(self.current_version)\n raise e\n\n finally:\n self.ui.buttonBox.button(QDialogButtonBox.Ok).setEnabled(True)\n\n super().accept()","repo_name":"smalbadger/social","sub_path":"src/gui/releasedialog.py","file_name":"releasedialog.py","file_ext":"py","file_size_in_byte":4705,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"20434382831","text":"# -*- coding: utf-8 -*-\n\"\"\"Physical constants.\n\nNote : more units available in :\n- scipy.constants\n- sympy.physics.units\n\n\n-------------------------------------------------------------------------------\n\"\"\"\n\n# %% SI units\n\neV = 1.602176634e-19 # J\n\"\"\"float: electron volt (J)\n\nhttps://physics.nist.gov/cgi-bin/cuu/Value?e\n\"\"\"\n\nh = 6.62607015e-34\n\"\"\"float: Planck constant (m2.kg.s-1 = J.s)\n\nhttps://physics.nist.gov/cgi-bin/cuu/Value?h|search_for=planck\"\"\"\n\nk_b = 1.3806490e-23\n\"\"\"float: Boltzmann constant (m2.kg.s-2.K-1)\n\nhttps://physics.nist.gov/cgi-bin/cuu/Value?k|search_for=boltzmann\n\"\"\"\n\nc = 2.99792458e8\n\"\"\"float: light velocity (m/s)\n\nhttps://physics.nist.gov/cgi-bin/cuu/Value?c\n\"\"\"\n\na_0 = 5.29177e-11\n\"\"\"float: First Bohr radius (m)\"\"\"\n\nm_e = 9.1093837015e-31\n\"\"\"float: Electron mass (kg)\n\nhttps://physics.nist.gov/cgi-bin/cuu/Value?me|search_for=electron+mass\"\"\"\n\nRy = 13.605693122994\n\"\"\"float: Rydberg unit of energy (eV)\n\nhttps://physics.nist.gov/cgi-bin/cuu/Value?rydhcev|search_for=rydberg\"\"\"\n\nAv = 6.02214076e23\n\"\"\"float: Avogadro constant (molecules / mol)\n\nhttps://physics.nist.gov/cgi-bin/cuu/Value?na|search_for=avogadro\"\"\"\nNa = Av # just an alias\n\neps_0 = 8.8541878128e-12\n\"\"\"float: Vacuum permittivity (Farads / m)\n\nhttps://physics.nist.gov/cgi-bin/cuu/Value?ep0|search_for=vacuum+permittivity\"\"\"\n\nhc_k = h * c / k_b * 100 #\n\"\"\"float: cm to K conversion (~ 1.44 K/cm), used in Boltzmann factors\"\"\"\n\n\n# %% HITRAN (CGS) units\n\nk_b_CGS = 1.380648813e-16\n\"\"\"float: Boltzmann constant (erg / K)\"\"\"\n\nc_CGS = 2.99792458e10\n\"\"\"float: Light velocity (cm / s)\"\"\"\n\nh_CGS = 6.626196e-27\n\"\"\"float: Planck constant (erg * s)\"\"\"\n","repo_name":"radis/radis","sub_path":"radis/phys/constants.py","file_name":"constants.py","file_ext":"py","file_size_in_byte":1641,"program_lang":"python","lang":"en","doc_type":"code","stars":173,"dataset":"github-code","pt":"81"} +{"seq_id":"74794761545","text":"class Solution:\r\n def maxEnvelopes(self, envelopes: List[List[int]]) -> int:\r\n # dp\r\n envelopes.sort()\r\n \r\n ans = 0\r\n dp = [0] * len(envelopes)\r\n for i in range(len(envelopes)-1, -1, -1):\r\n val = 0\r\n for j in range(i+1, len(envelopes)):\r\n if envelopes[i][0] < envelopes[j][0] and envelopes[i][1] < envelopes[j][1]:\r\n val = max(val, dp[j])\r\n dp[i] = val + 1\r\n ans = max(ans, dp[i])\r\n \r\n return ans","repo_name":"novayo/LeetCode","sub_path":"0354_Russian_Doll_Envelopes/try_1.py","file_name":"try_1.py","file_ext":"py","file_size_in_byte":533,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"81"} +{"seq_id":"8897744857","text":"'''\nHelper functions for data science workshop\n'''\n\nimport os\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport cartopy.crs as ccrs\nimport cartopy.feature as cfeature\nimport seaborn as sns\n \ndef cuteplot(gpd_df, crs=\"Mollweide\", title=None, kdp=False, map_extend=(-27, 45, 33, 73.5), bw=0.2):\n '''\n Function to leverage the cartopy library to plot geographical data\n '''\n # map projections\n proj = {\"PlateCarree\": (\"+proj=eqc +lat_ts=0 +lat_0=0 +lon_0=0 +x_0=0 +y_0=0 +ellps=WGS84 +datum=WGS84 +units=m +no_defs\",\n ccrs.PlateCarree()),\n \"Mollweide\": (\"+proj=moll +lon_0=0 +x_0=0 +y_0=0 +ellps=WGS84 +datum=WGS84 +units=m +no_defs\",\n ccrs.Mollweide()),\n \"Robinson\": (\"+proj=robin +lon_0=0 +x_0=0 +y_0=0 +ellps=WGS84 +datum=WGS84 +units=m +no_defs\",\n ccrs.Robinson()),\n \"UTM32N\": (\"+proj=utm +zone=32 +ellps=intl +units=m +no_defs\",\n ccrs.EuroPP()),\n \"Orthographic\": (\"+proj=ortho\", ccrs.Orthographic())\n }\n\n # plot figure\n fig = plt.figure()\n ax = plt.axes(projection=proj.get(crs)[1])\n # add features\n ax.coastlines(resolution='50m')\n ax.stock_img()\n countries = cfeature.NaturalEarthFeature(category='cultural',\n name='admin_0_boundary_lines_land',\n scale='50m',\n facecolor='none',\n edgecolor=\"black\")\n ax.add_feature(countries)\n\n # extend\n ax.set_extent(map_extend)\n # plot geopandas data frame\n if crs != \"PlateCarree\":\n gpd_df = gpd_df.to_crs(proj.get(crs)[0])\n\n if kdp:\n kdp_germany = sns.kdeplot(gpd_df['Target Longitude'],\n gpd_df['Target Latitude'], # y-axis\n cmap=\"viridis\",\n shade=True,\n shade_lowest=False,\n bw=bw,\n transform = ccrs.PlateCarree()\n )\n kdp_germany.plot()\n else:\n gpd_df.plot(ax=ax, marker='o', color='red',\n markersize=5, alpha=0.01)\n # add gridlines\n ax.gridlines()\n\n if title is not None:\n ax.set_title(title, size=16)\n plt.tight_layout()\n\n","repo_name":"eotp/python-FU-class","sub_path":"05-2023-05-26/src/helper_funcs.py","file_name":"helper_funcs.py","file_ext":"py","file_size_in_byte":2476,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"81"} +{"seq_id":"9648652802","text":"import statistics as s\nimport random\nfrom src.utils.utils import isPrime\n\n\nclass ConservativeCountSketch(object):\n def __init__(self, h, w):\n self.num_hash = h\n self.bucket_size = w\n self.countsketch = [[0 for i in range(self.bucket_size)] for j in range(h)]\n self.first_nums = [random.randint(1, 1000) for i in range(self.num_hash)]\n self.second_nums = [random.randint(1, 1000) for i in range(self.num_hash)]\n self.sign_firsts = [random.randint(1, 1000) for i in range(self.num_hash)]\n self.sign_seconds = [random.randint(1, 1000) for i in range(self.num_hash)]\n print(\"first nums {} second nums {} sign firsts {} sign seconds {}\".format(self.first_nums, self.second_nums,\n self.sign_firsts, self.sign_seconds))\n self.ps = []\n self.sign_ps = []\n for i in range(self.num_hash):\n a = random.randint(self.bucket_size + 1, self.bucket_size + 3000)\n while not isPrime(a):\n a = random.randint(self.bucket_size + 1, self.bucket_size + 3000)\n self.ps.append(a)\n b = random.randint(self.bucket_size + 1, self.bucket_size + 3000)\n while not isPrime(b):\n b = random.randint(self.bucket_size + 1, self.bucket_size + 3000)\n self.sign_ps.append(b)\n print(\"sign ps {} ps {}\".format(self.sign_ps, self.ps))\n for a, b, p in zip(self.first_nums, self.second_nums, self.ps):\n print(\"zip results a b p {} {} {}\".format(a, b, p))\n\n first_hash_function = lambda number: ((self.first_nums[0] * number + self.second_nums[0]) % self.ps[0]) % w\n second_hash_function = lambda number: ((self.first_nums[1] * number + self.second_nums[1]) % self.ps[1]) % w\n third_hash_function = lambda number: ((self.first_nums[2] * number + self.second_nums[2]) % self.ps[2]) % w\n self.hashes = [first_hash_function, second_hash_function, third_hash_function]\n first_sign_function = lambda number: 1 if ((self.sign_firsts[0] * number + self.sign_seconds[0]) % self.sign_ps[\n 0] % 2) == 0 else -1\n second_sign_function = lambda number: 1 if ((self.sign_firsts[1] * number + self.sign_seconds[1]) %\n self.sign_ps[1] % 2) == 0 else 1\n third_sign_function = lambda number: 1 if ((self.sign_firsts[2] * number + self.sign_seconds[2]) % self.sign_ps[\n 2] % 2) == 0 else -1\n self.signhashes = [first_sign_function, second_sign_function, third_sign_function]\n\n def get_hash_values(self, number):\n return [(i, self.first_nums[i], self.second_nums[i], self.hashes[i](number)) for i in range(len(self.hashes))]\n\n def update(self, number, value):\n median_value = self.query(number)\n for i in range(self.num_hash):\n if value > 0:\n if self.countsketch[i][self.hashes[i](number)]*self.signhashes[i](number) <= median_value:\n self.countsketch[i][self.hashes[i](number)] += self.signhashes[i](number) * value\n else:\n if self.countsketch[i][self.hashes[i](number)]*self.signhashes[i](number) >= median_value:\n self.countsketch[i][self.hashes[i](number)] += self.signhashes[i](number) * value\n return self.query(number)\n\n def print_cms(self):\n print(self.countsketch)\n\n def query(self, number):\n return s.median(\n [self.countsketch[i][self.hashes[i](number)] * self.signhashes[i](number) for i in range(self.num_hash)])\n\n\nif __name__ == '__main__':\n cms = ConservativeCountSketch(3, 10)\n print(cms.get_hash_values(9))\n cms.update(8,10)\n # cms.update(-8)\n cms.update(8,8)\n # cms.update(-8)\n cms.update(8,7)\n # cms.update(-5)\n cms.update(5,7)\n cms.update(8, -2)\n cms.update(6, -20)\n cms.update(6, 15)\n print(\"query {} {}\".format(8, cms.query(8)))\n print(\"query {} {}\".format(5, cms.query(5)))\n print(\"query {} {}\".format(6, cms.query(6)))\n cms.print_cms()\n","repo_name":"neerajsharma9195/count-sketch-feature-selection","sub_path":"src/sketches/conservative_count_sketch.py","file_name":"conservative_count_sketch.py","file_ext":"py","file_size_in_byte":4109,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"26524663704","text":"\"\"\"\nRuns the Huggingface BertForSequenceClassification model using the Lazy Tensor Core with the TorchScript backend.\n\nRequirements to run example:\n- `transformers` Python package by HuggingFace\n- `lazy_tensor_core` Python package\n For information on how to obtain the `lazy_tensor_core` Python package,\n see here:\n\n https://github.com/pytorch/pytorch/blob/lazy_tensor_staging/lazy_tensor_core/QUICKSTART.md\n\nTo run the example, make sure `/path/to/pytorch/lazy_tensor_core` is in your\nPYTHONPATH. Then, run\n\n python lazytensor_bert_example.py\n\nThe output of this example can be found in\n `lazytensor_bert_example_output.txt`\n\nMost of the code in this example was barrowed from\n https://github.com/ramiro050/lazy-tensor-samples/blob/main/lazytensor_resnet18_example.py\n https://github.com/llvm/torch-mlir/blob/main/build_tools/torchscript_e2e_heavydep_tests/minilm_sequence_classification.py\n\"\"\"\n\nimport torch\nimport lazy_tensor_core as ltc\nfrom lazy_tensor_core.debug import metrics\n\nfrom torch._C import CompilationUnit\nfrom torch_mlir_e2e_test.linalg_on_tensors_backends.refbackend \\\n import RefBackendLinalgOnTensorsBackend\nfrom torch_mlir.passmanager import PassManager\n\nfrom utils.annotator import Annotation\nfrom utils.torch_mlir_types import TorchTensorType\n# from lazytensor.builder import build_module\n\nltc._LAZYC._ltc_init_ts_backend()\n\nDEVICE = 'lazy'\n\n# Initialize HuggingFace transformers\nfrom transformers import BertTokenizer, BertForSequenceClassification\n\ntokenizer = BertTokenizer.from_pretrained(\"bert-base-uncased\")\n\ndef _prepare_sentence_tokens(sentence: str):\n return torch.tensor([tokenizer.encode(sentence)])\n\nclass HFBertModule(torch.nn.Module):\n def __init__(self):\n super().__init__()\n self.bert = BertForSequenceClassification.from_pretrained(\"bert-base-uncased\", \n num_labels=\n 2, # The number of output labels--2 for binary classification.\n output_attentions=\n False, # Whether the model returns attentions weights.\n output_hidden_states=\n False, # Whether the model returns all hidden-states.\n torchscript=True).to(DEVICE)\n self.bert.eval()\n\n # @export\n # @annotate_args([\n # None,\n # ([-1, -1], torch.int64, True),\n # ])\n def forward(self, tokens):\n return self.bert.forward(tokens)[0]\n\n\ndef main():\n\n # Create dummy text input\n test_input = _prepare_sentence_tokens(\"this project is very interesting\").to(DEVICE)\n\n bert_module = HFBertModule()\n print('Running bert.forward...')\n result = bert_module.forward(test_input)\n\n print('\\nMetrics report:')\n print(metrics.metrics_report())\n graph_str = ltc._LAZYC._get_ltc_tensors_backend([bert_module.forward(test_input)])\n print(graph_str)\n graph = torch._C.parse_ir(graph_str)\n\n\n # Create a torch.jit.ScriptFunction out of the graph\n cu = CompilationUnit()\n func_name = 'my_method'\n script_function = cu.create_function(func_name, graph)\n\nif __name__ == '__main__':\n main()\n","repo_name":"erwei-xilinx/lazy-tensor-bert-example","sub_path":"lazytensor_bert_example.py","file_name":"lazytensor_bert_example.py","file_ext":"py","file_size_in_byte":3062,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"12782858060","text":"'''\nEditDistanceKernel -- Kernel Methods for Machine Learning 2017-2018 -- RATNAMOGAN Pirashanth -- SAYEM Othmane\nThis file contains all the tools in order to use the Edit Distance Kernel (Neuhaus et al., 2006)\n'''\n\n\nimport numpy as np\nfrom multiprocessing import Pool\n\ndef LevenshteinDistance(str1,str2):\n '''\n Compute the edit distance between str1 and str2\n Param: @(str1): (str) string 1 for the comparison\n @(str2): (str) string 2 for the comparison\n Return (int) distance\n '''\n len_s1 = len(str1) +1\n len_s2 = len(str2) +1\n m = np.zeros((len_s1,len_s2))\n for i in range(len_s1):\n m[i,0] = i\n \n for j in range(len_s2):\n m[0,j] = j\n \n for i in range(1,len_s1):\n for j in range(1,len_s2):\n if str1[i-1]==str2[j-1]:\n m[i,j]= min(m[i-1,j]+1,m[i,j-1]+1,m[i-1,j-1])\n else:\n m[i,j] =min(m[i-1,j]+1,m[i,j-1]+1,m[i-1,j-1]+1)\n return m[-1,-1]\n \n\n\n\n\ndef compute_kernel_edit(str1,str2,str0):\n \"\"\" \n Calculate the application of the edit distance rk on str1 and str1 given the root str0\n Param: @str1: (string) data 1 to use to feed the kernel computation\n @str2: (string) data 2 to use to feed the kernel computation\n @str0: (string) root used to compute the kernel function\n \"\"\"\n d_xx0 = LevenshteinDistance(str1,str0)\n d_xxp = LevenshteinDistance(str1,str2)\n d_x0xp = LevenshteinDistance(str0,str2)\n \n return 0.5*(d_xx0**2+d_x0xp**2 - d_xxp**2)\n\ncompute_diag_lev = lambda X,x_0,i: compute_kernel_edit(X[i], X[i],x_0)\ncompute_element_kernel_square_lev = lambda X1,x_0,sim_docs_kernel_value,i,j: compute_kernel_edit(X1[i],X1[j],x_0)/(sim_docs_kernel_value[i] *sim_docs_kernel_value[j])**0.5\ncompute_element_kernel_lev = lambda X1,X2,x_0,sim_docs_kernel_value,i,j: compute_kernel_edit(X1[i], X2[j],x_0)/(sim_docs_kernel_value[1][i] *sim_docs_kernel_value[2][j])**0.5\n\n\n\n'''\nIn order to allow the use of parallelization and the \nmultiprocessing library we have computed some really basic functions using classes\nThe next few functions must be easy to understand\n'''\nclass compute_diag_lev_copy(object):\n def __init__(self, X,x_0):\n self.X = X\n self.x_0 = x_0\n \n def __call__(self, i):\n return compute_diag_lev(self.X,self.x_0,i)\n\nclass compute_element_i_lev(object):\n def __init__(self, X,x_0,sim_docs_kernel_value,i):\n self.X = X\n self.sim_docs_kernel_value = sim_docs_kernel_value\n self.i = i\n self.x_0 = x_0\n def __call__(self, j):\n return compute_element_kernel_square_lev(self.X,self.x_0,self.sim_docs_kernel_value,self.i,j)\n\n\n\nclass compute_element_i_general_lev(object):\n def __init__(self, X,X_p,x_0,sim_docs_kernel_value,i):\n self.X = X\n self.X_p = X_p\n self.sim_docs_kernel_value = sim_docs_kernel_value\n self.i = i\n self.x_0 = x_0\n def __call__(self, j):\n return compute_element_kernel_lev(self.X,self.X_p,self.x_0,self.sim_docs_kernel_value,self.i,j)\n\n\ndef kernel_Edit_distance(X1,x_0,X2=[],n_proc=4):\n '''\n This function computes the edit distance kernel gram matrix. \n Param: @X1: (list) list of strings in the train set\n @X2: (list) list of strings in the test set (if empty compute the gram matrix for training else compute\n the gram matrix for testing)\n @n_proc: (int) allows to use more processor in order to compute the gram matrix quickly\n Return: Edit distance Gram matrix\n '''\n pool = Pool(processes= n_proc)\n \n len_X2= len(X2)\n len_X1 = len(X1)\n sim_docs_kernel_value = {}\n if len_X2 ==0:\n # numpy array of Gram matrix\n gram_matrix = np.zeros((len_X1, len_X1), dtype=np.float32)\n sim_docs_kernel_value = pool.map(compute_diag_lev_copy(X1,x_0),range(len_X1))\n for i in range(len_X1):\n gram_matrix[i, i:len_X1] = pool.map(compute_element_i_lev(X1,x_0,sim_docs_kernel_value,i),range(i,len_X1))\n\n gram_matrix = gram_matrix+gram_matrix.T - np.diag(np.diag(gram_matrix))\n \n pool.close()\n #calculate Gram matrix\n return gram_matrix\n else:\n gram_matrix = np.zeros((len_X1, len_X2), dtype=np.float32)\n\n sim_docs_kernel_value[1] = {}\n sim_docs_kernel_value[2] = {}\n #store K(s,s) values in dictionary to avoid recalculations\n sim_docs_kernel_value[1] = pool.map(compute_diag_lev_copy(X1,x_0),range(len_X1))\n sim_docs_kernel_value[2] = pool.map(compute_diag_lev_copy(X2,x_0),range(len_X2))\n\n for i in range(len_X1):\n gram_matrix[i, :] = pool.map(compute_element_i_general_lev(X1,X2,x_0,sim_docs_kernel_value,i),range(len_X2))\n \n pool.close()\n\n return gram_matrix\n","repo_name":"PirashanthR/Kernel-Methods-For-Machine-Learning-MVA-Challenge","sub_path":"Kernel/EditDistanceKernel.py","file_name":"EditDistanceKernel.py","file_ext":"py","file_size_in_byte":4753,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"81"} +{"seq_id":"6143574822","text":"import os, re\nfrom subprocess import Popen, PIPE\n\nos.chdir(os.path.dirname(os.path.realpath(__file__)))\n\noutput = Popen([\"git\", \"log\", \"-1\"], stdout=PIPE)\nresponse = output.communicate()[0].decode('utf-8')\ncommit = re.findall(\"commit ([^\\n]+)\\n\", response)[0]\n\nwith open(\"/var/www/html/data/commit.txt\", \"w\") as fout:\n\tfout.write(commit)","repo_name":"AntoineMeler/Paraglidable","sub_path":"scripts/cron_tasks/set_current_commit.py","file_name":"set_current_commit.py","file_ext":"py","file_size_in_byte":337,"program_lang":"python","lang":"en","doc_type":"code","stars":75,"dataset":"github-code","pt":"81"} +{"seq_id":"31355755834","text":"import tkinter as tk\n\ncell_width = 10\ncell_height = 10\n\nhor_cells = 106\nver_cells = 17\n\ncanvas_height = cell_height * ver_cells\ncanvas_width = cell_width * hor_cells\n\n#drawing_matrix = [[None for j in range(ver_cells)] for i in range(hor_cells)]\ndrawing_matrix = [[None for j in range(hor_cells)] for i in range(ver_cells)]\n\ndef toggle_cell(event):\n x = event.x\n y = event.y\n\n chosen_cell_x = int(x//cell_width)\n chosen_cell_y = int(y//cell_height)\n\n #print(\"Cell: \" + str(chosen_cell_x) + \", \" + str(chosen_cell_y))\n #print(\"Coords: \" + str(event.x) + \", \" + str(event.y))\n \n if(not drawing_matrix[chosen_cell_y][chosen_cell_x]):\n drawing_matrix[chosen_cell_y][chosen_cell_x] = canvas.create_rectangle(cell_width * chosen_cell_x,\n cell_height * chosen_cell_y,\n cell_width * (chosen_cell_x + 1),\n cell_height * (chosen_cell_y + 1),\n fill=\"black\")\n else:\n canvas.delete(drawing_matrix[chosen_cell_y][chosen_cell_x])\n drawing_matrix[chosen_cell_y][chosen_cell_x] = None\n\n \n\ndef clear_drawing_matrix():\n for i in range(hor_cells):\n for j in range(ver_cells):\n canvas.delete(drawing_matrix[j][i])\n drawing_matrix[j][i] = None\n\n\ndef get_k():\n total_k_bin = ''\n for i in range(hor_cells):\n #print(len(drawing_matrix[0]))\n column = [1 if row[i] != None else 0 for row in drawing_matrix]\n #column.reverse()\n \n k_part_bin = ''.join([str(digit) for digit in column])\n #print(k_part_bin)\n total_k_bin = k_part_bin + total_k_bin\n\n k_value = int(total_k_bin, 2)*17\n k_textbox.delete(0, 'end')\n k_textbox.insert(0, k_value)\n\n print('K = ' + str(k_value), end='\\n')\n\n'''\ndef draw_k():\n k_value = int(k_textbox.get())\n total_k_bin = bin(k_value)[2:]\n for i in range(hor_cells):\n column = \n'''\n\ntop = tk.Tk()\n\ntext_label = tk.Label(top, text=\"Hello!\")\ntext_label.grid(row = 1, column = 1)\n\n# Canvas\ncanvas = tk.Canvas(top, bg=\"white\", height=canvas_height, width=canvas_width)\ncanvas.grid(row = 2, column = 1, columnspan = 2, padx = 5, pady = 5)\n\ncanvas.bind(\"\", toggle_cell)\n\n\n# K label and textbox\nk_frame = tk.Frame(top)\nk_frame.grid(row = 3, column = 1, padx = 5, pady = 5)\n\nk_label = tk.Label(k_frame, text=\"K=\")\nk_label.pack(side = \"left\")\n\nk_textbox = tk.Entry(k_frame)\nk_textbox.pack(side = \"left\")\n\nk_textbox.text = 'sadfdsf'\n\n# Clear and Get K buttons\nclear_get_frame = tk.Frame(top)\nclear_get_frame.grid(row = 3, column = 2)\n\nclear_button = tk.Button(clear_get_frame, text = \"Clear\", command = clear_drawing_matrix)\nclear_button.pack(side=\"left\", padx = 5, pady = 5)\n\nget_k_button = tk.Button(clear_get_frame, text = \"Get K\", command = get_k)\nget_k_button.pack(side=\"left\", padx = 5, pady = 5)\n\ndraw_k_button = tk.Button(clear_get_frame, text = \"Draw K\")\nget_k_button.pack(side=\"left\", padx = 5, pady = 5)\n\n\ntop.mainloop()\n","repo_name":"Ahmed42/TupperViz","sub_path":"tupper.py","file_name":"tupper.py","file_ext":"py","file_size_in_byte":3205,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"69858999306","text":"# attempt to recreate slurm-able skorch script\n# for a multitask learning setting\n# adapting for E. coli iModulon prediction\n\nimport argparse\nimport torch\nfrom torch import nn\nfrom torch.nn import functional as F\n\nimport altair as alt\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport os\nimport pandas as pd\nimport pickle\nimport random\nimport seaborn as sns\nimport scipy\nimport yaml\n\nfrom sklearn.model_selection import GridSearchCV, RandomizedSearchCV\nfrom scipy.stats import loguniform,uniform\nfrom skmultilearn.model_selection import iterative_train_test_split\nfrom sklearn.metrics import multilabel_confusion_matrix,ConfusionMatrixDisplay,classification_report\n\nfrom skorch import NeuralNetRegressor,NeuralNetClassifier\nfrom skorch.callbacks import EarlyStopping,Checkpoint,GradientNormClipping\nfrom skorch.dataset import Dataset\nfrom skorch.helper import predefined_split\n\n\n# print(\"PRE-DASK\")\n# # atempted DASK stuff?\n# from dask.distributed import Client\n# from joblib import parallel_backend\n# print(\"Post-DASK import\")\n# client = Client('127.0.0.1:8786')\n# print(\"Post-DASK client start\")\n# client.upload_file(\"models.py\")\n# # client.upload_file(\"utils.py\")\n# # client.upload_file(\"torch_utils.py\")\n# print(\"Post-DASK client upload\")\n\nimport utils as u \nimport torch_utils as tu\nimport models as m \n\n\ndef set_seed(seed: int = 42) -> None:\n np.random.seed(seed)\n random.seed(seed)\n torch.manual_seed(seed)\n torch.cuda.manual_seed(seed)\n # When running on the CuDNN backend, two further options must be set\n torch.backends.cudnn.deterministic = True\n torch.backends.cudnn.benchmark = False\n # Set a fixed value for the hash seed\n #os.environ[\"PYTHONHASHSEED\"] = str(seed)\n print(f\"Random seed set as {seed}\")\nset_seed(46)\n\n\nDEVICE = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\nprint(\"Device:\",DEVICE)\n\ndef load_iMod_binarized_data(config):\n # +-----------------+\n # | Load iMod files |\n # +-----------------+\n \n # load file with iModulon data (gene info + M values)\n XY = pd.read_csv(config['imod_info_m'],sep='\\t')\n \n id_col = config['id_col']\n seq_col = config['seq_col']\n loc2seq = dict([(x,z) for (x,z) in XY[['locus_tag','upstream_region']].values])\n\n # get iModulon column labels\n M = pd.read_csv(config['M_matrix'],index_col=0)\n imods = [x.strip() for x in M.columns]\n\n # load binarized version of M matrix\n Mb = pd.read_csv(config['gene_presence_matrix'],index_col=0).astype(int)\n Mb.index.name='locus_tag'\n\n # Convert XY into binarazed version\n XYb = pd.merge(XY.drop(imods,axis=1), Mb.reset_index(),on='locus_tag')\n XYb\n \n # +------------------------+\n # | Filter out small iMods |\n # +------------------------+\n thresh = config['imod_count_thresh']\n XYim = XYb[imods]\n # m binarized count dict\n mbc = dict([(XYim.T.iloc[i].name,sum(XYim.T.iloc[i])) for i in range(XYim.shape[1])])\n imods_filt = [x for x in mbc if mbc[x]>thresh]\n print(f\"num iMods that pass threshold of {thresh}:\",len(imods_filt))\n\n # these iMods seem too small to meaningfully try to predict\n # (some are single-gene iMods)\n imods_exclude = [x for x in mbc if mbc[x]<=thresh]\n print(f\"num iMods filtered out b/c fewer than {thresh+1} genes: {len(imods_exclude)}\")\n\n # drop excluded iMods and keep binary labels\n XY = XYb.drop(imods_exclude,axis=1)\n XY\n\n return XY, loc2seq, imods, imods_filt, \n\ndef get_opts(opts):\n '''\n Given a list of optimizer names as strings, return the torch.optim object.\n (Is there a way to specify the optimizer via string in PyTorch?)\n '''\n optimizers = {\n 'Adam': torch.optim.Adam,\n 'AdamW' : torch.optim.AdamW,\n 'Adagrad' : torch.optim.Adagrad,\n 'RMSprop' : torch.optim.RMSprop,\n 'SGD' : torch.optim.SGD,\n }\n for opt in opts:\n if opt not in optimizers:\n raise ValueError(f\"{opt} optimizer not in list of options. Currently available: {optimizers.keys()}\")\n else:\n return [optimizers[opt] for opt in opts]\n\n\ndef get_params(filename):\n\n with open(filename) as f:\n params = yaml.load(f, Loader=yaml.FullLoader)\n\n params['optimizer'] = get_opts(params['optimizer'])\n \n return params \n\n\ndef setup_config(filename):\n\n with open(filename) as f:\n config = yaml.load(f, Loader=yaml.FullLoader)\n\n config['skorch_params'] = get_params(config['param_file']),\n\n return config\n\n\ndef make_st_skorch_dfs(df,seq_col='seq',target_col='score'):\n '''\n Make basic X,y matrix,vec for skorch fit() loop.\n '''\n seqs = list(df[seq_col].values) \n ohe_seqs = torch.stack([torch.tensor(u.one_hot_encode(x)) for x in seqs])\n\n labels = torch.tensor(list(df[target_col].values)).unsqueeze(1)\n # had to unsqueeze here or else errors later\n \n return ohe_seqs.float(), labels.float()\n\n\ndef make_mt_skorch_dfs(df,seq_col='seq',target_cols=['highCu','noCu']):\n '''\n Make multi-task X,y matrix,vec for skorch fit() loop.\n '''\n seqs = list(df[seq_col].values) \n ohe_seqs = torch.stack([torch.tensor(u.one_hot_encode(x)) for x in seqs])\n\n # number of labels = len(target_cols)\n labels = torch.tensor(list(df[target_cols].values))\n # bad dimension? fixed in model.forward for now\n \n return ohe_seqs.float(), labels.float()\n\n\ndef get_model_choice(choice):\n \n # LINEAR\n if choice == 'LinearDeep':\n return m.DNA_Linear_Deep\n\n # CNN \n elif choice == \"CNN\":\n return m.DNA_CNN\n elif choice == \"2CNN\":\n return m.DNA_2CNN\n\n # CNN Multi\n elif choice == \"2CNN_Multi\":\n return m.DNA_2CNN_Multi\n\n # LSTM\n elif choice == \"LSTM\":\n return m.DNA_LSTM\n\n # CNN-LSTM\n elif choice == \"CNNLSTM\":\n return m.DNA_CNNLSTM\n\n # Kmer \n elif choice == \"Kmer\":\n return m.Kmer_Linear\n\n # 2CNN_2FC\n elif choice == 'DNA_2CNN_2FC_Multi':\n return m.DNA_2CNN_2FC_Multi\n\n\n else:\n choices = ['LinearDeep', 'CNN', '2CNN', 'LSTM','CNNLSTM','Kmer',\n '2CNN_Multi','DNA_2CNN_2FC_Multi'\n ]\n raise ValueError(f\"{choice} model choice not recognized. Options are: {choices}\")\n\n\ndef get_class_counts(ys):\n '''\n Given a list of iMod vector labels, sum the number of\n positive examples for each iModulon\n '''\n y_sum = torch.tensor(np.zeros(ys.shape[1]))\n for ex in ys:\n y_sum += ex\n\n return y_sum\n\n# https://discuss.pytorch.org/t/weights-in-bcewithlogitsloss/27452/11?u=crypdick\ndef get_pos_weights(ys):\n '''\n Determine loss reweighting vector by the inverse of the positive\n examples for each iMod task\n '''\n class_counts = get_class_counts(ys)\n pos_weights = np.ones_like(class_counts)\n neg_counts = [len(ys)-pos_count for pos_count in class_counts] # <-- HERE \n \n for cdx, (pos_count, neg_count) in enumerate(zip(class_counts, neg_counts)):\n #print(f\"{cdx}| pos:{pos_count} neg:{neg_count}\")\n #print(\"val:\", neg_count / (pos_count + 1e-5))\n pos_weights[cdx] = neg_count / (pos_count + 1e-5)\n \n\n return torch.as_tensor(pos_weights, dtype=torch.float)\n\n\ndef quick_loss_plot_simple(data_label_list,out_file,loss_type=\"MSE Loss\",sparse_n=0):\n '''\n For each train/test loss trajectory, plot loss by epoch\n '''\n fig = plt.figure()\n for i,((train_data,test_data),label) in enumerate(data_label_list):\n # plot only 1 in every sparse_n points\n if sparse_n:\n train_data = [x for i,x in enumerate(train_data) if (i%sparse_n==0)]\n test_data = [x for i,x in enumerate(test_data) if (i%sparse_n==0)]\n \n plt.plot(train_data,'--',color=f\"C{i}\", label=f\"{label} Train\")\n plt.plot(test_data,'o-',color=f\"C{i}\", label=f\"{label} Test\",linewidth=3.0)\n \n\n plt.legend()\n plt.ylabel(loss_type)\n plt.xlabel(\"Epoch\")\n plt.legend(bbox_to_anchor=(1,1),loc='upper left')\n plt.savefig(out_file,bbox_inches='tight')\n\ndef parity_plot(model_name,ytrue,ypred, pearson,rigid=False, out_dir=\"out_dir\"):\n \n fig = plt.figure()\n plt.scatter(ytrue, ypred, alpha=0.2)\n \n # y=x line\n xpoints = ypoints = plt.xlim()\n if rigid:\n plt.ylim(min(xpoints),max(xpoints)) \n plt.plot(xpoints, ypoints, linestyle='--', color='k', lw=2, scalex=False, scaley=False)\n\n plt.xlabel(\"Actual Score\",fontsize=14)\n plt.ylabel(\"Predicted Score\",fontsize=14)\n plt.title(f\"{model_name} (pearson:{pearson:.3f})\",fontsize=20)\n plt.savefig(f'{out_dir}/{model_name}_parity_plot.png',bbox_inches='tight')\n\ndef alt_cls_summary2(df):\n heat = alt.Chart(df).mark_rect().encode(\n x=alt.X('imod:O'),\n y=alt.Y('metric:O'),\n color=alt.Color('score:Q',scale=alt.Scale(domain=(0.0,1.0))),\n tooltip=['metric:N','score:Q']\n ).properties(width=600)\n\n support = alt.Chart(df).mark_bar().encode(\n x=alt.X('imod:O',title='',axis=alt.Axis(labels=False)),\n color=alt.Color('support:Q', legend=None,scale=alt.Scale(scheme='greys')),\n y='support:Q',\n tooltip=['support']\n ).properties(width=600,height=50)\n\n return alt.vconcat(support,heat\n ).resolve_scale(color='independent'\n ).configure_concat(\n spacing=0\n )\n\ndef view_cls_report(sk_model,Xs,ys,imods):\n '''\n For a given model and set of X,y examples, save and display \n a summary of the primary classification metrics\n '''\n # get the predictions and classification report\n y_preds = sk_model.predict(Xs)\n cls_rep = classification_report(ys, y_preds,target_names=imods,output_dict=True)\n \n # conver the dict into a df for viewing\n cls_df = pd.DataFrame.from_dict(cls_rep,orient='index')\n cls_df.index.name='imod'\n cls_df = cls_df.reset_index()\n \n # drop the micro/macro average colums\n cls_df = cls_df.drop(cls_df[~cls_df['imod'].isin(imods)].index)\n # convert to int for sorting\n cls_df['imod'] = cls_df['imod'].apply(lambda x: int(x))\n \n # melt the df for altair\n cls_melt = cls_df.melt(\n id_vars=['imod','support'],\n value_vars=['precision','recall','f1-score'],\n var_name='metric',\n value_name='score')\n \n #alt_cls_summary(cls_melt)\n chart = alt_cls_summary2(cls_melt)\n\n return cls_df,chart\n\n# #####################################################\ndef main():\n parser = argparse.ArgumentParser(description='Run hyperparam search with skorch and sklearn.')\n \n # Required args\n parser.add_argument('config_file', help='config file specified as yaml')\n\n args = parser.parse_args()\n\n # +----------------------+\n # | Load data and config |\n # +----------------------+\n config = setup_config(args.config_file)\n id_col = config['id_col']\n seq_col = config['seq_col']\n\n out_dir = config['out_dir']\n if not os.path.isdir(out_dir):\n print(f\"creating dir {out_dir}\")\n os.mkdir(out_dir)\n\n XY, loc2seq, imods_all, target_cols = load_iMod_binarized_data(config)\n # imods_filt are target_cols\n\n print(\"Done Loading.\")\n print(\"Full df shape:\", XY.shape)\n\n # +------------------------+\n # | Multi-task training WF |\n # +------------------------+\n print(f\"Running MULTI task learning for {target_cols}...\")\n X, y = make_mt_skorch_dfs(XY, seq_col=seq_col,target_cols=target_cols)\n print(\"X:\",X.shape)\n print(\"y:\",y.shape)\n\n # use stratified splitting across the tasks\n # (best effort to ensure the train/test/val splits\n # each have some positive examples of each task)\n Xfull_train_strat, yfull_train_strat, Xtest_strat, ytest_strat = iterative_train_test_split(X, y, test_size = 0.2)\n Xtrain_strat, ytrain_strat, Xval_strat, yval_strat = iterative_train_test_split(Xfull_train_strat, yfull_train_strat, test_size = 0.2)\n valid_ds = Dataset(Xval_strat, yval_strat)\n\n # get weights for binary cross entropy loss\n bce_pos_weights = get_pos_weights(y)\n\n # get the input sequence length\n seq_len = len(XY[seq_col].values[0])\n\n model_type = get_model_choice(config['model_type'])\n \n # make skorch object\n net_search = NeuralNetClassifier(\n model_type,\n module__seq_len=seq_len,\n module__n_tasks=y.shape[1],\n max_epochs=config['epochs'],\n #lr=0.001,\n device=DEVICE,#'cuda', # uncomment this to train with CUDA\n verbose=0, # without 0 it prints the every epoch loss\n callbacks=[\n Checkpoint(dirname=out_dir,f_pickle='best_chkpt.pkl'), # load_best=True\n EarlyStopping(patience=config['patience']),\n GradientNormClipping(),\n ],\n train_split=predefined_split(valid_ds),\n criterion=torch.nn.BCEWithLogitsLoss(pos_weight=bce_pos_weights)\n )\n\n # make sklearn search object\n search = RandomizedSearchCV(\n net_search, \n config['skorch_params'], \n n_iter=config['search_iters'], \n scoring=['f1_macro'], \n refit='f1_macro',\n n_jobs=-1, # TODO: set this more explicitly\n cv=3,#cv, \n random_state=1,\n verbose=1\n )\n\n # learn stuff\n #with parallel_backend('dask'):\n print(\"Fitting...\")\n search.fit(Xtrain_strat,ytrain_strat)\n\n # print stuff\n print(search.best_params_)\n print(search.best_estimator_)\n\n print(\"Saving searchCV obj....\")\n # save search obj\n search_dump_file = open(f\"{out_dir}/{config['job_name']}.pkl\",'wb')\n pickle.dump(search, search_dump_file)\n\n # viz stuff\n\n # train/val loss plot\n search_label = [\n (\n (\n search.best_estimator_.history[:, 'train_loss'], \n search.best_estimator_.history[:, 'valid_loss']\n ), \n config['job_name'])\n ]\n loss_plot_filename = f\"{out_dir}/{config['job_name']}_loss_plot.png\"\n quick_loss_plot_simple(search_label,loss_plot_filename,loss_type='BCEWithLogitsLoss')\n\n # results\n res_df = pd.DataFrame(search.cv_results_)\n res_df['opt_name'] = res_df['param_optimizer'].apply(lambda x: x.__name__)\n res_df.to_csv(f\"{out_dir}/{config['job_name']}_skres_df.tsv\",sep='\\t', index=False)\n\n # Create classification reports for full train and test\n cls_full_train_df,full_train_metric_chart = view_cls_report(search.best_estimator_,Xtrain_strat,ytrain_strat,target_cols)\n full_train_metric_chart.save(f\"{out_dir}/best_est_full_train_metric_chart.html\")\n \n cls_test_df,test_metric_chart = view_cls_report(search.best_estimator_,Xtest_strat,ytest_strat,target_cols)\n test_metric_chart.save(f\"{out_dir}/best_est_test_metric_chart.html\")\n\n\n print(\"DONE!\")\n \n\nif __name__ == '__main__':\n main()","repo_name":"erinhwilson/deep-5g-sandbox","sub_path":"skorch4slurm_ec_iMod.py","file_name":"skorch4slurm_ec_iMod.py","file_ext":"py","file_size_in_byte":14683,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"19198596824","text":"from django.urls import path\nfrom . import views\n\nurlpatterns = [\n path('', views.index),\n path('login/', views.login),\n path('login/login_action', views.login_action),\n path('read/', views.read),\n path('profile/', views.profile),\n path('myprofile/', views.myprofile),\n path('edit_profile', views.edit_profile),\n path('add_blog/', views.add_blog),\n path(\"edit_blog/\", views.edit_blog),\n path(\"delete_blog/\", views.delete_blog),\n path(\"comment_blog/\", views.comment_blog),\n path('sign_up/', views.sign_up),\n path('sign_up/sign_up_action', views.sign_up_action),\n path('add_blog/add_blog_action//', views.add_blog_action),\n path('logout/', views.logout),\n path('search/', views.search),\n path('about/', views.about)\n\n]\n","repo_name":"aseel-sm/Blog-MES","sub_path":"mains/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":863,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"81"} +{"seq_id":"30009504901","text":"import sys\n\nfrom xcalar.external.LegacyApi.WorkItem import WorkItemAppSet, WorkItemAppRun, WorkItemAppReap\nfrom xcalar.external.LegacyApi.XcalarApi import XcalarApiStatusException\nfrom xcalar.compute.coretypes.Status.ttypes import StatusT\n\nfrom xcalar.compute.util.utils import XcUtil\n\nfrom xcalar.compute.localtypes.App_pb2 import AppStatusRequest\n\n\nclass App(object):\n NotebookAppName = \"NotebookApp\"\n\n def __init__(self, client):\n self.client = client\n\n def set_py_app(self, name, exec_str):\n workItem = WorkItemAppSet(name, \"Python\", exec_str)\n return self.client._execute(workItem)\n\n def is_app_alive(self, group_id):\n req = AppStatusRequest()\n req.group_id = int(group_id)\n res = self.client._app_service.appStatus(req)\n return res.is_alive\n\n def run_py_app(self, name, is_global, in_str):\n app_group_id = self.run_py_app_async(name, is_global, in_str)\n return self.get_app_result(app_group_id, max_retries=sys.maxsize)\n\n def get_app_result(self,\n app_group_id,\n max_retries=0,\n retry_sleep_timeout=1):\n workItem = WorkItemAppReap(app_group_id)\n retry_xc_codes = XcUtil.RETRY_XC_STATUS_CODES + [\n StatusT.StatusAppInProgress\n ]\n try:\n appOutput = XcUtil.retryer(\n self.client._execute,\n workItem,\n retry_exceptions=[],\n max_retries=max_retries,\n retry_sleep_timeout=retry_sleep_timeout,\n retry_xc_status_codes=retry_xc_codes)\n outStr = appOutput.output.outputResult.appReapOutput.outStr\n errStr = appOutput.output.outputResult.appReapOutput.errStr\n except Exception as e:\n if e.__class__ == XcalarApiStatusException:\n outStr = e.output.appReapOutput.outStr\n errStr = e.output.appReapOutput.errStr\n else:\n raise e\n\n return (outStr, errStr)\n\n # returns groupId of running app\n def run_py_app_async(self, name, is_global, in_str):\n workItem = WorkItemAppRun(name, is_global, in_str)\n outputRun = self.client._execute(workItem)\n\n return str(outputRun.output.outputResult.appRunOutput.appGroupId)\n\n def cancel(self, group_id):\n workItem = WorkItemAppReap(group_id, cancel=True)\n self.client._execute(workItem)\n","repo_name":"varlogtim/xcalar","sub_path":"src/bin/sdk/xdp/xcalar/external/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2445,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"81"} +{"seq_id":"37145590790","text":"import logging\nimport os\nfrom datetime import datetime\nfrom enum import Enum\nfrom math import log10\nfrom typing import Any, Dict, Iterable, List, Optional, Tuple\n\nimport parse\nimport pydeequ\nfrom pydeequ.analyzers import AnalyzerContext\nfrom pyspark.conf import SparkConf\nfrom pyspark.sql import SparkSession\nfrom pyspark.sql.dataframe import DataFrame\nfrom pyspark.sql.types import (\n ArrayType,\n BinaryType,\n BooleanType,\n ByteType,\n DateType,\n DecimalType,\n DoubleType,\n FloatType,\n IntegerType,\n LongType,\n MapType,\n NullType,\n ShortType,\n StringType,\n StructField,\n StructType,\n TimestampType,\n)\nfrom pyspark.sql.utils import AnalysisException\nfrom smart_open import open as smart_open\n\nfrom datahub.emitter.mce_builder import make_data_platform_urn, make_dataset_urn\nfrom datahub.emitter.mcp import MetadataChangeProposalWrapper\nfrom datahub.ingestion.api.common import PipelineContext\nfrom datahub.ingestion.api.decorators import (\n SourceCapability,\n SupportStatus,\n capability,\n config_class,\n platform_name,\n support_status,\n)\nfrom datahub.ingestion.api.source import Source, SourceReport\nfrom datahub.ingestion.api.workunit import MetadataWorkUnit\nfrom datahub.ingestion.source.aws.s3_util import is_s3_uri, make_s3_urn, strip_s3_prefix\nfrom datahub.ingestion.source.data_lake.config import DataLakeSourceConfig\nfrom datahub.ingestion.source.data_lake.profiling import _SingleTableProfiler\nfrom datahub.ingestion.source.data_lake.report import DataLakeSourceReport\nfrom datahub.ingestion.source.schema_inference import avro, csv_tsv, json, parquet\nfrom datahub.metadata.com.linkedin.pegasus2avro.metadata.snapshot import DatasetSnapshot\nfrom datahub.metadata.com.linkedin.pegasus2avro.mxe import MetadataChangeEvent\nfrom datahub.metadata.com.linkedin.pegasus2avro.schema import (\n BooleanTypeClass,\n BytesTypeClass,\n DateTypeClass,\n NullTypeClass,\n NumberTypeClass,\n RecordTypeClass,\n SchemaFieldDataType,\n SchemaMetadata,\n StringTypeClass,\n TimeTypeClass,\n)\nfrom datahub.metadata.schema_classes import (\n ChangeTypeClass,\n DatasetPropertiesClass,\n MapTypeClass,\n OtherSchemaClass,\n)\nfrom datahub.telemetry import stats, telemetry\nfrom datahub.utilities.perf_timer import PerfTimer\n\n# hide annoying debug errors from py4j\nlogging.getLogger(\"py4j\").setLevel(logging.ERROR)\nlogger: logging.Logger = logging.getLogger(__name__)\n\n\n# for a list of all types, see https://spark.apache.org/docs/3.0.3/api/python/_modules/pyspark/sql/types.html\n_field_type_mapping = {\n NullType: NullTypeClass,\n StringType: StringTypeClass,\n BinaryType: BytesTypeClass,\n BooleanType: BooleanTypeClass,\n DateType: DateTypeClass,\n TimestampType: TimeTypeClass,\n DecimalType: NumberTypeClass,\n DoubleType: NumberTypeClass,\n FloatType: NumberTypeClass,\n ByteType: BytesTypeClass,\n IntegerType: NumberTypeClass,\n LongType: NumberTypeClass,\n ShortType: NumberTypeClass,\n ArrayType: NullTypeClass,\n MapType: MapTypeClass,\n StructField: RecordTypeClass,\n StructType: RecordTypeClass,\n}\n\n\ndef get_column_type(\n report: SourceReport, dataset_name: str, column_type: str\n) -> SchemaFieldDataType:\n \"\"\"\n Maps known Spark types to datahub types\n \"\"\"\n TypeClass: Any = None\n\n for field_type, type_class in _field_type_mapping.items():\n if isinstance(column_type, field_type):\n TypeClass = type_class\n break\n\n # if still not found, report the warning\n if TypeClass is None:\n\n report.report_warning(\n dataset_name, f\"unable to map type {column_type} to metadata schema\"\n )\n TypeClass = NullTypeClass\n\n return SchemaFieldDataType(type=TypeClass())\n\n\n# config flags to emit telemetry for\nconfig_options_to_report = [\n \"platform\",\n \"use_relative_path\",\n \"ignore_dotfiles\",\n]\n\n# profiling flags to emit telemetry for\nprofiling_flags_to_report = [\n \"profile_table_level_only\",\n \"include_field_null_count\",\n \"include_field_min_value\",\n \"include_field_max_value\",\n \"include_field_mean_value\",\n \"include_field_median_value\",\n \"include_field_stddev_value\",\n \"include_field_quantiles\",\n \"include_field_distinct_value_frequencies\",\n \"include_field_histogram\",\n \"include_field_sample_values\",\n]\n\n\nS3_PREFIXES = [\"s3://\", \"s3n://\", \"s3a://\"]\n\n\n@platform_name(\"Data lake files\")\n@config_class(DataLakeSourceConfig)\n@support_status(SupportStatus.CERTIFIED)\n@capability(SourceCapability.DATA_PROFILING, \"Optionally enabled via configuration\")\nclass DataLakeSource(Source):\n \"\"\"\n This plugin extracts:\n\n - Row and column counts for each table\n - For each column, if profiling is enabled:\n - null counts and proportions\n - distinct counts and proportions\n - minimum, maximum, mean, median, standard deviation, some quantile values\n - histograms or frequencies of unique values\n\n This connector supports both local files as well as those stored on AWS S3 (which must be identified using the prefix `s3://`). Supported file types are as follows:\n\n - CSV\n - TSV\n - JSON\n - Parquet\n - Apache Avro\n\n Schemas for Parquet and Avro files are extracted as provided.\n\n Schemas for schemaless formats (CSV, TSV, JSON) are inferred. For CSV and TSV files, we consider the first 100 rows by default, which can be controlled via the `max_rows` recipe parameter (see [below](#config-details))\n JSON file schemas are inferred on the basis of the entire file (given the difficulty in extracting only the first few objects of the file), which may impact performance.\n We are working on using iterator-based JSON parsers to avoid reading in the entire JSON object.\n\n :::caution\n\n If you are ingesting datasets from AWS S3, we recommend running the ingestion on a server in the same region to avoid high egress costs.\n\n :::\n\n ## Setup\n\n To install this plugin, run `pip install 'acryl-datahub[data-lake]'`. Note that because the profiling is run with PySpark, we require Spark 3.0.3 with Hadoop 3.2 to be installed (see [compatibility](#compatibility) for more details). If profiling, make sure that permissions for **s3a://** access are set because Spark and Hadoop use the s3a:// protocol to interface with AWS (schema inference outside of profiling requires s3:// access).\n\n The data lake connector extracts schemas and profiles from a variety of file formats (see below for an exhaustive list).\n Individual files are ingested as tables, and profiles are computed similar to the [SQL profiler](../../../../metadata-ingestion/docs/dev_guides/sql_profiles.md).\n\n Enabling profiling will slow down ingestion runs.\n\n :::caution\n\n Running profiling against many tables or over many rows can run up significant costs.\n While we've done our best to limit the expensiveness of the queries the profiler runs, you\n should be prudent about the set of tables profiling is enabled on or the frequency\n of the profiling runs.\n\n :::\n\n Because data lake files often have messy paths, we provide the built-in option to transform names into a more readable format via the `path_spec` option. This option extracts identifiers from paths through a format string specifier where extracted components are denoted as `{name[index]}`.\n\n For instance, suppose we wanted to extract the files `/base_folder/folder_1/table_a.csv` and `/base_folder/folder_2/table_b.csv`. To ingest, we could set `base_path` to `/base_folder/` and `path_spec` to `./{name[0]}/{name[1]}.csv`, which would extract tables with names `folder_1.table_a` and `folder_2.table_b`. You could also ignore the folder component by using a `path_spec` such as `./{folder_name}/{name[0]}.csv`, which would just extract tables with names `table_a` and `table_b` – note that any component without the form `{name[index]}` is ignored.\n\n If you would like to write a more complicated function for resolving file names, then a {transformer} would be a good fit.\n\n \"\"\"\n\n source_config: DataLakeSourceConfig\n report: DataLakeSourceReport\n profiling_times_taken: List[float]\n\n def __init__(self, config: DataLakeSourceConfig, ctx: PipelineContext):\n super().__init__(ctx)\n self.source_config = config\n self.report = DataLakeSourceReport()\n self.profiling_times_taken = []\n\n config_report = {\n config_option: config.dict().get(config_option)\n for config_option in config_options_to_report\n }\n config_report = {**config_report, \"profiling_enabled\": config.profiling.enabled}\n\n telemetry.telemetry_instance.ping(\n \"data_lake_config\",\n config_report,\n )\n\n if config.profiling.enabled:\n telemetry.telemetry_instance.ping(\n \"data_lake_profiling_config\",\n {\n config_flag: config.profiling.dict().get(config_flag)\n for config_flag in profiling_flags_to_report\n },\n )\n self.init_spark()\n\n def init_spark(self):\n\n conf = SparkConf()\n\n # None by default, which corresponds to local\n if self.source_config.profiling.spark_cluster_manager:\n conf.setMaster(self.source_config.profiling.spark_cluster_manager)\n\n conf.set(\n \"spark.jars.packages\",\n \",\".join(\n [\n \"org.apache.hadoop:hadoop-aws:3.0.3\",\n \"org.apache.spark:spark-avro_2.12:3.0.3\",\n pydeequ.deequ_maven_coord,\n ]\n ),\n )\n\n if self.source_config.aws_config is not None:\n\n aws_access_key_id = self.source_config.aws_config.aws_access_key_id\n aws_secret_access_key = self.source_config.aws_config.aws_secret_access_key\n aws_session_token = self.source_config.aws_config.aws_session_token\n\n aws_provided_credentials = [\n aws_access_key_id,\n aws_secret_access_key,\n aws_session_token,\n ]\n\n if any(x is not None for x in aws_provided_credentials):\n\n # see https://hadoop.apache.org/docs/r3.0.3/hadoop-aws/tools/hadoop-aws/index.html#Changing_Authentication_Providers\n if all(x is not None for x in aws_provided_credentials):\n conf.set(\n \"spark.hadoop.fs.s3a.aws.credentials.provider\",\n \"org.apache.hadoop.fs.s3a.TemporaryAWSCredentialsProvider\",\n )\n\n else:\n conf.set(\n \"spark.hadoop.fs.s3a.aws.credentials.provider\",\n \"org.apache.hadoop.fs.s3a.SimpleAWSCredentialsProvider\",\n )\n\n if aws_access_key_id is not None:\n conf.set(\"spark.hadoop.fs.s3a.access.key\", aws_access_key_id)\n if aws_secret_access_key is not None:\n conf.set(\n \"spark.hadoop.fs.s3a.secret.key\",\n aws_secret_access_key,\n )\n if aws_session_token is not None:\n conf.set(\n \"spark.hadoop.fs.s3a.session.token\",\n aws_session_token,\n )\n else:\n # if no explicit AWS config is provided, use a default AWS credentials provider\n conf.set(\n \"spark.hadoop.fs.s3a.aws.credentials.provider\",\n \"org.apache.hadoop.fs.s3a.AnonymousAWSCredentialsProvider\",\n )\n\n conf.set(\"spark.jars.excludes\", pydeequ.f2j_maven_coord)\n conf.set(\"spark.driver.memory\", self.source_config.spark_driver_memory)\n\n self.spark = SparkSession.builder.config(conf=conf).getOrCreate()\n\n @classmethod\n def create(cls, config_dict, ctx):\n config = DataLakeSourceConfig.parse_obj(config_dict)\n\n return cls(config, ctx)\n\n def read_file_spark(self, file: str, is_aws: bool) -> Optional[DataFrame]:\n\n if is_aws:\n file = f\"s3a://{file}\"\n\n extension = os.path.splitext(file)[1]\n\n telemetry.telemetry_instance.ping(\"data_lake_file\", {\"extension\": extension})\n\n if file.endswith(\".parquet\"):\n df = self.spark.read.parquet(file)\n elif file.endswith(\".csv\"):\n # see https://sparkbyexamples.com/pyspark/pyspark-read-csv-file-into-dataframe\n df = self.spark.read.csv(\n file,\n header=\"True\",\n inferSchema=\"True\",\n sep=\",\",\n ignoreLeadingWhiteSpace=True,\n ignoreTrailingWhiteSpace=True,\n )\n elif file.endswith(\".tsv\"):\n df = self.spark.read.csv(\n file,\n header=\"True\",\n inferSchema=\"True\",\n sep=\"\\t\",\n ignoreLeadingWhiteSpace=True,\n ignoreTrailingWhiteSpace=True,\n )\n elif file.endswith(\".json\"):\n df = self.spark.read.json(file)\n elif file.endswith(\".avro\"):\n try:\n df = self.spark.read.format(\"avro\").load(file)\n except AnalysisException:\n self.report.report_warning(\n file,\n \"To ingest avro files, please install the spark-avro package: https://mvnrepository.com/artifact/org.apache.spark/spark-avro_2.12/3.0.3\",\n )\n return None\n\n # TODO: add support for more file types\n # elif file.endswith(\".orc\"):\n # df = self.spark.read.orc(file)\n else:\n self.report.report_warning(file, f\"file {file} has unsupported extension\")\n return None\n\n # replace periods in names because they break PyDeequ\n # see https://mungingdata.com/pyspark/avoid-dots-periods-column-names/\n return df.toDF(*(c.replace(\".\", \"_\") for c in df.columns))\n\n def get_table_schema(\n self,\n file_path: str,\n table_name: str,\n is_aws: bool,\n properties: Optional[Dict[str, str]],\n ) -> Iterable[MetadataWorkUnit]:\n\n data_platform_urn = make_data_platform_urn(self.source_config.platform)\n dataset_urn = make_dataset_urn(\n self.source_config.platform, table_name, self.source_config.env\n )\n\n dataset_name = os.path.basename(file_path)\n\n dataset_snapshot = DatasetSnapshot(\n urn=dataset_urn,\n aspects=[],\n )\n\n dataset_properties = DatasetPropertiesClass(\n description=\"\",\n customProperties=properties if properties is not None else {},\n )\n dataset_snapshot.aspects.append(dataset_properties)\n\n if is_aws:\n if self.source_config.aws_config is None:\n raise ValueError(\"AWS config is required for S3 file sources\")\n\n s3_client = self.source_config.aws_config.get_s3_client()\n\n file = smart_open(\n f\"s3://{file_path}\", \"rb\", transport_params={\"client\": s3_client}\n )\n\n else:\n\n file = open(file_path, \"rb\")\n\n fields = []\n\n try:\n if file_path.endswith(\".parquet\"):\n fields = parquet.ParquetInferrer().infer_schema(file)\n elif file_path.endswith(\".csv\"):\n fields = csv_tsv.CsvInferrer(\n max_rows=self.source_config.max_rows\n ).infer_schema(file)\n elif file_path.endswith(\".tsv\"):\n fields = csv_tsv.TsvInferrer(\n max_rows=self.source_config.max_rows\n ).infer_schema(file)\n elif file_path.endswith(\".json\"):\n fields = json.JsonInferrer().infer_schema(file)\n elif file_path.endswith(\".avro\"):\n fields = avro.AvroInferrer().infer_schema(file)\n else:\n self.report.report_warning(\n file_path, f\"file {file_path} has unsupported extension\"\n )\n file.close()\n except Exception as e:\n self.report.report_warning(\n file_path, f\"could not infer schema for file {file_path}: {e}\"\n )\n file.close()\n\n fields = sorted(fields, key=lambda f: f.fieldPath)\n schema_metadata = SchemaMetadata(\n schemaName=dataset_name,\n platform=data_platform_urn,\n version=0,\n hash=\"\",\n fields=fields,\n platformSchema=OtherSchemaClass(rawSchema=\"\"),\n )\n\n dataset_snapshot.aspects.append(schema_metadata)\n\n mce = MetadataChangeEvent(proposedSnapshot=dataset_snapshot)\n wu = MetadataWorkUnit(id=file_path, mce=mce)\n self.report.report_workunit(wu)\n yield wu\n\n def get_table_name(self, relative_path: str, full_path: str) -> str:\n\n if self.source_config.path_spec is None:\n name, extension = os.path.splitext(full_path)\n\n if extension != \"\":\n extension = extension[1:] # remove the dot\n return f\"{name}_{extension}\"\n\n return name\n\n def warn():\n self.report.report_warning(\n relative_path,\n f\"Unable to determine table name from provided path spec {self.source_config.path_spec} for file {relative_path}\",\n )\n\n name_matches = parse.parse(self.source_config.path_spec, relative_path)\n\n if name_matches is None:\n warn()\n return relative_path\n\n if \"name\" not in name_matches:\n warn()\n return relative_path\n\n name_matches_dict = name_matches[\"name\"]\n\n # sort the dictionary of matches by key and take the values\n name_components = [\n v for k, v in sorted(name_matches_dict.items(), key=lambda x: int(x[0]))\n ]\n\n return \".\".join(name_components)\n\n def ingest_table(\n self,\n full_path: str,\n relative_path: str,\n is_aws: bool,\n properties: Optional[Dict[str, str]] = None,\n ) -> Iterable[MetadataWorkUnit]:\n\n table_name = self.get_table_name(relative_path, full_path)\n\n # yield the table schema first\n logger.debug(\n f\"Ingesting {full_path}: making table schemas {datetime.now().strftime('%d/%m/%Y %H:%M:%S')}\"\n )\n yield from self.get_table_schema(full_path, table_name, is_aws, properties)\n\n # If profiling is not enabled, skip the rest\n if not self.source_config.profiling.enabled:\n return\n\n # read in the whole table with Spark for profiling\n table = self.read_file_spark(full_path, is_aws)\n\n # if table is not readable, skip\n if table is None:\n self.report.report_warning(\n table_name, f\"unable to read table {table_name} from file {full_path}\"\n )\n return\n\n with PerfTimer() as timer:\n # init PySpark analysis object\n logger.debug(\n f\"Profiling {full_path}: reading file and computing nulls+uniqueness {datetime.now().strftime('%d/%m/%Y %H:%M:%S')}\"\n )\n table_profiler = _SingleTableProfiler(\n table,\n self.spark,\n self.source_config.profiling,\n self.report,\n full_path,\n )\n\n logger.debug(\n f\"Profiling {full_path}: preparing profilers to run {datetime.now().strftime('%d/%m/%Y %H:%M:%S')}\"\n )\n # instead of computing each profile individually, we run them all in a single analyzer.run() call\n # we use a single call because the analyzer optimizes the number of calls to the underlying profiler\n # since multiple profiles reuse computations, this saves a lot of time\n table_profiler.prepare_table_profiles()\n\n # compute the profiles\n logger.debug(\n f\"Profiling {full_path}: computing profiles {datetime.now().strftime('%d/%m/%Y %H:%M:%S')}\"\n )\n analysis_result = table_profiler.analyzer.run()\n analysis_metrics = AnalyzerContext.successMetricsAsDataFrame(\n self.spark, analysis_result\n )\n\n logger.debug(\n f\"Profiling {full_path}: extracting profiles {datetime.now().strftime('%d/%m/%Y %H:%M:%S')}\"\n )\n table_profiler.extract_table_profiles(analysis_metrics)\n\n time_taken = timer.elapsed_seconds()\n\n logger.info(\n f\"Finished profiling {full_path}; took {time_taken:.3f} seconds\"\n )\n\n self.profiling_times_taken.append(time_taken)\n\n mcp = MetadataChangeProposalWrapper(\n entityType=\"dataset\",\n entityUrn=make_dataset_urn(\n self.source_config.platform, table_name, self.source_config.env\n ),\n changeType=ChangeTypeClass.UPSERT,\n aspectName=\"datasetProfile\",\n aspect=table_profiler.profile,\n )\n wu = MetadataWorkUnit(\n id=f\"profile-{self.source_config.platform}-{full_path}\", mcp=mcp\n )\n self.report.report_workunit(wu)\n yield wu\n\n def get_workunits_s3(self) -> Iterable[MetadataWorkUnit]:\n\n plain_base_path = strip_s3_prefix(self.source_config.base_path)\n\n # append a trailing slash if it's not there so prefix filtering works\n if not plain_base_path.endswith(\"/\"):\n plain_base_path = plain_base_path + \"/\"\n\n if self.source_config.aws_config is None:\n raise ValueError(\"AWS config is required for S3 file sources\")\n\n s3 = self.source_config.aws_config.get_s3_resource()\n bucket = s3.Bucket(plain_base_path.split(\"/\")[0])\n\n base_obj_paths: List[Tuple[str, Dict[str, str]]] = []\n\n for obj in bucket.objects.filter(\n Prefix=plain_base_path.split(\"/\", maxsplit=1)[1]\n ):\n\n s3_path = f\"s3://{obj.bucket_name}/{obj.key}\"\n\n # if table patterns do not allow this file, skip\n if not self.source_config.schema_patterns.allowed(s3_path):\n continue\n\n # if the file is a directory, skip it\n if obj.key.endswith(\"/\"):\n continue\n\n file = os.path.basename(obj.key)\n\n if self.source_config.ignore_dotfiles and file.startswith(\".\"):\n continue\n\n base_obj_path = f\"{obj.bucket_name}/{obj.key}\"\n\n properties = {\n \"owner\": str(obj.owner) if obj.owner else \"\",\n \"e_tag\": str(obj.e_tag) if obj.e_tag else \"\",\n \"last_modified\": str(obj.last_modified) if obj.last_modified else \"\",\n \"size\": str(obj.size) if obj.size else \"\",\n \"storage_class\": str(obj.storage_class) if obj.storage_class else \"\",\n \"service_name\": str(obj.meta.service_name)\n if obj.meta and obj.meta.service_name\n else \"\",\n }\n logger.debug(f\"Adding file {base_obj_path} for ingestion\")\n base_obj_paths.append((base_obj_path, properties))\n\n for aws_file in sorted(base_obj_paths, key=lambda a: a[0]):\n path = aws_file[0]\n properties = aws_file[1]\n relative_path = \"./\" + path[len(plain_base_path) :]\n\n # pass in the same relative_path as the full_path for S3 files\n yield from self.ingest_table(\n path, relative_path, is_aws=True, properties=properties\n )\n\n def get_workunits_local(self) -> Iterable[MetadataWorkUnit]:\n for root, dirs, files in os.walk(self.source_config.base_path):\n for file in sorted(files):\n\n if self.source_config.ignore_dotfiles and file.startswith(\".\"):\n continue\n\n full_path = os.path.join(root, file)\n\n relative_path = \"./\" + os.path.relpath(\n full_path, self.source_config.base_path\n )\n\n # if table patterns do not allow this file, skip\n if not self.source_config.schema_patterns.allowed(full_path):\n continue\n\n yield from self.ingest_table(full_path, relative_path, is_aws=False)\n\n def get_workunits(self) -> Iterable[MetadataWorkUnit]:\n\n with PerfTimer() as timer:\n\n # check if file is an s3 object\n if is_s3_uri(self.source_config.base_path):\n yield from self.get_workunits_s3()\n\n else:\n yield from self.get_workunits_local()\n\n if not self.source_config.profiling.enabled:\n return\n\n total_time_taken = timer.elapsed_seconds()\n\n logger.info(\n f\"Profiling {len(self.profiling_times_taken)} table(s) finished in {total_time_taken:.3f} seconds\"\n )\n\n time_percentiles: Dict[str, float] = {}\n\n if len(self.profiling_times_taken) > 0:\n percentiles = [50, 75, 95, 99]\n percentile_values = stats.calculate_percentiles(\n self.profiling_times_taken, percentiles\n )\n\n time_percentiles = {\n f\"table_time_taken_p{percentile}\": 10\n ** int(log10(percentile_values[percentile] + 1))\n for percentile in percentiles\n }\n\n telemetry.telemetry_instance.ping(\n \"data_lake_profiling_summary\",\n # bucket by taking floor of log of time taken\n {\n \"total_time_taken\": 10 ** int(log10(total_time_taken + 1)),\n \"count\": 10 ** int(log10(len(self.profiling_times_taken) + 1)),\n \"platform\": self.source_config.platform,\n **time_percentiles,\n },\n )\n\n def get_report(self):\n return self.report\n\n def close(self):\n pass\n","repo_name":"raft-tech/datahub-metadata-day-2022","sub_path":"metadata-ingestion/src/datahub/ingestion/source/data_lake/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":26197,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"81"} +{"seq_id":"29291218494","text":"### Novell Glosary Scraping\n## by Marlon Aviz\n\nFILE_PATH = \"scraped-data_optmized.txt\"\nsaveTo = \"final_data.txt\"\nhandle = open(FILE_PATH, 'r', encoding=\"utf-8\")\nc = 0\nword = None\ndefinition = []\nfor line in handle:\n\tline = line.strip()\n\tif c == 1:\n\t\tword = line\n\t\tc = 0\n\t\tcontinue\n\tif line == \"######\":\n\t\tif len(definition) > 0:\n\t\t\tdefinition_text = '. '.join(definition)\n\t\t\tshandle = open(saveTo, 'a', encoding='utf-8')\n\t\t\tshandle.write(word + \"\\t\" + definition_text + '\\n\\n')\n\t\t\tshandle.close()\n\t\t\tdefinition.clear()\n\t\tc = 1\n\t\tcontinue\n\tif line != \"\":\n\t\tdefinition.append(line)","repo_name":"avizmarlon/novell_glossary_scraper","sub_path":"fix_formatting.py","file_name":"fix_formatting.py","file_ext":"py","file_size_in_byte":579,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"36992244560","text":"import configparser\nimport os\nimport shutil\nimport sys\nfrom common.logs import Logger\nimport psycopg2\nimport yaml\n\n\ndef get_config(path, name):\n cf = configparser.ConfigParser()\n dir_path = cf.read(os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + path)\n cf.read(dir_path)\n items = dict(cf.items(name))\n return items\n\n\ndef yaml_load(path):\n \"\"\"\n 封装yaml文件的解析\n :param path: yaml文件路径\n :return:python对象\n \"\"\"\n dir_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\n with open(dir_path + path, encoding='UTF-8') as f:\n return yaml.safe_load(f)\n\n\ndef del_file(filepath):\n \"\"\"\n 删除某一目录下的所有文件或文件夹\n :param filepath: 路径\n :return:\n \"\"\"\n try:\n del_list = os.listdir(filepath)\n for f in del_list:\n file_path = os.path.join(filepath, f)\n if os.path.isfile(file_path):\n os.remove(file_path)\n elif os.path.isdir(file_path):\n shutil.rmtree(file_path)\n except FileNotFoundError:\n print('目录不存在')\n\n\ndef clear_file(filepath):\n dir_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\n with open(dir_path + filepath, 'r+') as f:\n f.truncate()\n\n\nlog = Logger()\n\n\ndef my_assert(ass, *args):\n \"\"\"\n 封装断言+日志\n \"\"\"\n try:\n exec(ass)\n log.logger.info(\n '{}: 用例通过 \\t 实际: {} \\t 预期: {}'.format(sys._getframe().f_back.f_code.co_name, args[0], args[1]))\n except AssertionError:\n log.logger.error(\n '{}: 断言失败 \\t 实际: {} \\t 预期: {}'.format(sys._getframe().f_back.f_code.co_name, args[0], args[1]))\n raise AssertionError('断言失败')\n\n\nclass PgSql:\n def __init__(self):\n self.host = get_config('/config.ini', 'all_config')['host']\n self.conn = psycopg2.connect(database=\"hulattp\", user=\"postgres\", password=\"hb2gZVUos7vosADO\", host=self.host,\n port=\"5432\")\n\n def clear_home(self):\n if self.host == '1.1.1.1':\n return\n cur = self.conn.cursor()\n cur.execute(\"DELETE FROM homepage WHERE title like '%自动化%';\")\n # self.cur.fetchall() # 检索查询结果\n self.conn.commit()\n self.conn.close()\n\n def clear_label(self):\n if self.host == '1.1.1.1':\n return\n cur = self.conn.cursor()\n cur.execute(\n \"DELETE FROM label WHERE ID IN (SELECT ID FROM label RIGHT JOIN ( SELECT label_id FROM label_group_to_label WHERE group_id = ( SELECT ID FROM label_group WHERE NAME = '自动化标签组' ) ) AS son ON ID = label_id);\") # 先删标签\n cur.execute(\n \"DELETE FROM label_group_to_label WHERE group_id = (SELECT id FROM label_group WHERE name='自动化标签组');\") # 再删关系\n cur.execute(\"DELETE FROM label_group WHERE name='自动化标签组';\") # 再删标签组\n cur.execute(\"DELETE FROM label WHERE name like '%自动化%';\") # 可能没有删干净,再删一次\n cur.execute(\"delete from nav_bar where NAME like '%自动化%';\") # 删除推荐页导航栏\n self.conn.commit()\n self.conn.close()\n\n def clear_topic(self):\n if self.host == '1.1.1.1':\n return\n content_id = []\n cur = self.conn.cursor()\n # 根据话题名称获取所有content_id\n cur.execute(\n \"select content_id from content_to_topic where topic_id in (select id from topic where title like '%自动化%');\")\n rows = cur.fetchall()\n for i in rows:\n content_id.append(i[0])\n # 删除content_to_topic对应关系\n cur.execute(\"delete from content_to_topic where topic_id in (select id from topic where title like '%自动化%');\")\n # 删除content\n for i in content_id:\n cur.execute(\"delete from content where id={};\".format(i))\n\n # 删除topic_to_topic_group对应关系\n cur.execute(\n \"delete from topic_to_topic_group where topic_id in (select id from topic where title like '%自动化%');\")\n cur.execute(\n \"delete from topic_to_topic_group where group_id in (select id from topic_group where title like '%自动化%');\")\n # 删除author_follow_topic关注关系\n cur.execute(\n \"delete from author_follow_topic where topic_id in (select id from topic where title like '%自动化%');\")\n # 删除话题\n cur.execute(\"delete from topic where title like '%自动化%';\")\n # 删除话题组\n cur.execute(\"delete from topic_group where title like '%自动化%';\")\n\n self.conn.commit()\n self.conn.close()\n\n\nif __name__ == '__main__':\n PgSql().clear_home()\n","repo_name":"bigllxx/testframework-ui","sub_path":"common/action.py","file_name":"action.py","file_ext":"py","file_size_in_byte":4822,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"71607666505","text":"#!/usr/bin/env python\n\nimport os\nimport re\nfrom setuptools import find_packages, setup\nfrom setuptools.command.develop import develop\nfrom setuptools.command.install import install\n\nthisScriptDir = os.path.dirname(os.path.realpath(__file__))\n\ndef EnsureNewline(line):\n line = line.rstrip()\n line = line + '\\n'\n return line\n\ndef ReplaceBtwnLines(fPath, startLine, endLine, txtBlock):\n repRe = re.compile(startLine + '.*' + endLine, re.DOTALL)\n replTxt = EnsureNewline(startLine) + EnsureNewline(txtBlock) + endLine\n \n try:\n with open(fPath, 'r') as f:\n oldTxt = f.read()\n except IOError:\n return False\n if repRe.search(oldTxt):\n newTxt = repRe.sub(replTxt, oldTxt)\n with open(fPath, 'w') as f:\n f.write(newTxt)\n return True\n else:\n return False\n \ndef AppendBlockToFile(fPath, startLine, endLine, txtBlock):\n oldTxt = ''\n newTxt = EnsureNewline(startLine) + EnsureNewline(txtBlock) + endLine\n try:\n with open(fPath, 'r') as f:\n oldTxt = f.read()\n oldTxt = EnsureNewline(oldTxt) + '\\n'\n except IOError:\n pass\n with open(fPath, 'w') as f:\n f.write(oldTxt)\n f.write(newTxt)\n \nclass CustomSetupCommand:\n '''\n customized setup command base class\n meant to be used in a subclass that also inherits either setuptools.command.install.install or .develop\n '''\n leapSDKEnvVar = 'LEAPSDK_DIR'\n \n def run(self):\n self._writeLeapConfig()\n self._writePymolrc()\n \n def _writeLeapConfig(self):\n '''\n write config file to set path to leap motion packages\n '''\n if self.leapSDKEnvVar not in os.environ:\n raise EnvironmentError('%s%s' % ('You need to set the %s environment variable before installing ocumol, ' % self.leapSDKEnvVar,\n 'e.g. you could run `LEAPSDK_DIR=/usr/local/LeapSDK pip install ocumol`'))\n leapSDKDir = os.environ.get(self.leapSDKEnvVar)\n with open('ocumol/leapConfig.py', 'w') as f:\n f.write(\"leapPath = '%s'\" % os.path.join(leapSDKDir, 'lib'))\n \n def _writePymolrc(self):\n pymolrcPath = os.path.expanduser('~/.pymolrc.py')\n ocumolStartBumper = '#'*4 + 'START_OCUMOL_PLUGIN' + '#'*4\n ocumolEndBumper = '#'*4 + 'END_OCUMOL_PLUGIN' + '#'*4\n with open(os.path.join(thisScriptDir, 'pymolrc'), 'r') as f:\n ocumolPluginTxt = f.read()\n if not ReplaceBtwnLines(pymolrcPath, ocumolStartBumper, ocumolEndBumper, ocumolPluginTxt):\n AppendBlockToFile(pymolrcPath, ocumolStartBumper, ocumolEndBumper, ocumolPluginTxt)\n\nclass CustomDevelopCommand(CustomSetupCommand, develop):\n def run(self):\n CustomSetupCommand.run(self)\n develop.run(self)\n\nclass CustomInstallCommand(CustomSetupCommand, install):\n def run(self):\n CustomSetupCommand.run(self)\n install.run(self)\n\nsetup(\n author = 'Max Klein, Jeliazko Jeliazkov, Henry Lessen, Mariusz Matyszewski',\n cmdclass = {'develop': CustomDevelopCommand,'install': CustomInstallCommand},\n description = 'adds VR support to various molecular viewers',\n license = 'apache',\n name = \"ocumol\",\n packages=find_packages(),\n url='https://github.com/lqtza/OcuMOL_Leap'\n )\n","repo_name":"lqtza/OcuMOL_Leap","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":3336,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"81"} +{"seq_id":"1864815086","text":"\"\"\"\r\nCopyright (C) 2019. Huawei Technologies Co., Ltd. All rights reserved.\r\n\r\nTiling helper, set and get a fixed tiling\r\n\"\"\"\r\nimport os\r\nimport copy\r\nimport json\r\nfrom te import tvm\r\n\r\n\r\nclass Singleton():\r\n \"\"\"Singleton base class\r\n \"\"\"\r\n __instance = None\r\n __tiling = None\r\n __tiling_type = None\r\n __input_params = None\r\n\r\n def __init__(self):\r\n self._singleton__tiling = None\r\n self._singleton__tiling_type = None\r\n self._singleton__input_params = None\r\n\r\n get_config_path_fun = tvm.get_global_func(\"_query_config_path\")\r\n config_path = get_config_path_fun()\r\n config_path = os.path.realpath(config_path)\r\n if os.path.exists(config_path):\r\n with open(config_path, 'r') as handler:\r\n config = json.load(handler)\r\n self._singleton__tiling_type = config.get(\"tiling_type\")\r\n if not self._singleton__tiling_type:\r\n self._singleton__tiling_type = \"auto_tiling\"\r\n\r\n def __new__(cls, *args, **kw):\r\n if not cls.__instance:\r\n cls.__instance = super(Singleton, cls).__new__(cls, *args, **kw)\r\n return cls.__instance\r\n\r\n def get_params(self):\r\n \"\"\"Get tiling input params\r\n\r\n Notice\r\n ------\r\n this function is create for auto tune tool to get tiling input params\r\n\r\n Returns\r\n ----------\r\n input_params: dict\r\n set by tiling query or get tiling\r\n \"\"\"\r\n return copy.deepcopy(self._singleton__input_params)\r\n\r\n def set_params(self, inputs):\r\n \"\"\"Set get tiling or tiling query input params\r\n\r\n Parameters\r\n ----------\r\n inputs: dict\r\n build up by schedule\r\n\r\n Notice\r\n ------\r\n this function is create for auto tune tool to get tiling input params,\r\n params set last time should be same to get_tiling inputs, usually\r\n called under non-tuning_tiling mode by schedule when building\r\n executable binary file\r\n\r\n \"\"\"\r\n self._singleton__input_params = copy.deepcopy(inputs)\r\n\r\n def get_tiling(self, inputs):\r\n \"\"\"Get the tiling from Singleton object\r\n Parameters\r\n ----------\r\n\r\n Notice\r\n ------\r\n this function is work under tuning tiling mode together with\r\n set tiling, input params used is set by set_params last\r\n time, should be exaclty same to inputs\r\n\r\n some list value given is tvm.expr.Int, so compare use string\r\n and not original dict\r\n\r\n Returns\r\n -------\r\n tiling: dict\r\n The tiling saved in Singleton object\r\n \"\"\"\r\n if not isinstance(inputs, dict) or not inputs:\r\n raise RuntimeError(\"illegal inputs: %s\" % str(inputs))\r\n\r\n pre = copy.copy(self._singleton__input_params)\r\n if not isinstance(inputs, dict) or not pre:\r\n raise RuntimeError(\"set params when tuning tiling, like: %s\"\r\n % str(inputs))\r\n cur = copy.copy(inputs)\r\n ignore_list = [\"reserved_ub\"]\r\n for item in ignore_list:\r\n if item in pre:\r\n pre.pop(item)\r\n if item in cur:\r\n cur.pop(item)\r\n if str(cur) != str(pre):\r\n raise RuntimeError(\"tiling params is changed, previous is: %s, \"\r\n \"input is %s\"\r\n % (str(pre), str(cur)))\r\n\r\n return copy.deepcopy(self._singleton__tiling)\r\n\r\n def set_tiling(self, tiling):\r\n \"\"\"Set the tiling to private member variable of Singleton object\r\n Parameters\r\n ----------\r\n tiling: dict\r\n The setting tiling\r\n\r\n Returns\r\n -------\r\n \"\"\"\r\n type_list = [\"tuning_tiling\", \"atc_tuning_tiling\"]\r\n if self._singleton__tiling_type not in type_list:\r\n raise RuntimeError(\"tiling mode is not tuning tiling, \"\r\n \"current is %s\"\r\n % str(self._singleton__tiling_type))\r\n\r\n if isinstance(tiling, dict):\r\n self._singleton__tiling = copy.deepcopy(tiling)\r\n else:\r\n raise TypeError('tiling is not a dict.')\r\n\r\n def get_tiling_type(self):\r\n \"\"\"Get the tiling type from Singleton object\r\n Parameters\r\n ----------\r\n\r\n Returns\r\n -------\r\n tiling_type: string\r\n The tiling type saved in Singleton object\r\n \"\"\"\r\n return copy.deepcopy(self._singleton__tiling_type)\r\n\r\n def set_tiling_type(self, tiling_type):\r\n \"\"\"Set the tiling type to private member variable of Singleton object\r\n Parameters\r\n ----------\r\n tiling_type: string\r\n The setting tiling type\r\n\r\n Returns\r\n -------\r\n \"\"\"\r\n if isinstance(tiling_type, str):\r\n self._singleton__tiling_type = copy.deepcopy(tiling_type)\r\n else:\r\n raise TypeError('tiling is not a str.')\r\n\r\nTILING_INSTANCE = Singleton()\r\n","repo_name":"jizhuoran/caffe-huawei-atlas-convertor","sub_path":"convertor/huawei/te/domain/tiling/tiling_helper.py","file_name":"tiling_helper.py","file_ext":"py","file_size_in_byte":5086,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"81"} +{"seq_id":"72770202824","text":"\n\n\n\n# Tuple summation\n# Using list() + sum()\n\n# initializing tup\nitems = (10, 77,40,38,40,20,50,83,45,38,20)\n\n# printing original tuple\n\n\n# Tuple elements inversions\n# Using list() + sum()\nres = sum(list(items))\n\n# printing result\nprint(res)\n\n\n","repo_name":"DAVIDMIGWI/python","sub_path":"assignment on tuple.py","file_name":"assignment on tuple.py","file_ext":"py","file_size_in_byte":244,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"5909135851","text":"from db.models import Annotation, Genome, ParamFile\nfrom errors import NotFound\nfrom services import organism_service\nfrom flask import current_app as app\nfrom utils import common_functions\n\nGENERAL_PARAMS = ['name','taxid']\nGENOME_LOCATIONS = ['fastaLocation','faiLocation','gziLocation']\nANNOTATION_LOCATIONS = ['gffGzLocation','tabIndexLocation','targetGenome','evidenceSource']\nPARAM_FILE_LOCATIONS = ['paramLocation']\n\ndef validate_params(params, required_fields):\n return [key for key in required_fields if key not in params.keys()]\n\n#return model\ndef model_handler(model):\n if model == 'genomes':\n return Genome\n elif model == 'annotations':\n return Annotation\n elif model == 'parameters':\n return ParamFile\n else:\n return None\n\ndef organism_handler(model, file, organism):\n if model == 'genomes':\n organism.genomes.append(file)\n elif model == 'annotations':\n organism.annotations.append(file)\n elif model == 'parameters':\n organism.param_files.append(file)\n else:\n return\n organism.save()\n return organism\n\ndef reference_handler(model, organism):\n if model == 'genomes':\n return organism.genomes\n elif model == 'annotations':\n return organism.annotations\n else:\n return organism.param_files\n\ndef location_handler(model):\n if model == 'genomes':\n return GENOME_LOCATIONS \n elif model == 'annotations':\n return ANNOTATION_LOCATIONS\n elif model == 'parameters':\n return PARAM_FILE_LOCATIONS\n else:\n return None\n#model to retrieve file path for download\ndef create_file_model(params, model):\n saved_file_model = model(**params).save()\n return saved_file_model\n\ndef payload_parser(request, model):\n params = dict(**request.json) if request.is_json else dict(**request.form)\n if not 'API_KEY' in params.keys() or not common_functions.auth_request(params['API_KEY']):\n raise NotFound\n else:\n params.pop('API_KEY')\n error_keys=validate_params(params, GENERAL_PARAMS+location_handler(model))\n if error_keys:\n return error_keys\n model_obj = model_handler(model)\n ##pop taxid from payload dict\n taxid = params.pop('taxid')\n organism = organism_service.get_or_create_organism(taxid)\n saved_file_object=create_file_model(params,model_obj)\n updated_organism = organism_handler(model,saved_file_object,organism)\n if updated_organism:\n return saved_file_object.to_json()\n else:\n return list()\n\ndef search_by_taxid(request, model):\n args = request.args\n model_obj = model_handler(model)\n if 'taxid' in args.keys():\n taxid = args['taxid']\n organism = organism_service.get_or_create_organism(taxid)\n ids = [ref.id for ref in reference_handler(model,organism)]\n return model_obj.objects(id__in=ids).exclude('id').to_json()\n else:\n return model_obj.objects().exclude('id').to_json()\n#manage file deletion and organism and taxon deletion cascade\ndef delete_file(name,model):\n model_obj = model_handler(model)\n file_obj = model_obj.objects(name=name).first()\n\n \n\n","repo_name":"guigolab/gene-predictions-web","sub_path":"server/services/file_service.py","file_name":"file_service.py","file_ext":"py","file_size_in_byte":3144,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"40937148392","text":"import numpy as np\nimport sys\nimport matplotlib.pyplot as plt\nimport tensorflow\nfrom tensorflow.keras.models import load_model, Model\nfrom matplotlib.widgets import Slider, Button, RadioButtons\nsys.path.append(\"../\")\nfrom MLTK.data import DataGenerator\n\nmodel = load_model('/home/attilasimko/Documents/out/server/paired_training/45_g.h5')\nmaps_model = Model(inputs=[model.inputs[0]], \n outputs=[model.get_layer('activation').output,\n model.get_layer('lambda').output,\n model.get_layer('lambda_1').output])\ndata_path = '/mnt/4a39cb60-7f1f-4651-81cb-029245d590eb/DS0048/validating'\n# model = load_model('C:/Users/attil/Downloads/out/45_g.h5')\n# data_path = 'C:/Users/attil/Documents/Datasets/DS0048_val/'\ngen = DataGenerator(data_path,\n inputs=[['im1', False, 'float32'], ['ter1', False, 'int']],\n outputs=[],\n batch_size=1,\n shuffle=False)\nfile_idx = 0\nimg_in, _ = gen[file_idx]\nimg_out = maps_model.predict([img_in[0], np.expand_dims(0, axis=0), np.expand_dims(0, axis=0)])\nT1 = img_out[1][0, :, :, 0]\n\nplt.subplot(221)\nplt.imshow(T1, cmap='gray')\nplt.subplot(222)\nplt.imshow(np.exp(-1/T1), cmap='gray')\nplt.show()","repo_name":"attilasimko/drs","sub_path":"MT/old_present_results/present_maps.py","file_name":"present_maps.py","file_ext":"py","file_size_in_byte":1295,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"32863611041","text":"import cv2\nimport numpy as np\nimg = cv2.imread(\"imori.jpg\").astype(np.float32)\nb = img[:,:,0].copy()\ng = img[:,:,1].copy()\nr = img[:,:,2].copy()\n\nout = 0.2126 * r + 0.7152 * g + 0.0722 * b #0.2126+0.7152+0.0722 = 1\nout = out.astype(np.uint8)\n\ncv2.imwrite(\"question02.jpg\",out)\ncv2.imshow(\"result\",out)\ncv2.waitKey(0)\ncv2.destroyAllWindows()\n","repo_name":"uehir0/Gasyori100knock","sub_path":"Question_01_10/codes/question02.py","file_name":"question02.py","file_ext":"py","file_size_in_byte":341,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"81"} +{"seq_id":"41210205083","text":"import json\nimport pugsql\nimport os\nfrom scrapy.crawler import Crawler\nfrom scrapy.utils.project import get_project_settings\nfrom newsSpiders.types import SiteConfig\nfrom newsSpiders import ptt\nfrom newsSpiders.spiders.basic_discover_spider import BasicDiscoverSpider\nfrom newsSpiders.spiders.dcard_dicsover_spider import DcardDiscoverSpider\nfrom newsSpiders.spiders.toutiao_discover_spider import ToutiaoDiscoverSpider\n\n\ndef run(runner, site_id, args=None):\n queries = pugsql.module(\"./queries\")\n queries.connect(os.getenv(\"DB_URL\"))\n\n site_info = queries.get_site_by_id(site_id=site_id)\n dedup_limit = args[\"dedup_limit\"] or 500\n recent_articles = queries.get_recent_articles_by_site(\n site_id=site_id, limit=dedup_limit\n )\n\n queries.disconnect()\n\n site_conf = SiteConfig.default()\n site_conf.update(json.loads(site_info[\"config\"]))\n site_conf[\"url\"] = site_info[\"url\"]\n site_conf[\"type\"] = site_info[\"type\"]\n\n if args is not None:\n site_conf.update(args)\n\n settings = {\n **get_project_settings(),\n \"DEPTH_LIMIT\": site_conf[\"depth\"],\n \"DOWNLOAD_DELAY\": site_conf[\"delay\"],\n \"USER_AGENT\": site_conf[\"ua\"],\n }\n\n if \"dcard\" in site_conf[\"url\"]:\n crawler = Crawler(DcardDiscoverSpider, settings)\n crawler.stats.set_value(\"site_id\", site_id)\n\n runner.crawl(\n crawler,\n site_id=site_id,\n site_url=site_conf[\"url\"],\n article_url_excludes=[a[\"url\"] for a in recent_articles],\n )\n elif \"toutiao\" in site_conf[\"url\"]:\n crawler = Crawler(ToutiaoDiscoverSpider, settings)\n crawler.stats.set_value(\"site_id\", site_id)\n\n runner.crawl(\n crawler,\n site_id=site_id,\n site_url=site_conf[\"url\"],\n article_url_excludes=[a[\"url\"] for a in recent_articles],\n )\n elif \"ptt.cc\" in site_conf[\"url\"]:\n ptt.DiscoverSite(site_info).run(depth=site_conf[\"depth\"])\n\n else:\n crawler = Crawler(BasicDiscoverSpider, settings)\n crawler.stats.set_value(\"site_id\", site_id)\n runner.crawl(\n crawler,\n site_id=site_id,\n site_url=site_conf[\"url\"],\n article_url_patterns=site_conf[\"article\"],\n following_url_patterns=site_conf[\"following\"],\n article_url_excludes=[a[\"url\"] for a in recent_articles],\n selenium=site_conf.get(\"selenium\", False),\n )\n","repo_name":"disinfoRG/ZeroScraper","sub_path":"newsSpiders/runner/discover.py","file_name":"discover.py","file_ext":"py","file_size_in_byte":2460,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"81"} +{"seq_id":"26479116628","text":"import machine\nfrom machine import Pin, PWM\nimport time\nimport picounicorn as uni\nimport _thread\nimport gc\n\n# **--------------------------------------------------**\n# Configure Garbage Collection\n# **--------------------------------------------------**\n# Enable automatic garbage collection in Out Of Memory condition\ngc.enable()\n\n# Trigger carbage collection after 100000 bytes\n# of heap memory have been allocated\ngc.threshold(100000)\n\n# **--------------------------------------------------**\n# Set Variables\n# **--------------------------------------------------**\n# Loop Counters\ncore0_loop_n = 0\nglobal core1_loop_n\ncore1_loop_n = 0\nalert_loop_n = 0\n\n# **--------------------------------------------------**\n# Configure Unicorn Matrix Alerts\n# **--------------------------------------------------**\nuni.init()\n\n# set the width and height for the led matrix\nuni_width = uni.get_width()\nuni_height = uni.get_height()\n\n# define led matrix colors for temperature states\ndef matrix_red():\n for x in range(1, 16):\n for y in range(uni_height):\n uni.set_pixel(x, y, 255, 0, 0)\n\ndef matrix_green():\n for x in range(1, 16):\n for y in range(uni_height):\n uni.set_pixel(x, y, 0, 50, 0)\n\ndef matrix_blue():\n for x in range(1, 16):\n for y in range(uni_height):\n uni.set_pixel(x, y, 0, 0, 50)\n\ndef matrix_black():\n for x in range(1, 16):\n for y in range(uni_height):\n uni.set_pixel(x, y, 0, 0, 0)\n\n# Define Thread Running Confirmation\ndef thread_0_running_led():\n for x in range(0, 1):\n for y in range(0, 2):\n uni.set_pixel(x, y, 50, 50, 50)\n time.sleep(0.5)\n for x in range(0, 1):\n for y in range(0, 2):\n uni.set_pixel(x, y, 0, 0, 0)\n time.sleep(0.5)\n \ndef thread_1_running_led():\n for x in range(0, 1):\n for y in range(5, 7):\n uni.set_pixel(x, y, 50, 50, 50)\n time.sleep(0.5)\n for x in range(0, 1):\n for y in range(5, 7):\n uni.set_pixel(x, y, 0, 0, 0)\n time.sleep(0.5)\n\n# Define taking temperature notification\ndef taking_temp_note():\n for x in range(0, 1):\n for y in range(2, 5):\n uni.set_pixel(x, y, 255, 0, 255)\n time.sleep(0.2)\n for x in range(0, 1):\n for y in range(2, 5):\n uni.set_pixel(x, y, 0, 0, 0)\n time.sleep(0.2)\n\n# **--------------------------------------------------**\n# Configure Pico's Onboard temperature sensor\n# **--------------------------------------------------**\n# reads from Pico's temp sensor and converts it into a more manageable number\nsensor_temp = machine.ADC(4) \nconversion_factor = 3.3 / (65535)\n\n# add a variable to manually adjust the accuracy of the sensor\nt_adjust = 3.1 \n\n# variables to set the upper and lower temperature limits\nt_hot = 23\nt_cold = 18\n\ntemperatures = []\n\n# **--------------------------------------------------**\n# Define Buzzer and Mute Button\n# **--------------------------------------------------**\n# set up the piezzo buzzer\nbuzzer = PWM(Pin(0))\nbuzzer.freq(500)\n\n# Add a button to mute the buzzer\nbutton = machine.Pin(28, machine.Pin.IN, machine.Pin.PULL_DOWN)\n\nglobal buzzer_mute\nbuzzer_mute = False\n\n# **--------------------------------------------------**\n# Define Console Print Info for Debugging\n# **--------------------------------------------------**\ndef status_print():\n print(\"*--------------------------*\")\n print(\"Core 0 Loop #\" + str(core0_loop_n))\n print(\"Core 1 Loop #\" + str(core1_loop_n))\n print(\"*--------------------------*\")\n print(\"Sensor reading: \" + str(reading))\n print(\"Temperature: \" + str(temperature))\n print(\"Decimal temperature: \" + str(temp_float))\n print(\"\\n\")\n print(\"Alert Count: \" + str(alert_loop_n) + \" Loops In Total\")\n print(\"Temp Alert Status: \" + str(temp_alert))\n print(\"Buzzer Mute Status:\" + str(buzzer_mute))\n print(\"\\n\")\n print(\"Free Memory: \" + str(gc.mem_free()) + \" bytes of available heap RAM\")\n print(\"Allocared Memory: \" + str(gc.mem_alloc()) + \" bytes of allocated heap RAM\")\n print(\"*--------------------------*\")\n print(\"\\n\")\n\n# **--------------------------------------------------**\n# Define Alert Thread on Core 1\n# **--------------------------------------------------**\nglobal temp_alert\ntemp_alert = False\n\n# Define a function for the alert thread on core 1\ndef alert_thread():\n global temp_alert\n global buzzer_mute\n global core1_loop_n\n while True:\n # Start counting the loops\n core1_loop_n += 1\n\n # Watch for mute button press\n if button.value() == 1:\n time.sleep(0.01)\n buzzer_mute = True\n\n # Visual and Audiable alert for over temperature\n if temp_alert == True and buzzer_mute == False:\n matrix_red()\n buzzer.duty_u16(1000)\n time.sleep(0.2)\n matrix_black()\n buzzer.duty_u16(0)\n time.sleep(0.2)\n \n # Visual Only Alert (Buzzer Mute is Active)\n elif temp_alert == True and buzzer_mute == True:\n matrix_red()\n time.sleep(0.2)\n matrix_black()\n time.sleep(0.2)\n\n else:\n # Toggle LED to Show Thread is running\n thread_1_running_led()\n\n_thread.start_new_thread(alert_thread, ())\n\n# **--------------------------------------------------**\n# Main Program On Core 0\n# **--------------------------------------------------**\nwhile True:\n # start counting the loops\n core0_loop_n += 1\n\n # taking teperature notification\n taking_temp_note()\n\n # the following two lines convert the value from the temp sensor into celsius\n reading = (sensor_temp.read_u16() * conversion_factor)\n temp_float = round((27 - (reading - 0.706) / 0.001721) + t_adjust, 1)\n temperature = int(temp_float)\n \n # set the temperature alert\n if temperature >= t_hot:\n temp_alert = True\n alert_loop_n += 1\n\n else:\n if temperature > t_cold and temperature < t_hot:\n temp_alert = False\n buzzer_mute = False\n matrix_green()\n else:\n temp_alert = False\n buzzer_mute = False\n matrix_blue()\n \n status_print()\n\n # set the delay in seconds between temperature checks\n for delay in range(30):\n thread_0_running_led()\n","repo_name":"SilentWoof/Pico_Unicorn_Pack_Temperature_Alert","sub_path":"pico-unicorn-pack-temp-alert.py","file_name":"pico-unicorn-pack-temp-alert.py","file_ext":"py","file_size_in_byte":6423,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"81"} +{"seq_id":"12725195132","text":"nilai = 73\n\nif nilai >= 0 and nilai <= 100 :\n if nilai >= 86 and nilai <= 100 :grade = \"A\"\n elif nilai >= 53 and nilai <= 86 :grade = \"B\"\n elif nilai == 51 or nilai == 52 :grade = \"C\"\n elif nilai < 51 : grade = \"D\"\n\nprint(\"Grade Nilai = \",grade)\n\nif not (nilai >= 0 and nilai <= 100 ): #dapat diganti dengan pernyataan else\n print(\"Nilai yang anda masukkan salah\") ","repo_name":"Yasir1st/100-Days-Of-Coding","sub_path":"pemilihan3.py","file_name":"pemilihan3.py","file_ext":"py","file_size_in_byte":380,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"19692921991","text":"from python18.ATM.card import Card\nfrom python18.ATM.person import Person\nimport os\nimport random\nimport pickle\n\n\nclass Operation(object):\n def __init__(self):\n self.Load_user()\n self.Load_userid()\n # print(self.user_dict)\n\n def Load_user(self):\n \"\"\"先判断文件是否存在\"\"\"\n if os.path.exists(\"user.txt\"):\n with open(\"user.txt\", \"rb\") as f:\n self.user_dict = pickle.load(f)\n else:\n self.user_dict = {}\n\n def Load_userid(self):\n if os.path.exists(\"userid.txt\"):\n with open(\"userid.txt\", \"rb\") as f:\n self.user_id_dict = pickle.load(f)\n else:\n self.user_id_dict = {}\n\n def Register(self):\n \"\"\"注册\"\"\"\n # 输入姓名\n name = input(\"请输入您的姓名:\")\n # 输入身份证号\n userid = input(\"请输入您的身份证号:\")\n # 输入手机号\n phone = input(\"请输入您的手机号:\")\n # 设置密码\n passwd = self.Get_pwd()\n # 生成卡号\n cardid = self.Get_cardid()\n\n # 生成卡\n card = Card(cardid, passwd, 10)\n\n # ��过卡找到用户\n user = Person(name, userid, phone, card)\n self.user_dict[cardid] = user\n self.user_id_dict[userid] = cardid\n print(\"恭喜%s开卡成功,卡号%s,当前余额%s\" % (name, cardid, card.money))\n\n def Get_pwd(self):\n while True:\n pwd1 = input(\"请输入您的密码:\")\n pwd2 = input(\"请确认您的密码:\")\n\n if pwd1 == pwd2:\n return pwd1\n else:\n print(\"两次密码不一致,请从新输入。\")\n\n def Get_cardid(self):\n while True:\n cardid = random.randint(100000, 999999)\n if cardid not in self.user_dict:\n return cardid\n\n def Query(self):\n \"\"\"查询功能\"\"\"\n # 拿到一张卡\n card = self.Get_card_info()\n if not card:\n print(\"卡不存在\")\n else:\n if card.islock:\n print(\"卡被锁了!\")\n else:\n # 检测密码\n if self.Check_pwd(card):\n print(\"卡内余额%s\" % (card.money))\n\n def Check_pwd(self, card):\n # 检测卡密码\n count = 1\n while count < 4:\n pwd = input(\"请输入您的密码:\")\n # 判断用户输入的密码和卡内的密码是否一致\n if pwd == card.passwd:\n return True\n else:\n count += 1\n print(\"密码输入错误,还有%s次机会\" % (4 - count))\n if count == 4:\n card.islock = True\n print(\"密码输入3次失败,卡被冻结\")\n\n def Get_card_info(self):\n cardid = int(input(\"请输入您的卡号:\"))\n if cardid not in self.user_dict:\n return False\n else:\n # 通过卡找到用户\n user = self.user_dict[cardid]\n # 通过用户找到卡\n card = user.card\n return card\n\n def Save_money(self):\n \"\"\"存钱\"\"\"\n # 拿到一张卡\n card = self.Get_card_info()\n # 通过卡找到用户\n user = self.user_dict[card.cardid]\n if not card:\n print(\"卡号不存在!\")\n else:\n # 检查卡号是否被锁\n if card.islock:\n print(\"卡被冻结,请先解锁!\")\n else:\n print(\"您输入的账户名为:%s\" % (user.name))\n sure = input(\"确认存款请按1,返回菜单请按0\")\n if sure == \"1\":\n # 输入存款金额\n money = int(input(\"请输入需要存款的金额:\"))\n if money < 0:\n print(\"输入的存款金额不正确,请从新输入\")\n else:\n card.money += money\n print(\"成功存入%s元\" % (money))\n elif sure == \"0\":\n return\n\n def Get_money(self):\n \"\"\"取钱\"\"\"\n # 拿到一张卡\n card = self.Get_card_info()\n if not card:\n print(\"卡号不存在!\")\n else:\n if card.islock:\n print(\"卡被冻结,请先解锁!\")\n else:\n self.Check_pwd(card)\n money = int(input(\"请输入取款金额:\"))\n if money > 0 and money <= card.money:\n card.money -= money\n print(\"成功取款%s元,卡内余额%s元\" % (money, card.money))\n else:\n print(\"输入金额有误,请从新输入\")\n\n def Trans_money(self):\n card = self.Get_card_info()\n if not card:\n print(\"卡号不存在\")\n else:\n if card.islock:\n print(\"卡被冻结,请先解卡!\")\n else:\n if self.Check_pwd(card):\n otherid = int(input(\"请输入对方账号:\"))\n if otherid not in self.user_dict:\n print(\"转账账号不存在!\")\n else:\n other_user = self.user_dict[otherid]\n sure = input(\"您将给%s进行转账,确认请安1,返回主菜单请按其他键\" % (other_user.name))\n if sure == \"1\":\n money = int(input(\"请输入转账金额:\"))\n if money > 0 and money <= card.money:\n card.money -= money\n other_user.card.money += money\n print(\"您向%s成功转账%s元\" % (other_user.name, money))\n else:\n print(\"转账金额有误!\")\n else:\n return\n\n def Change_pwd(self):\n \"\"\"修改密码\"\"\"\n card = self.Get_card_info()\n if not card:\n print(\"卡不存在\")\n else:\n if card.islock:\n print(\"账户被冻结,请先解卡!\")\n else:\n choice = input(\"请选择改密方式:原密码修改:1 身份信息验证修改:2\")\n if choice == \"1\":\n if self.Check_pwd(card):\n passwd = self.Get_pwd()\n card.passwd = passwd\n print(\"****修改密码成功****\")\n elif choice == \"2\":\n userid = input(\"请输入身份证号码:\")\n user = self.user_dict[card.cardid]\n if userid == user.userid:\n passwd = self.Get_pwd()\n card.passwd = passwd\n print(\"****修改密码成功****\")\n else:\n print(\"身份信息有误!\")\n else:\n print(\"请输入正确的选项!\")\n\n def Lock(self):\n \"\"\"锁卡\"\"\"\n card = self.Get_card_info()\n if not card:\n print(\"卡不存在!\")\n else:\n if card.islock:\n print(\"卡已经被冻结\")\n else:\n choice = input(\"使用密码锁卡:1 使用身份信息验证锁卡:2\")\n if choice == \"1\":\n if self.Check_pwd(card):\n card.islock = True\n print(\"****锁卡成功****\")\n elif choice == \"2\":\n userid = input(\"请输入身份证号码:\")\n user = self.user_dict[card.cardid]\n if userid == user.userid:\n card.islock = True\n print(\"****锁卡成功****\")\n\n def Unlock(self):\n \"\"\"解锁\"\"\"\n card = self.Get_card_info()\n if not card:\n print(\"卡不存在!\")\n else:\n userid = input(\"请输入身份证号:\")\n user = self.user_dict[card.cardid]\n if userid == user.userid:\n card.islock = False\n print(\"****解卡成功****\")\n\n def New_card(self):\n \"\"\"补卡\"\"\"\n userid = input(\"请输入您的身份证号:\")\n if userid in self.user_id_dict:\n # 通过身份证找到卡号\n cardid = self.user_id_dict[userid]\n # 通过卡号找到用户\n user = self.user_dict[cardid]\n # 通过用户找到卡\n card = user.card\n # 生成卡号\n new_cardid = self.Get_cardid()\n print(new_cardid)\n # 更换字典的键\n self.user_dict[new_cardid] = self.user_dict.pop(card.cardid)\n # 更换卡号\n card.cardid = new_cardid\n # 更换身份证对应的卡号\n self.user_id_dict[userid] = new_cardid\n print(card.cardid)\n\n def Save(self):\n \"\"\"存储用户信息\"\"\"\n with open(\"user.txt\", \"wb\") as f:\n pickle.dump(self.user_dict, f)\n with open(\"userid.txt\", \"wb\") as f:\n pickle.dump(self.user_id_dict, f)\n","repo_name":"luyasi/python_study","sub_path":"python18/ATM/operation.py","file_name":"operation.py","file_ext":"py","file_size_in_byte":9347,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"12089386817","text":"from gmssl import sm4\n\nimport binascii\n\n\nsm4_key = 'ky95TLsSRgFcAYoGW7vH1AK3boH06SOg9uoj49phN8PJMpb01l2YHL65vMgRfTszlAMoLcIB3v11DCm637Qz2ni4okIRrw+8WiAJkahsI47+rcU475+VnDtC875P6R5Dgd8zZg6O4w2XMPvbH9em+JGjdMFPG6GlQlBfTQPeszf9WRW6rzUV9p92+TVkzGztIP+1P7VnCKjMVr1nFECusxQbE2XQUPBLq8eK8Sf2zoSTPN94ei4j0fOAd75SEvnof6H95z7tHtcsj4kgCfvLYb75PH5Xtw6sdFye++O9oMnDlwET326rm31p3lQXAGiyAcVAAkM5gfQ6I00brRxSHg==' # RSA私钥解密后, 不满16位则自动重复,取前16位\n\ndef SM4(input_data, encode=1):\n # SM4加密解密,默认为加密\n # gmssl==3.2.1\n\n if not isinstance(input_data, bytes):\n input_data = str(input_data).encode()\n\n key = (sm4_key * 16)[:16]\n if not isinstance(key, bytes):\n key = str(key).encode()\n\n crypt = sm4.CryptSM4()\n crypt_type = sm4.SM4_ENCRYPT if encode else sm4.SM4_DECRYPT\n crypt.set_key(key, crypt_type)\n\n try:\n return crypt.crypt_ecb(input_data)\n except Exception as e:\n print('Error: 国密SM4处理出错!!', e)\n return ''\n\n\nif __name__ == \"__main__\":\n # 加密:encode=1 解密:encode=0\n\n data_jia_bytes = SM4('12345')\n data_jie_bytes = SM4(data_jia_bytes, encode=0)\n print(data_jia_bytes) # bytes\n print(data_jie_bytes) # bytes\n\n data_jia_str = SM4('12345').hex()\n data_jie_str = SM4(binascii.unhexlify(data_jia_str), encode=0).decode()\n print(data_jia_str) # str\n print(data_jie_str)","repo_name":"lwaxx/small_example","sub_path":"Python/SM4加解密.py","file_name":"SM4加解密.py","file_ext":"py","file_size_in_byte":1428,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"81"} +{"seq_id":"70646129866","text":"import boto3\nimport sys\n\nsns_topic = 'arn:aws:sns:us-east-1::updated_beans_sns.fifo'\nsns_client = boto3.client('sns')\nfile_name = sys.argv[1]\nfile_handle = open(file_name)\n\nfor message_data in file_handle:\n message_values = message_data.strip().split(':')\n quantity = int(message_values[2])\n if quantity > 0:\n response = sns_client.publish(\n TopicArn=sns_topic,\n Message=message_data.strip(),\n Subject='New bean delivery',\n MessageGroupId='bean_message_group'\n )\n \n print(response)\n else:\n response = sns_client.publish(\n TopicArn=sns_topic,\n Message=message_data.strip(),\n Subject='New bean delivery',\n MessageAttributes={\n 'inventory_alert': {\n 'DataType': 'String',\n 'StringValue': 'out_of_stock'\n }\n },\n MessageGroupId='bean_message_group'\n )\n \n print(response)","repo_name":"whbb98/aws-dev-Amazon_Cognito","sub_path":"resources/sqs-sns/send_beans_update.py","file_name":"send_beans_update.py","file_ext":"py","file_size_in_byte":1014,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"81"} +{"seq_id":"38841503976","text":"import urllib\nimport urllib.request \nimport bs4 as bs\nimport pandas \nimport csv\n#\n#jalan-tol-balikpapan-samarinda\nsoup1 = urllib.request.urlopen('https://kppip.go.id/proyek-prioritas/jalan/jalan-tol-balikpapan-samarinda/').read()\n##Melakukan request dan open terhadap url yang di inginkan\np_soup1 = bs.BeautifulSoup(soup1,'lxml')\n#BeautifulSoup\n#mencari class container , karena sudah tahu data terletak dimana \n#maka index data yang di tuju adalah 3\ntitle_1 = p_soup1.findAll('div',class_='container')[3]\nget_title_1 = title_1.h1.text\n#mendapatkan title yang di inginkan\nprint(get_title_1)\n#membuat suatu list\nmylist = []\nmylist2=[]\n#menambahkan elemen setiap list\nmylist.append(get_title_1)\nprint(mylist)\ntabel_1 = p_soup1.findAll('table')[0]\nget_tbody_1 = tabel_1.findAll('tbody')[0]\nget_tr_1 = get_tbody_1.findAll('tr')[0]\nget_invest1 = get_tr_1.findAll('td')[2].get_text()\nprint(get_invest1)\n#mendapatkan nilai investasi yang di inginkan\n#menambahkan element list\nmylist2.append(get_invest1)\nprint (mylist2)\n\n\n#jalan-tol-manado-bitung\nsoup2 = urllib.request.urlopen('https://kppip.go.id/proyek-prioritas/jalan/jalan-tol-manado-bitung/').read()\np_soup2 = bs.BeautifulSoup(soup2,'lxml')\ntitle_2 = p_soup2.findAll('div',class_='container')[3]\nget_title_2 = title_2.h1.text\nprint(get_title_2)\nmylist.append(get_title_2)\nprint(mylist)\ntabel_2 = p_soup2.findAll('table')[0]\nget_tbody_2 = tabel_2.findAll('tbody')[0]\nget_tr_2 = get_tbody_2.findAll('tr')[0]\nget_invest2 = get_tr_2.findAll('td')[2].get_text()\nprint(get_invest2)\nmylist2.append(get_invest2)\nprint(mylist)\n'''\ndf = pandas.DataFrame(data={\"proyek_jalan\": mylist, \"nilai_investasi\": mylist2})\ndf.to_csv(\"./file.csv\", sep=',',index=False)\n'''\n#jalan-tol-serang-panimbang\nsoup3 = urllib.request.urlopen('https://kppip.go.id/proyek-prioritas/jalan/jalan-tol-serang-panimbang/').read()\np_soup3 = bs.BeautifulSoup(soup3,'lxml')\ntitle_3 = p_soup3.findAll('div',class_='container')[3]\nget_title_3 = title_3.h1.text\nprint(get_title_3)\ntabel_3 = p_soup3.findAll('table')[0]\nget_tbody_3 = tabel_3.findAll('tbody')[0]\nget_tr_3 = get_tbody_3.findAll('tr')[0]\nget_invest3 = get_tr_3.findAll('td')[2].get_text()\nprint(get_invest3)\nmylist.append(get_title_3)\nmylist2.append(get_invest3)\n\n\n#ERROR 404\n'''\nsoup4 = urllib.request.urlopen('https://kppip.go.id/proyek-prioritas/jalan/8-ruas-jalan-tol-trans-sumatera/').read()\np_soup4 = bs.BeautifulSoup(soup4,'lxml')\ntitle_4 = p_soup4.findAll('div',class_='container')[3]\nget_title_4 = title_4.h1.text\nprint(get_title_4)\ntabel_4 = p_soup4.findAll('table')[0]\nget_tbody_4 = tabel_4.findAll('tbody')[0]\nget_tr_4 = get_tbody_4.findAll('tr')[1]\nget_td_4 = get_tr_4.findAll('td')[3].get_text()\nprint(get_td_4)\n'''\n#jalan-tol-probolinggo-banyuwangi-17036km\nsoup5 = urllib.request.urlopen('https://kppip.go.id/proyek-prioritas/jalan/jalan-tol-probolinggo-banyuwangi-17036km//').read()\np_soup5 = bs.BeautifulSoup(soup5,'lxml')\ntitle_5 = p_soup5.findAll('div',class_='container')[3]\nget_title_5 = title_5.h1.text\nprint(get_title_5)\ntabel_5 = p_soup5.findAll('table')[0]\nget_tbody_5 = tabel_5.findAll('tbody')[0]\nget_tr_5 = get_tbody_5.findAll('tr')[1]\nget_invest5 = get_tr_5.findAll('td')[2].get_text()\nprint(get_invest5)\n\nmylist.append(get_title_5)\nmylist2.append(get_invest5)\n\n#jalan-tol-yogyakarta-bawen-71km\n\nsoup6 = urllib.request.urlopen('https://kppip.go.id/proyek-prioritas/jalan/jalan-tol-yogyakarta-bawen-71km/').read()\np_soup6 = bs.BeautifulSoup(soup6,'lxml')\ntitle_6 = p_soup6.findAll('div',class_='container')[3]\nget_title_6 = title_6.h1.text\nprint(get_title_6)\ntabel_6 = p_soup6.findAll('table')[0]\nget_tbody_6 = tabel_6.findAll('tbody')[0]\nget_tr_6 = get_tbody_6.findAll('tr')[1]\nget_invest6 = get_tr_6.findAll('td')[2].get_text()\nprint(get_invest6)\n\n\nmylist.append(get_title_6)\nmylist2.append(get_invest6)\n\n\n#\n\ndf = pandas.DataFrame(data={\"nama_proyek\": mylist, \"nilai_investasi\": mylist2})\ndf.to_csv(\"ProyekJalan\", sep=',',index=False)\n\n\n#mylist.append(get_invest1)\n\n","repo_name":"aldomatthew/WebService_Progif","sub_path":"Progif/src/ProyekPrioritas/ProyekJalan/PrioritasJalan.py","file_name":"PrioritasJalan.py","file_ext":"py","file_size_in_byte":3964,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"41636050827","text":"from telegram.ext import CommandHandler, MessageHandler, Filters, Updater\n\nimport telegram\n\nfrom functools import wraps\n\nimport os\nimport pickle\nimport datetime as dt\n\nfrom lib import *\n\nclass TelegramError(SystemError):\n pass\n\nclass Chat:\n\n def __init__(self, chat_id):\n self.chat_id = chat_id\n self.started = False\n\n self.data = {}\n\nclass Bot:\n \"\"\" Interface for building Telegram Bots, built upon the python-telegram-bot extension module.\n\n Example:\n bot = Bot()\n bot.init()\n \"\"\"\n\n @staticmethod\n def START_TEXT(json):\n return \"Hello World!\"\n\n @staticmethod\n def UNKNOWN_TEXT(json):\n return \"Unknown command `{text}`.\".format(**json)\n\n @staticmethod\n def parse_context(context):\n return {\n 'bot' : context.bot\n }\n\n @staticmethod\n def parse_update(update):\n return {\n 'chat_id' : update.message.chat_id,\n 'date' : update.message.date,\n 'msg' : update.message,\n 'text' : update.message.text,\n 'audio' : update.message.audio,\n 'video' : update.message.video,\n 'voice' : update.message.voice,\n }\n @staticmethod\n def parse(update, context):\n json = {}\n json.update(Bot.parse_update(update))\n json.update(Bot.parse_context(context))\n return json\n\n @staticmethod\n def lock_start(callback):\n @wraps(callback)\n def new_callback(self, update, context):\n json = self.parse(update, context)\n\n if self.started(json):\n return callback(self, update, context)\n else:\n return\n return new_callback\n\n def __init__(self, *args, **kwargs):\n debug = kwget('debug', kwargs, False)\n level = kwget('level', kwargs, None)\n\n self.debug = Debugger(debug, level)\n\n self.fname = kwget('fname', kwargs, 'BOT')\n\n self.handlers = []\n self.chats = {}\n\n self.debug[0]('[Bot __init__ Ready]')\n\n def cmd_handler(self, cmd, **kwargs):\n def decor(callback):\n handler = CommandHandler(cmd, lambda update, context: callback(self, update, context), **kwargs)\n self.handlers.append(handler)\n return handler \n return decor \n\n def msg_handler(self, msg, **kwargs):\n def decor(callback):\n handler = MessageHandler(msg, lambda update, context: callback(self, update, context), **kwargs)\n self.handlers.append(handler)\n return handler \n return decor\n\n def add_handlers(self):\n for handler in self.handlers:\n self.dispatcher.add_handler(handler)\n\n def build(self):\n self.updater = Updater(self.token, use_context=True)\n\n self.dispatcher = self.updater.dispatcher\n\n self.add_handlers()\n\n def init(self):\n self.debug[0]('[Init]')\n\n ## Build Handlers\n self.debug[1]('[Build]')\n self.build()\n\n ## Setup Polling\n self.debug[1]('[Start Polling]')\n self.updater.start_polling()\n self.updater.idle()\n\n def __enter__(self):\n self.init_open()\n\n def __exit__(self, *args):\n self.init_close()\n\n def init_open(self):\n \"\"\"\n \"\"\"\n ## Default /start command\n @self.cmd_handler('start')\n def start(self, update, context):\n self.debug[1]('[cmd :: Start]')\n\n json = self.parse(update, context)\n\n self.debug[2]('[obj :: json]', json)\n\n if self.started(json):\n self.debug[1]('[Already Started for {}]'.format(json['chat_id']))\n return\n else:\n self.debug[1]('[Starting for {}]'.format(json['chat_id']))\n self.chats[json['chat_id']] = Chat(json['chat_id'])\n\n kw = {\n 'chat_id' : json['chat_id'],\n 'text' : self.START_TEXT(json),\n 'parse_mode' : telegram.ParseMode.MARKDOWN,\n }\n\n self.debug[2]('[obj :: kw]', kw)\n\n json['bot'].send_message(**kw)\n\n self.chats[json['chat_id']].started = True\n\n return start\n\n def init_close(self):\n \"\"\"\n \"\"\"\n ## Unknown Command\n @self.msg_handler(Filters.command)\n @self.lock_start\n def unknown(self, update, context):\n self.debug[1]('[cmd :: unknown]')\n\n json = self.parse(update, context)\n\n self.debug[2]('[obj :: json]', json)\n\n kw = {\n 'chat_id' : json['chat_id'],\n 'text' : self.UNKNOWN_TEXT(json),\n 'parse_mode' : telegram.ParseMode.MARKDOWN,\n }\n\n self.debug[2]('[obj :: kw]', kw)\n\n json['bot'].send_message(**kw)\n\n return unknown\n\n def started(self, json):\n return (json['chat_id'] in self.chats) and (self.chats[json['chat_id']].started)\n\n @staticmethod\n def load(**kwargs):\n \"\"\"\n \"\"\"\n bot = Bot(**kwargs)\n bot.debug[0]('[Load]')\n try:\n with open(\"{}.bot\".format(bot.fname), 'rb') as file:\n bot.debug[1]('[Loading Bot]')\n bot.chats.update(pickle.load(file))\n bot.debug[1]('[Bot Loaded]')\n return bot\n except FileNotFoundError:\n bot.debug[1]('[Creating new Bot]')\n return bot\n\n def dump(self):\n \"\"\"\n \"\"\"\n self.debug[0]('[Dump]')\n\n with open(\"{}.bot\".format(self.fname), 'wb') as file:\n pickle.dump(self.chats, file)\n\n def run(self):\n try:\n self.init()\n except KeyboardInterrupt:\n pass\n except:\n raise\n finally:\n self.dump()\n\n @property\n def token(self):\n self.debug[1]('[Load Token]')\n return self.__load_token()\n\n @staticmethod\n def __load_token():\n from dotenv import load_dotenv\n \n load_dotenv()\n\n return os.getenv(\"TELEGRAM_TOKEN\")","repo_name":"pedromxavier/760D","sub_path":"src/telebot/core.py","file_name":"core.py","file_ext":"py","file_size_in_byte":6101,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"5146488744","text":"import urllib\nfrom flask import Flask\nfrom datetime import datetime\nfrom flask_sqlalchemy import SQLAlchemy\napp = Flask(__name__)\nconnection_string =\\\n urllib.parse.quote_plus('Driver={ODBC Driver 17 for SQL Server};Server=localhost\\MSSQLSERVER01;Database=db_Data;Trusted_Connection=yes;')\nconnection_string = \"mssql+pyodbc:///?odbc_connect=%s\" % connection_string\napp.config['SQLALCHEMY_DATABASE_URI'] = connection_string\napp.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False\nsession_option = {\n 'autocommit': True\n}\ndb = SQLAlchemy(app, session_options=session_option)\ndb.init_app(app)\nsession1 = db.session\n@app.route('/')\ndef testdb():\n try:\n session1.begin()\n session1.execute(\"update [table] set UserName = 'Ksing' where ScanSubscriptionID = 1600336614\")\n session1.commit()\n return '

It works.

'\n except Exception as e:\n raise e\n finally:\n print(f'Time is :{datetime.utcnow()}')\n #session1.close()\n\n\nif __name__ == '__main__':\n app.run(debug=True)\n","repo_name":"kanwar28/testrepo","sub_path":"app2.py","file_name":"app2.py","file_ext":"py","file_size_in_byte":1028,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"36838484168","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\n\nCommand Injection Services\nAccess to SCOS-2000 commanding system\n\n\"\"\"\n\nimport sys\nimport CORBA, IBASE, ITC, ITC_INJ, ITC_INJ__POA\n\n#==============================================================================\n# Implement client side view\n#==============================================================================\n\ntry:\n class CommandInjectMngrView(ITC_INJ__POA.CommandInjectMngrView):\n \n def __init__(self):\n print('Creating View object...')\n \n self.requestCounter = 0\n \n self.requestStatusList = []\n self.systemStatusList = []\n def ping(self):\n print('Pong')\n \n def updateRequestStatus(self,status):\n print('Request Status Update: ')\n print(status)\n self.requestStatusList.append(status)\n \n if self.requestStatusList[self.requestCounter].m_stage == 's': \n print(\"Current command stage is PTV_STATIC\")\n \n if self.requestStatusList[self.requestCounter].m_stage_status == 128: \n print(\"\\033[1;37;41m CEV FAILED \\033[0m\")\n \n self.requestCounter = self.requestCounter + 1\n #return self.requestStatusList\n \n def updateSystemStatus(self,status):\n print('System Status Update: ')\n print(status)\n self.systemStatusList.append(status)\n #return self.systemStatusList\n \n injMngrViewObject = CommandInjectMngrView()\n\n#==============================================================================\n# Get Telecommand Parameter Injection server manager\n#==============================================================================\n\n orb = CORBA.ORB_init()\n tcInjServerMngr = orb.string_to_object(\"corbaname::192.168.56.101:20001/NameService#TC_INJ_002\")\n # in case tcInjServerMngr is a generic CORBA.Object, for safety purposes \n tcInjServerMngr = tcInjServerMngr._narrow(ITC_INJ.TCinjectServerMngr)\n\n#==============================================================================\n# Activate View object \n#==============================================================================\n\n # creates omniORB.PortableServer.POA object with persistent object policies\n# poa = orb.resolve_initial_references(\"omniINSPOA\")\n# poaId = \"MyObjectId\"\n# poa.activate_object_with_id(poaId,injMngrViewObject)\n\n poa = orb.resolve_initial_references(\"RootPOA\")\n poa.activate_object(injMngrViewObject)\n cmdInjMngrView = poa.servant_to_reference(injMngrViewObject)\n\n # activate the poa, that incoming requests are served\n poaManager = poa._get_the_POAManager()\n poaManager.activate()\n\n#==============================================================================\n# Get Command Injection Interface from server \n#============================================================================== \n \n cmdInjMngr = tcInjServerMngr.getTCinjectMngr(cmdInjMngrView, \"Client\")\n\n#==============================================================================\n# Definition of a Command Request Structure\n#==============================================================================\n\n\t# empty time, command is not time tagged\n _emptyTime = IBASE.Time(0,0,True)\n \n _context = \"context\"\n _destination = \"dest\"\n _mapId = 0xFF\n _vcId = 0xFF\n _cmdName = \"PPC00201\"\n _cmdParameters = [ITC.CommandParam(m_name='DSP00010', m_isEngValue=False, m_unit='', m_radix='H', m_value=IBASE.Variant(m_ulongFormat = 1140863488)),\n ITC.CommandParam(m_name='DSP00011', m_isEngValue=False, m_unit='', m_radix='H', m_value=IBASE.Variant(m_ulongFormat = 2)),\n ITC.CommandParam(m_name='PPP00003', m_isEngValue=False, m_unit='', m_radix='H', m_value=IBASE.Variant(m_ulongFormat = 0)),\n ITC.CommandParam(m_name='PPP00003', m_isEngValue=False, m_unit='', m_radix='H', m_value=IBASE.Variant(m_ulongFormat = 1))]\n _paramSets = []\n _info = ITC_INJ.ReleaseInfo(_emptyTime,_emptyTime,_emptyTime,_emptyTime,ITC.CHECK_ENABLED,ITC.CHECK_ENABLED,False,0x80)\n _ilockType = ITC.IL_NONE\n _ilockStageType = ITC_INJ.IL_UV_GS_ACCEPT\n _additionalInfo = \"addInfo\"\n _tcRequestID = 0\n \n cmdRequest = ITC_INJ.CommandRequest(_context,_destination,_mapId,_vcId,_cmdName,_cmdParameters,_paramSets,_info,_ilockType,_ilockStageType,_additionalInfo,_tcRequestID)\n\n#==============================================================================\n# Inject Command\n#==============================================================================\n \n print(\"Injecting command '\" + _cmdName + \"'...\")\n injRequestID = cmdInjMngr.injectCmd(cmdRequest)\n \n # default is BD, AD also possible (Command Frame Type)\n print(\"Command frame type is: \" + str(cmdInjMngr.getTransferMode()))\n \n #orb.run()\n\n#==============================================================================\n \nexcept Exception as e:\n print('\\033[1;37;41m Exited with exception:', e, '\\033[0m')\n # inform Command Inject Manager that Command Inject Manager View has finished with it\n # close connection, no further callbacks \n cmdInjMngr.deregister()\n sys.exit(1)\n \nelse:\n print('\\033[1;37;42m Exited without exception \\033[0m')\n cmdInjMngr.deregister()\n sys.exit(0)\n ","repo_name":"MuelA1/SCOS_CORBA","sub_path":"Scripts/TCInjection.py","file_name":"TCInjection.py","file_ext":"py","file_size_in_byte":5566,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"21333461352","text":"import asyncio\nimport websockets\nimport os\n\nfrom config import get_save_location\nfrom utils.logging import logger\nfrom websocket.exception import WebsocketRequestException\nfrom websocket.packet import Packet\nfrom websocket.connection import dispatch, receive, register_client, unregister_client\nfrom websocket.events import on_download, on_search, on_pause, on_play, on_skip\n\n\nasync def handler(websocket: websockets.WebSocketCommonProtocol, path):\n # A copy of this callback is ran for each individual connection\n register_client(websocket)\n while not websocket.closed:\n try:\n packet: Packet = await receive(websocket)\n\n logger.info(f'Received a {packet.event} request from {packet.user}')\n event_params = (websocket, packet)\n\n if packet.event == 'download':\n await on_download(*event_params)\n elif packet.event == 'search':\n await on_search(*event_params)\n elif packet.event == 'pause':\n await on_pause(*event_params)\n elif packet.event == 'play':\n await on_play(*event_params)\n elif packet.event == 'skip':\n await on_skip(*event_params)\n else:\n logger.error(f'Received unrecognized request')\n error = WebsocketRequestException(\n event=packet.event,\n body='Invalid request'\n )\n return await dispatch(websocket, error)\n except websockets.ConnectionClosed:\n unregister_client(websocket)\n\n\nif __name__ == '__main__':\n ip = os.environ.get('IP_ADDRESS', 'localhost')\n port = os.environ.get('PORT', '100000')\n\n logger.info(f'Starting server at {ip}:{port}')\n logger.info(f'Saving media at {get_save_location()}')\n\n server = websockets.serve(handler, ip, port)\n asyncio.get_event_loop().run_until_complete(server)\n asyncio.get_event_loop().run_forever()\n","repo_name":"Xetera/StrawberryPlayer","sub_path":"server/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1976,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"81"} +{"seq_id":"21209212947","text":"from collections import defaultdict\nfrom itertools import product\nimport os\nimport random\nimport networkx as nx\nfrom tqdm import tqdm\nimport matplotlib.pyplot as plt\nimport matplotlib.lines as mlines\n\nimport osmnx as ox\nimport geopandas as gpd\nfrom shapely.geometry import Point\n\nfrom dwave.system import DWaveSampler, EmbeddingComposite\n\n# Set the environment variable for your DWave API token\nwith open('./dwave_api_token.txt', 'r') as f:\n os.environ['DWAVE_API_TOKEN'] = f.readline()\n\nSEED = 11223344550\nrandom.seed(SEED)\n\nA, B = 100, 1\nNUM_READS = 500\n\n# Number of random points in the city of Calgary on which we will compute the solution of the TSP.\n# Due to the limited connectivity of the chimera graph of the D-Wave QPU, this must be kept fairly low in order\n# to find a valid embedding.\nn_points = 7\n\n# Load the city boundary data\ncity = gpd.read_file('CityBoundary/geo_export_829045c7-570b-4230-a4fd-8e88e4b92774.shp')\n\n# Get the bounds of the city\nminx, miny, maxx, maxy = city.geometry.total_bounds\n\n# Get a graph of the road network in Calgary\nprint('Obtaining graph of the city of Calgary from OSM...')\ncalgary_graph = ox.graph_from_bbox(maxy, miny, maxx, minx, network_type='drive')\n\n# Generate n_points random points within the city of Calgary\npoints = set()\nwhile len(points) < n_points:\n point = Point(random.uniform(minx, maxx), random.uniform(miny, maxy))\n if not any(city.geometry.contains(point)):\n continue\n # Replace the random point with the nearest graph node\n nearest_node = ox.nearest_nodes(calgary_graph, point.x, point.y)\n if nearest_node not in points:\n points.add(nearest_node)\npoints = list(points)\n\n# Compute the shortest paths between each pair of points\nweighted_edges = []\nweight_dict = {}\nshortest_path_dict = {}\nfor start_node, end_node in tqdm(\n product(points, points), total=n_points**2, desc='Computing network shortest paths'\n):\n if start_node == end_node:\n continue\n\n # Find the shortest path and its length in km\n shortest_path = nx.shortest_path(calgary_graph, start_node, end_node, weight='length')\n shortest_path_length = sum(\n calgary_graph.edges[shortest_path[i], shortest_path[i + 1], 0]['length'] for i in range(len(shortest_path) - 1)\n )\n # Convert the length to km\n shortest_path_length /= 1000\n\n weighted_edges.append((start_node, end_node, shortest_path_length))\n weight_dict[(start_node, end_node)] = shortest_path_length\n shortest_path_dict[(start_node, end_node)] = shortest_path\n\n# Create a graph representing the order locations and the shortest paths between them\ntsp_graph = nx.DiGraph()\ntsp_graph.add_weighted_edges_from(weighted_edges)\n\n# Define the dicitonary to hold our QUBO coefficients\nQUBO_matrix = defaultdict(lambda: 0)\n\n# The first part of the Hamiltonian enforces that each vertex only appears once in a cycle\nfor v in range(n_points):\n for i in range(n_points):\n QUBO_matrix[((v, i), (v, i))] -= A\n for j in range(i + 1, n_points):\n QUBO_matrix[((v, i), (v, j))] += 2 * A\n\n# The second enforces that there must be an ith node in the cycle for each i\nfor i in range(n_points):\n for v in range(n_points):\n QUBO_matrix[((v, i), (v, i))] -= A\n for w in range(v + 1, n_points):\n QUBO_matrix[((v, i), (w, i))] += 2 * A\n\n# The third enforces that two vertices cannot appear consecutively in the cycle if there is no edge connecting them\nnode_list = list(tsp_graph.nodes)\nedge_set = set(tsp_graph.edges)\nfor u, v in product(range(n_points), range(n_points)):\n if (node_list[u], node_list[v]) in edge_set:\n continue\n for i in range(n_points):\n QUBO_matrix[((u, i), (v, (i + 1) % n_points))] += A\n\n# The last adds the TSP constraint, i.e. that the sum of the weights along the path is minimized\nfor u, v in product(range(n_points), range(n_points)):\n if (node_list[u], node_list[v]) in edge_set:\n for i in range(n_points):\n QUBO_matrix[((u, i), (v, (i + 1) % n_points))] += B * weight_dict[(node_list[u], node_list[v])]\n\n# Instantiate the DWave sampler and sample from the QUBO model\nsampler = DWaveSampler(solver={'qpu': True})\nsampler_embedded = EmbeddingComposite(sampler)\nresponse = sampler_embedded.sample_qubo(QUBO_matrix, num_reads=NUM_READS)\n\nsolution = response.first.sample\n\n# Check that each vertex is visited exactly once\nfor v in range(n_points):\n s = 0\n for i in range(n_points):\n s += solution[(v, i)]\n assert s == 1, f'Node {v} visited more or less than one time!'\n\n# Check that each step has exactly one associated vertex\nfor i in range(n_points):\n s = 0\n for v in range(n_points):\n s += solution[(v, i)]\n assert s == 1, f'Step {i} is not associated to exaclty one node!'\nprint('The solution represents a valid path!')\n\n# Get the nodes associated with the TSP route\npath = [-1] * n_points\nfor (v, i), x in solution.items():\n if x == 1:\n path[i] = v\n\n# Rotate the path such that we start at node 0\nzero_index = path.index(0)\npath = path[zero_index:] + path[:zero_index]\n\n# Replace the node indices by their labels in the tsp_graph\npath = [node_list[node] for node in path]\n\nprint(f'Solution: {path}')\nprint(\n f'Path length: {sum(tsp_graph.edges[path[i], path[(i + 1) % n_points]][\"weight\"] for i in range(n_points)):.3f} km'\n)\n\n# Check if the solution provided by networkx agrees with our solution\nif n_points < 8:\n print('Computing networkx solution...')\n nx_solution = nx.algorithms.approximation.traveling_salesman_problem(tsp_graph, weight='weight', nodes=points)[:-1]\n for i in range(n_points):\n if path[i:] + path[:i] == nx_solution:\n print('Solution agrees with networkx!')\n break\n else:\n fail_str = (\n f'Solution does not agree with networkx! Try adjusting A (currently set to {A}) and\\n'\n + f'B (currently set to {B}). A lower A/B ratio will increase the importance of minimizing\\n'\n + f'the total path length, but setting A/B too low will break the other constraints! Also,\\n'\n + f'increasing NUM_READS (currently set to {NUM_READS}) will increase the probability of\\n'\n + f'finding a minimum energy solution.'\n )\n print(fail_str)\n nx_path_length = sum(\n tsp_graph.edges[nx_solution[i], nx_solution[(i + 1) % n_points]][\"weight\"] for i in range(n_points)\n )\n print(f'Networkx path length: {nx_path_length:.3f} km')\n\n# Plot the solution\nroute = [shortest_path_dict[(path[i], path[(i + 1) % n_points])] for i in range(n_points)]\nroute_colors = ['red'] * n_points\nif n_points < 8:\n route = [shortest_path_dict[(nx_solution[i], nx_solution[(i + 1) % n_points])] for i in range(n_points)] + route\n route_colors = (['green'] * n_points) + route_colors\nox.plot_graph_routes(calgary_graph, route, route_colors=route_colors, show=False, close=False)\n\nlegend_handles = [mlines.Line2D([], [], color='red', marker='_', markersize=15, label='Quantum solution')]\nif n_points < 8:\n legend_handles.append(mlines.Line2D([], [], color='green', marker='_', markersize=15, label='networkx solution'))\nplt.legend(handles=legend_handles, loc='upper right')\nplt.show()\n","repo_name":"adamreidsmith/dwave-models","sub_path":"travelling_salesman.py","file_name":"travelling_salesman.py","file_ext":"py","file_size_in_byte":7219,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"34469718668","text":"\n\ndef get_next(start, used):\n\tl = []\n\n\tif start + '1' not in used:\n\t\tl.append(start + '1')\n\tif start + '0' not in used:\n\t\tl.append(start + '0')\n\n\treturn l\n\ndef get_arrangements(n, current, used, concat, depth=1):\n\tif depth == 2 ** n:\n\t\tresults.append(concat)\n\t\treturn 1\n\n\tfor option in get_next(current[1:], used):\n\t\tused.add(option)\n\t\tget_arrangements(n, option, used, concat + option[-1], depth + 1)\n\t\tused.remove(option)\n\n\nn = 5\nstart = '0' * n\nused = set([start])\n\nresults = []\nget_arrangements(n, start, used, start)\n\nresults = [int(i, 2) >> (n - 1) for i in results]\nprint(sum(results))","repo_name":"matejm/project-euler","sub_path":"problem265.py","file_name":"problem265.py","file_ext":"py","file_size_in_byte":592,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"1560172588","text":"import numpy as np\r\ndef countSort(L):\r\n\tn = len(L)\r\n\tm = np.max(L)+1\r\n\thisto = [0]*m\r\n\tfor i in range(n):\r\n\t\thisto[L[i]] += 1\r\n\tT = []\r\n\tfor i in range(m):\r\n\t\tfor j in range(histo[i]):\r\n\t\t\tT.append(i)\r\n\treturn T\r\n\r\nimport random as rand\r\nL = [rand.randint(0,20) for i in range(10)]\r\nT = countSort(L)\r\nprint(L)\r\nprint(T)\r\n\r\n\r\ndef longueur(L):\r\n if L == []:\r\n return 0\r\n return 1 + longueur(L[1:])\r\n\r\nprint(longueur(L))\r\n\r\n\r\n\r\ndef countSortZ(L):\r\n\tm = np.min(L)\r\n\tfL = [n-m for n in L]\r\n\treturn [n+m for n in countSort(fL)]\r\n\r\nL = [rand.randint(-10,10) for i in range(10)]\r\nT = countSortZ(L)\r\nprint(L)\r\nprint(T)","repo_name":"ltheodon/Tris","sub_path":"countSort.py","file_name":"countSort.py","file_ext":"py","file_size_in_byte":622,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"13331774077","text":"#!/bin/python3\n# Part 1\nwordbank= [\"indentation\", \"spaces\"] \n\n# Part 2\ntlgstudents= ['Albert', 'Anthony', 'Brenden', 'Craig', 'Deja', 'Elihu', 'Eric', 'Giovanni', 'James', 'Joshua', 'Maria', 'Mohamed', 'PJ', 'Philip', 'Sagan', 'Suchit', 'Meka', 'Trey', 'Winton', 'Xiuxiang', 'Yaping']\n\n# Part 3\nwordbank.append(4)\n\n#Part 4 & 5\ndef get_number(message):\n while True: \n try:\n number = int(input(message))\n if (number >= 0) and (number <=len(tlgstudents)):\n return number - 1\n except ValueError:\n print(f\"Not an integer between 0 and {len(tlgstudents) - 1}\")\n\nnum = get_number(f\"Enter a number, between 0 and {len(tlgstudents) - 1}: \")\n\n# Part 5b\nstudent = tlgstudents[num]\n\n# Part 6\nprint(f\"{student} alwayse use {wordbank[-1]} {wordbank[1]} to indent.\")\n","repo_name":"hoolies/mycode","sub_path":"61/list_input_concantenation.py","file_name":"list_input_concantenation.py","file_ext":"py","file_size_in_byte":817,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"34237784263","text":"import argparse\r\nimport os\r\nimport sys\r\n\r\nimport torch\r\nimport tensorflow.compat.v1 as tf\r\nimport tensorflow as tf2\r\nfrom tfdeterminism import patch\r\n\r\nimport time\r\nimport pickle as pk\r\nimport numpy as np\r\n\r\nimport operator\r\nimport random as rn\r\nfrom torch.utils.tensorboard import SummaryWriter\r\nfrom functools import reduce\r\n\r\nimport model.reader as reader\r\nimport model.config as config\r\nimport model.train as train\r\nimport model.evaluate as evaluate\r\nimport model.fun_eval as fun_eval\r\n#import plotting.tsne as tsne_plot\r\nfrom model.model import Model\r\nfrom model.util import load_train_args, load_ent_vecs\r\nfrom preprocessing.util import reverse_dict, load_wiki_name_id_map, load_wikiid2nnid\r\nfrom evaluation.metrics import Evaluator, metrics_calculation, threshold_calculation, _filtered_spans_and_gm_gt_list\r\n\r\n\"\"\"\r\n#############################################################################################################################################################################################\r\n# FONCTIONS #\r\n# - tsne_fusion : GÉNÈRE UNE REPRÉSENTATION FUSIONNANT SUR UN MÊME GRAPHES LES T-SNE DES EMBEDDINGS DE MÊME TYPE POUR DIFFÉRENTS MODÈLES. S'OCCUPE DE RÉCUPÉRER LES EMBEDDINGS NÉCESSAIRES. #\r\n# - melting_embeddings : CONCATÈNE LES EMBEDDINGS DE DIFFÉRENTS TYPES POUR EN FAIRE UN AFFICHAGE TENSORBOARD. /!\\ INNOPÉRANT, NE FONCTIONNE PAS NI NE PEUT ÊTRE DÉBUGGUÉ /!\\ #\r\n# - extract_embeddings : EXTRAIT LES EMBEDDINGS (METADATA INCLUS POUR LES ENTITÉS) DEMANDÉS POUR TOUS LES MODÈLES DEMANDÉS #\r\n#############################################################################################################################################################################################\r\n\"\"\"\r\n\r\ntf.disable_eager_execution() #Compatibilité V1 to V2\r\ntf.disable_v2_behavior() #Compatibilité V1 to V2\r\n#tf.debugging.set_log_device_placement(True)\r\n\r\ndef extract_embeddings(melting_args, to_extract=set([0,1,2,3]), verbose=True):\r\n final_emb_model = dict()\r\n for experiment_name, training_name in melting_args: # OLDVERSION for el_datasets, el_names, model in list_model:\r\n ## RETRIEVE THE MODEL\r\n (el_datasets, el_names, model), eval_args, train_args = fun_eval.retrieve_model_args(experiment_name, training_name)\r\n model_name = model.args.experiment_name\r\n final_emb_model[model_name] = [[],[],[],[],[]]\r\n # extract the embeddings from the model\r\n for datasets, names in zip([el_datasets], [el_names]):\r\n ## RUN THE MODEL\r\n model.restore_session(\"el\")\r\n test_iterator, test_handle = fun_eval.ed_el_testset_handles(model.sess, names, datasets)\r\n model.sess.run(test_iterator.initializer)\r\n cand_entities, ground_truth, projectors, _ = fun_eval.run_model_ent_and_proj(model, test_handle, verbose=verbose)\r\n ## TRAITEMENT PROJECTORS\r\n for index_tensor in range(len(projectors)):\r\n if index_tensor > 3: break #le cas spécifique du \"bert_embeddings\" ne nous intéresse pas\r\n if index_tensor not in to_extract: continue #only requested\r\n for index_batch in range(len(projectors[index_tensor])):\r\n tensor = projectors[index_tensor][index_batch]\r\n ts = np.shape(tensor)\r\n nts = (reduce(operator.mul,ts[0:-1],1),ts[-1])\r\n tensor = np.reshape(tensor,nts)\r\n if index_tensor == 1: # catch metadata for entities\r\n metadata = fun_eval.generate_cand_metadata(cand_entities[index_batch], eval_args, details=True)\r\n final_emb_model[model_name][-1].append(metadata)\r\n final_emb_model[model_name][index_tensor].append(tensor)\r\n tf.reset_default_graph()\r\n return final_emb_model\r\n\r\ndef tsne_fusion(melting_args, summary_folder, use_old_data=False, verbose=True):\r\n final_emb_summary = SummaryWriter(summary_folder + 'global_embedding_projector/')\r\n if use_old_data :\r\n print(\"LOADING DATA... \",end=\"\")\r\n names = pk.load(open(summary_folder+\"names_embs.pk\",\"rb\"))\r\n embs = pk.load(open(summary_folder+\"embs_embs.pk\",\"rb\"))\r\n print(\"DONE\")\r\n else:\r\n print(\"GENERATING AND SAVING DATA\")\r\n top = time.time()\r\n extraction = set([0,2,3]) # 0 : Word EMbedding - 1 : Entities Embeddings - 2 : Context Embeddings - 3 : Mention Embeddings\r\n final_emb_model = extract_embeddings(melting_args,to_extract = extraction)\r\n names = list(final_emb_model.keys()) # list of string. Dimension = nb de model chargés\r\n embs = list(final_emb_model.values()) # list of list of list of tensor. Dimension = nb model x 4 x 4\r\n pk.dump(names,open(summary_folder+\"names_embs.pk\",\"wb\"))\r\n pk.dump(embs,open(summary_folder+\"embs_embs.pk\",\"wb\"))\r\n print(\"DONE IN {}s\".format(int(time.time()-top)))\r\n # Print data stats\r\n labels = [\"word_embeddings_global\", \"entities_embeddings_global\", \"context_bi_lstm_global\", \"mention_embeddings_global\"]\r\n print(\"data about embeddings :\")\r\n print(\"names:\\n\\tlen : {}\\n\\ttype : {}\".format(len(names),type(names),))\r\n print(\"embs:\\n\\tlen : {}x{}x{}\\n\\ttype : {}x{}x{}\".format(len(embs),len(embs[0]),len(embs[0][0]),type(embs),type(embs[0]),type(embs[0][0])))\r\n # Create TSNE\r\n if verbose : print(\"Create TSNE model ...\",end=\"\")\r\n top = time.time()\r\n tsne_model = tsne_plot._TSNE(iteration=5000,component=3,learning_rate=10,perplexity=30)\r\n if verbose : print(\"... done in {}s\\n##### ##### #####\".format(int(time.time()-top)))\r\n toptop = time.time()\r\n if melting_args.compact_batch :\r\n for i in range(4):\r\n if len(embs[0][i]) == 0: continue\r\n for j in range(1,4):\r\n for x in range(len(embs)):\r\n print(\"shape : {} <- {}\".format(np.shape(embs[x][i][0]),np.shape(embs[x][i][j]))) \r\n embs[x][i][0] = np.append(embs[x][i][0],embs[x][i][j],axis=0)\r\n embs[x][i] = [embs[x][i][0]]\r\n print(\"de-batch embs:\\n\\tlen : {}x{}x{}\\n\\ttype : {}x{}x{}\".format(len(embs),len(embs[0]),len(embs[0][0]),type(embs),type(embs[0]),type(embs[0][0]))) \r\n lenJ = 1\r\n else : lenJ = 4\r\n for i in range(4): # on a 4 embeddings\r\n if len(embs[0][i]) == 0 : continue\r\n for j in range(lenJ) : # on a un batch de taille lenJ\r\n name = labels[i]+\"_{}\".format(\"all\") if melting_args.compact_batch else labels[i]+\"_{}\".format(j)\r\n file_name = summary_folder+\"images/{}\".format(name)\r\n metadata = []\r\n legend = []\r\n for x in range(len(names)): \r\n metadata.extend([x for plouf in range(len(embs[x][i][j]))])\r\n legend.append(names[x])\r\n if verbose : \r\n print(\"Generating TSNE embeddings ...\",end=\"\")\r\n sys.stdout.flush() \r\n top = time.time()\r\n TSNE_embs = [tsne_plot._TSNE_fit(np.array(embs[x][i][j]),tsne_model) for x in range(len(embs))]\r\n if verbose : \r\n print(\"... done in {}s\".format(int(time.time()-top)))\r\n sys.stdout.flush() \r\n X = TSNE_embs[0] \r\n for tsne_emb in TSNE_embs[1:]: X = np.append(X,tsne_emb,axis=0) #np.concatenate(TSNE_embs,axis=0)\r\n if verbose: print(\"TSNE shape : {}\\nConcat Shape : {}\\nplotting TSNE ...\".format(\" \".join([str(np.shape(t)) for t in TSNE_embs]),np.shape(X)),end=\"\")\r\n top = time.time()\r\n tsne_plot.PlotterMultiTriDimension(1,[X], #La concaténation des représentations d'embeddings à afficher\r\n [legend], #La légende : le nom des modèles (x)\r\n [name], #Le titre du graphe : le type d'embeddings représenté\r\n [metadata], #les int associés à chaque embeddings permettant de les regrouper par modèle\r\n file_name+\".png\")\r\n tsne_plot.PlotterMultiTriDimension(len(embs),\r\n TSNE_embs, #list des représentations d'embeddings à afficher (3)\r\n [[names[x]] for x in range(len(names))], #La Légende : le nom du modèle pour chacune des représentation (1 par groupe - 3 groupes)\r\n [name+\"_{}\".format(x) for x in names], #Le titre des graphes : le type d'embeddigs représenté + nom du modèle\r\n [[x for plouf in range(len(embs[x][i][j]))] for x in range(len(names))], #les int associé à chaque embeddings (1 couleur par groupe - 3 groupe) \r\n file_name+\"_separated.png\")\r\n if verbose : \r\n print(\"... done in {}s\\nImage to '{}'\".format(int(time.time()-top),file_name))\r\n sys.stdout.flush() \r\n if verbose : print(\"##### ##### #####\\nALL DONE IN {}s\".format(int(time.time()-toptop)))\r\n \r\ndef melting_embeddings(melting_args, summary_folder, use_old_data=False, verbose=True):\r\n final_emb_summary = SummaryWriter(summary_folder + 'global_embedding_projector/fusion_projectors/')\r\n if use_old_data :\r\n print(\"LOADING DATA\")\r\n names = pk.load(open(summary_folder+\"names_embs.pk\",\"rb\"))\r\n embs = pk.load(embs,open(summary_folder+\"embs_embs.pk\",\"rb\"))\r\n else:\r\n print(\"GENERATING AND SAVING DATA\")\r\n final_emb_model = extract_embeddings(melting_args, to_extract=set([1])) #to_extract = [1] : only entities\r\n names = list(final_emb_model.keys()) # list of string. Dimension = nb de model chargés\r\n embs = list(final_emb_model.values()) # list of list of list of tensor. Dimension = nb model x 4 x 4\r\n pk.dump(names,open(summary_folder+\"names_embs.pk\",\"wb\"))\r\n pk.dump(embs,open(summary_folder+\"embs_embs.pk\",\"wb\"))\r\n # Print data stats\r\n labels = [\"word_embeddings_global\", \"entities_embeddings_global\", \"context_bi_lstm_global\", \"mention_embeddings_global\"]\r\n print(\"data about embeddings :\")\r\n print(\"names:\\n\\tlen : {}\\n\\ttype : {}\".format(len(names),type(names),))\r\n print(\"embs:\\n\\tlen : {}x{}x{}\\n\\ttype : {}x{}x{}\".format(len(embs),len(embs[0]),len(embs[0][0]),type(embs),type(embs[0]),type(embs[0][0])))\r\n for i in range(4): # on a 4 embeddings\r\n if len(embs[0][i]) == 0 : continue\r\n for j in range(4) : # on a un batch de taille 4\r\n step_zero = 100*i+10*j\r\n label = labels[i]+\"_{}\".format(j)\r\n global_emb = np.concatenate([np.array(embs[x][i][j]) for x in range(len(embs))],axis=-1) #IMPOSSIBLE A CONCATENER\r\n metadata = []\r\n for x in range(len(names)): metadata.extend([names[x] for plouf in range(len(embs[x][i][j]))])\r\n if(verbose):\r\n print(\"test range:\\n\\tarrayxlen(embs) = {}\\n\\tlen(names)xrange(embs) = {}\".format((len(embs[0][i][j])*len(embs)),\r\n (len(names)*len(embs[0][i][j]))))\r\n print(\"\\tconcatenation = {}\".format(sum([len(plouf) for plouf in [np.array(embs[x][i][j]) for x in range(len(embs))]])))\r\n print(\"data global_emb:\\n\\tmetadata : {}\\n\\tnb embs : {}\\n\\tlabel : {}\".format(len(metadata),len(global_emb),label))\r\n #final_emb_summary.add_embedding(global_emb, tag=label, \r\n # metadata=metadata,\r\n # global_step=step_zero)\r\n if i==1 : \r\n for x in range(len(embs)): \r\n if verbose : print(\"entities summary :\\n\\tentities embs : {}\\n\\tentities labels : {}\".format(len(embs[x][i][j]),len(embs[x][-1][j])))\r\n step = step_zero + x\r\n final_emb_summary.add_embedding(embs[x][i][j], tag=label, \r\n metadata=embs[x][-1][j],\r\n global_step=step)\r\n\r\ndef generating_metadata(args):\r\n save_file = \"../data/basic_data/idtoent.txt\"\r\n args.entity_extension = None\r\n args.wikiid2nnid_name = \"wikiid2nnid_FR.txt\"\r\n args.entity_vecs_name = \"ent_vecs_fr_true_15.npy\"\r\n entities_embeddings = load_ent_vecs(args)\r\n idtocand, _, _ = fun_eval.load_data(args, verbose=True)\r\n idonly = list(idtocand.keys())\r\n print(\"idtocand : {}\".format(list(idtocand.items())[:10]))\r\n print(\"id min : {}\\nid max : {}\".format(min(idonly), max(idonly)))\r\n print(\"ent size = {}\\nidtocand size = {}\".format(len(entities_embeddings),len(idtocand)))\r\n with open(save_file,\"w\") as txt:\r\n for i in range(len(entities_embeddings)):\r\n if i in idtocand: txt.write(\"{}\\n\".format(idtocand[i]))\r\n else: txt.write(\"\\n\")\r\n print(\"metadata done at '{}'\".format(save_file))\r\n \r\n\r\n \r\ndef melt_to_melting_args(melt_args):\r\n experiment_names = melt_args.experiment_name.split(\"_z_\")\r\n training_names = melt_args.training_name.split(\"_z_\") \r\n melting_args = list(zip(experiment_names,training_names))\r\n return melting_args\r\n \r\ndef _parse_args():\r\n parser = argparse.ArgumentParser()\r\n parser.add_argument(\"--experiment_name\", help=\"under folder data/tfrecords/\\nList of folder separate by '_z_'\")\r\n parser.add_argument(\"--training_name\", help=\"under folder data/tfrecords/\\nList of folder separate by '_z_'\")\r\n parser.add_argument(\"--load_existing_data\",dest=\"load_data\",action=\"store_true\")\r\n parser.add_argument(\"--compact_batch\",dest=\"compact_batch\",action=\"store_true\")\r\n parser.set_defaults(load_data=False)\r\n parser.set_defaults(compact_batch=False)\r\n args = parser.parse_args()\r\n return args\r\n \r\nif __name__==\"__main__\":\r\n args = _parse_args() #parse list of model to load and use\r\n summary_folder = \"../data/tfrecords/\"\r\n generating_metadata(args)\r\n #melting_args = melt_to_melting_args(args)\r\n #print(\"nb model : {}\\ntype model : \\n\\tel_dataset : {}\\n\\tel_names : {}\\n\\tmodel : {}\".format(len(list_model),type(list_model[0][0]),type(list_model[0][1]),type(list_model[0][2])))\r\n #melting_embeddings(melting_args, summary_folder, use_old_data=args.load_data))\r\n #tsne_fusion(melting_args, summary_folder, use_old_data=args.load_data)\r\n \r\n","repo_name":"Denescor/end_to_end_EL_Reforged","sub_path":"end2end/code/model/melt_embeddings.py","file_name":"melt_embeddings.py","file_ext":"py","file_size_in_byte":14755,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"71181311306","text":"import importlib\nimport inspect\nimport json\nimport logging\nimport os\nimport sys\n\nimport addict as addict\nimport falcon\nimport requests\nimport ruamel.yaml\n\n\nclass microservice:\n def __init__(self, converter, *args, **kwargs):\n name = converter.__class__.__name__\n self.service_name = \"micro_\" + name.lower()\n self.converter = converter\n\n docker_kwargs = (\n {} if not hasattr(converter, \"docker_kwargs\") else converter.docker_kwargs\n )\n\n g = converter.predict\n\n def p(*args, **kwargs):\n return g(*args, **kwargs)\n\n self.p = p\n self.converter.predict = self.remote_call\n\n if not os.environ.get(\"INSIDE\", False) and not (\n os.environ.get(\"INSIDE\", False) == \"no_update\"\n ):\n self.converter = converter\n self.imports = inspect.getmembers(sys.modules[__name__], inspect.isclass)\n try:\n with open(\"../docker-compose.override.yaml\") as f:\n compose = f.read()\n except Exception:\n compose = \"\"\n\n compose = addict.addict.Dict(ruamel.yaml.safe_load(compose))\n full_path = converter.__class__.__module__\n full_path = full_path.replace(\"python.\", \"\")\n service_def = {\n \"container_name\": self.service_name,\n \"logging\": {\n \"driver\": \"json-file\",\n \"options\": {\"max-file\": \"5\", \"max-size\": \"10m\"},\n },\n \"image\": \"full_python\",\n **(\n {\n \"build\": {\n \"context\": \"python\",\n \"dockerfile\": \"$CWD/python\" + converter.Dockerfile.replace(\n os.getcwd(), \"\"\n ) + \"/Dockerfile\",\n \"args\": {\n \"CONTEXT\": full_path.replace(\".\", \"/\"),\n \"OUTSIDE_CONTEXT\": converter.Dockerfile.replace(\n os.getcwd(), \"\"\n ),\n },\n }\n }\n if hasattr(converter, \"Dockerfile\")\n else {\n \"build\": \"python\",\n }\n ),\n \"restart\": \"unless-stopped\",\n \"entrypoint\": f\"python3 -c 'from {full_path} import {name}; from wsgiref import simple_server; simple_server.make_server(\\\"0.0.0.0\\\", 7777, {name}.application).serve_forever()'\",\n \"environment\": {\n \"INSIDE\": \"true\",\n \"LC_ALL\": \"en_US.UTF-8\",\n \"LANG\": \"en_US.UTF - 8\",\n \"LANGUAGE\": \"en_US.UTF-8\",\n \"GDB_PASSWORD\": \"${GDB_PASSWORD}\",\n \"GDB_HOST\": \"gdb\",\n },\n \"networks\": [\"db\"],\n \"volumes\": [\n \"$CWD/python:/home/finn/Programming/self-reading-library/python\",\n *(\n [\n \"$CWD/python\"\n + converter.Dockerfile.replace(os.getcwd(), \"\")\n + \"/\"\n + v\n + \":/volumes/\"\n + v.replace(\"../\", \"\")\n for v in converter.volumes\n ]\n if hasattr(converter, \"volumes\")\n else []\n ),\n ],\n **docker_kwargs,\n }\n compose.update({\"services\": {self.service_name: service_def}})\n compose = compose.to_dict()\n try:\n with open(\"../docker-compose.override.yaml\", \"w\") as f:\n ruamel.yaml.dump(compose, f)\n except Exception as e:\n logging.error(\"Could not update docker-compose.override!\")\n\n else:\n self.app = {self.service_name: self}\n import falcon\n from falcon_cors import CORS\n\n cors = CORS(\n allow_origins_list=[\"*\"],\n allow_all_origins=True,\n allow_all_headers=True,\n allow_credentials_all_origins=True,\n allow_all_methods=falcon.HTTP_METHODS,\n )\n\n from falcon_multipart.middleware import MultipartMiddleware\n\n application = falcon.App(\n middleware=[cors.middleware, MultipartMiddleware()]\n )\n application.add_route(\"/\" + self.service_name, self)\n logging.debug(\"Service at /\" + self.service_name)\n\n importlib.import_module(self.converter.__module__).application = application\n converter.application = application\n self.application = application\n\n converter.load()\n\n def remote_call(self, *args, **kwargs):\n\n send_data = json.dumps((args, kwargs))\n\n if os.environ.get(\"INSIDE\", False) == False:\n return self.p(*args, **kwargs)\n\n resp = requests.post(\n f\"http://{self.service_name}:7777/{self.service_name}\",\n send_data,\n headers={\"origin\": \"localhost\", \"content-Type\": \"application/json\"},\n )\n if not resp.status_code == 200:\n logging.error(\n f\"Error on microservice request {self.service_name} {resp.text}\"\n )\n else:\n return json.loads(resp.text)\n\n def on_post(self, req, resp):\n try:\n args, kwargs = req.media\n res = self.p(*args, **kwargs)\n resp.text = json.dumps(res)\n resp.status = falcon.HTTP_200\n except Exception as e:\n print(e)\n logging.error(\"Could not calculate result\", exc_info=True)\n resp.status = falcon.HTTP_500\n resp.text = str(e)\n\n def __call__(self, *args, **kwargs):\n return self.converter(*args, **kwargs)\n","repo_name":"c0ntradicti0n/self-reading-library","sub_path":"python/core/microservice.py","file_name":"microservice.py","file_ext":"py","file_size_in_byte":6105,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"81"} +{"seq_id":"32902140002","text":"import streamlit as st\nimport requests\nfrom streamlit import beta_container\nfrom streamlit_custom_notification_box import custom_notification_box\n\nst.title('Search hotels')\n\n# st.session_state['hotel'] = None\n# st.session_state['location'] = None\n\nAPI_ENDPOINT = \"https://a91201uwt9.execute-api.us-east-1.amazonaws.com/dev/search\"\n\n# Get the search query from the user\nlocation = st.text_input(\"Location\")\ncheckin_date = st.date_input('Check-in date')\ncheckout_date = st.date_input('Check-out date')\nnum_of_adults = st.text_input(\"Number of adults\")\nnum_of_children = st.text_input(\"Number of children\")\nchildren_age = st.text_input(\"Children age\")\nroom_number = st.text_input(\"Number of rooms\")\nfree_cancellation = st.selectbox(\"Need free cancellation\", [\"No\", \"Yes\"])\nif free_cancellation == \"Yes\":\n free_cancellation = 1\nelse:\n free_cancellation = 0\n\n\ndef set_state(hotel):\n #print(hotel_name)\n #st.text(\"Please go to Book Hotel page to finish your booking\")\n styles = {'material-icons':{'color': 'blue'},\n 'text-icon-link-close-container': {'box-shadow': '#3896de 0px 4px'},\n 'notification-text': {'':''},\n 'close-button':{'':''},\n 'link':{'':''}}\n\n custom_notification_box(icon='info', textDisplay='Please go to Book Hotel page to finish your booking', externalLink='', url='#', styles=styles, key=\"foo\")\n st.session_state.hotel = hotel\n st.session_state.checkin_date = checkin_date\n st.session_state.checkout_date = checkout_date\n print(st.session_state)\n API_ENDPOINT = \"https://a91201uwt9.execute-api.us-east-1.amazonaws.com/dev/rec\"\n response = requests.post(API_ENDPOINT, params={\"hotel_name\": hotel[\"name\"]})\n st.session_state.rec = response.json()\n print(\"debug\")\n\n# Define the search function\ndef search():\n # Send the GET request to the API endpoint\n response = requests.get(API_ENDPOINT, params={\"location\": location, \"adults_number\": num_of_adults, \"checkin_date\": checkin_date, \"checkout_date\": checkout_date, \"children_age\": children_age, \"children_number\": num_of_children, \"room_number\": room_number, \"free_cancellation\": free_cancellation})\n st.session_state[\"location\"] = location\n # Process the response and display the results\n results = response.json()\n # print(\"results:\", results)\n # print(\"hotel:\")\n #for result in results:\n #\n count = 0\n for hotel in results:\n # print(hotel)\n with st.form(key=str(count)):\n # Add some elements to the container\n st.text(\"Name: \" + hotel[\"name\"])\n st.text(\"Address: \" + hotel[\"address\"])\n st.text(\"Rating: \" + hotel[\"score\"])\n st.image(hotel[\"pic_url\"], width=300)\n st.text(\"Price: $\" + str(hotel[\"price\"]))\n #st.checkbox(\"Choose this hotel\", on_change=set_state, args=(hotel['name'],), key=str(count))\n #st.markdown('Book', unsafe_allow_html=True)\n st.form_submit_button(label=\"Choose\", on_click=set_state, args=(hotel,))\n count += 1\n #st.write(results)\n\n\n# Add a button to perform the search\nif st.button(\"Search\"):\n search()\n","repo_name":"Racheltrq/CloudCompProject","sub_path":"pages/1_Search_Hotels.py","file_name":"1_Search_Hotels.py","file_ext":"py","file_size_in_byte":3288,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"3102260911","text":"from django.urls import path\n\nfrom tp_book.views import *\n\nurlpatterns = [\n path('get-all-data/', GetAllData.as_view()),\n path('detail-data//', DetailData.as_view()),\n path('get-fav-data/', get_fav_data),\n path('create-data/', CreateData.as_view()),\n path('search/', SerachData.as_view()),\n]\n\n\n\n\n","repo_name":"rezarezaeedev/BookShop-drf","sub_path":"tp_book/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":315,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"81"} +{"seq_id":"28449130138","text":"\n\nimport logging\nimport json \n\nfrom .analyses import SourceSinkAnalysis\n\nl = logging.getLogger(\"StaticHeapTransitionsHunterGT\")\nl.setLevel(\"INFO\")\n\n\ndef shut_up(thing):\n lol = logging.getLogger(thing)\n lol.setLevel(\"CRITICAL\")\n\n'''\nThis is the threat identifier when using random CTF \nchallenges as target.\n'''\nclass StaticHeapTransitionsHunterGT:\n \n def __init__(self, project, funcs_cc, malloc, free, basic_functions_addrs, mmio_nodes):\n\n self.project = project \n self.malloc = malloc\n self.free = free\n self.funcs_cc = funcs_cc\n self.basic_functions_addrs = basic_functions_addrs\n self.mmio_nodes = mmio_nodes\n\n self.writing_bf_funcs = [\"memcpy\", \"memset\", \"strncpy\", \"strcpy\", \"strcat\", \"strncat\"]\n\n # Functions containing calls to these procedures are considered returing\n # user input. ( affected by false positive if the return value is not affected by user and\n # from false negative if we are missing some functions)\n self.user_sources = [\"strtoul\", \"getchar\", \"scanf\", \"strtoul\", \n \"read\", \"gets\", \"fgets\", \"fgetc\",\n \"fscanf\", \"strtoull\"]\n \n self.valid_user_sources = {}\n self.user_sources_callers = []\n\n self.exploitability_metadata = []\n\n # Store here calls to function that get user data\n # This is mainly to compensate bad RD over AMD64 and \n # the missing tag of function call argument for specific functions.\n # NOTE: here I store the calls to\n self.critical_codelocs = []\n\n def get_xrefs_chain(self, target):\n curr_func_cfg_node = self.project.cfg.get_node(target)\n\n # this will contains the address of all the calls to malloc\n # that can be reached from a mmio node.\n calls_to_malloc_from_mmio = set()\n\n for p in curr_func_cfg_node.predecessors:\n \n curr_func_cfg_node = self.project.cfg.get_node(p.function_address)\n all_func_xrefs = set()\n all_func_xrefs.add(p)\n worklist = set()\n \n for pp in curr_func_cfg_node.predecessors:\n worklist.add((pp.function_address, pp.addr))\n all_func_xrefs.add(pp)\n while len(worklist) != 0:\n w = worklist.pop()\n func_addr = w[0]\n curr_func_cfg_node = self.project.cfg.get_node(func_addr)\n for ppp in curr_func_cfg_node.predecessors:\n if ppp not in all_func_xrefs:\n worklist.add((ppp.function_address, ppp.addr))\n all_func_xrefs.add(ppp)\n\n # Check if any of the xrefs is a mmio_node\n for a in all_func_xrefs:\n l.info(\"Testing {}\".format(hex(a.function_address)))\n if a.function_address in self.mmio_nodes:\n calls_to_malloc_from_mmio.add(p)\n \n if len(calls_to_malloc_from_mmio) != 0:\n l.info(\"Can reach function {} from an MMIO node!\".format(hex(target)))\n l.info(\" Reachable calls: {}\".format([hex(x.addr) for x in calls_to_malloc_from_mmio]))\n return True, calls_to_malloc_from_mmio\n else:\n l.info(\"Cannot reach function {} from MMIO node\".format(hex(target)))\n return False, None\n\n def guess_external_source(self):\n for fus in self.user_sources:\n for k,v in self.project.loader.main_object.plt.items():\n if k == fus:\n self.valid_user_sources[fus] = v\n break\n l.info(\"[+] Found the following user source functions in the binary:\")\n for fus_name, fus_addr in self.valid_user_sources.items():\n l.info(\"[+] {}@{}\".format(fus_name, hex(fus_addr)))\n\n \n\n def run(self):\n # base_state = get_init_state(self.project, self.hb_state, self.hb_state[\"final_allocator\"][\"mem_dump_path\"])\n # We are going to rank the exploitability using different features that we collect in a static way:\n #\n # 1- PATH_TO_MALLOC_FROM_MMIO: does it exist a path from a mmio function to malloc? \n # 2- CONNECTION_MALLOC_FREE: does it exist a path where malloc's return value flows into free? \n # 3- ARB_FREE: does it exist a path where free is called with an argument not immediately returned by a call to malloc? \n # 4- PATH_TO_WRITE_BF_FROM_MALLOC_RET: does it exist a path in which return value of malloc is consumed by a BF that writes data?\n # \n # OTHERS?\n # 5- ARBITRARY SIZE MALLOC OR ALL CONSTANTS? \n # 6- \n # ========================\n # Exploitation Primitives\n # =========================\n # FAKE-FREE: YES if ARB_FREE \n # DOUBLE_FREE: YES if PATH_TO_MALLOC_FROM_MMIO AND ARB_FREE\n # HEAP-OVERFLOW: YES if PATH_TO_MALLOC_FROM_MMIO and PATH_TO_WRITE_BF_FROM_MALLOC_RET\n # UAF: YES if PATH_TO_MALLOC_FROM_MMIO AND (CONNECTION_MALLOC_FREE OR ARB_FREE) AND PATH_TO_WRITE_BF_FROM_MALLOC_RET\n \n #shut_up(\"heapster.source_sink_analysis\")\n \n self.guess_external_source()\n\n if self.malloc != 0x0:\n result_xrefs_chain, calls_to_malloc_from_mmio = self.get_xrefs_chain(self.malloc)\n if result_xrefs_chain:\n calls_to_malloc_from_mmio = list(calls_to_malloc_from_mmio)\n self.exploitability_metadata.append(\"PATH_TO_MALLOC_FROM_MMIO\")\n\n\n if self.free != 0x0:\n result_xrefs_chain, calls_to_free_from_mmio = self.get_xrefs_chain(self.free)\n if result_xrefs_chain:\n l.info(\"Can reach call to free using {}\".format(calls_to_free_from_mmio))\n self.exploitability_metadata.append(\"PATH_TO_FREE_FROM_MMIO\")\n\n if calls_to_malloc_from_mmio is None:\n l.info(\"Cannot reach malloc from a MMIO functon!\")\n else:\n\n valid_codelocs_source_sink = [ self.project.factory.block(addr=x.addr, opt_level=1).instruction_addrs[-1] for x in calls_to_malloc_from_mmio]\n\n if self.free != 0x0:\n \n l.info(\"Starting inter-functional RD analysis for free parameter!\")\n\n curr_func_cfg_node = self.project.cfg.get_any_node(self.free)\n #scope_functions = [ x.function_address for x in curr_func_cfg_node.predecessors] \n\n # Which are the parameter of free.\n # If we use challenges it is usually the standard prototype.\n target_free_arg = self.funcs_cc[\"arg0\"]\n \n ssa = SourceSinkAnalysis(self.project, \n self.project.cfg, \n self.project.kb.functions[self.malloc],\n self.project.kb.functions[self.free],\n [target_free_arg],\n scope=1, # just put a value != 0, doesn't matter what.\n valid_source = valid_codelocs_source_sink,\n )\n ssa.run()\n \n # FIXME this can generate some false positives?\n #if len(ssa.observed_arb_param) != 0:\n # self.exploitability_metadata.append(\"ARB_FREE\")\n \n # source sink only at codelocation where malloc is called from mmio functions!\n if len(ssa.observed_source_sink) != 0:\n self.exploitability_metadata.append(\"CONNECTION_MALLOC_FREE\")\n \n if calls_to_free_from_mmio and self.malloc != 0x0:\n valid_codelocs_free = [ self.project.factory.block(addr=x.addr, opt_level=1).instruction_addrs[-1] for x in calls_to_free_from_mmio]\n l.info(\"[+] Valid codeloc for free are:\")\n for vi, vf in enumerate(valid_codelocs_free):\n l.info(\"[+] Call-{} {}\".format(vi+1, hex(vf)))\n\n l.info(\"[+] Starting inter-functional RD analysis for mmio-free parameter!\")\n\n curr_func_cfg_node = self.project.cfg.get_any_node(self.free)\n #scope_functions = [ x.function_address for x in curr_func_cfg_node.predecessors] \n\n # Which are the parameter of free.\n # If we use challenges it is usually the standard prototype.\n target_free_arg = self.funcs_cc[\"arg0\"]\n \n for fus in self.valid_user_sources.values():\n l.info(\"[+] Considering function user source {}\".format(hex(fus)))\n import ipdb; ipdb.set_trace()\n ssa = SourceSinkAnalysis(self.project, \n self.project.cfg, \n self.project.kb.functions[fus],\n self.project.kb.functions[self.free],\n [target_free_arg],\n scope=1, # just put a value != 0, doesn't matter what.\n valid_sink = valid_codelocs_free\n )\n ssa.run()\n \n # FIXME this can generate some false positives?\n if len(ssa.observed_source_sink) != 0:\n l.info(\"[+] Observed param from {}\".format(ssa.observed_source_sink))\n self.exploitability_metadata.append(\"ARB_FREE\")\n\n \n # Check where malloc ret val flows\n # the following analysis can be merged with the pointer sources one\n l.info(\"[+] Checking source sink of writing basic functions and malloc calls\")\n found_malloc_wbf_path = False\n\n for bf_candidate in self.basic_functions_addrs:\n bf_name = bf_candidate[0]\n bf_addr = bf_candidate[1]\n bf_ptr_args = bf_candidate[2]\n\n l.info(\"[+] Checking wbf: {} | addr: {} | arg: {}\".format(bf_name, hex(bf_addr), bf_ptr_args))\n\n if not self.project.kb.functions.get(bf_addr, None):\n continue\n\n ssa = SourceSinkAnalysis(self.project, \n self.project.cfg, \n self.project.kb.functions[self.malloc],\n self.project.kb.functions[bf_addr],\n bf_ptr_args,\n scope=1, # just put a value !=0 doesn't matter what.\n valid_source = valid_codelocs_source_sink\n )\n ssa.run()\n \n if len(ssa.observed_source_sink) != 0:\n l.info(\"[+] ✓ Found source-sink relation between malloc and writing bf\")\n self.exploitability_metadata.append(\"PATH_TO_WRITE_BF_FROM_MALLOC_RET\")\n found_malloc_wbf_path = True \n break\n\n if found_malloc_wbf_path:\n break\n\n l.info(\"Report for exploitability:\")\n exploitability_report = []\n\n # FAKE-FREE: YES if ARB_FREE \n # DOUBLE_FREE: YES if PATH_TO_MALLOC_FROM_MMIO AND ARB_FREE\n # HEAP-OVERFLOW: YES if PATH_TO_MALLOC_FROM_MMIO and PATH_TO_WRITE_BF_FROM_MALLOC_RET\n # UAF: YES if PATH_TO_MALLOC_FROM_MMIO AND (CONNECTION_MALLOC_FREE OR ARB_FREE) AND PATH_TO_WRITE_BF_FROM_MALLOC_RET\n\n if \"ARB_FREE\" in self.exploitability_metadata:\n exploitability_report.append(\"FAKE-FREE\")\n if \"PATH_TO_MALLOC_FROM_MMIO\" in self.exploitability_metadata and \"ARB_FREE\" in self.exploitability_metadata:\n exploitability_report.append(\"DOUBLE_FREE\")\n if \"PATH_TO_MALLOC_FROM_MMIO\" in self.exploitability_metadata and \"PATH_TO_WRITE_BF_FROM_MALLOC_RET\" in self.exploitability_metadata:\n exploitability_report.append(\"HEAP-OVERFLOW\")\n if \"PATH_TO_MALLOC_FROM_MMIO\" in self.exploitability_metadata and \\\n (\"CONNECTION_MALLOC_FREE\" in self.exploitability_metadata or \"ARB_FREE\" in self.exploitability_metadata) and \\\n \"PATH_TO_WRITE_BF_FROM_MALLOC_RET\" in self.exploitability_metadata:\n exploitability_report.append(\"UAF\")\n\n l.info(\" {}\".format(exploitability_report))\n\n","repo_name":"ucsb-seclab/heapster","sub_path":"heapster-env/heapster/identify_threats/DEPRECATED/threat_explorer_static_gt.py","file_name":"threat_explorer_static_gt.py","file_ext":"py","file_size_in_byte":12791,"program_lang":"python","lang":"en","doc_type":"code","stars":34,"dataset":"github-code","pt":"81"} +{"seq_id":"70690639944","text":"from pymongo import MongoClient\nfrom bson.objectid import ObjectId\nfrom pprint import pprint\nimport datetime\nimport random\nfrom random import randrange\nfrom faker import Faker\n\ndef random_date(start, end):\n delta = end - start\n int_delta = (delta.days * 24 * 60 * 60) + delta.seconds\n random_second = randrange(int_delta)\n return start + datetime.timedelta(seconds=random_second)\n\nd1 = datetime.datetime.strptime('12/15/2017 1:30 PM', '%m/%d/%Y %I:%M %p')\nd2 = datetime.datetime.strptime('1/9/2018 4:50 AM', '%m/%d/%Y %I:%M %p')\nfake = Faker()\n\nclient = MongoClient('mongodb://fuckingtelegramuser:fuckfuckfuck@ds059546.mlab.com:59546/fuckingtelegrambot')\n\ndb = client.fuckingtelegrambot\n\ncoin_names = ['Bitcoin','Ethereum','Litecoin','NEO','NEM','Stratis','BitShares','Stellar','Ripple','Dash','Lisk','Waves','Ethereum Classic','Monero','ZCash']\n\ncities = ['Алматы','Астана','Шымкент','Караганда','Актобе','Тараз','Павлодар','Семей','Усть-Каменогорск','Уральск','Костанай','Кызылорда','Петропавловск','Кызылорда','Атырау','Актау','Талдыкорган']\n\nexchanges =['COINMARKETCAP', 'BLOCKCHAIN', 'CEX.IO', 'ALONIX', 'BITTREX', 'EXMO.ME', 'BITFINEX', 'POLONIEX']\n\nusernames = ['hancapital', 'zshanabek', 'Yermuhanbet', 'KassymkhanTJ', 'bimurat_mukhtar','vakidzaci']\nsell = db.sell\ntraders = db.traders\n\ndb.sell.delete_many({}) \n \n# for i in range(0,200):\n# sell.insert_one({\n# 'name': random.choice(coin_names),\n# 'price': random.randint(10, 200000),\n# 'percent': random.randint(0, 20),\n# 'exchange': random.choice(exchanges), \n# 'city': random.choice(cities),\n# 'username': random.choice(usernames),\n# 'comment': fake.text(), \n# 'phone_number': fake.phone_number(),\n# \"created_at\": random_date(d1, d2)\n# })\ncursor = sell.find({'price': {'$gte': 0}, 'percent': {'$gte': 0}, 'created_at': {'$gte': datetime.datetime(2017, 11, 27, 20, 30, 34, 587092)}, 'city': 'Алматы', 'name': 'Monero'})\nfor document in cursor: \n pprint(document)\n","repo_name":"zshanabek/coinkz_bot","sub_path":"src/db.py","file_name":"db.py","file_ext":"py","file_size_in_byte":2180,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"21533293464","text":"from scrapy.selector import Selector\nfrom scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor\nfrom scrapy.contrib.spiders import CrawlSpider, Rule\nfrom rleague_crawler.items import RleagueCrawlerItem\n\nclass StatsRleagueComSpider(CrawlSpider):\n name = 'stats_rleague_com'\n allowed_domains = ['stats.rleague.com']\n start_urls = ['http://stats.rleague.com/rl/seas/2014.html']\n\n rules = (\n Rule(SgmlLinkExtractor(allow=r'scorers/games/2014/\\d+\\.html'), callback='parse_item', follow=True),\n )\n\n def parse_item(self, response):\n sel = Selector(response)\n i = RleagueCrawlerItem()\n\n i['teamone'] = {\n 'name': ''.join(sel.xpath('normalize-space(//table//tr[1]/th[1])').extract()),\n 'players': [],\n }\n\n i['teamtwo'] = {\n 'name': ''.join(sel.xpath('normalize-space(//table//tr[1]/th[2])').extract()),\n 'players': [],\n }\n \n for tr in sel.xpath('//table//tr[position() > 2 and position() < last() - 1]'): \n i['teamone']['players'].append({\n 'pos': ''.join(tr.xpath('td[1]//text()').extract()).strip(),\n 'player': ''.join(tr.xpath('td[2]//text()').extract()).strip(),\n 't': ''.join(tr.xpath('td[3]//text()').extract()).strip(),\n 'g': ''.join(tr.xpath('td[4]//text()').extract()).strip(),\n 'fg': ''.join(tr.xpath('td[5]//text()').extract()).strip(),\n 'pts': ''.join(tr.xpath('td[6]//text()').extract()).strip(),\n })\n\n i['teamtwo']['players'].append({\n 'pos': ''.join(tr.xpath('td[7]//text()').extract()).strip(),\n 'player': ''.join(tr.xpath('td[8]//text()').extract()).strip(),\n 't': ''.join(tr.xpath('td[9]//text()').extract()).strip(),\n 'g': ''.join(tr.xpath('td[10]//text()').extract()).strip(),\n 'fg': ''.join(tr.xpath('td[11]//text()').extract()).strip(),\n 'pts': ''.join(tr.xpath('td[12]//text()').extract()).strip(),\n })\n\n\n i['scrums'] = ''.join(sel.xpath('normalize-space(//table//tr[last()]/td/*[contains(., \"Scrums\")]/following-sibling::text()[1])').extract())\n i['penalties'] = ''.join(sel.xpath('normalize-space(//table//tr[last()]/td/*[contains(., \"Penalties\")]/following-sibling::text()[1])').extract())\n i['referees'] = sel.xpath('//table//tr[last()]/td/*[contains(., \"Venue\")]/preceding-sibling::a//text()').extract()\n i['venue'] = ''.join(sel.xpath('normalize-space(//table//tr[last()]/td/*[contains(., \"Venue\")]/following-sibling::*[1]/text())').extract())\n i['crowd'] = ''.join(sel.xpath('normalize-space(//table//tr[last()]/td/*[contains(., \"Crowd\")]/following-sibling::text()[1])').extract())\n i['date'] = ''.join(sel.xpath('normalize-space(//table//tr[last()]/td/*[contains(., \"Date\")]/following-sibling::text()[1])').extract())\n i['link'] = response.url\n\n if i['teamone'] != '':\n return i\n","repo_name":"jbinfo/scrapy_stats.rleague.com","sub_path":"rleague_crawler/spiders/stats_rleague_com.py","file_name":"stats_rleague_com.py","file_ext":"py","file_size_in_byte":3122,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"81"} +{"seq_id":"17569683381","text":"# -*- coding: utf-8 -*-\n# Run this app with `python app.py` and\n# visit http://127.0.0.1:8050/ in your web browser.\nimport dash\nfrom dash import dcc\nfrom dash import html\nimport plotly.express as px\nimport pandas as pd\nexternal_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']\napp = dash.Dash(__name__, external_stylesheets=external_stylesheets)\n\n# assume you have a \"long-form\" data frame\n# see https://plotly.com/python/px-arguments/ for more options\ndf = pd.DataFrame({\n \"Fruit\": [\"Apples\", \"Oranges\", \"Bananas\", \"Apples\", \"Oranges\", \"Bananas\"],\n \"Amount\": [4, 1, 2, 2, 4, 5],\n \"City\": [\"SF\", \"SF\", \"SF\", \"Montreal\", \"Montreal\", \"Montreal\"]\n})\nfig = px.bar(df, x=\"Fruit\", y=\"Amount\", color=\"City\", barmode=\"group\")\ncolors = {\n 'background': '#111111',\n 'text': '#7FDBFF'\n}\n\ndf2 = pd.read_csv('https://gist.githubusercontent.com/chriddyp/c78bf172206ce24f77d6363a2d754b59/raw/c353e8ef842413cae56ae3920b8fd78468aa4cb2/usa-agricultural-exports-2011.csv')\n\n\ndef generate_table(dataframe, max_rows=10):\n return html.Table([\n html.Thead(\n html.Tr([html.Th(col) for col in dataframe.columns])\n ),\n html.Tbody([\n html.Tr([\n html.Td(dataframe.iloc[i][col]) for col in dataframe.columns\n ]) for i in range(min(len(dataframe), max_rows))\n ])\n ])\n\nmarkdown_text = '''\n### Dash and Markdown\n\nDash apps can be written in Markdown.\nDash uses the [CommonMark](http://commonmark.org/)\nspecification of Markdown.\nCheck out their [60 Second Markdown Tutorial](http://commonmark.org/help/)\nif this is your first introduction to Markdown!\n'''\n\napp.layout = html.Div(style={'backgroundColor': colors['background']}, children=[\n html.H1(children='Hello Dash'),\n html.Div(children='''\n Dash: A web application framework for Python.\n '''),\n dcc.Graph(\n id='example-graph',\n figure=fig\n ),\n html.H4(children='US Agriculture Exports (2011)'),\n generate_table(df2),\n dcc.Markdown(children=markdown_text)\n])\nif __name__ == '__main__':\n app.run_server(dev_tools_hot_reload=False)\n","repo_name":"AndreMwendwa/Modus_Python","sub_path":"Traitement/dashboard.py","file_name":"dashboard.py","file_ext":"py","file_size_in_byte":2109,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"81"} +{"seq_id":"16145185725","text":"import requests\nimport json\nimport datetime\nimport pandas as pd\n\ncrtfc_key = 'OpenDart 인증키 입력'\ntoday = datetime.date.today().strftime(\"%Y%m%d\")\n\n# 모든 기업, 오늘날짜 기준, 페이지당 100개\nurl = \"https://opendart.fss.or.kr/api/list.json?crtfc_key=%s&end_de=%s&page_count=100\" % (crtfc_key, today)\n\nresponse = requests.get(url)\ndata_json = json.loads(response.text)\n\nitems = ['corp_cls', 'corp_name', 'corp_code', 'stock_code', 'report_nm', 'rcept_no', 'flr_nm', 'rcept_dt', 'rm']\ncols = ['법인구분', '종목명', '고유번호', '종목코드', '보고서명', '보고서링크', '공시제출인명', '접수일자', '공']\nlink_base = 'http://m.dart.fss.or.kr/html_mdart/MD1007.html?rcpNo='\nresult = []\n\nif data_json['status'] == '000':\n for data in data_json['list']:\n result.append([])\n for item in items:\n if item in data.keys():\n if item == 'rcept_no':\n result[-1].append(link_base + data[item])\n else:\n result[-1].append(data[item])\n else:\n result[-1].append('')\n df = pd.DataFrame(result, columns=cols)\n print(df.head())\n\nelse:\n print('데이터없음')","repo_name":"kamzzang/WebCrawler","sub_path":"Crawler_OpenDartAPI.py","file_name":"Crawler_OpenDartAPI.py","file_ext":"py","file_size_in_byte":1220,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"81"} +{"seq_id":"40026586081","text":"#Program for Magic 8 ball\r\n'''welcome = input(\"Hello!. What is your name? \")\r\nprint(f\"Welcome, {welcome.title()}!\")\r\nmessage = input(\"Enter your response here or Q to quit:\")\r\nprint(\"Hello {}\". format(message))\r\nmsg = \" \"\r\nprompt = \"\\n Tell me something and I will repeat it back to you:\"\r\nprompt += \"\\nEnter 'quit' to end the program. \"\r\n#temp = \"i am fine\"\r\nwhile True:\r\n\tmsg= input(prompt)\r\n\t#print(msg)\r\n\tif msg.lower() == 'quit':\r\n\t\tbreak\r\n\t\t\r\n\t''if\tmsg.find(temp):\r\n\t\tbreak\r\n\t\t\r\n\tprint(msg.title())\r\n\t\r\nprint(\"END\")\r\n\t\t\r\n\r\n\r\nwhile message != 'quit':\r\n message = input(prompt)\r\n print(message)'''\r\n\t\r\nanswers = {'1':'It is certain', '2': 'It is decidedly so', '3' : ' Without a doubt', '4' : 'yes definitely', '5' : 'You may rely on it', '6' : 'As I see it, yes',\r\n\t\t\t'7' : 'Most likely', '8' : 'Outlook good', '9' : 'Yes', '10' : 'Signs point to yes', '11' : 'Reply hazy try again', '12' : 'Ask again later',\r\n\t\t\t'13' : 'Better not tell you now', '14' : 'Cannot predict now', '15' : 'Concentrate and ask again', '16' : 'Don\\'t count on it', '17' : 'My reply is no',\r\n\t\t\t'18' : 'My sources say no', '19' : 'Outlook not so good', '20' : 'Very doubtful'\r\n }\r\n \r\nch = random.randint(1,18)\r\nprint(ch)\r\n\"\"\"for choice, answer in answers:\r\n\tch = random(1,18)\r\n\tprint(ch.answer)\"\"\"","repo_name":"Sonalipj/Immersive-data","sub_path":"sj_magic8.py","file_name":"sj_magic8.py","file_ext":"py","file_size_in_byte":1284,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"1819327274","text":"import sys\nsys.setrecursionlimit(int(1e7))\ninput = sys.stdin.readline\n\n\ndef dfs(y: int, x: int) -> None:\n for k in range(4):\n dy, dx = dydx[k]\n ny = y + dy\n nx = x + dx\n if 0 <= ny < N and 0 <= nx < N:\n if not visited[ny][nx] and graph[ny][nx] == \"*\":\n visited[ny][nx] = True\n dfs(ny, nx)\n\n\ndydx = [(-1, 0), (0, 1), (1, 0), (0, -1)]\nN = int(input()) # 격자판의 크기\ngraph = [] # 그래프\nfor _ in range(N):\n graph.append(list(input().rstrip()))\n\nvisited = [[False for _ in range(N)] for _ in range(N)]\n\nsector = 0\n\nfor i in range(N):\n for j in range(N):\n if not visited[i][j] and graph[i][j] == \"*\":\n visited[i][j] = True\n dfs(i, j) # 깊이 우선 탐색\n sector += 1 # 섹터의 번호를 증가\n\nprint(sector)","repo_name":"siwon-park/Problem-Solving","sub_path":"Baekjoon_Solve/Graph/5958/5958_DFS.py","file_name":"5958_DFS.py","file_ext":"py","file_size_in_byte":840,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"81"} +{"seq_id":"30537390584","text":"from queue import Queue\n\n\nclass Stack:\n def __init__(self):\n self.__queue1 = Queue()\n self.__queue2 = Queue()\n self.__top = -1\n\n def push(self, item):\n self.__top += 1\n self.__queue1.put(item)\n\n def pop(self):\n if not self.isEmpty():\n lastElem = None\n while not self.__queue1.empty():\n lastElem = self.__queue1.get()\n self.__queue2.put(lastElem)\n if lastElem is not None:\n self.__top -= 1\n if self.__top < 0:\n return lastElem\n while not self.__queue2.empty():\n self.__queue1.put(self.__queue2.get())\n return lastElem\n\n def isEmpty(self):\n return self.__queue1.empty()\n","repo_name":"AjayKrP/GoogleInterview","sub_path":"DS_Practice/Stack/stack-using-queue.py","file_name":"stack-using-queue.py","file_ext":"py","file_size_in_byte":770,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"40110968782","text":"import numpy\nfrom environment import Arrays\nimport pathos.multiprocessing as multiprocessing\nimport scipy.stats as stats\nimport pandas\n\n#\n# TODO: \n# 1) Install CuPy https://docs-cupy.chainer.org/en/stable/install.html#dependencies\n# 2) Make randomized block functions GPU Aware: If GPU is present use it, otherwise default to numpy (http://stsievert.com/blog/2016/07/01/numpy-gpu/).\n#\n\n \ndef init_pool(pool):\n if pool is None:\n return multiprocessing.Pool(multiprocessing.cpu_count())\n\n return pool\n\ndef cell_count(samples, processing_pool):\n if type(samples) is numpy.ndarray:\n return samples.size\n else:\n return numpy.sum(processing_pool.map(lambda sample: len(sample), samples))\n \n\ndef cell_sum(samples, processing_pool):\n if type(samples) is numpy.ndarray:\n return numpy.sum(samples)\n else:\n return numpy.sum(processing_pool.map(lambda x: numpy.sum(x), samples))\n\n\nclass Reductor(object):\n\n @classmethod\n def to_array(clazz, samples):\n if type(samples) is numpy.ndarray:\n return samples;\n elif type(samples) is pandas.DataFrame:\n return samples.values;\n\n else:\n return samples;\n\n @classmethod \n def correction_for_mean(clazz, samples, pool = None): # aka CM\n \"\"\"\n Args:\n samples (2d array like): .-\n pool (optional pathos.multiprocessing.Pool or multiprocessing.Pool): Required to parallelize operations. \n Return:\n (sum of all observations)^2 divided by # of observations \n \"\"\" \n\n processing_pool = init_pool(pool) \n n = cell_count(samples, processing_pool)\n s = numpy.square(cell_sum(samples, processing_pool))\n\n return (s / n)\n\n \n @classmethod \n def sum_of_squares_total(clazz, samples, pool = None): # aka SST\n \"\"\"\n Args:\n samples (2d array like): .-\n pool (optional pathos.multiprocessing.Pool or multiprocessing.Pool): Required to parallelize operations. \n Return:\n The sum of the squares of the difference of the dependent variable and its mean (https://en.wikipedia.org/wiki/Total_sum_of_squares)\n \"\"\"\n Y = samples\n processing_pool = init_pool(pool)\n s = numpy.sum(processing_pool.map(lambda y: numpy.square(numpy.sum(y)) / len(y), Y))\n cm = Reductor.correction_for_mean(Y, processing_pool)\n\n return (s - cm)\n\n\n @classmethod \n def total_ss(clazz, samples, pool = None): # aka Total SS\n \"\"\"\n Args:\n samples (2d array like): .-\n pool (optional pathos.multiprocessing.Pool or multiprocessing.Pool): Required to parallelize operations. \n Return:\n Total SS\n \"\"\"\n processing_pool = init_pool(pool)\n cm = Reductor.correction_for_mean(samples, pool)\n s = numpy.sum(processing_pool.map(lambda Y: numpy.sum(tuple(map(lambda y: numpy.square(y), Y))), samples))\n return (s - cm)\n\n @classmethod \n def standard_squared_error(clazz, samples, pool = None): # aka SSE\n \"\"\"\n Args:\n samples (2d array like): .-\n pool (optional pathos.multiprocessing.Pool or multiprocessing.Pool): Required to parallelize operations. \n Return:\n SSE\n \"\"\"\n return Reductor.total_ss(samples, pool) - Reductor.sum_of_squares_total(samples, pool)\n\n @classmethod \n def mean_squared_error(clazz, samples, pool = None):# aka MSE\n \"\"\"\n Args:\n samples (2d array like): .-\n pool (optional pathos.multiprocessing.Pool or multiprocessing.Pool): Required to parallelize operations. \n Return:\n The mean squared error (MSE) or mean squared deviation (MSD).\n \"\"\" \n processing_pool = init_pool(pool)\n n = numpy.sum(processing_pool.map(lambda sample: len(sample),samples))\n return Reductor.standard_squared_error(samples, pool) / ( n - len(samples))\n\n ","repo_name":"rafael-paypal-solano/machine-learning-stats","sub_path":"lib/numeric/Reductor.py","file_name":"Reductor.py","file_ext":"py","file_size_in_byte":4185,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"26085470268","text":"'''\nThis file is part of the amoebots project developed under the IPFW Senior Design Capstone.\n\nCreated on Nov 1, 2016\n\nView the full repository here https://github.com/car-chase/amoebots\n'''\n\nimport sys\nimport socketserver\nimport json\nfrom message import Message\n\nclass TCPListener:\n \"\"\"\n Listens for new bots trying to communicate over TCP. It acts as a TCP server so that TCP bots\n can register their ports and ip addresses with the system. Registered bots are given a port\n where they can expect to hear from the server. After registering with the TCP listener, bots\n must create a TCP server and wait for commands from the controller.\n\n NOTE:\n The data sent to the listener should be an encided dictionary like the following\n b'{\\\"type\\\": \\\"SMORES\\\",\\\"ip\\\": \\\"192.168.1.1\\\"}'\n\n Args:\n options (dict): The dictionary containing the program settings.\n\n Attributes:\n options (dict): The dictionary containing the program settings.\n static_com_input (Queue): Static value. Queue for pushing commands from the TCPHandler\n static_next_port (int): Static value. The next available port for a TCP robot to use.\n listener_input (Queue): The queue for receiving messages in the listener level.\n com_input (Queue): The queue for sending messages to the communication level.\n keep_running (bool): Boolean that keeps the main event loop running.\n \"\"\"\n\n # Need a static queue since there is no other way to send messages from the TCPHandler\n static_com_input = None\n\n # Need static port numbers so that the TCPHandler can access this value\n static_next_port = 10000\n\n def __init__(self, options):\n self.options = options\n self.listener_input = None\n self.com_input = None\n self.keep_running = True\n TCPListener.static_next_port = self.options[\"TCP_LISTENER_START_PORT\"]\n\n def tcp_listener_main(self, listener_input, com_input):\n \"\"\"\n The main event loop of the tcp listener. The loop checks for messages to the level,\n interprets the message, and performs the appropriate action.\n\n Args:\n main_input (Queue): The queue for receiving messages in the TCP listener.\n com_input (Queue): The queue for sending messages to the communication level.\n \"\"\"\n\n # Set queues\n self.com_input = com_input\n self.listener_input = listener_input\n TCPListener.static_com_input = com_input\n\n self.com_input.put(Message('TCP_LISTENER', 'MAIN_LEVEL', 'info', {\n 'message': 'TCP_LISTENER is running'\n }))\n\n # Create the server, binding the localhost to the assigned port.\n server = socketserver.TCPServer(\n (self.options[\"TCP_LISTENER_IP\"], self.options[\"TCP_LISTENER_PORT\"]),\n TCPListener.TCPHandler\n )\n server.socket.settimeout(1)\n\n # Enter the main event loop\n while self.keep_running:\n while not self.listener_input.empty():\n\n message = self.listener_input.get()\n\n # Appropriately process the message depending on its category\n if isinstance(message, Message) and message.category == 'command':\n self.process_command(message)\n\n else:\n # Echo back the message if it doesn't know what to do\n self.com_input.put(message)\n\n server.handle_request()\n\n def process_command(self, message):\n \"\"\"\n The command processor of the TCP listener. It processes messages categorized as\n \"commands\".\n\n Args:\n message (Message): The message object to be processed.\n \"\"\"\n\n if message.data['directive'] == 'shutdown' and message.origin == 'COM_LEVEL':\n\n # the listener has been told to shutdown.\n self.com_input.put(Message('TCP_LISTENER', 'MAIN_LEVEL', 'info', {\n 'message': 'Shutting down TCP_LISTENER'\n }))\n\n self.keep_running = False\n sys.exit()\n\n class TCPHandler(socketserver.BaseRequestHandler):\n \"\"\"\n Handles a TCP request.\n \"\"\"\n\n def handle(self):\n # self.request is the TCP socket connected to the client\n # data should be a byte string containing an encoded dictionary\n self.data = self.request.recv(1024).strip().decode(\"utf-8\")\n\n # attempt to load the dictionary\n try:\n self.data = json.loads(self.data)\n\n # check if it is a supported model\n if self.data.get(\"type\") == \"SMORES\":\n # assign the robot a port and inform the com level\n self.request.send(bytes(self.data['ip'] + ' ' +\n str(TCPListener.static_next_port),\n \"utf-8\"))\n\n TCPListener.static_com_input.put(Message(\n \"TCP:\" + str(TCPListener.static_next_port),\n 'COM_LEVEL', 'command',\n {\n 'directive': 'add',\n 'args': self.data,\n 'message': 'Received TCP information'\n }\n ))\n\n TCPListener.static_next_port = TCPListener.static_next_port + 1\n\n else:\n self.request.send(bytes(\"Unsupported robot type\", \"utf-8\"))\n\n except Exception as err:\n # Catch all exceptions and log them.\n TCPListener.static_com_input.put(Message('TCP_LISTENER', 'MAIN_LEVEL', 'error', {\n 'message': str(err)\n }))\n\n # exception occurred, attempt to inform the client of the error.\n self.request.send(bytes(\"Unsupported data type\", \"utf-8\"))\n\n finally:\n # close the socket\n self.request.close()\n","repo_name":"carchase/amoebots","sub_path":"source/ai_controller/tcp_listener.py","file_name":"tcp_listener.py","file_ext":"py","file_size_in_byte":6028,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"81"} +{"seq_id":"41298493402","text":"import numpy as np\nimport torch\n\n\ndef _lanczos_step(vec, size, current_draw):\n\n pass\n\n\ndef lanczos(\n operator,\n max_steps=20,\n tol=1e-6,\n num_lanczos_vectors=None,\n init_vec=None,\n use_gpu=False,\n):\n \"\"\"\n Use the scipy.sparse.linalg.eigsh hook to the ARPACK lanczos algorithm\n to find the top k eigenvalues/eigenvectors.\n\n Parameters\n -------------\n operator: power_iter.Operator\n linear operator to solve.\n num_eigenthings : int\n number of eigenvalue/eigenvector pairs to compute\n which : str ['LM', SM', 'LA', SA']\n L,S = largest, smallest. M, A = in magnitude, algebriac\n SM = smallest in magnitude. LA = largest algebraic.\n max_steps : int\n maximum number of arnoldi updates\n tol : float\n relative accuracy of eigenvalues / stopping criterion\n num_lanczos_vectors : int\n number of lanczos vectors to compute. if None, > 2*num_eigenthings\n init_vec: [torch.Tensor, torch.cuda.Tensor]\n if None, use random tensor. this is the init vec for arnoldi updates.\n use_gpu: bool\n if true, use cuda tensors.\n\n Returns\n ----------------\n eigenvalues : np.ndarray\n array containing `num_eigenthings` eigenvalues of the operator\n eigenvectors : np.ndarray\n array containing `num_eigenthings` eigenvectors of the operator\n \"\"\"\n if isinstance(operator.size, int):\n size = operator.size\n else:\n size = operator.size[0]\n\n if num_lanczos_vectors is None:\n num_lanczos_vectors = min(2 * num_eigenthings, size - 1)\n if num_lanczos_vectors < 2 * num_eigenthings:\n warn(\n \"[lanczos] number of lanczos vectors should usually be > 2*num_eigenthings\"\n )\n\n return eigenvals\n","repo_name":"imirzadeh/stable-continual-learning","sub_path":"external_libs/hessian_eigenthings/spectral_density.py","file_name":"spectral_density.py","file_ext":"py","file_size_in_byte":1764,"program_lang":"python","lang":"en","doc_type":"code","stars":73,"dataset":"github-code","pt":"81"} +{"seq_id":"33323784137","text":"\"\"\"\nCore API interfaces\n\"\"\"\nfrom fin.datetime import CalendarDate, CalendarDateDelta\n\nclass HistoricalData:\n def historical_data(self, ticker, duration=CalendarDateDelta(years=1), end=None,* , select=None):\n \"\"\"\n Return the historical data corresponding to the parameters as a fin.seq.Table\n instance.\n\n The default for duration is one year.\n The default for end (the end date) is today.\n\n The returned table will have the folling columns (order is not garanteed):\n * `Data`\n * `Open`\n * `High`\n * `Low`\n * `Close`\n * `Adj Close`\n * `Volume`\n \"\"\"\n if end is None:\n end = CalendarDate.today()\n t = self._historical_data(ticker, duration, end)\n\n if select:\n t = t.select(*select)\n\n return t\n","repo_name":"s-leroux/fin","sub_path":"fin/api/core.py","file_name":"core.py","file_ext":"py","file_size_in_byte":840,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"27446316968","text":"#!/usr/bin/env python\nimport numpy as np\nfrom time import time\nimport os, pickle, pwd, argparse\n\nparser = argparse.ArgumentParser(\n description='Sensitivity vs. Declination'\n )\nparser.add_argument(\n '--dec', type=float, default=None,\n help='Declination in degrees')\nargs = parser.parse_args()\n\nimport csky as cy\n\ndec = args.dec\ndelta_t = 1e5\n\ngammas = np.linspace(1.5, 4., 21)\nra = 0.\nmjd = 56293.0\n\nusername = pwd.getpwuid(os.getuid())[0]\nana_dir = cy.utils.ensure_dir(f'/home/{username}/central_energies/csky_cache/')\n# Pick your favorite data sample, I used GFU for no particular reason\nana = cy.get_analysis(cy.selections.repo, \n 'version-002-p05', \n cy.selections.GFUDataSpecs.GFU_IC86_2011_2018, \n dir=ana_dir)\n\nconf = {'ana': ana,\n 'extended': True,\n 'space': \"ps\",\n 'time': \"transient\",\n 'sig': 'transient',\n }\n\ndef get_sens(gamma, thresh, delta_t, low_e=0., high_e=np.inf):\n tr = cy.get_trial_runner(conf, ana=ana, src=src, \n flux = cy.hyp.PowerLawFlux(gamma, energy_range=(low_e, high_e)))\n ntrials = 6000 if delta_t < 3e5 else 2000\n sens = tr.find_n_sig(thresh, 0.9,\n batch_size=ntrials,\n max_batch_size=ntrials,\n logging=False)\n if low_e < 1e3:\n e0 = 1.\n else:\n e0 = 1e3\n return tr.to_E2dNdE(sens, E0=e0, unit=1e3)\n\nsens_dict = dict()\n\ndelta_t_days = delta_t / 86400.\n\nsrc = cy.utils.Sources(ra=ra,\n dec=np.radians(dec),\n mjd=mjd,\n sigma_t=0.,\n t_100=delta_t_days)\ntr = cy.get_trial_runner(conf, ana=ana, src=src)\ntry:\n bg_trials = tr.get_many_fits(5000)\n print(np.count_nonzero(bg_trials.ts))\n chi2 = cy.dists.Chi2TSD(bg_trials)\n median = chi2.median()\nexcept:\n median = np.median(bg_trials.ts)\n\nfor gamma in gammas:\n print(f\"Beginning gamma: {gamma:.3f}\")\n\n cy.CONF['src'] = src\n cy.CONF['mp_cpus'] = 5\n\n sens_no_cut = get_sens(gamma, median, delta_t)\n sens_dict[gamma] = sens_no_cut\n\noutput_dir = cy.utils.ensure_dir(f'/home/{username}/central_dnde/central_energies/results/')\noutput_f = output_dir + f'sens_vs_gamma_dec_{dec:.1f}.pkl'\nwith open(output_f, 'wb') as fo:\n pickle.dump(sens_dict, fo)\n","repo_name":"apizzuto/flux_conventions","sub_path":"central_energies/sens_vs_gamma.py","file_name":"sens_vs_gamma.py","file_ext":"py","file_size_in_byte":2215,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"36142879755","text":"from django.views.generic import CreateView, ListView, DetailView\n\nfrom .forms import AddServerForm\nfrom .models import Server\n\n\nclass ServerListView(ListView):\n model = Server\n\n\nclass ServerDetailView(DetailView):\n model = Server\n\n\nclass AddServerCreateView(CreateView):\n template_name = 'mcservers/server_create.html'\n form_class = AddServerForm\n","repo_name":"spiltfish/MinecraftServerSelectWeb","sub_path":"mcservers/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":360,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"27477631350","text":"import yaml\nfrom config.read import get_fund_code, get_stock_code\nfrom core import FundData, StockData\n\n\ndef get_data(fund_code_set, stock_code_set, remind_fs_conf) -> list:\n data_dict = {}\n for fund_code in fund_code_set:\n fund_data = FundData(fund_code, remind_fs_conf[fund_code])\n fund_data.load()\n fund_data.transform()\n data_dict[fund_code] = fund_data\n for stock_code in stock_code_set:\n stock_data = StockData(stock_code, remind_fs_conf[stock_code])\n stock_data.load()\n stock_data.transform()\n data_dict[stock_code] = stock_data\n return data_dict\n\n\nif __name__ == \"__main__\":\n fund_code_set = get_fund_code()\n stock_code_set = get_stock_code()\n data_dict = get_data(fund_code_set, stock_code_set)\n print(data_dict)\n","repo_name":"kingfuzhu/fs_monitor","sub_path":"load.py","file_name":"load.py","file_ext":"py","file_size_in_byte":802,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"81"} +{"seq_id":"13707327583","text":"# coding: utf-8\n\n# In[1]:\n# -------------------------------- #\n### set plotting options\nget_ipython().magic(u'matplotlib')\n# -------------------------------- #\n\n\n## SELECT YOUR LOGGING LEVEL ##\n_logging_level = \"DEBUG\"\n#_logging_level = \"INFO\"\n#_logging_level = \"WARNING\"\n#_logging_level = \"CRITICAL\"\n## ------------------------ ##\nimport logging\n_level = eval(\"logging.\"+_logging_level)\nlogging.basicConfig(level=_level)\n\n\n\n\n# In[2]:\n# -------------------------------- #\n## import code for data processing\nimport peaks.footprint\nfootprint = peaks.footprint.Footprinter()\n# -------------------------------- #\n\n\n# In[20]:\n# -------------------------------- #\n### Import data of 'Peak Scanner 2'-Output and input_trace-file\ntrace_list = footprint.get_data(\"input_traces.csv\")\n# -------------------------------- #\n\n\n# In[21]:\n# -------------------------------- #\n### Set options\n## accepted_offset: peaks are clustered, if their size (=bp) lies within this difference (in bp)\n## factor_method: if \"num\" look for optimal factor (free-floating), if \"peak\" find a footprinting-insensitive peak\n## weight_smaller/weight_bigger: importance of misfit peaks which are smaller / bigger than reference peaks\n## relative_mode: if \"True\" determine the importance of misfit peaks due to their relative size compared to the reference peak, if \"False\" consider absolute difference (in AU)\n## from_bp/ to_bp: peaks in this interval of sizes (=bp) shall be considered for analysis.\n\n\n_accepted_offset = 0.3\n_factor_method = \"num\"\n_weight_smaller = .5\n_weight_bigger = .5\n_relative_mode = False\n_from_bp = float(\"-inf\")\n_to_bp = float(\"+inf\")\n_normalize_to = 1000\n_how_many_peaks_necessary = -1\n\n### Generate the reference trace\nref = footprint.generate_averaged_negative_control(trace_list,accepted_offset=_accepted_offset,factor_method=_factor_method, weight_smaller=_weight_smaller, weight_bigger=_weight_bigger, relative_mode=_relative_mode, from_bp=_from_bp, to_bp=_to_bp, normalize_to=_normalize_to, how_many_peaks_necessary=_how_many_peaks_necessary)\n# -------------------------------- #\n\n\n# In[22]:\n# -------------------------------- #\nfootprint.cluster_peaks(ref,trace_list,accepted_offset=_accepted_offset)\n# -------------------------------- #\n","repo_name":"rgiessmann/peaks","sub_path":"scripts/run_MinimalInit.py","file_name":"run_MinimalInit.py","file_ext":"py","file_size_in_byte":2263,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"81"} +{"seq_id":"35697945685","text":"from broccoli.types import App\nfrom broccoli.traceback import Traceback\n\n\nclass AsyncResult:\n\n def __init__(self, app: App, result_key: str) -> None:\n self.app = app\n self.result_key = result_key\n\n def wait(self, raise_exception=True, timeout=None):\n if self.result_key is None:\n msg = 'Task has no result'\n raise TypeError(msg)\n # noinspection PyUnresolvedReferences\n result = self.app._broker.get_result(self.result_key, timeout=timeout)\n if result is None:\n raise TimeoutError()\n elif result.get('exc'):\n if raise_exception:\n tb = Traceback(result['traceback']) if result.get('traceback') else None\n raise result['exc'] from tb\n return result['exc']\n else:\n return result['value']\n\n def __repr__(self):\n return '%s(result_key=%r)' % (self.__class__.__name__, self.result_key)\n","repo_name":"aachurin/broccoli","sub_path":"broccoli/result.py","file_name":"result.py","file_ext":"py","file_size_in_byte":947,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"81"} +{"seq_id":"22249129286","text":"s = input()\nl = []\nfor i in range(len(s)):\n if s[i] in 'EUIOeuioAa':\n l.append(i+1)\n \nif len(l) >= 1:\n for i in l:\n print(i,end = \" \")\nelse:\n print(\"-1\")","repo_name":"DhanushA1307/My_Codes","sub_path":"python/sample_folders/n_number_files/vowel_position.py","file_name":"vowel_position.py","file_ext":"py","file_size_in_byte":183,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"81"} +{"seq_id":"5877641417","text":"import cv2\nimport numpy as np\n\n# set image path\npath = \"/Users/vansh/PycharmProjects/Text-Extractor/image_processing/\"\nfilename = \"8_image_without_lines_noise_removed.jpg\"\n\n# read input image\ninputimage = cv2.imread(path+filename)\n\n# deep copy for results:\ninputimagecopy = inputimage.copy()\n\n# convert bgr to grayscale:\ngrayscaleimage = cv2.cvtcolor(inputimage, cv2.color_bgr2gray)\n\n# threshold via otsu:\nthreshvalue, binaryimage = cv2.threshold(grayscaleimage, 0, 255, cv2.thresh_binary_inv+cv2.thresh_otsu)","repo_name":"vanshpundir/Text-Extractor","sub_path":"script/image_segmentation.py","file_name":"image_segmentation.py","file_ext":"py","file_size_in_byte":509,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"43312649735","text":"\"\"\"Decorator to make it cope with two staged computation easily.\"\"\"\n\nfrom typing import Any, Callable, Generator, Tuple, Union, cast\n\nimport dask\n\nfrom .intermediate import Intermediate\n\nDecoratee = Callable[..., Generator[Any, Any, Intermediate]]\n\nCompletion = Callable[[Any], Intermediate]\n\n\ndef staged(\n func: Decoratee,\n) -> Callable[..., Union[Tuple[Any, Completion], Intermediate]]:\n \"\"\"Transform a two stage computation into a result and a completion function.\"\"\"\n\n def staged_imp(\n *args: Any, _staged: bool = False, **kwargs: Any\n ) -> Union[Tuple[Any, Completion], Intermediate]:\n gen = func(*args, **kwargs)\n\n def completion(computed: Any) -> Intermediate:\n try:\n gen.send(computed)\n raise RuntimeError(\"Computation didn't stop.\")\n except StopIteration as stop:\n return cast(Intermediate, stop.value)\n\n if _staged:\n return next(gen), completion\n else:\n (computed,) = dask.compute(next(gen))\n return completion(computed)\n\n return staged_imp\n","repo_name":"sfu-db/dataprep","sub_path":"dataprep/eda/staged.py","file_name":"staged.py","file_ext":"py","file_size_in_byte":1101,"program_lang":"python","lang":"en","doc_type":"code","stars":1813,"dataset":"github-code","pt":"81"} +{"seq_id":"40780767936","text":"#!/usr/bin/env python3\n# Firas Akermi\nimport json \nimport pandas as pd\nimport argparse\nimport boto3\nimport botocore\n\ndef from_json_to_csv(input_file,output_file,version,env,date,ref,tool,cluster):\n f = open(cluster)\n f = json.load(f)\n tool_version=f[\"witty\"][\"image\"].split(\":\")[1]\n t_l=tool+\":\"+tool_version \n print(tool_version,\"tool_version\")\n with open(input_file, 'r') as file:\n data=file.read()\n obj = json.loads(data)\n df=[i['DetailedStats'] for i in obj['PerSampleStats']]\n Variant_stats_event={\"VariantType\":[],'StatsType':[],\"TruthTpCount\":[],\n \"TruthFnCount\":[],\"TruthTotalCount\":[],\"Recall\":[],\"QueryTpCount\":[],\"QueryFpCount\":[],\n 'QueryTotalCount':[],\"Precision\":[],'Fscore':[]}\n Variant_stats_base={\"VariantType\":[],'StatsType':[],\"TruthTpCount\":[],\n \"TruthFnCount\":[],\"TruthTotalCount\":[],\"Recall\":[],\"QueryTpCount\":[],\"QueryFpCount\":[],\n 'QueryTotalCount':[],\"Precision\":[],'Fscore':[]}\n varianttype_event=[i['VariantType'] for i in df[0]]\n overall=[i['OverallStats'][0] for i in df[0]]\n base=[i['OverallStats'][1] for i in df[0] if len(i['OverallStats'])>1]\n varianttype_base= [e for e in varianttype_event if e not in ('Insertion',\n 'IntraChromosomeBreakend', \n 'Inversion', \n 'TranslocationBreakend')]\n for i, j in zip(varianttype_event, overall):\n Variant_stats_event['VariantType'].append(i)\n Variant_stats_event['StatsType'].append(j['StatsType'])\n Variant_stats_event['TruthTpCount'].append(j['TruthTpCount'])\n Variant_stats_event['TruthFnCount'].append(j['TruthFnCount'])\n Variant_stats_event['TruthTotalCount'].append(j['TruthTotalCount'])\n Variant_stats_event['Recall'].append(j['Recall'])\n Variant_stats_event['QueryTpCount'].append(j['QueryTpCount'])\n Variant_stats_event['QueryFpCount'].append(j['QueryFpCount'])\n Variant_stats_event['QueryTotalCount'].append(j['QueryTotalCount'])\n Variant_stats_event['Precision'].append(j['Precision'])\n Variant_stats_event['Fscore'].append(j['Fscore'])\n for i, j in zip(varianttype_base, base):\n Variant_stats_base['VariantType'].append(i)\n Variant_stats_base['StatsType'].append(j['StatsType'])\n Variant_stats_base['TruthTpCount'].append(j['TruthTpCount'])\n Variant_stats_base['TruthFnCount'].append(j['TruthFnCount'])\n Variant_stats_base['TruthTotalCount'].append(j['TruthTotalCount'])\n Variant_stats_base['Recall'].append(j['Recall'])\n Variant_stats_base['QueryTpCount'].append(j['QueryTpCount'])\n Variant_stats_base['QueryFpCount'].append(j['QueryFpCount'])\n Variant_stats_base['QueryTotalCount'].append(j['QueryTotalCount'])\n Variant_stats_base['Precision'].append(j['Precision'])\n Variant_stats_base['Fscore'].append(j['Fscore'])\n df_event=pd.DataFrame.from_dict(Variant_stats_event)\n df_base=pd.DataFrame.from_dict(Variant_stats_base)\n df_event=df_event.astype({'Recall': 'float32','Precision':'float32',\"Fscore\":\"float32\"})\n df_base=df_base.astype({'Recall': 'float32','Precision':'float32',\"Fscore\":\"float32\"})\n df_event=df_event.fillna(0)\n df_base=df_base.fillna(0)\n df_event.drop(columns=['StatsType',\"QueryTpCount\"],axis=1,inplace=True)\n df_base.drop(columns=['StatsType',\"QueryTpCount\"],axis=1,inplace=True)\n new_cols = [\"VariantType\",\"TruthTpCount\",\"TruthFnCount\",\"TruthTotalCount\",\"QueryFpCount\",\n \"QueryTotalCount\",\"Precision\",\"Fscore\",\"Recall\"]\n df_event=df_event.reindex(columns=new_cols)\n df_base=df_base.reindex(columns=new_cols)\n New_name={'VariantType':'Categorie','TruthTotalCount':'Total.Standard','TruthTpCount':'VP.Standard','TruthFnCount':'FN.Standard',\n 'QueryTotalCount':'Total.Ech','QueryFpCount':'FP.Ech','Recall':'Rappel','Precision':\"Precision\",\n 'Fscore':'Fscore'}\n df_event=df_event.rename(columns=New_name)\n df_base=df_base.rename(columns=New_name)\n df_event['Version']=list((version,) * len(df_event['Categorie'].values))\n df_event['Environnement']=list((env,) * len(df_event['Categorie'].values))\n df_event['Date']=list((date,) * len(df_event['Categorie'].values))\n df_event['Reference']=list((ref,) * len(df_event['Categorie'].values))\n df_event['Outils']=list((t_l,) * len(df_event['Categorie'].values))\n df_event.reset_index(inplace=True)\n df_event.drop(['index'],axis=1,inplace=True)\n df_base['Version']=list((version,) * len(df_base['Categorie'].values))\n df_base['Environnement']=list((env,) * len(df_base['Categorie'].values))\n df_base['Date']=list((date,) * len(df_base['Categorie'].values))\n df_base['Reference']=list((ref,) * len(df_base['Categorie'].values))\n df_base['Outils']=list((t_l,) * len(df_base['Categorie'].values))\n df_base.reset_index(inplace=True)\n df_base.drop(['index'],axis=1,inplace=True)\n df_event.to_csv(output_file,index=False)\ndef download(user,ip_file,file_path2,bucket_name,file_name2):\n boto3.setup_default_session(profile_name='default')\n with open(ip_file, 'r') as f:\n data = json.load(f)\n for adress in data[\"s3\"]:\n try:\n print('trying ip: {}'.format(adress))\n s3client = boto3.client('s3', endpoint_url=\"http://\"+adress)\n \n s3client.download_file(bucket_name,file_path2,file_name2)\n print(\"Download succeded\")\n break\n except botocore.exceptions.ReadTimeoutError as error: \n continue\ndef upload(user,ip_file,file_path,bucket_name,file_name,file_name2,output_file):\n df=pd.read_csv(file_name2)\n data= pd.read_csv(file_path)\n csv=pd.concat([df,data],sort=False)\n csv.to_csv(output_file,index=False)\n boto3.setup_default_session(profile_name='default')\n with open(ip_file, 'r') as f:\n data = json.load(f)\n for adress in data[\"s3\"]:\n try:\n print('trying ip: {}'.format(adress))\n s3client = boto3.client('s3', endpoint_url=\"http://\"+adress)\n \n s3client.upload_file(file_path,bucket_name,file_name)\n print(\"Upload succeded\")\n break\n except botocore.exceptions.ReadTimeoutError as error: \n continue\nif __name__ == '__main__':\n print(\"script start\")\n parser = argparse.ArgumentParser(description = \"Python script to edit file to aws s3\")\n parser.add_argument(\"-i\",\"--input\", type = str, required= True)\n parser.add_argument(\"-o\",\"--output\", type = str, required= True)\n parser.add_argument(\"-v\",\"--version\", type = str, required= True)\n parser.add_argument(\"-e\",\"--env\", type = str, required= True)\n parser.add_argument(\"-d\",\"--date\", type = str, required= True)\n parser.add_argument(\"-r\",\"--ref\", type = str, required= True)\n parser.add_argument(\"-t\",\"--tool\", type = str, required= True)\n parser.add_argument(\"-u\",\"--user\", type = str, required= True)\n parser.add_argument(\"-ip\",\"--endpoint\", type = str, required= True)\n parser.add_argument(\"-f\",\"--file_path\", type = str, required= True)\n parser.add_argument(\"-b\",\"--bucket_name\", type = str, required= True)\n parser.add_argument(\"-n\",\"--file_name\", type = str, required= True)\n parser.add_argument(\"-f2\",\"--file_path2\", type = str, required= True)\n parser.add_argument(\"-n2\",\"--file_name2\", type = str, required= True)\n parser.add_argument(\"-c\",\"--cluster\", type = str, required= True)\n \n args = parser.parse_args()\n print(\"Script is going to launch\")\n from_json_to_csv(args.input,args.output,args.version,args.env,args.date,args.ref,args.tool,args.cluster)\n print(\"From json to csv end\")\n download(user= args.user,ip_file=args.endpoint,file_path2=args.file_path2,\n bucket_name=args.bucket_name,file_name2=args.file_name2)\n print(\"script download end\")\n upload(user= args.user,ip_file=args.endpoint,file_path=args.file_path,\n bucket_name=args.bucket_name,file_name=args.file_name,file_name2=args.file_name2,output_file=args.output)\n print(\"upload end\")","repo_name":"firas-akermi/pipeline_wgs","sub_path":"script/witty_to_csv.py","file_name":"witty_to_csv.py","file_ext":"py","file_size_in_byte":8644,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"10315186387","text":"from django.urls import path\nfrom . import views\nfrom .views import HomeView, DeetView, AddPost, EditPost, DeletePost, AddCat, AddCatView, AddCatListView, LikeView, AddComment\n\n\nurlpatterns = [\n # path('', views.home, name = \"home\"),\n path('', HomeView.as_view(), name = \"home\"),\n path('article/', DeetView.as_view(), name = \"article_view\"),\n path('addBlog/', AddPost.as_view(), name = \"addBlog\"),\n path('addCategory/', AddCat.as_view(), name = \"addCat\"),\n path('article/edit/', EditPost.as_view(), name = \"edit_post\"),\n path('article//remove', DeletePost.as_view(), name = \"delete_post\"),\n path('category//', AddCatView, name = \"category\"),\n path('category-list/', AddCatListView, name = \"category-list\"),\n path('like/', LikeView, name = \"like_post\"),\n path('article//comment/', AddComment.as_view(), name = \"addComment\"),\n]","repo_name":"nikithashekhar/simple_blog","sub_path":"Trish/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":907,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"24664192454","text":"from Store.models import Order\nimport datetime\nfrom random import randint\nfrom Users.models import Profile\n\nimport django\n\ndef update(username, day, month, year):\n i = Order.objects.get(_player__user__username=username)\n i.orderDate = datetime.datetime.strptime((\"%d %d %d\" % (day, month, year)), \"%d %m %Y\")\n i.paymentDate = i.orderDate # change paymentDate\n i.orderDateY = i.orderDate.strftime(\"%Y\")\n i.orderDateYM = i.orderDate.strftime(\"%Y%m\")\n i.orderDateYW = i.orderDate.strftime(\"%Y%U\")\n i.orderDateYMD = i.orderDate.strftime(\"%Y%m%d\")\n i.save()\n\n\nif __name__ == '__main__':\n django.setup()\n update('user1', 10, 12, 2015)\n update('user2', 28, 11, 2015)\n update('user3', 15, 12, 2015)\n update('user58', 25, 11, 2015)","repo_name":"luispdm/GameStore","sub_path":"docs/randomize_order_date.py","file_name":"randomize_order_date.py","file_ext":"py","file_size_in_byte":762,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"81"} +{"seq_id":"17459110848","text":"import cv2\nimport random\nimport math\nimport numpy as np\nfrom libs.utils.utils import show_bboxes\nfrom libs.utils.align import get_aligned_faces\nfrom libs.mtcnn.mtcnn import MTCNN\nfrom beepy import beep\nimport time\n\ndataDIR = \"C:\\\\Users\\\\Xafold\\\\Desktop\\\\Major_Project\\\\DataCollection\\\\Data\\\\\"\n\ndetector =MTCNN()\n\nprint(\"********** Please enter your Name and Type: Ex: Utsav Masked/Unmasked *********\")\nname,category = input(\"Enter a two value: \").split()\nimage_no = random.randint(0, 1000000)\n\n\ncap = cv2.VideoCapture(0)\ncounter = 0\n############################################\nbeep(sound='ready')\n\nwhile cap.isOpened():\n image_no += 1 \n ret, frame = cap.read()\n frame = cv2.flip(frame,1)\n landmarks, bboxs = detector(frame)\n\n faces = get_aligned_faces(frame, bboxs, landmarks)\n frame = show_bboxes(frame , bboxs , landmarks,'.')\n try:\n\n for face in faces:\n \n if category == \"Masked\":\n counter += 1\n \n x = dataDIR+str(category)+'\\\\'+str(category)+str(name)+str(image_no)+\".JPG\"\n print(x)\n cv2.imwrite(x,face)\n counter += 1\n time.sleep(0.1)\n \n if category == \"Unmasked\":\n \n x = dataDIR+str(category)+'\\\\'+str(category)+str(name)+str(image_no)+\".JPG\"\n cv2.imwrite(x,face)\n counter += 1 \n time.sleep(0.1)\n \n #if category == \"Improper\":\n #x = dataDIR+str(category)+'\\\\'+str(category)+str(name)+str(image_no)+\".JPG\"\n #cv2.imwrite(x,face)\n #counter += 1 \n #time.sleep(0.1)\n\n #cv2.imshow(\"faces\",face)\n #cv2.setWindowProperty(\"faces\", cv2.WND_PROP_TOPMOST, 1)\n\n\n except:\n print(\"No face Deteceted\")\n cv2.putText(frame, \"Please Wait unitil 100\", (5, 30), cv2.FONT_HERSHEY_COMPLEX_SMALL, 1, (0, 0, 255), 1)\n \n cv2.putText(frame, str(counter), (5, 100), cv2.FONT_HERSHEY_COMPLEX_SMALL, 1, (0, 0, 255), 1)\n cv2.imshow(\"Frame\", frame)\n cv2.setWindowProperty(\"Frame\", cv2.WND_PROP_TOPMOST, 1)\n if cv2.waitKey(25) & 0xFF == ord('q'):\n break\n if counter == 150:\n break\n \ncap.release()\ncv2.destroyAllWindows()","repo_name":"xafold/Face-Mask-Detection-System","sub_path":"DataCollection/Datacollect.py","file_name":"Datacollect.py","file_ext":"py","file_size_in_byte":2303,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"81"} +{"seq_id":"72937454026","text":"import numpy as np\n\n\ndef sort_match(i, j):\n \"\"\"\n In the world of matches, the matches are not sorted, but we work with sorted tuples.\n The order is that the first entry is smaller than the second.\n This utility function fixes (j, i) to (i, j) if i > j.\n \"\"\"\n if i < j:\n return (i, j)\n else:\n assert j < i, \"Team does not play itself.\"\n return (j, i)\n\n\ndef get_random_costs(nteams, ratio, seed) -> np.array:\n # Determine the cost matrix\n nrounds = nteams - 1\n nmatches = ((nteams * (nteams - 1)) // 2)\n nelements_costs = nmatches * nrounds\n nselected = int(nelements_costs * ratio) # How many of the matches must we select?\n costs = np.zeros((nteams, nteams, nrounds), dtype=int)\n np.random.seed(seed)\n selected = 0\n choices_matches = np.random.choice(np.arange(nelements_costs), size=nselected, replace=False)\n lower_i, lower_j = np.where(np.arange(nteams)[:, np.newaxis] < np.arange(nteams)[np.newaxis, :])\n # Set the lower diagonal\n costs[lower_i[choices_matches % nmatches], lower_j[choices_matches % nmatches], choices_matches // nmatches] = 1\n # Symmetric matrix.\n costs[lower_j[choices_matches % nmatches], lower_i[choices_matches % nmatches], choices_matches // nmatches] = 1\n assert costs.sum() == nselected * 2\n return costs\n","repo_name":"JasperNL/round-robin","sub_path":"project/srr/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":1325,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"81"} +{"seq_id":"27784651719","text":"import os\nimport tempfile\nimport cv2\nfrom base64 import b64encode\nfrom flask import Flask, request\nfrom utils import ImageProcess\nfrom google.cloud import storage\n\napp = Flask(__name__)\n\n@app.route('/')\ndef home():\n return \"

Hello, This is OCR to Text!

\"\n\n@app.route('/ocr', methods=['POST'])\ndef ocr():\n content_type = request.headers.get('Content-Type')\n if (content_type == 'application/json'):\n body = request.get_json()\n # Download image from cloud storage\n path = body['path']\n list_path = path.split('/')\n form_path = './image/card.jpg'\n list_form_path = form_path.split('/')\n # tmp_form_path = os.path.join(tempfile.gettempdir(), list_form_path[1])\n tmp_image_path = os.path.join(tempfile.gettempdir(), list_path[1])\n storage_client = storage.Client()\n bucket = storage_client.bucket('ocr-card')\n blob_image = bucket.blob(path)\n blob_image.download_to_filename(tmp_image_path)\n image = cv2.imread(tmp_image_path)\n form = cv2.imread(form_path)\n cropped_image = ImageProcess.align_images(image, form)\n cvbase64string = b64encode(cv2.imencode('.jpg', cropped_image)[1]).decode(\"UTF-8\")\n texts = ImageProcess.ocr(cvbase64string)\n list_texts = []\n for text in texts:\n list_texts = text.description.split('\\n')\n break\n response = {\n 'full': list_texts,\n 'status': 'success',\n 'id': list_texts[1].replace(\" \", \"\"),\n 'name_thai': list_texts[4].split(' ').pop(1) + list_texts[4].split(' ').pop(2) + ' ' + list_texts[4].split(' ').pop(3),\n 'name_eng': list_texts[5].split(' ').pop(1) + list_texts[5].split(' ').pop(2) + ' ' + list_texts[7].split(' ').pop(2)\n }\n return response\n else:\n return 'Content-Type not supported!'","repo_name":"ingchoff/ocr-card-backend","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1736,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"9533381098","text":"\"\"\"\n\nWIP \n\nImplement algorithms from \nS. Rodriguez and M. Ludkovski, ACM Trans. Model. Comput. Simul. 30, 1, Article 2. \nhttps://doi.org/10.1145/3355607\n\nTo do: entropy driven sampling from\nS. Rodriguez and M. Ludkovski, European Journal of Operational Research 286 (2020) 588-603.\nhttps://doi.org/10.1016/j.ejor.2020.03.049\n\ndemo: \n>>> from bisection import exper\n>>> nIter = 20 # number of coordinates sampled\n>>> nReps = 1 # number of iterations at the same coordinate\n>>> t = exper(nIter,nReps)\n\n\"\"\" \n\nimport numpy as np\nimport random\nimport logging\nimport copy\nimport matplotlib.pyplot as plt\nfrom scipy.stats import norm\nfrom scipy.special import binom\nfrom scipy.interpolate import interp1d\n\nFORMAT = '%(asctime)-15s- %(levelname)s - %(name)s -%(message)s'\nlogging.basicConfig(format=FORMAT, level=logging.INFO)\nlogger = logging.getLogger(__name__)\n\ndef oracle(xq, noisy=True):\n \"\"\"\n returns h and sigma. if no estimate for sigma, return -1\n \"\"\"\n xs = 4.5\n func = np.loadtxt(\"input.csv\",usecols=[1,2])\n\n # apply the desired offset along the x-axis (i.e., move the zero-crossing)\n x = func[:,0]+xs\n # invert the function so that it's monotonically decreasing\n y = -func[:,1]\n\n f = interp1d(x, y)\n\n h = f([xq])[0]\n\n sigma = 0.3\n\n #h = (xs - xq)\n\n if(noisy):\n Z = random.gauss(h, sigma)\n else :\n Z = h\n return Z,sigma\n\n\nclass State:\n \n def __init__(self, logf):\n self._logf = copy.deepcopy(logf)\n self._xq = np.nan\n self._data = []\n self._Z = np.nan\n self._sig = np.nan\n self._P = np.nan\n self._theta = np.nan\n self._B = np.nan\n self._Bmax = np.nan\n self._K = np.nan\n\n def copy(self):\n copystate = State(copy.deepcopy(self._logf))\n copystate.set_xq(self._xq)\n copystate.set_data(self._data)\n copystate.set_Z(self._Z)\n copystate.set_sig(self._sig)\n copystate.set_theta(self._theta)\n copystate.set_K(self._K)\n copystate.set_B(self._B, self._Bmax)\n return copystate\n \n def get_logf(self): \n return copy.deepcopy(self._logf)\n\n def get_xq(self): \n return copy.deepcopy(self._xq)\n \n def get_Z(self): \n return copy.deepcopy(self._Z)\n\n def get_sig(self): \n return copy.deepcopy(self._sig)\n\n def get_theta(self):\n return copy.deepcopy(self._theta)\n \n def get_K(self): \n return copy.deepcopy(self._K)\n\n def get_Bmax(self): \n return copy.deepcopy(self._Bmax)\n\n\n \n def set_logf(self,logf): \n self._logf = copy.deepcopy(logf)\n\n def set_xq(self,xq): \n self._xq = copy.deepcopy(xq)\n\n def set_data(self,data): \n self._data = copy.deepcopy(data)\n\n def set_Z(self,Z): \n self._Z = copy.deepcopy(Z)\n\n def set_sig(self,sig): \n self._sig = copy.deepcopy(sig)\n\n def set_theta(self,theta):\n \"\"\"\n theta := probability of a positive answer \n P := accuracy or specificity, i.e. probability that the answer is correct\n \"\"\" \n self._theta = copy.deepcopy(theta)\n self._P = max(theta, 1-theta)\n\n def set_K(self, K):\n self._K = copy.deepcopy(K)\n \n def set_B(self, B, Bmax): \n self._B = copy.deepcopy(B)\n self._Bmax = copy.deepcopy(Bmax)\n\n\n \nclass bisect:\n\n def __init__(self, name, oracle, xmin, xmax, xbin, prior=None):\n\n # this may fail to find a zero if it's located within eps/2 of xmax or min\n self.name = name\n \n steps = int(np.floor(xmax-xmin)/xbin)\n rounding = xmax - xmin - xbin*steps\n self.x = [ xmin + rounding/2 + xq*xbin for xq in np.arange(steps+1) ] # edges\n self.oracle = oracle\n self.noisy_oracle = lambda xq : self.oracle(xq, noisy = True) \n \n if prior is not None:\n f = [ prior(xq) for xq in self.x ]\n else: \n f = [ 1 for xq in self.x ] # use uniform prior\n logprior = np.log(f/np.sum(f))\n\n loedge_state = State(logprior)\n loedge_state.set_xq(self.x[0])\n loedge_state.set_theta(1.)\n \n hiedge_state = State(logprior)\n hiedge_state.set_xq(self.x[-1])\n hiedge_state.set_theta(-1.)\n \n self.trial = [loedge_state, hiedge_state]\n \n self.get_next_x = self.sampling_DQS\n self.query = lambda xq, data : self.S(xq, data, empirical = False) \n\n self.mlog = -15.+np.log(1./steps) \n\n\n \n def bisect_ask(self):\n \"\"\"\n gets the last logf from trial history\n generate the next sampling point \n \"\"\" \n return self.get_next_x(self.trial[-1].get_logf()) \n\n \n def bisect_tell(self, xq, data):\n \"\"\"\n pass xq as well, b/c one may actually have changed xq before this step ...\n \"\"\"\n\n self.trial.append(\n self.update_posterior(\n self.query(xq, data)\n )\n )\n \n return self.trial[-1]\n\n \n def run(self, N_iter, K_batches):\n\n for ie in range(N_iter):\n\n xq = self.bisect_ask()\n\n data = []\n for _ in range(K_batches):\n data.append( self.noisy_oracle(xq) )\n\n self.bisect_tell(xq, data)\n \n return len(self.trial)\n \n\n def get_posterior_quantile(self, logf, q):\n\n f = np.exp(logf)\n alpha = np.sum(f) * q\n \n return self.x[np.argmin(np.abs(np.cumsum(f) / np.sum(f) - q))] \n\n def sampling_DQS(self, logf):\n \"\"\" \n\n \"\"\"\n q = [0.25,0.75]\n #q = [0.5]\n index = len(self.trial)%len(q)\n return self.get_posterior_quantile( logf, q[index] )\n #return self.get_posterior_quantile( logf, random.choice(q) )\n \n def sampling_RQS(self, logf):\n \"\"\" \n\n \"\"\"\n q = random.uniform(0,1) \n return self.get_posterior_quantile( logf, q ) \n\n \n def S(self, xq, data, empirical=False):\n \n state = self.trial[-1].copy()\n state.set_xq(xq)\n state.set_data(data)\n \n K = len(data)\n state.set_K(K)\n \n Z=0 ; sig=0 ; ZZ=0\n for h,s in data:\n Z+=h ; sig+=s ; ZZ+=h*h\n if K>0: \n Z/=K ; ZZ/=K ; sig/=K\n if (empirical and K>1): \n sig=np.sqrt((ZZ-Z*Z)*K/(K-1))\n\n state.set_Z(Z)\n state.set_sig(sig)\n\n Bmax = 1\n B = int(Z>0)\n state.set_B(B, Bmax)\n \n \n if (sig>0):\n theta = norm.cdf(np.sqrt(K)*Z/sig)\n else:\n theta = 0.5\n state.set_theta(theta)\n \n return state\n\n \n def update_posterior(self, state):\n\n newstate = state.copy()\n xq = newstate._xq\n P = newstate._P\n B = newstate._B\n Bmax = newstate._Bmax\n\n logP = max(self.mlog,np.log(P))\n logQ = max(self.mlog,np.log(1-P))\n\n logf = newstate.get_logf()\n logf[self.x >= xq] += ( B*logP+(Bmax-B)*logQ )\n logf[self.x < xq] += ( B*logQ+(Bmax-B)*logP )\n \n f = np.exp(logf)\n f /= np.sum(f)\n logf = np.log(f)\n \n newstate.set_logf(logf)\n \n return newstate\n\n \n\n \n \ndef exper(N_iter=10, K_batches=3):\n\n logger.info(\"IMPORTANT! To proceed with the next step, close the matplotlib window!\")\n \n bis = bisect(\"test\",oracle,-20,20,0.1)\n bis.run(N_iter,K_batches)\n\n alpha = (1.-0.95)/2\n \n for t in bis.trial:\n posterior_median = bis.get_posterior_quantile(t.get_logf(),0.5)\n left = bis.get_posterior_quantile(t.get_logf(),alpha)\n right = bis.get_posterior_quantile(t.get_logf(),1-alpha)\n xq = t.get_xq()\n logger.info(f\"xq = {xq} : x* = {posterior_median} [{left} - {right}]\")\n fig, ax = plt.subplots()\n ax.plot(bis.x, np.exp(t.get_logf()))\n ax.set(xlabel='bin', ylabel='posterior',\n title='posterior after update with xq')\n ax.grid()\n plt.show()\n \n return bisect\n\n\nif __name__ == '__main__':\n exper(20,1)\n\n","repo_name":"stracka/bisect","sub_path":"bisection.py","file_name":"bisection.py","file_ext":"py","file_size_in_byte":8166,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"4009293760","text":"from scripts import convert_roman_numeral_to_integer, validate_input\n\n\ndef main():\n string = input('Enter Roman numeral string: ')\n try:\n validate_input(string)\n except ValueError as exception:\n print(exception)\n else:\n value = convert_roman_numeral_to_integer(string)\n print(\"The integer representation of\", string, \"is\", value)\n\n\n# Call the main function to run the program.\nmain()\n","repo_name":"lincolnpowell/foxguard-roman-numeral-converter-python","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":424,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"81"} +{"seq_id":"15954865704","text":"from django.contrib.admin.models import LogEntry, ADDITION, CHANGE\nfrom django.contrib.contenttypes.models import ContentType\nfrom django.core.files.base import ContentFile\nfrom django.db import transaction\n\nfrom ecwsp.admissions.models import *\nfrom ecwsp.sis.models import *\nfrom ecwsp.schedule.models import *\nfrom ecwsp.sis.xlsReport import *\nfrom ecwsp.sis.uno_report import *\nfrom ecwsp.attendance.models import *\n\nimport xlrd\nimport re\nfrom heapq import merge\nfrom datetime import time\nimport datetime\nimport sys\nfrom decimal import *\nimport subprocess\n\nclass Importer:\n def __init__(self, file=None, user=None):\n \"\"\"Opens file. If not xls, convert to xls using uno\n supports any file Openoffice.org supports\"\"\"\n if file:\n self.file = file\n if file.name[-3:] == \"xls\":\n self.book = xlrd.open_workbook(file_contents=file.read())\n else: # convert to xls\n destination = open('/tmp/' + file.name, 'wb+')\n destination.write(file.read())\n destination.close()\n document = uno_open('/tmp/' + str(file.name))\n tmp, filename, content = uno_save(document, file.name, \"xls\")\n self.book = xlrd.open_workbook(tmp.name)\n self.error_data = {}\n self.error_titles = {}\n self.errors = 0\n self.user = user\n \n def do_mysql_backup(self, database='default'):\n args = []\n database = settings.DATABASES[database]\n if 'USER' in database:\n args += [\"--user=%s\" % database['USER']]\n if 'PASSWORD' in database:\n args += [\"--password=%s\" % database['PASSWORD']]\n if 'HOSTNAME' in database:\n args += [\"--host=%s\" % database['HOSTNAME']]\n if 'PORT' in database and database['PORT']:\n args += [\"--port=%s\" % database['PORT']]\n args += [database['NAME']]\n \n new_version = (2,7)\n current_version = sys.version_info\n if current_version >= new_version:\n mysql_as_string = subprocess.check_output('mysqldump %s' % (' '.join(args),),shell=True)\n else:\n mysql_as_string = subprocess.Popen('mysqldump %s' % (' '.join(args),),shell=True).communicate()[0]\n return ContentFile(mysql_as_string)\n \n def make_log_entry(self, user_note=\"\"):\n self.log = ImportLog(user=self.user, user_note=user_note, import_file=self.file)\n file_name = datetime.datetime.now().strftime(\"%Y%m%d%H%M\") + \".sql\"\n if (hasattr(settings, 'BASE_URL') and settings.BASE_URL != 'http://localhost:8000') or not hasattr(settings, 'BASE_URL'):\n self.log.sql_backup.save(file_name, self.do_mysql_backup())\n self.log.save()\n # Clean up old log files\n for import_log in ImportLog.objects.filter(date__lt=datetime.datetime.now() - datetime.timedelta(60)):\n import_log.delete()\n \n def handle_error(self, row, colname, exc, name):\n \"\"\" Add error infomation to exception list and error_date which will be\n transfered to html and a xls file. Also print to stderr. \"\"\"\n transaction.rollback()\n if not hasattr(colname, \"value\") or colname.value:\n value_row = []\n for cell in row:\n value_row += [cell.value]\n error = \"Error at: \" + str(colname) + \" \" + unicode(exc[0]) + unicode(exc[1])\n value_row += [error]\n self.error_data[name] += [value_row]\n self.errors += 1\n \n def sanitize_item(self, name, value):\n \"\"\" Checks to make sure column and cell have data, if not ignore them\n Returns true is valid data \"\"\"\n if value and value.value != \"\" and name and name.value != \"\":\n name = unicode.lower(unicode(name.value))\n value = value.value\n if type(value) is float:\n value = str(value).rstrip('0').rstrip('.')\n return True, name, value\n return False, name, value\n \n def gen_username(self, fname, lname):\n \"\"\"Generate a unique username for a ***User*** (not MdlUser) based on first and last name\n Try first the first letter of the first name plus the last name\n if fail, try adding more letters of the first name\n if fail, add an incrementing number to the end.\n This function should always find a name and never fail except in\n absurd scenarios with many users and limited varchar space\n \"\"\"\n # We have to kill blanks now; consider a stupid case like fname=\" Joe\" lname=\"Student\"\n # username would end up being just \"student\", which is no bueno\n fname = \"\".join(fname.split());\n lname = \"\".join(lname.split());\n try:\n i = 1\n username = unicode(fname[:i]) + unicode(lname)\n while User.objects.filter(username=username).count() > 0:\n i += 1\n username = unicode(fname[:i]) + unicode(lname)\n if username == \"\": raise UsernameError\n except:\n number = 1\n username = unicode(fname[:i]) + unicode(lname) + unicode(number)\n while User.objects.filter(username=username).count() > 0:\n number += 1\n username = unicode(fname[:i]) + unicode(lname) + unicode(number)\n return unicode.lower(username)\n \n def import_number(self, value):\n phonePattern = re.compile(r'''\n # don't match beginning of string, number can start anywhere\n (\\d{3}) # area code is 3 digits (e.g. '800')\n \\D* # optional separator is any number of non-digits\n (\\d{3}) # trunk is 3 digits (e.g. '555')\n \\D* # optional separator\n (\\d{4}) # rest of number is 4 digits (e.g. '1212')\n \\D* # optional separator\n (\\d*) # extension is optional and can be any number of digits\n $ # end of string\n ''', re.VERBOSE)\n a, b, c, ext = phonePattern.search(value).groups()\n if ext == \"0000\":\n ext = \"\"\n return a + \"-\" + b + \"-\" + c, ext\n \n def convert_date(self, value):\n \"\"\"Tries to convert various ways of storing a date to a python date\"\"\"\n try:\n return datetime.datetime.strptime(str(value), \"%Y-%m-%d\")\n except: pass\n try:\n return datetime.datetime.strptime(str(value), \"%m-%d-%Y\")\n except: pass\n try:\n return date(*(xlrd.xldate_as_tuple(float(value), 0)[0:3]))\n except: pass\n try:\n return datetime.datetime.strptime(str(value), \"%Y%m%d\")\n except: pass\n try:\n date_split = value.split(\"-\")\n return datetime.datetime.strptime(str(date_split[0] + \"-\" +date_split[1]), \"%Y-%m\")\n except: pass\n return None\n \n def get_student(self, items, allow_none=False, try_secondary=False):\n \"\"\" Lookup a student based on id, unique id, username, or ssn\n items: name and value from the imported data\n allow_none: Allow not finding a student. If False an exceptions\n try_secondary: \n is raised if the student isn't found. default False\"\"\"\n for (name, value) in items:\n is_ok, name, value = self.sanitize_item(name, value)\n if is_ok:\n if name == \"student id\":\n return Student.objects.get(id=value)\n elif name == \"student unique id\":\n return Student.objects.get(unique_id=value)\n elif name == \"hs_student_id\": # Naviance\n try:\n return Student.objects.get(unique_id=value)\n except:\n return Student.objects.get(id=value)\n elif name == \"student username\":\n return Student.objects.get(username=value)\n elif name == \"ssn\" or name == \"social security number\" or name == \"student ssn\":\n ssn = str(value).translate(None, '- _') # Because student clearing house likes stray _\n ssn = ssn[:3] + '-' + ssn[3:5] + '-' + ssn[-4:] # xxx-xx-xxxx\n return Student.objects.get(ssn=ssn)\n \n # No ID....try secondary keys.\n if try_secondary:\n fname = None\n lname = None\n mname = None\n address = None\n for (name, value) in items:\n is_ok, name, value = self.sanitize_item(name, value)\n if is_ok:\n if name in ['first name','first_name','fname']:\n fname = value\n elif name in ['last name','last_name','lname']:\n lname = value\n elif name in ['middle name','middle_name','mname']:\n mname = value\n elif name in ['address','street address', 'street_address']:\n address = value\n if fname and lname:\n if mname:\n if Student.objects.filter(fname=fname,lname=lname,mname=mname).count() == 1:\n return Student.objects.get(fname=fname,lname=lname,mname=mname)\n if address:\n if Student.objects.filter(fname=fname,lname=lname,address=address).count() == 1:\n return Student.objects.get(fname=fname,lname=lname,address=address)\n if Student.objects.filter(fname=fname,lname=lname).count() == 1:\n return Student.objects.get(fname=fname,lname=lname)\n \n if not allow_none:\n raise Exception(\"Could not find student, check unique id, username, or id\")\n \n def convert_day(self, value):\n \"\"\" Converts day of week to ISO day of week number\n Ex: Monday returns 1\"\"\"\n value = unicode.lower(unicode(value))\n if value == \"monday\" or value == \"m\": return 1\n elif value == \"tuesday\" or value == \"t\": return 2\n elif value == \"wednesday\" or value == \"w\": return 3\n elif value == \"thursday\" or value == \"th\": return 4\n elif value == \"friday\" or value == \"f\": return 5\n elif value == \"saturday\" or value == \"sat\": return 6\n elif value == \"sunday\" or value == \"sun\": return 7\n else: return value\n \n def convert_time(self, value):\n \"\"\"Tries to convert various ways of storing a date to a python time\n Includes excel date format\"\"\"\n pdate = None\n try:\n pdate = datetime.strptime(str(value), \"%H-%M-%S\")\n except:\n pdate = time(*(xlrd.xldate_as_tuple(float(value), 0)[3:]))\n return pdate\n \n def determine_truth(self, value):\n value = unicode(value)\n value = unicode.lower(value)\n if value == \"true\" or value == \"yes\" or value == \"y\" or value == True or value == 1 or value == \"1\" or value == \"1.0\":\n return True\n else:\n return False\n \n def log_and_commit(self, object, inserted=None, updated=None, addition=True):\n if addition:\n LogEntry.objects.log_action(\n user_id = self.user.pk, \n content_type_id = ContentType.objects.get_for_model(object).pk,\n object_id = object.pk,\n object_repr = unicode(object), \n action_flag = ADDITION\n )\n if inserted != None:\n inserted += 1\n else:\n LogEntry.objects.log_action(\n user_id = self.user.pk, \n content_type_id = ContentType.objects.get_for_model(object).pk,\n object_id = object.pk,\n object_repr = unicode(object), \n action_flag = CHANGE\n )\n if updated != None:\n updated += 1\n transaction.commit()\n return inserted, updated\n \n def import_prep(self, sheet):\n x = 0\n header = sheet.row(x)\n x += 1\n inserted = 0\n updated = 0\n header_values = []\n for cell in header:\n header_values += [cell.value]\n header_values += ['Error']\n self.error_titles[sheet.name] = [header_values]\n self.error_data[sheet.name] = []\n return (x, header, inserted, updated)\n \n def get_sheet_by_case_insensitive_name(self, name):\n \"\"\" Use xlrd to get a sheet, but ignore case! \"\"\"\n i = 0\n for sheet_name in self.book.sheet_names():\n if sheet_name.lower() == name.lower():\n return self.book.sheet_by_index(i)\n i += 1\n \n def magic_import_everything(self):\n \"\"\"Import a workbook using sheet names to determine what to import\"\"\"\n self.make_log_entry()\n inserted = 0\n updated = 0\n msg = \"\"\n \n sheet = self.get_sheet_by_case_insensitive_name(\"students\")\n if sheet:\n inserted, updated = self.import_students(sheet)\n msg += \"%s students inserted, %s students updated.
\" % (inserted, updated)\n sheet = self.get_sheet_by_case_insensitive_name(\"emergency contact\")\n if sheet:\n inserted, updated = self.import_emergency_contacts(sheet)\n msg += \"%s emergency contacts inserted, %s emergency contacts updated.
\" % (inserted, updated)\n sheet = self.get_sheet_by_case_insensitive_name(\"faculty\")\n if sheet:\n inserted, updated = self.import_faculty(sheet)\n msg += \"%s faculty inserted, %s faculty updated.
\" % (inserted, updated)\n sheet = self.get_sheet_by_case_insensitive_name(\"attendance\")\n if sheet:\n inserted = self.import_attendance(sheet)\n msg += \"%s attendance records inserted.
\" % (inserted)\n sheet = self.get_sheet_by_case_insensitive_name(\"discipline\")\n if sheet:\n inserted = self.import_discipline(sheet)\n msg += \"%s discipline records inserted.
\" % (inserted)\n sheet = self.get_sheet_by_case_insensitive_name(\"school year\")\n if sheet:\n inserted = self.import_year(sheet)\n msg += \"%s year records inserted.
\" % (inserted)\n sheet = self.get_sheet_by_case_insensitive_name(\"marking period\")\n if sheet:\n inserted = self.import_mp(sheet)\n msg += \"%s marking period records inserted.
\" % (inserted)\n sheet = self.get_sheet_by_case_insensitive_name(\"days off\")\n if sheet:\n inserted = self.import_days_off(sheet)\n msg += \"%s days off records inserted.
\" % (inserted)\n sheet = self.get_sheet_by_case_insensitive_name(\"period\")\n if sheet:\n inserted, updated = self.import_period(sheet)\n msg += \"%s period records inserted. %s period records updated.
\" % (inserted, updated)\n sheet = self.get_sheet_by_case_insensitive_name(\"cohort\")\n if sheet:\n inserted = self.import_cohort(sheet)\n msg += \"%s cohort records inserted.
\" % (inserted)\n sheet = self.get_sheet_by_case_insensitive_name(\"course\")\n if sheet:\n inserted, updated = self.import_course(sheet)\n msg += \"%s course records inserted and %s updated.
\" % (inserted, updated)\n sheet = self.get_sheet_by_case_insensitive_name(\"course enrollment\")\n if sheet:\n inserted = self.import_course_enrollment(sheet)\n msg += \"%s course enrollment records inserted.
\" % (inserted)\n sheet = self.get_sheet_by_case_insensitive_name(\"grade\")\n if sheet:\n inserted, updated = self.import_grades_admin(sheet)\n msg += \"%s grades inserted, %s grades updated.
\" % (inserted, updated)\n sheet = self.get_sheet_by_case_insensitive_name(\"grade comments\")\n if sheet:\n inserted, updated = self.import_grades_comment(sheet)\n msg += \"%s grades comments inserted, %s grades comments updated.
\" % (inserted, updated)\n sheet = self.get_sheet_by_case_insensitive_name(\"standard test\")\n if sheet:\n inserted = self.import_standard_test(sheet)\n msg += \"%s standard tests inserted
\" % (inserted)\n sheet = self.get_sheet_by_case_insensitive_name(\"course meet\")\n if sheet:\n inserted, updated = self.import_course_meet(sheet)\n msg += \"%s course meets inserted, %s course meets updated.
\" % (inserted, updated)\n sheet = self.get_sheet_by_case_insensitive_name(\"workteam\")\n if sheet:\n inserted, updated = self.import_workteams(sheet)\n msg += \"%s workteams inserted, %s workteams updated.
\" % (inserted, updated)\n sheet = self.get_sheet_by_case_insensitive_name(\"student worker\")\n if sheet:\n inserted, updated = self.import_student_workers(sheet)\n msg += \"%s workers inserted, %s workers updated.
\" % (inserted, updated)\n sheet = self.get_sheet_by_case_insensitive_name(\"company contact\")\n if sheet:\n inserted, updated = self.import_company_contacts(sheet)\n msg += \"%s company contacts inserted, %s company contacts updated.
\" % (inserted, updated)\n sheet = self.get_sheet_by_case_insensitive_name(\"applicant\")\n if sheet:\n inserted, updated = self.import_applicants(sheet)\n msg += \"%s applicants inserted, %s applicants updated
\" % (inserted, updated)\n sheet = self.get_sheet_by_case_insensitive_name(\"adm checks\")\n if sheet:\n inserted, updated = self.import_admissions_checks(sheet)\n msg += \"%s admission checks inserted,
\" % (inserted,)\n sheet = self.get_sheet_by_case_insensitive_name(\"adm log\")\n if sheet:\n inserted, updated = self.import_admissions_log(sheet)\n msg += \"%s admission contact log entries inserted,
\" % (inserted,)\n sheet = self.get_sheet_by_case_insensitive_name(\"alumni note\")\n if sheet:\n inserted, updated = self.import_alumni_note(sheet)\n msg += \"%s alumni note entries inserted,
\" % (inserted,) \n sheet = self.get_sheet_by_case_insensitive_name(\"college enrollment\")\n if sheet:\n inserted, updated = self.import_college_enrollment(sheet)\n msg += \"%s college enrollments inserted, %s college enrollments updated.
\" % (inserted, updated)\n sheet = self.get_sheet_by_case_insensitive_name(\"benchmarks\")\n if sheet:\n inserted, updated = self.import_benchmarks(sheet)\n msg += \"%s benchmarks inserted, %s benchmarks updated
\" % (inserted, updated)\n sheet = self.get_sheet_by_case_insensitive_name(\"company contract\")\n if sheet:\n inserted, updated = self.import_contract_information(sheet)\n msg += \"%s contracts inserted, %s contracts updated
\" % (inserted, updated)\n sheet = self.get_sheet_by_case_insensitive_name(\"student work history\")\n if sheet:\n inserted, updated = self.import_student_work_history(sheet)\n msg += \"%s student work history records inserted, %s student work history records updated
\" % (inserted, updated)\n sheet = self.get_sheet_by_case_insensitive_name(\"survey\")\n if sheet:\n inserted, updated = self.import_survey(sheet)\n msg += \"%s survey records inserted, %s survey records updated
\" % (inserted, updated)\n\n sheet = self.get_sheet_by_case_insensitive_name(\"work study attendance\")\n if sheet:\n inserted, updated = self.import_work_study_attendance(sheet)\n msg += \"%s work study attendance records inserted, %s work study attendance records updated
\" % (inserted, updated)\n sheet = self.get_sheet_by_case_insensitive_name(\"family access\")\n if sheet:\n inserted, updated = self.import_family_access(sheet)\n msg += \"%s family access records inserted, %s family access records updated
\" % (inserted, updated)\n \n if msg == \"\":\n msg = \"No files found. Check if sheets are named correctly. \"\n \n msg += unicode(self.errors) + \" error(s). \"\n \n filename = 'import_error.xls'\n if len(self.error_data):\n self.log.errors = True\n self.log.save()\n report = customXls(\"\")\n save = False\n for key, error_page in self.error_data.items():\n if len(error_page):\n save = True\n report.addSheet(error_page, self.error_titles[key][0], heading=key, heading_top=False)\n if save:\n report.save(filename)\n else:\n filename = None\n return msg, filename\n \n def import_just_standard_test(self, test=None):\n inserted = 0\n msg = \"\"\n try:\n sheet = self.book.sheet_by_index(0) # Just get the first one\n inserted = self.import_standard_test(sheet, test)\n msg += \"%s standard tests inserted
\" % (inserted)\n except: pass\n \n if msg == \"\":\n msg = \"No files found. Check if sheets are named correctly. \"\n \n msg += unicode(self.errors) + \" error(s). \"\n \n filename = 'import_error.xls'\n if len(self.error_data):\n report = customXls(\"\")\n save = False\n for key, error_page in self.error_data.items():\n if len(error_page):\n save = True\n report.addSheet(error_page, self.error_titles[key][0], heading=key, heading_top=False)\n if save:\n report.save(filename)\n else:\n filename = None\n return msg, filename\n \n def import_benchmarks(self, sheet, test=None):\n \"\"\"Import Standardized tests. Does not allow updates.\n test: if the test named is already known. \"\"\"\n from ecwsp.omr.models import Benchmark, MeasurementTopic\n from ecwsp.omr.models import Department as omrDepartment\n x, header, inserted, updated = self.import_prep(sheet)\n while x < sheet.nrows:\n with transaction.commit_manually():\n try:\n name = None\n row = sheet.row(x)\n items = zip(header, row)\n created = False\n topic = b_name = number = year = measurement_topic_description = measurement_topic_department = None\n for (name, value) in items:\n is_ok, name, value = self.sanitize_item(name, value)\n if is_ok:\n if name == \"benchmark\":\n b_name = value\n elif name == \"number\":\n number = value\n elif name == \"year\":\n year = value\n elif name in [\"measurement_topics\", \"measurement topic\", \"measurement topics\"]:\n topic = value\n elif name in [\"measurement_topics description\", \"measurement topic description\", \"measurement topics description\"]:\n measurement_topic_description = value\n elif name in [\"measurement_topics department\", \"measurement topic department\", \"measurement topics department\"]:\n measurement_topic_department = value\n if measurement_topic_department:\n measurement_topic_department = omrDepartment.objects.get_or_create(name=measurement_topic_department)[0]\n if topic:\n # Secondary key for measurement topic is department + name.\n if measurement_topic_department == \"\":\n measurement_topic_department = None\n topic = MeasurementTopic.objects.get_or_create(name=topic, department=measurement_topic_department)[0]\n if measurement_topic_description and topic:\n topic.description = measurement_topic_description\n topic.save()\n if measurement_topic_department and topic:\n topic.department = measurement_topic_department\n topic.save()\n model, created = Benchmark.objects.get_or_create(number=number, name=b_name)\n #if number and Benchmark.objects.filter(number=number).count():\n # model = Benchmark.objects.filter(number=number)[0]\n #else:\n # model = Benchmark(number=number)\n # created = True\n if year:\n try:\n model.year = GradeLevel.objects.get(name=year)\n except:\n model.year = GradeLevel.objects.get(id=year)\n model.full_clean()\n model.save()\n model.measurement_topics.add(topic)\n self.log_and_commit(model, addition=created)\n if created:\n inserted += 1\n else:\n updated += 1\n except:\n self.handle_error(row, name, sys.exc_info(), sheet.name)\n x += 1\n return inserted, updated\n \n def import_standard_test(self, sheet, known_test=None):\n \"\"\"Import Standardized tests. Does not allow updates.\n test: if the test name is already known. \"\"\"\n x, header, inserted, updated = self.import_prep(sheet)\n test = known_test\n while x < sheet.nrows:\n with transaction.commit_manually():\n try:\n name = None\n row = sheet.row(x)\n items = zip(header, row)\n created = False\n model = StandardTestResult()\n is_plan = False\n test = None\n if known_test:\n test = known_test\n model.test = test\n model.student = self.get_student(items)\n for (name, value) in items:\n is_ok, name, value = self.sanitize_item(name, value)\n if is_ok:\n if name == \"test name\":\n test, created = StandardTest.objects.get_or_create(name=value)\n model.test = test\n elif name in [\"date\",\"test_date\",\"test date\"]:\n model.date = self.convert_date(value)\n elif name == \"is_plan\":\n is_plan = self.determine_truth(value)\n if is_plan:\n test = StandardTest.objects.get_or_create(name=\"PLAN\")\n model.test = test\n elif name[:9] == \"category \":\n model.save()\n category, created = StandardCategory.objects.get_or_create(name=name[9:], test=test)\n grade, created = StandardCategoryGrade.objects.get_or_create(category=category, result=model, grade=value)\n elif name in [\"verbal\", \"math\", \"writing\", \"english\", \"reading\", \"science\", \"composite\"]: # Naviance\n model.save()\n category = StandardCategory.objects.get_or_create(name=name, test=test)[0]\n grade = StandardCategoryGrade.objects.get_or_create(category=category, result=model, grade=value)[0]\n elif name in [\"show_on_reports\",\"show on reports\",\"show on report\"]:\n model.show_on_reports = self.determine_truth(value)\n model.full_clean()\n model.save()\n self.log_and_commit(model, addition=True)\n inserted += 1\n except:\n self.handle_error(row, name, sys.exc_info(), sheet.name)\n x += 1\n return inserted\n \n def import_alumni_note(self, sheet):\n from ecwsp.alumni.models import Alumni, AlumniNote, AlumniNoteCategory\n x, header, inserted, updated = self.import_prep(sheet)\n name = None\n while x < sheet.nrows:\n with transaction.commit_manually():\n try:\n name = None\n row = sheet.row(x)\n items = zip(header, row)\n student = self.get_student(items,try_secondary=True)\n category = note = date = user = None\n if hasattr(student, 'alumni'):\n alumni = student.alumni\n else:\n alumni = Alumni(student=student)\n alumni.save()\n for (name, value) in items:\n is_ok, name, value = self.sanitize_item(name, value)\n if is_ok:\n if name == \"category\":\n category = AlumniNoteCategory.objects.get_or_create(name=value)[0]\n elif name == \"note\":\n note = value\n elif name == \"date\":\n date = self.convert_date(value)\n elif name == \"user\":\n user = User.objects.get(username=value)\n note, created = AlumniNote.objects.get_or_create(\n alumni=alumni,\n category=category,\n note=note,\n date=date,\n user=user,\n )\n if created:\n self.log_and_commit(note, addition=created)\n inserted += 1\n \n except:\n if hasattr(sheet, 'name'):\n self.handle_error(row, name, sys.exc_info(), sheet.name)\n else:\n self.handle_error(row, name, sys.exc_info(), \"Unknown\")\n x += 1\n return inserted, updated\n \n def import_college_enrollment(self, sheet):\n from ecwsp.alumni.models import Alumni, College, CollegeEnrollment\n x, header, inserted, updated = self.import_prep(sheet)\n name = None\n while x < sheet.nrows:\n with transaction.commit_manually():\n try:\n name = None\n row = sheet.row(x)\n items = zip(header, row)\n student = self.get_student(items,try_secondary=True)\n search_date = code = college_name = state = year = type = begin = end = None\n status = graduated = graduation_date = degree_title = major = record_found = None\n if hasattr(student, 'alumni'):\n alumni = student.alumni\n alumni_created = False\n else:\n alumni = Alumni(student=student)\n alumni.save()\n alumni_created = True\n for (name, value) in items:\n is_ok, name, value = self.sanitize_item(name, value)\n if is_ok:\n if name == \"search date\":\n search_date = self.convert_date(value)\n elif name in [\"college code\", 'college code/branch','college_code/branch']:\n code = value\n elif name in ['name', 'college name','college_name']:\n college_name = value\n elif name in ['state', 'college state', 'college_state']:\n state = value\n elif name in ['year', '2-year/4-year', '2-year / 4-year']:\n if value == \"4-year\": value = \"4\"\n elif value == \"2-year\": value = \"2\"\n year = value\n elif name in ['type', 'public/private', 'public / private']:\n type = value\n elif name in ['begin', 'enrollment begin','enrollment_begin']:\n begin = self.convert_date(value)\n elif name in ['end', 'enrollment end','enrollment_end']:\n end = self.convert_date(value)\n elif name in ['status', 'enrollment status','enrollment_status']:\n status = value.strip()\n elif name in ['graduated', 'graduated?']:\n graduated = self.determine_truth(value)\n elif name in ['graduation date', 'graduation_date']:\n graduation_date = self.convert_date(value)\n elif name in ['degree_title', 'degree title']:\n degree_title = value\n elif name in ['major']:\n major = value\n elif name in ['record_found', 'record_found_y/n']:\n record_found = self.determine_truth(value)\n \n if record_found:\n # First get or create college\n college, c_created = College.objects.get_or_create(code=code)\n if c_created:\n college.name = college_name\n college.state = state\n college.type = type\n college.save()\n if not graduated and begin:\n # Get or create enrollment based on secondary key\n model, created = CollegeEnrollment.objects.get_or_create(\n college=college,\n program_years=year,\n begin=begin,\n end=end,\n status=status,\n alumni=alumni,\n )\n model.search_date = search_date\n model.graduated = graduated\n model.graduation_date = graduation_date\n model.degree_title = degree_title\n model.major = major\n \n model.full_clean()\n model.save()\n self.log_and_commit(model, addition=created)\n if created:\n inserted += 1\n else:\n updated += 1\n elif not alumni.college_override:\n # Graduated but no enrollment data\n alumni.graduated = graduated\n alumni.graduation_date = graduation_date\n if not alumni.college:\n alumni.college = college\n alumni.full_clean()\n alumni.save()\n self.log_and_commit(alumni, addition=alumni_created)\n if alumni_created:\n inserted += 1\n else:\n updated += 1\n else:\n self.log_and_commit(alumni, addition=alumni_created)\n if alumni_created:\n inserted += 1\n else:\n updated += 1\n except:\n if hasattr(sheet, 'name'):\n self.handle_error(row, name, sys.exc_info(), sheet.name)\n else:\n self.handle_error(row, name, sys.exc_info(), \"Unknown\")\n x += 1\n return inserted, updated\n \n def import_cohort(self, sheet):\n \"\"\"Import cohorts. Does not allow updates. \"\"\"\n x, header, inserted, updated = self.import_prep(sheet)\n while x < sheet.nrows:\n with transaction.commit_manually():\n try:\n name = None\n row = sheet.row(x)\n items = zip(header, row)\n created = False\n model = None\n student = model.student = self.get_student(items)\n student_cohort = None\n \n for (name, value) in items:\n is_ok, name, value = self.sanitize_item(name, value)\n if is_ok:\n if name == \"cohort name\":\n model, created = Cohort.objects.get_or_create(name=value)\n if created: model.save()\n elif name == \"primary\":\n if self.determine_truth(value):\n try:\n student_cohort = StudentCohort.objects.get(student=student, cohort=model)\n student_cohort.primary = True\n except: pass\n model.students.add(student)\n model.full_clean()\n model.save()\n if student_cohort: student_cohort.save()\n self.log_and_commit(model, addition=True)\n inserted += 1\n except:\n self.handle_error(row, name, sys.exc_info(), sheet.name)\n x += 1\n return inserted\n \n #@transaction.commit_manually\n def import_course_enrollment(self, sheet):\n \"\"\"Import course enrollments. Does not allow updates. \"\"\"\n x, header, inserted, updated = self.import_prep(sheet)\n while x < sheet.nrows:\n with transaction.commit_manually():\n try:\n name = None\n row = sheet.row(x)\n items = zip(header, row)\n created = False\n model = CourseEnrollment()\n for (name, value) in items:\n is_ok, name, value = self.sanitize_item(name, value)\n if is_ok:\n if name == \"course\":\n model.course = Course.objects.get(fullname=value)\n elif name == \"user\":\n try:\n model.user = MdlUser.objects.get(username=value)\n except:\n try:\n model.user = MdlUser.objects.get(id=value)\n except:\n model.user = MdlUser.objects.get(unique_id=value)\n elif name == \"role\":\n model.role = unicode(value)\n elif name == \"year\":\n try:\n model.year = GradeLevel.objects.get(name=value)\n except: pass\n model.year = GradeLevel.objects.get(id=value)\n model.full_clean()\n model.save()\n self.log_and_commit(model, addition=True)\n inserted += 1\n except:\n self.handle_error(row, name, sys.exc_info(), sheet.name)\n x += 1\n return inserted\n \n #@transaction.commit_manually\n def import_faculty(self, sheet):\n x, header, inserted, updated = self.import_prep(sheet)\n while x < sheet.nrows:\n with transaction.commit_manually():\n try:\n name = None\n row = sheet.row(x)\n items = zip(header, row)\n model = None\n created = False\n comment = \"\"\n for (name, value) in items:\n is_ok, name, value = self.sanitize_item(name, value)\n if is_ok:\n if name == \"username\":\n model, created = Faculty.objects.get_or_create(username=value)\n elif name == \"first name\":\n model.fname = value\n elif name == \"last name\":\n model.lname = value\n elif name == \"is teacher\":\n model.teacher = self.determine_truth(value)\n model.save()\n if created:\n self.log_and_commit(model, addition=True)\n inserted += 1\n else:\n self.log_and_commit(model, addition=False)\n updated += 1 \n except:\n self.handle_error(row, name, sys.exc_info(), sheet.name)\n x += 1\n return inserted, updated\n \n #@transaction.commit_manually\n def import_grades_comment(self, sheet):\n x, header, inserted, updated = self.import_prep(sheet)\n while x < sheet.nrows:\n with transaction.commit_manually():\n try:\n name = None\n row = sheet.row(x)\n items = zip(header, row)\n model = None\n created = False\n comment = \"\"\n for (name, value) in items:\n is_ok, name, value = self.sanitize_item(name, value)\n if is_ok:\n if name == \"id\":\n model, created = GradeComment.objects.get_or_create(id=value)\n elif name == \"comment\":\n model.comment = value\n model.save()\n if created:\n self.log_and_commit(model, addition=True)\n inserted += 1\n else:\n self.log_and_commit(model, addition=False)\n updated += 1\n except:\n self.handle_error(row, name, sys.exc_info(), sheet.name)\n x += 1\n return inserted, updated\n \n def import_grades_admin(self, sheet):\n x, header, inserted, updated = self.import_prep(sheet)\n while x < sheet.nrows:\n with transaction.commit_manually():\n try:\n name = None\n row = sheet.row(x)\n items = zip(header, row)\n created = False\n grade = None\n letter_grade = None\n student = self.get_student(items)\n course = None\n marking_period = None\n override_final = False\n comment = \"\"\n for (name, value) in items:\n is_ok, name, value = self.sanitize_item(name, value)\n if is_ok:\n if name == \"grade\":\n grade = value\n elif name == \"comment code\":\n for cc in str(value).strip().split(','):\n try:\n comment += unicode(GradeComment.objects.get(id=int(float(str(cc).strip()))).comment) + \" \"\n except:\n if comment:\n comment += unicode(cc) + \" IS NOT VALID COMMENT CODE! \"\n elif name == \"comment\":\n comment = unicode(value) + \" \"\n elif name == \"course\":\n course = Course.objects.get(fullname=value)\n elif name == \"marking period\":\n marking_period = MarkingPeriod.objects.get(name=value)\n elif name == \"override final\":\n override_final = self.determine_truth(value)\n if student and course and grade:\n model, created = Grade.objects.get_or_create(student=student, course=course, marking_period=marking_period, override_final=override_final)\n model.comment = comment\n model.set_grade(grade)\n model.override_final = override_final\n model.save()\n if created:\n self.log_and_commit(model, addition=True)\n inserted += 1\n else:\n self.log_and_commit(model, addition=False)\n updated += 1\n else:\n raise Exception('Requires student, course, and grade')\n except:\n self.handle_error(row, header, sys.exc_info(), sheet.name)\n x += 1\n return inserted, updated\n \n #@transaction\\.commit_manually\n def import_course(self, sheet):\n \"\"\"Import Courses. Does allow updates. \"\"\"\n x, header, inserted, updated = self.import_prep(sheet)\n while x < sheet.nrows:\n with transaction.commit_manually():\n try:\n name = None\n location = None\n row = sheet.row(x)\n items = zip(header, row)\n created = False\n model = None\n for (name, value) in items:\n is_ok, name, value = self.sanitize_item(name, value)\n if is_ok:\n if name == \"fullname\":\n model, created = Course.objects.get_or_create(fullname=value)\n elif name == \"shortname\":\n model.shortname = unicode(value)\n elif name == \"description\":\n model.description = unicode(value)\n elif name == \"active\":\n model.active = value\n elif name == \"teacher username\" or name == \"teacher\":\n model.teacher = Faculty.objects.get(username=value)\n elif name == \"location\":\n location, c = Location.objects.get_or_create(name=value)\n if c: location.save()\n elif name == \"level\":\n try:\n model.level = GradeLevel.objects.get(name=value)\n except:\n model.level = GradeLevel.objects.get(id=value)\n elif name == \"homeroom\":\n model.homeroom = value\n elif name == \"graded\":\n model.graded = value\n elif name == \"department\":\n model.department, created = Department.objects.get_or_create(name=value)\n elif name[:14] == \"marking period\":\n model.save()\n model.marking_period.add(MarkingPeriod.objects.get(name=value))\n elif name == \"enroll cohort\":\n model.save()\n cohort, created = Cohort.objects.get_or_create(name=value)\n model.add_cohort(cohort)\n model.full_clean()\n model.save()\n if created:\n self.log_and_commit(model, addition=True)\n inserted += 1\n else:\n self.log_and_commit(model, addition=False)\n updated += 1\n except:\n self.handle_error(row, name, sys.exc_info(), sheet.name)\n x += 1\n return inserted, updated\n \n #@transaction\\.commit_manually\n def import_course_meet(self, sheet):\n x, header, inserted, updated = self.import_prep(sheet)\n while x < sheet.nrows:\n with transaction.commit_manually():\n try:\n name = None\n row = sheet.row(x)\n items = zip(header, row)\n created = False\n course = None\n period = None\n day = None\n location = None\n for (name, value) in items:\n is_ok, name, value = self.sanitize_item(name, value)\n if is_ok:\n if name == \"course\" or name == \"course fullname\":\n course = Course.objects.get(fullname=value)\n elif name == \"period\":\n period = Period.objects.get(name=value)\n elif name == \"day\":\n day = self.convert_day(value)\n elif name == \"location\":\n location = Location.objects.get_or_create(name=value)[0]\n if course and period and day:\n meet, created = CourseMeet.objects.get_or_create(course=course, period=period, day=day)\n if location:\n meet.location = location\n meet.save()\n if created:\n inserted += 1\n else:\n updated += 1\n else:\n raise Exception('Requires course, period, and day')\n except:\n self.handle_error(row, name, sys.exc_info(), sheet.name)\n x += 1\n return inserted, updated\n \n #@transaction\\.commit_manually\n def import_period(self, sheet):\n \"\"\"Import periods. Does not allow updates. \"\"\"\n x, header, inserted, updated = self.import_prep(sheet)\n while x < sheet.nrows:\n with transaction.commit_manually():\n try:\n name = None\n row = sheet.row(x)\n items = zip(header, row)\n created = False\n model = Period()\n for (name, value) in items:\n is_ok, name, value = self.sanitize_item(name, value)\n if is_ok:\n if name == \"name\":\n model, created = Period.objects.get_or_create(name=value)\n elif name == \"start time\":\n model.start_time = self.convert_time(value)\n elif name == \"end time\":\n model.end_time = self.convert_time(value)\n model.full_clean()\n model.save()\n if created:\n self.log_and_commit(model, addition=True)\n inserted += 1\n else:\n self.log_and_commit(model, addition=False)\n updated += 1\n except:\n self.handle_error(row, name, sys.exc_info(), sheet.name)\n x += 1\n return inserted, updated\n \n #@transaction\\.commit_manually\n def import_days_off(self, sheet):\n \"\"\"Import days off for a marking period. Does not allow updates. \"\"\"\n x, header, inserted, updated = self.import_prep(sheet)\n while x < sheet.nrows:\n with transaction.commit_manually():\n try:\n name = None\n row = sheet.row(x)\n items = zip(header, row)\n created = False\n model = DaysOff()\n for (name, value) in items:\n is_ok, name, value = self.sanitize_item(name, value)\n if is_ok:\n if name == \"date\":\n model.date = self.convert_date(value)\n elif name == \"marking period\":\n model.marking_period = MarkingPeriod.objects.get(name=value)\n model.full_clean()\n model.save()\n self.log_and_commit(model, addition=True)\n inserted += 1\n except:\n self.handle_error(row, name, sys.exc_info(), sheet.name)\n x += 1\n return inserted\n \n #@transaction\\.commit_manually\n def import_mp(self, sheet):\n \"\"\"Import marking periods. Does not allow updates. \"\"\"\n x, header, inserted, updated = self.import_prep(sheet)\n while x < sheet.nrows:\n with transaction.commit_manually():\n try:\n name = None\n row = sheet.row(x)\n items = zip(header, row)\n created = False\n model = MarkingPeriod()\n for (name, value) in items:\n is_ok, name, value = self.sanitize_item(name, value)\n if is_ok:\n if name == \"name\":\n model.name = unicode(value)\n if name == \"shortname\" or name == \"short name\":\n model.shortname = unicode(value)\n elif name == \"start date\":\n model.start_date = self.convert_date(value)\n elif name == \"end date\":\n model.end_date = self.convert_date(value)\n elif name == \"school year\":\n model.school_year = SchoolYear.objects.get(name=value)\n elif name == \"monday\":\n if value == \"True\" or value == \"Yes\" or value == True or value == 1:\n model.monday = True\n elif name == \"tuesday\":\n if value == \"True\" or value == \"Yes\" or value == True or value == 1:\n model.tuesday = True\n elif name == \"wednesday\":\n if value == \"True\" or value == \"Yes\" or value == True or value == 1:\n model.wednesday = True\n elif name == \"thursday\":\n if value == \"True\" or value == \"Yes\" or value == True or value == 1:\n model.thursday = True\n elif name == \"friday\":\n if value == \"True\" or value == \"Yes\" or value == True or value == 1:\n model.friday = True\n elif name == \"saturday\":\n if value == \"True\" or value == \"Yes\" or value == True or value == 1:\n model.saturday = True\n elif name == \"sunday\":\n if value == \"True\" or value == \"Yes\" or value == True or value == 1:\n model.sunday = True\n model.full_clean()\n model.save()\n self.log_and_commit(model, addition=True)\n inserted += 1\n except:\n self.handle_error(row, name, sys.exc_info(), sheet.name)\n x += 1\n return inserted\n \n #@transaction\\.commit_manually\n def import_year(self, sheet):\n \"\"\"Import school year. Does not allow updates. \"\"\"\n x, header, inserted, updated = self.import_prep(sheet)\n while x < sheet.nrows:\n with transaction.commit_manually():\n try:\n name = None\n row = sheet.row(x)\n items = zip(header, row)\n created = False\n model = SchoolYear()\n for (name, value) in items:\n is_ok, name, value = self.sanitize_item(name, value)\n if is_ok:\n if name == \"name\":\n model.name = unicode(value)\n elif name == \"start date\":\n model.start_date = self.convert_date(value)\n elif name == \"end date\":\n model.end_date = self.convert_date(value)\n elif name == \"active year\":\n if value == \"True\" or value == \"Yes\" or value == True or value == 1:\n model.active_year = True\n model.full_clean()\n model.save()\n self.log_and_commit(model, addition=True)\n inserted += 1\n except:\n self.handle_error(row, name, sys.exc_info(), sheet.name)\n x += 1\n return inserted\n \n #@transaction\\.commit_manually\n def import_discipline(self, sheet):\n \"\"\"Import discipline linking them to each a student. Does not allow updates. \n If a infraction or action doesn't already exist, it is created\"\"\"\n x, header, inserted, updated = self.import_prep(sheet)\n while x < sheet.nrows:\n model = None\n with transaction.commit_manually():\n try:\n name = None\n row = sheet.row(x)\n items = zip(header, row)\n created = False\n model = StudentDiscipline()\n action_instance = None\n student = self.get_student(items)\n for (name, value) in items:\n is_ok, name, value = self.sanitize_item(name, value)\n if is_ok:\n if name == \"date\":\n model.date = self.convert_date(value)\n elif name == \"teacher username\":\n model.teacher = Faculty.objects.get(username=value)\n elif name == \"infraction\":\n infr, created = PresetComment.objects.get_or_create(comment__iexact=value)\n if created:\n infr.comment = value \n infr.save()\n model.infraction = infr\n elif name == \"comments\":\n model.comments = unicode(value)\n elif name == \"action\":\n action, created = DisciplineAction.objects.get_or_create(name__iexact=value)\n if created: action.save()\n model.save()\n action_instance = DisciplineActionInstance(action=action, student_discipline=model)\n elif name == \"action quantity\":\n action_instance.quantity = value \n model.full_clean()\n model.save()\n model.students.add(student)\n if action_instance: action_instance.save()\n self.log_and_commit(model, addition=True)\n inserted += 1\n except:\n self.handle_error(row, name, sys.exc_info(), sheet.name)\n x += 1\n return inserted\n \n #@transaction\\.commit_manually\n def import_attendance(self, sheet):\n \"\"\"Import attendance linking them to each a student. Does not allow updates. \n If a status doesn't already exist, it is created\"\"\"\n x, header, inserted, updated = self.import_prep(sheet)\n while x < sheet.nrows:\n with transaction.commit_manually():\n try:\n name = None\n row = sheet.row(x)\n items = zip(header, row)\n created = False\n model = StudentAttendance()\n name = \"student\"\n model.student = self.get_student(items)\n for (name, value) in items:\n is_ok, name, value = self.sanitize_item(name, value)\n if is_ok:\n if name == \"date\":\n model.date = self.convert_date(value)\n elif name == \"status\":\n status, created = AttendanceStatus.objects.get_or_create(name=value)\n if created: \n status.name = unicode(value)\n status.save()\n model.status = status\n elif name == \"code\":\n model.status = AttendanceStatus.objects.get(code=value)\n elif name == \"notes\":\n model.notes = unicode(value)\n model.full_clean()\n model.save()\n self.log_and_commit(model, addition=True)\n inserted += 1\n except:\n self.handle_error(row, name, sys.exc_info(), sheet.name)\n x += 1\n return inserted\n \n #@transaction\\.commit_manually\n def import_emergency_contacts(self, sheet):\n \"\"\"Import emergency contacts. Link to student by either username or\n unique id. Will attempt to lookup duplicates and update instead of \n create by using get_or_create on\n student and fname and lname and relationship\"\"\"\n x, header, inserted, updated = self.import_prep(sheet)\n while x < sheet.nrows:\n with transaction.commit_manually():\n try:\n name = None\n row = sheet.row(x)\n items = zip(header, row)\n created = False\n model = None\n id = None\n fname = None\n mname = None\n lname = None\n relationship = None\n email = None\n street = None\n city = state = None\n zips = None # not sure why I can't use zip\n unknown_number = None\n work = None\n home = None\n cell = None\n primary = False\n applicant = None\n student = self.get_student(items, allow_none=True)\n \n for (name, value) in items:\n is_ok, name, value = self.sanitize_item(name, value)\n if is_ok:\n if name == \"emergency contact id\":\n id = value\n elif name == \"applicant id\":\n from ecwsp.admissions.models import Applicant\n applicant = Applicant.objects.get(id=value)\n elif name == \"first name\":\n fname = value\n elif name == \"last name\":\n lname = value\n elif name == \"relationship\":\n relationship = value\n elif name == \"email\":\n email = value\n elif name == \"number\":\n unknown_number = value\n elif name == \"home number\":\n home = value\n elif name == \"cell number\":\n cell = value\n elif name == \"work number\":\n work = value\n elif name == \"primary\":\n primary = self.determine_truth(value)\n elif name == \"street\":\n street = value\n elif name == \"city\":\n city = value\n elif name == \"state\":\n state = value\n elif name == \"zip\":\n zips = value\n elif name ==\"middle name\":\n mname = value\n if id:\n model, created = EmergencyContact.objects.get_or_create(id=id)\n elif student and fname and lname:\n # Secondary key, good enough to find unique emergency contact\n ecs = EmergencyContact.objects.filter(fname=fname, lname=lname, student=student)\n if ecs.count() == 1:\n model = ecs[0]\n else:\n model = EmergencyContact()\n elif applicant and fname and lname:\n ecs = EmergencyContact.objects.filter(fname=fname, lname=lname, applicant=applicant)\n if ecs.count() == 1:\n model = ecs[0]\n else:\n model = EmergencyContact()\n else:\n model = EmergencyContact()\n if fname: model.fname = fname\n if mname: model.mname = mname\n if lname: model.lname = lname\n if email: model.email = email\n if street: model.street = street\n if city: model.city = city\n if state: model.state = state\n if zips: model.zip = zips\n model.primary_contact = primary\n if relationship: model.relationship_to_student = relationship\n model.full_clean()\n model.save()\n if student: model.student_set.add(student)\n if applicant: model.applicant_set.add(applicant)\n if unknown_number:\n number, extension = self.import_number(unknown_number)\n ecNumber, ecNumberCreated = EmergencyContactNumber.objects.get_or_create(number=number, ext=extension, type=\"\" , contact=model)\n ecNumber.contact = model\n ecNumber.save()\n if home: \n number, extension = self.import_number(home)\n ecNumber, ecNumberCreated = EmergencyContactNumber.objects.get_or_create(number=number, ext=extension, type=\"H\" , contact=model)\n ecNumber.contact = model\n ecNumber.save()\n if cell: \n number, extension = self.import_number(cell)\n ecNumber, ecNumberCreated = EmergencyContactNumber.objects.get_or_create(number=number, ext=extension, type=\"C\" , contact=model)\n ecNumber.contact = model\n ecNumber.save()\n if work: \n number, extension = self.import_number(work)\n ecNumber, ecNumberCreated = EmergencyContactNumber.objects.get_or_create(number=number, ext=extension, type=\"W\" , contact=model)\n ecNumber.contact = model\n ecNumber.save()\n model.save()\n if model.id:\n self.log_and_commit(model, addition=False)\n updated += 1\n else:\n self.log_and_commit(model, addition=True)\n inserted += 1\n except:\n self.handle_error(row, name, sys.exc_info(), sheet.name)\n x += 1\n return inserted, updated\n \n #@transaction.commit_manually\n def import_students(self, sheet):\n x, header, inserted, updated = self.import_prep(sheet)\n while x < sheet.nrows:\n with transaction.commit_manually():\n try:\n name = None\n p_fname = p_mname = p_lname = p_relationship_to_student = p_street = p_city = None\n p_state = p_zip = p_email = home = cell = work = other = None\n row = sheet.row(x)\n items = zip(header, row)\n created = False\n model = None\n password = None\n custom_fields = []\n for (name, value) in items:\n is_ok, name, value = self.sanitize_item(name, value)\n if is_ok:\n if name == \"id\":\n try:\n model = Student.objects.get(id=value)\n created = False\n except:\n raise Exception(\"Student ID not found. ID should not be set when creating new student, use unique ID for this.\")\n elif name == \"unique id\" or name == \"unique_id\":\n if model:\n model.unique_id = value\n else:\n students = Student.objects.filter(unique_id=value)\n if students:\n model = students[0]\n created = False\n else:\n model = Student(unique_id=value)\n created = True\n elif name in [\"student username\", \"username\"]:\n if model:\n model.username = value\n else:\n students = Student.objects.filter(username=value)\n if students:\n model = students[0]\n created = False\n else:\n model = Student(username=value)\n created = True\n for (name, value) in items:\n is_ok, name, value = self.sanitize_item(name, value)\n if is_ok and model:\n if name in ['first name','first_name','fname']:\n model.fname = value\n elif name == \"last name\" or name == \"lname\":\n model.lname = value\n elif name == \"student e-mail\" or name == \"student email\":\n model.email = value\n elif name == \"alert\":\n model.alert = value\n elif name == \"grad date\":\n model.grad_date = self.convert_date(value)\n elif name == \"gender\" or name == \"sex\":\n model.sex = unicode.upper(value)\n elif name == \"birth date\" or name == \"birthday\" or name == \"birth day\" or name == \"bday\":\n model.bday = self.convert_date(value)\n elif name == \"year\" or name == \"grade level\":\n try:\n model.year = GradeLevel.objects.get(name=value)\n except:\n model.year = GradeLevel.objects.get(id=value)\n elif name == \"picture\":\n model.pic = value\n elif name in [\"class of year\", \"class of\", \"class_of_year\"]:\n try:\n year = int(value)\n year = ClassYear.objects.get_or_create(year=year)[0]\n self.class_of_year = year\n except:\n year = ClassYear.objects.get(full_name=value)\n self.class_of_year = year\n elif name == \"parent e-mail\" or name == \"parent email\" or name == \"parentemail\" or name == \"parent__email\":\n model.parent_email = value\n elif name == \"middle name\" or name == \"mname\":\n model.mname = value\n elif name == \"homeroom\":\n model.home_room = value\n elif name == \"ssn\" or name == \"social security\":\n model.ssn = value\n elif name in ['preferred language', 'language', 'family preferred language']:\n language = LanguageChoice.objects.get_or_create(name=value)[0]\n model.name = language\n elif name == \"deleted\":\n model.deleted = self.determine_truth(value)\n \n # Import emergency contact shortcut\n elif name in [\"parent first name\", 'parent 1 first name']:\n p_fname = value\n elif name in [\"parent middle name\", 'parent 1 middle name']:\n p_mname = value\n elif name in ['parent last name', 'parent 1 last name']:\n p_lname = value\n elif name in ['parent relationship to student', 'parent 1 relationship to student']:\n p_relationship_to_student = value\n elif name in ['parent street', 'parent 1 street']:\n p_street = value\n elif name in ['parent city', 'parent 1 city']:\n p_city = value\n elif name in ['parent state', 'parent 1 state']:\n p_state = value\n elif name in ['parent zip', 'parent 1 zip']:\n p_zip = value\n elif name in [\"parent e-mail\", \"parent email\", \"parentemail\", \"parent__email\", 'parent 1 email', 'parent 1 e-mail']:\n p_email = value\n elif name in ['parent home number', 'parent 1 home number', 'parent home phone', 'parent 1 home phone']:\n home = value\n elif name in ['parent cell number', 'parent 1 cell number', 'parent cell phone', 'parent 1 cell phone']:\n cell = value\n elif name in ['parent work number', 'parent 1 work number', 'parent work phone', 'parent 1 work phone']:\n work = value\n elif name in ['parent number', 'parent 1 number', 'parent other number', 'parent 1 other number', 'parent phone', 'parent 1 phone', 'parent other phone', 'parent 1 other phone']:\n other = value\n elif name == \"password\":\n password = value\n \n # Custom\n elif name.split() and name.split()[0] == \"custom\":\n custom_fields.append([name.split()[1], value])\n \n if not model.username and model.fname and model.lname:\n model.username = self.gen_username(model.fname, model.lname)\n model.save()\n if password:\n user = User.objects.get(username = model.username)\n user.set_password(password)\n user.save()\n model.save()\n for (custom_field, value) in custom_fields:\n model.set_custom_value(custom_field, value)\n \n for (name, value) in items:\n is_ok, name, value = self.sanitize_item(name, value)\n if is_ok:\n if name == \"student phone\": \n number, extension = self.import_number(value)\n contactModel, contactCreated = StudentNumber.objects.get_or_create(number=number, ext=extension, type=\"H\" , student=model)\n contactModel.save()\n elif name == \"student cell ph\" or name == \"student cell\" or name == \"student cell phone\":\n number, extension = self.import_number(value)\n contactModel, contactCreated = StudentNumber.objects.get_or_create(number=number, ext=extension, type=\"C\" , student=model)\n contactModel.save()\n elif name == \"student phone other\":\n number, extension = self.import_number(value)\n contactModel, contactCreated = StudentNumber.objects.get_or_create(number=number, ext=extension, type=\"O\" , student=model)\n contactModel.save()\n elif name == \"student phone work\":\n number, extension = self.import_number(value)\n contactModel, contactCreated = StudentNumber.objects.get_or_create(number=number, ext=extension, type=\"W\" , student=model)\n contactModel.save()\n elif name == \"primary cohort\":\n cohort = Cohort.objects.get_or_create(name=value)[0]\n student_cohort = StudentCohort.objects.get_or_create(student=model, cohort=cohort)[0]\n student_cohort.primary = True\n student_cohort.save()\n # add emergency contacts (parents)\n if p_lname and p_fname:\n ecs = EmergencyContact.objects.filter(fname=p_fname, lname=p_lname, street=p_street)\n if ecs.count():\n model.emergency_contacts.add(ecs[0])\n else:\n ec = EmergencyContact(\n fname = p_fname,\n mname = p_mname,\n lname = p_lname,\n relationship_to_student = p_relationship_to_student,\n street = p_street,\n city = p_city,\n state = p_state,\n zip = p_zip,\n email= p_email,\n primary_contact = True,\n )\n ec.save()\n if other:\n number, extension = self.import_number(other)\n ecNumber, ecNumberCreated = EmergencyContactNumber.objects.get_or_create(number=number, ext=extension, type=\"\" , contact=ec)\n ecNumber.contact = ec\n ecNumber.save()\n if home: \n number, extension = self.import_number(home)\n ecNumber, ecNumberCreated = EmergencyContactNumber.objects.get_or_create(number=number, ext=extension, type=\"H\" , contact=ec)\n ecNumber.contact = ec\n ecNumber.save()\n if cell: \n number, extension = self.import_number(cell)\n ecNumber, ecNumberCreated = EmergencyContactNumber.objects.get_or_create(number=number, ext=extension, type=\"C\" , contact=ec)\n ecNumber.contact = ec\n ecNumber.save()\n if work: \n number, extension = self.import_number(work)\n ecNumber, ecNumberCreated = EmergencyContactNumber.objects.get_or_create(number=number, ext=extension, type=\"W\" , contact=ec)\n ecNumber.contact = ec\n ecNumber.save()\n model.emergency_contacts.add(ec)\n if created:\n self.log_and_commit(model, addition=True)\n inserted += 1\n else:\n self.log_and_commit(model, addition=False)\n updated += 1\n except:\n self.handle_error(row, name, sys.exc_info(), sheet.name)\n x += 1\n return inserted, updated\n \n \n #@transaction\\.commit_manually\n def import_applicants(self, sheet):\n x, header, inserted, updated = self.import_prep(sheet)\n while x < sheet.nrows:\n with transaction.commit_manually():\n try:\n name = None\n p_fname = p_mname = p_lname = p_relationship_to_student = p_street = p_city = None\n p_state = p_zip = p_email = home = cell = work = other = None\n p2_fname = p2_mname = p2_lname = p2_relationship_to_student = p2_street = p2_city = None\n p2_state = p2_zip = p2_email = home2 = cell2 = work2 = other2 = None\n row = sheet.row(x)\n items = zip(header, row)\n created = True\n model = Applicant()\n model.save()\n for (name, value) in items:\n is_ok, name, value = self.sanitize_item(name, value)\n if is_ok:\n if name == \"id\":\n model = Applicant.objects.get(id=value)\n created = False\n model.save()\n elif name == \"first name\" or name == \"fname\":\n model.fname = value\n elif name == \"last name\" or name == \"lname\":\n model.lname = value\n elif name == \"middle name\" or name == \"mname\":\n model.mname = value\n elif name ==\"social security\" or name == \"ssn\" or name == \"social security number\":\n model.ssn = value\n elif name == \"gender\" or name == \"sex\":\n if value == \"Male\":\n model.sex = \"M\"\n elif value == \"Female\":\n model.sex = \"F\"\n else:\n model.sex = unicode.upper(value)\n elif name == \"birth date\" or name == \"birthday\" or name == \"birth day\" or name == \"bday\":\n model.bday = self.convert_date(value)\n elif name == \"student street\" or name == \"street\":\n model.street = value\n elif name == \"student city\" or name == \"city\":\n model.city = value\n elif name == \"student state\" or name == \"state\":\n model.state = value\n elif name == \"student zip\" or name == \"zip\":\n model.zip = value\n elif name == \"notes\":\n model.notes = value\n elif name == \"year\" or name == \"grade level\":\n #try:\n model.year = GradeLevel.objects.get(name=value)\n #except: pass\n #model.year = GradeLevel.objects.get(id=value)\n elif name == \"school year\" or name == \"school_year\":\n model.school_year = SchoolYear.objects.get(name=value)\n elif name == \"e-mail\" or name == \"email\":\n model.email = value\n elif name == \"home_country\" or name == \"home country\":\n model.home_country = value\n elif name == \"relationship_to_student\" or name == \"relationship to student\":\n model.relationship_to_student = value\n elif name == \"ethnicity\":\n model.ethnicity = EthnicityChoice.objects.get_or_create(name=value)[0]\n elif name == \"hs_grad_yr\" or name == \"high school grad year\":\n model.hs_grad_yr = value\n elif name == \"elem_grad_yr\" or name == \"elem grad year\":\n model.elem_grad_yr = value\n elif name == \"present_school\" or name == \"present school\":\n model.present_school = FeederSchool.objects.get_or_create(name=value)[0]\n elif name == \"religion\":\n model.religion = ReligionChoice.objects.get_or_create(name=value)[0]\n elif name == \"heard_about_us\" or name == \"heard about us\":\n model.heard_about_us = HeardAboutUsOption.objects.get_or_create(name=value)[0]\n elif name == \"first_contact\" or name == \"first contact\":\n model.first_contact = FirstContactOption.objects.get_or_create(name=value)[0]\n elif name == \"borough\":\n model.borough = BoroughOption.objects.get_or_create(name=value)[0]\n elif name == \"application_decision\" or name == \"application decision\":\n model.application_decision = ApplicationDecisionOption.objects.get_or_create(name=value)[0]\n elif name == \"withdrawn\":\n model.withdrawn = WithdrawnChoices.objects.get_or_create(name=value)[0]\n elif name == \"withdrawn_note\" or name == \"withdrawn note\":\n model.withdrawn_note = value\n elif name == \"ready for export\":\n model.ready_for_export = self.determine_truth(value)\n elif name == \"student id\":\n model.sis_student = Student.objects.get(id=value)\n \n elif name in [\"parent first name\", 'parent 1 first name']:\n p_fname = value\n elif name in [\"parent middle name\", 'parent 1 middle name']:\n p_mname = value\n elif name in ['parent last name', 'parent 1 last name']:\n p_lname = value\n elif name in ['parent relationship to student', 'parent 1 relationship to student']:\n p_relationship_to_student = value\n elif name in ['parent street', 'parent 1 street']:\n p_street = value\n elif name in ['parent city', 'parent 1 city']:\n p_city = value\n elif name in ['parent state', 'parent 1 state']:\n p_state = value\n elif name in ['parent zip', 'parent 1 zip']:\n p_zip = value\n elif name in [\"parent e-mail\", \"parent email\", \"parentemail\", \"parent__email\", 'parent 1 email', 'parent 1 e-mail']:\n p_email = value\n elif name in ['parent home number', 'parent 1 home number', 'parent home phone', 'parent 1 home phone']:\n home = value\n elif name in ['parent cell number', 'parent 1 cell number', 'parent cell phone', 'parent 1 cell phone']:\n cell = value\n elif name in ['parent work number', 'parent 1 work number', 'parent work phone', 'parent 1 work phone']:\n work = value\n elif name in ['parent number', 'parent 1 number', 'parent other number', 'parent 1 other number', 'parent phone', 'parent 1 phone', 'parent other phone', 'parent 1 other phone']:\n other = value\n \n elif name in ['parent 2 first name']:\n p2_fname = value\n elif name in [\"parent 2 middle name\"]:\n p2_mname = value\n elif name in ['parent 2 last name']:\n p2_lname = value\n elif name in ['parent 2 relationship to student']:\n p2_relationship_to_student = value\n elif name in ['parent 2 street']:\n p2_street = value\n elif name in ['parent 2 city']:\n p2_city = value\n elif name in ['parent 2 state']:\n p2_state = value\n elif name in ['parent 2 zip']:\n p2_zip = value\n elif name in [\"parent 2 e-mail\", \"parent 2 email\"]:\n p2_email = value\n elif name in ['parent 2 home number', 'parent 2 home phone']:\n home2 = value\n elif name in ['parent 2 cell number', 'parent 2 cell phone']:\n cell2 = value\n elif name in ['parent 2 work number', 'parent 2 work phone']:\n work2 = value\n elif name in ['parent 2 number', 'parent 2 other number', 'parent 2 phone', 'parent 2 other phone']:\n other2 = value\n \n model.save()\n # add emergency contacts (parents)\n if p_lname and p_fname:\n ecs = EmergencyContact.objects.filter(fname=p_fname, lname=p_lname, street=p_street)\n if ecs.count():\n model.parent_guardians.add(ecs[0])\n else:\n ec = EmergencyContact(\n fname = p_fname,\n mname = p_mname,\n lname = p_lname,\n relationship_to_student = p_relationship_to_student,\n street = p_street,\n city = p_city,\n state = p_state,\n zip = p_zip,\n email= p_email,\n primary_contact = True,\n )\n ec.save()\n if other:\n number, extension = self.import_number(other)\n ecNumber, ecNumberCreated = EmergencyContactNumber.objects.get_or_create(number=number, ext=extension, type=\"\" , contact=ec)\n ecNumber.contact = ec\n ecNumber.save()\n if home: \n number, extension = self.import_number(home)\n ecNumber, ecNumberCreated = EmergencyContactNumber.objects.get_or_create(number=number, ext=extension, type=\"H\" , contact=ec)\n ecNumber.contact = ec\n ecNumber.save()\n if cell: \n number, extension = self.import_number(cell)\n ecNumber, ecNumberCreated = EmergencyContactNumber.objects.get_or_create(number=number, ext=extension, type=\"C\" , contact=ec)\n ecNumber.contact = ec\n ecNumber.save()\n if work: \n number, extension = self.import_number(work)\n ecNumber, ecNumberCreated = EmergencyContactNumber.objects.get_or_create(number=number, ext=extension, type=\"W\" , contact=ec)\n ecNumber.contact = ec\n ecNumber.save()\n model.parent_guardians.add(ec)\n if p2_lname and p2_fname:\n ecs = EmergencyContact.objects.filter(fname=p2_fname, lname=p2_lname, street=p2_street)\n if ecs.count():\n model.parent_guardians.add(ecs[0])\n else:\n ec2 = EmergencyContact(\n fname = p2_fname,\n mname = p2_mname,\n lname = p2_lname,\n relationship_to_student = p2_relationship_to_student,\n street = p2_street,\n city = p2_city,\n state = p2_state,\n zip = p2_zip,\n email= p2_email,\n primary_contact = False,\n )\n ec2.save()\n if other2:\n number, extension = self.import_number(other2)\n ecNumber, ecNumberCreated = EmergencyContactNumber.objects.get_or_create(number=number, ext=extension, type=\"\" , contact=ec)\n ecNumber.contact = ec2\n ecNumber.save()\n if home2: \n number, extension = self.import_number(home2)\n ecNumber, ecNumberCreated = EmergencyContactNumber.objects.get_or_create(number=number, ext=extension, type=\"H\" , contact=ec)\n ecNumber.contact = ec2\n ecNumber.save()\n if cell2: \n number, extension = self.import_number(cell2)\n ecNumber, ecNumberCreated = EmergencyContactNumber.objects.get_or_create(number=number, ext=extension, type=\"C\" , contact=ec)\n ecNumber.contact = ec2\n ecNumber.save()\n if work2:\n number, extension = self.import_number(work2)\n ecNumber, ecNumberCreated = EmergencyContactNumber.objects.get_or_create(number=number, ext=extension, type=\"W\" , contact=ec)\n ecNumber.contact = ec2\n ecNumber.save()\n model.parent_guardians.add(ec2)\n model.save()\n for (name, value) in items:\n is_ok, name, value = self.sanitize_item(name, value)\n if is_ok:\n if name == \"siblings\":\n model.siblings.add(Student.objects.get(value))\n elif name == \"open_house_attended\" or name == \"open house attended\":\n try:\n house = OpenHouse.objects.get_or_create(date=self.convert_date(value))[0]\n except:\n house = OpenHouse.objects.get_or_create(name=value)[0]\n model.open_house_attended.add(house)\n elif name == \"checklist\":\n check = AdmissionCheck.objects.get(name=value)\n model.checklist.add(check)\n \n inserted, updated = self.log_and_commit(model, inserted, updated, created)\n except:\n self.handle_error(row, name, sys.exc_info(), sheet.name)\n x += 1\n return inserted, updated\n \n #@transaction\\.commit_manually\n def import_admissions_checks(self, sheet):\n from ecwsp.admissions.models import Applicant, AdmissionCheck\n x, header, inserted, updated = self.import_prep(sheet)\n while x < sheet.nrows:\n try:\n name = None\n row = sheet.row(x)\n items = zip(header, row)\n created = True\n applicant = None\n check = None\n \n for (name, value) in items:\n is_ok, name, value = self.sanitize_item(name, value)\n if is_ok:\n if name == \"applicant id\":\n applicant = Applicant.objects.get(id=value)\n elif name == \"check name\":\n check = AdmissionCheck.objects.get(name=value)\n applicant.checklist.add(check)\n self.log_and_commit(applicant, addition=False)\n if created:\n inserted += 1\n else:\n updated += 1\n except:\n self.handle_error(row, name, sys.exc_info(), sheet.name)\n x += 1\n return inserted, updated\n \n #@transaction\\.commit_manually\n def import_admissions_log(self, sheet):\n from ecwsp.admissions.models import Applicant, ContactLog\n x, header, inserted, updated = self.import_prep(sheet)\n while x < sheet.nrows:\n with transaction.commit_manually():\n try:\n name = None\n row = sheet.row(x)\n items = zip(header, row)\n created = True\n applicant = None\n model = ContactLog()\n \n for (name, value) in items:\n is_ok, name, value = self.sanitize_item(name, value)\n if is_ok:\n if name == \"applicant id\":\n model.applicant = Applicant.objects.get(id=value)\n elif name == \"date\":\n model.date = self.convert_date(value)\n elif name == \"note\":\n model.note = value\n elif name == \"user\":\n model.user = User.objects.get(username=value)\n model.save()\n self.log_and_commit(model, addition=False)\n if created:\n inserted += 1\n else:\n updated += 1\n except:\n self.handle_error(row, name, sys.exc_info(), sheet.name)\n x += 1\n return inserted, updated\n \n @transaction.commit_on_success\n def import_grades(self, course, marking_period):\n \"\"\" Special import for teachers to upload grades\n Returns Error Message \"\"\" \n from ecwsp.grades.models import Grade,GradeComment\n try:\n sheet = self.get_sheet_by_case_insensitive_name(marking_period.name)\n except:\n return \"Could not find a sheet named %s\" % (marking_period,)\n x = 0\n if not sheet:\n return \"Could not find a sheet named %s\" % (marking_period,)\n header = sheet.row(x)\n while x < sheet.nrows:\n try:\n name = None\n row = sheet.row(x)\n items = zip(header, row)\n created = False\n model = None\n grade = None\n comment = \"\"\n del_comments = False\n for (name, value) in items:\n is_ok, name, value = self.sanitize_item(name, value)\n if is_ok:\n if name == \"username\":\n student = Student.objects.get(username=value)\n model, created = Grade.objects.get_or_create(student=student, course=course, marking_period=marking_period)\n elif name in [\"final grade %\",'marking period grade (%)','grade']:\n grade = value\n elif name == \"comment code\" or name == \"comment codes\" or name == \"comment\\ncodes\":\n value = unicode.lower(unicode(value))\n for cc in value.split(','):\n try:\n comment += unicode(GradeComment.objects.get(id=int(float(str(cc)))).comment) + \" \"\n except:\n comment += unicode(cc) + \" IS NOT VALID COMMENT CODE! \"\n value = unicode.lower(value)\n if value.strip() == \"none\":\n del_comments = True\n elif name == \"comment\":\n comment = unicode(value) + \" \"\n if value.strip() == \"none\":\n del_comments = True\n if model and grade:\n model.set_grade(grade)\n model.save()\n self.log_and_commit(model, addition=False)\n if model and comment:\n model.comment = comment\n model.save()\n if model and del_comments:\n model.comment = \"\"\n model.save()\n except:\n print >> sys.stderr, str(sys.exc_info())\n x += 1 \n\n #@transaction\\.commit_manually\n def import_workteams(self, sheet):\n from ecwsp.work_study.models import *\n x, header, inserted, updated = self.import_prep(sheet)\n while x < sheet.nrows:\n with transaction.commit_manually():\n try:\n name = None\n row = sheet.row(x)\n items = zip(header, row)\n model = None\n created = False\n cra = None\n for (name, value) in items:\n is_ok, name, value = self.sanitize_item(name, value)\n if is_ok:\n if name == \"id\" or name == \"workteam id\":\n model = WorkTeam.objects.get(id=value)\n created = False\n elif name == \"workteam\" or name == \"work team\" or name == \"name\":\n model, created = WorkTeam.objects.get_or_create(team_name=value)\n if name == \"company\":\n model.company = Company.objects.get_or_create(name=value)[0]\n elif name == \"login\":\n login = WorkTeamUser.objects.get_or_create(username=value)[0]\n group = Group.objects.get_or_create(name=\"Company\")[0]\n login.groups.add(group)\n model.login.add(login)\n login.save()\n elif name == \"password\":\n login.set_password(value)\n login.save()\n elif name == \"paying\":\n if value == \"Paying\": model.paying = \"P\"\n elif value == \"Non-Paying\": model.paying = \"N\"\n elif value == \"Funded\": model.paying = \"F\"\n else: model.paying = value\n elif name == \"funded_by\" or name ==\"funded by\":\n model.funded_by = value\n elif name == \"cra\":\n cra, created = CraContact.objects.get_or_create(name=User.objects.get(username=value))\n elif name == \"industry_type\" or name == \"industry type\":\n model.industry_type = value\n elif name == \"train_line\" or name == \"train line\":\n model.train_line = value\n elif name == \"industry_type\" or name == \"industry type\":\n model.industry_type = value\n elif name == \"stop_location\" or name == \"stop location\":\n model.stop_location = value\n elif name == \"dropoff_location\" or name == \"dropoff location\":\n model.dropoff_location = PickupLocation.objects.get_or_create(location=value)[0]\n elif name == \"pickup_location\" or name == \"pickup location\":\n model.pickup_location = PickupLocation.objects.get_or_create(location=value)[0]\n elif name == \"address\":\n model.address = value\n elif name == \"city\":\n model.city = value\n elif name == \"state\":\n model.state = value\n elif name == \"zip\":\n model.zip = value\n elif name == \"directions_to\" or name == \"directions to\":\n model.directions_to = value\n elif name == \"directions_pickup\" or name == \"directions pickup\":\n model.directions_pickup = value\n elif name == \"use_google_maps\" or name == \"use google maps\":\n model.use_google_maps = self.determine_truth(value)\n elif name == \"job_description\" or name == \"job description\":\n model.job_description = value\n model.save()\n if cra:\n model.cras.add(cra)\n if created:\n self.log_and_commit(model, addition=True)\n inserted += 1\n else:\n self.log_and_commit(model, addition=False)\n updated += 1\n except:\n self.handle_error(row, name, sys.exc_info(), sheet.name)\n x += 1\n return inserted, updated\n\n #@transaction\\.commit_manually\n def import_company_contacts(self, sheet):\n from ecwsp.work_study.models import *\n x, header, inserted, updated = self.import_prep(sheet)\n while x < sheet.nrows:\n with transaction.commit_manually():\n try:\n name = None\n row = sheet.row(x)\n items = zip(header, row)\n model = Contact()\n created = True\n fname = None\n lname = None\n phone = None\n phone_cell = None\n fax = None\n email = None\n workteam = None\n for (name, value) in items:\n is_ok, name, value = self.sanitize_item(name, value)\n if is_ok:\n if name == \"id\":\n model = Contact.objects.get(id=value)\n created = False\n elif name == \"guid\":\n model.guid = value\n elif name == \"fname\" or name == \"first name\":\n fname = value\n elif name == \"lname\" or name == \"last name\":\n lname = value\n elif name == \"phone\":\n number, ext = self.import_number(value)\n if ext:\n phone = number + \" \" + ext\n else:\n phone = number\n elif name == \"phone_cell\" or name == \"phone cell\":\n number, ext = self.import_number(value)\n if ext:\n phone_cell = number + \" \" + ext\n else:\n phone_cell = number\n elif name == \"email\":\n email = value\n elif name == \"fax\":\n fax = value\n elif name == \"work team\":\n workteam = WorkTeam.objects.get(team_name=value)\n existing_contacts = Contact.objects.filter(fname=fname,lname=lname)\n if existing_contacts.count()==1:\n model = Contact.objects.get(id = existing_contacts[0].id)\n created = False\n elif existing_contacts.count() >1:\n exist_filter_by_workteam = existing_contacts.workteam_set.filter(workteam)\n if exist_filter_by_workteam.count()==1:\n model = Contact.objects.get(id = exist_filter_by_workteam[0].id)\n created = False\n else:\n model.fname =fname\n model.lname = lname\n else:\n model.fname = fname\n model.lname = lname\n if phone: model.phone = phone\n if phone_cell: model.phone_cell = phone_cell\n if fax: model.fax = fax\n if email: model.email = email\n model.save()\n if workteam: model.workteam_set.add(workteam)\n \n model.save()\n if created:\n self.log_and_commit(model, addition=True)\n inserted += 1\n else:\n self.log_and_commit(model, addition=False)\n updated += 1\n except:\n self.handle_error(row, name, sys.exc_info(), sheet.name)\n x += 1\n \n return inserted, updated\n\n #@transaction\\.commit_manually\n def import_student_workers(self, sheet):\n \"\"\" Import students workers \"\"\"\n from ecwsp.work_study.models import *\n x, header, inserted, updated = self.import_prep(sheet)\n while x < sheet.nrows:\n with transaction.commit_manually():\n try:\n name = None\n row = sheet.row(x)\n items = zip(header, row)\n model = None\n supid = None\n created = True\n try:\n student = self.get_student(items)\n created = False\n except:\n student = None\n for (name, value) in items:\n is_ok, name, value = self.sanitize_item(name, value)\n if is_ok:\n if student:\n if hasattr(student, 'studentworker'):\n model = student.studentworker\n else:\n student.promote_to_worker()\n student = StudentWorker.objects.get(id=student.id)\n else:\n if name == \"student unique id\":\n model = StudentWorker(unique_id=value)\n elif name == \"student username\":\n model = StudentWorker(username=value)\n if name == \"day\" or name == \"work day\":\n value = unicode.lower(value)\n if value == \"monday\": model.day = \"M\"\n elif value == \"tuesday\": model.day = \"T\"\n elif value == \"wednesday\": model.day = \"W\"\n elif value == \"thursday\": model.day = \"TH\"\n elif value == \"friday\": model.day = \"F\"\n else: model.day = value\n elif name == \"workteam id\" or name == 'workteam_id':\n model.placement = WorkTeam.objects.get(id=value)\n elif name == \"workteam name\" or name == \"placement\":\n model.placement = WorkTeam.objects.get(team_name=value)\n elif name == \"work permit\" or name == \"work permit number\":\n model.work_permit_no = value\n elif name == \"primary supervisor id\" or name == \"supervisor id\":\n supid = value\n if Contact.objects.get(id=supid):\n model.primary_contact = Contact.objects.get(id=supid)\n model.save()\n if created:\n self.log_and_commit(model, addition=True)\n inserted += 1\n else:\n self.log_and_commit(model, addition=False)\n updated += 1\n except:\n self.handle_error(row, name, sys.exc_info(), sheet.name)\n x += 1\n return inserted, updated\n\n def import_student_work_history(self, sheet):\n #does not allow updates\n from ecwsp.work_study.models import *\n x, header, inserted, updated = self.import_prep(sheet)\n while x < sheet.nrows:\n with transaction.commit_manually():\n try:\n name = None\n row = sheet.row(x)\n items = zip(header, row)\n model = CompanyHistory()\n try:\n student = self.get_student(items)\n except:\n student = None\n created = True\n for (name, value) in items:\n is_ok, name, value = self.sanitize_item(name, value)\n if is_ok:\n if student:\n if not hasattr(student, 'studentworker'):\n student.promote_to_worker()\n model.student = StudentWorker.objects.get(id=student.id)\n \n else:\n if name == \"student unique id\" or name == \"unique id\":\n model.student = StudentWorker(unique_id=value)\n elif name == \"student username\":\n model.student = StudentWorker(username=value)\n if name ==\"placement\" or name == \"workteam\":\n model.placement = WorkTeam.objects.get(team_name=value)\n elif name == \"date\" or name== \"date left\":\n model.date = self.convert_date(value)\n elif name == \"fired\":\n model.fired = self.determine_truth(value)\n model.full_clean()\n model.save()\n if created:\n self.log_and_commit(model, addition=True)\n inserted += 1\n else:\n self.log_and_commit(model, addition=False)\n updated += 1\n except:\n self.handle_error(row, name, sys.exc_info(), sheet.name)\n x += 1\n return inserted, updated\n\n #@transaction\\.commit_manually\n def import_contract_information(self, sheet):\n #does not allow updates\n from ecwsp.work_study.models import *\n x, header, inserted, updated = self.import_prep(sheet)\n while x < sheet.nrows:\n with transaction.commit_manually():\n try:\n name = None\n row = sheet.row(x)\n items = zip(header, row)\n model = None\n \n created = True\n for (name, value) in items:\n is_ok, name, value = self.sanitize_item(name, value)\n if is_ok:\n if name == \"company\":\n model = CompContract(company = Company.objects.get(name=value))\n elif name == \"official company name\" or name == \"official name\" or name == \"company name\":\n model.company_name = value\n elif name == \"name\" or name == \"contact name\":\n model.name = value\n elif name == \"contact title\" or name ==\"title\":\n model.title = value\n elif name == \"date\" or name == \"effective date\" or name == \"start date\":\n model.date = self.convert_date(value)\n elif name == \"school year\":\n model.school_year = SchoolYear.objects.get(name=value)\n elif name == \"number of students\" or name == \"number students\" or name == \"students\":\n model.number_students = value\n elif name == \"payment option\" or name == \"payment\":\n model.payment = PaymentOption.objects.get(name=value)\n elif name.find(\"responsibilities\") != -1:\n model.save()\n try:\n model.student_functional_responsibilities.add(StudentFunctionalResponsibility.objects.get(name=value))\n except:\n model.student_functional_responsibilities_other += value\n elif name.find(\"skills\") != -1:\n model.save()\n try:\n model.student_desired_skills.add(StudentDesiredSkill.objects.get(name = value))\n except:\n model.student_desired_skills_other += value\n elif name == \"student leave\" or name == \"leave\":\n model.student_leave = self.determine_truth(value)\n elif name == \"student leave lunch\" or name == \"leave lunch\" or name == \"lunch\":\n model.student_leave_lunch = self.determine_truth(value)\n elif name == \"student leave errands\" or name == \"leave errands\" or name == \"errands\":\n model.student_leave_errands = self.determine_truth(value)\n elif name == \"student leave other\" or name == \"leave other\":\n model.student_leave_other = value\n elif name == \"signed\":\n model.signed = self.determine_truth(value)\n \n \n model.save()\n if created:\n self.log_and_commit(model, addition=True)\n inserted += 1\n else:\n self.log_and_commit(model, addition=False)\n updated += 1\n except:\n self.handle_error(row, name, sys.exc_info(), sheet.name)\n x += 1\n return inserted, updated\n \n def import_survey(self, sheet):\n #does not allow updates\n from ecwsp.work_study.models import Survey, StudentWorker, WorkTeam\n x, header, inserted, updated = self.import_prep(sheet)\n while x < sheet.nrows:\n with transaction.commit_manually():\n try:\n name = None\n row = sheet.row(x)\n items = zip(header, row)\n model = Survey()\n questions = []\n answers = []\n student = None\n survey = None\n company = None\n date = None\n try:\n student = self.get_student(items)\n except:\n student = None\n created = True\n for (name, value) in items:\n is_ok, name, value = self.sanitize_item(name, value)\n if is_ok:\n if student:\n student = StudentWorker.objects.get(id=student.id)\n \n else:\n if name == \"student unique id\" or name == \"unique id\":\n student = StudentWorker(unique_id=value)\n elif name == \"student username\":\n student = StudentWorker(username=value)\n if name == \"survey\" or name == \"title\" or name == \"name\":\n survey = value\n elif name ==\"company\" or name == \"workteam\":\n company = WorkTeam.objects.get(team_name=value)\n elif name == \"date\":\n date = self.convert_date(value)\n elif name[:9] == \"question \":\n questions.append(name[9:])\n answers.append(value)\n ct = 0\n for question in questions:\n if student: model.student = student\n if survey: model.survey = survey\n if company: model.company = company\n if date: model.date = date\n model.question = question\n model.answer = answers[ct]\n model.full_clean()\n model.save()\n ct+=1\n self.log_and_commit(model, addition=True)\n inserted += 1\n model = Survey()\n \n except:\n self.handle_error(row, name, sys.exc_info(), sheet.name)\n x += 1\n return inserted, updated\n \n def import_work_study_attendance(self, sheet):\n from ecwsp.work_study.models import StudentWorker, Attendance, AttendanceFee, AttendanceReason\n x, header, inserted, updated = self.import_prep(sheet)\n while x < sheet.nrows:\n with transaction.commit_manually():\n try:\n name = None\n row = sheet.row(x)\n items = zip(header, row)\n created = True\n absence_date = None\n tardy = None\n tardy_time_in = None\n fee = None\n paid = None\n billed = None\n reason = None\n waive = None\n notes = None\n try:\n student = self.get_student(items)\n except:\n student = None\n for (name, value) in items:\n is_ok, name, value = self.sanitize_item(name, value)\n if is_ok:\n if name == \"id\":\n id = value\n if student:\n student = StudentWorker.objects.get(id=student.id)\n else:\n if name == \"student unique id\" or name == \"unique id\":\n student = StudentWorker(unique_id=value)\n elif name == \"student username\":\n student = StudentWorker(username=value)\n if name == \"date\" or name == \"absence date\":\n absence_date = self.convert_date(value)\n if name == \"tardy\" or name == \"attendance type\":\n tardy = value\n elif name == \"tardy time in\" or name == \"time in\":\n tardy_time_in = value\n elif name == \"fee\":\n fee = value\n elif name == \"paid\" or name==\"amount paid\" or name==\"student paid\":\n paid = value\n elif name == \"billed\":\n billed = self.determine_truth(value)\n elif name == \"reason\":\n reason = value\n elif name == \"half day\":\n half_day = self.determine_truth(value)\n elif name == \"waive\" or name == \"waive fee\":\n waive = self.determine_truth(value)\n elif name == \"notes\":\n notes = value\n \n if id:\n model, created = Attendance.objects.get_or_create(id=id)\n elif student and date:\n attendances = EmergencyContact.objects.filter(student=student, date=date)\n if attendances.count() == 1:\n model = attendances[0]\n created = False\n else:\n model = Attendance()\n if student: model.student = student\n if absence_date: model.absence_date = absence_date\n if tardy_time_in: model.tardy_time_in = self.convert_time(tardy_time_in)\n if paid: model.paid = paid\n if billed: model.billed = billed\n if reason: model.reason, created = AttendanceReason.objects.get_or_create(name = reason)\n if half_day:\n model.half_day = half_day\n if waive: model.waive = waive\n if notes: model.notes = notes\n if fee:\n try:\n model.fee = AttendanceFee.objects.get(name = fee)\n except:\n model.fee = AttendanceFee.objects.get(value = fee)\n \n if tardy:\n if tardy == \"A\" or tardy == \"T\":\n model.tardy = tardy\n elif tardy.lower() == \"absent\":\n model.tardy = \"A\"\n elif tardy.lower() == \"half day\":\n model.tardy = \"A\"\n model.half_day = True\n elif tardy.lower() == \"tardy\" or tardy.lower() == \"late\":\n model.tardy = \"T\"\n model.full_clean()\n model.save()\n if created:\n self.log_and_commit(model, addition=True)\n inserted += 1\n else:\n self.log_and_commit(model, addition=False)\n updated += 1\n except:\n self.handle_error(row, name, sys.exc_info(), sheet.name)\n x += 1\n return inserted, updated\n\n def import_family_access(self, sheet):\n from ecwsp.sis.models import Student, FamilyAccessUser\n x, header, inserted, updated = self.import_prep(sheet)\n while x < sheet.nrows:\n try:\n with transaction.commit_manually():\n name = None\n student_username = None\n row = sheet.row(x)\n items = zip(header, row)\n\n model = None\n for (name, value) in items:\n is_ok, name, value = self.sanitize_item(name, value)\n if is_ok and name == 'family username':\n model, created = FamilyAccessUser.objects.get_or_create(username=value)\n\n if model is None:\n raise Exception(\"The column 'family username' must have a value for each row.\")\n # kills this iteration\n\n for (name, value) in items:\n is_ok, name, value = self.sanitize_item(name, value)\n if is_ok:\n if name in ['first name','first_name','fname']:\n model.first_name = value\n elif name in ['last name','last_name','lname']:\n model.last_name = value\n elif name == 'password':\n model.set_password(value)\n elif name in ['student username', 'student']:\n student_username = value\n \n model.full_clean()\n model.save()\n if created:\n self.log_and_commit(model, addition=True)\n inserted += 1\n else:\n self.log_and_commit(model, addition=False)\n updated += 1\n\n Student.objects.get(username=student_username).family_access_users.add(model)\n except:\n self.handle_error(row, name, sys.exc_info(), sheet.name)\n x += 1\n return inserted, updated\n","repo_name":"google-code-export/student-worker-relational-database","sub_path":"ecwsp/sis/importer.py","file_name":"importer.py","file_ext":"py","file_size_in_byte":134612,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"81"} +{"seq_id":"452551640","text":"from maya import OpenMayaUI as OpenMayaUI\nfrom PySide2.QtWidgets import QWidget\nfrom gt.utils import version_utils\nfrom shiboken2 import wrapInstance\nfrom PySide2.QtGui import QIcon\nimport maya.cmds as cmds\n\n\ndef build_gui_about_gt_tools():\n \"\"\" Creates \"About\" window for the GT Tools menu \"\"\"\n\n gt_version = version_utils.get_installed_version()\n\n window_name = \"build_gui_about_gt_tools\"\n if cmds.window(window_name, exists=True):\n cmds.deleteUI(window_name, window=True)\n\n cmds.window(window_name, title=\"About - GT Tools\", mnb=False, mxb=False, s=True)\n cmds.window(window_name, e=True, s=True, wh=[1, 1])\n\n cmds.columnLayout(\"main_column\", p=window_name)\n\n # Title Text\n cmds.separator(h=12, style='none') # Empty Space\n cmds.rowColumnLayout(nc=1, cw=[(1, 310)], cs=[(1, 10)], p=\"main_column\") # Window Size Adjustment\n cmds.rowColumnLayout(nc=1, cw=[(1, 300)], cs=[(1, 10)], p=\"main_column\") # Title Column\n cmds.text(\"GT Tools\", bgc=[.4, .4, .4], fn=\"boldLabelFont\", align=\"center\")\n cmds.separator(h=10, style='none', p=\"main_column\") # Empty Space\n\n cmds.rowColumnLayout(nc=1, cw=[(1, 300)], cs=[(1, 10)], p=\"main_column\")\n cmds.text(l='Version Installed: ' + gt_version, align=\"center\", fn=\"boldLabelFont\")\n cmds.separator(h=5, style='none') # Empty Space\n cmds.text(l='GT Tools is a free collection of Maya scripts', align=\"center\")\n\n cmds.separator(h=15, style='none') # Empty Space\n cmds.text(l='About:', align=\"center\", fn=\"boldLabelFont\")\n cmds.text(l='This is my collection of scripts for Autodesk Maya.\\n'\n 'These scripts were created with the aim of automating,\\n e'\n 'nhancing or simply filling the missing details of what\\n I find lacking in Maya.', align=\"center\")\n cmds.separator(h=15, style='none') # Empty Space\n cmds.text(\n l='When installed you can find a pull-down menu that\\n provides easy access to a variety of related tools.',\n align=\"center\")\n cmds.separator(h=5, style='none') # Empty Space\n cmds.text(l='This menu contains sub-menus that have been\\n organized to contain related tools.\\n '\n 'For example: modeling, rigging, utilities, etc...', align=\"center\")\n cmds.separator(h=15, style='none') # Empty Space\n cmds.text(l='All of these items are supplied as is.\\nYou alone are responsible for any issues.\\n'\n 'Use at your own risk.', align=\"center\")\n cmds.separator(h=15, style='none') # Empty Space\n cmds.text(l='Hopefully these scripts are helpful to you\\nas they are to me.', align=\"center\")\n cmds.separator(h=15, style='none') # Empty Space\n cmds.rowColumnLayout(nc=2, cw=[(1, 140), (2, 140)], cs=[(1, 10), (2, 0)], p=\"main_column\")\n cmds.text('Guilherme Trevisan ')\n cmds.text(l='TrevisanGMW@gmail.com', hl=True, highlightColor=[1, 1, 1])\n cmds.rowColumnLayout(nc=2, cw=[(1, 140), (2, 140)], cs=[(1, 10), (2, 0)], p=\"main_column\")\n cmds.separator(h=15, style='none') # Empty Space\n cmds.text(l='Github', hl=True, highlightColor=[1, 1, 1])\n cmds.separator(h=7, style='none') # Empty Space\n\n # Close Button\n cmds.rowColumnLayout(nc=1, cw=[(1, 300)], cs=[(1, 10)], p=\"main_column\")\n cmds.separator(h=10, style='none')\n cmds.button(l='OK', h=30, c=lambda args: close_help_gui())\n cmds.separator(h=8, style='none')\n\n # Show and Lock Window\n cmds.showWindow(window_name)\n cmds.window(window_name, e=True, s=False)\n\n # Set Window Icon\n qw = OpenMayaUI.MQtUtil.findWindow(window_name)\n widget = wrapInstance(int(qw), QWidget)\n icon = QIcon(':/question.png')\n widget.setWindowIcon(icon)\n\n def close_help_gui():\n if cmds.window(window_name, exists=True):\n cmds.deleteUI(window_name, window=True)\n","repo_name":"TrevisanGMW/gt-tools","sub_path":"gt/tools/package_setup/about_window.py","file_name":"about_window.py","file_ext":"py","file_size_in_byte":3878,"program_lang":"python","lang":"en","doc_type":"code","stars":96,"dataset":"github-code","pt":"81"} +{"seq_id":"74245541066","text":"from turtle import Turtle, colormode\nfrom random import randint\n\ncolormode(255)\n\n\nclass Car(Turtle):\n\n def __init__(self):\n super().__init__()\n self.shape(\"square\")\n self.shapesize(stretch_len=2, stretch_wid=1)\n self.penup()\n self.setheading(180)\n self.x = 0\n self.y = 0\n self.random_position()\n self.color(randint(0, 255), randint(0, 255), randint(0, 255))\n\n def move_car(self):\n self.forward(5)\n\n def random_position(self):\n self.y = randint(-250, 250)\n self.setpos(300, self.y)\n","repo_name":"edernonato/turtle_crossing_game","sub_path":"cars.py","file_name":"cars.py","file_ext":"py","file_size_in_byte":574,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"40904335944","text":"import numpy as np\r\n# pylint: disable=E1101\r\nimport matplotlib.pyplot as plt\r\nimport random\r\nfrom math import floor, ceil\r\nfrom logger import log\r\n\r\ndef genRoughFault(filename, mesh, surfacePts, centerPts, rseed, length, depth, lambdaMin, alpha, Hurst):\r\n # Input parameters:\r\n # filename: Filename for saving .ply file\r\n # mesh: Boolian value for defining whether to create a mesh\r\n # surfacePts: Empty array for saving the surface points (for creating an intersection)\r\n # centerPts: Empty array for saving the points at central depth (for creating fault receivers)\r\n # rseed: Seed for random number generator\r\n # length: Length of the fault (in km)\r\n # depth: Depth of the fault (in km)\r\n # lambdaMin: Minimal wavelength (in km)\r\n # alpha: Amplitude to wavelength ratio\r\n # Hurst: Hurst exponent\r\n\r\n random.seed(rseed)\r\n\r\n L = max(length,depth)\r\n lambdaMax = L\r\n\r\n Ncutoff = int(L/lambdaMin)\r\n\r\n # Factor 2 due to neg & pos. frequencies, refinement, + 1 due to frequency (0, 0)\r\n refine = 4\r\n N = refine * Ncutoff * 2 + 1\r\n\r\n freqs = np.zeros(N * N, dtype=complex)\r\n freqs.shape = (N, N)\r\n beta = 2 * (Hurst + 1.)\r\n\r\n for kx in range(0, Ncutoff+1):\r\n for kz in range(0, Ncutoff+1):\r\n\r\n # No frequency of 0 (constant value)\r\n if max(kx,kz)==0:\r\n continue\r\n\r\n # Calculate desired amplitude\r\n k = np.sqrt(kx**2 + kz**2)\r\n fac = pow(k, -beta * 0.5)\r\n\r\n # Calculate random phases and scale with desired amplitude\r\n randPhase = random.random()*np.pi*2.\r\n freqs[kx,kz]=fac*np.exp(randPhase*1.j)\r\n\r\n # Copy conjugates to other quadrants, to get real values in spacial domain\r\n if kx != 0:\r\n freqs[N-kx, kz] = np.conjugate(freqs[kx,kz])\r\n if kz != 0:\r\n freqs[kx, N-kz] = np.conjugate(freqs[kx,kz])\r\n if min(kx, kz) != 0:\r\n freqs[N-kx, N-kz] = freqs[kx,kz]\r\n\r\n Y = np.real(np.fft.ifft2(freqs))\r\n\r\n dx=L/(N - 1) # -1 because of point (0,0)\r\n x=np.arange(-length/2,length/2+dx,dx)\r\n z=np.arange(0.,depth+dx,dx)\r\n\r\n X, Z = np.meshgrid(x, z)\r\n\r\n # Crop square to rectangle\r\n Y=Y[0:len(z),0:len(x)]\r\n\r\n # compute hrms roughness\r\n hrms = np.std(Y)\r\n\r\n #scale to targeted Hrms\r\n target_hrms = alpha * lambdaMax\r\n # log(\"hrms = {}, targeted hrms = {}\".format(hrms, target_hrms))\r\n Y = Y * target_hrms / hrms\r\n # log(\"Corrected hrms: {}\".format(np.std(Y)))\r\n\r\n #for the following study\r\n # freqs=freqs*target_hrms/hrms\r\n\r\n # Show color map\r\n # plt.pcolormesh(X,Z,Y)\r\n # plt.colorbar()\r\n # plt.show()\r\n\r\n # Save surface points for intersection with box\r\n for i in range(0, len(x)):\r\n surfacePts.append([1e3 * x[i], 1e3 * Y[0,i]])\r\n\r\n # Save points at central depth for creating fault receivers\r\n ctrDepth = int(0.5 * len(z))\r\n for i in range(0, len(x)):\r\n centerPts.append([1e3 * x[i], 1e3 * Y[ctrDepth, i], -1e3 * z[ctrDepth]])\r\n\r\n Xf=X.flatten()\r\n Yf=Y.flatten()\r\n Zf=Z.flatten()\r\n\r\n # Write ply-file\r\n fout=open(filename,'w')\r\n # Header\r\n fout.write(\"ply\\n\")\r\n fout.write(\"format ascii 1.0\\n\")\r\n fout.write(\"element vertex %i\\n\" % len(Yf))\r\n fout.write(\"property float32 x\\n\")\r\n fout.write(\"property float32 y\\n\")\r\n fout.write(\"property float32 z\\n\")\r\n # Header for faces\r\n if mesh:\r\n fout.write(\"element face %i\\n\" % (2 * (len(z) - 1) * (len(x) - 1)))\r\n fout.write(\"property list uint8 int32 vertex_index\\n\")\r\n fout.write(\"end_header\\n\")\r\n\r\n # Vertices\r\n for i in range(0, len(Yf)):\r\n if Zf[i] == 0: # prevent -0.000000\r\n fout.write(str(1e3*Xf[i]) + \" \" + str(1e3*Yf[i]) + \" \" + str(0.) + \"\\n\") # do not use the % Operator due to precision consistency\r\n else:\r\n fout.write(str(1e3*Xf[i]) + \" \" + str(1e3*Yf[i]) + \" \" + str(-1e3*Zf[i]) + \"\\n\") # do not use the % Operator due to precision consistency\r\n\r\n # Faces\r\n if mesh:\r\n for i in range(0, len(z) - 1):\r\n for j in range(0, len(x) - 1):\r\n n = j + i * len(x)\r\n fout.write(\"3 %i %i %i\\n\" %(n, n+len(x), n+1))\r\n fout.write(\"3 %i %i %i\\n\" %(n+1, n+len(x), n+1+len(x)))\r\n fout.close()\r\n\r\nif __name__ == '__main__':\r\n surfPts = []\r\n ctrPts = []\r\n genRoughFault(\"roughFault.ply\", True, surfPts, ctrPts, '0254887388', 40., 20., 1., pow(10.,-1.9), 0.8)\r\n","repo_name":"gasteigerjo/roughgen","sub_path":"gen_mesh/generateRoughFault.py","file_name":"generateRoughFault.py","file_ext":"py","file_size_in_byte":4520,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"5653126038","text":"from ext import db\nfrom flask import url_for\nfrom settings import BaseConfig\n\nclass Pagination(object):\n _model = None\n _query = None\n _page_num = 1\n _objs = []\n _obj_page = []\n _per_page = BaseConfig.ADMIN_PER_PAGE\n _page_count = _per_page\n\n def __init__(self,model,page_num=None,query=None):\n if query is None:\n self._query = model.query.order_by(db.desc(model.id))\n else:\n self._query = query\n self._model = model\n self._page_num = page_num or self._page_num\n self._objs = self._query.all()\n self.set_page(self._objs)\n\n def set_page(self,obj_list):\n s = ((self._per_page*self._page_num)-self._per_page)\n self._obj_page = []\n total = 0\n while total != self._per_page:\n for i in range(self._per_page):\n try:\n self._obj_page.append(obj_list[s])\n except:\n break\n finally:\n s+=1 \n total += 1\n break\n \n\n\n @property\n def has_next(self):\n return self._page_num != self._per_page*len(self._objs)\n\n @property\n def has_prev(self):\n return self._page_num != 1\n\n @property\n def next_link(self):\n if self.has_next:\n return url_for('admin.page_{}'.format(self._model.__name__.lower()),page_num=self.page_num+1)\n return '#'\n \n @property\n def prev_link(self):\n if self.has_prev:\n return url_for('admin.page_{}'.format(self._model.__name__.lower()),page_num=self._page_num-1)\n return '#'\n \n\ndef get_pk(obj):\n if 'id' in obj.__dict__:\n return obj.id\n raise IOError\n\n","repo_name":"jstacoder/flask-xxl","sub_path":"flask_xxl/apps/admin/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1734,"program_lang":"python","lang":"en","doc_type":"code","stars":387,"dataset":"github-code","pt":"81"} +{"seq_id":"38678274775","text":"import streamlit as st\nimport io\nfrom typing import Callable\n\nfrom os import walk\n\nMAGE_EMOJI_URL = \"https://emojipedia-us.s3.dualstack.us-west-1.amazonaws.com/thumbs/240/twitter/259/mage_1f9d9.png\"\n\nst.set_page_config(\n page_title=\"IMAGE CAMP\", page_icon=MAGE_EMOJI_URL, initial_sidebar_state=\"collapsed\"\n)\n\nimport apps\n\napps_path = \"./apps\"\nfilenames = list(\n map(lambda x: x.split(\".py\")[0], next(walk(apps_path), (None, None, []))[2])\n) # [] if no file\nfilenames.remove(\"home\")\nfilenames.remove(\"__init__\")\nprint(filenames)\n\nPAGE_PARAM = \"p\"\nCONTENT = {\n \"Home\": apps.home.main,\n \"Demo\": {\n \"\": apps.home.main,\n # \"icheft\": apps.icheft.app,\n # \"ID\": apps.id.app,\n },\n}\n\nfor i in filenames:\n CONTENT[\"Demo\"][i] = getattr(apps, i).app\n\n# LONG_TO_SHORT = {\"課程大綱與說明\": \"doc\", \"評分標準\": \"metrics\", \"成果展示\": \"demo\"}\n\n\ndef main():\n query_params = st.experimental_get_query_params()\n page_param = query_params[PAGE_PARAM][0] if PAGE_PARAM in query_params else \"home\"\n\n page_selected = None\n\n index = -1\n cur_index = 0\n\n for page_name, page_function in CONTENT[\"Demo\"].items():\n if cur_index != 0:\n st.session_state[page_name] = page_name == page_param\n if st.session_state[page_name]:\n index = cur_index\n # print(st.session_state[page_name])\n cur_index += 1\n if index == -1:\n st.session_state[\"home\"] = True\n index = 0\n\n selector = list(CONTENT[\"Demo\"].keys())\n\n homepage = st.sidebar.button(\"🏠\")\n\n if homepage:\n index = 0\n\n st.sidebar.title(\"成果展示\")\n\n page_selected = st.sidebar.selectbox(\"選擇你的帳號\", selector, index=index)\n\n # if page_selected in st.session_state and st.session_state[page_selected]:\n # query_params = st.experimental_get_query_params()\n # query_params[PAGE_PARAM] = page_selected\n # print(query_params)\n\n # st.experimental_set_query_params(**query_params)\n\n if page_selected == \"\" or homepage:\n query_params[PAGE_PARAM] = \"home\"\n else:\n query_params[PAGE_PARAM] = page_selected\n st.experimental_set_query_params(**query_params)\n\n if page_selected == \"\" or homepage:\n page_function = CONTENT[\"Home\"]\n else:\n page_function = CONTENT[\"Demo\"][page_selected]\n if isinstance(page_function, Callable):\n # st.sidebar.success(page_selected)\n page_function()\n # if app_mode == selector[0]:\n # readme.main()\n # elif app_mode == selector[1]:\n # # readme_text.empty()\n # st.sidebar.success(\"評分標準\")\n # draft.main()\n # elif app_mode == selector[2]:\n # # readme_text.empty()\n # st.sidebar.success(\"Demo 範例參考\")\n # demo.main()\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"icheft/IMAGE-st","sub_path":"streamlit_app.py","file_name":"streamlit_app.py","file_ext":"py","file_size_in_byte":2831,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"25029825404","text":"import sys\nsys.stdin = open('input.txt', 'r')\n\nfrom collections import deque\n\ndef rotate():\n ret = [[0] * N for _ in range(N)]\n for r in range(N):\n for c in range(N):\n ret[N - 1 - c][r] = arr[r][c]\n for i in range(N):\n for j in range(N):\n arr[i][j] = ret[i][j]\n\ndef Move():\n for j in range(N):\n for i in range(N - 1, -1, -1):\n if arr[i][j] < 0: continue\n index = i + 1\n canMove = None\n while index != N:\n if arr[index][j] == -1: break\n if arr[index][j] == -2:\n canMove = [index, j]\n index += 1\n if canMove:\n arr[canMove[0]][canMove[1]], arr[i][j] = arr[i][j], arr[canMove[0]][canMove[1]]\n\ndef LFG(i, j, color):\n global flag, info\n standard_block = None\n rainbow_num = 0\n all_num = 1\n blocks = [(i, j)]\n\n li = [[0] * N for _ in range(N)]\n li[i][j] = 1\n q = deque()\n q.append((i, j))\n while q:\n r, c = q.popleft()\n for k in range(4):\n rr, cc = r + dr[k], c + dc[k]\n if not (0 <= rr < N) or not (0 <= cc < N): continue\n if li[rr][cc] == 1: continue\n if arr[rr][cc] == 0 or arr[rr][cc] == color:\n if arr[rr][cc] == 0:\n rainbow_num += 1\n elif arr[rr][cc] == color:\n flag[rr][cc] = 1\n all_num += 1\n blocks.append((rr, cc))\n q.append((rr, cc))\n li[rr][cc] = 1\n blocks.sort()\n for block in blocks:\n if arr[block[0]][block[1]] != 0:\n standard_block = block\n break\n result = [all_num, rainbow_num, standard_block[0], standard_block[1], blocks]\n for i in range(4):\n if result[i] == info[i]: continue\n elif result[i] > info[i]:\n info = result\n break\n else:\n break\n\n# main\nanswer = 0\nN, M = map(int, input().split())\narr = [list(map(int, input().split())) for _ in range(N)]\ndr, dc = [0, 0, 1, -1], [1, -1, 0, 0]\n\nwhile True:\n flag = [[0] * N for _ in range(N)]\n info = [0, 0, -1, -1, None]\n # step 1\n for i in range(N):\n for j in range(N):\n if flag[i][j] == 0 and arr[i][j] >= 1:\n flag[i][j] = 1\n LFG(i, j, arr[i][j])\n # step 2\n if info[0] < 2: break\n answer += info[0] ** 2\n for i, j in info[4]: arr[i][j] = -2\n # step 3\n Move()\n # step 4\n rotate()\n # step 5\n Move()\nprint(answer)","repo_name":"parkbum11/Algorithm","sub_path":"BOJ/삼성기출/21609_상어중학교.py","file_name":"21609_상어중학교.py","file_ext":"py","file_size_in_byte":2559,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"70974748745","text":"import numpy as np\nimport torch\nimport argparse\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport shutil\nfrom torch.autograd import Variable\nfrom torch.utils import data\n\nfrom pypse import pypse\nfrom dataset import CTW1500Testset\nfrom models import resnet50\nfrom models.loss import dice_loss\nfrom myutils import Logger\nfrom myutils import AverageMeter\nfrom myutils import RunningScore\nfrom myutils import ohem_single, ohem_batch\nfrom myutils import adjust_learning_rate_StepLR\nimport os\nimport sys\nimport time\nimport collections\nimport pyclipper\nimport Polygon as plg\nimport cv2\nfrom tqdm import tqdm\n#from pse import pse\n\ndef generate_txt_result_ctw(bboxes, result_filename, root_path):\n if not os.path.exists(root_path):\n os.makedirs(root_path)\n result_filepath = os.path.join(root_path, 'result_%s.txt'%(result_filename))\n with open(result_filepath, 'w') as f:\n lines = []\n for bbox in bboxes:\n bbox = [int(v) for v in bbox]\n #line = '%d, %d, %d, %d, %d, %d, %d, %d\\n' % tuple(bbox)\n line = '%d'%bbox[0]\n for idx in range(1, len(bbox)):\n line += ', %d'%bbox[idx]\n line += '\\n'\n lines.append(line)\n f.writelines(lines)\n\ndef generate_img_result(image, result_filename, root_path):\n if not os.path.exists(root_path):\n os.makedirs(root_path)\n result_filepath = os.path.join(root_path, 'result_%s.jpg'%(result_filename))\n cv2.imwrite(result_filepath, image)\n\n\ndef test(args):\n testset = CTW1500Testset()\n testloader = torch.utils.data.DataLoader(dataset=testset,\n batch_size=1,\n shuffle=False,\n num_workers=1,\n drop_last=True)\n if args.backbone == 'res50':\n model = resnet50(pretrained=True, num_classes=7)\n\n for param in model.parameters():\n param.requires_grad = False\n model = model.cuda()\n\n if args.resume is not None:\n if os.path.exists(args.resume):\n print('Load from', args.resume)\n checkpoint = torch.load(args.resume)\n # 这里为什么不直接用model.load_state_dict(checkpoint['state_dict'])\n # 是因为训练时使用多卡训练,模型中各个参数的名字前面有个前缀,需要去除该前缀\n d = collections.OrderedDict()\n for key, value in checkpoint['state_dict'].items():\n tmp = key[7:]\n d[tmp] = value\n model.load_state_dict(d)\n else:\n print('No such checkpoint file at', args.resume)\n\n model.eval()\n\n for idx, (img, original_img) in tqdm(enumerate(testloader)):\n img = Variable(img.cuda())\n\n original_img = original_img.numpy().astype('uint8')[0]\n original_img = original_img.copy()\n\n outputs = model(img)\n\n score = torch.sigmoid(outputs[:, 0, :, :])\n outputs = (torch.sign(outputs - 1.0) + 1) / 2\n\n output_text = outputs[:, 0, :, :]\n output_kernels= outputs[:, 0:3, :, :] * output_text\n\n score = score.data.cpu().numpy()[0].astype(np.float32)\n output_text = output_text.data.cpu().numpy()[0].astype(np.uint8)\n output_kernels = output_kernels.data.cpu().numpy()[0].astype(np.uint8)\n\n pred = pypse(output_kernels, 10)\n # pred = pse(output_kernels, 10)\n\n scale = (original_img.shape[1] / pred.shape[1], original_img.shape[0] / pred.shape[0])\n bboxes = []\n num_label = np.max(pred) + 1\n for i in range(1, num_label):\n points_loc = np.array(np.where(pred == i)).transpose((1, 0))\n # points = points[:,::-1]\n if points_loc.shape[0] < 300:\n continue\n score_i = np.mean(score[pred == i])\n if score_i < 0.93:\n continue\n\n binary = np.zeros(pred.shape, dtype='uint8')\n binary[pred == i] = 1\n\n contours, _ = cv2.findContours(binary, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)\n contour = contours[0]\n contour = contour * scale\n if contour.shape[0] <= 2:\n continue\n contour = contour.astype('int32')\n bboxes.append(contour.reshape(-1))\n torch.cuda.synchronize()\n for bbox in bboxes:\n cv2.drawContours(original_img, [bbox.reshape(int(bbox.shape[0] / 2), 2)], -1, (0, 0, 255), 1)\n image_name = testset.img_paths[idx].split('/')[-1].split('.')[0]\n generate_txt_result_ctw(bboxes, image_name, 'outputs/result_ctw_txt_wh_new')\n generate_img_result(original_img, image_name, 'outputs/result_ctw_img_wh_new')\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('--backbone', nargs='?', type=str, default='res50')\n parser.add_argument('--resume', nargs='?', type=str, default='/home/data1/zhm/pretrained_models/ctw1500_res50.pth.tar')\n args = parser.parse_args()\n test(args)","repo_name":"HumanZhong/PAN-reimplement","sub_path":"test_ctw1500.py","file_name":"test_ctw1500.py","file_ext":"py","file_size_in_byte":5075,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"81"} +{"seq_id":"2780886431","text":"\ndef fibo(n):\n if n==0:\n return 0\n elif n==1:\n return 1\n else:\n return fibo(n-1) + fibo(n-2)\n\n\nt = int(input())\nfor _ in range(t):\n n = int(input())\n zero = [1,0]\n first = [0,1]\n","repo_name":"hanuirangroovy/study","sub_path":"211101/1003.py","file_name":"1003.py","file_ext":"py","file_size_in_byte":217,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"15449105355","text":"import iso8601\nfrom flask import Flask, request, render_template, url_for, redirect, abort\nfrom redis import StrictRedis\n\nfrom .util import utcnow\n\n\napp = Flask(__name__)\nconn = StrictRedis()\n\n\ndef format_timedelta(value):\n hours = value.seconds\n hours, seconds = divmod(hours, 60)\n hours, minutes = divmod(hours, 60)\n result = '{0:02}:{1:02}:{2:02}'.format(hours, minutes, seconds)\n if value.days > 0:\n result = '{0} days '.format(value.days) + result\n return result\napp.jinja_env.filters['timedeltaformat'] = format_timedelta\n\n\ndef linecount(value):\n return len(value.splitlines())\napp.jinja_env.filters['linecount'] = linecount\n\n\n@app.route('/')\ndef index():\n now = utcnow()\n stack_top = None\n key = conn.lindex('stack', 0)\n if not key and conn.exists('tasks/idle'):\n key = conn.get('tasks/idle')\n if key:\n task = load_task(key)\n task['elapsed'] = now - task['created_at']\n stack_top = task\n stack_size = max(0, conn.llen('stack') - 1)\n return render_template('index.html', now=now,\n top=stack_top, size=stack_size)\n\n\n@app.route('/tasks/push')\ndef form_push_task():\n return render_template('push_task.html')\n\n\n@app.route('/tasks', methods=['POST'])\ndef push_task():\n title = request.form['title']\n context = request.form.get('context', u'')\n now = utcnow()\n key = add_task(title, created_at=now, context=context)\n if conn.llen('stack') <= 0 and conn.exists('tasks/idle'):\n conn.set(conn.get('tasks/idle') + '/completed_at', now.isoformat())\n conn.lpush('stack', key)\n conn.rpush('archive', key)\n return redirect(url_for('index'))\n\n\n@app.route('/tasks//edit', methods=['POST'])\ndef edit_task(task_id):\n key = 'tasks/{0}'.format(task_id)\n if not conn.exists(key + '/context'):\n abort(404)\n context = request.form['context']\n conn.set(key + '/context', context)\n return redirect(url_for('index'))\n\n\n@app.route('/tasks/pop', methods=['POST'])\ndef pop_task():\n stack_size = conn.llen('stack')\n if stack_size <= 0:\n abort(400)\n key = conn.lpop('stack')\n now = utcnow()\n conn.set(key + '/completed_at', now.isoformat())\n if conn.llen('stack') == 0:\n key = add_task(u'Idle', created_at=now)\n conn.set('tasks/idle', key)\n return redirect(url_for('index'))\n\n\ndef add_task(title, created_at=None, context=u''):\n created_at = created_at or utcnow()\n key = 'tasks/{0}'.format(created_at.isoformat())\n conn.set(key + '/title', title)\n conn.set(key + '/context', context)\n return key\n\n\ndef load_task(key):\n created_at = iso8601.parse_date(key[6:])\n return {'id': key.rsplit('/', 1)[-1],\n 'title': unicode(conn.get(key + '/title'), 'utf-8'),\n 'context': unicode(conn.get(key + '/context'), 'utf-8'),\n 'created_at': created_at}\n","repo_name":"Kroisse/stackwatch","sub_path":"stackwatch/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2878,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"81"} +{"seq_id":"15053989913","text":"import torch\nimport torch.nn as nn\nfrom torch.autograd import Variable\nimport torch.nn.functional as functional\nimport math\nimport logging\n\nclass PositionalEncoder(nn.Module):\n def __init__(self, d_model, max_seq_length=200, dropout=0.1):\n super().__init__()\n \n self.d_model = d_model\n self.dropout = nn.Dropout(dropout)\n self._max_seq_length = max_seq_length\n \n pe = torch.zeros(max_seq_length, d_model)\n \n for pos in range(max_seq_length):\n for i in range(0, d_model, 2):\n pe[pos, i] = math.sin(pos/(10000**(2*i/d_model)))\n pe[pos, i+1] = math.cos(pos/(10000**((2*i+1)/d_model)))\n pe = pe.unsqueeze(0) \n self.register_buffer('pe', pe)\n\n @torch.jit.script\n def splice_by_size(source, target):\n \"\"\"Custom function to splice the source by target's second dimension. Required due to torch.Size not a torchTensor. Why? hell if I know.\"\"\"\n length = target.size(1);\n return source[:, :length]\n\n self.splice_by_size = splice_by_size\n \n def forward(self, x):\n if(x.shape[1] > self._max_seq_length):\n logging.warn(\"Input longer than maximum supported length for PE detected. Build a model with a larger input_max_length limit if you want to keep the input; or ignore if you want the input trimmed\")\n x = x[:, x:self._max_seq_length]\n \n x = x * math.sqrt(self.d_model)\n \n spliced_pe = self.splice_by_size(self.pe, x) # self.pe[:, :x.shape[1]]\n# pe = Variable(spliced_pe, requires_grad=False)\n pe = spliced_pe.requires_grad_(False)\n \n# if x.is_cuda: # remove since it is a sub nn.Module\n# pe.cuda()\n# assert all([xs == ys for xs, ys in zip(x.shape[1:], pe.shape[1:])]), \"{} - {}\".format(x.shape, pe.shape)\n\n x = x + pe\n x = self.dropout(x)\n \n return x\n\nclass MultiHeadAttention(nn.Module):\n def __init__(self, heads, d_model, dropout=0.1):\n super().__init__()\n assert d_model % heads == 0\n \n self.d_model = d_model\n self.d_k = d_model // heads\n self.h = heads\n\n # three casting linear layer for query/key.value\n self.q_linear = nn.Linear(d_model, d_model)\n self.k_linear = nn.Linear(d_model, d_model)\n self.v_linear = nn.Linear(d_model, d_model)\n \n self.dropout = nn.Dropout(dropout)\n self.out = nn.Linear(d_model, d_model)\n \n def forward(self, q, k, v, mask=None):\n \"\"\"\n Args:\n q / k / v: query/key/value, should all be [batch_size, sequence_length, d_model]. Only differ in decode attention, where q is tgt_len and k/v is src_len\n mask: either [batch_size, 1, src_len] or [batch_size, tgt_len, tgt_len]. The last two dimensions must match or are broadcastable.\n Returns:\n the value of the attention process, [batch_size, sequence_length, d_model].\n The used attention, [batch_size, q_length, k_v_length]\n \"\"\"\n bs = q.shape[0]\n q = self.q_linear(q).view(bs, -1, self.h, self.d_k)\n k = self.k_linear(k).view(bs, -1, self.h, self.d_k)\n v = self.v_linear(v).view(bs, -1, self.h, self.d_k)\n \n q = q.transpose(1, 2)\n k = k.transpose(1, 2)\n v = v.transpose(1, 2)\n \n value, attn = self.attention(q, k, v, mask, self.dropout)\n concat = value.transpose(1, 2).contiguous().view(bs, -1, self.d_model)\n output = self.out(concat)\n return output, attn\n\n def attention(self, q, k, v, mask=None, dropout=None):\n \"\"\"Calculate the attention and output the attention & value\n Args:\n q / k / v: query/key/value already transformed, should all be [batch_size, heads, sequence_length, d_k]. Only differ in decode attention, where q is tgt_len and k/v is src_len\n mask: either [batch_size, 1, src_len] or [batch_size, tgt_len, tgt_len]. The last two dimensions must match or are broadcastable.\n Returns: \n the attentionized but raw values [batch_size, head, seq_length, d_k]\n the attention calculated [batch_size, heads, sequence_length, sequence_length]\n \"\"\"\n \n# d_k = q.shape[-1]\n scores = torch.matmul(q, k.transpose(-2, -1)) / math.sqrt(self.d_k)\n \n if mask is not None:\n mask = mask.unsqueeze(1) # add a dimension to account for head\n scores = scores.masked_fill(mask==0, -1e9)\n # softmax the padding/peeking masked attention\n scores = functional.softmax(scores, dim=-1)\n \n if dropout is not None:\n scores = dropout(scores)\n \n output = torch.matmul(scores, v)\n return output, scores\n\nclass Norm(nn.Module):\n def __init__(self, d_model, eps = 1e-6):\n super().__init__()\n \n self.size = d_model\n \n # create two learnable parameters to calibrate normalisation\n self.alpha = nn.Parameter(torch.ones(self.size))\n self.bias = nn.Parameter(torch.zeros(self.size))\n \n self.eps = eps\n \n def forward(self, x):\n norm = self.alpha * (x - x.mean(dim=-1, keepdim=True)) \\\n / (x.std(dim=-1, keepdim=True) + self.eps) + self.bias\n return norm\n\nclass FeedForward(nn.Module):\n \"\"\"A two-hidden-linear feedforward layer that can activate and dropout its transition state\"\"\"\n def __init__(self, d_model, d_ff=2048, internal_activation=functional.relu, dropout=0.1):\n super().__init__() \n self.linear_1 = nn.Linear(d_model, d_ff)\n self.dropout = nn.Dropout(dropout)\n self.linear_2 = nn.Linear(d_ff, d_model)\n\n self.internal_activation = internal_activation\n \n def forward(self, x):\n x = self.dropout(self.internal_activation(self.linear_1(x)))\n x = self.linear_2(x)\n return x\n","repo_name":"KCDichDaNgu/KC4.0_MultilingualNMT","sub_path":"layers/prototypes.py","file_name":"prototypes.py","file_ext":"py","file_size_in_byte":5953,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"81"} +{"seq_id":"21999992246","text":"import aeidon\nimport gaupol\n_ = aeidon.i18n._\n\nfrom gi.repository import Gtk\n\n\nclass ClearTextsAction(gaupol.Action):\n\n \"\"\"Clear the selected texts.\"\"\"\n\n def __init__(self):\n \"\"\"Initialize a :class:`ClearTextsAction` object.\"\"\"\n gaupol.Action.__init__(self, \"clear_texts\")\n self.props.label = _(\"Cl_ear\")\n self.props.stock_id = Gtk.STOCK_CLEAR\n self.props.tooltip = _(\"Clear the selected texts\")\n self.accelerator = \"C\"\n self.action_group = \"main-unsafe\"\n\n def _affirm_doable(self, application, page, selected_rows):\n \"\"\"Raise :exc:`aeidon.AffirmationError` if action cannot be done.\"\"\"\n aeidon.util.affirm(page is not None)\n aeidon.util.affirm(selected_rows)\n col = page.view.get_focus()[1]\n aeidon.util.affirm(col is not None)\n aeidon.util.affirm(page.view.is_text_column(col))\n\n\nclass CopyTextsAction(gaupol.Action):\n\n \"\"\"Copy the selected texts to the clipboard.\"\"\"\n\n def __init__(self):\n \"\"\"Initialize a :class:`CopyTextsAction` object.\"\"\"\n gaupol.Action.__init__(self, \"copy_texts\")\n self.props.label = _(\"_Copy\")\n self.props.stock_id = Gtk.STOCK_COPY\n self.props.tooltip = _(\"Copy the selected texts to the clipboard\")\n self.accelerator = \"C\"\n self.action_group = \"main-unsafe\"\n\n def _affirm_doable(self, application, page, selected_rows):\n \"\"\"Raise :exc:`aeidon.AffirmationError` if action cannot be done.\"\"\"\n aeidon.util.affirm(page is not None)\n aeidon.util.affirm(selected_rows)\n col = page.view.get_focus()[1]\n aeidon.util.affirm(col is not None)\n aeidon.util.affirm(page.view.is_text_column(col))\n\n\nclass CutTextsAction(gaupol.Action):\n\n \"\"\"Cut the selected texts to the clipboard.\"\"\"\n\n def __init__(self):\n \"\"\"Initialize a :class:`CutTextsAction` object.\"\"\"\n gaupol.Action.__init__(self, \"cut_texts\")\n self.props.label = _(\"Cu_t\")\n self.props.stock_id = Gtk.STOCK_CUT\n self.props.tooltip = _(\"Cut the selected texts to the clipboard\")\n self.accelerator = \"X\"\n self.action_group = \"main-unsafe\"\n\n def _affirm_doable(self, application, page, selected_rows):\n \"\"\"Raise :exc:`aeidon.AffirmationError` if action cannot be done.\"\"\"\n aeidon.util.affirm(page is not None)\n aeidon.util.affirm(selected_rows)\n col = page.view.get_focus()[1]\n aeidon.util.affirm(col is not None)\n aeidon.util.affirm(page.view.is_text_column(col))\n\n\nclass EditPreferencesAction(gaupol.Action):\n\n \"\"\"Configure Gaupol.\"\"\"\n\n def __init__(self):\n \"\"\"Initialize an :class:`EditPreferencesAction` object.\"\"\"\n gaupol.Action.__init__(self, \"edit_preferences\")\n self.props.label = _(\"_Preferences\")\n self.props.stock_id = Gtk.STOCK_PREFERENCES\n self.props.tooltip = _(\"Configure Gaupol\")\n self.action_group = \"main-safe\"\n\n\nclass EditNextValueAction(gaupol.Action):\n\n \"\"\"Edit the focused column of the next subtitle.\"\"\"\n\n def __init__(self):\n \"\"\"Initialize an :class:`EditNextValueAction` object.\"\"\"\n gaupol.Action.__init__(self, \"edit_next_value\")\n self.props.label = _(\"Edit _Next Cell\")\n self.props.stock_id = Gtk.STOCK_EDIT\n self.props.tooltip = _(\"Edit the focused column of the next subtitle\")\n self.accelerator = \"space\"\n self.action_group = \"main-unsafe\"\n\n def _affirm_doable(self, application, page, selected_rows):\n \"\"\"Raise :exc:`aeidon.AffirmationError` if action cannot be done.\"\"\"\n aeidon.util.affirm(page is not None)\n row, col = page.view.get_focus()\n aeidon.util.affirm(not None in (row, col))\n aeidon.util.affirm(row < len(page.project.subtitles) - 1)\n column = page.view.get_column(col)\n renderer = column.get_cells()[0]\n mode = renderer.props.mode\n aeidon.util.affirm(mode == Gtk.CellRendererMode.EDITABLE)\n\n\nclass EditValueAction(gaupol.Action):\n\n \"\"\"Edit the focused cell.\"\"\"\n\n def __init__(self):\n \"\"\"Initialize an :class:`EditValueAction` object.\"\"\"\n gaupol.Action.__init__(self, \"edit_value\")\n self.props.is_important = True\n self.props.label = _(\"_Edit Cell\")\n self.props.stock_id = Gtk.STOCK_EDIT\n self.props.tooltip = _(\"Edit the focused cell\")\n self.accelerator = \"Return\"\n self.action_group = \"main-unsafe\"\n\n def _affirm_doable(self, application, page, selected_rows):\n \"\"\"Raise :exc:`aeidon.AffirmationError` if action cannot be done.\"\"\"\n aeidon.util.affirm(page is not None)\n row, col = page.view.get_focus()\n aeidon.util.affirm(not None in (row, col))\n column = page.view.get_column(col)\n renderer = column.get_cells()[0]\n mode = renderer.props.mode\n aeidon.util.affirm(mode == Gtk.CellRendererMode.EDITABLE)\n\n\nclass EndEarlierAction(gaupol.Action):\n\n \"\"\"End the selected subtitle earlier.\"\"\"\n\n def __init__(self):\n \"\"\"Initialize a :class:`EndEarlierAction` object.\"\"\"\n gaupol.Action.__init__(self, \"end_earlier\")\n self.props.label = _(\"E_nd Earlier\")\n self.props.tooltip = _(\"End the selected subtitle earlier\")\n self.accelerator = \"E\"\n self.action_group = \"main-unsafe\"\n\n def _affirm_doable(self, application, page, selected_rows):\n \"\"\"Raise :exc:`aeidon.AffirmationError` if action cannot be done.\"\"\"\n aeidon.util.affirm(page is not None)\n aeidon.util.affirm(page.project.subtitles)\n aeidon.util.affirm(len(selected_rows) == 1)\n\n\nclass EndLaterAction(gaupol.Action):\n\n \"\"\"End the selected subtitle later.\"\"\"\n\n def __init__(self):\n \"\"\"Initialize a :class:`EndLaterAction` object.\"\"\"\n gaupol.Action.__init__(self, \"end_later\")\n self.props.label = _(\"En_d Later\")\n self.props.tooltip = _(\"End the selected subtitle later\")\n self.accelerator = \"R\"\n self.action_group = \"main-unsafe\"\n\n def _affirm_doable(self, application, page, selected_rows):\n \"\"\"Raise :exc:`aeidon.AffirmationError` if action cannot be done.\"\"\"\n aeidon.util.affirm(page is not None)\n aeidon.util.affirm(page.project.subtitles)\n aeidon.util.affirm(len(selected_rows) == 1)\n\n\nclass ExtendSelectionToBeginningAction(gaupol.Action):\n\n \"\"\"Extend the selection up to the first subtitle.\"\"\"\n\n def __init__(self):\n \"\"\"Initialize an :class:`ExtendSelectionToBeginningAction` object.\"\"\"\n gaupol.Action.__init__(self, \"extend_selection_to_beginning\")\n self.props.label = _(\"Extend To _Beginning\")\n self.props.tooltip = _(\"Extend the current selection \"\n \"up to the first subtitle\")\n\n self.accelerator = \"Home\"\n self.action_group = \"main-unsafe\"\n\n def _affirm_doable(self, application, page, selected_rows):\n \"\"\"Raise :exc:`aeidon.AffirmationError` if action cannot be done.\"\"\"\n aeidon.util.affirm(page is not None)\n aeidon.util.affirm(page.project.subtitles)\n aeidon.util.affirm(selected_rows)\n\n\nclass ExtendSelectionToEndAction(gaupol.Action):\n\n \"\"\"Extend the selection up to the last subtitle.\"\"\"\n\n def __init__(self):\n \"\"\"Initialize an :class:`ExtendSelectionToEndAction` object.\"\"\"\n gaupol.Action.__init__(self, \"extend_selection_to_end\")\n self.props.label = _(\"Extend To _End\")\n self.props.tooltip = _(\"Extend the current selection \"\n \"up to the last subtitle\")\n\n self.accelerator = \"End\"\n self.action_group = \"main-unsafe\"\n\n def _affirm_doable(self, application, page, selected_rows):\n \"\"\"Raise :exc:`aeidon.AffirmationError` if action cannot be done.\"\"\"\n aeidon.util.affirm(page is not None)\n aeidon.util.affirm(page.project.subtitles)\n aeidon.util.affirm(selected_rows)\n\n\nclass InsertSubtitleAtVideoPositionAction(gaupol.Action):\n\n \"\"\"Insert a new subtitle at video position.\"\"\"\n\n def __init__(self):\n \"\"\"Initialize an :class:`InsertSubtitleAtVideoPositionAction` object.\"\"\"\n gaupol.Action.__init__(self, \"insert_subtitle_at_video_position\")\n self.props.label = _(\"Inser_t Subtitle At Video Position\")\n self.props.stock_id = Gtk.STOCK_ADD\n self.props.tooltip = _(\"Insert a new subtitle at video position\")\n self.accelerator = \"J\"\n self.action_group = \"main-unsafe\"\n\n def _affirm_doable(self, application, page, selected_rows):\n \"\"\"Raise :exc:`aeidon.AffirmationError` if action cannot be done.\"\"\"\n aeidon.util.affirm(page is not None)\n aeidon.util.affirm(application.player is not None)\n\n\nclass InsertSubtitlesAction(gaupol.Action):\n\n \"\"\"Insert subtitles.\"\"\"\n\n def __init__(self):\n \"\"\"Initialize an :class:`InsertSubtitlesAction` object.\"\"\"\n gaupol.Action.__init__(self, \"insert_subtitles\")\n self.props.label = _(\"_Insert Subtitles…\")\n self.props.short_label = _(\"Insert\")\n self.props.stock_id = Gtk.STOCK_ADD\n self.props.tooltip = _(\"Insert new subtitles\")\n self.accelerator = \"I\"\n self.action_group = \"main-unsafe\"\n\n def _affirm_doable(self, application, page, selected_rows):\n \"\"\"Raise :exc:`aeidon.AffirmationError` if action cannot be done.\"\"\"\n aeidon.util.affirm(page is not None)\n if page.project.subtitles:\n aeidon.util.affirm(selected_rows)\n\n\nclass InvertSelectionAction(gaupol.Action):\n\n \"\"\"Invert the current selection.\"\"\"\n\n def __init__(self):\n \"\"\"Initialize an :class:`InvertSelectionAction` object.\"\"\"\n gaupol.Action.__init__(self, \"invert_selection\")\n self.props.label = _(\"_Invert Selection\")\n self.props.tooltip = _(\"Invert the current selection\")\n self.accelerator = \"I\"\n self.action_group = \"main-unsafe\"\n\n def _affirm_doable(self, application, page, selected_rows):\n \"\"\"Raise :exc:`aeidon.AffirmationError` if action cannot be done.\"\"\"\n aeidon.util.affirm(page is not None)\n aeidon.util.affirm(page.project.subtitles)\n\n\nclass MergeSubtitlesAction(gaupol.Action):\n\n \"\"\"Merge the selected subtitles.\"\"\"\n\n def __init__(self):\n \"\"\"Initialize a :class:`MergeSubtitlesAction` object.\"\"\"\n gaupol.Action.__init__(self, \"merge_subtitles\")\n self.props.label = _(\"_Merge Subtitles\")\n self.props.tooltip = _(\"Merge the selected subtitles\")\n self.accelerator = \"M\"\n self.action_group = \"main-unsafe\"\n\n def _affirm_doable(self, application, page, selected_rows):\n \"\"\"Raise :exc:`aeidon.AffirmationError` if action cannot be done.\"\"\"\n aeidon.util.affirm(page is not None)\n aeidon.util.affirm(len(selected_rows) > 1)\n block = list(range(selected_rows[0], selected_rows[-1]+1))\n aeidon.util.affirm(list(selected_rows) == block)\n\n\nclass PasteTextsAction(gaupol.Action):\n\n \"\"\"Paste texts from the clipboard.\"\"\"\n\n def __init__(self):\n \"\"\"Initialize a :class:`PasteTextsAction` object.\"\"\"\n gaupol.Action.__init__(self, \"paste_texts\")\n self.props.label = _(\"_Paste\")\n self.props.stock_id = Gtk.STOCK_PASTE\n self.props.tooltip = _(\"Paste texts from the clipboard\")\n self.accelerator = \"V\"\n self.action_group = \"main-unsafe\"\n\n def _affirm_doable(self, application, page, selected_rows):\n \"\"\"Raise :exc:`aeidon.AffirmationError` if action cannot be done.\"\"\"\n aeidon.util.affirm(page is not None)\n aeidon.util.affirm(not application.clipboard.is_empty())\n aeidon.util.affirm(selected_rows)\n col = page.view.get_focus()[1]\n aeidon.util.affirm(col is not None)\n aeidon.util.affirm(page.view.is_text_column(col))\n\n\nclass RedoActionAction(gaupol.Action):\n\n \"\"\"Redo the last undone action.\"\"\"\n\n __gtype_name__ = \"RedoActionAction\"\n\n def __init__(self):\n \"\"\"Initialize a :class:`RedoActionAction` object.\"\"\"\n gaupol.Action.__init__(self, \"redo_action\")\n self.props.label = _(\"_Redo\")\n self.props.stock_id = Gtk.STOCK_REDO\n self.props.tooltip = _(\"Redo the last undone action\")\n self.accelerator = \"Z\"\n self.action_group = \"main-unsafe\"\n self.tool_item_type = Gtk.MenuToolButton\n\n def _affirm_doable(self, application, page, selected_rows):\n \"\"\"Raise :exc:`aeidon.AffirmationError` if action cannot be done.\"\"\"\n aeidon.util.affirm(page is not None)\n aeidon.util.affirm(page.project.can_redo())\n\n\nclass RemoveSubtitlesAction(gaupol.Action):\n\n \"\"\"Remove the selected subtitles.\"\"\"\n\n def __init__(self):\n \"\"\"Initialize a :class:`RemoveSubtitlesAction` object.\"\"\"\n gaupol.Action.__init__(self, \"remove_subtitles\")\n self.props.label = _(\"Rem_ove Subtitles\")\n self.props.short_label = _(\"Remove\")\n self.props.stock_id = Gtk.STOCK_REMOVE\n self.props.tooltip = _(\"Remove the selected subtitles\")\n self.accelerator = \"Delete\"\n self.action_group = \"main-unsafe\"\n\n def _affirm_doable(self, application, page, selected_rows):\n \"\"\"Raise :exc:`aeidon.AffirmationError` if action cannot be done.\"\"\"\n aeidon.util.affirm(page is not None)\n aeidon.util.affirm(selected_rows)\n\n\nclass SelectAllAction(gaupol.Action):\n\n \"\"\"Select all subtitles.\"\"\"\n\n def __init__(self):\n \"\"\"Initialize a :class:`SelectAllAction` object.\"\"\"\n gaupol.Action.__init__(self, \"select_all\")\n self.props.label = _(\"Select _All\")\n self.props.stock_id = Gtk.STOCK_SELECT_ALL\n self.props.tooltip = _(\"Select all subtitles\")\n self.accelerator = \"A\"\n self.action_group = \"main-unsafe\"\n\n def _affirm_doable(self, application, page, selected_rows):\n \"\"\"Raise :exc:`aeidon.AffirmationError` if action cannot be done.\"\"\"\n aeidon.util.affirm(page is not None)\n aeidon.util.affirm(page.project.subtitles)\n\n\nclass SetEndFromVideoPositionAction(gaupol.Action):\n\n \"\"\"Set subtitle end from video position.\"\"\"\n\n def __init__(self):\n \"\"\"Initialize an :class:`SetEndFromVideoPositionAction` object.\"\"\"\n gaupol.Action.__init__(self, \"set_end_from_video_position\")\n self.props.label = _(\"Set En_d From Video Position\")\n self.props.tooltip = _(\"Set subtitle end from video position\")\n self.accelerator = \"K\"\n self.action_group = \"main-unsafe\"\n\n def _affirm_doable(self, application, page, selected_rows):\n \"\"\"Raise :exc:`aeidon.AffirmationError` if action cannot be done.\"\"\"\n aeidon.util.affirm(page is not None)\n aeidon.util.affirm(application.player is not None)\n aeidon.util.affirm(len(selected_rows) == 1)\n\n\nclass ShowSelectionMenuAction(gaupol.MenuAction):\n\n \"\"\"Show the selection menu.\"\"\"\n\n def __init__(self):\n \"\"\"Initialize a :class:`ShowSelectionMenuAction` object.\"\"\"\n gaupol.MenuAction.__init__(self, \"show_selection_menu\")\n self.props.label = _(\"Sele_ction\")\n self.action_group = \"main-unsafe\"\n\n def _affirm_doable(self, application, page, selected_rows):\n \"\"\"Raise :exc:`aeidon.AffirmationError` if action cannot be done.\"\"\"\n aeidon.util.affirm(page is not None)\n aeidon.util.affirm(page.project.subtitles)\n\n\nclass ShowStretchMenuAction(gaupol.MenuAction):\n\n \"\"\"Show the stretch menu.\"\"\"\n\n def __init__(self):\n \"\"\"Initialize a :class:`ShowStretchMenuAction` object.\"\"\"\n gaupol.MenuAction.__init__(self, \"show_stretch_menu\")\n self.props.label = _(\"Stretc_h Subtitle\")\n self.action_group = \"main-unsafe\"\n\n def _affirm_doable(self, application, page, selected_rows):\n \"\"\"Raise :exc:`aeidon.AffirmationError` if action cannot be done.\"\"\"\n aeidon.util.affirm(page is not None)\n aeidon.util.affirm(page.project.subtitles)\n aeidon.util.affirm(len(selected_rows) == 1)\n\n\nclass SplitSubtitleAction(gaupol.Action):\n\n \"\"\"Split the selected subtitle.\"\"\"\n\n def __init__(self):\n \"\"\"Initialize a :class:`SplitSubtitleAction` object.\"\"\"\n gaupol.Action.__init__(self, \"split_subtitle\")\n self.props.label = _(\"_Split Subtitle\")\n self.props.tooltip = _(\"Split the selected subtitle\")\n self.accelerator = \"S\"\n self.action_group = \"main-unsafe\"\n\n def _affirm_doable(self, application, page, selected_rows):\n \"\"\"Raise :exc:`aeidon.AffirmationError` if action cannot be done.\"\"\"\n aeidon.util.affirm(page is not None)\n aeidon.util.affirm(len(selected_rows) == 1)\n\n\nclass StartEarlierAction(gaupol.Action):\n\n \"\"\"Start the selected subtitle earlier.\"\"\"\n\n def __init__(self):\n \"\"\"Initialize a :class:`StartEarlierAction` object.\"\"\"\n gaupol.Action.__init__(self, \"start_earlier\")\n self.props.label = _(\"_Start Earlier\")\n self.props.tooltip = _(\"Start the selected subtitle earlier\")\n self.accelerator = \"Q\"\n self.action_group = \"main-unsafe\"\n\n def _affirm_doable(self, application, page, selected_rows):\n \"\"\"Raise :exc:`aeidon.AffirmationError` if action cannot be done.\"\"\"\n aeidon.util.affirm(page is not None)\n aeidon.util.affirm(page.project.subtitles)\n aeidon.util.affirm(len(selected_rows) == 1)\n\n\nclass StartLaterAction(gaupol.Action):\n\n \"\"\"Start the selected subtitle later.\"\"\"\n\n def __init__(self):\n \"\"\"Initialize a :class:`StartLaterAction` object.\"\"\"\n gaupol.Action.__init__(self, \"start_later\")\n self.props.label = _(\"S_tart Later\")\n self.props.tooltip = _(\"Start the selected subtitle later\")\n self.accelerator = \"W\"\n self.action_group = \"main-unsafe\"\n\n def _affirm_doable(self, application, page, selected_rows):\n \"\"\"Raise :exc:`aeidon.AffirmationError` if action cannot be done.\"\"\"\n aeidon.util.affirm(page is not None)\n aeidon.util.affirm(page.project.subtitles)\n aeidon.util.affirm(len(selected_rows) == 1)\n\n\nclass UndoActionAction(gaupol.Action):\n\n \"\"\"Undo the last action.\"\"\"\n\n __gtype_name__ = \"UndoActionAction\"\n\n def __init__(self):\n \"\"\"Initialize an :class:`UndoActionAction` object.\"\"\"\n gaupol.Action.__init__(self, \"undo_action\")\n self.props.is_important = True\n self.props.label = _(\"_Undo\")\n self.props.stock_id = Gtk.STOCK_UNDO\n self.props.tooltip = _(\"Undo the last action\")\n self.accelerator = \"Z\"\n self.action_group = \"main-unsafe\"\n self.tool_item_type = Gtk.MenuToolButton\n\n def _affirm_doable(self, application, page, selected_rows):\n \"\"\"Raise :exc:`aeidon.AffirmationError` if action cannot be done.\"\"\"\n aeidon.util.affirm(page is not None)\n aeidon.util.affirm(page.project.can_undo())\n\n\n__all__ = tuple(x for x in dir() if x.endswith(\"Action\"))\n","repo_name":"unho/gaupol","sub_path":"gaupol/actions/edit.py","file_name":"edit.py","file_ext":"py","file_size_in_byte":18951,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"81"} +{"seq_id":"23693605486","text":"import urllib2\nimport json as simplejson\nimport werkzeug\nimport requests\n\nfrom openerp import models, fields, api\nfrom openerp.exceptions import Warning\n\nimport logging\n_logger = logging.getLogger(__name__)\n\n\nclass SaasPortalClient(models.Model):\n _inherit = 'saas_portal.client'\n \n backup = fields.Boolean('Backup on Modify', help=\"Backs up first before deleting \\\n or upgrading\", default=True)\n \n @api.multi \n def action_backup(self):\n '''\n call to backup database\n '''\n self.ensure_one()\n if not self[0].backup:\n return\n state = {\n 'd': self.name,\n 'client_id': self.client_id,\n }\n\n url = self.server_id._request_server(path='/saas_server/backup_database', state=state, client_id=self.client_id)[0]\n res = requests.get(url, verify=(self.server_id.request_scheme == 'https' and self.server_id.verify_ssl))\n _logger.info('delete database: %s', res.text)\n if res.ok != True:\n msg = \"\"\"Status Code - %s \n Reason - %s\n URL - %s\n \"\"\" % (res.status_code, res.reason, res.url)\n raise Warning(msg)\n data = simplejson.loads(res.text)\n if data[0]['status'] != 'success':\n warning = data[0].get('message', 'Could not backup database; please check your logs')\n raise Warning(warning)\n return True\n \n @api.multi\n def delete_database(self):\n self.action_backup()\n return super(SaasPortalClient, self).delete_database()\n \n \n @api.multi\n def upgrade_database(self):\n self.action_backup()\n return super(SaasPortalClient, self).upgrade_database()\n","repo_name":"jani435/odoo-saas-tools","sub_path":"saas_sysadmin_backup/models/saas_portal.py","file_name":"saas_portal.py","file_ext":"py","file_size_in_byte":1730,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"81"} +{"seq_id":"32526145339","text":"#! /usr/bin/python3\n\nimport argparse\nimport lector\n# importacion de librerias\n\ndef leer_archivo(path):\n # path es la ruta del archivo .txt a leer\n # ejemplo: \"C:/Users/My Folder/sample.txt\"\n # ejemplo: \"/tmp/episodioX.txt\"\n # fh es nuestra variable fileholder, open es la funcion\n # para abrir archivos, insertamos la ruta, y \"r\" indica que leeremos\n # leemos el archivo y lo asignamos a una variable String\n # al igual que se abrio para leer, requiere cerrarse\n # fh = open(path, \"r\")\n try: \n with open(path, \"r\") as fh:\n texto = fh.read()\n lineas = texto.splitlines()\n texto_limpio = \" \".join(lineas)\n except:\n texto_limpio=\"\"\n return texto_limpio\n\n\ndef contar(archivo,stopwords_url):\n texto = lector.leer_archivo(archivo)\n #dicc = dict() # se crea un diccionario para facilitar el contar\n #dicc2 = dict()\n # indicamos que cada palabra se diferencia por un espacio \" \"\n lista_palabras = texto.split(\" \")\n total = lista_palabras\n stopwords = lector.leer_stopwords(stopwords_url)\n #palabras_clave = texto.split(\" \")\n dpc = dict() #dicc.palabras clave\n dps = dict() #dicc.palabras stopwords\n \n for palabra in lista_palabras:\n # ignoraremos los puntos y comas de las palabras\n p = palabra.lower().strip(\",.\")\n if p in stopwords: #es stopwords?\n if p in dps: #ya existe?\n dps[p] += 1 #agregamos 1\n else: # si no, se creara\n dps[p] = 1 #inicial con 1 \n else:\n if p in dpc: #ya existe?\n dpc[p] += 1 #agregamos 1\n else:\n dpc[p] = 1 #creamos con 1 \n \n #if \"\" in dicc:\n # del(dicc[\"\"])\n print(len(dps),\"Palabras stropwords\") #imprime el numero de stopwords\n print(len(dpc),\"Palabras clave\") #imprime las palabras clave\n print(len(total),\"Palabras totales\") #escribe las palabras totales en el archivo \n return total\n \n # for palabra in lista_palabras:\n # ignoraremos los puntos y comas de las palabras\n # p = palabra.strip(\",.\")\n # if p in dicc: # si existe la palabra, se le sumara\n # dicc[p] += 1\n # else: # si no, se creara\n # dicc[p] = 1 \n \n #if \"\" in dicc:\n # del(dicc[\"\"]) \n #return dicc \n\ndef main(archivo,minimo,archivo_stopwords):\n texto = leer_archivo(archivo)\n \n #texto = leer_archivo(path)\n #stopwords = leer_archivo(stopwords)\n #texto = eliminar_stopwords(texto,stopwords)\n #dicc = contar_palabras(texto)\n #texto = eliminar_stopwords(dicc,stopwords) \n #imprime_diccionario(dicc)\n texto = contar(archivo, archivo_stopwords)\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument('-a', '--archivo', dest='archivo', help=\"nombre de archivo\", required=True) \n parser.add_argument('-m', '--minimo', dest='minimo', default = 3, help=\"minimo de palabras repetidas\", type = int, required=False)\n parser.add_argument('-s', '--stopwords', dest='stopwords', help=\"nombre de archivo\",default = \"spanish_stopwords.txt\", required=False)\n args = parser.parse_args()\n archivo = args.archivo\n minimo = args.minimo\n stopwords = args.stopwords\n main(archivo, minimo, stopwords) ","repo_name":"shunix1999/jose","sub_path":"contar_palabras.py","file_name":"contar_palabras.py","file_ext":"py","file_size_in_byte":3689,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"41819909638","text":"from Box2D.examples.framework import (Framework, Keys, main)\nfrom random import random\nfrom math import sqrt, sin, cos\n\nfrom Box2D import (b2BodyDef, b2CircleShape, b2Color, b2EdgeShape,\n b2FixtureDef, b2PolygonShape, b2RayCastCallback, b2Vec2,\n b2_dynamicBody, b2_pi)\n\n\nclass RayCastClosestCallback(b2RayCastCallback):\n \"\"\"This callback finds the closest hit\"\"\"\n\n def __repr__(self):\n return 'Closest hit'\n\n def __init__(self, **kwargs):\n b2RayCastCallback.__init__(self, **kwargs)\n self.fixture = None\n self.hit = False\n\n def ReportFixture(self, fixture, point, normal, fraction):\n '''\n Called for each fixture found in the query. You control how the ray\n proceeds by returning a float that indicates the fractional length of\n the ray. By returning 0, you set the ray length to zero. By returning\n the current fraction, you proceed to find the closest point. By\n returning 1, you continue with the original ray clipping. By returning\n -1, you will filter out the current fixture (the ray will not hit it).\n '''\n self.hit = True\n self.fixture = fixture\n self.point = b2Vec2(point)\n self.normal = b2Vec2(normal)\n # NOTE: You will get this error:\n # \"TypeError: Swig director type mismatch in output value of\n # type 'float32'\"\n # without returning a value\n return fraction\n\n\nclass RayCastAnyCallback(b2RayCastCallback):\n \"\"\"This callback finds any hit\"\"\"\n\n def __repr__(self):\n return 'Any hit'\n\n def __init__(self, **kwargs):\n b2RayCastCallback.__init__(self, **kwargs)\n self.fixture = None\n self.hit = False\n\n def ReportFixture(self, fixture, point, normal, fraction):\n self.hit = True\n self.fixture = fixture\n self.point = b2Vec2(point)\n self.normal = b2Vec2(normal)\n return 0.0\n\n\nclass RayCastMultipleCallback(b2RayCastCallback):\n \"\"\"This raycast collects multiple hits.\"\"\"\n\n def __repr__(self):\n return 'Multiple hits'\n\n def __init__(self, **kwargs):\n b2RayCastCallback.__init__(self, **kwargs)\n self.fixture = None\n self.hit = False\n self.points = []\n self.normals = []\n\n def ReportFixture(self, fixture, point, normal, fraction):\n self.hit = True\n self.fixture = fixture\n self.points.append(b2Vec2(point))\n self.normals.append(b2Vec2(normal))\n return 1.0\n\n\nclass Raycast (Framework):\n name = \"Raycast\"\n description = \"Press 1-5 to drop stuff, d to delete, m to switch callback modes\"\n p1_color = b2Color(0.4, 0.9, 0.4)\n s1_color = b2Color(0.8, 0.8, 0.8)\n s2_color = b2Color(0.9, 0.9, 0.4)\n\n def __init__(self):\n super(Raycast, self).__init__()\n\n self.world.gravity = (0, 0)\n # The ground\n ground = self.world.CreateBody(\n shapes=b2EdgeShape(vertices=[(-40, 0), (40, 0)])\n )\n\n # The various shapes\n w = 1.0\n b = w / (2.0 + sqrt(2.0))\n s = sqrt(2.0) * b\n\n self.shapes = [\n b2PolygonShape(vertices=[(-0.5, 0), (0.5, 0), (0, 1.5)]),\n b2PolygonShape(vertices=[(-0.1, 0), (0.1, 0), (0, 1.5)]),\n b2PolygonShape(\n vertices=[(0.5 * s, 0), (0.5 * w, b), (0.5 * w, b + s),\n (0.5 * s, w), (-0.5 * s, w), (-0.5 * w, b + s),\n (-0.5 * w, b), (-0.5 * s, 0.0)]\n ),\n b2PolygonShape(box=(0.5, 0.5)),\n b2CircleShape(radius=0.5),\n ]\n self.angle = 0\n\n self.callbacks = [RayCastClosestCallback,\n RayCastAnyCallback, RayCastMultipleCallback]\n self.callback_class = self.callbacks[0]\n\n def CreateShape(self, shapeindex):\n try:\n shape = self.shapes[shapeindex]\n except IndexError:\n return\n\n pos = (10.0 * (2.0 * random() - 1.0), 10.0 * (2.0 * random()))\n defn = b2BodyDef(\n type=b2_dynamicBody,\n fixtures=b2FixtureDef(shape=shape, friction=0.3),\n position=pos,\n angle=(b2_pi * (2.0 * random() - 1.0)),\n )\n\n if isinstance(shape, b2CircleShape):\n defn.angularDamping = 0.02\n\n self.world.CreateBody(defn)\n\n def DestroyBody(self):\n for body in self.world.bodies:\n if not self.world.locked:\n self.world.DestroyBody(body)\n break\n\n def Keyboard(self, key):\n if key in (Keys.K_1, Keys.K_2, Keys.K_3, Keys.K_4, Keys.K_5):\n self.CreateShape(key - Keys.K_1)\n elif key == Keys.K_d:\n self.DestroyBody()\n elif key == Keys.K_m:\n idx = ((self.callbacks.index(self.callback_class) + 1) %\n len(self.callbacks))\n self.callback_class = self.callbacks[idx]\n\n def Step(self, settings):\n super(Raycast, self).Step(settings)\n\n def draw_hit(cb_point, cb_normal):\n cb_point = self.renderer.to_screen(cb_point)\n head = b2Vec2(cb_point) + 0.5 * cb_normal\n\n cb_normal = self.renderer.to_screen(cb_normal)\n self.renderer.DrawPoint(cb_point, 5.0, self.p1_color)\n self.renderer.DrawSegment(point1, cb_point, self.s1_color)\n self.renderer.DrawSegment(cb_point, head, self.s2_color)\n\n # Set up the raycast line\n length = 11\n point1 = b2Vec2(0, 10)\n d = (length * cos(self.angle), length * sin(self.angle))\n point2 = point1 + d\n\n callback = self.callback_class()\n\n self.world.RayCast(callback, point1, point2)\n\n # The callback has been called by this point, and if a fixture was hit it will have been\n # set to callback.fixture.\n point1 = self.renderer.to_screen(point1)\n point2 = self.renderer.to_screen(point2)\n\n if callback.hit:\n if hasattr(callback, 'points'):\n for point, normal in zip(callback.points, callback.normals):\n draw_hit(point, normal)\n else:\n draw_hit(callback.point, callback.normal)\n else:\n self.renderer.DrawSegment(point1, point2, self.s1_color)\n\n self.Print(\"Callback: %s\" % callback)\n if callback.hit:\n self.Print(\"Hit\")\n\n if not settings.pause or settings.singleStep:\n self.angle += 0.25 * b2_pi / 180\n\nif __name__ == \"__main__\":\n main(Raycast)\n","repo_name":"pybox2d/pybox2d","sub_path":"library/Box2D/examples/raycast.py","file_name":"raycast.py","file_ext":"py","file_size_in_byte":6526,"program_lang":"python","lang":"en","doc_type":"code","stars":455,"dataset":"github-code","pt":"81"} +{"seq_id":"70782749066","text":"from flask import Flask, render_template, request, redirect, session, url_for\n\napp = Flask(__name__)\napp.secret_key = 'secret_for_realsies'\n\n\n@app.route('/')\ndef index():\n return render_template('index.html')\n\n\n@app.route('/cats')\ndef cats():\n display = False\n return render_template('cats.html', display=display)\n\n\n@app.route('/form')\ndef form_page():\n return render_template('form.html')\n\n@app.route('/form', methods=['POST'])\ndef form_submit():\n display = True\n session['name'] = request.form['name'] \n session['gender'] = request.form['gender']\n session['comment'] = request.form['comment']\n return render_template('cats.html',\n display=display,\n name=session['name'],\n gender=session['gender'],\n comments=session['comment'])\n\n\napp.run(debug=True)\n","repo_name":"ayuspark/apprenti_assignment","sub_path":"flask_assignments_my_env/03_landing_page/routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":883,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"27455266602","text":"import pandas as pd\r\nfrom pymongo import MongoClient\r\nimport json\r\nimport boto3\r\nimport os\r\n\r\nBUCKET_NAME = 'bigdatabucket115585644'\r\nOBJECT_NAME = 'data.csv'\r\npath = \"./\"\r\nDB_NAME = 'resultDB'\r\n\r\n\r\ndef download_file(bucket_name, object_name, path):\r\n\r\n s3_client = boto3.client('s3')\r\n\r\n s3_client.download_file(bucket_name, object_name, path)\r\n print('download success')\r\n\r\n\r\ndef mongoimport(csv_path, db_name, db_url='localhost', db_port=27017):\r\n\r\n client = MongoClient(db_url, db_port)\r\n df = pd.read_csv(csv_path)\r\n data = df.to_dict(orient=\"records\")\r\n db = client[db_name]\r\n print(db)\r\n collection_name = input(\"Collection name : \")\r\n db.create_collection(collection_name).insert_many(data)\r\n\r\n\r\ndef main():\r\n\r\n bucket_name = input(\"S3 Bucket Name : \")\r\n object_name = input(\"Filename : \")\r\n # path = input(\"Set a local path (File will be remove from this path): \")\r\n db_name = input(\"Name of the database : \")\r\n try:\r\n download_file(bucket_name, object_name, path + object_name)\r\n mongoimport(path + object_name, db_name)\r\n os.remove(path + object_name)\r\n except:\r\n print(\"Import failed\")\r\n\r\n\r\nif __name__ == '__main__':\r\n main()","repo_name":"Burbanit0/ProjetBigData","sub_path":"scripts/mongo_import.py","file_name":"mongo_import.py","file_ext":"py","file_size_in_byte":1217,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"35721340613","text":"#Modifications to this program by John Ming Ngo\n#UCalgary ID 30020834, Tutorial Number T11\n#Program version 1.0.0, last change 17/11/2016\n\n\n# Author: James Tam\n# Version: November 16, 2016\n#\n# The start() function was written entirely by the above author.\n# The original code for the button_clicked() function was also \n# written by this author. The code in both functions was used with\n# the permission of this person.\nfrom tkinter import *\n\naWindow = Frame()\naButton = Button(aWindow)\ncookieCounter = 0\n\n# Since the parameter list is pre-defined passing aButton into the function\n# is problematic (created as a global).\n# Original version: nothing happens when the button is pressed.\ndef button_clicked() :\n global aButton\n global cookieCounter\n print(\"BOOM! YOU HAVE CLICKED ME! YOU HAVE TRIGGERED ME! YOU!!!!!\", cookieCounter)\n cookieCounter += 1\n aButton[\"text\"] = \"BOOM! Ok you can stop now.\", cookieCounter\n\ndef start ():\n global aWindow\n global aButton\n\n aWindow.pack()\n aButton[\"text\"] = \"Press me\"\n aButton[\"command\"] = button_clicked\n aButton.grid(row=0, column=0)\n aWindow.mainloop()\n\nstart()\n","repo_name":"John-Ming-Ngo/Uni-Code","sub_path":"231/MiniAssignments/MinIAssignment4B/button_events.py","file_name":"button_events.py","file_ext":"py","file_size_in_byte":1142,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"19803860274","text":"import fitsio\nimport argparse\nimport time\nfrom SaclayMocks import util\nimport scipy as sp\n\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"-i\", type=str)\nparser.add_argument(\"-o\", type=str)\nparser.add_argument(\"--to-do\", type=str, help='QSO or DLA', default='QSO')\nparser.add_argument(\"--downsampling-z-cut\", default=0, type=float)\nparser.add_argument(\"--downsampling-z-cut-max\", default=10, type=float)\nparser.add_argument(\"--downsampling-nb\", default=None, type=float)\nparser.add_argument(\"--rsd\", type=str, default='True')\nparser.add_argument(\"--rand\", type=str, default='False')\nargs = parser.parse_args()\n\nprint(\"Starging conversion of master.fits\")\nprint(\"Input is {}\".format(args.i))\nprint(\"Output is {}\".format(args.o))\nt0 = time.time()\nrsd_cond = util.str2bool(args.rsd)\nrand_cond = util.str2bool(args.rand)\ndownsampling_z_cut = args.downsampling_z_cut\ndownsampling_z_cut_max = args.downsampling_z_cut_max\ndownsampling_nb = args.downsampling_nb\nmaster = fitsio.FITS(args.i)\nra = master[1]['RA'][:].astype('float64')\ndec = master[1]['DEC'][:].astype('float64')\nif not rand_cond:\n if rsd_cond:\n zqso = master[1]['Z_{}_RSD'.format(args.to_do)][:]\n else:\n zqso = master[1]['Z_{}_NO_RSD'.format(args.to_do)][:]\nelse:\n zqso = master[1]['Z'][:]\n\nthid = master[1]['MOCKID'][:]\nmaster.close()\n\nif downsampling_nb:\n print(\"Applying downsampling...\")\n print(\"zmin={}\".format(downsampling_z_cut))\n print(\"zmax={}\".format(downsampling_z_cut_max))\n if zqso[(zqso>downsampling_z_cut)&(zqsodownsampling_z_cut)&(zqsodownsampling_z_cut)&(zqsodownsampling_z_cut)&(zqso low_y:\n y = lowest_y + (step * step_size)\n else:\n y = lowest_y - (step * step_size)\n x = m * y + b\n line_positions.append((x, y))\n return line_positions\n\n\ndef makeHorizontalLine(high_x, low_x, lowest_x, high_y, low_y, step_size, num_steps):\n \"\"\"\n return a list of tuples of the x,y positions for a scan. The positions form\n a horizontal line that can be diagonal.\n \"\"\"\n line_positions = []\n m = (high_y - low_y) / (high_x - low_x)\n b = high_y - m * high_x\n for step in range(num_steps):\n if high_x > low_x:\n x = lowest_x + (step * step_size)\n else:\n x = lowest_x - (step * step_size)\n y = m * x + b\n line_positions.append((x, y))\n return line_positions\n\n\ndef makeGrid(vert_high_y, vert_low_y, vert_lowest_y, vert_high_x, vert_low_x,\n vert_step_size, vert_num_steps, horz_high_x, horz_low_x, horz_lowest_x,\n horz_high_y, horz_low_y, horz_step_size, horz_num_steps):\n \"\"\"\n return a list of tuples of the x,y positions for a scan. The positions form\n a grid that can be skewed.\n \"\"\"\n grid_positions = []\n vert_m = (vert_high_x - vert_low_x) / (vert_high_y - vert_low_y)\n vert_b = vert_high_x - vert_m * vert_high_y\n horz_m = (horz_high_y - horz_low_y) / (horz_high_x - horz_low_x)\n horz_b = horz_high_y - horz_m * horz_high_x\n for vert_step in range(vert_num_steps):\n if vert_high_y > vert_low_y:\n vert_y = vert_lowest_y + (vert_step * vert_step_size)\n else:\n vert_y = vert_lowest_y - (vert_step * vert_step_size)\n vert_x_center = vert_m * vert_y + vert_b\n for horz_step in range(horz_num_steps):\n if horz_high_x > horz_low_x:\n x = horz_lowest_x + (horz_step * horz_step_size) + (vert_x_center - vert_low_x)\n else:\n x = horz_lowest_x - (horz_step * horz_step_size) + (vert_x_center - vert_low_x)\n y = (horz_m * x + horz_b) + (vert_y - horz_low_y)\n grid_positions.append((x, y))\n return grid_positions\n","repo_name":"jonathanjdenney/spatial_experiments_28_id","sub_path":"spatial_experiments_28_id/movement_builder.py","file_name":"movement_builder.py","file_ext":"py","file_size_in_byte":2474,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"32377953060","text":"'''\nWhen provided with a number between 0-9, return it in words.\n\nInput :: 1\n\nOutput :: \"One\".\n\nIf your language supports it, try using a switch statement.\n'''\n\ndef switch_it_up(number):\n # Define a dictionary to map numbers to words\n num_to_word = {\n 0: \"Zero\",\n 1: \"One\",\n 2: \"Two\",\n 3: \"Three\",\n 4: \"Four\",\n 5: \"Five\",\n 6: \"Six\",\n 7: \"Seven\",\n 8: \"Eight\",\n 9: \"Nine\"\n }\n\n # Check if the number is in the dictionary, and return the corresponding word\n if number in num_to_word:\n return num_to_word[number]\n else:\n return \"Number out of range\"\n\n# Test cases\nprint(switch_it_up(1)) # Output: \"One\"\nprint(switch_it_up(9)) # Output: \"Nine\"\nprint(switch_it_up(12)) # Output: \"Number out of range\"","repo_name":"Jared951/codewars","sub_path":"num_2_str.py","file_name":"num_2_str.py","file_ext":"py","file_size_in_byte":797,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"20258419078","text":"# Gianluca Croso, Heather Han, Nitin Kumar, Eric Walker\r\n# EN.600.439 Computational Genomics\r\n# Final Project: jam.py\r\n\r\nimport sys\r\nimport math\r\nimport fasta\r\nimport var_decode\r\nimport peak_decode\r\nimport var_encode\r\nimport peak_encode\r\n\r\n\r\ndef main(argv):\r\n # Check that the number of arguments in the line matches the expected\r\n if len(argv) != 5:\r\n sys.stderr.write(\"Usage: python3 jam.py \" +\r\n \" input_file ref_genome\\n\")\r\n sys.stderr.write(\"commands:\\n\" +\r\n \" e or d for encode or decode (action)\\n\" +\r\n \" p or v for peaks or variants (application)\\n\")\r\n exit(1)\r\n\r\n # Grab parameters\r\n action = argv[1]\r\n application = argv[2]\r\n fin = argv[3]\r\n ref = argv[4]\r\n # pre-process the fasta file to get list of the chromosomes & their lengths\r\n # list printed in .fai file\r\n fasta.gen_fai(ref)\r\n chrdict = {}\r\n chrbits = 1\r\n posbits = 1\r\n # use pre-processed fasta .fai file gather info\r\n with open(ref + '.fai') as fai:\r\n i = 0\r\n # For each chromosome in .fai file\r\n for line in fai:\r\n # grab name and length\r\n line = line.strip().split()\r\n seq = line[0]\r\n ln = line[1]\r\n # if encoding associate read name with a number\r\n if action == 'e':\r\n chrdict[seq] = i\r\n # if decoding associate a number with read name\r\n elif action == 'd':\r\n chrdict[i] = seq\r\n # make sure using the least # of bits to handle the #\r\n # of chromosomes\r\n if i == (2**chrbits):\r\n chrbits += 1\r\n i += 1\r\n # also make sure the # of position bits can handle\r\n # the lengths of the reads\r\n lgln = int(math.ceil(math.log(float(ln), 2)))\r\n if lgln > posbits:\r\n posbits = lgln\r\n # check if encoding\r\n if action == 'e':\r\n # if so, see whether to run peak or variant (or if error)\r\n if application == 'p':\r\n peak_encode.encode(fin, chrbits, posbits, chrdict)\r\n elif application == 'v':\r\n var_encode.encode(fin, ref, chrbits, posbits, chrdict)\r\n else:\r\n sys.stderr.write(\"Invalid application (not implemented).\" +\r\n \" See Usage.\\n\")\r\n # else if decoding\r\n elif action == 'd':\r\n # check if peak or variant decoding\r\n if application == 'p':\r\n peak_decode.decode(fin, ref, chrbits, posbits, chrdict)\r\n elif application == 'v':\r\n var_decode.decode(fin, ref, chrbits, posbits, chrdict)\r\n else:\r\n sys.stderr.write(\"Invalid application (not implemented).\" +\r\n \" See Usage.\\n\")\r\n else:\r\n sys.stderr.write(\"Invalid action (must be e or d). See Usage.\\n\")\r\n return\r\n\r\n\r\nif __name__ == \"__main__\":\r\n main(sys.argv)\r\n","repo_name":"ewalke31/jam","sub_path":"jam.py","file_name":"jam.py","file_ext":"py","file_size_in_byte":2985,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"38889213819","text":"with open(\"input_data.txt\", \"r\") as f:\n data = f.read()\n\nterminal = data.split(\"\\n\")\nfolder_tree = {\"/\":[]}\ncurrent_directory = \"/\"\n\nfor line in terminal:\n if \"$\" == line[:1]:\n if line[2:4] == \"cd\":\n if line[5:7] == \"..\":\n dirs = current_directory.split(\"/\")\n dirs = dirs[:-2]\n dirs.remove(\"\")\n current_directory = \"/\".join(dirs)\n if len(current_directory) == 0:\n current_directory = \"/\"\n else:\n current_directory = \"/{}/\".format(current_directory)\n elif not line[5:] == \"/\":\n current_directory += line[5:] + \"/\"\n\n elif line[2:4] == \"ls\":\n pass\n else:\n if line[:3] == \"dir\":\n directory = \"{}{}/\".format(current_directory, line[4:])\n try:\n _i = folder_tree[directory]\n except:\n folder_tree[directory] = []\n else:\n line = line.split(\" \")\n new_file = {\"name\": line[1], \"size\": line[0]}\n folder_tree[current_directory].append(new_file)\n\nover_sized_total = 0\nfor directory in folder_tree:\n directory_size = 0\n for folder_name in folder_tree:\n if directory in folder_name:\n for item in folder_tree[folder_name]:\n\n directory_size += int(item[\"size\"])\n \n # curr_dir_items = folder_tree[directory]\n # for item in curr_dir_items:\n # directory_size += int(item[\"size\"])\n\n print(\"{} - {}\".format(directory, directory_size))\n if directory_size < 100000:\n over_sized_total += directory_size\n\nprint(\"RESULT: {}\".format(over_sized_total))\n","repo_name":"AleksiHiltunen/aoc","sub_path":"7/task1.py","file_name":"task1.py","file_ext":"py","file_size_in_byte":1700,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"34710925678","text":"import nltk\nfrom nltk import word_tokenize, sent_tokenize\nfrom nltk.corpus import stopwords\nfrom nltk.stem import PorterStemmer\n\n\n\n#download nltk\nnltk.download()\n\ntext_input = \"Hello Mr. Smith! How are you doing? The weather seems to be really nice.\"\n\nprint(word_tokenize(text_input))\n\nfor i in word_tokenize(text_input):\n print (i)\n\nexample_sentence = \"I have been riding a car lately since the beginning of last year and it has been traumatizing\"\n\nstop_words = set(stopwords.words(\"english\"))\n\nprint(stop_words)\n\nwords = word_tokenize(example_sentence)\nprint(words)\nfiltered_text = []\nfor i in words:\n if i not in stop_words:\n filtered_text.append(i)\nfiltered_text\n\nps = PorterStemmer()\n\nwords = word_tokenize(example_sentence)\n\n\nfor i in words:\n print(ps.stem(i))","repo_name":"saanville/learning-nltk","sub_path":"learning_nltk.py","file_name":"learning_nltk.py","file_ext":"py","file_size_in_byte":782,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"74394015625","text":"from typing import *\nfrom math import *\nfrom collections import *\n\n# 1. Two Sum\nclass Solution:\n # Time complexity: O(n) because you run through the entire List at worst\n # Space complexity: O(n) as you may store the entire List in the hashmap at worst\n def twoSum(self, nums: List[int], target: int) -> List[int]:\n hash = {}\n # Note: Range gives you a range from 0 to the number (not inclusive of the number) if only a single argument is provided\n for i in range(len(nums)):\n complement = target - nums[i]\n if complement in hash:\n return [hash[complement], i]\n hash[nums[i]] = i\n\n# 3. Longest Substring Without Repeating Characters\nclass Solution:\n # Time complexity: O(n); We are going through the entire string\n # Space complexity: O(n); We may potentially store all of the characters of the string into our hashmap - technically we can argue that this is O(min(n, m)) where m is the size of our character set\n def lengthOfLongestSubstring(self, s: str) -> int:\n # We want to return the longest substring's length so we need to set up a variable tracking the length\n longest = 0\n # We want to track the seen characters by their last seen indexes\n seen = {}\n # We are using a sliding window from [i, j] to determine the longest substring\n i = 0\n # Use a different variable for the range\n for j in range(len(s)):\n # If the current index that we are looking at has already been in seen, we need to replace the start of our window with the seen index\n # We want to make sure that we set it to the max of itself or seen[s[j]] in case we come across another repeated character\n if s[j] in seen:\n i = max(seen[s[j]], i)\n # Then we want to calculate the longest - remember to add 1 because we are zero-indexed\n longest = max(longest, j - i + 1)\n # Then set the seen character's index in the hashmap to j + 1 (because we are zero-indexed)\n seen[s[j]] = j + 1\n # Return longest\n return longest\n\n# 13. Roman to Integer\nclass Solution:\n # Time complexity: O(n); You are running through each character of the string to determine the final result\n # Space complexity: O(1); While we are using a hashmap to store some constants, we are actually not using any additional space complexity that is based on input size\n def romanToInt(self, s: str) -> int:\n # Create a numerals hashmap\n numerals = {\n \"I\": 1,\n \"V\": 5,\n \"X\": 10,\n \"L\": 50,\n \"C\": 100,\n \"D\": 500,\n \"M\": 1000\n }\n\n total = 0\n i = 0\n while i < len(s):\n # Check if the number ahead is greater than the current number - if it is, then we know we are supposed to subtract the first number and add to the second number\n if i + 1 < len(s) and numerals[s[i]] < numerals[s[i + 1]]:\n total += numerals[s[i + 1]] - numerals[s[i]]\n # Skip by 2 since we know we just added two figures\n i += 2\n else:\n # Otherwise we can just add it\n total += numerals[s[i]]\n i += 1\n\n return total\n\n# 15. 3Sum\nclass Solution:\n # Terrible solution - would suggest no-sort solution\n # Time complexity: Asymptotically this is O(n^2) but you should point out that it is actually O(n + nlogn + 2n^2)\n # Space complexity: O(n); We are storing a bunch of lists and sets that cumulate to O(n) space max\n def threeSum(self, nums: List[int]) -> List[List[int]]:\n results = set()\n\n neg, pos, zeros = [], [], []\n for num in nums:\n if num > 0:\n pos.append(num)\n elif num < 0:\n neg.append(num)\n else:\n zeros.append(num)\n \n # (0, 0, 0)\n if len(zeros) >= 3:\n results.add((0,0,0))\n \n neg_set, pos_set = set(neg), set(pos)\n\n # (-3, 0, 3)\n if zeros:\n for num in pos_set:\n if -1 * num in neg_set:\n results.add((-1 * num, 0, num))\n \n # (-1, -2, 3)\n for i in range(len(neg)):\n for j in range(i + 1, len(neg)):\n target = -1 * (neg[i] + neg[j])\n if target in pos_set:\n results.add(tuple(sorted([neg[i], neg[j], target])))\n \n # (1, 2, -3)\n for i in range(len(pos)):\n for j in range(i + 1, len(pos)):\n target = -1 * (pos[i] + pos[j])\n if target in neg_set:\n results.add(tuple(sorted([pos[i], pos[j], target])))\n\n return results\n\n\"\"\"\nclass Solution:\n def threeSum(self, nums: List[int]) -> List[List[int]]:\n res, dups = set(), set()\n seen = {}\n for i, val1 in enumerate(nums):\n if val1 not in dups:\n dups.add(val1)\n for j, val2 in enumerate(nums[i+1:]):\n complement = -val1 - val2\n if complement in seen and seen[complement] == i:\n res.add(tuple(sorted((val1, val2, complement))))\n seen[val2] = i\n return res\n\"\"\"\n\n# 20. Valid Parentheses\nclass Solution:\n # Time complexity: O(n) because you run through the entire string\n # Space complexity: O(n) as the stack will be the size of the input\n def isValid(self, s: str) -> bool:\n # String is not valid if it is an odd length as that means the stack will always have a remaining character\n if len(s) % 2 == 1:\n return False\n \n # Sets up a hashmap containing matching pairs of valid parentheses\n hash = {\n \"(\":\")\",\n \"{\":\"}\",\n \"[\":\"]\"\n }\n \n # Stack allows you to go through the string in order to pop off items on the stack in order; you can use a List or Array for stacks (recall from aA)\n stack = []\n for char in s:\n if char in hash:\n stack.append(char)\n elif len(stack) == 0 or hash[stack.pop()] != char:\n return False\n\n return len(stack) == 0\n\n# 21. Merge Two Sorted Lists\nclass ListNode:\n def __init__(self, val = 0, next = None):\n self.val = val\n self.next = next\n\nclass Solution:\n # Time complexity: O(n + m) as it depends on the size of both linked lists\n # Space complexity: O(1) because we only set up a few variables that are not determined by input size\n def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:\n # We set up two variables here because sort_list will continuously be reassigned to its next value whereas output will only keep a receipt of the sort_list nexts\n output = sort_list = ListNode(0)\n\n # Checks if both lists are populated; if not, we know that we can just assign the sorted_list to the remaining list\n while (list1 and list2):\n if (list1.val < list2.val):\n sort_list.next = list1.val\n # Need to make sure that you reassign list1 to be its next value or the while loop will keep going\n list1 = list1.next\n else:\n sort_list.next = list2.val\n # Need to make sure that you reassign list2 to be its next value or the while loop will keep going\n list2 = list2.next\n # Makes sure to go to the next node of sort_list so that the next tail value can be assigned to another list value\n sort_list = sort_list.next\n \n # Will set sort_list head to whichever linked list has values remaining\n sort_list = list1 or list2\n return output.next\n\n# 53. Maximum Subarray\nclass Solution:\n # Time complexity: O(n); We iterate through each number in the List once so the time complexity at worse will be O(n)\n # Space complexity: O(1); We do not use any extra space based on input size as we only set two variables\n def maxSubArray(self, nums: List[int]) -> int:\n # This is a dynamic programming solution using Kadane's Algorithm; Essentially, we iterate through each element of the array and determine whether that array is worth keeping\n # Set up two variables equal to the first element of the input List\n current_sub = max_sub = nums[0]\n\n # For each number starting from the second element of the input List\n for num in nums[1:]:\n # Continuously set current_sub to either the max of the number it is enumerating or the current_sub + the number if higher; this will basically take out any negatives and reset the current_sub to the current number if that's higher\n current_sub = max(num, current_sub + num)\n # You want to also set the max_sub equal to either the max of itself and the current_sub\n max_sub = max(max_sub, current_sub)\n \n # Return max_sub at the end because that's what we are really looking for\n return max_sub\n\n# 56. Merge Intervals\nclass Solution:\n # Time complexity: O(n logn); We use a sort to then do a one-pass through\n # Space complexity: O(n); We are using variable combined to store our merged intervals so our solution could be at worst O(n) in case nothing gets merged\n def merge(self, intervals: List[List[int]]) -> List[List[int]]:\n # Sort the input intervals by each element's starting time (x[0])\n sorted_intervals = sorted(intervals, key=lambda x: x[0])\n # Create a combined interval that will store our results - input the first sorted interval\n combined = [ sorted_intervals[0] ]\n \n # Starting from the second element of sorted_intervals...\n for current_interval in sorted_intervals[1:]:\n # We deconstruct the last added interval\n last_start, last_end = combined[-1]\n # We also deconstruct the current interval that we are looking at\n current_start, current_end = current_interval\n # We check if the current start is less than or equal to the last interval's ending value - if it is, then we know that there is an intersecting interval\n if current_start <= last_end:\n # However, we need to check if this is the only interval that we need to check, so we need to check if the current end is greater than the last end - if it is, then we know that the new interval should just be last_start, current_end\n if current_end > last_end:\n # We replace the last interval\n combined[-1] = [last_start, current_end]\n else:\n # Otherwise, if we don't have an intersecting interval, we can just add it to our combined intervals\n combined.append(current_interval)\n \n return combined\n\n# 57. Insert Interval\nclass Solution:\n # Time complexity: O(n); We are passing the array once so our worst time complexity is O(n)\n # Space complexity: O(n); Our output is storing the new array which at worst can be O(n) size\n def insert(self, intervals: List[List[int]], newInterval: List[int]) -> List[List[int]]:\n # We set up an i to track the index we are going through and an output to track our results\n n = len(intervals)\n i, output = 0, []\n \n # In our first while loop, we need to figure out which intervals are not even overlapping with our new interval beginning yet; this can be determined by checking whether the end of an interval is less than our new interval start\n while i < n and intervals[i][1] < newInterval[0]:\n output.append(intervals[i])\n i += 1\n \n # Once the first while loop ends, we know that we have found the interval that overlaps with our new interval and must now iterate until we find an interval that does not start before our new interval end\n while i < n and intervals[i][0] <= newInterval[1]:\n # As we continuously increment i, we need to continuously reset the new interval start to the minimum of the intervals in between and the maximum of the interval ends\n newInterval[0] = min(intervals[i][0], newInterval[0])\n newInterval[1] = max(intervals[i][1], newInterval[1])\n i += 1\n # Once we exit out of the previous while loop, we know that we have found our interval and can just append the new one\n output.append(newInterval)\n \n # We are now iterating through the rest of our intervals and just adding whatever we have remaining into our output\n while i < n:\n output.append(intervals[i])\n i += 1\n \n return output\n\n# 70. Climbing Stairs\nclass Solution:\n # Time complexity: O(n); You must go through n steps to calculate the number of steps\n # Space complexity: O(n); We are storing all of the results from climbing stairs so we use O(n) space\n def climbStairs(self, n: int) -> int:\n # Set up a hashmap that will memoize the results that we have already calculated - this will help reduce the function from O(n^2) to O(n) since we are not running the sequence multiple times for results that we have already calculated\n memo = {}\n # Initialize the results of climbing stairs once or twice\n memo[1] = 1\n memo[2] = 2\n\n # Helper function to actually climb and store data into the memo\n def climb(n):\n # If we already have the result in our memo, we shouldn't want to run another recursive call on it - we should just pull it from our hashmap\n if n in memo:\n return memo[n]\n # If we don't have the result in our memo already, then we should recursively call climb to get the result - this is basically the Fibonacci sequence\n else:\n # Make sure that we memoize it though\n memo[n] = climb(n - 1) + climb(n - 2)\n return memo[n]\n\n # Call climb(n) to get the number of steps possible - this is basically just the Fibonacci sequence answer\n # You can technically answer this question in the same manner of the Fibonacci Number (#509)\n return climb(n)\n\n# 98. Valid Binary Search Tree\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\nclass Solution:\n # Time complexity: O(n); We go through every node in the tree\n # Space complexity: O(n); We temporarily store all node values in an \"order\" array that will be used to determine whether the tree is inorder or not\n def isValidBST(self, root: Optional[TreeNode]) -> bool:\n # Binary Search Tree's must be in order of values or it is NOT a binary search tree\n # We set up an order array that will contain all node values -> this will then be iterated through to determine whether values are in order or not\n order = []\n # Use a helper function to build out the inorder values\n self.inOrder(root, order)\n\n # Simple function to determine whether a node's value is not in order\n for i in range(len(order) - 1):\n if order[i] >= order[i + 1]:\n return False\n\n # After everything, we can return True\n return True\n\n # Recursively add the left values first and then the middle and then the right values\n def inOrder(self, root, order):\n # Return early if root is None because we've reached the end of tree\n if root is None:\n return\n\n # Recurse left first because we want this in order!\n self.inOrder(root.left, order)\n # Then add the current node\n order.append(root.val)\n # Then recurse right\n self.inOrder(root.right, order)\n\n# 110. Balanced Binary Tree\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\nclass Solution:\n # Time complexity: O(n); For every subtree, we compute its height in constant time as well as compare the height of its children\n # Space complexity: O(n); The cursion stack may go up to O(n) if the tree is unbalanced\n def _isBalanced(self, root: TreeNode):\n # An empty tree is balanced and has a height of -1\n if not root:\n return True, -1\n\n # Check the subtrees to see if they are balanced\n leftIsBalanced, leftHeight = self._isBalanced(root.left)\n if not leftIsBalanced:\n return False, 0\n\n rightIsBalanced, rightHeight = self._isBalanced(root.right)\n if not rightIsBalanced:\n return False, 0\n\n # If the subtrees are balanced, check if the current tree is balanced using their height\n return (abs(leftHeight - rightHeight) < 2), 1 + max(leftHeight, rightHeight)\n \n def isBalanced(self, root: Optional[TreeNode]) -> bool:\n return self._isBalanced(root)[0]\n\n# 121. Best Time to Buy / Sell Stock\nclass Solution:\n # Time complexity: O(n) as we only go through the input array of prices once; Space complexity: O(1) because we only set up two variables that aren't determined by input size\n def maxProfit(self, prices: List[int]) -> int:\n # Set up two variables, min_price which acts as our left pointer and is initially set to an arbitrarily large figure (infinity) to ensure that it is replaced by any stock value\n # And max_profit, which is set to 0 to ensure that we return 0 if we do not find any profits at all\n min_price, max_profit = float('inf'), 0\n\n # price acts as our right pointer and will basically check if the right pointer value gives us a profit against the left pointer -> this will update max_profit if higher\n for price in prices:\n min_price = min(min_price, price)\n max_profit = max(max_profit, price - min_price)\n \n # Returns the max_profit at the end which can be zero if no profits have been found or if the List was empty in the first place\n return max_profit\n\n# 125. Valid Palindrome\nclass Solution:\n # Time complexity: O(n), we traverse over each character at-most once until the two pointers meet in the middle\n # Space complexity: O(1), we only save variables for the pointers and their size is not determined by the size of the string input\n def isPalindrome(self, s: str) -> bool:\n # Set up two pointers, left and right, determined by the starting and ending index of the string\n left, right = 0, len(s) - 1\n \n # Makes sure that the pointers meet in the middle\n while left < right:\n # Checks if either the left or the right character is not an alphanumeric character; basically removes any spaces\n while left < right and not s[left].isalnum():\n left += 1\n while left < right and not s[right].isalnum():\n right -= 1\n \n # Actually checks if the alphanumeric characters are not the same going forward and backwards, meaning it's not a palindrome if found to be false\n if s[left].lower() != s[right].lower():\n return False\n \n # Want to make sure that you're still going through the string even after checking\n left += 1\n right -= 1\n \n # Return true because the while loop has been exited\n return True\n\n# 141. Linked List Cycle\nclass Solution:\n # Time complexity: O(n); The fast pointer reaches the end first and the run time depends on the list's length, which is O(n)\n # Space complexity: O(1); We only use two variable nodes (slow and fast) so the space complexity is going to be O(1)\n # Use Floyd's Cycle Finding Algorithm:\n # Set two pointers that act as a slow and fast runner - eventually, the fast runner will catch up to the slow runner if this is cyclical\n # If the fast runner never catches up or the linked list ends, then you know that the list does not cycle\n def hasCycle(self, head: Optional[ListNode]) -> bool:\n # This is for empty lsits\n if head is None:\n return False\n \n # Set up two pointers that act as a slow and fast runner\n slow = head\n fast = head.next\n\n # Continuously iterate through the linked list to check if the fast runner's nodes are None - if they are, then you know that the linked list ends and is not cyclical\n while slow != fast:\n if fast is None or fast.next is None:\n return False\n\n slow = slow.next\n fast = fast.next.next\n\n # You only return true after exiting the while loop (after determining that slow is indeed equal to fast)\n return True\n\n# 150. Evaluate Reverse Polish Notation\nclass Solution:\n # Time complexity: O(n); We are going through the entire list\n # Space complexity: O(n); We are using a stack to temporarily store our numbers\n def evalRPN(self, tokens: List[str]) -> int:\n # Define our operations - we need to make sure that we check if our token is in here\n operations = \"+-/*\"\n # This problem is stack related - if we look at the input list it is obvious that we can iterate through this using a stack\n stack = []\n\n # For each \"token\"\n for token in tokens:\n # If the token is not in the operations, we can just store it into our stack\n if token not in operations:\n # IMPORTANT - we need to add INTEGERS of the token\n stack.append(int(token))\n # Instead of continue, you can make the below an if and the rest and elif\n continue\n \n # Pop off the last two numbers of the stack - we should always have two numbers in the stack\n num_2 = stack.pop()\n num_1 = stack.pop()\n\n # Set up a variable worth zero that will be used to temporarily store our resulting operation into the stack\n result = 0\n if token == \"+\":\n result = num_1 + num_2\n elif token == \"-\":\n result = num_1 - num_2\n elif token == \"*\":\n result = num_1 * num_2\n # VERY IMPORTANT - we need to make the num_1 / num_2 an integer to round up!\n else:\n result = int(num_1 / num_2)\n \n # Append the result as it will become the next number\n stack.append(result)\n\n # Return the result\n return stack.pop()\n\n# 152. Maximum Product Subarray\nclass Solution:\n # Time complexity: O(n); We will go through the entire array so we are size O(n)\n # Space complexity: O(1); We are using constant space to track our variables\n def maxProduct(self, nums: List[int]) -> int:\n # Base case if nums list is empty\n if not nums:\n return 0\n\n # Set up two variables - one will track the highest and the other will track the lowest\n result = max_so_far = min_so_far = nums[0]\n # Result will be returned but should be continuously set to max_so_far\n\n for i in range(1, len(nums)):\n curr = nums[i]\n # We need to track both the lowest min (negative) and highest max (positive) and then determine whether that is our temp_max\n temp_max = max(curr, max_so_far * curr, min_so_far * curr)\n min_so_far = min(curr, max_so_far * curr, min_so_far * curr)\n\n max_so_far = temp_max\n\n result = max(max_so_far, result)\n\n return result\n\n# 167. Two Sum II\nclass Solution:\n # This is a twist on the classic Two Sum except the input array is now sorted, which indicates that you should probably use a binary search or two pointers; note that binary search is slightly slower O(nlog n)\n # Time complexity: O(n); We are using two pointers method to check the elements at each pointer but at worst we may still go through every element in the array\n # Space complexity: O(1); We are only using two variables so this is constant space\n def twoSum(self, numbers: List[int], target: int) -> List[int]:\n # Set up the left and right pointers to be equal to the start of the index and the end of the index, respectively\n left, right = 0, len(numbers) - 1\n\n # While left is less than right...\n while left < right:\n # Check if the left number + right number is equal to the target and return the answer (in this case we add +1 because the solution specifies so)\n if numbers[left] + numbers[right] == target:\n return [left + 1, right + 1]\n # Else if the added number is less than the target, then we know we have to increment the left pointer to increase the sum\n elif numbers[left] + numbers[right] < target:\n left += 1\n # Else if the added number is greater than the target, then we know we have to decrement the right pointer to decrease the sum\n else:\n right -= 1\n \n # Return [-1, -1] if we cannot find a pair that sums up to the target\n return [-1, -1]\n\n# 169. Majority Element\nclass Solution:\n # First solution is by solving using a hashmap\n # Time complexity: O(n); You must go through the list at least once to store all of the integers\n # Space complexity: O(n); You must store all of the integers in the list into the hashmap so the worst space complexity is O(n)\n def majorityElement(self, nums: List[int]) -> int:\n # Create a hashmap and set it as a variable\n hashmap = {}\n # For each number, we want to increment the count and then check whether it is the majority number\n for num in nums:\n hashmap[num] = hashmap.get(num, 0) + 1\n if hashmap[num] > len(nums) / 2:\n return num\n\n # Second solution is by solving using Boyer-Moore majority voting algorithm\n # Time complexity: O(n); Boyer-Moore performs constant work n times, so the algorithm runs in linear time\n # Space complexity: O(1); Allocates only constant memory\n def majorityElement2(self, nums: List[int]) -> int:\n # Set up a majority and count variable to track the majority number and a count that will keep track of the majority count\n majority = 0\n count = 0\n for num in nums:\n # If the count is zero, then you know that the majority number has been reset and should thus be set to the new num\n if count == 0:\n majority = num\n # If the majority isn't already the number, then just decrement the count of it\n if majority != num:\n count -= 1\n # However, if the majority is already the number, then we need to increment the count of it\n else:\n count += 1\n # Return the tracked majority number\n return majority\n\n# 217. Contains Duplicate\nclass Solution:\n # Time complexity: O(n); You run through the entire list once\n # Space complexity: O(n); You store at most all of the numbers into the temporary hashmap\n def containsDuplicate(self, nums: List[int]) -> bool:\n hash = {}\n for i in nums:\n if i not in hash:\n hash[i] = 0\n else:\n return True\n return False\n\n# 226. Invert Binary Tree\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\nclass Solution:\n # Time complexity: O(n); You must traverse the entire node tree so the best possible solution is O(n)\n # Space complexity: O(n); You must return the reversed tree so it will be O(n) space complexity (dependent on input)\n def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:\n # Checks if the root node exists\n if root:\n # Recursively reverses the root node's branches\n root.left, root.right = self.invertTree(root.right), self.invertTree(root.left)\n # Make sure to return root here so that the recursion continues unless if statement is no longer completed\n return root\n # No need to explicitly return root here but invertTree would return [] if no root\n return root\n\n# 235. Lowest Common Ancestor of a Binary Search Tree\n# Note that this is a Binary Search Tree, which requires the left and right node values to be less than and greater than, respectively, the root node values\n# Time Complexity: O(n); This is the worst case scenario as you might have to traverse every node in the tree if the tree is a singly-linked list; Note that the average time complexity would be O(log(n)) as you split the tree nodes in half in this iterative solution\n# Space Complexity: O(1); This is not iterated using recursion so there is no stack and the only variable that is saved is not reliant on the input size\n\nclass Solution:\n def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':\n # Set a current node to continuously check through\n # Note that this assumes that there is a p and q\n node = root\n # While this node exists (is not None)\n while node:\n parent_val = node.val\n # Since we know this is a binary search tree, we can check if p and q are both less than or greater than. If one is less and the other is greater, than it means that the current node must be our lowest common ancestor because we cannot traverse down left or right and find another common ancestor\n # Else if p and q are both greater than or less than the current node value, then we can just traverse into one side (left or right) to get closer to the LCA\n if p.val > parent_val and q.val > parent_val:\n node = node.right\n elif p.val < parent_val and q.val < parent_val:\n node = node.left\n else:\n return node\n\n# 236. Lowest Common Ancestor of a Binary Tree\n# Time complexity: O(n); We must iterate through every node in the tree to determine the lowest common ancestor\n# Space complexity: O(n); We are using a recursive call which will have us use a stack of at worst O(n)\nclass Solution:\n # This is a very simple recursive function that will solve for the lowest common ancestor of both p and q\n def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':\n # if root is None, p, or q, we should just return it\n if root in (None, p, q ):\n return root\n\n # Otherwise, we set up a left and right pathway that looks for p and q in its left / right nodes\n left, right = (self.lowestCommonAncestor(kid, p, q) for kid in (root.left, root.right))\n # If left and right both return a root value (not a None), then we know that our path has been found and we can return it\n # Otherwise, we must go into either left or right to determine which has both ancestors\n return root if left and right else left or right\n\n# 242. Valid Anagram\nclass Solution:\n # Time complexity: O(n); You must traverse both strings whose length is n each\n # Space complexity: O(1); Size of the strings doesn't matter as only a hashmap is stored containing the count of the strings\n def isAnagram(self, s: str, t: str) -> bool:\n # Checks if the length of the strings are the same; if not, return False\n if len(s) != len(t):\n return False\n \n # Counter is a built-in Python function that comes from collections library; it iterates through every character in the string and creates a hashmap counter\n return collections.Counter(s) == collections.Counter(t)\n\n # Otherwise, you can use the following answer to be more explicit:\n # counter = collections.defaultdict(int)\n # for char in s: counter[char] += 1\n # for char in t: counter[char] -= 1\n # return all(char == 0 for char in counter.values())\n\n# 252. Meeting Rooms\nclass Solution:\n # Time complexity: O(nlog n); You sort the intervals so the best time complexity is O(nlog n)\n # Space complexity: O(1); No additional space needed to solve this\n def canAttendMeetings(self, intervals: List[List[int]]) -> bool:\n # Sort all of the intervals by the starting time\n intervals.sort(key=lambda x: x[0])\n\n # For each interval starting from the second one, check if the starting interval is less than the previous ending interval\n for i in range(1, len(intervals) - 1):\n # If it is less, then we know that we have intersecting meeting times and thus the person cannot attend all meetings -> return False\n if intervals[i][0] < intervals[i - 1][-1]:\n return False\n\n # If no falses, then we should be good\n return True\n\n# 392. Is Subsequence\nclass Solution:\n # Time complexity: O(t); At worst, we will go through all of string t\n # Space complexity: O(1); We use constant space to track our pointers\n def isSubsequence(self, s: str, t: str) -> bool:\n # If string s is shorter than string t, then there is no way that string s will be a subsequence of string t\n if len(s) > len(t):\n return False\n \n # If string s is length 0 or non-existent, then it is automatically a subsequence of string t (can just delete all characters)\n if len(s) == 0:\n return True\n \n subsequence = 0\n # We set our first pointer, i, to track the characters at index i of string t\n for i in range(len(t)):\n # If the subsequence is currently less than the length of string s and the current character we are looking at matches, then we can add 1 to subsequence\n # Subsequence tracks the order and characters of string s - if we go in order and find that we contain all of the characters from string t, we know that string s is a valid subsequence\n if subsequence <= len(s) - 1 and s[subsequence] == t[i]:\n subsequence += 1\n \n # We just check at the end if we have reached the length of string s, aka checked every character\n return subsequence == len(s)\n\n# 409. Longest Palindrome\nclass Solution:\n # Time complexity: O(n); You must go through each character in the input string to store into the set\n # Space complexity: O(n); You may store every character in the input string into a set in the worst case (every character is different)\n def longestPalindrome(self, s: str) -> int:\n # Set up a new set using Python set\n count = set()\n # For every character in the input string (whether it is capitalized or not), input the character into the set if not already there and remove it if it is\n for char in s:\n if char not in count:\n count.add(char)\n else:\n count.remove(char)\n \n # Check if the length of the set is 0; if it is zero, then you know that every character in the input string has a pair and is therefore the longest palindrome\n # Otherwise, you know that the length of the remaining set contains all of the non-paired characters that can be removed from the \"longest\" calculation\n # You add one to the end of the answer because you want to make sure that one of the non-paired characters is included into the longest palindrome\n if len(count) != 0:\n return len(s) - len(count) + 1\n else:\n return len(s)\n\n# 509. Fibonacci Number\nclass Solution:\n # This is a two-pointer solution to the classic Fibonacci problem\n # Time complexity: O(n); You must iterate n times to return the final fibonacci number\n # Space complexity: O(1); You use constant space for the variables assigned\n def fib(self, n: int) -> int:\n # Assign two variables to 0 and 1\n a, b = 0, 1\n # For each number from 0 to n, you will reassign a and b variables to b and a + b, respectively, essentially getting to the next fibonnaci number by using two pointers\n for i in range(n):\n a, b = b, a + b\n # You want to return a instead of b here because b will always be reassigned to the next fibonacci number and not the current one\n return a\n # Note: There is a more optimal solution here using the golden ratio forumla but it would require you to know the golden ratio (1 + (5 ** 0.5)) / 2\n # The time complexity is more efficient using the golden ratio (O(log n)) but it requires knowledge of the golden ratio \n\n# 542. 01 Matrix\nfrom collections import deque\n\nclass Solution:\n # Time complexity: O(x * y); We must go through every position in the grid\n # Space complexity: O(x * y); At worst, we may have to temporarily store every number in the grid for our queue\n # We are going to implement this solution using BFS because we must determine the distance away from a 0\n def updateMatrix(self, grid: List[List[int]]) -> List[List[int]]:\n # We are using BFS so set up a queue\n queue = deque()\n # We don't want to revisit any cells that we've already calculated values for, so set up a set\n visited = set()\n for x in range(len(grid)):\n for y in range(len(grid[0])):\n # For every cell, we want to see the distance from 0's - we can calculate this by starting from every 0 and working towards a non-zero figure\n if grid[x][y] == 0:\n visited.add((x, y))\n queue.append((x, y))\n\n while queue:\n # Deconstruct x and y from the queue's topmost position\n x, y = queue.popleft()\n directions = [(0, 1), (0, -1), (1, 0), (-1, 0)]\n # For each direction, we want to check if the neighbors have already been visited and whether they are valid\n # If they have not been visited and are valid, we know that they must be NON-ZERO figures (otherwise they would have been in visited already) - we can increment their values based on that\n for dirr in directions:\n dx, dy = dirr\n newX, newY = x + dx, y + dy\n x_inbounds = 0 <= newX < len(grid)\n y_inbounds = 0 <= newY < len(grid[0])\n\n if x_inbounds and y_inbounds and (newX, newY) not in visited:\n # Increment by one using the current position's value (could be > 0)\n grid[newX][newY] = grid[x][y] + 1\n # Make sure to add our new neighbor to the visited since we have technically changed its value and visited it\n visited.add((newX, newY))\n # Then make sure to add it to our queue so that we can check its neighbors as well\n queue.append((newX, newY))\n \n return grid\n\n# 543. Diameter of a Binary Tree\nclass Solution:\n # Time complexity: O(n); You must iterate through all nodes to determine the diameter of the binary tree\n # Space complexity: O(n); You recursively call upon longest_path so there is an stack containing each node\n def diameterOfBinaryTree(self, root: Optional[TreeNode]) -> int:\n # Set up a diameter variable that will track the diamater and be returned later\n diameter = 0\n\n # Set up a helper function that will actually count the nodes for us\n def longest_path(node):\n # We use Python's nonlocal here to bring the previously issued variable into the scope of this function\n nonlocal diameter\n\n # We know that if the node is None then we can just return 0 instead of adding to the current distance\n if not node:\n return 0\n\n # Recursively call longest_path on the left and right paths of the node assuming - assuming they are not None, they will continue calling and adding to their path\n left_path = longest_path(node.left)\n right_path = longest_path(node.right)\n\n # We know both paths now so we can set diameter equal to the max of either itself or the paths\n diameter = max(diameter, left_path + right_path)\n\n # You want to return the max of both paths + 1 because you are recursively returning this value to be set as your new diameter; \n return max(left_path, right_path) + 1\n\n # Don't forget to call the actual function on the root so that it updates the diamater\n longest_path(root)\n # Return the diameter because that's what we are looking for here\n return diameter\n\n# 680. Valid Palindrome II\nclass Solution:\n # Time complexity: O(n); We are using two pointers to iterate through every character in the string\n # Space complexity: O(1); We are using a few variables but none depend on the input size of the string\n def validPalindrome(self, s: str) -> bool:\n # Create a helper function that just determines if the string is a valid palindrome\n def check_palindrome(s, i, j):\n while i < j:\n if s[i] != s[j]:\n return False\n i += 1\n j -= 1\n return True\n \n # Set up the two pointers to be at the start and end of the string\n i = 0\n j = len(s) - 1\n # In our while loop, we want to check if any of the characters are NOT equal (i.e., not a palindrome) and then check if we can still create a palindrome by excluding a letter\n while i < j:\n if s[i] != s[j]:\n # The result of this should be true if either side is a palindrome (i.e., one letter was removed and still palindrome)\n return check_palindrome(s, i + 1, j) or check_palindrome(s, i, j - 1)\n i += 1\n j -= 1\n # If we have checked all our letters and they are equal, then we can just return True\n return True\n\n# 704. Binary Search\nclass Solution:\n # Time complexity: O(log N); You are splitting the input size of the list (nums) in half in each iteration of your while loop\n # Space complexity: O(1); You are only creating variables with constant space complexity as none of them are dependent on the input size\n def search(self, nums: List[int], target: int) -> int:\n # Set up two variables (two pointers) to track left and right indexes\n left, right = 0, len(nums) - 1\n\n # should conclude if left ever goes over the right\n while (left <= right):\n # Sets the new mid up at the beginning of every while loop as to account for a new \"view\" of the array\n # // operator returns floor division, rounding down to the nearest whole integer\n mid = (left + right) // 2\n # Checks if the middle index is the target; if it is, returns it\n if nums[mid] == target:\n return mid\n # Checks if the middle index is to the left of the target, in which case it makes left = mid + 1 so that the \"view\" is only on the right part of the array\n elif nums[mid] < target:\n left = mid + 1\n # Else, we know that the target is less than the nums[mid] so set right = mid - 1 to \"view\" only the left portion of the array\n else:\n right = mid - 1\n # If all else fails, return -1 to indicate that the number does not exist in the solution\n return -1\n\n# 733. Flood Fill\nclass Solution:\n # Time complexity: O(n); You are going to visiting every \"pixel\" of the image so you will iterate through N pixels\n # Space complexity: O(n); The size of the implicit call stack using DFS\n def floodFill(self, image: List[List[int]], sr: int, sc: int, newColor: int) -> List[List[int]]:\n # Set up two variables that will hold the max dimensions of the image (X, Y)\n X, Y = len(image), len(image[0])\n # Set up a variable to track the color at the starting pixel (sr, sc)\n color = image[sr][sc]\n # You want to return the image here if the color is already equal to the newColor because you don't want to flood fill the same color again\n if color == newColor: return image\n\n def dfs(x, y):\n if image[x][y] == color:\n # Set the current pixel to the new color if it isn't already\n image[x][y] = newColor\n # DFS the pixel left and right if they aren't out of bounds\n if x >= 1:\n dfs(x - 1, y)\n if x + 1 < X:\n dfs(x + 1, y)\n # DFS the pixel above and below if they aren't out of bounds\n if y >= 1:\n dfs(x, y - 1)\n if y + 1 < Y:\n dfs(x, y + 1)\n \n # Don't forget to actually run the DFS on the image starting at the starting pixel\n dfs(sr, sc)\n # Remember that the image will be altered and thus should be returned as is\n return image\n\n# 1029. Two City Scheduling\nclass Solution:\n # Time complexity: O(nlogn); We are sorting our costs to determine the cheapest cities to go to City A and the cheapest to go to City B\n # Space complexity: O(n); In Python, the sort function uses the Timsort algorithm which is a combination of Merge Sort and Insertion Sort -> this takes O(n) additional space\n def twoCitySchedCost(self, costs: List[List[int]]) -> int:\n # Sort the costs in-place by determining which cities are cheaper to go to City A first; all of the cities that are greater (x[0] - x[1]) will end up being cheaper for City B\n costs.sort(key = lambda x: x[0] - x[1])\n\n # Set up the total costs variable since this is what we want to return\n total = 0\n # N represents the length of the costs divided by 2 because we need to \n n = len(costs) // 2\n # The beginning half of the sorted costs show cheaper costs to go to City A - we add those; the ending half of the sorted costs show cheaper costs to go to City B - we add those\n for i in range(n):\n total += costs[i][0] + costs[i + n][1]\n\n # Don't forget to return the total!\n return total\n\n# 1064. Fixed Point\nclass Solution:\n # Time complexity: O(log n); Since we're using a binary search, we halve the size of the array in each loop and thus reduce our time complexity to O(log n) time\n # Space complexity: O(1); We don't use any additional space to perform the binary search so the space complexity is constant\n def fixedPoint(self, arr: List[int]) -> int:\n # Set up two variables that will serve as our binary search pointers\n left, right = 0, len(arr) - 1\n # Initiate the answer as -1 in case we never find our fixedPoint\n answer = -1\n\n # Binary search starts with the left pointer being less than or equal to the right pointer\n while left <= right:\n # Set up a middle variable that will track the current mid of the current arr[left::right]\n mid = (left + right) // 2\n\n # If the index is equal to itself at the middle of the arr, then we can say that the answer is mid\n # We decrement the right to mid - 1 because we still want to check if there is a SMALLER index that satisfies arr[i] == 1\n if arr[mid] == mid:\n answer = mid\n right = mid - 1\n # Else we check if the arr[mid] is less than the current mid - if it is, we must increment left\n elif arr[mid] < mid:\n left = mid + 1\n # Finally if all else fails, we know that arr[mid] is greater than the midpoint so we should decrement right\n else:\n right = mid - 1\n\n # Make sure to return the answer - this should be a new value or -1 if nothing is found\n return answer\n\n# 1396. Design Underground System\nimport collections\nclass UndergroundSystem:\n def __init__(self):\n self.checked_in = {}\n self.journey_data = collections.defaultdict(lambda: [0, 0])\n\n # Time complexity: O(n) worst case; O(1) average to insert\n # Space complexity: O(n) worst case\n def checkIn(self, id: int, stationName: str, t: int) -> None:\n self.checked_in[id] = [stationName, t]\n\n # Time complexity: O(n) worst case; O(1) average to delete\n # Space complexity: O(n) worst case\n def checkOut(self, id: int, stationName: str, t: int) -> None:\n startStation, startTime = self.checked_in.pop(id)\n self.journey_data[(startStation, stationName)][0] += t - startTime\n self.journey_data[(startStation, stationName)][1] += 1\n\n # Time complexity: O(n) worst case; O(1) average to search\n # Space complexity: O(n) worst case\n def getAverageTime(self, startStation: str, endStation: str) -> float:\n total_time, total_trips = self.journey_data[(startStation, endStation)]\n return total_time / total_trips\n","repo_name":"leochung97/Data-Structures-Algorithms","sub_path":"Leetcode.py","file_name":"Leetcode.py","file_ext":"py","file_size_in_byte":45467,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"81"} +{"seq_id":"71554085065","text":"from fastapi import FastAPI, Request\nfrom pydantic import BaseModel\nfrom typing import Union\nimport json\nimport uvicorn\nfrom fastapi.middleware.cors import CORSMiddleware\nfrom typing import List\nfrom MathModel import haversine, sorting_by_coef_poly, sorting_by_coef_post\n\nwith open(\"AreaList.json\") as f:\n areaListData = json.load(f)\nf.close()\nareaList = areaListData[\"area\"]\n\ndef isPointInCircle(p_lon, p_lat, c_lon, c_lat, c_radius):\n if haversine(p_lon, p_lat, c_lon, c_lat) > c_radius:\n return False\n return True\n\nclass Item(BaseModel):\n name: str\n\nclass RequestDistrict(BaseModel):\n AdministrativeDistricts: List[str]\n Area: List[str]\n objectType: List[str]\n calculationModel: str\n maxConsumers: str\n minConsumers: str\n numberPosts: int\n\nclass RequestCircle(BaseModel):\n objectType: List[str]\n maxConsumers: str\n minConsumers: str\n Longtitude: float\n Lattitude: float\n Radius: int\n numberPosts: int\n\nclass ClientProcessing:\n app = FastAPI()\n origins = [\"*\"]\n app.add_middleware(\n CORSMiddleware,\n allow_origins=origins,\n allow_credentials=True,\n allow_methods=[\"*\"],\n allow_headers=[\"*\"],\n )\n @app.post(\"/district\")\n async def getByDistrict(req: RequestDistrict):\n response = {}\n with open(\"DataBase.json\") as f:\n jsonData = json.load(f)\n f.close()\n\n dataBase = jsonData[\"Data\"][0]\n i=1\n if req.calculationModel == \"Model1\":\n response = { \"Postamats\": [] }\n for object in req.objectType:\n for area in req.Area:\n for postamat in dataBase[area][object]:\n if float(req.minConsumers) < postamat['coefficient'] < float(req.maxConsumers):\n if i > req.numberPosts:\n break\n postamat[\"id\"] = i\n response['Postamats'].append(postamat)\n # response = sorting_by_coef_post(response, req.numberPosts)\n i+=1\n # print(response)\n return sorting_by_coef_post(response, req.numberPosts)\n\n else:\n response = { \"Postamats\": [] }\n for object in req.objectType:\n for area in req.Area:\n for postamat in dataBase[area][object]:\n if float(req.minConsumers) < postamat['coefficient'] < float(req.maxConsumers):\n if i > req.numberPosts:\n break\n postamat[\"id\"] = i\n response['Postamats'].append(postamat)\n # response = sorting_by_coef_poly(response, req.numberPosts)\n i+=1\n print(response)\n return sorting_by_coef_post(response, req.numberPosts)\n \n # return response\n\n @app.post(\"/circle\")\n async def getByCircle(req: RequestCircle):\n response = { \"Postamats\": [] }\n with open(\"DataBase.json\") as f:\n jsonData = json.load(f)\n f.close()\n dataBase = jsonData[\"Data\"][0]\n i=1\n for area in areaList:\n for object in req.objectType:\n for postamat in dataBase[area][object]:\n if float(req.minConsumers) < postamat['coefficient'] < float(req.maxConsumers):\n if isPointInCircle(postamat[\"longtitude\"], postamat[\"lattitude\"], req.Longtitude, req.Lattitude, req.Radius):\n if i > req.numberPosts:\n break\n postamat[\"id\"] = i\n response['Postamats'].append(postamat)\n i+=1\n return sorting_by_coef_post(response, req.numberPosts)\n\n def start(self):\n with open(\"config.json\") as f:\n config_data = json.load(f)\n f.close()\n uvicorn.run(self.app, host=config_data[\"ip_addr\"], port=config_data[\"port\"])","repo_name":"aUser972/memchiki","sub_path":"ClientProcessing.py","file_name":"ClientProcessing.py","file_ext":"py","file_size_in_byte":3525,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"72929444746","text":"from sys import stdin\n\ninput = lambda: stdin.readline().rstrip()\n\nif __name__ == \"__main__\":\n N = int(input())\n H = list(map(int, input().split()))\n\n H.sort()\n ans = int(2e9)\n for i in range(N):\n for j in range(i + 3, N):\n left, right = i + 1, j - 1\n while left < right:\n temp = (H[i] + H[j]) - (H[left] + H[right])\n ans = min(abs(temp), ans)\n if temp < 0:\n right -= 1\n else:\n left += 1\n print(ans)\n\n","repo_name":"boorooksus/Algorithm-Study","sub_path":"백준/CH08_Two Pointers/G3-20366-Do_You_Wanna_Build_Snow_Men2.py","file_name":"G3-20366-Do_You_Wanna_Build_Snow_Men2.py","file_ext":"py","file_size_in_byte":545,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"70591677385","text":"import time\r\nimport os\r\nimport gc\r\nimport jieba\r\nfrom sklearn.model_selection import train_test_split\r\nfrom sklearn.feature_extraction.text import TfidfVectorizer,CountVectorizer\r\nfrom sklearn.naive_bayes import MultinomialNB\r\nfrom sklearn import metrics\r\nimport pandas as pd\r\nimport numpy as np\r\n\r\nfrom gensim.models import Word2Vec\r\n\r\nfrom keras.layers import *\r\nfrom keras.models import *\r\nfrom keras.preprocessing.text import Tokenizer\r\nfrom keras.preprocessing.sequence import pad_sequences\r\nfrom keras.engine.topology import Layer\r\n\r\nfrom tqdm import tqdm\r\n\r\nembed_size=200\r\nmaxlen = 100\r\nmax_features = 73915 #73662 # 95000\r\n\r\n\"去除指定无用的符号,这里我们主要拿空格举例\"\r\npuncts = [' ']\r\ndef clean_text(x):\r\n x=x.strip()\r\n for punct in puncts:\r\n x=x.replace(punct,'')\r\n return x\r\n\r\n\"让文本只保留文字\"\r\ndef is_chinese(xchar):\r\n if xchar>=u'\\u4e00' and xchar<=u'\\u9fa5':\r\n return True\r\n else:\r\n return False\r\ndef keep_chinese_text(x):\r\n out_str=''\r\n for i in x:\r\n if is_chinese(i):\r\n out_str=out_str+i\r\n return out_str\r\n\r\ndef seg_sentence(sentence,stopwords):\r\n \"对句子进行分词和去除停用词\"\r\n sentence_seged=jieba.cut(sentence)\r\n outstr=''\r\n for word in sentence_seged:\r\n if word not in stopwords:\r\n outstr+=word\r\n outstr+=\" \"\r\n return outstr\r\n\r\ndef build_vocab(sentences,verbose=True):\r\n \"追踪训练词汇表,遍历所有文本对单词进行计数\"\r\n vocab={}\r\n for sentence in tqdm(sentences,disable=(not verbose)):\r\n for word in sentence.split():\r\n try:\r\n vocab[word]+=1\r\n except KeyError:\r\n vocab[word]=1\r\n #vocab=sorted(vocab.items(),key=lambda d:d[1],reverse=True) # 分词后共出现73915个单词\r\n # vocab=vocab[:vocab_size]\r\n return vocab\r\n\r\ndef texts_to_sequences(sentences,vocab,verbose=True):\r\n seq_sentences=[]\r\n unk_vec=np.random.random(embed_size)*0.5\r\n unk_vec=unk_vec-unk_vec.mean()\r\n for sentence in tqdm(sentences,disable=(not verbose)):\r\n seq_sentence=[]\r\n for word in sentence.split():\r\n seq_sentence.append(vocab.get(word,unk_vec))\r\n seq_sentences.append(seq_sentence)\r\n return seq_sentences\r\n\r\ndef load_and_prec():\r\n #文件读取\r\n train_df=pd.read_csv('data/news_classification_dataset.csv')\r\n\r\n #train_df, test_df = train_test_split(train_df, test_size=0.01, random_state=2019)\r\n\r\n #创建停用词列表\r\n stopwords = ['的', '呀', '这', '那', '就', '的话', '如果']\r\n\r\n train_df[\"text\"]=train_df[\"text\"].apply(lambda x:clean_text(x))\r\n #test_df[\"text\"]=test_df[\"text\"].apply(lambda x:clean_text(x))\r\n\r\n train_df[\"text\"]=train_df[\"text\"].apply(lambda x:keep_chinese_text(x))\r\n #test_df[\"text\"]=test_df[\"text\"].apply(lambda x:keep_chinese_text(x))\r\n\r\n train_df[\"text\"]=train_df[\"text\"].apply(lambda x:seg_sentence(x,stopwords))\r\n #test_df[\"text\"]=test_df[\"text\"].apply(lambda x:seg_sentence(x,stopwords))\r\n\r\n vocab=build_vocab(train_df[\"text\"],True)\r\n\r\n # split to train and val\r\n train_df, test_df = train_test_split(train_df, test_size=0.01, random_state=2019)\r\n train_df,val_df=train_test_split(train_df,test_size=0.01,random_state=2019)\r\n\r\n # print(\"Train shape: \",train_df.shape) # (34623, 3)\r\n # print(\"Val shape: \",val_df.shape) # (3848, 3)\r\n\r\n ## Get the input values\r\n train_X=train_df[\"text\"].values\r\n val_X=val_df[\"text\"].values\r\n test_X=test_df[\"text\"].values\r\n\r\n ## Get the target values\r\n train_y=train_df[\"label\"].values\r\n val_y=val_df[\"label\"].values\r\n test_y=test_df[\"label\"].values\r\n\r\n np.random.seed(2019)\r\n trn_idx=np.random.permutation(len(train_X))\r\n val_idx=np.random.permutation(len(val_X))\r\n\r\n train_X=train_X[trn_idx]\r\n val_X=val_X[val_idx]\r\n train_y=train_y[trn_idx]\r\n val_y=val_y[val_idx]\r\n\r\n # Tokenize the sentences\r\n train_X=texts_to_sequences(train_X, vocab)\r\n val_X=texts_to_sequences(val_X,vocab)\r\n test_X=texts_to_sequences(test_X,vocab)\r\n # Pad the sentences\r\n train_X=pad_sequences(train_X,maxlen=maxlen)\r\n val_X=pad_sequences(val_X,maxlen=maxlen)\r\n test_X=pad_sequences(test_X,maxlen=maxlen)\r\n\r\n return train_df,test_df,train_X,val_X,test_X,train_y,val_y,test_y,vocab\r\n\r\ndef word2vec_model(train_df, test_df, vocab):\r\n count=0\r\n nb_words=len(vocab)\r\n print(nb_words)\r\n start=time.clock()\r\n all_data=pd.concat([train_df[\"text\"],test_df[\"text\"]])\r\n file_name='data/word2vec.model'\r\n if not os.path.exists(file_name):\r\n model=Word2Vec([[word for word in sentence.split()] for sentence in all_data.values],\r\n size=embed_size,window=5,iter=10,workers=11,seed=2019,min_count=2)\r\n model.save(file_name)\r\n else:\r\n model=Word2Vec.load(file_name)\r\n print(\"add word2vec finished...\")\r\n end=time.clock()\r\n print('Running time: %s Seconds' %(end-start))\r\n\r\n nb_words=min(max_features,len(vocab))\r\n embedding_word2vec_matrix=np.zeros((nb_words,embed_size))\r\n for word,i in vocab.items():\r\n if i>max_features:continue\r\n embedding_vector=model[word] if word in model else None\r\n if embedding_vector is not None:\r\n count+=1\r\n embedding_word2vec_matrix[i]=embedding_vector\r\n else:\r\n unk_vec=np.random.random(embed_size)*0.5\r\n unk_vec=unk_vec-unk_vec.mean()\r\n embedding_word2vec_matrix[i]=unk_vec\r\n del model;\r\n gc.collect()\r\n return embedding_word2vec_matrix\r\n\r\n\"\"\"Attention Layer\"\"\"\r\nclass Attention(Layer):\r\n def __init__(self, step_dim,\r\n W_regularizer=None, b_regularizer=None,\r\n W_constraint=None, b_constraint=None,\r\n bias=True, **kwargs):\r\n self.supports_masking = True\r\n self.init = initializers.get('glorot_uniform')\r\n\r\n self.W_regularizer = regularizers.get(W_regularizer)\r\n self.b_regularizer = regularizers.get(b_regularizer)\r\n\r\n self.W_constraint = constraints.get(W_constraint)\r\n self.b_constraint = constraints.get(b_constraint)\r\n\r\n self.bias = bias\r\n self.step_dim = step_dim\r\n self.features_dim = 0\r\n super(Attention, self).__init__(**kwargs)\r\n\r\n def build(self, input_shape):\r\n assert len(input_shape) == 3\r\n\r\n self.W = self.add_weight((input_shape[-1],),\r\n initializer=self.init,\r\n name='{}_W'.format(self.name),\r\n regularizer=self.W_regularizer,\r\n constraint=self.W_constraint)\r\n self.features_dim = input_shape[-1]\r\n\r\n if self.bias:\r\n self.b = self.add_weight((input_shape[1],),\r\n initializer='zero',\r\n name='{}_b'.format(self.name),\r\n regularizer=self.b_regularizer,\r\n constraint=self.b_constraint)\r\n else:\r\n self.b = None\r\n\r\n self.built = True\r\n\r\n def compute_mask(self, input, input_mask=None):\r\n return None\r\n\r\n def call(self, x, mask=None):\r\n features_dim = self.features_dim\r\n step_dim = self.step_dim\r\n\r\n eij = K.reshape(K.dot(K.reshape(x, (-1, features_dim)),\r\n K.reshape(self.W, (features_dim, 1))), (-1, step_dim))\r\n\r\n if self.bias:\r\n eij += self.b\r\n\r\n eij = K.tanh(eij)\r\n\r\n a = K.exp(eij)\r\n\r\n if mask is not None:\r\n a *= K.cast(mask, K.floatx())\r\n\r\n a /= K.cast(K.sum(a, axis=1, keepdims=True) + K.epsilon(), K.floatx())\r\n\r\n a = K.expand_dims(a)\r\n weighted_input = x * a\r\n return K.sum(weighted_input, axis=1)\r\n\r\n def compute_output_shape(self, input_shape):\r\n return input_shape[0], self.features_dim\r\n\r\n\"CNN Model\"\r\ndef model_cnn(embedding_matrix):\r\n filter_sizes=[1,2,3,5]\r\n num_filters=36\r\n\r\n inp=Input(shape=(maxlen,))\r\n x=Embedding(max_features,embed_size,weights=[embedding_matrix])(inp)\r\n x=Reshape((maxlen,embed_size,1))(x)\r\n\r\n maxpool_pool=[]\r\n for i in range(len(filter_sizes)):\r\n conv=Conv2D(num_filters,kernel_size=(filter_sizes[i],embed_size),\r\n kernel_initializer='he_normal',activation='elu')(x)\r\n maxpool_pool.append(MaxPool2D(pool_size=(maxlen-filter_sizes[i]+1,1))(conv))\r\n\r\n z=Concatenate(axis=1)(maxpool_pool)\r\n z=Flatten()(z)\r\n z=Dropout(0.1)(z)\r\n\r\n outp=Dense(1,activation=\"sigmoid\")(z)\r\n\r\n model=Model(inputs=inp,outputs=outp)\r\n model.compile(loss='binary_crossentropy',optimizer='adam',metrics=['accuracy'])\r\n return model\r\n\r\n\"LSTM models\"\r\ndef model_lstm_attn(embedding_matrix):\r\n inp=Input(shape=(maxlen,))\r\n x=Embedding(max_features,embed_size,weights=[embedding_matrix],trainable=False)(inp)\r\n x=Bidirectional(LSTM(128,return_sequences=True))(x)\r\n x=Bidirectional(LSTM(64,return_sequences=True))(x)\r\n x=Attention(maxlen)(x)\r\n x=Dense(64,activation=\"relu\")(x)\r\n x=Dense(1,activation=\"sigmoid\")(x)\r\n model=Model(inputs=inp,outputs=x)\r\n model.compile(loss='binary_crossentropy',optimizer='adam',metrics=['accuracy'])\r\n return model\r\n\r\n\"\"\"Train and predict\"\"\"\r\ndef train_pred(model,epochs=2):\r\n for e in range(epochs):\r\n model.fit(train_X,train_y,batch_size=512,epochs=1,validation_data=(val_X,val_y))\r\n pred_val_y=model.predict([val_X],batch_size=1024,verbose=0)\r\n pred_test_val=model.predict([val_X],batch_size=1024,verbose=0)\r\n return pred_val_y,pred_test_val\r\n\r\ndef train_pred_F1(model,epochs=2):\r\n for e in range(epochs):\r\n model.fit(train_X,train_y,batch_size=512,epochs=1,validation_data=(val_X,val_y))\r\n pred_val_y=model.predict([val_X],batch_size=1024,verbose=0)\r\n\r\n best_thresh=0.5\r\n best_score=0.0\r\n for thresh in np.arange(0.1,0.501,0.01):\r\n thresh=np.round(thresh,2)\r\n score=metrics.f1_score(val_y,(pred_val_y>thresh).astype(int))\r\n if score>best_score:\r\n best_thresh=thresh\r\n best_score=score\r\n print(\"Val F1 Score: {:.4f}\".format(best_score))\r\n\r\n pred_test_y=model.predict([test_X],batch_size=1024,verbose=0)\r\n return pred_val_y,pred_test_y,best_score\r\n\r\nif __name__ == '__main__':\r\n train_df, test_df, train_X, val_X,test_X, train_y, val_y, test_y, vocab=load_and_prec()\r\n embedding_word2vec_matrix=word2vec_model(train_df,test_df,vocab)\r\n print(embedding_word2vec_matrix.shape) #(73915, 200)\r\n\r\n # model_gru_atten_3=model_gru_atten_3(embedding_word2vec_matrix)\r\n # model_gru_atten_3.summary()\r\n\r\n outputs=[]\r\n\r\n pred_val_y,pred_test_y,best_score=train_pred_F1(model_cnn(embedding_word2vec_matrix),epochs=1)\r\n outputs.append([pred_val_y,pred_test_y,best_score,'2d CNN']) # 0.912718204488778 2d CNN\r\n\r\n pred_val_y,pred_test_y,best_score=train_pred_F1(model_lstm_attn(embedding_word2vec_matrix),epochs=1)\r\n outputs.append([pred_val_y,pred_test_y,best_score,'2 LSTM x/ attention']) # 0.9282051282051282 2 LSTM x/ attention\r\n\r\n outputs.sort(key=lambda x:x[2])\r\n weights=[i for i in range(1,len(outputs)+1)]\r\n weights=[float(i)/sum(weights) for i in weights]\r\n\r\n for output in outputs:\r\n print(output[2],output[3])\r\n\r\n from sklearn.linear_model import LinearRegression\r\n X=np.asarray([outputs[i][0] for i in range(len(outputs))])\r\n print(X.shape) # (2, 381, 1)\r\n X=X[...,0] # 只取最后一维的第零个元素,是对验证集的预测值\r\n print(X.shape) # (2, 381)\r\n reg=LinearRegression().fit(X.T,val_y)\r\n print(reg.score(X.T,val_y),reg.coef_) # 0.7642986141890105 [0.17936741 0.8483659 ]\r\n\r\n pred_val_y=np.sum([outputs[i][0]*reg.coef_[i] for i in range(len(outputs))],axis=0)\r\n\r\n thresholds=[]\r\n for thresh in np.arange(0.1,0.501,0.01):\r\n thresh=np.round(thresh,2)\r\n res=metrics.f1_score(val_y,(pred_val_y>thresh).astype(int))\r\n thresholds.append([thresh,res])\r\n print(\"F1 score at threshold {0} is {1}\".format(thresh,res))\r\n\r\n thresholds.sort(key=lambda x:x[1],reverse=True)\r\n best_thresh=thresholds[0][0]\r\n print(\"Best threshold: \",best_thresh)\r\n\r\n pred_test_y=np.sum([outputs[i][1]*reg.coef_[i] for i in range(len(outputs))],axis=0)\r\n pred_test_y=(pred_test_y>best_thresh).astype(int)\r\n # test_df=pd.read_csv(\"data/test.csv\",usecols=[\"qid\"])\r\n out_df=pd.DataFrame({\"id\":test_df[\"id\"].values})\r\n print(len(out_df))\r\n out_df['prediction']=pred_test_y\r\n out_df.to_csv(\"submission.csv\",index=False)\r\n\r\n \"\"\"score_f1 : 0.9172932330827067\r\n score_acc : 0.9142857142857143\"\"\"\r\n score_f1 = metrics.f1_score(test_y, (pred_test_y > best_thresh).astype(int))\r\n print(\"score_f1 : \",score_f1)\r\n score_acc = metrics.accuracy_score(test_y, (pred_test_y > best_thresh).astype(int))\r\n print(\"score_acc : \",score_acc)\r\n\r\n\r\n","repo_name":"yuanxin1220/ERINE_news_classification","sub_path":"blend-models-processed.py","file_name":"blend-models-processed.py","file_ext":"py","file_size_in_byte":13054,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"81"} +{"seq_id":"10365029397","text":"import tqdm\nimport numpy as np\nimport scipy as sp\nimport joblib\n\nfrom scipy.sparse import load_npz\nfrom sklearn.model_selection import train_test_split\n\nfrom sklearn.naive_bayes import MultinomialNB\n\nNUM_CLASSES = 537\nNUM_FEATURES = 5024\n\n\ndef main():\n all_data: sp.sparse.csr_matrix = load_npz(\"data/training_data.npz\")\n all_targets = np.load(\"data/training_targets.npy\")\n\n train_data, test_data, train_targets, test_targets = train_test_split(all_data, all_targets, train_size=0.7, test_size=0.3)\n\n train_data = train_data.toarray()\n test_data = test_data.toarray()\n\n print(\"Data Has Been Loaded\")\n model = MultinomialNB()\n model.fit(train_data, train_targets)\n\n print(\"Data Has Been Fitted\")\n train_results = model.predict(train_data)\n test_results = model.predict(test_data)\n\n # Evaluation\n print(\"Train Accuracy\", np.count_nonzero(train_results == train_targets) / len(train_results))\n print(\"Test Accuracy\", np.count_nonzero(test_results == test_targets) / len(test_results))\n\n joblib.dump(model, \"model.sav\")\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"TheMatthewDu/PortfolioMiscellaneous","sub_path":"uoft_course_recommender_system/naive_bayes.py","file_name":"naive_bayes.py","file_ext":"py","file_size_in_byte":1101,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"36158417368","text":"import requests\nfrom bs4 import BeautifulSoup\nimport random\n\n\ndef crawl_img():\n num = random.randint(1,300)\n url = \"https://memes.tw/wtf?sort=hot&page=\"+str(num)\n\n res = requests.get(url)\n soup = BeautifulSoup(res.text, 'lxml')\n array = soup.find_all('img',{'class': 'img-fluid lazy'})\n \n rand = random.randint(0,len(array)-1)\n \n \"\"\"\n for img in array:\n print(img)\n \"\"\"\n \n\n\n #while array[rand].find('img',class_='img_fluid lazy') == None:\n #rand = random.randint(0,len(array)-1)\n #print(array[rand])\n \n print(array[rand]['data-src'])\n return array[rand]['data-src']\n\n \n\n","repo_name":"hochunlin28/TOC_linebot_project","sub_path":"crawler.py","file_name":"crawler.py","file_ext":"py","file_size_in_byte":634,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"40165083423","text":"import os\nfrom collections import namedtuple\nfrom contextlib import contextmanager\nfrom os.path import join, dirname\n\nFIXTURE_DIR = join(dirname(__file__), 'fixtures')\n\nDeviceStub = namedtuple('NamedTuple', ['idVendor', 'idProduct', 'serial_number'])\n\n\n@contextmanager\ndef change_dir(new_dir):\n old_dir = os.getcwd()\n os.chdir(new_dir)\n try:\n yield\n finally:\n os.chdir(old_dir)\n\n\ndef run_invoke_cmd(cli, args):\n try:\n cli.main(args=args)\n except SystemExit as e:\n return e.code\n","repo_name":"vznncv/vznncv-stlink-tools-wrapper","sub_path":"tests/testing_utils.py","file_name":"testing_utils.py","file_ext":"py","file_size_in_byte":524,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"81"} +{"seq_id":"15983280000","text":"from flask import Flask, request, Response\n\napp = Flask(__name__)\n\n@app.route('/health')\ndef health():\n return {\"Healthy\": \"Up\"}\n\n@app.route('/status')\ndef get():\n code = request.args.get('code')\n return Response(\"{'message','Status Code has been created.', 'code': \"+code+\"}\", status=code, mimetype='application/json')\n\napp.run(host='0.0.0.0', debug=True, port=\"5000\")","repo_name":"dispiny/http_status_code_generator","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":378,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"38834910877","text":"import unittest\n\nfrom ..analisis_datos import *\n\nclass TestAnalisisDatos(unittest.TestCase):\n\n\tdef test_poblacion(self):\n\t\tpoblacion = numero_habitantes(\"Murchante\", 2019)\n\t\tself.assertEquals(poblacion, 4154)\n\n\tdef test_pagos_basicos_municipio(self):\n\t\tpagos = pagos_basicos(\"Murchante\", 2017, 0, 100)\n\t\tself.assertEquals(len(pagos), 76)\n\n\tdef test_pagos_basicos_cuantiles(self):\n\t\t# Test cuantil superior\n\t\tpagos = pagos_basicos(\"Barillas\", 2017, 0, 99)\n\t\tself.assertEquals(len(pagos), 2)\n\t\t\n\t\t# Test cuantil inferior\n\t\tpagos = pagos_basicos(\"Barillas\", 2017, 1, 100)\n\t\tself.assertEquals(len(pagos), 2)\n\t\t\n\t\t# Test cuantil superior e inferior\n\t\tpagos = pagos_basicos(\"Barillas\", 2017, 1, 99)\n\t\tself.assertEquals(len(pagos), 1)\n\n\tdef test_histograma(self):\n\t\thistograma_texto = histograma(\"Barillas\", 2019, False, 0, 100, 2000)\n\t\tself.assertTrue(isinstance(histograma_texto, str))\n\n\t\thistograma_texto_per_capita = histograma(\"Barillas\", 2019, True, 0, 100, 2000)\n\t\tself.assertTrue(isinstance(histograma_texto_per_capita, str))\n","repo_name":"RubenRubens/hpacm","sub_path":"src/histograma/tests/test_analisis_datos.py","file_name":"test_analisis_datos.py","file_ext":"py","file_size_in_byte":1027,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"23133937705","text":"import logging\nimport numpy as np\nimport scipy as sp\nfrom typing import *\nimport loompy\nimport cytograph as cg\nimport pandas as pd\n\nimport igraph as ig\nfrom sklearn import preprocessing\n\nclass CountsNormalizer:\n \"\"\"\n Normalize and optionally standardize a dataset, dealing properly with edge cases such as division by zero.\n \"\"\"\n def __init__(self,\n mu: np.ndarray = None,\n sd: np.ndarray = None,\n totals = None,\n mean_center: bool = True,\n normalize_variance: bool = True,\n level: int = 10000) -> None:\n\n self.sd = sd # type: np.ndarray\n self.mu = mu # type: np.ndarray\n self.totals = totals # type: np.ndarray\n self.level = level\n self.mean_center = mean_center\n self.normalize_variance = normalize_variance\n\n def norm_factor_from_totals(self, totals):\n norm_factor = (self.level/totals)\n norm_factor[~np.isfinite(norm_factor)] = 0\n norm_factor = sp.sparse.diags(norm_factor).tocsr()\n return norm_factor\n\n def fit(self, vals: sp.sparse.csr_matrix, cells: np.ndarray = None) -> None:\n totals = vals.sum(0).A.reshape(-1)\n norm_factor = self.norm_factor_from_totals(totals)\n\n vals = vals.dot(norm_factor).T\n if cells is not None:\n vals = vals[cells, :]\n\n #Standard scaler is particularly fast and works with sparse arrays (it computes the mean even if it is not used in rescaling).\n scaler = preprocessing.StandardScaler(with_mean=False)\n scaler.fit(vals)\n\n self.mu = scaler.mean_\n self.sd = np.sqrt(scaler.var_)\n self.totals = totals\n\n def transform(self, vals: sp.sparse.csr_matrix, cells: np.ndarray = None, genes: np.ndarray = None) -> np.ndarray:\n \"\"\"\n Normalize a matrix using the previously calculated aggregate statistics\n\n Args:\n vals (sp.sparse.csr_matrix): Matrix of shape (n_genes, n_cells)\n cells (ndarray): Optional indices of the cells that are represented in vals\n cells (ndarray): Optional indices of the genes that are represented in vals\n\n Returns:\n vals_adjusted (ndarray): The normalized values\n \"\"\"\n\n if genes is not None:\n vals = vals[genes, :]\n else:\n genes = np.arange(vals.shape[0])\n\n norm_factor = norm_factor = self.norm_factor_from_totals(self.totals)\n if cells is not None:\n vals = vals[:, cells]\n norm_factor = norm_factor[cells, :][:, cells]\n\n vals = vals.dot(norm_factor).A\n\n if self.mean_center:\n vals = vals - self.mu[genes][:, None]\n if self.normalize_variance:\n vals = div0(vals.T, self.sd[genes]).T\n \n return vals\n \ndef div0(a: np.ndarray, b: np.ndarray) -> np.ndarray:\n \"\"\" ignore / 0, div0( [-1, 0, 1], 0 ) -> [0, 0, 0] \"\"\"\n with np.errstate(divide='ignore', invalid='ignore'):\n c = np.true_divide(a, b)\n c[~np.isfinite(c)] = 0 # -inf inf NaN\n return c\n\n\nfrom sklearn.svm import SVR\n\nclass FeatureSelection:\n def __init__(self) -> None:\n self.genes = None # type: np.ndarray\n self.mu = None # type: np.ndarray\n self.sd = None # type: np.ndarray\n self.totals = None # type: np.ndarray\n\n def fit(self, ds: loompy.LoomConnection, vals: sp.sparse.csr_matrix,\n cells: np.ndarray = None,\n mu: np.ndarray = None,\n sd: np.ndarray = None) -> np.ndarray:\n \"\"\"\n Fits a noise model (CV vs mean)\n\n Args:\n ds (LoomConnection): Dataset\n n_genes (int): number of genes to include\n cells (ndarray): cells to include when computing mean and CV (or None)\n mu, std: Precomputed mean and standard deviations (optional)\n\n Returns:\n ndarray of selected genes (list of ints)\n \"\"\"\n if cells is not None:\n vals = vals[:, cells]\n self.fit_cells = cells\n\n if mu is None or sd is None:\n scaler = preprocessing.StandardScaler(with_mean=False)\n scaler.fit(vals.T)\n mu = scaler.mean_\n sd = np.sqrt(scaler.var_)\n\n # if \"_Valid\" in ds.ra:\n # valid = ds.ra._Valid == 1\n # else:\n # valid = np.ones(ds.shape[0], dtype='bool')\n # valid = ((valid) & (mu > self.min_expr)).astype(int)\n ok = (mu > 0) & (sd > 0)\n\n self.mu = mu\n self.sd = sd\n self.ok = ok\n # self.valid = valid\n\n cv = sd[ok] / mu[ok]\n log2_m = np.log2(mu[ok])\n log2_cv = np.log2(cv)\n\n svr_gamma = 1000. / len(mu[ok])\n clf = SVR(gamma=svr_gamma)\n clf.fit(log2_m[:, np.newaxis], log2_cv)\n fitted_fun = clf.predict\n # Score is the relative position with respect of the fitted curve\n fitted_val = fitted_fun(log2_m[:, np.newaxis])\n score = log2_cv - fitted_val\n # score = score * valid[ok]\n\n self.fitted_val = fitted_val\n self.score = score\n self.log2_cv = log2_cv\n self.log2_m = log2_m\n\n def select_genes(self, n_genes=1000, min_expr=0.001, valid_genes=None):\n _valid = (self.mu > min_expr)\n if valid_genes is not None:\n _valid = _valid & valid_genes\n _valid_score = self.score * _valid[self.ok].astype(float)\n\n picked_genes = np.where(self.ok)[0][np.argsort(_valid_score)][-n_genes: ]\n return picked_genes\n\n\nfrom sklearn.decomposition import PCA\n\nclass PCAProjection:\n \"\"\"\n Project a dataset into a reduced feature space using PCA. The projection can be fit\n to one dataset then used to project another. To work properly, both datasets must be normalized in the same \n way prior to projection.\n \"\"\"\n def __init__(self, genes: np.ndarray, max_n_components: int = 50) -> None:\n \"\"\"\n Args:\n genes: The genes to use for the projection\n max_n_components: The maximum number of projected components\n nng Non-neuronal genes, to be zeroed in neurons (where TaxonomyRank1 == \"Neurons\")\n \"\"\"\n self.genes = genes\n self.n_components = max_n_components\n\n self.cells = None # type: np.ndarray\n self.pca = None # type: IncrementalPCA\n self.sigs = None # type: np.ndarray\n # self.scan_batch_size = scan_batch_size\n\n def fit(self, vals: sp.sparse.csr_matrix, normalizer: cg.Normalizer, cells: np.ndarray = None) -> None:\n n_cells = vals.shape[1] if cells is None else cells.shape[0]\n n_genes = self.genes.shape[0]\n\n self.pca = PCA(n_components=self.n_components)\n norm_vals = normalizer.transform(vals, genes=self.genes, cells=cells)\n self.pca.fit(norm_vals.T)\n\n def transform(self, vals: sp.sparse.csr_matrix, normalizer: cg.Normalizer, cells: np.ndarray = None) -> np.ndarray:\n \n n_cells = vals.shape[1] if cells is None else cells.shape[0]\n n_genes = self.genes.shape[0]\n\n norm_vals = normalizer.transform(vals, genes=self.genes, cells=cells)\n transformed = self.pca.transform(norm_vals.T)\n return transformed\n\n def fit_transform(self, vals: sp.sparse.csr_matrix, normalizer: cg.Normalizer, cells: np.ndarray = None) -> np.ndarray:\n self.fit(vals, normalizer, cells)\n return self.transform(vals, normalizer, cells)\n\n\nimport logging\nimport numpy as np\nfrom typing import *\nfrom sklearn.svm import SVR\nfrom statsmodels.sandbox.stats.multicomp import multipletests\nimport loompy\nimport cytograph as cg\n\n\nclass MarkerSelection:\n def __init__(self, n_markers: int = 10) -> None:\n self.alpha = 0.1\n\n def fit(self, vals: sp.sparse.csr_matrix, labels: np.ndarray) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:\n \"\"\"\n Finds n_markers genes per cluster using enrichment score\n\n Args:\n vals: Dataset, as a sparse array loaded in memory\n\n Returns:\n ndarray of selected genes (list of ints)\n ndarray of enrichment scores\n ndarray of FDR-corrected P values (i.e. q values)\n \"\"\"\n # Get the observed enrichment statistics\n\n enrichment = self._fit(vals, labels)\n \n rand_labels = np.random.permutation(labels)\n null_enrichment = self._fit(vals, rand_labels)\n qvals = np.zeros_like(enrichment)\n \n for ix in range(enrichment.shape[1]):\n null_values = null_enrichment[:, ix]\n null_values.sort()\n values = enrichment[:, ix]\n pvals = 1 - np.searchsorted(null_values, values) / values.shape[0]\n (_, q, _, _) = multipletests(pvals, self.alpha, method=\"fdr_bh\")\n qvals[:, ix] = q\n\n self.enrichment = enrichment\n self.qvals = qvals\n\n def _fit(self, vals: sp.sparse.csr_matrix, labels: np.ndarray) -> Tuple[np.ndarray, np.ndarray]:\n \"\"\"\n Finds n_markers genes per cluster using enrichment score\n\n Args:\n vals: Dataset, as a sparse array loaded in memory\n\n Returns:\n ndarray of selected genes (list of ints)\n ndarray of enrichment scores\n \"\"\"\n n_labels = max(labels) + 1\n n_cells = vals.shape[1]\n labels_mat = sp.sparse.coo_matrix((np.ones_like(labels), (np.arange(n_cells), labels)))\n\n # Number of cells per cluster\n sizes = np.bincount(labels, minlength=n_labels)\n\n means = (vals.dot(labels_mat).A)/sizes\n nnz = (vals > 0).dot(labels_mat).A\n\n means_overall = vals.mean(1).A.ravel()\n nnz_overall = (vals > 0).sum(1).A.ravel()\n\n f_nnz = nnz / sizes\n f_nnz_overall = nnz_overall / n_cells\n\n means_other = ((means_overall * n_cells)[None].T - (means * sizes)) / (n_cells - sizes)\n f_nnz_other = ((f_nnz_overall * n_cells)[None].T - (f_nnz * sizes)) / (n_cells - sizes)\n\n enrichment = (f_nnz + 0.1) / (f_nnz_other + 0.1) * (means + 0.01) / (means_other + 0.01)\n return enrichment\n\n def select_markers(self, n_markers=50, qval_threshold=0.001, valid_genes = None):\n is_marker = (pd.DataFrame(self.enrichment).rank(ascending=False).values <= n_markers) & (self.qvals < qval_threshold)\n if valid_genes is not None:\n is_marker = is_marker & (np.tile(valid_genes, (self.enrichment.shape[1], 1)).T)\n return is_marker\n\n\n\ndef clean_labels(labels, min_cluster_size=10, zero_is_null=None):\n bigs = np.where(np.bincount(labels) >= min_cluster_size)[0]\n mapping = {k: v for v, k in enumerate(bigs)}\n labels = np.array([mapping[x]+1 if x in bigs else 0 for x in labels])\n return labels\n\n\nimport numpy_groupies as npg\nfrom sklearn import preprocessing\nclass CellLabels():\n def __init__(self, labels, null_label=0):\n \n self.original = labels\n self.null_label = null_label\n self.is_labelled = np.where(self.original != null_label)[0]\n self.is_unlabelled = np.where(self.original == null_label)[0]\n \n self.le = preprocessing.LabelEncoder()\n self.encoded = self.le.fit_transform(self.original[self.is_labelled])\n\n\n def pseudobulk_counts(self, vals, level=10000, gene_names=None):\n\n label_marker_counts = npg.aggregate(self.encoded,\n vals[:, :].A,\n func='sum', axis=1)\n label_total_counts = npg.aggregate(self.encoded,\n vals.sum(0).A.ravel(),\n func='sum')\n label_norm_counts = ((label_marker_counts/label_total_counts) * level).T\n\n original_grp_names = self.le.inverse_transform(np.arange(label_norm_counts.shape[0]))\n\n label_norm_counts = pd.DataFrame(label_norm_counts,\n index = original_grp_names, \n columns = gene_names,\n )\n\n\n return label_norm_counts\n\n\n\nfrom sklearn.neighbors import NearestNeighbors \ndef get_mknn(X, n_neighbors=100, correct_disconnected_nodes=False, seed=0):\n np.random.seed(seed)\n nn = NearestNeighbors(n_neighbors=n_neighbors, algorithm=\"ball_tree\", n_jobs=4)\n nn.fit(X)\n knn = nn.kneighbors_graph(mode='connectivity')\n knn = knn.tocoo()\n mknn = knn.minimum(knn.transpose())\n\n if correct_disconnected_nodes:\n is_isolated_in_mknn = (mknn.sum(1).A.ravel() == 0).astype(float)\n nearest_single_neighbor = nn.kneighbors_graph(mode='connectivity', n_neighbors=1)\n # Keep only edges from those isolated notes\n isolation_correction = sp.sparse.diags(is_isolated_in_mknn).dot(nearest_single_neighbor)\n mknn = mknn + isolation_correction\n\n return mknn.tocoo()\n\ntry:\n import igraph as ig\n import louvain\nexcept:\n pass\ndef get_louvain(mknn, min_cluster_size=10, resolution_parameter=1.0, seed=0):\n g = ig.Graph(n=mknn.shape[0], edges=list(zip(mknn.row, mknn.col)), directed=False)\n\n # Louvain clustering over the mKNN graph\n louvain.set_rng_seed(seed)\n part = louvain.find_partition(g,\n louvain.RBConfigurationVertexPartition,\n resolution_parameter=resolution_parameter)\n \n return CellLabels(clean_labels(part.membership, min_cluster_size=min_cluster_size)) \n\ntry:\n import leidenalg\nexcept:\n pass\ndef get_leiden(mknn, min_cluster_size=10, resolution_parameter=1.0, seed=0, n_iterations=5):\n\n g = ig.Graph(n=mknn.shape[0], edges=list(zip(mknn.row, mknn.col)), directed=False)\n\n part = leidenalg.find_partition(g, leidenalg.RBConfigurationVertexPartition,\n seed = seed, n_iterations = n_iterations,\n resolution_parameter=resolution_parameter,\n )\n\n return CellLabels(clean_labels(part.membership, min_cluster_size=min_cluster_size)) \n\n\ndef update_cluster_based_filter(initial_filter, cluster_labels,\n force_false=[], force_true = []):\n new_filter = initial_filter.copy().astype(int)\n for lb in force_false:\n new_filter[cluster_labels==lb] = 0\n for lb in force_true:\n new_filter[cluster_labels==lb] = 1\n return new_filter\n\ndef merge_split_dataset_filter(ds_dict, merged_ds, filter_attr):\n\n passing_cell_ids = []\n for di, _ds in ds_dict.items():\n passing_cell_ids += list(_ds.ca.CellID[np.where(_ds.ca[filter_attr] > 0)[0]])\n\n merged_filter = np.isin(merged_ds.ca.CellID, passing_cell_ids)\n merged_ds.ca[filter_attr] = merged_filter\n","repo_name":"meltonlab/scbeta_indrops","sub_path":"scbeta_scrnaseq/cytograph_inmem_utils.py","file_name":"cytograph_inmem_utils.py","file_ext":"py","file_size_in_byte":14489,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"81"} +{"seq_id":"72375440266","text":"import pandas as pd\nfrom sklearn.model_selection import train_test_split\nimport numpy as np\nimport csv\n\nfrom utils import gen_random_batch\n\n\ndef export(x, y, size, out):\n x = x.reshape(INPUT_SHAPES).astype('int') # .astype('float32') / 255.\n y = y.astype('int')\n\n groups = [x[np.where(y == i)[0]] for i in np.unique(y)]\n num = int(np.floor(size / 2))\n imgTrue_A, imgTrue_B, similarityTrue = gen_random_batch(groups, num, similarity=1)\n imgFalse_A, imgFalse_B, similarityFalse = gen_random_batch(groups, num, similarity=0)\n\n with open(out, mode='w') as employee_file:\n employee_writer = csv.writer(employee_file, delimiter=',', quotechar='\"', quoting=csv.QUOTE_MINIMAL)\n\n for idx in range(num):\n employee_writer.writerow(imgTrue_A[idx].reshape(-1))\n employee_writer.writerow(imgTrue_B[idx].reshape(-1))\n employee_writer.writerow([similarityTrue[idx]])\n\n employee_writer.writerow(imgFalse_A[idx].reshape(-1))\n employee_writer.writerow(imgFalse_B[idx].reshape(-1))\n employee_writer.writerow([similarityFalse[idx]])\n\n\ndef read(path):\n print(f'Reading {path}')\n imgA = []\n imgB = []\n similarity = []\n with open(path) as csv_file:\n csv_reader = csv.reader(csv_file, delimiter=',', quoting=csv.QUOTE_NONNUMERIC)\n\n idx = 0\n for row in csv_reader:\n row = np.asarray(row).astype(int)\n if idx == 0:\n imgA.append(row)\n elif idx == 1:\n imgB.append(row)\n elif idx == 2:\n similarity.append(row[0])\n idx += 1\n if idx == 3:\n idx = 0\n\n return np.asarray(imgA)/255., np.asarray(imgB)/255., np.asarray(similarity)\n\n\nif __name__ == '__main__':\n INPUT_SHAPES = (-1, 28, 28, 1)\n INPUT_SHAPE = (28, 28, 1)\n\n TRAINING_SET = './dataset/fashion-mnist/train.csv'\n TEST_SET = './dataset/fashion-mnist/test.csv'\n\n MYTRAINING = './dataset/fashion-mnist/mytraining.csv'\n TRAINING_SIZE = 100000\n\n MYTEST = './dataset/fashion-mnist/mytest.csv'\n TEST_SIZE = 50000\n\n # Create training set\n def create_trainingset():\n data_train = pd.read_csv(TRAINING_SET)\n X_full = data_train.iloc[:, 1:].to_numpy()\n y_full = data_train.iloc[:, :1].to_numpy()\n export(X_full, y_full, TRAINING_SIZE, MYTRAINING)\n create_trainingset()\n\n\n def create_testset():\n data_test = pd.read_csv(TEST_SET)\n X_full = data_test.iloc[:, 1:].to_numpy()\n y_full = data_test.iloc[:, :1].to_numpy()\n export(X_full, y_full, TEST_SIZE, MYTEST)\n create_testset()\n #\n # mode = 'read'\n # if mode == 'export':\n #\n # elif mode == 'read':\n # imgA, imgB, similarity = read(MYTRAINING)\n # print(imgA.shape)\n # print(imgB.shape)\n # print(similarity.shape)\n","repo_name":"ducanhnguyen/siamese_network","sub_path":"dataset_generation.py","file_name":"dataset_generation.py","file_ext":"py","file_size_in_byte":2879,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"30589331717","text":"import sys\r\nimport argparse\r\nimport os\r\n\r\nimport pyexiv2\r\nimport pandas as pd\r\nimport numpy as np\r\nimport datetime as dt\r\n\r\n# Get argment\r\nparser = argparse.ArgumentParser()\r\nparser.add_argument(\"--csv\", help=\"CSV file\", type=str)\r\n\r\n#\r\n# Get csv file name.\r\n#\r\ndef getCsvFileName():\r\n return parser.parse_args().csv\r\n\r\n#\r\n# Read data from a csv file which is the list for conversion.\r\n#\r\ndef readCsvData():\r\n fileName = getCsvFileName()\r\n\r\n if os.path.isfile(fileName) == True:\r\n # Read csv file.\r\n data = pd.read_csv(fileName)\r\n else :\r\n # Error : file does not exist.\r\n print(\"file does not exist :\", fileName)\r\n exit()\r\n\r\n # Return a csv data.\r\n return data\r\n\r\n#\r\n# open Exif file.\r\n#\r\ndef openImgData( filename ):\r\n if os.path.isfile( filename ) == True:\r\n return pyexiv2.Image( filename )\r\n else :\r\n print(\"file does not exist :\", filename )\r\n exit()\r\n\r\n\r\ndef convDeg2Dms( deg ):\r\n d = int(deg)\r\n tmp_m = (deg - d) * 60\r\n m = int(tmp_m)\r\n s = round((tmp_m - m) * 60, 2)\r\n return d, m, s\r\n\r\ndef getDmsString( degree, minutes, seconds ):\r\n return (str(degree) + \"/1 \" + str(minutes) +\"/1 \"+ str(int(seconds * 100)) +\"/100\")\r\n\r\n# main\r\nif __name__ == '__main__':\r\n # read meta data\r\n csvData = readCsvData()\r\n\r\n # counter\r\n num = 0\r\n\r\n while num < len(csvData):\r\n img = openImgData( csvData.loc[num, \"filename\"] )\r\n metadata = img.read_exif()\r\n\r\n # delete unnecessary tags.\r\n if 'Exif.Image.Make' in metadata:\r\n del metadata['Exif.Image.Make']\r\n\r\n if 'Exif.Image.Model' in metadata:\r\n del metadata['Exif.Image.Model']\r\n\r\n if 'Exif.Image.Software' in metadata:\r\n del metadata['Exif.Image.Software']\r\n\r\n # update shooting date.\r\n dt = dt.datetime(csvData.loc[num, \"year\"], csvData.loc[num, \"month\"], csvData.loc[num, \"day\"], csvData.loc[num, \"hour\"], csvData.loc[num, \"min\"], 0)\r\n metadata['Exif.Image.DateTime'] = dt.strftime(\"%Y:%m:%d %H:%M:%S\")\r\n metadata['Exif.Image.DateTimeOriginal'] = dt.strftime(\"%Y:%m:%d %H:%M:%S\")\r\n metadata['Exif.Photo.DateTimeOriginal'] = dt.strftime(\"%Y:%m:%d %H:%M:%S\")\r\n metadata['Exif.Photo.DateTimeDigitized'] = dt.strftime(\"%Y:%m:%d %H:%M:%S\")\r\n\r\n if not pd.isnull(csvData.loc[num, \"latitude\"]) and not pd.isnull(csvData.loc[num, \"longitude\"]):\r\n # create geotag (latitude and longitude as GPS information).\r\n metadata['Exif.GPSInfo.GPSVersionID'] = '2 2 0 0'\r\n\r\n if csvData.loc[num, \"latitude\"] > 0:\r\n metadata['Exif.GPSInfo.GPSLatitudeRef'] = \"N\"\r\n else:\r\n metadata['Exif.GPSInfo.GPSLatitudeRef'] = \"S\"\r\n \r\n d, m, s = convDeg2Dms( csvData.loc[num, \"latitude\"] )\r\n metadata['Exif.GPSInfo.GPSLatitude'] = getDmsString( d, m, s )\r\n\r\n if csvData.loc[num, \"longitude\"] > 0:\r\n metadata['Exif.GPSInfo.GPSLongitudeRef'] = \"E\"\r\n else:\r\n metadata['Exif.GPSInfo.GPSLongitudeRef'] = \"W\"\r\n\r\n d, m, s = convDeg2Dms( csvData.loc[num, \"longitude\"] )\r\n metadata['Exif.GPSInfo.GPSLongitude'] = getDmsString( d, m, s )\r\n\r\n #print(metadata)\r\n\r\n # once delete old (original) metadata before modification.\r\n img.clear_exif()\r\n img.modify_exif( metadata )\r\n\r\n # close image file.\r\n img.close()\r\n\r\n # update counter.\r\n num += 1 \r\n","repo_name":"otameshitech/updateExifMetadata","sub_path":"updateExifMetadata.py","file_name":"updateExifMetadata.py","file_ext":"py","file_size_in_byte":3520,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"75179298505","text":"import subprocess\r\n\r\nfrom nums.core.version import __version__\r\n\r\n\r\ndef runproc(*args):\r\n print(\" \".join(args))\r\n return subprocess.Popen(args,\r\n stdin=subprocess.PIPE,\r\n stdout=subprocess.PIPE,\r\n stderr=subprocess.PIPE)\r\n\r\n\r\ndef communicate(*args):\r\n p = runproc(*args)\r\n return tuple(map(lambda x: x.decode(\"utf-8\"), p.communicate()))\r\n\r\n\r\ndef execute():\r\n input_handler = input\r\n\r\n out, err = communicate(\"git\", \"version\")\r\n if err:\r\n raise Exception(err)\r\n\r\n out, err = communicate(\"git\", \"tag\")\r\n versions = list(map(lambda x: x.strip(\"\\r\"), out.strip(\"\\n\\r\").split(\"\\n\")))\r\n\r\n print(\"\")\r\n print(\"tagged versions:\")\r\n for version in versions:\r\n print(version)\r\n print(\"\")\r\n\r\n # Prefix versions with \"v\"\r\n v = \"v\" + __version__\r\n if v in versions:\r\n r = input_handler(\"%s already tagged, force update (y/n)?\" % v)\r\n if r != \"y\":\r\n return\r\n out, err = communicate(\"git\", \"tag\", v, \"-f\")\r\n print(out)\r\n print(err)\r\n out, err = communicate(\"git\", \"push\", \"--tags\", \"-f\")\r\n print(out)\r\n print(err)\r\n else:\r\n r = input_handler(\"tag %s (y/n)?\" % v)\r\n if r != \"y\":\r\n return\r\n out, err = communicate(\"git\", \"tag\", v)\r\n print(out)\r\n print(err)\r\n out, err = communicate(\"git\", \"push\", \"--tags\")\r\n print(out)\r\n print(err)\r\n\r\n\r\nif __name__ == \"__main__\":\r\n execute()\r\n","repo_name":"liuhanyao98/nums_gpu_draft","sub_path":"version-tag.py","file_name":"version-tag.py","file_ext":"py","file_size_in_byte":1543,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"37334393819","text":"import telebot\nimport requests\nfrom bs4 import BeautifulSoup\n\nheaders = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) '\\\n 'AppleWebKit/537.36 (KHTML, like Gecko) '\\\n 'Chrome/75.0.3770.80 Safari/537.36'}\n\n\ndef cotacao(item):\n if item == \"/milho\":\n pagina = requests.get('https://www.cepea.esalq.usp.br/br/indicador/milho.aspx', headers=headers)\n\n tipo = \"DO MILHO\"\n \n elif item == \"/soja\":\n pagina = requests.get('https://www.cepea.esalq.usp.br/br/indicador/soja.aspx', headers = headers)\n\n tipo = \"DA SOJA\"\n\n else:\n pagina = requests.get('https://www.cepea.esalq.usp.br/br/indicador/cafe.aspx', headers = headers)\n\n tipo = \"DO CAFÉ\"\n\n\n conteudo = pagina.content\n\n site = BeautifulSoup(conteudo, 'html.parser')\n\n tabela = site.find('div', attrs={'class':'imagenet-table-responsiva'})\n\n cot1 = tabela.find('tbody')\n\n cot2 = cot1.find_all('td')[0].get_text()\n\n cot3 = cot1.find_all('td')[1]\n\n cot4 = cot1.find_all('td')[5]\n\n cot5 = cot1.find_all('td')[6]\n\n cot6 = cot1.find_all('td')[10]\n\n cot7 = cot1.find_all('td')[11]\n\n cot8 = cot1.find_all('td')[15]\n\n cot9 = cot1.find_all('td')[16]\n\n cot10 = cot1.find_all('td')[20]\n\n cot11 = cot1.find_all('td')[21]\n\n mensagem = (f'''COTAÇÃO {tipo} (SACA DE 60Kg)↓↓↓\t\n {cot2} = R${cot3.text}\n {cot4.text} = R${cot5.text}\n {cot6.text} = R${cot7.text}\n {cot8.text} = R${cot9.text}\n {cot10.text} = R${cot11.text}''')\n \n return mensagem\n\napi = '5292833591:AAFs1BgWkcPHl4g0ozllgkq9djipeBpbZBU'\n\nbot = telebot.TeleBot(api)\n\n\n@bot.message_handler(commands=['milho', 'soja', 'cafe'])\ndef opcao1(a):\n bot.reply_to(a, f\"{cotacao(a.text)}\")\n \n\ndef verificar(a):\n return True\n\n@bot.message_handler(func=verificar)\ndef responder(a): \n bot.reply_to(a, '''Olá, sou o Cotador, seu robô que traz cotações atualizadas do Milho, Soja e Café\n/milho para consultar o preço do Milho\n/soja para consultar o preço da Soja\n/cafe para consultar o preço do Café\n\nClique em uma das opções acima\n''')\n\n\n\n\n\n\n\n\n\n\n\n\nbot.polling()","repo_name":"JoseAugusto83/BotTelegram","sub_path":"SecondCode/telegramBot.py","file_name":"telegramBot.py","file_ext":"py","file_size_in_byte":2019,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"74052056265","text":"import torch\nfrom torchvision import models\nimport lightning.pytorch as pl\nfrom sklearn.metrics import roc_auc_score\nimport numpy as np\n\n\nclass LitClassifier(pl.LightningModule):\n def __init__(self, device, lr):\n super().__init__()\n self.model = models.densenet121(weights=\"DEFAULT\")\n self.criterion = torch.nn.BCELoss()\n self.dev = device\n self.lr = lr\n\n # for param in self.model.parameters():\n # param.requires_grad = False\n\n self.model.classifier = torch.nn.Sequential(\n torch.nn.Linear(self.model.classifier.in_features, 1),\n torch.nn.Sigmoid(),\n )\n self.model.to(self.dev)\n\n def forward(self, x):\n return self.model(x)\n\n def training_step(self, batch, batch_idx):\n imgs, labels = batch\n imgs = imgs.to(self.dev)\n labels = labels.unsqueeze(1).to(self.dev)\n\n outputs = self.model(imgs)\n loss = self.criterion(outputs, labels)\n with torch.no_grad():\n self.log(\"train_loss\", loss)\n self.log(\n \"train_auc\",\n roc_auc_score(\n labels.to(torch.float32).cpu(),\n outputs.to(torch.float32).cpu(),\n ).astype(np.float32),\n )\n return loss\n\n def validation_step(self, batch, batch_idx):\n imgs, labels = batch\n imgs = imgs.to(self.dev)\n labels = labels.unsqueeze(1).to(self.dev)\n\n outputs = self.model(imgs)\n loss = self.criterion(outputs, labels)\n self.log(\"val_loss\", loss)\n self.log(\n \"val_auc\",\n roc_auc_score(\n labels.to(torch.float32).cpu(),\n outputs.to(torch.float32).cpu(),\n ).astype(np.float32),\n )\n\n def configure_optimizers(self):\n optimizer = torch.optim.Adam(self.parameters(), lr=self.lr)\n return optimizer\n","repo_name":"sxg/CheXpert-Replica","sub_path":"LitClassifier.py","file_name":"LitClassifier.py","file_ext":"py","file_size_in_byte":1926,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"6700404909","text":"from telegram.ext import Updater\nfrom telegram import Update\nfrom telegram.ext import CallbackContext\nfrom telegram.ext import CommandHandler\nimport telegram\nimport subprocess\nimport logging\n\nlogging.basicConfig(\n filename='botlog.txt',\n filemode='a',\n format='%(asctime)s,%(msecs)d %(name)s %(levelname)s %(message)s',\n datefmt='%H:%M:%S',\n level=logging.DEBUG\n)\nlogger = logging.getLogger(__name__)\n\n# Use your Own chat ID - and group Title to limit the bot to your own group for privacy\ndef private_check(update):\n if str(update.message.chat.id) == \"-123456789\" and update.message.chat.type == \"supergroup\" and update.message.chat.title == \"Group Title\":\n return True\n else:\n update.message.reply_text('go play with your own bot , this is mine (: ')\n\n\ndef terraform_show():\n terraform_show = subprocess.run(\"terraform show -json | jq -r \\'.values.root_module.resources[] | \\\" \\(.values.name) \\(.values.network[].ip) \\(.values.server_type) \\(.values.status)\\\"'\", shell=True, text=True, capture_output=True, check=True)\n output = f\"*Live Instances*: ```{terraform_show.stdout} ```\"\n return output\n\n\ndef start(update: Update, context: CallbackContext):\n if private_check(update):\n update.message.reply_text('start')\n\n\ndef show_instances(update: Update, context: CallbackContext):\n if private_check(update):\n res = terraform_show()\n update.message.reply_text(res,parse_mode=\"MARKDOWN\")\n\n\ndef plan(update: Update, context: CallbackContext):\n if private_check(update):\n try:\n num = int(context.args[0])\n plan = subprocess.run(f\"terraform plan -var instance_count={num} -no-color | grep Plan: \", shell=True, text=True, capture_output=True, check=True )\n update.message.reply_text(f\"🔄 {plan.stdout}\")\n\n except IndexError as e:\n update.message.reply_text(\"give me a number after the command\")\n\n\ndef apply(update: Update, context: CallbackContext):\n\n chat_id = update.effective_chat.id\n message_id = update.message.message_id\n\n if private_check(update):\n try:\n num = int(context.args[0])\n wait_message = update.message.reply_text(\"Please Wait..\")\n\n try:\n apply = subprocess.run(f\"terraform apply -no-color -auto-approve -var=instance_count={num} | grep Apply\", shell=True, text=True, capture_output=True, check=True)\n context.bot.edit_message_text(text=f\"✅ {apply.stdout}\", chat_id=chat_id, message_id=wait_message.message_id)\n update.message.reply_text(text=terraform_show(), parse_mode=\"MARKDOWN\")\n\n except subprocess.CalledProcessError as e:\n logger.info(\"Terraform apply command failed with an error:\")\n logger.info(e.stderr)\n context.bot.edit_message_text(\"*Terraform Error* ❌\", parse_mode=\"MARKDOWN\", chat_id=chat_id, message_id=wait_message.message_id)\n update.message.reply_text(e.stderr)\n\n except IndexError as e:\n logger.info(e)\n update.message.reply_text(\"give me a number after the command\")\n\n# Replace with your own Token\nupdater = Updater(token='<< TELEGRAM-BOT-TOKEN >>', use_context=True)\ndispatcher = updater.dispatcher\n\nstart_handler = CommandHandler('start', start)\nshow_handler = CommandHandler('show', show_instances)\napply_handler = CommandHandler('apply', apply)\nplan_handler = CommandHandler('plan', plan)\n\ndispatcher.add_handler(start_handler)\ndispatcher.add_handler(show_handler)\ndispatcher.add_handler(apply_handler)\ndispatcher.add_handler(plan_handler)\n\nupdater.start_polling()\nupdater.idle()\n","repo_name":"sinanejadebrahim/terraform-telegram-bot","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":3647,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"81"} +{"seq_id":"16147797795","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# vim: ai ts=4 sts=4 et sw=4 nu\n\nimport datetime\n\nimport cx_Oracle\n\nfrom anamdesktop.dbimport import mx, nname, cl, to_date, ANAMDB_USER_ID\nfrom anamdesktop.locations import (get_asserted_commune_id,\n get_cercle_id, get_region_id)\n\n\ndef request_perso_id(conn):\n stmt = (\"SELECT ANAM.SQ_PERSONNES.NEXTVAL INTO :gen_perso_id FROM DUAL\")\n\n cursor = conn.cursor()\n gen_perso_id = None\n try:\n cursor.execute(stmt)\n gen_perso_id = cursor.fetchone()[-1]\n except:\n raise\n finally:\n cursor.close()\n\n return gen_perso_id\n\n\ndef create_hh_member(conn, dos_id, member_data, target, ind_id=None):\n ''' insert an IM_PERSONNES_MOBILE into ANAM DB '''\n stmt = (\"INSERT INTO IM_PERSONNES_MOBILE (\"\n \"PERSO_ID, OGD_ID, DOS_ID,\"\n \"PERSO_CIVILITE, PERSO_NOM, PERSO_PRENOM, PERSO_SEXE, \"\n \"PERSO_DATE_NAISSANCE, PERSO_LOCALITE_NAISSANCE, \"\n \"PERSO_SIT_MAT, PERSO_NATIONALITE, PERSO_PAYS_NAISSANCE, \"\n \"PERSO_NOM_PERE, PERSO_NOM_MERE, PERSO_RELATION, \"\n \"PERSO_TYPE_PERSO, \"\n \"PERSO_ADR_REGION_DISTRICT, PERSO_ADR_LOCALITE, \"\n \"PERSO_ADR_QUARTIER, PERSO_ADR_TEL, PERSO_NINA, \"\n \"PERSO_ETAT_VALIDATION, \"\n \"PERSO_PRENOM_PERE, PERSO_PRENOM_MERE, \"\n \"PERSO_SAISIE_PAR, PERSO_SAISIE_DATE, \"\n \"PERSO_PERSO_ID, PERSO_ETAT_IMMATRICULATION \"\n \") VALUES (\"\n \":perso_id, :ogd_id, :dos_id,\"\n \":perso_civilite, :perso_nom, :perso_prenom, :perso_sexe, \"\n \":perso_date_naissance, :perso_localite_naissance, \"\n \":perso_sit_mat, :perso_nationalite, :perso_pays_naissance, \"\n \":perso_nom_pere, :perso_nom_mere, :perso_relation, \"\n \":perso_type_perso, \"\n \":perso_adr_region_district, :perso_adr_localite, \"\n \":perso_adr_quartier, :perso_adr_tel, :perso_nina, \"\n \":perso_etat_validation, \"\n \":perso_prenom_pere, :perso_prenom_mere, \"\n \":perso_saisie_par, :perso_saisie_date, \"\n \":perso_perso_id, :perso_etat_immatriculation)\")\n\n perso_id = request_perso_id(conn)\n\n now = datetime.datetime.now()\n type_perso = \"IND\" if member_data['relation'] != 'A' else \"\"\n pays_naissance = \"MLI\" if member_data['loc_naissance'] != '0' else \"000\"\n nationalite = \"MALIENNE\" if pays_naissance == \"MLI\" else \"INCONNUE\"\n\n payload = {\n 'perso_id': perso_id,\n 'ogd_id': 40,\n 'dos_id': dos_id,\n 'perso_civilite': member_data['civilite'],\n 'perso_nom': mx(nname(member_data['nom']), 35),\n 'perso_prenom': mx(nname(member_data['prenom']), 60),\n 'perso_sexe': member_data['sexe'],\n 'perso_date_naissance': member_data['ddn'],\n 'perso_localite_naissance': member_data['loc_naissance'],\n 'perso_sit_mat': member_data['sit_mat'],\n 'perso_nationalite': mx(nationalite, 15),\n 'perso_pays_naissance': mx(pays_naissance, 3),\n 'perso_nom_pere': mx(nname(member_data['nom_pere']), 30),\n 'perso_nom_mere': mx(nname(member_data['nom_mere']), 30),\n 'perso_relation': member_data['relation'],\n 'perso_type_perso': type_perso,\n 'perso_adr_region_district': member_data.get('district'),\n 'perso_adr_localite': member_data.get('commune'),\n 'perso_adr_quartier': mx(member_data.get('quartier'), 30),\n 'perso_adr_tel': mx(member_data.get('tel'), 12),\n 'perso_nina': mx(member_data.get('nina'), 15),\n 'perso_etat_validation': \"N\",\n 'perso_prenom_pere': mx(nname(member_data['prenom_pere']), 30),\n 'perso_prenom_mere': mx(nname(member_data['prenom_mere']), 30),\n 'perso_saisie_par': mx(ANAMDB_USER_ID, 30),\n 'perso_saisie_date': now,\n 'perso_perso_id': ind_id,\n 'perso_etat_immatriculation': \"N\",\n }\n\n cursor = conn.cursor()\n try:\n cursor.execute(stmt, payload)\n except:\n raise\n finally:\n cursor.close()\n\n return perso_id\n\n\ndef get_situtation_matrimoniale(data):\n ''' converts situtation_matrimoniale from xform to ANAM DB '''\n return {\n 'celibataire': \"C\",\n 'divorce': \"D\",\n 'marie': \"M\",\n 'veuf': \"V\"}.get(data, \"A\")\n\n\ndef get_sexe(data):\n ''' converts sexe from xform to ANAM DB '''\n return {\n 'masculin': \"M\",\n 'feminin': \"F\",\n }.get(data, \"M\")\n\n\ndef get_civilite(sexe, is_child=False):\n ''' converts civilite from xform to ANAM DB '''\n if sexe == 'M':\n return \"M\"\n else:\n return \"MLLE\" if is_child else \"MME\"\n\n\ndef get_ddn(tddn, ddn, an):\n ''' datetime from xform data based on supplied dob or yob '''\n return to_date(ddn) if tddn == \"ddn\" else datetime.date(int(an), 1, 1)\n\n\ndef get_lieu_naissance(data, prefix):\n ''' converts xfrom lieu_naissance to ANAMDB location ID '''\n naiss_region_slug = data.get(\"{}region\".format(prefix))\n naiss_region_id = get_region_id(naiss_region_slug)\n naiss_cercle_slug = data.get(\"{}cercle\".format(prefix))\n naiss_cercle_id = get_cercle_id(naiss_cercle_slug)\n naiss_commune_slug = data.get(\"{}commune\".format(prefix))\n try:\n naiss_commune_id = get_asserted_commune_id(\n naiss_commune_slug, naiss_cercle_slug)\n except:\n naiss_commune_id = None\n\n naissance_location = None\n if naiss_commune_id:\n naissance_location = naiss_commune_id\n elif naiss_cercle_id:\n naissance_location = naiss_cercle_id\n elif naiss_region_id:\n naissance_location = naiss_region_id\n\n return naissance_location\n\n\ndef get_indigent_data(target):\n ''' preprare member_data for the indigent based on `target` '''\n sit_mat = get_situtation_matrimoniale(\n target.get(\"enquete/situation-matrimoniale\"))\n sexe = get_sexe(target.get(\"enquete/sexe\"))\n\n ddn = get_ddn(target.get(\"enquete/type-naissance\"),\n target.get(\"enquete/ddn\"),\n target.get(\"enquete/annee-naissance\"))\n\n lieu_naissance = get_lieu_naissance(target, \"enquete/\")\n\n # survey location\n addr_region_slug = target.get(\"localisation-enquete/lieu_region\")\n addr_region_id = get_region_id(addr_region_slug)\n addr_cercle_slug = target.get(\"localisation-enquete/lieu_cercle\")\n addr_cercle_id = get_cercle_id(addr_cercle_slug)\n addr_commune_slug = target.get(\"localisation-enquete/lieu_commune\")\n try:\n addr_commune_id = get_asserted_commune_id(\n addr_commune_slug, addr_cercle_slug)\n except:\n addr_commune_id = None\n\n if addr_cercle_id:\n district = addr_cercle_id\n else:\n district = addr_region_id\n\n tel = None\n for d in target.get(\"enquete/telephones\", []):\n _tel = d.get(\"enquete/telephones/numero\")\n if _tel:\n tel = _tel\n break\n\n return {\n 'sexe': sexe,\n 'civilite': get_civilite(sexe, False),\n 'nom': cl(target.get(\"enquete/nom\")),\n 'prenom': cl(target.get(\"enquete/prenoms\")),\n 'ddn': ddn,\n 'loc_naissance': lieu_naissance,\n 'sit_mat': sit_mat,\n 'nom_pere': cl(target.get(\"enquete/filiation/nom-pere\")),\n 'prenom_pere': cl(target.get(\"enquete/filiation/prenoms-pere\")),\n 'nom_mere': cl(target.get(\"enquete/filiation/nom-mere\")),\n 'prenom_mere': cl(target.get(\"enquete/filiation/prenoms-mere\")),\n 'relation': \"A\",\n\n 'district': district,\n 'commune': addr_commune_id,\n 'quartier': cl(target.get(\"enquete/adresse\")),\n 'tel': tel,\n 'nina': cl(target.get(\"nina\"))}\n\n\ndef get_spouse_data(ind_id, target, index):\n ''' preprare member_data for the specified spouse based on `target` '''\n\n spouse = target.get(\"epouses\", [])[index]\n\n lieu_naissance = get_lieu_naissance(spouse, \"epouses/e_\")\n ind_sexe = get_sexe(target.get(\"enquete/sexe\"))\n sexe = \"M\" if ind_sexe == \"F\" else \"F\"\n\n ddn = get_ddn(spouse.get(\"epouses/e_type-naissance\"),\n spouse.get(\"epouses/e_ddn\"),\n spouse.get(\"epouses/e_annee-naissance\"))\n\n return {\n 'ind_id': ind_id,\n\n 'sexe': sexe,\n 'civilite': get_civilite(sexe, False),\n 'nom': cl(spouse.get(\"epouses/e_nom\")),\n 'prenom': cl(spouse.get(\"epouses/e_prenoms\")),\n 'ddn': ddn,\n 'loc_naissance': lieu_naissance,\n 'sit_mat': \"M\",\n 'nom_pere': cl(spouse.get(\"epouses/e_p_nom\")),\n 'prenom_pere': cl(spouse.get(\"epouses/e_p_prenoms\")),\n 'nom_mere': cl(spouse.get(\"epouses/e_m_nom\")),\n 'prenom_mere': cl(spouse.get(\"epouses/e_m_prenoms\")),\n 'relation': \"C\",\n }\n\n\ndef get_child_data(ind_id, target, index):\n ''' preprare member_data for the specified child based on `target` '''\n\n child = target.get(\"enfants\", [])[index]\n lieu_naissance = get_lieu_naissance(child, \"enfants/enfant_\")\n ind_sexe = get_sexe(target.get(\"enquete/sexe\"))\n sexe = get_sexe(child.get(\"enfants/enfant_sexe\"))\n\n ddn = get_ddn(child.get(\"enfants/enfant_type-naissance\"),\n child.get(\"enfants/enfant_ddn\"),\n child.get(\"enfants/enfant_annee-naissance\"))\n\n ind_noms = [cl(target.get(\"enquete/nom\")),\n cl(target.get(\"enquete/prenoms\"))]\n autre_noms = [cl(child.get(\"enfants/nom-autre-parent\")),\n cl(child.get(\"enfants/prenoms-autre-parent\"))]\n\n if ind_sexe == \"M\":\n pere_noms = ind_noms\n mere_noms = autre_noms\n else:\n pere_noms = autre_noms\n mere_noms = ind_noms\n\n return {\n 'ind_id': ind_id,\n\n 'sexe': sexe,\n 'civilite': get_civilite(sexe, True),\n 'nom': cl(child.get(\"enfants/enfant_nom\")),\n 'prenom': cl(child.get(\"enfants/enfant_prenoms\")),\n 'ddn': ddn,\n 'loc_naissance': lieu_naissance,\n 'sit_mat': \"\",\n 'nom_pere': pere_noms[0],\n 'prenom_pere': pere_noms[1],\n 'nom_mere': mere_noms[0],\n 'prenom_mere': mere_noms[1],\n 'relation': \"E\",\n }\n","repo_name":"yeleman/anam-desktop","sub_path":"anamdesktop/dbimport/personnes.py","file_name":"personnes.py","file_ext":"py","file_size_in_byte":10082,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"31566692274","text":"import tkinter as tk\nfrom tkinter import ttk\n\n\nwindow = tk.Tk()\nwindow.title('Frames and parenting')\nwindow.geometry('600x400')\n\n\n#frames\nframe = ttk.Frame(window, width = 200, height = 200, borderwidth = 10, relief = tk.GROOVE)\n#This line makes it that the border of the frame doesnt shrink to the size of the widgets in it, Default = True\nframe.pack_propagate(False)\nframe.pack(side ='left')\n\n\n#parenting\nlabel = ttk.Label(frame, text= 'Label in frame')\nlabel.pack()\n\nbutton = ttk.Button(frame,text = 'Button in a Frame')\nbutton.pack()\n\n\nlabel2 = ttk.Label(window, text= 'Label out of frame')\nlabel2.pack()\n\n#exercise\nframe2 = ttk.Frame(window, width = 200, height = 200, borderwidth = 10, relief = tk.GROOVE)\n#This line makes it that the border of the frame doesnt shrink to the size of the widgets in it, Default = True\nframe2.pack_propagate(False)\nframe2.pack(side ='right')\n\nlabel3 = ttk.Label(frame2, text= 'Label in frame')\nlabel3.pack()\n\nbutton2 = ttk.Button(frame2,text = 'Button in a Frame')\nbutton2.pack()\n\nentry = ttk.Entry(frame2,text = 'Button in a Frame')\nentry.pack()\n\n\n\nwindow.mainloop()","repo_name":"AuroGx/Gui_experiment","sub_path":"11_gui.py","file_name":"11_gui.py","file_ext":"py","file_size_in_byte":1105,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"22507127182","text":"# Define here the models for your scraped items\n#\n# See documentation in:\n# http://doc.scrapy.org/en/latest/topics/items.html\n\nfrom scrapy.item import Item, Field\n\nclass Job(Item):\n '''\n Represent a Job object from Hasjob board.\n '''\n source = Field()\n title = Field()\n companyName = Field()\n companyURL = Field()\n companyLogo = Field()\n companyDetails = Field()\n description = Field()\n location = Field()\n postedDate = Field()\n jobPerks = Field()\n","repo_name":"tanwanirahul/hasjob-scrapper","sub_path":"hasjobs/items.py","file_name":"items.py","file_ext":"py","file_size_in_byte":491,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"971285951","text":"import time\nimport requests\nfrom requests.adapters import HTTPAdapter\n\n\n# https://www.cnblogs.com/gl1573/p/10129382.html\n\nsession = requests.Session()\nsession.mount('http://', HTTPAdapter(max_retries=3))\nsession.mount('https://', HTTPAdapter(max_retries=3))\n\nprint(time.strftime('%Y-%m-%d %H:%M:%S'))\ntry:\n r = session.get('https://www.cnblogs.com/gl1573/p/10129382.html', timeout=5)\n print(r.text)\nexcept requests.exceptions.RequestException as e:\n print(e)\n\nprint(time.strftime('%Y-%m-%d %H:%M:%S'))\n","repo_name":"MrRobot5/python-snippet","sub_path":"mysite/m3u8/request_retry_tester.py","file_name":"request_retry_tester.py","file_ext":"py","file_size_in_byte":511,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"14018990977","text":"from turtle import Turtle\r\n\r\n# state name written at its location on the map\r\nclass StateName(Turtle):\r\n\r\n def __init__(self, name):\r\n super().__init__()\r\n self.color(\"black\")\r\n self.penup()\r\n self.hideturtle()\r\n self.write(f\"{name}\", font=(\"Times New Roman\", 8, \"normal\"))\r\n\r\n def move(self, x, y):\r\n self.goto(x, y)","repo_name":"rummeltf/states_game.py","sub_path":"us-states-game-start/state_name.py","file_name":"state_name.py","file_ext":"py","file_size_in_byte":365,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"13257618763","text":"import sys\n\nfrom mycrypto import *\n\n\ndef encrypt_data(data, base, power, mod):\n return [byte * modular_exponentiation(base, power, mod) % mod for byte in data]\n\n\ndef write_bytes_to_file(data, file_name):\n file = open(file_name, \"wb\")\n\n for byte in data:\n file.write(byte.to_bytes(1, sys.byteorder))\n\n\np = generate_sophie_germain(1 << 8, 10 ** 9)\ng = generate_primitive_root(p)\n\n# приватный ключ\ncb = random.randrange(1, p)\n\n# открытый ключ\ndb = modular_exponentiation(g, cb, p)\n\nk = random.randrange(1, p - 2)\nr = modular_exponentiation(g, k, p)\n\nprint(f'p = {p}\\ng = {g}\\ncb = {cb}\\tdb = {db}')\n\norig_data = open('data/image.jpg', 'rb').read()\n\n# шифрование\nencrypted = encrypt_data(orig_data, db, k, p)\n\n\nopen('data/image_encrypted.jpg', 'w').write(str(encrypted))\n\n\n# расшифровка\ndecrypted = encrypt_data(encrypted, r, p - 1 - cb, p)\nwrite_bytes_to_file(decrypted, 'data/image_decrypted.jpg')\n","repo_name":"RipeCherries/information-protection","sub_path":"lab2/elgamal.py","file_name":"elgamal.py","file_ext":"py","file_size_in_byte":958,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"71592820104","text":"# Speeding Up Motif Finding\n\nfrom .helpers import Parser\n\n\ndef kmp_preprocess(seq):\n \"\"\"KMP preprocessing algorithm\"\"\"\n j = -1\n b = [j]\n for i in range(len(seq)):\n while j >= 0 and seq[i] != seq[j]:\n j = b[j]\n j += 1\n b.append(j)\n return b[1:]\n\n\ndef main(file):\n seq = Parser(file).fastas()[0].seq\n print(*kmp_preprocess(seq))\n","repo_name":"danhalligan/rosalind.info","sub_path":"rosalind/bioinformatics_stronghold/kmp.py","file_name":"kmp.py","file_ext":"py","file_size_in_byte":380,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"81"} +{"seq_id":"5220915669","text":"from rest_framework import serializers\nfrom .models import (InstagramUser, ImageUrl, InstagramStory)\nfrom django.core.exceptions import ValidationError\n\n\nclass InstagramUserSerializer(serializers.ModelSerializer):\n\n class Meta:\n model \t= InstagramUser\n fields \t= '__all__'\n\nclass ImageUrlSelrializer(serializers.ModelSerializer):\n\t''' Serializer for the purpuse of excluding the 'id' form the nested fields. '''\n\tclass Meta:\n\t\tmodel \t= ImageUrl\n\t\texclude = ['id',]\n\nclass InstagramStorySerializer(serializers.ModelSerializer):\n\n\timage_urls \t= ImageUrlSelrializer(many=True, read_only=True)\n\n\tclass Meta:\n\t\tmodel \t= InstagramStory\n\t\tfields = [\n\t\t\t'image_urls',\n\t\t\t'upload_date',\n\t\t]\n\t\tdepth \t= 1\n\nclass CreateInstagramStorySerializer(serializers.ModelSerializer):\n\n\tclass Meta:\n\t\tmodel \t= InstagramStory\n\t\tfields \t= [\n\t\t\t'username',\n\t\t\t'upload_date',\n\t\t]\n\nclass CreateInstagramStoryUrlSerializer(serializers.ModelSerializer):\n\tusername \t= serializers.CharField(required=True, allow_blank=False)\n\tupload_date = serializers.CharField(required=True, allow_blank=False)\n\timage_url \t= serializers.URLField(required=True, max_length=300)\n\tupload_time = serializers.CharField(required=True, allow_blank=False)\n\n\tclass Meta:\n\t\tmodel \t= InstagramStory\n\t\tfields \t= [\n\t\t\t'username',\n\t\t\t'upload_date',\n\t\t\t'image_url',\n\t\t\t'upload_time',\n\t\t]\n\n\tdef validate(self, data):\n\t\tusername \t= data[\"username\"]\n\t\tupload_date = data[\"upload_date\"]\n\t\timage_url \t= data[\"image_url\"]\n\t\tupload_time = data[\"upload_time\"]\n\t\tqueryset = InstagramStory.objects.all()\n\n\t\tif not queryset.filter(username=username).exists():\n\t\t\traise ValidationError(\"Username does not exist.\")\n\t\telif not queryset.filter(upload_date=upload_date).exists():\n\t\t\traise ValidationError(\"Date is not valid.\")\n\n\t\tinstagram_story = None\n\t\tinstagram_story = InstagramStory.objects.get(username=username, upload_date=upload_date)\n\n\t\tif instagram_story is None:\n\t\t\traise ValidationError(\"The username and upload_date combination is incorrect.\")\n\n\t\timage = ImageUrl()\n\t\timage.image_url = image_url\n\t\timage.upload_time = upload_time\n\t\timage.save()\n\t\tinstagram_story.image_urls.add(image)\n\t\tinstagram_story.save()\n\n\t\treturn data\n","repo_name":"RUGSoftEng/2018-JuicyStory","sub_path":"back-end/application/database/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":2173,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"22221777540","text":"from typing import Iterator, Tuple, List, Callable, Dict, Union\nfrom pathlib import Path\nfrom asyncio import Queue\nfrom aiofiles import open as aiofiles_open\nfrom .upload_utils import STOP_SIGNAL\nfrom .upload_settings import AppConfig\n\n\ndef chunkify(file_name_raw: str,\n file_end: int,\n size: int) -> Iterator[Tuple]:\n \"\"\" Return a new chunk \"\"\"\n with open(file_name_raw, 'rb') as file:\n chunk_end = file.tell()\n while True:\n chunk_start = chunk_end\n file.seek(size, 1)\n file.readline()\n chunk_end = file.tell()\n if chunk_end > file_end:\n chunk_end = file_end\n yield chunk_start, chunk_end - chunk_start\n break\n else:\n yield chunk_start, chunk_end - chunk_start\n\n\nasync def reader_file(config: AppConfig,\n queue_input: Queue,\n positions: List[Tuple],\n logger):\n errors = 0\n filename = config.input_file\n # how to convert list of strings in utf-8 from file\n convert_function: Callable = config.operations.converter_raw_function\n if Path(filename).exists():\n async with aiofiles_open(str(filename), mode='rb') as file:\n for chunk_start, chunk_size in positions:\n await file.seek(chunk_start)\n _lines = await file.read(chunk_size)\n try:\n lines = _lines.decode('utf-8').splitlines()\n except Exception as exp:\n errors += 1\n logger.error(f'error lines, start:{chunk_start}, size:{chunk_size}')\n logger.error(exp)\n async with aiofiles_open('errors.data', 'ab') as error_file:\n await error_file.write(_lines)\n await error_file.write('b\\n')\n else:\n config.statistics['all_records'] += len(lines)\n records: List[Dict] = convert_function(lines=lines)\n await queue_input.put(records)\n logger.info(f'errors:{errors}')\n await queue_input.put(STOP_SIGNAL)\n else:\n logger.error(f'{filename} - not found')\n await queue_input.put(STOP_SIGNAL)\n\n\nasync def reader_file_from_memory(config: AppConfig,\n queue_input: Queue,\n blocks: Union[List[List[str]], Iterator],\n logger):\n errors = 0\n convert_function: Callable = config.operations.converter_raw_function\n for lines in blocks:\n config.statistics['all_records'] += len(lines)\n try:\n records: List[Dict] = convert_function(lines=lines)\n await queue_input.put(records)\n except Exception as exp:\n errors += 1\n logger.error(f'error lines:...')\n logger.error(exp)\n async with aiofiles_open('errors.data', 'at') as error_file:\n await error_file.write('\\n'.join(lines))\n await error_file.write('b\\n')\n\n await queue_input.put(STOP_SIGNAL)\n","repo_name":"JohnEskimSmith/export-elasticmq","sub_path":"lib/upload_files_utils.py","file_name":"upload_files_utils.py","file_ext":"py","file_size_in_byte":3160,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"81"} +{"seq_id":"21898390945","text":"import equip\n\n#all equip arr\narmor_arr = []\nweapon_arr = []\nbots_arr = []\namulet_arr = []\n\n#create common equip\nclass CommonArmor(equip.Armor):\n\tname = \"Common Armor\"\n\tdefense = 3\n\thp = 20\n\tprice = 10\n\t\nclass CommonWeapon(equip.Weapon):\n\tname = \"Common Weapon\"\n\tdamage = 4\n\tprice = 10\n\t\nclass CommonBots(equip.Bots):\n\tname = \"Common Bots\"\n\tdodge = 3\n\tprice = 10\n\t\nclass CommonAmulet(equip.Amulet):\n\tname = \"Common Amulet\"\n\thp_recovery = 10\n\tprice = 10\n\t\n#add equip\narmor_arr.append(CommonArmor)\nweapon_arr.append(CommonWeapon)\nbots_arr.append(CommonBots)\namulet_arr.append(CommonAmulet)\n\n\n#create uncommon equip\nclass UncommonArmor(equip.Armor):\n\tname = \"Uncommon Armor\"\n\tdefense = 7\n\thp = 35\n\tprice = 25\n\t\nclass UncommonWeapon(equip.Weapon):\n\tname = \"Uncommon Weapon\"\n\tdamage = 8\n\tprice = 25\n\t\nclass UncommonBots(equip.Bots):\n\tname = \"Uncommon Bots\"\n\tdodge = 6\n\tprice = 25\n\t\nclass UncommonAmulet(equip.Amulet):\n\tname = \"Uncommon Amulet\"\n\thp_recovery = 15\n\tprice = 25\n\t\n#add equip\narmor_arr.append(UncommonArmor)\nweapon_arr.append(UncommonWeapon)\nbots_arr.append(UncommonBots)\namulet_arr.append(UncommonAmulet)\n\n\n#create Epic equip\nclass EpicArmor(equip.Armor):\n\tname = \"Epic Armor\"\n\tdefense = 10\n\thp = 50\n\tprice = 40\n\t\nclass EpicWeapon(equip.Weapon):\n\tname = \"Epic Weapon\"\n\tdamage = 12\n\tprice = 40\n\t\nclass EpicBots(equip.Bots):\n\tname = \"Epic Bots\"\n\tdodge = 10\n\tprice = 40\n\t\nclass EpicAmulet(equip.Amulet):\n\tname = \"Epic Amulet\"\n\thp_recovery = 25\n\tprice = 40\n\t\n#add equip\narmor_arr.append(EpicArmor)\nweapon_arr.append(EpicWeapon)\nbots_arr.append(EpicBots)\namulet_arr.append(EpicAmulet)\n\n\n#create Legendary equip\nclass LegendaryArmor(equip.Armor):\n\tname = \"Legendary Armor\"\n\tdefense = 15\n\thp = 100\n\tprice = 75\n\t\nclass LegendaryWeapon(equip.Weapon):\n\tname = \"Legendary Weapon\"\n\tdamage = 20\n\tprice = 75\n\t\nclass LegendaryBots(equip.Bots):\n\tname = \"Legendary Bots\"\n\tdodge = 18\n\tprice = 75\n\t\nclass LegendaryAmulet(equip.Amulet):\n\tname = \"Legendary Amulet\"\n\thp_recovery = 40\n\tprice = 75\n\t\n#add equip\narmor_arr.append(LegendaryArmor)\nweapon_arr.append(LegendaryWeapon)\nbots_arr.append(LegendaryBots)\namulet_arr.append(LegendaryAmulet)\n","repo_name":"THEDAN320/Rpg_game","sub_path":"rpg_game.1/equip_for_shop.py","file_name":"equip_for_shop.py","file_ext":"py","file_size_in_byte":2127,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"34736034051","text":"import cv2\nimport numpy as np\nimport tensorflow as tf\n\n\ndef initialise_model():\n json_file = open(\"./model/model.json\", \"r\")\n loaded_model_json = json_file.read()\n json_file.close()\n model = tf.keras.models.model_from_json(loaded_model_json)\n model.load_weights(\"./model/weights.h5\")\n return model\n\n\n# We are assuming that the largest contour of the image is the sudoku board's border\ndef largest_contour(contours):\n large_contour = None\n max_area = 1000\n\n for contour in contours:\n contour_area = cv2.contourArea(contour)\n contour_perimeter = cv2.arcLength(contour, closed=True)\n approximate_polygon = cv2.approxPolyDP(\n contour, 0.02 * contour_perimeter, closed=True\n )\n if len(approximate_polygon) == 4 and contour_area > max_area:\n large_contour = approximate_polygon\n max_area = contour_area\n\n if large_contour is not None:\n large_contour = organise_corners(large_contour)\n\n return large_contour\n\n\n# Organise the corners anti-clockwise for perspective transformation\ndef organise_corners(sudoku_contour):\n sudoku_contour = sudoku_contour.reshape((4, 2))\n\n # Create an empty array which we will set the corner points to in the right order\n organised_corners = np.zeros((4, 1, 2), dtype=np.int32)\n\n add = sudoku_contour.sum(1)\n # Bottom Left\n # Has smallest (x + y) value\n organised_corners[0] = sudoku_contour[np.argmin(add)]\n # Top Right\n # Has largest (x + y) value\n organised_corners[3] = sudoku_contour[np.argmax(add)]\n\n diff = np.diff(sudoku_contour, axis=1)\n # Top Left\n # Has smallest (x - y) value\n organised_corners[1] = sudoku_contour[np.argmin(diff)]\n # Bottom Right\n # Has smallest (x - y) value\n organised_corners[2] = sudoku_contour[np.argmax(diff)]\n\n return organised_corners\n\n\n# Apply perspective transformation so only the sudoku board is displayed on the image\ndef warp_image(image, organised_corners, image_width, image_height):\n # Input and output points are now in right order (in an anti-clockwise direction)\n input_points = np.float32(organised_corners)\n output_points = np.float32(\n [\n [0, 0],\n [image_width - 1, 0],\n [0, image_height - 1],\n [image_width - 1, image_height - 1],\n ]\n )\n\n transformation_matrix = cv2.getPerspectiveTransform(input_points, output_points)\n output_image = cv2.warpPerspective(\n image, transformation_matrix, (image_width, image_height)\n )\n return output_image\n\n\n# axis=0 for vertical axis, axis=1 for horizontal axis\ndef get_lines(image, axis):\n # Specify size on vertical/horizontal axis\n rows = image.shape[axis]\n # 10 horizontal and vertical lines on a sudoku grid (includes border)\n line_size = rows // 10\n\n # Create structure element for extracting vertical/horizontal lines through morphology operations\n if axis == 0:\n line_structure = cv2.getStructuringElement(cv2.MORPH_RECT, (1, line_size))\n else:\n line_structure = cv2.getStructuringElement(cv2.MORPH_RECT, (line_size, 1))\n\n # Apply morphology operations\n image = cv2.erode(image, line_structure)\n image = cv2.dilate(image, line_structure)\n return image\n\n\n# https://opencv24-python-tutorials.readthedocs.io/en/latest/py_tutorials/py_imgproc/py_houghlines/py_houghlines.html\ndef hough_line_transform(grid):\n # If rho is any larger some lines come out angled, which is not what we want.\n hough_lines = cv2.HoughLines(grid, 0.3, np.pi / 90, 150)\n\n # Remove axes of length 1\n hough_lines = np.squeeze(hough_lines)\n\n if len(hough_lines.shape) < 2:\n\n return None\n\n else:\n\n for rho, theta in hough_lines:\n # find out where the line stretches to and draw them\n a = np.cos(theta)\n b = np.sin(theta)\n x0 = a * rho\n y0 = b * rho\n x1 = int(x0 + 1000 * (-b))\n y1 = int(y0 + 1000 * a)\n x2 = int(x0 - 1000 * (-b))\n y2 = int(y0 - 1000 * a)\n\n # Draws a line of thickness four and colour white on the image\n cv2.line(grid, (x1, y1), (x2, y2), (255, 255, 255), 3)\n\n # We need to invert grid, so we can add the grid and preprocessed warp image together\n # Doing so removes the grid lines (so we only have the numbers)\n inverted_grid = cv2.bitwise_not(grid)\n return inverted_grid\n\n\n# Splits sudoku grid into 81 evenly sized boxes\ndef split_image_boxes(number_image):\n boxes = list()\n # Splits image into 9 evenly sized columns\n cols = np.vsplit(number_image, 9)\n for col in cols:\n # Splits column into 9 evenly sized rows (9 boxes)\n rows = np.hsplit(col, 9)\n for row in rows:\n # Add each box to the list of boxes\n boxes.append(row)\n return boxes\n\n\n# Cleans the images (ie makes boxes with no numbers completely black and centers boxes with numbers)\ndef clean_number_images(images):\n clean_boxes = list()\n for image in images:\n height, width = image.shape\n mid = width // 2\n if number_image_check(image, height, width, mid):\n clean_boxes.append(False) # Sets it to False if not a number\n else:\n # Center the number in the box\n contours, _ = cv2.findContours(\n image, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE\n )\n contours = sorted(contours, key=cv2.contourArea, reverse=True)\n x, y, w, h = cv2.boundingRect(contours[0])\n\n start_x = (width - w) // 2\n start_y = (height - h) // 2\n\n # Removes all noise from the box (leaving just the number)\n new_image = np.zeros_like(image)\n new_image[start_y : start_y + h, start_x : start_x + w] = image[\n y : y + h, x : x + w\n ]\n\n clean_boxes.append(new_image)\n\n return clean_boxes\n\n\ndef get_num_clues(images):\n counter = 0\n for image in images:\n if type(image) is not bool:\n counter += 1\n return counter\n\n\n# Checks where the box contains a number or not\ndef number_image_check(image, height, width, mid):\n # Checks that the majority of the image is black\n if np.isclose(image, 0).sum() / (image.shape[0] * image.shape[1]) >= 0.95:\n return True\n # Checks that the majority of the center of the image is black\n elif (\n np.isclose(image[:, int(mid - width * 0.4) : int(mid + width * 0.4)], 0).sum()\n / (2 * width * 0.4 * height)\n >= 0.925\n ):\n return True\n # If it reaches here then we know that the box must contain a number\n else:\n return False\n\n\n# Resizes the image so that they are the correct shape for the CNN\ndef resize_number_images(images, dimension):\n new_images = list()\n for image in images:\n if type(image) is not bool:\n # Image is resized\n image = cv2.resize(image, (dimension, dimension))\n\n # Image is reshaped so it can be passed into CNN\n image = np.reshape(image, (1, dimension, dimension, 1))\n new_images.append(image)\n else:\n new_images.append(False)\n return new_images\n\n\n# Gets all the numbers for the sudoku puzzle\ndef get_sudoku(images, model):\n sudoku = str()\n checker = list()\n # Appends nine lists of nine numbers to the sudoku list\n for j in range(0, len(images), 9):\n sudoku_row = list()\n start = j\n stop = j + 9\n for i in range(start, stop):\n if type(images[i]) is not bool:\n # Predicts what the digit is using the CNN\n prediction = model.predict(images[i])\n prediction_value = np.argmax(prediction)\n sudoku += str(prediction_value + 1)\n sudoku_row.append(str(prediction_value + 1))\n else:\n sudoku += str(0)\n sudoku_row.append(str(0))\n checker.append(sudoku_row)\n return sudoku, checker\n\n\n# Overlay the solution found on the warped image\ndef overlay_solution(image, solved_puzzle, initial_puzzle, dimension, text_colour):\n for y in range(len(solved_puzzle)):\n for x in range(len(solved_puzzle[y])):\n # Check to make sure the number wasn't already on the sudoku board\n if initial_puzzle[y][x] == \"0\":\n number = solved_puzzle[y][x]\n\n # Retrieves the corners and center of the box\n top_left = (x * dimension, y * dimension)\n bottom_right = ((x + 1) * dimension, (y + 1) * dimension)\n center = (\n (top_left[0] + bottom_right[0]) // 2,\n (top_left[1] + bottom_right[1]) // 2,\n )\n\n # Calculates the size and position of there the number will go in the box\n text_size, _ = cv2.getTextSize(\n number, cv2.FONT_HERSHEY_SIMPLEX, 0.75, 4\n )\n text_position = (\n center[0] - text_size[0] // 2,\n center[1] + text_size[1] // 2,\n )\n\n # Adds number to the right box on the board\n cv2.putText(\n image,\n number,\n text_position,\n cv2.FONT_HERSHEY_COMPLEX_SMALL,\n 2,\n text_colour,\n 2,\n )\n return image\n\n\ndef unwarp_image(\n sudoku_solution_image,\n original_image,\n corners,\n overlay_width,\n overlay_height,\n original_width,\n original_height,\n):\n # Input and output points are now in right order (in an anti-clockwise direction)\n input_points = np.float32(corners)\n output_points = np.float32(\n [\n [0, 0],\n [overlay_width - 1, 0],\n [0, overlay_height - 1],\n [overlay_width - 1, overlay_height - 1],\n ]\n )\n\n # Applies the inverse transformation\n transformation_matrix = cv2.getPerspectiveTransform(input_points, output_points)\n unwarped = cv2.warpPerspective(\n sudoku_solution_image,\n transformation_matrix,\n (original_height, original_width),\n flags=cv2.WARP_INVERSE_MAP,\n )\n\n # Combines the original and unwarped image to get the final result\n final_result = np.where(\n unwarped.sum(axis=-1, keepdims=True) != 0, unwarped, original_image\n )\n\n return final_result\n","repo_name":"michaelwoodsy/Augmented-Reality-Sudoku-Solver","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":10528,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"2500763454","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\ndef add_intercept(X_):\n m, n = X_.shape\n X = np.zeros((m, n + 1))\n X[:, 0] = 1\n X[:, 1:] = X_\n return X\n\n\ndef load_data(filename):\n D = np.loadtxt(filename)\n Y = D[:, 0]\n X = D[:, 1:]\n return add_intercept(X), Y\n\n\ndef calc_grad(X, Y, theta):\n m, n = X.shape\n grad = np.zeros(theta.shape)\n\n margins = Y * X.dot(theta)\n probs = 1. / (1 + np.exp(margins))\n grad = -(1. / m) * (X.T.dot(probs * Y))\n\n return grad\n\n\ndef cal_loss(X, Y, theta):\n margins = Y * X.dot(theta)\n probs = 1. / (1 - np.exp(margins))\n return -np.sum(probs)\n\n\ndef display(X, Y, theta):\n plt.scatter(x=X[:, 1][Y == 1], y=X[:, 2][Y == 1], c='r', marker='o')\n plt.scatter(x=X[:, 1][Y == -1], y=X[:, 2][Y == -1], c='b', marker='x')\n x = np.linspace(0,1,100)\n plt.plot(x, -(theta[1] * x + theta[0]) / theta[2])\n plt.show()\n\n\ndef logistic_regression(X, Y):\n m, n = X.shape\n theta = np.zeros(n)\n # learning_rate = 1\n learning_rate = 50\n\n diffs = []\n\n i = 0\n while True:\n i += 1\n prev_theta = theta\n grad = calc_grad(X, Y, theta)\n theta = theta - learning_rate * (grad)\n\n diff = np.linalg.norm(prev_theta - theta)\n if i % 10000 == 0:\n p = cal_loss(X, Y, theta)\n print('Finished %d iterations' % i)\n diffs.append(diff)\n if diff < 1e-15:\n print('Converged in %d iterations' % i)\n break\n return\n\n\ndef main():\n # print('==== Training model on data set A ====')\n # Xa, Ya = load_data('data_a.txt')\n # logistic_regression(Xa, Ya)\n\n print('\\n==== Training model on data set B ====')\n Xb, Yb = load_data('data_b.txt')\n logistic_regression(Xb, Yb)\n\n return\n\n\n# def display_a():\n# plt.scatter(x=Xa[:, 1][Ya == 1], y=Xa[:, 2][Ya == 1], c='r', marker='o')\n# plt.scatter(x=Xa[:, 1][Ya == -1], y=Xa[:, 2][Ya == -1], c='b', marker='x')\n# plt.show()\n#\n#\n# def display_b():\n# plt.scatter(x=Xb[:, 1][Yb == 1], y=Xb[:, 2][Yb == 1], c='r', marker='o')\n# plt.scatter(x=Xb[:, 1][Yb == -1], y=Xb[:, 2][Yb == -1], c='b', marker='x')\n# plt.show()\n\nif __name__ == '__main__':\n main()\n","repo_name":"bounceQSF/cs229","sub_path":"ps2/ps2-1.py","file_name":"ps2-1.py","file_ext":"py","file_size_in_byte":2213,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"27175043920","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\nimport math\n\n# Length of array(number of elements in array)\n# is simple algorithm\n# Iterates through array\n# at each iteration (count) variable\n# is incremented\n# \n# This solution is ideal for small array\n# But not that good for bigger array's\n\n# There are many ways to do same thing\n# but always go with solution that is\n# simple, and has least instructions\n# for computer to execute, making\n# process faster\n\n# is_ap parameter indicates weather array\n# is an arithmetic progression or not\n#\n# Similarly, \n# is_gp indicates weather array is an geometric progression or not\n# If array is either ap or gp then it's length can be\n# found by derivation of it's general term formula\n# e.g. ap's general term,\n# tn = a + (n - 1)d\n# thus, n = (tn - a) / d + 1 \n\ndef length(ar, is_ap = False, is_gp = False, big_data = False, data_outline = []):\n\t# Length of data if it is an arithmetic progression\n\t# using derived formula, n = (tn - a) / d + 1\n\tif is_ap:\n\t\treturn ((ar[-1] - ar[0]) / (ar[1] - ar[0])) + 1\n\n\t# Length of data if it is an geometric progression\n\t# using derived formula, n = ((log base 10 an / a1) / log 10 r) + 1\n\telif is_gp:\n\t\t# length is never a float\n\t\treturn int(math.log10((ar[-1] / ar[0])) / math.log10((ar[1] / ar[0])) + 1)\n\n\t# Length of big data using data outline\n\t# data outline is selective elements to be counted from entire\n\t# data\n\telif big_data:\n\t\tcount = 0\n\t\tfor element in data_outline:\n\t\t\tcount += ar.count(element)\n\t\treturn count \n\t\n\t# Sequential counting\n\t# of elements in array\n\telse:\n\t\tres = 0\n\t\tfor item in ar:\n\t\t\tres += 1\n\t\treturn res \n\t\t\n\n# Test\n# Geometric progression Test\nif length([1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096], None, is_gp = True) == 13:\n\tprint(\"\\nLength of geometric progression: \" + str(13))\n\tprint(\"--> geometric progression counting works!\\n\")\nelse:\n\tprint(\"Something's wrong with gp feature\")\n\n# Arithmetic progression test\nif length([1, 4, 7, 10, 13, 16, 19, 22, 25, 28, 31, 34, 37, 40, 43], is_ap = True) == 15:\n\tprint(\"Length of arithmetic progression: \" + str(15))\n\tprint(\"--> arithmetic progression counting works!\\n\")\nelse:\n\tprint(\"Something's wrong with ap feature\")\n\n# Big data test\n# Passing only useful numbers in outline array\nif length([1, 1, 4, 5, 7, 1, 9, 5, 2, 4, 3, 5, 9], None, None, True, [1, 4, 5, 7, 9]) == 11:\n\tprint(\"Length of arithmetic progression: \" + str(11))\n\tprint(\"--> big data counting works!\\n\")\nelse:\n\tprint(\"Something's wrong with ap feature\")\n\n# Small data\nprint(\"Length: \" + str(length([1, 1, 2, 3, 5, 8, 13, 21, 34, 55])))\nprint(\"Everything Works!\\n\")\n","repo_name":"zeta-punk-x1/Beginners-Python-Examples","sub_path":"algorithms/analysis/length.py","file_name":"length.py","file_ext":"py","file_size_in_byte":2606,"program_lang":"python","lang":"en","doc_type":"code","stars":247,"dataset":"github-code","pt":"81"} +{"seq_id":"70355034824","text":"import time\nimport cv2 as cv\nimport os\nimport numpy as np\n\nclass BBox:\n confidence = 1.0\n\n def __init__(self, classId, x1, y1, x2, y2, w, h, confidence=1.0, mask=None, mask2=None):\n self.classId = int(classId)\n self.w = w\n self.h = h\n self.box = (x1, y1, x2, y2)\n self.confidence = confidence\n self.mask = mask\n self.mask2 = mask2\n\n def getYolo(self):\n x1, y1, x2, y2 = self.box\n x = (x1 + x2) / (2.0 * (self.w or 1))\n y = (y1 + y2) / (2.0 * (self.h or 1))\n w = (x2 - x1) / float(self.w)\n h = (y2 - y1) / float(self.h)\n\n return f\"{self.classId} {x} {y} {w} {h}\"\n\n def __repr__(self):\n return f\"class={self.classId} box={self.box}\"\n\n def show(self, frame, truth=True):\n cls = self.classId # int(box.cls[0])\n if truth:\n color = (255, 0, 0)\n else:\n color = (255, 255, 255)\n if cls == 81:\n color = (0, 0, 255)\n\n confidence = round(self.confidence * 100)\n if truth:\n label = f\"{cls}\"\n else:\n label = f\"{cls} {confidence:02}%\"\n fsize, _ = cv.getTextSize(label, cv.FONT_HERSHEY_SIMPLEX, 1.0, 2)\n fw, fh = fsize\n delta = 2\n\n x1, y1, x2, y2 = map(int, self.box)\n cv.rectangle(frame, (x1, y1), (x2, y2), color, 2, lineType=cv.LINE_AA)\n\n top = y1\n if truth:\n top = y2 + fh + 2 * delta\n\n cv.rectangle(frame, (x1, top - fh - 2 * delta), (x2, top), color, -1)\n\n cv.putText(\n frame,\n label,\n (x1, top - delta),\n 0,\n 0.9,\n (0, 0, 0),\n 2,\n lineType=cv.LINE_AA,\n )\n\n def show_mask(self, mask_img):\n color = (0,255,0)\n x1, y1, x2, y2 = map(int, self.box)\n crop_mask = self.mask[y1:y2, x1:x2, np.newaxis]\n crop_mask_img = mask_img[y1:y2, x1:x2]\n crop_mask_img = crop_mask_img * (1 - crop_mask) + crop_mask * color\n mask_img[y1:y2, x1:x2] = crop_mask_img\n\n def show_mask2(self, frame):\n return cv.addWeighted(frame, 1.0, self.mask2, 0.5, 0) \n\nclass BBoxes:\n def __init__(self, truth=True, segmentation=False):\n self.bboxes = [] # bboxes\n self.id = time.time()\n self.truth = truth\n self.segmentation = segmentation\n\n def __repr__(self):\n result = [f\"bboxes={self.id}\"]\n for box in self.bboxes:\n result.append(str(box))\n return \"\\n\".join(result)\n\n def get(self):\n return self.bboxes\n\n def reset(self):\n self.bboxes = []\n\n def add(self, bbox: BBox):\n self.bboxes.append(bbox)\n\n def extend(self, bboxes):\n for box in bboxes:\n self.add(box)\n\n def has(self, classId):\n if not isinstance(classId, list):\n classId = [classId]\n for bbox in self.bboxes:\n if bbox.classId in classId:\n return True\n return False\n\n def hasOnly(self, classId):\n if not isinstance(classId, list):\n classId = [classId]\n for bbox in self.bboxes:\n # print(classId, bbox.classId, classId!=bbox.classId)\n if not bbox.classId in classId:\n return False\n return True\n\n def import_txt(self, txtfile, w, h, classes={}):\n if not os.path.exists(txtfile):\n return []\n data = open(txtfile).readlines()\n for obj in data:\n datas = [float(x) for x in obj.strip().split(\" \")]\n if len(datas) == 5: # yolo bounding boxes\n classId, xc, yc, wf, hf = datas\n wp = wf * w\n hp = hf * h\n x1 = xc * w - wp / 2\n y1 = yc * h - hp / 2\n self.bboxes.append(BBox(classId, x1, y1, x1 + wp, y1 + hp, w, h))\n else:\n pass #print(\"yolo segmentation\")\n return self.bboxes\n\n def draw(self, frame, mask_alpha=0.4):\n for box in self.bboxes:\n box.show(frame, self.truth)\n if self.segmentation:\n masked = frame.copy()\n #masked = cv.cvtColor(frame, cv.COLOR_BGR2BGRA)\n mask2 = False\n for box in self.bboxes:\n if box.mask is not None:\n #print(\"masked=\", masked.shape, \"mask=\", box.mask.shape)\n box.show_mask(masked)\n if box.mask2 is not None:\n masked = box.show_mask2(masked)\n mask2 = True\n if mask2:\n return masked\n else:\n return cv.addWeighted(masked, mask_alpha, frame, 1 - mask_alpha, 0)\n return frame\n\n def merge(self, bboxes_in, filter_classes):\n \"\"\"\n add to self.bboxes bboxes_in if bbox is in filter_classes replacing those in self\n\n \"\"\"\n bboxes_result = BBoxes()\n\n # non abbiamo nulla da aggiungere\n if not filter_classes:\n return bboxes_in\n\n # rimuoviamo tutti i bbox che sono in filter_classes perchè quelli in bboxes_in sono prioritari\n for bbox in self.bboxes:\n if not bbox.classId in filter_classes:\n bboxes_result.add(bbox)\n\n # aggiungiamo quelli in bboxes_in se appartengono a filter_class\n for bbox_in in bboxes_in.bboxes:\n if bbox_in.classId in filter_classes:\n bboxes_result.add(bbox_in)\n\n return bboxes_result\n\n def save(self, frame, filename, path, include=[]):\n if not os.path.exists(path):\n os.makedirs(path)\n\n basename = os.path.basename(filename).split(\".\")[0]\n\n classes_txt = os.path.join(path, \"classes.txt\")\n if not os.path.exists(classes_txt):\n with open(classes_txt, \"w\") as f:\n f.write(\"\\n\".join([str(c) for c in include]))\n\n filename_new = os.path.join(path, basename + \".txt\")\n filename_jpg = os.path.join(path, basename + \".jpg\")\n with open(filename_new, \"w\") as f:\n log.info(\"save to %s\", filename_new)\n for bbox in self.bboxes:\n if not include or bbox.classId in include:\n f.write(bbox.getYolo() + \"\\n\")\n cv.imwrite(filename_jpg, frame, [cv.IMWRITE_JPEG_QUALITY, 100])\n","repo_name":"scipioni/yolorun","sub_path":"yolorun/lib/bboxes.py","file_name":"bboxes.py","file_ext":"py","file_size_in_byte":6318,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"81"} +{"seq_id":"18190917445","text":"import json\nimport datetime\nimport urllib\n\ndef load(thing):\n '''\n loads api into dictionary\n '''\n return json.loads(urllib.request.urlopen(thing).read())\n\ndef load_bypass(thing):\n '''\n loads api into dictionary while bypassing some security features\n '''\n req = urllib.request.Request(thing,headers={'User-Agent': 'Mozilla/5.0'})\n webpage = urllib.request.urlopen(req).read()\n return json.loads(webpage)\n\ndef horoscope(ss):\n '''\n generates horoscope information\n '''\n d = {}\n\n requrl = \"http://horoscope-api.herokuapp.com/horoscope/today/\" + ss\n try:\n today = load(requrl)\n d[\"today\"] = today[\"horoscope\"]\n except:\n today = None\n\n requrl = \"http://horoscope-api.herokuapp.com/horoscope/week/\" + ss\n try:\n week = load(requrl)\n d[\"week\"] = week[\"horoscope\"]\n except:\n week = None\n\n requrl = \"http://horoscope-api.herokuapp.com/horoscope/month/\" + ss\n try:\n month = load(requrl)\n d[\"month\"] = month[\"horoscope\"]\n except:\n month = None\n\n requrl = \"http://horoscope-api.herokuapp.com/horoscope/year/\" + ss\n try:\n year = load(requrl)\n d[\"year\"] = year[\"horoscope\"]\n except:\n year = None\n\n ss = ss[0].upper() + ss[1:]\n\n t = ss + \" horoscope\"\n\n return {\"title\":t, \"dict\":d, \"sign\":ss}\n\ndef suntimeparse(s):\n '''\n generates horoscope suntime\n '''\n l = s.split(\"T\")\n s = l[1]\n s = str((int(s[:2]) - 5) % 12) + s[2:]\n l = s.split(\"+\")\n s = l[0]\n return s\n\ndef maincontent(x):\n '''\n generates other api information\n '''\n with open(\"keys.json\") as json_file:\n key_loc = json.load(json_file)\n my_dict = key_loc\n\n # location\n\n requrl = \"https://ipapi.co/json/\"\n if len(x) > 0:\n requrl = \"https://ipapi.co/{0}/json/\".format(x)\n try:\n d = load(requrl)\n lon = d[\"longitude\"]\n lat = d[\"latitude\"]\n currcity = d[\"city\"]\n currreg = d[\"region\"]\n regid = d[\"region_code\"]\n currcoun = d[\"country_name\"]\n counid = d[\"country\"]\n\n locationinfo = {\"currcity\":currcity, \"currreg\":currreg, \"currcoun\": currcoun}\n except:\n lon = 0\n lat = 0\n locationinfo = None\n\n # holidays\n\n requrl = \"https://www.calendarindex.com/api/v1/holidays/json?\"\n data = {}\n data[\"country\"] = counid\n data[\"year\"] = datetime.datetime.today().year\n data[\"state\"] = regid\n data[\"api_key\"] = my_dict[\"calendarindex\"]\n\n requrl += urllib.parse.urlencode(data)\n\n try:\n d = load_bypass(requrl)\n holidays = d[\"response\"][\"holidays\"]\n except:\n holidays = None\n\n # news\n\n requrl = \"https://newsapi.org/v2/top-headlines?\"\n data = {}\n data[\"country\"] = counid\n data[\"apiKey\"] = my_dict[\"newsapi\"]\n\n requrl += urllib.parse.urlencode(data)\n\n try:\n d = load(requrl)\n newsarticles = []\n for i in range(10):\n newsarticles.append([d[\"articles\"][i][\"url\"], d[\"articles\"][i][\"title\"].split(\" - \")[0]])\n except:\n newsarticles = None\n\n # weather\n\n requrl = \"https://api.darksky.net/forecast/\" + my_dict[\"darksky\"] + \"/\" + str(lat) + \",\" + str(lon)\n\n try:\n d = load(requrl)\n weatheralerts = []\n if \"alerts\" in d.keys():\n for alert in d[\"alerts\"]:\n weatheralerts.append([alert[\"title\"], alert[\"uri\"]])\n currentweather = d[\"minutely\"][\"summary\"]\n currtemp = d[\"currently\"][\"temperature\"]\n weekweather = d[\"daily\"][\"summary\"]\n except:\n weatheralerts = None\n currentweather = None\n weekweather = None\n currtemp = None\n\n # sunrise/sunset (today)\n\n requrl = \"https://api.sunrise-sunset.org/json?\"\n data = {}\n data[\"lat\"] = lat\n data[\"lng\"] = lon\n data[\"date\"] = datetime.date.today()\n data[\"formatted\"] = 0\n\n requrl += urllib.parse.urlencode(data)\n\n try:\n d = load(requrl)\n srisetoday = suntimeparse(d[\"results\"][\"sunrise\"])\n ssettoday = suntimeparse(d[\"results\"][\"sunset\"])\n except:\n srisetoday = None\n ssettoday = None\n\n # sunrise/sunset (tomorrow)\n\n requrl = \"https://api.sunrise-sunset.org/json?\"\n data = {}\n data[\"lat\"] = lat\n data[\"lng\"] = lon\n data[\"date\"] = datetime.date.today() + datetime.timedelta(days=1)\n data[\"formatted\"] = 0\n\n requrl += urllib.parse.urlencode(data)\n\n try:\n d = load(requrl)\n srisetmw = suntimeparse(d[\"results\"][\"sunrise\"])\n ssettmw = suntimeparse(d[\"results\"][\"sunset\"])\n except:\n srisetmw = None\n ssettmw = None\n\n # nasa imaging\n\n requrl = \"https://api.nasa.gov/planetary/earth/imagery/?\"\n data = {}\n data[\"lon\"] = lon\n data[\"lat\"] = lat\n data[\"dim\"] = \"0.2\"\n data[\"api_key\"] = my_dict[\"nasa\"]\n requrl += urllib.parse.urlencode(data)\n try:\n d = load(requrl)\n nasaimg = d[\"url\"]\n except:\n nasaimg = None\n\n # poems\n\n requrl = \"https://www.poemist.com/api/v1/randompoems\"\n try:\n d.load_bypass(requrl)\n\n poem = {\"title\":d[0][\"title\"], \"poet\":d[0][\"poet\"][\"name\"], \"poem\":d[0][\"content\"]}\n except:\n poem = None\n\n # place all api data into a dict\n\n d = {}\n d[\"currtime\"] = str(datetime.datetime.now().time())[:9]\n d[\"locationinfo\"] = locationinfo\n d[\"holidays\"] = holidays\n d[\"newsarticles\"] = newsarticles\n if weatheralerts != []:\n d[\"weatheralerts\"] = weatheralerts\n d[\"currentweather\"] = currentweather\n d[\"currenttemp\"] = currtemp\n d[\"weekweather\"] = weekweather\n d[\"srisetoday\"] = srisetoday\n d[\"ssettoday\"] = ssettoday\n d[\"srisetmw\"] = srisetmw\n d[\"ssettmw\"] = ssettmw\n d[\"nasaimg\"] = nasaimg\n d[\"poem\"] = poem\n\n return d\n","repo_name":"jason-tung/sd_p01","sub_path":"util/apiretrieve.py","file_name":"apiretrieve.py","file_ext":"py","file_size_in_byte":5804,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"29541124876","text":"from tkinter import E\nimport cv2\nimport chess.svg\nfrom chessboard import display\nfrom ChessPiece import *\nimport numpy as np\nfrom matplotlib import pyplot as plt\nimport json\nfrom time import time, sleep\nimport os\nimport glob\nfrom shapely.geometry import Point\nfrom shapely.geometry.polygon import Polygon\nimport copy\nimport argparse\nfrom getch import getch\nimport mediapipe as mp\n\nwhT = 320\nconf_threshold = 0.2\nnms_threshold = 0.5\n\n# Pauses the game on spacebar button press\ndef pause_game(pause_flag, pause_ctr):\n while True:\n try: \n key = getch()\n if ord(key) == 32:\n pause_ctr.value = (pause_ctr.value+1)%2\n if pause_ctr.value == 1:\n print(\"\\tGame paused\")\n pause_flag.value = 1\n else:\n print(\"\\tGame resumed\")\n pause_flag.value = 0 \n except KeyboardInterrupt:\n print(\"\\n\\tGame interrupted!\")\n\ndef get_chess_tiles(img, show = 0):\n if show == 1:\n # Display original image\n cv2.imshow('Original', img)\n cv2.waitKey(0)\n\n # Convert to graycsale\n img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n\n # Blur the image for better edge detection\n img_blur = cv2.GaussianBlur(img_gray, (3,3), 0)\n if show == 1:\n cv2.imshow('Blurred and gray-scaled', img_blur)\n cv2.waitKey(0)\n\n # Sobel Edge Detection\n sobelx = cv2.Sobel(src=img_blur, ddepth=cv2.CV_64F, dx=1, dy=0, ksize=5) # Sobel Edge Detection on the X axis\n sobely = cv2.Sobel(src=img_blur, ddepth=cv2.CV_64F, dx=0, dy=1, ksize=5) # Sobel Edge Detection on the Y axis\n sobelxy = cv2.Sobel(src=img_blur, ddepth=cv2.CV_64F, dx=1, dy=1, ksize=5) # Combined X and Y Sobel Edge Detection\n # Display Sobel Edge Detection Images\n if show == 1:\n cv2.imshow('Sobel X', sobelx)\n cv2.waitKey(0)\n cv2.imshow('Sobel Y', sobely)\n cv2.waitKey(0)\n cv2.imshow('Sobel X Y using Sobel() function', sobelxy)\n cv2.waitKey(0)\n\n # Canny Edge Detection\n edges = cv2.Canny(image=img_blur, threshold1=100, threshold2=200) # Canny Edge Detection\n # Display Canny Edge Detection Image\n if show == 1:\n cv2.imshow('Canny Edge Detection', edges)\n cv2.waitKey(0)\n cv2.destroyAllWindows()\n\n return (sobelx, sobely, sobelxy, edges)\n\ndef get_frame_with_chess_pieces_located_images(img, chess_pieces):\n chess_pieces_located_images = list()\n frame_with_chess_pieces_located_images = np.zeros(img.shape)\n # Get all individual masks of small image boxes and save them into a single image\n for el in chess_pieces:\n frame_with_chess_pieces_located_images += el.get_ChessPiece_located_image(img)\n\n return frame_with_chess_pieces_located_images\n\n# initializes yolo darknet model ---> returns yolo darknet model, class names\ndef yolo_init():\n # Opening yolo_init.json file\n with open('yolo_init.json') as yolo_init_json_file:\n yolo_init_dict = json.load(yolo_init_json_file)\n\n # set custom classes file\n with open(yolo_init_dict[\"classesFile\"],'rt') as f:\n className = f.read().rstrip('\\n').split('\\n')\n\n # set custom model configuration\n modelConfiguration = yolo_init_dict[\"modelConfiguration\"]\n\n # set custom model weights\n modelWeights = yolo_init_dict[\"modelWeights\"]\n\n # set YOLO-v3 network\n net = cv2.dnn.readNetFromDarknet(modelConfiguration, modelWeights)\n net.setPreferableBackend(cv2.dnn.DNN_BACKEND_OPENCV)\n net.setPreferableTarget(cv2.dnn.DNN_TARGET_CPU)\n\n return net, className\n\n# finds chess pieces with respective bounding boxes ---> returns array of chessPiece objects\ndef get_chess_pieces(outputs, img, chess_board_tiles_dict, chess_board_square, className, frame_id = 0, save_images = 1, show = 0):\n hT, wT, cT = img.shape\n bbox, confs, classIDs = [], [], []\n chess_pieces = list()\n\n # Get all chess pieces and respective bounding boxes\n for output in outputs:\n for detection in output:\n scores = detection[5:]\n classID = np.argmax(scores)\n confidence = scores[classID]\n if confidence > conf_threshold:\n w, h = int(detection[2]*wT), int(detection[3]*wT)\n x, y = int(detection[0]*wT - w/2), int(detection[1]*hT - h/2)\n if chess_board_square.contains(Point(x+w/2, y+h/2)):\n bbox.append([x, y, w, h])\n classIDs.append(classID)\n confs.append(float(confidence))\n\n # Delete close duplicate bounding boxes\n indices = cv2.dnn.NMSBoxes(bbox, confs, conf_threshold, nms_threshold)\n\n # Append the correct remaining chess pieces in the list\n if show == 1:\n print(\"\\tPrinting chess pieces...\")\n for counter, object_i in enumerate(indices):\n i = int(object_i)\n box = bbox[i]\n # Draw bounding boxes and save the new image\n if save_images == 1:\n xd, yd, wd, hd = box[0], box[1], box[2], box[3]\n cv2.rectangle(img, (xd, yd), (xd + wd, yd + hd), (0, 255, 0), 2)\n cv2.putText(img, f'{className[classIDs[i]]}{int(confs[i]*100)}%',\n (xd, yd-5), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 200, 0), 1)\n\n # Fetch the data and use the to initialize a temporary buffer object\n x, y, w, h = box[0]+box[2]/2, box[1]+box[3]/2, box[2], box[3]\n temp_chessPiece = ChessPiece(label = classIDs[i], x = x, y = y, width = w, height = h, confidence = confs[i])\n temp_chessPiece.set_currPosition(chess_board_tiles_dict)\n if show == 1:\n print(counter+1, temp_chessPiece)\n chess_pieces.append(temp_chessPiece)\n\n if save_images == 1:\n cv2.putText(img, str(frame_id), (25, 25), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 1)\n cv2.imwrite(\"output_images/Chess_pieces_bounding_boxes.jpg\", img)\n cv2.imwrite(\"output_images/Current_frame.jpg\", img)\n if show == 1:\n cv2.imshow('Chess pieces bounding boxes', img)\n cv2.waitKey(0)\n print(\"\\tThis frame contains\", len(chess_pieces), \"chess pieces.\")\n\n return chess_pieces\n\n# initializes the chess_board_tiles_dict\ndef chess_board_tiles_init():\n # Create dict with tile names as keys\n chess_board_tiles_dict = {\"A8\": -1,\"B8\": -1,\"C8\": -1,\"D8\": -1,\"E8\": -1,\"F8\": -1,\"G8\": -1,\"H8\": -1,\n \"A7\": -1,\"B7\": -1,\"C7\": -1,\"D7\": -1,\"E7\": -1,\"F7\": -1,\"G7\": -1,\"H7\": -1,\n \"A6\": -1,\"B6\": -1,\"C6\": -1,\"D6\": -1,\"E6\": -1,\"F6\": -1,\"G6\": -1,\"H6\": -1,\n \"A5\": -1,\"B5\": -1,\"C5\": -1,\"D5\": -1,\"E5\": -1,\"F5\": -1,\"G5\": -1,\"H5\": -1,\n \"A4\": -1,\"B4\": -1,\"C4\": -1,\"D4\": -1,\"E4\": -1,\"F4\": -1,\"G4\": -1,\"H4\": -1,\n \"A3\": -1,\"B3\": -1,\"C3\": -1,\"D3\": -1,\"E3\": -1,\"F3\": -1,\"G3\": -1,\"H3\": -1,\n \"A2\": -1,\"B2\": -1,\"C2\": -1,\"D2\": -1,\"E2\": -1,\"F2\": -1,\"G2\": -1,\"H2\": -1,\n \"A1\": -1,\"B1\": -1,\"C1\": -1,\"D1\": -1,\"E1\": -1,\"F1\": -1,\"G1\": -1,\"H1\": -1\n }\n return chess_board_tiles_dict\n\n# updates the chess_board_tiles_dict\ndef set_chess_board_tiles(img, chess_board_tiles_dict, draw_corners = 0, save_images = 1, show =0):\n # Defining the dimensions of checkerboard\n CHECKERBOARD = (7,7)\n gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)\n gray[gray>180] = 255\n gray[gray<100] = 0\n # Find the chess board corners\n ret, corners = cv2.findChessboardCornersSB(gray, CHECKERBOARD, cv2.CALIB_CB_ADAPTIVE_THRESH + cv2.CALIB_CB_ACCURACY+ cv2.CALIB_CB_NORMALIZE_IMAGE + cv2.CALIB_CB_FAST_CHECK)\n if ret == True:\n corners1 = copy.copy(corners)\n corners1 = corners1.reshape((7,7,1,2))\n corners2 = np.zeros((9,9,1,2))\n dx = corners1[:,1,:,0]-corners1[:,0,:,0]\n dy = corners1[1,:,:,1]-corners1[0,:,:,1]\n corners2[1:-1,1:-1,:,:] = corners1[:,:,:,:]\n corners2[0,1:-1,:,0] = corners1[0,:,:,0]\n corners2[0,1:-1,:,1] = corners1[0,:,:,1]-dy\n corners2[-1,1:-1,:,0] = corners1[-1,:,:,0]\n corners2[-1,1:-1,:,1] = corners1[-1,:,:,1]+dy\n corners2[:,0,:,1] = corners2[:,1,:,1]\n corners2[:,0,:,0] = corners2[:,1,:,0]- dx[0]\n corners2[:,-1,:,1] = corners2[:,-2,:,1]\n corners2[:,-1,:,0] = corners2[:,-2,:,0]+dx[0]\n corners3 = np.zeros((81,1,2))\n j = 0\n for row in corners2:\n for col in row:\n corners3[j,:,:] = col\n j+=1\n # Fill the dict with quadruples of points to define bounding boxes\n j = 0\n for id, key in enumerate(chess_board_tiles_dict.keys()):\n points =np.array([[corners3[id+j,0,0], corners3[id+j,0,1]],\n [corners3[id+j+1,0,0], corners3[id+j+1,0,1]],\n [corners3[id+j+10,0,0], corners3[id+j+10,0,1]],\n [corners3[id+j+9,0,0], corners3[id+j+9,0,1]]], dtype = np.int32)\n chess_board_tiles_dict[key] = Polygon(points)\n if draw_corners == 1:\n cv2.polylines(img, [points], 1, (0,0,255),2)\n cv2.putText(img, str(key),(int(corners3[id+j+9,0,0])+10, int(corners3[id+j+9,0,1])-18), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 1)\n if id%8 == 7:\n j+=1\n # Draw and display the corners\n if draw_corners == 1:\n img = cv2.drawChessboardCorners(img, CHECKERBOARD, corners, ret)\n if save_images == 1:\n cv2.imwrite(\"output_images/Chess_board_tiles_bounding_boxes.jpg\",img)\n if show == 1:\n cv2.imshow('Chess board tiles bounding boxes', img)\n cv2.waitKey(0)\n cv2.destroyAllWindows()\n return ret\n\ndef get_chess_board(chess_pieces):\n chess_board = [['*','*','*','*','*','*','*','*'], # 8\n ['*','*','*','*','*','*','*','*'], # 7\n ['*','*','*','*','*','*','*','*'], # 6\n ['*','*','*','*','*','*','*','*'], # 5\n ['*','*','*','*','*','*','*','*'], # 4\n ['*','*','*','*','*','*','*','*'], # 3\n ['*','*','*','*','*','*','*','*'], # 2\n ['*','*','*','*','*','*','*','*']] # 1\n # A # B # C # D # E # F # G # H\n for chess_piece in chess_pieces:\n pos = 8-int(chess_piece.currPosition[1]), ord(chess_piece.currPosition[0])-65\n chess_board[pos[0]][pos[1]] = chess_piece.piece.symbol()\n blanks_counter = 0\n chess_board_string = \"\"\n for row in chess_board:\n blanks_counter = 0\n for el in row:\n if el == '*':\n blanks_counter+=1\n else:\n if blanks_counter!=0:\n chess_board_string = chess_board_string + str(blanks_counter) + el\n blanks_counter = 0\n else:\n chess_board_string = chess_board_string + el\n blanks_counter = 0\n if blanks_counter != 0:\n chess_board_string = chess_board_string + str(blanks_counter)\n chess_board_string+='/'\n chess_board_string = chess_board_string[:-1] + \" w - - 0 1\"\n return chess_board_string\n # arrows=[chess.svg.Arrow(chess.E4, chess.F6, color=\"#0000cccc\")],squares=chess.SquareSet(chess.BB_DARK_SQUARES & chess.BB_FILE_B)\n\ndef show_chess_board(chess_board_string):\n game = display.start(chess_board_string,(0,200,255), 'Grand Master Chess')\n # Checking GUI window for QUIT event. (Esc or GUI CANCEL)\n try:\n while True:\n display.check_for_quit()\n except:\n try:\n display.terminate()\n except:\n print(\"Error hase occurred during game. Leaving the game...\")\n finally:\n display.terminate()\n print(\"Game was closed! Game data are lost!\")\n\n# Vizualize chess game\ndef update_chess_board(chess_board_string, frame_id):\n game = display.start(chess_board_string,(0,200,255), 'Grand Master Chess \\nTurn '+str(frame_id))\n # Checking GUI window for QUIT event. (Esc or GUI CANCEL)\n display.check_for_quit()\n # display.update(chess_board_string, game)\n","repo_name":"Gjergjiluarasi/Grand-Master-Chess-Demo","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":12196,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"18097773419","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Jan 1 13:21:35 2019\n\n@author: khale\n\"\"\"\n\n# Standard library imports.\nimport sys\nimport time\n\n# Third party imports.\nimport numpy as np\nimport scipy as sc\nimport pandas as pd\nimport numba\n\n#from scipy.sparse.linalg import spsolve\n\n# Local imports.\ntry:\n from ..math_funcs._cython_definitions.matrix_funcs import matrix_assembler\nexcept ModuleNotFoundError:\n print(\"Cythonized modules not found!\")\n print(\"Falling back to -less efficient- numba mode!\")\n from ..math_funcs.numba_funcs import matrix_assembler\n\n###############################################################################\n###############################################################################\n\n@numba.njit(cache=True, nogil=True)\ndef solve(A, b):\n x = np.linalg.solve(A, b)\n return x\n\n\ndef progress_bar(steps, i, t0, t_sim):\n sys.stdout.write('\\r')\n length = (100*(1+i)//(4*steps))\n percentage = 100*(1+i)//steps\n t = time.perf_counter() - t0\n format_ = ('='*length,percentage,i+1, steps, t_sim, t)\n sys.stdout.write(\"[%-25s] %d%%, (%s/%s) steps. Sim Time = %.5s | CPU Time = %.5s (s)\" % format_)\n sys.stdout.flush()\n\n###############################################################################\n###############################################################################\n\nclass abstract_solver(object):\n \n def __init__(self, model):\n self.model = model\n self._construct_system_arrays()\n self._initialize_model()\n self._create_indicies()\n self._construct_containers()\n \n def _construct_system_arrays(self):\n n = self.model.n\n nc = self.model.nc\n self._q = np.zeros((n, 1), dtype=np.float64)\n self._qd = np.zeros((n, 1), dtype=np.float64)\n self._qdd = np.zeros((n, 1), dtype=np.float64)\n\n self._lgr = np.zeros((nc, 1), dtype=np.float64)\n #self._pos_m = np.zeros((nc, 1), dtype=np.float64)\n #self._vel_m = np.zeros((nc, 1), dtype=np.float64)\n #self._acc_m = np.zeros((nc, 1), dtype=np.float64)\n\n self._jac_ = np.zeros((nc, n), dtype=np.float64)\n self._mass = np.zeros((n, n), dtype=np.float64)\n self._mass_matrix_rows = np.arange(self.model.ncols, dtype=np.intc)\n\n self._coeff_matrix = np.zeros((n + nc, n + nc), dtype=np.float64)\n \n \n def set_initial_states(self, q, qd):\n assert q.shape == self._q.shape\n assert qd.shape == self._q.shape\n self._set_gen_coordinates(q)\n self._set_gen_velocities(qd)\n self._pos_history[0] = q.copy()\n self._vel_history[0] = qd.copy()\n\n \n def set_time_array(self, duration, spacing):\n \n if duration > spacing:\n time_array = np.arange(0, duration, spacing)\n step_size = spacing\n elif duration < spacing:\n time_array, step_size = np.linspace(0, duration, spacing, retstep=True)\n else:\n raise ValueError('Time array is not properly sampled.')\n self.time_array = time_array\n self.step_size = step_size\n\n self._construct_containers(time_array.size)\n self.set_initial_states(self.model._q, self.model._qd)\n \n \n def eval_reactions(self):\n self._reactions = {}\n time_array = self.time_array\n bar_length = len(time_array)\n print(\"\\nEvaluating System Constraints' Forces.\")\n t0 = time.perf_counter()\n dt = self.step_size\n for i, t in enumerate(time_array):\n # Updating the progress bar\n progress_bar(bar_length, i, t0, t+dt)\n self._set_time(t)\n self._set_gen_coordinates(self._pos_history[i])\n self._set_lagrange_multipliers(self._lgr_history[i])\n reactions = self._eval_reactions_eq()\n self._reactions[i] = reactions\n \n values = {i:np.concatenate(list(v.values())) for i,v in self._reactions.items()}\n \n self.reactions_dataframe = pd.DataFrame(\n data = np.concatenate(list(values.values()),1).T,\n columns = self._reactions_indicies)\n self.reactions_dataframe['time'] = time_array\n\n \n def _initialize_model(self):\n model = self.model\n model.initialize(self._q, self._qd, self._qdd, self._lgr)\n\n def _create_indicies(self):\n model = self.model\n sorted_coordinates = {v:k for k,v in model.indicies_map.items()}\n self._coordinates_indicies = []\n for name in sorted_coordinates.values():\n self._coordinates_indicies += ['%s.%s'%(name, i) \n for i in ['x', 'y', 'z', 'e0', 'e1', 'e2', 'e3']]\n \n self._reactions_indicies = []\n for name in model.reactions_indicies:\n self._reactions_indicies += ['%s.%s'%(name, i) \n for i in ['x','y','z']]\n \n def _construct_containers(self, size=None):\n self._pos_history = {}#np.empty((size,), dtype=np.ndarray)\n self._vel_history = {}#np.empty((size,), dtype=np.ndarray)\n self._acc_history = {}#np.empty((size,), dtype=np.ndarray)\n self._lgr_history = {}#np.empty((size,), dtype=np.ndarray)\n\n def _creat_results_dataframes(self):\n columns = self._coordinates_indicies\n constraints = self._reactions_indicies\n \n pos_data = list(self._pos_history.values())\n vel_data = list(self._vel_history.values())\n acc_data = list(self._acc_history.values())\n lgr_data = list(self._lgr_history.values())\n\n self.pos_dataframe = pd.DataFrame(\n data = np.concatenate(pos_data,1).T,\n columns = columns)\n self.vel_dataframe = pd.DataFrame(\n data = np.concatenate(vel_data,1).T,\n columns = columns)\n self.acc_dataframe = pd.DataFrame(\n data = np.concatenate(acc_data,1).T,\n columns = columns)\n self.lgr_dataframe = pd.DataFrame(\n data = np.concatenate(lgr_data,1).T,\n columns = range(self.model.nc))\n \n time_array = self.time_array\n self.pos_dataframe['time'] = time_array\n self.vel_dataframe['time'] = time_array\n self.acc_dataframe['time'] = time_array\n self.lgr_dataframe['time'] = time_array\n \n def _assemble_equations(self, data):\n mat = np.concatenate(data)\n return mat\n \n def _set_time(self, t):\n self.model.t = t\n \n def _set_gen_coordinates(self, q):\n self._q[:] = q\n \n def _set_gen_velocities(self, qd):\n self._qd[:] = qd\n \n def _set_gen_accelerations(self, qdd):\n self._qdd[:] = qdd\n \n def _set_lagrange_multipliers(self, lgr):\n self._lgr[:] = lgr\n\n \n def _eval_pos_eq(self):\n self.model.eval_pos_eq()\n data = self.model.pos_eq_blocks\n mat = self._assemble_equations(data)\n return mat\n \n def _eval_vel_eq(self):\n self.model.eval_vel_eq()\n data = self.model.vel_eq_blocks\n mat = self._assemble_equations(data)\n return mat\n \n def _eval_acc_eq(self):\n self.model.eval_acc_eq()\n data = self.model.acc_eq_blocks\n mat = self._assemble_equations(data)\n return mat\n \n def _eval_jac_eq(self):\n self.model.eval_jac_eq()\n rows = self.model.jac_rows\n cols = self.model.jac_cols\n data = self.model.jac_eq_blocks\n shape = (self.model.nc, self.model.n)\n matrix_assembler(self._jac_, data, rows, cols, shape)\n return self._jac_\n \n def _eval_mass_eq(self):\n self.model.eval_mass_eq()\n data = self.model.mass_eq_blocks\n n = self.model.n\n rows = cols = self._mass_matrix_rows\n matrix_assembler(self._mass, data, rows, cols, (n, n))\n return self._mass\n \n def _eval_frc_eq(self):\n self.model.eval_frc_eq()\n data = self.model.frc_eq_blocks\n mat = self._assemble_equations(data)\n return mat\n \n def _eval_reactions_eq(self):\n self.model.eval_reactions_eq()\n return self.model.reactions\n\n# @profile\n def _solve_constraints(self, guess):\n self._set_gen_coordinates(guess)\n \n A = self._eval_jac_eq()\n b = self._eval_pos_eq()\n lu, p = self._factorize_jacobian(A)\n delta_q = sc.linalg.lu_solve((lu, p), -b)\n #delta_q = solve(A, -b)\n \n itr=0\n while np.linalg.norm(delta_q)>1e-4:\n# print(np.linalg.norm(delta_q))\n guess += delta_q\n \n self._set_gen_coordinates(guess)\n b = self._eval_pos_eq()\n delta_q = sc.linalg.lu_solve((lu, p), -b)\n \n if (itr % 10) == 0 and itr != 0:\n #print('Updating Jacobian\\n')\n A = self._eval_jac_eq()\n lu, p = self._factorize_jacobian(A)\n delta_q = sc.linalg.lu_solve((lu, p), -b)\n if itr > 50:\n print(\"Iterations exceded \\n\")\n #raise ValueError(\"Iterations exceded \\n\")\n break\n itr+=1\n self._jac = self._eval_jac_eq()\n\n def _factorize_jacobian(self, jacobian):\n lu, p = sc.linalg.lu_factor(jacobian)\n return lu, p\n\n\n","repo_name":"khaledghobashy/uraeus_nmbd_python","sub_path":"uraeus/nmbd/python/engine/numerics/solvers/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":9308,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"10498528711","text":"\"\"\"Custom thread class and signals emitted by worker threads.\"\"\"\nimport sys\nimport traceback\nfrom collections.abc import Callable, Generator\nfrom typing import Any\n\nfrom PySide6.QtCore import QObject, QRunnable, Signal\nfrom src.domain.progress import Progress\n\n\nclass WorkerSignals(QObject):\n\n \"\"\"Signals emitted by worker threads.\"\"\"\n\n finished = Signal()\n error = Signal(tuple)\n result = Signal(dict)\n progress = Signal(Progress)\n\n\nclass Worker(QRunnable):\n\n \"\"\"Custom thread class.\"\"\"\n\n def __init__(\n self, func: Callable[..., Generator[dict[str, int], None, None]], *args: Any, **kwargs: Any\n ) -> None:\n \"\"\"Initialize worker object.\"\"\"\n super().__init__()\n self.func = func\n self.args = args\n self.kwargs = kwargs\n self.signals = WorkerSignals()\n\n def run(self) -> None:\n try:\n results = self.func(args=self.args, kwargs=self.kwargs)\n for result in results:\n progress_value, remaining_time = result[\"progress\"], result[\"remaining_time\"]\n progress = Progress(\n value=progress_value,\n remaining_time=remaining_time,\n )\n self.signals.progress.emit(progress)\n self.signals.result.emit(result)\n except Exception: # noqa: BLE001\n traceback.print_exc()\n exc_type, value = sys.exc_info()[:2]\n self.signals.error.emit((exc_type, value, traceback.format_exc()))\n finally:\n try:\n self.signals.finished.emit()\n except RuntimeError:\n return\n\n def stop(self) -> None:\n self.terminate()\n","repo_name":"ieasybooks/almufarrigh","sub_path":"src/domain/threadpool.py","file_name":"threadpool.py","file_ext":"py","file_size_in_byte":1706,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"81"} +{"seq_id":"15990333360","text":"from django.core.exceptions import PermissionDenied\nfrom django.http import HttpResponse\nfrom django.views.decorators.csrf import csrf_exempt\n\nfrom . import dispatcher as dp\nfrom .bot import BotConfigurator\n\ntBot = BotConfigurator()\nbot = tBot.get_bot()\n\n\n@csrf_exempt\ndef get_hook(request):\n if request.META[\"CONTENT_TYPE\"] == \"application/json\":\n json_data = request.body.decode(\"utf-8\")\n update = tBot.update(json_data)\n bot.process_new_updates([update])\n return HttpResponse(status=200)\n else:\n raise PermissionDenied\n\n\n@bot.message_handler(commands=[\"start\"])\ndef start_command(message):\n dp.entrypoint(message, bot)\n\n\n@bot.message_handler(content_types=[\"text\"])\ndef text_messages(message):\n dp.text_echo(message, bot)\n\n\n@bot.callback_query_handler(func=lambda call: True)\ndef callback_queries(call):\n dp.callback_echo(call, bot)\n","repo_name":"Ocinu/EVEAnalizer","sub_path":"Bot/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":886,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"14940627931","text":"import pandas as pd\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport matplotlib.pyplot as plt\n\n# 加载数据\nfile_path = \"/Users/hanfeilong/Desktop/模型/完整代码/北京天气.xlsx\" # 请替换为实际的文件路径\ndf = pd.read_excel(file_path)\n\n# 对类别数据进行编码\ndf[\"PM2.5\"] = pd.factorize(df[\"PM2.5\"])[0]\n\ndef transform_data(data, timesteps=5):\n X, y = [], []\n for i in range(len(data) - timesteps):\n X.append(data[i:i+timesteps])\n y.append(data[i+timesteps])\n return np.array(X), np.array(y)\n\ndata = df[\"PM2.5\"].values\nX, y = transform_data(data)\n\n# 切割数据集为训练集和验证集\nsplit_ratio = 0.8\nsplit_idx = int(len(X) * split_ratio)\nX_train, X_val = X[:split_idx], X[split_idx:]\ny_train, y_val = y[:split_idx], y[split_idx:]\n\n# 定义MLP模型\nclass MLP(nn.Module):\n def __init__(self, input_dim):\n super(MLP, self).__init__()\n self.fc1 = nn.Linear(input_dim, 100)\n self.fc2 = nn.Linear(100, 50)\n self.fc3 = nn.Linear(50, 1)\n\n def forward(self, x):\n x = torch.relu(self.fc1(x))\n x = torch.relu(self.fc2(x))\n return self.fc3(x)\n\nmodel = MLP(X.shape[1])\ncriterion = nn.MSELoss()\noptimizer = optim.Adam(model.parameters(), lr=0.01)\n\nX_train_tensor = torch.FloatTensor(X_train)\ny_train_tensor = torch.FloatTensor(y_train).view(-1, 1)\nX_val_tensor = torch.FloatTensor(X_val)\ny_val_tensor = torch.FloatTensor(y_val).view(-1, 1)\n\n# 训练模型\nepochs = 200\ntrain_losses = []\nval_losses = []\n\nfor epoch in range(epochs):\n model.train()\n optimizer.zero_grad()\n train_outputs = model(X_train_tensor)\n train_loss = criterion(train_outputs, y_train_tensor)\n train_loss.backward()\n optimizer.step()\n\n model.eval()\n with torch.no_grad():\n val_outputs = model(X_val_tensor)\n val_loss = criterion(val_outputs, y_val_tensor)\n\n train_losses.append(train_loss.item())\n val_losses.append(val_loss.item())\n\n if (epoch + 1) % 20 == 0:\n print(f\"Epoch [{epoch+1}/{epochs}], Train Loss: {train_loss.item():.4f}, Validation Loss: {val_loss.item():.4f}\")\n\n# 画出训练和验证损失曲线\nplt.plot(train_losses, label=\"Training Loss\")\nplt.plot(val_losses, label=\"Validation Loss\")\nplt.xlabel(\"Epoch\")\nplt.ylabel(\"Loss\")\nplt.title(\"Training and Validation Losses over Epochs\")\nplt.legend()\nplt.savefig(\"training_validation_loss.png\")\nplt.show()\n","repo_name":"a186232641/model","sub_path":"MLP.py","file_name":"MLP.py","file_ext":"py","file_size_in_byte":2431,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"6591266136","text":"class Conjunto:\n __elementos = []\n\n def __init__(self):\n self.__elementos = []\n \n def agregarElemento(self, elemento):\n if isinstance(elemento, int):\n if elemento not in self.__elementos:\n self.__elementos.append(elemento)\n self.__elementos.sort()\n\n def getTamaño(self):\n return len(self.__elementos)\n\n def getElementoPorIndice(self, indice):\n return self.__elementos[indice]\n\n def quitarElemento(self, elemento):\n if elemento in self.__elementos:\n self.__elementos.remove(elemento)\n\n def __add__(self, otro):\n nuevo = None\n if isinstance(otro, Conjunto):\n nuevo = Conjunto()\n i = 0\n j = 0\n while i < self.getTamaño() and j < self.getTamaño():\n if self.getElementoPorIndice(i) < otro.getElementoPorIndice(j):\n nuevo.agregarElemento(self.getElementoPorIndice(i))\n i += 1\n elif self.getElementoPorIndice(i) > otro.getElementoPorIndice(j):\n nuevo.agregarElemento(otro.getElementoPorIndice(j))\n j += 1\n else:\n nuevo.agregarElemento(self.getElementoPorIndice(i))\n i += 1\n j += 1\n while i < self.getTamaño():\n nuevo.agregarElemento(self.getElementoPorIndice(i))\n i += 1\n while j < otro.getTamaño():\n nuevo.agregarElemento(otro.getElementoPorIndice(j))\n j += 1\n return nuevo\n \n def __sub__(self, otro):\n nuevo = None\n if isinstance(otro, Conjunto):\n nuevo = Conjunto()\n i = 0\n j = 0\n while i < self.getTamaño():\n nuevo.agregarElemento(self.getElementoPorIndice(i))\n i += 1\n while j < otro.getTamaño():\n nuevo.quitarElemento(otro.getElementoPorIndice(j))\n j += 1\n return nuevo\n \n def __eq__(self, otro):\n resultado = False\n if isinstance(otro, Conjunto):\n if self.getTamaño() == otro.getTamaño():\n band = True\n i = 0\n while i < self.getTamaño() and band:\n if self.getElementoPorIndice(i) != otro.getElementoPorIndice(i):\n band = False\n i += 1\n resultado = band\n return resultado\n \n def __str__(self):\n if self.getTamaño() == 0:\n cadena = \"{}\"\n else:\n cadena = \"{\"\n for unElemento in self.__elementos:\n cadena += \"{0}; \".format(unElemento)\n cadena = cadena[0:-2] + \"}\"\n return cadena","repo_name":"ignacio745/POO-Unidad2-Ejercicio8","sub_path":"ClaseConjunto.py","file_name":"ClaseConjunto.py","file_ext":"py","file_size_in_byte":2808,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"19380752870","text":"import time\r\n\r\nfrom z3 import *\r\n\r\n\r\ndef _parse_z3_model(model):\r\n solution = []\r\n for declare in model.decls():\r\n name = declare.name()\r\n value = model[declare]\r\n solution.append({'name': name, 'value': value})\r\n return solution\r\n\r\n\r\n# 传入的timeout的单位是ms\r\ndef add_and_solve_constraints(constraint_set,\r\n timeout=-1):\r\n start = 0\r\n end = 0\r\n s = Solver()\r\n if timeout > 0:\r\n s.set(timeout=timeout)\r\n\r\n for constraint in constraint_set:\r\n s.add(constraint)\r\n\r\n declare_set = []\r\n unknown_reason = ''\r\n # 开始计时\r\n start = time.time_ns()\r\n # 判断是否有可行解\r\n sat_or_not = s.check()\r\n if sat_or_not == sat:\r\n model = s.model()\r\n end = time.time_ns()\r\n print(\"end time: %f\" % end)\r\n # 输出变量声明的集合\r\n declare_set = _parse_z3_model(model)\r\n elif sat_or_not == unsat:\r\n # 输出时间\r\n end = time.time_ns()\r\n # 输出一个空的declare_set\r\n elif sat_or_not == unknown:\r\n end = time.time_ns()\r\n # 输出一个空的declare_set\r\n # 输出unknown的原因\r\n unknown_reason = s.reason_unknown()\r\n pass\r\n\r\n time_used_in_second = (end - start) / 1000000000\r\n\r\n print('time_used:')\r\n print(time_used_in_second)\r\n\r\n # 返回time_used_in_second、sat_or_not、\r\n # declare_set、(unknown reason)\r\n return {'time_used_in_second': time_used_in_second, 'sat_or_not': str(sat_or_not),\r\n 'declare_set': declare_set, 'unknown_reason': unknown_reason}\r\n\r\n\r\ndef _main():\r\n return\r\n\r\n\r\nif __name__ == '__main__':\r\n _main()\r\n","repo_name":"fast-codesign/OpenTSN2.0","sub_path":"Software/open-planner-master/lib/z3_constraints_solver.py","file_name":"z3_constraints_solver.py","file_ext":"py","file_size_in_byte":1685,"program_lang":"python","lang":"en","doc_type":"code","stars":25,"dataset":"github-code","pt":"81"} +{"seq_id":"44074194115","text":"import collections\nclass Solution(object):\n def uncommonFromSentences(self, A, B):\n \"\"\"\n :type A: str\n :type B: str\n :rtype: List[str]\n \"\"\"\n words = collections.Counter(A.split(\" \") + B.split(\" \"))\n\n return [word for word in words if words[word] == 1]\n ","repo_name":"ericcheng09/LeetCodeSolution_Python","sub_path":"Scripts/884.py","file_name":"884.py","file_ext":"py","file_size_in_byte":316,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"32000618864","text":"import multiprocessing\nimport os\nimport time\nfrom datetime import datetime\nfrom queue import Empty\n\nimport numpy as np\nimport pandas as pd\n\npd.set_option(\"display.float_format\", lambda x: \"%.5f\" % x) # pandas\npd.set_option(\"display.max_columns\", 100)\npd.set_option(\"display.max_rows\", 100)\npd.set_option(\"display.width\", 600)\n\nfrom settings import BaseConfig\n\nfrom zmq_high_speed_subs.message_handler import MessageHandler, array_columns\n\nfrom zmq_high_speed_subs.utils import setup_db_connection, setup_logging\n\nclass Worker(MessageHandler, multiprocessing.Process):\n \"\"\"\n The Worker's Sole Purpose in Life is to take Data from it's Queue, Format it, and then Insert into Database\n \"\"\"\n name = \"Worker\"\n\n def __init__(self, queue, status_queue, kill_switch, interval_time=30):\n super().__init__()\n multiprocessing.Process.__init__(self)\n self.status_queue = status_queue\n self.interval_time = interval_time\n self.queue = queue\n self.kill_switch = kill_switch\n self.show_first_message = True\n self.table_name = f\"{datetime.now().strftime('%Y%m%d')}_LVL1\"\n self.initialize_counters()\n\n def run(self):\n \"\"\"\n Starts worker that connects to the Pusher\n \"\"\"\n self.initialize()\n\n self.engine = setup_db_connection(driver=\"Fake\")\n self.logger = multiprocessing.get_logger()\n self.logger.handlers[0] = setup_logging()\n\n self.logger.debug(\"\\n\\n\")\n self.logger.debug(f'Spawning Worker')\n self.logger.debug(\"\\n\\n\")\n\n self.time_start_process = time.time()\n self.time_start_cycle = time.time()\n\n # -------------------------------\n # Start Processing Data\n\n\n data_unprocessed = self.get_data_from_queue()\n\n df = pd.DataFrame()\n\n df = self.process_data(data_unprocessed)\n\n if not df.empty:\n self.insert_data_into_database(df)\n\n # -------------------------------\n\n self.check_status(\"COMPLETED\")\n return\n\n def get_data_from_queue(self, init_array_size=5000):\n\n self.current_loop_iteration = 0\n self.current_loop_pause = 0\n count = 0\n\n # allocate array prior to appending\n temp_array = [()] * init_array_size\n\n while not self.kill_switch.is_set():\n\n try:\n packed = self.queue.get()\n\n if packed == \"--END--\":\n break\n\n message = tuple(packed.decode().split(','))\n\n temp_array[count] = message\n count += 1\n\n self.check_status(message)\n\n except Empty as empty:\n self.logger.debug(f'')\n self.logger.debug(f'Current Loop Iteration:\\ {self.current_loop_iteration}')\n self.logger.debug(f'Current Numpy Array:\\t {count}')\n self.logger.debug(f'Waiting for more messages...')\n self.logger.debug(f'')\n time.sleep(0.01)\n\n except Exception as E:\n self.logger.debug(f\"Empty Queue\\t{E}\")\n\n self.counter_messages_total += count\n self.counter_messages_period = count\n\n return temp_array\n\n def process_data(self, temp_array):\n\n df = pd.DataFrame(temp_array, columns=array_columns)\n\n return df\n\n def insert_data_into_database(self, df):\n\n try:\n self.logger.debug(f'Starting to Insert into Database')\n\n if self.engine:\n df.to_sql(name=self.table_name, con=self.engine, index=False, if_exists=\"append\")\n self.logger.debug(f'Completed to Insert into Database')\n else:\n self.logger.debug(f'Couldnt find DB Connection. Not Saving Data')\n del df\n return\n\n except Exception as e:\n self.logger.error(e)\n\n\n def initialize_counters(self):\n # counters for benchmarking\n self.counter = 0\n self.counter_messages_current = 0\n self.counter_total_database = 0\n self.counter_total_manager = 0\n self.current_loop_iteration = 0\n self.counter_messages_total = 0\n self.counter_messages_period = 0\n self.counter_messages_period_sleep = 0\n self.counter_messages_current = 0\n self.counter_total_consumer = 0\n self.counter_messages_period_sleep = 0\n self.counter_messages_total = 0\n self.time_total = 0\n\n def check_status(self, message=None):\n\n self.current_loop_iteration += 1\n self.current_loop_pause += 1\n self.counter_total_database += 1\n self.counter_total_manager += 1\n self.counter_messages_period += 1\n self.counter_messages_total += 1\n\n if time.time() - self.time_start_cycle > self.interval_time or message == \"COMPLETED\":\n time_now = time.time()\n time_cycle = time_now - self.time_start_cycle\n self.time_total = self.time_total + time_cycle\n self.logger.info(f'Worker Messages Time Elapsed:\\t{round(self.time_total, 2)} seconds')\n self.logger.debug(f'Worker Messages:\\t{self.counter_total_manager}')\n self.logger.info(f'Worker Messages Per Second:\\t{round((self.counter_total_manager / self.time_total), 2)}\\n\\n')\n self.logger.debug(f\"{message}\")\n self.time_start_cycle = time.time()\n self.logger.debug(f'\\n\\n')\n self.counter_messages_period = 0\n self.time_count = 0\n self.current_loop_pause = 0\n self.counter_messages_period_sleep = 0\n\n def __repr__(self):\n return self.name\n\n def __str__(self):\n return self.name\n","repo_name":"ryansmccoy/zmq-high-speed-subs","sub_path":"zmq_high_speed_subs/_14_worker.py","file_name":"_14_worker.py","file_ext":"py","file_size_in_byte":5683,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"81"} +{"seq_id":"13963931971","text":"import asyncio\nimport time\n\n\"\"\"\n使用async关键字定义的协程对象,使用await可以针对耗时的操作\n进行挂起(是生成器中的yield的替代,但是本地协程函数不允许使用),让出当前控制权。\n协程遇到await,事件循环将会挂起该协程,执行别的协程,直到其他协程也挂起,或者执行完毕,在进行下一个协程的执行\n\n使用asyncio.sleep模拟阻塞操作。\n\n\"\"\"\n\n\nasync def func1(num):\n print(num, 'before---func1----')\n await asyncio.sleep(num)\n return \"recv num %s\" % num\n\n\nif __name__ == \"__main__\":\n begin = time.time()\n\n coroutine1 = func1(5)\n coroutine2 = func1(3)\n loop = asyncio.get_event_loop()\n task1 = asyncio.ensure_future(coroutine1)\n task2 = asyncio.ensure_future(coroutine2)\n tasks = asyncio.gather(*[task1, task2]) # gather可以实现同时注册多个任务,实现并发操作。wait方法使用一致\n loop.run_until_complete(tasks)\n loop.close()\n end = time.time()\n print(end - begin)\n","repo_name":"loyess/Note","sub_path":"asyncio/06_阻塞和await.py","file_name":"06_阻塞和await.py","file_ext":"py","file_size_in_byte":1032,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"37226067521","text":"#\n# @lc app=leetcode.cn id=199 lang=python3\n#\n# [199] 二叉树的右视图\n#\n# https://leetcode-cn.com/problems/binary-tree-right-side-view/description/\n#\n# algorithms\n# Medium (65.44%)\n# Likes: 631\n# Dislikes: 0\n# Total Accepted: 175K\n# Total Submissions: 267.3K\n# Testcase Example: '[1,2,3,null,5,null,4]'\n#\n# 给定一个二叉树的 根节点 root,想象自己站在它的右侧,按照从顶部到底部的顺序,返回从右侧所能看到的节点值。\n# \n# \n# \n# 示例 1:\n# \n# \n# \n# \n# 输入: [1,2,3,null,5,null,4]\n# 输出: [1,3,4]\n# \n# \n# 示例 2:\n# \n# \n# 输入: [1,null,3]\n# 输出: [1,3]\n# \n# \n# 示例 3:\n# \n# \n# 输入: []\n# 输出: []\n# \n# \n# \n# \n# 提示:\n# \n# \n# 二叉树的节点个数的范围是 [0,100]\n# -100  \n# \n# \n#\n\n# @lc code=start\n# 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 rightSideView(self, root: TreeNode) -> List[int]:\n #层序遍历\n if not root:\n return []\n if not root.left and not root.right:\n return [root.val]\n layer_num = [[root.val]]\n layer_node = [[root]]\n while 1:\n cur_layer_num = []\n cur_layer_node = []\n for i in range(len(layer_node[-1])):\n node = layer_node[-1][i]\n if node.left:\n cur_layer_node.append(node.left)\n cur_layer_num.append(node.left.val)\n if node.right:\n cur_layer_node.append(node.right)\n cur_layer_num.append(node.right.val)\n if len(cur_layer_node)==0:\n break\n else:\n layer_node.append(cur_layer_node)\n layer_num.append(cur_layer_num)\n return [item[-1] for item in layer_num]\n\n# @lc code=end\n\n","repo_name":"LianShuaiLong/Codebook","sub_path":"leetcode/199.二叉树的右视图.py","file_name":"199.二叉树的右视图.py","file_ext":"py","file_size_in_byte":1948,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"81"} +{"seq_id":"31789954118","text":"from bs4 import BeautifulSoup\nimport requests\nimport csv\nimport sys\n\nif len(sys.argv) < 3:\n print('two arguments are needed: [wikipedia url] [csv output name]')\n exit()\n\nurl = sys.argv[1]\ncsv_file = sys.argv[2]\n\nresponse = requests.get(url)\n\nsoup = BeautifulSoup(response.content, \"html.parser\")\n\ntable = soup.find(\"table\", attrs={\"class\": \"wikitable\"})\n\nwith open(\"../data/\" + csv_file + \".csv\", \"w\", newline=\"\", encoding=\"utf-8\") as csv_file:\n writer = csv.writer(csv_file, delimiter=',')\n \n table_header = []\n for row in table.find_all(\"th\"):\n table_header.append(row.text.strip())\n\n writer.writerow(table_header)\n\n rowspan_size = 0\n rowspan_index = 0\n rowspan_value = \"\"\n for row in table.find_all(\"tr\"):\n cells = row.find_all(\"td\")\n if rowspan_size > 0:\n cells.insert(rowspan_index, rowspan_value)\n rowspan_size -= 1\n \n tds = []\n if (len(cells) > 0):\n for index, cell in enumerate(cells):\n if cell.has_attr('rowspan'):\n rowspan_size = int(cell.get('rowspan'))-1\n del cell['rowspan']\n rowspan_index = index\n rowspan_value = cell\n\n tds.append(cell.get_text().strip())\n \n writer.writerow(tds)","repo_name":"openvideogamedata/openvideogamedata.github.io","sub_path":"src/wikipedia-table-to-csv-file.py","file_name":"wikipedia-table-to-csv-file.py","file_ext":"py","file_size_in_byte":1196,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"81"} +{"seq_id":"6119093216","text":"from django.shortcuts import render\nfrom django.http import HttpResponse, HttpResponseRedirect, HttpResponseNotAllowed\nfrom .models import Agendamentos\nfrom django.contrib.auth.decorators import login_required\nfrom .form import AgendamentosForm\nfrom accounts.models import User_Turma\nfrom turmas.models import Turma\n\n#listar\n@login_required\ndef index(request):\n turmas = User_Turma.objects.filter(user=request.user).values_list('turma')\n agendamentos = Agendamentos.objects.filter(turma__in=turmas)\n context = {\n 'agendamentos': agendamentos\n }\n return render(request, 'agendamentos/index.html', context)\n\n#detalhar\n@login_required\ndef detalhar(request, agendamentos_id):\n agendamentos = Agendamentos.objects.get(pk = agendamentos_id)\n context = {\n 'agendamentos': agendamentos\n }\n return render(request, 'agendamentos/detalhar.html', context)\n\n# @login_required\n@login_required\ndef criar(request):\n if request.user.cargo != 'PF':\n return HttpResponseNotAllowed(['GET', 'POST'])\n\n if request.method == \"POST\":\n form = AgendamentosForm(request.POST)\n if form.is_valid():\n form.save()\n \n return HttpResponseRedirect(\"/agendamentos\")\n else: \n form = AgendamentosForm()\n # Somente turmas que o professor está cadastrado\n turmas = User_Turma.objects.filter(user=request.user).values_list('turma')\n form.fields['turma'].queryset = Turma.objects.filter(pk__in=turmas)\n\n context = {\n 'form': form\n }\n return render(request, 'agendamentos/criar.html', context)\n\n@login_required\ndef editar(request, agendamentos_id):\n if request.user.cargo != 'PF':\n return HttpResponseNotAllowed(['GET', 'POST'])\n agendamentos = Agendamentos.objects.get(pk = agendamentos_id)\n \n if request.method == \"POST\":\n form = AgendamentosForm(request.POST, instance=agendamentos)\n if form.is_valid():\n form.save()\n return HttpResponseRedirect(\"/agendamentos\")\n else:\n form = AgendamentosForm(instance=agendamentos)\n turmas = User_Turma.objects.filter(user=request.user).values_list('turma')\n form.fields['turma'].queryset = Turma.objects.filter(pk__in=turmas)\n\n \n context = {\n 'form': form,\n 'agendamentos_id': agendamentos_id\n }\n return render(request, 'agendamentos/editar.html', context)\n\n#excluir\n@login_required\ndef excluir(request, agendamentos_id):\n if request.user.cargo != 'PF':\n return HttpResponseNotAllowed(['GET', 'POST'])\n \n Agendamentos.objects.get(pk=agendamentos_id).delete()\n \n return HttpResponseRedirect(\"/agendamentos\")","repo_name":"Cailane034/projeto","sub_path":"agendamentos/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2680,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"7801219985","text":"ciclos = int(input())\n\nwhile ciclos > 0:\n\n lim = int(input())\n soma = 0\n temp = 1\n\n for i in range(0, lim, 1):\n soma = temp * 2\n temp = soma\n\n print((soma -1))\n\n ciclos -= 1","repo_name":"antonio-abrantes/Estudo-Python-Basico-Solyd-URI","sub_path":"URI/trianguloPascal.py","file_name":"trianguloPascal.py","file_ext":"py","file_size_in_byte":205,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"18319477750","text":"import pandas as pd\nimport pickle\n\ndef compare():\n\n with open('./tmp.pkl', 'rb') as f:\n t = pickle.load(f)\n\n df = pd.read_csv('./data/ra-268.csv')\n\n t2 = []\n for i in range(len(df.index)):\n f = df['audio'].iloc[i].split('/')[-1]\n n = int(df['manual_pauses'].iloc[i])\n t2.append((f, n))\n\n t3 = []\n for i in t:\n for j in t2:\n f1, n1 = i\n n1 -= 1\n f2, n2 = j\n if f1 == f2:\n t3.append((f1, n1, n2))\n\n cnt = 0\n for i in t3:\n if i[1] == i[2]:\n cnt += 1\n\n return cnt * 100.0 / len(t3)\n","repo_name":"jojuo123/pte_silience","sub_path":"utils/compare.py","file_name":"compare.py","file_ext":"py","file_size_in_byte":617,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"43170539722","text":"# model settings\nnorm_cfg = dict(type='SyncBN', requires_grad=True)\nbackbone_norm_cfg = dict(type='LN', requires_grad=True)\nmodel = dict(\n type='EncoderDecoder',\n pretrained=None,\n backbone=dict(\n type='D2SwinTransformer',\n pretrain_img_size=224,\n embed_dims=96,\n patch_size=4,\n window_size=7,\n mlp_ratio=4,\n depths=[2, 2, 6, 2],\n num_heads=[3, 6, 12, 24],\n strides=(4, 2, 2, 2),\n out_indices=(0, 1, 2, 3),\n qkv_bias=True,\n qk_scale=None,\n patch_norm=True,\n drop_rate=0.,\n attn_drop_rate=0.,\n drop_path_rate=0.3,\n use_abs_pos_embed=False,\n out_features=[\"res2\", \"res3\", \"res4\", \"res5\"],\n use_checkpoint=False),\n decode_head=dict(\n type='MaskFormerHead',\n in_channels=[96, 192, 384, 768],\n in_index=[0, 1, 2, 3],\n channels=512,\n dropout_ratio=0.1,\n num_classes=18,\n norm_cfg=norm_cfg,\n align_corners=False,\n loss_decode=dict(\n type='SetCriterion', num_classes=18, losses=[\"labels\", \"masks\"])),\n # model training and testing settings\n train_cfg=dict(),\n test_cfg=dict(mode='whole'))\n","repo_name":"yixinzhishui/mmsegmentation_rsipac","sub_path":"configs_custom/_base_/models/mask2former_swin.py","file_name":"mask2former_swin.py","file_ext":"py","file_size_in_byte":1209,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"12402379076","text":"import glob\nimport numpy as np \nimport matplotlib.pylab as plt\nfrom matplotlib.path import Path\nfrom matplotlib import cm, colors, patches\nfrom astropy.io import fits\nfrom skimage.feature import canny, peak_local_max\nfrom scipy.optimize import curve_fit\nfrom sklearn.cluster import KMeans\nfrom astropy import constants\nfrom scipy.ndimage import gaussian_gradient_magnitude\n\nhalfwidth = 256\npeak_threshold = 0.9 #this really finds the right x-ray peak\n# smoothed_img = gaussian_filter(imcut, 1)\n\ndef filter_edge(file,plot=False, isfile=True,edgecontrast = 4, edge_threshold=0, cut = False):\n\tif isfile:\n\t\timg = fits.open(file)[0].data\n\telse:\n\t\timg = file\n\tcentre = peak_local_max(img,threshold_rel=peak_threshold)\n\tif cut:\n\t\tif len(centre) > 1:\n\t\t\t#is there one peak or are there two?\n\t\t\tkmeans = KMeans(n_clusters=1)\n\t\t\tkmeans.fit(centre)\n\t\t\tccentres = kmeans.cluster_centers_\n\t\t\twss1 = np.mean(np.linalg.norm(centre - ccentres, axis=1))\n\n\t\t\tkmeans = KMeans(n_clusters=2)\n\t\t\tkmeans.fit(centre)\n\t\t\tcid = kmeans.predict(centre)\n\t\t\tccentres = kmeans.cluster_centers_\n\t\t\twss2 = np.mean(np.linalg.norm(centre[cid==0] - ccentres[0], axis=1))\n\t\t\t+np.mean(np.linalg.norm(centre[cid==1] - ccentres[1], axis=1))\n\n\t\t\tif wss2 < wss1: #i.e. 2 clusters better fit\n\t\t\t\tprint(\"2 bright peaks\")\n\t\t\t\tbigger_cluster = np.argmax(np.bincount(cid))\n\t\t\t\tcentre = centre[cid == bigger_cluster] #subselect points around main cluster\n\t\t\tcentre = np.mean(centre,axis = 0)\n\t\t\tcentre = (int(centre[0]), int(centre[1]))\n\n\t\tif type(centre[0]) != int:\n\t\t\tcentre = centre[0]\n\t\tif (centre[0]-halfwidth) < 0:\n\t\t\tleft = 0\n\t\t\tright = 2*halfwidth\n\t\telif (centre[0]+halfwidth) > img.shape[0]:\n\t\t\tright = img.shape[0]\n\t\t\tleft = right - 2*halfwidth\n\t\telse:\n\t\t\tleft, right = centre[0] - halfwidth, centre[0] + halfwidth\n\t\tif (centre[1]-halfwidth) < 0:\n\t\t\tbottom = 0\n\t\t\ttop = 2*halfwidth\n\t\telif (centre[1]+halfwidth) > img.shape[0]:\n\t\t\ttop = img.shape[0]\n\t\t\tbottom = right - 2*halfwidth\n\t\telse:\n\t\t\tbottom, top = centre[1] - halfwidth, centre[1] + halfwidth\n\t\t\n\t\timcut = img[left:right, bottom:top]\n\telse:\n\t\tdim = img.shape[0]\n\t\timcut = img[int(dim/4):int(3*dim/4), int(dim/4):int(3*dim/4)]\n\t\t\n\tedge1 = canny(np.log10(imcut), sigma=edgecontrast, high_threshold=edge_threshold)\n\n\tif plot:\n\t\tplt.imshow(imcut, cmap = cm.viridis, norm = colors.LogNorm(imcut.max()/1e4, imcut.max()))\n\t\tplt.imshow(np.ma.masked_less(edge1*imcut, imcut.max()*peak_threshold), cmap = cm.gray_r, norm = colors.LogNorm(imcut.max()/1e4, imcut.max()))\n\t\t\n\t\ttime = float(file.split('proj_')[1].split('.')[0])/10.\n\t\tplt.title('%0.2f Gyr' % time)\n\t\tplt.savefig('featuremaps/sq_weighted_%0.2f.png' % time)\n\tprint(\"Edges found!\")\n\treturn edge1, imcut\n\nfrom sklearn.cluster import SpectralClustering\nfrom sklearn.preprocessing import StandardScaler\n\ndef cluster(features, nclusters=5):\n\tX = StandardScaler().fit_transform(features)\n\tmodel = SpectralClustering(n_clusters=nclusters, affinity='nearest_neighbors',\n\t\tassign_labels='kmeans')\n\treturn model.fit_predict(X)\n\nfiles = glob.glob('fitsfiles/temp/*fits')\nfiles.sort()\n\nmfp_a2146 = 23 #mean free path in kpc\nresolution = fits.getheader(files[0])['CDELT1']\n\ndef find_features(filenum,isfile=True,type='temp'):\n\tif isfile:\n\t\tfile = files[filenum]\n\telse:\n\t\tfile = filenum\n\timg_edges, img = filter_edge(file, isfile=isfile)\n\tpts = np.argwhere(img_edges)\n\t\n\tif type == 'temp':\n\t\timg *= constants.k_B.to('keV K**-1').value\n\tggm = gaussian_gradient_magnitude(img[img_edges], sigma=mfp_a2146/resolution)\n\n\tpeak = np.argmax(ggm) #can do for more points than just this one \n\treturn img_edges, img, pts, peak, resolution \n\ndef radial_profile(data, center):\n y, x = np.indices((data.shape))\n r = np.sqrt((x - center[0])**2 + (y - center[1])**2)\n r = r.astype(np.int)\n\n keep = ~np.isnan(data.ravel())\n tbin = np.bincount(r.ravel()[keep], data.ravel()[keep])\n nr = np.bincount(r.ravel()[keep])\n radialprofile = tbin / nr\n return radialprofile \n\nfiles = glob.glob('fitsfiles/temp/*fits')\nfiles.sort()\nimg_edges, img, pts, peak, resolution = find_features(5)\n\nfiles = glob.glob('fitsfiles/xray_sb/*fits')\nfiles.sort()\nsb_edges, sb_img, sb_pts, sb_peak, resolution = find_features(16)\n\n##this part is currently very manual because SpectralClustering SUCKS\n##instead, get Paul's script running.\ncid = cluster(pts, nclusters = 7)\nfeature = pts[cid == 1]\nsid = cluster(feature, nclusters = 4)\nbow = feature[sid == 0]\n\ndef main(sb_img, img, bow):\n\tcentre = peak_local_max(sb_img, min_distance = 15)\n\tcentre = centre[0]\n\ttheta = np.rad2deg(np.arctan2(bow[:,0] - centre[0], bow[:,1] - centre[1]))\n\ttheta[theta < 0] += 360\n\trad = np.mean(np.linalg.norm(bow - centre, axis=1))\n\tw1 = patches.Wedge((centre[1], centre[0]), 1.2*rad, theta.min(), theta.max(),color='w', alpha=0.4)\n\t\n\tX,Y=np.mgrid[0:img.shape[1],0:img.shape[0]]\n\tpoints = np.vstack((X.ravel(),Y.ravel())).T\n\n\tpath = Path(w1.properties()['path'].vertices)\n\tgrid = path.contains_points(points).reshape(img.shape)\n\twedge = img*grid.T\n\twedge[wedge == 0] = np.nan\n\tprofile = radial_profile(wedge, centre)\n\tplt.plot(np.arange(len(profile)), profile)\n","repo_name":"milchada/GalaxyClusterMergerAnalysis","sub_path":"doc/build/lib/gcmerge/make_profiles.py","file_name":"make_profiles.py","file_ext":"py","file_size_in_byte":5081,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"22706491326","text":"import copy\nimport time\n\netapa = 1 #etapa curenta\nnrMiscariFaraStergere = 0\neuristica = 0\nnrMiscariJMIN = 0\nnrMiscariJMAX = 0\n\nclass Joc:\n \"\"\"\n Clasa care defineste jocul. Se va schimba de la un joc la altul.\n \"\"\"\n SIMBOLURI_JUC = ['X', 'O']\n JMIN = None\n JMAX = None\n GOL = '#'\n\n def __init__(self, tabla=None):\n self.config = tabla or [Joc.GOL] * 24\n self.liniiMori = [\n [0,1,2], [2,4,7], [5,6,7], [0,3,5], [8,9,10], [10,12,15], [13,14,15], [8,11,13], [16,17,18], [18,20,23],\n [21,22,23], [16,19,21], [1,9,17], [4,12,20], [6,14,22], [3,11,19]\n ]\n\n\n def numarPiese(self, piesa): #functie care numara cate piese de un anumit fel sunt pe tabla\n return self.config.count(piesa)\n\n\n def pozitiiVecine(self, poz): #functie care primeste ca parametru o pozitie si intoarce o lista cu\n vecini = [ #pozitiile vecine acelei pozitii\n [1, 3], #0\n [0, 2, 9], #1\n [1, 4], #2\n [0, 5, 11], #3\n [2, 7, 12], #4\n [3, 6], #5\n [5, 7, 14], #6\n [4, 6], #7\n [9, 11], #8\n [1, 8, 10, 17], #9\n [9, 12], #10\n [3, 8, 13, 19], #11\n [4, 10, 15, 20], #12\n [11, 14], #13\n [6, 13, 15, 22], #14\n [12, 14], #15\n [17, 19], #16\n [9, 16, 18], #17\n [17, 20], #18\n [11, 16, 21], #19\n [12, 18, 23], #20\n [19, 22], #21\n [14, 21, 23], #22\n [20, 22], #23\n ]\n\n return vecini[poz]\n\n\n def verifica2Pozitii(self, tabla, piesaJucator, p1, p2): #verifica daca pe cele 2 pozitii p1, p2 se\n if (tabla[p1] == piesaJucator and tabla[p2] == piesaJucator): #afla piese care apartin aceluiasi jucator\n return True\n return False\n\n\n def verificaVecini(self, tabla, piesaJucator, poz): #verifica daca exista 2 pozitii pe aceeasi linie\n #cu poz in care sa fie piese ale aceluiasi jucator\n lista = [\n (self.verifica2Pozitii(tabla, piesaJucator, 1, 2) or self.verifica2Pozitii(tabla, piesaJucator, 3, 5)), #0\n (self.verifica2Pozitii(tabla, piesaJucator, 0, 2) or self.verifica2Pozitii(tabla, piesaJucator, 9, 17)), #1\n (self.verifica2Pozitii(tabla, piesaJucator, 0, 1) or self.verifica2Pozitii(tabla, piesaJucator, 4, 7)), #2\n (self.verifica2Pozitii(tabla, piesaJucator, 0, 5) or self.verifica2Pozitii(tabla, piesaJucator, 11, 19)), #3\n (self.verifica2Pozitii(tabla, piesaJucator, 2, 7) or self.verifica2Pozitii(tabla, piesaJucator, 12, 20)), #4\n (self.verifica2Pozitii(tabla, piesaJucator, 0, 3) or self.verifica2Pozitii(tabla, piesaJucator, 6, 7)), #5\n (self.verifica2Pozitii(tabla, piesaJucator, 5, 7) or self.verifica2Pozitii(tabla, piesaJucator, 14, 22)), #6\n (self.verifica2Pozitii(tabla, piesaJucator, 2, 4) or self.verifica2Pozitii(tabla, piesaJucator, 5, 6)), #7\n (self.verifica2Pozitii(tabla, piesaJucator, 9, 10) or self.verifica2Pozitii(tabla, piesaJucator, 11, 13)), #8\n (self.verifica2Pozitii(tabla, piesaJucator, 8, 10) or self.verifica2Pozitii(tabla, piesaJucator, 1, 17)), #9\n (self.verifica2Pozitii(tabla, piesaJucator, 8, 9) or self.verifica2Pozitii(tabla, piesaJucator, 12, 15)), #10\n (self.verifica2Pozitii(tabla, piesaJucator, 3, 19) or self.verifica2Pozitii(tabla, piesaJucator, 8, 13)), #11\n (self.verifica2Pozitii(tabla, piesaJucator, 20, 4) or self.verifica2Pozitii(tabla, piesaJucator, 10, 15)), #12\n (self.verifica2Pozitii(tabla, piesaJucator, 8, 11) or self.verifica2Pozitii(tabla, piesaJucator, 14, 15)), #13\n (self.verifica2Pozitii(tabla, piesaJucator, 13, 15) or self.verifica2Pozitii(tabla, piesaJucator, 6, 22)), #14\n (self.verifica2Pozitii(tabla, piesaJucator, 13, 14) or self.verifica2Pozitii(tabla, piesaJucator, 10, 12)), #15\n (self.verifica2Pozitii(tabla, piesaJucator, 17, 18) or self.verifica2Pozitii(tabla, piesaJucator, 19, 21)), #16\n (self.verifica2Pozitii(tabla, piesaJucator, 1, 9) or self.verifica2Pozitii(tabla, piesaJucator, 16, 18)), #17\n (self.verifica2Pozitii(tabla, piesaJucator, 16, 17) or self.verifica2Pozitii(tabla, piesaJucator, 20, 23)), #18\n (self.verifica2Pozitii(tabla, piesaJucator, 16, 21) or self.verifica2Pozitii(tabla, piesaJucator, 3, 11)), #19\n (self.verifica2Pozitii(tabla, piesaJucator, 12, 4) or self.verifica2Pozitii(tabla, piesaJucator, 18, 23)), #20\n (self.verifica2Pozitii(tabla, piesaJucator, 16, 19) or self.verifica2Pozitii(tabla, piesaJucator, 22, 23)), #21\n (self.verifica2Pozitii(tabla, piesaJucator, 6, 14) or self.verifica2Pozitii(tabla, piesaJucator, 21, 23)), #22\n (self.verifica2Pozitii(tabla, piesaJucator, 18, 20) or self.verifica2Pozitii(tabla, piesaJucator, 21, 22)), #23\n ]\n\n return lista[poz]\n\n\n def esteMoara(self, tabla, poz): #verifica daca exista o moara pentru un jucator\n #in pozitia poz\n piesaJucator = tabla[poz]\n\n if(piesaJucator == '#'):\n return False\n\n return self.verificaVecini(tabla, piesaJucator, poz)\n\n def toatePieseleInMoara(self, jucator): #verifica daca toate piesele unui jucator se afla in mori\n toateMoara = True\n for i in range(0,24):\n if self.config[i] == jucator:\n if not self.esteMoara(self.config, i):\n toateMoara = False\n break\n\n return toateMoara\n\n def jucatorOpus(self, jucator):\n if jucator == Joc.JMIN:\n return Joc.JMAX\n else:\n return Joc.JMIN\n\n\n def nrValoriPeLinieDeschisa(self, jucator, n): #returneaza numarul de linii in care nu exista piese apartinand oponentului si in care\n #se afla n piese ale jucatorului\n count = 0\n adversar = self.jucatorOpus(jucator)\n for linie in self.liniiMori:\n valori = [self.config[linie[0]], self.config[linie[1]], self.config[linie[2]]]\n if adversar not in valori:\n nr = valori.count(jucator)\n if nr == n:\n count += 1\n\n return count\n\n\n def final(self):\n if etapa != 1:\n nrPieseJMIN = self.numarPiese(Joc.JMIN)\n nrPieseJMAX = self.numarPiese(Joc.JMAX)\n\n nrMutariJMIN = len(self.mutari_joc(Joc.JMIN))\n nrMutariJMAX = len(self.mutari_joc(Joc.JMAX))\n\n if nrPieseJMIN <= 2 or nrMutariJMIN == 0:\n return Joc.JMAX\n elif nrPieseJMAX <= 2 or nrMutariJMAX == 0:\n return Joc.JMIN\n elif nrMiscariFaraStergere == 20:\n if nrPieseJMAX > nrPieseJMIN:\n return Joc.JMAX\n elif nrPieseJMAX < nrPieseJMIN:\n return Joc.JMIN\n else:\n return 'remiza'\n else:\n return False\n else:\n return False\n\n\n def mutari_joc(self, jucator):\n \"\"\"\n Pentru configuratia curenta de joc \"self.config\" (de tip lista, cu 24 elemente),\n trebuie sa returnati o lista \"l_mutari\" cu elemente de tip Joc,\n corespunzatoare tuturor configuratiilor-succesor posibile.\n\n \"jucator\" este simbolul jucatorului care face mutarea\n \"\"\"\n l_mutari = []\n\n if etapa == 1: #etapa 1: plasarea pieselor fara restrictii\n for i in range(len(self.config)):\n if self.config[i] == Joc.GOL:\n copieTabla = copy.deepcopy(self.config)\n copieTabla[i] = jucator\n\n if self.esteMoara(copieTabla, i):\n for j in range(len(copieTabla)):\n if copieTabla[j] == self.jucatorOpus(jucator) and not self.esteMoara(copieTabla, j):\n copieTablaStergere = copy.deepcopy(copieTabla)\n copieTablaStergere[j] = Joc.GOL\n l_mutari.append(Joc(copieTablaStergere))\n else:\n l_mutari.append(Joc(copieTabla))\n\n else:\n if self.numarPiese(jucator) != 3: #etapa 2: mutarea de piese in pozitii adiacente\n for i in range(len(self.config)):\n if self.config[i] == jucator:\n pozitiiAdiacente = self.pozitiiVecine(i)\n\n for poz in pozitiiAdiacente:\n if self.config[poz] == Joc.GOL:\n copieTabla = copy.deepcopy(self.config)\n copieTabla[i] = Joc.GOL\n copieTabla[poz] = jucator\n\n if self.esteMoara(copieTabla, poz):\n for j in range(len(copieTabla)):\n if copieTabla[j] == self.jucatorOpus(jucator) and not self.esteMoara(copieTabla, j):\n copieTablaStergere = copy.deepcopy(copieTabla)\n copieTablaStergere[j] = Joc.GOL\n l_mutari.append(Joc(copieTablaStergere))\n else:\n l_mutari.append(Joc(copieTabla))\n\n else:\n for i in range(len(self.config)): #etapa 3: mutarea de piese in orice pozitie libera cand jucatorul ajunge la 3 piese\n if self.config[i] == jucator:\n for j in range(len(self.config)):\n if self.config[j] == Joc.GOL:\n copieTabla = copy.deepcopy(self.config)\n copieTabla[i] = Joc.GOL\n copieTabla[j] = jucator\n\n if self.esteMoara(copieTabla, j):\n for k in range(len(copieTabla)):\n if copieTabla[k] == self.jucatorOpus(jucator) and not self.esteMoara(copieTabla, k):\n copieTablaStergere = copy.deepcopy(copieTabla)\n copieTablaStergere[k] = Joc.GOL\n l_mutari.append(Joc(copieTablaStergere))\n else:\n l_mutari.append(Joc(copieTabla))\n\n return l_mutari\n\n def euristicaNrPiese(self): #euristica care se foloseste de numarul de piese ale jucatorilor\n nrPieseJMIN = self.numarPiese(Joc.JMIN)\n nrPieseJMAX = self.numarPiese(Joc.JMAX)\n\n return nrPieseJMAX - nrPieseJMIN\n\n\n def eursiticaNrLiniiDeschise(self):\n linii2PieseJMAX = self.nrValoriPeLinieDeschisa(Joc.JMAX, 2)\n linii2PieseJMIN = self.nrValoriPeLinieDeschisa(Joc.JMIN, 2)\n linii1PiesaJMAX = self.nrValoriPeLinieDeschisa(Joc.JMAX, 1)\n linii1PiesaJMIN = self.nrValoriPeLinieDeschisa(Joc.JMIN, 1)\n\n return (2 * linii2PieseJMAX + linii1PiesaJMAX + self.numarPiese(Joc.JMAX)) - (2 * linii2PieseJMIN + linii1PiesaJMIN + self.numarPiese(Joc.JMIN))\n\n\n def estimeaza_scor(self, adancime):\n t_final = self.final()\n if t_final == Joc.JMAX:\n return (99 + adancime)\n elif t_final == Joc.JMIN:\n return (-99 - adancime)\n elif t_final == 'remiza':\n return 0\n else:\n if euristica == 1:\n return self.euristicaNrPiese()\n if euristica == 2:\n return self.eursiticaNrLiniiDeschise()\n\n def __str__(self):\n sir = (\n \"[00]\" + self.config[0] + \"------------------------[01]\" + self.config[1] + \"------------------------[02]\" + self.config[2] + \"\\n\" +\n \" | | |\" + \"\\n\" +\n \" | | |\" + \"\\n\" +\n \" | [08]\" + self.config[8] + \"--------------[09]\" + self.config[9] + \"--------------[10]\" + self.config[10] + \" |\" + \"\\n\" +\n \" | | | | |\" + \"\\n\" +\n \" | | | | |\" + \"\\n\" +\n \" | | [16]\" + self.config[16] + \"----[17]\" + self.config[17] + \"----[18]\" + self.config[18] + \" | |\" + \"\\n\" +\n \" | | | | | |\" + \"\\n\" +\n \" | | | | | |\" + \"\\n\" +\n \"[03]\" + self.config[3] + \"-----[11]\" + self.config[11] + \"-----[19]\" + self.config[19] + \" [20]\" + self.config[20] + \"-----[12]\" + self.config[12] + \"-----[04]\" +self.config[4] + \"\\n\" +\n \" | | | | | |\" + \"\\n\" +\n \" | | | | | |\" + \"\\n\" +\n \" | | [21]\" + self.config[21] + \"----[22]\" + self.config[22] + \"----[23]\" + self.config[23] + \" | |\" + \"\\n\" +\n \" | | | | |\" + \"\\n\" +\n \" | | | | |\" + \"\\n\" +\n \" | [13]\" + self.config[13] + \"--------------[14]\" + self.config[14] + \"--------------[15]\" + self.config[15] + \" |\" + \"\\n\" +\n \" | | |\" + \"\\n\" +\n \" | | |\" + \"\\n\" +\n \"[05]\" + self.config[5] + \"------------------------[06]\" + self.config[6] + \"------------------------[07]\" + self.config[7] + \"\\n\"\n )\n\n return sir\n\n\nclass Stare:\n \"\"\"\n Clasa folosita de algoritmii minimax si alpha-beta\n Are ca proprietate tabla de joc\n Functioneaza cu conditia ca in cadrul clasei Joc sa fie definiti JMIN si JMAX (cei doi jucatori posibili)\n De asemenea cere ca in clasa Joc sa fie definita si o metoda numita mutari_joc() care ofera lista cu\n configuratiile posibile in urma mutarii unui jucator\n \"\"\"\n\n ADANCIME_MAX = None\n\n def __init__(self, tabla_joc, j_curent, adancime, parinte=None, scor=None):\n self.tabla_joc = tabla_joc # un obiect de tip Joc => „tabla_joc.matr”\n self.j_curent = j_curent # simbolul jucatorului curent\n\n # adancimea in arborele de stari\n #\t(scade cu cate o unitate din „tata” in „fiu”)\n self.adancime = adancime\n\n # scorul starii (daca e finala, adica frunza a arborelui)\n # sau scorul celei mai bune stari-fiice (pentru jucatorul curent)\n self.scor = scor\n\n # lista de mutari posibile din starea curenta\n self.mutari_posibile = [] # lista va contine obiecte de tip Stare\n\n # cea mai buna mutare din lista de mutari posibile pentru jucatorul curent\n self.stare_aleasa = None\n\n def jucator_opus(self):\n if self.j_curent == Joc.JMIN:\n return Joc.JMAX\n else:\n return Joc.JMIN\n\n def mutari_stare(self):\n l_mutari = self.tabla_joc.mutari_joc(self.j_curent)\n juc_opus = self.jucator_opus()\n\n l_stari_mutari = [Stare(mutare, juc_opus, self.adancime - 1, parinte=self) for mutare in l_mutari]\n return l_stari_mutari\n\n def __str__(self):\n sir = str(self.tabla_joc) + \"(Juc curent:\" + self.j_curent + \")\\n\"\n return sir\n\n\n\"\"\" Algoritmul MinMax \"\"\"\n\n\ndef min_max(stare):\n # Daca am ajuns la o frunza a arborelui, adica:\n # - daca am expandat arborele pana la adancimea maxima permisa\n # - sau daca am ajuns intr-o configuratie finala de joc\n if stare.adancime == 0 or stare.tabla_joc.final():\n # calculam scorul frunzei apeland \"estimeaza_scor\"\n stare.scor = stare.tabla_joc.estimeaza_scor(stare.adancime)\n return stare\n\n # Altfel, calculez toate mutarile posibile din starea curenta\n stare.mutari_posibile = stare.mutari_stare()\n\n # aplic algoritmul minimax pe toate mutarile posibile (calculand astfel subarborii lor)\n mutari_scor = [min_max(mutare) for mutare in stare.mutari_posibile]\n\n if stare.j_curent == Joc.JMAX:\n # daca jucatorul e JMAX aleg starea-fiica cu scorul maxim\n stare.stare_aleasa = max(mutari_scor, key=lambda x: x.scor)\n else:\n # daca jucatorul e JMIN aleg starea-fiica cu scorul minim\n stare.stare_aleasa = min(mutari_scor, key=lambda x: x.scor)\n\n # actualizez scorul „tatalui” = scorul „fiului” ales\n stare.scor = stare.stare_aleasa.scor\n return stare\n\n\ndef alpha_beta(alpha, beta, stare):\n # Daca am ajuns la o frunza a arborelui, adica:\n # - daca am expandat arborele pana la adancimea maxima permisa\n # - sau daca am ajuns intr-o configuratie finala de joc\n if stare.adancime == 0 or stare.tabla_joc.final():\n # calculam scorul frunzei apeland \"estimeaza_scor\"\n stare.scor = stare.tabla_joc.estimeaza_scor(stare.adancime)\n return stare\n\n # Conditia de retezare:\n if alpha >= beta:\n return stare # este intr-un interval invalid, deci nu o mai procesez\n\n # Calculez toate mutarile posibile din starea curenta (toti „fiii”)\n stare.mutari_posibile = stare.mutari_stare()\n\n if stare.j_curent == Joc.JMAX:\n scor_curent = float('-inf') # scorul „tatalui” de tip MAX\n\n # pentru fiecare „fiu” de tip MIN:\n for mutare in stare.mutari_posibile:\n # calculeaza scorul fiului curent\n stare_noua = alpha_beta(alpha, beta, mutare)\n\n # incerc sa imbunatatesc (cresc) scorul si alfa\n # „tatalui” de tip MAX, folosind scorul fiului curent\n if scor_curent < stare_noua.scor:\n stare.stare_aleasa = stare_noua\n scor_curent = stare_noua.scor\n\n if alpha < stare_noua.scor:\n alpha = stare_noua.scor\n if alpha >= beta: # verific conditia de retezare\n break # NU se mai extind ceilalti fii de tip MIN\n\n\n elif stare.j_curent == Joc.JMIN:\n scor_curent = float('inf') # scorul „tatalui” de tip MIN\n\n # pentru fiecare „fiu” de tip MAX:\n for mutare in stare.mutari_posibile:\n stare_noua = alpha_beta(alpha, beta, mutare)\n\n # incerc sa imbunatatesc (scad) scorul si beta\n # „tatalui” de tip MIN, folosind scorul fiului curent\n if scor_curent > stare_noua.scor:\n stare.stare_aleasa = stare_noua\n scor_curent = stare_noua.scor\n\n if beta > stare_noua.scor:\n beta = stare_noua.scor\n if alpha >= beta: # verific conditia de retezare\n break # NU se mai extind ceilalti fii de tip MAX\n\n # actualizez scorul „tatalui” = scorul „fiului” ales\n stare.scor = stare.stare_aleasa.scor\n\n return stare\n\n\ndef afis_daca_final(stare_curenta):\n final = stare_curenta.tabla_joc.final()\n if (final):\n if (final == \"remiza\"):\n print(\"Remiza!\")\n print(\"Scor jucator: \" + str(stare_curenta.tabla_joc.numarPiese(Joc.JMIN)))\n print(\"Scor calculator: \" + str(stare_curenta.tabla_joc.numarPiese(Joc.JMAX)))\n else:\n print(\"A castigat \" + final)\n print(\"Scor jucator: \" + str(stare_curenta.tabla_joc.numarPiese(Joc.JMIN)))\n print(\"Scor calculator: \" + str(stare_curenta.tabla_joc.numarPiese(Joc.JMAX)))\n\n return True\n\n return False\n\n\ndef main():\n # initializare algoritm\n global etapa, nrMiscariFaraStergere, euristica, nrMiscariJMIN, nrMiscariJMAX\n raspuns_valid = False\n while not raspuns_valid:\n tip_algoritm = input(\"Algorimul folosit? (raspundeti cu 1 sau 2)\\n 1.Minimax\\n 2.Alpha-Beta\\n \")\n if tip_algoritm in ['1', '2']:\n raspuns_valid = True\n else:\n print(\"Nu ati ales o varianta corecta!\")\n\n # initializare dificultate\n raspuns_valid = False\n nivel = [1, 2, 3]\n while not raspuns_valid:\n n = int(input(\"Nivelul de dificultate:\\n 1.Usor\\n 2.Mediu\\n 3.Avansat\\n \"))\n if n in nivel:\n if n == 1:\n Stare.ADANCIME_MAX = 2\n if n == 2:\n Stare.ADANCIME_MAX = 4\n if n == 3:\n Stare.ADANCIME_MAX = 6\n raspuns_valid = True\n else:\n print(\"Trebuie sa introduceti un numar natural intre 1 si 3!\")\n\n raspuns_valid = False\n while not raspuns_valid:\n tip_euristica = input(\"Euristica folosita? \\n 1.Numar de piese\\n 2.Numar de linii deschise\\n \")\n if tip_euristica in ['1', '2']:\n euristica = int(tip_euristica)\n raspuns_valid = True\n else:\n print(\"Nu ati ales o varianta corecta!\")\n\n # initializare jucatori\n raspuns_valid = False\n while not raspuns_valid:\n Joc.JMIN = input(\"Doriti sa jucati cu X sau cu O? \")\n if (Joc.JMIN in Joc.SIMBOLURI_JUC):\n raspuns_valid = True\n else:\n print(\"Raspunsul trebuie sa fie X sau O.\")\n Joc.JMAX = 'O' if Joc.JMIN == 'X' else 'X'\n\n # initializare tabla\n tabla_curenta = Joc()\n print(\"Tabla initiala\")\n print(str(tabla_curenta))\n\n # creare stare initiala\n stare_curenta = Stare(tabla_curenta, Joc.JMIN, Stare.ADANCIME_MAX)\n\n for i in range(18):\n if (stare_curenta.j_curent == Joc.JMIN):\n #plaseaza jucatorul\n t_inainte = int(round(time.time() * 1000))\n raspuns_valid = False\n while not raspuns_valid:\n try:\n poz = input(\"\\nPlaseaza piesa pe pozitia: \")\n\n if poz == 'exit':\n print(\"Scor jucator: \" + str(stare_curenta.tabla_joc.numarPiese(Joc.JMIN)))\n print(\"Scor calculator: \" + str(stare_curenta.tabla_joc.numarPiese(Joc.JMAX)))\n return\n\n poz = int(poz)\n\n if (poz in range(0, 24)):\n if stare_curenta.tabla_joc.config[poz] == Joc.GOL: #daca pozitia e goala\n stare_curenta.tabla_joc.config[poz] = Joc.JMIN #plasam piesa\n if stare_curenta.tabla_joc.esteMoara(stare_curenta.tabla_joc.config, poz): #daca este moara\n piesaStearsa = False\n while not piesaStearsa:\n try:\n poz = int(input(\"\\nSterge piesa adversarului: \"))\n\n if poz in range(0,24):\n if stare_curenta.tabla_joc.config[poz] == Joc.JMAX and not stare_curenta.tabla_joc.esteMoara(stare_curenta.tabla_joc.config, poz) or (\n stare_curenta.tabla_joc.esteMoara(stare_curenta.tabla_joc.config, poz) and stare_curenta.tabla_joc.numarPiese(Joc.JMIN) == 3) or (\n stare_curenta.tabla_joc.toatePieseleInMoara(Joc.JMAX)\n ):\n stare_curenta.tabla_joc.config[poz] = Joc.GOL\n piesaStearsa = True\n else:\n print(\"\\nPozitie invalida!\")\n else:\n print(\"\\nPozitie invalida! (trebuie sa fie un numar intre 0 si 23).\")\n except ValueError:\n print(\"\\nPozitia trebuie sa fie numer intreg!\")\n\n raspuns_valid = True\n else:\n print(\"\\nExista deja o piesa in pozitia ceruta!\")\n else:\n print(\"\\nPozitie invalida! (trebuie sa fie un numar intre 0 si 23).\")\n\n except ValueError:\n print(\"\\nPozitia trebuie sa fie numer intreg!\")\n\n print(\"\\nTabla dupa mutarea jucatorului\")\n print(str(stare_curenta))\n\n nrMiscariJMIN += 1\n\n t_dupa = int(round(time.time() * 1000))\n print(\"Jucatorul a \\\"gandit\\\" timp de \" + str(t_dupa - t_inainte) + \" milisecunde.\")\n\n if (afis_daca_final(stare_curenta)):\n break\n\n stare_curenta.j_curent = stare_curenta.jucator_opus()\n\n else:\n #plaseaza calculatorul\n t_inainte = int(round(time.time() * 1000))\n if tip_algoritm == '1':\n stare_actualizata = min_max(stare_curenta)\n else: # tip_algoritm==2\n stare_actualizata = alpha_beta(-500, 500, stare_curenta)\n stare_curenta.tabla_joc = stare_actualizata.stare_aleasa.tabla_joc\n print(\"Tabla dupa mutarea calculatorului\")\n print(str(stare_curenta))\n\n nrMiscariJMAX += 1\n\n # preiau timpul in milisecunde de dupa mutare\n t_dupa = int(round(time.time() * 1000))\n print(\"Calculatorul a \\\"gandit\\\" timp de \" + str(t_dupa - t_inainte) + \" milisecunde.\")\n\n if (afis_daca_final(stare_curenta)):\n break\n\n # S-a realizat o mutare. Schimb jucatorul cu cel opus\n stare_curenta.j_curent = stare_curenta.jucator_opus()\n\n etapa = 2\n\n while True:\n if (stare_curenta.j_curent == Joc.JMIN):\n # plaseaza jucatorul\n nrPieseJMAX = stare_curenta.tabla_joc.numarPiese(Joc.JMAX)\n t_inainte = int(round(time.time() * 1000))\n raspuns_valid = False\n while not raspuns_valid:\n try:\n poz = input(\"\\nMuta piesa de pe pozitia: \")\n\n if poz == 'exit':\n print(\"Scor jucator: \" + str(stare_curenta.tabla_joc.numarPiese(Joc.JMIN)))\n print(\"Scor calculator: \" + str(stare_curenta.tabla_joc.numarPiese(Joc.JMAX)))\n return\n\n poz = int(poz)\n\n if (poz in range(0, 24)):\n if stare_curenta.tabla_joc.config[poz] == Joc.JMIN: # daca pozitia are piesa JMIN\n if(stare_curenta.tabla_joc.numarPiese(Joc.JMIN) == 3): #daca jucatorul are doar 3 piese(este in etapa 3)\n piesaPlasata = False\n while not piesaPlasata:\n pozNoua = int(input(\"\\nPozitie noua: \"))\n\n if (pozNoua in range(0, 24)):\n if stare_curenta.tabla_joc.config[pozNoua] == Joc.GOL:\n stare_curenta.tabla_joc.config[poz] = Joc.GOL\n stare_curenta.tabla_joc.config[pozNoua] = Joc.JMIN\n\n if stare_curenta.tabla_joc.esteMoara(stare_curenta.tabla_joc.config,\n pozNoua): # daca este moara\n piesaStearsa = False\n while not piesaStearsa:\n try:\n pozSt = int(input(\"\\nSterge piesa adversarului: \"))\n\n if pozSt in range(0, 24):\n if stare_curenta.tabla_joc.config[\n pozSt] == Joc.JMAX and not stare_curenta.tabla_joc.esteMoara(\n stare_curenta.tabla_joc.config, pozSt) or (\n stare_curenta.tabla_joc.esteMoara(\n stare_curenta.tabla_joc.config,\n pozSt) and stare_curenta.tabla_joc.numarPiese(\n Joc.JMIN) == 3) or (stare_curenta.tabla_joc.toatePieseleInMoara(Joc.JMAX)):\n stare_curenta.tabla_joc.config[pozSt] = Joc.GOL\n piesaStearsa = True\n else:\n print(\"\\nPozitie invalida!\")\n else:\n print(\"\\nPozitie invalida! (trebuie sa fie un numar intre 0 si 23).\")\n except ValueError:\n print(\"\\nPozitia trebuie sa fie numer intreg!\")\n\n piesaPlasata = True\n raspuns_valid = True\n\n else:\n print(\"\\nExista deja o piesa in pozitia ceruta!\")\n else:\n print(\"\\nPozitie invalida! (trebuie sa fie un numar intre 0 si 23).\")\n\n else: #daca jucatorul are mai mult de 3 piese (este in etapa 2)\n vecini = stare_curenta.tabla_joc.pozitiiVecine(poz) #aflam pozitiile adiacente cu poz\n pozVecinaLibera = False\n for p in vecini:\n if stare_curenta.tabla_joc.config[p] == Joc.GOL: #verificam daca exista o pozitie vecina libera\n pozVecinaLibera = True\n break\n\n if pozVecinaLibera:\n piesaPlasata = False\n while not piesaPlasata:\n pozNoua = int(input(\"\\nPozitie noua: \"))\n\n if (pozNoua in vecini):\n if stare_curenta.tabla_joc.config[pozNoua] == Joc.GOL:\n stare_curenta.tabla_joc.config[poz] = Joc.GOL\n stare_curenta.tabla_joc.config[pozNoua] = Joc.JMIN\n\n if stare_curenta.tabla_joc.esteMoara(stare_curenta.tabla_joc.config,\n pozNoua): # daca este moara\n piesaStearsa = False\n while not piesaStearsa:\n try:\n pozSt = int(input(\"\\nSterge piesa adversarului: \"))\n if pozSt in range(0, 24):\n if stare_curenta.tabla_joc.config[\n pozSt] == Joc.JMAX and not stare_curenta.tabla_joc.esteMoara(\n stare_curenta.tabla_joc.config, pozSt) or (\n stare_curenta.tabla_joc.esteMoara(\n stare_curenta.tabla_joc.config,\n pozSt) and stare_curenta.tabla_joc.numarPiese(\n Joc.JMIN) == 3) or (stare_curenta.tabla_joc.toatePieseleInMoara(Joc.JMAX)):\n stare_curenta.tabla_joc.config[pozSt] = Joc.GOL\n piesaStearsa = True\n else:\n print(\"\\nPozitie invalida!\")\n else:\n print(\"\\nPozitie invalida! (trebuie sa fie un numar intre 0 si 23).\")\n except ValueError:\n print(\"\\nPozitia trebuie sa fie numer intreg!\")\n\n piesaPlasata = True\n raspuns_valid = True\n\n else:\n print(\"\\nExista deja o piesa in pozitia ceruta!\")\n else:\n print(\"\\nPozitie invalida!\")\n else:\n print(\"\\nPiesa este blocata!\")\n\n except ValueError:\n print(\"\\nPozitia trebuie sa fie numer intreg!\")\n\n print(\"\\nTabla dupa mutarea jucatorului\")\n print(str(stare_curenta))\n\n nrMiscariJMIN += 1\n\n t_dupa = int(round(time.time() * 1000))\n print(\"Jucatorul a \\\"gandit\\\" timp de \" + str(t_dupa - t_inainte) + \" milisecunde.\")\n\n nrPieseJMAXNou = stare_curenta.tabla_joc.numarPiese(Joc.JMAX)\n nrMiscariFaraStergere += 1\n if(nrPieseJMAXNou < nrPieseJMAX):\n nrMiscariFaraStergere = 0\n\n\n if (afis_daca_final(stare_curenta)):\n break\n\n stare_curenta.j_curent = stare_curenta.jucator_opus()\n # --------------------------------\n else: # jucatorul e JMAX (calculatorul)\n # plaseaza calculatorul\n nrPieseJMIN = stare_curenta.tabla_joc.numarPiese(Joc.JMIN)\n t_inainte = int(round(time.time() * 1000))\n if tip_algoritm == '1':\n stare_actualizata = min_max(stare_curenta)\n else: # tip_algoritm==2\n stare_actualizata = alpha_beta(-500, 500, stare_curenta)\n stare_curenta.tabla_joc = stare_actualizata.stare_aleasa.tabla_joc\n print(\"Tabla dupa mutarea calculatorului\")\n print(str(stare_curenta))\n\n nrMiscariJMAX += 1\n\n # preiau timpul in milisecunde de dupa mutare\n t_dupa = int(round(time.time() * 1000))\n print(\"Calculatorul a \\\"gandit\\\" timp de \" + str(t_dupa - t_inainte) + \" milisecunde.\")\n\n nrPieseJMINNou = stare_curenta.tabla_joc.numarPiese(Joc.JMIN)\n nrMiscariFaraStergere += 1\n if (nrPieseJMINNou < nrPieseJMIN):\n nrMiscariFaraStergere = 0\n\n if (afis_daca_final(stare_curenta)):\n break\n\n # S-a realizat o mutare. Schimb jucatorul cu cel opus\n stare_curenta.j_curent = stare_curenta.jucator_opus()\n\nif __name__ == \"__main__\":\n t_inainte = int(round(time.time() * 1000))\n main()\n t_dupa = int(round(time.time() * 1000))\n print(\"Meciul a durat \" + str(t_dupa - t_inainte) + \" milisecunde.\")\n print(\"Numar miscari jucator: \" + str(nrMiscariJMIN))\n print(\"Numar miscari calculator: \" + str(nrMiscariJMAX))","repo_name":"MikeDerWolf/Nine-men-s-morris-intar-","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":36861,"program_lang":"python","lang":"ro","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"71558831946","text":"import logging\nfrom functools import lru_cache\n\nimport torch\nimport torch.nn.functional as F\nfrom torch import nn\n\nfrom models.utils import allgather_wgrad\nfrom utils.distributed import get_rank, get_world_size\nfrom utils.easydict import EasyDict\n\nlogger = logging.getLogger(__name__)\n\n\ndef get_sim(\n vision_proj: torch.Tensor,\n text_proj: torch.Tensor,\n temp=1.0,\n):\n \"\"\"calculate pair-wise video-text similarity.\n\n Args:\n vision_proj (torch.Tensor): The vision representation. Shape: [B,T,C].\n text_proj (torch.Tensor): The text representation. Shape: [B,C].\n temp (torch.Tensor): The temperature. Shape: [].\n\n Returns: The similarity between video and text. Shape: [B,B].\n\n \"\"\"\n vision_proj = F.normalize(vision_proj, dim=-1)\n text_proj = F.normalize(text_proj, dim=-1)\n sim_v2t = torch.einsum(\"mld,nd->mln\", vision_proj, text_proj).mean(1) / temp # (B,B)\n sim_t2v = sim_v2t.T\n return sim_v2t, sim_t2v\n\n\nclass VTC_VTM_Loss(nn.Module):\n \"\"\"video-text contrastive and matching losses.\"\"\"\n\n def __init__(self, vtm_hard_neg):\n super().__init__()\n self.vtm_hard_neg = vtm_hard_neg\n\n def vtc_loss(\n self,\n vision_proj: torch.Tensor,\n text_proj: torch.Tensor,\n idx: torch.Tensor,\n temp=1.0,\n all_gather=True,\n ):\n \"\"\"forward to calculate the loss\n\n Args:\n vision_proj (torch.Tensor): The vision representation. Shape: [B,T,C].\n text_proj (torch.Tensor): The text representation. Shape: [B,C].\n idx (torch.Tensor): The index for each example. Shape: [B,].\n temp (torch.Tensor): The temperature. Shape: [].\n all_gather (bool): If true, will gather samples across all the GPUs and calculate loss across the gathered samples.\n\n Returns: loss_vtc (torch.Tensor): The video-text contrastive loss. Shape: [].\n\n \"\"\"\n if all_gather:\n gather_args = self.get_gather_args()\n vision_proj = allgather_wgrad(vision_proj, gather_args)\n text_proj = allgather_wgrad(text_proj, gather_args)\n if idx is not None:\n idx = allgather_wgrad(idx, gather_args)\n\n sim_v2t, sim_t2v = get_sim(vision_proj, text_proj, temp)\n\n with torch.no_grad():\n sim_v2t_targets = self.get_mask(sim_v2t, idx=idx, normalize=True)\n sim_t2v_targets = sim_v2t_targets\n\n loss_i2t = -torch.sum(F.log_softmax(sim_v2t, dim=1) * sim_v2t_targets, dim=1).mean()\n loss_t2i = -torch.sum(F.log_softmax(sim_t2v, dim=1) * sim_t2v_targets, dim=1).mean()\n\n loss_vtc = (loss_i2t + loss_t2i) / 2\n return loss_vtc\n\n def vtm_loss(\n self,\n multimodal_encoder,\n vtm_head: nn.Module,\n temp,\n vision_embeds: torch.Tensor,\n text_embeds: torch.Tensor,\n vision_proj: torch.Tensor,\n text_proj: torch.Tensor,\n text_atts: torch.Tensor,\n idx: torch.Tensor,\n ):\n \"\"\"video-text matching loss.\n\n Args:\n multinomial_encoder (nn.Module): The multimodal_encoder.\n vtm_head (nn.Module): The head to produce the video-text matching score.\n temp (torch.Tensor): temporature for similarity calculation.\n vision_embeds (torch.Tensor): The features of all patches in the video. Shape: [B,T,L,C].\n text_embeds (torch.Tensor): The features of all tokens in the text. Shape: [B,L,C].\n vision_proj (torch.Tensor): The vision representation. Shape: [B,T,C].\n text_proj (torch.Tensor): The text representation. Shape: [B,C].\n text_atts (torch.Tensor): The padded mask for text tokens. 0 is padded. Shape: [B,L].\n idx (torch.Tensor): The index for each example. Shape: [B,].\n\n Returns: TODO\n\n \"\"\"\n with torch.no_grad():\n sim_v2t, sim_t2v = get_sim(vision_proj, text_proj, temp)\n vision_atts = torch.ones(\n vision_embeds.size()[:-1], dtype=torch.long, device=vision_embeds.device\n )\n weights_v2t = F.softmax(sim_v2t + 1e-4, dim=1) # (N, N)\n weights_t2v = F.softmax(sim_t2v + 1e-4, dim=1)\n\n mask = self.get_mask(sim_v2t, idx=idx).bool()\n weights_v2t.masked_fill_(mask, 0)\n weights_t2v.masked_fill_(mask, 0)\n weights_v2t = torch.nan_to_num_(weights_v2t, nan=1e-2, posinf=1e-2, neginf=1e-2)\n weights_t2v = torch.nan_to_num_(weights_t2v, nan=1e-2, posinf=1e-2, neginf=1e-2)\n\n # select a negative image for each text\n if self.vtm_hard_neg:\n vision_neg_indices = torch.multinomial(weights_t2v, 1).squeeze()\n txt_neg_indices = torch.multinomial(weights_v2t, 1).squeeze()\n else:\n vision_neg_indices = self.get_rand_indices(mask, 1).squeeze()\n txt_neg_indices = self.get_rand_indices(mask, 1).squeeze()\n\n vision_embeds_neg = vision_embeds[vision_neg_indices] # [B, T*L, c]\n text_embeds_neg = text_embeds[txt_neg_indices] # [B, L, d]\n text_atts_neg = text_atts[txt_neg_indices]\n\n # concat embeddings\n vision_embeds_all = torch.cat([vision_embeds, vision_embeds_neg, vision_embeds], dim=0)\n text_embeds_all = torch.cat([text_embeds, text_embeds, text_embeds_neg], dim=0)\n vision_atts_all = torch.cat([vision_atts, vision_atts, vision_atts], dim=0)\n text_atts_all = torch.cat([text_atts, text_atts, text_atts_neg], dim=0)\n\n output = multimodal_encoder(\n encoder_embeds=text_embeds_all,\n attention_mask=text_atts_all,\n encoder_hidden_states=vision_embeds_all,\n encoder_attention_mask=vision_atts_all,\n return_dict=True,\n mode=\"fusion\",\n )\n\n vtm_embeds = output.last_hidden_state[:, 0] # pos (N, d) + neg (2N, d)\n\n vtm_logits = vtm_head(vtm_embeds) # [3*B, 2]\n\n bs = vtm_logits.shape[0] // 3\n vtm_labels = vtm_logits.new_ones(3 * bs, dtype=torch.long)\n vtm_labels[bs:] = 0\n loss_vtm = F.cross_entropy(vtm_logits, vtm_labels)\n return loss_vtm\n\n def get_rand_indices(self, mask, k):\n \"\"\"get rand indices according to mask.\n Args:\n mask (torch.Tensor): Shape: (N, L) 0 indicates the positions that we can sample, 1 otherwise\n k (int): the number indices to sample at each row.\n Returns:\n The sampled indices. Shape: [N,k].\n (N, k) indices\n \"\"\"\n mask = mask.float()\n mask = mask - 10000 * mask\n mask += torch.randn_like(mask)\n _, indices = torch.sort(mask, dim=1, descending=True)\n indices = indices[:, :k].contiguous()\n return indices\n\n @torch.no_grad()\n def get_mask(self, sim, idx=None, normalize=False):\n \"\"\"\n Args:\n sim (torch.Tensor): The similarity between videos and texts. shape: (B, B).\n idx (torch.Tensor): The index for each video. Shape: [B].\n normalize (bool): If true, make row sum equal to 1\n \"\"\"\n if idx is not None:\n idx = idx.view(-1, 1)\n mask = torch.eq(idx, idx.T).to(sim.dtype)\n if normalize:\n mask = mask / mask.sum(1, keepdim=True)\n else:\n mask = torch.zeros_like(sim)\n mask.fill_diagonal_(1)\n return mask # `1` mark valid/matched location\n\n @lru_cache(maxsize=16)\n def get_gather_args(self):\n \"\"\"obtain the args for all_gather\n Returns: dict.\n\n \"\"\"\n return EasyDict({\"world_size\": get_world_size(), \"rank\": get_rank()})\n\n\nclass MLMLoss(nn.Module):\n \"\"\"masked language modeling loss.\"\"\"\n\n def __init__(self, masking_prob, tokenizer):\n super(MLMLoss, self).__init__()\n self.tokenizer = tokenizer\n self.masking_prob = masking_prob\n\n def mlm_loss(\n self,\n text_encoder,\n text,\n vision_embeds,\n vision_atts,\n ):\n input_ids = text.input_ids.clone()\n labels = input_ids.clone()\n probability_matrix = torch.full(labels.shape, self.masking_prob)\n input_ids, labels = self.mask(\n input_ids,\n text_encoder.config.vocab_size,\n input_ids.device,\n targets=labels,\n probability_matrix=probability_matrix,\n )\n\n intermediate_mlm_output = text_encoder.bert(\n input_ids,\n attention_mask=text.attention_mask,\n encoder_hidden_states=vision_embeds,\n encoder_attention_mask=vision_atts,\n return_dict=True,\n mode=\"text\",\n )\n\n text_embeds = intermediate_mlm_output.last_hidden_state\n\n mlm_output = text_encoder(\n encoder_embeds=text_embeds,\n attention_mask=text.attention_mask,\n encoder_hidden_states=vision_embeds,\n encoder_attention_mask=vision_atts,\n return_dict=True,\n labels=labels,\n soft_labels=None,\n mode=\"fusion\",\n )\n return mlm_output.loss\n\n def simple_mlm_loss(\n self,\n text_encoder,\n text,\n text_embeds,\n vision_embeds,\n vision_atts,\n labels\n ):\n mlm_output = text_encoder(\n encoder_embeds=text_embeds,\n attention_mask=text.attention_mask,\n encoder_hidden_states=vision_embeds,\n encoder_attention_mask=vision_atts,\n return_dict=True,\n labels=labels,\n soft_labels=None,\n mode=\"fusion\",\n )\n return mlm_output.loss\n\n def mask(\n self,\n input_ids,\n vocab_size,\n device,\n targets=None,\n masked_indices=None,\n probability_matrix=None,\n ):\n if masked_indices is None:\n masked_indices = torch.bernoulli(probability_matrix).bool()\n\n masked_indices[input_ids == self.tokenizer.pad_token_id] = False\n masked_indices[input_ids == self.tokenizer.cls_token_id] = False\n\n if targets is not None:\n # We only compute loss on masked tokens\n targets[~masked_indices] = -100\n\n # 80% of the time, we replace masked input tokens with tokenizer.mask_token ([MASK])\n indices_replaced = (\n torch.bernoulli(torch.full(input_ids.shape, 0.8)).bool() & masked_indices\n )\n input_ids[indices_replaced] = self.tokenizer.mask_token_id\n\n # 10% of the time, we replace masked input tokens with random word\n indices_random = (\n torch.bernoulli(torch.full(input_ids.shape, 0.5)).bool()\n & masked_indices\n & ~indices_replaced\n )\n random_words = torch.randint(vocab_size, input_ids.shape, dtype=torch.long).to(device)\n input_ids[indices_random] = random_words[indices_random]\n # The rest of the time (10% of the time) we keep the masked input tokens unchanged\n\n if targets is not None:\n return input_ids, targets\n else:\n return input_ids\n\n\nclass UTA_Loss(nn.Module):\n \"\"\"unmasked token alignment loss.\"\"\"\n\n def __init__(self, uta_norm_type='l2', uta_loss_type='l2'):\n super().__init__()\n self.norm_type = uta_norm_type\n self.loss_type = uta_loss_type\n logger.info(f'Norm type: {uta_norm_type}')\n logger.info(f'Loss type: {uta_loss_type}')\n\n if uta_loss_type == 'mse':\n self.loss_func = nn.MSELoss()\n elif uta_loss_type == 'smooth_l1':\n self.loss_func = nn.SmoothL1Loss()\n \n def uta_loss(self, student_output, clip_output):\n \"\"\"forward to calculate the loss\n\n Args:\n student_output (torch.Tensor): The student output. Shape: [K,B,N,C].\n clip_output (torch.Tensor): The teacher representation. Shape: [K,B,N,C].\n\n Returns: loss_uta (torch.Tensor): The mask clip alignment loss. Shape: [].\n \"\"\"\n\n if self.norm_type == 'l2':\n student_output = student_output / student_output.norm(dim=-1, keepdim=True)\n clip_output = clip_output / clip_output.norm(dim=-1, keepdim=True)\n elif self.norm_type == 'none':\n pass\n else:\n raise NotImplementedError\n\n if self.loss_type == 'l2':\n loss_uta = (2 - 2 * (student_output * clip_output).sum(dim=-1)).mean()\n elif self.loss_type in ['mse', 'smooth_l1']:\n loss_uta = self.loss_func(input=student_output, target=clip_output)\n else:\n raise NotImplementedError\n\n return loss_uta","repo_name":"OpenGVLab/unmasked_teacher","sub_path":"multi_modality/models/criterions.py","file_name":"criterions.py","file_ext":"py","file_size_in_byte":12632,"program_lang":"python","lang":"en","doc_type":"code","stars":184,"dataset":"github-code","pt":"81"} +{"seq_id":"4934842148","text":"import json\nimport requests\nimport time\nimport urllib\n\nimport sqlalchemy\nimport db\nfrom db import Task\n\nclass HandleBot():\n def __init__(self):\n self.TOKEN = self.get_token()\n self.URL = \"https://api.telegram.org/bot{}/\".format(self.TOKEN.rstrip())\n self.HELP = \"\"\"\n/new NOME\n/new NOME, PRIORITY{low, medium, high}\n/todo ID\n/doing ID\n/done ID\n/delete ID\n/list\n/rename ID NOME\n/dependson ID ID...\n/duplicate ID\n/priority ID PRIORITY{low, medium, high}\n/showpriority\n/duedate ID DATE{MM/DD/YYYY}\n/help\n/log\n\"\"\"\n def get_token(self):\n file_token = \"token.txt\"\n inFile = open(file_token, 'r')\n token = inFile.readline()\n return token\n\n def get_url(self, url):\n response = requests.get(url)\n content = response.content.decode(\"utf8\")\n return content\n\n def get_json_from_url(self, url):\n content = self.get_url(url)\n js = json.loads(content)\n return js\n\n def get_updates(self, offset=None):\n url = self.URL + \"getUpdates?timeout=100\"\n if offset:\n url += \"&offset={}\".format(offset)\n js = self.get_json_from_url(url)\n return js\n\n def send_message(self, text, chat_id, reply_markup=None):\n text = urllib.parse.quote_plus(text)\n url = self.URL + \"sendMessage?text={}&chat_id={}&parse_mode=Markdown\".format(text, chat_id)\n if reply_markup:\n url += \"&reply_markup={}\".format(reply_markup)\n self.get_url(url)\n\n def get_last_update_id(self, updates):\n update_ids = []\n for update in updates[\"result\"]:\n update_ids.append(int(update[\"update_id\"]))\n max_update = max(update_ids)\n return max_update\n\n def deps_text(self, task, chat, preceed=''):\n text = ''\n last_dependency = len(task.dependencies.split(',')[:-1])\n range_dependency = range(last_dependency)\n for i in range_dependency:\n line = preceed\n query = db.session.query(Task).filter_by(id=int(task.dependencies.split(',')[:-1][i]), chat=chat)\n dep = query.one()\n\n icon = '\\U0001F195'\n if dep.status == 'DOING':\n icon = '\\U000023FA'\n elif dep.status == 'DONE':\n icon = '\\U00002611'\n\n if i + 1 == last_dependency:\n line += '└── [[{}]] {} {}\\n'.format(dep.id, icon, dep.name)\n line += self.deps_text(dep, chat, preceed + ' ')\n else:\n line += '├── [[{}]] {} {}\\n'.format(dep.id, icon, dep.name)\n line += self.deps_text(dep, chat, preceed + '│ ')\n\n text += line\n\n return text\n\n def message_check(self, msg):\n if msg != '':\n if len(msg.split(', ')) > 1:\n text = msg.split(', ')[-1]\n return msg.split(', ', 1)[0]\n else:\n return msg\n\n def query_one(self, task_id, chat):\n query = db.session.query(Task).filter_by(id=task_id, chat=chat)\n task = query.one()\n return task\n\n def check_dependency(task, target, chat):\n if not task.parents == '':\n epic_id = task.parents.split(',')\n epic_id.pop()\n\n numbers = [int(id_epic) for id_epic in epic_id]\n\n if target in numbers:\n return False\n else:\n query = db.session.query(Task).filter_by(id=numbers[0], chat=chat)\n epic_id = query.one()\n return check_dependency(parent, target, chat)\n\n return True\n\n def puts_icon_to_priority(self, task):\n icon_priority = ''\n if task == 'low':\n icon_priority += '\\U00002755'\n elif task == 'medium':\n icon_priority += '\\U00002757'\n elif task == 'high':\n icon_priority += '\\U0000203C'\n return icon_priority\n\n def four0four(self, chat, task_id):\n self.send_message(\"_404_ Task {} not found, 404taskbot working as intended\".format(task_id), chat)\n return True\n\n\n\"\"\"\nFunctions for the bot\n\"\"\"\n","repo_name":"TecProg-20181/T--404tasknotfoundbot","sub_path":"handlebot.py","file_name":"handlebot.py","file_ext":"py","file_size_in_byte":4080,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"81"} +{"seq_id":"28616289429","text":"from __future__ import print_function\nimport numpy as np\nimport gdal, sys, glob, pickle\nfrom gdalconst import GA_ReadOnly\n\nfrom flink.functions.FilterFunction import FilterFunction\nfrom flink.functions.FlatMapFunction import FlatMapFunction\nfrom flink.io.PythonInputFormat import PythonInputFormat, FileInputSplit\nfrom flink.io.PythonOutputFormat import PythonOutputFormat\nfrom flink.plan.Environment import get_environment\nfrom flink.spatial.ImageWrapper import ImageWrapper, TupleToTile, TileToTuple\n\n\nclass Tokenizer(FlatMapFunction):\n def flat_map(self, value, collector):\n print(\"collecting in Tokenizer\")\n sys.stdout.flush()\n collector.collect(value)\n\n\nclass GDALInputFormat(PythonInputFormat):\n def __init__(self, jobID):\n super(GDALInputFormat, self).__init__()\n self.jobID = jobID\n\n def getFiles(self):\n # get sceneids for jobid:\n # SELECT sceneids FROM scenejobs WHERE id = ?\n # get filenames for sceneids:\n # SELECT filename FROM scenes WHERE id = ?\n # filter bsq?\n #files = [\n # \"file:/opt/gms_sample/227064_000202_BLA_SR.bsq\",\n # \"file:/opt/gms_sample/227064_000321_BLA_SR.bsq\"\n # ]\n\n files = []\n for f in glob.glob(\"/opt/gms_sample/*.bsq\"):\n print(\"file:\"+f)\n files.append(\"file:\"+f)\n\n\n return files\n\n def createInputSplits(self, minNumSplits, path, collector):\n additional = dict()\n pickled = pickle.dumps(additional, pickle.HIGHEST_PROTOCOL)\n for f in self.getFiles():\n collector.collect(FileInputSplit(f, 0, 1, (\"localhost\",), pickled))\n\n\n def _userInit(self):\n gdal.AllRegister() # TODO: register the ENVI driver only\n\n def deliver(self, split, collector):\n path = split[0]\n ds = gdal.Open(path[5:], GA_ReadOnly)\n if ds is None:\n print('Could not open image', path[5:])\n return\n rows = ds.RasterYSize\n cols = ds.RasterXSize\n bandsize = rows * cols\n bands = ds.RasterCount\n\n imageData = np.empty(bands * bandsize, dtype=np.int16)\n for j in range(bands):\n band = ds.GetRasterBand(j+1)\n data = np.array(band.ReadAsArray())\n lower = j*bandsize\n upper = (j+1)*bandsize\n imageData[lower:upper] = data.ravel()\n\n\n metaData = self.readMetaData(path[5:-4])\n\n #this is just a hack to cope with the hacky readMetaData-fct (since this is just a throwaway example anyway)\n leftlatlong = metaData[\"upperleftcornerlatlong\"]\n rightlatlong = metaData[\"lowerrightcornerlatlong\"]\n metaData[\"coordinates\"] = [leftlatlong[0], leftlatlong[1], rightlatlong[0], rightlatlong[1]]\n metaData[\"width\"] = metaData[\"samples\"]\n metaData[\"height\"] = metaData[\"lines\"]\n metaData[\"band\"] = \"0\"\n metaData[\"xPixelWidth\"] = metaData[\"pixelsize\"]\n metaData[\"yPixelWidth\"] = metaData[\"pixelsize\"]\n\n metaBytes = ImageWrapper._meta_to_bytes(metaData)\n bArr = bytearray(imageData)\n retVal = (metaData['scene id'], metaBytes, bArr)\n #retVal = (metaData['scene id'], bytearray(), bytearray())\n print(metaData['scene id'])\n sys.stdout.flush()\n collector.collect(retVal)\n\n def readMetaData(self, path):\n headerPath = path+'.hdr'\n f = open(headerPath, 'r')\n\n if f.readline().find(\"ENVI\") == -1:\n f.close()\n raise IOError(\"Not an ENVI header.\")\n\n lines = f.readlines()\n f.close()\n\n dict = {}\n try:\n while lines:\n line = lines.pop(0)\n if '=' not in line or line[0] == ';':\n continue\n\n (key, sep, val) = line.partition('=')\n key = key.strip().lower()\n val = val.strip()\n if val and val[0] == '{':\n txt = val.strip()\n while txt[-1] != '}':\n line = lines.pop(0)\n if line[0] == ';':\n continue\n\n txt += '\\n' + line.strip()\n if key == 'description':\n dict[key] = txt.strip('{}').strip()\n else:\n vals = txt[1:-1].split(',')\n for j in range(len(vals)):\n vals[j] = vals[j].strip()\n dict[key] = vals\n else:\n dict[key] = val\n return dict\n except:\n raise IOError(\"Error while reading ENVI file header.\")\n\nclass GMSOF(PythonOutputFormat):\n def write(self, value):\n print(\"OF: value: \", value[0])\n sys.stdout.flush()\n\nclass Filter(FilterFunction):\n def __init__(self):\n super(Filter, self).__init__()\n\n def filter(self, value):\n print(\"Filter: \", value[0])\n sys.stdout.flush()\n return True\n\n\ndef main():\n env = get_environment()\n env.set_sendLargeTuples(True)\n\n inputFormat = GDALInputFormat(26184107)\n\n data = env.read_custom(\"/opt/gms_sample/\", \".*?\\\\.bsq\", True,\n inputFormat)\n\n #result = data \\\n # .flat_map(TupleToTile()) \\\n # .flat_map(Tokenizer()) \\\n # .flat_map(TileToTuple())\n\n result = data.filter(Filter())\n\n result.write_custom(GMSOF(\"/opt/output\"))\n\n\n filtered = result.filter(Filter())\n filtered.write_custom(GMSOF(\"/opt/output\"))\n\n env.set_parallelism(2)\n\n env.execute(local=False)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"mathiaspet/pyflink","sub_path":"flink-libraries/flink-python/src/main/python/org/apache/flink/python/api/flink/example/CustomInput.py","file_name":"CustomInput.py","file_ext":"py","file_size_in_byte":5642,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"81"} +{"seq_id":"36521112664","text":"import tweepy\nfrom datetime import datetime, timedelta\nfrom collections import namedtuple\nimport keys\n\nTweet = namedtuple(\"Tweet\", \"id text author_id author_name author_image author_bio\")\nclient = tweepy.Client(keys.TWITTER_BEARER_TOKEN)\n\n\ndef search_tweets(last_search: datetime) -> list[Tweet]:\n with open(\"twitter/filters.txt\", \"r\") as file:\n lines = file.read().split(\"\\n\")\n age = timedelta(hours=int(lines[2]))\n keywords = lines[4]\n min_retweets = int(lines[6])\n max_followers = int(lines[8])\n ret = []\n for resp in tweepy.Paginator(\n method=client.search_recent_tweets,\n start_time=last_search - age,\n end_time=datetime.utcnow() - age,\n query=f\"({keywords}) -is:reply -is:retweet lang:en -is:verified\",\n tweet_fields=[\"public_metrics\"],\n expansions=[\"author_id\"],\n user_fields=[\"public_metrics\", \"profile_image_url\", \"description\"],\n max_results=100\n ):\n tweets = resp.data\n authors = resp.includes[\"users\"]\n for tt in tweets:\n author = next((a for a in authors if a.id == tt.author_id))\n if tt.public_metrics[\"retweet_count\"] >= min_retweets \\\n and author.public_metrics[\"followers_count\"] <= max_followers:\n ret.append(Tweet(tt.id, tt.text, author.id, author.username, author.profile_image_url, author.description))\n return ret","repo_name":"iHazzu/Twiptter","sub_path":"twitter/search.py","file_name":"search.py","file_ext":"py","file_size_in_byte":1450,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"18563237565","text":"import Emerson\nimport numpy as np\n\n# create spectrum objects array\nspectra = np.full(shape=10, fill_value=Emerson.spectrum)\n\n# print(len(spectra[0].amps))\n\ni = 0\nfor s in spectra:\n # print(s.amps)\n # print(len(s.amps))\n print(i)\n i+=1\n\n","repo_name":"ciromolina86/test_ThinkDSP","sub_path":"Ciro Testing/testing_dummy.py","file_name":"testing_dummy.py","file_ext":"py","file_size_in_byte":248,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"81"} +{"seq_id":"74199808586","text":"import pickle\nfrom typing import Dict, List, Tuple\nimport pandas as pd\nfrom sklearn.utils import Bunch\nimport polars as pl\nfrom caumim.constants import (\n COLNAME_MORTALITY_28D,\n COLNAME_MORTALITY_90D,\n COLNAME_INTERVENTION_START,\n COLNAME_INTERVENTION_STATUS,\n COLNAME_PATIENT_ID,\n DIR2COHORT,\n DIR2MIMIC,\n COLNAME_INCLUSION_START,\n FILENAME_INCLUSION_CRITERIA,\n FILENAME_TARGET_POPULATION,\n)\nfrom loguru import logger\n\nfrom caumim.framing.utils import (\n create_cohort_folder,\n get_base_population,\n get_cohort_hash,\n roll_inclusion_criteria,\n)\nfrom caumim.utils import to_lazyframe\n\n\"\"\"\nThis script defines the cohort of patients that will be used for the albumin. I\ntimplements the framing of the question by building: Population, Intervention,\nControl and Outcome elements as well as the Time of followup.\n\"\"\"\n\nobservation_window_in_day = 1\nCOHORT_CONFIG_ALBUMIN_FOR_SEPSIS = Bunch(\n **{\n \"min_age\": 18,\n \"min_icu_survival_unit_day\": observation_window_in_day, # the patient should survive at least one day.\n \"min_los_icu_unit_day\": observation_window_in_day, # the patient should stay in ICU at least one day.\n \"treatment_observation_window_unit_day\": observation_window_in_day, # the treatment should happen during the first day.\n \"cohort_name\": \"albumin_for_sepsis\",\n \"save_cohort\": True,\n }\n)\n\n\ndef get_population(cohort_config) -> Tuple[pd.DataFrame, Dict[str, List[str]]]:\n \"\"\"\n This function defines the population of interest for the albumin for sepsis.\n It returns static information with treatment status and important timestamps such as:\n COLNAME_INCLUSION_START, COLNAME_INTERVENTION_START and outcomes.\n \"\"\"\n cohort_folder = create_cohort_folder(cohort_config)\n # 1 - Define the inclusion events, ie. the event that defines when a patient\n # enter the cohort.\n # Inclusion event: First administration of crystalloids during the 24 first\n # hours of ICU stay\n input_events = pl.scan_parquet(DIR2MIMIC / \"mimiciv_icu.inputevents/*\")\n icu_stays = pl.scan_parquet(DIR2MIMIC / \"mimiciv_icu.icustays/*\")\n # full list of crystalloids taken from :https://www.ncbi.nlm.nih.gov/books/NBK537326/\n crystalloids_itemids = [\n 226364, # operating room crystalloids\n 226375, # post-anesthesia care unit crystalloids\n 225158, # NaCl 0.9%,\n 225159, # NaCl 0.45%,\n 225161, # NaCl 3%\n 220967, # Dextrose 5% / Ringers Lactate,\n 220968, # Dextrose 10% / Ringers\n 220964, # \"Dextrose 5% / Saline 0,9%\"\n 220965, # \"Dextrose 5% / Saline 0,45%\"\n ]\n crystalloids_inputs = input_events.filter(\n pl.col(\"itemid\").is_in(crystalloids_itemids)\n ).join(icu_stays.select([\"stay_id\", \"intime\"]), on=\"stay_id\", how=\"inner\")\n first_crystalloids = (\n crystalloids_inputs.sort([\"stay_id\", \"starttime\"])\n .groupby(\"stay_id\")\n .agg([pl.first(\"starttime\"), pl.first(\"intime\")])\n .collect()\n .to_pandas()\n .rename(columns={\"starttime\": COLNAME_INCLUSION_START})\n )\n first_crystalloids[\"delta_crystalloids_icu_intime\"] = (\n first_crystalloids[COLNAME_INCLUSION_START]\n - first_crystalloids[\"intime\"]\n )\n # Consider only crystalloids before max_los_before_treatment\n crystralloids_first_24h = first_crystalloids.loc[\n (\n first_crystalloids[\n \"delta_crystalloids_icu_intime\"\n ].dt.total_seconds()\n <= (cohort_config.treatment_observation_window_unit_day * 24 * 3600)\n )\n & (\n first_crystalloids[\n \"delta_crystalloids_icu_intime\"\n ].dt.total_seconds()\n >= 0\n )\n ]\n # 2 - Then define different inclusion criteria, applied at the statistical unit\n # level: here it is the **stay level**.\n #\n # First ICU stay of patients older than 18 years old, with at least 1 day of\n # ICU survival and 1 day of ICU.\n base_population = get_base_population(\n min_age=cohort_config.min_age,\n min_icu_survival_unit_day=cohort_config.min_icu_survival_unit_day,\n min_los_icu_unit_day=cohort_config.min_los_icu_unit_day,\n )\n # sepsis\n sepsis3_stays = pd.read_parquet(DIR2MIMIC / \"mimiciv_derived.sepsis3\")\n sepsis3_stays = sepsis3_stays.loc[\n sepsis3_stays[\"sepsis3\"] == True, [\"stay_id\"]\n ]\n observation_window_in_hour_str = str(\n int(24 * cohort_config.treatment_observation_window_unit_day)\n )\n inclusion_criteria = {\n f\"Aged over 18, ICU lOS >= {cohort_config.min_los_icu_unit_day}\": base_population,\n \"Sepsis patients\": sepsis3_stays,\n f\"inclusion_event\": crystralloids_first_24h,\n }\n # Run successively the inclusion criteria\n target_population, inclusion_ids = roll_inclusion_criteria(\n inclusion_criteria\n )\n # 3 - Define the treatment events\n albumin_itemids = [\n # 220861, #\"Albumin (Human) 20% Not in use\n 220862, # Albumin 25%,Albumin 25%\n # 220863, #Albumin (Human) Not in use\n 220864, # Albumin 5%\n ]\n albumin = input_events.filter(pl.col(\"itemid\").is_in(albumin_itemids))\n combined_albumin_for_target_population = to_lazyframe(\n target_population[\n [\"stay_id\", \"icu_intime\", COLNAME_INCLUSION_START]\n ].drop_duplicates()\n ).join(albumin, on=\"stay_id\", how=\"inner\")\n\n # First albumin\n first_albumin = (\n combined_albumin_for_target_population.sort(\"starttime\")\n .groupby(\"stay_id\")\n .agg(\n [\n pl.first(\"starttime\"),\n pl.first(\"icu_intime\"),\n pl.first(COLNAME_INCLUSION_START),\n ]\n )\n .collect()\n .to_pandas()\n .rename(columns={\"starttime\": COLNAME_INTERVENTION_START})\n )\n # Consider only first day albumin\n first_albumin[\"delta_albumin_icu_intime\"] = (\n first_albumin[COLNAME_INTERVENTION_START] - first_albumin[\"icu_intime\"]\n )\n first_albumin_in24h = first_albumin.loc[\n (\n (\n first_albumin[\"delta_albumin_icu_intime\"].dt.total_seconds()\n <= (\n cohort_config.treatment_observation_window_unit_day\n * 24\n * 3600\n )\n )\n & (\n first_albumin[\"delta_albumin_icu_intime\"].dt.total_seconds()\n >= 0\n )\n )\n ]\n first_albumin_in24h = first_albumin_in24h.loc[\n first_albumin_in24h[COLNAME_INTERVENTION_START]\n > first_albumin_in24h[COLNAME_INCLUSION_START]\n ]\n\n # 4- Define treatment and control population:\n target_trial_population = target_population.merge(\n first_albumin_in24h[\n [\"stay_id\", COLNAME_INTERVENTION_START]\n ].drop_duplicates(),\n on=\"stay_id\",\n how=\"left\",\n )\n\n target_trial_population[COLNAME_INTERVENTION_STATUS] = (\n target_trial_population[COLNAME_INTERVENTION_START]\n .notnull()\n .astype(int)\n )\n # target_trial_population[COLNAME_FOLLOWUP_START] = target_trial_population[\n # COLNAME_INCLUSION_START\n # ]\n # # forcing followup to be either inclusion or treatment start.\n # # It introduces a blan\n # mask_treated = target_trial_population[COLNAME_INTERVENTION_STATUS] == 1\n # target_trial_population.loc[\n # mask_treated,\n # COLNAME_FOLLOWUP_START,\n # ] = target_trial_population.loc[mask_treated, COLNAME_INTERVENTION_START]\n\n # 5 - Define outcomes\n # 28-days and 90-days mortality\n mask_dod = target_trial_population[\"dod\"].notnull()\n days_to_death = (\n target_trial_population[\"dod\"]\n - target_trial_population[COLNAME_INCLUSION_START]\n ).dt.days\n\n target_trial_population[COLNAME_MORTALITY_28D] = (\n mask_dod & (days_to_death <= 28)\n ).astype(int)\n target_trial_population[COLNAME_MORTALITY_90D] = (\n mask_dod & (days_to_death <= 90)\n ).astype(int)\n\n col_name_outcomes = [COLNAME_MORTALITY_28D, COLNAME_MORTALITY_90D]\n # 6 - Save the cohort\n for outcome in col_name_outcomes:\n logger.info(\n f\"Outcome `{outcome}` prevalence: {100 * target_trial_population[outcome].mean():.2f}%\"\n )\n logger.info(\n f\"Number of treated patients: {target_trial_population[COLNAME_INTERVENTION_STATUS].sum()}\",\n )\n logger.info(\n f\"Number of control patients: {(1 - target_trial_population[COLNAME_INTERVENTION_STATUS]).sum()}\",\n )\n if cohort_config.save_cohort:\n target_trial_population.to_parquet(\n cohort_folder / (FILENAME_TARGET_POPULATION)\n )\n logger.info(\n f\"Saved cohort at {cohort_folder / (FILENAME_TARGET_POPULATION)}\"\n )\n\n # create inclusion criteria dictionnary\n inclusion_ids[\n f\"Crystalloids in first {observation_window_in_hour_str}h\"\n ] = inclusion_ids[f\"inclusion_event\"]\n inclusion_ids.pop(\"inclusion_event\")\n inclusion_ids[f\"Albumin in first {observation_window_in_hour_str}h\"] = (\n target_trial_population.loc[\n target_trial_population[COLNAME_INTERVENTION_STATUS] == 1,\n COLNAME_PATIENT_ID,\n ]\n .unique()\n .tolist()\n )\n pickle.dump(\n inclusion_ids,\n open(str(cohort_folder / FILENAME_INCLUSION_CRITERIA), \"wb\"),\n )\n return target_population, inclusion_criteria\n\n\nif __name__ == \"__main__\":\n get_population(cohort_config=COHORT_CONFIG_ALBUMIN_FOR_SEPSIS)\n","repo_name":"soda-inria/causal_ehr_mimic","sub_path":"caumim/framing/albumin_for_sepsis.py","file_name":"albumin_for_sepsis.py","file_ext":"py","file_size_in_byte":9588,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"81"} +{"seq_id":"15467087830","text":"def firstNotRepeatingCharacter(s):\n\n map = {}\n for i,letter in enumerate(s):\n if letter in map:\n map[letter] = False\n else:\n map[letter] = i\n\n lowest = None\n lowest_letter = \"_\"\n for letter in map:\n if map[letter] is not False and (lowest is None or map[letter] < lowest):\n lowest = map[letter]\n lowest_letter = letter\n\n return lowest_letter\n\nprint(firstNotRepeatingCharacter(\"z\"))","repo_name":"jeremiahtenbrink/code-challenge-solutions","sub_path":"first_none_repeating_character/index.py","file_name":"index.py","file_ext":"py","file_size_in_byte":464,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"14735655315","text":"import numpy as np\nimport cv2\nfrom hog_calculation import hog_descriptor\nimport bolt_hog\n\ndef gamma_transform(gamma, img):\n \"\"\"\n This is a gamma correction function.\n Parameters:\n param1 - the power number\n param2 - img that needs to do gamma correction\n Returns:\n img\n Raises:\n \"\"\"\n img = np.power(img, gamma)\n return img\n\ndef show_img(name, img):\n \"\"\"\n This is a showing img function for the convience of saving time typing imshow, waitKey...etc.\n Parameters:\n param1 - the window name\n param2 - the img that you want to show\n Returns:\n Raises:\n \"\"\"\n cv2.imshow(name, img)\n cv2.waitKey(0)\n cv2.destroyAllWindows()\n\nif __name__ == '__main__':\n path = \"./img/cat1.jpg\"\n img_cat_1 = cv2.imread(path)# original image size:(y:1427, x:1920, 3)\n # You can use both grayscale and RGB when calculating by cv2.\n # If you want to use hog_descriptor.hog(),\n # please use with grayscale. (path,0)\n\n img_cat_1 = cv2.resize(img_cat_1, (640, 384)) # (parameter1:x parameter2:y),\n # resize it because the img is too big\n img_cat_1 = img_cat_1[0:320, 150:470] # cut to the cat head with width:320px,height:320px\n # show_img('cat',img_cat_1)\n\n norm_cat_1 = cv2.normalize(img_cat_1, None, alpha=0, beta=1, norm_type=cv2.NORM_MINMAX, dtype=cv2.CV_32F)\n # show_img('norm_img',norm_cat_1)\n\n imgGamma_0p5 = gamma_transform(1/2, norm_cat_1)\n # show_img('imgGamma_0p5',imgGamma_0p5)\n normback_cat_1 = cv2.normalize(imgGamma_0p5, None, alpha=0, beta=255, norm_type=cv2.NORM_MINMAX, dtype=cv2.CV_32F)\n normback_cat_1 = np.uint8(normback_cat_1) # cv2.HOGDescriptor only read uint8 img\n # show_img('normback_cat_1', normback_cat_1)\n\n # Lab_cat_1 = cv2.cvtColor(normback_cat_1, cv2.COLOR_BGR2Lab) # I didn't use Lab domain.\n # show_img('Lab_cat_1', Lab_cat_1)\n\n #### CALCULATE BY cv2.HOGDescriptor.compute() ######\n winSize = (320, 320) #p1:x, p2:y\n blockSize = (16, 16)\n blockStride = (8, 8)\n cellSize = (8, 8)\n nbins = 9\n hog2 = cv2.HOGDescriptor(winSize, blockSize, blockStride, cellSize, nbins)\n hist_cat = hog2.compute(normback_cat_1)\n\n hist_cat = np.reshape(hist_cat, (int(hist_cat.shape[0]/36), 36)) # reshape hist_cat with four histograms(=block size)\n new_hist = bolt_hog.cal_histogram_2(hist_cat, nbins) # reorganize the final histograms (4 cells per new histogram)\n # using cal_histogram_2 func from bolt_hog.py\n h_obj = hog_descriptor(normback_cat_1, 8, 16, 8, 9) # create a hog_descriptor obj\n cat_1 = hog_descriptor.draw_gradient(h_obj, new_hist, normback_cat_1) # use the draw_gradient method of the obj\n cv2.imwrite('./img/gradient_output/cat1_cv2.jpg', cat_1) # save the output\n # cat_1 = cv2.resize(cat_1, (int(cat_1.shape[1]*3), int(cat_1.shape[0]*3))) #zoom in\n\n\n #### CALCULATE BY hog_descriptor.hog() ######\n # h_obj = hog_descriptor(normback_cat_1, 8, 8, 0, 9)\n # new_hist = h_obj.hog()\n # cat_1 = h_obj.draw_gradient(new_hist, img_cat_1)\n # cv2.imwrite('./img/gradient_output/cat1_calculate_myself.jpg', cat_1)\n","repo_name":"PengWenChen/HOG","sub_path":"image_preprocessing.py","file_name":"image_preprocessing.py","file_ext":"py","file_size_in_byte":3290,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"42721379746","text":"#!/usr/bin/env python3\n\nfrom setuptools import setup, find_packages\n\nrequires = [\n \"equations (>=1.0,<2.0)\",\n # \"discord.py (>=1.0,<2.0)\",\n \"sqlalchemy (>=1.2,<2.0)\",\n \"psycopg2 (>=2.7,<3.0)\",\n]\n\nsetup(name='Dice-bot',\n version='1.0.1',\n description='Discord bot for managing D&D characters',\n author='BHodges',\n url='https://github.com/b-hodges/dice-bot',\n install_requires=requires,\n scripts=['dice-bot.py'],\n packages=find_packages())\n","repo_name":"a-hodges/dice-bot","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":485,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"41294931842","text":"\"\"\"\n\"\"\"\nimport os\nimport tensorflow as tf\n\nimport enet.datasets as datasets\nimport enet.model_enet as model_enet\n\n\ndef build_training_model():\n \"\"\"\n \"\"\"\n FLAGS = tf.app.flags.FLAGS\n\n sd_images = tf.placeholder(\n shape=[None, 32, 32, 3], dtype=tf.float32, name='sd_images')\n\n bq_images = tf.placeholder(\n shape=[None, 128, 128, 3], dtype=tf.float32, name='bq_images')\n\n hd_images = tf.placeholder(\n shape=[None, 128, 128, 3], dtype=tf.float32, name='hd_images')\n\n model = model_enet.build_enet(\n sd_images, bq_images, hd_images, FLAGS.model, FLAGS.vgg19_path)\n\n model['image_batches'] = datasets.image_batches(\n FLAGS.train_dir_path, 4.0, batch_size=FLAGS.batch_size)\n\n return model\n\n\ndef build_summaries(model):\n \"\"\"\n \"\"\"\n FLAGS = tf.app.flags.FLAGS\n\n summaries = {}\n\n # NOTE: discriminator loss summaries\n if 'a_loss' in model:\n summaries['discriminator'] = \\\n tf.summary.scalar('discriminator_loss', model['a_loss'])\n\n # NOTE: generator loss summaries\n summaries_generator = []\n\n if 'g_loss' in model:\n summaries_generator.append(\n tf.summary.scalar('generator_loss', model['g_loss']))\n\n if 'p_loss' in model:\n summaries_generator.append(\n tf.summary.scalar('perceptual_loss', model['p_loss']))\n\n if 't_loss' in model:\n summaries_generator.append(\n tf.summary.scalar('texture_loss', model['t_loss']))\n\n if len(summaries_generator) > 0:\n summaries['generator'] = tf.summary.merge(summaries_generator)\n\n # NOTE: build image summaries (real v.s. fake)\n sd_images = model['bq_images']\n sr_images = model['sr_images']\n hd_images = model['hd_images']\n\n images = tf.concat([sd_images, sr_images, hd_images], axis=2)\n\n images = tf.reshape(images, [1, FLAGS.batch_size * 128, 3 * 128, 3])\n\n images = tf.saturate_cast(images * 127.5 + 127.5, tf.uint8)\n\n summaries['images'] = tf.summary.image('bq_sr_hd', images, max_outputs=4)\n\n return summaries\n\n\ndef main(_):\n \"\"\"\n \"\"\"\n FLAGS = tf.app.flags.FLAGS\n\n # NOTE: sanity check\n if FLAGS.model not in ['p', 'pa', 'pat']:\n FLAGS.model = 'pat'\n\n model = build_training_model()\n\n reporter = tf.summary.FileWriter(FLAGS.log_path)\n\n summaries = build_summaries(model)\n\n source_ckpt_path = tf.train.latest_checkpoint(FLAGS.ckpt_path)\n target_ckpt_path = os.path.join(FLAGS.ckpt_path, 'model.ckpt')\n\n with tf.Session() as session:\n saver = tf.train.Saver()\n\n if source_ckpt_path is None:\n session.run(tf.global_variables_initializer())\n else:\n tf.train.Saver().restore(session, source_ckpt_path)\n\n while True:\n step = session.run(model['step'])\n\n if step % 1000 == 999:\n saver.save(session, target_ckpt_path, global_step=step)\n\n # NOTE: train discriminator\n if step % 3 == 0 and 'd_trainer' in model:\n sd_images, bq_images, hd_images = next(model['image_batches'])\n\n feeds = {\n model['sd_images']: sd_images,\n model['bq_images']: bq_images,\n model['hd_images']: hd_images,\n }\n\n fetch = {\n 'step': model['step'],\n 'trainer': model['d_trainer']\n }\n\n if 'discriminator' in summaries:\n fetch['summary_losses'] = summaries['discriminator']\n\n fetched = session.run(fetch, feed_dict=feeds)\n\n if 'summary_losses' in fetched:\n reporter.add_summary(fetched['summary_losses'], step)\n\n # NOTE: train generator\n if 'g_trainer' in model:\n sd_images, bq_images, hd_images = next(model['image_batches'])\n\n feeds = {\n model['sd_images']: sd_images,\n model['bq_images']: bq_images,\n model['hd_images']: hd_images,\n }\n\n fetch = {\n 'step': model['step'],\n 'trainer': model['g_trainer']\n }\n\n if 'generator' in summaries:\n fetch['summary_losses'] = summaries['generator']\n\n if 'images' in summaries and step % 100 == 0:\n fetch['summary_images'] = summaries['images']\n\n fetched = session.run(fetch, feed_dict=feeds)\n\n if 'summary_losses' in fetched:\n reporter.add_summary(fetched['summary_losses'], step)\n if 'summary_images' in fetched:\n reporter.add_summary(fetched['summary_images'], step)\n\n\nif __name__ == '__main__':\n tf.app.flags.DEFINE_string('train_dir_path', None, '')\n tf.app.flags.DEFINE_string('vgg19_path', None, '')\n tf.app.flags.DEFINE_string('ckpt_path', None, '')\n tf.app.flags.DEFINE_string('log_path', None, '')\n tf.app.flags.DEFINE_string('model', 'pat', '')\n\n tf.app.flags.DEFINE_integer('batch_size', 64, '')\n\n tf.app.run()\n","repo_name":"imironhead/ml_super_resolution","sub_path":"enet/enet/experiment_train.py","file_name":"experiment_train.py","file_ext":"py","file_size_in_byte":5123,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"81"} +{"seq_id":"18351620565","text":"import os\n\nfrom oslo_log import log as logging\n\nfrom sahara import context\nfrom sahara.i18n import _\nfrom sahara.i18n import _LI\nfrom sahara.plugins import exceptions as ex\nfrom sahara.plugins.vanilla.hadoop2 import config_helper as c_helper\nfrom sahara.plugins.vanilla import utils as vu\nfrom sahara.utils import edp\nfrom sahara.utils import files\nfrom sahara.utils import general as g\n\nLOG = logging.getLogger(__name__)\n\n\ndef start_all_processes(instances, filternames):\n with context.ThreadGroup() as tg:\n for instance in instances:\n processes = set(instance.node_group.node_processes)\n procs = processes\n if filternames:\n procs = processes.intersection(filternames)\n if procs:\n tg.spawn('vanilla-start-processes-%s' %\n instance.instance_name,\n _start_processes,\n instance, list(procs))\n\n\ndef _start_processes(instance, processes):\n with instance.remote() as r:\n for process in processes:\n if process in ['namenode', 'datanode']:\n r.execute_command(\n 'sudo su - -c \"hadoop-daemon.sh start %s\" hadoop'\n % process)\n elif process in ['resourcemanager', 'nodemanager']:\n r.execute_command(\n 'sudo su - -c \"yarn-daemon.sh start %s\" hadoop' % process)\n else:\n raise ex.HadoopProvisionError(\n _(\"Process %s is not supported\") % process)\n\n\ndef start_hadoop_process(instance, process):\n instance.remote().execute_command(\n 'sudo su - -c \"hadoop-daemon.sh start %s\" hadoop' % process)\n\n\ndef start_yarn_process(instance, process):\n instance.remote().execute_command(\n 'sudo su - -c \"yarn-daemon.sh start %s\" hadoop' % process)\n\n\ndef start_historyserver(instance):\n instance.remote().execute_command(\n 'sudo su - -c \"mr-jobhistory-daemon.sh start historyserver\" hadoop')\n\n\ndef start_oozie_process(pctx, instance):\n with instance.remote() as r:\n if c_helper.is_mysql_enabled(pctx, instance.cluster):\n _start_mysql(r)\n LOG.debug(\"Creating Oozie DB Schema...\")\n sql_script = files.get_file_text(\n 'plugins/vanilla/hadoop2/resources/create_oozie_db.sql')\n script_location = \"create_oozie_db.sql\"\n r.write_file_to(script_location, sql_script)\n r.execute_command('mysql -u root < %(script_location)s && '\n 'rm %(script_location)s' %\n {\"script_location\": script_location})\n\n _oozie_share_lib(r)\n _start_oozie(r)\n\n\ndef format_namenode(instance):\n instance.remote().execute_command(\n 'sudo su - -c \"hdfs namenode -format\" hadoop')\n\n\ndef refresh_hadoop_nodes(cluster):\n nn = vu.get_namenode(cluster)\n nn.remote().execute_command(\n 'sudo su - -c \"hdfs dfsadmin -refreshNodes\" hadoop')\n\n\ndef refresh_yarn_nodes(cluster):\n rm = vu.get_resourcemanager(cluster)\n rm.remote().execute_command(\n 'sudo su - -c \"yarn rmadmin -refreshNodes\" hadoop')\n\n\ndef _oozie_share_lib(remote):\n LOG.debug(\"Sharing Oozie libs\")\n # remote.execute_command('sudo su - -c \"/opt/oozie/bin/oozie-setup.sh '\n # 'sharelib create -fs hdfs://%s:8020\" hadoop'\n # % nn_hostname)\n\n # TODO(alazarev) return 'oozie-setup.sh sharelib create' back\n # when #1262023 is resolved\n\n remote.execute_command(\n 'sudo su - -c \"mkdir /tmp/oozielib && '\n 'tar zxf /opt/oozie/oozie-sharelib-*.tar.gz -C '\n '/tmp/oozielib && '\n 'hadoop fs -mkdir /user && '\n 'hadoop fs -mkdir /user/hadoop && '\n 'hadoop fs -put /tmp/oozielib/share /user/hadoop/ && '\n 'rm -rf /tmp/oozielib\" hadoop')\n\n LOG.debug(\"Creating sqlfile for Oozie\")\n remote.execute_command('sudo su - -c \"/opt/oozie/bin/ooziedb.sh '\n 'create -sqlfile oozie.sql '\n '-run Validate DB Connection\" hadoop')\n\n\ndef _start_mysql(remote):\n LOG.debug(\"Starting mysql\")\n remote.execute_command('/opt/start-mysql.sh')\n\n\ndef _start_oozie(remote):\n remote.execute_command(\n 'sudo su - -c \"/opt/oozie/bin/oozied.sh start\" hadoop')\n\n\ndef await_datanodes(cluster):\n datanodes_count = len(vu.get_datanodes(cluster))\n if datanodes_count < 1:\n return\n\n LOG.info(_LI(\"Waiting %s datanodes to start up\"), datanodes_count)\n with vu.get_namenode(cluster).remote() as r:\n while True:\n if _check_datanodes_count(r, datanodes_count):\n LOG.info(\n _LI('Datanodes on cluster %s have been started'),\n cluster.name)\n return\n\n context.sleep(1)\n\n if not g.check_cluster_exists(cluster):\n LOG.info(\n _LI('Stop waiting datanodes on cluster %s since it has '\n 'been deleted'), cluster.name)\n return\n\n\ndef _check_datanodes_count(remote, count):\n if count < 1:\n return True\n\n LOG.debug(\"Checking datanode count\")\n exit_code, stdout = remote.execute_command(\n 'sudo su -lc \"hdfs dfsadmin -report\" hadoop | '\n 'grep \\'Live datanodes\\|Datanodes available:\\' | '\n 'grep -o \\'[0-9]\\+\\' | head -n 1')\n LOG.debug(\"Datanode count='%s'\" % stdout.rstrip())\n\n return exit_code == 0 and stdout and int(stdout) == count\n\n\ndef _hive_create_warehouse_dir(remote):\n LOG.debug(\"Creating Hive warehouse dir\")\n remote.execute_command(\"sudo su - -c 'hadoop fs -mkdir -p \"\n \"/user/hive/warehouse' hadoop\")\n\n\ndef _hive_copy_shared_conf(remote, dest):\n LOG.debug(\"Copying shared Hive conf\")\n dirname, filename = os.path.split(dest)\n remote.execute_command(\n \"sudo su - -c 'hadoop fs -mkdir -p %s && \"\n \"hadoop fs -put /opt/hive/conf/hive-site.xml \"\n \"%s' hadoop\" % (dirname, dest))\n\n\ndef _hive_create_db(remote):\n LOG.debug(\"Creating Hive metastore db...\")\n remote.execute_command(\"mysql -u root < /tmp/create_hive_db.sql\")\n\n\ndef _hive_metastore_start(remote):\n LOG.debug(\"Starting Hive Metastore Server...\")\n remote.execute_command(\"sudo su - -c 'nohup /opt/hive/bin/hive\"\n \" --service metastore > /dev/null &' hadoop\")\n\n\ndef start_hiveserver_process(pctx, instance):\n with instance.remote() as r:\n _hive_create_warehouse_dir(r)\n _hive_copy_shared_conf(\n r, edp.get_hive_shared_conf_path('hadoop'))\n\n if c_helper.is_mysql_enabled(pctx, instance.cluster):\n oozie = vu.get_oozie(instance.node_group.cluster)\n if not oozie or instance.hostname() != oozie.hostname():\n _start_mysql(r)\n\n sql_script = files.get_file_text(\n 'plugins/vanilla/hadoop2/resources/create_hive_db.sql'\n )\n\n r.write_file_to('/tmp/create_hive_db.sql', sql_script)\n _hive_create_db(r)\n _hive_metastore_start(r)\n LOG.info(_LI(\"Hive Metastore server at %s has been \"\n \"started\"),\n instance.hostname())\n","repo_name":"esikachev/scenario","sub_path":"sahara/plugins/vanilla/hadoop2/run_scripts.py","file_name":"run_scripts.py","file_ext":"py","file_size_in_byte":7276,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"70314770826","text":"\"\"\"Handler file for all routes pertaining to auths\"\"\"\n\nfrom _main_.utils.route_handler import RouteHandler\nfrom _main_.utils.common import get_date_and_time_in_milliseconds\nfrom api.services.auth import AuthService\nfrom _main_.utils.massenergize_response import MassenergizeResponse\nfrom _main_.utils.massenergize_errors import NotAuthorizedError\nfrom _main_.utils.context import Context\nfrom _main_.settings import RUN_SERVER_LOCALLY\nfrom api.constants import WHEN_USER_AUTHENTICATED_SESSION_EXPIRES\n\nONE_YEAR = 365*24*60*60\nONE_DAY = 24*60*60\n# ONE_DAY = 2*60 # FOR TESTING UNCOMMENT THIS (2 Minutes instead of 24hrs)\n\nclass AuthHandler(RouteHandler):\n\n def __init__(self):\n super().__init__()\n self.service = AuthService()\n self.registerRoutes()\n\n def registerRoutes(self):\n self.add(\"/auth.login\", self.login) \n self.add(\"/auth.logout\", self.logout)\n self.add(\"/auth.verify\", self.whoami)\n self.add(\"/auth.whoami\", self.whoami)\n self.add(\"/auth.test\", self.whoami)\n self.add(\"/auth.verifyCaptcha\", self.verify_captcha)\n self.add(\"/auth.signinasguest\", self.guest_login) \n self.add(\"/auth.email.verification\", self.email_verification) \n\n def login(self, request): \n context: Context = request.context\n user_info, token, err = self.service.login(context)\n if err:\n return err\n\n # create a response\n response: MassenergizeResponse = MassenergizeResponse(user_info)\n\n # set cookie on response before sending\n # cookie expiration set to 1yr\n MAX_AGE = ONE_YEAR\n\n # if the signin is from an admin site then set it to 24 hrs\n if(context.is_admin_site):\n MAX_AGE = ONE_DAY\n expiration_time = get_date_and_time_in_milliseconds(hours=24) # UNDO BEFORE PR , BPR\n # expiration_time = get_date_and_time_in_milliseconds(hours=0.033) # FOR TESTING, UNCOMMENT THIS\n request.session[WHEN_USER_AUTHENTICATED_SESSION_EXPIRES] = expiration_time\n\n if RUN_SERVER_LOCALLY:\n response.set_cookie(\"token\", value=token, max_age=MAX_AGE, samesite='Strict')\n else:\n response.set_cookie(\"token\", secure=True, value=token, max_age=MAX_AGE, samesite='None')\n return response\n \n def logout(self, request): \n # create a response\n response = MassenergizeResponse()\n # delete token cookie on it before sending\n response.delete_cookie(\"token\")\n\n return response\n\n\n def whoami(self, request): \n context: Context = request.context\n\n user_info, err = self.service.whoami(context)\n if err:\n return err\n return MassenergizeResponse(data=user_info)\n\n\n\n def verify_captcha(self, request): \n context: Context = request.context\n captcha_string = context.args.get('captchaString', None)\n verification, err = self.service.verify_captcha(context, captcha_string)\n if err:\n return err\n \n return MassenergizeResponse(data=verification)\n\n def guest_login(self, request): \n context: Context = request.context\n\n # if the signin is from an admin site then set it to 24 hrs\n if(context.is_admin_site):\n return NotAuthorizedError()\n\n user_info, token, err = self.service.guest_login(context)\n if err:\n return err\n\n # create a response\n response: MassenergizeResponse = MassenergizeResponse(user_info)\n\n # set cookie on response before sending\n # cookie expiration set to 1yr\n MAX_AGE = ONE_DAY\n\n if RUN_SERVER_LOCALLY:\n response.set_cookie(\"token\", value=token, max_age=MAX_AGE, samesite='Strict')\n else:\n response.set_cookie(\"token\", secure=True, value=token, max_age=MAX_AGE, samesite='None')\n return response\n \n\n\n def email_verification(self, request): \n context: Context = request.context\n args: dict = context.args\n self.validator.expect('email', str, is_required=True)\n self.validator.expect(\"url\",str, is_required=True)\n self.validator.expect(\"community_id\",str, is_required=True)\n\n args, err = self.validator.verify(args)\n\n if err:\n return err\n \n res, err = self.service.email_verification(context, args)\n if err:\n return err\n return MassenergizeResponse(data=res)","repo_name":"massenergize/api","sub_path":"src/api/handlers/auth.py","file_name":"auth.py","file_ext":"py","file_size_in_byte":4093,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"81"} +{"seq_id":"37977201594","text":"#!/usr/bin/env python\nimport sys\nimport os\nimport requests\n\n# url to download the requests documentation as a PDF file\n# (the file is displayed after retrieval)\n\nREQUESTS_DOCS_URL = 'http://readthedocs.org/projects/requests/downloads/pdf/master/'\nREQUESTS_DOCS_FILENAME = 'requests_docs.pdf'\n\ntry:\n response = requests.get(REQUESTS_DOCS_URL)\nexcept requests.HTTPError as err:\n print(\"Sorry,\", err)\n exit(1)\n\nif response.status_code == requests.codes.ok:\n\n with open(REQUESTS_DOCS_FILENAME, 'wb') as docs_out:\n docs_out.write(response.content)\n\n if sys.platform == 'win32':\n cmd = REQUESTS_DOCS_FILENAME\n elif sys.platform == 'darwin':\n cmd = 'open ' + REQUESTS_DOCS_FILENAME\n else:\n cmd = 'acroread ' + REQUESTS_DOCS_FILENAME\n\n os.system(cmd)\n\nelse:\n print(\"Unable to read document\")\n","repo_name":"jnshwu/py3gemast","sub_path":"EXAMPLES/req_download_pdf.py","file_name":"req_download_pdf.py","file_ext":"py","file_size_in_byte":839,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"74230261063","text":"from flask import Flask, render_template, request\nfrom model.model import Converter\nimport utils.checker as Checker\nimport model.function as Model\nfrom flask_cors import CORS\n\napp = Flask(__name__)\nCORS(app)\n\n\n@app.route(\"/\", methods=[\"GET\"])\ndef main():\n return render_template(\"index.html\")\n\n\n@app.route(\"/api/check\", methods=[\"GET\"])\ndef check():\n url = request.args[\"url\"].replace(\" \", \"\")\n\n if Checker.isWhitelist(url):\n print(\"Url is in whitelist\")\n return \"0\"\n\n if Checker.isBlacklist(url):\n print(\"Url is in blacklist\")\n return \"1\"\n\n # if Checker.isSpam(url):\n # print(\"Url is spam\")\n # return \"1\"\n\n if Checker.checkPageRank(url):\n print(\"Url is low pagerank\")\n return \"1\"\n\n if Model.check(url):\n print(\"Model: Url is phishing\")\n return \"1\"\n else:\n print(\"Model: Url is normal\")\n return \"0\"\n\n\nif __name__ == \"__main__\":\n app.run(threaded=True, debug=True, port=8080)\n","repo_name":"Chisj1/AVL-team","sub_path":"AVL-server/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":986,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"7670071901","text":"# -*- coding: utf-8 -*-\n\n'''\nCommand line interface for yaspc.\n'''\nfrom __future__ import absolute_import, print_function\n\nimport sys\nimport os\nimport json\n\nfrom argparse import ArgumentParser\nfrom argparse import RawTextHelpFormatter\n\nfrom frontend import log\nfrom frontend import compiler\n\nfrom frontend import explain\n\nfrom backend.ir.ir import import_ir\nfrom backend.sys_dep.x86.code_generator import CodeGenerator\nfrom backend.asm.inttype import IntType\n\nfrom optimization import do_optimization\n\n__version__ = 0.4\n__date__ = '2017-06-02'\n\nDEBUG = 0\n\n\nclass CLIError(Exception):\n '''Generic exception to raise and log different fatal errors.'''\n\n def __init__(self, msg):\n super(CLIError).__init__(type(self))\n self.msg = \"E: %s\" % msg\n\n def __str__(self):\n return self.msg\n\n def __unicode__(self):\n return self.msg\n\ndef analysisarg(argv):\n \"\"\" 对输入的参数进行解析 \"\"\"\n\n if argv is None:\n argv = sys.argv\n else:\n sys.argv.extend(argv)\n\n program_name = os.path.basename(sys.argv[0])\n program_version = \"v%s\" % __version__\n program_build_date = str(__date__)\n program_version_message = '%%(prog)s %s (%s)' % (program_version,\n program_build_date)\n program_shortdesc = 'Pascal 1973 compiler'\n\n # Setup argument parser\n parser = ArgumentParser(\n prog=program_name,\n description=program_shortdesc,\n formatter_class=RawTextHelpFormatter)\n\n parser.add_argument(\"-t\", \"--syntax-tree\", dest=\"tree\",\n action=\"store_true\", help=\"print the syntax tree to stdout\")\n\n parser.add_argument(\"-C\", \"--json-backend\", dest=\"json_backend\",\n action=\"store_true\", help=\"translate json IR to ASM\")\n\n parser.add_argument(\"-F\", \"--json-frontend\", dest=\"json_frontend\",\n action=\"store_true\", help=\"translate PAS to json IR\")\n\n parser.add_argument(\"-A\", \"--json-asm\", dest=\"json_asm\",\n action=\"store_true\", help=\"translate json IR to ASM\")\n\n parser.add_argument(\"-S\", \"--emit-llvm\", dest=\"ir_code\",\n action=\"store_true\", help=\"save LLVM-IR (plain text)\")\n parser.add_argument(\"-b\", \"--bit-code\", dest=\"bit_code\",\n action=\"store_true\", help=\"save LLVM-IR (bit code)\")\n parser.add_argument(\"-o\", \"--object-code\", dest=\"obj_code\",\n action=\"store_true\", help=\"save object code\")\n parser.add_argument(\"-O\", \"--optimize\", dest=\"optimize\", metavar=\"LEVEL\", action=\"store\",\n choices=['0', '1', '2', '3'], default='0',\n help=\"run various optimizations on the LLVM-IR code\")\n parser.add_argument('-a', '--asm', dest='asm_code',\n action='store_true', help='save native assembly code')\n parser.add_argument('-e', '--executable', dest='exe',\n action='store_true', help='generate executable file using clang and save')\n\n parser.add_argument(\"-T\", \"--triple\", dest=\"triple\", action=\"store\", default=None,\n help=\"define the target triple, e.g. x86_64-pc-linux or i686-pc-win32\")\n\n parser.add_argument(\"-mcpu\", dest=\"cpu\", default=None,\n help='target specific cpu type')\n\n parser.add_argument(\"-v\", \"--verbosity\",\n dest=\"verbosity\", action=\"count\", default=0)\n parser.add_argument('-V', '--version', action='version',\n version=program_version_message)\n parser.add_argument(dest=\"ifile\", metavar=\"ifile\")\n parser.add_argument(dest=\"ofile\", metavar=\"ofile\")\n\n # Process arguments\n args = parser.parse_args()\n\n return args\n\ndef json_optimize(level, input_file, output_file):\n '''\n 对JSON格式的IR依据指定的优化级别level���行优化\n @param level: 优化级别\n @param input_file: 输入的JSON文件\n @param output_file: 输出的JSON文件 \n '''\n\n if level != 0:\n # set default value\n control_flow_flag = False\n reach_defination_flag = False\n loop_optimization_flag = False\n if level >= 3:\n loop_optimization_flag = True\n if level >= 2:\n reach_defination_flag = True\n if level >= 1:\n control_flow_flag = True\n\n # do optimization\n do_optimization.optimize_exec(\n input_file,\n output_file,\n control_flow_flag,\n reach_defination_flag,\n loop_optimization_flag)\n\n\ndef json_backend(input_file, output_file):\n \"\"\" 对JSON格式的IR进行后端处理,把JSON格式的IR转换为汇编语言ASM \"\"\"\n\n with open(input_file, \"r\") as json_ir_file:\n ''' 打开JSON格式的IR文件,转换成JSON流 '''\n json_file_str = json_ir_file.read()\n json_file_data = json.loads(json_file_str)\n\n json_ir = import_ir(json_file_data, output_file)\n\n # 对JSON文件格式的IR进行后端处理,产生汇编代码\n asm = CodeGenerator(None, IntType.INT32)\n json_new_file = asm.generate(json_ir)\n\n json_file_str = json_new_file.to_source()\n\n # 把转换后的汇编程序写到文件中\n with open(output_file, 'w') as json_output_file:\n json_output_file.write(json_file_str)\n\n\ndef run(argv=None):\n \"\"\" 主函数的流程 \"\"\"\n sys.setrecursionlimit(50000)\n\n try:\n\n args = analysisarg(argv)\n\n if args.verbosity:\n log.set_verbosity(args.verbosity)\n else:\n log.set_verbosity(0)\n\n input_file = args.ifile\n output_file = args.ofile\n\n llvm_ir = (args.ir_code or args.bit_code or\n args.obj_code or args.asm_code or\n args.exe)\n\n if llvm_ir or args.json_frontend or args.json_asm or args.tree:\n current_compiler = compiler.Compiler(input_file)\n current_compiler.analyze()\n\n if args.tree:\n current_compiler.print_tree()\n\n if llvm_ir:\n current_compiler.synthesize(args.triple, args.cpu)\n\n if args.optimize:\n current_compiler.optimize(int(args.optimize))\n\n # 后面的选项同时只有一个有效,若没有指定,则默认按照LLVM IR输出\n if args.ir_code:\n current_compiler.save_ir(output_file)\n elif args.bit_code:\n current_compiler.save_bit_code(output_file)\n elif args.obj_code:\n current_compiler.save_obj_code(output_file)\n elif args.asm_code:\n current_compiler.save_asm_code(output_file)\n elif args.exe:\n current_compiler.save_executable(output_file)\n else:\n current_compiler.save_ir(output_file)\n\n else:\n\n # 若只进行前端操作,则进行词法、语法和语义处理,产生中间表示语言IR(JSON格式)\n if args.json_frontend:\n ir_json = explain.explain()\n ir_json.programExplain(current_compiler.ast)\n ir_json.store(output_file)\n\n # 优化作为可选项,进行优化。若不指定,则优化级别为0\n optimize_level = int(args.optimize)\n if optimize_level != 0:\n\n # 若前端指定,则优化的输入和输出文件都是前端的输出文件\n if args.json_frontend:\n opt_input_file = output_file\n opt_output_file = output_file\n else:\n opt_input_file = input_file\n opt_output_file = output_file\n\n json_optimize(optimize_level, opt_input_file, opt_output_file)\n\n if args.json_backend:\n\n # 若前端指定,则后端的输入和输出文件都是前端的输出文件\n if args.json_frontend:\n backend_input_file = output_file\n backend_output_file = output_file\n else:\n backend_input_file = input_file\n backend_output_file = output_file\n\n json_backend(backend_input_file, backend_output_file)\n\n return 0\n\n except KeyboardInterrupt:\n return 0\n","repo_name":"zengljnwpu/yaspc","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":8324,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"20443189798","text":"# -*- coding:utf-8 -*-\n# email:bingchengzhou@foxmail.com\n# create: 2020/12/\nimport torch\nimport torch.nn as nn\nimport numpy as np\nfrom utils.dl_util import cal_feat_mask\nimport torch.nn.functional as F\nimport math\nfrom operators.self_patch import Selfpatch\nfrom operators.se_layer import SELayer\n\n\ndef gussin(v, width=32):\n outk = []\n v = v\n for i in range(width):\n for k in range(width):\n\n out = []\n for x in range(width):\n row = []\n for y in range(width):\n cord_x = i\n cord_y = k\n dis_x = np.abs(x - cord_x)\n dis_y = np.abs(y - cord_y)\n dis_add = -(dis_x * dis_x + dis_y * dis_y)\n dis_add = dis_add / (2 * v * v)\n dis_add = math.exp(dis_add) / (2 * math.pi * v * v)\n\n row.append(dis_add)\n out.append(row)\n\n outk.append(out)\n\n out = np.array(outk)\n f = out.sum(-1).sum(-1)\n q = []\n for i in range(width * width):\n g = out[i] / f[i]\n q.append(g)\n out = np.array(q)\n return torch.from_numpy(out)\n\n\nclass BASE(nn.Module):\n def __init__(self, inner_nc):\n super(BASE, self).__init__()\n se = SELayer(inner_nc, 16)\n model = [se]\n gus = gussin(1.5).cuda()\n self.gus = torch.unsqueeze(gus, 1).double()\n self.model = nn.Sequential(*model)\n self.down = nn.Sequential(\n nn.Conv2d(1024, 512, 1, 1, 0, bias=False),\n nn.InstanceNorm2d(512),\n nn.LeakyReLU(negative_slope=0.2)\n )\n\n def forward(self, x):\n Nonparm = Selfpatch()\n out_32 = self.model(x)\n b, c, h, w = out_32.size()\n if self.gus.device != out_32.device:\n self.gus = self.gus.to(out_32.device)\n\n gus = self.gus.float()\n gus_out = out_32[0].expand(h * w, c, h, w)\n gus_out = gus * gus_out\n gus_out = torch.sum(gus_out, -1)\n gus_out = torch.sum(gus_out, -1)\n gus_out = gus_out.contiguous().view(b, c, h, w)\n csa2_in = F.sigmoid(out_32)\n csa2_f = torch.nn.functional.pad(csa2_in, (1, 1, 1, 1))\n csa2_ff = torch.nn.functional.pad(out_32, (1, 1, 1, 1))\n csa2_fff, csa2_f, csa2_conv = Nonparm.buildAutoencoder(csa2_f[0], csa2_in[0], csa2_ff[0], 3, 1)\n csa2_conv = csa2_conv.expand_as(csa2_f)\n csa_a = csa2_conv * csa2_f\n csa_a = torch.mean(csa_a, 1)\n a_c, a_h, a_w = csa_a.size()\n csa_a = csa_a.contiguous().view(a_c, -1)\n csa_a = F.softmax(csa_a, dim=1)\n csa_a = csa_a.contiguous().view(a_c, 1, a_h, a_h)\n out = csa_a * csa2_fff\n out = torch.sum(out, -1)\n out = torch.sum(out, -1)\n out_csa = out.contiguous().view(b, c, h, w)\n out_32 = torch.cat([gus_out, out_csa], 1)\n out_32 = self.down(out_32)\n return out_32\n\n\nclass PartialConv(nn.Module):\n def __init__(self, in_channels, out_channels, kernel_size, stride=1,\n padding=0, dilation=1, groups=1, bias=True):\n super().__init__()\n self.input_conv = nn.Conv2d(in_channels, out_channels, kernel_size,\n stride, padding, dilation, groups, bias)\n self.mask_conv = nn.Conv2d(in_channels, out_channels, kernel_size,\n stride, padding, dilation, groups, False)\n\n torch.nn.init.constant_(self.mask_conv.weight, 1.0)\n\n # mask is not updated\n for param in self.mask_conv.parameters():\n param.requires_grad = False\n\n def forward(self, inputt):\n # http://masc.cs.gmu.edu/wiki/partialconv\n # C(X) = W^T * X + b, C(0) = b, D(M) = 1 * M + 0 = sum(M)\n # W^T* (M .* X) / sum(M) + b = [C(M .* X) – C(0)] / D(M) + C(0)\n\n input = inputt[0]\n mask = inputt[1].float().to(inputt[1].device)\n # output W^T *x\n output = self.input_conv(input * mask)\n if self.input_conv.bias is not None:\n output_bias = self.input_conv.bias.view(1, -1, 1, 1).expand_as(\n output)\n else:\n output_bias = torch.zeros_like(output)\n # output_bias: W^T * X + B\n\n # 在进行部分卷积之后,进行Mask的更新。更新规则为:\n # 如果卷积(滑动)窗口对应的Mask值至少有一个对应的1,那么就更新卷积后对应位置Mask为1。\n with torch.no_grad():\n output_mask = self.mask_conv(mask)\n\n no_update_holes = output_mask == 0\n mask_sum = output_mask.masked_fill_(no_update_holes.bool(), 1.0)\n # output_pre 即为 W^T* (M .* X) / sum(M) + b\n output_pre = (output - output_bias) / mask_sum + output_bias\n output = output_pre.masked_fill_(no_update_holes.bool(), 0.0)\n new_mask = torch.ones_like(output)\n new_mask = new_mask.masked_fill_(no_update_holes.bool(), 0.0)\n out = []\n out.append(output)\n out.append(new_mask)\n return out\n\n\nclass PCBActiv(nn.Module):\n def __init__(self, in_ch, out_ch, bn=True, sample='none-3', activ='leaky',\n conv_bias=False, innorm=False, inner=False, outer=False):\n super().__init__()\n if sample == 'same-5':\n self.conv = PartialConv(in_ch, out_ch, 5, 1, 2, bias=conv_bias)\n elif sample == 'same-7':\n self.conv = PartialConv(in_ch, out_ch, 7, 1, 3, bias=conv_bias)\n elif sample == 'down-3':\n self.conv = PartialConv(in_ch, out_ch, 3, 2, 1, bias=conv_bias)\n else:\n self.conv = PartialConv(in_ch, out_ch, 3, 1, 1, bias=conv_bias)\n\n if bn:\n self.bn = nn.InstanceNorm2d(out_ch, affine=True)\n if activ == 'relu':\n self.activation = nn.ReLU()\n elif activ == 'leaky':\n self.activation = nn.LeakyReLU(negative_slope=0.2)\n self.innorm = innorm\n self.inner = inner\n self.outer = outer\n\n def forward(self, input):\n out = input\n if self.inner:\n out[0] = self.bn(out[0])\n out[0] = self.activation(out[0])\n out = self.conv(out)\n out[0] = self.bn(out[0])\n out[0] = self.activation(out[0])\n\n elif self.innorm:\n out = self.conv(out)\n out[0] = self.bn(out[0])\n out[0] = self.activation(out[0])\n elif self.outer:\n out = self.conv(out)\n out[0] = self.bn(out[0])\n else:\n out = self.conv(out)\n out[0] = self.bn(out[0])\n if hasattr(self, 'activation'):\n out[0] = self.activation(out[0])\n return out\n\n\nclass ConvDown(nn.Module):\n def __init__(self, in_c, out_c, kernel, stride, padding=0, dilation=1, groups=1, bias=False, layers=1, activ=True):\n super().__init__()\n nf_mult = 1\n nums = out_c / 64\n sequence = []\n\n for i in range(1, layers + 1):\n nf_mult_prev = nf_mult\n if nums == 8:\n if in_c == 512:\n nf_mult = 1\n else:\n nf_mult = 2\n else:\n nf_mult = min(2 ** i, 8)\n if kernel != 1:\n\n if activ == False and layers == 1:\n sequence += [\n nn.Conv2d(nf_mult_prev * in_c, nf_mult * in_c,\n kernel_size=kernel, stride=stride, padding=padding, bias=bias),\n nn.InstanceNorm2d(nf_mult * in_c)\n ]\n else:\n sequence += [\n nn.Conv2d(nf_mult_prev * in_c, nf_mult * in_c,\n kernel_size=kernel, stride=stride, padding=padding, bias=bias),\n nn.InstanceNorm2d(nf_mult * in_c),\n nn.LeakyReLU(0.2, True)\n ]\n\n else:\n\n sequence += [\n nn.Conv2d(in_c, out_c,\n kernel_size=kernel, stride=stride, padding=padding, bias=bias),\n nn.InstanceNorm2d(out_c),\n nn.LeakyReLU(0.2, True)\n ]\n\n if activ == False:\n if i + 1 == layers:\n if layers == 2:\n sequence += [\n nn.Conv2d(nf_mult * in_c, nf_mult * in_c,\n kernel_size=kernel, stride=stride, padding=padding, bias=bias),\n nn.InstanceNorm2d(nf_mult * in_c)\n ]\n else:\n sequence += [\n nn.Conv2d(nf_mult_prev * in_c, nf_mult * in_c,\n kernel_size=kernel, stride=stride, padding=padding, bias=bias),\n nn.InstanceNorm2d(nf_mult * in_c)\n ]\n break\n\n self.model = nn.Sequential(*sequence)\n\n def forward(self, input):\n return self.model(input)\n\n\nclass ConvUp(nn.Module):\n def __init__(self, in_c, out_c, kernel, stride, padding=0, dilation=1, groups=1, bias=False):\n super().__init__()\n\n self.conv = nn.Conv2d(in_c, out_c, kernel,\n stride, padding, dilation, groups, bias)\n self.bn = nn.InstanceNorm2d(out_c)\n self.relu = nn.LeakyReLU(negative_slope=0.2)\n\n def forward(self, input, size):\n out = F.interpolate(input=input, size=size, mode='bilinear')\n out = self.conv(out)\n out = self.bn(out)\n out = self.relu(out)\n return out\n\n\nclass InnerCos(nn.Module):\n def __init__(self):\n super(InnerCos, self).__init__()\n self.criterion = nn.L1Loss()\n self.target = None\n self.down_model = nn.Sequential(\n nn.Conv2d(256, 3, kernel_size=1,stride=1, padding=0),\n nn.Tanh()\n )\n\n def set_target(self, input_gt):\n self.structure_gt = F.interpolate(input_gt, size=(32, 32), mode='bilinear')\n\n def get_target(self):\n return self.target\n\n def forward(self, x_structure_fi):\n if self.training:\n structure_fi = self.down_model(x_structure_fi)\n self.loss = self.criterion(structure_fi, self.structure_gt)\n return self.loss\n\n def backward(self, retain_graph=True):\n if self.training:\n self.loss.backward(retain_graph=retain_graph)\n return self.loss\n\n def __repr__(self):\n\n return self.__class__.__name__\n\n\nclass PCconv(nn.Module):\n def __init__(self, input_w=1024, nc=None, nw=None,\n use_base=True, use_inner_loss=False):\n super(PCconv, self).__init__()\n # input_w mush be 2^k, 64设置为\n ni = 6\n if nc is None:\n nc = [64, 128, 256, 512, 512, 512]\n if nw is None:\n nw = [512, 128, 32, 16, 8, 4]\n self.nc = nc\n self.nw = nw\n # 使用第三层作为mask信息的特征feature\n mask_w = nw[2]\n mask_c = nc[2]\n self.mask_w = mask_w\n self.conv_feat_mask_layer_num = int(np.log2(input_w / mask_w))\n self.activation = nn.LeakyReLU(negative_slope=0.2)\n\n # feature sample 层, 分为上采样和下采样\n self.down_1 = ConvDown(nc[0], 2 * nc[0], 8, 4, padding=2, layers=2)\n self.down_2 = ConvDown(nc[1], 2 * nc[1], 8, 4, padding=2, layers=1)\n self.down_3 = ConvDown(nc[2], nc[2], 1, 1)\n # 上采样层基本一致\n self.up = ConvUp(512, mask_c, 1, 1)\n\n # feature 层融合后的下采样层\n self.down = ConvDown(3 * mask_c, mask_c, 1, 1)\n\n # texture和structure融合后的下采样层\n self.fuse = ConvDown(2 * mask_c, 2 * mask_c, 1, 1)\n\n # texture和structure融合后上采样和下采样到input channel中\n self.up_1 = ConvUp(2 * mask_c, nc[0], 1, 1)\n self.up_2 = ConvUp(2 * mask_c, nc[1], 1, 1)\n self.up_3 = ConvUp(2 * mask_c, nc[2], 1, 1)\n\n self.down_4 = ConvDown(2 * mask_c, 2 * mask_c, 4, 2, padding=1, layers=int(np.log2(mask_w / nw[3])))\n self.down_5 = ConvDown(2 * mask_c, 2 * mask_c, 4, 2, padding=1, layers=int(np.log2(mask_w / nw[4])))\n self.down_6 = ConvDown(2 * mask_c, 2 * mask_c, 4, 2, padding=1, layers=int(np.log2(mask_w / nw[5])))\n self.use_base = use_base\n\n if self.use_base:\n self.base = BASE(512) # 将feature equalization texture feature and structure feature\n\n # partial conv层\n seuqence_3 = []\n seuqence_5 = []\n seuqence_7 = []\n for i in range(5):\n seuqence_3 += [PCBActiv(256, 256, innorm=True)]\n seuqence_5 += [PCBActiv(256, 256, sample='same-5', innorm=True)]\n seuqence_7 += [PCBActiv(256, 256, sample='same-7', innorm=True)]\n self.cov_3 = nn.Sequential(*seuqence_3)\n self.cov_5 = nn.Sequential(*seuqence_5)\n self.cov_7 = nn.Sequential(*seuqence_7)\n self.device = torch.device(\"cuda:0\")\n\n self.use_inner_loss = use_inner_loss\n\n def reset_device(self, device):\n self.device = device\n\n def get_features(self, input):\n for i in range(len(input)):\n if self.device != input[i].device:\n input[i] = input[i].to(self.device)\n x_1 = self.activation(input[0])\n x_2 = self.activation(input[1])\n x_3 = self.activation(input[2])\n x_4 = self.activation(input[3])\n x_5 = self.activation(input[4])\n x_6 = self.activation(input[5])\n # Change the shape of each layer and intergrate low-level/high-level features\n\n x_1 = self.down_1(x_1)\n x_2 = self.down_2(x_2)\n x_3 = self.down_3(x_3)\n x_4 = self.up(x_4, (self.mask_w, self.mask_w))\n x_5 = self.up(x_5, (self.mask_w, self.mask_w))\n x_6 = self.up(x_6, (self.mask_w, self.mask_w))\n\n # The first three layers are Texture/detail\n # The last three layers are Structure\n x_texture = torch.cat([x_1, x_2, x_3], 1)\n x_structure = torch.cat([x_4, x_5, x_6], 1)\n\n x_texture = self.down(x_texture)\n x_structure = self.down(x_structure)\n return x_texture, x_structure\n\n def forward(self, input, mask):\n if self.device != mask.device:\n mask = mask.to(self.device)\n\n mask = cal_feat_mask(mask, self.conv_feat_mask_layer_num, 1)\n # input[2]:256 32 32\n b, c, h, w = input[2].size()\n mask_1 = torch.add(torch.neg(mask.float()), 1)\n mask_1 = mask_1.expand(b, c, h, w)\n\n x_texture, x_structure = self.get_features(input)\n\n # Multi Scale PConv fill the Details\n x_texture_3 = self.cov_3([x_texture, mask_1])\n x_texture_5 = self.cov_5([x_texture, mask_1])\n x_texture_7 = self.cov_7([x_texture, mask_1])\n x_texture_fuse = torch.cat([x_texture_3[0], x_texture_5[0], x_texture_7[0]], 1)\n x_texture_fi = self.down(x_texture_fuse)\n\n # Multi Scale PConv fill the Structure\n x_structure_3 = self.cov_3([x_structure, mask_1])\n x_structure_5 = self.cov_5([x_structure, mask_1])\n x_structure_7 = self.cov_7([x_structure, mask_1])\n x_structure_fuse = torch.cat([x_structure_3[0], x_structure_5[0], x_structure_7[0]], 1)\n x_structure_fi = self.down(x_structure_fuse)\n\n x_cat_fuse = self.fuse(torch.cat([x_structure_fi, x_texture_fi], 1))\n if self.use_base:\n x_cat_fuse = self.base(x_cat_fuse)\n\n x_1 = self.up_1(x_cat_fuse, (self.nw[0], self.nw[0])) + input[0]\n x_2 = self.up_2(x_cat_fuse, (self.nw[1], self.nw[1])) + input[1]\n x_3 = self.up_3(x_cat_fuse, (self.nw[2], self.nw[2])) + input[2]\n x_4 = self.down_4(x_cat_fuse) + input[3]\n x_5 = self.down_5(x_cat_fuse) + input[4]\n x_6 = self.down_6(x_cat_fuse) + input[5]\n\n out = [x_1, x_2, x_3, x_4, x_5, x_6]\n if self.use_inner_loss:\n loss = [x_texture_fi, x_structure_fi]\n return out, loss\n else:\n return out\n\n","repo_name":"zhou3968322/dl-lab","sub_path":"networks/pc_conv.py","file_name":"pc_conv.py","file_ext":"py","file_size_in_byte":16105,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"20251333530","text":"import typing\nfrom typing import *\nfrom operator import eq\nfrom .. import dataset as ds\nfrom .fixtures.employee_adapter import EmployeeAdapter, EmployeeDataFrameAdapter\nfrom ..query_parser import parse, parse_statement\nfrom ..ast import *\nfrom ..utils.visualizer import LogicalPlanViz \nfrom ..query import Query\n\ndataset = ds.DataSet()\nadapter = EmployeeDataFrameAdapter()\ndataset.add_adapter(adapter)\n\ndef test_getChildren():\n sql = \"select * from employees, employees_2 where employees.employee_id = employees_2.employee_id\"\n ast = parse_statement(sql)\n \"\"\"\n The ast should look like:\n selection: employees.employee_id = employees_2.employee_id\n |\n join: true\n / \\\n load load \n \"\"\"\n child1 = getChildren(ast)\n assert len(child1) == 1\n assert isinstance(child1[0], JoinOp)\n child2 = getChildren(child1[0])\n assert len(child2) == 2\n assert isinstance(child2[0], LoadOp)\n assert isinstance(child2[1], LoadOp)\n child3 = getChildren(child2[0])\n assert len(child3) == 0\n \ndef test_equalExprs_all_cases():\n sql = \"select * from employees, employees_2 where employees.employee_id = employees_2.employee_id\"\n ast = parse_statement(sql)\n ast2 = parse_statement(sql)\n assert equalUnresolvedExprs(ast, ast2)\n query1 = Query(dataset, ast)\n query2 = Query(dataset, ast2)\n assert equalResolvedExprs(query1.operations, query2.operations)\n sql2 = \"select * from employees join employees_2 on employees.employee_id = employees_2.employee_id\"\n ast3 = parse_statement(sql2)\n \"\"\"\n The ast3 should look like:\n join: employees.employee_id = employees_2.employee_id\n / \\\n load load \n \"\"\"\n assert not equalUnresolvedExprs(ast, ast3)\n query3 = Query(dataset, ast3)\n assert not equalResolvedExprs(query1.operations, query3.operations)\n \n assert equalExprs(ast, ast2)\n assert equalExprs(ast, query2.operations, ignore_schema=True, match_loadop_and_relation=True)\n assert not equalExprs(ast, query2.operations, ignore_schema=False, match_loadop_and_relation=True)\n assert not equalExprs(ast, query2.operations, ignore_schema=True, match_loadop_and_relation=False)\n assert not equalExprs(ast, query2.operations, ignore_schema=False, match_loadop_and_relation=False)\n\ndef test_traverse():\n sql = \"\"\"\n select * \n from \n (select employee_id from employees, employees_2 where employees.employee_id = employees_2.employee_id) as table1, \n (select employee_id from employees, employees_2 where employees.employee_id = employees_2.employee_id) as table2\n where \n table1.employee_id = table2.employee_id\n \"\"\"\n ast = parse_statement(sql)\n #LogicalPlanViz.show(ast)\n \"\"\"\n The ast should look like:\n selection: table1.employee_id = table2.employee_id\n |\n join: true\n / \\ \n alias alias\n | |\n projection projection: employee_id\n | |\n selection selection: employees.employee_id = employees_2.employee_id\n | |\n join: true join: true\n / \\ / \\ \n load load load: employees load: employees_2\n \"\"\"\n i = 0\n dfs_truth_node_seq = [\n SelectionOp, \n JoinOp, \n AliasOp, ProjectionOp, SelectionOp, JoinOp, LoadOp, LoadOp, \n AliasOp, ProjectionOp, SelectionOp, JoinOp, LoadOp, LoadOp\n ]\n dfs_truth_node_parent_seq = [\n (None, 0), \n (SelectionOp, 0), \n (JoinOp, 0), \n (AliasOp, 0), (ProjectionOp, 0), (SelectionOp, 0), (JoinOp, 0), (JoinOp, 1), \n (JoinOp, 1), (AliasOp, 0), (ProjectionOp, 0), (SelectionOp, 0), (JoinOp, 0), (JoinOp, 1)\n ]\n bfs_truth_node_seq = [\n SelectionOp, \n JoinOp, \n AliasOp, AliasOp, \n ProjectionOp, ProjectionOp, \n SelectionOp, SelectionOp, \n JoinOp, JoinOp, \n LoadOp, LoadOp, LoadOp, LoadOp\n ]\n bfs_truth_node_parent_seq = [\n (None, 0), \n (SelectionOp, 0), \n (JoinOp, 0), (JoinOp, 1), \n (AliasOp, 0), (AliasOp, 0), \n (ProjectionOp, 0), (ProjectionOp, 0), \n (SelectionOp, 0), (SelectionOp, 0), \n (JoinOp, 0), (JoinOp, 1), (JoinOp, 0), (JoinOp, 1)\n ]\n for node in traverse(ast, 'dfs'):\n assert isinstance(node, dfs_truth_node_seq[i])\n i += 1\n i = 0\n for node in traverse(ast, 'bfs'):\n assert isinstance(node, bfs_truth_node_seq[i])\n i += 1\n i = 0\n for node, parent, idx in traverseWithParent(ast, None, 0, 'dfs'):\n assert isinstance(node, dfs_truth_node_seq[i]) \n if i == 0:\n assert parent is None\n else:\n assert isinstance(parent, dfs_truth_node_parent_seq[i][0]) and idx == dfs_truth_node_parent_seq[i][1]\n i += 1\n i = 0\n for node, parent, idx in traverseWithParent(ast, None, 0, 'bfs'):\n assert isinstance(node, bfs_truth_node_seq[i])\n if i == 0:\n assert parent is None\n else:\n assert isinstance(parent, bfs_truth_node_parent_seq[i][0]) and idx == bfs_truth_node_parent_seq[i][1]\n i += 1\n \ndef test_deepcopyAST():\n sql = \"\"\"\n select * \n from \n (select employee_id from employees, employees_2 where employees.employee_id = employees_2.employee_id) as table1, \n (select employee_id from employees, employees_2 where employees.employee_id = employees_2.employee_id) as table2\n where \n table1.employee_id = table2.employee_id\n \"\"\"\n ast = parse_statement(sql)\n copy_ast = deepCopyAST(ast)\n ast_node_seq = [node for node in traverse(ast, 'dfs')]\n copy_ast_node_seq = [node for node in traverse(copy_ast, 'dfs')]\n assert len(ast_node_seq) == len(copy_ast_node_seq)\n for i in range(len(ast_node_seq)):\n assert isinstance(copy_ast_node_seq[i], ast_node_seq[i].__class__)\n assert id(copy_ast_node_seq[i]) != id(ast_node_seq[i])\n\n","repo_name":"wyfunique/DBSim","sub_path":"dbsim/tests/test_ast.py","file_name":"test_ast.py","file_ext":"py","file_size_in_byte":5725,"program_lang":"python","lang":"en","doc_type":"code","stars":15,"dataset":"github-code","pt":"81"} +{"seq_id":"11180658916","text":"import logging\nimport pytz\nfrom time import sleep\nimport math\nimport os\nimport psutil\nfrom inorbit_edge.robot import COMMAND_CUSTOM_COMMAND\nfrom inorbit_edge.robot import COMMAND_MESSAGE\nfrom inorbit_edge.robot import COMMAND_NAV_GOAL\nfrom inorbit_edge.robot import RobotSession\nfrom inorbit_edge.video import OpenCVCamera\nfrom .mir_api import MirApiV2\nfrom .mission import MirInorbitMissionTracking\nfrom ..config.mir100_model import MiR100Config\n\n\n# Publish updates every 1s\nCONNECTOR_UPDATE_FREQ = 1\n\n# Available MiR states to select via actions\nMIR_STATE = {3: \"READY\", 4: \"PAUSE\", 11: \"MANUALCONTROL\"}\n\n\nclass Mir100Connector:\n \"\"\"MiR100 connector.\n\n This class handles by-directional interaction between a MiR100 robot and\n the InOrbit platform using mainly the InOrbit python EdgeSDK.\n\n Arguments:\n robot_id (str): The ID of the MiR100 robot.\n config (MiR100Config): The configuration object for the MiR100 connector.\n \"\"\"\n\n def __init__(self, robot_id: str, config: MiR100Config) -> None:\n \"\"\"Initialize the MiR100 connector.\"\"\"\n\n log_level = config.log_level.value\n self.logger = logging.getLogger(name=self.__class__.__name__)\n self.logger.setLevel(log_level)\n\n # Configure the connection to the robot\n self.mir_api = MirApiV2(\n mir_base_url=config.connector_config.mir_base_url,\n mir_username=config.connector_config.mir_username,\n mir_password=config.connector_config.mir_password,\n loglevel=log_level,\n )\n\n # Configure the timezone\n self.robot_tz_info = pytz.timezone(\"UTC\")\n try:\n self.robot_tz_info = pytz.timezone(config.location_tz)\n except pytz.exceptions.UnknownTimeZoneError as ex:\n self.logger.error(\n f\"Unknown timezone: '{config.location_tz}', defaulting to 'UTC'. {ex}\"\n )\n\n # The `api_key` is obtained from the `INORBIT_KEY` environment variable\n # to avoid repeting it on the YAML configuration file. Consider adding\n # a 'common' section to be used by all connectors.\n robot_session_params = {\n \"robot_id\": robot_id,\n \"robot_name\": robot_id,\n \"api_key\": os.environ[\"INORBIT_KEY\"],\n \"robot_key\": config.inorbit_robot_key,\n }\n if \"INORBIT_URL\" in os.environ:\n robot_session_params[\"endpoint\"] = os.environ[\"INORBIT_URL\"]\n # Configure InOrbit session object\n self.inorbit_sess = RobotSession(**robot_session_params)\n self.inorbit_sess.connect()\n\n # Set up environment variables\n user_scripts_config = config.user_scripts.model_dump()\n for env_var_name, env_var_value in user_scripts_config.get(\"env_vars\", {}).items():\n self.logger.info(f\"Setting environment variable '{env_var_name}'\")\n os.environ[env_var_name] = env_var_value\n\n # Get user_scripts path. The model will default the value to None, but the key always exists\n path = user_scripts_config.get(\"path\")\n if path is None:\n path = f\"~/.inorbit_connectors/connector-{robot_id}/local/\"\n user_scripts_path = os.path.expanduser(path)\n # Create the user_scripts folder if it doesn't exist\n if not os.path.exists(user_scripts_path):\n self.logger.info(f\"Creating user_scripts directory: {user_scripts_path}\")\n os.makedirs(user_scripts_path, exist_ok=True)\n\n # Delegate script execution to the RobotSession\n # NOTE: this only supports bash execution (exec_name_regex is set to files with '.sh'\n # extension).\n # More script types can be supported, but right now is only limited to bash scripts\n self.logger.info(f\"Registering user_scripts path: {user_scripts_path}\")\n self.inorbit_sess.register_commands_path(user_scripts_path, exec_name_regex=r\".*\\.sh\")\n\n self.inorbit_sess.register_command_callback(self.command_callback)\n\n # Set up camera feeds\n for idx, camera_config in enumerate(config.cameras):\n self.inorbit_sess.register_camera(str(idx), OpenCVCamera(**camera_config.model_dump()))\n\n # Set up InOrbit Mission Tracking\n self.mission_tracking = MirInorbitMissionTracking(\n mir_api=self.mir_api,\n inorbit_sess=self.inorbit_sess,\n robot_tz_info=self.robot_tz_info,\n loglevel=log_level,\n enable_io_mission_tracking=config.connector_config.enable_mission_tracking,\n )\n\n def command_callback(self, command_name, args, options):\n \"\"\"Callback method for command messages.\n\n The callback signature is `callback(command_name, args, options)`\n\n Arguments:\n command_name -- identifies the specific command to be executed\n args -- is an ordered list with each argument as an entry. Each\n element of the array can be a string or an object, depending on\n the definition of the action.\n options -- is a dictionary that includes:\n - `result_function` can be called to report command execution result.\n It has the following signature: `result_function(return_code)`.\n - `progress_function` can be used to report command output and has\n the following signature: `progress_function(output, error)`.\n - `metadata` is reserved for the future and will contains additional\n information about the received command request.\n \"\"\"\n if command_name == COMMAND_CUSTOM_COMMAND:\n self.logger.info(f\"Received '{command_name}'!. {args}\")\n script_name = args[0]\n script_args = args[1]\n # TODO (Elvio): Needs to be re designed.\n # 1. script_name is not standarized at all\n # 2. Consider implementing a callback for handling mission specific commands\n # 3. Needs an interface for supporting mission related actions\n if script_name == \"queue_mission\" and script_args[0] == \"--mission_id\":\n self.mission_tracking.mir_mission_tracking_enabled = (\n self.inorbit_sess.missions_module.executor.wait_until_idle(0)\n )\n self.mir_api.queue_mission(script_args[1])\n elif script_name == \"run_mission_now\" and script_args[0] == \"--mission_id\":\n self.mission_tracking.mir_mission_tracking_enabled = (\n self.inorbit_sess.missions_module.executor.wait_until_idle(0)\n )\n self.mir_api.abort_all_missions()\n self.mir_api.queue_mission(script_args[1])\n elif script_name == \"abort_missions\":\n self.inorbit_sess.missions_module.executor.cancel_mission(\"*\")\n self.mir_api.abort_all_missions()\n elif script_name == \"set_state\":\n if script_args[0] == \"--state_id\":\n state_id = script_args[1]\n if not state_id.isdigit() or int(state_id) not in MIR_STATE.keys():\n self.logger.error(f\"Invalid `state_id` ({state_id})\")\n options[\"result_function\"](\"1\")\n return\n state_id = int(state_id)\n self.logger.info(\n f\"Setting robot state to state {state_id}: {MIR_STATE[state_id]}\"\n )\n self.mir_api.set_state(state_id)\n if script_args[0] == \"--clear_error\":\n self.logger.info(\"Clearing error state\")\n self.mir_api.clear_error()\n elif script_name == \"set_waiting_for\" and script_args[0] == \"--text\":\n self.logger.info(f\"Setting 'waiting for' value to {script_args[1]}\")\n self.mission_tracking.waiting_for_text = script_args[1]\n else:\n # Other kind if custom commands may be handled by the edge-sdk (e.g. user_scripts)\n # and not by the connector code itself\n # Do not return any result and leave it to the edge-sdk to handle it\n return\n # Return '0' for success\n options[\"result_function\"](\"0\")\n elif command_name == COMMAND_NAV_GOAL:\n self.logger.info(f\"Received '{command_name}'!. {args}\")\n pose = args[0]\n self.mir_api.send_waypoint(pose)\n elif command_name == COMMAND_MESSAGE:\n msg = args[0]\n if msg == \"inorbit_pause\":\n self.mir_api.set_state(4)\n elif msg == \"inorbit_resume\":\n self.mir_api.set_state(3)\n\n else:\n self.logger.info(f\"Received '{command_name}'!. {args}\")\n\n def start(self):\n \"\"\"Run the main loop of the Connector\"\"\"\n\n self._should_run = True\n while self._should_run:\n sleep(CONNECTOR_UPDATE_FREQ)\n try:\n # TODO(Elvio): Move this logic to another class to make it easier to maintain and\n # scale in the future\n self.status = self.mir_api.get_status()\n # TODO(Elvio): Move this logic to another class to make it easier to maintain and\n # scale in the future\n self.metrics = self.mir_api.get_metrics()\n except Exception as ex:\n self.logger.error(f\"Failed to get robot API data: {ex}\")\n continue\n # publish pose\n pose_data = {\n \"x\": self.status[\"position\"][\"x\"],\n \"y\": self.status[\"position\"][\"y\"],\n \"yaw\": math.radians(self.status[\"position\"][\"orientation\"]),\n }\n self.logger.debug(f\"Publishing pose: {pose_data}\")\n self.inorbit_sess.publish_pose(**pose_data)\n\n # publish odometry\n odometry = {\n \"linear_speed\": self.status[\"velocity\"][\"linear\"],\n \"angular_speed\": math.radians(self.status[\"velocity\"][\"angular\"]),\n }\n self.logger.debug(f\"Publishing odometry: {odometry}\")\n self.inorbit_sess.publish_odometry(**odometry)\n if self.inorbit_sess.missions_module.executor.wait_until_idle(0):\n mode_text = self.status[\"mode_text\"]\n state_text = self.status[\"state_text\"]\n mission_text = self.status[\"mission_text\"]\n else:\n mode_text = \"Mission\"\n state_text = \"Executing\"\n mission_text = \"Mission\"\n # publish key values\n # TODO(Elvio): Move key values to a \"values.py\" and represent them with constants\n key_values = {\n \"battery percent\": self.status[\"battery_percentage\"],\n \"battery_time_remaining\": self.status[\"battery_time_remaining\"],\n \"uptime\": self.status[\"uptime\"],\n \"localization_score\": self.metrics.get(\"mir_robot_localization_score\"),\n \"robot_name\": self.status[\"robot_name\"],\n \"errors\": self.status[\"errors\"],\n \"distance_to_next_target\": self.status[\"distance_to_next_target\"],\n \"mission_text\": mission_text,\n \"state_text\": state_text,\n \"mode_text\": mode_text,\n \"robot_model\": self.status[\"robot_model\"],\n \"waiting_for\": self.mission_tracking.waiting_for_text,\n # NOTE: System stats come from the system where the connector is running,\n # likely a server and not the robot itself\n # TODO(b-Tomas): Report more system stats\n # TODO(b-Tomas): Include this in the edge-sdk\n \"cpu\": psutil.cpu_percent(), # System-wide load average since last call (0-100)\n \"memory_usage\": psutil.virtual_memory().percent, # Memory usage percentage (0-100)\n }\n self.logger.debug(f\"Publishing key values: {key_values}\")\n self.inorbit_sess.publish_key_values(key_values)\n\n # publish mission data\n try:\n self.mission_tracking.report_mission(self.status, self.metrics)\n except Exception:\n self.logger.exception(\"Error reporting mission\")\n\n def stop(self):\n \"\"\"Exit the Connector cleanly.\"\"\"\n self._should_run = False\n self.inorbit_sess.disconnect()\n","repo_name":"inorbit-ai/inorbit-robot-connectors","sub_path":"mir_connector/inorbit_mir_connector/src/connector.py","file_name":"connector.py","file_ext":"py","file_size_in_byte":12459,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"81"} +{"seq_id":"43515171762","text":"\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nimport torch\n\nimport json\n\ndef phone_num_count(phone_nums):\n '''\n Returns the count of phone numbers in the column. If it is missing return 0 count instead of np.nan\n\n Args:\n ----\n phone_nums(str) - phone number in the string form '+91 2232323423\\n+91 123233323' or np.nan\n\n returns:\n --------\n counts of phone number\n\n '''\n \n phones_n = 0\n # check for if not NaNs or missing\n if phone_nums == '0' or phone_nums == 0 or type(phone_nums) == float:\n return 0\n length = 0\n # checks for 8 continuos integers and increases the count by 1\n for i in range(len(phone_nums)):\n try:\n if int(phone_nums[i]):\n length += 1\n if length == 8:\n phones_n += 1\n except:\n length = 0\n #return count, 0 if np.nan else phone counts\n return phones_n\n\ndef lower_(x):\n '''\n function takes a string and replcaes the spaces and returns a lower case string\n\n Args:\n -----\n x(str) - String input \n\n returns:\n -------\n string with no spaces and lower case\n\n '''\n #Function returns by converting string to lower and removing the spaces\n if type(x) == str:\n return x.replace(\" \",\"\").lower()\n \ndef type_x(x,n):\n '''\n function separates the string by comma and returns first index if n = 1 or second index if n = 2\n \n Args:\n ----\n x(str)- comma separated string\n n - 1 or 2 to return the comma separated string at index 0 or 1\n \n returns\n ------\n returns string at n-1 index from list created by comma separation\n '''\n # function separates the string by comma and returns first index of n = 1 or second index if n = 2\n if type(x) == str:\n #x = x.replace(\" \",\"\")\n x = x.replace(\" \",\"\").lower()\n x = x.split(\",\")\n if len(x) >= n:\n return(x[n-1])\n else:\n return np.nan\n else:\n return np.nan\n\ndef str_to_float(cost):\n '''\n function returns the float value for cost of two \n \n Args:\n ----\n cost(str)- string form of cost '1,700'\n \n returns\n ------\n returns float value of cost else 500 i.e is the median of the cust_for_two if missing\n '''\n #returns string cost '1,700' as float 1700.0\n if type(cost) == str:\n cost = cost.replace(\",\",\"\").replace(\" \",\"\")\n return(float(cost))\n else:\n #if np.nan, return median of cost_for_two for the population is 500\n return 500\n\ndef process(rows,listed_rest_types,listed_rest_city_loc,unique_rest,unique_cuisines,phone_minmax,c_minmax):\n \n '''\n Function takes in dataframe containing NEW restaurant rows and performs all the preprocesing performed on the train and test data\n \n Args:\n ----\n rows(DataFrame) - data frame containing rows of NEW restaurant\n listed_rest_types(list) - list of 7 unique types of restaurant as mentioned by Zomato for quick search - to form the dummies\n listed_rest_city_loc(list) - List of 30 locations/zones to fir all the restaurants for quick searches - to form the dummies\n unique_rest(list) - unique 25 restaurant types as listed by the restaurant on zomato - to form the dummies\n unique_cuisines(list) - list of 107 unique cusines - to form the dummies\n phone_minmax(list) - list containing the min and max count of phones in the column phone\n c_minmax(list) - list containing the min and max count of cost for two\n \n returns:\n --------\n processed rows containing 307 columns and all the restaurants having rate as \"NEW\"\n \n '''\n \n rows.drop(columns=['url', 'address','name','rate','votes','menu_item','dish_liked','reviews_list'],inplace = True, errors ='ignore')\n \n #calculating number of phones given\n rows['phone'] = rows.apply(lambda x: (phone_num_count(x.phone) - phone_minmax[0])/(phone_minmax[1] - phone_minmax[0]), axis=1)\n rows['cost_for_two'] = rows.apply(lambda x: (str_to_float(x.cost_for_two) - c_minmax[0])/(c_minmax[1] - c_minmax[0]) , axis = 1)\n \n #dummies for online order\n # 2 dummy columns created here\n for noyes in ['no','yes']:\n column_name1 = 'online_order_'+ noyes\n #online_order_yes and online_order_no\n rows[column_name1] = rows.apply(lambda x: 1 if x.online_order.lower() == noyes else 0, axis=1)\n #print(rows.columns)\n \n #dummies for book tabler\n # 2 dummy columns created here\n for noyes in ['no','yes']:\n column_name1 = 'book_table_'+ noyes\n #book_table_yes and book_table_no dummy created\n rows[column_name1] = rows.apply(lambda x: 1 if x.book_table.lower() == noyes else 0, axis=1)\n #print(rows.columns)\n \n #creating dummies for restauant listed in 7 types\n #7 dummy columns created here\n rows['listed_in_type'] = rows.apply(lambda x: x.listed_in_type.replace(\" \",\"_\").lower(), axis = 1)\n for rest_listed in listed_rest_types:\n rest_listed = rest_listed.lower().replace(\" \",\"_\") \n column_name1 = 'listed_in_type_'+ rest_listed\n rows[column_name1] = rows.apply(lambda x: 1 if x.listed_in_type == rest_listed else 0, axis=1)\n \n #creating dummies for location listed in 30 types\n #30 dummy columns created here\n rows['listed_in_city'] = rows.apply(lambda x: x.listed_in_city.replace(\" \",\"_\").lower(), axis = 1)\n for rest_loc in listed_rest_city_loc:\n rest_loc = rest_loc.replace(\" \",\"_\").lower()\n column_name1 = 'listed_in_city_'+ rest_loc\n rows[column_name1] = rows.apply(lambda x: 1 if x.listed_in_city == rest_loc else 0, axis=1)\n \n # dropping location of the restaurant\n rows.drop(columns = ['location','listed_in_city','listed_in_type','online_order','book_table'],inplace = True, axis = 1) \n \n #spliting rest types in rest_type separated by comma and storing it in two columns\n rows['rest_type'] = rows.apply(lambda x: lower_(x.rest_type), axis=1)\n rows['rest_type1'] = rows.apply(lambda x: type_x(x.rest_type,1), axis=1)\n rows['rest_type2'] = rows.apply(lambda x: type_x(x.rest_type,2), axis=1)\n \n #creating dummies for rest_type1 and rest_type2 listed in 25 types each\n #50 dummy columns created here\n for rest in unique_rest:\n #rest = rest.lower\n #print(rest)\n column_name1 = 'rest_type1_'+ rest\n column_name2 = 'rest_type2_' + rest\n rows[column_name1] = rows.apply(lambda x: 1 if x.rest_type1 == rest else 0, axis=1)\n rows[column_name2] = rows.apply(lambda x: 1 if x.rest_type2 == rest else 0, axis=1)\n \n #dropping columns after creting dummies\n rows.drop(columns =['rest_type1','rest_type2','rest_type'],inplace = True) \n \n #spliting first two cuisines in cuisines_1 and cuisines_2 separated by comma\n rows['cuisines'] = rows.apply(lambda x: lower_(x.cuisines), axis=1)\n rows['cuisines_1'] = rows.apply(lambda x: type_x(x.cuisines,1), axis=1)\n rows['cuisines_2'] = rows.apply(lambda x: type_x(x.cuisines,2), axis=1)\n \n \n #creating dummies for cuisines_1 and cuisines_2 listed in 107 types each\n #214 dummy columns created here\n for cuisine in unique_cuisines:\n #cuisine = cuisine.lower()\n column_name1 = 'cuisines_1_'+ cuisine\n column_name2 = 'cuisines_2_' + cuisine\n rows[column_name1] = rows.apply(lambda x: 1 if x.cuisines_1 == cuisine else 0, axis=1)\n rows[column_name2] = rows.apply(lambda x: 1 if x.cuisines_2 == cuisine else 0, axis=1)\n \n #dropping columns after creating dumies\n rows.drop(columns =['cuisines_1','cuisines_2','cuisines'],inplace = True)\n \n return rows \n\ndef predict(model,X):\n '''\n Prints graph for top three predictions with probabilities\n \n args:\n ----\n model(NN) : Trained neural network\n X - processed row to be predicted\n '''\n \n \n #freeze the gradients of the model\n with torch.no_grad():\n #remove the dropouts\n model.eval()\n \n #predict\n prediction = model(X)\n ps = torch.exp(prediction)\n \n #get top 3 prediction\n top_p, top_class = ps.topk(3)\n top_p = top_p.cpu().numpy().tolist()[0]\n top_class = top_class.cpu().numpy().tolist()[0]\n \n #print(top_class)\n with open('rates.json', 'r') as f:\n class_to_bin = json.load(f)\n \n #convert the prediction class to bins in string\n list_str = [class_to_bin.get(str(int(x))) for x in top_class]\n \n #print(list_str,top_p)\n \n #plot the probabilties and predicted top bins \n plt.barh(list_str,top_p)\n plt.xlabel(\"probability\")\n plt.ylabel(\"Prediction class\")\n plt.title(\"Prediction and probabilities\")\n #print(\"The Bin Predicted by the model is\",list_str[0],\"The probability of predicting based on training data is:\",top_p[0])\n \n ","repo_name":"shreyasdhuliya/Restaurant-Rating-prediction-onZomato","sub_path":"predict.py","file_name":"predict.py","file_ext":"py","file_size_in_byte":8956,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"81"} +{"seq_id":"26401967507","text":"n = int(input())\nk = int(input())\nli = [[0 for _ in range(n)] for _ in range(n)]\nx = y = n // 2\ndx = [-1, 1, 0, 0] #상하좌우\ndy = [0, 0, -1, 1]\ncount = 1\ncircle = 0\nans = [0, 0]\n\nwhile x != 0 and y != 0:\n for i in range(1):\n\n circle += 1\n if circle != 1:\n count -= 1\n li[x][y] = count\n x += dx[0]\n y += dy[0]\n count += 1\n li[x][y] = count\n if k == count:\n ans[0] = x\n ans[1] = y\n count += 1\n for i in range(circle * 2 - 1):\n x += dx[3]\n y += dy[3]\n li[x][y] = count\n if k == count:\n ans[0] = x\n ans[1] = y\n count += 1\n for i in range(circle * 2):\n\n x += dx[1]\n y += dy[1]\n li[x][y] = count\n if k == count:\n ans[0] = x\n ans[1] = y\n count += 1\n for i in range(circle * 2):\n x += dx[2]\n y += dy[2]\n li[x][y] = count\n if k == count:\n ans[0] = x\n ans[1] = y\n count += 1\n for i in range(circle * 2):\n x += dx[0]\n y += dy[0]\n li[x][y] = count\n if k == count:\n ans[0] = x\n ans[1] = y\n count += 1\n\nfor i in range(n):\n for j in range(n):\n print(li[i][j], end=\" \")\n print()\nprint(ans[0] + 1, end=\" \")\nprint(ans[1] + 1)\n","repo_name":"glossyyoon/DailyCoding","sub_path":"1913.py","file_name":"1913.py","file_ext":"py","file_size_in_byte":1365,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"12613094678","text":"#-*-coding:utf-8-*-\nimport pandas as pd\nfrom mpl_toolkits.basemap import Basemap\nimport matplotlib.pyplot as plt\nfrom pandas import DataFrame,Series\nimport numpy as np\ndata=pd.read_csv('/home/jethro/文档/pydata-book-master/data/haiti/Haiti.csv')\n#print(data[['INCIDENT DATE','LATITUDE','LONGITUDE']][:10])\n#print(data['CATEGORY'][:6])\ndata.describe()\ndata=data[(data.LATITUDE>18)&(data.LATITUDE<20)&(data.LONGITUDE>-75)&(data.LONGITUDE<-70)&(data.CATEGORY.notnull())]\n#print(data)\ndef to_cat_list(catstr):\n stripped=(x.strip() for x in catstr.split(','))\n return [x for x in stripped if x ]\ndef get_all_categories(cat_series):\n cat_sets=(set(to_cat_list(x)) for x in cat_series)\n return sorted(set.union(*cat_sets))\ndef get_english(cat):\n code,names=cat.split('.')\n if '|' in names:\n names=names.split(' | ')[1]\n return code,names.strip()\n\nprint(get_english('2.Urgences logistiques | Vital Lines'))\nall_cats=get_all_categories(data.CATEGORY)\nenglish_mapping=dict(get_english(x) for x in all_cats)\nprint(english_mapping['2a'])\nprint(english_mapping['6c'])\ndef get_code(seq):\n return [x.split('.')[0] for x in seq if x ]\nall_codes=get_code(all_cats)\ncode_index=pd.Index(np.unique(all_codes))\ndummy_frame=DataFrame(np.zeros((len(data),len(code_index))),index=data.index,columns=code_index)\n#print(dummy_frame.ix[:,:6])\nfor row,cat in zip(data.index,data.CATEGORY):\n codes=get_code(to_cat_list(cat))\n dummy_frame.ix[row,codes]=1\ndata=data.join(dummy_frame.add_prefix('category_'))\nprint(data.ix[:,10:15])\ndef basic_haiti_map(ax=None,lllat=17.25,urlat=20.25,lllon=-75,urlon=-71):\n #创建极球面投影的Basemap实例\n m=Basemap(ax=ax,projection='stere',lon_0=(urlon+lllon)/2,lat_0=(urlat+lllat)/2,llcrnrlat=lllat,urcrnrlat=urlat,lllcrnrlon=lllon,urcrnrlon=urlon,resolution='f')\n #绘制海岸线,州界,国界以及地图边界\n m.drawcoastlines()\n m.drawstates()\n m.drawcountries()\n return m\nfig,axes=plt.subplots(nrows=2,ncols=2,figsize=(12,10))\nfig.subplots_adjust(hspace=0.05,wspace=0.05)\nto_plot=['2a','1','3c','7a']\nlllat=17.25;urlat=20.25;lllon=-75;urlon=-71\nfor code,ax in zip(to_plot,axes.flat):\n m=basic_haiti_map(ax,lllat=lllat,urlat=urlat,lllon=lllon,urlon=urlon)\ndata=pd.read_csv('/home/jethro/文档/pydata-book-master/data/haiti/Haiti.csv')\ncat_data=data[data['category_%s '% code ==1]]\n#计算地图的投影坐标\nx,y=m(cat_data.LONGITUDE,cat_data.LATITUDE)\nm.plot('x,y,k.',alpha=0.5)\nax.set_title('%s:%s ' %(code,english_mapping[code]))\n\n\n","repo_name":"JH95-ai/Python-for-data-analysis","sub_path":"matplotlibtext/huizhiditu.py","file_name":"huizhiditu.py","file_ext":"py","file_size_in_byte":2518,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"40919023178","text":"# import ModuleName\n# import module1[, module2[,... moduleN]\n\n# import specific attributes from a module\n# from ModuleName import name1[, name2[, ... nameN]]\n\n# to import the function fibonacci from the module fib\n# from fib import fibonacci\n\n# to import all names from a module\n# from ModuleName import *\n\n'''\nLocating Modules\n--------------------------------\nWhen you import a module, the Python interpreter searches for the module in the following sequences −\n * The current directory.\n * If the module isn't found, Python then searches each directory in the shell variable PYTHONPATH.\n * If all else fails, Python checks the default path. On UNIX, this default path is normally /usr/local/lib/python/.\n'''\n\n\n# Namespaces and Scoping\n'''\nA Python statement can access variables in a local namespace and in the global namespace. \nIf a local and a global variable have the same name, the local variable shadows the global variable.\n\nEach function has its own local namespace. Class methods follow the same scoping rule as ordinary functions.\n\nPython makes educated guesses on whether variables are local or global. It assumes that any variable assigned a \nvalue in a function is local.\n'''\n\n\nimport math\nMoney = 2000\n\n\ndef AddMoney():\n global Money\n Money = Money + 1\n\n\nprint(Money)\nAddMoney()\nprint(Money)\n\n# dir() built-in function returns a sorted list of strings containing the names defined by a module.\ncontent = dir(math)\nprint(content)\n\n# ----------------------------------------------\n\n# The globals() and locals() Functions\n\n'''\nThe globals() and locals() functions can be used to return the names in the global and local \nnamespaces depending on the location from where they are called.\n\nIf locals() is called from within a function, it will return all the names that can be accessed locally \nfrom that function.\n\nIf globals() is called from within a function, it will return all the names that can be accessed globally \nfrom that function.\n\nThe return type of both these functions is dictionary. Therefore, names can be extracted using the keys() function.\n'''\n\ntotal = 0 # This is global variable.\n\n\ndef sum(arg1, arg2):\n total = arg1 + arg2 # Here total is local variable.\n # so kann man eine globale Variable ändern, die den selben Namen mit einer lokalen Variable hat\n # globals()['total'] = arg1 + arg2\n print(\"Inside the function local total : \", total)\n return total\n\n\nsum(10, 20)\nprint(\"Outside the function global total : \", total)\n","repo_name":"serdarayalp/my-python-tp","sub_path":"modules.py","file_name":"modules.py","file_ext":"py","file_size_in_byte":2489,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"33741403775","text":"NUMBER_OF_DAYS = 256\nFILENAME = \"day6data\"\n\ndata = open(FILENAME, \"r\").read()\ndata = list(map(int, data.split(\",\")))\n\ndaysleft = [0 for i in range(9)]\n\nfor i in data:\n daysleft[i] += 1\n\nfor i in range(NUMBER_OF_DAYS):\n newdays = [0 for i in range(9)]\n for j in range(len(daysleft)-1, 0, -1):\n newdays[j-1] = daysleft[j]\n newdays[6] += daysleft[0]\n newdays[8] = daysleft[0]\n daysleft = newdays\nans = 0\nfor i in daysleft:\n ans += i\n\nprint(ans)\n","repo_name":"Alex-Ralph/aoc2021","sub_path":"Day6/day6-2.py","file_name":"day6-2.py","file_ext":"py","file_size_in_byte":470,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"26565194105","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nSpyder Editor\r\n\r\nEste é um arquivo de script temporário.\r\n\"\"\"\r\n\r\n\r\n\r\n\r\nfrom functools import reduce\r\n\r\nminha_lista = [2, 4, 5, 2]\r\n\r\nproduto_total = reduce(lambda x, y: x * y, minha_lista)\r\nprint(produto_total) # 80","repo_name":"hussyvel/python3","sub_path":"temp.py","file_name":"temp.py","file_ext":"py","file_size_in_byte":248,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"37812799471","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Dec 6 17:39:32 2020\n\n@author: mmezyk\n\"\"\"\n\nimport h5py\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport keras\nimport tensorflow as tf\nfrom scipy import fftpack\nfrom scipy.signal import hilbert\nfrom keras import models\nfrom PIL import Image\nimport io\n\ndef plot_gather(panel,amin=-1,amax=1,scale=True):\n if scale == False:\n plt.figure(figsize=(10,10))\n amin=np.amin(panel)/10000\n amax=np.amax(panel)/10000\n plt.imshow(panel,vmin=amin,vmax=amax)\n elif scale == True:\n plt.figure(figsize=(10,10))\n plt.imshow(rms_scale(panel),vmin=amin,vmax=amax)\n \ndef plot_images_for_activations(data,mode,dim1=1,dim_scalar=1):\n if mode == 0:\n fig, axs = plt.subplots(1,6,figsize=(15,15),sharex=True)\n axs[0].imshow(data[0],vmin=0,vmax=40,cmap='nipy_spectral')\n axs[0].set_ylabel('AFFT_10_20Hz')\n #axs[0].set_title(str(np.int(labels[ii])))\n axs[1].imshow(data[1],vmin=0,vmax=40,cmap='nipy_spectral')\n axs[1].set_ylabel('AFFT_20_30Hz')\n axs[2].imshow(data[2],vmin=0,vmax=40,cmap='nipy_spectral')\n axs[2].set_ylabel('AFFT_30_40Hz')\n axs[3].imshow(data[3],vmin=0,vmax=30,cmap='nipy_spectral')\n axs[3].set_ylabel('AMP_MAX')\n axs[4].imshow(data[4],vmin=0,vmax=1250,cmap='nipy_spectral')\n axs[4].set_ylabel('ENV_0_33')\n axs[5].imshow(data[5],vmin=0,vmax=1250,cmap='nipy_spectral')\n axs[5].set_ylabel('ENV_33_66')\n fig.tight_layout()\n elif mode == 1:\n fig, axs = plt.subplots(data.shape[0],dim1,figsize=(dim1*dim_scalar,6*dim_scalar),sharex=True,sharey=True)\n for i in np.arange(0,dim1):\n axs[0,i].imshow(data[0,:,:,i],aspect='auto')\n axs[1,i].imshow(data[1,:,:,i],aspect='auto')\n axs[2,i].imshow(data[2,:,:,i],aspect='auto')\n axs[3,i].imshow(data[3,:,:,i],aspect='auto')\n axs[4,i].imshow(data[4,:,:,i],aspect='auto')\n axs[5,i].imshow(data[5,:,:,i],aspect='auto')\n for j in np.arange(0,6):\n axs[j,i].set_xticks([])\n axs[j,i].set_yticks([])\n plt.subplots_adjust(wspace = 0, hspace = 0)\n \ndef generate_fmap(freqs,fsize,panel,fs=0.004,n=2):\n fmap=np.zeros((len(freqs)+1,panel.shape[1]))\n for i in np.arange(0,panel.shape[1]):\n amp=np.abs(fftpack.fft(panel[:,i]))\n amp=amp[0:amp.size//2]\n amp=20*np.log10(amp+1)\n #amp=minmax_scale(amp)\n freq = fftpack.fftfreq(panel.shape[0], fs)\n freq = freq[0:freq.size//2]\n if np.logical_or(np.sum(amp)==0,np.isinf(np.sum(amp))):\n fmap[:,i]=0\n else:\n for j in np.arange(0,len(freqs)):\n frange=np.where(np.logical_and(freq>=freqs[j],freq= 0:\n plus[i] += 1\n else:\n minus[i*(-1)] += 1\n\n# print(plus)\n# print(minus)\n#\n# print(cards)\n# print(check)\n\nrst = []\nfor i in check:\n if i >= 0:\n rst.append(plus[i])\n else:\n rst.append(minus[i*(-1)])\n\nprint(*rst)\n","repo_name":"choihyeonseok/algo","sub_path":"bj/10816.py","file_name":"10816.py","file_ext":"py","file_size_in_byte":549,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"70706614344","text":"# Example showing all Kraken markets that already\n# gained at least 5% over the current weekly candle.\n\n\nimport cryptowatch as cw\nfrom datetime import datetime, timedelta\n\n\n# Get all Kraken markets\nkraken = cw.markets.list(\"kraken\")\n\n# For each Kraken market...\nfor market in kraken.markets:\n\n # Forge current market ticker, like KRAKEN:BTCUSD\n ticker = \"{}:{}\".format(market.exchange, market.pair).upper()\n # Request weekly candles for that market\n candles = cw.markets.get(ticker, ohlc=True, periods=[\"1w\"])\n\n # Each candle is a list of [close_timestamp, open, high, low, close, volume, volume_quote]\n # Get close_timestamp, open and close from the most recent weekly candle\n close_ts, wkly_open, wkly_close = (\n candles.of_1w[-1][0],\n candles.of_1w[-1][1],\n candles.of_1w[-1][4],\n )\n\n # Compute market performance, skip if open was 0\n if wkly_open == 0:\n continue\n perf = (wkly_open - wkly_close) * 100 / wkly_open\n\n # If the market performance was 5% or more, print it\n if perf >= 5:\n open_ts = datetime.utcfromtimestamp(close_ts) - timedelta(days=7)\n print(\"{} gained {:.2f}% since {}\".format(ticker, perf, open_ts))\n","repo_name":"cryptowatch/cw-sdk-python","sub_path":"examples/get_all_kraken_markets_with_5percent_perf_on_weekly.py","file_name":"get_all_kraken_markets_with_5percent_perf_on_weekly.py","file_ext":"py","file_size_in_byte":1203,"program_lang":"python","lang":"en","doc_type":"code","stars":149,"dataset":"github-code","pt":"81"} +{"seq_id":"74363501384","text":"from flask import Flask, render_template, request, jsonify\nimport pymysql\nfrom pymysql.cursors import DictCursor\nfrom datetime import datetime, timedelta\nimport json\nimport logging\nimport machine_learning\nfrom datetime import datetime as dt\n\nimport configparser\n\nlogging.basicConfig(level=logging.DEBUG)\n\nconfig = configparser.ConfigParser()\n\nconfig.read('/home/ubuntu/git/SD_Group_4/config.ini')\n#config.read('/Users/eoin/Documents/GitHub/SD_Group_4/config.ini')\n\ngoogle_maps_key = config.get('api_keys', 'GOOGLE_MAPS_API_KEY')\ndb_host = config.get('Database', 'db_host')\ndb_user = config.get('Database', 'db_user')\ndb_password = config.get('Database', 'db_password')\ndb_database_static = config.get('Database', 'staticDatabase')\ndb_database_dynamic = config.get('Database', 'dynamicDatabase')\nconfig.read('config.ini')\n\n\napp = Flask(__name__)\n\n\n\ndef get_dynamic_data():\n mydb_dynamic = pymysql.connect(\n host=db_host,\n user=db_user,\n password=db_password,\n database=db_database_dynamic\n )\n\n mycursor = mydb_dynamic.cursor(DictCursor)\n mycursor.execute(\"\"\"\n SELECT *\n FROM Dynamic\n WHERE (ID, DateTime) IN (\n SELECT ID, MAX(DateTime)\n FROM Dynamic\n GROUP BY ID\n )\n \"\"\")\n\n\n\n dynamic_data = mycursor.fetchall()\n mycursor.close()\n mydb_dynamic.close()\n return dynamic_data\n\ndef getWeatherData():\n mydb_weather = pymysql.connect(\n host=db_host,\n user=db_user,\n password=db_password,\n database=\"openweatherapi\"\n )\n\n\n mycursor = mydb_weather.cursor(DictCursor)\n mycursor.execute(\"\"\"SELECT Main,Temp,WindSpeed\n FROM openweatherapi.Weather\n ORDER BY DateTime DESC LIMIT 1;\"\"\")\n\n weatherData = mycursor.fetchall()\n mycursor.close()\n mydb_weather.close()\n return weatherData\n\n@app.route('/')\ndef main_page():\n dynamic_data = get_dynamic_data()\n return render_template('index.html', dynamic_data=dynamic_data, google_maps_api_key=google_maps_key)\n\n\n@app.route(\"/weather_data\")\ndef weatherData():\n weatherData = getWeatherData()\n return jsonify(weatherData)\n\n\n\n\n# retrieves the bike station data from the DBikeStatic and DBikeDynamicV2 databases, merges the data into a list of dictionaries, and returns the data as a JSON response.\n@app.route(\"/bike_stations\")\ndef bike_stations():\n # Fetch the dynamic data\n dynamic_data = get_dynamic_data()\n\n\n # Fetch the static data\n mydb_static = pymysql.connect(\n host=db_host,\n user=db_user,\n password=db_password,\n database=db_database_static\n )\n\n mycursor = mydb_static.cursor(DictCursor)\n mycursor.execute(\"SELECT * FROM Stations\")\n\n static_data = mycursor.fetchall()\n mycursor.close()\n mydb_static.close()\n\n # Merge the static and dynamic data into a single list\n bike_data = []\n for static_station, dynamic_station in zip(static_data, dynamic_data):\n bike_data.append({\n \"number\": static_station[\"Number\"],\n \"name\": static_station[\"Name\"],\n \"latitude\": static_station[\"Latitude\"],\n \"longitude\": static_station[\"Longitude\"],\n \"capacity\": dynamic_station[\"Capacity\"],\n \"available_bikes\": dynamic_station[\"AvailableBike\"],\n \"status\": dynamic_station[\"Status\"],\n \"banking\": static_station[\"Banking\"]\n })\n\n # Return the data as JSON\n return jsonify(bike_data)\n\ndef getFutureData(dateOrdinal,stationData):\n bikes = False\n i = 0\n while i < len(stationData):\n if machine_learning.machine_learn(stationData[i]['Station'],dateOrdinal)[0] > 1:\n bikes = True\n \n if bikes == True:\n dataArray = [stationData[i]['Station'],machine_learning.machine_learn(stationData[i]['Station'],dateOrdinal)[0]]\n return(dataArray)\n i+=1\n\n\n@app.route('/my_endpoint', methods=['POST'])\ndef my_endpoint():\n data = request.get_json()\n date_string = data[0]['date']\n date = dt.strptime(date_string, '%Y-%m-%d').date()\n ordinalDate = date.toordinal()\n results = getFutureData(ordinalDate,data)\n \n return results\n\n\n# retrieves data for the specified bike station from the DBikeDynamicV2 database and returns the data as a JSON response.\n@app.route('/station_data/')\ndef station_data(station_id):\n # Connect to the dynamic database\n mydb = pymysql.connect(\n host=db_host,\n user=db_user,\n password=db_password,\n database=db_database_dynamic\n )\n\n mycursor = mydb.cursor(DictCursor)\n\n def get_hourly_availability_data(station_id, day_start, day_end):\n mycursor.execute(\"\"\"\n SELECT HOUR(DateTime) AS Hour, AVG(AvailableBike) AS AverageAvailableBike\n FROM Dynamic\n WHERE ID = %s AND DateTime >= %s AND DateTime <= %s\n GROUP BY HOUR(DateTime)\n ORDER BY Hour\n \"\"\", (station_id, day_start, day_end))\n\n data = mycursor.fetchall()\n\n labels = [f\"{x['Hour']:02d}:00\" for x in data]\n values = [x[\"AverageAvailableBike\"] for x in data]\n\n # trialling new time format. Commented out version shows times in 1,8,14,20 format instead of 14:00 for example. Can return to this point when we're dressing up the site.\n # labels = [x[\"Hour\"] for x in data]\n # values = [x[\"AverageAvailableBike\"] for x in data]\n\n return {\"labels\": labels, \"data\": values}\n\n now = datetime.now()\n today_start = now.replace(hour=0, minute=0, second=0, microsecond=0)\n today_end = now\n yesterday_start = today_start - timedelta(days=1)\n yesterday_end = today_start - timedelta(seconds=1)\n day_before_yesterday_start = yesterday_start - timedelta(days=1)\n day_before_yesterday_end = yesterday_start - timedelta(seconds=1)\n\n today_data = get_hourly_availability_data(station_id, today_start, today_end)\n yesterday_data = get_hourly_availability_data(station_id, yesterday_start, yesterday_end)\n day_before_yesterday_data = get_hourly_availability_data(station_id, day_before_yesterday_start, day_before_yesterday_end)\n\n mycursor.close()\n mydb.close()\n\n return jsonify({\n \"today\": today_data,\n \"yesterday\": yesterday_data,\n \"dayBeforeYesterday\": day_before_yesterday_data,\n })\n\n\n@app.route('/average_station_data/', methods=['GET'])\ndef average_station_data(station_number):\n # Connect to the dynamic database\n mydb = pymysql.connect(\n host=db_host,\n user=db_user,\n password=db_password,\n database=db_database_dynamic\n )\n\n cur = mydb.cursor(DictCursor)\n\n # Get the current day of the week (0 = Monday, 1 = Tuesday, etc.)\n current_day = datetime.today().weekday()\n\n query = '''\n SELECT HOUR(DateTime) AS hour, AVG(AvailableBike) as avg_available_bikes\n FROM Dynamic\n WHERE ID = %s AND WEEKDAY(DateTime) = %s\n GROUP BY hour\n ORDER BY hour\n '''\n\n cur.execute(query, (station_number, current_day))\n results = cur.fetchall()\n\n cur.close()\n mydb.close()\n\n # Convert the results to the format expected by the chart\n labels = []\n data = []\n for row in results:\n hour = row[\"hour\"]\n avg_available_bikes = row[\"avg_available_bikes\"]\n labels.append(f\"{int(hour)}:00\")\n data.append(avg_available_bikes)\n\n return jsonify({\"labels\": labels, \"data\": data})\n\n\n\nif __name__ == '__main__':\n app.run(debug=True)","repo_name":"D-Mallon/SD_Group_4","sub_path":"flask/Flask_DM/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":7479,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"81"} +{"seq_id":"39194270497","text":"import cv2\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom cvBaseOperation import cv_show\n\ndef erodeTest():\n img = cv2.imread(\"./images/dige.png\")\n print(img.shape)\n # cv_show(img)\n kernel = np.ones((5, 5), np.uint8)\n # 总共有两个参数: kernel 和 循环次数;\n # 腐蚀会使白色变小\n erosion = cv2.erode(img, kernel, iterations=1) # 白字变细了, 胡须没有了\n cv_show(erosion)\n\ndef erodeTest2():\n img = cv2.imread(\"./images/pie.png\")\n print(img.shape)\n # cv_show(img)\n kernel = np.ones((30, 30), np.uint8)\n erosion_1 = cv2.erode(img, kernel, iterations=1)\n erosion_2 = cv2.erode(img, kernel, iterations=2)\n erosion_3 = cv2.erode(img, kernel, iterations=3)\n res = np.hstack((erosion_1, erosion_2, erosion_3))\n cv_show(res)\n\ndef dilateTest():\n img = cv2.imread(\"./images/dige.png\")\n print(img.shape)\n # cv_show(img)\n kernel = np.ones((3, 3), np.uint8)\n erosion = cv2.erode(img, kernel, iterations=1)\n dige_dilate = cv2.dilate(erosion, kernel, iterations=1) # 白色被放大\n cv_show(dige_dilate)\n\ndef dilateTest2():\n img = cv2.imread(\"./images/pie.png\")\n print(img.shape)\n # cv_show(img)\n kernel = np.ones((30, 30), np.uint8)\n dilate_1 = cv2.dilate(img, kernel, iterations=1)\n dilate_2 = cv2.dilate(img, kernel, iterations=2)\n dilate_3 = cv2.dilate(img, kernel, iterations=3)\n res = np.hstack((dilate_1, dilate_2, dilate_3))\n cv_show(res)\n\ndef openMorphTest():\n # 开运算: 先腐蚀,再膨胀\n # 没有胡须\n img = cv2.imread(\"./images/dige.png\")\n kernel = np.ones((5, 5), np.uint8)\n\n opening = cv2.morphologyEx(img, cv2.MORPH_OPEN, kernel)\n\n cv_show(opening)\n\ndef closeMorphTest():\n # 闭运算: 先膨胀,再腐蚀\n # 膨胀后 胡须变大,再腐蚀,就会腐蚀失败\n img = cv2.imread(\"./images/dige.png\")\n\n kernel = np.ones((5, 5), np.uint8)\n\n closing = cv2.morphologyEx(img, cv2.MORPH_CLOSE, kernel)\n\n cv_show(closing)\n\ndef gradientTest():\n # 梯度 = 膨胀 - 腐蚀\n img = cv2.imread(\"./images/pie.png\")\n kernel = np.ones((7, 7), np.uint8)\n\n # 膨胀\n dilate = cv2.dilate(img, kernel, iterations=1)\n # 腐蚀\n erosion = cv2.erode(img, kernel, iterations=1)\n\n res = np.hstack((dilate, erosion))\n\n gradient = cv2.subtract(dilate, erosion)\n cv_show(gradient)\n\ndef gradientTest2():\n img = cv2.imread(\"./images/pie.png\")\n kernel = np.ones((7, 7), np.uint8)\n # 计算梯度\n gradient = cv2.morphologyEx(img, cv2.MORPH_GRADIENT, kernel)\n\n cv_show(gradientTest())\n\ndef topHatTest():\n # 顶帽 = 原始输入 - 开运算结果\n # 只有细节信息\n img = cv2.imread(\"./images/dige.png\")\n kernel = np.ones((7, 7), np.uint8)\n topHat = cv2.morphologyEx(img, cv2.MORPH_TOPHAT, kernel)\n cv_show(topHat)\n\ndef blackHatTest():\n # 黑帽 = 闭运算 - 原始输入\n # 原始的小轮廓\n img = cv2.imread(\"./images/dige.png\")\n kernel = np.ones((7, 7), np.uint8)\n blackHat = cv2.morphologyEx(img, cv2.MORPH_BLACKHAT, kernel)\n cv_show(blackHat)\n\n\nif __name__==\"__main__\":\n # erodeTest()\n # erodeTest2()\n # dilateTest()\n # dilateTest2()\n # openMorphTest()\n # closeMorphTest()\n # gradientTest()\n # gradientTest2()\n # topHatTest()\n blackHatTest()","repo_name":"yangshunxin/openCV_python","sub_path":"morphologyOperation.py","file_name":"morphologyOperation.py","file_ext":"py","file_size_in_byte":3330,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"81"} +{"seq_id":"13175662530","text":"\"\"\"\n Name : c11_04_show_z_genative.py\n Book : Python for Finance (2nd ed.)\n Publisher: Packt Publishing Ltd. \n Author : Yuxing Yan\n Date : 6/6/2017\n email : yany@canisius.edu\n paulyxy@hotmail.com\n\"\"\"\n\nfrom scipy.stats import norm\nconfidence_level=0.99\nz=norm.ppf(1-confidence_level)\nprint(z)\n","repo_name":"PacktPublishing/Python-for-Finance-Second-Edition","sub_path":"Chapter11/c11_04_show_z_negative.py","file_name":"c11_04_show_z_negative.py","file_ext":"py","file_size_in_byte":327,"program_lang":"python","lang":"en","doc_type":"code","stars":251,"dataset":"github-code","pt":"81"} +{"seq_id":"16733058324","text":"# ## Assignment Part-1\r\n# Q1. Why do we call Python as a general purpose and high-level programming language?\r\n# ANS: Code is understandable and we write in english\r\n\r\n# Q2. Why is Python called a dynamically typed language?\r\n# Strong typing means that variables do have a type and that the type matters when performing operations on a variable. Dynamic typing means that the type of the variable is determined only during runtime .\r\n\r\n# Q3. List some pros and cons of Python programming language?\r\n# Ans: large community--pros\r\n #slower than compiled language---cons\r\n \r\n# Q4. In what all domains can we use Python?\r\n# Ans: WEB , app Development and data domains\r\n\r\n# Q5. What are variable and how can we declare them?\r\n# ANS: Variables are reference to the data stored in a location , it is like an address\r\n\r\n# Q6. How can we take an input from the user in Python?\r\n\r\n# a=input()\r\n\r\n# Q7. What is the default datatype of the value that has been taken as an input using input() function?\r\n# ANS: str\r\n\r\n# Q8. What is type casting?\r\n# Ans: Changng the data type of variable or data\r\n\r\n# Q9. Can we take more than one input from the user using single input() function? If yes, how? If no, why?\r\n# ans: Yes \r\n# names= input().split(\" \")\r\n\r\n# Q10. What are keywords?\r\n# Keywords are some predefined and reserved words in python that have special meanings \r\n\r\n# Q11. Can we use keywords as a variable? Support your answer with reason.\r\n# No , \r\n\r\n# Q12. What is indentation? What's the use of indentaion in Python?\r\n# Ans: Indentation refers to the spaces at the beginning of a code line\r\n\r\n# Q13. How can we throw some output in Python?\r\n# Ans: with print function\r\n\r\n# Q14. What are operators in Python?\r\n# Ans: they are used to perform specific operations like addition,subtraction, etc.\r\n\r\n# Q15. What is difference between / and // operators?\r\n# ans: / is gives float output and // gives int output\r\n\r\n# Q16. Write a code that gives following as an output.\r\n# ```\r\n# iNeuroniNeuroniNeuroniNeuron\r\n# ```\r\nprint(\"iNeuroniNeuroniNeuroniNeuron\")\r\n\r\n# Q17. Write a code to take a number as an input from the user and check if the number is odd or even.\r\nnumber = int(input())\r\nif number%2==0:\r\n print(\"even\")\r\nelse:\r\n print(\"odd\") \r\n\r\n# Q18. What are boolean operator?\r\n# AND, OR, NOT\r\n\r\n# Q19. What will the output of the following?\r\n# ```\r\n# 1 or 0-----> 1\r\n\r\n# 0 and 0----->0\r\n\r\n# True and False and True----->False\r\n\r\n# 1 or 0 or 0---->1\r\n# ```\r\n\r\n# Q20. What are conditional statements in Python?\r\n# if,else,elif\r\n\r\n# Q21. What is use of 'if', 'elif' and 'else' keywords?\r\n# used to write logic based on conditions\r\n\r\n# Q22. Write a code to take the age of person as an input and if age >= 18 display \"I can vote\". If age is < 18 display \"I can't vote\".\r\nage=int(input())\r\nif age>18:\r\n print(\"I can vote\")\r\nelse:\r\n print(\"I can't vote\") \r\n\r\n# Q23. Write a code that displays the sum of all the even numbers from the given list.\r\n# ```\r\n# numbers = [12, 75, 150, 180, 145, 525, 50]\r\n# ```\r\nnumbers = [12, 75, 150, 180, 145, 525, 50]\r\nsum=0\r\nfor i in range(len(numbers)):\r\n if numbers[i]%2==0:\r\n sum+=numbers[i]\r\nprint(sum)\r\n\r\n# Q24. Write a code to take 3 numbers as an input from the user and display the greatest no as output.\r\nx,y,z=input().split(\",\")\r\nif x>y and x>z:\r\n print(x)\r\nelif y>x and y>z:\r\n print(y)\r\nelse:\r\n print(z)\r\n \r\n\r\n# Q25. Write a program to display only those numbers from a list that satisfy the following conditions\r\n\r\n# - The number must be divisible by five\r\n\r\n# - If the number is greater than 150, then skip it and move to the next number\r\n\r\n# - If the number is greater than 500, then stop the loop\r\n# ```\r\n# numbers = [12, 75, 150, 180, 145, 525, 50]\r\n# ```\r\nnumbers = [12, 75, 150, 180, 145, 525, 50]\r\nfor i in range(len(numbers)):\r\n if numbers[i]%5==0:\r\n if numbers[i]<=150:\r\n if numbers[i]<=500:\r\n print(numbers[i])\r\n else:\r\n break ","repo_name":"sai448/Big_data_assignments","sub_path":"Assignment_1.py","file_name":"Assignment_1.py","file_ext":"py","file_size_in_byte":3983,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"26528034444","text":"from tkinter import *\r\nimport pyshorteners\r\n\r\nroot = Tk()\r\nroot.title(\"URL Shortener\")\r\nroot.geometry(\"600x500\")\r\nroot.config(bg=\"#5996F3\")\r\nroot.resizable(False,False)\r\n\r\ndef url():\r\n if url1.get() == '':\r\n print(\"Please Enter URL\")\r\n else:\r\n url_entry = url1.get()\r\n result = pyshorteners.Shortener().tinyurl.short(url_entry)\r\n urlE.insert(END, result)\r\n\r\nLabel(root,text=\"Generate Short URL\",font=(\"arial\",15,\"bold\"),fg=\"black\",bg=\"#5996F3\").pack(pady=10)\r\n\r\nframe = Frame(root)\r\nlabel = Label(frame,text=\"URL :\",font=(\"arial\",15,\"bold\"),fg=\"black\",bg=\"#5996F3\").pack(side=LEFT)\r\nurl1 = Entry(frame,width=35,font=(\"arial\",15,\"bold\"),fg=\"blue\")\r\nurl1.pack()\r\nframe.pack(pady=10)\r\n\r\nButton(root,text=\"Generate Link\",font=(\"arial\",15),fg=\"red\",bg=\"green\",command=url).pack(pady=10)\r\n\r\nframe2 = Frame(root)\r\nlabel1 = Label(frame2,text=\"Shorted URL : \",font=(\"arial\",15,\"bold\",),fg=\"black\",bg=\"#5996F3\").pack(side=LEFT)\r\nurlE = Entry(frame2,width=20,font=(\"arial\",15),fg=\"blue\")\r\nurlE.pack()\r\nframe2.pack(pady=10)\r\nroot.mainloop()\r\n\r\n","repo_name":"girishlearner/shortening_URL","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1066,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"21176217490","text":"def textoFormatado(txt):\n comp = len(txt) + 10\n txt = txt.upper()\n print('?' * comp)\n print(txt.center(comp).upper())\n print('?' * comp)\n\n\ndef texto(txt):\n print(txt*30)\n\n\ndef var(b):\n # global a assume a variavle global a dentro de def\n a = 8 # variavél local\n b += 4 # variavél local\n c = 2 # variavél local\n print(f'A dentro vale {a}')\n print(f'b += 4 dentro vale {b}')\n print(f'C dentro vale {c}')\n\n\ndef soma(a=0, b=0, c=0):\n s = a + b + c\n print(f'Dentro de def soma(a,b,c) s = {s}')\n return s # irá retornar o valor da soma para a chamada da função\n\n\ndef fatorial(num=1): # 1 se nehum valor for informado\n f = 1 #pega o c inicial e assume o valor\n for c in range(num, 1, -1):\n f *= c #inicio f = 1 e c = 5, f=5 c= 4, f=120 c= 3, ....\n return f\n\ndef par(num):\n if num % 2 == 0:\n num = True\n else:\n num = False\n return num\n\n\n\ntextoFormatado('Variavel global e local')\na = 9\nprint(f'Declarande a=9 no programa principal a = {a}')\nprint('Chamando def var(b) onde b será a variavel a')\nvar(a)\ntextoFormatado(' retorno de valores - return ')\nprint('Declarando que retornoDef = soma(4,7,2)')\nretornoDef = soma(4,7,2)\nprint(f'retornoDef = {retornoDef}')\nprint('Usando o print para o return temos > ',soma(3, 7, 8))\nr1 = soma(1,3,5)\nr2 = soma(2,4)\nr3 = (7)\nprint('''Passando para soma \\nr1 = soma(1,3,5)\nr2 = soma(2,4)\nr3 = (7)''')\nprint(f'Os valores de retorno serão\\nr1 = {r1}, r2 = {r2}, r3 = {r3}')\ntexto('-')\nf1 = fatorial(5)\nf2 = fatorial(6)\nf3 = fatorial()\nprint(f' f1 = {f1}, f2 = {f2},f3 = {f3}')\ntexto('-')\nx = int(input('Digite um numero: '))\nprint(par(x))\nprint('Logo na condição if True ou False')\nif par(x):\n print('É par')\nelse:\n print('É impar')\n\n","repo_name":"Alexandre1961/Python","sub_path":"curso_em_video/aula21b_funções.py","file_name":"aula21b_funções.py","file_ext":"py","file_size_in_byte":1768,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"22594170291","text":"\"\"\"Global configuration.\"\"\"\nimport os\nimport inspect\nimport shutil\n\nimport pytest\nimport matlab2cpp\nfrom matlab2cpp import collection\n\n\n@pytest.fixture(scope=\"session\")\ndef workspace_folder(tmpdir_factory):\n \"\"\"Create a temporary folder to perform tests from.\"\"\"\n return str(tmpdir_factory.mktemp(\"workspace\"))\n\n\n@pytest.fixture(scope=\"function\", autouse=True)\ndef workspace(workspace_folder, doctest_namespace):\n \"\"\"Fill temporary folder for each test.\"\"\"\n # move data to workspace:\n source = os.path.join(os.path.dirname(inspect.stack()[0][1]), \"test\", \"data\")\n if os.path.isdir(workspace_folder):\n shutil.rmtree(workspace_folder)\n shutil.copytree(source, workspace_folder)\n\n # add content to doctest namespace:\n doctest_namespace[\"workspace\"] = workspace_folder\n doctest_namespace[\"matlab2cpp\"] = matlab2cpp\n doctest_namespace[\"collection\"] = collection\n\n # change to workspace:\n curdir = os.path.abspath(os.path.curdir)\n os.chdir(workspace_folder)\n\n yield workspace_folder\n\n # clean up:\n os.chdir(curdir)\n shutil.rmtree(workspace_folder)\n","repo_name":"jonathf/matlab2cpp","sub_path":"conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":1103,"program_lang":"python","lang":"en","doc_type":"code","stars":178,"dataset":"github-code","pt":"81"} +{"seq_id":"24613394670","text":"from datetime import datetime\nfrom os import read, system\nfrom elasticsearch import Elasticsearch\nimport csv\nimport json\nimport elastic_test_resumes\nfrom gensim.models import Word2Vec\n\n\n#Not called\ndef load_csv(filename):\n with open('cv_accenture_1.csv', newline='') as csvfile:\n reader = csv.DictReader(csvfile)\n #reader = csv.reader(csvfile)\n for row in reader:\n print(row)\n print(str(row))\n return json.loads(str(row))\n\nes = Elasticsearch()\n\n#Update name for every new index created\n#Since this is test code, there currently is no index management here.\nindex_name= \"test-cv-v70\"\n\n\nes.indices.create(index = index_name, mappings=elastic_test_resumes.get_mapping())\n\nmodel = Word2Vec.load(\"saved_model\")\n\n\nindex=1\nfor resume in elastic_test_resumes.get_resumes():\n for skill in resume.get(\"skills\"):\n lower_case= skill.get(\"skill\").lower()\n if skill.get(\"skill\").lower() in model.wv.key_to_index :\n skill[\"skill_vector\"] = model.wv.get_vector(skill.get(\"skill\").lower())\n res = es.index(index=index_name, id=index, document=resume)\n print(\"++++ Adding Resume \" + str(index) + \" ++++\")\n print(res['result'])\n print(\"------------\\n\")\n index += 1\n\n\nprint(\"++++ Getting Resumes ++++\")\nprint(\"------------\")\nfor i in range(1, index):\n print(\"--- \" + str(i) + \" ---\")\n\n res = es.get(index=index_name, id=i)\n print(res['_source'])\n print(\"--- ---\\n\")\nprint(\"------------\")\nprint(\"++++\\n\")","repo_name":"PraPraPraPra/delivery","sub_path":"code/elastic_main.py","file_name":"elastic_main.py","file_ext":"py","file_size_in_byte":1495,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"32914371518","text":"import uno\nimport unohelper\n\nfrom com.sun.star.util import XCloseListener\nfrom com.sun.star.util import CloseVetoException\n\nfrom com.sun.star.logging.LogLevel import INFO\nfrom com.sun.star.logging.LogLevel import SEVERE\n\nfrom com.sun.star.ucb import IllegalIdentifierException\n\nfrom .oauth2 import g_oauth2\nfrom .oauth2 import getOAuth2UserName\n\nfrom .unotool import createService\nfrom .unotool import getResourceLocation\nfrom .unotool import getSimpleFile\nfrom .unotool import getUrlPresentation\nfrom .unotool import parseUrl\n\nfrom .configuration import g_cache\n\nfrom .dbconfig import g_folder\nfrom .dbconfig import g_protocol\nfrom .dbconfig import g_options\nfrom .dbconfig import g_shutdown\n\nfrom .dbtool import getDataSourceLocation\nfrom .dbtool import getDataSourceInfo\nfrom .dbtool import getDataSourceJavaInfo\nfrom .dbtool import registerDataSource\n\nfrom .ucp import ContentUser\n\nfrom .provider import Provider\n\nfrom .replicator import Replicator\n\nfrom .database import DataBase\n\nfrom .logger import getLogger\n\nfrom .configuration import g_identifier\nfrom .configuration import g_scheme\n\ng_message = 'datasource'\n\nimport traceback\n\n\nclass DataSource(unohelper.Base,\n XCloseListener):\n def __init__(self, ctx, logger, sync, lock):\n self._ctx = ctx\n self._default = ''\n self._users = {}\n self._logger = logger\n self.Error = None\n self._sync = sync\n self._lock = lock\n self._factory = createService(ctx, 'com.sun.star.uri.UriReferenceFactory')\n datasource, url, created = self._getDataSource(False)\n self.DataBase = DataBase(self._ctx, datasource)\n if created:\n self.Error = self.DataBase.createDataBase()\n if self.Error is None:\n self.DataBase.storeDataBase(url)\n self.DataBase.addCloseListener(self)\n folder, link = self.DataBase.getContentType()\n self._provider = Provider(ctx, folder, link, logger)\n self.Replicator = Replicator(ctx, datasource, self._provider, self._users, self._sync, self._lock)\n self._logger.logprb(INFO, 'DataSource', '__init__()', 301)\n\n # DataSource\n def getDefaultUser(self):\n return self._default\n\n # FIXME: Get called from ParameterizedProvider.queryContent()\n def queryContent(self, source, authority, identifier):\n user, path = self._getUser(source, identifier.getContentIdentifier(), authority)\n content = user.getContent(path, authority)\n return content\n\n # XCloseListener\n def queryClosing(self, source, ownership):\n if ownership:\n raise CloseVetoException('cant close', self)\n print(\"DataSource.queryClosing() ownership: %s\" % ownership)\n if self.Replicator.is_alive():\n self.Replicator.cancel()\n self.Replicator.join()\n self.DataBase.shutdownDataBase(self.Replicator.fullPull())\n self._logger.logprb(INFO, 'DataSource', 'queryClosing()', 331, self._provider.Scheme)\n def notifyClosing(self, source):\n pass\n\n # Private methods\n def _getUser(self, source, url, authority):\n default = False\n uri = self._factory.parse(url)\n if uri is None:\n msg = self._logger.resolveString(311, url)\n raise IllegalIdentifierException(msg, source)\n if authority:\n if uri.hasAuthority() and uri.getAuthority() != '':\n name = uri.getAuthority()\n else:\n msg = self._logger.resolveString(312, url)\n raise IllegalIdentifierException(msg, source)\n elif self._default:\n name = self._default\n else:\n name = self._getUserName(source, url)\n default = True\n # User never change... we can cache it...\n if name in self._users:\n user = self._users[name]\n else:\n user = ContentUser(self._ctx, self._logger, source, self.DataBase,\n self._provider, name, self._sync, self._lock)\n self._users[name] = user\n # FIXME: if the user has been instantiated then we can consider it as the default user\n if default:\n self._default = name\n return user, uri.getPath()\n\n def _getUserName(self, source, url):\n name = getOAuth2UserName(self._ctx, self, self._provider.Scheme)\n if not name:\n msg = self._logger.resolveString(321, url)\n raise IllegalIdentifierException(msg, source)\n return name\n\n def _getDataSource(self, register):\n print(\"DataSource._getDataSource() 1\")\n path = '%s/%s.odb' % (g_folder, g_scheme)\n location = getResourceLocation(self._ctx, g_identifier, path)\n url = getUrlPresentation(self._ctx, location)\n dbcontext = createService(self._ctx, 'com.sun.star.sdb.DatabaseContext')\n print(\"DataSource._getDataSource() 2\")\n if getSimpleFile(self._ctx).exists(url):\n if register and dbcontext.hasByName(g_scheme):\n print(\"DataSource._getDataSource() 3\")\n datasource = dbcontext.getByName(g_scheme)\n else:\n print(\"DataSource._getDataSource() 4\")\n datasource = dbcontext.getByName(url)\n created = False\n else:\n print(\"DataSource._getDataSource() 5\")\n datasource = dbcontext.createInstance()\n print(\"DataSource._getDataSource() 6\")\n datasource.URL = self._getDataSourceLocation(url, True)\n print(\"DataSource._getDataSource() 7\")\n datasource.Info = getDataSourceInfo()\n created = True\n if register and created:\n print(\"DataSource._getDataSource() 8\")\n registerDataSource(dbcontext, g_scheme, url)\n print(\"DataSource._getDataSource() 9\")\n return datasource, url, created\n\n def _getDataSourceLocation(self, url, shutdown):\n url = g_protocol + url + g_options\n if shutdown:\n url += g_shutdown\n return url\n\n","repo_name":"prrvchr/gDriveOOo","sub_path":"uno/lib/uno/ucb/datasource.py","file_name":"datasource.py","file_ext":"py","file_size_in_byte":6034,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"81"} +{"seq_id":"5732884367","text":"import torch\r\nimport torch.nn as nn\r\nfrom torch.autograd import Variable\r\nfrom include import IMG_h\r\nfrom include import CNN_h\r\nfrom include import UI_h\r\nimport torch.utils.data as Data\r\n\r\ntrain_path = 'D:/PycharmProjects/Num_distinguish/train_data/labels.txt'\r\ntest_path = 'D:/PycharmProjects/Num_distinguish/test_data'\r\n\r\ntrain_data = CNN_h.MyDataset(train_path)\r\ntrain_loader = Data.DataLoader(dataset=train_data, batch_size=1, shuffle=True, num_workers=0)\r\n\r\ncnn = CNN_h.CNN()\r\noptimizer = torch.optim.Adam(cnn.parameters(), lr=0.001)\r\nloss_func = nn.CrossEntropyLoss()\r\n\r\nfor i in range(10):\r\n for step, (x, y) in enumerate(train_loader):\r\n real_x = Variable(x)\r\n real_y = Variable(y)\r\n pre_y = cnn(real_x)\r\n loss = loss_func(pre_y, real_y)\r\n\r\n optimizer.zero_grad()\r\n loss.backward()\r\n optimizer.step()\r\n #print('loss:', float(loss.data))\r\n\r\n\r\nimg_dist = IMG_h.Carlicense_distinguish()\r\nimg_dist.carlicense_distinguish()\r\n\r\n\r\ntest_data = CNN_h.predicted_data(test_path)\r\n\r\ndecode_input = []\r\nfor i in range(len(test_data)):\r\n pre_test = cnn(test_data[i])\r\n decode_input.append(int(torch.max(pre_test,1)[1].data.numpy().squeeze()))\r\n\r\nprint(CNN_h.decode_output(decode_input))\r\nUI_h.window(CNN_h.decode_output(decode_input))\r\n","repo_name":"guyuehome/guyueclass","sub_path":"planning&perception/number_distinguish/src/MAIN.py","file_name":"MAIN.py","file_ext":"py","file_size_in_byte":1295,"program_lang":"python","lang":"en","doc_type":"code","stars":534,"dataset":"github-code","pt":"81"} +{"seq_id":"29506668588","text":"#!/usr/bin/env python\n\n## title = \"mylit\"\n## stylesheet = \"pygments_style.css\"\n\n#

mylit

\n# mylit is a simple tool for literate programming in Python. To convert a literate Python\n# program called somefile.py to HTML, run python -m mylit\n# somefile.py. The following documentation has been generated from the\n# mylit source.\n\n#! TODO: automatic links between identifiers, macros\n\n# We use itertools\n# for chaining sequences.\nimport itertools\n\n# To make sure we only parse lines beginning with # that actually\n# are comments (and not, e.g., inside strings), we double-check with the tokenize module.\nimport tokenize\n\n# We use Pygments for syntax highlighting.\nfrom pygments import highlight\nfrom pygments.lexers import PythonLexer\nfrom pygments.formatters import HtmlFormatter\n\n# This is the HTML template that will be filled with code:\ntemplate = \"\"\"\n\n \n %(title)s\n \n \n \n \n
\n %(body)s\n
\n \n\n\"\"\"\n\n# strip_left() removes whitespace from each line in\n# block, plus additional amount characters. This is\n# defined as a function because the list comprehension cannot be used directly\n# in format_program(), which uses an exec statement.\ndef strip_left(block, amount=0):\n return [x.lstrip()[amount:] for x in block]\n\n# find_comments() returns a list of (row, column) tuples of\n# locations where comments start. Row indices are one-based!\ndef find_comments(data):\n # This helper function splits data into newline-terminated\n # lines for generate_tokens.\n def readline(data):\n for line in data.splitlines():\n yield line + \"\\n\"\n yield \"\"\n\n # Here we generate tokens, extract comments end remember only the starting\n # index.\n return [start for ttype, tstring, start, end, line in tokenize.generate_tokens(readline(data).next) if ttype == tokenize.COMMENT]\n\n# lines() splits data into newline-terminated lines.\n# Again, this is defined outside of format_program() because of\n# the exec() call.\ndef lines(data):\n return (line + \"\\n\" for line in data.splitlines())\n\n# format_program iterates over the lines object and\n# returns HTML.\ndef format_program(data, title=\"\", stylesheet=\"http://pygments.org/media/pygments_style.css\"):\n # The HTML body is stored in body.\n body = []\n\n # Adjacent lines of the same type are aggregated in block and\n # formatted together.\n block = []\n # The type of the last block is stored in last_block_type.\n last_block_type = None\n\n # Here we store a list of beginning indices of comment tokens.\n comments = find_comments(data)\n\n # Now we iterate over the lines, formatting comments and code as\n # appropriate. None is appended to the list\n # of lines to terminate the last block. The line numbers start at one\n # to be consistent with the tokenizer.\n for lineno, line in enumerate(itertools.chain(lines(data), [None]), 1):\n # Comment lines starting with #! are ignored. This\n # includes the traditional \"shebang\" line as well as any code the user\n # may want to exclude from the output.\n if line is not None and line.strip().startswith(\"#!\") and (lineno, line.find(\"#\")) in comments:\n continue\n\n # A None line terminates the previous block.\n if line is None:\n block_type = None\n # Comment lines starting with ## are executed. This can be\n # used to set configuration variables, for example.\n elif line.strip().startswith(\"##\") and (lineno, line.find(\"#\")) in comments:\n block_type = \"exec\"\n # Any other comment line starting with # is a comment to\n # include in the HTML output.\n elif line.strip().startswith(\"#\") and (lineno, line.find(\"#\")) in comments:\n block_type = \"comment\"\n # Blank lines terminate comment blocks only.\n elif not line.strip() and last_block_type == \"comment\":\n block_type = None\n # All other lines are considered code.\n else:\n block_type = \"code\"\n\n # Adjacent lines of the same type are aggregated.\n if block_type == last_block_type:\n block.append(line)\n # As soon as the block type changes, the previous block is formatted.\n else:\n # Code is formatted by Pygments.\n if last_block_type == \"code\":\n body.append('
' + highlight(\"\".join(block), PythonLexer(), HtmlFormatter()) + '
')\n # Exec lines are executed and not copied to the output.\n elif last_block_type == \"exec\":\n exec(\"\".join(strip_left(block, len(block[0]) - len(block[0].lstrip()[2:].lstrip()))))\n # Comments are copied verbatim to the output.\n elif last_block_type == \"comment\":\n body.append('

' + \" \".join(strip_left(block, 1)) + '

')\n last_block_type = block_type\n block = [line]\n\n # Insert missing variables into the template and return.\n body = \"\\n\".join(body)\n return template % locals()\n\n# When the script is called from the command line, parse the arguments and run\n# format_program.\nif __name__ == \"__main__\":\n # argparse\n # is used for parsing the command line arguments.\n import argparse\n # os is used for\n # file name manipulation.\n import os\n # sys contains\n # the standard output stream.\n import sys\n\n # The parser is constructed here.\n parser = argparse.ArgumentParser(description=\"Convert a literate Python program to HTML.\")\n # infilename is a mandatory positional argument.\n parser.add_argument(\"infilename\", help=\"the input file\")\n # outfilename is an optional argument.\n parser.add_argument(\"outfilename\", nargs=\"?\", help=\"the output file, '-' for standard output\")\n # title and stylesheet can be specified if the\n # script does not do so itself.\n parser.add_argument(\"--title\", \"-t\", help=\"the document title\")\n parser.add_argument(\"--stylesheet\", \"-s\", help=\"the document title\")\n # Parse the arguments.\n args = parser.parse_args()\n # If outfilename is not specified, it is generated from infilename.\n if args.outfilename is None:\n args.outfilename = os.path.splitext(args.infilename)[0] + os.path.extsep + \"html\"\n\n # Pop any arguments that are not meant to end up in the format_program call.\n infilename = args.__dict__.pop(\"infilename\")\n outfilename = args.__dict__.pop(\"outfilename\")\n\n # Open the input file and format it.\n with open(infilename, \"r\") as f:\n result = format_program(f.read(), **args.__dict__)\n # Write the results. This happens after the input file is closed, so that\n # in-place formatting is possible.\n with sys.stdout if outfilename == \"-\" else open(outfilename, \"w\") as f:\n f.write(result)\n\n","repo_name":"swenger/mylit","sub_path":"mylit.py","file_name":"mylit.py","file_ext":"py","file_size_in_byte":7920,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"43684531475","text":"#!/usr/bin/env python\n\nimport csv\n\nfrom sys import argv\n\nfrom itertools import takewhile, imap\n\nfrom python_csv_brackets.utils import handle_args, it_consumes, smart_open\n\n\ndef main():\n handle_args()\n csv_kwargs = dict(delimiter=',', quotechar='\"')\n\n with open(argv[1], 'rt') as f0:\n r = csv.reader(f0, **csv_kwargs)\n rows = tuple(imap(\n lambda line: ''.join('{}\\0'.format(''.join(takewhile(lambda ch: ch != '(', col))).rstrip()\n for col in line), r))\n\n with smart_open(argv[2]) as f1:\n w = csv.writer(f1, quoting=csv.QUOTE_MINIMAL, **csv_kwargs)\n it_consumes(imap(lambda line: w.writerow(line.split('\\0')), rows))\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"SamuelMarks/python-csv-brackets","sub_path":"python_csv_brackets/__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":"81"} +{"seq_id":"33235915198","text":"from asgiref.sync import sync_to_async\nfrom djangochannelsrestframework.consumers import AsyncAPIConsumer\nfrom djangochannelsrestframework.observer import model_observer\n\nfrom . import serializer\nfrom .. import models\n\n\nclass ModelConsumerObserver(AsyncAPIConsumer):\n async def accept(self, **kwargs):\n await super().accept(**kwargs)\n await self.report_item_change.subscribe()\n await self.report_change.subscribe()\n\n @model_observer(models.ReportScannedItem, serializer_class=serializer.ReportScannedItemSerializer)\n async def report_item_change(self, message, action=None, **kwargs):\n # in this case since we subscribe int he `accept` method\n # we do not expect to have any `subscribing_request_ids` to loop over.\n if action == \"create\":\n instance = await sync_to_async(\n models.Instance.objects\n .select_related(\"object\")\n .values_list(\"inventory_number\", \"object__name\").get\n )(pk=message[\"instance\"])\n message.update({\n \"id\": str(message[\"report\"]),\n \"instanceId\": str(message[\"instance\"]),\n \"number\": instance[0],\n \"name\": instance[1],\n \"model\": \"report-item\"\n })\n del message[\"instance\"]\n del message[\"report\"]\n\n await self.reply(data=message, action=action)\n\n @model_observer(models.Report, serializer_class=serializer.ReportSerializer)\n async def report_change(self, message, action=None, **kwargs):\n if action == \"update\":\n message.update({\"model\": \"report\"})\n await self.reply(data=message, action=action)\n","repo_name":"Demetrous-fd/AGOI","sub_path":"backend/inventory/api/consumers.py","file_name":"consumers.py","file_ext":"py","file_size_in_byte":1707,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"70073893384","text":"def task8():\n my_list = [1, 0, 'Hi', 10]\n my_set = {3, 5, 'b'}\n my_set.update(my_list)\n print(*my_set)\n\n\ndef task10():\n my_str = 'Найдите сумму его неповторяющихся элементов'\n my_set = set(my_str)\n print(*my_set)\n\n\ndef task11():\n list1 = [1, 0, 1, 10, 5, 6, 7, 4, 4, 1, 6, 2, 5]\n temp_set = set(list1)\n print(list(temp_set))\n\n\ndef task12():\n A = {0, 1, 2, 6, 7, 8, 9}\n B = {1, 3, 6, 10, 21, 5}\n print(A.intersection(B))\n\n\nif __name__ == \"__main__\":\n print(\"\\nЗадание: 8\")\n task8()\n\n print(\"\\nЗадание: 10\")\n task10()\n\n print(\"\\nЗадание: 11\")\n task11()\n\n print(\"\\nЗадание: 12\")\n task12()\n","repo_name":"barbolin-semyon/ProgrammingTechnologiesWithPython","sub_path":"ProgrammingTechnologies-master/lab2/WorkWithSet.py","file_name":"WorkWithSet.py","file_ext":"py","file_size_in_byte":716,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"32352476162","text":"# В одномерном массиве найти сумму элементов, находящихся между минимальным и максимальным элементами.\n# Сами минимальный и максимальный элементы в сумму не включать.\n\nfrom random import shuffle\n\nrandom_array = list(range(10))\nshuffle(random_array)\nstart = 0\nstop = 0\nsum_between_min_max = 0\n\nfor key, value in enumerate(random_array):\n if value > random_array[start]:\n start = key\n if value < random_array[stop]:\n stop = key\n\nif start > stop:\n start, stop = stop, start\n\nfor i in range(start + 1, stop):\n sum_between_min_max += random_array[i]\n\nprint(f'В массиве {random_array}\\n'\n f'cумма элементов массива между максимальным и минимальным равна {sum_between_min_max}.')\n","repo_name":"grgblb/GB-Python-Algorithms","sub_path":"lesson_3/task_6.py","file_name":"task_6.py","file_ext":"py","file_size_in_byte":905,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"13600365200","text":"from django.conf.urls import url\nfrom django.urls import path\nfrom django.contrib.auth import views as auth_views\nfrom . import views\napp_name = \"blog\"\n\nurlpatterns = [\n path('', views.index, name = 'index'),\n path('search', views.search),\n path('//', views.post, name = 'post'),\n \n path('register/', views.register, name=\"register\"),\n path('login/',auth_views.LoginView.as_view(template_name=\"login.html\"), name=\"login\"),\n path('logout/',auth_views.LogoutView.as_view(next_page='/blog'),name='logout'),\n path('/', views.topicview, name = 'topic'),\n]","repo_name":"longphan1810/CVweb2","sub_path":"blog/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":598,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"11974937990","text":"import typing\nfrom itertools import zip_longest\n\ntutors = ['Иван', 'Анастасия', 'Петр', 'Сергей', 'Дмитрий', 'Борис', 'Елена']\nclasses = ['9А', '7В', '9Б', '9В', '8Б', '10А', '10Б', '9А']\n\n\ndef check_gen(tutors: list, classes: list) -> typing.Generator:\n \"\"\" Функция возвращает генератор, созданный на основе двух списков \"\"\"\n\n return ((tutor, klass) for tutor, klass in zip_longest(tutors, classes) if tutor)\n\n\ngenerator = check_gen(tutors, classes)\n# добавьте здесь доказательство, что создали именно генератор\nprint(type(generator))\n\nfor _ in range(len(tutors)):\n print(next(generator))\nnext(generator) # если раскомментировать, то должно падать в traceback по StopIteration\n","repo_name":"tkvitko/study_python_basics","sub_path":"Kvitko_Taras_dz_5/task_5_3.py","file_name":"task_5_3.py","file_ext":"py","file_size_in_byte":880,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"854819531","text":"import numpy as np\nfrom collections import Counter\nimport pandas as pd\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import accuracy_score, confusion_matrix, classification_report, precision_score, recall_score\n\nclass DecisionTreeClassifier:\n def __init__(self, max_depth=None):\n self.max_depth = max_depth\n self.tree = None\n\n def fit(self, X, y):\n self.tree = self._build_tree(X, y, depth=0)\n\n def _build_tree(self, X, y, depth):\n X = np.array(X)\n y = np.array(y)\n n_samples, n_features = X.shape\n unique_classes = np.unique(y)\n\n if depth == self.max_depth or len(unique_classes) == 1:\n return Counter(y).most_common(1)[0][0]\n\n best_gain = -1\n best_feature = None\n for feature in range(n_features):\n values = X[:, feature]\n unique_values = np.unique(values)\n for value in unique_values:\n left_indices = np.where(values <= value)\n right_indices = np.where(values > value)\n left_y = y[left_indices]\n right_y = y[right_indices]\n if len(left_y) > 0 and len(right_y) > 0:\n gain = self._information_gain(y, left_y, right_y)\n if gain > best_gain:\n best_gain = gain\n best_feature = (feature, value)\n\n if best_feature is None:\n return Counter(y).most_common(1)[0][0]\n\n feature, value = best_feature\n left_indices = np.where(X[:, feature] <= value)\n right_indices = np.where(X[:, feature] > value)\n left_subtree = self._build_tree(X[left_indices], y[left_indices], depth + 1)\n right_subtree = self._build_tree(X[right_indices], y[right_indices], depth + 1)\n\n return (feature, value, left_subtree, right_subtree)\n\n def _entropy(self, y):\n class_counts = Counter(y)\n probs = [count / len(y) for count in class_counts.values()]\n entropy = -np.sum([p * np.log2(p) for p in probs])\n return entropy\n\n def _information_gain(self, parent, left, right):\n parent_entropy = self._entropy(parent)\n left_weight = len(left) / len(parent)\n right_weight = len(right) / len(parent)\n weighted_child_entropy = (left_weight * self._entropy(left)) + (right_weight * self._entropy(right))\n information_gain = parent_entropy - weighted_child_entropy\n return information_gain\n\n def predict(self, X):\n predictions = [self._predict(sample) for sample in X]\n return np.array(predictions)\n\n def _predict(self, sample):\n node = self.tree\n while isinstance(node, tuple):\n feature, value, left_subtree, right_subtree = node\n if sample[feature] <= value:\n node = left_subtree\n else:\n node = right_subtree\n return node\n\ndata = pd.read_csv(\"amd.csv\", low_memory=False)\nlabel_model = LabelEncoder()\ndata = data.apply(label_model.fit_transform)\nX = data.drop(['class'], axis = 1)\ny = data['class']\nx_train, x_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=23)\n\ntree_classifier = DecisionTreeClassifier(max_depth=3)\ntree_classifier.fit(X, y)\n\nx_test = np.array(x_test)\nx_train = np.array(x_train)\ny_test = np.array(y_test)\ny_train = np.array(y_train)\nY_prediction = tree_classifier.predict(x_test)\nprint('\\nACCURACY SCORE = ', accuracy_score(y_test, Y_prediction), '\\n')\nprint('PRECISION SCORE = ', precision_score(y_test, Y_prediction, average = None), '\\n')\nprint('RECALL SCORE = ', recall_score(y_test, Y_prediction, average = None), '\\n')\nprint('CONFUSION MATRIX = \\n', confusion_matrix(y_test, Y_prediction), '\\n')\nprint(classification_report(y_test, Y_prediction, zero_division = 1))\n","repo_name":"midxdle/android-malware-detection","sub_path":"decision_tree.py","file_name":"decision_tree.py","file_ext":"py","file_size_in_byte":3876,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"81"} +{"seq_id":"73642417225","text":"import os\nimport cv2\nfrom PIL import Image\nimport numpy as np\n# \n\n# \ndata=[]\nlabels=[]\n# \n# ----------------\n# LABELS\n# Daisy 0\n# Dandelion 1\n# Roses 2\n# Sunflowers 3\n# Tulips 4\n# ----------------\n\n# Daisy 0\ndaisy = os.listdir(os.getcwd() + \"/CNN/data/daisy\")\nfor x in daisy:\n imag=cv2.imread(os.getcwd() + \"/CNN/data/daisy\" + x)\n img_from_ar = Image.fromarray(imag, 'RGB')\n resized_image = img_from_ar.resize((180, 180))\n data.append(np.array(resized_image))\n labels.append(0)\n\n# Dandeliion 1\ndandenion = os.listdir(os.getcwd() + \"/CNN/data/dandelion\")\nfor x in dandenion:\n imag=cv2.imread(os.getcwd() + \"/CNN/data/dandelion\" + x)\n img_from_ar = Image.fromarray(imag, 'RGB')\n resized_image = img_from_ar.resize((180, 180))\n data.append(np.array(resized_image))\n labels.append(1)\n\n# Roses 2\nroses = os.listdir(os.getcwd() + \"/CNN/data/roses\")\nfor x in roses:\n imag=cv2.imread(os.getcwd() + \"/CNN/data/roses\" + x)\n img_from_ar = Image.fromarray(imag, 'RGB')\n resized_image = img_from_ar.resize((180, 180))\n data.append(np.array(resized_image))\n labels.append(2)\n\n# Sunflowers 3\nsunflowers = os.listdir(os.getcwd() + \"/CNN/data/sunflowers\")\nfor x in sunflowers:\n imag=cv2.imread(os.getcwd() + \"/CNN/data/sunflowers\" + x)\n img_from_ar = Image.fromarray(imag, 'RGB')\n resized_image = img_from_ar.resize((180, 180))\n data.append(np.array(resized_image))\n labels.append(3)\n\n# Tulips 4\ntulips = os.listdir(os.getcwd() + \"/CNN/data/tulips\")\nfor x in tulips:\n imag=cv2.imread(os.getcwd() + \"/CNN/data/tulips\" + x)\n img_from_ar = Image.fromarray(imag, 'RGB')\n resized_image = img_from_ar.resize((180, 180))\n data.append(np.array(resized_image))\n labels.append(4)\n\n\nflowers=np.array(data)\nlabels=np.array(labels)\n# \nnp.save(\"flowers\",flowers)\nnp.save(\"labels\",labels)","repo_name":"Kerriea-star/Flowers-classifier","sub_path":"CNN/load.py","file_name":"load.py","file_ext":"py","file_size_in_byte":1831,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"81"} +{"seq_id":"23307609312","text":"\"\"\"\nhttps://projecteuler.net/problem=112\n\nWorking from left-to-right if no digit is exceeded by the digit to its left\nit is called an increasing number; for example, 134468.\n\nSimilarly if no digit is exceeded by the digit to its right it is called\na decreasing number; for example, 66420.\n\nWe shall call a positive integer that is neither increasing nor decreasing a \"bouncy\" number; for example, 155349.\n\nClearly there cannot be any bouncy numbers below one-hundred, but just over half of the numbers below one-thousand (525) are bouncy. In fact, the least number for which the proportion of bouncy numbers first reaches 50% is 538.\n\nSurprisingly, bouncy numbers become more and more common and by the time we reach 21780 the proportion of bouncy numbers is equal to 90%.\n\nFind the least number for which the proportion of bouncy numbers is exactly 99%.\n\"\"\"\nfrom typing import Optional\n\n\ndef is_bouncy_by_recursion(number: int) -> bool:\n def assess_direction(cur_num: str, next_num: str, direction: Optional[str]) -> str:\n cur_int = int(cur_num)\n next_int = int(next_num)\n\n cur_next_comparison = None\n\n if cur_int > next_int:\n cur_next_comparison = \"dec\"\n elif cur_int < next_int:\n cur_next_comparison = \"inc\"\n\n # no direction had been detected prior to this\n if cur_next_comparison is None and direction is not None:\n cur_next_comparison = direction\n\n return cur_next_comparison\n\n def record_bounce(\n cur_num: str, next_num: str, direction: Optional[str], remainders: [str] = None\n ) -> bool:\n cur_next_comparison = assess_direction(cur_num, next_num, direction)\n\n if direction != cur_next_comparison and direction is not None:\n return True # direction changed, so it's bouncy\n\n if len(remainders) == 0:\n return False # no more numbers\n\n return record_bounce(\n next_num, remainders.pop(), cur_next_comparison, remainders\n )\n\n num_str = list(number.__str__())\n num_str_len = len(num_str)\n\n if num_str_len in [1, 2]:\n return False\n\n return record_bounce(num_str.pop(), num_str.pop(), None, num_str)\n\n\ndef is_bouncy_by_list_comparison(number: int) -> bool:\n num_str = list(number.__str__())\n num_str_len = len(num_str)\n\n if num_str_len in [1, 2]:\n return False\n\n sorted_num_str = sorted(num_str)\n\n if sorted_num_str == num_str:\n return False # increasing\n\n sorted_num_str.reverse()\n if sorted_num_str == num_str:\n return False # decreasing\n\n return True\n\n\nis_bouncy = is_bouncy_by_list_comparison # is_number_bouncy_recursively\n\n\ndef find_number_with_bouncy_percentage(percent: int) -> int:\n test_number = 0\n numbers_tested = 0\n bouncy_count = 0\n\n while True:\n test_number += 1\n number_bounces = is_bouncy(test_number)\n numbers_tested += 1\n\n if number_bounces:\n bouncy_count += 1\n percent_bouncy_numbers = int((bouncy_count / numbers_tested) * 100)\n if percent_bouncy_numbers == percent:\n return test_number\n\n\nif __name__ == \"__main__\":\n percentage = 99\n number_with_percentage = find_number_with_bouncy_percentage(percentage)\n print(f\"{percentage}% of the numbers under {number_with_percentage} are bouncy\")\n","repo_name":"btgrant-76/python-euler","sub_path":"py_euler/one_hundred_twelve.py","file_name":"one_hundred_twelve.py","file_ext":"py","file_size_in_byte":3347,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"18900248924","text":"\"\"\"\nGiven inorder and postorder traversal of a tree, construct the binary tree.\n\nNote:\nYou may assume that duplicates do not exist in the tree.\n\nFor example, given\n\ninorder = [9,3,15,20,7]\npostorder = [9,15,7,20,3]\nReturn the following binary tree:\n\n 3\n / \\\n 9 20\n / \\\n 15 7\n\"\"\"\nfrom typing import List\n\nfrom btree import TreeNode\n\n\nclass ConstructBinaryTreefromInorderandPostorderTraversal:\n def buildTree(self, inorder: List[int], postorder: List[int]) -> TreeNode:\n valindex = {val:i for i, val in enumerate(inorder)}\n\n def helper(infrom: int, postfrom: int, length: int) -> TreeNode:\n if length == 0:\n return None\n rootval = postorder[postfrom+length-1]\n node = TreeNode(rootval)\n inorderindex = valindex[rootval]\n leftlen = inorderindex - infrom\n rightlen = length - 1 - leftlen\n\n node.left = helper(infrom, postfrom, leftlen)\n node.right = helper(infrom+leftlen+1, postfrom+leftlen, rightlen)\n return node\n\n def helper2(low:int, hight: int) -> TreeNode:\n if low > hight:\n return None\n rootval = postorder.pop();\n node = TreeNode(rootval)\n mid = valindex[rootval];\n node.right = helper2(mid+1, hight)\n node.left = helper2(low, mid-1)\n return node\n\n return helper2(0, len(postorder)-1)\n #return helper(0, 0, len(inorder))\n","repo_name":"yangmingxuan/pythonalgorithms","sub_path":"btree/ConstructBinaryTreefromInorderandPostorderTraversal.py","file_name":"ConstructBinaryTreefromInorderandPostorderTraversal.py","file_ext":"py","file_size_in_byte":1485,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"44952489956","text":"import os\nimport html\nimport discord\nimport mysql.connector\nimport datetime\nfrom dotenv.main import load_dotenv\nfrom discord.ext import commands\nfrom general_bot import bot_speaks\nfrom permissions import check_perms\n\nclass dates(commands.Cog):\n def __init__(self, bot):\n self.bot = bot\n\n @commands.command(aliases=['date-see'])\n async def _dates_see_command(self, ctx, arg1: str):\n if check_perms('basic', ctx):\n load_dotenv()\n mydb = mysql.connector.connect(\n host=os.getenv('DB_SERVERNAME'),\n user=os.getenv('DB_USERNAME'),\n password=os.getenv('DB_PASSWORD'),\n database=os.getenv('DB_NAME')\n )\n mycursor = mydb.cursor()\n mycursor.execute(f\"SELECT * FROM `tbl_brands` WHERE `name` = '{html.escape(arg1)}';\")\n myresult = mycursor.fetchall()\n id_value = myresult[0][0]\n name_value = myresult[0][1]\n gname_value = myresult[0][2]\n description_value = myresult[0][3]\n\n link = arg1.replace(' ', '%20')\n\n embed=discord.Embed(title=arg1.upper(), url=f'https://acg.groningenrp.xyz/products_page.php?brand={link}', color=0xff0000)\n embed.add_field(name='id', value=id_value, inline=False)\n embed.add_field(name='name', value=name_value, inline=False)\n \n if gname_value != None:\n embed.add_field(name='gname', value=gname_value, inline=False)\n\n embed.add_field(name='description', value=description_value, inline=False)\n embed.set_footer(text=self.bot.user.name)\n await ctx.send(embed=embed)\n\n\n @commands.command(aliases=['date-fix'])\n async def _dates_add_fix(self, ctx):\n if check_perms('dev', ctx):\n enabled = False\n if (enabled):\n load_dotenv()\n mydb = mysql.connector.connect(\n host=os.getenv('DB_SERVERNAME'),\n user=os.getenv('DB_USERNAME'),\n password=os.getenv('DB_PASSWORD'),\n database=os.getenv('DB_NAME')\n )\n\n mycursor = mydb.cursor()\n await ctx.send(\"Ik begin.\")\n start_date = datetime.date(2021, 1, 1)\n end_date = datetime.date(2021, 10, 7)\n delta = datetime.timedelta(days=1)\n\n while start_date <= end_date:\n qry = \"INSERT INTO `tbl_dates`(`id`, `date`) VALUES (null, %s);\"\n mycursor.execute(qry, (start_date,))\n start_date += delta\n\n mydb.commit()\n await ctx.send(\"Ik ben klaar.\")\n \ndef setup(bot):\n bot.add_cog(dates(bot))","repo_name":"lachiu/VerzekeringskantoorPy","sub_path":"tmp/dates.py","file_name":"dates.py","file_ext":"py","file_size_in_byte":2781,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"72152387784","text":"\"\"\"add field active on store model\n\nRevision ID: 362319c8973b\nRevises: 3e132b795b56\nCreate Date: 2022-07-12 14:46:00.966713\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '362319c8973b'\ndown_revision = '3e132b795b56'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('store', sa.Column('active', sa.Boolean(), nullable=True))\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_column('store', 'active')\n # ### end Alembic commands ###\n","repo_name":"dschmitz545/pyfoods","sub_path":"pyfoods/pyfoods/migrations/versions/362319c8973b_add_field_active_on_store_model.py","file_name":"362319c8973b_add_field_active_on_store_model.py","file_ext":"py","file_size_in_byte":668,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"21962133267","text":"import view\nimport export_data\nimport import_data\n\n\ndef button():\n mode = view.get_mode()\n if mode == 1:\n last_name = view.get_value('Введите Фамилию: ')\n first_name = view.get_value('Введите Имя: ')\n surname = view.get_value('Введите Отчество: ')\n phone_number = view.get_value('Введите номер телефона: ')\n export_data.save_data_to_file(export_data.init_user(last_name, first_name, surname, phone_number),export_data.file)\n button()\n elif mode == 2:\n list_contact = import_data.read_file(export_data.file)\n import_data.print_contacts(list_contact)\n button()\n elif mode == 3:\n list_contact = import_data.read_file(export_data.file)\n choise_record = export_data.choise_record(list_contact)\n export_data.delete_record(list_contact, choise_record)\n button()\n elif mode == 4:\n search_param, what = view.ask_search()\n list_contact = import_data.read_file(export_data.file)\n res = export_data.search_contact(list_contact, search_param, what)\n if len(res) == 0:\n button()\n else:\n import_data.print_contacts(res)\n button()\n elif mode == 5:\n list_contact = import_data.read_file(export_data.file)\n choise_record = export_data.choise_record(list_contact)\n search_param, what = view.ask_change_contact()\n mode_file = view.ask_where_save_file()\n name = input('Введите название файла')\n new_file = export_data.init_file(name)\n export_data.change_contact(list_contact, choise_record, search_param, what, mode_file, new_file)\n button()\n else:\n return print('Программа завершена')","repo_name":"Ilya-Kolotov/Homework_Python_Analitics","sub_path":"Seminar_8/controller.py","file_name":"controller.py","file_ext":"py","file_size_in_byte":1804,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"13252061136","text":"import simplekml\nimport nltk\nimport logging\nimport json\n\n#-----------------------------------------------------------------------------\n# RAW REPORT\n#-----------------------------------------------------------------------------\ndef create_raw_report(user, tweets, filename):\n if not filename.endswith('.json'):\n filename = filename + '.json'\n\n logging.info('Writing RAW report to {0}.'.format(filename))\n\n report = {'user': user, 'tweets': tweets}\n\n raw = open(filename, 'w')\n raw.write(json.dumps(report, indent=2))\n raw.close()\n\n\n#-----------------------------------------------------------------------------\n# KML REPORT\n#-----------------------------------------------------------------------------\ndef create_kml_report(tweets, filename):\n if not filename.endswith('.kml'):\n filename = filename + '.kml'\n\n logging.info('Writing KML report to {0}.'.format(filename))\n\n kml = simplekml.Kml()\n\n for tweet in tweets:\n if tweet['coordinates'] is not None:\n timestamp = simplekml.TimeStamp(when=tweet['created_at'])\n kml.newpoint(name=tweet['id_str'],\n description=tweet['text'],\n timestamp=timestamp,\n coords=[tuple(tweet['coordinates']['coordinates'])])\n\n kml.save(filename)\n\n\n#-----------------------------------------------------------------------------\n# MARKDOWN REPORT\n#-----------------------------------------------------------------------------\ndef __md_user(user):\n '''\n Print various attributes of the user.\n '''\n u = u''\n u += u'{0}\\n'.format(user['screen_name']) \n u += '-' * len(user['screen_name']) + '\\n'\n u += u'Name: {0}\\n'.format(user['name'])\n u += u'Description: {0}\\n'.format(user['description'])\n u += u'Location: {0}\\n'.format(user['location'])\n u += 'Time Zone: {0}\\n'.format(user['time_zone'])\n u += 'UTC Offset: {0}\\n'.format(user['utc_offset']/3600)\n u += 'Tweets: {0}\\n'.format(user['statuses_count'])\n u += 'Favorites: {0}\\n'.format(user['favourites_count'])\n u += 'Listed: {0}\\n'.format(user['listed_count'])\n u += 'Followers: {0}\\n'.format(user['followers_count'])\n u += 'Following: {0}\\n'.format(user['friends_count'])\n u += '\\n'\n\n return u.encode('utf-8')\n\n\ndef __md_distribution(title, items, top=20):\n '''\n Calculate the frequency distribution of the list of items. Convert the\n top most frequent items in the list to Markdown\n '''\n d = u''\n if len(items) != 0:\n d += '{0}\\n'.format(title)\n d += '-' * len(title) + '\\n'\n\n dist = nltk.FreqDist(items)\n\n for k in dist.keys()[:top]:\n if title == 'Hashtags':\n link = 'https://twitter.com/search?q=%23{0}'.format(k)\n d += u'* [#{0}]({1}) - {2}\\n'.format(k, link, dist[k])\n elif title == 'Mentions':\n link = 'https://twitter.com/{0}'.format(k)\n d += u'* [@{0}]({1}) - {2}\\n'.format(k, link, dist[k])\n elif title == 'Links':\n d += u'* [{0}]({0}) - {1}\\n'.format(k, dist[k])\n else:\n d += u'* {0} - {1}\\n'.format(k, dist[k])\n\n d += '\\n'\n\n return d.encode('utf-8')\n\n\ndef create_markdown_report(user, analysis, filename):\n if not filename.endswith('.md'):\n filename = filename + '.md'\n\n logging.info('Writing Markdown report to {0}.'.format(filename))\n \n md = open(filename, 'w')\n md.write('Twanalyze Report\\n')\n md.write('================\\n')\n md.write(__md_user(user))\n md.write(__md_distribution('Hashtags', analysis['hashtags']))\n md.write(__md_distribution('Mentions', analysis['mentions']))\n md.write(__md_distribution('Links', analysis['links']))\n md.write(__md_distribution('3-word Phrases', analysis['phrase3']))\n md.write(__md_distribution('4-word Phrases', analysis['phrase4']))\n md.write(__md_distribution('5-word Phrases', analysis['phrase5']))\n md.write(__md_distribution('Timestamps', analysis['times'], top=24))\n md.write(__md_distribution('Places', analysis['places']))\n md.close()\n\n#-----------------------------------------------------------------------------\n# HTML REPORT\n#-----------------------------------------------------------------------------\ndef __html_user(user):\n '''\n Print various attributes of the user in HTML.\n '''\n u = u''\n u += u'

{0}

\\n'.format(user['screen_name'])\n u += '
    \\n' \n u += u'
  • Name: {0}
  • \\n'.format(user['name'])\n u += u'
  • Description: {0}
  • \\n'.format(user['description'])\n u += u'
  • Location: {0}
  • \\n'.format(user['location'])\n u += '
  • Time Zone: {0}
  • \\n'.format(user['time_zone'])\n u += '
  • UTC Offset: {0}
  • \\n'.format(user['utc_offset']/3600)\n u += '
  • Tweets: {0}
  • \\n'.format(user['statuses_count'])\n u += '
  • Favorites: {0}
  • \\n'.format(user['favourites_count'])\n u += '
  • Listed: {0}
  • \\n'.format(user['listed_count'])\n u += '
  • Followers: {0}
  • \\n'.format(user['followers_count'])\n u += '
  • Following: {0}
  • \\n'.format(user['friends_count'])\n u += '
'\n\n return u.encode('utf-8')\n\n\ndef __html_distribution(title, items, top=20):\n '''\n Calculate the frequency distribution of the list of items. Print the 20\n most frequent items in the list.\n '''\n d = u''\n if len(items) != 0:\n d += '

{0}

\\n'.format(title)\n d += '
    \\n'\n\n dist = nltk.FreqDist(items)\n\n for k in dist.keys()[:top]:\n if title == 'Hashtags':\n link = 'https://twitter.com/search?q=%23{0}'.format(k)\n d += u'
  • '.format(link)\n d += u'#{0} - {1}
  • \\n'.format(k, dist[k])\n elif title == 'Mentions':\n link = 'https://twitter.com/{0}'.format(k)\n d += u'
  • '.format(link)\n d += u'@{0} - {1}
  • \\n'.format(k, dist[k])\n elif title == 'Links':\n d += u'
  • '.format(k)\n d += u'{0} - {1}
  • \\n'.format(k, dist[k])\n else:\n d += u'
  • {0} - {1}
  • \\n'.format(k, dist[k])\n\n d += '
\\n'\n\n return d.encode('utf-8')\n\n\ndef create_html_report(user, analysis, filename):\n if not filename.endswith('.html'):\n filename = filename + '.html'\n\n logging.info('Writing HTML report to {0}.'.format(filename))\n\n html = open(filename, 'w')\n html.write('\\n\\n\\n')\n html.write('\\n\\n\\n')\n html.write('

Twanalyze Report

\\n')\n html.write(__html_user(user))\n html.write(__html_distribution('Hashtags', analysis['hashtags']))\n html.write(__html_distribution('Mentions', analysis['mentions']))\n html.write(__html_distribution('Links', analysis['links']))\n html.write(__html_distribution('3-word Phrases', analysis['phrase3']))\n html.write(__html_distribution('4-word Phrases', analysis['phrase4']))\n html.write(__html_distribution('5-word Phrases', analysis['phrase5']))\n html.write(__html_distribution('Timestamps', analysis['times'], top=24))\n html.write(__html_distribution('Places', analysis['places']))\n html.write('\\n\\n')\n html.close()\n","repo_name":"averagesecurityguy/twanalyze","sub_path":"twanalyze/report.py","file_name":"report.py","file_ext":"py","file_size_in_byte":7563,"program_lang":"python","lang":"en","doc_type":"code","stars":35,"dataset":"github-code","pt":"81"} +{"seq_id":"14096780395","text":"from Queue import Queue\nimport random\nfrom printer import Printer\nfrom task import Task\n\n# 随机判断是否有作业产生\ndef newPrintTask():\n num = random.randint(0, 180)\n if num == 1:\n return True\n else:\n return False\n\n\ndef simulation(numSeconds, pages) -> int:\n labprinter = Printer(pages)\n printQueue = Queue()\n waitingTimes = []\n for currentSecond in range(numSeconds):\n if newPrintTask():\n task = Task(currentSecond)\n printQueue.enqueue(task)\n if (not labprinter.bush()) and (not printQueue.isEmpty()):\n nextTask = printQueue.dequeue()\n waitingTimes.append(nextTask.waitTime(currentSecond))\n labprinter.startNext(nextTask)\n\n labprinter.tick()\n\n avgWaitTime = sum(waitingTimes) / len(waitingTimes)\n return f'打印机完成了{len(waitingTimes)}个任务平均用时{round(avgWaitTime,2)}秒,还有{printQueue.size()}个任务在等待。'\n\n\ndef main():\n for i in range(10):\n print(simulation(3600, 5))\n\n\nif __name__ == '__main__':\n main()\n\n'''\n一个具体的实例配置如下:\n一个实验室,在任意的一个小时内,大约有10名学生在场,\n这一小时中,每人会发起2次左右的打印,每次1~20页\n打印机的性能是:\n以草稿模式打印的话,每分钟10页,\n以正常模式打印的话,打印质量好,但速度下降为每分钟5页。\n\n问题是:怎么设定打印机的模式,让大家都不会等太久的前提下尽量提高打印质量?\n这是一个典型的决策支持问题,但无法通过规则直接计算\n令我们要用一段程序来模拟这种打印任务场景,然后对程序运行结果进行分析,以支持对打印机模式设定的决策。\n\n'''\n","repo_name":"xz2046/Data-Structures-and-Algorithms","sub_path":"打印模拟/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1764,"program_lang":"python","lang":"zh","doc_type":"code","stars":1,"dataset":"github-code","pt":"81"} +{"seq_id":"14154031580","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.animation import FuncAnimation\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom reward import Axis\nfrom math import asin, acos, sin, cos, exp, pi, tan\nfrom random import random\n\nfig = plt.figure()\nax = plt.axes(projection='3d')\nline1, = ax.plot([],[],[], color = 'red')\nline2, = ax.plot([],[],[], color = 'red')\nline3, = ax.plot([],[],[], color = 'black')\nline4, = ax.plot([],[],[], color = 'black')\n\nclass Visualization():\n def __init__(self):\n theta = np.linspace(0, 3.14*4, 200)\n # r = np.linspace(0, 1, 200)\n r = 0.5\n self.x = r * np.cos(theta)\n self.y = r * np.sin(theta)\n self.z = np.linspace(0, 2, 200)\n self.a = [0]\n self.b = [0]\n self.c = [0]\n self.trajectory = [np.array([[0 , 0 , -0.5, 1],\n [0.5, -0.5, 0 , 0],\n [0 , 0 , 0 , 0]])]\n for i in range(1, 200):\n d = ((self.x[i] - self.x[i-1])**2+(self.y[i] - self.y[i-1])**2)**0.5\n theta = asin((self.y[i] - self.y[i-1])/d)\n if acos((self.x[i] - self.x[i-1])/d) > pi/2:\n theta = pi - theta\n theta -= pi/2\n self.a.append(theta)\n d = ((self.z[i] - self.z[i-1])**2+(self.y[i] - self.y[i-1])**2+(self.x[i] - self.x[i-1])**2)**0.5\n self.b.append(asin((self.z[i] - self.z[i-1])/d))\n self.c.append(self.c[-1]+0.1*random()-0.2)\n axis = Axis(self.a[-1], self.b[-1], self.c[-1])\n self.trajectory.append(axis.transform(np.array([[0 , 0 , -0.03, 0.06],\n [0.03, -0.03, 0 , 0],\n [0 , 0 , 0 , 0]]), reverse=True))\n self.trajectory = np.array(self.trajectory)\n # print(np.array(self.a[1:])-np.array(self.a[:-1]))\n # print(self.b)\n # for i in range(200):\n # speed = np.array([cos(self.a[i]), sin(self.a[i]), tan(self.b[i])])\n # # speed = self.trajectory[i,:,1] - self.trajectory[i,:,0]\n # test = self.trajectory[i,:,3] - self.trajectory[i,:,2]\n # speed = speed/(speed@speed)**0.5\n # test = test/(test@test)**0.5\n # print(test, speed, test@speed)\n \n def update(self, t):\n ax.set_xlim(-0.5,0.5)\n ax.set_ylim(-0.5,0.5)\n ax.set_zlim(0,2)\n line1.set_data_3d(self.trajectory[1:t,0,0]+self.x[1:t], self.trajectory[1:t,1,0]+self.y[1:t], self.trajectory[1:t,2,0]+self.z[1:t])\n line2.set_data_3d(self.trajectory[1:t,0,1]+self.x[1:t], self.trajectory[1:t,1,1]+self.y[1:t], self.trajectory[1:t,2,1]+self.z[1:t])\n line3.set_data_3d([self.trajectory[t,0,0]+self.x[t], self.trajectory[t,0,1]+self.x[t]], [self.trajectory[t,1,0]+self.y[t],self.trajectory[t,1,1]+self.y[t]], [self.trajectory[t,2,0]+self.z[t], self.trajectory[t,2,1]+self.z[t]])\n line4.set_data_3d([self.trajectory[t,0,2]+self.x[t], self.trajectory[t,0,3]+self.x[t]], [self.trajectory[t,1,2]+self.y[t],self.trajectory[t,1,3]+self.y[t]], [self.trajectory[t,2,2]+self.z[t], self.trajectory[t,2,3]+self.z[t]])\n return line1, line2, line3, line4\n\n# def getData(t):\n# theta = np.linspace(0, 3.14*4, 200)[:t]\n# r = np.linspace(0, 1, 200)[:t]\n# x = r * np.cos(theta)[:t]\n# y = r * np.sin(theta)[:t]\n# z = np.linspace(0, 2, 200)[:t]\n# return x, y, z\n\n# def update(t):\n# ax.set_xlim(-0.5,0.5)\n# ax.set_ylim(-1,1)\n# x,y,z = getData(t)\n# line.set_data_3d(x,y,z)\n# return line\n\nvisual = Visualization()\nani = FuncAnimation(fig, visual.update, frames = np.arange(199), interval = 50)\nani.save(\"move.gif\", writer = 'Pillow', fps = 10)\nplt.show()","repo_name":"hch211/TX_DRL","sub_path":"model_train/ppo/utils/visualization.py","file_name":"visualization.py","file_ext":"py","file_size_in_byte":3801,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"81"} +{"seq_id":"5877956061","text":"#!/usr/bin/env python\n\nfrom __future__ import print_function\n\nfrom circuit_htn.srv import PredictNext, PredictNextResponse\nimport copy\nfrom difflib import SequenceMatcher\nimport networkx as nx\nimport pickle\nimport rospkg\nimport rospy\nfrom circuit_htn_node import CircuitHTNNode\n\nclass PredictionNode:\n\n def __init__(self):\n\n # Instance of RosPack with the default file path\n path = rospkg.RosPack().get_path('circuit_htn')\n\n # Load the task model\n model_name = rospy.get_param('~model_name', 'htn')\n print('Loading', (model_name + '.pkl...'))\n self.model = pickle.load(open(path + '/models/' + model_name + '.pkl', 'rb'))\n\n print(self.model.text_output())\n print('Task model loaded.')\n\n print('Calculating all paths through the model with associated probabilities...')\n self.paths = self.create_paths(self.model)\n self.path_strings = []\n for path in self.paths:\n self.path_strings.append(self.path_to_string(path['path']))\n print('All paths calculated.')\n print(self.path_strings)\n\n # initialize the service and pass in inputs\n self.service = rospy.Service('predict_next_action', PredictNext, self.predict_next)\n\n def prediction_test(self):\n '''load a data file to test prediction offline'''\n path = rospkg.RosPack().get_path('circuit_htn')\n frames = []\n with open(path + '/data/parallel.txt') as f:\n frames = f.readlines()\n frames = [x.strip() for x in frames]\n #actions = self.frames_to_action_list(frames)\n\n for i in range(len(frames)):\n action_preds, probs = self.predict_next_action(frames[0:i+1])\n output = 'next action: '\n for j in range(len(action_preds)):\n output += action_preds[j] + ' (' + str('{0:3.1f}'.format(probs[j]*100) + ')')\n if j+1 < len(action_preds):\n output += ', '\n print(output)\n\n def frames_to_action_list(self, frames):\n ''' Filter a list of per-frame classifications to a list of actions (note: filtering behavior is hardcoded\n for the drill assembly task)\n\n :param frames: per-frame classification (list of strings)\n :return: list of actions\n '''\n actions = []\n prev_action = 'none'\n count = 0\n actions_seen = []\n for s in frames:\n if s == prev_action and count < 300:\n count += 1\n if count == 6 and s != 'none':\n if s in actions_seen:\n s += '2'\n else:\n actions_seen.append(s)\n s += '1'\n actions.append(s)\n else:\n count = 0\n prev_action = s\n return actions\n\n def path_to_string(self, path):\n ''' Change path (list of actions) to a string representation for string similarity functions\n :param path: a list of actions\n :return: list of actions in string form, where one character represents one action\n '''\n s = ''\n for a in path:\n s += self.action_to_char(a)\n return s\n\n def action_to_char(self, action):\n if action == 'grab_tools1':\n return 'a'\n elif action == 'attach_shell1':\n return 'b'\n elif action == 'screw1':\n return 'c'\n elif action == 'hold_for_robot1':\n return 'd'\n elif action == 'grab_tools2':\n return 'e'\n elif action == 'attach_shell2':\n return 'f'\n elif action == 'screw2':\n return 'g'\n elif action == 'hold_for_robot2':\n return 'h'\n\n def predict_next(self, req):\n actions, probs = self.predict_next_action(req.prev_actions)\n\n print('actions:', actions)\n print('probabilities:', probs)\n\n return PredictNextResponse([actions], [probs])\n\n def predict_next_action(self, action_history):\n path = self.frames_to_action_list(action_history)\n if len(path) == 0:\n action_pred = {}\n for i in range(len(self.paths)):\n next_action = self.paths[i]['path'][0]\n prob = self.paths[i]['prob']\n if action_pred.has_key(next_action):\n action_pred[next_action] += prob\n else:\n action_pred[next_action] = prob\n actions = sorted(action_pred, key=action_pred.get)\n actions.reverse()\n probs = action_pred.values()\n probs.sort()\n probs.reverse()\n return actions, probs\n\n # compute (Ratcliff-Obershelp) similarity between query sequence and every path\n path_string = self.path_to_string(path)\n action_pred = {}\n for i in range(len(self.paths)):\n compare_str = self.path_strings[i]\n full_path = self.paths[i]['path']\n if len(compare_str) > len(path_string):\n # compare_str = self.path_strings[i][:min(len(path_string)+1, len(compare_str))] # buffer of 1 in case there's an incorrect number of actions\n compare_str = self.path_strings[i][:len(path_string)] # assumes query sequence has correct number of actions\n\n # get next action in the matched path sequence (the action following the last action in the query path)\n next_i = self.path_strings[i].find(path_string[-1])\n if next_i == -1:\n continue\n next_i += 1\n if next_i >= len(full_path):\n next_action = 'end_task'\n else:\n next_action = full_path[next_i]\n\n # calculate similarity value [0,1] between paths, multiply by probability of path\n sm = SequenceMatcher(a=path_string, b=compare_str)\n prob = sm.ratio()*self.paths[i]['prob']\n\n # print('query:', path)\n # print('path:', self.paths[i]['path'])\n # print('similarity:', sm.ratio())\n\n # update action prediction probabilities\n if action_pred.has_key(next_action):\n action_pred[next_action] += prob\n else:\n action_pred[next_action] = prob\n\n # get action predictions sorted from highest to lowest probability\n actions = sorted(action_pred, key=action_pred.get)\n actions.reverse()\n probs = action_pred.values()\n probs.sort()\n probs.reverse()\n\n # normalize probabilities\n sum = 0\n for p in probs:\n sum += p\n for i in range(len(probs)):\n probs[i] /= float(sum)\n\n return actions, probs\n\n def find_root(self):\n nodes = list(self.model.nodes())\n n = nodes[0]\n while len(list(self.model.predecessors(n))) > 0:\n n = list(self.model.predecessors(n))[0]\n return n\n\n def create_paths(self, node, paths=[{'prob':1.0, 'path':[]}]):\n if node.node_type == CircuitHTNNode.PRIMITIVE:\n for p in paths:\n p['path'].append(node.action)\n return paths\n\n elif node.node_type == CircuitHTNNode.SEQUENCE:\n for child in node.children:\n paths = self.create_paths(child, paths)\n return paths\n\n elif node.node_type == CircuitHTNNode.CHOICE:\n in_paths = paths\n paths = []\n for i in range(len(node.children)):\n child_paths = copy.deepcopy(in_paths)\n for cp in child_paths:\n cp['prob'] = cp['prob']*node.probabilities[i]\n child_paths = self.create_paths(node.children[i], child_paths)\n paths.extend(child_paths)\n return paths\n\n return paths\n\n\nif __name__ == \"__main__\":\n\n rospy.init_node('prediction_node')\n classify = PredictionNode()\n print('Ready for action prediction.')\n\n # print()\n # print('Action filtering test:')\n # classify.prediction_test()\n\n rospy.spin()\n","repo_name":"GT-RAIL/circuit_htn","sub_path":"src/circuit_htn/prediction_node.py","file_name":"prediction_node.py","file_ext":"py","file_size_in_byte":8091,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"37755814514","text":"import random\r\n\r\ndef random_sex():\r\n random_number = random.randint(0,1)\r\n if(random_number==0):\r\n return \"man\"\r\n else:\r\n return \"woman\"\r\n\r\nclass human:\r\n def __init__(self):\r\n self.age = 1\r\n self.sex = random_sex()\r\n\r\npenny = []\r\n\r\nfor loop in range(20):\r\n obj = human()\r\n penny.append(obj)\r\n\r\nprint(obj)","repo_name":"LeVeloute/world-v1","sub_path":"human.py","file_name":"human.py","file_ext":"py","file_size_in_byte":351,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"1866039130","text":"class Solution():\n def mergeList(self,left, right):\n if len(left) == 0:#如果list只有一边有值,直接回传 \n return right\n if len(right) == 0: \n return left \n if left[0] <= right[0]:#左右两个list的第一个值比大小,若右边大,就将左边的放入,其余的值继续排序\n return [left[0]] + self.mergeList(left[1:], right)\n if left[0] >= right[0]: #与上一段相反\n return [right[0]] + self.mergeList(left, right[1:])\n def merge_sort(self,nums):\n if len(nums)<=1:#如果list只有一个值,直接回传 \n return nums\n mid = len(nums)//2#找出中间位置\n left = nums[0:mid]\n right = nums[mid:]#将list分成左右\n \n leftData = self.merge_sort(left)\n rightData = self.merge_sort(right)# 不断分割,直到List内剩下一个值\n \n return self.mergeList(leftData, rightData)#当所有list都剩一个数字,开始合并\n\n\n#参考资料\n#https://newaurora.pixnet.net/blog/post/224658923-%E5%90%88%E4%BD%B5%E6%8E%92%E5%BA%8F%E6%B3%95---%E4%BD%BF%E7%94%A8python\n","repo_name":"jeff880714/lesson","sub_path":"HW2/merge_sort_06170118.py","file_name":"merge_sort_06170118.py","file_ext":"py","file_size_in_byte":1174,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"70751834185","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport boto3\nimport json\nfrom kafka import KafkaProducer\nimport pandas as pd\n\n\ndef main():\n \"\"\"\n Opens historical trade data from amazon S3 and sends them into Kafka.\n \"\"\"\n flush_amount = 10000\n # communicate with master node of ec2 instance\n producer = KafkaProducer(bootstrap_servers=['localhost:9092'],\n value_serializer=lambda v: json.dumps(v).encode('utf-8'))\n s3 = boto3.client('s3')\n response = s3.get_object(Bucket=\"feb2019taq\", Key=\"0204.csv\")\n df = pd.read_csv(response['Body'], header=None, low_memory=False)\n # drop last 2 rows since it contains Nan for some fields\n df.drop(df.tail(2).index, inplace=True)\n df[0] = df[0].astype(dtype=int)\n df[2] = df[2].astype(dtype=int)\n df[3] = df[3].astype(dtype=float)\n for i in range(len(df.index)/flush_amount):\n for j in range(flush_amount):\n b = list(df.iloc[i*flush_amount+j])\n producer.send(topic='test', value=b)\n # flushing every 10 thousand rows\n producer.flush()\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"daanonymous12/RiskControl","sub_path":"kafka/producer.py","file_name":"producer.py","file_ext":"py","file_size_in_byte":1128,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"31795422806","text":"import copy\nimport math\nimport bisect\nimport itertools\n\nimport torch\nfrom torch import distributed as dist\nfrom torch.utils.data.sampler import BatchSampler\nfrom torch.utils.data.sampler import Sampler\n\ndef _quantize(x, bins):\n bins = copy.copy(bins)\n bins = sorted(bins)\n quantized = list(map(lambda y: bisect.bisect_right(bins, y), x))\n return quantized\n\n\n\ndef _compute_aspect_ratios(dataset):\n aspect_ratios = []\n for i in range(len(dataset)):\n img_info = dataset.get_image_meta(i)\n aspect_ratio = float(img_info[\"height\"]) / float(img_info[\"width\"])\n aspect_ratios.append(aspect_ratio)\n return aspect_ratios\n\n\ndef make_batch_data_sampler(\n dataset, sampler, aspect_grouping, images_per_batch):\n\n if aspect_grouping:\n if not isinstance(aspect_grouping, (list, tuple)):\n aspect_grouping = [aspect_grouping]\n aspect_ratios = _compute_aspect_ratios(dataset)\n group_ids = _quantize(aspect_ratios, aspect_grouping)\n batch_sampler = GroupedBatchSampler(\n sampler, group_ids, images_per_batch, drop_uneven=False\n )\n else:\n batch_sampler = torch.utils.data.sampler.BatchSampler(\n sampler, images_per_batch, drop_last=False\n )\n \n return batch_sampler\n \ndef get_sampler(dataset, shuffle, distributed):\n if distributed: \n return DistributedSampler(dataset, shuffle=shuffle)\n \n if shuffle:\n return torch.utils.data.sampler.RandomSampler(dataset)\n else:\n return torch.utils.data.sampler.SequentialSampler(dataset)\n \n \n\n# Reference from facebook\n# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.\n\n\nclass GroupedBatchSampler(BatchSampler):\n \"\"\"\n Wraps another sampler to yield a mini-batch of indices.\n It enforces that elements from the same group should appear in groups of batch_size.\n It also tries to provide mini-batches which follows an ordering which is\n as close as possible to the ordering from the original sampler.\n\n Arguments:\n sampler (Sampler): Base sampler.\n batch_size (int): Size of mini-batch.\n drop_uneven (bool): If ``True``, the sampler will drop the batches whose\n size is less than ``batch_size``\n\n \"\"\"\n\n def __init__(self, sampler, group_ids, batch_size, drop_uneven=False):\n if not isinstance(sampler, Sampler):\n raise ValueError(\n \"sampler should be an instance of \"\n \"torch.utils.data.Sampler, but got sampler={}\".format(sampler)\n )\n self.sampler = sampler\n self.group_ids = torch.as_tensor(group_ids)\n assert self.group_ids.dim() == 1\n self.batch_size = batch_size\n self.drop_uneven = drop_uneven\n\n self.groups = torch.unique(self.group_ids).sort(0)[0]\n\n self._can_reuse_batches = False\n\n def _prepare_batches(self):\n dataset_size = len(self.group_ids)\n # get the sampled indices from the sampler\n sampled_ids = torch.as_tensor(list(self.sampler))\n # potentially not all elements of the dataset were sampled\n # by the sampler (e.g., DistributedSampler).\n # construct a tensor which contains -1 if the element was\n # not sampled, and a non-negative number indicating the\n # order where the element was sampled.\n # for example. if sampled_ids = [3, 1] and dataset_size = 5,\n # the order is [-1, 1, -1, 0, -1]\n order = torch.full((dataset_size,), -1, dtype=torch.int64)\n order[sampled_ids] = torch.arange(len(sampled_ids))\n\n # get a mask with the elements that were sampled\n mask = order >= 0\n\n # find the elements that belong to each individual cluster\n clusters = [(self.group_ids == i) & mask for i in self.groups]\n # get relative order of the elements inside each cluster\n # that follows the order from the sampler\n relative_order = [order[cluster] for cluster in clusters]\n # with the relative order, find the absolute order in the\n # sampled space\n permutation_ids = [s[s.sort()[1]] for s in relative_order]\n # permute each cluster so that they follow the order from\n # the sampler\n permuted_clusters = [sampled_ids[idx] for idx in permutation_ids]\n\n # splits each cluster in batch_size, and merge as a list of tensors\n splits = [c.split(self.batch_size) for c in permuted_clusters]\n merged = tuple(itertools.chain.from_iterable(splits))\n\n # now each batch internally has the right order, but\n # they are grouped by clusters. Find the permutation between\n # different batches that brings them as close as possible to\n # the order that we have in the sampler. For that, we will consider the\n # ordering as coming from the first element of each batch, and sort\n # correspondingly\n first_element_of_batch = [t[0].item() for t in merged]\n # get and inverse mapping from sampled indices and the position where\n # they occur (as returned by the sampler)\n inv_sampled_ids_map = {v: k for k, v in enumerate(sampled_ids.tolist())}\n # from the first element in each batch, get a relative ordering\n first_index_of_batch = torch.as_tensor(\n [inv_sampled_ids_map[s] for s in first_element_of_batch]\n )\n\n # permute the batches so that they approximately follow the order\n # from the sampler\n permutation_order = first_index_of_batch.sort(0)[1].tolist()\n # finally, permute the batches\n batches = [merged[i].tolist() for i in permutation_order]\n\n if self.drop_uneven:\n kept = []\n for batch in batches:\n if len(batch) == self.batch_size:\n kept.append(batch)\n batches = kept\n return batches\n\n def __iter__(self):\n if self._can_reuse_batches:\n batches = self._batches\n self._can_reuse_batches = False\n else:\n batches = self._prepare_batches()\n self._batches = batches\n return iter(batches)\n\n def __len__(self):\n if not hasattr(self, \"_batches\"):\n self._batches = self._prepare_batches()\n self._can_reuse_batches = True\n return len(self._batches)\n\n\n\n# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.\n# Code is copy-pasted exactly as in torch.utils.data.distributed.\n# FIXME remove this once c10d fixes the bug it has\n\n\nclass DistributedSampler(Sampler):\n \"\"\"Sampler that restricts data loading to a subset of the dataset.\n It is especially useful in conjunction with\n :class:`torch.nn.parallel.DistributedDataParallel`. In such case, each\n process can pass a DistributedSampler instance as a DataLoader sampler,\n and load a subset of the original dataset that is exclusive to it.\n .. note::\n Dataset is assumed to be of constant size.\n Arguments:\n dataset: Dataset used for sampling.\n num_replicas (optional): Number of processes participating in\n distributed training.\n rank (optional): Rank of the current process within num_replicas.\n \"\"\"\n\n def __init__(self, dataset, num_replicas=None, rank=None, shuffle=True):\n if num_replicas is None:\n if not dist.is_available():\n raise RuntimeError(\"Requires distributed package to be available\")\n num_replicas = dist.get_world_size()\n if rank is None:\n if not dist.is_available():\n raise RuntimeError(\"Requires distributed package to be available\")\n rank = dist.get_rank()\n self.dataset = dataset\n self.num_replicas = num_replicas\n self.rank = rank\n self.epoch = 0\n self.num_samples = int(math.ceil(len(self.dataset) * 1.0 / self.num_replicas))\n self.total_size = self.num_samples * self.num_replicas\n self.shuffle = shuffle\n\n def __iter__(self):\n if self.shuffle:\n # deterministically shuffle based on epoch\n g = torch.Generator()\n g.manual_seed(self.epoch)\n indices = torch.randperm(len(self.dataset), generator=g).tolist()\n else:\n indices = torch.arange(len(self.dataset)).tolist()\n\n # add extra samples to make it evenly divisible\n indices += indices[: (self.total_size - len(indices))]\n assert len(indices) == self.total_size\n\n # subsample\n offset = self.num_samples * self.rank\n indices = indices[offset : offset + self.num_samples]\n assert len(indices) == self.num_samples\n\n return iter(indices)\n\n def __len__(self):\n return self.num_samples\n\n def set_epoch(self, epoch):\n self.epoch = epoch\n","repo_name":"ricky40403/Fcos_seg","sub_path":"Fcos_seg/utils/sampler_helper.py","file_name":"sampler_helper.py","file_ext":"py","file_size_in_byte":8811,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"15232076070","text":"from openerp.osv import fields, orm\n\n\nclass program_result(orm.Model):\n\n _name = 'program.result'\n _parent_name = 'parent_id'\n\n _columns = {\n 'name': fields.char(\n 'Name', required=True, select=True, translate=True),\n 'parent_id': fields.many2one(\n 'program.result', string='Parent', select=True),\n 'child_ids': fields.one2many(\n 'program.result', 'parent_id', string='Sub-results'),\n 'transverse_ids': fields.many2many(\n 'program.result', 'transverse_rel', 'from_id', 'to_id',\n string='Transverse'),\n 'code': fields.char('Code', size=32),\n 'result_level_id': fields.many2one(\n 'program.result.level', string='Level', select=True),\n 'date_from': fields.date('Start Date'),\n 'date_to': fields.date('End Date'),\n 'description': fields.text('Description', translate=True),\n 'target_audience': fields.text('Target Audience', translate=True),\n 'target_audience_type_ids': fields.many2many(\n 'program.result.target', string='Target Audience Types'\n ),\n }\n","repo_name":"bwrsandman/program","sub_path":"program/program_result.py","file_name":"program_result.py","file_ext":"py","file_size_in_byte":1122,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"81"} +{"seq_id":"16536222954","text":"from red_black_tree import Node\r\nfrom red_black_tree import RedBlackTree\r\nimport pygame\r\nimport math\r\nimport sys\r\n\r\n\r\nSCREENWIDTH = 1200\r\nSCREENLENGTH = 600\r\ndef drawBT(node, x=SCREENWIDTH//2, y=0, l=1):\r\n if node == None or node.getKey() == None:\r\n return\r\n if node.color == \"Black\":\r\n color = (0,0,0)\r\n if node.color == \"Red\":\r\n color = (255, 0, 0)\r\n if node.looking == True:\r\n fontColor = (255, 255, 0)\r\n else:\r\n fontColor = (255, 255, 255)\r\n screen.blit(font.render(str(node.getKey()), True, fontColor, color), (math.floor(x), y))\r\n screen.blit(font.render(str(node.getValue()), True, fontColor, color), (math.floor(x), y+20))\r\n drawBT(node.getLeftChild(),x-SCREENWIDTH/math.pow(2,l+1) , y+50, l+1)\r\n drawBT(node.getRightChild(),x+SCREENWIDTH/math.pow(2,l+1), y+50, l+1)\r\npygame.init()\r\nscreen = pygame.display.set_mode((SCREENWIDTH, SCREENLENGTH))\r\nfont = pygame.font.Font(None, 24)\r\nT = RedBlackTree()\r\nclock = pygame.time.Clock()\r\ncurrent = None\r\nwhile True:\r\n clock.tick(30)\r\n screen.fill((255,255,255))\r\n for i in pygame.event.get():\r\n if i.type == pygame.QUIT:\r\n sys.exit()\r\n if i.type == pygame.KEYDOWN:\r\n if i.key == pygame.K_ESCAPE:\r\n sys.exit()\r\n if i.key == pygame.K_i:\r\n print(\"Enter key(must be number): \")\r\n key = float(input())\r\n print(\"Enter value: \")\r\n value = input()\r\n T.insert(Node(key, value))\r\n if i.key == pygame.K_f:\r\n if current != None:\r\n current.looking = False\r\n print(\"Enter key(must be number): \")\r\n key = float(input())\r\n current = T.find(key)\r\n if current != None:\r\n current.looking = True\r\n if i.key == pygame.K_r:\r\n print(\"Enter key(must be number): \")\r\n T.remove(float(input()))\r\n if i.key == pygame.K_p:\r\n T.printInOrder()\r\n drawBT(T.root)\r\n pygame.display.flip()\r\n","repo_name":"kennym11o/RedBlackTree","sub_path":"draw.py","file_name":"draw.py","file_ext":"py","file_size_in_byte":2110,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"26153096776","text":"from .virtual_sensor import *\nimport pandas as pd\n\n\ndef serializer_for_kafka_producer(data):\n\n return dumps(data).encode('utf-8')\n\nclass Heart_Rate(Virtual_Sensor):\n\n def __init__(self, kafka_producer_ip_port, produce_to_topic, config_data):\n\n super(Heart_Rate, self).__init__(\n config_data['config_data'], \n serializer_for_kafka_producer, \n kafka_producer_ip_port, \n produce_to_topic)\n\n self.time_window = 2\n\n def get_data(self):\n \n data_set=pd.read_csv(self.dir_path + self.file_name)\n data_set.columns=['time_in_sec','HR']\n\n sec = 1.0\n for x in range(15):\n\n greater_than = data_set.time_in_sec >= sec\n less_than = data_set.time_in_sec <= sec + 2\n _range = greater_than == less_than\n\n\n data_wrt_time = np.array(data_set[_range].HR)\n\n for data_item in data_wrt_time:\n self.send_data({\n \"data\" : data_item\n })\n \n # print(data_wrt_time.mean(),'\\n\\n\\n')\n sec += self.time_window\n sleep(2)\n \n \n return False","repo_name":"Zahid-Iqbal-Marth/FIT---FrameWorkForIOTapplications","sub_path":"Application-Code/sensors/heart_rate_sensor.py","file_name":"heart_rate_sensor.py","file_ext":"py","file_size_in_byte":1187,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"36019965668","text":"#!/usr/bin/env python3\n# -*- coding: utf-8; -*-\n\nfrom __future__ import (\n absolute_import,\n division,\n print_function,\n unicode_literals,\n)\n\nimport argparse\nimport cgi\nimport hashlib\nfrom html.parser import HTMLParser\nimport json\nimport logging as _logging\nimport os\nimport os.path\nimport plistlib\nimport posixpath\nimport pwd\nimport re\nimport shutil\nimport subprocess\nimport sys\nimport tempfile\nimport urllib.error\nimport urllib.parse\nimport urllib.request\n\n\nlogger = _logging.getLogger(\"macfit\")\n\n\ndef is_url(string):\n return re.search(r\"(?i)^[a-z]+://\", string)\n\n\ndef create_file(path):\n fd = os.open(path, os.O_CREAT | os.O_EXCL | os.O_WRONLY)\n return os.fdopen(fd, \"wb\")\n\n\ndef get_url_path_base_name(url):\n return posixpath.basename(urllib.parse.urlparse(url).path)\n\n\n# Homebrew uses ditto (and mkbom and ugh) to copy apps. rsync from\n# MacPorts is the only utility tested by Backup Bouncer[1] that passes\n# all tests (ditto fails two; I was testing on macOS 10.13), but I\n# don't want to depend on MacPorts. macOS's built-in rsync fails more\n# tests than its built-in tar. tar and ditto both fail the same two\n# tests (one of which is file creation time BTW). tar is easier to\n# use, so that's what I'm using.\n#\n# [1]: https://github.com/n8gray/Backup-Bouncer\ndef copy_with_tar(src, dst_dir):\n src_dir, src_name = os.path.split(src.rstrip(\"/\"))\n assert src_name\n src_tar_cmd = [\n \"/usr/bin/tar\",\n \"-cf\",\n \"-\",\n \"-C\",\n src_dir or \".\",\n \"--\",\n src_name,\n ]\n logger.debug(\"Source tar command: %r\", src_tar_cmd)\n src_tar = subprocess.Popen(src_tar_cmd, stdout=subprocess.PIPE)\n if not os.path.isdir(dst_dir):\n os.makedirs(dst_dir)\n # \"-k\" to prevent tar from overwriting anything---that should\n # never happen.\n dst_tar_cmd = [\n \"/usr/bin/tar\",\n \"-xpk\",\n \"--preserve\",\n \"-f\",\n \"-\",\n \"-C\",\n dst_dir,\n ]\n dst_tar = subprocess.Popen(dst_tar_cmd, stdin=src_tar.stdout)\n dst_tar.wait()\n src_tar.wait()\n if dst_tar.returncode != 0 or src_tar.returncode != 0:\n raise Exception(\n \"tar failed (src=%r dst=%r)\"\n % (src_tar.returncode, dst_tar.returncode)\n )\n\n\ndef change_owner(path, uid, gid):\n logger.debug(\"Setting ownership of %r to %d:%d\", path, uid, gid)\n subprocess.check_call([\"chown\", \"-R\", \"%d:%d\" % (uid, gid), path])\n\n\ndef chmod_recursive(path, mode=\"u+rwX,og+rX,og-w\"):\n logger.debug(\"Calling chmod -R %r %r\", path, mode)\n subprocess.check_call([\"chmod\", \"-R\", mode, path])\n\n\ndef is_bundle(path):\n # This is just meant to be a \"good enough\" test for whether\n # something looks like a macOS app, preference pane, Mail.app\n # bundle, or Sketch plug-in.\n path = path.rstrip(\"/\")\n if re.search(\n r\"(?i)\\.(?:app|prefpane|mailbundle|sketchplugin)$\", path\n ) and os.path.isdir(path):\n contents_dir = os.path.join(path, \"Contents\")\n file_in_contents_dir = (\n \"Sketch\" if path.endswith(\"sketchplugin\") else \"Info.plist\"\n )\n return os.path.isdir(contents_dir) and os.path.exists(\n os.path.join(contents_dir, file_in_contents_dir)\n )\n return False\n\n\ndef open_url(url, user_agent=None):\n # I preferred urllib2 to urllib here because it raises a nice\n # error on e.g. HTTP 404.\n headers = {\"Accept\": \"*/*\"}\n if user_agent:\n headers[\"User-Agent\"] = user_agent\n logger.debug(\"Fetching URL %r\", url)\n request = urllib.request.Request(url, headers=headers)\n return urllib.request.urlopen(request)\n\n\nTYPE_DMG = \"dmg\"\nTYPE_PKG = \"pkg\"\nTYPE_BUNDLE = \"bundle\"\n\n\nclass Installer:\n def __init__(\n self,\n download_cache_dir=None,\n user_agent=None,\n agree_eulas=None,\n dir_handler=None,\n install_predicate=None,\n dst_dir=None,\n owner=None,\n check_dmg_signature=None,\n check_pkg_signature=None,\n check_bundle_signature=None,\n ):\n self.download_cache_dir = download_cache_dir\n self.user_agent = user_agent\n self.agree_eulas = agree_eulas\n self.dir_handler = dir_handler\n self.install_predicate = install_predicate or (\n lambda _installer, _path: True\n )\n if dst_dir is None:\n if os.getuid() == 0:\n dst_dir = DST_DIR_SYSTEM\n else:\n dst_dir = DST_DIR_USER\n self.dst_dir = dst_dir\n logger.debug(\"Destination directory is %r\", dst_dir)\n if owner:\n pwent = pwd.getpwnam(owner)\n self.owner_uid = pwent.pw_uid\n self.owner_gid = pwent.pw_gid\n else:\n self.owner_uid = None\n self.owner_gid = None\n self.check_dmg_signature = check_dmg_signature\n self.check_pkg_signature = check_pkg_signature\n self.check_bundle_signature = check_bundle_signature\n self._clean_ups = []\n self._dev_null = open(os.devnull, \"wb\")\n self._add_clean_up(self._dev_null.close)\n self._temp_dir = tempfile.mkdtemp()\n logger.debug(\"Temp directory is %r\", self._temp_dir)\n self._add_clean_up(shutil.rmtree, self._temp_dir, ignore_errors=True)\n\n def _add_clean_up(self, func, *args, **kwargs):\n self._clean_ups.append((func, args, kwargs))\n\n def clean_up(self, raise_exceptions=None):\n while self._clean_ups:\n try:\n func, args, kwargs = self._clean_ups.pop()\n func(*args, **kwargs)\n except Exception:\n if raise_exceptions:\n raise\n else:\n logger.exception(\n \"Ignoring exception from clean-up %r(*%r, **%r)\",\n func,\n args,\n kwargs,\n )\n\n def __enter__(self):\n return self\n\n def __exit__(self, _exc_type, _exc_value, _traceback):\n self.clean_up()\n\n @property\n def _should_set_owner(self):\n return self.owner_uid is not None\n\n def _dst_dir_for_bundle(self, extension):\n assert extension.startswith(\".\")\n dst_dir = self.dst_dir\n if dst_dir in (DST_DIR_SYSTEM, DST_DIR_USER):\n if extension == \".app\":\n dst_dir = \"/Applications\"\n elif extension == \".prefpane\":\n dst_dir = \"/Library/PreferencePanes\"\n elif extension == \".mailbundle\":\n dst_dir = \"/Library/Mail/Bundles\"\n elif extension == \".sketchplugin\":\n dst_dir = \"/Library/Application Support/com.bohemiancoding.sketch3/Plugins\"\n else:\n raise Exception(\n \"Unsupported bundle extension %r\" % (extension,)\n )\n if self.dst_dir == DST_DIR_USER:\n assert dst_dir.startswith(\"/\")\n dst_dir = os.path.expanduser(\"~%s\" % (dst_dir,))\n return dst_dir\n\n def install_from_url(self, url, download_name=None, check_hash=None):\n logger.debug(\"Installing from URL %r\", url)\n if self.download_cache_dir:\n cache_file_name = download_name or get_url_path_base_name(url)\n if cache_file_name:\n cache_path = os.path.join(\n self.download_cache_dir, cache_file_name\n )\n logger.debug(\"Looking for cache at %r\", cache_path)\n if os.path.exists(cache_path):\n logger.info(\"Using cached %r\", cache_path)\n return self.install_from_path(\n cache_path, check_hash=check_hash\n )\n logger.info(\"Downloading %r\", url)\n response = open_url(url, user_agent=self.user_agent)\n if self.download_cache_dir:\n download_dir = self.download_cache_dir\n download_name = cache_file_name\n else:\n download_dir = tempfile.mkdtemp(dir=self._temp_dir)\n if not download_name:\n # Code for reading Content-Disposition courtesy\n # https://stackoverflow.com/a/11783319.\n _, params = cgi.parse_header(\n response.headers.get(\"Content-Disposition\", \"\")\n )\n download_name = params.get(\"filename\")\n if not download_name:\n # If we followed a redirect, maybe the final URL has a better\n # base name than the original URL.\n download_name = get_url_path_base_name(response.geturl())\n if not download_name:\n download_name = get_url_path_base_name(url)\n if not download_name:\n raise Exception(\"Can't figure out a file name for %r\" % (url,))\n software_path = os.path.join(download_dir, download_name)\n logger.debug(\"Will download to %r\", software_path)\n if not os.path.isdir(download_dir):\n # XXX Error not setting owner/perms here? See\n # self._should_set_owner.\n os.makedirs(download_dir)\n with create_file(software_path) as download:\n shutil.copyfileobj(response, download)\n response.close()\n if download_dir == self.download_cache_dir and self._should_set_owner:\n logger.debug(\n \"Chowning cached download to %d:%d\",\n self.owner_uid,\n self.owner_gid,\n )\n os.chown(software_path, self.owner_uid, self.owner_gid)\n return self.install_from_path(software_path, check_hash=check_hash)\n\n def install_from_path(self, path, check_hash=None):\n logger.debug(\"Visiting %r\", path)\n if os.path.isfile(path):\n return self.install_from_file(path, check_hash=check_hash)\n if check_hash:\n raise Exception(\"Cannot check hash of non-file %r\" % (path,))\n if is_bundle(path):\n return self.install_bundle(path)\n if not os.path.isdir(path):\n return []\n if self.dir_handler:\n should_traverse, installed = self.dir_handler(self, path)\n if not isinstance(installed, list):\n installed = list(installed)\n if not should_traverse:\n return installed\n else:\n installed = []\n try:\n children = os.listdir(path)\n except os.error as ex:\n # OK!\n logger.warning(\n \"Ignoring exception trying to list %r: %s: %s\",\n path,\n ex.__class__.__name__,\n ex,\n )\n return []\n for child in children:\n child_path = os.path.join(path, child)\n if os.path.islink(child_path):\n # Ignore\n pass\n elif os.path.isfile(child_path):\n installed.extend(self.install_from_file(child_path))\n elif os.path.isdir(child_path):\n if is_bundle(child_path):\n installed.extend(self.install_bundle(child_path))\n else:\n installed.extend(self.install_from_path(child_path))\n return installed\n\n def install_from_file(self, path, check_hash=None):\n if check_hash:\n hash_type, expected_hash = check_hash.split(\":\", 1)\n hash_type = hash_type.lower()\n hash_obj = hashlib.new(hash_type)\n with open(path, \"rb\") as the_file:\n while True:\n # 16 KiB is good enough for shutil.copyfileobj, so\n # it's good enough for me.\n chunk = the_file.read(16384)\n if not chunk:\n break\n hash_obj.update(chunk)\n actual_hash = hash_obj.hexdigest()\n if actual_hash != expected_hash:\n raise Exception(\n (\n \"%s hash for %r is %r, does not match expected hash %r\"\n % (hash_type, path, actual_hash, expected_hash)\n )\n )\n logger.debug(\"Hash check on %r passed\", path)\n match = re.search(r\"(?i)\\.(dmg|pkg|zip|tar(?:\\.(?:z|gz|bz2?))?)$\", path)\n if match:\n # Extra split here to lob compression suffixes off tarballs.\n ext = match.group(1).split(\".\")[0].lower()\n method = getattr(self, \"install_from_%s\" % (ext,))\n return method(path)\n else:\n return []\n\n def _add_hdiutil_detach_clean_up(self, mount_point):\n self._add_clean_up(\n subprocess.check_call,\n [\"hdiutil\", \"detach\", mount_point],\n stdout=self._dev_null,\n )\n\n def _check_signature(self, file_path, file_type):\n if file_type == TYPE_DMG:\n assessment_type = \"open\"\n check_signature = self.check_dmg_signature\n elif file_type == TYPE_PKG:\n assessment_type = \"install\"\n check_signature = self.check_pkg_signature\n elif file_type == TYPE_BUNDLE:\n assessment_type = \"execute\"\n check_signature = self.check_bundle_signature\n else:\n raise Exception(\"Unknown file_type %r\" % (file_type,))\n if not check_signature:\n logger.debug(\"No signature check requested for %r\", file_path)\n return\n logger.debug(\"Checking signature for %r\", file_path)\n try:\n stdout = subprocess.check_output(\n [\n \"spctl\",\n \"-a\",\n \"-t\",\n assessment_type,\n # I think this is only necessary for testing DMG\n # files, but it seems harmless for the other\n # purposes as well.\n \"--context\",\n \"context:primary-signature\",\n \"--raw\",\n \"-vv\",\n file_path,\n ],\n stderr=self._dev_null,\n )\n except subprocess.CalledProcessError:\n raise Exception(\n \"Failed to verify signature on %r (spctl failed)\" % (file_path,)\n )\n result = plistlib.loads(stdout)\n if not result.get(\"assessment:verdict\"):\n raise Exception(\n \"spctl did not report a true verdict for %r\" % (file_path,)\n )\n if callable(check_signature):\n originator = result.get(\"assessment:originator\", \"\")\n logger.debug(\n \"Calling signature checker for originator: %r\", originator\n )\n check_signature(file_path, file_type, originator)\n logger.debug(\"Signature check passed\")\n\n def install_from_dmg(self, path):\n self._check_signature(path, TYPE_DMG)\n logger.info(\"Mounting DMG %r\", path)\n # \"IDME\" seems to be something that could happen automatically\n # when mounting a disk image. I don't think anyone uses it,\n # and it's been disabled by default since forever. Still, for\n # security reasons, and because Homebrew does it, I explicitly\n # disable it here.\n hdiutil = subprocess.Popen(\n [\n \"hdiutil\",\n \"attach\",\n \"-plist\",\n \"-readonly\",\n \"-noidme\",\n \"-nobrowse\",\n path,\n ],\n stdin=subprocess.PIPE,\n stdout=subprocess.PIPE,\n )\n stdout, _ = hdiutil.communicate(b\"qy\\n\")\n if hdiutil.wait() != 0:\n raise Exception(\"hdiutil failed (%r)\" % (hdiutil.returncode,))\n match = re.search(rb\"^<\\?xml\", stdout, re.M)\n plist_xml = stdout[match.start() :]\n plist = plistlib.loads(plist_xml)\n any_device = None\n mount_point = None\n for entity in plist[\"system-entities\"]:\n if \"mount-point\" in entity:\n if mount_point:\n raise Exception(\n (\n \"I don't know what to do with DMG that has\"\n \" multiple mount points\"\n )\n )\n mount_point = entity[\"mount-point\"]\n # Note that, at least on my recent-ish macOS,\n # detaching one mount point detaches the whole DMG, if\n # I'm reading hdiutil(1) correctly.\n self._add_hdiutil_detach_clean_up(mount_point)\n elif not any_device:\n any_device = entity.get(\"dev-entry\")\n if not mount_point:\n if any_device:\n self._add_hdiutil_detach_clean_up(mount_point)\n raise Exception(\n (\n \"Attached disk image but found no mount point\"\n \" (image may still be attached in some form)\"\n )\n )\n logger.debug(\"Mounted DMG at %r\", mount_point)\n return self.install_from_path(mount_point)\n\n def install_from_zip(self, path):\n extract_dir = tempfile.mkdtemp(dir=self._temp_dir)\n # Python's ZipFile.extractall doesn't preserve permissions\n # (https://bugs.python.org/issue15795). Sometimes \"unzip\"\n # can't extract an archive\n # (https://github.com/signalapp/Signal-Desktop/issues/3128).\n # ditto is our new best hope.\n subprocess.check_call([\"/usr/bin/ditto\", \"-x\", \"-k\", path, extract_dir])\n return self.install_from_path(extract_dir)\n\n def install_from_tar(self, path):\n extract_dir = tempfile.mkdtemp(dir=self._temp_dir)\n # tarfile module is around but I don't know/trust that it\n # preserves all the things tar -p does, so I just use tar. -k\n # means don't overwrite anything, since that should never be\n # happening here.\n subprocess.check_call(\n [\"/usr/bin/tar\", \"-xkp\", \"-C\", extract_dir, \"-f\", path]\n )\n return self.install_from_path(extract_dir)\n\n def install_from_pkg(self, path):\n if not self.install_predicate(self, path):\n return []\n self._check_signature(path, TYPE_PKG)\n logger.info(\"Calling installer to install %r\", path)\n subprocess.check_call([\"installer\", \"-pkg\", path, \"-target\", \"/\"])\n return [os.path.basename(path)]\n\n def install_bundle(self, path):\n if not self.install_predicate(self, path):\n return []\n path = path.rstrip(\"/\")\n if not path.lower().endswith(\".sketchplugin\"):\n self._check_signature(path, TYPE_BUNDLE)\n bundle_name = os.path.basename(path)\n ext = os.path.splitext(bundle_name)[1].lower()\n dst_dir = self._dst_dir_for_bundle(ext)\n dst_bundle = os.path.join(dst_dir, bundle_name)\n if os.path.exists(dst_bundle):\n raise Exception(\n \"%r already exists, will not overwrite\" % (dst_bundle,)\n )\n real_temp_dir = os.path.realpath(self._temp_dir)\n real_bundle_path = os.path.realpath(path)\n can_move = real_bundle_path.startswith(real_temp_dir + os.sep)\n if can_move:\n logger.info(\"Moving %r to %r\", path, dst_bundle)\n shutil.move(path, dst_bundle)\n else:\n logger.info(\"Copying %r to %r\", path, dst_dir)\n copy_with_tar(path, dst_dir)\n if self._should_set_owner:\n change_owner(dst_bundle, self.owner_uid, self.owner_gid)\n chmod_recursive(dst_bundle)\n return [bundle_name]\n\n\ndef install_nothing_predicate(_installer, _path):\n return False\n\n\ndef make_regexp_install_predicate(regexps):\n def regexp_install_predicate(_, path):\n return any(re.search(regexp, path) for regexp in regexps)\n\n return regexp_install_predicate\n\n\ndef make_dir_handler_to_run_installer(installer_rel_path, installer_args):\n def dir_handler(_, path):\n installer_path = os.path.join(path, installer_rel_path)\n if os.path.isfile(installer_path) and os.access(\n installer_path, os.X_OK\n ):\n subprocess.check_call([installer_path] + list(installer_args))\n return True, [installer_path]\n return True, []\n\n return dir_handler\n\n\ndef make_dir_handler_to_run_bundle(bundle_rel_path):\n def dir_handler(_, path):\n bundle_path = os.path.join(path, bundle_rel_path)\n if is_bundle(bundle_path):\n subprocess.check_call(\n [\"/usr/bin/open\", \"--wait-apps\", \"--new\", bundle_path]\n )\n return True, [bundle_path]\n return True, []\n\n return dir_handler\n\n\nclass Sentinel:\n def __init__(self, name):\n self.name = name\n\n def __repr__(self):\n return \"\" % (self.name,)\n\n\nDST_DIR_SYSTEM = Sentinel(\"DST_DIR_SYSTEM\")\nDST_DIR_USER = Sentinel(\"DST_DIR_USER\")\n\n\nclass ScrapedLink(Exception):\n def __init__(self, url):\n Exception.__init__(self)\n self.url = url\n\n\nclass LinkScraper(HTMLParser):\n def __init__(self, base_url, link_regexp):\n HTMLParser.__init__(self)\n self._base_url = base_url\n self._link_regexp = re.compile(link_regexp)\n\n def handle_starttag(self, tag, attrs):\n if tag.lower() == \"a\":\n for name, value in attrs:\n if name.lower() == \"href\":\n url = urllib.parse.urljoin(self._base_url, value)\n if self._link_regexp.search(url):\n # Raising an exception seems to be the\n # best/only way to stop HTMLParser.\n raise ScrapedLink(url)\n\n\ndef scrape_download_link_in_html(html_url, regexp, user_agent=None):\n scraper = LinkScraper(html_url, regexp)\n logger.debug(\"Fetching %r for scraping\", html_url)\n response = open_url(html_url, user_agent=user_agent)\n # Poor man's encoding detection for HTML. Completely ignoring\n # meta tags. If this fails, just whack to ASCII and hope for the\n # best. Reason I want to get from str → unicode in Python 2 is\n # because HTMLParser seems to try and decode character entity\n # references in the HTML, and those come out unicode, so\n # internally it may want to convert your input to unicode anyway.\n _, params = cgi.parse_header(response.headers.get(\"Content-Type\", \"\"))\n encoding = params.get(\"charset\", \"utf-8\")\n data = response.read()\n response.close()\n try:\n data = data.decode(encoding)\n except UnicodeDecodeError:\n data = data.decode(\"ascii\", \"ignore\")\n try:\n scraper.feed(data)\n except ScrapedLink as ex:\n url = ex.url\n else:\n raise Exception(\"No link matching %r on %r\" % (regexp, html_url))\n # Today I hate MsgFiler because their MsgFiler Engine download\n # page uses friggin' Dropbox links. They look like they're\n # inserted by hand, and the most recent one has the \"?dl=0\" at the\n # end, which we can't do much with. Look out for this abomination\n # and fix it. I am definitely too old for this shit.\n url_parts = urllib.parse.urlsplit(url)\n if (\n re.search(r\"^(?:www\\.)dropbox.com$\", url_parts.hostname)\n and url_parts.query\n ):\n params = urllib.parse.parse_qs(url_parts.query)\n if params.get(\"dl\") == [\"0\"]:\n params[\"dl\"] = [\"1\"]\n query = urllib.parse.urlencode(params, doseq=True)\n url = urllib.parse.urlunsplit(url_parts._replace(query=query))\n return url\n\n\ndef make_signature_checker(regexp):\n if regexp.startswith(\"id:\"):\n regexp = r\"\\(%s\\)$\" % (re.escape(regexp[3:]),)\n\n def check_signature(file_path, _file_type, originator):\n if not re.search(regexp, originator):\n raise Exception(\n (\n \"Signature originator on %r does not match %r: %r\"\n % (file_path, regexp, originator)\n )\n )\n\n return check_signature\n\n\ndef main(argv):\n _logging.basicConfig()\n parser = argparse.ArgumentParser(prog=argv[0])\n parser.add_argument(\n \"--debug\",\n \"-d\",\n action=\"store_true\",\n default=False,\n help=\"\"\"\\\n Output lots of extra information about what the tool is\n doing.\"\"\",\n )\n parser.add_argument(\n \"--owner\",\n help=(\n \"Owner for the installed applications.\"\n \" Ignored when installing an Installer package.\"\n ),\n )\n install_opts = parser.add_mutually_exclusive_group()\n install_opts.add_argument(\n \"--install\",\n \"-i\",\n dest=\"install_regexps\",\n action=\"append\",\n default=[],\n metavar=\"REGEXP\",\n help=\"\"\"\\\n Regexp for bundle or Installer pkg file to install within\n extracted files. May be specified multiple times.\"\"\",\n )\n install_opts.add_argument(\n \"--run-installer\",\n \"-r\",\n nargs=2,\n metavar=(\"NAME\", \"ARGS\"),\n help=\"\"\"\\\n Run an installer from one of the extracted directories or\n mounted volumes. PATH must be a relative path, though it\n may be relative to any directory within the install files\n (though not within a bundle). If PATH is found while\n extracting and traversing the install location, it will be\n run. All other candidates for installation (bundles,\n packages) will be ignored. ARGS must be either the empty\n string, or else a JSON array which gives a list of string\n arguments to call the installer with.\"\"\",\n )\n install_opts.add_argument(\n \"--run-bundle\",\n \"-R\",\n metavar=\"NAME\",\n help=\"\"\"\\\n Run a bundle from one of the extracted directories or\n mounted volumes. PATH must be a relative path, though it\n may be relative to any directory within the install files\n (though not within a bundle). If PATH is found while\n extracting and traversing the install location, it will be\n run. All other candidates for installation (bundles,\n packages) will be ignored.\"\"\",\n )\n parser.add_argument(\n \"--check-signature\",\n \"-C\",\n metavar=\"REGEXP\",\n help=\"\"\"\\\n All DMG files, installer packages, and bundles (app\n bundles, preference panes, Mail bundles, Sketch plug-ins)\n must have a valid signature from an originator matching\n REGEXP, as output by spctl. REGEXP may also be the string\n \\\"valid\\\", in which case any valid signature will be\n accepted.\"\"\",\n )\n parser.add_argument(\n \"--check-dmg-signature\",\n metavar=\"REGEXP\",\n help=\"Like --check-signature, but only applies to DMG files.\",\n )\n parser.add_argument(\n \"--check-pkg-signature\",\n metavar=\"REGEXP\",\n help=\"Like --check-signature, but only applies to installer packages.\",\n )\n parser.add_argument(\n \"--check-bundle-signature\",\n metavar=\"REGEXP\",\n help=\"\"\"\\\n Like --check-signature, but only applies to app bundles,\n preference panes, and mail bundles.\"\"\",\n )\n parser.add_argument(\n \"--check-hash\",\n metavar=\"TYPE:HASH\",\n help=\"\"\"\\\n Check the downloaded or supplied file's hash matches the\n argument before proceeding to use it. TYPE must be a hash\n type supported by your Python installation, such as sha256\n (always supported by Python). HASH should be in hex.\"\"\",\n )\n dest_args = parser.add_mutually_exclusive_group()\n dest_args.add_argument(\n \"--dest\",\n dest=\"dst_dir\",\n help=\"\"\"\\\n Directory where bundles will be installed. Ignored when\n installing an Installer package. Defaults to\n /Applications when run as root, otherwise\n ~/Applications.\"\"\",\n )\n dest_args.add_argument(\n \"--dest-system\",\n dest=\"dst_dir\",\n action=\"store_const\",\n const=DST_DIR_SYSTEM,\n help=\"Install into system directory.\",\n )\n dest_args.add_argument(\n \"--dest-user\",\n dest=\"dst_dir\",\n action=\"store_const\",\n const=DST_DIR_USER,\n help=\"Install into user home directory.\",\n )\n parser.add_argument(\n \"--cache\",\n \"-c\",\n metavar=\"PATH\",\n help=\"\"\"\\\n Directory or file to download to. If PATH is a directory,\n the file will be downloaded into the directory.\n Otherwise, the file will be downloaded as PATH. However,\n if PATH ends with a slash, PATH will be unconditionally\n interpreted as a directory. Directories will be created\n if they do not already exist.\"\"\",\n )\n parser.add_argument(\n \"--name\",\n \"-n\",\n dest=\"download_name\",\n help=\"\"\"\\\n Name of the downloaded file. If not given, will be\n inferred from the URL, or from the server response.\n Ignored when installing a local file.\"\"\",\n )\n download_args = parser.add_mutually_exclusive_group()\n download_args.add_argument(\n \"--cask\",\n action=\"store_true\",\n default=False,\n help=\"\"\"\\\n The given install location is the name of a Homebrew Cask.\n Retrieve the URL (and do signature checks) as specified in\n the Cask's description. This ONLY reads the URL (and\n hash) from Homebrew, NOTHING else.\"\"\",\n )\n download_args.add_argument(\n \"--github\",\n metavar=\"REGEXP\",\n dest=\"github_regexp\",\n help=\"\"\"\\\n Download latest release from GitHub repo. In this case,\n what_to_install is the name of a GitHub repo, such as\n robertklep/quotefixformac. The REGEXP is to match a\n download name from the latest tagged release.\"\"\",\n )\n download_args.add_argument(\n \"--scrape-html\",\n metavar=\"REGEXP\",\n help=\"\"\"\\\n what_to_install is a URL to an HTML page where we will\n look for an = display_width or lead_x < 0 or lead_y >= display_height or lead_y < 0:\r\n gameExit = True\r\n \r\n\r\n \r\n## THIS AIN'T FUCKING NEEDED, JUST GOOD TO KNOW \r\n## if event.type == pygame.KEYUP:\r\n## if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT or event.key == pygame.K_UP or event.key == pygame.K_DOWN:\r\n## lead_x_change = 0\r\n## lead_y_change = 0\r\n\r\n \r\n lead_x += lead_x_change\r\n lead_y += lead_y_change\r\n gameDisplay.fill(white)\r\n #render other graphics here\r\n pygame.draw.rect(gameDisplay, black, [lead_x,lead_y, block_size, block_size]) #parameters see documentation\r\n pygame.display.update()\r\n\r\n clock.tick(FPS)\r\n\r\nmessage_to_screen(\"You Lose\", red)\r\npygame.display.update()\r\ntime.sleep(2)\r\n#Exiting pygame\r\npygame.quit()\r\nquit()\r\n","repo_name":"jreboqui/Pygame","sub_path":"Framework.py","file_name":"Framework.py","file_ext":"py","file_size_in_byte":2445,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"21264532799","text":"# -*- coding: utf-8 -*-\nfrom shutil import copyfile\nfrom promebuilder import gen_metadata, setup\nfrom promebuilder.utils import REQUIREMENTSFILE\n\nBUILREQFILE = 'build-requirements.txt'\n\nprint(\"Duplicating {} into {}\".format(BUILREQFILE, REQUIREMENTSFILE))\ncopyfile(BUILREQFILE, REQUIREMENTSFILE)\n\nMETADATA = gen_metadata(\n name=\"promebuilder\",\n description=\"Prometeia Package Builder\",\n email=\"pytho_support@prometeia.com\",\n url=\"https://github.com/prometeia/promebuilder\",\n keywords=\"setup build pipeline ci\",\n entry_points={\n 'console_scripts': [\n 'promescanner = promebuilder.scanner:scan_here',\n 'activatenrt = promebuilder.activatenrt:activate_nrt'\n ]\n }\n)\n\n\nif __name__ == '__main__':\n setup(METADATA)\n","repo_name":"prometeia-erm/promebuilder","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":768,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"81"} +{"seq_id":"72649375625","text":"from django.shortcuts import get_object_or_404, render\n\nfrom jobs.models import Job\n\n\ndef index(request):\n all_jobs = Job.objects.all()\n open_jobs = [job for job in all_jobs if job.is_job_open]\n expired_jobs = [job for job in all_jobs.reverse() if not job.is_job_open][:5]\n return render(\n request, \"index.html\", {\"open_jobs\": open_jobs, \"expired_jobs\": expired_jobs}\n )\n\n\ndef detail(request, job_id, **kwargs):\n job = get_object_or_404(Job, pk=job_id)\n return render(request, \"job.html\", {\"job\": job})\n","repo_name":"chttrjeankr/GCETTB-TPO","sub_path":"jobs/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":531,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"81"} +{"seq_id":"18819102294","text":"import requests\n\nstops = ['340060','340061','40115','060814']\n\nfor t in range(len(stops)):\n stopnum = stops[t]\n #vrisko to onoma tis stasis\n stopnamelink=\"http://telematics.oasa.gr/api/?act=getStopNameAndXY&p1=\"+stopnum\n r = requests.get(stopnamelink)\n table3=r.json()\n print(\"--------------\")\n print (\"*\"+table3[0]['stop_descr']+\"*\")\n###### vrisko to lineid px 218\n linenamelink=\"http://telematics.oasa.gr/api/?act=webRoutesForStop&p1=\"+stopnum\n r = requests.get(linenamelink)\n table4=r.json()\n######\n link=\"http://telematics.oasa.gr/api/?act=getStopArrivals&p1=\"+stopnum\n r = requests.get(link)\n table=r.json()\n if table != None:\n for i in range(len(table)):\n routecode=table[i]['route_code']\n time=table[i]['btime2']\n for t in range(len(table4)):\n if routecode==table4[t]['RouteCode']:\n linename=table4[t]['RouteDescr']\n linenumber=table4[t]['LineID']\n print (\"[\"+linenumber+\"] \"+linename+\" σε \"+time+\" λεπτα!\")\n","repo_name":"haunter81/oasa_telematics","sub_path":"oasa_v2.py","file_name":"oasa_v2.py","file_ext":"py","file_size_in_byte":1048,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"30564882301","text":"#day18.py\n\ndef print_grid(grid):\n for i in range(0, len(grid)):\n for j in range(0, len(grid[0])):\n print(grid[i][j], end = '')\n print(\"\")\n\ndef on_count(grid):\n count = 0\n for i in range(0, len(grid)):\n for j in range(0, len(grid[0])):\n if grid[i][j] == '#':\n count += 1\n return count\n \ndef on_neighbors(grid, x, y):\n count = 0\n start_x = x - 1\n if start_x < 0:\n start_x = 0\n end_x = x + 1\n if end_x >= len(grid[0]):\n end_x = len(grid[0]) - 1\n start_y = y - 1\n if start_y < 0:\n start_y = 0\n end_y = y + 1\n if end_y >= len(grid):\n end_y = len(grid) - 1\n for i in range(start_y, end_y + 1):\n for j in range(start_x, end_x + 1):\n if i == y and j == x:\n continue\n if grid[i][j] == '#':\n count += 1\n return count\n\ndef step(gridA, gridB, part2 = False):\n for i in range(0, len(gridA)):\n for j in range(0, len(gridA[0])):\n if part2 and ((i == 0 and j == 0) or (i == len(gridA) - 1 and j == 0) or (i == 0 and j == len(gridA[0]) - 1) or (i == len(gridA) - 1 and j == len(gridA[0]) - 1)):\n continue\n neighbors = on_neighbors(gridA, j, i)\n if gridA[i][j] == '#' and (neighbors == 2 or neighbors == 3):\n gridB[i][j] = '#'\n elif gridA[i][j] == '.' and neighbors == 3:\n gridB[i][j] = '#'\n else:\n gridB[i][j] = '.'\n\ndef day18(infile):\n f = open(infile, 'r')\n lines = f.readlines()\n f.close()\n \n gridA = []\n gridB = []\n steps = 100\n for i in range(0, len(lines)):\n line = lines[i].replace('\\n', '')\n gridA.append([])\n gridB.append([])\n for j in range(0, len(line)):\n gridA[i].append(line[j])\n gridB[i].append(line[j])\n \n for i in range(0, steps + 1):\n if i % 2 == 0:\n step(gridA, gridB)\n else:\n step(gridB, gridA)\n \n part1 = 0\n if steps % 2 == 0:\n part1 = on_count(gridA)\n else:\n part1 = on_count(gridB)\n \n # reset grid\n for i in range(0, len(lines)):\n line = lines[i].replace('\\n', '')\n for j in range(0, len(line)):\n gridA[i][j] = line[j]\n \n gridA[0][0] = '#'\n gridB[0][0] = '#'\n gridA[0][len(gridA[0]) - 1] = '#'\n gridB[0][len(gridA[0]) - 1] = '#'\n gridA[len(gridA) - 1][0] = '#'\n gridB[len(gridA) - 1][0] = '#'\n gridA[len(gridA) - 1][len(gridA[0])-1] = '#'\n gridB[len(gridA) - 1][len(gridA[0])-1] = '#'\n \n for i in range(0, steps + 1):\n if i % 2 == 0:\n step(gridA, gridB, True)\n else:\n step(gridB, gridA, True)\n \n part2 = 0\n if steps % 2 == 0:\n part2= on_count(gridA)\n else:\n part2 = on_count(gridB)\n \n print(\"Part 1: %d\" % (part1))\n print(\"Part 2: %d\" % (part2))","repo_name":"marty777/adventofcode2015","sub_path":"src/day18.py","file_name":"day18.py","file_ext":"py","file_size_in_byte":2957,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"39600648966","text":"from sklearn.datasets import load_svmlight_file\nimport numpy as np\nimport sys\nimport math\nimport operator\n\n\ndef predict(Xtr, Ytr, Xts, metric=None):\n\n N, D = Xtr.shape\n\n assert N == Ytr.shape[0], \"Number of samples don't match\"\n assert D == Xts.shape[1], \"Train and test dimensions don't match\"\n\n if metric is None:\n metric = np.identity(D)\n\n Yts = np.zeros((Xts.shape[0], 1))\n k = 1;\n for i in range(Xts.shape[0]):\n M = Xtr - np.matmul(np.ones(len(Xts[i])).T, Xts[i])\n dist = np.sqrt(np.sum(np.square(M), axis=1))\n \n #print(\"dist shape = \",dist.shape)\n #print(dist)\n neighbors = []\n for x in range(len(Ytr)):\n neighbors.append((int(Ytr[x]),dist[x]))\n neighbors.sort(key=operator.itemgetter(1), reverse=True)\n\n f = open('myfile', 'a')\n\n # for x in range(k):\n # f.write(str(neighbors))\n # # f.write(str(neighbors[x][0])) # python will convert \\n to os.linesep\n # # f.write(' -> ')\n # # f.write(str(neighbors[x][1]))\n # # f.write('\\n')\n \n for x in range(k):\n print(neighbors[x][0])\n\n classVotes = {}\n classVotes[1] = 0\n classVotes[2] = 0\n classVotes[3] = 0\n\n for x in range(k):\n classVotes[int(neighbors[x][0])] += 1\n\n if classVotes[3] > classVotes[2]:\n if classVotes[3] > classVotes[1]:\n Yts[i] = 3\n else:\n Yts[i] = 1\n else:\n if classVotes[2] > classVotes[1]:\n Yts[i] = 2\n else:\n Yts[i] = 1\n\n print('#',i,' -> ',Yts[i],sep='')\n \n '''\n Predict labels for test data using k-NN. Specify your tuned value of k here\n '''\n f.write('--------------------------------------------\\n') # python will convert \\n to os.linesep\n\n\n f.close() # you can omit in most cases as the destructor will call it\n\n return Yts\n\ndef main(): \n\n # Get training and testing file names from the command line\n traindatafile = sys.argv[1]\n testdatafile = sys.argv[2]\n print('started')\n # The training file is in libSVM format\n tr_data = load_svmlight_file(traindatafile)\n\n Xtr = tr_data[0].toarray();\n Ytr = tr_data[1];\n\n # The testing file is in libSVM format too\n ts_data = load_svmlight_file(testdatafile)\n\n Xts = ts_data[0].toarray();\n # The test labels are useless for prediction. They are only used for evaluation\n\n # Load the learned metric\n # metric = np.load(\"model.npy\")\n metric = None\n ### Do soemthing (if required) ###\n\n Yts = predict(Xtr, Ytr, Xts, metric)\n Yts_actual = ts_data[1]\n\n correct = 0\n for x in range(len(Yts)):\n if Yts_actual[x] == Yts[x]:\n correct += 1\n print('Accuracy for k = 1 => ',(correct/float(len(Yts))) * 100.0)\n # Save predictions to a file\n\t# Warning: do not change this file name\n np.savetxt(\"testY.dat\", Yts)\n\nif __name__ == '__main__':\n main()\n","repo_name":"HarshaNalluru/CS771-Machine-Learning-A1","sub_path":"q6/backup_q6#1.py","file_name":"backup_q6#1.py","file_ext":"py","file_size_in_byte":3038,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"31294090274","text":"###트레인 7일치씩 해서 다음 2일치를 예측하기\n## cpu로 돌아간다.\n\nimport numpy as np\nimport pandas as pd\nimport os\nimport glob\nimport random\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\ntrain= pd.read_csv('C:/data/dacon_data/train/train.csv', encoding='cp949')\n# print(train.head())\n#337 7일차 337행\n# print(train.shape) # (52560,8)\n\nsubmission = pd.read_csv('C:/data/dacon_data/sample_submission.csv', encoding='cp949')\n# print(submission.tail())\n\n\ndef preprocess_data(data, is_train=True):\n \n temp = data.copy()\n temp = temp[['Hour', 'TARGET', 'DHI', 'DNI', 'WS', 'RH', 'T']]\n\n if is_train==True: \n \n temp['Target1'] = temp['TARGET'].shift(-48).fillna(method='ffill')\n temp['Target2'] = temp['TARGET'].shift(-48*2).fillna(method='ffill')\n temp = temp.dropna()\n \n return temp.iloc[:-96]\n\n elif is_train==False:\n \n temp = temp[['Hour', 'TARGET', 'DHI', 'DNI', 'WS', 'RH', 'T']]\n \n return temp.iloc[-48:, :]\n\n\ndf_train = preprocess_data(train)\ndf_train.iloc[:48]\n# print(df_train.head())\n\ntrain.iloc[48:96]\ntrain.iloc[48+48:96+48]\n\n# print(df_train.tail())\n\ndf_test = []\n\nfor i in range(81):\n file_path = 'C:/data/dacon_data/test/' + str(i) + '.csv'\n temp = pd.read_csv(file_path)\n temp = preprocess_data(temp, is_train=False)\n df_test.append(temp)\n\nx_test = pd.concat(df_test)\n# print(x_test.shape) #(3888, 7)\n\n# print(x_test.head(48))\n# print(df_train.head())\ndf_train.iloc[-48:]\n\nfrom sklearn.model_selection import train_test_split\nx_train_1, x_val_1, y_train_1, y_val_1 = train_test_split(\n df_train.iloc[:, :-2], df_train.iloc[:, -2], test_size=0.3, random_state=0)\nx_train_2, x_val_2, y_train_2, y_val_2 = train_test_split(\n df_train.iloc[:, :-2], df_train.iloc[:, -1], test_size=0.3, random_state=0)\n\n# print(x_train_1.head())\n# print(x_test.head())\n\nquantiles = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9]\n\n\n###########LGBM\nfrom lightgbm import LGBMRegressor\n\n# Get the model and the predictions in (a) - (b)\ndef LGBM(q, x_train, y_train, x_valid, y_valid, x_test):\n \n # (a) Modeling \n model = LGBMRegressor(objective='quantile', alpha=q, \n n_estimators=3300, bagging_fraction=0.7, learning_rate=0.1,\n max_depth=4, subsample=0.7, feature_fraction=0.9, boosting_type='gbdt',\n colsample_bytree=0.5, reg_lambda=5, n_jobs=-1)\n \n model.fit(x_train, y_train, eval_metric = ['quantile'], \n eval_set=[(x_valid, y_valid)], early_stopping_rounds=400, verbose=500)\n\n # (b) Predictions\n pred = pd.Series(model.predict(x_test).round(3)) #소수점 3번째 자리까지\n return pred, model\n\n\n# Target 예측\ndef train_data(x_train, y_train, x_valid, y_valid, x_test):\n\n LGBM_models=[]\n LGBM_actual_pred = pd.DataFrame()\n\n for q in quantiles:\n print(q)\n pred , model = LGBM(q, x_train, y_train, x_valid, y_valid, x_test)\n LGBM_models.append(model)\n LGBM_actual_pred = pd.concat([LGBM_actual_pred,pred],axis=1)\n\n LGBM_actual_pred.columns=quantiles\n \n return LGBM_models, LGBM_actual_pred\n\n# Target1\nmodels_1, results_1 = train_data(x_train_1, y_train_1, x_val_1, y_val_1,x_test)\nresults_1.sort_index()[:48]\n\n# Target2\nmodels_2, results_2 = train_data(x_train_2, y_train_2, x_val_2, y_val_2, x_test)\nresults_2.sort_index()[:48]\n\n# print(results_1.shape, results_2.shape)\nsubmission.iloc[:48]\nsubmission.loc[submission.id.str.contains(\"Day7\"), \"q_0.1\":] = results_1.sort_index().values\nsubmission.loc[submission.id.str.contains(\"Day8\"), \"q_0.1\":] = results_2.sort_index().values\n# print(submission)\nsubmission.iloc[:48]\nsubmission.iloc[48:96]\n\nsubmission.to_csv('C:/data/dacon_data/sub_0121_LGBM_1.csv', index=False)\n\n'''\n1.9991544728 --> 데이콘 점수 \n'''\n","repo_name":"seoyoungs/dacon","sub_path":"dacon_solar/dacon_0121_2_LG.py","file_name":"dacon_0121_2_LG.py","file_ext":"py","file_size_in_byte":3903,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"81"} +{"seq_id":"2958445345","text":"###############################################################################\n# Building the Model\n\n# Importing the libraries\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\nfrom sklearn.externals import joblib\n# import pickle\n\n# opening the databases\ntrain_df = pd.read_csv('data/train_data_modified.csv')\ntest_df = pd.read_csv('data/test_data_modified.csv')\n\n# now let's find mean based prediction\nmean_sales = train_df['Item_Outlet_Sales'].mean()\n\n# making baseline models helps in setting a benchmark.\n# If the predictive algorithm is below this,\n# there is something going seriously wrong with the algorithm or data\n\nbaseline = pd.DataFrame({\n 'Item_Identifier': test_df['Item_Identifier'],\n 'Outlet_Identifier': test_df['Outlet_Identifier'],\n 'Item_Outlet_Sales': mean_sales\n}, columns=['Item_Identifier', 'Outlet_Identifier', 'Item_Outlet_Sales'])\n\n# Export the baseline result\nbaseline.to_csv('data/mean_result.csv', index=False)\n\ndef trainModel(regressor, X_train, y_train, filename):\n # fitting the training set on the model\n regressor.fit(X_train, y_train)\n # print the regressor accuracy\n print(filename,\"score on training set: %.4f\" %(lr.score(X_train,y_train)))\n # Applying K-Fold cross validation\n from sklearn.model_selection import cross_val_score\n\n accuracies = cross_val_score(estimator=regressor, X=X_train, y=y_train,\n cv=10, n_jobs=-1)\n print(\"mean accuracy of \"+filename+\" Model on training set: %.4f\"\n %(accuracies.mean()))\n print(\"standard deviation of \"+filename+\" Model on training set: %.4f\"\n %(accuracies.std()))\n # Save the trained model\n joblib.dump(regressor,str(\"models/\"+filename+\".sav\"))\n # Save the Trained Model\n # pickle.dump(regressor, open(\"filename.sav\", 'wb'))\n # regressor = picle.load(open(\"filename.sav\",'wb'))\n\n\n# Extracting the training set\nX_train = train_df.drop(['Item_Outlet_Sales', 'Item_Identifier',\n 'Outlet_Identifier'], axis=1)\ny_train = train_df['Item_Outlet_Sales']\n\n# Linear Regression Model\nfrom sklearn.linear_model import LinearRegression\nlr = LinearRegression(normalize=True)\n\ntrainModel(lr, X_train, y_train, 'linear_regressor')\n\n# Decision Tree Model\nfrom sklearn.tree import DecisionTreeRegressor\ntree = DecisionTreeRegressor(max_depth=9, min_samples_leaf=150)\ntrainModel(tree, X_train, y_train, 'decision_tree_regressor')\n\n# RandomForest\nfrom sklearn.ensemble import RandomForestRegressor\nrf = RandomForestRegressor(n_estimators=300, max_depth=8, min_samples_leaf=100, n_jobs=-1)\ntrainModel(lr, X_train, y_train, 'random_forest_regressor')\n\n# SVM\nfrom sklearn.svm import SVR\nsvr_reg = SVR(kernel='rbf', gamma=0.5)\ntrainModel(lr, X_train, y_train, 'svm_regressor')\n\n\n# Gradiant Boosting Regression Model\nfrom sklearn.ensemble import GradientBoostingRegressor\ngbr = GradientBoostingRegressor(n_estimators=300, min_samples_leaf=100, max_depth=8)\n\ntrainModel(gbr, X_train, y_train, \"gradient_boost_regressor\")\n\nprint(\"The models are successfully trained\")","repo_name":"saddhu1005/BigMartsSalesPrediction","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":3070,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"81"} +{"seq_id":"2970787067","text":"#724. Find Pivot Index\n\nfrom typing import List\n\n\ndef pivotIndex(self, nums: List[int]) -> List[int]:\n lsum = 0\n rsum = sum(nums)\n for i in range(0, len(nums)):\n rsum -= nums[i]\n if lsum == rsum:\n return i\n lsum += nums[i]\n\n return 0\n\nnums = [1,7,3,6,5,6]\nprint(pivotIndex(0, nums))\n","repo_name":"POskar/LeetCodeProblems","sub_path":"solved/#724.py.py","file_name":"#724.py.py","file_ext":"py","file_size_in_byte":327,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"70021486026","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 ('simple_budget', '0015_account_account_hidden'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='account',\n name='account_opening_date',\n field=models.DateField(default=datetime.datetime(2015, 2, 19, 8, 41, 44, 534230, tzinfo=utc)),\n preserve_default=False,\n ),\n ]\n","repo_name":"buzz1274/simple_budget","sub_path":"simple_budget/migrations/0016_account_account_opening_date.py","file_name":"0016_account_account_opening_date.py","file_ext":"py","file_size_in_byte":571,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"81"} +{"seq_id":"74173413706","text":"import requests\nfrom bs4 import BeautifulSoup\n\nMAIN_URL_WALL_1 = 'http://wallpaperswide.com/page/'\nHEADERS = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:73.0) Gecko/20100101 Firefox/73.0',\n 'Accept': '*/*'}\nstart_page = int(input('First page: '))\nend_page = int(input('Last page: '))\n\n\ndef get_html(url):\n r = requests.post(url)\n return r\n\n\ndef get_content(html):\n soup = BeautifulSoup(html, 'html.parser')\n items = soup.find_all('div', class_='thumb')\n pictures = []\n for item in items:\n with_dot_html = item.find('a').get('href')\n pictures.append(\n 'http://wallpaperswide.com/download' + with_dot_html[:len(with_dot_html) - 16] + '-3840x2160.html')\n for aaa in pictures:\n if requests.get(aaa).status_code == 200:\n name_of_pict = aaa[35:len(aaa) - 5]\n image_to_download = requests.get(aaa, stream=True)\n fi = open(name_of_pict + '.jpg', 'wb')\n fi.write(image_to_download.content)\n image_to_download.close()\n print(f'{aaa} download successful')\n else:\n pass\n\n\ndef parse():\n global start_page\n while start_page <= end_page:\n MAIN_URL_WALL = MAIN_URL_WALL_1 + str(start_page)\n html = get_html(MAIN_URL_WALL)\n if html.status_code == 200:\n print(f'Downloading from {start_page} page...')\n get_content(html.text)\n start_page += 1\n else:\n print(f'\\nPage not foud')\n print(\"Downloading is complete\")\n\n\nparse()\n","repo_name":"itrance/trance_py","sub_path":"download from WW/parse.py","file_name":"parse.py","file_ext":"py","file_size_in_byte":1548,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"3475538666","text":"from django.db import models\nfrom users.models import CustomUser, HouseUser\n\n\n# Расходы дома\nclass Expenses(models.Model):\n created = models.DateTimeField('Создан', auto_now_add=True, db_index=True)\n category = models.ForeignKey('CatExpenses', on_delete=models.PROTECT, verbose_name=\"Категория расходов\", default=1)\n name = models.ForeignKey('ProductName', on_delete=models.PROTECT, verbose_name=\"Наименование продукта\", default=1)\n volume = models.IntegerField('Кличество, объем')\n money = models.BigIntegerField('Сумма')\n status = models.BooleanField('Статус покупки, исполнена или нет')\n user = models.ForeignKey('CustomUser', on_delete=models.PROTECT, verbose_name=\"Пользователь\", default=1)\n home = models.ForeignKey('HouseUser', on_delete=models.PROTECT, verbose_name=\"Дом\", default=1)\n\n\n\n#Категории расходов\nclass CatExpenses(models.Model):\n category = models.CharField('Название категории', max_length=50)\n\nclass ProductName(models.Model):\n name = models.CharField('Наименование продукта', max_length=100)\n","repo_name":"sagiem/home-accounting","sub_path":"core/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1214,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"74621022986","text":"import os\nimport torch\nfrom tensorboardX import SummaryWriter\n\n\ndef save_checkpoint(\n outpath, model, optimizer=None,\n is_best=False, save_all=False, **kwargs\n ):\n\n if hasattr(model, 'module'):\n model = model.module\n\n state_dict = {\n 'model': model.state_dict(),\n 'optimizer': optimizer.state_dict(),\n }\n\n state_dict.update(**kwargs)\n\n if not save_all:\n epoch = -1\n else:\n epoch = kwargs['iteration']\n\n torch.save(\n obj=state_dict,\n f=os.path.join(outpath, f'checkpoint_{epoch}.pkl'),\n )\n\n if is_best:\n import shutil\n shutil.copy(\n os.path.join(outpath, f'checkpoint_{epoch}.pkl'),\n os.path.join(outpath, 'best_model.pkl'),\n )\n\n\ndef restore_checkpoint(path, model=None, optimizer=False):\n state_dict = torch.load(\n path, map_location=lambda storage, loc: storage\n )\n new_state = {}\n for k, v in state_dict['model'].items():\n new_state[k.replace('module.', '')] = v\n\n if model is None:\n from ..model.model import LAVSE\n model_params = state_dict['args']['model_args']\n model = LAVSE(**model_params)\n\n model.load_state_dict(new_state)\n state_dict['model'] = model\n\n if optimizer:\n optimizer = state_dict['optimizer']\n state_dict['optimizer'] = None\n\n return state_dict\n\n\n# def adjust_learning_rate(\n# optimizer, epoch, initial_lr,\n# interval=1, decay=0.\n# ):\n\n# lr = initial_lr * (decay ** (epoch // interval))\n# for param_group in optimizer.param_groups:\n# param_group['lr'] = lr\n# if 'name' in param_group:\n# param_group['lr'] = lr\n\n# return lr\n\n\ndef get_tb_writer(logger_path):\n\n if logger_path == 'runs/':\n tb_writer = SummaryWriter()\n logger_path = tb_writer.file_writer.get_logdir()\n else:\n tb_writer = SummaryWriter(logger_path)\n\n return tb_writer\n\n\ndef get_device(gpu_id):\n\n if gpu_id >= 0:\n device = torch.device('cuda:{}'.format(gpu_id))\n else:\n device = torch.device('cpu')\n\n return device\n\n\ndef reset_pbar(pbar):\n from time import time\n pbar.n = 0\n pbar.last_print_n = 0\n pbar.start_t = time()\n pbar.last_print_t = time()\n pbar.update()\n return pbar\n\n\ndef print_tensor_dict(tensor_dict, print_fn):\n line = []\n for k, v in sorted(tensor_dict.items()):\n try:\n v = v.item()\n except AttributeError:\n pass\n line.append(f'{k.title()}: {v:10.6f}')\n print_fn(', '.join(line))\n\n\ndef get_data_path(opt):\n from pathlib import Path\n if 'DATA_PATH' not in os.environ:\n data_path = opt.dataset.data_path\n else:\n data_path = os.environ['DATA_PATH']\n return Path(data_path)\n","repo_name":"jwehrmann/lavse","sub_path":"lavse/utils/helper.py","file_name":"helper.py","file_ext":"py","file_size_in_byte":2781,"program_lang":"python","lang":"en","doc_type":"code","stars":22,"dataset":"github-code","pt":"81"} +{"seq_id":"23565653024","text":"from setuptools import setup, find_packages\n\nwith open('README.md', \"r\") as rf:\n long_description = rf.read()\n\nsetup(\n name='ezblast',\n version='0.1.0',\n author='John Stanco',\n description='Command-line tool for ncbi BLAST search',\n entry_points={\n 'console_scripts': ['ezblast=ezblast.cli:main']\n },\n long_description=long_description,\n packages=find_packages(),\n install_requires=[]\n)\n","repo_name":"jstanco/ezblast","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":424,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"14764228671","text":"import os\nimport platform\nimport sys\n\nfrom archivo import Archivo\nfrom adaptador import ArchivoAdaptador\nfrom automata_finito import AutomataFinito\nfrom automata_finito_comprobador import AutomataFinitoComprobador\nfrom tipo_automata import TipoAutomata\n\narchivo = None\ntabla_de_transiciones = []\n\ndef get_clear_command_by_os():\n\n\tswitcher = { 'Linux': \"clear\", 'Windows': \"cls\", 'Darwin': \"clear\" }\n\treturn switcher[ platform.system() ]\n\ndef display_tittle_bar():\n\t\n\tos.system(get_clear_command_by_os())\n\n\tprint(\"\\t********************************************************************************\")\n\tprint(\"\\t*** Laboratorio teoría de Lenguajes 201901 - Practica 1: Autómatas finitos ***\")\n\tprint(\"\\t********************************************************************************\")\n\ndef get_user_choice():\n\n\tprint (\"Selecciona una opción\")\n\n\tprint (\"\\t1 - Cargar archivo con tabla de transición\")\n\tprint (\"\\t2 - Mostrar automata finito\")\n\tprint (\"\\t3 - Determinar tipo autómata finito\")\n\tprint (\"\\t4 - Convertir a deterministico\")\n\tprint (\"\\t5 - Simplificar\")\n\tprint (\"\\t6 - Comprobar\")\n\tprint (\"\\tq - Salir\")\n\t\n\treturn input(\"inserta un numero valor >> \")\n\nchoice = ''\ndisplay_tittle_bar()\n\nwhile choice != 'q':\n\n\tchoice = get_user_choice()\n\n\tdisplay_tittle_bar()\n\n\tif choice == \"1\":\n\n\t\tprint (\"\")\n\n\t\tnombre_archivo = input(\"Ingres el nombre del archivo\\n>>\")\n\t\tarchivo = Archivo()\n\t\tarchivo.cargar_archivo(\"./tablas_transicion_estados/\" + nombre_archivo,\"r\")\n\t\ttabla_de_transiciones = archivo.obtener_lista_tabla_transicion()\n\n\t\tarchivo_adaptador = ArchivoAdaptador()\n\t\tautomata_finito = archivo_adaptador.pasar_a_automata_finito(archivo)\n\t\t\n\t\tinput(\"Has pulsado la opción 1...\\npulsa una tecla para continuar\")\n\n\telif choice == \"2\":\n\n\t\tprint (\"\")\n\n\t\tif automata_finito is None:\t\t\t\n\t\t\t\n\t\t\tprint(\"Cargue el automata a validar (Opción 1)\")\n\t\t\n\t\telse:\n\t\t\t\n\t\t\tprint(tabla_de_transiciones)\n\n\t\tinput(\"Has pulsado la opción 2...\\npulsa una tecla para continuar\")\n\t\n\telif choice == \"3\":\n\n\t\tprint (\"\")\n\n\t\tif automata_finito is None:\t\t\t\n\t\t\t\n\t\t\tprint(\"Cargue el automata a validar (Opción 1)\")\n\t\t\n\t\t#else:\n\t\t\t\n\t\t\tinput(\"Has pulsado la opción 3...\\npulsa una tecla para continuar\")\n\t\t\n\t\telse:\n\t\t\t\n\t\t\ttipo_automata = TipoAutomata()\n\t\t\ttipo_automata.automata_ND_D(automata_finito)\t\t\t\n\n\t\tinput(\"Has pulsado la opción 3...\\npulsa una tecla para continuar\")\n\t\n\telif choice == \"4\":\n\n\t\tprint (\"\")\n\t\tif automata_finito is None:\t\t\t\n\t\t\t\n\t\t\tprint(\"Cargue el automata a validar (Opción 1)\")\n\n\t\telse:\n\t\t\t\n\t\t\ttipo_automata = TipoAutomata()\n\t\t\t_deterministico = tipo_automata.automata_ND_D(automata_finito)\n\t\t\n\t\tinput(\"Has pulsado la opción 4...\\npulsa una tecla para continuar\")\n\t\t\n\telif choice == \"5\":\n\n\t\tprint (\"\")\n\t\tinput(\"Has pulsado la opción 5...\\npulsa una tecla para continuar\")\n\t\n\telif choice == \"6\":\n\n\t\tprint (\"\")\n\n\t\tif automata_finito is None:\t\t\t\n\t\t\t\n\t\t\tprint(\"Cargue el automata a validar (Opción 1)\")\n\t\t\n\t\telse:\n\t\t\t\n\t\t\tsecuencia = input(\"Ingrese la secuencia a comprobar\\n>>\")\n\t\t\t\n\t\t\tautomata_finito_comprobador = AutomataFinitoComprobador()\n\t\t\tes_estado_aceptacion = automata_finito_comprobador.comprobar( automata_finito, secuencia)\n\t\t\tif es_estado_aceptacion == True:\n\t\t\t\tprint(\"Secuencia válida\")\n\t\t\telse:\n\t\t\t\tprint(\"Secuencia invalida\")\n\t\t\n\t\tinput(\"Has pulsado la opción 6...\\npulsa una tecla para continuar\")\n\n\telif choice == \"q\":\n\n\t\tprint(\"...Hasta luego\")\t\t\n\n\telse:\n\n\t\tprint (\"\")\n\t\tinput(\"No has pulsado ninguna opción correcta...\\npulsa una tecla para continuar\")\n\n\n\t\n\n\n","repo_name":"yaquelinehoyos/AutomatasFinitos","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3488,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"25816174193","text":"import numpy as np\n\ndef find_seat(_input, range_length):\n '''This solves the problem using a 'distance travelled' approach\n to the problem. \n\n We move the midpoint of every interval either towards 0 (-) or\n the end of the range (+) based on the letter. The distance travelled\n does not depend on the letter and is always an exponent of 2, since this\n distanced is halved every turn.\n\n We start at the midpoint of the range (start). Our initial distance \n travelled is f (we start at half of the range, so 1st move is 1/2 that).\n\n The end position is our starting position + the distance travelled.\n '''\n\n start = ((range_length - 1) / 2)\n f = range_length / 4\n\n signs = [1 if l in [\"B\", \"R\"] else -1 for l in _input]\n weights = [f *(2**-i) for i, e in enumerate(signs)]\n\n signs, weights = np.array(signs), np.array(weights)\n\n vals = signs * weights\n\n return start + sum(vals)\n\ndef compute_seat_id(_input, row_length, col_length):\n # Split String\n row_instruc, col_instruc = _input[:-3], _input[-3:]\n\n # Get Seat Number\n row_val = find_seat(row_instruc, row_length)\n col_val = find_seat(col_instruc, col_length)\n\n return (row_val * 8) + col_val\n\ndef elimination_process(_input):\n # Find & Remove Seats w/ Neighbors\n drop_seats = [s for s in all_seat_ids if s + 1 in all_seat_ids and s - 1 in all_seat_ids]\n\n # Rest is Solution Candidates\n neighbor_candidates = [s for s in all_seat_ids if s not in drop_seats]\n\n # Actual Solution Seats will have another candidate seat 2 places away in either direction\n solution = [s for s in neighbor_candidates if s + 2 in neighbor_candidates or s - 2 in neighbor_candidates]\n\n return np.mean(solution)\n\nif __name__ == \"__main__\":\n _input = open(\"aoc_5.txt\").read().splitlines()\n \n print(\"PART 1\")\n all_seat_ids = list(map(compute_seat_id, _input, [128 for i in _input], [8 for i in _input]))\n max(all_seat_ids)\n print(\"\")\n print(\"PART 2\")\n elimination_process(all_seat_ids)","repo_name":"IAjimi/AdventOfCode","sub_path":"2020/AOC5.py","file_name":"AOC5.py","file_ext":"py","file_size_in_byte":2023,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"26624753304","text":"from tkinter import *\nfrom Functions import Buttons\nfrom Functions import Labels\nfrom Functions import InsertBoxs\n\n\ndef window_organize(window, name = 'Window', width = 1280, height = 720, resizable_width = False, resizable_height = False, min_width = 200, min_height = 200):\n '''\n -> Function to organizes your window\n :param window: Window param\n :param name: (Optional) Window name\n :param width: (Optional) Window width\n :param height: (Optional) Widnow height\n :param resizable_width: (Optional) If window width can resize\n :param resizable_height: (Optional) If window width can resize\n :param min_width: (Optional) Minimum value to resize width\n :param min_height: (Optional) Minimum value to resize height\n '''\n window.title(name)\n window.geometry(f'{width}x{height}')\n window.minsize(min_width, min_height)\n window.resizable(resizable_width, resizable_height)\n\n\nwindow_layout = {'window_name': 'Discord Bot Interface',\n 'width': 1280, 'height': 720,\n 'min_width': 200, 'min_height': 200,\n 'backgroud_color': 'white'}\n\nwindow = Tk()\nwindow_organize(window, window_layout['window_name'],\n window_layout['width'], window_layout['height'],\n min_width = window_layout['min_width'], min_height = window_layout['min_height'])\n\n\nwhile True:\n # Button\n button_list = Buttons.Buttons(window)\n button_list[0].pack()\n button_list[1].pack()\n button_list[2].pack()\n button_list[2].place(bordermode=OUTSIDE, x = 0, y = window_layout['height'] - 30)\n\n # Label\n label_list = Labels.Labels(window)\n label_list[0].pack()\n label_list[0].place(bordermode=OUTSIDE, x = 20, y = 0)\n\n # Insert Box\n\n insert_box_list = InsertBoxs.insert_boxs(window)\n insert_box_list[0].pack()\n insert_box_list[0].place(bordermode=OUTSIDE, x = 60, y = window_layout['height'] - 26)\n\n\n InsertBoxs.get_insert_box(insert_box_list[0])\n\n\n window.mainloop()","repo_name":"KaueGuimaraes/Discord-Bot-Interface","sub_path":"Discord Bot Interface/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1961,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"36291198367","text":"from django.db import models\nfrom django.contrib.auth.models import User\n\n\n\nclass Item(models.Model):\n #id = models.AutoField(primary_key=True)\n seller = models.ForeignKey('UserProfile', unique=False, related_name=\"item\" )\n name = models.CharField(max_length = 50)\n description = models.CharField(\"Description\",max_length = 1000)\n price = models.DecimalField(decimal_places=2, max_digits=6)\n sold = models.BooleanField()\n date_added = models.DateField(auto_now_add=True)\n photo = models.FileField(upload_to='photos/%Y/%m/%d')\n BEDROOM = 'BD'\n BATHROOM = 'BA'\n KITCHEN = 'KH'\n LIVING_ROOM = 'LR'\n FURNITURE_CHOICES = (\n (BEDROOM, 'Bedroom'),\n (BATHROOM, 'Bathroom'),\n (KITCHEN, 'Kitchen'),\n (LIVING_ROOM, 'Living Room'),\n )\n category = models.CharField(max_length = 2, choices=FURNITURE_CHOICES, default=LIVING_ROOM)\n\n\n def get_fields(self):\n return [(field, field.verbose_name(self)) for field in Item._meta.fields]\n\nclass UserProfile(models.Model):\n user = models.ForeignKey(User, unique=True, related_name=\"profile\")\n items_for_sale = models.ManyToManyField(Item, related_name=\"profile\")\n watched_items = models.ManyToManyField(Item, related_name=\"user_prof\")\n\n def get_user_name(self):\n u = User.objects.get(user=user)\n return self.u.name\n\n def __unicode__(self):\n return self.user.username\n\n\n\n\nclass Offer(models.Model):\n seller = models.ForeignKey(UserProfile, unique=False, related_name=\"seller_offer\")\n buyer = models.ForeignKey(UserProfile, unique=False, related_name=\"buyer_offer\")\n item = models.ForeignKey(Item, unique=False, related_name=\"item_offer\")\n date = models.DateField(auto_now_add=True)\n bid = models.DecimalField(decimal_places=2, max_digits=6) #default should be item price\n\n\n","repo_name":"adrind/jumbolist","sub_path":"jlist/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1833,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"81"} +{"seq_id":"23789049549","text":"\nfrom sklearn.datasets import fetch_20newsgroups\nfrom nltk.stem.snowball import SnowballStemmer\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn.feature_extraction.text import TfidfTransformer\nfrom sklearn.decomposition import TruncatedSVD\nimport re\n\ncomputer_technology_subclasses = ['comp.graphics', 'comp.os.ms-windows.misc', 'comp.sys.ibm.pc.hardware', 'comp.sys.mac.hardware']\nrecreational_activity_subclasses = ['rec.autos', 'rec.motorcycles', 'rec.sport.baseball', 'rec.sport.hockey']\n \ntraining_data = fetch_20newsgroups(subset='train', categories=computer_technology_subclasses+recreational_activity_subclasses, shuffle=True, random_state=42, remove=('headers', 'footers', 'quotes'))\n\nstemmer = SnowballStemmer(\"english\")\n\n\n#===================Remove Punctuation & Stem & Stop Words=====================\npunctuations = '[! \\\" # $ % \\& \\' \\( \\) \\* + , \\- \\. \\/ : ; < = > ? @ \\[ \\\\ \\] ^ _ ` { \\| } ~]'\ndef remove_punctuation_and_stem(data_list):\n for i in range(len(data_list)):\n data_list[i] = \" \".join([stemmer.stem(data) for data in re.split(punctuations, data_list[i])])\n data_list[i] = data_list[i].replace('\\n','').replace('\\t','').replace('\\r','')\n\n\nremove_punctuation_and_stem(training_data.data)\n\n\ncount_vect = CountVectorizer(min_df=10, stop_words ='english')\nX_counts = count_vect.fit_transform(training_data.data)\n\n#==============================================================================\n\ntfidf_transformer = TfidfTransformer()\nX_tfidf = tfidf_transformer.fit_transform(X_counts)\n\nsvd = TruncatedSVD(n_components = 50, n_iter = 10,random_state = 42)\nsvd.fit(X_tfidf)\nLSI = svd.transform(X_tfidf)\n\n\n\n\n\n\n\n\n\n","repo_name":"ttommytang/EE219","sub_path":"Project2/Codes/d.py","file_name":"d.py","file_ext":"py","file_size_in_byte":1673,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"19692717551","text":"import tkinter\n\nwin = tkinter.Tk()\n\nwin.title(\"entry\")\n\nwin.geometry(\"500x500+500+40\")\nvar = tkinter.Variable()\nentry = tkinter.Entry(win, show=\"*\", textvariable=var)\nentry.pack()\n\n\ndef print_func():\n print(var.get())\n\n\nbutton = tkinter.Button(win, text=\"打印\", command=print_func)\nbutton.pack()\n\nwin.mainloop()\n","repo_name":"luyasi/python_study","sub_path":"python-16-20180926/4.entry.py","file_name":"4.entry.py","file_ext":"py","file_size_in_byte":317,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"33049874716","text":"#!/bin/python3\nfrom collections import Counter\n\ndef main():\n t = int(input())\n\n for _ in range(t):\n n = int(input())\n sticks = [int(i) for i in input().split()]\n print(\"%.2f\" % expected_len(sticks))\n\ndef expected_len(sticks):\n expected = 0\n length = len(sticks)\n count = 0\n\n s = Counter(sticks)\n\n for stick in sorted(s, reverse=True):\n count += s[stick]\n expected += s[stick] * (length + 1) / (count + 1)\n\n return expected\n\nif __name__ == '__main__':\n main()\n","repo_name":"cpt-r3tr0/mathematics","sub_path":"Probability/VerticalSticks.py","file_name":"VerticalSticks.py","file_ext":"py","file_size_in_byte":483,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"25815921333","text":"def parse_line(line):\n new_key, op1, new_val, _, cond_key, op2, cond_val = line.split(' ')\n\n op_sign = 1 if op1 == 'inc' else -1\n new_val = int(new_val)\n _bool = 'd[\"' + cond_key + '\"]' + op2 + cond_val\n\n return new_key, op_sign, new_val, cond_key, _bool\n\ndef run(_input):\n d = {}\n _max = 0\n\n for line in _input:\n new_key, op_sign, new_val, cond_key, _bool = parse_line(line)\n\n if new_key not in d.keys():\n d[new_key] = 0\n if cond_key not in d.keys():\n d[cond_key] = 0\n\n if eval(_bool):\n d[new_key] += op_sign * new_val\n if d[new_key] > _max:\n _max = d[new_key]\n\n return max(d.values()), _max\n\nif __name__ == \"__main__\":\n _input = open(\"2017/aoc_8.txt\").read().splitlines()\n sol1, sol2 = run(_input) # 8022, 9819\n print(f\"PART 1: {sol1} \\n PART 2: {sol2}\")","repo_name":"IAjimi/AdventOfCode","sub_path":"2017/AOC8.py","file_name":"AOC8.py","file_ext":"py","file_size_in_byte":880,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"18715416163","text":"import configparser\nimport datetime\nimport os\nfrom pathlib import Path\n\n\nBASE_DIR = Path(__file__).resolve().parent.parent\nconfig_ini = configparser.ConfigParser()\nconfig_ini_path = os.path.join(BASE_DIR, 'config.ini')\nconfig_ini.read(config_ini_path, encoding='utf-8')\n\n\ndef get_search_date_range():\n year = int(config_ini.get('YOUTUBE', 'YEAR'))\n month = int(config_ini.get('YOUTUBE', 'MONTH'))\n if month == 12:\n next_year = year + 1\n else:\n next_year = year\n published_after = datetime.datetime(year=year, month=month, day=1).isoformat(\"T\") + \"Z\"\n published_before = datetime.datetime(year=next_year, month=(month % 12) + 1, day=1).isoformat(\"T\") + \"Z\"\n return published_after, published_before\n\n\ndef iso_to_jstdt(iso_str):\n return datetime.datetime.strptime(iso_str, '%Y-%m-%dT%H:%M:%SZ')\n","repo_name":"kenta-takeuchi/youtube_information_to_csv","sub_path":"task/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":831,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"16120305917","text":"from db_models.modelsv2 import Projects, ProjectSharing\nfrom db.db import session\nfrom flask import Flask, request\nfrom flask_restful import Resource, fields, marshal_with, abort, reqparse\nimport modules.log_helper_module as log_module\nfrom resv2.projects_resources import OUTPUT_FIELDS\n\n#PARAMS\nENTITY_NAME = \"Projects by User\"\nMODEL = Projects\nROUTE =\"/v2/userProjects/\"\nEND_POINT = \"v2-projects-by-user\"\n\n\nclass UserProjectListResource(Resource):\n def __init__(self):\n self.route = ROUTE\n self.end_point = END_POINT\n pass\n\n @marshal_with(OUTPUT_FIELDS)\n def get(self, id):\n try:\n action_type = 'GET'\n log_module.log_user_actions(ROUTE, id, action_type)\n user_projects = session.query(MODEL).filter(MODEL.user_id == id)\n shared_projects = session.query(MODEL) \\\n .join(ProjectSharing, MODEL.id == ProjectSharing.project_id) \\\n .filter(ProjectSharing.users_ids.any(id))\n projects = user_projects.union(shared_projects).distinct().all()\n if not projects:\n abort(400, message='Ошибка получения данных. Данные не найдены')\n\n return projects\n except Exception as e:\n log_module.add_log(\"Exception on route: {0} - {1}\".format(self.route, e))\n abort(400, message=\"Неопознанная ошибка\")\n\n","repo_name":"vyadzmak/Landau.X.Api","sub_path":"cross_res/projects_by_user_resources.py","file_name":"projects_by_user_resources.py","file_ext":"py","file_size_in_byte":1448,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"896837507","text":"import uuid\nfrom flask_restful import Resource, reqparse\nfrom flask_jwt_extended import jwt_required, get_jwt_identity\n\nfrom modals.Project import Project\n\nclass ProjectListResource(Resource):\n\n parser = reqparse.RequestParser()\n parser.add_argument('title',\n type=str,\n required=True,\n help=\"This field cannot be left blank!\"\n )\n parser.add_argument('description',\n type=str,\n required=True,\n help=\"This field cannot be left blank!\"\n )\n parser.add_argument('importance',\n type=str,\n required=True,\n help=\"This field cannot be left blank!\"\n )\n parser.add_argument('priority',\n type=str,\n required=True,\n help=\"This field cannot be left blank!\"\n )\n parser.add_argument('startDate',\n type=str,\n required=True,\n help=\"This field cannot be left blank!\"\n )\n parser.add_argument('endDate',\n type=str,\n required=True,\n help=\"This field cannot be left blank!\"\n )\n parser.add_argument('archived',\n type=str,\n required=False,\n help=\"This field cannot be left blank!\"\n )\n \n @jwt_required(fresh=True)\n def get(self, boardUUID):\n identity = get_jwt_identity()\n return Project.find_by_user_uuid(\"\", boardUUID, identity['companyUUID'], identity['teams']), 200, {'Content-Type': 'application/json; charset=utf-8'}\n\n @jwt_required(fresh=True)\n def put(self, boardUUID):\n data = ProjectListResource.parser.parse_args()\n identity = get_jwt_identity()\n data['projectUUID'] = str(uuid.uuid4())\n data['boardUUID'] = boardUUID\n data['companyUUID'] = identity['companyUUID']\n data['teams'] = identity['teams']\n result = Project.addEpic(data)\n if result['status']:\n return ('', 201)\n else:\n return {'errorMessage': result['message']}, 400, {'Content-Type': 'application/json; charset=utf-8'}\n\n","repo_name":"sravan6666/dachrs-server","sub_path":"resources/project/ProjectListResource.py","file_name":"ProjectListResource.py","file_ext":"py","file_size_in_byte":2450,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"41293600297","text":"arr = list(map(int, input().split()))\ndivisor = int(input())\n\ndef solution(arr, divisor):\n answer = []\n for i in range(len(arr)):\n if arr[i] % divisor == 0: answer.append(arr[i])\n\n answer.sort()\n if len(answer)==0: answer.append(-1)\n return answer\n\ndef solution2(arr, divisor):\n return sorted([n for n in arr if n%divisor == 0]) or [-1]\n\n# print(solution(arr, divisor).sort()) # sort는 제자리 메서드라 이런식으로 쓰면 None이 나와버림\nprint(solution(arr, divisor))\nprint(solution2(arr, divisor))","repo_name":"wish9/Algorithms","sub_path":"Programmers/lv1/An_array_of_divisible_numbers.py","file_name":"An_array_of_divisible_numbers.py","file_ext":"py","file_size_in_byte":539,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"32922029773","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu Jun 07 16:32:39 2018\r\n\r\n@author: Edward\r\n\"\"\"\r\nfrom __future__ import print_function\r\nimport numpy as np\r\nimport pickle\r\nimport sys\r\nimport io\r\n\r\nMAGIC_PREFIX = b'\\x93NUMPY'\r\nMAGIC_LEN = len(MAGIC_PREFIX) + 2\r\n\r\ndef _read_bytes(fp, size, error_template=\"ran out of data\"):\r\n \"\"\"\r\n Read from file-like object until size bytes are read.\r\n Raises ValueError if not EOF is encountered before size bytes are read.\r\n Non-blocking objects only supported if they derive from io objects.\r\n Required as e.g. ZipExtFile in python 2.6 can return less data than\r\n requested.\r\n \"\"\"\r\n data = bytes()\r\n while True:\r\n # io files (default in python3) return None or raise on\r\n # would-block, python2 file will truncate, probably nothing can be\r\n # done about that. note that regular files can't be non-blocking\r\n try:\r\n r = fp.read(size - len(data))\r\n data += r\r\n if len(r) == 0 or len(data) == size:\r\n break\r\n except io.BlockingIOError:\r\n pass\r\n if len(data) != size:\r\n msg = \"EOF: reading %s, expected %d bytes got %d\"\r\n raise ValueError(msg % (error_template, size, len(data)))\r\n else:\r\n return data\r\n\r\ndef read_magic(fp):\r\n \"\"\" Read the magic string to get the version of the file format.\r\n Parameters\r\n ----------\r\n fp : filelike object\r\n Returns\r\n -------\r\n major : int\r\n minor : int\r\n \"\"\"\r\n magic_str = _read_bytes(fp, MAGIC_LEN, \"magic string\")\r\n if magic_str[:-2] != MAGIC_PREFIX:\r\n msg = \"the magic string is not correct; expected %r, got %r\"\r\n raise ValueError(msg % (MAGIC_PREFIX, magic_str[:-2]))\r\n if sys.version_info[0] < 3:\r\n major, minor = map(ord, magic_str[-2:])\r\n else:\r\n major, minor = magic_str[-2:]\r\n return major, minor\r\n\r\ndef _filter_header(s):\r\n \"\"\"Clean up 'L' in npz header ints.\r\n Cleans up the 'L' in strings representing integers. Needed to allow npz\r\n headers produced in Python2 to be read in Python3.\r\n Parameters\r\n ----------\r\n s : byte string\r\n Npy file header.\r\n Returns\r\n -------\r\n header : str\r\n Cleaned up header.\r\n \"\"\"\r\n import tokenize\r\n if sys.version_info[0] >= 3:\r\n from io import StringIO\r\n else:\r\n from StringIO import StringIO\r\n\r\n tokens = []\r\n last_token_was_number = False\r\n # adding newline as python 2.7.5 workaround\r\n string = asstr(s) + \"\\n\"\r\n for token in tokenize.generate_tokens(StringIO(string).readline):\r\n token_type = token[0]\r\n token_string = token[1]\r\n if (last_token_was_number and\r\n token_type == tokenize.NAME and\r\n token_string == \"L\"):\r\n continue\r\n else:\r\n tokens.append(token)\r\n last_token_was_number = (token_type == tokenize.NUMBER)\r\n # removing newline (see above) as python 2.7.5 workaround\r\n return tokenize.untokenize(tokens)[:-1]\r\n\r\ndef _read_array_header(fp, version):\r\n \"\"\"\r\n see read_array_header_1_0\r\n \"\"\"\r\n # Read an unsigned, little-endian short int which has the length of the\r\n # header.\r\n import struct\r\n if version == (1, 0):\r\n hlength_type = '0):\r\n activeXY.append(xy)\r\n activeFrames = 0\r\n for t in range(len(dataShapes[xy])):\r\n if len(dataShapes[xy][t])>0:\r\n activeFrames += 1\r\n activeXYFrames.append(activeFrames)\r\nactiveXY = np.unique(activeXY)\r\n\r\nprint('activeXY: ',activeXY)\r\nprint('activeXYFrames: ',activeXYFrames)","repo_name":"esudzilovsky/organoidTracker","sub_path":"testLoad.py","file_name":"testLoad.py","file_ext":"py","file_size_in_byte":5775,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"35136217195","text":"'''\n041\n다음과 같은 문자열이 있을 때 이를 대문자 BTC_KRW로 변경하세요.\n\nticker = \"btc_krw\"\n'''\nticker = \"btc_krw\"\nticker1 = ticker.upper()\nprint(ticker1)\n\n\n'''\n042\n다음과 같은 문자열이 있을 때 이를 소문자 btc_krw로 변경하세요.\n\nticker = \"BTC_KRW\"\n'''\nticker = \"BTC_KRW\"\nticker2 = ticker.lower()\nprint(ticker2)\n\n\n'''\n043\n문자열 'hello'가 있을 때 이를 'Hello'로 변경해보세요.\n'''\na = 'hello'\na = a.replace('h', 'H')\nprint(a) # 나의 풀이\n\na = \"hello\"\na = a.capitalize()\nprint(a) # 정답\n\n\n'''\n044\n파일 이름이 문자열로 저장되어 있을 때\nendswith 메서드를 사용해서 파일 이름이 'xlsx'로 끝나는지 확인해보세요.\n\nfile_name = \"보고서.xlsx\"\n'''\nfile_name = \"보고서.xlsx\"\nfile_name.endswith(\"xlsx\")\n\n\n'''\n045\n파일 이름이 문자열로 저장되어 있을 때 endswith 메서드를 사용해서 파일 이름이 'xlsx' 또는 'xls'로 끝나는지 확인해보세요.\n\nfile_name = \"보고서.xlsx\"\n'''\nfile_name = \"보고서.xlsx\"\nfile_name.endswith((\"xlsx\", \"xls\"))\n\n\n'''\n046\n파일 이름이 문자열로 저장되어 있을 때 startswith 메서드를 사용해서 파일 이름이 '2020'로 시작하는지 확인해보세요.\n\nfile_name = \"2020_보고서.xlsx\"\n'''\nfile_name = \"2020_보고서.xlsx\"\nfile_name.startswith(\"2020\")\n\n\n'''\n047\n다음과 같은 문자열이 있을 때 공백을 기준으로 문자열을 나눠보세요.\n\na = \"hello world\"\n'''\na = \"hello world\"\na.split()\n\n\n'''\n048\n다음과 같이 문자열이 있을 때 btc와 krw로 나눠보세요.\n\nticker = \"btc_krw\"\n'''\nticker = \"btc_krw\"\nticker.split('_')\n\n\n'''\n049\n다음과 같이 날짜를 표현하는 문자열이 있을 때 연도, 월, 일로 나눠보세요.\n\ndate = \"2020-05-01\"\n'''\ndate = \"2020-05-01\"\ndate.split('-')\n\n\n'''\n문자열의 오른쪽에 공백이 있을 때 이를 제거해보세요.\n\ndata = \"039490 \"\n'''\ndata = \"039490 \"\ndata = data.rstrip()\n\n'''\n수정했어요\n'''\n","repo_name":"hyoeunla/JANDI","sub_path":"lahyoeun/1week/beginner_041-050.py","file_name":"beginner_041-050.py","file_ext":"py","file_size_in_byte":1982,"program_lang":"python","lang":"ko","doc_type":"code","stars":3,"dataset":"github-code","pt":"81"} +{"seq_id":"12024665248","text":"import os\nimport sys\n\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n# Define paths to easily import custom modules.\n# Assuming the script is located two directories deep from the root of the project.\ncurrent_directory = os.path.dirname(os.path.abspath(__file__))\nroot_directory = os.path.abspath(os.path.join(current_directory, \"..\", \"..\"))\nprint(\"Root\", root_directory)\n# Adding the root directory to the system path\nsys.path.append(root_directory)\n\nfrom Bilinear_model_fNIRS.src.components.BilinearModel_Miscellaneous import *\n\n\ndef generate_physiological_noise(timestamps, parameter):\n \"\"\"Generates more realistic physiological noise for a given physiological parameter.\"\"\"\n parameters = {\n \"heart\": {\"frequency\": 1.08, \"std_freq\": 0.16},\n \"breathing\": {\"frequency\": 0.22, \"std_freq\": 0.07},\n \"vasomotion\": {\"frequency\": 0.082, \"std_freq\": 0.016},\n }\n if parameter not in parameters:\n raise ValueError(\"Parameter must be 'heart', 'breathing', or 'vasomotion'\")\n param_info = parameters[parameter]\n base_freq = np.abs(\n np.random.normal(param_info[\"frequency\"], param_info[\"std_freq\"])\n )\n primary_noise = np.sin(2 * np.pi * base_freq * timestamps)\n harmonic_noise = generate_harmonic_noise(base_freq, timestamps)\n pink_noise_component = pink_noise(len(timestamps))\n pink_noise_component *= np.std(primary_noise) / np.std(\n pink_noise_component\n ) # normalize amplitude\n return primary_noise + harmonic_noise + pink_noise_component\n\n\ndef generate_harmonic_noise(base_freq, timestamps, num_harmonics=5):\n \"\"\"Generates harmonic components of physiological noise.\"\"\"\n harmonic_noise = np.zeros_like(timestamps)\n for i in range(1, num_harmonics + 1):\n harmonic_freq = (i + 1) * base_freq\n harmonic_noise += 0.5 ** (i + 1) * np.sin(\n 2 * np.pi * harmonic_freq * timestamps\n )\n return harmonic_noise\n\n\ndef generate_noise(timestamps, noise_type):\n \"\"\"Factory function for generating different types of noise.\"\"\"\n if noise_type == \"white\":\n return generate_white_noise(timestamps)\n else:\n return generate_physiological_noise(timestamps, noise_type)\n\n\ndef synthetic_physiological_noise_model_v1(\n timestamps,\n noise_types,\n HemodynamicSample,\n percent_error=0,\n):\n \"\"\"Generates physiological noises and applies gains to them.\"\"\"\n noises = [generate_noise(timestamps, noise_type) for noise_type in noise_types]\n physiological_signals_amp = [max_amplitude(noise) for noise in noises]\n gains = physiologicalNoise_gains(\n physiological_signals_amp, percent_error, max_amplitude(HemodynamicSample)\n )\n return [noise * gain for noise, gain in zip(noises, gains)]\n\n\ndef synthetic_physiological_noise_model(\n timestamps, noise_types, HemodynamicSample, percent_error=0\n):\n \"\"\"Generates physiological noises and scales them to a combined amplitude that is a percentage of the HemodynamicSample's amplitude.\"\"\"\n # Generate individual noises\n noises = [generate_noise(timestamps, noise_type) for noise_type in noise_types]\n\n # Calculate the desired total amplitude of the noises\n hemodynamic_max_amp = max_amplitude(HemodynamicSample)\n desired_total_noise_amp = hemodynamic_max_amp * (percent_error / 100)\n\n # Calculate current total amplitude of the noises\n current_total_noise_amp = sum(max_amplitude(noise) for noise in noises)\n\n # If the current total amplitude is zero, avoid division by zero\n if current_total_noise_amp == 0:\n raise ValueError(\"Current total amplitude of noises is zero, cannot scale.\")\n\n # Calculate the scaling factor\n scale_factor = desired_total_noise_amp / current_total_noise_amp\n\n # Apply the scaling factor to each noise signal\n scaled_noises = [noise * scale_factor for noise in noises]\n\n return scaled_noises\n\n\ndef combine_noises(noises_with_gains, nRegions):\n # Sum up all the noises\n combined_noise = np.sum(np.array(noises_with_gains), axis=0)\n\n # Adjust the combined_noise to match the number of regions\n if combined_noise.ndim == 1:\n # If combined_noise is 1D, repeat it for each region\n combined_noise = np.tile(combined_noise, (nRegions, 1))\n else:\n # If combined_noise is already 2D, but does not match nRegions, handle accordingly\n # Example: take only the first nRegions rows, or repeat/interpolate to match nRegions\n combined_noise = (\n combined_noise[:nRegions, :]\n if combined_noise.shape[0] >= nRegions\n else np.vstack([combined_noise] * nRegions)\n )\n\n return combined_noise\n\n\ndef synthetic_noise_plots(timestamps, noises, labels):\n \"\"\"Plots different types of synthetic noises.\"\"\"\n plt.figure(figsize=(12, 8))\n if len(noises) != len(labels):\n raise ValueError(\"The length of noises and labels must be the same\")\n for i, (noise, label) in enumerate(zip(noises, labels), start=1):\n plt.subplot(len(noises), 1, i)\n plt.plot(timestamps, noise, label=f\"{label} Noise\", linewidth=0.75)\n plt.xlabel(\"Time (s)\")\n plt.ylabel(\"Amplitude\")\n plt.title(f\"{label} Noise\")\n plt.legend()\n plt.tight_layout()\n plt.show()\n","repo_name":"MarSH-Up/PhD-Repository","sub_path":"Bilinear_model_fNIRS/src/components/BilinearModel_SyntheticNoise.py","file_name":"BilinearModel_SyntheticNoise.py","file_ext":"py","file_size_in_byte":5241,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"72489770506","text":"#!/usr/bin/python3\n\"\"\"Get state\"\"\"\n\n\nif __name__ == \"__main__\":\n import sys\n from model_state import Base, State\n from sqlalchemy.orm import Session\n from sqlalchemy import (create_engine)\n from model_city import City\n\n engine = create_engine(\n 'mysql+mysqldb://{}:{}@localhost/{}'\n .format(sys.argv[1], sys.argv[2], sys.argv[3]),\n pool_pre_ping=True)\n\n Base.metadata.create_all(engine)\n\n session = Session(engine)\n state = State(name='California')\n city = City(name='San Francisco')\n state.cities.append(city)\n session.add(state)\n session.commit()\n session.close()\n","repo_name":"Diego-Guarise/holbertonschool-higher_level_programming","sub_path":"0x0F-python-object_relational_mapping/100-relationship_states_cities.py","file_name":"100-relationship_states_cities.py","file_ext":"py","file_size_in_byte":629,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"81"} +{"seq_id":"5860317907","text":"import torch\nimport torch.nn as nn\nimport time, pdb\nimport numpy as np\n\nfrom util import py_softmax,MovingAverage\nfrom multigpu import gpu_mul_Ax, gpu_mul_xA, aggreg_multi_gpu, gpu_mul_AB\n\ndef cpu_sk(o1):\n \"\"\" Sinkhorn Knopp optimization on CPU\n * stores activations to RAM\n * does matrix-vector multiplies on CPU\n * slower than GPU\n \"\"\"\n # 1. aggregate inputs:\n N = len(o1.pseudo_loader.dataset)\n if o1.hc == 1:\n o1.PS = np.zeros((N, o1.K), dtype=o1.dtype)\n else:\n o1.PS_pre = np.zeros((N, o1.presize), dtype=o1.dtype)\n now = time.time()\n l_dl = len(o1.pseudo_loader)\n time.time()\n batch_time = MovingAverage(intertia=0.9)\n o1.model.headcount = 1\n for batch_idx, (data, _, _selected) in enumerate(o1.pseudo_loader):\n data = data.to(o1.dev)\n mass = data.size(0)\n if o1.hc == 1:\n p = nn.functional.softmax(o1.model(data), 1)\n o1.PS[_selected, :] = p.detach().cpu().numpy().astype(o1.dtype)\n else:\n p = o1.model(data)\n o1.PS_pre[_selected, :] = p.detach().cpu().numpy().astype(o1.dtype)\n batch_time.update(time.time() - now)\n now = time.time()\n if batch_idx % 50 == 0:\n print(f\"Aggregating batch {batch_idx:03}/{l_dl}, speed: {mass / batch_time.avg:04.1f}Hz\",\n end='\\r', flush=True)\n o1.model.headcount = o1.hc\n print(\"Aggreg of outputs took {0:.2f} min\".format((time.time() - now) / 60.), flush=True)\n \n # 2. solve label assignment via sinkhorn-knopp:\n if o1.hc == 1:\n o1 = optimize_L_sk(o1, nh=0)\n else:\n for nh in range(o1.hc):\n print(\"computing head %s \" % nh, end=\"\\r\", flush=True)\n tl = getattr(o1.model, \"top_layer%d\" % nh)\n time_mat = time.time()\n\n # clear memory\n try:\n del o1.PS\n except:\n pass\n\n # apply last FC layer (a matmul and adding of bias)\n o1.PS = (o1.PS_pre @ tl.weight.cpu().numpy().T.astype(o1.dtype)\n + tl.bias.cpu().numpy().astype(o1.dtype))\n print(f\"matmul took {(time.time() - time_mat)/60:.2f}min\", flush=True)\n o1.PS = py_softmax(o1.PS, 1)\n o1 = optimize_L_sk(o1, nh=nh)\n return o1\n\ndef gpu_sk(o1):\n \"\"\" Sinkhorn Knopp optimization on GPU\n * stores activations on multiple GPUs (needed when dataset is large)\n * does matrix-vector multiplies on GPU (extremely fast)\n * recommended variant\n * due to multi-GPU use, it's a bit harder to understand what's happening -> see CPU variant to understand\n \"\"\"\n # 1. aggregate inputs:\n start_t = time.time()\n if o1.hc == 1:\n o1.PS, indices = aggreg_multi_gpu(o1.model, o1.pseudo_loader,\n hc=o1.hc, dim=o1.outs[0], TYPE=o1.dtype)\n\n else:\n try: # just in case stuff\n del o1.PS_pre\n except:\n pass\n torch.cuda.empty_cache()\n time.sleep(1)\n o1.PS_pre, indices = aggreg_multi_gpu(o1.model, o1.pseudo_loader,\n hc=o1.hc, dim=o1.presize, TYPE=torch.float32)\n o1.model.headcount = o1.hc\n print(\"Aggreg of outputs took {0:.2f} min\".format((time.time() - start_t) / 60.), flush=True)\n # 2. solve label assignment via sinkhorn-knopp:\n if o1.hc == 1:\n o1 = optimize_L_sk_multi(o1, nh=0)\n o1.L[0,indices] = o1.L[0,:]\n else:\n for nh in range(o1.hc):\n tl = getattr(o1.model, \"top_layer%d\" % nh)\n time_mat = time.time()\n try:\n del o1.PS\n torch.cuda.empty_cache()\n except:\n pass\n\n # apply last FC layer (a matmul and adding of bias)\n o1.PS = gpu_mul_AB(o1.PS_pre, tl.weight.t(),\n c=tl.bias, dim=o1.outs[nh], TYPE=o1.dtype)\n print(\"matmul took %smin\" % ((time.time() - time_mat) / 60.), flush=True)\n o1 = optimize_L_sk_multi(o1, nh=nh)\n o1.L[nh][indices] = o1.L[nh]\n return o1\n\ndef optimize_L_sk(o1, nh=0):\n N = max(o1.L.size())\n tt = time.time()\n o1.PS = o1.PS.T # now it is K x N\n r = np.ones((o1.outs[nh], 1), dtype=o1.dtype) / o1.outs[nh]\n c = np.ones((N, 1), dtype=o1.dtype) / N\n o1.PS **= o1.lamb # K x N\n inv_K = o1.dtype(1./o1.outs[nh])\n inv_N = o1.dtype(1./N)\n err = 1e6\n _counter = 0\n while err > 1e-1:\n r = inv_K / (o1.PS @ c) # (KxN)@(N,1) = K x 1\n c_new = inv_N / (r.T @ o1.PS).T # ((1,K)@(KxN)).t() = N x 1\n if _counter % 10 == 0:\n err = np.nansum(np.abs(c / c_new - 1))\n c = c_new\n _counter += 1\n print(\"error: \", err, 'step ', _counter, flush=True) # \" nonneg: \", sum(I), flush=True)\n # inplace calculations.\n o1.PS *= np.squeeze(c)\n o1.PS = o1.PS.T\n o1.PS *= np.squeeze(r)\n o1.PS = o1.PS.T\n argmaxes = np.nanargmax(o1.PS, 0) # size N\n newL = torch.LongTensor(argmaxes)\n o1.L[nh] = newL.to(o1.dev)\n print('opt took {0:.2f}min, {1:4d}iters'.format(((time.time() - tt) / 60.), _counter), flush=True)\n return o1\n\ndef optimize_L_sk_multi(o1, nh=0):\n \"\"\" optimizes label assignment via Sinkhorn-Knopp.\n\n this implementation uses multiple GPUs to store the activations which allow fast matrix multiplies\n\n Parameters:\n nh (int) number of the head that is being optimized.\n\n \"\"\"\n N = max(o1.L.size())\n tt = time.time()\n r = torch.ones((o1.outs[nh], 1), device='cuda:0', dtype=o1.dtype) / o1.outs[nh]\n c = torch.ones((N, 1), device='cuda:0', dtype=o1.dtype) / N\n ones = torch.ones(N, device='cuda:0', dtype=o1.dtype)\n inv_K = 1. / o1.outs[nh]\n inv_N = 1. / N\n\n # inplace power of softmax activations:\n [qq.pow_(o1.lamb) for qq in o1.PS] # K x N\n\n err = 1e6\n _counter = 0\n ngpu = torch.cuda.device_count()\n splits = np.cumsum([0] + [a.size(0) for a in o1.PS])\n while err > 1e-1:\n r = inv_K / (gpu_mul_xA(c.t(), o1.PS,\n ngpu=ngpu, splits=splits, TYPE=o1.dtype)).t() # ((1xN)@(NxK)).T = Kx1\n c_new = inv_N / (gpu_mul_Ax(o1.PS, r,\n ngpu=ngpu, splits=splits, TYPE=o1.dtype)) # (NxK)@(K,1) = N x 1\n torch.cuda.synchronize() # just in case\n if _counter % 10 == 0:\n err = torch.sum(torch.abs((c.squeeze() / c_new.squeeze()) - ones)).cpu().item()\n c = c_new\n _counter += 1\n print(\"error: \", err, 'step ', _counter, flush=True)\n\n # getting the final tranportation matrix #####################\n for i, qq in enumerate(o1.PS):\n torch.mul(qq, c[splits[i]:splits[i + 1], :].to('cuda:' + str(i + 1)), out=qq)\n [torch.mul(r.to('cuda:' + str(i + 1)).t(), qq, out=qq) for i, qq in enumerate(o1.PS)]\n argmaxes = torch.empty(N, dtype=torch.int64, device='cuda:0')\n\n start_idx = 0\n for i, qq in enumerate(o1.PS):\n amax = torch.argmax(qq, 1)\n argmaxes[start_idx:start_idx + len(qq)].copy_(amax)\n start_idx += len(qq)\n newL = argmaxes\n print('opt took {0:.2f}min, {1:4d}iters'.format(((time.time() - tt) / 60.), _counter), flush=True)\n # finally, assign the new labels ########################\n o1.L[nh] = newL\n return o1\n\n","repo_name":"BruntonUWBio/cross-modal-ssl-htnet","sub_path":"sinkhornknopp_multi.py","file_name":"sinkhornknopp_multi.py","file_ext":"py","file_size_in_byte":7379,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"81"} +{"seq_id":"19160802331","text":"from rest_framework.views import APIView\nfrom rest_framework.response import Response\nfrom rest_framework import authentication, permissions\nfrom userprofile.models import User\nfrom api.common.utils import get_error_message\nfrom django.core.exceptions import ValidationError\nfrom rest_framework import exceptions as rest_exceptions\n\n\ndef get_response(message=\"\", result={}, status=True, status_code=200):\n return {\n \"message\" : message,\n \"result\" : result,\n \"status\" : status,\n \"status_code\" : status_code,\n }\n\n\nclass BaseView(APIView):\n # will be use for put the common code like, pagination, sorting etc ..\n expected_exceptions = {\n ValidationError: rest_exceptions.ValidationError\n }\n\n def handle_exception(self, exc):\n if isinstance(exc, tuple(self.expected_exceptions.keys())):\n drf_exception_class = self.expected_exceptions[exc.__class__]\n drf_exception = drf_exception_class(get_error_message(exc))\n\n return super().handle_exception(drf_exception)\n\n return super().handle_exception(exc)\n pass\n\n \n","repo_name":"yk2408/ecommerce","sub_path":"ecommerce/api/base/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1110,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"23828985200","text":"import numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.nn.parameter import Parameter\n\n\nclass GeneratorCNN(nn.Module):\n def __init__(self, nw=40, nh=40, nl=5,\n n_filters=(15, 9),\n kernel_size=(15, 11),\n n_cell=1,\n sampler=torch.distributions.bernoulli.Bernoulli,\n is_shared_noise=[False, False, False]):\n super(GeneratorCNN, self).__init__()\n self.nW = nw\n self.nH = nh\n self.nL = nl\n self.nFiltL1 = n_filters[0]\n self.nFiltL2 = n_filters[1]\n self.szFiltL1 = kernel_size[0]\n self.szFiltL2 = kernel_size[1]\n self.n_cell = n_cell\n self.sampler = sampler\n self.latent_dim = 3\n self.n_t = 1 # Number of spikes bin to be predicted by generator\n self.is_shared_noise = is_shared_noise\n\n self.l3_filt_shape = None\n\n self.conv1 = nn.Conv2d(in_channels=self.nL,\n out_channels=self.nFiltL1,\n kernel_size=(self.szFiltL1, self.szFiltL1),\n stride=1,\n padding=0,\n bias=True)\n\n self.conv2 = nn.Conv2d(in_channels=self.nFiltL1,\n out_channels=self.nFiltL2,\n kernel_size=(self.szFiltL2, self.szFiltL2),\n stride=1,\n padding=0,\n bias=True)\n\n if torch.cuda.is_available():\n self.cuda()\n\n in_shp, conv2outShape = self._compute_fc_in()\n self.l3_filt_shape = (self.n_cell, *conv2outShape)\n\n self.fc = nn.Linear(in_features=in_shp,\n out_features=self.n_cell,\n bias=True)\n self.shared_noise = Parameter(torch.ones(3).fill_(.05))\n\n def _compute_fc_in(self):\n x = np.random.random([1, self.nL, self.nW, self.nH])\n x = torch.tensor(x)\n x = self.conv1(x)\n x = self.conv2(x)\n conv2shape = x.size()[1:]\n x = x.view(x.size(0), -1)\n return x.size(1), conv2shape\n\n def forward(self, z, stim):\n x_conv1 = self.conv1(stim)\n x = F.relu(x_conv1)\n if self.is_shared_noise[0]:\n x = x + self.shared_noise[0] * z[:, 0].view(-1, 1, 1, 1).repeat((1, *x_conv1.shape[1:]))\n x_conv2 = self.conv2(x)\n x = F.relu(x_conv2)\n if self.is_shared_noise[1]:\n x = x + self.shared_noise[1] * z[:, 1].view(-1, 1, 1, 1).repeat((1, *x_conv2.shape[1:]))\n x = self.fc(x.view([x.shape[0], -1]))\n if self.is_shared_noise[2]:\n x = x + (self.shared_noise[2] * z[:, 2]).unsqueeze(1)\n return x.unsqueeze(1)\n\n def generate(self, z, stim):\n r\"\"\"\n Generate spikes\n Args:\n z (tensor): input noise\n stim (tensor): stimulus\n\n Returns:\n spikes (tensor): discrete spikes\n \"\"\"\n with torch.no_grad():\n logits = self.forward(z, stim)\n sampling_distribution = self.sampler(logits=logits)\n spikes = sampling_distribution.sample()\n return spikes\n","repo_name":"bmeatayi/neurogan","sub_path":"models/gen_cnn.py","file_name":"gen_cnn.py","file_ext":"py","file_size_in_byte":3324,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"13324572863","text":"\"\"\"home URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/1.11/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.conf.urls import url, include\n 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))\n\"\"\"\nfrom django.conf.urls import url\nfrom django.contrib import admin\nfrom .views import HomeView, department, user_signin, logout_view, sub_list, lec_list, res_list\n\nurlpatterns = [\n url(r'^$', HomeView.as_view(), name='home'),\n url(r'^admin/', admin.site.urls),\n url(r'^department/', department, name='department'),\n url(r'^login/', user_signin, name='login'),\n url(r'^subjects', sub_list, name='subjects'),\n url(r'^lecturers', lec_list, name='lecturers'),\n url(r'^results', res_list, name='results'),\n url(r'^logout', logout_view, name='logout'),\n # url(r'^subject/', sub_by_user, name='sub_user')\n]","repo_name":"saimounikanedunuri/New-Repository","sub_path":"first/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1277,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"10554319484","text":"import matplotlib.pyplot as plt\n\nfrom matplotlib import pyplot as plt\nimport numpy as np\n\n\nclass PorkchopPlotter:\n \"\"\"\n Class Implementation for Porkchop Plot.\n \"\"\"\n\n def __init__(\n self,\n departure_body,\n target_body,\n launch_span,\n arrival_span,\n ax=None,\n is_plot_tof=True,\n is_plot_arrive_v=True,\n max_c3=45.0,\n max_vhp=5\n ):\n \"\"\"\n \n Parameters\n ----------\n departure_body: \n Body from which departure is done\n\n target_body: \n Body for targetting\n\n launch_span: \n Time span for launch\n\n arrival_span: \n Time span for arrival\n\n ax: matplotlib.axes.Axes\n For custom figures\n\n is_plot_tof: bool\n For plotting time flight contour lines\n\n vhp: bool\n For plotting arrival velocity contour lines\n\n max_c3: float\n Sets the maximum C3 value for porkchop\n\n max_vhp: float\n Sets the maximum arrival velocity for porkchop\n\n \"\"\"\n self.departure_body = departure_body\n self.target_body = target_body\n self.launch_span = launch_span\n self.arrival_span = arrival_span\n self.ax = ax\n self.is_plot_tof = is_plot_tof\n self.is_plot_arrive_v = is_plot_arrive_v\n self.max_c3 = max_c3\n self.max_vhp = max_vhp\n\n def porkchop(self):\n \"\"\"\n Plots porkchop between two bodies.\n \"\"\"\n dv_launch, dv_arrival = donnager.interplan.calc_porkchop(\n self.departure_body,\n self.target_body,\n self.launch_span[np.newaxis, :],\n self.arrival_span[:, np.newaxis])\n\n if self.ax is None:\n fig, self.ax = plt.subplots(figsize=(15, 15))\n else:\n fig = self.ax.figure\n\n c3_levels = np.linspace(0, self.max_c3, 30)\n\n c = self.ax.contourf(\n [depart.to_datetime() for depart in self.launch_span],\n [arrive.to_datetime() for arrive in self.arrival_span],\n dv_launch**2,\n c3_levels)\n\n line = self.ax.contour(\n [depart.to_datetime() for depart in self.launch_span],\n [arrive.to_datetime() for arrive in self.arrival_span],\n dv_launch**2,\n c3_levels,\n colors=\"black\",\n linestyles=\"solid\")\n\n cbar = fig.colorbar(c)\n cbar.set_label(\"km2 / s2\")\n self.ax.clabel(line, inline=1, fmt=\"%1.1f\", colors=\"k\", fontsize=10)\n\n if self.is_plot_tof:\n time_levels = np.linspace(100, 500, 5)\n\n tfl_contour = self.ax.contour(\n [depart.to_datetime() for depart in self.launch_span],\n [arrive.to_datetime() for arrive in self.arrival_span],\n tof,\n time_levels,\n colors=\"red\",\n linestyles=\"dashed\",\n linewidths=3.5)\n\n self.ax.clabel(\n tfl_contour, \n inline=1, \n fmt=\"%1.1f\", \n colors=\"r\", \n fontsize=14)\n\n if self.is_plot_arrive_v:\n vhp_levels = np.linspace(0, self.max_vhp, 5)\n\n vhp_contour = self.ax.contour(\n [depart.to_datetime() for depart in self.launch_span],\n [arrive.to_datetime() for arrive in self.arrival_span],\n dv_arrival,\n vhp_levels,\n colors=\"navy\",\n linewidths=2.0)\n\n self.ax.clabel(\n vhp_contour, \n inline=1, \n fmt=\"%1.1f\", \n colors=\"navy\", \n fontsize=12)\n\n self.ax.grid()\n fig.autofmt_xdate()\n\n if not hasattr(self.target_body, \"name\"):\n self.ax.set_title(\n f\"{self.departure_body.name} - Target Body for year {self.launch_span[0].datetime.year}, C3 Launch\",\n fontsize=14,\n fontweight=\"bold\")\n else:\n self.ax.set_title(\n f\"{self.departure_body.name} - {self.target_body.name} for year {self.launch_span[0].datetime.year}, C3 Launch\",\n fontsize=14,\n fontweight=\"bold\")\n\n self.ax.set_xlabel(\n \"Launch date\", \n fontsize=10, \n fontweight=\"bold\")\n \n self.ax.set_ylabel(\n \"Arrival date\", \n fontsize=10, \n fontweight=\"bold\")\n ","repo_name":"Thomas-Oz-Dunn/donnager","sub_path":"python/donnager/porkchop_plotting.py","file_name":"porkchop_plotting.py","file_ext":"py","file_size_in_byte":4530,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"81"} +{"seq_id":"6198725118","text":"'''\n10. Write a Python program that accepts an integer (n) and computes the value of n+nn+nnn. \n'''\n\ntotal = 0\n\nwhile True:\n try:\n userInput = int(input(\"Please enter a number : \"))\n if(userInput < -9 or userInput > 9):\n raise Exception(\"Please enter a number between 0-9.\")\n except Exception as excObject:\n print(excObject)\n else:\n break\n \nnumber = userInput\n\nfor index in range(3):\n total += number\n number = number *10 + userInput\n \nprint(total)\n\n\n##########################################################################################################\n\na = int(input(\"Input an integer : \"))\nn1 = int( \"%s\" % a )\nn2 = int( \"%s%s\" % (a,a) )\nn3 = int( \"%s%s%s\" % (a,a,a) )\nprint (n1+n2+n3)","repo_name":"ErenBtrk/Python-Exercises-2","sub_path":"Exercise10.py","file_name":"Exercise10.py","file_ext":"py","file_size_in_byte":752,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"38841716487","text":"class User:\n def __init__(self, username, is_admin):\n self.username = username\n self.is_admin = is_admin\n\nclass Operator:\n def __init__(self, id, user):\n self.id = id\n self.user = user\n\nclass System:\n def __init__(self, operator):\n self.operator = operator\n \n def config(self):\n if self.operator.user.is_admin == True :\n print('You are allowed to config the system...')\n else:\n print(\"You not allowed to config the system...\")\n\n\n######################################\n\nu1 = User('cha552',True)\no1 = Operator('10',u1)\nsys1 = System(o1)\n\nsys1.config()\n\n\n","repo_name":"sadegh-dev/design_patterns","sub_path":"adapter.py","file_name":"adapter.py","file_ext":"py","file_size_in_byte":638,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"73471748745","text":"class Solution:\n def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode:\n def listify(head):\n l = []\n while head:\n l.append(head)\n head = head.next\n return l\n A = listify(headA)\n B = listify(headB)\n a = len(A) - 1\n b = len(B) - 1\n while a >=0 and b >= 0 and A[a] == B[b]:\n a -= 1\n b -= 1\n \n if a + 1 < len(A) and b + 1 < len(B) and A[a+1] == B[b+1]:\n return A[a + 1]\n else:\n return None\n","repo_name":"gauravaror/programming","sub_path":"getIntersectionNodes.py","file_name":"getIntersectionNodes.py","file_ext":"py","file_size_in_byte":582,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"21602719682","text":"\"\"\"\n# 203 - Remove Linked List Elements\n\n- https://leetcode.com/problems/remove-linked-list-elements/\n- Fast & Slow Pointers\n\n\n## Challenge\n\nGiven the head of a linked list and an integer val,\nremove all the nodes of the linked list that has Node.val == val,\nand return the new head.\n\n\n## Solution\n\nSee also problem 83\n\n1. current node exists and the next node exists check if the value matches 'val'\n\n2. same value? skip the node with head.next.next (the fast pointer)\n different value? just move to the next node\n \n3. Don't forget to store a copy of the head\n\n4. Compare this with porblem 0083, we can have an edge case on the start that we need to remove\n\"\"\"\n\n# Definition for singly-linked list.\nclass ListNode:\n def __init__(self, val=0, next=None):\n self.val = val\n self.next = next\n\nclass Solution:\n\n def removeElements(self, head: ListNode, val: int) -> ListNode:\n\n start = head\n \n # remove all the middle and end cases\n while head and head.next: \n if head.next.val == val:\n head.next = head.next.next\n else:\n head = head.next\n \n # edge case, matching value on the start\n if start and start.val == val:\n start = start.next\n \n return start","repo_name":"mccornet/leetcode_challenges","sub_path":"Python/0203.py","file_name":"0203.py","file_ext":"py","file_size_in_byte":1305,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"81"} +{"seq_id":"71433319946","text":"from flask import Flask, render_template, request, redirect\nfrom dataload import loadData\nimport os\nfrom voicebotfunc import talk\napp = Flask(__name__)\n\nstrs = []\n@app.route('/')\ndef hello():\n\treturn render_template('index.html', lis = strs, length = len(strs))\n\n@app.route('/submit', methods = ['POST'])\ndef submit():\n if request.method == 'POST':\n file = request.files['data']\n file.save(file.filename)\n #loadData(file.filename)\n q = 'python Backend/dynamictrain.py ' + file.filename\n #os.system(q)\n os.system('python Backend/train.py')\n print(\"trained\")\n\n return redirect('/')\n\n@app.route('/mike', methods = ['POST'])\ndef mike():\n if request.method == 'POST':\n\n message, botmessage = talk()\n\n\n strs.append(message)\n strs.append(botmessage)\n \n return redirect('/')\n #loadtheModule(file.filename, file.filename)\n\n return redirect('/')\n\n@app.route(\"/details\", methods = ['GET'])\ndef details():\n lisp = []\n with open('../botfiles/records.json') as json_file: \n data = json.load(json_file) \n for dic in data.values():\n lisp.append(dic)\n return render_template('details.html', lis = lisp)\n\nif __name__ == '__main__':\n app.run(debug = True)\n","repo_name":"Adityashar/Project1-ChatBot","sub_path":"citibot/Backend/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1277,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"81"} +{"seq_id":"7932933320","text":"# -*- coding: utf-8 -*-\n#マイク0番からの入力を受ける。一定時間(RECROD_SECONDS)だけ録音し、ファイル名:入力名.wavで保存する。\n \nimport pyaudio\nimport sys\nimport time\nimport wave\n \nif __name__ == '__main__':\n CHUNK = 1024 #1024\n FORMAT = pyaudio.paInt16\n CHANNELS = 1 #monoral\n #サンプリングレート、マイク性能に依存\n RATE = 44100\n # 録音時間\n RECORD_SECONDS = input('Please input recoding time>>>')\n filename=input('input filename=')\n \n p = pyaudio.PyAudio()\n input_device_index = 0 #RasPi;mic 0番のとき、Windowsは不要だが、あっても動く\n \n stream = p.open(format=FORMAT,\n channels=CHANNELS,\n rate=RATE,\n input=True,\n frames_per_buffer=CHUNK)\n\n print(\"* recording\")\n\n frames = []\n\n for i in range(0, int(RATE / CHUNK * int(RECORD_SECONDS))):\n data = stream.read(CHUNK)\n frames.append(data)\n\n print(\"* done recording\")\n\n stream.stop_stream()\n stream.close()\n p.terminate()\n\n wf = wave.open(filename+'.wav', 'wb')\n wf.setnchannels(CHANNELS)\n wf.setsampwidth(p.get_sample_size(FORMAT)) #width=2 ; 16bit\n wf.setframerate(RATE)\n wf.writeframes(b''.join(frames))\n wf.close()","repo_name":"MuAuan/Scipy-Swan","sub_path":"micinput.py","file_name":"micinput.py","file_ext":"py","file_size_in_byte":1299,"program_lang":"python","lang":"ja","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"12639470300","text":"import json\nimport os\nfrom tqdm import tqdm\ninput_dir = \"/sharefs/baai-mmdataset/wudaomm-5m\"\n\ndef load_mm(input_path, access_way=\"name\"):\n allpairs = {}\n with open(input_path, 'r') as f:\n batchpairs = json.load(f)\n for pair in tqdm(batchpairs):\n allpairs[pair[access_way]] = pair\n return allpairs\n","repo_name":"AlexZhangUPUPUP/AI","sub_path":"wudao_altclip_pipleline/MMPreprocessor/add_columns.py","file_name":"add_columns.py","file_ext":"py","file_size_in_byte":331,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"71635408264","text":"import time\ndef display_time(func):\n def wrapper(*args):\n t1=time.time()\n result=func(*args)\n t2=time.time()\n print(\"共计用了时间:{:.4}秒\".format(t2-t1))\n return result\n return wrapper\n\ndef is_prime(num):\n if num<2:\n return False\n elif num==2:\n return True\n else:\n for i in range(2,num):\n if num % i ==0:\n return False\n return True \n@display_time\ndef prime_nums(maxnumber):\n count=0\n for i in range(2,maxnumber):\n if is_prime(i):\n count=count+1\n return count\n\ncount=prime_nums(10)\nprint(count)\n # print(i)\n # t2=time.time()\n # print(t2-t1)\n\n# prime_nums()","repo_name":"yaoxs7503/pythontest","sub_path":"deco_zishu.py","file_name":"deco_zishu.py","file_ext":"py","file_size_in_byte":640,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"30782834343","text":"from odoo import fields\n\nfrom odoo.addons.shopinvader.tests.common import CommonCase\n\n\nclass TestShopinvaderBackend(CommonCase):\n \"\"\"\n Tests for shopinvader.backend\n \"\"\"\n\n def setUp(self):\n super().setUp()\n self.template = self.env.ref(\n \"shopinvader_pending_cart_reminder.\"\n \"mail_template_shopinvader_sale_reminder\"\n )\n self.backend.write({\"pending_cart_reminder_template_id\": self.template.id})\n\n def test_auto_reminder_start_date(self):\n \"\"\"\n Ensure the reminder_start_date is correctly updated\n :return:\n \"\"\"\n # Set to a previous date and disable the reminder\n today = \"2019-01-01\"\n reminder = 0\n self.backend.write(\n {\n \"pending_cart_reminder_delay\": reminder,\n \"reminder_start_date\": today,\n }\n )\n # Ensure the write is done\n self.assertEqual(self.backend.pending_cart_reminder_delay, reminder)\n self.assertEqual(\n self.backend.reminder_start_date, fields.Date.from_string(today)\n )\n # Now enable the reminder\n today = fields.Date.today()\n reminder = 10\n self.backend.write({\"pending_cart_reminder_delay\": reminder})\n # Ensure the reminder_start_date is updated\n self.assertEqual(self.backend.pending_cart_reminder_delay, reminder)\n self.assertEqual(self.backend.reminder_start_date, today)\n # Disable the reminder\n reminder = 0\n self.backend.write({\"pending_cart_reminder_delay\": reminder})\n # The date shouldn't change\n self.assertEqual(self.backend.pending_cart_reminder_delay, reminder)\n self.assertEqual(self.backend.reminder_start_date, today)\n return\n","repo_name":"shopinvader/odoo-shopinvader","sub_path":"shopinvader_pending_cart_reminder/tests/test_shopinvader_backend.py","file_name":"test_shopinvader_backend.py","file_ext":"py","file_size_in_byte":1782,"program_lang":"python","lang":"en","doc_type":"code","stars":105,"dataset":"github-code","pt":"81"} +{"seq_id":"26402443637","text":"import sys\nsugar = int(sys.stdin.readline())\nbags = 0\nwhile(True):\n if sugar%5==0:\n bags += sugar//5\n print(bags)\n break\n sugar -=3\n bags +=1\n if sugar <0:\n print(-1)\n break","repo_name":"glossyyoon/DailyCoding","sub_path":"greedy2839_1.py","file_name":"greedy2839_1.py","file_ext":"py","file_size_in_byte":220,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"44430853313","text":"from urllib.parse import parse_qs\nfrom .constants import Action, ContentType, ParameterKeys\nfrom .encoder import EncoderFactory\n\n\nclass ParametersError(ValueError):\n \"\"\"Raise when there is an error parsing the parameters\"\"\"\n\n\nclass ParametersBuilder(object):\n \"\"\"Helper to collect the parameters from different parts of the request and\n build a Parameters class.\n\n It collects the parameters from:\n * Request Method\n * Url path\n * Url query string\n * Body, which can be:\n + raw data\n + a query string\n + json data\n * Headers\n * Cookies\n \"\"\"\n\n def __init__(\n self,\n action=None,\n path=None,\n offset=None,\n size=None,\n encoding=None,\n append=None,\n data=None\n ):\n self.action = action\n self.path = path\n self.offset = offset\n self.size = size\n self.encoding = encoding\n self.append = append\n self.data = data\n\n def build(self):\n try:\n return self._try_build()\n except ValueError as ex:\n raise ParametersError(str(ex))\n\n def _try_build(self):\n if self.offset is None:\n offset = 0\n else:\n offset = int(self.offset)\n\n if self.size is not None:\n size = int(self.size)\n else:\n size = self.size\n\n if self.data is None:\n data = b\"\"\n else:\n data = self.data\n\n return Parameters(\n action=self.action,\n path=self.path,\n offset=offset,\n size=size,\n encoder=EncoderFactory.create(self.encoding),\n append=bool(self.append),\n data=data\n )\n\n @classmethod\n def from_request(cls, request):\n builder = cls()\n builder.update_from_method(request.method)\n builder.update_from_path(request.path)\n builder.update_from_query_string(request.url.query_string)\n builder.update_from_request_content(request)\n builder.update_from_dictionary(request.headers)\n builder.update_from_dictionary(request.cookies)\n return builder\n\n def update_from_request_content(self, request):\n content_length = request.content_length\n if content_length > 0:\n content = request.rfile.read(content_length)\n if request.content_type == ContentType.URLENCODED:\n self.update_from_query_string_bytes(parse_qs(content))\n else:\n self.update_from_raw_data(content)\n\n def update_from_method(self, method):\n other = self.from_method(method)\n self.update(other)\n\n @classmethod\n def from_method(cls, method):\n if method == \"POST\" or method == \"PUT\":\n return cls(action=Action.UPLOAD)\n else:\n return cls(action=Action.DOWNLOAD)\n\n def update_from_path(self, path):\n other = self.from_path(path)\n self.update(other)\n\n @classmethod\n def from_path(cls, path):\n return cls(path=path)\n\n def update_from_query_string(self, qs):\n other = self.from_query_string(qs)\n self.update(other)\n\n @classmethod\n def from_query_string(cls, qs):\n d = {}\n for member in ParameterKeys:\n key = member.value\n if key in qs:\n if key == ParameterKeys.data.value:\n d[key] = qs[key][0].encode()\n else:\n d[key] = qs[key][0]\n\n return cls.from_dictionary(d)\n\n def update_from_query_string_bytes(self, qs):\n other = self.from_query_string_bytes(qs)\n self.update(other)\n\n @classmethod\n def from_query_string_bytes(cls, qs):\n d = {}\n for member in ParameterKeys:\n key = member.value\n key_bytes = key.encode()\n if key_bytes in qs:\n if key == ParameterKeys.data.value:\n d[key] = qs[key_bytes][0]\n else:\n d[key] = qs[key_bytes][0].decode()\n\n return cls.from_dictionary(d)\n\n def update_from_dictionary(self, d):\n other = self.from_dictionary(d)\n self.update(other)\n\n @classmethod\n def from_dictionary(cls, d):\n action = None\n path = None\n offset = None\n size = None\n encoding = None\n append = None\n data = None\n\n for key, value in d.items():\n if ParameterKeys.is_action_parameter(key):\n action = value\n elif ParameterKeys.is_path_parameter(key):\n path = value\n elif ParameterKeys.is_offset_parameter(key):\n offset = value\n elif ParameterKeys.is_size_parameter(key):\n size = value\n elif ParameterKeys.is_encoding_parameter(key):\n encoding = value\n elif ParameterKeys.is_append_parameter(key):\n append = True\n elif ParameterKeys.is_data_parameter(key):\n data = value\n\n return cls(\n action=action,\n path=path,\n offset=offset,\n size=size,\n encoding=encoding,\n append=append,\n data=data\n )\n\n def update_from_raw_data(self, raw_data):\n other = self.from_raw_data(raw_data)\n self.update(other)\n\n @classmethod\n def from_raw_data(cls, raw_data):\n return cls(data=raw_data)\n\n def update(self, other):\n for key, value in other.__dict__.items():\n if value is not None:\n self.__dict__[key] = value\n\n\nclass Parameters:\n \"\"\"Store the parameters received from a request.\"\"\"\n\n def __init__(\n self,\n action,\n path,\n offset,\n size,\n encoder,\n append,\n data\n ):\n self.action = action\n self.path = path\n self.offset = offset\n self.size = size\n self.encoder = encoder\n self.append = append\n self.data = data\n\n @classmethod\n def from_request(cls, request):\n return ParametersBuilder.from_request(request).build()\n\n def __repr__(self):\n return repr(self.__dict__)\n","repo_name":"zer1t0/httpsweet","sub_path":"httpsweetlib/parameters.py","file_name":"parameters.py","file_ext":"py","file_size_in_byte":6269,"program_lang":"python","lang":"en","doc_type":"code","stars":24,"dataset":"github-code","pt":"81"} +{"seq_id":"22177567213","text":"from flask import Flask, request, abort,flash, redirect, url_for\nimport hashlib\nimport json\nimport requests\nimport os\nfrom flask_cors import cross_origin\nfrom werkzeug.utils import secure_filename\napp = Flask(__name__)\n\n#app.config['CAPTURE'] = bool(os.environ.get('CAPTURE'))\n#app.config['CACHE_DIR'] = os.environ.get('CACHE_DIR', '/tmp/cache')\n\n@app.route('/', defaults={'path': ''},methods=['POST','GET'])\n@app.route('/',methods = ['POST','GET'])\n@cross_origin()\n#@app.route(\"/\")\ndef hello(path):\n urldata = path.split('/',1)\n if urldata[0] == 'file':\n return route_file(urldata[1])\n url = 'http://localhost' + ':' + urldata[0]\n if len(urldata)==2:\n url = url +'/'+urldata[1]\n if request.method == 'GET':\n print('getrequest')\n incparms = request.args\n return _retrieve(url,incparms)\n if request.method == 'POST':\n print('postrequest')\n incparms = request.data\n print(incparms)\n return _retrieve(url,incparms)\n# if request.method == 'POST':\n# incparms = request.form\n# return _retrieve(url,incparms)\n# if not url or url.startswith('http://localhost'):\n# return abort(400)\n print('normalrequest')\n return _retrieve(url)\n\n\ndef _retrivepost():\n kwargs = __adapt_request_args(url)\n return response.text,response.status_code, __process_response_headers(response)\n\ndef _retrieve(url,incparms=[]):\n response = _request(url,incparms)\n return response.text,response.status_code, __process_response_headers(response)\n# path = _cache_path(url)\n\n# if not os.path.exists(path):\n# if app.config['CAPTURE']:\n# response = _request(url)\n# _store(url, response)\n# else:\n# return abort(404)\n\n# with open(path, 'r') as f:\n# cached = json.loads(f.read())\n# return cached['body'], cached['status'], cached['headers']\n\n\ndef _request(url,incparms=[]):\n kwargs = __adapt_request_args(url)\n if len(incparms)==0:\n r = requests.request(request.method, url, **kwargs)\n return r\n r = requests.request(request.method, url,params=incparms, **kwargs)\n return r\n\n\ndef __adapt_request_args(url):\n kwargs = {\n 'data': request.data,\n 'allow_redirects': False\n }\n headers = dict([(key.upper(), value)\n for key, value in request.headers.items()])\n\n # Explicitly set content-length request header\n if 'CONTENT-LENGTH' not in headers or not headers['CONTENT-LENGTH']:\n headers['CONTENT-LENGTH'] = str(len(kwargs['data']))\n\n # Let requests reset the host for us.\n if 'HOST' in headers:\n del headers['HOST']\n kwargs['headers'] = headers\n# print(kwargs)\n return kwargs\n\n\ndef _store(url, response):\n cached = json.dumps({\n 'body': response.text,\n 'headers': __process_response_headers(response),\n 'status': response.status_code\n })\n\n path = _cache_path(url)\n dir_ = path.rsplit('/', 1)[0]\n if not os.path.isdir(dir_):\n os.makedirs(dir_)\n with open(path, 'w') as w:\n w.write(cached)\n\n\ndef __process_response_headers(response):\n headers = dict(response.headers)\n headers['content-type'] = 'text/html; charset=utf-8'\n if 'content-encoding' in headers:\n del headers['content-encoding']\n if 'transfer-encoding' in headers:\n del headers['transfer-encoding']\n return headers\n\n\ndef _cache_path(url):\n to_hash = \"%s%s%s\" % (request.method, url, request.data)\n hashed = hashlib.md5(to_hash).hexdigest()\n address = (hashed[:2], hashed[2:4], hashed)\n return '%s/%s/%s/%s.json' % (app.config['CACHE_DIR'], address)\n\n\n\n\n\n@app.route('/file', defaults={'path': ''},methods=['POST','GET'])\ndef route_file(path):\n urldata = path.split('/',1)\n url = 'http://localhost' + ':' + urldata[0]\n if len(urldata)==2:\n url = url +'/'+urldata[1]\n if request.method == 'POST':\n # check if the post request has the file part\n if 'file' not in request.files:\n flash('No file part')\n return redirect(request.url)\n# print(request.files)\n fp = request.files['file']\n# kwargs = __adapt_request_args(url)\n# print('filename- {},stream-{},contyoe-{},headers-{}'.format(fp.filename, fp.stream,fp.content_type, fp.headers))\n response = requests.post(url, files={'file':\n (fp.filename, fp.stream,\n fp.content_type, fp.headers)},data=request.data)\n return response\n return '''\n \n Upload new File\n

Upload new File

\n
\n \n \n
\n '''\n#uploadfile\nUPLOAD_FOLDER = '/var/www/html/frontends'\nALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif','html','htm','php'])\napp.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER\ndef allowed_file(filename):\n return '.' in filename and \\\n filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS\n\n@app.route('/upload', methods=['GET', 'POST'])\ndef upload_file():\n if request.method == 'POST':\n # check if the post request has the file part\n if 'file' not in request.files:\n flash('No file part')\n return redirect(request.url)\n file = request.files['file']\n # if user does not select file, browser also\n # submit an empty part without filename\n if file.filename == '':\n flash('No selected file')\n return redirect(request.url)\n if file and allowed_file(file.filename):\n filename = secure_filename(file.filename)\n file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))\n return 'uploaded successfully'\n return '''\n \n Upload new File\n

Upload new File

\n
\n \n \n
\n '''\n\n\nif __name__ == \"__main__\":\n app.run(host='0.0.0.0',port='1111',debug=True)\n","repo_name":"frier-sam/Flask_proxy","sub_path":"fproxyserver.py","file_name":"fproxyserver.py","file_ext":"py","file_size_in_byte":6176,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"37830273713","text":"# encoding:UTF-8\n\n\"\"\"\nquantOS的行情和模拟交易接口\n官方网址:https://www.quantos.org/\n\"\"\"\n \nfrom vnpy.trader import vtConstant\nfrom quantosGateway import QuantosGateway\n\ngatewayClass = QuantosGateway\ngatewayName = 'QuantOS'\ngatewayDisplayName = u'QuantOS'\ngatewayType = vtConstant.GATEWAYTYPE_EQUITY\ngatewayQryEnabled = True\n\n","repo_name":"cao6237699/quantosGateway","sub_path":"__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":343,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"81"} +{"seq_id":"10051762842","text":"import copy\nimport os\nimport torch\nimport torch.nn as nn\nfrom mmdet3d.models.detectors import Base3DDetector\nfrom mmdet3d.core import bbox3d2result\nfrom mmdet.core import multi_apply\nfrom mmdet.models import DETECTORS\n\n\n@DETECTORS.register_module()\nclass BEVDetTraced(nn.Module):\n def __init__(self, model):\n super(BEVDetTraced, self).__init__()\n _model = copy.deepcopy(model)\n self.img_backbone = _model.img_backbone\n self.img_neck = _model.img_neck\n self.img_view_transformer_depthnet = _model.img_view_transformer.depthnet\n _model.img_view_transformer.depthnet = nn.Identity()\n self.img_view_transformer = _model.img_view_transformer\n self.bev_encoder_backbone = _model.img_bev_encoder_backbone\n self.bev_encoder_neck = _model.img_bev_encoder_neck\n self.head = _model.pts_bbox_head\n self.head_shared_conv = _model.pts_bbox_head.shared_conv\n self.head_task_heads = _model.pts_bbox_head.task_heads\n self.img_view_transformer_quant = nn.Identity()\n self.img_view_transformer_quant.remove = (\n False # a hack impl of quant the input of LSS\n )\n self.loss = _model.pts_bbox_head.loss\n self.get_bboxes = _model.pts_bbox_head.get_bboxes\n\n def image_encoder(self, img):\n imgs = img\n B, N, C, imH, imW = imgs.shape\n imgs = imgs.view(B * N, C, imH, imW)\n x = self.img_backbone(imgs)\n x = self.img_neck(x)\n _, output_dim, ouput_H, output_W = x.shape\n x = x.view(B, N, output_dim, ouput_H, output_W)\n return x\n\n def image_view_transformer_encoder(self, x):\n B, num_cams, oldC, H, W = x.shape # 512\n x = x.view(B * num_cams, oldC, H, W)\n x = self.img_view_transformer_depthnet(x)\n x = self.img_view_transformer_quant(x)\n x = x.view(B, num_cams, -1, H, W)\n return x\n\n def bev_encoder(self, x):\n x = self.bev_encoder_backbone(x)\n x = self.bev_encoder_neck(x)\n return x\n\n def forward_single(self, x):\n x = self.head_shared_conv(x)\n task_heads = self.head_task_heads\n # unfold loop\n ret_dicts = []\n ret_dicts.append(task_heads[0](x))\n ret_dicts.append(task_heads[1](x))\n ret_dicts.append(task_heads[2](x))\n ret_dicts.append(task_heads[3](x))\n ret_dicts.append(task_heads[4](x))\n ret_dicts.append(task_heads[5](x))\n return ret_dicts\n\n def forward_pts_head(self, feats):\n return multi_apply(self.forward_single, feats)\n\n def enable_traced(self):\n self.traced = True\n\n def forward(self, img_inputs, img_metas, rescale=False, **kwargs):\n \"\"\"Calls either :func:`forward_train` or :func:`forward_test` depending\n on whether ``return_loss`` is ``True``.\n\n Note this setting will change the expected inputs. When\n ``return_loss=True``, img and img_meta are single-nested (i.e. Tensor\n and List[dict]), and when ``resturn_loss=False``, img and img_meta\n should be double nested (i.e. List[Tensor], List[List[dict]]), with\n the outer list indicating test time augmentations.\n \"\"\"\n img, rots, trans, intrins, post_rots, post_trans = img_inputs\n x = self.image_encoder(img)\n x = self.image_view_transformer_encoder(x)\n x = self.img_view_transformer([x, rots, trans, intrins, post_rots, post_trans])\n x = self.bev_encoder(x)\n x = self.forward_pts_head([x])\n return x\n\n\n@DETECTORS.register_module()\nclass BEVDetForward(Base3DDetector):\n def __init__(self, ori_model, graph_module):\n super(BEVDetForward, self).__init__()\n self.graph_module = graph_module\n self.loss = ori_model.loss\n self.get_bboxes = ori_model.get_bboxes\n\n def extract_feat(self):\n pass\n\n def forward_train(\n self,\n points=None,\n img_metas=None,\n gt_bboxes_3d=None,\n gt_labels_3d=None,\n gt_labels=None,\n gt_bboxes=None,\n img_inputs=None,\n proposals=None,\n gt_bboxes_ignore=None,\n ):\n outs = self.graph_module(img_inputs)\n loss_inputs = [gt_bboxes_3d, gt_labels_3d, outs]\n losses = self.loss(*loss_inputs)\n return losses\n\n def forward_test(self, points=None, img_metas=None, img_inputs=None, **kwargs):\n \"\"\"\n Args:\n points (list[torch.Tensor]): the outer list indicates test-time\n augmentations and inner torch.Tensor should have a shape NxC,\n which contains all points in the batch.\n img_metas (list[list[dict]]): the outer list indicates test-time\n augs (multiscale, flip, etc.) and the inner list indicates\n images in a batch\n img (list[torch.Tensor], optional): the outer\n list indicates test-time augmentations and inner\n torch.Tensor should have a shape NxCxHxW, which contains\n all images in the batch. Defaults to None.\n \"\"\"\n for var, name in [(img_inputs, \"img_inputs\"), (img_metas, \"img_metas\")]:\n if not isinstance(var, list):\n raise TypeError(\"{} must be a list, but got {}\".format(name, type(var)))\n\n num_augs = len(img_inputs)\n if num_augs != len(img_metas):\n raise ValueError(\n \"num of augmentations ({}) != num of image meta ({})\".format(\n len(img_inputs), len(img_metas)\n )\n )\n\n if not isinstance(img_inputs[0][0], list):\n img_inputs = [img_inputs] if img_inputs is None else img_inputs\n points = [points] if points is None else points\n return self.simple_test(points[0], img_metas[0], img_inputs[0], **kwargs)\n else:\n return self.aug_test(None, img_metas[0], img_inputs[0], **kwargs)\n\n def aug_test(self, points, img_metas, img=None, rescale=False):\n \"\"\"Test function without augmentaiton.\"\"\"\n combine_type = self.test_cfg.get(\"combine_type\", \"output\")\n if combine_type == \"output\":\n return self.aug_test_combine_output(points, img_metas, img, rescale)\n elif combine_type == \"feature\":\n return self.aug_test_combine_feature(points, img_metas, img, rescale)\n else:\n assert False\n\n def simple_test(self, points, img_metas, img=None, rescale=False):\n \"\"\"Test function without augmentaiton.\"\"\"\n outs = self.graph_module(img)\n bbox_list = self.get_bboxes(outs, img_metas, rescale=rescale)\n bbox_pts = [\n bbox3d2result(bboxes, scores, labels)\n for bboxes, scores, labels in bbox_list\n ]\n bbox_list = [dict() for _ in range(len(img_metas))]\n for result_dict, pts_bbox in zip(bbox_list, bbox_pts):\n result_dict[\"pts_bbox\"] = pts_bbox\n return bbox_list\n","repo_name":"megvii-research/Sparsebit","sub_path":"examples/quantization_aware_training/nuscenes/bevdet/projects/mmdet3d_plugin/models/detectors/qbevdet.py","file_name":"qbevdet.py","file_ext":"py","file_size_in_byte":6918,"program_lang":"python","lang":"en","doc_type":"code","stars":308,"dataset":"github-code","pt":"81"} +{"seq_id":"34192882700","text":"#!/usr/bin/env python3\n# Name: Bryan Thornlow\n# Date: 2/1/2018\n# compareDatabases.py\n\nimport sys\nimport os\nimport datetime\nimport random\nimport numpy\nimport gzip\nimport math\n\n\n##########################\n##### MAIN FUNCTIONS #####\n##########################\n\n# MANUALLY CHANGE KV888377.1.tRNA1-LysTTT to tRNA-Lys-TTT-1-7\n\ndef combineAllTables():\n mySpecies = ['ANANC2','BTAUR8','CASIA1','CFAMI3','CHIRC1','CLANI1','CPORC3','DNOVE3','ECABA2','EEURO2','EFUSC1','GGORI5']\n mySpecies += ['HGLAB2','HSAPI38','JJACU1','MMARM2','MMULA8','MMURI3','MMUSC10','MOCHR1','MPUTO1','OCUNI2','ODEGU1','OORCA1']\n mySpecies += ['PALEC1','PPYGM3','PTROG5','RNORV6','SSCRO11']\n\n speciesToFull = {}\n speciesToFull['ANANC2'] = 'Aotus_nancymaae'\n speciesToFull['BTAUR8'] = 'Bos_taurus'\n speciesToFull['CASIA1'] = 'Chrysochloris_asiatica' \n speciesToFull['CFAMI3'] = 'Canis_lupus_familiaris'\n speciesToFull['CHIRC1'] = 'Capra_hircus'\n speciesToFull['CLANI1'] = 'Chinchilla_lanigera'\n speciesToFull['CPORC3'] = 'Cavia_porcellus'\n speciesToFull['DNOVE3'] = 'Dasypus_novemcinctus'\n speciesToFull['ECABA2'] = 'Equus_caballus'\n speciesToFull['EEURO2'] = 'Erinaceus_europaeus'\n speciesToFull['EFUSC1'] = 'Eptesicus_fuscus'\n speciesToFull['GGORI5'] = 'Gorilla_gorilla'\n speciesToFull['HGLAB2'] = 'Heterocephalus_glaber'\n speciesToFull['HSAPI38'] = 'Homo_sapiens'\n speciesToFull['JJACU1'] = 'Jaculus_jaculus'\n speciesToFull['MMARM2'] = 'Marmota_marmota'\n speciesToFull['MMULA8'] = 'Macaca_mulatta'\n speciesToFull['MMURI3'] = 'Microcebus_murinus'\n speciesToFull['MMUSC10'] = 'Mus_musculus'\n speciesToFull['MOCHR1'] = 'Microtus_ochrogaster'\n speciesToFull['MPUTO1'] = 'Mustela_putorius'\n speciesToFull['OCUNI2'] = 'Oryctolagus_cuniculus'\n speciesToFull['ODEGU1'] = 'Octodon_degus'\n speciesToFull['OORCA1'] = 'Orcinus_orca'\n speciesToFull['PALEC1'] = 'Pteropus_alecto'\n speciesToFull['PPYGM3'] = 'Pongo_abelii'\n speciesToFull['PTROG5'] = 'Pan_troglodytes'\n speciesToFull['RNORV6'] = 'Rattus_norvegicus'\n speciesToFull['SSCRO11'] = 'Sus_scrofa'\n\n myHeader = 'species\\ttRNA\\tchr\\tstart\\tend\\tstrand\\t'\n #myHeader += 'tRNAPhyloPAvg\\t5PhyloPAvg\\tCpGDensity\\tObsExpUp\\tGenBit\\ttRNA10kb\\tProt75kb\\tTTTT\\tCodon\\tMFE\\tprediction\\tprobability\\tinTestSet\\n'\n myHeader += 'Total Number of tRNA Genes With Identical Anticodon\\tMinimum Free Energy of Canonical tRNA Secondary Structure\\ttRNAscan-SE General Bit Score\\t'\n myHeader += 'Average PhyloP Score in tRNA Gene Sequence\\tDistance To Nearest TTTT Transcription Termination Sequence\\tCpG Density Across tRNA Locus\\t'\n myHeader += \"Observed/Expected CpG Islands Score Upstream of tRNA Gene\\tAverage PhyloP Score in 5' Flanking Region\\t\"\n myHeader += 'tRNA Genes Within 10 Kilobases\\tExons Within 75 Kilobases\\tprediction\\tprobability\\tinTestSet\\n'\n myOutString = myHeader\n for species in mySpecies:\n tRNAToChrStartEndStrand = {}\n for line in open(species+'/tRNAHiConf.bed'):\n splitLine = (line.strip()).split('\\t')\n tRNAToChrStartEndStrand[splitLine[3]] = [splitLine[0],splitLine[1],splitLine[2],splitLine[5]]\n tRNAToData = {} \n for line in open(species+'/alltRNAData.tsv'):\n s = (line.strip()).split('\\t')\n if s[0] != 'tRNA':\n tRNAToData[s[0]] = [s[9],s[10],s[5],s[1],s[8],s[3],s[4],s[2],s[6],s[7]]\n tRNAToTestSet = {}\n tRNAToPred = {}\n mytRNAs = []\n for line in open(species+'/'+partLower(species)+'tRNAClassificationsNewFixedNoSegDups.txt'):\n splitLine = (line.strip()).split('\\t')\n tRNAToTestSet[splitLine[0]] = True\n for line in open(species+'/'+partLower(species)+'tRNAClassificationsNewWithSegDups.txt'):\n splitLine = (line.strip()).split('\\t')\n tRNAToPred[splitLine[0]] = [splitLine[2],splitLine[1]]\n mytRNAs.append(splitLine[0])\n print(species)\n for t in sorted(mytRNAs):\n myOutString += speciesToFull[species]+'\\t'+t+'\\t'+joiner(tRNAToChrStartEndStrand[t])+'\\t'+joiner(tRNAToData[t])+'\\t'+joiner(tRNAToPred[t])+'\\t'\n if t in tRNAToTestSet:\n myOutString += 'True\\n'\n else:\n myOutString += 'False\\n'\n open('all_species_all_trnas_fixed.txt','w').write(myOutString)\n\n\ndef joiner(entry):\n \"\"\"\n Helper function to print lists in \n tab separated format.\n \"\"\"\n newList = []\n for k in entry:\n newList.append(str(k))\n return '\\t'.join(newList)\n\ndef partLower(myString):\n return(myString[0]+(myString[1:].lower()))\n\n\n\n\ndef main():\n combineAllTables()\n\nif __name__ == \"__main__\":\n \"\"\"\n Calls main when program is run by user.\n \"\"\"\n main();\n raise SystemExit\n\n","repo_name":"bpt26/tRAP","sub_path":"manuscript_files_all/get_anticodon_distributions/getAllSpeciesAlltRNAs.py","file_name":"getAllSpeciesAlltRNAs.py","file_ext":"py","file_size_in_byte":4791,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"81"} +{"seq_id":"72929464586","text":"from sys import stdin\nfrom typing import List\nfrom collections import deque\ninput = lambda: stdin.readline().rstrip()\n\n\ndef shuffle(arr: List[int], k: int) -> List[int]:\n dq = deque(arr)\n cnt = 2 ** k\n dq.rotate(cnt)\n for i in range(2, k + 2):\n temp = deque()\n for _ in range(cnt):\n temp.append(dq.popleft())\n cnt = 2 ** (k - i + 1)\n temp.rotate(cnt)\n temp.extend(dq)\n dq = temp\n return list(dq)\n\n\nif __name__ == \"__main__\":\n N = int(input())\n cards = list(map(int, input().split()))\n\n i = 1\n while 2 ** i < N:\n j = 1\n while 2 ** j < N:\n res = shuffle(shuffle(list(k for k in range(1, N + 1)), i), j)\n if res == cards:\n print(i, j)\n exit()\n j += 1\n i += 1\n","repo_name":"boorooksus/Algorithm-Study","sub_path":"백준/CH11_Brute Force/G5-21315-Cards_Shuffle.py","file_name":"G5-21315-Cards_Shuffle.py","file_ext":"py","file_size_in_byte":820,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"3811409298","text":"# MCS 260 Project Three by Amanda\nimport sys,getopt\nfrom collections import Counter\n\ndef get_file_data(infile):\n\twith open(infile, encoding='utf-8') as my_file:\n\t\t## Initialize dictionary\n\t\twordMap = {}\n\t\tfor line in my_file:\n\t\t\ttry:\n\t\t\t\t### Split by a single space\n\t\t\t\tfrequency = Counter(line.split(\" \"))\n\n\t\t\t\tfor word in frequency:\n\t\t\t\t\t## If the key doesnt exists\n\t\t\t\t\tif(word in wordMap):\n\t\t\t\t\t\twordMap[word] = int(wordMap[word]) + frequency[word]\n\t\t\t\t\t## if exists add frequency\n\t\t\t\t\telse:\n\t\t\t\t\t\twordMap[word] = int(frequency[word])\n\t\t\t\n\t\t\texcept UnicodeDecodeError:\n\t\t\t\tprint(\"xml error\")\n\t\t## Printing frequency and length\n\t\tprint(wordMap)\n\t\tprint(\"number of words : \" + str(len(wordMap)))\n##\n# Main Function to get arguments \n##\nif __name__==\"__main__\":\n\tinfile = input(\"Give a file name : \")\n\tget_file_data(infile)\n\n","repo_name":"Stanwar/RandomPython","sub_path":"CircularFrequencyTable/makeFreq.py","file_name":"makeFreq.py","file_ext":"py","file_size_in_byte":826,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"43684488435","text":"import pytest\n\nfrom app.controllers import VacuumController\nfrom app.exceptions import (\n InvalidRequest,\n InvalidSurfaceCoordinates,\n InvalidVacuumPosition\n)\n\n\n@pytest.fixture\ndef controller():\n return VacuumController()\n\n\n@pytest.fixture\ndef valid_requests():\n return [\n ('5 5\\n1 2 N\\nLFLFLFLFF\\n3 3 E\\nFFRFFRFRRF',\n 'DONE\\n1 3 N\\n5 1 E'),\n ('5 5\\n1 3 N\\nRFFF\\n2 3 S\\nRFFF',\n 'FAILED\\n1 3 E\\n2 3 W'),\n ('5 5\\n1 3 N\\nRFFF\\n2 3 S\\nLLFF',\n 'DONE\\n4 3 E\\n2 5 N'),\n ('5 5\\n1 3 N\\nRFFFFF\\n2 3 S\\nLLFFFF',\n 'FAILED\\n5 3 E\\n2 5 N'),\n ]\n\n\n@pytest.fixture\ndef invalid_requests():\n return [\n ('abc',\n InvalidRequest,\n 'Request is not well formatted:\\nabc'),\n ('5 5\\n1 2 N\\nLFLFLFLFF\\n3 3 E',\n InvalidRequest,\n 'Request is not well formatted:\\n5 5\\n1 2 N\\nLFLFLFLFF\\n3 3 E'),\n ]\n\n\n@pytest.fixture\ndef invalid_surface_coordinates():\n return [\n ('0 5\\n1 2 N\\nLFLFLFLFF\\n3 3 E\\nFFRFFRFRRF',\n InvalidSurfaceCoordinates,\n 'Surface coordinates are not valid: 0 5'),\n ('5 -1\\n1 2 N\\nLFLFLFLFF\\n3 3 E\\nFFRFFRFRRF',\n InvalidSurfaceCoordinates,\n 'Surface coordinates are not valid: 5 -1'),\n ]\n\n\n@pytest.fixture\ndef invalid_vacuum_coordinates():\n return [\n ('5 5\\n-1 2 N\\nLFLFLFLFF\\n3 3 E\\nFFRFFRFRRF',\n InvalidVacuumPosition,\n 'Position outside the surface limits: -1 2'),\n ('5 5\\n1 -2 N\\nLFLFLFLFF\\n3 3 E\\nFFRFFRFRRF',\n InvalidVacuumPosition,\n 'Position outside the surface limits: 1 -2'),\n ('5 5\\n10 2 N\\nLFLFLFLFF\\n3 3 E\\nFFRFFRFRRF',\n InvalidVacuumPosition,\n 'Position outside the surface limits: 10 2'),\n ('5 5\\n1 20 N\\nLFLFLFLFF\\n3 3 E\\nFFRFFRFRRF',\n InvalidVacuumPosition,\n 'Position outside the surface limits: 1 20'),\n ('5 5\\n1 2 N\\nLFLFLFLFF\\n1 2 E\\nFFRFFRFRRF',\n InvalidVacuumPosition,\n 'Position occupied by another vacuum: 1 2'),\n ]\n\n\n@pytest.fixture\ndef invalid_cardinal_points():\n return [\n ('5 5\\n1 2 Q\\nLFLFLFLFF\\n3 3 E\\nFFRFFRFRRF',\n ValueError,\n \"'Q' is not a valid CardinalPoint\"),\n ('5 5\\n1 2 e\\nLFLFLFLFF\\n3 3 E\\nFFRFFRFRRF',\n ValueError,\n \"'e' is not a valid CardinalPoint\"),\n ]\n\n\n@pytest.fixture\ndef invalid_instructions():\n return [\n ('5 5\\n1 2 N\\nQRQRQRQRR\\n3 3 E\\nFFRFFRFRRF',\n ValueError,\n \"'Q' is not a valid Instruction\"),\n ('5 5\\n1 2 N\\nlflflflff\\n3 3 E\\nFFRFFRFRRF',\n ValueError,\n \"'l' is not a valid Instruction\"),\n ]\n\n\ndef test_valid_requests(controller, valid_requests):\n for request, expected_response in valid_requests:\n response = controller.handle(request)\n assert expected_response == response\n\n\ndef test_invalid_requests(controller, invalid_requests):\n for request, exception, message in invalid_requests:\n with pytest.raises(exception, match=message):\n controller.handle(request)\n\n\ndef test_invalid_surface_coordinates(controller, invalid_surface_coordinates):\n for request, exception, message in invalid_surface_coordinates:\n with pytest.raises(exception, match=message):\n controller.handle(request)\n\n\ndef test_invalid_vacuum_coordinates(controller, invalid_vacuum_coordinates):\n for request, exception, message in invalid_vacuum_coordinates:\n with pytest.raises(exception, match=message):\n controller.handle(request)\n\n\ndef test_invalid_cardinal_points(controller, invalid_cardinal_points):\n for request, exception, message in invalid_cardinal_points:\n with pytest.raises(exception, match=message):\n controller.handle(request)\n\n\ndef test_invalid_instructions(controller, invalid_instructions):\n for request, exception, message in invalid_instructions:\n with pytest.raises(exception, match=message):\n controller.handle(request)\n","repo_name":"samuelmaudo/robot-vacuums","sub_path":"tests/test_controllers.py","file_name":"test_controllers.py","file_ext":"py","file_size_in_byte":3979,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"69964038025","text":"\"\"\"\nDownload all trips for a day.\n\"\"\"\nimport os\nos.environ[\"CALITP_BQ_MAX_BYTES\"] = str(400_000_000_000)\n\nimport datetime as dt\nimport pandas as pd\nimport sys \n\nfrom loguru import logger\n\nfrom shared_utils import gtfs_utils_v2\nfrom segment_speed_utils.project_vars import COMPILED_CACHED_VIEWS\n\n\ndef get_operators(analysis_date: str):\n \"\"\"\n Operators to download: favor subfeeds over combined regional feed.\n \"\"\"\n all_operators = gtfs_utils_v2.schedule_daily_feed_to_gtfs_dataset_name(\n selected_date = analysis_date,\n keep_cols = None,\n get_df = True,\n feed_option = \"use_subfeeds\"\n ).rename(columns = {\"gtfs_dataset_name\": \"name\"})\n\n keep_cols = [\"feed_key\", \"name\"]\n\n operators_to_include = all_operators[keep_cols]\n\n # There shouldn't be any duplicates by name, since we got rid \n # of precursor feeds. But, just in case, don't allow dup names.\n operators_to_include = (operators_to_include\n .drop_duplicates(subset=\"name\")\n .reset_index(drop=True)\n )\n \n return operators_to_include\n\n\ndef download_one_day(analysis_date: str):\n \"\"\"\n Download single day for trips.\n \"\"\"\n logger.info(f\"Analysis date: {analysis_date}\")\n start = dt.datetime.now()\n\n operators_df = get_operators(analysis_date)\n\n FEEDS_TO_RUN = sorted(operators_df.feed_key.unique().tolist()) \n\n logger.info(f\"# operators to run: {len(FEEDS_TO_RUN)}\")\n\n dataset = \"trips\"\n logger.info(f\"*********** Download {dataset} data ***********\")\n\n keep_trip_cols = [\n \"feed_key\", \"gtfs_dataset_key\", \n \"name\", \"regional_feed_type\", \n \"service_date\", \"trip_start_date_pacific\",\n \"trip_id\", \n \"trip_instance_key\", # https://github.com/cal-itp/data-infra/pull/2489\n \"route_key\", \"route_id\", \"route_type\", \n \"route_short_name\", \"route_long_name\", \"route_desc\",\n \"direction_id\", \n \"shape_array_key\", \"shape_id\",\n \"trip_first_departure_datetime_pacific\", \n \"trip_last_arrival_datetime_pacific\",\n \"service_hours\",\n \"trip_start_date_local_tz\", \"trip_first_departure_datetime_local_tz\",\n \"trip_last_arrival_datetime_local_tz\"\n ]\n\n trips = gtfs_utils_v2.get_trips(\n selected_date = analysis_date,\n operator_feeds = FEEDS_TO_RUN,\n trip_cols = keep_trip_cols,\n get_df = True,\n ) \n\n trips.to_parquet(\n f\"{COMPILED_CACHED_VIEWS}{dataset}_{analysis_date}.parquet\") \n \n end = dt.datetime.now()\n logger.info(f\"execution time: {end-start}\")\n \n return\n\n \nif __name__==\"__main__\":\n \n from update_vars import analysis_date_list\n \n logger.add(\"./logs/download_data.log\", retention=\"3 months\")\n logger.add(sys.stderr, \n format=\"{time:YYYY-MM-DD at HH:mm:ss} | {level} | {message}\", \n level=\"INFO\")\n \n for analysis_date in analysis_date_list:\n download_one_day(analysis_date)","repo_name":"cal-itp/data-analyses","sub_path":"gtfs_funnel/download_trips.py","file_name":"download_trips.py","file_ext":"py","file_size_in_byte":3047,"program_lang":"python","lang":"en","doc_type":"code","stars":19,"dataset":"github-code","pt":"81"} +{"seq_id":"27524450623","text":"import pUtils\nfrom PIL import Image\nfrom io import BytesIO\nfrom PySide2.QtGui import QImage, QPixmap\nfrom PixelView.imageContainers.rgb888Image import Rgb888Image\nfrom PixelView.imageContainers.rgba8888Image import Rgba8888Image\n\n\ndef loadImage(filePath, nullColor=None):\n\n def genPlaceHolder():\n # If we couldn't load an image we generate a placeholder\n # This is necessary since we may be dealing with a list of images\n # and we can't just end the application when one 'unloadable' image\n # is found.\n # By generating a place holder instead, we allow the user to keep\n # reviewing the images on the list as well as indicating something\n # went wrong.\n\n width = 100\n height = 100\n t = Rgba8888Image(bytearray(nullColor + [0]) * width * height, width, height)\n t.srcFileFormat = 'nullImage'\n return t\n\n try:\n data = pUtils.quickFileRead(filePath, 'rb')\n except Exception:\n if nullColor: return genPlaceHolder()\n raise\n\n try:\n img = Rgba8888Image()\n img.load(filePath, data=data)\n return img\n except Exception: pass\n\n try:\n img = Rgb888Image()\n img.load(filePath, data=data)\n return img\n except Exception: pass\n\n try:\n img = Image.open(BytesIO(data))\n except Exception:\n raise Exception('Unable to identify image format')\n\n try:\n if img.format != 'PNG': raise Exception('Unsupported image format ' + img.format)\n\n width, height = img.size\n data = bytearray(img.tobytes())\n if img.mode == 'RGBA':\n t = Rgba8888Image(data, width, height)\n elif img.mode == 'RGB':\n t = Rgb888Image(data, width, height)\n else:\n raise Exception('Unknown Image mode')\n t.srcFilePath = filePath\n t.srcFileFormat = 'PNG'\n return t\n except Exception:\n if nullColor: return genPlaceHolder()\n raise\n\n\ndef dropAlpha(img):\n if isinstance(img, Rgb888Image):\n return img\n\n if isinstance(img, Rgba8888Image):\n data = img.data\n red = data[0::4]\n green = data[1::4]\n blue = data[2::4]\n\n newData = bytearray([0, 0, 0] * int(len(data) / 4))\n newData[0::3] = red\n newData[1::3] = green\n newData[2::3] = blue\n return Rgb888Image(newData, img.width, img.height)\n\n raise Exception('Invalid input parameter type')\n\n\ndef getAlphaImage(img):\n if isinstance(img, Rgb888Image):\n return None\n\n if isinstance(img, Rgba8888Image):\n data = img.data\n alpha = data[3::4]\n\n newData = bytearray([alpha[i // 3] for i in range(len(alpha) * 3)])\n return Rgb888Image(newData, img.width, img.height)\n\n raise Exception('Invalid input parameter type')\n\n\ndef widgetDisplayImage(widget, img):\n imgFormat = QImage.Format_RGB888\n\n img = dropAlpha(img)\n displayImage = QImage(img.data,\n img.width, img.height,\n imgFormat)\n\n displayImagePix = QPixmap.fromImage((displayImage))\n widget.setPixmap(displayImagePix)\n","repo_name":"NVIDIA/PixelView","sub_path":"PixelView/utils/image.py","file_name":"image.py","file_ext":"py","file_size_in_byte":3140,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"81"} +{"seq_id":"28927269654","text":"grocery = 'Milk\\nChicken\\r\\nBread\\rButter'\r\n\r\nprint(grocery.splitlines())\r\nprint(grocery.splitlines(True))\r\n\r\ngrocery = 'Milk Chicken Bread Butter'\r\nprint(grocery.splitlines())\r\n\r\nimport sys\r\nimport collections\r\nhurap_file = open(sys.argv[1], \"r\")\r\n\r\nschuckscii_file = open(sys.argv[2], \"r\")\r\n\r\nvirus_codes_file = open(sys.argv[3], \"r\")\r\n\r\nrepresentations = {'0': '0', '1': '1', '2': '2', '3': '3', '4': '4', '5': '5', '6': '6',\r\n '7': '7', '8': '8', '9': '9', '10': \"A\", '11': \"B\", '12': \"C\",\r\n '13': \"D\", '14': \"E\", '15': \"F\"}\r\nalex = []\r\nsubstituted = {}\r\nw = 0\r\nAlien = []\r\nfor i in schuckscii_file.read().splitlines():\r\n print(i)\r\n\r\nfor line in hurap_file.read().split():\r\n print(line)\r\n if not line.startswith(\"0\" or \"1\"):\r\n continue\r\n else:\r\n Alien.append(line)\r\n\r\nprint(Alien)","repo_name":"b21627868/drafts","sub_path":"splitlines.py","file_name":"splitlines.py","file_ext":"py","file_size_in_byte":846,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"10109468719","text":"\r\n# 多分类问题\r\n\r\nimport pandas as pd\r\nimport numpy as np\r\nfrom sklearn.metrics import f1_score\r\nimport matplotlib.pyplot as plt\r\nfrom sklearn.neural_network import MLPClassifier#神经网络分类器\r\nfrom sklearn.preprocessing import MinMaxScaler\r\nfrom sklearn.ensemble import RandomForestClassifier,AdaBoostClassifier#随机森林,adaboost\r\nfrom sklearn.neighbors import KNeighborsClassifier#k近邻\r\nfrom sklearn.metrics import confusion_matrix,plot_confusion_matrix\r\nimport warnings\r\nfrom sklearn.tree import DecisionTreeClassifier#决策树分类器\r\n\r\nplt.rc('font', family='Times New Roman')\r\nwarnings.filterwarnings(\"ignore\")\r\n\r\npaTH = '/Data_an/industry/train data.xlsx'\r\ndf = pd.read_excel(paTH)\r\ndata_train = pd.DataFrame(df,columns=['机器编号','机器质量等级','室温(K)','机器温度(K)','转速(rpm)',\r\n\t\t\t\t\t\t\t\t '扭矩(Nm)','使用时长(min)','是否发生故障','具体故障类别'])\r\n#在这里一共取出来了4列数据信息。\r\nle = data_train['机器质量等级']\r\nT = data_train['室温(K)']\r\nT_machine = data_train['机器温度(K)']\r\nerror_type = data_train['具体故障类别']\r\n\r\n\r\n#查看数据的信息\r\n\r\n\r\nM_sum = data_train.shape[0]#查看总共的数据\r\n\r\n# 建立温升,插入数据中,定名 Tr。两列数据进行相减。\r\nsub_t = T_machine - T\r\ndata_train.insert(loc=9,column='Tr',value=sub_t)#在数据中第九列中插入一列数据。\r\n\r\n# 对机器质量进行处理,分为三列 L M H\r\n#在这里使用的是人工处理方法,one-hot编码方式。\r\nq_ls = []\r\nfor i in range(M_sum):\r\n\tif le[i] == 'L':\r\n\t\tq_ls.append([1,0,0])\r\n\t\tcontinue\r\n\telif le[i] == 'M':\r\n\t\tq_ls.append([0,1,0])\r\n\t\tcontinue\r\n\telif le[i] == 'H':\r\n\t\tq_ls.append([0,0,1])\r\nprint()\r\nq_ls = np.array(q_ls)\r\n\r\ntrain_set = np.array([data_train['转速(rpm)'],\r\n\t\t\t\t data_train['扭矩(Nm)'],\r\n\t\t\t\t data_train['使用时长(min)'],\r\n\t\t\t\t\t data_train['Tr']])\r\ntrain_set = train_set.T\r\n# 归一化\r\nscale = MinMaxScaler()\r\nprint(\"未归一化特征数据集及维度:\")\r\nprint(train_set,train_set.shape,sep='\\n')\r\ntrain_set = scale.fit_transform(train_set)\r\nprint(\"归一化特征数据集:\")\r\nprint(train_set,train_set.shape,sep='\\n')\r\ntrain_set = np.hstack((q_ls,train_set))#按照水平方向上来进行拼接。\r\n\r\nUnique = error_type.unique()\r\n\r\n# 对故障数据进行处理。这里是对数据进行处理。\r\nerror_type_ls = []\r\nfor i in range(M_sum):\r\n\tif error_type[i] == 'TWF':\r\n\t\terror_type_ls.append([1])\r\n\telif error_type[i] == 'HDF':\r\n\t\terror_type_ls.append([2])\r\n\telif error_type[i] == 'PWF':\r\n\t\terror_type_ls.append([3])\r\n\telif error_type[i] == 'OSF':\r\n\t\terror_type_ls.append([4])\r\n\telif error_type[i] == 'RNF':\r\n\t\terror_type_ls.append([5])\r\n\telse:\r\n\t\terror_type_ls.append([0])\r\n\r\nlabel_set = np.array(error_type_ls) # 标签数据集\r\n\r\nfrom sklearn.model_selection import train_test_split as TTS#数据集进行划分\r\n\r\n\r\n\r\n\r\n# 数据集 8:1:1\r\nsplit1 = int(M_sum*0.8)\r\nsplit2 = int(M_sum*0.9)\r\ntrain_x = train_set[:split1,:]\r\ntrain_y = label_set[:split1,:]\r\ncv_x = train_set[split1:split2,:]\r\ncv_y = label_set[split1:split2,:]\r\ntest_x = train_set[split2:,:]\r\ntest_y = label_set[split2:,:]\r\n\r\n\r\n\r\n\r\n\r\n\r\n# 分类器\r\nclf_RF = RandomForestClassifier(n_estimators=120,random_state=40)#随机森林,在这里设置了120颗决策树。\r\nclf_NN = MLPClassifier(solver='lbfgs', alpha=1e-4,\r\n hidden_layer_sizes=(15,), random_state=4)#使用神经网络来进行预测\r\nclf_ada = AdaBoostClassifier(n_estimators=100)#\r\nclf_knn = KNeighborsClassifier(n_neighbors=5)#使用k近邻来进行预测\r\nclf_tree = DecisionTreeClassifier()#使用决策树来进行预测\r\n\r\n# 模型选择\r\n# 用在验证级上的表现作为衡量标准\r\nclassifer_ls = [clf_RF,clf_NN,clf_ada,clf_knn,clf_tree]\r\nfor clf in classifer_ls:\r\n\tclf.fit(train_x, train_y)\r\n\tpred = clf.predict(cv_x)\r\n\tC = confusion_matrix(cv_y, pred)\r\n\tF1 = f1_score(cv_y, pred,average=\"micro\")\r\n\tprint(f'clf:{clf},其中的F1_SCORE为:{F1}')\r\n\r\n# 选择MLP作为多元分类器 在测试集上的表现\r\npred = clf_NN.predict(test_x)\r\nprint(test_x.shape)\r\nC = confusion_matrix(test_y, pred)\r\nF1 = f1_score(test_y, pred,average=\"micro\")\r\nplot_confusion_matrix(clf_NN, test_x, test_y, cmap=plt.cm.Blues)\r\nprint(f'\\n选择MLP作为多元分类器 在测试集上的表现,其F1表现为:{F1}')\r\nplt.show()\r\n\r\n\r\npred = clf_NN.predict(train_x)\r\nprint(train_x.shape)\r\nC = confusion_matrix(train_y, pred)\r\nF1 = f1_score(train_y, pred,average=\"micro\")\r\nplot_confusion_matrix(clf_NN, train_x, train_y, cmap=plt.cm.Blues)\r\nprint(f'\\n选择MLP作为多元分类器 在测试集上的表现,其F1表现为:{F1}')\r\nplt.show()","repo_name":"Keep-Doing-guoguo/data_analyse","sub_path":"scikit-learn/data_anlysis/industry.py","file_name":"industry.py","file_ext":"py","file_size_in_byte":4712,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"}